Firstly try and do as few computation as possible - e.g. the
np.logspace call is essentially constant, no reason to call it over
and over for every single element.

Also the dtype of object for surface_density makes using NumPy
somewhat useless for that array, try instead one dimension more and the
right datatype / dimensions of the array to actually save some space /
make things faster.

With NumPy you really want to avoid these loops and try to find some
operations that work on the whole array instead of per-element.  If
there's no way to do that easily, consider some of the apply functions
to at least make it look better and then look into processing parts of
the array in multiple threads / processes to speed things up as it looks
like to be a highly parallel computation.  Also Cython, but it's not clear to me if it would help that much here, even though trying it is not very complicated, so you could just do that and see.

Also avoid slower language features like the variable arguments in often called functions, e.g. here pass a fixed number of arguments instead of doing the *args thing.

Unrelated to NumPy and won't help here, but related to general Python, just in case for your next scripts:

There's also a typo in surface_denstiy_profile, it should be
density.
Don't use the range(..., len(...)) pattern, better would be to have
enumerate since you get both the index and value delivered
directly.


There's a possibility that user may enter invalid characters at input. If that's the case, subsequent calls to scanf() fail, as these characters remain in buffer of input stream, thus printing error message infinitely.

You can use construct like the one below to avoid that. It looks like this may serve you better based on the requirement.

while (true)
{
    if (scanf("%ld",&input) != 1 || input < 0)
    {
        fprintf(stderr,"error: invalid input\n");  /* arbitrary */
        exit(EXIT_FAILURE);
    }
    else
    {
        // rest of code
    }
}


I can't say, that my variant of normalize function is easier to understand, but at least it is linear and it works correct (as i think) with x, that is less than -width

this._normalize = function(x, y) {
    x = x % this._width;
    y = y % this._height;

    x = (this._width + x) % this._width;
    y = (this._height + y) % this._height;

    return {'x': x, 'y': y};
}

Also, you missed this statement in get and set functions (looks like a typo):

this.get = function(x, y){
    var coords = this._normalize(x, y);
    return this._grid[(coords.y * coords.x) + coords.x];
}
this.set = function(x, y, item){
    var coords = this._normalize(x, y);
    this._grid[(coords.y * coords.x) + coords.x] = item;
}

It is better to move get, set and normalize functions to Grid prototype.
Putting these functions in prototype will increase execution speed and require less memory for creating an instance of Grid because these functions will not
be created every time Grid instance is created.
Like this:

var Grid = function(w, h){
    this._width = w;
    this._height = h;
    this._grid = new Array((this._width * this._height) | 0);
};
Grid.prototype.get = function(x, y) {
    // get code
};
Grid.prototype.set = function(x, y, item){
    // set code
};
Grid.prototype._normalize = function(x, y){
    // normalize code
};


From an algorithm flow viewpoint, it looks good. However, I'd make a few small changes:

public void drawRoute(String directions) throws JSONException
{
    // First parse the JSON to extract the points into an easily manipulated form
    List<List<HashMap<String, String>>> routes = new DirectionsHelper().parsePathsFromJson(directions);

    // Only one polyline can be shown on the map at a time
    hideRoute();

    ArrayList<LatLng> points;
    PolylineOptions polyLineOptions = null;

    // Traversing through routes
    for (int i = 0; i < routes.size(); i++)
    {
        points = new ArrayList<LatLng>();
        polyLineOptions = new PolylineOptions();
        List<HashMap<String, String>> path = routes.get(i);

        for (int j = 0; j < path.size(); j++)
        {
            HashMap<String, String> point = path.get(j);

            double lat = Double.parseDouble(point.get("lat"));
            double lng = Double.parseDouble(point.get("lng"));
            LatLng position = new LatLng(lat, lng);

            points.add(position);
        }

        polyLineOptions.addAll(points);
        polyLineOptions.color(ContextCompat.getColor(_context, R.color.colorPrimary));
    }

    _currentPolyline =  _map.addPolyline(polyLineOptions);
}

In drawRoute, you first declare polyLineOptions = new PolylineOptions();, and then after the for loop, you assign values.

I think it'd be better if you moved the creation of PolylineOptions so that it's created and used in one place:

 public void drawRoute(String directions) throws JSONException
{
    // First parse the JSON to extract the points into an easily manipulated form
    List<List<HashMap<String, String>>> routes = new DirectionsHelper().parsePathsFromJson(directions);

    // Only one polyline can be shown on the map at a time
    hideRoute();

    ArrayList<LatLng> points;
    PolylineOptions polyLineOptions = null;

    // Traversing through routes
    for (int i = 0; i < routes.size(); i++)
    {
        points = new ArrayList<LatLng>();
        List<HashMap<String, String>> path = routes.get(i);

        for (int j = 0; j < path.size(); j++)
        {
            HashMap<String, String> point = path.get(j);

            double lat = Double.parseDouble(point.get("lat"));
            double lng = Double.parseDouble(point.get("lng"));
            LatLng position = new LatLng(lat, lng);

            points.add(position);
        }

        polyLineOptions = new PolylineOptions();
        polyLineOptions.addAll(points);
        polyLineOptions.color(ContextCompat.getColor(_context, R.color.colorPrimary));
    }

    _currentPolyline =  _map.addPolyline(polyLineOptions);
}

And for the hideRoute function,

public void hideRoute()
{
    if (_currentPolyline != null)
    {
        _currentPolyline.removeRoute();
    }
}

You should set _currentPolyline to null so you can't remove it twice (if that matters), plus it allows the GC to clean up the polyline.


Repeat an action for a set of elements until all succeed, or progression halts

I quite like your aim for simplifying the function and factoring out the generic part. One solution (untested, just compiled) could be done using iterateUntilM from Control.Monad.Loops:

repeatUntilAll :: (Monad m) => ([a] -> m [Bool]) -> [a] -> m [a]
repeatUntilAll f = fmap snd . iterateUntilM fst step . ((,) True)
  where
    step (_, xs) = do
        results <- f xs
        let ys = map fst $ filter (not . snd) $ zip xs results
        return (length xs > length ys, ys)

We pass an additional boolean flag that tells if a particular step was an improvement or not. Note that we don't need to check for the final condition - if everything succeeds, there will be one final step with an empty list and then we'll stop.

However, I like a bit more yet another solution. Notice this: Let's say the first removal succeeds, the second fails and because of this, everything else. Then we iterate through the whole list, and then once more, before we finish. But in fact we know that we're bound to fail when we fail to remove all the other elements. In this second solution, we loop over all elements without distinguishing a full pass. Instead we "reset" the state every time we succeed and try all the failed elements again. I also like its simplicity, compared to the previous one:

-- | Tries to repeatedly act on each element until the action succeeds on each.
-- Alternatively stops when the action fails for all unfinished elements in one full round.
tryOnAll :: (Monad m) => (a -> m Bool) -> [a] -> m [a]
tryOnAll f = loop []
  where
    loop fs [] = return fs
    loop fs (w : ws) = do
        r <- f w
        if r then loop [] (fs ++ ws)
             else loop (w : fs) ws

(Again compiled but untested.) Note that in fs ++ ws we change the order of elements. This shouldn't be a problem, as we need to try out all before we fail anyway, but if you don't like it, you can use Seq instead of [] and maintain sequential order. Or you could also replace it with ws ++ reverse fs, but only if the total number of elements is moderate, otherwise you could start having problems with its O(n) complexity.

A tiny nit, unrelated to the main problem: Haddock comments allow you to generate nice documentation.


The loop to find the starting date is clearly not needed.  This can be done with library object TimeSpan -- like this:

void Main()
{
  var startDate = new DateTime(2014, 1, 1);
  var dates = new List<DateBlock>();

  int priorPeriods = ((DateTime.UtcNow-startDate).Days) / 30;

  DateTime dateIndex = startDate.AddDays(priorPeriods*30);
  for(int index = 0; index < 6; index++)
  {
     dates.Add(new DateBlock { StartDate = dateIndex, EndDate = dateIndex.AddDays(30) });
     dateIndex = dateIndex.AddDays(30);
  }
}

public class DateBlock
{
   public DateTime StartDate { get; set;}
   public DateTime EndDate { get; set; }
}

You might have to check the edge case (today is exactly divisible by 30) to see it matches requirements.

Here is how you do it with linq (looks cooler, but slower)

void Main()
{
  var startDate = new DateTime(2014, 1, 1);
  var dates = new List<DateBlock>();

  int priorPeriods = ((DateTime.UtcNow-startDate).Days) / 30;

  dates = Enumerable.Range(0,6)
                .Select(index => new DateBlock {
                                   StartDate = startDate.AddDays((priorPeriods+index)*30),
                                   EndDate =startDate.AddDays((priorPeriods+index+1)*30)
                }).ToList();
 }

public class DateBlock
{
   public DateTime StartDate { get; set;}
   public DateTime EndDate { get; set; }
}


Performance:
def get_char(self):
    new_byte = ''

    for bit in range(0, 8):
        byte = self.fh.read(1)

        new_byte += str(ord(byte) & 0x01)

    n = int(new_byte, 2)
    desteg_char = binascii.unhexlify('%x' % n)
    desteg_char = ''.join(map(chr, desteg_char))
    return desteg_char

This is not as simple as it could be. You are reading 8 bits as strings to build a single byte, converting it to an integer, then to a hex string (string format before unhexlify), then to a hexadecimal string, then mapping to a character, and then joining them together. I recommend doing more math and less string conversion and concatenation.
Style:
1. Use consistent string delimiters

You have ' in most places, like open(StegImageFile, 'rb'), but you also have DELIMITER = "$" and open(StegImageFile, "wb"). Use ' everywhere if that's what you're using.

2. Remove unnecessary parentheses

if (s_sz != ''): should be if s_sz != '':, or even more concise: if s_sz:.

3. Consider meaningful variable names

s_sz isn't a helpful variable name, and I don't know what it is at a glance, other than that it's the string form of sz (also not helpful).

4. Remove the space in print (text)

You don't use spaces after any other function names.

5. Remove weird leading spaces

The space before # Consts

The space before import binascii


Json Web Token-like implementation in Rust

Run clippy to be automatically told about things like:

warning: single-character string constant used as pattern
  --> src/main.rs:30:40
   |
30 |     let parts: Vec<&str> = token.split(".").collect();
   |                            ------------^^^- help: try using a char instead: `token.split('.')`
   |
   = note: #[warn(single_char_pattern)] on by default
   = help: for further information visit https://github.com/Manishearth/rust-clippy/wiki#single_char_pattern

warning: this creates an owned instance just for comparison
  --> src/main.rs:41:8
   |
41 |     if signature.to_string() == parts[2] {
   |        ^^^^^^^^^^^^^^^^^^^^^ help: try `signature`
   |
   = note: #[warn(cmp_owned)] on by default
   = help: for further information visit https://github.com/Manishearth/rust-clippy/wiki#cmp_owned

Tests, tests, tests, TESTS! Who even knows if this code works? Who knows if the changes I made broken anything? I sure don't know, but all the provided tests passed!
Encoding and decoding have highly related parts, so I'd introduce a struct to bundle them together; this allows extracting the key and signing bits which are reused across both. It also makes it easier to start to use an environment variable.
There's a lot of allocation that doesn't seem needed. For example, you can Base-64 encode into an existing String. Splitting the string on . and then joining it back together when verifying the token also seems inefficient.
Encoding into a string introduces some duplication with the details around the encoding, so I extracted that to a new type as well.
I chose to take some generics to avoid having to call as_bytes and friends everywhere.
Construct the key once when the object is created, then you can reuse it. This also makes it easier to change how the key is constructed.
When collecting, you usually don't need to specify the type inside the collection. Instead, do Vec<_>.
Returning Value::Null conflates an error case with a valid value. Use Result instead.
The API is unbalanced; encoding takes a string, but decoding returns a JSON Value. These should be symmetrical.
The practice of putting & before a result value (let foo = &some_function();)  is not usual and it's very distracting. Usually, you'd just take the reference when you need it.
Libraries should not unwrap things unless it's the author of the libraries mistake. Panicking in a library should be very rare and highly documented. Usually, you should return an error. If you do panic, use expect to give yourself a hint what went wrong.
Since you have a Vec<u8>, you can convert it to a String, no need to make a &str. Even better though, you can parse JSON from a slice, no need to explicitly check for UTF-8.
There's no need to introduce a temporary variable for the result of serde_json::from_str, just return it directly.

extern crate base64;
extern crate ring;
extern crate chrono;
extern crate serde_json;

use base64::{encode, decode};
use ring::{digest, hmac};
use chrono::prelude::Utc;
use std::str;
use serde_json::Value;

static RWT_SECRET: &str = "some secret"; // this should be from an environment variable

#[derive(Debug, Default)]
struct Encoder {
    buffer: String,
}

impl Encoder {
    fn new() -> Self {
        Self::default()
    }

    fn encode<D>(&mut self, data: D)
    where
        D: AsRef<[u8]>,
    {
        base64::encode_config_buf(data.as_ref(), base64::STANDARD, &mut self.buffer);
    }

    fn finish_part(&mut self) {
        self.buffer.push_str(".");
    }
}

impl AsRef<[u8]> for Encoder {
    fn as_ref(&self) -> &[u8] {
        self.buffer.as_bytes()
    }
}

impl From<Encoder> for String {
    fn from(me: Encoder) -> String {
        me.buffer
    }
}

pub struct Thang {
    key: hmac::SigningKey,
}

impl Thang {
    fn new() -> Self {
        Thang { key: hmac::SigningKey::new(&digest::SHA256, RWT_SECRET.as_bytes()) }
    }

    fn sign<D>(&self, data: D) -> hmac::Signature
    where
        D: AsRef<[u8]>,
    {
        hmac::sign(&self.key, data.as_ref())
    }

    fn encoded_signature<D>(&self, data: D) -> String
    where
        D: AsRef<[u8]>,
    {
        encode(&hmac::sign(&self.key, data.as_ref()))
    }

    pub fn make(&self, payload: &str) -> String {
        let mut token = Encoder::new();

        let time = Utc::now().to_string();
        token.encode(time);
        token.finish_part();
        token.encode(payload);

        let signature = self.sign(&token);

        token.finish_part();
        token.encode(signature);

        token.into()
    }

    pub fn get_payload(&self, token: &str) -> Result<Value, Error> {
        let first_dot = token.find('.').ok_or(Error)?;
        let second_dot = first_dot + 1 + token[(first_dot + 1)..].find('.').ok_or(Error)?;

        // let header = &token[..first_dot]; // TODO: check header
        let payload = &token[(first_dot + 1)..second_dot];
        let header_and_payload = &token[..second_dot];
        let actual_signature = &token[(second_dot + 1)..];

        let expected_signature = self.encoded_signature(header_and_payload);

        if expected_signature == actual_signature {
            let payload = decode(payload).map_err(|_| Error)?;
            return serde_json::from_slice(&payload).map_err(|_| Error);
        }

        Err(Error)
    }
}

#[derive(Debug)]
pub struct Error; // TODO: implement std::error::Error, maybe promote to an enum

fn main() {
    let x = Thang::new().make(r#"{"hello": true}"#);
    println!("{}", x);
    let x = Thang::new().get_payload(&x);
    println!("{:?}", x);
}

  Are there any security holes or issues with what you can see here?

I'm not qualified to make any such judgements. I will note that you've hardcoded the signature type, which doesn't mesh with real JWT.


Classifying rows of data by the number of days to close

In addition to Heslacher's review, I'd also move the initial if-check to a separate function:

private bool IsRowInvalid(DataRow row)
{
    return row["total_daysclose"] == System.DBNull.Value
           || row["closed_in0to3_count"] == System.DBNull.Value
           ||row["closed_in4to7_count"] == System.DBNull.Value
           || row["closedGtr7_count"] == System.DBNull.Value
           ||row["Closed"] == System.DBNull.Value;
}

This method you then call like this:

foreach (DataRow row in dt.Rows)
{
    if (IsRowInvalid(row))
    {
        continue;
    }

    // other logic here
}

I would also rethink names like "0to3" and "total_daysclose" if possible: these naming styles are inconsistent and IMHO bad; I'd much prefer "ZeroToThree" and "TotalDaysClose". "Gtrthan7" is even worse, since it contains an abbreviation and I really can't see any reason why.

Note that I would also move column names to constants, perhaps even move those to a static class, e.g.

internal static class ColumnName
{
    public const string AverageDays = "AverageDays";
    public const string Closed = "Closed";
}

I didn't implement this in the method above because it was too much work.

I just noticed your edit, and I'm wondering whether the NULL checks are even necessary, since I don't see any NULLs in your sample output. I also agree with the comments that this code indicates issues elsewhere, and that simply focusing on this method is not enough.


String literals vs. constants vs. enums
I think that the biggest terrible thing that you are doing here is 1) using magic string literals that are not defined as constants. 2) using a string when you can use an enum instead.
public enum SaveResult
{
    Exists, NotSaved, Success
}

In fact, your current code returns "NotSaved", while you check for case "Not Saved":. That's why you should use constants or an enum! Also, having success as the "default" case is not something I would recommend. It'd be better to assume failure unless success has been explicitly confirmed. Or even better, default is for "Oops, I forgot to check this case explicitly!", which would help you notice that you had written "Not Saved" instead of "NotSaved".
In the end, an enum is the choice I would recommend here.
Catching
That said and done, I really question the catch (Exception). In my experience, you should only catch the exceptions that you really need to catch. If the code would throw a NullReferenceException for example, that should propagate upwards and tell you that there is a serious bug in the code that needs to be fixed. Some Exceptions are just not meant to be caught.
Your question, and the database aspect
Besides this, I think that what you are doing here is reasonable. I think that it is  However, I would also like to point out that if you are using a RDMS here, then you might want to make your table have a primary key - or another unique index - over two columns: Both ShiftId and ShiftHour. Technically, that's the only way to really make sure that your table will not have duplicates over these values. Personally, I think it is perfectly OK to do a select-before-insert though. I think that is better than inserting without knowing if things go wrong or not, and catching the appropriate exception if things actually have gone wrong - i.e. a duplicate existed.
Be aware though, that after your SELECT query checking for a duplicate and before your INSERT query, there can theoretically be another query that just inserted a duplicate, effectively causing a race-condition. If such a situation would occur, the catch would still catch it of course (assuming you have the appropriate indexes in your table set up).


Determine if 2 lists with similar objects contain a partial duplicate

There are certain reasons I would not prefer your approach. These are:

1) There are multiple method calls which reduces the readability.

2) You are using filter twice which decreases the performances. You could do it inside the same filter like I've shown below

3) With this approach you don't have a consolidated List which contains common elements. For that you need another else condition which increases the cyclomatic complexity.

4) A null check which could produce NPE if not handled carefully as you are using findFirst() which returns Optional (Although null can be replaced with default new Person("","") object which is again not recommended).

5) Finally don't use ArrayList<Person> originalPeople = new ArrayList<>();; rather declare as List, to follow programming to interface.

Rather I would use below approach:

private static List<Person> getPersonInList(
            final List<Person> newPeople, List<Person> originalPeople) {
        List<Person> list = new ArrayList<>();

        newPeople.forEach(p ->
                originalPeople.stream()
                              .filter(p1 -> p.getFirstName().equals(p1.getFirstName()) &&
                                      p.getLastName().equals(p1.getLastName()))
                              .forEach(list::add));
        return list;
    }


First, you should avoid using null to represent an empty list.  Use an actual empty list, or even Collections.emptyList(), which is a immutable singleton.  This will avoid the need for null checks.

Second, you are filtering by getting a sub attribute, checking conditions on that object, then requesting the same sub attribute in the next step.  Instead, you should map to the sub attribute, then filter & process.

    ...
    .map(ChildModel::getChildrenDatas)
    .filter(data -> data != null && !data.isEmpty())
    .flatMap(List::stream)
    ...

Third, the .isEmpty() check is unnecessary, as .flatMap works fine with an empty stream.

   ...
    .map(ChildModel::getChildrenDatas)
    .filter(Objects::nonNull)
    .flatMap(List::stream)
    ...

Again, if you don’t use null to represent empty lists, the filter line can be removed entirely.


I would use some MV* library for this kind of task.
Maybe you have a look at Backbone. A small library (about 7k in production) with lots of nice functionality for those kinds of tasks.

1) You have models representing you data as a proper javascript object.
Each model is instantiated with:

var MyModel = Backbone.Model.extend({});
var instance = new MyModel();

You could use defaults:

var MyModel = Backbone.Model.extend({
    defaults: { name: 'Freddy Krueger', age: 0, child: '' }
});

Models have events to which you could subscribe. Most used is the "change" event. So you could bind a function to a general change by just declaring

model.on("change", function(){});

Or if you want to watch a specific attribute to change

model.on("change:name", function(){});

Of course you could "trigger" custom events

model.trigger("outOfOrder");

2) You could use views to render the different forms

View = Backbone.View.extend({
    el: $("#placeToRender"),
    render:function(){
        $(this.el).html(yourMagicHTML);
    }
});

Even better: you have microtemplating on board, which means:
You could define HTML including placeholders within a script-tag

<script type="text/template" id="#maintemplate">
    <div>
       <%= content %>
    </div>
</script>

That wouldn't be rendered by your browser, but you could get its content by

$("#maintemplate").html()

So that your view could render itself easily with:

View = Backbone.View.extend({
    el: $("#main"),
    template:_template($("#maintemplate").html()),
    render:function(){
        $(this.el).html(template(this.model.toJSON()));
    }
});

Where

this.model.toJSON()

is in fact a model with a key called "content" (e.g. {content:"blah!"}), which is used to render the template,

so that <%= content %> is substituted with the actual content.
And many more stuff to discover.

Referring to your problem - you could abstract your problem with backbone like the following:
Every tab you need to display is a view to which belongs a template to determine its html as well as a model, which represents the content of the tab.
You could embed each tab in another view, such that you have one embracing view to control the whole tabbing system and nesting views, which represent each individual tab.

You could write a custom show() method to show an individual tab and a method which coordinates which of the tabs is shown and which should be hidden.

So instead of doing the annoying work yourself, it may be a good idea to use a library to help.

Some places to start (besides the official API and documentation):

http://backbonetutorials.com/

http://ricostacruz.com/backbone-patterns/

http://coenraets.org/blog/2011/12/backbone-js-wine-cellar-tutorial-part-1-getting-started/

http://addyosmani.github.io/backbone-fundamentals/


Deploying treasure in 4×4 board and finding them in Python

Styling

The Python style guide, PEP 8, has some good things to say.  I have found very few things in it of which I do not approve.  Certainly there are some that I don't agree with, but for the most part it makes your code easier to understand if you follow its guidelines.

These two rules from PEP 8 you aren't following:

  Always surround these binary operators with a single space on either side: assignment (=), augmented assignment (+=, -= etc.), comparisons (==, <, >, !=, <>, <=, >=, in, not in, is, is not), Booleans (and, or, not).

and

  Use 4 spaces per indentation level.

You break that last in only one place: in your while treasure: loop.  It might be just a typo, but even typos sometimes break your program.

Using first = a-1 is not against PEP 8, but I think it looks better to use first = a - 1.

Naming

You have many variables with names that are almost or completely meaningless.  For example, r = randint(0, len(board)-1).  If I look down a couple lines, I can gather that r stands for row; but what's wrong with naming it row in the first place?  Each line of code should be semi-readable without any other lines as context.  You use just about half of the letters in the alphabet as variable names, but you have only about five names that are actually descriptive.  You use first, second, third, and fourth; but what are they really?  Are they perhaps row_start, row_end, column_start, and column_end?

Logic

I'm not sure; maybe this should go under Styling, but I think you should use parentheses in your print statements.  Python3 has print as a function so they are required.  They are allowed in Python2, so I usually use them.  It can trip you up sometimes if you do print("Your score was", 45), say, because it would print ('Your score was', 45) instead of Your score was 45.  Since you aren't using comma-separated values in your print calls, everything should look exactly the same.  You may want to put from __future__ import print_function at the top so that if you add something later that uses comma-separated values, it will still print out all right.

q = "@"

Why do you use "@"?  I'm guessing that you use it because "@" is the default space-filler.  You use "@" in many places, so what if you decided to use "%" instead?  That would require a lot of modification.  What you have right now is called hard-coded values.  Instead of that, define a constant at the beginning of the file that defines which character it is, and use that constant instead of saying "@" explicitly.

board = []
for x in range(0, 4):
    board.append(["0"] * 4)

range() by default starts at 0, so you could use for x in range(4): instead.  Since you aren't using x, the standard name is _.  The easy way to define board would be to use a list comprehension:

board = [["0"] * 4 for _ in range(4)]

r = randint(0, len(board)-1)

There is another function in the random module that is closer to what you want: randrange().  Of course, you would need to change from random import randint to from random import randrange, but the code would be:

row = randrange(len(board))
column = randrange(len(board[row]))

first = a-1
second = b-1
third = a+1
fourth = b+1
if(first < 0):
    first = first + 1;
if(second < 0):
    second = second + 1;
if(third == 4):
    third = third - 1;
if(fourth == 4):
    fourth = fourth -1;

For one thing, those semicolons are redundant.  You could also shorten your code using max() and min():

first = max([a - 1, 0])
second = max([b - 1, 0])
third = min([a + 1, 4])
fourth = min([b + 1, 4])

But why do you use 4?  What's special about it?  Is that another hard-coded value?

All together, you have done very well for studying only five hours.  I haven't seen you on StackOverflow, so you appear to be quite good at researching what you need.  I believe that your main problem is that you are too focused on the project at hand.  You haven't made it easy to change little details about the program, and you haven't made it easy for other people to understand your code.  PEP 8 mentions that code is read much more often than it is written.  If you came back in five years, would you be able to explain the program to someone else?


IServiceProvider
So you decided to reinvent the IServiceProvider Interface :-) which

Defines a mechanism for retrieving a service object; that is, an object that provides custom support to other objects.

Your public interface IPandaClass { } is exactly the same. I guess you forgot to mention that it has the GetHandler method or otherwise it would be completely meaningless.
Then we read:

This interface is implemented by a class or value type that provides a service to other objects.

This is the missing GetHandler method.

Generics vs strings

RegisterHandler("messages", Utilities.CreateInstanceOf<MessageHandler>());

Instead of hardcoding strings you could use generics and derive the name from the class name or just use the type as a key.

Dependency Injection
Do you really need all classes in one handler? Have you tried something like Autofac etc.?


Opening a workbook and copying pages to master workbook

Separating tasks into multiple subroutines will make the code easier to test and modify.

This  video: Excel VBA Introduction Part 5 - Selecting Cells (Range, Cells, Activecell, End, Offset) will explain why you rarely need to Select or Activate an Object.

I would use .Range("A1") instead of .Range("A1").Rows("1:1") because Range.Copy targets the first cell in the destination.

Refactored Code

Sub Load()
    LoadDailyWorkbook
    LoadLastWeeksWorkbook
End Sub

Sub LoadDailyWorkbook()
    Const A1BJ200 As String = "A1:BJ200"
    Const A1L3 As String = "A1:L3"
    Dim masterWB As Workbook
    Dim dailyWB As Workbook
    'Set Current Workbook as Master
    Set masterWB = Application.ThisWorkbook
    'Set some Workbook as the one you are copying from
    Set dailyWB = getWorkbook(Sheets("Control Manager").Range("O2"))

    If Not dailyWB Is Nothing Then
        With dailyWB
            'Copy the Range from dailyWB and Paste it into the MasterWB
            .Worksheets("Summary1").Range(A1BJ200).Copy masterWB.Worksheets("Summary").Range("A1")
            TrimRange masterWB.Worksheets("Summary").Range(A1BJ200)
            'repeat for next Sheet
            .Worksheets("risk1").Range(A1BJ200).Copy masterWB.Worksheets("risk").Range("A1")
            TrimRange masterWB.Worksheets("risk").Range(A1BJ200)

            'repeat for CS sheet
            .Worksheets("CS today").Range(A1L3).Copy masterWB.Worksheets("CS").Range("A1").Rows("1:1")
            TrimRange masterWB.Worksheets("CS").Range(A1L3)
            .Close SaveChanges:=False
        End With

    End If
End Sub

Sub LoadLastWeeksWorkbook()
    Const A1BJ200 As String = "A1:BJ200"
    Dim masterWB As Workbook
    Dim lastweekWB As Workbook

    'Set Current Workbook as Master
    Set masterWB = Application.ThisWorkbook

    ''''''''''''Get Last Week Data''''''''''''''''''''''
    Set lastweekWB = getWorkbook(Workbooks.Open(Sheets("Control Manager").Range("O3")))
    If Not lastweekWB Is Nothing Then
        With lastweekWB
            'repeat for next risk Sheet
            .Worksheets("risk2").Range(A1BJ200).Copy masterWB.Worksheets("risk_lastweek").Range("A1")
            TrimRange masterWB.Worksheets("risk_lastweek").Range(A1BJ200)

            TrimRange masterWB.Columns("A:BB")
            .Close SaveChanges:=False
        End With
    End If
End Sub

Function getWorkbook(FullName As String) As Workbook
    If Len(Dir(FullName)) = 0 Then
        MsgBox FullName & " not found found", vbCritical, "File Not Found"
    Else
        Set getWorkbook = Workbooks.Open(FullName)
    End If
End Function

Sub TrimRange(Target As Range)
    Dim results As Variant
    Set Target = Intersect(Target.Parent.UsedRange, Target)
    If Target Is Nothing Then
        Exit Sub
    ElseIf Target.Count = 1 Then
        Target.Value = Trim(Target.Value)
        Exit Sub
    Else
        results = Target.Value

        Dim r As Long, c As Long
        For r = 1 To UBound(results)
            For c = 1 To UBound(results, 2)
                results(r, c) = Trim(results(r, c))
            Next
        Next
        Target.Value = results
    End If
    Target.Columns.EntireColumn.AutoFit
End Sub


Recognise numbers 1 to 6 in various notations

Your code for print all and print rule is needlessly verbose. You can convert the float into a integer and fraction part - like you did in check_float but never used. And then just check if the integer is in the bounds and that there is no fraction part.
def print_rule(number):
    integer, fraction = divmod(number, 0)
    if 1 <= integer <= 6 and not fraction:
        print(f"rule{int(number)}")

Print all can also just be a for loop.
def print_all():
    for number in range(1, 7):
        print(f"rule{number}")

The programming challenge is bad. The challenge is just complicated and handling 0 differently to 1-6 is just a gimmick. I'd suggest using a different site, because the challenge is figuring out the challenge is just poorly worded.
When you get a programming challenge that says "this is ok, this is ok, this is ok" and what is ok is constantly being expanded on then the recommended approach is normally to regex. However we can think of it in a more general way; split the code into three parts:

Extracting raw data.
You start with building a means to extract what you need from the input. If the challenge says not to allow something this is a problem for later.
This is normally done with regex but sometimes using plain Python can be advantageous.

Evaluate the raw data.
Here we're converting the raw data into something we can use.
Here this is just using float, but sometimes this can be a bit more hands on.

Validate the data.
Here you're coding the "if number == 0 ...". Since we've parsed the data this makes the code much simpler.

Your code bundles all this together.
The programming challenge can be reworded to be something far simpler.

Split the input by whitespace into segments.
for segment in TEXT.split():

Evaluate the number from scientific notation; if not possible output the segment.
try:
    number = float(segment)
except ValueError:
    print(segment)
else:
    # ...

If the evaluated number is 1, 2, 3, 4, 5 or 6 then output "rule{number}".
If the evaluated number is 0 output "rule1", "rule2", ... "rule6".
if number in range(0, 7):
    numbers = range(1, 7) if number == 0 else [int(number)]
    for number in numbers:
        print(f"rule{number}")

Otherwise output the segment.
print(segment)

Then the challenge just becomes as simple benign for loop with some horrible conditions. If value is this and value is this and value is this... And ultimately forces you to use the arrow anti-pattern to have clean code. Not a fan.
TEXT = """\
1.0  03

 +5

 2.0e0
+.4e1
6.E+00
20e-1 2e1 2ва . 1e-307\
"""

def main():
    for segment in TEXT.split():
        try:
            number = float(segment)
        except ValueError:
            pass
        else:
            if number in range(0, 7):
                numbers = range(1, 7) if number == 0 else [int(number)]
                for number in numbers:
                    print(f"rule{number}")
                continue
        print(segment)

if __name__ == "__main__":
    main()

If you think just calling float is cheating then you can manually extract and evaluate the number.
To extract we should turn to regex. We can build up from the items in the challenge description.

1,2,3 ,4,5,6

[0-6]

+1, +2, ... +6

\+?[0-6]

1.0, 2.0,... 6.0

\+?[0-6](?:\.0)?

Negative numbers should simply be printed as-is: -1 prints '-1'

[\-\+]?[0-6](?:\.0)?

any scientific notation that represent numbers 1 to 6.

Firstly we now need to accept any digit not just 0 and 0-6, because +.4e1 = 4.
And the numbers can be any length, .04e2 = 4.
[\-\+]?(?:\d*\.\d*|\d+)

Then we need to get scientific notation, which is just smacking an e in-between two numbers.
{number}(?:[eE]{number})?

[\-\+]?(?:\d*\.\d*|\d+)(?:[eE][\-\+]?(?:\d*\.\d*|\d+))?

Since we want to check if the segment is completely a number then we can check that the match starts at the start and ends at the end too. Or use re.fullmatch
^[\-\+]?(?:\d*\.\d*|\d+)(?:[eE][\-\+]?(?:\d*\.\d*|\d+))?$

Evaluating a number in scientific notation is simple as we split out the base and exponent. We then convert both to floats and then put them in the equation \$b10^e\$, where b is base and e is exponent. Defaulting the exponent to 0 if it doesn't exist.
def scientific_float(number):
    base, _, exponent = number.partition("e")
    return float(base) * 10**float(exponent or "0")

This automatically handles +\d, -\d, .\d and \d. if you think this is cheating then you can make your own float function.
In all this shows the three stages
import re

# Extract
NUMBER = "[\-\+]?(?:\d*\.\d*|\d+)"
SCIENTIFIC_NUMBER = f"{NUMBER}(?:[eE]{NUMBER})?"
NUMBER_MATCHER = re.compile(SCIENTIFIC_NUMBER)

def scientific_float(number):  # Evaluate
    base, _, exponent = number.partition("e")
    return float(base) * 10**float(exponent or "0")

def main():
    for segment in TEXT.split():  # Extract
        if None is not (match := NUMBER_MATCHER.fullmatch(segment)):  # Extract + Validate
            try:
                number = scientific_float(match.group(0))  # Evaluate
            except ValueError:
                pass
            else:
                if number in range(0, 7):
                    numbers = range(1, 7) if number == 0 else [int(number)]
                    for number in numbers:
                        print(f"rule{number}")
                    continue
        print(segment)

if __name__ == "__main__":
    main()


Instead of using a list to store your points (which has an \$O(n)\$ look-up time), you can use a set object which has an \$O(1)\$ look-up time. For more information regarding Pythonic time complexity, you can look here.

I have a couple comments on your style:

Instead of x and y, I would use column/col and row. Even though x and y are mathematical coordinate names, I still prefer to be more explicit.
Group declarations are OK in the right circumstances, like unpacking an iterator or defining groups of like variables. The way you do this doesn't quite fit into the 'right circumstances' category: you are assigning and then slicing.

To get a better implementation, there are a couple of options:

Split the statement into its components (assigning x, y and slicing the list)
Calling list.pop() to do both at the same time

These two options, in terms of efficiency, are probably identical. So, its up to you to choose which one you want to use. Here is their syntax:

# 2 statements.
col, row = stack[0]
stack = stack[1:]

# Using `pop`.
col, row = stack.pop(0)

In Python 3, use the * operator to unpack the list

This option is the least applicable (due to your comments below). However, for reference here is that syntax:

(col, row), *stack = stack

This assigns the first element of the stack to (col, row) and the rest to itself, effectively popping off the first element.

P.S. Congratulations. This is probably my shortest review on this site.


Bug
Your program fails on this test:
ls.solve("abddc", "acddb");

Your program finds "ab" and "ac" as the longest subsequences, but the actual answer should be "add".
The problem is that your algorithm is greedy, and it will always use any match, even if the match skips over a part that would produce a better answer.  In my test case, the b in the first string matches the b at the end of the second string, thereby  skipping over the dd in the middle.


Function for setting a streak of strings in a Pandas

For starter, your implementation is too tightly tied to your data, making it not reusable for other kind of dataframe where you would want to count streaks. If you provided a column (pd.Series) to the function instead, it would be much more versatile; allowing calls such as count_streak(df.Artist), count_streak(pd.Series([1, 2, 2, 1, 1, 3]) or even count_streak('abcdccbdddbbbbcaaacbddba').

Doing so, you would remove the need for itertuple and favor regular iteration. This would ease the use of enumerate to check for the previous element:

def count_streak(sequence):
    streaks = []

    for index, element in enumerate(sequence):
        if not index or sequence[index - 1] != element:
            count = 1
        else:
            count += 1
        streaks.append(count)

    return streaks

Much simpler. But this is all without taking into account the wonderful itertools module and its groupby function. It will make group of consecutive data that evaluate equals, yielding both the value, and the entire group. The other advantage being that any iterable will be accepted:

def count_streak(iterable):
    return [
        i for _, g in itertools.groupby(iterable)
        for i, _ in enumerate(g, start=1)
    ]

Since you wish to stay in pandas' world, you also have a groupby method available on DataFrames and Series. But contrary to itertools.groupby that stops at each boundaries, pandas' groupby return all occurences of similar data even if some are discontinuous. But you can make use of cumsum and cumcount to get an equivalent and vectorize these operation instead of a slow python loop. This would require a pandas.Series as parameter, though, not any iterable:

def count_streak(serie):
    return serie.groupby((serie != serie.shift()).cumsum()).cumcount() + 1

usage being

df['Streak'] = count_streak(df.Artist)

And since you commented on performances, here is a small benchmark comparing the approaches. I’ve thrown in a couple extra approaches, out of curiosity. The code to produce the results is:

import pandas as pd
import numpy as np
import timeit

def python_streaks(sequence):
  streaks = []
  for index, element in enumerate(sequence):
    if not index or sequence[index - 1] != element:
      count = 1
    else:
      count += 1
    streaks.append(count)
  return streaks

def python2_streaks(sequence):
  streaks = [1] * len(sequence)
  for index, element in enumerate(sequence):
    if index and sequence[index - 1] == element:
      streaks[index] += streaks[index - 1]
  return streaks

def numpy_streaks(sequence):
  streaks = pd.Series(np.ones(len(sequence), dtype=int))
  for index, element in enumerate(sequence):
    if index and sequence[index - 1] == element:
      streaks[index] += streaks[index - 1]
  return streaks

def itertools_streak(iterable):
  return [
    i for _, g in itertools.groupby(iterable)
    for i, _ in enumerate(g, start=1)
  ]

def pandas_streaks(serie):
  return serie.groupby((serie != serie.shift()).cumsum()).cumcount() + 1

for size in range(8):
  size = 10**size
  for name in ('python', 'python2', 'numpy', 'pandas', 'itertools'):
    setup = 'import pandas as pd;from random import choice;from __main__ import {}_streaks as streaks; df = pd.DataFrame({{"Artist": [choice("abcde") for _ in range({})]}})'.format(name, size)
    elapsed = timeit.timeit('df["Streaks"] = streaks(df.Artist)', setup=setup, number=1000)
    print(name, size, elapsed)

And the results are (I stopped pure Python loops as they were taking too much time):

or, without using log scale on the Y-axis:

So depending on the amount of data you wish to process, either itertools (up to 10000ish elements) or pandas version is better.


Keeping attribute names simple when using getters and setters

I think this is the best way to do it:

class Part(object):
    def __init__(self, pn):
        self.pn = pn

    @property
    def pn(self):
        return self._pn

    @pn.setter
    def pn(self, value):
        if type(value) != str:
            raise Exception("Part number must be a string")
        self._pn = value

Remarks:

The _ prefix for properties is well-accepted, see the docs
self.pn = pn is to reuse the validation implemented in the setter
Class names should be CamelCase
Modern classes should extend object (class Part(object): ... as opposed to plain class Path: ...)
Doc strings should be """class description""" instead of 'class description'


You could potentially do:

var vowels = Console.ReadLine()
     .Where(c => "aeiouAEIOU".Contains(c))
     .Distinct();

foreach(var vowel in vowels)
     Console.WriteLine("Your phrase contains a vowel of {0}", vowel);

if(!vowels.Any())
    Console.WriteLine("No vowels have been detected.");

So you understand the code a bit:

Where() : Will test each character to see if it is indeed a vowel or not.
Distinct() : Will remove duplicate vowels found.

Then you loop through the vowels stating what exist inside, then the if will simply return when loop is empty.


I don't see why this should have a hypothetical name:

void foo() {
    printf("hello by %p\n", ::std::this_thread::get_id());
    sleep(1);
}

If this is meant as a test function, then name it as such.  As obvious as the functionality may be, there's still need for such names in an otherwise serious program.

Also, you can use std::this_thread::sleep_for, which is as of C++11:

std::this_thread::sleep_for(std::chrono::seconds(1));

If you also have C++14, use a literal instead:

std::this_thread::sleep_for(1s);

(You'll also need <chrono> for all of this.)


The embed function is well-suited for constructing trailing vectors by row:

 Dspke[ , paste0("E3", 1:3)] <- NA     # create columns to hold the trailing values
 Dspke[4:nrow(Dspke), 5:7] <- embed(Dspke$NEE, 3)
 Dspke$NEE3 <- ifelse( apply(Dspke[,5:7], 1, sd) >2,   #test
                             rowMeans(Dspke[,5:7]),   # result if TRUE
                             Dspke[,"NEE"])           # result if FALSE

I see the count vector being created but cannot tell from your description what it is supposed to do. Perhaps you should store the value of:

> apply(Dspke[,5:7], 1, sd) > 2)
    1     2     3     4     5     6
   NA    NA    NA FALSE FALSE FALSE

(Not a very good test of the code presented by the data since all of the tests are FALSE.)


Consider passing in the array size rather than fixing it at 6 in the polynomial(), nodeSuccession() functions.

// polynomial(xVal, xNode, yNode)
polynomial(6, xVal, xNode, yNode)

Minor stuff

Two backspaces may not truly "back-space".  Less problematic to not print unwanted text.  Various solutions. Perhaps as below.

const char *separator = "";
printf("xNode [");
for (i = 0; i < GRADE + 1; i++) {
  xNode[i] = i;
  printf("%s%.4f", separator, xNode[i]);
  yNode[i] = 0;
  separator = ", ";
}
printf("\n");

The various calls to like code suggest that a helper print function should be written.
For printing double, I find %e more informative than %f.
Rather than allocate to the size of the type, allocate to the size of the de-referenced pointer.  It easier to code correctly, review and maintain.  Putting the sizeof part first insures any integer math is done with at least size_t width.  Checking for a NULL allocation makes for robust code.

// sum = malloc(GRADE * sizeof(double));
sum = malloc(sizeof *sum * GRADE);
if (sum == NULL) TBD();

Use const with the pointers to insure wider application of the function and allow optimizations the compiler may not readily recognize.

// double* polynomial(double *xVal, double *xNode, double *yNode){
double* polynomial(const double *xVal, const double *xNode, const double *yNode){

// double* error(double *xVal, double *sum)
double* error(const double *xVal, const double *sum)

Help convey the double-ness of the variable.

// sum[j] = 0;  // This looks `int`-ish
sum[j] = 0.0;


Cześć Łukasz,
I'd personally move some of the logic to the separate file. Eg. getBudgedSummary.That way, Your component will be more readable and easier to test.
btw,
instead of expensesSum: expensesSum, You can simply go for expensesSum


Simple class exercise using the "this" pointer

It's hard to say whether the solution is proper when there isn't a problem to solve.  How a class should be designed depends on how it will be used; a class in isolation is hard to judge.  Even if you want to focus on some specific aspect, try to fit it into the context of a larger problem.

Back to the code: I suspect showgolf should be a const function.  I don't see why printing a Golf would change it.  You probably also meant to pass your constructor a const std::string&.  Finally, are you sure a showgolf member function is really what you want -- why not an operator<< overload?

Moving on to the Golf::setgolf function specifically, I don't think such a function is meaningful.  An operator>> overload or a free queryGolf function sound significantly more sensible to me.  More specifically, the usage:

Golf golf;
golf.setgolf();

Why not just auto golf = queryGolf();?  It's simpler, it means you can't forget to check whether things succeeded, and given setGolf's implementation it is likely to be just as efficient.

Speaking of checking whether things succeeded, why not throw an exception if the input is invalid?  There are valid reasons, but it's certainly a solution you should consider.  (By the way, if my previous solution sounded bad due to the need for exceptions, have no fear: boost::optional fits the use-case very well.)

And, in a similar vein: it sounds like you're trying to prevent the creation of invalid Golfs.  However, your default constructor does exactly that.  Are you sure default-construction is more valuable than guaranteed validity?  Again, depending on what you do with the class, the answer varies.

All in all, I'd suggest dropping showgolf and writing:

Golf promptGolf() {
    Golf golf;
    // read into fullname and handicap.  promptGolf may be a friend.
    if (/* golf is not valid, std::cin died, etc. */)
        throw TerribleError{};
    return golf;
}


Too complex
Always strive to keep source code complexity as low as possible.
The implementation of InfiniteScroll is way too complex.
It should not be an instantiatable object as it only works if there is one instance, and will only work once.

Page counting need only one variable not 3    this.maxCount, this.numberOfPages and this.hasNextPage can be replace with a single counter. See rewrite pageCount which counts down.

There is no need to store iterationCount or hasNextPage in markup. this.postsContainer.dataset.currentPage = this.iterationCount;

Use Pseudo-class ":last-child" to select last post. querySelector(".post:last-child")

In function getLastPost you reference an undefined variable const allPosts = postsContainer.querySelectorAll(".post");  should be const allPosts = this.postsContainer.querySelectorAll(".post");

The second argument of the IntersectionObserver is a reference to the same object you already have a reference to, there is no need to use the second argument.

When the observer callback is called there will only be one entry that you need to handle. Rather than entries.forEach use entries.find to locate the entry.

Rewrite
The rewrite does not create an object. The function InfiniteScroll holds the observer. When observer.disconnect() is called the IntersectionObserver callback will be de-referenced and the closure containing the InfiniteScroll will be cleaned up automatically.
To prevent InfiniteScroll from being called again it is de-referenced on the first call.
It works the same but with over 65% less code

function InfiniteScroll() {
    InfiniteScroll = undefined;
    const query = (qStr, root = document) => root.querySelector(qStr);
    const lastPost = () => query(".post:last-child", container);

    const perPage = 5;
    const container = query("#postsContainer");
    const posts = container.querySelectorAll(".post");
    var pageCount = container.dataset.maxCount / perPage | 0;

    const observer = new IntersectionObserver(intersect);
    observer.observe(lastPost());

    function intersect(entries) {
        const intersecting = entries.find(entry => entry.isIntersecting);
        if (intersecting) {
            observer.unobserve(intersecting.target);
            posts.forEach(item => container.appendChild(item.cloneNode(true)));
            --pageCount ? observer.observe(lastPost()) : observer.disconnect();
        }
    }
}

InfiniteScroll();
body, body * {
  margin: 0;
  padding: 0;
}

body {
  font-family: Arial, Helvetica, sans-serif;
}

.post {
  margin: 20px;
  padding: 15px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

p {
  line-height: 1.5;
}

Title 1

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque dolorum consequatur nostrum sapiente ipsa! Veniam, laudantium accusantium, odio maxime quo adipisci possimus enim quam, voluptate quidem animi perferendis delectus aliquam?

Title 2

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque dolorum consequatur nostrum sapiente ipsa! Veniam, laudantium accusantium, odio maxime quo adipisci possimus enim quam, voluptate quidem animi perferendis delectus aliquam?

Title 3

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque dolorum consequatur nostrum sapiente ipsa! Veniam, laudantium accusantium, odio maxime quo adipisci possimus enim quam, voluptate quidem animi perferendis delectus aliquam?

Title 4

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque dolorum consequatur nostrum sapiente ipsa! Veniam, laudantium accusantium, odio maxime quo adipisci possimus enim quam, voluptate quidem animi perferendis delectus aliquam?


Is this roulette selection extension method beautiful or disgusting?

I am on the it's disgusting side.

I usually think at extension methods as something that could be useful by themselves. In your case you need to provide some external context with max, which could lead to confusing code. Who should be in charge of updating it? In my opinion you should have something that has both the responsibilities of keeping track of the current max values and to select the next one.

Also, I'm not sure if you're talking about this selection method, but there they divide the fitness value of an item by the sum of the fitness values of all the items, not by a maximum value.

You cannot test it. The calls to list.getRandom() and Rand.NextDouble() make it impossible. I'd rather make the dependencies on random number generators explicit.

As a matter of style I don't like having an empty body for a loop.

Given that you want to implement the selection method I linked earlier, I'd probably go for another different approach. I'm not sure yours actually implements it (but I have not looked at it for long enough to be sure it doesn't work as you would expect to).

public static T RouletteSelect<T>(this List<T> list, Func<T, double> fitnessFunction, double randomValue)
{
    var fitnessValues = list.Select(x => fitnessFunction(x));
    var totalFitness  = fitnessValues.Sum();
    var probabilities = fitnessValues.Select(x => x/totalFitness).ToList();
    var i = 0;
    var sum = probabilities[0];
    while(randomValue <= sum)
    {
      i = i + 1;
      sum += probabilities[i];
    }
    return list[i];
}


Reading bytes between two quotes from a stream and decoding it to its appropriate character set

the only advice, that I can give you, is to separate the logic in multiple methods. This will make your method shorter and allow the code to be reused.

Personally, I see two other methods.

    String readString(Reader r, Charset charset) throws IOException {
        ByteArrayOutputStream ostream = copyInputToStream(r);

        final ByteBuffer byteBuffer = ByteBuffer.wrap(ostream.toByteArray());

        return decodeBufferAsString(charset, byteBuffer);
    }

    private String decodeBufferAsString(Charset charset, ByteBuffer byteBuffer) throws CharacterCodingException {
        return charset.newDecoder().decode(byteBuffer).toString();
    }

    private ByteArrayOutputStream copyInputToStream(Reader reader) throws IOException {
        ByteArrayOutputStream ostream = new ByteArrayOutputStream();

        int cp;

        while ((cp = reader.read()) > 0) {

            if (cp == '"') {
                break;
            }

            ostream.write(cp);
        }

        return ostream;
    }


If you're using some kind of TDD all classes must be test-covered. Adding classes that are not mentioned in tests at least confusing, at most - leads to unnecessary complexity.

What is the difference between Cell, MineCell, Bordercell and BlankCell? They are storing input/output methods but must be responsible for business logic, I think. They are acting like higher level of Position abstraction. BTW, Position.each - good "trick".

Code is readable and easy to understand.

When I looked through once again, I noticed that this part can be improved:

def blank?
  false
end
def mine?
  false
end
def border?
  false
end
######
def blank?
  self.is_a?(BlankCell)
end
def mine?
  self.is_a?(MineCell)
end
def border?
  self.is_a?(BorderCell)
end

This methods definitions can be removed from Cell's subclasses.

My way (written in "least resistance way" with tests):

class ValueError < RuntimeError; end

class Board

  def self.transform(input)
    validate(input)
    out = mark_field(substitute(input[1..-2]))
    to_s(out, input)
  end

private

  class << self
    def mark_field(field)
      field.each.with_index.with_object(field) do |(row, r_indx), obj|
        row.each.with_index do |cell, c_indx|
          increment_cells(r_indx, c_indx, obj) unless cell
        end
      end
    end

    def substitute(input)
      input.map do |line|
        line.gsub(/[^*\s]/, '').chars.map{ |ch| ch == '*' ? nil : 0 }
      end
    end

    def closest_cells(row, col, field)
      arr = (row-1..row+1).flat_map{ |r| [r].product([*(col-1..col+1)])}
      arr.reject{ |r, c| r < 0 || c < 0 || [r, c] == [row, col] || !(field[r] && field[r][c]) }
    end

    def increment_cells(row, col, arr)
      closest_cells(row, col, arr).each { |r, c| arr[r][c] += 1 }
    end

    def to_s(out, input)
      input[1..-2] = out.map do |line|
        "|#{line.map{ |c| c == 0 ? ' ' : c ? c : '*' }.join}|"
      end
      input
    end

    def validate(input)
      raise ValueError unless input.map(&:size).uniq.count == 1 &&
        input.reject{ |line| line.count('|') == 2 }.size == 2 &&
        !input.join.gsub!(/[^*\s\|\+\-]/, '')
    end
  end

end


Determining maximum profit to be made from selling shares

The trick to getting this problem in O(n) is some clever pre-processing.

Examples

Let's take 2 trials:

Trial 1: 1, 2, 3, 4, 5

Trail 2: 5, 4, 3, 2, 1

Obviously best case in Trial 1 is to buy for 4 days and sell on the 5th, for profit of 10.
In Trial 2, there is no profit to be gained, because the price never increases, because there is never a higher maximum down the line.

Trick

This points towards the trick: starting from the end make a note of the maximum encountered thus far.

For Trial 1, the maximums are 5, 5, 5, 5, 5

For Trial 2, the maximums are the same as the prices

Let's try this for a more complex scenario: 10, 1, 9, 2, 8, 3, 7

The corresponding maximums would be: 10, 9, 9, 8, 8, 7, 7

Then, for every day that price < maximum, you should buy. If price = maximum, you should sell, and if price > maximum, wait it out.

Code

This yields the following code, assuming you parse the prices into a non-empty long[] named prices:

long[] maximums = new long[prices.length];
maximums[prices.length - 1] = prices[prices.length - 1];
// fill maximums array, from the end
for (int i = prices.length - 2; i >= 0; i--) {
    if (prices[i] > maximums[i + 1])
        maximums[i] = prices[i];
    else
        maximums[i] = maximums[i + 1];
}

// Trade!
long profit = 0;
for (int i = 0; i < prices.length; i++) {
    if (prices[i] < maximums[i]) {
        // BUY now and SELL at max
        profit += maximums[i] - prices[i];
    }
}


"Invert" a JavaScript object hash whose values are arrays to produce a new object hash with keys as the elements of those original value vectors

lodash and underscore both have a reduce (aka "fold") function that works on objects, meaning you could also do this:

function arrayAwareInvert(obj) {
  return _.reduce(obj, function (result, values, key) {
    _.forEach(values, function (value) { result[value] = key; });
    return result;
  }, {});
}

It's pretty much the functional-style equivalent of Bergi's answer.

Point is, reduce is probably what you want for this.

Edit: As Bergi points out in the comments the inner iteration could also be a reduce operation

function arrayAwareInvert(obj) {
  return _.reduce(obj, function (result, values, key) {
    return _.reduce(values, function (result, value) {
      result[value] = key;
      return result;
    }, result);
  }, {});
}


First, if n == 1the method returns, so there is no need for the else.
Let us see what 6! would result in: 6 * 5! which is just 6 * 5 * 4! and so on.
Now we see a patter: n! = n * (n-1)!
Keeping this in mind we can refactor the given method to only take one parameter and to be recursive.
def factorial(n):
    if n < 0 :
        raise ValueError("Negative values are not allowed.")
    if n == 0 : return 1

    return n * factorial(n-1)

print factorial(6)

As James Snell stated correctly in his comment, we can replace the n == 1 check with a n <= 2 check if we assume n >= 1.
As jonrsharpe stated correctly in his comment, 0! should return 1 and also negative numbers don't have a factorial.
As Simon André Forsberg stated correctly in his comment, rasing an error for a negative parameter should be done.


Alternate method of iterating than os.walk

Style

According to PEP 8, functions should be named using lower_case().
Python code typically doesn't have parentheses around if conditions.
You call os.path.join() everywhere.  It would be worthwhile to assign the joined path to a variable.

Error handling

If any operation fails (for example, if you do not have permission to list some directory), then the whole search aborts with an exception.

Modularity and reusability

The inclusion and exclusion lists should be parameters rather than globals.

By the Single Responsibility Principle, a function should do just one thing.  The function you have written not only finds the directories that have the desired names, it also prints their path to sys.stdout, appends the results to a list, and logs the occurrence.

By making the function into a generator, you would give the caller the flexibility to do whatever it wants with the results.  The caller can even have the option to terminate early after the first result.  find_dirs() would then become a more generically useful function.

from __future__ import print_function
import os
import sys

def find_dirs(root_dir, names, exclude_folders=[]):
    try:
        for entry in os.listdir(root_dir):
            entry_path = os.path.join(root_dir, entry)
            entry_lowercase = entry.lower()
            if os.path.isdir(entry_path):
                if entry_lowercase in names:
                    yield entry_path
                elif entry_lowercase not in exclude_folders:
                    for result in find_dirs(entry_path, names, exclude_folders):
                        yield result
    except OSError as e:
        print(e, file=sys.stderr)

product_dirs = []
event_log_path = '/tmp/findlog.txt'
with open(event_log_path, 'a') as log:
    for lib in find_dirs('/', ['lib', 'library'], ['user']):
        print(lib)
        product_dirs.append(lib)
        log.write(lib + "\n")
        break      # Stop after finding the first match


Unit testing an unspecific order of method calls

You're right, the way you're mocking the methods is tightly coupling the sequence of events, even though you don't really care about the order.  What you really care about is that given a list, both methods are called, with the input/outputs chained and the overall output is the list without the filtered items.  You can achieve this by rewriting your test:

public void Gets_No_Bad_Ranking_And_No_Low_Points()
{
    // Create three entities, one to be removed by each of the filter functions
    // and one to be left over, since checking for an empty list isn't conclusive
    var badEntity = Substitute.For<MyEntity>();
    var lowEntity = Substitute.For<MyEntity>();
    var remainingEntity = Substitute.For<MyEntity>();

    // put all of the created entities into the initial list
    var myEntities = new List<MyEntity>() { badEntity, lowEntity, remainingEntity };
    var myMethodClass = Substitute.For<IMyMethodClass>();
    var target = new MyTargetClass(myMethodClass);

    // When RemoveBadRanking is called, we match against any parameter of the correct type,
    // then we filter the supplied list to exclude the badEntity
    myMethodClass.RemoveBadRanking(Arg.Any<IEnumerable<MyEntity>>())
        .Returns(args => ((List<MyEntity>)args[0]).Where(e => e != badEntity).ToList());

    // Do the same thing, but for lowEntity
    myMethodClass.RemoveLowPoints(Arg.Any<IEnumerable<MyEntity>>())
        .Returns(args => ((List<MyEntity>)args[0]).Where(e => e != lowEntity).ToList());

    var filteredEntites = target.GetFilteredEntites(myEntities);

    // If both substitutes have been called, then the returned list should only
    // have the remainingEntity in it.
    Assert.AreEqual(1, filteredEntites.Count);
    Assert.AreSame(remainingEntity, filteredEntites.First());
}

Whether or not this is an improvement is a bit subjective... it's trading the added complexity of the test for the looser coupling.


Using a spinner like a HTML select to display string but return int value

As long as you are hard-coding the values, I would go with an enum

public enum Muppets {
    Kermit, Gonzo, Fozzie, Animal, Swedish_Chef, Miss_Piggy,
    Statler, Waldorf, Beaker, Beauregard, Dr_Benson_Honeydew,
    Crazy_Harry, Rowlf, Dr_Teeth, Zoot, Janice, Floyd;
    // Sorry, I just thought your list of muppets was way too short

    public int getNumber() {
        return this.ordinal() + 1;
    }
    @Override
    public String toString() {
        return super.toString().replaceAll("_", " ");
    }
}

(To make things easier for you, you can also add your Please Select as a muppet and override the toString method to return a custom string if this == PLEASE_SELECT, this would also remove the need for adding one in getNumber, and would greatly simplify adding the items to the adapter)

Then I would use the ArrayAdapter as ArrayAdapter<Muppet>, so that you can get the selected item like this:

Muppet selectedMuppet = spinner.getSelectedItem();
int value = selectedMuppet.getNumber();

To get an array of all the muppet enums, use Muppets.values().

If you want the possibility to add muppets dynamically at run-time, I would make a List<String> and get the position of an item using list.indexOf(muppetName).


What you want is called the BoxLayout, which feeds UI elements in columns or rows. And then you can nest them one inside another, e.g. have one horizontal box layout panel as an element in another that is vertical (kind of like nested HTML tables). Here is a pretty decent tutorial about layout managers and it includes the BoxLayout.


Follow-up: How can we optimizing Java BigInteger operations?

Log2(n)
Math.ceil(Math.log(x)/Math.log(2)) is not the fastest way of determining \$\lceil\log_2{n}\rceil\$, of an integer n.  That requires converting the integer to a double, calculating the transcendental function, dividing by a constant, and then converting back to an integer, while rounding up.
Much faster is to count the number of bits in the value. \$\lceil\log_2{255}\rceil\$ is 8, and \$255 = 11111111_2\$ which has 8 bits.  Exact powers of two are represented by a 1 followed by \$\log_2\$ zeros; we can fix this with a tiny amount of preprocessing: subtracting 1.
Java doesn't directly provide the number of bits in an int, but it does give us Integer.numberOfLeadingZeros(), which will we can use to get the answer:
int ceil_log_2(int n) {
    if (n < 1)
        return Integer.MIN_VALUE;
    return 32 - Integer.numberOfLeadingZeros(n - 1);
}

Java's BigInteger does give us the BigInteger.bitLength() which does directly give the number of bits required to represent the number, so will give us the answer more directly:
int ceil_log_2(BigInteger n) {
    if (n.compareTo(BigInteger.ONE) < 0)
        return Integer.MIN_VALUE;
    return n.subtract(BigInteger.ONE).bitLength();
}

bigIntOps
Even/Odd
In bigIntOps(), you are now dividing by 2 using a shiftRight(1) operation.  Good; that faster than actual division.
But you are testing if the value is even by and'ing the BigInteger value with BigInteger.ONE, which likely allocates a new BigInteger value, which after being used must be garbage collected.  Then, you discard all of the upper bits of the value keeping only the lower 8 with .byteValue(), and finally test if that is zero.
You could simply discard the upper bits, then and with 1, and test:
if (n.byteValue() & 1 == 0)

Now no additional BigInteger temporary object is being created, which is a win.  But that is still doing unnecessary work.  Java directly provides a way of testing individual bits of a BigInteger, with .testBit():
if (n.testBit(0) == false)

Looping
While the result is even, you are dividing by 2.  You are doing this by shifting by 1 bit, which is faster than division, but still creates a new BigInteger object each step.
You notice this with your power-of-two test in longOps, and handle a power-of-two final value in one operation, instead of doing it in multiple steps.
Why not do that in bigIntOps as well?
BigInteger.getLowestSetBit() will tell you the number of trailing zero bits in the number, which is the number of times it can be divided evenly by 2.  And this works not only for exact power-of-twos
int zeros = n.getLowestSetBit();
n = n.shiftRight(zeros)
count += zeros;

Note that this works for integers as well:
int zeros = Integer.numberOfTrailingZeros(n);
n >>= zeros;
count += zeros;

So instead of doing a bunch of divisions one at a time, you can do them in bulk.  And not just for power of twos.
With the value \$3*2^{1024}\$, you'd do 1024 divisions by 2 in one step, leaving 3, which you'd then subtract 1, and then divide by 2, for 1026 steps, done in 3 calculations.
mod-4
Like the n.and(one) early, n.mod(four).byteValue() == 1 takes a possibly 1000-bit number, and does expensive modulo-4 division, and creates a new BigInteger value to store the result in, which must be allocated, and then garbage collected later.  You then discard all of the upper bits, and compare the result with 1.
Again, since your doing modulo-4 math, you can do modulo-256 math first, without changing the result.  n.byteValue() % 4 == 1.  This means no temporary BigInteger object needs to be created.
But because you know that n is odd (or you would be doing division-by-2), the results must be 1 or 3.  This means you are effectively just testing whether or not bit 1 is set.  n.testBit(1) == false.  Which is a lot clearer and more direct:
isPrimitive
Every time, isPrimitive is called, this statement is executed:
    return n.compareTo(new BigInteger(String.valueOf(Long.MAX_VALUE))) < 0;

You are converting Long.MAX_VALUE to a string, and then converting that back to binary form in BigInteger.
EVERY TIME!
If ever there was time to declare a constant, that was it, so it was done once, and not every call.
It could also be made more efficient by getting rid of the string intermediate step, and simple use BigInteger.valueOf(Long.MAX_VALUE).

Improved Code
import java.math.BigInteger;

public class Solution {

    private final static BigInteger MAX_LONG = BigInteger.valueOf(Long.MAX_VALUE);

    public static int solution(String s) {
        BigInteger n = new BigInteger(s);
        int count = 0;

        while (n.compareTo(MAX_LONG) > 0) {
            int zeros = n.getLowestSetBit();

            if (zeros > 0) {          // Even!
                n = n.shiftRight(zeros);
                count += zeros;
            } else {                  // Odd
                if (n.testBit(1))        // At least 2 least significant one bits
                    n = n.add(BigInteger.ONE);
                else                     // Only 1 least significant one bit
                    n = n.subtract(BigInteger.ONE);
                count++;
            }
        }

        // Value now fits with a primitive long
        long lv = n.longValue();

        while (lv > 3) {
            int zeros = Long.numberOfTrailingZeros(lv);
            if (zeros > 0) {          // Even!
                lv >>= zeros;
                count += zeros;
            } else {                  // Odd
                if (lv % 4 == 1)        // Only 1 least significant one bit
                    lv--;
                else
                    lv++;               // At least 2 least significant one bits
                count++;
            }
        }

        if (lv == 3)
            count += 2;
        if (lv == 2)
            count += 1;

        return count;
    }
}

Notice:

The BigInteger loop condition loops while the value is greater than Long.MAX_VALUE, instead of while greater than 1.  This naturally breaks out of the loop when the value is small enough.  No need for a separate test.
The n.byteValue() == 3 special case is not even present in BigInteger case, since it does not change the number of steps, and adding the test will slow execution down.
The lv == 3 special case can been removed from the primitive loop as well, by only looping while lv > 3!

Improved Algorithm
Consider:
11111000000111111100000000111111100000000111011100000111100000111     +1
11111000000111111100000000111111100000000111011100000111100001000     / 2^3
11111000000111111100000000111111100000000111011100000111100001        -1
11111000000111111100000000111111100000000111011100000111100000        / 2^5
111110000001111111000000001111111000000001110111000001111             +1
111110000001111111000000001111111000000001110111000010000             / 2^4
11111000000111111100000000111111100000000111011100001                 -1
11111000000111111100000000111111100000000111011100000                 / 2^5
111110000001111111000000001111111000000001110111                      +1
111110000001111111000000001111111000000001111000                      / 2^3
111110000001111111000000001111111000000001111                         +1
111110000001111111000000001111111000000010000                         / 2^4
11111000000111111100000000111111100000001                             -1
11111000000111111100000000111111100000000                             / 2^8
111110000001111111000000001111111                                     +1
111110000001111111000000010000000                                     / 2^7
11111000000111111100000001                                            -1
11111000000111111100000000                                            / 2^8
111110000001111111                                                    +1
111110000010000000                                                    / 2^7
11111000001                                                           -1
11111000000                                                           / 2^6
11111                                                                 +1
100000                                                                / 2^5

How many bits were there originally?  How many divide by 2's?
How many groups of 1 bits were there?  How many extra operations did a single 1 bit require?  How many operations did a group of more than a single 1 bit require?
Can you just count groups of 1's, single 1's, and total number of bits?  Are there any special cases you need to consider, like ending with 3, or a single 0 bit?


Splitting a command line into key/value pairs

Like @palacsint I will recommend an external library. Apache commons-cli is a decent choice. Another choice (my preference) is java gnu-getopt ... I like it because I am familiar with the notations and standards from previous work. It can be a little complicated the first time around otherwise.

On the other hand, I tend not to use an external library unless the code is already going to be relatively complicated....

But, back to your code.

Why do you have everything in a single String? Why is it not part of the String...args ?

The first thing about command-line arguments is that they get complicated very fast. What if the argument was:

String command = "-ps 4 -pe 5 -E opInstallDir=/opt/OSS-EVAL/thiscode -E opWD=/home/paul/remake -E opFam=fam -E opAppli=appli -Edocs='My Documents' -Eparse=key=value";

I have thrown in a few things there.

First up, on our one machine at work, we really do have the directory /opt/OSS-EVAL/ which we use to install/evaluate OSS software/libraries.

The above will break your parsing because it has the -E embedded in the name.

Next up, is 'POSIX-style' commandline arguments can have quoted values, and also values with an = in the value.

So, things I would recommend to you:

Locate the source of your command-line values. It will likely be available as an array, not a single string. Keep the data as an array!

Second, with the array, it is easier to look for stand-alone values that are -E, or, if the input is -Ekey=value then you look for values that start with -E.

Finally, when you split the key/value on the =, limit the split to 2.

String[] kv = pair.split("=", 2);

Which will preserve any of the = tokens inside the value part.

EDIT:

You have suggested in your edit that this is for sending data to an external command.

If you are using Java to initialize the external command, then please, please, please use the version of exec() that takes a command array, or use the ProcessBuilder which allows you to send all the command-line parameters as separate values in an array!!!


hand optimising javascript selector function

This is twice as slow as native (the original being 4x as slow)

function select (selector, context) {
    var c = selector.charAt(0),
        method,
        context = context || document;

    if (c === '#') {
        selector = selector.substring(1);
        method = context.getElementById(selector);
    }

    else if (c === '.') {
        selector = selector.substring(1);
        method = context.getElementsByClassName(selector);
    }

    else {
        method = context.getElementsByTagName(selector);
    }

    return method
}


Remove duplicate values in array with one loop?

Yes, there is.

Your current solution has a O(n²) runtime complexity which is worse then necessary.

By sorting the array and then only marching once, comparing only neighboring elements, extracting unique elements costs only O(n * log(n)).

var arr=[10,20,30,20,40,10];

function uniqueBySorting(array) {
  var sortedArray = array.slice().sort(function(a, b) {
    return a > b ? 1 : 0;
  });
  var result = [];

  result.push(sortedArray[0]);
  for (var i = 1, length = sortedArray.length; i < length; i++) {
    if (sortedArray[i] !== sortedArray[i - 1]) {
      result.push(sortedArray[i]);
    }
  }
  return result;
}

console.log(uniqueBySorting(arr));

However, that comes at the cost of loosing the sort order, which might not be desired. If the sort order matters, use a hashed set for remembering which elements you already encountered instead of the inner loop, so you finally end up with a O(n) complexity.

var arr=[10,20,30,20,40,10];

function uniqueWithObjectHashSet(array) {
  var hashSet = {}, result = [];
  array.forEach(function(element) {
    if (!element in hashSet) {
      newarr.push(element);
      hashSet[element] = true;
    }
  });
  return result;
}

console.log(uniqueWithObjectHashSet(arr));

Inserting elements into a hash set and looking them up requires only constant time, opposed to the linear time required for iterating over the target array.

Technically JS does not have any native hashset implementation, but lucky for you most JS engines tend to implement objects as hashsets internally (unless the JIT can identify properties with constant names), so you can abuse that behavior.

See Hashset in Javascript for more information on the last point.

Comparison of the HashSet implementation (including @hindmost's variant) to previous solutions: http://jsperf.com/cr-57581/7

Not surprising, all versions with nested loops are left far behind. As of April 2015, the hashSet version using Array.prototype.forEach is by far the fastest algorithm in Firefox. In Chrome with V8 however, the sorting based solution is much faster, most likely due to a more efficient implementation of Array.prototype.sort.


Making a binary tree using an array in C

Do not cast the malloc value. It serves no purpose, and may mask a serious problem.
Allocating sizeof(TreeNode) assumes the knowledge of the type of resTree.root, and results in the double maintenance. A preferred idiom is malloc(sizeof(*resTree.root)).
As written, the node tests for validity of its (future) children. It is more natural for the node to test its own validity:

if (size == 0) {
    return NULL;
}

halfSize = size/2;
if (arr[halfSize == -1) {
    return NULL;
}

resTree.root = malloc(sizeof(*resTree.root));
resTree.root->data = data;
resTree.root->left = BuildTreeFromArray(....).root;
resTree.root->right = BuildTreeFromArray(....).root;

return resTree;

I don see a reason why TreeNode is wrapped into Tree. More context would be nice.


If this is actually your first SQL you're quite good in learning new languages.

Some remarks:

The Group By is not weird, it's the SUM, you apply a conditional aggregation but the result is the same as a simple COUNT(*) (you can always get the same result using different ways in SQL).

The ORDER BY 'Downvotes' DESC will not work as expected, because single quotes specify strings in SQL, so this is not sorting by the actual number of downvotes, but by the string 'Downvotes' (which of course is the same for all rows). In your case you can simply use Downvotes, [] ([Downvotes]) or better Standard SQL double quotes ("Downvotes") are only needed for names including spaces or non-standard characters, like "foo bar?"

declare @user_id int = ##UserId:int##

SELECT
    p.Id as "Post Link",
    p.Score,
    count(*) as Downvotes
FROM
    Posts p
inner join
    Votes v on p.Id = v.PostId
WHERE
    p.OwnerUserId = @user_id
and v.VoteTypeId=3
GROUP BY
    p.Id, p.Score
ORDER BY Downvotes DESC, Score DESC


Interesting application.

  Is this running on parallel threads?

Ummm, kind of. But in the kernel, not in python threads. Suppose you have four cores. Then what is good about the await ... readchunk() is that if in steady state it consumes 10% of a core, then python could get nearly 40 webserver threads to do useful work for that many clients before the onset of thrashing. (Webservers are open loop, rather than a closed loop queueing system, so you pretty much always need to have a little headroom available, a few idle cycles, to stay out of pathological performance regimes.)

    path_without_file = local_path.rsplit('/', 1)[0]

I'm sure this is right, but it's not very idiomatic. You don't like os.path.dirname() ?

    pathlib.Path(path_without_file).mkdir(parents=True, exist_ok=True)

Ok, that's a little crazy. Yes, I understand that nginx only hands you authenticated requests. But still. You just accepted arbitrary bytes under control of the web client and used it to mutate your local filesystem. I recommend at least verifying that folder or path_without_file conforms to some sane regex (no unicode combining marks). Same remarks, but more so, for the open(local_path, 'wb') fragment.

            f.write(chunk)

You didn't post any timing figures, so it's not clear if network input or disk output is the bottleneck. But if you want to go wild you might consider tracking current offset and doing an aio write at that offset, to obtain greater queue depth against your local RAID or other storage. When benching, be sure to try lots of slow clients and also try a couple of heavy hitters. You may find that the output of tcpdump -r trace -ttt is instructive, for revealing stalls.

Security remarks aside, kudos on some nice simple, solid code. Looks like it accomplishes what you set out to do.


I believe your answer is correct, although I'm not sure why you need the identity, inc, and sum-integers procedure on the bottom for your solution.


Catching multiple types of exceptions when writing JSON

It is okay to just catch Exception and print the stack trace.
However rather than catching the top level Exception class, you may want to look at the Java 7 exception handling: http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html

In your case:

try {
    mapper.writeValue(outStream, myVal);
} catch (JsonGenerationException | JsonMappingException | IOException e) {
    e.printStackTrace();
}


What do you want to do when there are no words? The current solution isn't satisfactory at all. You're simply failing silently, and hasWord will always return false. By the way, if there's an exception in the middle of of the loop, will your file be closed?
Searching in a Vector takes O(n) time. This means that if you double the size of the vector, it will take twice as long. Other containers such as TreeSet have O(log n) access time: doubling their size will only slow the process by one iteration. HashSet has O(1) access time. Your lookups will be way faster.
Do you know that in a standard text unknown words account for ~10% of your text?


This might be against the spirit of Code Review, but you don't need to write your own single instance manager for WPF! Microsoft has already written code to accomplish this, but it has been poorly advertised.

Microsoft's single instance manager is extremely comprehensive, and I have yet to find any issues with it. (And if you don't want to use it, it can at least be a good reference for your own implementation.)

How to manage single instances in WPF

Step 1: Add the System.Runtime.Remoting reference to your project.

Step 2: Add this single instance class to your project.

Step 3: Implement the ISingleInstanceApp interface in your main application class in App.xaml.cs (this interface is provided by the SingleInstance.cs file).

For example:

public partial class App : Application, ISingleInstanceApp

Step 4: Change your startup object by going to Project --> <projectname> Properties in Visual Studio, clicking the Application tab. Locate Startup object: and select the <projectname>.App option.

Step 5: Define a Main method in App.xaml.cs, and give it a unique string in the Unique variable.

// TODO: Make this unique!
private const string Unique = "Change this to something that uniquely identifies your program.";

[STAThread]
public static void Main()
{
    if (SingleInstance<App>.InitializeAsFirstInstance(Unique))
    {
        var application = new App();
        application.InitializeComponent();
        application.Run();

        // Allow single instance code to perform cleanup operations
        SingleInstance<App>.Cleanup();
    }
}

#region ISingleInstanceApp Members
public bool SignalExternalCommandLineArgs(IList<string> args)
{
    // Handle command line arguments of second instance
    return true;
}
#endregion

Step 6: Right-click on App.xaml in the Solution Explorer, select Properties, and change the Build Action to Page.

Single Instance techniques

Do nothing when new instance is opened

If you don't want anything to happen when a single instance is launched, you don't need to modify the sample code above.

Activate original window when new instance is opened

Rather than doing nothing when a user attempts to open a second instance of the program, it's often beneficial to Activate the original window and change its window state to WindowState.Normal, which can provide an improved user experience if the original window was minimized.

To activate and make the window visible, modify the SignalExternalCommandLineArgs method as shown . (Note that MainWindow is a property of the App class, not to be confused with an arbitrarily-named MainWindow.xaml.cs class.)

public bool SignalExternalCommandLineArgs(IList<string> args)
{
    // Bring window to foreground
    if (this.MainWindow.WindowState == WindowState.Minimized)
    {
        this.MainWindow.WindowState = WindowState.Normal;
    }

    this.MainWindow.Activate();

    return true;
}


Passing variables by values without the dreaded if/switch/eval

Now The Angular Way™ to do this is to push off the data to a higher scope visible to both controllers and let two-way binding do its thing. This is typically done by using a parent controller. Scope operates similar to prototypal inheritance. If it's not in the child scope, it looks for it in the parent scope.

var app = angular.module('plunker', []);

app.controller('ParentController', function($scope) {
  $scope.data = {
    data1: 'data1',
    data2: 'data2',
  }
});

app.controller('Ctrl1', function($scope) {
  // Stuff local to Ctrl 1
});

app.controller('Ctrl2', function($scope) {
  // Stuff local to Ctrl 2
});

      Output 1: {{data.data1}}

Output 2: {{data.data2}}

      Input 1:
      <input type='text' ng-model='data.data1'>

Input 2:
      <input type='text' ng-model='data.data2'>

This works for small apps. When your apps become large, it's better if you use a service/factory/provider. Use it to hold your data, expose an API to mutate the data and make it emit events when data changes. That way, controllers can pull them in as dependencies, call the API and listen to data changes.

As for other things, Angular allows you to define controllers with implicit dependency format. It uses the name of the variables introduced to the function as the names of the dependencies.


Project Euler # 62 Cubic permutations in Python

Several issues with your code:

You are storing too much data.
Inefficient usage of Counter()
Is Counter() ordered?
You are needing to guess at upper bounds to the solution
Your timing code is flawed.

Storing too much data

You store the cubes of 1 to \$10^4\$:

cubes = [str(number ** 3) for number in range(1, upper_bound)]

This is then used once as input to computing sorted_cubes, and then once to look up the value at a single index.

When you get an index value from sorted.cubes.index(sorted_cube), say 1000, you look up the value of cubes[1000].  The value at that location will be the string representation of the cube of the 1000th value, which by looking at the range() limits, we can conclude is the \$1001^3\$.

So, you could instead:

return (sorted_cubes.index(sorted_cube) + 1) ** 3

Now that we've removed that pesky final lookup, cubes is only used once in the computation of sorted_cubes, so you can eliminate it entirely.

sorted_cubes = [''.join(sorted(str(number ** 3))) for number in range(1, upper_bound)]

Memory usage has been cut in half.

Inefficient usage of Counter()

As mentioned by @Tweakimp in their answer , you're using Counter() poorly:

count = Counter()
for sorted_cube in sorted_cubes:
    count[sorted_cube] += 1

can be written as:

count = Counter(sorted_cubes)

Is Counter() ordered?

Counter is a dict subclass, and as such on Python 3.6+, it maintains insertion order of the keys.  But in earlier versions, the contents is unordered.

This means, if two or more sets of cubic permutations of the required size are found, in Python 3.6+, the first cube added to the dictionary will be returned first in count.items(), and the correct sorted_cube will be used.  This cannot be relied upon in prior versions of Python.

Guessing at the upper bounds

Where do you need to stop searching for 5 permutations?  How about for 13 permutations?  How about 20?  Where did UPPER_BOUND = 10 ** 4 come from?  Did you just keep increasing it until it worked?

You know there is an answer, so why not keep searching until one is found?  Start at 1 digit cubes, and look for the required number of permutations.  Then try 2 digit cubes, then 3 digit cubes, until an answer is found.  The search space for each would be: \$\sqrt[3]{10^{n}} \le x \lt \sqrt[3]{10^{n+1}}\$, where n is the number of digits in the cube.

Your timing code is flawed.

This code:

START_TIME = perf_counter()
MINIMUM_CUBE = ...
print(f"... {MINIMUM_CUBE} ...")
print(f'Time: {perf_counter() - START_TIME} seconds.')

produces different results on my computer depending on whether the cursor is at the top of a blank terminal window, or at the bottom long scroll of previous text.  Avoid, as much as possible, including printing in timing results.

START_TIME = perf_counter()
MINIMUM_CUBE = ...
END_TIME = perf_counter()
print(f"... {MINIMUM_CUBE} ...")
print(f'Time: {END_TIME - START_TIME} seconds.')

Better implementation

Python 3.6+ only:

def cubic_permutations(required_permutations):
     min_cube = 1
     third = 1/3

     while True:
         max_cube = min_cube * 10 - 1
         lo = int(min_cube ** third)
         hi = int(max_cube ** third)

         cubes = [ "".join(sorted(str(x**3))) for x in range(lo, hi+1) ]
         count = Counter(cubes)
         digits = next((digits for digits, n in count.items()
                        if n == required_permutations), None)

         if digits:
             root = cubes.index(digits) + lo
             return root ** 3

         min_cube *= 10

This code runs over 5 times faster than @Tweakimp's code for their 13 permutation code.  No artificial upper bound is required.  Memory usage is further reduced, since smaller subsets (from lo to hi) of cubes and count are in memory at once.


Instantiating shapes using the Factory Design Pattern in Java

You could rewrite getShape as follows:

public static Shape getShape(String shapeType) {
    switch (shapeType.trim().toUpperCase()) {
        case "CIRCLE":
            return new Circle();

        case "RECTANGLE":
            return new Rectangle();

        case "TRIANGLE":
            return new Triangle();

        default:
            return null;
    }
}


Function to store data in MySQL database (using OurSQL)

You might want to try doing everything inside a transaction. It may be faster that way. I think with InnoDB you might be creating a committing a transaction for every statement which will be slow.

keys = str(tuple(keys)).replace("'", "")

That's an odd way of doing that, use

keys = '(%s)' % ','.join(keys)


Finding the first two numbers that sum to a given number

Some issues with the code:

close isn't defined anywhere and will shoot up to the global scope.
Your variables are terribly named. Use names that make sense.
Suggesting a var per variable so they become portable. You can easily copy and paste without having to remove the comma and re-add the var.
I am not sure why you would need parseInt for the end part of your logic when ints appears to be an array of numbers.
Prefer function declaration (function foo(){}) over function expression (var foo = function(){}). Although variables and functions have the same namespace, function declarations get hoisted. They will always be available regardless if they appear later in the code.
JS uses camelCase convention.

For performance:

I suggest you keep a hash of first values so that whenever they come up again, like [ 1, 2, 3, 1, 6, 7], you can skip the second time it occurs, saving you a full run through the array.

Here's my take on it:

function sumPairs(numbers, sum){
  let first = null;
  let second = null;
  let firstHistory = {};

  for(let i = 0; i < numbers.length; i++){
    first = numbers[i]

    // Skip if we've already seen this number as the first number
    if(firstHistory[first]) continue;

    // Remember that we've seen this number before
    firstHistory[first] = true;

    for(let j = 0; j < numbers.length; j++){
      second = numbers[j];

      // Skip if we're on the same index
      if(i === j) continue;

      // Return once we've found it. Forget the rest.
      if(first + second === sum) return [first, second];
    }
  }

  // The only time the function ever reaches this point is when it never
  // returned (it never found the values). Functions return an implicit
  // undefined, which satisfies your "not found" case.
}

It doesn't cover one test case though. It sees [10, 5, 2, 3, 7, 5] as [5, 5] instead of [3, 7]. However, the definition of "earlier" in the condition is not clear. [5, 5] is found earlier than [3, 7] from an execution perspective.

And it might not be perfect, but the idea is there.