The thing most likely, in my mind, to cause problems here is that using frames is not guaranteed to work in any other Python implementation besides CPython.

inspect.currentframe()
Return the frame object for the caller’s stack frame.
CPython implementation detail: This function relies on Python stack frame support in the interpreter, which isn’t guaranteed to exist in all implementations of Python. If running in an implementation without Python stack frame support this function returns None.

This will end up throwing an error if you try to unpack None because the implementation doesn't support your function. If you were dead-set on using stack inspection, then you should give a more useful error message than AttributeError: 'NoneType' object has no attribute 'f_back'. You should test for if you get a frame or not, and then use platform to print a more helpful error message.
def f(s):
    frame = inspect.currentframe()
    if frame is not None:
        return s.format(**frame.f_back.f_locals)
    else:
        raise NotImplementedError(
            "Python implementation {} does not support stack inspection.".format(
                platform.python_implementation()
            )
        )

At this point, then, you should make sure this is a well-documented limitation of your library, and I would probably write some unit tests where it asserts that is raised for certain implementations.
The real problem, however, isn't that you're using something that isn't guaranteed (although that's certainly a problem). The real problem is that stack inspection is almost never the right answer. We don't need it here either.  What we're going to want to do is something like this:
def _poor_fstring(namespace):
    def _():
        return namespace
    return _

get_namespace = _poor_fstring(locals())

def f(s):
    return s.format(**get_namespace())

This still isn't ideal - you'll need to redeclare get_namespace in any scope you want access to it - but you avoid stack inspection, which is worth it in my mind.
Really though, I don't see a huge benefit between using your function and just calling s.format(**namespace), where namespace is whatever lookup table you want.  The one benefit would be if, as you said, it supported arbitrary expressions. And the only way to get arbitrary expressions is to, well, evaluate them.  You'll basically have to parse the string and extract everything between curly braces. Then try a lookup in the namespace and replace that, otherwise compile it, and then eval what you find. Hopefully I don't need to point out that evaling random strings is... dangerous.
Going into actually parsing a format string is way beyond the scope of this question.
In short, my recommendation would be to just suffer through... or upgrade your Python version.


Speeding up repetitive initialisation with structured data?

You should be able to prevent casting to a string 100 times.

First create all strings in a cell array, then just loop over the strings.

Though it does not show up on the profiler, this looks higly dubious:

i=num2str(i)
ubs_str(i)=i/100;

Now you will get the character code of 'i' and divide that by 100.


I really like what you wrote there, though I am afraid at this point you ought to expand the code, not reduce it.

r, r1, r2, cx, cy, beta are all variables that need better ( more meaningful ) names
You need to indent your code, just hit TidyUp in your fiddle and you will see
This is not part of your core code, but you should not simply assign something to window.onload, you should use addEventListener
Your code had support for using custom colors, and then you took it out, if you really want to take that out, then you should also take out the parameter, the commented out code and the  if (color == "rainbow"){ statement
in your var statement, you could simply do cy = cx
be consistent in your name, and use lowerCamelCase: stroke_width -> strokeWidth
You did not declare i with var
While straightforward, your code has no comments at all..


Representing a long regular expression in a Polynomial class

Rather than construct the polynomial string incorrectly, then fix it with regex's, it may be easier to contruct it directly.  This is one way you could do that.

class Polynomial
  def initialize(coefficients)
    @coefficients = coefficients
  end

  def to_s
    coeffs = @coefficients.each_with_index.select { |c,k| c.nonzero? || k==0 }.reverse
    coeffs.each_with_object('') do |(c,k), s|
      cneg = (c.to_f < 0.0)
      if [c,k] == coeffs.first
        s << '-' if cneg
      else
        s << (cneg ? ' - ' : ' + ')
      end
      s << "#{c.abs}" unless (c.abs.to_f == 1.0 && k > 0)
      s << "x" if k > 0
      s << "^#{k}" if k > 1
    end
  end
end

coefficients = [2.1, 3, 1.0, 0, -6.1, 1, -5.3, 0.2]
p Polynomial.new(coefficients).to_s
  # => 0.2x^7 - 5.3x^6 + x^5 - 6.1x^4 + x^2 + 3x + 2.1

For this example value of coefficients, this is what's happening:

First save each coeffient's index with its value:

a = @coefficients.each_with_index
  # => [[2.1,0], [3,1], [1.0,2], [0,3], [-6.1,4], [1,5], [-5.3,6], [0.2,7]]

Next, select only pairs for which the value is non-zero or the exponent is zero:

b = a.select { |c,k| c.nonzero? || k==0 }
  # => [[2.1, 0], [3, 1], [1.0, 2], [-6.1, 4], [1, 5], [-5.3, 6], [0.2, 7]]

Notice that [0,3] has been removed.  Now reverse the elements of the array:

coeffs = b.reverse
  # => [[0.2, 7], [-5.3, 6], [1, 5], [-6.1, 4], [1.0, 2], [3, 1], [2.1, 0]]

each_with_object('') creates an empty string, designated s in the block.  It is then a simple matter to consider each element of each term in the polynomial to build up the string.

I'm not certain if I followed the formatting rules exactly, but if I did not, it should be easy to modify the code to conform.

(Edited to fix boo-boos spotted by @200_success.)


Reducing execution time for a python program

Really, to answer your question, you need to profile your code. You need to understand what is taking up all that time. Just by looking at your code, it's impossible to tell, but my guess would be that the most time is spent in one of the following places:

Running every *.csv file you run into through the XML parser. I get the feeling you consider this necessary in order to discard XML files that are pretending to be CSV files. Ideally, you should do this once, then properly label your files thenceforth so you don't have to do this check every time. This strikes me as a potentially very expensive thing to do; as such, I've modified this check below so it only occurs when you might actually be interested in the file later on (that is, its path contains 'results')
Kicking off the external process individually for each file you want to check. Launching processes is not a cheap operation. Ideally, you'd want to EITHER launch a single process for each rule, passing it all relevant file paths for it to check all at once, OR if you wrote your rules in Python, you could read each file in exactly once, then process it through all your rules all at once. Launching a new process for each rule, for each file, is probably a huge source of slowness.

There are also several parts of the code that just seem hacky and bad practice. Also, if you use Python 3.5+, you can use glob instead of your custom locate function. In the spirit of reviewing all your code anyway and making any suggestions that seem appropriate, here's how I'd suggest your code be written, though admittedly without any good suggestions about how to speed up the code (because, again, you MUST profile your code to understand what's actually taking the time):

import os
import subprocess
import xml.etree.ElementTree as ElementTree
from xml.parsers.expat import ExpatError
from glob import iglob

def is_xml(path):
    try:
        ElementTree.parse(path)
        return True
    except (SyntaxError, ExpatError):
        return False

def check_rule1(path):
    subprocess.run(['ConsoleApplication9.exe', path])
    state = open("logs/Rule_1.txt").read()

    with open('results/Rule_1_log.log', 'a+') as output:
        output.write("\n========" + path + "========\n")
        output.write(state)
    return "failed" not in state:

def main():
    csv_path = (path for path in iglob('**/*.csv', recursive=True) if 'results' in path and not is_xml(path))
    rules = [check_rule1]

    for rule_num, rule in enumerate(rules):
        rule_num += 1  # We want to count rules from 1 up
        passed = []
        failed = []

        for paths in csv_path:
            result = rule(paths)
            if result:
                passed.append(paths)
                #print("Rule 1 has passed for " + paths)
            else:
                failed.append(paths)
                #print("Rule 1 has failed for " + paths)

            os.remove('logs/Rule_1.txt')

        # Do something with passed/failed, presumably?

if __name__ == '__main__':
    main()


Yikes, you're running almost 3,000,000 individual queries.  If you could do 4 a second (and you probably cannot) that is still a day!

How about just

select username, tweets from tweets order by username

Then of course you have to do some fancy footwork to switch from one file to the next when the user changes.

It should only take a few hours to run.


There's not a lot of code here so there's not a lot to say. ^_^

Implementations like this are generally outside of the day-to-day knowledge of most programmers. You may wish to include a reference in the code to how the algorithm was derived and how it works.
The chosen variable names are pretty useless. I have no idea what an or sm mean. Because I don't know what they mean, I didn't change them, but you should. (Looking back at the Ada implementation, I see that sm should be sum and an is just the current value of the lookup table, but it shouldn't be required to find 2 other implementations to understand this one).
Leading underscores in a variable name means the variable is unused (but cannot be removed for some reason). Don't use a underscore and use the variable at the same time.
If something is a constant, make it so. Constants use const or static and are named with SCREAMING_SNAKE_CASE.
There is inconsistent alignment in the lookup table. The first column is aligned on the decimal point, the second and third columns are not.
The sm variable doesn't need an explicit type as type inference will cover it.
There are inplace operations like *= which are shorter than foo = foo * bar.
There's a f64::recip method which may be more intuitive.
Operators like / should have space on both sides.
Is there a benefit to iterating in reverse every time? I'd just reorder the table and iterate forwards. Computers generally like going forwards.
The loop can be simplified by using Iterator::fold.

const TAYLOR_COEFFICIENTS: [f64; 29] = [
    -0.00000000000000000023,  0.00000000000000000141,  0.00000000000000000119,
    -0.00000000000000011813,  0.00000000000000122678, -0.00000000000000534812,
    -0.00000000000002058326,  0.00000000000051003703, -0.00000000000369680562,
     0.00000000000778226344,  0.00000000010434267117, -0.00000000118127457049,
     0.00000000500200764447,  0.00000000611609510448, -0.00000020563384169776,
     0.00000113302723198170, -0.00000125049348214267, -0.00002013485478078824,
     0.00012805028238811619, -0.00021524167411495097, -0.00116516759185906511,
     0.00721894324666309954, -0.00962197152787697356, -0.04219773455554433675,
     0.16653861138229148950, -0.04200263503409523553, -0.65587807152025388108,
     0.57721566490153286061,  1.00000000000000000000,
];

const INITIAL_SUM: f64 = 0.00000000000000000002;

fn gamma(x: f64) -> f64 {
    TAYLOR_COEFFICIENTS.iter().fold(INITIAL_SUM, |sum, coefficient| {
        sum * (x - 1.0) + coefficient
    }).recip()
}

fn main() {
    for i in 1..11 {
        let f = i as f64;
        println!("{}", gamma(f / 3.0));
    }
}

Notes based on the original Ada implementation:

The lookup table was defined inside the gamma function, and the same could be done here. It's a matter of personal preference at this point in time.
Long numbers could be separated with underscores: 0.111_222_333.
The loop invariant 1.0 - x could be hoisted out of the loop, but I'd trust the optimizer to do that until proven otherwise.


Sorting an assortment of strings and integers together, while keeping them separate

Your test cases should include lexical sort of integers; that is, [9,11] must return [11,9].  (Your implementation does pass this test since you're converting everything to a string).

As you suspected, mangling the input is hacky.  This is better accomplished with a multi-criteria sort.  This technique maps each individual value to an array of sort criteria.  Ruby will compare the arrays only until it finds unequal elements; this means you can mix integers and strings in the second field, so long as the first field distinguishes them.

For our problem, the first field will be 0 for integers else 1.  The second field is the value itself.

Although this approach will never compare integers to strings—if the first criteria distinguishes the two elements, the comparison is done—the second criteria must be a string anyway, to satisfy the "sort alphabetically" requirement.

It's not necessary to sort the entire array or store a full copy of it.  Instead, count duplicates in a hash table.  Traverse the values of the hash to find a maximum.  Traverse again to extract the corresponding keys.

def highest_occurrence(arr)
    return arr if arr.size <= 1
    count = Hash.new(0)
    arr.each { |k| count[k] += 1 }
    max = count.max_by{|k,n| n}[1]
    return count.select { |k,n| n==max }.keys.sort_by { |k| [ k.is_a?(Integer)?0:1, k.to_s ] }
end


If mapFactors' is put in a where clause of mapFactors, it isn't globally accessible and you can call it go or something because the scoping already points out it belongs to mapFactors.

Swapping gos argument order lets you say mapFactors = go [].

++ [_] is a smell. Instead of passing down an accumulator and growing it to the right, you can pass it out as the return value and grow it to the left.

mapFactors :: [Int] -> [[Int]]
mapFactors = go where
  go [] = []
  go (x:xs) = newAcc $ go xs where
    factors = filter ((==0) . (`mod` x)) xs
    newAcc | null factors = id
           | otherwise = (:) factors

The filtering can happen after go is done.

mapFactors :: [Int] -> [[Int]]
mapFactors = filter (not . null) . go where
  go [] = []
  go (x:xs) = filter ((==0) . (`mod` x)) xs : go xs

tails helps express go in terms of map:

mapFactors :: [Int] -> [[Int]]
mapFactors = filter (not . null) . map go . tails where
  go [] = []
  go (x:xs) = filter ((==0) . (`mod` x)) xs

Let's use sum from that comment and inline the once-used twoStepFactors (imo if you're only giving a name to explain what something does, use comments)

answer :: [Int] -> Int
answer xs = sum $ map (sum . map length . mapFactors) $ mapFactors $ sort xs

There doesn't seem to be a reason to filter out the []s.

List comprehensions neatly let us skip the empty tail, and get rid of go.

mapFactors :: [Int] -> [[Int]]
mapFactors xss = [filter ((==0) . (`mod` x)) xs | x:xs <- tails xss]


Convenience function to save and load pickle objects

A few general tips:

Have a function name that indicates what the function does.  If it's hard to come up with a name that describes the function's purpose (e.g. because it does totally different things depending on what argument you pass it), it's a clue that the function needs to be broken up into multiple functions with clearer purposes.  It looks like your function will either save OR load depending what arguments you pass it; this is pretty bad from a software design point of view because it makes it less obvious what it's doing from the caller's perspective, and harder to verify correctness from the implementation's perspective.
Use type annotations.  These also help to make it clear what your function does, and they let you use mypy to automatically catch bugs.  Note that **kwargs are difficult to declare useful types for; any function call that takes **kwargs is impossible to check statically.  Given that your kwargs are only used to invoke func (I'm guessing func is a constructor?), I would just put the responsibility on the caller to construct the object before passing it to you; that way if the function is typed, the checking will happen in the caller's frame, rather than having your function "hide" the types and permit bugs to happen.
Don't have flags whose only purpose is to make the function a no-op.  This is needlessly confusing; if the caller wants nothing to happen, they can just not call your function.

Given those suggestions I think you'd end up with two different (and very simple) functions:

from typing import Optional

def load_pickle(file_name: str) -> Optional[object]:
   """Load a pickled object from file_name IFF the file exists."""
   return jl.load(file_name) if Path(file_name).exists() else None

def save_pickle(obj: object, file_name: str) -> None:
    """Pickle and save the object to file_name."""
    jl.dump(obj, file_name, compress=True)


The complexity here is much more than \$O(\log{n})\$. Let's go though it...

There's one \$O(o)\$ loop, where \$o\$ is the size of the outer List.

Now, for each outer loop, we then loop through all the members of innerList. If that has size \$i\$, the combined complexity is now \$O(o \times i)\$.

Inside that inner loop you then remove members of the innerList. The remove operation is horribly expensive too. First, it starts at the beginning of the list, and searches for the item to remove. When it finds it, it then goes through each remaining item in the list, and shuffles them forward one position, to 'remove' the item.

The resulting complexity that I can see here is.... \$O(o \times i^2)\$ which means, if the inner and outer data sets are about the same size (worst case), you have complexity of \$O(n^3)\$ where \$n\$ is the size of each list.

Now, that is tempered somewhat by the fact that you only do the inner remove if it actually matches something, and when it does, it makes the inner data list smaller. I don't believe this affects the complexity all that much though.

If you are looking for performance improvements, there are a few I can see.

First up, convert all the inner-member values to the key outside the outer loop and store them in a dictionary:

Dim innerKeyDict As Scripting.Dictionary
....

For Each innerValue In innerList
    innerKey = innerKeySelector.Execute(innerValue)
    innerKeyDict.Add innerKey, innerValue
Next

Then, this will save you having to recalculate the keys many times, and it also converts the lookup, and remove both to O(1) operations.

I believe, if you do this you end up with a \$O(n)\$ operation where \$n\$ is the combined size of inner and outer.


Idiomatic Clojure? Performant & functional enough?

I am a journeyman myself in clojure, and I don't have answers for all of your questions, but I have some input.

I am not sure I fully understand your algorithm, but it seems you really have two loops rolled in to one. You have an inner loop looking for what could be the next tile to paint (without counting i), and an outer loop actually filling pixels and counting i down from n. Maybe it could be clearer if you separated these two somehow.

And since you choose candidates on random, it will be random how long it takes for you to fill n tiles.

I have found that when I do:

(loop [result ()
       input input-seq]
    (let [item (computation input)]
        (recur (conj result item) (rest input)))

It can often be re-written as:

(reduce computation input-seq)

(But I can't immediately see if this applies to your function)

Have you considered implementing this using a 2d array of tiles, instead of a list of coordinates?

A couple of other issues:

you can create a function which always returns true with: (constantly true)
I really like the use of (for (map +)) for vector addition, but you can use (mapv) instead of (vector (map))


Ruby on Rails: refactor big search method

Some notes on your code:

As you know, in Rails, params usually refers to query strings in a request. In a model I'd use something like attributes or simply options to avoid confussion.
Variable cars reused multiple times: yes, it's a very usual pattern, but IMO it's not right. I think different values deserve different names.
You have a pattern to abstract here, use inject.

I gave an answer in SO a while ago with exactly this kind of problem, that's the approach I'd recommend: Approach post in SO


The main improvement with this code would be your handling of jQuery elements.  You should save them in the object literal like you did with plain elements.

Secondly, you can shorten up your code, using jQuery to pull the radio button value.

Your code might be a bit faster, as it works at a lower abstraction level, but if you do choose to use it, it might be better to abstract it out into a DOM function.

Below is the modified code.

$A.Class.create('private', {
    Name: 'Settings',
    J: {
        save_button:          $('#save_button'),
        cancel_button:        $('#cancel_button')
    },
    init: function () {
        var self = this;
        this.J.save_button.on("click", function () {
            $A.Packet.push({model: self.Name});
        });
        this.J.cancel_button.on("click", function () {
            Page.flip('fave');
        });
    },
    pre: function (packet) {
        packet.h_token = Storage.getRemembered();
        packet.privacy = this.getSaved();
        packet.state = true;
        return packet;
    },
    post: function (packet) {
        Page.flip('fave_custom');
        return packet;
    },
    getSaved: function () {
        return $('input[name=privacy]:checked', '#se_form').val();
    }
});

/* Put in a DOM abstraction library

            var form_elements = this.E.se_form.elements,
                send_value = '',
                iterator;
            for (iterator = 0; iterator < form_elements.length; iterator++) {
                if (form_elements[iterator].checked) {
                    send_value = form_elements[iterator].value;
                }
            }
            return send_value;
        }
*/


In merge you are doing list comparison (series1 != [] or series2 != []). This is expensive. You can avoid this by storing the length of two list beforehand and using that value to detect when to come out of the loop.

Also by using a small trick you can avoid using pop() function.

Avoid using continue. You can easily remove it by putting if else condition properly.

Your variable names are not indicating their actual purpose. It is recommended to use meaning names for variables.

def merge(series1, series2):

output = []
len_series1 = len(series1)
len_series2 = len(series2)
pointer_series1 = 0
pointer_series2 = 0

while pointer_series1 < len_series1 and pointer_series2 < len_series2:
    last1 = series1[pointer_series1] #the variable name is not indicating the actual task of this variable
    last2 = series2[pointer_series2]
    if last1 <= last2:
        output.append(last1)
        pointer_series1 += 1
    elif last2 < last1:
        output.append(last2)
        pointer_series2 += 1

output += series1[pointer_series1:]
output += series2[pointer_series2:]
#the above two statements removes the need to check the emptiness of each list
return output

In is_even function

if x%2== 0

can be rewritten as

if not x%2

The latter one is more 'pythonic'

If I were you I would define a function is_odd instead of is_even, because in the later part of the code you are checking whether a number is odd or not.

merge_sort can also be made more pythonic. The following code actually shows the power of Python to write complicated code in fewer lines:

def merge_sort(series):

iseries = [[i] for i in series]

while len(iseries) > 1:
    iseries = [merge(a,b) if b else a for a,b in map(None,*[iter(iseries)]*2) ]
return iseries[0]

# working explained
#iseries = [[1],[2],[3],[4]]
#iter(iseries) returns an iterable object lets say (o1)
# [iter(iseries)]*2 creates a list [o1,o1]
# map(None,[o1,o1]) calls Identity function; the arguments are o1.next() and o1.next()
# so for the first case Identity() is called on [1] (o1.next()) and [2] (o1.next())


Non sure what is the purpose to write your code in a java 8 way, please explain this part.

I think you mean using streams.

Anyway, here is an example.

Comparing with your code I introduced a filter that guarantee the key in list exists as a key in the map.

The other part are equivalent.

UPDATE: I added the _map_part that I had forgot previously.
The map can transform your list of string in a new list of different types.

In this case you use the list of string as a filter to get elements from the map. You don't want to operate on the String keys, instead you want to access the map values that are objects of type A.

list.stream()
    .filter(key -> (map.containsKey(key)))
    .map(key -> (map.get(key)))
    .forEach(a -> {
         if (a.values == null)
             a.values = new ArrayList<>();

         a.values.add(b);
     });

I think the main difference for this approach, compared with the old fashion is that you describe more your intentions, and the purpose of the code emerges much clearly.

But in trivial examples like yours the differences are not so clear and the functional approach seems much complicated.

Not all the case can be converted properly in this way, there are still cases where you whould prefer the loop over the streams.


Hanging semicolons in multiline statements

This is indeed purely personal, however, when you work in a group, or want to share your code, it's best to stick to certain conventions. A good source for this is:

http://www.php-fig.org/psr/psr-2

Eventhough these guidelines are quite good, I don't always follow them myself. For instance, I often use two spaces to indent, not four. Etc.

As for my personal opinion about any code: It should be very easy to read and understand. Your code wouldn't be accepted here, mainly due to the lack of comments and sometimes vague names. But that's not what your question is about. As for the concatenation dots, I like them at the end of lines:

$startOfLine = PHP_EOL.
               str_repeat(' ',$rbtSt_billToBox_leadingWidth);
$innerMargin = str_repeat(' ',$rbtSt_billToBox_innerMargin);
extract($statementInfoArray,'stm');
$rbt .= $startOfLine.
        padBothAndTruncate($stm_bill-to-addr1,$rbtSt_billToBox_addr_maxWidth).
        $innerMargin.
        substr($stm_bill-to-code,0,$rbtSt_billToBox_acctNum_maxWidth).
        $startOfLine.
        padBothAndTruncate($stm_bill-to-city.', '.$stm_bill-to-state.' '.$stm_bill-to-zip);

and then I align all the parts on the left side. This makes it very clear what belongs together. I am however sure there are many other ways to do this.


Making the controller clean and readable in (Ruby on Rails)

One thing you can do to simplify your controllers is use something like the scaffolding gem https://github.com/tubbo/controller_resources - that would reduce some of the boilerplate code.
For the #index method I would rewrite it chainging relations something like
  def index
    @movies = Movie.all.includes(:profile_photo)
    if params[:year].present?
      years = params[:year].split('-')
      @movies = @movies.search_on_ending_year(years.first)
      @movies = @movies.search_on_ending_year(years.last)
    end
    @movies = @movies.search_genre( params[:genre].first ) if params[:genre].present?
    # etc
    @movies = @movies.order_on_filter(params[:orders_filter].filter) if params[:orders_filter].present?
  end

If you define your scopes something like
scope search_on_ending_year, ->(year) { year ? some_condition : all }
then you can also remove the conditionals above
Note that you can combine that a simple way to check both nil? and empty? in one step is to use blank?. Likewise present? is very universal and checks that values are not nil, strings are not blank, arrays are not empty, etc
In the movie_params method
  def movie_params
    params.fetch(:movie, {}).permit(:name, :release_date, :video_quality, :synopsis, :genres, :language)
    params.fetch(:movie, {}).permit(:name, :release_date, :video_quality, :synopsis, :genres, :language, profile_photo_attributes: [:path])
  end

the first line is both redundant and ignored
I think your code would also be simpler if you structured your html to avoid array parameters like this params[:orders_filter][0]


Finding a passcode by comparing MD5 result

First of all, you have the passcode length hard-coded.  It would be better to make it a parameter, perhaps with a default value.  The same goes for the string the "interesting" hashes start with ("00000").

Also, there are several ways you could make the code more functional.  Here are a couple ideas:

Use recursion:  Computing an \$n\$ character pascode is accomplished by first computing an \$n-1\$ character passcode, then computing the next character.  Or, you could rewrite the loop in a tail-recursive form.
You could use streams.  Streams are Scala's version of a lazy list / sequence.

Using streams, we can use the following logic:

Generate a stream of consecutive Ints, starting at 0.
Combine each number in with doorId
Compute the hash of each combined string
Filter the hashes, keeping only hashes that start with five '0's
Take the sixth character of each hash
Take the first 8 - doorId.length characters, and append them to doorId

We can express this in code using something like:

def findPassCode(doorId: String): String = {
  val chars = Stream.from(0)                            // Step 1
                    .map(n => doorId + n)               // Step 2
                    .map(md5)                           // Step 3
                    .filter(h => h.startsWith("00000")) // Step 4
                    .map(h => h(5))                     // Step 5
  doorId + chars.take(8 - doorId.length).mkString       // Step 6
}


Recursive and Non-recursive SelectionSort

I'll take this a function at a time before looking at your end goal.

function findMinIndex(a){
    return a.reduce((iMin, x, i, arr) => x < arr[iMin]? i : iMin, 0);
}

The largest problem with this function is that it fails for empty arrays. findMinIndex([]) incorrectly returns 0, an index which does not exist. If the array is empty, I'd suggest returning a flag value of -1.

Since undefined is less than -Infinity, we then have to swap the comparison around to make it work with essentially the same logic.

function findMinIndex(a){
    return a.reduce((iMin, x, i, arr) => x > arr[iMin]? iMin : i, -1);
}

I would argue that this is still more complex than it needs to be. There is no need to use the arr parameter as we can just use a from the function call. (Some may disagree with me here) While we are at it, it improves the clarity to rename a to arr.

function findMinIndex(arr){
    return arr.reduce((iMin, x, i) => x > arr[iMin]? iMin : i, -1);
}

Next up:

function removeMin(a){
    idx = findMinIndex(a);
    minVal = a[idx];   // for [1, -5, 3], minVal = -5
    a.splice(idx, 1);  // [1, -5, 3] -> [1, 3]
    return minVal;
}

How this works if pretty obvious, which is good. The one issue is that you create the global variable minVal. It looks like you missed a let. Some people would tell you to avoid functions which mutate their parameters, and while I generally do this myself, since this function is very clear about what it is doing it probably isn't an issue. However, I would probably rewrite this as a one liner, or just inline it as you did in your answer.

function removeMin(a) {
    return a.splice(findMinIndex(a), 1)[0];
}

Now for your recursive function. It also creates a global variable minVal but besides that looks good to me! Really nothing to say here.

The non-recursive selection sort could certainly use some work.

function selectionSort(a) {
  var length = a.length;
  for (var i = 0; i < length; i++) {
    a.push(  // select and append at the end
      ...a.splice(
        findMinIndex( // get min in a sliced 'a'
          a.slice(0, length - i)), 1)
    );
  }
  return a;
}

Personally, I would prefer just simple for loops in this case. No need for all those function calls.

function selectionSort(a) {
    for (let i = 0; i < a.length; i++) {
        let iLow = i;
        for (let j = i + 1; j < a.length; j++) {
            if (a[j] < a[iLow]) iLow = j
        }
        // Fancy destructuring to swap indexes
        [a[i], a[iLow]] = [a[iLow], a[i]]
    }
    return a;
}

Lastly, I can't help but mention a.sort() though I know that's not the point of this exercise.


Color swatch selector with multiple mouseover and mouseout functions

HTML abuse

The HTML5 specification does not allow a
 element to have a value attribute.  You can use a data-* attribute (named data-color, for example).  A title attribute would also be reasonable.

You are misusing CSS classes as IDs.  An ID is a unique name for an individual element.  A class is a set of elements that should all be treated alike.  You should not have color and color-2 as two class names.  Rather, they should be a single class.

Confused terminology

Your wording is a bit off, in my opinion.  Each individual sample is a "swatch".  A color selector is a widget consisting of three swatches.

When you make a decision by clicking on a swatch, the swatch isn't just "active" — I would say that that color has been selected.

Based on the above, I would rename…

the color and color-2 classes both to swatch
the color-swatch class to swatch-selector
the active class to selected

jQuery

Once you rename the classes so that both widgets have the same class names, it becomes possible to write code that treats the swatch selector as a generic widget.

If you need to define both a mouseover and a mouseout handler, use hover() instead.

$(function() {
    'use strict';

    function showActiveColor($selector) {
        var selectorId = $selector.attr('id');
        var $selected = $selector.find('.swatch.selected');
        $('#active-' + selectorId).empty()
                                  .text($selected.data('color'))
                                  .css({ backgroundColor: $selected.css('background-color') });
    }

    $('.swatch-selector .swatch').hover(
        function mouseOver(event) {
            var colorName = $(this).data('color');
            var color = $(this).css('background-color');
            var selectorId = $(this).closest('.swatch-selector').attr('id');
            $('#active-' + selectorId).text(colorName)
                                      .css({ backgroundColor: color });
        },
        function mouseOut(event) {
            showActiveColor($(this).closest('.swatch-selector'));
        }
    ).click(function onClick(event) {
        $(this).addClass('selected')
               .siblings().removeClass('selected');
    });

    // Initialization so that you don't have to hard-code the span's
    // background-color and text to match the initial selection
    $('.swatch-selector').each(function(index, el) { showActiveColor($(el)); });
});
.swatch-selector .swatch {
    width: 25px;
    height: 25px;
    float: left;
    border: 1px solid #313131;
    margin-right: 5px;
}
.swatch-selector .swatch.selected {
    border: 3px solid #151515;
}
.color-name {
    width: 90px;
    height: 20px;
    color: #FFF;
    text-align: center;
    padding: 2px;
}

SELECTED COLOR 1:

SELECTED COLOR 2:


Well, there are a few points:

You make a copy of the object you output. That can be costly, impossible, or have undesirable side-effects. Use a constant reference instead.
There are essentially two modes for your byte_streamer: Output the raw bytes, or output as decimal values for each byte.
The latter is broken as each byte is variable-width (1-3 digits for octets), and there is no separator.
You use the member placeholder only to convey the type outT to other code. Why not use a typedef instead, avoiding inefficiency and painful contortions?
Only use std::endl if you want to flush the stream. Otherwise, using '\n' and avoiding that extra-work is simply far more efficient.
It's really unusual not to end the programs output with a line-break. Wonder where the prompt will end up if called from a terminal...

Imho, the only useful outputs would be hex-dump and raw-bytes.

class dump_hex_t {
    const void* p = nullptr;
    std::size_t s = 0;
public:
    constexpr dump_hex_t() noexcept = default;
    constexpr dump_hex_t(const void* p, std::size_t s) noexcept : p(p), s(s) {}

    template <class CharT, class Traits>
    friend auto& operator<<(std::basic_ostream<CharT, Traits>& os, dump_hex_t x) {
        ... // Dump as hex-digits however you like
    }
};

template <class T>
constexpr dump_hex_t dump_hex(const T& x) noexcept
{ return { std::addressof(x), sizeof x }; }

template <class T>
constexpr std::string_view dump_raw(const T& x) noexcept
{ return { (const char*)std::addressof(x), sizeof x }; }


Adding, deleting elements as per autocomplete results

I know that this comes a few years late and the code doesn't appear to exist on the github repository anymore. Perhaps you have learned much more about jQuery and the autocompletes since posting this but none-the-less here is a review of it.

It is great that the DOM reference for the category input (i.e. $("#category_inp")) is stored in a variable but others could be also - like the container for the list of selected categories (i.e. $("#category_list")).

Instead of binding the enterKey event to a callback, why not use the select event callback option? That way if the user selects an option with the mouse the callback will also be called.

And for the delete image click handler, it could be simplified using .parent():

$(document).on('click', ".delete-cat", function (e) {
    $(this).parent().remove();
});


Nice first post!

There are things that std::unique_ptr provides which are absent here, notably the aliasing constructor (so you can own the containing object of what's referenced) and weak pointers (so cached values don't cause unwanted object retention) but otherwise, this is pretty good.

Omissions

I had a couple of compilation errors, because it's missing #include <functional>.  Also, the deleter ought to have a specialization for array types (which need delete[] p; instead of delete p;).

Naming

On naming, I'd probably choose something like release() for what you've called free() - but that's probably just because of half a lifetime writing C.

Copy and swap

You mention the copy-and-swap idiom; this is how you'd use it for your assignment operator:

template<typename T>
SharedPointer<T>& SharedPointer<T>::operator=(SharedPointer rhs)
{
    swap(rhs);
    return *this;
}

Notice that we pass rhs by value, which means we're getting the copy constructor to do all the work for us.  Having swapped, rhs has our old value, which is then destructed at the end of the function, so we don't have to duplicate the work of the constructor.

Move-assignment

Move assignment doesn't need to reset rhs - just perform the swap, and expect the moved-from value to be destructed soon:

template <typename T>
SharedPointer<T> &SharedPointer<T>::operator=(SharedPointer &&rhs) noexcept
{
    swap(rhs);
    return *this;
}

Swap

The swap function doesn't need to be a friend, as it uses only the public interface of the shared pointer.

Use default arguments to simplify

You can reduce the number of constructors, like this:

SharedPointer(T *ptr = nullptr,
              const std::function<void(*)> &del = Deleter())
    : p(ptr),
      use_c(new std::size_t(ptr!=nullptr)),
      deleter(del)
{ }

This is also true for the reset() method.

Reset should change deleter

The condition in reset() skips changing the deleter if there's no change to the pointer.  But we might be calling reset() for exactly that purpose.  Also, if a null pointer is passed as the new value, it's treated the same as a non-null pointer.  Both of these problems can be avoided by using swap() and default arguments (to re-use our constructor and destructor):

    // declaration
    void reset(T* = nullptr, const std::function<void(T*)>& = Deleter());

template <typename T>
void SharedPointer<T>::reset(T *rhs, const std::function<void(T*)>& del)
{
    swap(SharedPointer(rhs, del));
}


split up a string into whitespace-seperated fields

Your code looks quite nice, but here are a few nitpicking comments, for what they are worth.

Missing headers, but I assume you just didn't paste them.
split_up should be static and get a better name
variable names are odd. argc/argv are the usual names for main() (missing here) but not for functions. I'd use tokens instead of argv, and maybe n instead of argc. Okay, n is not at all descriptive, but for such a short function it need not be.
assigning string to p gains nothing, as the original value is not required later on.
perhaps use braces, even for 1-line statements following while, for, if etc
I prefer to leave a space after keywords (while, if, etc)
when breaking out of the loop, why not do it immediately:

if (*p == '\0') {
    break;
}
argv[argc++] = p;

The while loop following this knows that *p is initially not \0, so put the check for that 2nd. Also it is better to add brackets round conditions, even if you think the precedence is obvious:

while(!isspace(*p) && (*p != '\0')) {
    p++;
}

you could also just check for *p instead of *p == '\0'.  But many will disagree.
you also have two blank lines near the end of split_up that make the code look a little messy.

Note also that you don't check for overflow of the argv array.  Okay, you gave it 1000 places for the purpose of the example and that is unlikely to overflow. But in practice you will use somewhat less than 1000 and overflow will be more likely.

And finally, my preference is not to nest loops. Your two nested while loops could be extracted into inline functions - they might be useful in themselves, after all. Here is an example with the loops extracted; you don't have to like it - it is just an example. I find this easier to read, but yours might well be slightly quicker, if that matters.

static inline char* next_token(char *p)
{
    while (isspace(*p)) {
        ++p;
    }
    return *p ? p : NULL;
}

static inline char* next_space(char *p)
{
    while (!isspace(*p) && *p) {
        ++p;
    }
    return *p ? p : NULL;
}

static int string_split(char *p, char* token[])
{
    int n = 0;
    while ((p = next_token(p)) != NULL) {
        token[n++] = p;
        if ((p = next_space(p)) == NULL) {
            break;
        }
        *p++ = '\0';
    }
    return n;
}

Or you could consider using strspn and strcspn and define your own whitespace characters...


Overriding the mouseout handler for an image when a button is clicked

It is bad practice as you add a new handler each time your event is fired.

To better understand this, try this:

$('p')
  .on('click', function(e) {
    console.log('1');
    $(this).on('click', function(e) {
      console.log('2');
    });
  });

  click me

Each time you click "click me", it should log one more "2".

A better way is to refactor your code to use a flag

(function() {
    var flag = true;

    $('#targetBtn')
        .on('mouseover', function(e) {
            $(this).find('img').attr('src', 'images/_hover.png');
        })
        .on('mouseout', function(e) {
            if(flag)
                $(this).find('img').attr('src', 'images/_mouseout.png');
            else
                $(this).find('img').attr('src', 'images/_selected.png');

            // or
            // $(this).find('img').attr('src', (flag ? 'images/_mouseout.png' : 'images/_selected.png'));
        })
        .on('click', function(e) {
            flag = false;
            $(this).find('img').attr('src', 'images/_selected.png');
        });
})();

See this demonstration to grasp the result:

(function() {
  var flag = true;

  $('#targetBtn')
    .on('mouseover', function(e) {
      console.log('src', 'images/_hover.png');
    })
    .on('mouseout', function(e) {
      if (flag)
        console.log('src', 'images/_mouseout.png');
      else
        console.log('src', 'images/_selected.png');

      // or
      //console.log('src', (flag ? 'images/_mouseout.png' : 'images/_selected.png'));
    })
    .on('click', function(e) {
      flag = false;
      console.log('src', 'images/_selected.png');
    });
})();

btn


Areas to fix/improve:

Namings

The function names like split_full_name_and_filter_stop_word, check_and_update_username_to_unique and alike are considered as anti-patterns for function naming.
run_and_fly or think_or_talk like names point to ambiguity or excessive responsibilities assigned to a function.A function should have a concrete responsibility. Therefore, you need to analyze those functions and apply whether Rename function or Extract function (in your case - split a function into several functions each with separate responsibility) technique.

Some variable and function names are too verbose:
name_words --> just names
get_name_from_list_of_words --> just compose_username
list_of_words --> just a plural words
unique_name_list --> just unique_names

def generate_username(self, full_name, size, unique_name_list=None) method.

to avoid passing the same unique_name_list across multiple methods - it's good to pass it into UniqueNameGenerator constructor at once.
full_name = re.sub("[^\sa-zA-Z]+", "", full_name). In case if full_name happened to be empty, to avoid redundant calls of subsequent functions - it's good to add a check for that:

...
full_name = re.sub("[^\sa-z]+", "", full_name.strip(), re.I)
if not full_name:
    raise ValueError(f'Incorrect full name `{full_name}`')

either of these complements:

if self.suffix:
    username = username + self.suffix
if self.prefix:
    username = self.prefix + username

can throw TypeError in case if caller would pass non-string argument for prefix or suffix.Instead, use flexible f-string formatting:

username = f'{self.prefix}{username}{self.suffix}'

def split_full_name_and_filter_stop_word(self, full_name, size) method

the function name is better named as filter_valid_words or select_valid_words (or alike)
" ".join(full_name.split(" ")).split() - this looks like a "5-wheel bicycle that circles rounds instead of going straight".Simply words = full_name.split()
the whole construction:

words_considered = []
for word in name_words:
    ignore_word = False
    if word.lower() in self.stop_words:
        ignore_word = True
    if not ignore_word:
        words_considered.append(word)

is a verbose "invention" of a simple list comprehension with if constraint:

valid_words = [w for w in words if w.lower() not in self.stop_words]

The restructured function would look as:

def filter_valid_words(self, full_name, size):
    words = full_name.split()
    if len(words) > size:
        words = words[:size]

    return [w for w in words if w.lower() not in self.stop_words]


Project Euler #70: Time Efficiency Improvement

Several minutes? My stupid approach takes 1.3 second. It uses precomputed factoring of numbers below 1e7, which itself takes 0.3 s.
List<Integer> l = new ArrayList<Integer>();
int[] primes = Helper.getPrimes(10000050);
for (int i = 378; i >= 1; i--) {
    for (int j = 239118; j > i; j--) {
        BigInteger num = BigInteger.valueOf(primes[i]).multiply(BigInteger.valueOf(primes[j]));
        if (num.compareTo(BigInteger.TEN.pow(7)) < 1) {
            int x = num.intValue();
            System.out.println(primes[i] + " * " + primes[j] + " = " + x);
            l.add(x);
        }
    }
}

BigInteger??? That's the culprit. The solution is a few millions and confortable fits into an int. Using long would give me a good feeling. Using Guava's LongMath.checkedMultiply would give a guaranty I'm not computing non-sense. And so would my saturated arithmetic.
BigInteger.valueOf(primes[i])

this should be done before the inner loop,
or better stored in an array

BigInteger.TEN.pow(7)

this is a contant and shouldn't be recomputing again and again

num.compareTo(BigInteger.TEN.pow(7)) < 1
So you want that num is at most 1e7 and are scared of it overflowing 9e18? How should this happen? Not at all as i * j <= 239118**2.
Another inefficiency: Whenever num gets too big, you know it'll be even bigger for a bigger prime. So if you were iterating upwards, you could use a break. For iterating downwards, you could use one division to determine the initial j.
int y = EulerTotient(x);
In order to compute the totient, you need the factorization. But you just have thrown the primes away! Use a map or alike.
Possibly you've lost several minutes already in this part and needn't read any further.

isPermutation
if (String.valueOf(x).length() != String.valueOf(b).length()) {
    return false;

This takes probably more time than the remaining computation, which is fine. I'd go for
    do {
        ++count[x % 10];
        --count[b % 10];
        x /= 10;
        b /= 10;
        if ((x != 0) != (b != 0)) return false; // different lengths
    } while (x != 0); // also b!=0

And I wouldn't call the arguments x and b as it's confusing (there are interchangeable so should be named similarly).
EulerTotient
Method names should start with a lowercase letter. Not even the best mathematicians deserve any exception.
This part is fine, except for that you need no such computation as you actually know the factorization when you create n. For this computation, you could add
n /= primes[i];

to the if-block and gain some speed due to an earlier loop exit.
getPrimes
No problem here. One can argue that in
        for (int j = i; j * i <= maxValue; j++) {
            isPrime[i * j] = false;
        }

the expression i*j gets computed twice or that you could keep the product in a variable and just add i on each iteration, but that's what JIT excels at. So it's fine as it is.


When working with NumPy, it's best to keep all our data in the form of NumPy arrays, instead of converting back and forth between NumPy and Python data structures.

So instead of creating a NumPy array for each point and then zipping them to extract tuples of \$x\$-coordinates and \$y\$-coordinates, create one array for all the points:

p = np.random.uniform(0., 1000., (N, 2))

We can extract the \$x\$-coordinates and \$y\$-coordinates, if we need them, by transposing the array:

x, y = p.T

but we won't need to do so until the very end when we pass the data to Matplotlib.
The coordinates of the origin can be computed like this:

o = (p.min(axis=0) + p.max(axis=0)) * .5

To scale the points about the origin, use:

q = o * (1 - scale) + p * scale

instead of (as in the code in the post):

delta = p - o
q = o + delta * scale

The former is slightly quicker, as it has only two arithmetic operations on arrays as long as p whereas the latter has three.

Putting this together:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches

N = 5
p = np.random.uniform(0., 1000., (N, 2))

# Center of points, defined as the center of the minimal rectangle
# that contains all points.
o = (p.min(axis=0) + p.max(axis=0)) * .5

# Scale factor (0. < scale)
scale = 1.5

# Points scaled about center.
q = o * (1 - scale) + p * scale

ax = plt.subplot(111)
ax.scatter(*p.T, c='b')           # Original points.
ax.scatter(*o, marker='x', c='g') # Center.
ax.scatter(*q.T, c='r')           # Scaled points.
ax.add_patch(patches.Rectangle(p.min(axis=0), *p.ptp(axis=0), fill=False))
plt.show()

Here numpy.ptp stands for peak-to-peak and computes the range of values (maximum − minimum) along an axis in an array.


Which is better for checking previous object in list?

The former would definitely be more efficient.

In the latter case, you "forget" a local variable that you have available (by letting it go out of scope), and then on the next iteration get it back by calling stages.get().  There's no way that the get() call will be as cheap as simply referencing the lastDirection variable.


A reference variable will save you from that wicked code bloat!
You can make iterative calls of this Stack Overflow answer from 2012.
Code: (Demo)
function assignArrayByPath(&$arr, $path, $value, $separator = '_') {
    $keys = explode($separator, $path);
    foreach ($keys as $key) {
        $arr = &$arr[$key];
    }
    $arr = $value;
}

foreach ($array as $key => $value) {
    unset($array[$key]);
    assignArrayByPath($array, $key, $value);
}
var_export($array);

Or boil it down to this: (Demo)
function assignArrayByPath(&$result, $path, $value) {
    foreach (explode('_', $path) as $key) {
        $result = &$result[$key];
    }
    $result = $value;
}

$result = [];
foreach ($array as $key => $value) {
    assignArrayByPath($result, $key, $value);
}
var_export($result);

This technique will require that you build logical (non-monkey-wrenching) paths as keys.  I mean:

If after 'max_size_photo' => 8000, you declare 'max' => 10000, then you will get an error.
If after 'max_size_photo' => 8000, you declare 'max_size' => 10000, then you will erase the previously expanded (deeper) elements from the output array.

p.s. You can also write it without any custom functions by nesting the loops so long as you maintain the technique of using a reference variable inside of a reference variable.  Trippy, right?
Code: (Demo)
$result = [];
foreach ($array as $path => $value) {
    $ref = &$result;
    foreach (explode('_', $path) as $key) {
        $ref = &$ref[$key];
    }
    $ref = $value;
}
var_export($result);


Determine if a string is a sequence of dictionary words

"""DocStrings"""

+1 for adding a doc string to the wordBreak() method, but -1 for not having any content in it.

PEP-008

Your code diverges from the PEP-008 guidelines in several areas:

Use snake_case for functions and variables, not mixedCase.
Use a single space around operators (elif i > len(s):), not 2 spaces, and then no spaces.
Add a blank line between the inner prune() function and the outer function, as well as between the class Solution and its first method.

Use pylint or pyflakes or similar to ensure your code follows proper conventions.

Variable Names

Variable names like s are very terse, but since it is given that name in the question, is forgivable.

Variable names like wordDict are misleading, and should be avoided!  wordDict is actually a list, not a dict.  Although that name was given in the question, you should correct it to word_list, or simply words to avoid confusion.  (+1 for the type hint; it helps avoid some confusion.  But rename the parameter anyway.)

i is acceptable as a loop index, but there is no obvious loop.  idx or pos may improve clarity.

m is unacceptable.  It in no way suggests it is the length of a word.  Use a more descriptive variable name.

Dead Code

elif i > len(s):
    return False

At what point will this branch every be taken?  The only way is if prune(i+m) is called when i+m is greater than len(s).  But if m is the length of word, and s[i:i+m] == word is true, it is impossible for i+m to exceed len(s).  This branch is dead code, and can be removed.

Algorithmic Improvements

You are sorting your "dictionary" by length, so that you check the longest words first.  However, this doesn't actually guarantee any speed improvements.  At any step, if the next possible word is the shortest one, you've guaranteed it will be the last one checked.  Ditch the sort.

What you want to do is reduce the number of words from the "dictionary" you are testing at each step.  One obvious way would be to turn the "dictionary" into an actual dict, say, storing the list of words which start with a given letter:

word_dict = {
              "a": ["apple"],
              "p": ["pen"],
            }

Or more programmatically:

word_dict = defaultdict(list, ((word[:1], word) for word in wordDict))

Then at each step, instead of comparing s[i:i+len(word)] to each and every word in wordDict, you would compare to the list of words in word_dict[s[i:i+1]], which should be significantly smaller.

This method will degenerate if all the dictionary words start with the same letter (["aaaa", "aaab", "aaac", "aaad"]), but you could handle this by storing the dictionary as a tree structure instead.

Another alternative would be to separate wordDict into sets of words of different lengths:

words_by_length = { 3: { "pen" }, 5: { "apple" } }

Then, at each stage, you could do a single set containment test for each word length:

for word_length, word_list in words_by_length.items():
    if s[i:i+word_length] in words_list:
        # ...


Array that stores values from two ranges and compares if one cell is blank

The fileArray variable can be replaced with 2 variables. When looking at fileArray in the locals window, from the IDE menu at the top View>Locals Window, you can see that it's it a Variant/Variant(0 to 1). Expanding that by clicking on the + icon to the left of the variable name it it contains two sub arrays. fileArray(0) and fileArray(1) are both of type Variant/Object/Range. These are distinct areas that should be named respectively. customerArea for those in column B and cifArea for those in the same column as targetCol let you refer to these ranges directly.

Because these variables house information stored vertically, that is X rows tall by 1 column wide, you can reference the rows by customerArea(checkRow).Value2. Doing this allows you to write self documenting code. Rather than

If fileArray(1)(1) = vbNullString And fileArray(0)(1) <> vbNullString Then

You have

If customerArea(checkRow).Value2 = vbNullString And cifArea(checkRow).Value2 <> vbNullString Then

I'm torn between how to go about checking each of the rows. Mulling it over I decided on extracting the check into a Sub. I added a guard clause, endRow > customerArea.Rows.Count Or endRow > cifArea.Rows.Count, that raises an error if the end row exceeds the number of rows in each area that's checked. You could also add a guard clauses to ensure that startRow >= 1, or ensure that customerArea.Rows.Count = cifArea.Rows.Count or any others you deem appropriate, but that I'll leave for you.

Instead of checking each row explicitly I condensed that with a For...Next statement and used a descriptive variable checkRow to let you know which row you're checking.

Private Sub CheckForEmptyCellsIn(ByVal customerArea As Range, ByVal cifArea As Range, ByVal startRow As Long, ByVal endRow As Long)
    Const InputMessage As String = "Please enter the CIF Number for "

    Const InvalidArgument As Long = 5
    If endRow > customerArea.Rows.Count Or endRow > cifArea.Rows.Count Then
        Err.Raise InvalidArgument, "CheckForEmptyCells Sub", "endRow argument exceeded number of rows in"
    End If

    Dim checkRow As Long
    For checkRow = startRow To endRow
        If customerArea(checkRow).Value2 = vbNullString And cifArea(checkRow).Value2 <> vbNullString Then
            customerArea.Parent.Range("CIF_" & checkRow).Value2 = InputBox(InputMessage & vbCrLf & cifArea(1).Value2)
        End If
    Next
End Sub

This refactoring leaves you with

Public Sub CodeReview()
    Dim loanData As Worksheet
    Set loanData = Worksheets("Loan Data")
    Dim finalRow As Long
    finalRow = loanData.Range("B" & Rows.Count).End(xlUp).Row
    Dim targetCol As Long
    targetCol = loanData.Range("A1").EntireRow.Find("CIF #").Column

    CheckForEmptyCellsIn loanData.Range("B2:B" & finalRow), _
                        loanData.Range(loanData.Cells(2, targetCol), loanData.Cells(finalRow, targetCol)), _
                        1, 8
End Sub


Extracting values from refs pointing to form inputs

These lines let firstName = this.refs.firstName.value.trim(); look like a code duplication to me. Could they be rewritten into something more elegant?

Looks ok to me. These fields are too few to be generalized by some generalization logic.

Now if the form does grow, you can just get a reference to the <form> and do a quick querySelectorAll for all input elements, including select and textarea that have a name.

var inputs = this.refs.form.querySelectorAll('input[name]');

You can then loop through them, get the name and value and use it as key and value for your object. For simple cases, this works. A slightly more complicated case is handling complex names like foo[a] and foo[b] which is usually interpreted as {foo: {a : 'value', b: 'value'}}.


Finding the output of sequence (a + 2^(i*b))

Performance

I tested your code, like so:

int r=0,c=1;
Deque<Integer> list = new ArrayDeque<>(1501);
list.add(500);
for (int x = 0; x < 500; x++)
{
    list.add(50);
    list.add(50);
    list.add(15);
}
long start = System.nanoTime();
int t=list.pop();
for(int i=0;i<t;i++){
    int a=list.pop();
    int b=list.pop();
    int n=list.pop();
    r=a;
    for(int j=0;j<n;j++){
        if(j==0)
            c=1;
        else
            c=c*2;
        r= r +c*b;
        System.out.print(r +" " );
    }
    System.out.println( );
}
long end = System.nanoTime();
System.out.println((end-start)+" nanos");

The resulting code prints "155156556 nanos", so took 155 milliseconds in total to run. I did a few more attempts and got durations in the range 120-145 millseconds.

When you say "have taken too much time to code the solution for this problem", did you mean "I took too long programming this"? Because there's no way to write code faster once it's written - the time has already been spent. 155 milliseconds for the largest inputs, for me, is fast enough.

I do not see any real opportunities for performance improvements. You could, in theory, do this:

        r=a + b;
        c = 1;
        System.out.print(r + " ");
        for(int j=1;j<n;j++){
            c=c*2;
            r= r +c*b;
            System.out.print(r +" " );
        }
        System.out.println( );

This would skip one cycle from the loop and remove a branch. Testing this version gives no large difference, and I see durations in the 120-140 ms range as well. Basically, I think the current version you have is good enough.

If you do want to go FASTER, though, here's what you'd do:

Don't print any output. The resulting code runs within a millisecond. String concatenation and output buffers hate you big time. Using StringBuilder gets the calculations down to 80 ms, but then printing the result takes another 40 ms.

The code you have will run about as fast as things will go.

Readability

What you can improve on is readability. For one, I'd add spaces around operators:

int r = 0, c = 1;
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for(int i = 0; i < t; i++){
    int a = sc.nextInt();
    int b = sc.nextInt();
    int n = sc.nextInt();
    r = a;
    for(int j = 0; j < n; j++){
        if(j == 0)
            c = 1;
        else
            c = c * 2;
        r = r + c * b;
        System.out.print(r + " ");
    }
    System.out.println();
}

Other things you could do is make use of += and *=:

            c *= 2;
        r += c * b;

In case of c * 2, though, you could shift all the bits left by 1 space, as that results in "multiply by 2"...

c <<= 1;

But maybe that's hard to read for others, so I would stick with *=.


Checking which pypi packages are Py3k-only

import xmlrpc.client

# pypi language version classifiers
PY3 =  ["Programming Language :: Python :: 3"]

Why do you have a single string in a list?

PY2 =  ["Programming Language :: Python :: 2"]
PY27 = ["Programming Language :: Python :: 2.7"]
PY26 = ["Programming Language :: Python :: 2.6"]
PY25 = ["Programming Language :: Python :: 2.5"]
PY24 = ["Programming Language :: Python :: 2.4"]
PY23 = ["Programming Language :: Python :: 2.3"]

You should put all these strings in one list.

def main():
    client = xmlrpc.client.ServerProxy('http://pypi.python.org/pypi')

    # get module metadata
    py3names = [name[0] for name in client.browse(PY3)]
    py2names = [name[0] for name in client.browse(PY2)]
    py27names = [name[0] for name in client.browse(PY27)]
    py26names = [name[0] for name in client.browse(PY26)]
    py25names = [name[0] for name in client.browse(PY25)]
    py24names = [name[0] for name in client.browse(PY24)]
    py23names = [name[0] for name in client.browse(PY23)]

If you put the python 2.x versions in a one list, you should be able to fetch all this data
into one big list rather then all of these lists.

    cnt = 0

Don't uselessly abbreviate, spell out counter

    for py3name in py3names:
        if py3name not in py27names \
           and py3name not in py26names \
           and py3name not in py25names \
           and py3name not in py24names \
           and py3name not in py23names \
           and py3name not in py2names:
            cnt += 1

I'd do something like: python3_only = [name for name in py3name if py3name not in py2names]. Then I'd get the number of packages as a len of that.

    print("Python3-only packages: {}".format(cnt))

main()

Usually practice is to the call to main inside if __name__ == '__main__': so that it only gets run if this script is the main script.


Clojure performance for solving Project Euler 72 (counting proper reduced fractions)

(time (solve))

=> "Elapsed time: 27363.381633 msecs"

Replace aset with aset-int:

(defn solve []
  (let [limit 1000000
        phi (int-array (range (inc limit)))]
    (loop [i 2 acc 0]
      (if (= i (aget phi i))
        (loop [j i]
          (if (<= j limit)
            (do (aset-int phi j (/ (* (aget phi j) (dec i)) i))
              (recur (+ j i))))))
      (if (< i limit)
        (recur (inc i) (+ acc (aget phi i)))
        acc))))

(time (solve))

=> "Elapsed time: 443.570909 msecs"

This is still three times slower than the Java, but not out of sight.

I thought the original might be using type reflection, but ...

(set! *warn-on-reflection* true)

... produces no response to the original code.


Updating items of one List that match another List

Your code is O(n m), where n is the length of a and m is the length of b.

You could make it O(n + m) (assuming only a small number of items from a match each item in b) by using a hash table. One possible way to do this is to use ToLookup():

var aLookup = a.ToLookup(x => new { x.MatchA, x.MatchB });

foreach (var bItem in b)
{
    foreach (var aItem in aLookup[new { bItem.MatchA, bItem.MatchB }])
        aItem.ToUpdate = bItem.ToUpdate;
}

Another way to do basically the same thing would be using join:

var pairs = from bItem in b
            join aItem in a
              on new { bItem.MatchA, bItem.MatchB } equals new { aItem.MatchA, aItem.MatchB }
            select new { bItem, aItem };

foreach (var pair in pairs)
    pair.aItem.ToUpdate = pair.bItem.ToUpdate;

Also, you should really use better variable names.


LeetCode "Jewels and Stones": counting certain characters in a string

Caution — naïve application of big-O analysis will lead you astray here!

First of all, you should be more precise about what you mean by "n".  In this problem, there are |J| and |S|: the lengths of J and S.  Your first approach is O(|J| |S|); your second one is O(|J| + |S|).

More importantly, big-O analysis only tells you how well an algorithm scales to handle large inputs.  In this challenge, though, |J| and |S| are at most 50 — very small inputs, by computer standards.  That means that the constant factors, which are disregarded in big-O analysis, actually matter.  (Another way to look at it: with those limits, |J| and |S| are both O(1), so any sane solution is also O(1)!)

Consider how much code is involved in making a HashSet.  A HashSet is actually a disguise for a HashMap.  A HashMap is implemented as an array of trees, each containing Map.Entry objects.  The array should be optimally sized to hold all the characters of J with no hashcode collisions, but you neglected to specify size hints when calling the HashSet<>() constructor.  Then, you have to insert each character of J, which involves boxing a char into a Character, calculating its hashcode, making a Map.Entry for it, and inserting it into the HashMap's table.  The problem is, Java makes it easy to execute a lot of operations without making you aware of how much work it actually is!

Since the challenge states that all characters are letters — which I interpret to mean the 52 letters in the English alphabet, you could achieve an efficient test of membership in J using a simple lookup table:

public int numJewelsInStones(String j, String s) {
    boolean[] jewels = new boolean[128];
    for (int i = 0; i < j.length(); i++) {
        jewels[j.codePointAt(i)] = true;
    }
    int count = 0;
    for (int i = 0; i < s.length(); i++) {
        if (jewels[s.codePointAt(i)]) {
            count++;
        }
    }
    return count;
}


Probably, you could do something similar by ... and succ.

enum Foo ( XA => 17, XB => 19, XC => 2, XD => 17, XE => 1, XF => 99 );
enum Goo < YA YB >;
XC, *.succ ... XE andthen .say

Thus your example could be rewritten

use Test;

subset EnumMember of Enumeration;

multi sub infix:<..>( EnumMember:D ::T $a, T:D $b ) {
    $a, *.succ ... $b
}

multi sub infix:<..>( EnumMember $a,  $b ) {
    die 'Can only do ranges for members of the same enum'
}

enum Foo ( XA => 17, XB => 19, XC => 2, XD => 17, XE => 1, XF => 99 );
enum Goo < YA YB >;

is-deeply( ( XC..XE ).Array, [XC, XD, XE] );
dies-ok({ XA..YB });

But you get Seq, not Range. So I prefer redefine the sequence operator ... and make a new role instead of a subtype.

use Test;

role EnumMember {};

multi sub infix:<...>( EnumMember:D ::T $a, T:D $b ) {
    $a, *.succ ... $b
}

multi sub infix:<...>( EnumMember $a,  $b ) {
    fail 'Can only do sequence for members of the same enum'
}

multi sub infix:<…>( EnumMember $a,  $b ) {
  $a ... $b
}

enum Foo does EnumMember ( XA => 17, XB => 19, XC => 2, XD => 17, XE => 1, XF => 99 );
enum Goo does EnumMember < YA YB >;

is (XC … XE), (XC, XD, XE);
dies-ok { XA … YB };


Program that prints out repetitions of 3 and 5

Moderation Note: This answer was being typed at the same time as the asker changed his code, to avoid this bug. Here's the code, as it was, when this answer was typed:

  Program that prints out repetitives of 3,5 and both of them

public static void main(String args[]) {

       for(int i = 1; i < 101; i++)
       {
           if(i%3 == 0)
           {
           System.out.println("repetitive of 3");
           }

           else if(i%5 == 0)
           {
           System.out.println("repetitive of 5");
           }

           else if(i%5 == 0 && i%3 == 0)
           {
           System.out.println("repetitive of 3 and 5");
           }
           else{
               System.out.println(i);
           }
       }
   }
}

First of please format your code properly as it helps to read it. I've formatted the code as it is suggested for java:

public static void main(String args[]) {
    for (int i = 1; i < 101; i++) {
        if (i%3 == 0) {
            System.out.println("repetitive of 3");
        } else if (i%5 == 0) {
            System.out.println("repetitive of 5");
        } else if (i%5 == 0 && i%3 == 0) {
            System.out.println("repetitive of 3 and 5");
        } else {
            System.out.println(i);
        }
    }
}

Now for the review:

The third if will never be reached as the first if already matches.

So to get the result wanted you have to change the first and third if branch:

public static void main(String args[]) {
    for (int i = 1; i < 101; i++) {
        if (i%5 == 0 && i%3 == 0) {
            System.out.println("repetitive of 3 and 5");
        } else if (i%5 == 0) {
            System.out.println("repetitive of 5");
        } else if (i%3 == 0) {
            System.out.println("repetitive of 3");
        } else {
            System.out.println(i);
        }
    }
}

Using the method main() for small tests is fine but it is better to create objects and use them from the beginning.

Else the program look good so far.


static {
    factoryMap = new HashMap<String, LoggingFactory>();
}

private static HashMap<String, LoggingFactory> factoryMap;

can be simplified to the following without any changes in functionality:

private static final Map<String, LoggingFactory> factoryMap = new HashMap<>();

public class LoggingInitializer {
    public LoggingInitializer() {
        LoggingFactory.register("ConsoleOutputLogger", new ConsoleOutputLoggingFactory());
        LoggingFactory.register("FileOutputLogger", new FileOutputLoggingFactory());
        LoggingFactory.register("ConsoleErrorLogger", new ConsoleErrorLoggingFactory());
        LoggingFactory.register("FileErrorLogger", new FileErrorLoggingFactory());
    }
}

The initialization of a class only happens in it's initializer blocks. Nowhere else.
What you're doing here is wiring up dependencies. Use  a DI framework for that ...

If you were going to set up the factories this way in the first place, you could've just not have them register themselves. It's weird that they register themselves anyways. That results in the following changes:

LoggerFactory implementations don't need to be derived from LoggingFactory to have access to the factoryMap, only to conform to the getLogger interface.
Actually the getLogger interface is what you'd have in a functional interface in modern Java.

This results in simplifications to your API. Instead of explicitly constructing factories and using getFactory, you're off much better hiding the implementation detail of Factories and instead using a Facade, like so:

public static final class LoggingFactory {
    private static final Map<String, Supplier<ILogger>> factoryMap = new HashMap<>();
    static {
        ILogger consoleOutLoggerSingleton = new ConsoleOutputLogger();
        factoryMap.put("ConsoleOutputLogger", () -> consoleOutputLoggerSingleton);

        ILogger fileOutputLoggerSingleton = new FileOutputLogger();
        factoryMap.put("FileOutputLogger", () -> fileOutputLoggerSingleton);

        ILogger consoleErrorLoggerSingleton = new ConsoleErrorLogger();
        factoryMap.put("ConsoleErrorLogger", () -> consoleErrorLoggerSingleton);

        ILogger fileErrorLoggerSingleton = new FileErrorLogger();
        factoryMap.put("FileErrorLogger", () -> fileErrorLoggerSingleton);
    }

    public static ILogger getLoggerFor(String name) {
        return factoryMap.getOrDefault(name, () -> new NoOpLogger()).get();
    }
}

This cuts away the "man in the middle" of your factory, not to mention the initialization outside the class. It also is more in line with usual Java logging APIs, where you directly obtain the logger.

In closing you should be aware that reinventing logging is usually a "Bad Idea™". If this hadn't been prefixed, I'd have washed your head for it :)

Finally: Just because there is a factory, the client of you API doesn't need to know- Generally the less indirection your API has, the easier it will be to use. Strive to minimize ways through your API.


You are calling queries in a for-loop for each day. Database queries are slow compared to C# code execution. Send only one query to the DB for the whole range of days.

You can do the grouping by day either as DB query or query the ungrouped records and group using LINQ-to-Objects later.

Also you are querying the lstSalesRepIDs within the loop. Why? The teamId seems not to change between the loop iterations. Query it before the loop.

Also your where-clause tests the days like this: o => o.DateCompleted >= dtStartDate && o.DateCompleted <= dtEndDate. Where dtEndDate is one day more than dtStartDate. It looks to me as if you were taking two days at a time. Is this intended? If you want to include all times of a single day, change the comparison to o.DateCompleted >= dtStartDate && o.DateCompleted < dtEndDate. (Note: I used < instead of <= for the upper bound.)

Don't make date calculations by converting from DateTime to string and back! DateTime contains all the functionality you need, without using any dirty tricks.

var salesRepIDs = new HashSet<int>(ppdb.ProPit_User
    .Where(ppu => ppu.teamID == teamId)
    .Select(ppu => ppu.SalesRepID)
    .AsEnumerable()); // HashSet.Contains is faster than List.Contains.

DateTime today = DateTime.Today;
DateTime startDate = new DateTime(today.Year, today.Month, 1);
DateTime endDate = today.AddDays(1);

// Note: If the DB contains no entries with future dates,
//       you can drop the test for the upper date!
var orders = db.Orders
    .Where(o => o.DateCompleted >= startDate
                && o.DateCompleted < endDate
                && (o.Status == 1 || o.Status == 2)
                && o.Kiosk != 0)
    .AsEnumerable();

// Because of AsEnumerable() we are working with LINQ-to-Objects now.
var ordersByCompletionDate = orders
    .Where(o => salesRepIDs.Contains(o.SalesRepID))
    .GroupBy(o => o.DateCompleted.Date); // .Date in order to drop the time part.
foreach (var dayGroup in ordersByCompletionDate) {
    decimal daylyTotal = dayGroup.Sum(o => o.OrderTotal);
    // ...
}

.AsEnumerable() has the advantage over .ToList() that the source is consumed on the fly, item by item. No in-memory list needs to be created.

The salesRepIDs.Contains(..) part requires special attention. It could be performed as part of the DB query; however depending on the implementation and the number of salesRepIDs this could create queries with long IN lists: WHERE id IN (1, 2, 3, ..). There is a limit for the length of these lists. This can lead to "Query too complex" exceptions. If this is not the case, i.e., if you know that you will always have a reasonable number of ID's, could can simplify the whole code and do everything (filtering, grouping and summing) with only one single DB query.


Chrome extension to get youtube video's URL

I don't know Javascript, but I will review the bash part.

First, replace if [ $count != 0 ]; then with if [ "$count" -ne 0 ]; then.  The double quotes are a best practice though not crucial in this case (more on that later).  The -ne is for arithmetic comparisons; != is for string comparisons.

The next bit which jumped out at me was:

if [ $filename != mergedList ]; then
    rm $filename
fi

Two things here: One, unless you have a very specific reason not to, you should always put $variablenames in double quotes.  Otherwise special characters can break your script.  (You did the same thing earlier in the script with YTBSTR and count, but those don't really matter because due to the way you assigned their value, you can determine that it is safe.  Still, it wouldn't hurt to double quote them.)  In this context the lack of double quotes is not safe.

(Actually I read somewhere that putting the static value first is safer, i.e. [ mergedlist != "$filename" ], but I don't know enough to be sure if that is true or to explain why.)

Two: This line compares a string $filename which was gotten from a file glob for *.txt, with a static string mergedList.  The two will never, ever match.  $filename will always end in .txt because of the way it is defined.  So you may as well remove that check entirely!

Next, you should single quote the output of echo.  In this case your echo commands will work, but for instance if you remove the space after the ! you will get an error.  Single quoting disables all special character interpretation.

There are definitely some other things here to fix—for instance there seem to be some assumptions made about the file mergedList that could cause weird errors or even security holes—but the above is a start.


Using a Boolean method that never returns "false" to check user permissions

The Question

The approach is acceptable and it's perfectly valid to use a method like canPerformAction. But it shouldn't return an unused boolean and can be static:

private static void ensureUserAuthorized(User user) throws ForbiddenActionException {
  if (user == null) {
    throw new ForbiddenActionException("message");
  }
  if (!user.belongsToCompany(company)) {
    throw new ForbiddenActionException("message");
  }
}

Other Stuff

The boilerplate response building instructions return Response.status... in service methods can be avoided in two ways:

1) Create an ad-hoc shortcut method like

private static Response buildResponse(Status status, Object entity) {
  return Response.status(status).entity(entity).build();
}

Or, better

2) If you are using Jersey behind your JAX-RS annotations, add an exception mapper class:

@Provider
public class ForbiddenActionMapper implements ExceptionMapper<ForbiddenActionException> {

  @Override
  public Response toResponse(ForbiddenActionException ex) {
    return Response.status(Response.Status.FORBIDDEN)
                   .entity(ex.getMessage())
                   .type(MediaType.APPLICATION_JSON)
                   .build();
  }
}

In this second case the service method can be shortened as follows:

@POST
@annotations...
public Contact saveContact(@PathParam("id") String id, Person contact) throws ForbiddenActionException {
  return saveContact(getUser(), contact);
}


Sum(), ForEach() with Lambda in a hierarchical List Collection

You can create lookup for children. That will involve single enumeration over items collection instead of enumerating all items for each calculation of each item.

I.e. you currently have 2 * N * N iterations for calculating child count and child item count. With lookup you will have N + N + N iterations

var children = items.ToLookup(i => i.ParentId);

foreach(var item in items)
{
    var subitems = children[item.Id];
    item.ChildCount = subitems.Count();
    item.ChildItemCount = subitems.Sum(i => i.DocumentCount) + item.DocumentCount;
}

Explanation: Let's look on this line

items.ForEach(z => z.ChildItemCount =
    items.Where(x => x.ParentId == z.Id).Sum(y => y.DocumentCount) + z.DocumentCount);

Here for each item in items collection you enumerate every item in items collection to get only items which are children of current. That gives you N * N iterations totally. Count is calculated same way.

Now lets look on my code.

var children = items.ToLookup(i => i.ParentId);

Here lookup is created. Internally it looks like enumerating over items and adding them to appropriate groupings of lookup. You can think of lookup as a Dictionary<TKey, List<TValue>>.

Next we do enumerating of all items (that's another N). In body of this loop we get children of item (getting appropriate group by key is pretty fast O(1) operation, comparing to enumerating all items and filtering them). Good news here is behavior of lookup when key not found - it simply returns EmptyEnumerable (i.e. empty array of TValue), so we don't need to check anything - further calculations will work without problems:

foreach(var item in items)
{
    var subitems = children[item.Id];
    // ...
}

Next we do two operations. First is getting count of items in group. Grouping implements ICollection with Count property, and it simply returns count of items in group, without enumerating them:

item.ChildCount = subitems.Count();

Second operation is calculating sum of documents in group. Thus total number of items in all groups will be N then enumerating all groups will take N iterations:

item.ChildItemCount = subitems.Sum(i => i.DocumentCount) + item.DocumentCount;

UPDATE: Thus you want ChildItemCount to contain sum


I can not express it in Lisp, but the idea is as follows:

use two pointers, at start point both to the list head. Then, increment one pointer by 1, and another by 2. If you detect two equal objects eventually, it means that list has a loop. In pseudo-code:

P0 = head;
P1 = head;
while(P0 != null and P1 != null) // Detect end of the list
  P0 = next(P0);
  P1 = next(next(P1));
  if ( *P0 == *P1 ) signal loop detected
end while

Of course, the list objects should be distinct and comparable, and next function must be correct.

Proof is not complicated. First, consider a case of "pure" loop when tail connected to head.

At step n (n'th iteration of the while loop in the code), P0 is at item (n mod N), and P1 is at item (2n mod N), which are equal if N is finite and n mod N == 0, or simply n = N

If the list has loop that starts somewhere inside, one can show that after some iterations the case will be reduced to the previous one.

Hope this helps. You can learn more about Cycle detection on Wikipedia.


Ruby tends to use two spaces for indents, rather than four.

Avoid for; it's very uncommon in Ruby and, while technically correct, doesn't make full use of Ruby's functionality. In the general case, you can replace

for a in b do

with

a.each do |b|

and the rest of the code is (probably) identical. For this case, however, since you're iterating over a range of integers, I'd suggest using upto:

1.upto(a.length-1) do |i|
  0.upto(sort_index) do |j|

Or, if you feel like you really should have for a in b or b.each do |a|, you can use 1...a.length to exclude the last element, instead of subtracting one.

Use more informative variable names -- i and j might make sense to you now, but it's rather difficult to understand if you don't already know how insertion sort works.

I don't see a difference between sort_index and i - 1, though I haven't had a chance to run it and test it yet.

You should return a if a.length == 1, not nothing, since sorting a 1-item array is still sorting. Because the sort won't do anything, you can just remove the check entirely from the first if and forget about it.

Sorts in Ruby should use <=> instead of < or > because <=> is the universal comparison operator. See the docs for Object#<=> for more information.


There isn't much to review here, but I would probably have introduced a variable for the awaited call's result, and then used a ternary to determine the outputString; the difference would have been that the awaited call would have stood out more, but there's nothing really wrong with the way you did it.

That said outputString would probably be better off as outputMessage, or simply output - having the type name in an identifier is never a sign of great naming.

I realize it's a tiny little example, but you have everything done in the UI's code-behind here - that's only good for prototype/throw-away code (which this probably is). In a real app you would have coded the logic elsewhere.


Simple python scheduled tasks script that runs once daily

You can get rid of doing any I/O and make your code cleaner in the process.

from datetime import datetime
from sheduled_tasks import daily_task1, daily_task2, weekly_task, monthly_tasks

schedule = {
    1: [daily_task1, daily_task2],
    7: [weekly_task],
    30: [monthly_tasks],
}

# this could also be the date of first invocation, just change the timestamp
arbitrary_date = datetime.fromtimestamp(1234567890)
days_past = (datetime.now() - arbitrary_date).days

for delay, tasks in schedule.items():
     if days_past % delay == 0:
        [task() for task in tasks]


The only (conceptual) problem I see in your code is that both encrypt/decrypt perform a O(n) operation (detect) for every character (so at then end it's a O(n*m) algorithm), that's unnecessarily inefficient. Build a hash object to use as an indexer:

class Caesar
  def initialize(shift, alphabet = ('a'..'z').to_a.join)
    @shift = shift
    @alphabet = alphabet
    @indexes = alphabet.chars.map.with_index.to_h
  end

  def encrypt(string)
    string.chars.map { |c| @alphabet[(@indexes[c] + @shift) % @alphabet.size] }.join
  end

  def decrypt(string)
    string.chars.map { |c| @alphabet[(@indexes[c] - @shift) % @alphabet.size] }.join
  end
end

You can also build encrypter/decrypter hash tables at initialization:

class Caesar
  def initialize(shift, alphabet = ('a'..'z').to_a.join)
    chars = alphabet.chars.to_a
    @encrypter = chars.zip(chars.rotate(shift)).to_h
    @decrypter = @encrypter.invert
  end

  def encrypt(string)
    @encrypter.values_at(*string.chars).join
  end

  def decrypt(string)
    @decrypter.values_at(*string.chars).join
  end
end


Demonstration of ChessBoard Traveling (CoderByte)

I see some things that may help you improve your code.

Fix the input parsing

The idea is sound but the implementation is flawed. Instead of the complex method currently used, I'd recommend using this single function:

std::replace_if(str.begin(), str.end(),
        [](char ch){ return !std::isdigit(ch); }, ' ');

Using this, we're guaranteed that the string will contain only spaces and digits.

Use objects

I'd suggest that one could make good use of a Point2D object to make calculations very clear:

struct Point2D {
    int x = 0;
    int y = 0;
    int dx(const Point2D &other) const {
        return x - other.x;
    }
    int dy(const Point2D &other) const {
        return y - other.y;
    }
    friend std::istream& operator>>(std::istream &in, Point2D &p) {
        return in >> p.x >> p.y;
    }
};

Reduce the numerical range for calculations

The current code uses a generic factorial which boils down to $$\frac{(dx + dy)!}{dx! dy!}$$  The maximum for \$dx\$ or \$dy\$ is 7, so the largest factorial required is \$14! = 87178291200\$.  ... Or is it?  In fact, we could consider instead how to generically calculate $$\frac{n!}{m!}$$ with \$m < n\$.  A simple way to do this is like so:

constexpr unsigned factDelta(unsigned n, unsigned m) {
    return n > m ? n * factDelta(n-1, m) : 1;
}

And the ordinary factorial function could be expressed as:

constexpr unsigned fact(unsigned n) {
    return factDelta(n, 1);
}

This can reduce the range of the multiplications somewhat, especially if we always choose the larger of \$dx\$ or \$dy\$ to divide.  This means that the return value will always be \$<= 7! = 5040\$ which easily fits into an unsigned.  Note, however, that these functions will overflow if they're given numbers outside that range.  For that reason, I'd recommend making them static functions and/or doing range checking.

Don't alter passed parameters

The current number_Of_Steps() routine takes a reference to a string and then alters the string.  It's not strictly wrong, but it's probably not the best interface design.  I would not expect that the passed string was altered.  Two ways to address this would be to pass a const reference or to simply declare the argument as std::string str which makes a local copy.  Because of the need to alter the string (by removing punctuation), I'd recommend the latter approach.

A worked example

Here's an alternative function that uses the functions and objects described above:

int alt(std::string str) {
    std::replace_if(str.begin(), str.end(),
            [](char ch){ return !std::isdigit(ch); }, ' ');
    std::istringstream in(str);
    Point2D a;
    Point2D b;
    in >> a >> b;
    int dx = b.dx(a);
    int dy = b.dy(a);
    if (dx <= 0 || dy <= 0) {
        return 0;
    }
    int m = dx + dy;
    if (dy > dx) {
        std::swap(dx, dy);
    }
    return factDelta(m, dx) / fact(dy);
}


Rewriting C# implementation of Snake class in F#

There are a few small differences in your translation. I would start with as literal a translation possible, then optimize/make idiomatic from there. If done incrementally it should be easy to spot performance problems as they occur. Here's a starting point:

(* stub *)
[<AllowNullLiteral>]
type Symbol =
  member x.Payout = [|0|]
  member x.Type = 0
  static member Add(sym1, sym2) : Symbol = null

(* stub *)
type Apple =
  abstract MySymbol : Symbol
  abstract Multiplier : int

type private BestSnake =
  | This
  | RecentSnake of Snake

and [<AllowNullLiteral>] Snake private (mySymbol: Symbol, multiplier, hit, bestSnake) as this =
  let payout = mySymbol.Payout.[hit - 1] * (match multiplier with 0 -> 1 | m -> m)
  let bestSnake =
    match bestSnake with
    | This -> this
    | RecentSnake bestRecentSnake ->
      if payout < bestRecentSnake.Payout ||
        (payout = bestRecentSnake.Payout && bestRecentSnake.MySymbol.Type = 1 && mySymbol.Type <> 1)
      then bestRecentSnake
      else null

  member val MySymbol : Symbol = mySymbol
  member val Multiplier = multiplier
  member val Hit = hit
  member val BestSnake = bestSnake
  member val Payout = payout

  new (mySymbol, multiplier, hit, bestRecentSnake) = Snake(mySymbol, multiplier, hit, RecentSnake bestRecentSnake)
  new (mySymbol, multiplier, hit) = Snake(mySymbol, multiplier, hit, This)
  new (myApple: Apple) = Snake(myApple.MySymbol, myApple.Multiplier, 1, This)

  member this.Eat(nextApple: Apple) =
    match Symbol.Add(this.MySymbol, nextApple.MySymbol) with
    | null -> null
    | resultSymbol -> Snake(resultSymbol, max this.Multiplier nextApple.Multiplier, this.Hit + 1, this.BestSnake)

The performance of this should be on par with C#.


Right, seeing as I could go on and review your code in comments, I'd thought I'd post my comments + extra review in one go instead (after all, that's what this site is for).

Starting from the top:

public function uploadFile($titulo,$file) {

A couple of niggles and suggestions

Please try to adhere to the PHP-FIG coding standards. They're not official, but there are no official standards. PHP-FIG is subscribed to by all the main players, so it's best you do, too
The $file argument is central to the entire method. Why isn't it the first argument? Suppose you want $titulo (I'm assuming it means title or something) optional, and default to a string?
What is $file meant to be? What do you expect it to be? If I am to use your class, I'd like to be able to know what I have to pass to your methods just by looking at their signature.

So, basically, I'd recommend changing your method signature to:

public function uploadFile(array $file, $titulo = 'optional default argument')
{//brace goes on new line
}

Even that wouldn't be to my liking, though. I should know I'm expected to pass a file, so why not write:

public function uploadFile(\SplFileInfo $file, $titulo = null)
{
}

In this case, you can get rid of that if (isset($file['name'])) bit, and focus on the stuff that matters.

Next:

$accepted_types = array(
                'application/zip',
                'application/x-zip-compressed',
                'multipart/x-zip',
                'application/x-compressed',
                'application/x-rar-compressed',
);

Now every time this method gets called, the array above will be constructed. After the function returns, its ref-count will (or should) be zero, and it'll get GC. If you want to call this method more than once, or if you want to re-use this class for other file manipulations, you should turn this into a property:

class Downloads
{
    private $accepted_mimes = array(
                'application/zip',
                'application/x-zip-compressed',
                'multipart/x-zip',
                'application/x-compressed',
                'application/x-rar-compressed',
    );
    public function uploadFile(\SplFileInfo $file, $titulo)
    {
        //code here
    }
}

Better yet: define an associative array (this can be a private static, for once) that groups the mime-types into "modes", which you can then use per constant:

class Downloads
{
    const MIME_MODE_FILE = 1;
    const MIME_MODE_TEXT = 2;
    const MIME_MODE_FOO = 4;//powers of 2, for easy bitwise operations

    private static $mime_modes = array(
        self::MIME_MODE_FILE => array(
                'application/zip',
                'application/x-zip-compressed',
                'multipart/x-zip',
                'application/x-compressed',
                'application/x-rar-compressed',
        ),
        self::MIME_MODE_TEXT => array(
            //mime-types for text content
        )
    );
    private $mime_mode = null;
    private $accepted = null;

    public function __construct($mode = self::MIME_MODE_FILE)
    {
        if (!isset(static::$mime_modes[$mode])) throw new InvalidArgumentException('Invalid mime-mode for '.__CLASS__);
        $this->mime_mode = $mode;
        $this->accepted = static::$mime_modes[$mode];
    }
}

And take it from there. The reason why bitwise operators can come in handy here is that, if I wanted to use your Download class to process text files, but then call a method that was intended for use on non-text files, like archive decompression, you could check the $this->mime_mode property.
However MS Office documents are, in effect zip files. So a mime-type to accept those would have to accept zip files, too. Thus, the mime-mode to set might have to be Downloads::MIME_MODE_FILE | Downloads::MIME_MODE_TEXT
Of course, you'll have to work on the constructor in that case, but that's something you can do yourself. It's not that hard.

As for the actual checking of the mime-type: I've previously linked this answer and discussed various ways to do so. You've decided to play it safe and go for the checking of the first n bytes. That's fine, but never trust the result of a single check, though: always check both the given mime-type, and the bytes, always go "Double Dutch".

Lastly: mysqli_* usage where prepared statements shine in absence.
Sure, you say this code will only be called deep in the bowels of your back-end system, and no user input will be used. Call me stupid, but an uploaded file is user input in my book. I haven't got the faintest idea as to what $titulo is, nor do I know what the filenames might look like. Personally, I'd still play it safe and use a prepared statement.
If you feel as if prepared statements will only cause overhead then don't, because prepared statements can be used more than once. You could lazy-load a statement:

class Downloads
{
    //all of the consts, methods and properties I've previously listed +:
    private $mysqli = null;
    private $stmts = array();
    //then add:
    private function getStatement($queryString)
    {
        if (!isset($stmts[$queryString]))
        {
            $this->stmts[$queryString] = $this->mysqli->prepare($queryString);
        }
        return $this->stmts[$queryString];
    }
}

The prepared statement won't exist until, from the uploadFile method you call:

$stmt = $this->getStatement(
    'INSERT INTO descargas (titulo,size,src,filename) VALUES
      (?,?,?,?)'
);

The first time this call is executed, you'll create a prepared statement, the following times, you'll just get the same prepared statement returned to you, ready to be used again. So the overhead isn't as big as you might expect it to be.
Security-wise, however, you'll be better of. And in a way, in terms of traffic between PHP and MySQL, you'll bode well, too: the query string from which the statement is prepared is sent once, for all subsequent execute calls, only the parameters are sent over to the server, via a different protocol, so if you execute this query 20 times or more, you'll possibly end up sending less data to the DB.