Improving what you have

                d = 2;

Part of the problem is this line.  Each time you find a matching divisor, you restart from the beginning.  This isn't necessary.  The code works without this.  Once you've removed all the 2s, nothing will put them back.

    static void searchPrims(long n, long n2){
        int d = 2;
        while (true){
            if(n%d==0){
                if(n2%d==0){
                    System.out.println("Sim");
                    return;
                }
                n/=d;
                d = 2;
            }
            else if(n==1){
                System.out.println("Nao");
                return;
            }
            else{
                if(d==2)
                    d=3;
                else{
                    d+=2;
                }
            }
        }
    }

I would find this easier to read as

    static boolean searchCommonFactors(long n, long n2){
        for (int d = 3; n >= d; d += 2) {
            if (n % d == 0) {
                if (n2 % d == 0) {
                    return true;
                }

                do {
                    n /= d;
                } while (n % d == 0);
            }
        }

        return n % 2 == 0 && n2 % 2 == 0;
    }

This returns a boolean value instead of printing.  So we would have to print outside it.  Something like

    static void printAnswer(boolean answer) {
        System.out.println(answer ? "Sim" : "Nao");
    }

This way we can split up the returns more naturally.  Also, this would be reusable in other problems with different output requirements.

This way we don't keep checking if n2 is divisible by a factor.  We check once.  If it is, we return immediately.  If it isn't, we know it never will be.  We discard all of that factor to reduce the maximum size of d.

Putting the even check at the end takes the special behavior out of the loop.  This way we can simplify the loop iteration.

We could get back some efficiency by putting that check first and then removing all the 2s from n.

        if (n % 2 == 0 && n2 % 2 == 0) {
            return true;
        }

        while (n % 2 == 0) {
            n /= 2;
        }

Alternative approaches

Your approach basically factors the smaller number.  If one of its factors is also a factor of the other number, you say that they are related.

A more efficient approach might be to use the Euclidean algorithm to see if the two numbers have a greatest common divisor (GCD) larger than 1.  So you'd say something like

    printAnswer(gcd(l1, l2) > 1);

to get the answer.

A little searching finds a gcd implementation:

public static long gcd(long a, long b) {
    while ( 0 != b ) {
        long temp = a;
        a = b;
        b = temp % b;
    }

    return a;
}

There's a relatively elegant recursive solution.

public static long gcd(long a, long b) {
    return (b == 0) ? a : gcd(b, a % b);
}

But the iterative version should normally be faster.

I would expect this to be faster than your code, as it reduces a and b to the greatest common factor rather than searching out every factor of a only to find that none of them match.


Generating a complicated data structure in a more efficient manner

You open the file, but you don't explicitly close it. Bad karma.
You read all lines into memory, it seems, rather than go through them one by one. Memory-wise that's pretty inefficient.
Any reason for $rate_plan_terms to be global? That too seems like bad karma. A constant would make more sense, I think.
Have you considered using Ruby's bundled CSV parser? It'll be more robust.
It'd be easier to just use Hash#values rather than map { |k, v| v }

As for the use of include?, you skip that by making :rate_plan a hash, and use a key like "#{offer_name}#{offer_cid}". Simpler to explain in code, so see below.

require "csv"

def generate(fname)
  puts "generating doc for #{fname}"

  terms = %w{pp 01 12 24 36}.freeze # just made this local here, a const would still be better
  offers = {}
  features = {}

  CSV.foreach(fname, headers: true, skip_blanks: true) do |row|
    # If the CSV file has a proper header line, you can also access cells by their name
    _region, offer_cid, _offer_code, offer_name, product_cid, product_name, component_name, component_cid = *row.fields

    offers[product_cid] ||= {
      offerType: product_name
      ratePlan: {}
    }

    key = "#{offer_name}#{offer_cid}"
    offers[product_cid][:ratePlan][key] ||= terms.map do |term|
      {
        ratePlanName: offer_name,
        ratePlanCode: offer_cid,
        ratePlanTerm: term,
        offerEffectiveDate: "",
        ratePlanMRC: ""
      }
    end

    features[component_cid] ||= {
      featureName: component_name,
      featureCode: component_cid,
      featureType: "FEATURE",
      featureTerm: "",
      featureEffectiveDate: "",
      featureMRC: ""
    }
  end

  offsers.each do |key, offer|
    offer[:ratePlan] = offer[:ratePlan].values
  end

  {
    PriceList: {
      features: { feature: features.values }
      ChannelOrgType: "OCM",
      Region: "ALL",
      product: [],
      businessRelationship: "",
      standardOffer: offers.values
    }
  }
end

Still not pretty (it's a tad over the 5-10 line limit you might strive for for methods in Ruby).

It might be nice to break things into methods like feature_hash(name, cid), which would generate the separate hashes.

require "csv"

TERMS = %w{pp 01 12 24 36}.freeze

def generate(fname)
  puts "generating doc for #{fname}"

  offers = {}
  features = {}

  CSV.foreach(fname, headers: true, skip_blanks: true) do |row|
    # If the CSV file has a proper header line, you can also access cells by their name
    _region, offer_cid, _offer_code, offer_name, product_cid, product_name, component_name, component_cid = *row.fields

    offers[product_cid] ||= {
      offerType: product_name
      ratePlan: {}
    }

    key = "#{offer_name}#{offer_cid}"
    offers[product_cid][:ratePlan][key] ||= rate_plan_array(offer_name, offer_cid)

    features[component_cid] ||= feature_hash(component_name, component_cid)
  end

  offsers.each do |key, offer|
    offer[:ratePlan] = offer[:ratePlan].values
  end

  {
    PriceList: {
      features: { feature: features.values }
      ChannelOrgType: "OCM",
      Region: "ALL",
      product: [],
      businessRelationship: "",
      standardOffer: offers.values
    }
  }
end

def rate_plan_array(name, cid)
  TERMS.map do |term|
    {
      ratePlanName: offer_name,
      ratePlanCode: offer_cid,
      ratePlanTerm: term,
      offerEffectiveDate: "",
      ratePlanMRC: ""
    }
  end
end

def feature_hash(name, cid)
  {
    featureName: name,
    featureCode: cid,
    featureType: "FEATURE",
    featureTerm: "",
    featureEffectiveDate: "",
    featureMRC: ""
  }
end

Either way you cut it, though, it probably won't win any beauty contests.


Jerry Coffin suggested that I should simply scale the image down to a smaller size, and then back up to the original size. (Thanks!)

Using Emgu CV, I was able to shorten my function to a single return statement.

private Image<Bgr, byte> PixelateImage(Image<Bgr, byte> image)
{
    return image.Resize((int)(image.Width * .25), (int)(image.Height * .25), Inter.Area)
        .Resize(image.Width, image.Height, Inter.Nearest);
}


'do { statement; } while(0)' against 'statement' when writing C macro?

I prefer the second one because it can be used with normal compound stamens without modifications or accidentally being used incorrectly.
if (condition)
    I2c_START;

Type 1: FAIL
Type 2: OK
Of course with good coding standards that can be avoided (always use '{' '}' on if). But every now and then people can be lazy (or just careless) and the second version prevents accidents from happening.
The best solution is not to use macros. Use functions and let the compiler work out when to inline.
Edited:
For billy: (Type 3) no do while
#define I2C_START()   \
{                             \
    I2C_WAIT_IDLE();          \
    SSP1CON2bits.SEN  = 1;    \
}

Unfortunately this fails if you use the else part of the if statement:
The trailing semi-colon (on type 3) marks the end of the if statement thus else is not syntactically allowed. At least this gives you a compilation error unlike above. But Type 2 still works as expected.
if (condition)
    I2C_START();
else
    std::cout << "FAIL this test\n";

Type 1: FAIL
Type 2: OK
Type 3: FAIL


How well or poorly structured are my routes in this NodeJS app?

From a once over of the code and the comments:

This code is fine, especially if you have only a dozen routes, I would not advise you to build your own route building infrastructure for such a small amount of routes
Dont worry about the /
Consider having your routes in separate files as per @GnrlBzik


The best solution is to make ComponentProperties know how to print itself.

 class ComponentProperties {
     friend std::ostream& operator<<(std::ostream& s, ComponentProperties const& d) {
         return d.print(s);
     }
     virtual std::ostream& print(std::ostream& s) const {
         return s << componentProperty_;
     }
     //  STUFF
 };

 class TextboxProperties: public ComponentProperties {
     virtual std::ostream& print(std::ostream& s) const {
         return ComponentProperties::print(s) << ", " << textboxProperty_;
     }
     // STUFF
  };

  class Component {
      // PS. I tend to put my simple friend class definitions.
      //     inline within the class. They are after all part
      //     of the classes public interface and tightly bound
      //     to the implementation of the class.
      friend std::ostream& operator<<(std::ostream& out, const Component& component) {
          return out << component.properties_;
      }
      // STUFF
  };

Advantage of doing it this way is you can get rid of this getter methods.


Efficient implementation of aggregating test/train data

How about:

x_train, y_train = np.hsplit(np.asarray(train), 2)

Which uses only numpy functions and should be a bit faster than your implementation using intermediate lists.


There's no need to convert lists to ints every time. Truncation from the right is an integer division by 10. Truncation from the left is modulo certain power of ten; you can keep track of the modulo as the loop progresses.

There's no need to run a very expensive primality every time. Keep track of the primes you already found.

PS: The biggest hint in the problem is that there's only 11 numbers of interest. There must be a way to prove that fact, and the proof is most likely constructive.


The code duplication problem can be solve using Operators.defaultArgs, which does pretty much what you're trying to do

AssetValue =
    match input.AssetValue with
    | Some x -> x
    | None -> previousYear.AssetValue * (1.0 + previousYear.InterestRate) ;
InterestRate =
    match input.InterestRate with
    | Some x -> x
    | None -> previousYear.InterestRate

to

AssetValue = defaultArg input.AssetValue <| previousYear.AssetValue * (1.0 + previousYear.InterestRate)

InterestRate = defaultArg input.InterestRate previousYear.InterestRate

I don't really have an idea for your data type. You both of your type doesn't have the same fields types, so you can't really inherit. And since both of your fields are optional, you can't really compose with another record.


document.querySelector
While it is a great function to use, you are using in the wrong situations.
For every time you use it, you are getting an array of elements with a class that you passed in to the function. Why not just use document.getElementsByClassName?
Sure, it takes a little bit longer to type but it's faster.
This about it: the querySelector function has to read the argument passed in and, based on it's syntax ('.' for classes, '#' for ids, and a few more), scan the document in a way unique to each type of identification (id, class, etc).
Wouldn't it be easier for the function to know that it was going to look for one class and for one class only?
Semicolons
They aren't entirely necessary, and the interpreter probably adds them in for you, but your code looks like JavaScript when you put them in (at least in my opinion).
HTML indentation
Your divs are perfectly indented, but when you go down to your as, you start to try and clump them on to one line.
Originally, when I was looking at the a tag(s), I thought it was one really long a tag.
JavaScript indentation
For the most part, it's really good. But there is one section that is bothering me: your public methods section.
I actually had to post this in to JSFiddle and click "Tidy up" to understand what was going on there.
I believe the problem is the closing bracket of nextSlide; it is too far back, and it looks like it is closing publicMethod.
Built in output
In the sendInTheClone method of publicMethod, it uses the function alert.
Not everyone using this module may want an alert popping up on their screen; maybe they want it written to the DOM, or maybe they use custom pop-up boxes.
(Excuse this section ("Built in output") if I misunderstood your sendInTheClone function)
Good things:

Contrary to what people have been commenting, I think that the big comments going across your code to split it up is a good idea. In my opinion, it helps with legibility.

The use of publicMethod. It's a pretty good idea; I like it.


Web service to add a phone number with SMS validation

There are several errors/bad styles here:

First do isn't necessary, as body of function can contain several expressions
instead of def inside function it's better to use let that allows to "define" several variables in one step, and they will visible only inside this let block. So 2nd & 3rd do could be replaced with corresponding let
if variable is used only once, then you can include function call directly into map

So your code will look like:

(defn add-phone
  [request auth-type]
  (println "Url requested is " (:request-method request) " " (:uri request))
  (println request)
  (let [auth-header ((:headers request) "authorization")
        auth-map (utils/get-auth-header auth-type auth-header)]
    (if (model/invalid-user-and-pass auth-map auth-type)
      {:status 401,
       :headers {"WWW-Authenticate" "Basic realm=\"smsauth.herokuapp.com\""}}
      (let [raw-phone-no (:phone_number (:params request))
            service-name (:service-name auth-map)]
        (if raw-phone-no
          (let [valid-phone-no (utils/parse-phone-no raw-phone-no) ; XXX get the service id some other way.
                service-map (model/service-in-db service-name)
                service-id (service-map :id) ; XXX check that service doesn't already have phone number
                ]
            (model/store-phone-no :numbers service-id valid-phone-no)
            (twilio/send-sms-verify twilio/sms-url valid-phone-no service-name)
                                        ; XXX jsonify this, send more information, document it.
            {:status 201,
             :body (json/json-str {
                                   :service_name service-name,
                                   :phone_number valid-phone-no,
                                   :status "active",
                                   :uri (:uri request)
                                        ; should have some kind of unique id for the phone number
                                        ; here.
                                        ; also return the date
                                   })})
          {:status 400,
           :body (json/json-str {:error "Please include a phone_number."})})))))

P.S. it's also good idea to check value of service-map - if it will nil, then you'll get NPE. So instead of (service-map :id) you can write (:id service-map) that will correctly work if service-map will nil...


Function to get the next character of a giving position of strings of a dataframe

Maybe this helps?  It will save you some if statements by just joining strings (although it will only read one position to the next dataframe element at the right in case you're in the last character of the y item).

So take care in case you have empty strings and you want your search to keep jumping over to the next item (in that case you can just delete y+2 in the code and leave [y:,0].

import numpy as np
import pandas as pd

ar = np.array(["aba", "bcb", "zab"])
df = pd.DataFrame(ar)

def get_char(df, y, z):
    a = ''.join(df.iloc[y:y+2,0])
    try:
        return a[z+1]
    except:
        return None

print(get_char(df, 1, 2))
# z
print(get_char(df, 2, 2))
# None


Please protect your internals by preceding them with private:

private float[] list;
private int pos;
private int capacity;

pos is a very poor name for a field caching the size of the list: size is more clear.

You don't need capacity, just ask list.length.

Instead of trace(), I would override the String toString() method.

All in all, I had this in mind:

import java.util.Random;

public class SortedList {

    private float[] list;
    private int size;

    public SortedList() {
        this.list = new float[2];
    }

    public void offer(float item) {
        if (size == list.length) {
            expandArray();
        }

        int i = 0;

        for (; i < size; ++i) {
            if (list[i] > item) {
                break;
            }
        }

        for (int j = size - 1; j >= i; --j) {
            list[j + 1] = list[j];
        }

        list[i] = item;
        size++;
    }

    public float median() {
        if (size == 0) {
            return Float.NaN;
        }

        if (size % 2 == 0) {
            return (list[size / 2 - 1] + list[(size / 2)]) / 2;
        } else {
            return list[(size / 2)];
        }
    }

    private void expandArray() {
        float[] arr = new float[2 * list.length];
        System.arraycopy(list, 0, arr, 0, list.length);
        list = arr;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder().append("[");

        for (int i = 0; i < size; ++i) {
            sb.append(list[i]);

            if (i < size - 1) {
                sb.append(", ");
            }
        }

        return sb.append(']').toString();
    }

    public static void main(String[] args) {
        long seed = System.nanoTime();
        SortedList l = new SortedList();
        Random random = new Random(seed);

        System.out.println("Seed = " + seed);

        for (int i = 0; i < 10; ++i) {
            l.offer(random.nextInt(100));
            System.out.println(l);
        }
    }
}

Hope this helps.


Indentation

  BOTH SAEM currentNumber AN 1, O RLY?
  YA RLY, FOUND YR cowntr, OIC

You're missing indentation here. In more mainstream languages, this construct looks like so:

  if (currentNumber == 1)
  return cowntr;

This is hard to read, and would be better if it were indented:

  if (currentNumber == 1)
      return cowntr;

  BOTH SAEM currentNumber AN 1, O RLY?
      YA RLY, FOUND YR cowntr
  OIC

Plus it's a good idea to just use braces in the first place.

The same thing goes for the constructs later on:

  DIFFRINT currentLength AN SMALLR OF currentLength AN maxLengthFound, O RLY?
  YA RLY, maxLengthFound R currentLength, longestAtValue R cowntr, OIC

  BOTH SAEM cowntr AN maxNumber, O RLY?
  YA RLY, FOUND YR longestAtValue, OIC

These also need proper indentation.

If you don't want to use the brace style, then just indent the YA RLY case one level. That way you get the indented look of mainstream languages...

if (condition)
    do thing

... which is easier to quickly parse than a wall of left-aligned code.

Bugs

Collatz of 1 doesn't return 1. It returns 3.

Loops

Looking at your code some more, I get the feeling that you went out of your way to dodge the regular loop structure as it didn't do what you wanted it to do the last time. But as a result you have to write your own incrementer and your own exit condition.

I think you'd be better off by using the regular loop structure. You can rely on the return.

HOW IZ I collatz YR currentNumber
  I HAS A cowntr ITZ 1
  IM IN YR collatzLoop
    BOTH SAEM 0 AN MOD OF currentNumber AN 2, O RLY?
      YA RLY, currentNumber R QUOSHUNT OF currentNumber AN 2
      NO WAI, currentNumber R SUM OF PRODUKT OF currentNumber AN 3 AN 1
    OIC
    cowntr R SUM OF cowntr AN 1
    BOTH SAEM currentNumber AN 1, O RLY?
    YA RLY, FOUND YR cowntr, OIC
  IM OUTTA YR collatzLoop
IF U SAY SO

becomes

HOW IZ I collatz YR currentNumber
  IM IN YR collatzLoop UPPIN YR cowntr
    BOTH SAEM currentNumber AN 1, O RLY?
    YA RLY,
      FOUND YR SUM OF cowntr AN 1
    OIC
    BOTH SAEM 0 AN MOD OF currentNumber AN 2, O RLY?
      YA RLY, currentNumber R QUOSHUNT OF currentNumber AN 2
      NO WAI, currentNumber R SUM OF PRODUKT OF currentNumber AN 3 AN 1
    OIC
  IM OUTTA YR collatzLoop
IF U SAY SO

And this loop...

I HAS A cowntr ITZ 1
IM IN YR maxCollatzLoop
  currentLength R I IZ collatz YR cowntr MKAY
  DIFFRINT currentLength AN SMALLR OF currentLength AN maxLengthFound, O RLY?
  YA RLY, maxLengthFound R currentLength, longestAtValue R cowntr, OIC
  cowntr R SUM OF cowntr AN 1
  BOTH SAEM cowntr AN maxNumber, O RLY?
  YA RLY, FOUND YR longestAtValue, OIC
IM OUTTA YR maxCollatzLoop

Becomes

IM IN YR maxCollatzLoop UPPIN YR cowntr WILE BOTH SAEM maxNumber AN BIGGR OF cowntr AN maxNumber
  I HAS A collatzNumbar ITZ SUM OF cowntr AN 1
  currentLength R I IZ collatz YR collatzNumbar MKAY
  DIFFRINT currentLength AN SMALLR OF currentLength AN maxLengthFound, O RLY?
  YA RLY,
    maxLengthFound R currentLength
    longestAtValue R collatzNumbar
  OIC
IM OUTTA YR maxCollatzLoop
FOUND YR longestAtValue

The reason my versions are longer is because I opted to split your multiple statements to individual lines.

Version number

OBTW
    WHICH STARTIN NUMBR, UNDR WAN MILLION, PRODUCEZ TEH LONGEST CHAIN?
TLDR

HAI 1.3

I think I said something about this before, but I'll say it again; version number goes at the top. It's needed for the interpreter. Even if they work fine without the version number at the top, I think it'd be best to put the version number at the top so that interpreters don't have to go searching for it.


Invocable callout(Post) from processbuilder

From a practical viewpoint, I think the methods that you have right now are splitting the responsibilities of your overall code fairly appropriately. You could further split things up, but the question to ask is what purpose would this serve?

The more methods and classes you break things into, the more you need to jump around in your class(es) to learn (if you're new to the codebase)/remember (if it has been long enough since you last touched the code) how things work.

Instead of focusing on that, there are more pressing issues:

Exceptions as flow control

This is generally viewed as an antipattern (i.e. something to avoid). The main purpose of exceptions is to (more) gracefully handle error conditions where continued processing is impossible.
In this particular case, running into a System.QueryException should be impossible. In the case where either of your queries returns 0 rows, you can't really continue processing. You'd run into a System.ListException when you try to access  os[0] or prop[0]

Non-bulkified @future call

You're calling your @future method one Id at a time. You can only make 50 @future calls in a given transaction, so if your ProcessBuilder tries to work on 51 records, you're liable to run into this governor limit.
The better option here would be to pass the entire list you accept as an argument to your InvocePostProperty() method to your @future method as well
Building on the previous suggestion, if possible, you should pass more than one event (I'm assuming it's an event service you're using, based on the language) per callout

No notification when async code fails

Asynchronous code, at least for me, has a pretty bad history of not printing debugs to logs. The fact that code is being run async also means that there's no direct way to alert you if the async portion of the code fails.
In my org, using async code means that we need to do our best to catch all possible errors, and create a Case or send an email to an appropriate person to let them know that a failure has occurred

My Suggestions:

I think that Queueable apex is probably more appropriate in your case. Unlike @future methods, queueable apex can be chained ad infinitum
Add explicit error notification to your async method(s)
Attempt to make more than one callout per async transaction. You can have 100 callouts in a single transaction (as long as your callouts in a given transaction don't collectively exceed 120 seconds of execution time)
Make use of the Limits class to determine whether or not you can make another callout in this transaction.
Don't forget to store the records you want to update in a list, and perform DML after you finish all of your callouts for a given transaction
Instead of trying to catch (and swallow) a System.QueryException, add a custom exception inner class to your or_service class. If you detect 0 rows returned by either of your queries, throw a new instance of this exception (and then do explicit notification)


Recursively checking the css class of an iFrame Element

Code structure wise, the recursive pattern in JavaScript/Selenium and Protractor code is a pretty common one. The biggest problem here is that, you don't have a recursive cycle exit condition - if result would never become equal to value, you'll eventually get the recursive call stack size overflow error.
This is a "negative" case for you and would probably mean a test failure, but, in the world end-to-end UI tests, you have to be as specific in your test failures as possible (the "difficulties in finding the root cause for a test failure" is one of the reasons we should generally write more unit tests as opposed to end-to-end tests, according to Google Testing Pyramid).
A better approach to tackle flakiness would be to use Explicit Waits, which are design to continuously execute a function until it evaluates to true, or a timeout is reached:

this.wait( condition, opt_timeout, opt_message ) → Thenable
Schedules a command to wait for a condition to hold. The condition may be specified by a Condition, as a custom function, or as any promise-like thenable.
For a Condition or function, the wait will repeatedly evaluate the condition until it returns a truthy value. If any errors occur while evaluating the condition, they will be allowed to propagate. In the event a condition returns a promise, the polling loop will wait for it to be resolved and use the resolved value for whether the condition has been satisified. Note the resolution time for a promise is factored into whether a wait has timed out.

Here is how you can apply wait() in your case:
// function looks for 'el', then switches iframe and extracts the desired cssValue, then compares it to the 'value' we expect
Page.checkCssValue = function (el, cssValue, value) {
    // find function, the '0' represents the iframe index
    var newEl = this.find(el, 0);

    // wait for the desired CSS value
    var timeout = 5000;  // in milliseconds
    this.driver.wait(function() {
        return newEl.getCssValue(cssValue).then(function (result) {
            return result === value;
        });
    }, timeout, "CSS value '" + cssValue + "' has not become equal to '" + value + "'.");

    return newEl.getCssValue(cssValue);
};

where this.driver is your selenium webdriver instance, 5000 is a timeout value in milliseconds.


Time Limit Exceeded for ETF - Euler Totient Function at Spoj

The way I would approach this problem is to find the prime factorization of n, and then use Euler's formula which says:

$$\varphi(n) = n \prod_{p|n}\left(1 - \frac{1}{p}\right)$$

The easiest way to do this is to find the prime factorization of n (which you are basically already doing), but store each distinct prime factor in a list. Once you are done, compute this formula for the primes, and you should have your answer fairly quickly.


Graph implementation in C++ using adjacency list

Some comments -

cout << "Invalid edge" is not a sane error-relaying mechanism. The C++ way to do things is to throw an exception. The calling code could catch the exception and print an error, or could let the app exit if this is a serious-enough error.
void display() needs to be void display() const. It doesn't modify anything.
Don't iterate through an STL container using an integer index. Iterate using an iterator. If you don't know what I mean, google around or read https://www.geeksforgeeks.org/iterators-c-stl/


Coin Flip Streak from Automate the Boring Stuff with Python

Bugs
torai(1, 10000)

This should print something around 50 %, since it's the individual count. But instead, it prints
1-streak count:  0
1-streak prob (percent):  0.0
longest streak:  19
process time:  0.046875 second

Avoid too many comments
There are too many comments in your code, which makes the code look unnecessarily convoluted. What I recommend is the usage of docstrings. IMO It isn't very important here, but its better than a million comments
def torai(seq,pop):
    tosses = []
    for i in range(pop):
        tosses.append(random.randint(1,2))
    streak = 0
    curlongstr = 0
    longeststr = 0
    peak = []
    for i in range(len(tosses)):
        if i == 0:
            continue
        elif tosses[i] == tosses[i-1]:
            streak += 1
            if i == len(tosses)-1:
                peak.append(streak)

        elif tosses[i] != tosses[i-1]:
            curlongstr = copy.copy(streak)
            if curlongstr > longeststr:
                longeststr = curlongstr
            streak = 0
            if curlongstr > streak:
                peak.append(curlongstr)

    truepeak = []
    for i in peak:
        truepeak.append(i+1)

    apr = []

    for i in truepeak:
        if i == seq:
            apr.append(i)

    print('%s-streak count: ' %seq, len(apr))
    print('%s-streak prob (percent): ' %seq, (len(apr)/pop)*100)
    print('longest streak: ',longeststr + 1)
    print('process time: ',time.process_time(), 'second\n')

    return (len(apr)/pop)*100

Simplify #1
    for i in range(len(tosses)):
        if i == 0:
            continue

It's clear to me that you want to skip the first element. In that case, you can specify the starting point for range()
    for i in range(1, len(tosses)):

Simplify #2
    for i in range(pop):
        tosses.append(random.randint(1,2))

Since this is going to be an immutable sequence, use a tuple, with a generator
tosses = tuple(random.randint(1, 2) for _ in range(pop)

Simplify #3
            if curlongstr > longeststr:
                longeststr = curlongstr

Your condition is simple. The new value is always the larger of the two
Just use the max() function
            longeststr = max(longeststr, curlongstr)

Simplify #4
truepeak = []
    for i in peak:
        truepeak.append(i+1)

You're creating an entirely new list, and fill it up with the exact same elements as peak except with a constant 1 added to them. Very inefficient. Either add the values with the +1 from the beginning or use the +1 where necessary.
    for i in peak:
        if i + 1 == seq:
            apr.append(i + 1)

But again, all you do with apr is get its length, so there's absolutely no point in maintaining so many lists when all you have to do is keep a counter. That also removes the need to maintain peak

Calculate tosses as you go
After removing all of the previous loops, there will still be 2 left. One for calculating the tosses and the other goes through them to calculate them. What I propose is, go through it only once, and keep track of two things. The current flip and the previous flip
def torai(seq, iterations ):
    total_streaks = 0

    previous_flip = random.randint(1, 2)
    for _ in range(1, iterations):
        current_flip = random.randint(1, 2)

        if current_flip == previous_flip:
            total_streaks += 1

        # other calculations

        current_flip = previous_flip

    print(f"Total streaks: {total_streaks}")


Live example

String.capitalize = function(str, everyWord) {
    return _.map(_.words(str), function(val, key) {
        return key === 0 || everyWord ? _.capitalize(val) : val;
    }).join(" ");
};

Write to String not String.prototype. Extending native prototypes is not friendly.

Use underscore and underscore.string.

Basically don't re-invent the wheel ;)


Just some things that jump out at me:

You don't reset OnError

Huge red flag right there. If you're going to change OnError Goto you should immediately write the corresponding lines to set it back to normal.

Specifically: (Square brackets for emphasis)

    On Error GoTo CurrencyTradesEmpty
    CountCurrencyTrades = tblCurrencyTrades.DataBodyRange.Rows.Count
    [On Error Goto 0]

CleanExit:

    Exit Function

CurrencyTradesEmpty:
    [On Error Goto 0]
    CountCurrencyTrades = 0
    Resume CleanExit

Your function has too many responsibilities

Single Responsibility Principle. Your function has a hardcoded worksheet, hardcoded listObject and then handles the counting of said object. I would have the function take a ListObject as an argument and let another function handle the retrieval of said objects. Like so:

    Option Explicit

    Public Function GetCurrencyTradesCount() As Long

        Dim sheetCurrencyTable As Worksheet
        Set sheetCurrencyTable = Worksheets("CurrencyTable")

        Dim tblCurrencyTrades As ListObject
        Set tblCurrencyTrades = sheetCurrencyTable.ListObjects("CurrencyQuery")

        GetCurrencyTradesCount = CountListRows(tblCurrencyTrades)

    End Function

    Private Function CountListRows(ByRef targetList As ListObject) As Long
        '/ On Error (I.E. empty list), returns 0

        On Error GoTo CleanFail
        CountListRows = targetList.DataBodyRange.Rows.Count
        On Error GoTo 0

CleanExit:
        Exit Function

CleanFail:
        On Error GoTo 0
        CountListRows = 0
        Resume CleanExit

    End Function

Scoping

Your function is implicitly public. You should explicitly set a Public or Private scope for it.

Integer

Is officially deprecated. The compiler will silently convert all Integers to Longs, so just use Long instead.

Error Handling

Do you really want your function to return 0 for all errors? What if it's given an empty object reference? I would rename your label to CleanFail: and think about what other failure scenarios it might want to deal with.


Observations

Your $maxlifetime parameter is unused.
One of the conditions is redundant: any session older than two weeks should be discarded unconditionally.
The capitalization of your column names is unconventional.  Usually, identifiers are lowercase, and SQL keywords are ALL CAPS.  (Note: identifiers in MySQL are case-sensitive on Unix, but not Windows.)

Proposal

DELETE FROM session
    WHERE last_activity < CURRENT_TIMESTAMP() - INTERVAL 2 WEEK
    OR (rememberuser = 'N' AND last_activity < CURRENT_TIMESTAMP() - INTERVAL 30 MINUTE);

Advantages

This is a fixed query with no parameters, which keeps things simple.
It's almost English-like in readability.

Caveats

This requires your last_activity column to be of the DATETIME or TIMESTAMP type.  You could also make it work with integer Unix timestamps instead, using

DELETE FROM session
    WHERE last_activity < UNIX_TIMESTAMP(CURRENT_TIMESTAMP() - INTERVAL 2 WEEK)
    OR (rememberuser = 'N' AND last_activity < UNIX_TIMESTAMP(CURRENT_TIMESTAMP() - INTERVAL 30 MINUTE));

This assumes that the last_activity times were set according to the database server's clock, not the application server's clock.  Otherwise, if they are running on separate machines, or if you are careless with your treatment of timezones, you could end up with clock skew.  Therefore, it's best to pick one clock and stick with it consistently.  I prefer to use the database server's clock, for several reasons:

If your application runs on multiple application servers, all connecting to a central database, then the database clock is the natural official time source.
Your queries can be simpler, as illustrated above.
Storing the timestamps in a DATETIME column is more meaningful than storing them as integers.

So, to make this work, the last_activity times have to be inserted or updated using CURRENT_TIMESTAMP() or NOW(), or established by default when a TIMEZONE column has no specified value.
Admittedly, this formulation uses MySQL-specific date / time functions, so it is less portable.  Similar solutions exist for other database systems, though.


Making Tic-Tac-Toe winning check more efficient

You could store the winning positions as follows:

winning = [[(0, 0), (1, 0), (2, 0)],
           [(0, 1), (1, 1), (2, 1)],
           [(0, 2), (1, 2), (2, 2)],
           ...]

Now you can much more easily loop through the positions and test them, using all:

for positions in winning:
    for symbol in 'xy':
        if all(grid[r][c] == symbol for r, c in positions):
            print("{} Victory! You won in {} rounds!".format(symbol.upper(),
                                                             rounds)
            stl = False
            break

I would wrap all of this in a class, to make life a bit easier:

class TicTacToe:

    BLANK = '-'

    WINNING = [[(0, 0), (1, 0), (2, 0)],
               [(0, 1), (1, 1), (2, 1)],
               [(0, 2), (1, 2), (2, 2)],
               ...]

    def __init__(self):
        self.grid = [[self.BLANK for _ in range(3)] for _ in range(3)]

    def __str__(self):
        return '\n'.join([' '.join(row) for row in self.grid])

    def won(self):
        """Return the winning symbol, or None if not yet won."""
        for positions in self.WINNING:
            for symbol in 'xy':
                if all(self.grid[r][c] == symbol for r, c in positions):
                    return symbol

   def make_move(self, symbol, row, col):
       if self.grid[row][col] != self.BLANK:
           raise ValueError("Position already occupied.")
       self.grid[row][col] = symbol

   ...

In terms of general code review, note that:

You should not have multiple statements on the same line (e.g. else:turn = 'x');
The style guide includes guidance on whitespace (e.g. see the spaces after commas in the code I have posted);
There's no need to assign the result of print - it is None, just print(i,j,k);
You should not have code just running within the script, write a main function and guard a call to it behind if __name__ == '__main__':; and
You should generally have more, smaller blocks of functionality (e.g. you could have a function whose job is to get the user to input a valid row/col selection).


It's very easy to understand each step in your program, even without understanding
the actual algorithm you're implementing, which is really nice. Here's how I would improve things.

Use Functions

Each part of your main() function looks to me like it should be a separate named function. For example, it's clear that you're asking for whether the user wants to encrypt or decrypt, then getting the input string, then asking for a and b, then doing the encryption or decryption. Each of those things is a separate task and as such should be its own function. Your main() should look more like this:

int main() {
    std::string choice = getTaskFromUser(); // returns either 'e' or 'd'
    std::string input = getInputFromUser(); // return string to encrypt or decrypt
    int a, b;
    getAAndB(a, b); // Gets a and b
    if (choice == TASK_ENCRYPT)
    {
        displayEncryptedText(input, a, b);
    }
    else
    {
        displayDecryptedText(input, a, b);
    }

    std::cout << "\n";
    return 0;
}

Usability

There are a few things in your program that are named confusingly. First, I had to look up what "coprime" meant. It's not a hard concept, but I'd never heard it before. It might be worth printing out a one or two-sentence description of what it means when asking the user to input coprime numbers.

The variables a and b may also be poorly named. What function do they serve in the algorithm? Looking at the linked page, it looks like the cypher consists of a linear equation of the form y = ax + b where a is the slope and b is the intercept. That might be a good set of names, or it might not depending on how a typical user of such an algorithm thinks about it. a and b aren't terrible given the abstractness of the algorithm, but if you can improve those names, I recommend it. Certainly, as a user, I wouldn't understand what they represent.

Avoid Magic Numbers

Looking at the code, I see this mysterious number "26" repeated in several places. What does it represent? As an English speaker, I can guess that it's the number of letters in the alphabet, but what if I want to include numbers and symbols? What if I want to implement this algorithm in a different language with more or fewer letters? At the very least, there should be a named constant for the value 26. I recommend something like:

const int kAlphabetSize = 26;

That way you can change it later. Also, the magic values a, A, z, and Z should be handled better. Do you want to preserve the case of the original text? It seems to me like it makes the cypher weaker if you do. It's additional context that someone trying to decrypt it can use. I recommend allowing at least all the (printable) ASCII characters to be used as one large alphabet. It simplifies the code as you don't end up special-casing as many things.


First off, install Shellcheck and routinely run it on your scripts, or configure your editor to run it automatically. Now, Shellcheck is pretty rigorous and you would be forgiven for not solving all its warnings, but at the very least be aware of them.

#!/bin/bash

On some systems there’s a more up to date bash installed in a different location. In general you’d want to use
#!/usr/bin/env bash

Though in the case of Bash on Linux I think yours is OK.1
Next, enable stricter error checking:
set -euo pipefail

From help set:

-e  Exit immediately if a command exits with a non-zero status.
-u  Treat unset variables as an error when substituting.
-o pipefail the return value of a pipeline is the status of
the last command to exit with a non-zero status,
or zero if no command exited with a non-zero status

Regarding your variables, there’s a convention to use UPPER_CASE for environment variables, and snake_case for others. Not mandatory, but a nice way to distinguish them.

wget $STORE_URL/$1 -O ./$ZIP

Even though in this specific case there are no spaces or other special characters in your variables, always double-quote them to prevent string splitting — there’s simply no reason ever not to do so, and it gets you into the habit of spotting potential errors when quotes are missing.

cd ~/Downloads

That directory might or might not exist. As we’re talking about a GNOME environment, you might want to use something like $(xdg-user-dir DOWNLOAD) to get the actual download directory. The same is usually true for the path ~/.local/share, but the GNOME shell extensions documentation makes it sound as if the path is actually hard-coded.

rm $ZIP

This will not be executed if the script failed earlier due to an error. To ensure cleanup on error or if the user aborted the script, replace this with a trap.
Resulting script:
#!/usr/bin/env bash

# Install a target gnome shell extension defined via url

set -euo pipefail

store_url="https://extensions.gnome.org/extension-data"
extensions_path="$HOME/.local/share/gnome-shell/extensions/"
zip="gnome-extension.zip"

cd "$(xdg-user-dir DOWNLOAD)"
wget "$store_url/$1" -O "$zip"
trap 'rm "$zip"' ERR INT TERM EXIT

uuid=$(unzip -c "$zip" metadata.json | grep uuid | cut -d \" -f4)

if [[ ! -d "$extensions_path/$uuid" ]]; then
    mkdir "$extensions_path/$uuid"
    unzip -q "$zip" -d "$extensions_path/$uuid"
    gnome-shell-extension-tool -e "$uuid"
fi

gnome-shell --replace &

1 On macOS, on the other hand, it’s a bad idea since the Bash version of /bin/bash is eternally stuck at 3.2 due to licensing issues, and if you want to use any more recent Bash features you need to rely on a user-installed version with a different path.


Object-oriented URL loading and HTTP client with requests in Python

It makes sense to model the API like this if things are more
complicated, e.g. ability to pass around requests and responses as
objects might come in handy.

The last example shows why this alone isn't that user-friendly though:
In addition to mentioning the specific request (with the Request
suffix always around) you also have to call the process method.

I'd suggest an additional wrapper to make things easier in the normal
case, i.e. have login function or method that does this for you.

The code as-is looks good to me with the exception of the process
method - firstly you can just write return r.json(), secondly the
exit call in there is ... questionable.  I most certainly wouldn't
want to have a library call that on my program ever.

A minor thing I've also noticed is that the subclasses of BaseRequest
can't override any values via the constructor.  I'm guessing that's
deliberate, I just usually expect to be able to do that (so in the base
class call self.headers.update(headers) instead of the other way
round).


Request dispatcher for PHP JSON web service

Now, to my best knowledge, $this->request in PHP always points to the HTTP-request when a HTTP-request has just been made

My guess is that you are thinking of the super-global $_REQUEST? That is not the same as $this->request (unless somehow that instance variable gets set to something else)...

  Is it okay to just ignore the warning or is there a best practice to deal with it?

Declare the property, just as the other instance properties are declared (i.e. $method, $endpoint, $verb, etc.):

class BaseAPI {

    protected $request;

That way the IDE will know that the property should at least exist for each instance (though it might not be assigned a value until that switch statement).

Other Feedback

Switch statement cases:

switch ($this->method) {
        case 'DELETE':
        case 'PUT':
            // don't do anything yet

Those first cases are missing a break; so the PHP pre-processor will fall-through to the POST case.

header() calls in constructor

The three calls to header() in the constructor feels a little strange but then again it is difficult to know what the rest of your code looks like. Typically those would go in a method to render/send output.


Avoid --compiler-options in makefile using nvcc

As mentioned in the comments, define two macros:

COMPILER_OPTIONS := -Wextra -Wall -O3 -Wno-unused-result -Wno-unused-parameters
CUDA_COMPILER_OPTIONS := $(foreach option, $(COMPILER_OPTIONS), --compiler-option $(option))

C in CFLAGS stands for compiler, and should contain only the compile phase options. Don't send CFLAGS to the linker, it is surely not interested in, say, -Wall. Conventionally the link phase options are passed in LDFLAGS.
I am surprised that

    $(CC) $(CFLAGS) $(LIBS) main.o -o main

did pick the math library. The linker processes the command line once and sequentially. As written, there is no undefined symbols lm could resolve by the time it is processed. The bulletproof way is to specify libraries after objects:

    $(CC) $(CFLAGS) main.o -o main $(LIBS)

Nitpick. CC is conventionally assumed to produce .o from .c. Since your source is .cu I recommend to alias nvcc to something else. NVCC perhaps.


One quick win for readability would be to rename item to player.  Another improvement would be to put each field on its own line, since the long lines vastly exceed the 79-character limit suggested by PEP 8.

For the 16 scores, you can write…

writer.writerow([
    'YEAR',
    'FILENAME',
    'PLAYER_KEY',
    'PLAYER_NAME',
    'SEASON_TOTAL',
    'CALCULATED_SEASON_TOTAL',
    'MEAN',
    'MEDIAN',
    'STD_DEVIATION',
    'CV'
] + ['WK{0}'.format(i + 1) for i in range(16)])

for player in list_of_players:
    writer.writerow([
        year,
        filename,
        player['player_key'],
        player['player_name'],
        player['season_total'],
        player['calculated_season_total'],
        player['mean'],
        player['median'],
        player['std_deviation'],
        player['coefficient_of_variation']
    ] + player['scores'])


There is still code-golf

Here you have some golfed code:

function(e){e.style.background = "";}

ungolf it:

function(e) {
    e.style.background = ""
}

Run away from arguments.callee

  The 5th edition of ECMAScript (ES5) forbids use of arguments.callee() in strict mode. Avoid using arguments.callee() by either giving function expressions a name or use a function declaration where a function must call itself.

 - arguments.callee on MDN

here you have:

e.addEventListener("click", function(s){

instead do...

var MyFunction = function(s) {

and then...

e.addEventListener("click", MyFunction);

this allows you to then do:

this.removeEventListener("click", MyFunction, false);

Don't forget whitespace:

e.className==="message"

add whitespace around the ===. There a lot more places where spaces could be added

Conflicting things

In one part you're using:

 Array.prototype.slice.call

in another you are using:

Array.from

you should probably decide on one

Don't to a ton of things in one line

maxHash = Math.max(destinationMessage.id.slice(destinationMessage.id.indexOf("-")+1), maxHash)

that is waaaay to much in one line for a code reviewer like me ;) to be supporting. This:

destinationMessage.id.slice(destinationMessage.id.indexOf("-")+1)

looks like it can become a regex:

( /-(\d+)/.exec(destinationMessage.id) || [])[1]

or even better:

destinationMessage.id.split("-")[1]

use .getAttribute

rather than something like:

e.id

prefer:

e.getAttribute("id")

Remove all code-golf

var destinationMessage = messages[Array.from(messages).indexOf(self)-k.length]

you should split this into multiple variables. What if indexOf returns -1, you should handle that because otherwise your code will error and completely breakdown

use .bind rather than self = this

You're having to introduce self because the forEach's function creates a new scope. Instead use .bind and keep your old scope

num.forEach(function(k) {
    // code
}.bind(this))

Even better, use e.target to get the element that's been clicked. I highly recommending avoiding using this in lambdas to store data.


Think of the phrase : public to mean "is a".

A dog is not a kennel, nor is a cat, so Dog and Cat should not inherit from Kennel. You need a class called Animal. Cats and dogs are animals, so Cat and Dog should derive from Animal. Animals are contained in a kennel.


Generic function With to do a one-liner using block

What is more clearer here?
This:
using (Model model = GetModel())
{
    foreach (var item in model.Databases)
    {
        Console.WriteLine(item.Name);
    }
}

or this:
With(GetModel(), model =>
    model.Databases.ToList().ForEach(c =>
        Console.WriteLine(c.Name)
    )
)

You've defined some method so you could rearrange some things and add additional levels of indirection to run slower and more inefficient than if you had just written the standard way using the using and foreach blocks.  What did you gain here?  I'll tell you, nothing.
Any half-decent C# programmer should know what the using and foreach blocks do.  There should be no question about it.  Seeing your block of code, it's not so clear... we'd have to figure out what you're doing here.
What if someone saw your block of code and wanted to know what is going on?  I look at that and see With... "With" what?  What the heck is that supposed to mean?  If anything, it is only more confusing to people who are familiar with VB.NET's With keyword (which does something completely different).  The name isn't very great.  You should have given it a more descriptive name.  UsingDisposable might have been a better choice or something along those lines.
Don't even get me started on the ToList/ForEach combo... You can never go right doing this instead of using a simple foreach loop.  Why would to take a perfectly good collection, copy that collection into another list, just so you can call some method to do stuff with the added overhead of calling another method to do something on each item?  The ForEach method has it's place and that's if and only if you start out with a list in the beginning.  The overhead of the delegate is more forgivable here since that's what it was designed for.  I understand that this particular usage is just a "hack" just to make this loop work, but this should never be the answer.  If you must, write an extension at least.
See reason number two of Eric Lippert's "foreach" vs "ForEach".  The same can be said here twofold, both for the With() method and your use of ForEach().
What happens if you need to do more than one statement in each of the blocks:
With(GetModel(), model =>
{
    HelloThere();
    model.Databases.ToList().ForEach(c =>
    {
        DoSomething();
        Console.WriteLine(c.Name);
        DoSomethingElse();
    });
    DoMoreStuff();
});

Here come the braces again and even more typing when instead you could have just done:
using (var model = GetModel())
{
    HelloThere();
    foreach (var item in model.Databases)
    {
        DoSomething();
        Console.WriteLine(item.Name);
        DoSomethingElse();
    }
    DoMoreStuff();
}

Save yourself the grief, just use the using and foreach blocks.


refresh() method must be processed by only one thread at a time ...

private final Semaphore refreshLock = new Semaphore(1);

A mutex is arguably a better synchronization object choice when you only need one thread at a time. So I would advise you to use a ReentrantLock instead, for instance.

synchronized (refreshLock) {
    if (refreshLock.hasQueuedThreads()) {
        System.out.println("skip this thread ... " + Thread.currentThread().getId());
        return; // don't put one more to the queue
    }
}

So in fact you are using not one but two synchronization objects, a semaphore and a monitor. The reason why you are doing this is because of your second requirement. However you can implement both of your requirements using only one synchronization object which would make your code simpler (hopefully).

Thread.sleep(5000);

No! I know you are doing this to emulate a long running operation. However long running operations should never execute within concurrent control, specially if it's running one at a time.

What this means effectively is that all threads calling refresh will be blocked by at least a whopping 5 seconds.

So obviously you have to implement your refresh method as a process that runs on the background. Meaning that you will be returning a Future that may complete at any given moment. For a thread that will do the process this moment will be when the process has finished, for all others this will be almost immediately.

This is the resulting implementation:

private final ReentrantLock refreshLock = new ReentrantLock();
private boolean hasRefreshed = false;
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);

public Future refresh() {
    System.out.println("call refresh()");
    try {
        refreshLock.lock();
        if(hasRefreshed) {
            System.out.println("already refreshed");
            return executor.submit(() -> {});
        }

        hasRefreshed = true;
        return executor.submit(() -> {
            System.out.println("process ... " + Thread.currentThread().getId());
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("### DONE");
        });

    }finally {
        refreshLock.unlock();
    }
}

Ideally the synchronization logic would be implemented in a generic class that would be able to handle any use case.

You will also have to change your main a bit, so your program doesn't exit immediately.

IntStream.range(0, 12)
    .mapToObj(i -> service.submit(new Task(i, scratch)))
    .forEach(f -> {
        try {
            f.get();
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (ExecutionException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    });


Checking for missing values in several columns of a spreadsheet

I discourage the use of single letter variable names. So, I recommend changing e to something else. I'm drawing a blank though because you can't use Cells in Excel's flavor of vba. That's the object that refers to the sheet's collection of all cells. Maybe cases would work given the context.
I like your use of the With statement here. I'm tossing that out there because I know others will disagree with me. With can be abused, but this is not the case with your code.
When declaring an iterator variable for a ForEach statement, I like to declare it just outside the loop. You should move Dim cell As Range.
j is a useless variable. I would just add two to i instead.
Speaking of 2, it's a magic number. I would consider declaring an offset variable.

    Dim i As Integer
    Const offset As Integer = 2

    For i = 1 To columnD.Count
        Range(("D" & i + offset), ("D" & columnD.Count + offset)) = columnD.item(i)
    Next i

I take back what I said about the With statement. It would be a good use, but you're using Range wrong. For example, this line doesn't do what you think it does.

Range(("D" & i + offset), ("D" & columnD.Count + offset))

You're using the global Range object, which is the same as saying ActiveSheet.Range(). That's not what you want. This can lead to some hard to track down heisenbugs. You want to work on your named sheet. You need to add the dot in order to be working on the named sheet.

.Range(("D" & i + offset), ("D" & columnD.Count + offset))

From here on out I'm at a bit of an unfair advantage because I wrote the Enumerable class that you're using.

You don't need the .value when using the useDefaultProperty option. Value is the default property of any Range object.

If Not (e.Contains(cell.value, True)) Then

Can be changed to

If Not (e.Contains(cell, True)) Then

The same thing applies to the Add method.

columnD.Add (cell.value)

Enumerable uses a magic attribute that gives it a default property as well. So, just like the built in Collection, there's no reason to use the verbose method of getting an item. Item is the default property.

columnD.item(i)

Becomes

columnD(i)


I would suggest something like that

public interface IDeviceScript
{
    string Name { get; }
    string SecurityScriptName { get; }
    string BusinessScriptName { get; }
    bool IsScriptApply(IDevice device);
}

public interface IDevice
{
    Locations Location { get; }
    // more methods and properties
}

[Serializable]
[AttributeUsage(AttributeTargets.Class)]
public class DeviceScriptAttribute : Attribute
{
}

[DeviceScript]
public class UnitedStatesScript : IDeviceScript
{
    public string Name
    {
        get { return "US_Script"; }
    }

    public string SecurityScriptName
    {
        get { return "US_SecurityScript"; }
    }

    public string BusinessScriptName
    {
        get { return "US_BusinessScript"; }
    }

    public bool IsScriptApply(IDevice device)
    {
        return device.Location == Locations.US;
    }
}

public IDeviceScript GetScriptForDevice(IDevice device)
{
    IEnumerable<IDeviceScript> deviceScripts =
        Assembly.GetExecutingAssembly()
                .GetTypes()
                .Where(t => t.GetCustomAttributes<DeviceScriptAttribute>().Any())
                .Select(t => Activator.CreateInstance(t))
                .Cast<IDeviceScript>();

    foreach (IDeviceScript deviceScript in deviceScripts)
    {
        if (deviceScript.IsScriptApply(device))
        {
            return deviceScript;
        }
    }

    return null;
}

Now you can add more scripts just by adding new classes to your project. No xml configs are required :)

Futher suggestions:

After calculating deviceScripts enumerable once you can store it in some static field for further use.
Name property of IDeviceScript could be moved to DeviceScriptAttribute if you don't need it in your code.
I would make GetScriptForDevice method static but unfortunately .net doesn't support statics in interfaces :(


Your code looks fine, depending on the use case in which it is applied. A few people have mentioned "composition over inheritance". This is a good point, but it is not directly practical in this situation. You need inheritance in order to get access to the functionality you use in the LinkedHashMap. But, there is an approach where you use inheritance to access the functionality, and composition to expose it.

If you assume the direct approach you have taken is useful for accessing additional functionality from the LinkedHashMap, then your code is good. The variables are well named, the code is consistent (there's a glitch on the one comment line...), and it's all fine.

Whether the hybrid approach is useful to you depends on whether your use case requires just a smallish subset of the the LinkedHashMap functionality. For example, if you needed to access the entries on the content as Map.Entry instances, or if you need to do more complicated iterations, then you start to lose the benefit of the composition.

In this case, the first approach you have using straight inheritance has a place. Th secnd approach requires wrapping the functionality you need from the private inner cache.

This second approach requires tailoring your LRU cache to its specific use cases. At the moment, you have a very general LRU cache. On the other hand, you are only using the put method (and presumably the get()). You can create a class with just these methods (and a selection of other ones that make sense) and gave an internal inherited instance for access to the LinkedHashMap. Consider the following:

public final LRUCacheVC<K,V>() {

    // use inheritence to access LinkedHashMap functionality.
    private static class AccessOrderCache<T,U> extends LinkedHashMap<T,U> {
        private final int capacity;
        AccessOrderCache(final int capacity) {
            super(capacity, 0.75f, true);
            this.capacity = capacity;
        }
        @Override
        protected boolean removeEldestEntry(java.util.Map.Entry<T, U> entry) {
            return size() > MAX_ENTRIES;
        }
    }

    // Use composition to access the Inherited Cache.
    private final AccessOrderCache<K,V> cache;

    public LRUCacheVC(final int capacity) {
        cache = new AccessOrderCache<>(capacity);
    }

    public V get(K key) {
        return cache.get(key);
    }

    public V put(K key, V value) {
        return cache.put(key, value)
    }

    @Override
    public int hashCode() {
        return cache.hashCode();
    }

    @Override
    public boolean equals(Object other) {
        return other != null
            && (other instanceof LRUCacheVC)
            && cache.equals(((LRUCacheVC)other).cache);
    }

    @Override
    public String toString() {
        return cache.toString();
    }
}

Note how you use inheritence to access the LinkedHashMap concepts, then use composition to incorporate that new class in to your code.

You only expose that limited functionality that you want (get and put), as well as a few other standard methods that make life easier.


First Python Script - Web Scraper with results saved to MySQL DB

Here are some notes grouped by categories.
HTML Parsing
Instead of collecting names and amounts in separate lists, iterate over the elements with a tab_row class and collect the results into a single list of dictionaries.
You can get performance improvements by switching to lxml from html.parser. Requires lxml to be installed.
You can use more concise CSS selectors instead of find_all().
You can also use SoupStrainer class that would allow to improve on parsing speed by limiting what the parsing tree to the desired part only.
Working with the database
First of all, do not use string formatting to pass your query parameters into the query. You are not only exposing your code to SQL injection attacks, but also get potential issues with character escaping and type conversions. Use parameterized queries instead.
If you are gonna collect your data into the list of dictionaries, you may do your insert via executemany() which, aside from being more concise,
may provide a performance boost as well.
It is also a good idea to use multi-line strings for your database queries.
Code Style
There are multiple code style issues. The code is not PEP8-complaint. Please analyze your code with flake8, pylint or other linters.
Also, don't repeat the database connection code, extract it into a separate function and reuse.

Here is the modified version of the code (renamed functions and logically separated into multiple functions):
import sys
import urllib2

import MySQLdb as mdb
from bs4 import BeautifulSoup, SoupStrainer

import dbconfig as cfg

def db_connect():
    connection = mdb.connect(cfg.mysql['host'], cfg.mysql['user'], cfg.mysql['passwd'], cfg.mysql['db'])
    cursor = connection.cursor()

    connection.set_character_set('utf8')
    cursor.execute('SET NAMES utf8;')
    cursor.execute('SET CHARACTER SET utf8;')
    cursor.execute('SET character_set_connection=utf8;')

    return connection, cursor

def pull_games(page):
    parse_only = SoupStrainer(class_='tab_row')
    soup = BeautifulSoup(page, 'lxml', parse_only=parse_only)

    return [
        {
            'name': row.h4.get_text(),
            'price': row.select_one(".discount_original_price").get_text(),
            'discount': row.select_one('.discount_final_price').get_text()
        }
        for row in soup.select(".tab_row")
    ]

def insert_games(connection, cursor, data):
    query = """
        INSERT INTO
          game_pricing
          (game_name, original_price, discount_price)
      VALUES
          (%(name)s, %(price)s, %(discount)s)
    """
    cursor.executemany(query, data)
    connection.commit()

def check_games(cursor):
    query = """
        SELECT
            game_name, original_price, discount_price
        FROM
            game_pricing
    """
    cursor.execute(query)

    result = cursor.fetchall()
    for game_name, original_price, discount_price in result:
        print("game_name=%s, original_price=%s, discount_price=%s" % (game_name, original_price, discount_price))

if __name__ == '__main__':
    reload(sys)
    sys.setdefaultencoding('UTF8')

    url = 'http://localhost'
    page = urllib2.urlopen(url)

    games = pull_games(page)

    try:
        connection, cursor = db_connect()
        insert_games(connection, cursor, games)

        check_games(cursor)
    finally:
        cursor.close()
        connection.close()


What I tend to do in these situations is have two states for the floaty thing:

When it's not in "stay on the page" mode, it has position:relative.
When the page is scrolled down enough, it gets position:fixed and stays on the page.

It is not animation intensive at all,  it's more like the way gmail used to be before the recent changes. You only change the element's style when the page scrolls up or down past a certain point, but most scroll events you just ignore.


The problem with code like this is that it grows very quickly.

switch (unitFrom) {
    case "Kilometers": switch (unitTo){

Adding one unit means that you have to provide conversions to every other unit. But there's a pattern in your code:

    case "Metres": initialValue *= 1000;
        break;
    case "Centimetres": initialValue *= 100000;
        break;
    case "Millimetres": initialValue *= 1000000;
        break;
    case "Feet": initialValue *= 3280.8399;
        break;
    case "Yards": initialValue *= 1093.6133;
        break;
    case "Inches": initialValue *= 39370.0787;

Each unit is essentially just a factor. And the conversion is just the multiplication of the length value with that factor.

Take a look at the SI unit system, where such factors are actually part of the unit:

1 mm = =1 millimeter = 1 * milli * meter = 1 * 10^(-3) * meter

"milli" which would generally be considered part of the unit is actually just a number with a name: 10^(-3)

Notice that the opposite conversion means to divide by that factor.

To simplify the conversion, you can choose a common base unit.
Now you don't have to convert every unit to every other unit but only have to specify one conversion: to/from the base unit.

Here's an example class doing this:

import java.util.HashMap;
import java.util.Set;

public class Converter
{
    public static void main (String[] args)
    {
        Converter converter = new Converter();

        Set<String> units = converter.availableUnits();

        double value = 5.4;

        for (String unitFrom : units)
        {
            System.out.println(value + " " + unitFrom + " are:");

            for (String unitTo : units)
            {
                System.out.println("\t" + converter.convert(unitFrom, unitTo, value) + " " + unitTo);
            }

            System.out.println();
        }
    }

    private HashMap<String, Double> _units;

    public Converter()
    {
        _units = new HashMap<String, Double>();

        _units.put("Millimetres", 1.0);
        _units.put("Metres", 1000.0);
        _units.put("Inches", 25.4);
        _units.put("Feet", 304.8);
        _units.put("Yards", 914.4);
    }

    public double convert(String from, String to, double value)
    {
        return value * _units.get(from) / _units.get(to);
    }

    private Set<String> availableUnits()
    {
        return _units.keySet();
    }
}

The program does every conversion possible.

I kept the conversion from one unit to itself in as a quick test. If you don't want that, opt-out when unitFrom == unitTo.

5.4 Millimetres are:
    5.4 Millimetres
    0.017716535433070866 Feet
    0.21259842519685043 Inches
    0.0054 Metres
    0.005905511811023623 Yards

5.4 Feet are:
    1645.92 Millimetres
    5.4 Feet
    64.80000000000001 Inches
    1.64592 Metres
    1.8 Yards

5.4 Inches are:
    137.16 Millimetres
    0.44999999999999996 Feet
    5.4 Inches
    0.13716 Metres
    0.15 Yards

5.4 Metres are:
    5400.0 Millimetres
    17.716535433070867 Feet
    212.5984251968504 Inches
    5.4 Metres
    5.905511811023622 Yards

5.4 Yards are:
    4937.76 Millimetres
    16.2 Feet
    194.4 Inches
    4.93776 Metres
    5.4 Yards

Additional thoughts:

The name of each unit is only specified once. Retyping string literals is prone to error "Millimetres" != "Millimeters", which the compiler cannot catch.

You could go further and define a class Unit, which besides the name and factor can contain, an abbreviation, plural and singular forms, etc.


Count power of big numbers and then apply modulo on this numbers

Your spelling of length is unconventional, and will cause errors.

Calculating the full result will generate a large number, slowing computation.  It's better to reduce the partial results as you compute the power, and keep the partial result mod n - you'll probably want to use binary exponentiation instead of the ** operator so that you can apply the modulus to the intermediate results.

I don't see what m = int(m) and similar lines are intended to achieve - probably worth a comment there.

How is the final (partial) block handled?  That seems to be missing altogether.


Finding the class to which the IP address belongs

Here are some things that may help you improve your code.

Eliminate unused variables

The parameter hb in the print() function and value in main() are unused variables and should be omitted from the program.

Fix your formatting

There are inconsistent spaces at the beginning of lines and inconsistent indentation.  Being consistent helps others read and understand your code.

Use only required #includes

The code has a number of #includes that are not needed.  In this code, for instance, nothing from <string.h> is used, so that header can and should be omitted.  Only include files that are actually needed.  This makes the code easier to understand and maintain and also may slightly speed up compiling.

Understand what standards don't guarantee

A knowledgeable reader of this code (and possibly the compiler) is likely to be puzzled by this line of code:

printf("The address in the structure is network byte order:(Big- Endian) %X %d\n", addr, addr);

The reason is that "%X" expects an unsigned int and "%d" expects an int but what you're passing is struct in_addr.  The man page tells us that the relevant defintion for that is as follows:

typedef uint32_t in_addr_t;

struct in_addr {
   in_addr_t s_addr;
};

This means that on machines where int is not the same size as uint32_t, there is a potential for trouble.  Specifically, if the code is compiled for a machine with a 16-bit int, this won't give the results you intend.  Better would be to have the compiler check to make sure that this doesn't happen.  One way to do this is to add these lines to the program:

#include <limits.h>
#if UINT_MAX == 65535
#error "This program requires at least a 32-bit unigned int."
#endif

Note that sizeof can't be used for the preprocessor, which is why we use the definition of UINT_MAX.  This isn't foolproof, since there are real machines using 24-bit words, but catches the more common case of a 16-bit.  To be completely sure, we can't really use the preprocessor.  We could do this:

if (sizeof(int) < 4) {
    printf("This program requires at least 32-bit int, but yours has a %ld-bit int\n", sizeof(int) * 8);
    return 1;
}

Then instead of passing addr to your printf, pass addr.s_addr instead.

Try to write portable code

Things that are guaranteed by the C standard are absolutely portable to conforming compilers on all platforms.  Things that are specified by POSIX standards are portable to the subset of machines that conform to POSIX.  Your life will be easier if you aim for those.  Things that are compiler extensions, such as error are not necessarily portable to other machines.  For that reason, I'd suggest that instead of using error in this program (which is a GNU extension), you could use the form shown above and use printf and return.  It's also worth noting that inet_aton is not actually in the POSIX standard, but is widely used (and much better than the poorly defined but standard inet_addr).  However, it may have some surprising attributes.  For example, it will interpret a single number as an IP address.  If we give the argument 3232236027 it will interpret this as the address 192.168.1.251.  If that's what you want, that's fine.  If not, you might consider instead using inet_pton (which is POSIX):

ret = inet_pton(AF_INET, IP, &addr);

Eliminate global variables where practical

The code declares and uses a global variable, bin.  Global variables obfuscate the actual dependencies within code and make maintainance and understanding of the code that much more difficult.  It also makes the code harder to reuse.  For all of these reasons, it's generally far preferable to eliminate global variables and to instead pass pointers to them.  That way the linkage is explicit and may be altered more easily if needed.  In this case, you could define bin within main like this:

int bin[32];

And then call print like this:

printf("Class - A\n");
print(1, 7, bin, 32);

Eliminate complexity where practical

The convert_to_binary() function is rather complex internally.  I'd recommend simplifying it or eliminating it entirely.  Here's one way to simplify it:

void convert_to_binary(uint32_t decimal, int *bin, size_t size)
{
    bin += size - 1;
    for ( ; size; --size) {
        *bin-- = decimal & 1u;
        decimal >>= 1;
    }
}

Rethink function interfaces

The essential piece of work done in the program is to identify the address class of the passed IPv4 address.  I'd put that into a function like this:

char address_class(uint32_t addr) {
    const struct class_mask {
        uint32_t mask;
        uint32_t classbits;
        char designator;
    } class_mask[3] = {
        { 0x80000000u, 0x00000000u, 'A' },
        { 0xc0000000u, 0x80000000u, 'B' },
        { 0xe0000000u, 0xc0000000u, 'C' },
    };
    for (unsigned i=0; i < 3; ++i) {
        if ((addr & class_mask[i].mask) == class_mask[i].classbits) {
            return class_mask[i].designator;
        }
    }
    return '?';
}

With a small change, we could actually turn this into the print function.  If we do so, the entire program then looks like this:

#include <stdio.h>
#include <arpa/inet.h>

char print_classification(uint32_t addr) {
    const struct class_mask {
        uint32_t mask;
        uint32_t classbits;
        uint32_t netmask;
        uint32_t hostmask;
        char designator;
    } class_mask[3] = {
        { 0x80000000u, 0x00000000u, 0x40000000u, 0x00800000u, 'A' },
        { 0xc0000000u, 0x80000000u, 0x20000000u, 0x00008000u, 'B' },
        { 0xe0000000u, 0xc0000000u, 0x10000000u, 0x00000080u, 'C' },
    };
    for (unsigned i=0; i < 3; ++i) {
        if ((addr & class_mask[i].mask) == class_mask[i].classbits) {
            printf("class = %c\nThe network bits are:\n", class_mask[i].designator);
            for (uint32_t mask = class_mask[i].netmask; mask; mask >>= 1) {
                if (mask == class_mask[i].hostmask) {
                    printf("\nThe host bits are:\n");
                }
                printf("%c ", addr & mask ? '1' : '0');
            }
            printf("\n");
            return class_mask[i].designator;
        }
    }
    printf("Unknown address class\n");
    return '?';
}

int main(int argc, char **argv)
{
    struct in_addr addr;

    if (sizeof(int) < 4) {
        printf("This program requires at least 32-bit int, but yours has a %ld-bit int\n", sizeof(int) * 8);
        return 1;
    }
    if (argc != 2) {
        printf("Usage: %s ipv4addr\nwhere ipv4addr is of the form xxx.xxx.xxx.xxx\n", argv[0]);
        return 1;
    }
    if (inet_pton(AF_INET, argv[1], &addr) == 0) {
        printf("Error: couldn't interpret %s as an IPv4 address\n", argv[1]);
    }
    print_classification(ntohl(addr.s_addr));
}

Rethink the purpose of the program

Perhaps this was just a programming exercise, but it's probably worth pointing out that the use of IPv4 address classes has been obsolete since the introduction of CIDR in 1993.


Streams should always be closed. You will have resource leaks if your method throws an exception. Either close the streams in a finally block, or use try-with-resources to make sure they get closed.
Optional curly braces aren't. Skipping them will often lead to bugs when code gets modified later.
The typical loop structure used for working with streams looks more like
int charsRead;
while ((charsRead = dis.read(buffer) > 0) {
    // do stuff
}

10,000 is pretty big for a buffer. That may not be the best choice.
Please don't swallow the stack trace. That's critical information when this code needs to be debugged later.
Opinion: var is icky.
If you apply all these changes, your code might look more like:
private void copyFile(File in, File out) {
    byte[] buffer = new byte[1024];
    try (FileInputStream dis = new FileInputStream(in);
            FileOutputStream dos = new FileOutputStream(out)) {
        int charsRead;
        while ((buffer = dis.read(buffer) > 0) {
                dos.write(buffer, 0, charsRead);
        }
    } catch (IOException e) {
        //I don't know how to use your logging library to display exception stack trace, so..
        e.printStackTrace(System.err);
    }
}

Of course, this is assuming that you can't use the rather intuitively named Files.copy() instead. That would be much better.
private void copyFile(File in, File out) {
    try {
        Files.copy(in.toPath(), out.toPath());
    } catch (IOException e) {
        e.printStackTrace(System.err);
    }
}


Too frenetic

I ran your program but it was very frenetic.  It was constantly clearing the "Loading" prompt and reprinting it which resulted in a flickering effect.  In addition, the cursor also moved around in a flickery manner (similar to the green box in the animated image).

To improve this, I would do two things:

Don't constantly draw when nothing has changed.  Instead, sleep until the next trigger time and then redraw.  This also has the added benefit of not using 100% of your cpu.  Presumably, you will have another thread running which is doing some loading work, and you don't want this thread to hog cpu time.
You don't need to clear and redraw the whole prompt until you get to the last dot.  Up until that point, you can just draw one dot at a time.

Rewrite

I rewrote your program with the above two fixes in mind:

#include <stdio.h>
#include <unistd.h>

int main(void)
{
    const int trigger = 500; // ms
    const int numDots = 4;
    const char prompt[] = "Loading";

    while (1) {
        // Return and clear with spaces, then return and print prompt.
        printf("\r%*s\r%s", sizeof(prompt) - 1 + numDots, "", prompt);
        fflush(stdout);

        // Print numDots number of dots, one every trigger milliseconds.
        for (int i = 0; i < numDots; i++) {
            usleep(trigger * 1000);
            fputc('.', stdout);
            fflush(stdout);
        }
    }
}

Rewrite 2

In response to the comment where @syb0rg indicated that the main thread should not sleep, here is what I would do in that case:

#include <stdio.h>
#include <time.h>

static void redrawPrompt(void);
static void doWork(void);

int main(void)
{
    const int trigger   = (CLOCKS_PER_SEC * 500) / 1000;  // 500 ms in clocks.
    clock_t   prevClock = clock() - trigger;

    while (1) {
        clock_t curClock = clock();

        if (curClock - prevClock >= trigger) {
            prevClock = curClock;
            redrawPrompt();
        }
        doWork();
    }
}

static void redrawPrompt(void)
{
    static int  numDots;
    const  int  maxDots = 4;
    const  char prompt[] = "Loading";

    // Return and clear with spaces, then return and print prompt.
    printf("\r%*s\r%s", sizeof(prompt) - 1 + maxDots, "", prompt);
    for (int i = 0; i < numDots; i++)
        fputc('.', stdout);
    fflush(stdout);
    if (++numDots > maxDots)
        numDots = 0;
}

static void doWork(void)
{
    // This function does loading work but returns at least every 500 ms.
}


Though not in Javascript, my uses of JWT have always used the password as the JWT secret.  The JWT payload is whatever you need to identify the user -- username in your case.  You can add in a CSRF token of some sort as well.  I have an example on my GitHub that is a very simple application using JWT as the authentication mechanism - https://github.com/dave-shawley/readings/blob/7d2504587daa6a174fc3cbc0a5478fa817412eea/readings/static/js/login.js#L10-L26 is the javascript login code.  Mind you that I am most certainly not a javascript programmer so don't read too much into my example for style advice ;)

My login code builds a JWT payload that looks something like:

{
  "exp": 1488027170,
  "iss": "https://whatever.example.com/login",
  "csrf": "123456ABCDEF",
  "nbf": 1488026870
}

where "nbf" is the current time, "exp" is the expiration time, and "iss" is the referring web site.  "csrf" is a one-time token that is embedded in the HTML form.

I encode this structure using the entered password as the secret and pass the resulting token to my login endpoint.  I have the user name in a secured cookie but it could be passed in the JWT payload as well.  On the receiving side, I look up the user information in my data store by the user name from the cookie.  Then I verify that the JWT payload was signed using the password as the secret and that it is still valid.  If everything checks out, then the user is authenticated.


The model you chose for your data is quite far from ideal. I guess that's one of the reasons your code became a little messy. However, even with this model, the end result can be reached in a more readable, and probably more efficient way:

var pricesPerWeek = weekPrices
    .Where(weekPrice => weekPrice.Year == DateTime.Now.Year)
    .SelectMany(
        (weekPrice) => weekPrice.Firms.Where(firm => firm.Name == "ABC"),
        (week, firm) => new {week.Week, firm.Price})
    .ToList();

In this code, weekPrices is a List<WeekPrice>. This code first selects week prices from the current year. It then uses the overload SelectMany to flatten the list of week prices to a collection of anonymous objects with properties Week and Price.

A complete and working sample of this code can be found on dotnetfiddle.net.

However, as said before, your model is not ideal. I would refactor your model to three classes: Firm, Product and ProductPrice:

// Represents a firm you track.
public class Firm
{
    public Firm()
    {
        Prices = new List<ProductPrice>();
    }

    public int Id {get;set;}
    public String Name {get;set;}
    public List<ProductPrice> Prices {get; private set;}
}

// Keeps record of the firm's price of a product at a certain moment
public class ProductPrice
{
    public int FirmId {get;set;}
    public int ProductId {get;set;}
    public int Year {get;set;}
    public int Week {get;set;}
    public decimal Price {get;set;}
}

// Represents a product you track.
public class Product
{
    public int Id {get;set;}
    public String Description {get;set;}
}

This model has several advantages over your model. For instance, firms do not get a new Id every week. Instead, the firm's Id and Name are stored once. The same goes for products (although that isn't part of your question). All you have to do every week, is add an entry of type ProductPrice for all product-firm combinations.

And now, with this model, back to your question. To select the weeks and prices for a certain firm (and product) you can do:

var pricesPerWeek = firms
    .Where(firm => firm.Id == 1)
    .SelectMany(firm => firm.Prices)
    .Where(
        productPrice => productPrice.Year == DateTime.Now.Year &&
        productPrice.ProductId == 1)
    .Select(productPrice => new {productPrice.Week, productPrice.Price})
    .ToList();

In this code, firms is a List<Firm>. This code first selects the correct firm, it then selects the correct weeks (and product) and then returns a collection of anonymous objects with properties Week and Price.

A complete and working sample of this code can be found on dotnetfiddle.net.


implementing simple stream processor with sockets

For the benefit of others (because this answer is two years late):

I had to implement a socket solution rapidly to accommodate testing a feature that required them. Ended up using socketserver to simplify the implementation, i.e., only about a dozen lines were needed.

Example below is pretty much straight out of the socket server docs:

""" creates, activates a socket server """
import socketserver

HOST, PORT = "localhost", 9999

class MyTCPHandler(socketserver.BaseRequestHandler):
    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        print("{} wrote:".format(self.client_address[0]))
        print(self.data)
        # just send back the same data, but upper-cased
        self.request.sendall(self.data.upper())

print("Creating the server, binding to localhost on port", PORT)
server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)

def activate_server():
    server.serve_forever()

def stop_server():
    print("Shutting the server on port", PORT)
    server.shutdown()

if __name__ == "__main__":
    activate_server()


The essence of the Factory method Pattern is to "Define an interface
  for creating an object, but let the subclasses decide which class to
  instantiate. The Factory method lets a class defer instantiation to
  subclasses."

If you insist on the above GoF definition there are two issues.

First, you should create a DriveableFactory interface and rename your DriveableFactory to (for example) CarDriveableFactory.

abstract class DriveableFactory
{
    static public function create($numberOfPeople);
}

class CarDriveableFactory extends DriveableFactory
{
    static public function create($numberOfPeople) { ... }
}

But your code is fine, if you don't need (don't have a reason) the abstract DriveableFactory interface do NOT add it to the code.

The second issue is that the create method should not be static. If it's static subclasses cannot override the create method.

Finally, the App class looks unnecessary. So, I'd write something like this:

DriveableFactory factory = new CarDriveableFactory();
$DriveableMachine = factory->getDriveableMachine(2);
$DriveableMachine->start();

Some small improvements:

3.5 is an allowed value? And 3.1415? If not consider changing

else if( $numberOfPeople >= 3 && $numberOfPeople < 4)

to

else if($numberOfPeople == 3 || $numberOfPeople == 4)

In the last line of the create() method I would throw an IllegalArgumentException (or a similar one in PHP) with the message "invalid value: " . $numberOfPeople.


A few things to add to Michael Zedeler's review:

Your formatting is a little odd. Pick an indenting scheme and stick with it. (This seems to be part of a bigger script though, so maybe it's just copy/paste gone wrong?)

Don't assume array indexes exist (read the first section of this).

You assume username's are available?

By the HTTP standard, Location headers must have a full URL.

I would pull the hashed password into PHP land and do the comparison there. This has multiple advantages:

1) You can know whether the error is because the user doesn't exist or because the password is wrong
2) The MySQL query log is guaranteed to not contain the password in plain text

Your last if clause is a perfect example of why you should always use braces with if/else. It comes down to a stylistic choice whether or not to actually always use them, but in this situation, your code is wrong without them on the last clause:

    else
        $stmt = $db->prepare("INSERT INTO users (username, password, email, salt, registered, registration_ip) VALUES (:username, :password, :email, :salt, :registered, :registration_ip)");
        $stmt->execute(array(':username'=>$username, ':password'=>sha1($salt.$password1), ':email'=>$email, ':salt'=>$gen_salt, ':registered'=>time(), ':registration_ip'=>$_SERVER['REMOTE_ADDR']));

Is the same thing as:

    else {
        $stmt = $db->prepare("INSERT INTO users (username, password, email, salt, registered, registration_ip) VALUES (:username, :password, :email, :salt, :registered, :registration_ip)");
    }
    $stmt->execute(array(':username'=>$username, ':password'=>sha1($salt.$password1), ':email'=>$email, ':salt'=>$gen_salt, ':registered'=>time(), ':registration_ip'=>$_SERVER['REMOTE_ADDR']));

This means if that if any of the other branches are followed, you'll get an invalid object fatal error since you'll be trying to call execute on null.

What is the data type of registered? I'm a little concerned that it might be an int. It should be either a timestamp or a datetime (likely a timestamp in this situation).

While you've made good steps using sha1 and a salt, you might should consider using a better scheme for hashing. There's a lot of good information here.

I'd use a different flow to handle the errors. In particular, there's no reason that a username error and a password error can't happen at the same time:

$errors = array();

if (strlen($username) < 4) {
    $errors[] = "Username must be at least 4 characters.";
}

if (strlen($password1) < 4) {
    $errors[] = "Password too short";
} else if ($password1 != $password2) {
    $errors[] = "Passwords do not match";
}

if (!$errors) {
    //Create the user
}

You should declare $errors ahead of appending to it. $errors[] will create the variable fine without complaining, but it's much easier to read code if you know where all of the variables come into play. And, from a technical perspective, reading a non-existent $errors will complain (and error reporting should be cranked all the way up! especially in development).

I don't like the g_ prefix for the groups table. What happens when you run out of letters? What happens if you have another g table? It seems odd. I would just name the columns naturally, and then when you join on it, alias the columns when necessary.

(I agree with Michael though: your authentication and access code should be separate. Authenticate first and then worry about permissions.)

I don't know how I feel about triming a password. That could be confusing for someone who legitimately wants a space on the end of a password (and I'm a huge fan of not restricting what characters are allowed in passwords). Then again, it's a rather questionable choice to end a password with white space anyway.

I like to always use named parameters in prepared statements. It's easier to read, and it can save you from a "Wtf?" later if you rearrange or add clauses.

I don't see a session_start() anywhere? But I guess this is just a snippet of a bigger script?


Counting users by the type in their profile

I'm creating a django

You probably mean that you're creating a web application on top of Django.

Given this code:

items = []
for vote in choice.vote_set.all():
    if vote.user not in items:
        items.append(vote.user)

you should instead be able to do

items = set(v.user for v in choice.vote_set.all())

This achieves the same goal - creating a collection of unique entries. The only catch is that order will not be preserved. If that's important, you'll have to do something more clever.

This:

types = {}
for user in items:
    if user.userprofile.typeOfPerson not in types:
        types[user.userprofile.typeOfPerson] = Vote.objects.filter(Choice=choice).count()

apparently makes an effort to avoid overwriting entries in a dictionary, but I'm not clear on whether that's necessary. If order doesn't matter, and if items all have equal priorities, then you can make this much more simple:

n_votes = Vote.objects.filter(Choice=choice).count()
types = {u.userprofile.typeOfPerson: n_votes for u in items}

This also assumes that Vote.objects.filter(Choice=choice).count() doesn't vary at all over the course of the loop.

This:

percent = 0
for type, value in types.items():
    percent += value
if percent == 0:
    percent = 1

can be:

percent = max(1, sum(types.values()))

This:

values = {}
for type, value in types.items():
    if type not in values:
        values[type] = value / percent * 100

can probably just be

values = {t: v/percent * 100 for t, v in types.items()}

Again, it's not clear why all three of your loops are attempting to be careful in avoiding rewriting values, or what the priority system should be.


Input/output for a simple Brainfuck interpreter

a better/clearer way to implement the read_cell and write_cell methods?

What you have seems pretty good to me. Rust's IO methods rely on having a buffer to read into. In many cases, you might see a single byte read with something like

let mut buf = [0; 1];
reader.read(&mut buf).unwrap();

In your case, you already have a buffer, so you might as well read directly into it.

  Can I write the same test without having to nest scopes?

Nope. Let's comment out the nested braces and look at the error messages:

error: cannot borrow `output` as immutable because it is also
       borrowed as mutable

match ( & ( $ left ) , & ( $ right ) ) {
                         ^~~~~~~~~~~
note: in expansion of assert_eq!

We are attempting to immutably borrow something that's already borrowed. The compiler is kind enough to show us where the borrow occurs:

note: previous borrow of `output` occurs here; the mutable borrow
      prevents subsequent moves, borrows, or modification of
      `output` until the borrow ends

let mut machine = Machine::new(input, &mut output);
                                           ^~~~~~

And where it ends:

note: previous borrow ends here

fn test_write_cell() {
...
}
^

When there is an outstanding mutable borrow, Rust only that borrow to exist. This removes whole classes of bugs around "spooky action at a distance" as well as potential data races. The extra braces provide a lifetime that the borrow can live during; once the block is exited, the borrow is no longer needed.

The only solution I know of is to use what I like to call an exploder. If you are familiar with constructors and destructors, then an exploder is like a destructor that returns values. There's a common pattern in the standard library with methods called into_inner. Here's how it could look for your code:

impl<In: Read, Out: Write> Machine<In, Out> {
    pub fn into_inner(self) -> (In, Out) {
        (self.input, self.output)
    }
}

fn test_write_cell() {
    let input = "".as_bytes();
    let output = vec![];

    let mut machine = Machine::new(input, output);
    machine.memory[machine.pointer] = 1;
    machine.write_cell();

    let (_, output) = machine.into_inner();

    assert_eq!(vec![1], output);
}


Simple local cache that checks by date else get from db

One approach you could pick here is to design your data stores in Storage interfaces in an increasing fashion.

private List<Cab> getCabs(Key key) {
    List<Cab> cabsByKey = this.cache.stream().filter(c -> c.equals(key)).anyMatch();
    if (cabsByKey.isEmpty()) {
       cabsByKey = this.higherStorage.getByKey(key);
    }

    return cabsByKey;
}

The idea is to store its higher level cache instance for each data storage and to propagate request up whenever nothing has been found.