text:
module Tang
  class Coupon < ActiveRecord::Base
    has_paper_trail
    # acts_as_paranoid

    has_many :customers, class_name: Tang.customer_class.to_s
    has_many :subscriptions
    has_many :invoices

    validates :stripe_id, presence: true
    validates :stripe_id, uniqueness: true # , if: "deleted_at.nil?"
    validates :duration, inclusion: { in: %w(once repeating forever) }
    validates :amount_off, numericality: { only_integer: true, greater_than: 0 }, allow_nil: true
    validates :currency, presence: true, if: -> { amount_off.present? }
    validates :duration_in_months, presence: true, numericality: { only_integer: true, greater_than: 0 }, if: :repeating?
    validates :max_redemptions, numericality: { only_integer: true, greater_than: 0 }, allow_nil: true
    validates :percent_off, numericality: { only_integer: true, greater_than_or_equal_to: 1, less_than_or_equal_to: 100 },
                            presence: true, if: -> { amount_off.nil? }
    validates :redeem_by, future: true, if: -> { redeem_by.present? }

    before_create :create_stripe_coupon
    before_update :update_stripe_coupon
    before_destroy :delete_stripe_coupon # should be soft delete

    DURATIONS = ['once', 'repeating', 'forever']

    def coupon_valid?
      # check if expired
      if self.redeem_by.present?
        return false if Time.now > self.redeem_by
      end

      if self.max_redemptions.present?
        # check if any discounts created
      end

      return true
    end

    def formatted_duration
      if repeating?
        "for #{duration_in_months} months"
      else
        duration
      end
    end

    def active_redemptions
      customer_table = ActiveRecord::Base.connection.quote_table_name(Customer.table_name)
      Tang.customer_class.
           joins(:subscriptions).
           where("#{customer_table}.coupon_id = ? OR tang_subscriptions.coupon_id = ?", self.id, self.id).
           where.not(tang_subscriptions: { status: :canceled }).
           uniq
    end

    def repeating?
      duration == "repeating"
    end

    def discount(amount)
      subtotal = amount
      if self.percent_off.present?
        subtotal = amount.to_f * (self.percent_off.to_f / 100.0)
      elsif self.amount_off.present?
        subtotal = self.amount_off
      end
      return -subtotal.to_f
    end

    def self.from_stripe(stripe_coupon)
      coupon = Coupon.find_or_create_by(stripe_id: stripe_coupon.id) do |c|
        c.percent_off = stripe_coupon.percent_off
        c.currency = stripe_coupon.currency
        c.amount_off = stripe_coupon.amount_off
        c.duration = stripe_coupon.duration
        c.duration_in_months = stripe_coupon.duration_in_months
        c.max_redemptions = stripe_coupon.max_redemptions
        c.redeem_by = DateTime.strptime(stripe_coupon.redeem_by.to_s, '%s') if stripe_coupon.redeem_by.present?
      end

      return coupon
    end

    private

    def create_stripe_coupon
      CreateCoupon.call(self)
    end

    def update_stripe_coupon
      UpdateCoupon.call(self)
    end

    def delete_stripe_coupon
      DeleteCoupon.call(self)
    end
  end
end


text:
package es.lnsd.citikey.di.modules;

import dagger.Module;
import dagger.Provides;
import es.lnsd.citikey.di.scopes.ActivityScope;
import es.lnsd.citikey.di.scopes.FragmentScope;
import es.lnsd.citikey.discovery.view.DiscoveryView;
import es.lnsd.citikey.discovery.view.presenters.DiscoveryPresenter;
import es.lnsd.citikey.intro.view.LocationPermissionSlideView;
import es.lnsd.citikey.intro.view.presenters.LocationPermissionSlidePresenter;
import es.lnsd.citikey.main.view.MainView;
import es.lnsd.citikey.main.view.presenters.MainPresenter;
import es.lnsd.mvp.core.views.BaseView;

@Module
public class PresenterModule {

    private final BaseView view;

    public PresenterModule(BaseView view) {
        this.view = view;
    }

    @Provides
    @ActivityScope
    MainPresenter providesMainPresenter() {
        return new MainPresenter();
    }

    @Provides
    @ActivityScope
    MainView providesMainView() {
        return (MainView) view;
    }

    @Provides
    @ActivityScope
    DiscoveryPresenter providesDiscoveryPresenter() {
        return new DiscoveryPresenter();
    }

    @Provides
    @ActivityScope
    DiscoveryView providesDiscoveryView() {
        return (DiscoveryView) view;
    }

    @Provides
    @FragmentScope
    LocationPermissionSlidePresenter providesLocationPermissionSlidePresenter() {
        return new LocationPermissionSlidePresenter();
    }

    @Provides
    @FragmentScope
    LocationPermissionSlideView providesLocationPermissionSlideView() {
        return (LocationPermissionSlideView) view;
    }
}

redpajama_set_name: RedPajamaGithub


text:
@interface NSNotificationViewController ()

@end

@implementation NSNotificationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.title = @"NSNotification";

    [self setUI];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setUI
{
    UIButton *button = [[UIButton alloc] init];
    button.viewSuperView(self.view).viewFrame(CGRectMake(10.0, 10.0, (self.view.width - 10.0 * 2), 40.0)).viewBackgroundColor([UIColor colorRandom]);
    [button setTitle:@"发消息" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];

    UILabel *label = [UILabel new];
    label.viewSuperView(self.view).viewFrame(CGRectMake(10.0, button.bottom + 10.0, button.width, 80.0));
    label.labelNumberOfLines(0).viewColorAlpha([UIColor colorRandom], 0.3).viewTag(1000);

    // 接收消息
    NSString *name = @"personInfo";
    SEL action = @selector(notificationAction:);
    // 方法1
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:action name:name object:nil];

    // 方法2
//    NSNotificationCenterReceive(name, self, action);

    // 方法3
    kSelfWeak;
    [NSNotificationCenter.defaultCenter receiveNotification:name handle:^(NSNotification *notification) {
        [weakSelf notificationAction:notification];
    }];
}

- (void)buttonClick:(UIButton *)button
{
    // 发消息
    NSString *name = @"personInfo";
    NSDictionary *dict = @{@"name":@"devZhang", @"age":@"30", @"job":@"iOSDev"};

    // 方法1
    [[NSNotificationCenter defaultCenter] postNotificationName:name object:nil userInfo:dict];

    // 方法2
//    NSNotificationCenterPost(name, dict);

    // 方法3
//    [[NSNotificationCenter defaultCenter] postNotificationWithName:name userInfo:dict];
}

- (void)notificationAction:(NSNotification *)notification
{
    NSString *name = notification.name;
    NSDictionary *dict = notification.userInfo;
    NSLog(@"name = %@ \n dict = %@", name, dict);

    NSMutableString *text = [NSMutableString string];
    for (NSString *key in dict.allKeys)
    {
        NSString *string = [NSString stringWithFormat:@"%@ - %@;", key, [dict objectForKey:key]];
        text.addString(string);
    }
    UILabel *label = (UILabel *)[self.view viewWithTag:1000];
    label.text = text;
}

@end


text:
MEAN.JS is a full-stack JavaScript open-source solution, which provides a solid starting point for [MongoDB](http://www.mongodb.org/), [Node.js](http://www.nodejs.org/), [Express](http://expressjs.com/), and [AngularJS](http://angularjs.org/) based applications. The idea is to solve the common issues with connecting those frameworks, build a robust framework to support daily development needs, and help developers use better practices while working with popular JavaScript components.

## Steps to follow:
npm install -g bower

npm install -g grunt-cli

npm install -g yo

npm install -g generator-meanjs


text:
This is an example minimal theme for MkDocs. You can see it running with a
build for this documentation. However, note that it is intended as a code
example rather than an example of a usable theme.

http://mkdocs.github.io/mkdocs-basic-theme/

[![PyPI Downloads][pypi-dl-image]][pypi-dl-link]
[![PyPI Version][pypi-v-image]][pypi-v-link]

[pypi-dl-image]: https://img.shields.io/pypi/dm/mkdocs-basic-theme.png
[pypi-dl-link]: https://pypi.python.org/pypi/mkdocs-basic-theme
[pypi-v-image]: https://img.shields.io/pypi/v/mkdocs-basic-theme.png
[pypi-v-link]: https://pypi.python.org/pypi/mkdocs-basic-theme


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Authentication extends CO_Controller {

    public function __construct()
    {
        parent::__construct();

        // Load form helper library
        $this->load->helper('form');

        // Load form validation library
        $this->load->library('form_validation');
    }

    public function index($current_page = NULL)
    {
        $user = $this->authentication_m->read_information();

        if($user){
            redirect('/finance');
        }

        $data['message_array'] = $this->session->flashdata('message_array');

        $action = $this->input->post('action');

        if($action === 'singin'){
            if($this->form_validation->run('login') !== FALSE){

                $account_exists = $this->authentication_m->check_for_account();
                if($account_exists){
                    // Add user data in session
                    $this->session->set_userdata('logged_in', array( 'email' => $this->input->post('email') ));
                    $user = $this->authentication_m->read_information();

                    if($user){
                        //enter your site
                        redirect('/finance');
                    }
                }else{

                    $data['message_array'] = array('type' => 'danger', 'message' => '
Error:
Wrong email or password!');
                }
            }else{
                $data['message_array'] = array('type' => 'danger', 'message' => '
Error:
'.validation_errors().'');
            }
        }

        $this->render(array('pages/authentication/index'), $data);
    }

    public function forgot()
    {
        $action = $this->input->post('action');
        $this->load->helper('string');

        $data['message_array'] = array();

        if ($action == 'forgot') {

            $email = $this->input->post('email');

            if($this->form_validation->run() === TRUE){

                $mal_chk = $this->authentication_m->check_mail($email);
                if($mal_chk){
                    $hash = random_string('alnum', 32);

                    $data['message_array'] = $this->authentication_m->insert_hash($hash, $mal_chk->id, $email);
                }
            }else{
                $data['message_array'] = array('type' => 'danger', 'message' => '
Error:
' . validation_errors() . '');
            }
        }

        $this->render(array('pages/authentication/forgot'), $data);
    }

    public function new_password($hash)
    {

        if(!$this->authentication_m->check_hash($hash)){
            redirect('forgot');
        }

        $action = $this->input->post('action');

        $data['message_array'] = array();

        if ($action === 'new_password'){

            if($this->form_validation->run('new_password') === TRUE){

                $return_message = $this->authentication_m->new_password($hash);

                $this->session->set_flashdata('message_array', $return_message);

                redirect('/');
            }else{
                $data['message_array'] = array('type' => 'danger', 'message' => '
Error:
' . validation_errors() . '');
            }
        }

        $this->render(array('pages/authentication/new_password'), $data);
    }

    public function logout()
    {
        // Removing session data
        $this->session->unset_userdata('logged_in', array( 'email' => '' ));

        // redirect user to login
        redirect('/');
    }
}


text:
from django.conf.urls.defaults import patterns, url

from mezzanine.conf import settings

SIGNUP_URL = getattr(settings, "SIGNUP_URL", "/account/signup/")
SIGNUP_VERIFY_URL = getattr(settings, "SIGNUP_VERIFY_URL", "/account/verify/")
LOGIN_URL = settings.LOGIN_URL
LOGOUT_URL = settings.LOGOUT_URL
PROFILE_URL = getattr(settings, "PROFILE_URL", "/users/")
PROFILE_UPDATE_URL = getattr(settings, "PROFILE_UPDATE_URL",
                             "/account/update/")
PASSWORD_RESET_URL = getattr(settings, "PASSWORD_RESET_URL",
                             "/account/password/reset/")
PASSWORD_RESET_VERIFY_URL = getattr(settings, "PASSWORD_RESET_VERIFY_URL",
                                    "/account/password/verify/")

verify_pattern = "/(?P<uidb36>[-\w]+)/(?P<token>[-\w]+)/$"

urlpatterns = patterns("mezzanine.accounts.views",
    url("^%s/$" % LOGIN_URL.strip("/"), "login", name="login"),
    url("^%s/$" % LOGOUT_URL.strip("/"), "logout", name="logout"),
    url("^%s/$" % SIGNUP_URL.strip("/"), "signup", name="signup"),
    url("^%s%s" % (SIGNUP_VERIFY_URL.strip("/"), verify_pattern),
        "signup_verify", name="signup_verify"),
    url("^%s/$" % PROFILE_UPDATE_URL.strip("/"), "profile_update",
        name="profile_update"),
    url("^%s/$" % PASSWORD_RESET_URL.strip("/"), "password_reset",
        name="mezzanine_password_reset"),
    url("^%s%s" % (PASSWORD_RESET_VERIFY_URL.strip("/"), verify_pattern),
        "password_reset_verify", name="password_reset_verify"),
)

if settings.ACCOUNTS_PROFILE_VIEWS_ENABLED:
    urlpatterns += patterns("mezzanine.accounts.views",
        url("^%s/(?P<username>.*)/$" % PROFILE_URL.strip("/"), "profile",
            name="profile"),
    )


text:
OpenStack-Ansible Galera Client
###############################
:tags: openstack, galera, client, cloud, ansible
:category: \*nix

This Ansible role installs the MariaDB operating system and Python packages
used to interact with and manage a Galera cluster.

Required Variables
------------------

To use this role, define the following variables:

.. code-block:: yaml

    galera_root_password: secrete

Dependencies
------------

This role depends on the ``config_template`` Ansible module provided
by `OpenStack-Ansible Plugins`_

.. _OpenStack-Ansible Plugins: https://github.com/openstack/openstack-ansible-plugins

Example Playbook
----------------

.. code-block:: yaml

    - name: Install Galera Client
      hosts: all
      user: root
      roles:
        - role: "openstack-ansible-galera_client"
          galera_address: "10.0.0.1"
          galera_root_password: secrete
          galera_root_user: root
          galera_client_drop_config_file: true


text:
package com.mirhoseini.autolabs;

import android.app.Application;
import android.content.Context;
import android.support.v7.app.AppCompatDelegate;

import com.mirhoseini.autolabs.weather.WeatherModule;
import com.mirhoseini.autolabs.weather.WeatherSubComponent;

/**
 * Created by Mohsen on 03/01/2017.
 */

public abstract class AutolabsApplication extends Application {
    private static ApplicationComponent component;
    private WeatherSubComponent weatherSubComponent;

    public static AutolabsApplication get(Context context) {
        return (AutolabsApplication) context.getApplicationContext();
    }

    public static ApplicationComponent getComponent() {
        return component;
    }

    protected AndroidModule getAndroidModule() {
        return new AndroidModule(this);
    }

    public WeatherSubComponent getWeatherSubComponent() {
        if (null == weatherSubComponent)
            createWeatherSubComponent();

        return weatherSubComponent;
    }

    public WeatherSubComponent createWeatherSubComponent() {
        weatherSubComponent = component.plus(new WeatherModule());
        return weatherSubComponent;
    }

    public void releaseWeatherSubComponent() {
        weatherSubComponent = null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO);

        initApplication();

        component = createComponent();
    }

    public ApplicationComponent createComponent() {
        return DaggerApplicationComponent.builder()
                .androidModule(getAndroidModule())
                .build();
    }

    abstract void initApplication();
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE415_Double_Free__new_delete_array_wchar_t_33.cpp
Label Definition File: CWE415_Double_Free__new_delete_array.label.xml
Template File: sources-sinks-33.tmpl.cpp
*/
/*
 * @description
 * CWE: 415 Double Free
 * BadSource:  Allocate data using new and Deallocae data using delete
 * GoodSource: Allocate data using new
 * Sinks:
 *    GoodSink: do nothing
 *    BadSink : Deallocate data using delete
 * Flow Variant: 33 Data flow: use of a C++ reference to data within the same function
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

namespace CWE415_Double_Free__new_delete_array_wchar_t_33
{

#ifndef OMITBAD

void bad()
{
    wchar_t * data;
    wchar_t * &dataRef = data;
    /* Initialize data */
    data = NULL;
    data = new wchar_t[100];
    /* POTENTIAL FLAW: delete the array data in the source - the bad sink deletes the array data as well */
    delete [] data;
    {
        wchar_t * data = dataRef;
        /* POTENTIAL FLAW: Possibly deleting memory twice */
        delete [] data;
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2B()
{
    wchar_t * data;
    wchar_t * &dataRef = data;
    /* Initialize data */
    data = NULL;
    data = new wchar_t[100];
    /* FIX: Do NOT delete the array data in the source - the bad sink deletes the array data */
    {
        wchar_t * data = dataRef;
        /* POTENTIAL FLAW: Possibly deleting memory twice */
        delete [] data;
    }
}

/* goodB2G() uses the BadSource with the GoodSink */
static void goodB2G()
{
    wchar_t * data;
    wchar_t * &dataRef = data;
    /* Initialize data */
    data = NULL;
    data = new wchar_t[100];
    /* POTENTIAL FLAW: delete the array data in the source - the bad sink deletes the array data as well */
    delete [] data;
    {
        wchar_t * data = dataRef;
        /* do nothing */
        /* FIX: Don't attempt to delete the memory */
        ; /* empty statement needed for some flow variants */
    }
}

void good()
{
    goodG2B();
    goodB2G();
}

#endif /* OMITGOOD */

} /* close namespace */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN

using namespace CWE415_Double_Free__new_delete_array_wchar_t_33; /* so that we can use good and bad easily */

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
require 'spec_helper'

describe Sigiss::Taker do

  before(:each) do
    @params = taker_params
    @taker = Sigiss::Taker.new(@params)
  end

  it '#to_hash' do
    expect(@taker.to_hash).to eq(taker_params)
  end

  context 'validations' do

    it 'has attributes' do
      expect(@taker).to have_attributes(@params)
    end

    it 'is not valid if missing tomador_tipo' do
      @taker.tomador_tipo = nil
      expect(@taker.valid?).to be_falsy
    end

    it 'is not valid if missing tomador_cnpj' do
      @taker.tomador_cnpj = nil
      expect(@taker.valid?).to be_falsy
    end

    it 'is not valid if missing tomador_razao' do
      @taker.tomador_razao = nil
      expect(@taker.valid?).to be_falsy
    end

    it 'is not valid if missing tomador_endereco' do
      @taker.tomador_endereco = nil
      expect(@taker.valid?).to be_falsy
    end

    it 'is not valid if missing tomador_numero' do
      @taker.tomador_numero = nil
      expect(@taker.valid?).to be_falsy
    end

    it 'is not valid if missing tomador_bairro' do
      @taker.tomador_bairro = nil
      expect(@taker.valid?).to be_falsy
    end

    it 'is not valid if missing tomador_CEP' do
      @taker.tomador_CEP = nil
      expect(@taker.valid?).to be_falsy
    end

    it 'is not valid if missing tomador_cod_cidade' do
      @taker.tomador_cod_cidade = nil
      expect(@taker.valid?).to be_falsy
    end

  end

  context 'recover code city' do

    it 'passing code city' do
      expect(Sigiss::Taker.new(tomador_cod_cidade: '3127107').tomador_cod_cidade).to eq('3127107')
    end

    it 'passing name city' do
      expect(Sigiss::Taker.new(cidade: 'Assis').tomador_cod_cidade).to eq('3504008')
    end

    it 'passing name and code city, code preferences' do
      expect(Sigiss::Taker.new(cidade: 'Marília', tomador_cod_cidade: '3127107').tomador_cod_cidade).to eq('3127107')
    end

  end

end


text:
id: 4845
title: 'A Guide to Questionable Russian Careers, or "Seryozha, That Guy with the Ambulance."'
date: 2011-04-26T13:13:54+00:00
author: Vicki
layout: post
guid: http://blog.vickiboykis.com/wlb/?p=4845
permalink: /2011/04/a-guide-to-questionable-russian-careers-or-seryozha-that-guy-with-the-ambulance/
categories:
  - Uncategorized
tags:
  - ambulances
  - Career
  - economics
  - immigrants
  - philly
  - Russian
  - Russian Jews
---

    This car is not big enough. Looks like it's ambulances for me from here on out until I become indicted for Medicare fraud!

  A couple weeks ago, we were having dinner with Real People, when the conversation turned to Russian career choices.  The hip thing to do in Philly if you’re Russian now is to own a privately-operated ambulance. Whether it’s because it’s convenient to leech money from insurance companies and commit fraud or  whether your Hummer is JUST NOT obnoxious enough for when you go out to the clubs, ambulances are THE in business to be in right now.

  Before ambulances, every Russian was in real estate, either as an agent or a mortgage broker,  because you could make a killing bilking people out of hundreds of thousands of dollars in a field where almost everyone has no clue what’s going on.

Before that, every Russian was selling cell phones and SIM cards. I have no idea how this started or what ended it, but I’m guessing it had something to do [with this](http://www.eurasianet.org/node/63243).

(P.S. Did you know when you search for Russian things, you get nice Russian search results:)

Before that, when the big wave of immigrants came in 1991,  the it thing was programming, which is the only real job on this list.  However, because it was so lucrative and so easy to get into back in the day, there are now a bunch of mediocre Russian programmers who were originally Russian language or horticulture majors back in the homeland that screw up the reputation of Russians who actually do know a do loop from an if loop.  In my immediate family alone, there are SEVEN programmers. And I currently work in IT, although not as a programmer, but that doesn’t count because I still read _The Economist_ and yearn for [that job](http://www.economist.com/classifieds/view_classified.cfm?sitd=10673&key=&sitd_type=R) in  Suisse.  The given amount of Russian programmers any Russian knows is inversely proportional to  **<big>∞.</big>**

What do all of the industries above have in common that are attractive to shady Russians?

  * Low barrier to entry (i.e. usually no college degree needed)
  * Slightly sketchy (come on, selling cell phones? really?)
  * Will be impressive to people who have no clue how it works
  * Has to seem cool enough for other Russians to jump on the bandwagon
  * Has to be vaguely written about in Russian newspapers to pique their interest
  * Has to be waning in interest among the general public

With that in mind, put your predictions for industries Russians in the United States will want to enter over the next 10 years in the comments.

I’ll start you off.

[

    This car is not big enough. Looks like it's ambulances for me from here on out until I become indicted for Medicare fraud!

  A couple weeks ago, we were having dinner with Real People, when the conversation turned to Russian career choices.  The hip thing to do in Philly if you’re Russian now is to own a privately-operated ambulance. Whether it’s because it’s convenient to leech money from insurance companies and commit fraud or  whether your Hummer is JUST NOT obnoxious enough for when you go out to the clubs, ambulances are THE in business to be in right now.

  Before ambulances, every Russian was in real estate, either as an agent or a mortgage broker,  because you could make a killing bilking people out of hundreds of thousands of dollars in a field where almost everyone has no clue what’s going on.

Before that, every Russian was selling cell phones and SIM cards. I have no idea how this started or what ended it, but I’m guessing it had something to do [with this](http://www.eurasianet.org/node/63243).

(P.S. Did you know when you search for Russian things, you get nice Russian search results:)

Before that, when the big wave of immigrants came in 1991,  the it thing was programming, which is the only real job on this list.  However, because it was so lucrative and so easy to get into back in the day, there are now a bunch of mediocre Russian programmers who were originally Russian language or horticulture majors back in the homeland that screw up the reputation of Russians who actually do know a do loop from an if loop.  In my immediate family alone, there are SEVEN programmers. And I currently work in IT, although not as a programmer, but that doesn’t count because I still read _The Economist_ and yearn for [that job](http://www.economist.com/classifieds/view_classified.cfm?sitd=10673&key=&sitd_type=R) in  Suisse.  The given amount of Russian programmers any Russian knows is inversely proportional to  **<big>∞.</big>**

What do all of the industries above have in common that are attractive to shady Russians?

  * Low barrier to entry (i.e. usually no college degree needed)
  * Slightly sketchy (come on, selling cell phones? really?)
  * Will be impressive to people who have no clue how it works
  * Has to seem cool enough for other Russians to jump on the bandwagon
  * Has to be vaguely written about in Russian newspapers to pique their interest
  * Has to be waning in interest among the general public

With that in mind, put your predictions for industries Russians in the United States will want to enter over the next 10 years in the comments.

I’ll start you off.

](http://www.environmentalgraffiti.com/news-russia%E2%80%99s-appetite-organic-and-bio-products) (straight from Chernobyl) spaceflight, social media, frozen yogurt, medical billing ([on the other hand, too late](http://books.google.com/books?id=RmGi5zDus7gC&pg=PA11&lpg=PA11&dq=medical+billing+russian&source=bl&ots=uPi6A-_Oq7&sig=SVzMTe1JerRFrJ0P_RYtclhBkH0&hl=en&ei=evy2TbG6Hor40gGV1eDlDw&sa=X&oi=book_result&ct=result&resnum=8&ved=0CFkQ6AEwBw#v=onepage&q=medical%20billing%20russian&f=false)), pet insurance, and iPhone applications.


text:
from parakeet import jit, testing_helpers
import numpy as np

def init_layer(input_size, n_elts):
  return np.random.randn(n_elts, input_size)

def create_mlp(n_inputs, n_hidden, n_outputs):
  W1 = init_layer(n_inputs, n_hidden)
  W2 = init_layer(n_hidden, n_outputs)
  return (W1, W2)

def dot(x,y):
  return sum(x*y)

def fprop_elt(x,w):
  return np.tanh(dot(x,w))

def fprop_layer(layer, x):
  return [fprop_elt(x,w) for w in layer]

fprop_layer_parakeet = jit(fprop_layer)

def fprop(network, x):
  for layer in network:
    x = fprop_layer_parakeet(layer, x)
  return x

def fprop_python(network, x):
  for layer in network:
    x = np.array(fprop_layer(layer,x))
  return x

n = 1000
d = 500
Xpos = np.random.randn(n,d)+1.0
Xneg = np.random.randn(n,d)-1.0
X = np.vstack([Xpos, Xneg])
Y = np.vstack([np.ones(n), np.ones(n)*-1])

network = create_mlp(d,50,1)

def test_fprop():
  parakeet_result = fprop(network, X[0])
  print "Parakeet result", parakeet_result
  python_result = fprop_python(network, X[0])
  print "Python result", python_result
  assert testing_helpers.eq(parakeet_result, python_result)

if __name__ == '__main__':
  testing_helpers.run_local_tests()


text:
layout: post
title: Simplify Your Code With Query Objects
---

Did you ever have problems with repository classes that just kept on growing over the years, with no end in sight?

This is a problem that I have encountered in multiple projects and companies. Usually the repository starts out small, but then more and more methods are added over time.

Let's assume that we are working on an online shop. In the beginning, our `OrderRepository` is very small and we just have a few methods.

```php?start_inline=1
interface OrderRepository
{
    public function find(OrderId $orderId): ?Order;

    public function findAll(Filters $filters): Orders;

    public function save(Order $order): void;
}
```

You keep working on the application and the business is doing well. A lot of orders are coming in and there are now too many to display on a single page. You add a few method to add pagination support.

```php?start_inline=1
interface OrderRepository
{
    public function find(OrderId $orderId): ?Order;

    public function findAll(Filters $filters, PaginationParameters $paginationParameters): Orders;

    public function countTotal(): int;

    public function countFiltered(Filters $filters): int;

    public function save(Order $order): void;
}
```

Two weeks later, the accounting department approaches you because they need a new page that shows all the orders with invoices that haven't been paid yet.

You add another method to the repository and create the page.

```php?start_inline=1
public function findWhereInvoiceWasNotPaid(): Orders;
```

A month later, the marketing department needs a new feature...

 You can see where I am going with this, the repository just keeps on growing. After a few years, it becomes hard to stay on top of things and your repository grows larger and larger.

Stuffing everything into a single repository leads to problems, but what are the alternatives?

You could split it up into multiple repositories, but then it will be hard to distinguish between them. How do you name all the repositories? How do you decide to which one a method belongs?

This is where query objects come into play. You take one of the methods and turn it into it's own object.

```php?start_inline=1
interface OrdersWhereInvoiceWasNotPaidQuery
{
    public function execute(): Orders;
}
```

Before, your classes always had to depend on the large repository class. Now they can depend on the few queries that they actually need (often it's just one).

Software development is all about making tradeoffs. Query objects make your code simpler, but they also have a couple of drawbacks.

The obvious one is that you have to create more classes. This is not necessarily a bad thing. It's the same as when you follow the single responsibility principle. You end up with many small and cohesive classes.

It's also harder to deduplicate code between query objects. This is a little more annoying. With a single repository, you can just extract code into a private method. With query objects, you have to extract the duplicate code into a separate class.

Don't replace your repositories with query objects. Use them both and put the query where it makes most sense. If you only need to read data, put it into a query object. If you need to read and write, the repository is probably the right place. I use both repositories and query objects in the tutorial part of my book [Professional PHP](/professional-php/).

Query objects work really well in applications that follows the command query responsibility segregation pattern (CQRS). You use them on the query side and repositories on the command side. I really like this approach, because it completely decouples my queries from the business logic.


text:
#ifndef GrResourceCache2_DEFINED
#define GrResourceCache2_DEFINED

#include "GrTypes.h"
#include "SkTInternalLList.h"

class GrGpuResource;

/**
 *  Eventual replacement for GrResourceCache. Currently it simply holds a list
 *  of all GrGpuResource objects for a GrContext. It is used to invalidate all
 *  the resources when necessary.
 */
class GrResourceCache2 {
public:
    GrResourceCache2() : fCount(0) {};
    ~GrResourceCache2();

    void insertResource(GrGpuResource* resource);

    void removeResource(GrGpuResource* resource);

    void abandonAll();

    void releaseAll();

private:
    int                             fCount;
    SkTInternalLList<GrGpuResource> fResources;
};

#endif


text:
package net.spy.memcached.spring;

import java.util.Collection;

import net.spy.memcached.AddrUtil;
import net.spy.memcached.ConnectionFactoryBuilder;
import net.spy.memcached.ConnectionFactoryBuilder.Locator;
import net.spy.memcached.ConnectionFactoryBuilder.Protocol;
import net.spy.memcached.ConnectionObserver;
import net.spy.memcached.FailureMode;
import net.spy.memcached.HashAlgorithm;
import net.spy.memcached.MemcachedClient;
import net.spy.memcached.OperationFactory;
import net.spy.memcached.auth.AuthDescriptor;
import net.spy.memcached.ops.OperationQueueFactory;
import net.spy.memcached.transcoders.Transcoder;

import org.springframework.beans.factory.FactoryBean;

/**
 * A Spring {@link FactoryBean} creating {@link MemcachedClient} instances.
 *

 * Usage example:
 *

 * {@code
 * <bean id="memcachedClient" class="net.spy.memcached.utils.MemcachedClientFactoryBean">
 *   <property name="servers" value="${pajamas.remoteHosts}"/>
 *   <property name="protocol" value="${pajamas.client.protocol}"/>
 *   <property name="transcoder">
 *     <bean class="net.rubyeye.xmemcached.transcoders.SerializingTranscoder"/>
 *   </property>
 *   <property name="hashAlg" value="${pajamas.client.hashAlg}"/>
 *   <property name="locatorType" value="${pajamas.client.locatorType}"/>
 * </bean>
 * }
 *

 *

 * @author Eran Harel
 */
public class MemcachedClientFactoryBean implements FactoryBean {
  private final ConnectionFactoryBuilder connectionFactoryBuilder = new ConnectionFactoryBuilder();
  private String servers;

  @Override
  public Object getObject() throws Exception {
    return new MemcachedClient(connectionFactoryBuilder.build(), AddrUtil.getAddresses(servers));
  }

  @Override
  public Class getObjectType() {
    return MemcachedClient.class;
  }

  @Override
  public boolean isSingleton() {
    return true;
  }

  public void setServers(final String servers) {
    this.servers = servers;
  }

  public void setAuthDescriptor(final AuthDescriptor to) {
    connectionFactoryBuilder.setAuthDescriptor(to);
  }

  public void setDaemon(final boolean d) {
    connectionFactoryBuilder.setDaemon(d);
  }

  public void setFailureMode(final FailureMode fm) {
    connectionFactoryBuilder.setFailureMode(fm);
  }

  public void setHashAlg(final HashAlgorithm to) {
    connectionFactoryBuilder.setHashAlg(to);
  }

  public void setInitialObservers(final Collection<ConnectionObserver> obs) {
    connectionFactoryBuilder.setInitialObservers(obs);
  }

  public void setLocatorType(final Locator l) {
    connectionFactoryBuilder.setLocatorType(l);
  }

  public void setMaxReconnectDelay(final long to) {
    connectionFactoryBuilder.setMaxReconnectDelay(to);
  }

  public void setOpFact(final OperationFactory f) {
    connectionFactoryBuilder.setOpFact(f);
  }

  public void setOpQueueFactory(final OperationQueueFactory q) {
    connectionFactoryBuilder.setOpQueueFactory(q);
  }

  public void setOpQueueMaxBlockTime(final long t) {
    connectionFactoryBuilder.setOpQueueMaxBlockTime(t);
  }

  public void setOpTimeout(final long t) {
    connectionFactoryBuilder.setOpTimeout(t);
  }

  public void setProtocol(final Protocol prot) {
    connectionFactoryBuilder.setProtocol(prot);
  }

  public void setReadBufferSize(final int to) {
    connectionFactoryBuilder.setReadBufferSize(to);
  }

  public void setReadOpQueueFactory(final OperationQueueFactory q) {
    connectionFactoryBuilder.setReadOpQueueFactory(q);
  }

  public void setShouldOptimize(final boolean o) {
    connectionFactoryBuilder.setShouldOptimize(o);
  }

  public void setTimeoutExceptionThreshold(final int to) {
    connectionFactoryBuilder.setTimeoutExceptionThreshold(to);
  }

  public void setTranscoder(final Transcoder<Object> t) {
    connectionFactoryBuilder.setTranscoder(t);
  }

  public void setUseNagleAlgorithm(final boolean to) {
    connectionFactoryBuilder.setUseNagleAlgorithm(to);
  }

  public void setWriteOpQueueFactory(final OperationQueueFactory q) {
    connectionFactoryBuilder.setWriteOpQueueFactory(q);
  }

}


text:
'use strict';

module.exports = {
  template: require('./chapter.html'),
  controller: ['$log', '$window', '$sce', ChapterController],
  controllerAs: 'chapterCtrl',
  bindings: {
    chapter: '<',
    manuscript: '<'
  }
};

function ChapterController($log, $window, $sce) {
  $log.debug('ChapterController');

  this.hideComments = true;

  this.fbcModal = {
    closeComments: true
  };

  this.trustAsHtml = function(body) {
    return $sce.trustAsHtml(body);
  };

  this.scrollUp = function() {
    $window.scrollTo(100, 0);
  };
}