text:
namespace ginkgo
{
namespace feedbackLoop
{
namespace production
{

////////////////////////////////////////////////////////////////////////////////////////////////////
//
// FluentClosureUsage
//
////////////////////////////////////////////////////////////////////////////////////////////////////

enum class FluentClosureUsage
{
	Unknown,
	NoFluentClosure,
	UseFluentClosure
};

////////////////////////////////////////////////////////////////////////////////////////////////////

std::ostream &operator<<(std::ostream &ostream, const FluentClosureUsage &fluentClosureUsage);
std::istream &operator>>(std::istream &istream, FluentClosureUsage &fluentClosureUsage);

////////////////////////////////////////////////////////////////////////////////////////////////////

}
}
}

#endif


text: export { default } from 'ember-legacy-controllers/object';

redpajama_set_name: RedPajamaGithub


text:
//
//  HysteriaPlayer.h
//
//  Version 1.0
//
//  Created by Saiday on 01/14/2013.
//  Copyright 2013 StreetVoice
//
// This code is distributed under the terms and conditions of the MIT license.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#import <AvailabilityMacros.h>
#import <AVFoundation/AVFoundation.h>

typedef NS_ENUM(NSUInteger, HysteriaPlayerReadyToPlay) {
    HysteriaPlayerReadyToPlayPlayer = 3000,
    HysteriaPlayerReadyToPlayCurrentItem = 3001,
};

typedef NS_ENUM(NSUInteger, HysteriaPlayerFailed) {
    HysteriaPlayerFailedPlayer = 4000,
    HysteriaPlayerFailedCurrentItem = 4001,
};

// Delegate
@protocol HysteriaPlayerDelegate <NSObject>

@optional
- (void)hysteriaPlayerWillChangedAtIndex:(NSUInteger)index;
- (void)hysteriaPlayerCurrentItemChanged:(AVPlayerItem *)item;
- (void)hysteriaPlayerRateChanged:(BOOL)isPlaying;
- (void)hysteriaPlayerDidReachEnd;
- (void)hysteriaPlayerCurrentItemPreloaded:(CMTime)time;
- (void)hysteriaPlayerDidFailed:(HysteriaPlayerFailed)identifier error:(NSError *)error;
- (void)hysteriaPlayerReadyToPlay:(HysteriaPlayerReadyToPlay)identifier;

@end

@protocol HysteriaPlayerDataSource <NSObject>

@optional
- (NSUInteger)hysteriaPlayerNumberOfItems;
/*!
 Recommend you use this method to handle your source getter, setupSourceAsyncGetter:ItemsCount: is for advanced usage.
 hysteriaPlayerURLForItemAtIndex:(NSUInteger)index and hysteriaPlayerAsyncSetUrlForItemAtIndex:(NSUInteger)index provides for the use of alternatives.
 @method HysteriaPlayerURLForItemAtIndex:(NSUInteger)index
 */
- (NSURL *)hysteriaPlayerURLForItemAtIndex:(NSUInteger)index preBuffer:(BOOL)preBuffer;
/*!
 If you are using asynchronously handle your items use this method to tell HysteriaPlayer which URL you would use for index, will excute until you call setupPlayerItemWithUrl:index:
 hysteriaPlayerURLForItemAtIndex:(NSUInteger)index and hysteriaPlayerAsyncSetUrlForItemAtIndex:(NSUInteger)index provides for the use of alternatives.
 @method HysteriaPlayerAsyncSetUrlForItemAtIndex:(NSUInteger)index
 */
- (void)hysteriaPlayerAsyncSetUrlForItemAtIndex:(NSUInteger)index preBuffer:(BOOL)preBuffer;

@end

typedef void (^ Failed)(HysteriaPlayerFailed identifier, NSError *error) DEPRECATED_MSG_ATTRIBUTE("deprecated since 2.5 version");
typedef void (^ ReadyToPlay)(HysteriaPlayerReadyToPlay identifier) DEPRECATED_MSG_ATTRIBUTE("deprecated since 2.5 version");
typedef void (^ SourceAsyncGetter)(NSUInteger index) DEPRECATED_MSG_ATTRIBUTE("deprecated since 2.5 version");
typedef NSURL * (^ SourceSyncGetter)(NSUInteger index) DEPRECATED_MSG_ATTRIBUTE("deprecated since 2.5 version");

typedef NS_ENUM(NSUInteger, HysteriaPlayerStatus) {
    HysteriaPlayerStatusPlaying = 0,
    HysteriaPlayerStatusForcePause,
    HysteriaPlayerStatusBuffering,
    HysteriaPlayerStatusUnknown,
};

typedef NS_ENUM(NSUInteger, HysteriaPlayerRepeatMode) {
    HysteriaPlayerRepeatModeOn = 0,
    HysteriaPlayerRepeatModeOnce,
    HysteriaPlayerRepeatModeOff,
};

typedef NS_ENUM(NSUInteger, HysteriaPlayerShuffleMode) {
    HysteriaPlayerShuffleModeOn = 0,
    HysteriaPlayerShuffleModeOff,
};

@interface HysteriaPlayer : NSObject <AVAudioPlayerDelegate>

@property (nonatomic, weak) id<HysteriaPlayerDelegate> delegate;
@property (nonatomic, weak) id<HysteriaPlayerDataSource> datasource;
@property (nonatomic) NSUInteger itemsCount;
@property (nonatomic) BOOL disableLogs;
@property (nonatomic, strong, readonly) NSArray *playerItems;
@property (nonatomic, readonly) BOOL isInEmptySound;
@property (nonatomic) BOOL popAlertWhenError;

+ (HysteriaPlayer *)sharedInstance;

- (void)registerHandlerReadyToPlay:(ReadyToPlay)readyToPlay DEPRECATED_MSG_ATTRIBUTE("use HysteriaPlayerDelegate instead");
- (void)registerHandlerFailed:(Failed)failed DEPRECATED_MSG_ATTRIBUTE("use HysteriaPlayerDelegate instead");

- (void)setupSourceGetter:(SourceSyncGetter)itemBlock ItemsCount:(NSUInteger) count DEPRECATED_MSG_ATTRIBUTE("use HysteriaPlayerDataSource instead.");
- (void)asyncSetupSourceGetter:(SourceAsyncGetter)asyncBlock ItemsCount:(NSUInteger)count DEPRECATED_MSG_ATTRIBUTE("use HysteriaPlayerDataSource instead.");
- (void)setItemsCount:(NSUInteger)count DEPRECATED_MSG_ATTRIBUTE("use HysteriaPlayerDataSource instead.");

/*!
 This method is necessary if you setting up AsyncGetter.
 After you your AVPlayerItem initialized should call this method on your asyncBlock.
 Should not call this method directly if you using setupSourceGetter:ItemsCount.
 @method setupPlayerItemWithUrl:index:
 */
- (void)setupPlayerItemWithUrl:(NSURL *)url index:(NSUInteger)index;
- (void)fetchAndPlayPlayerItem: (NSUInteger )startAt;
- (void)removeAllItems;
- (void)removeQueuesAtPlayer;
/*!
 Be sure you update hysteriaPlayerNumberOfItems or itemsCount when you remove items
 */
- (void)removeItemAtIndex:(NSUInteger)index;
- (void)moveItemFromIndex:(NSUInteger)from toIndex:(NSUInteger)to;
- (void)play;
- (void)pause;
- (void)pausePlayerForcibly:(BOOL)forcibly;
- (void)playPrevious;
- (void)playNext;
- (void)seekToTime:(double) CMTime;
- (void)seekToTime:(double) CMTime withCompletionBlock:(void (^)(BOOL finished))completionBlock;

- (void)setPlayerRepeatMode:(HysteriaPlayerRepeatMode)mode;
- (HysteriaPlayerRepeatMode)getPlayerRepeatMode;
- (void)setPlayerShuffleMode:(HysteriaPlayerShuffleMode)mode;
- (HysteriaPlayerShuffleMode)getPlayerShuffleMode;

- (BOOL)isPlaying;
- (AVPlayerItem *)getCurrentItem;
- (HysteriaPlayerStatus)getHysteriaPlayerStatus;

- (void)addDelegate:(id<HysteriaPlayerDelegate>)delegate DEPRECATED_MSG_ATTRIBUTE("set delegate property instead");
- (void)removeDelegate:(id<HysteriaPlayerDelegate>)delegate DEPRECATED_MSG_ATTRIBUTE("Use delegate property instead");;

- (float)getPlayingItemCurrentTime;
- (float)getPlayingItemDurationTime;
- (id)addBoundaryTimeObserverForTimes:(NSArray *)times queue:(dispatch_queue_t)queue usingBlock:(void (^)(void))block;
- (id)addPeriodicTimeObserverForInterval:(CMTime)interval queue:(dispatch_queue_t)queue usingBlock:(void (^)(CMTime time))block;
- (void)removeTimeObserver:(id)observer;

/*
 * Disable memory cache, player will run SourceItemGetter everytime even the media has been played.
 * Default is YES
 */
- (void)enableMemoryCached:(BOOL) isMemoryCached;
- (BOOL)isMemoryCached;

/*
 * Indicating Playeritem's play index
 */
- (NSNumber *)getHysteriaIndex:(AVPlayerItem *)item;

- (void)deprecatePlayer;

@end


text:
source ~/.bash_profile

workon scion
cd code/scioncc

# Buildout dependencies
python bootstrap.py -v 2.3.1
bin/buildout install extras

bin/generate_interfaces


text:
package jp.eure.device.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import jp.eure.device.R;
import jp.eure.device.model.Device;
import jp.eure.device.model.User;

/**
 * Created by katsuyagoto on 2014/10/26.
 */
public class UserAdapter extends ArrayAdapter<User> {

    public UserAdapter(Context context) {
        super(context, 0);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_user, null);
        }
        TextView nameView   = (TextView)convertView.findViewById(R.id.item_user_name);

        User user = getItem(position);
        nameView.setText(user.getName());
        return convertView;
    }

}


text:
@interface YWHomeViewController ()<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (nonatomic,strong)NSArray * nameArr;
@property (nonatomic,strong)NSArray * imgNameArr;
@property (nonatomic,strong)NSArray * subVCArr;

@property (nonatomic,strong)UIBarButtonItem * rightBarBtn;

@end

@implementation YWHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self makeNavi];
    [self dataSet];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

    [[[self.navigationController.navigationBar subviews] objectAtIndex:0] setAlpha:0.f];
    [self setAutomaticallyAdjustsScrollViewInsets:NO];
    [self isNewNotification:[UserSession instance].isNewNoticafication];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[[self.navigationController.navigationBar subviews] objectAtIndex:0] setAlpha:1.f];
}

- (void)makeNavi{
    self.title = @"首页";
    self.rightBarBtn = [UIBarButtonItem barItemWithImageName:@"MessageNoChatWhite" withSelectImage:@"MessageNoChatWhite" withHorizontalAlignment:UIControlContentHorizontalAlignmentCenter withTarget:self action:@selector(messageAction) forControlEvents:UIControlEventTouchUpInside withWidth:30.f];
    CGFloat redWidth = 8.f;
    UILabel * redLabel = [[UILabel alloc]initWithFrame:CGRectMake(20.f, 5.f, redWidth, redWidth)];
    redLabel.backgroundColor = [UIColor redColor];
    redLabel.layer.cornerRadius = redWidth/2;
    redLabel.layer.masksToBounds = YES;
    redLabel.tag = 1001;
    redLabel.hidden = YES;
    [self.rightBarBtn.customView addSubview:redLabel];
    self.navigationItem.rightBarButtonItem = self.rightBarBtn;
}

- (void)isNewNotification:(BOOL)isNew{
    UILabel * redLabel = (UILabel *)[self.rightBarBtn.customView viewWithTag:1001];
    redLabel.hidden = !isNew;
}
//Home_IMG1"
- (void)dataSet{
    self.nameArr = @[@"财务管理",@"提现管理",@"商品管理",@"口碑品牌",@"退款管理",@"预定管理",@"优惠券",@"相册管理",@"同业排行"];
    self.imgNameArr = @[@"Home_IMG0",@"Home_IMG9",@"Home_IMG1",@"Home_IMG3",@"Home_IMG4",@"Home_IMG5",@"Home_IMG2",@"Home_IMG7",@"Home_IMG8"];
    self.subVCArr = @[[YWFinancialViewController class],[YWHomeFestivalViewController class],[YWCategoryViewController class],[ShowMoreCommitViewController class],[YWHomeRefundVC class],[YWHomeAdvanceOrderViewController class],[YWHomeCouponViewController class],[StorePhotoViewController class],[YWHomeCompareViewController class]];
    [self.collectionView registerNib:[UINib nibWithNibName:@"YWHomeCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"YWHomeCollectionViewCell"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"YWHomeCollectionHeaderView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"YWHomeCollectionHeaderView"];

    //加载完数据之后,判断是否是推送了通知,如果是,就跳转制定页面
    NSString * documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSString * filePath1 = [NSString stringWithFormat:@"%@/isPush.plist",documentPath];
    NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithContentsOfFile:filePath1];
    if (dic == nil) {
        //表示没有这个文件时候。我们创建一个.plist文件
        NSMutableDictionary* arrM = [NSMutableDictionary dictionary];
        [arrM setObject:@"0" forKey:@"ispush"];
        [arrM writeToFile:filePath1 atomically:YES];
    }else{
        //说明已经有数据,在字典里面
        NSString * str = dic[@"ispush"];
        if ([str isEqualToString:@"1"]) {
            //说明是通知发送过来的
            YWHomeAdvanceOrderViewController*vc=[[YWHomeAdvanceOrderViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
            //跳转之后,把数据还原;
            [dic setValue:@"0" forKey:@"ispush"];
            [dic writeToFile:filePath1 atomically:YES];
        }
    }
}

- (void)messageAction{
    if (![UserSession userToComfired])return;
    YWHomeNoticaficationViewController * vc = [[YWHomeNoticaficationViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - UICollectionViewDataSource
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    YWHomeCollectionHeaderView * header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"YWHomeCollectionHeaderView" forIndexPath:indexPath];
    WEAKSELF;
    header.payBlock = ^(){
        if ([UserSession userToComfired]){
            YWHomePayBillViewController * vc = [[YWHomePayBillViewController alloc]init];
        [weakSelf.navigationController pushViewController:vc animated:YES];
        }
    };
    header.recordBlock = ^(){
        if ([UserSession userToComfired]){
            YWHomeQuickPayListVC * vc = [[YWHomeQuickPayListVC alloc]init];
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }
    };
    return header;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.nameArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    YWHomeCollectionViewCell * homeCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"YWHomeCollectionViewCell" forIndexPath:indexPath];
    homeCell.nameLabel.text = self.nameArr[indexPath.row];
    homeCell.showImage.image = [UIImage imageNamed:self.imgNameArr[indexPath.row]];
    return homeCell;
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (![UserSession userToComfired])return;
    Class viewClass = (Class)self.subVCArr[indexPath.row];
    UIViewController * vc = [[viewClass alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(kScreen_Width/3, ACTUAL_WIDTH(110.f));
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(kScreen_Width, 175.f);
}

@end


text:
require "spec_helper"

describe MongoODM::Document::AttributeMethods::Write do

end


text:
import logging

from pecan import conf  # noqa
from sqlalchemy import create_engine, Column, String, Unicode, UnicodeText
from sqlalchemy import Boolean, Integer, exc, event
from sqlalchemy import ForeignKey, UniqueConstraint
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
from sqlalchemy.ext.declarative import declarative_base
from contextlib import contextmanager

Base = declarative_base()
engine = None

logger = logging.getLogger(__name__)

def row2dict(row):
    ret = {}
    for column in row.__table__.columns:
        ret[column.name] = getattr(row, column.name)
        # TODO: Fix test and remove bellow hack!
        if not isinstance(ret[column.name], basestring) and \
           not isinstance(ret[column.name], bool):
            ret[column.name] = str(ret[column.name])
    return ret

class User(Base):
    __tablename__ = 'users'
    username = Column(Unicode(255), primary_key=True)
    fullname = Column(Unicode(255), nullable=False)
    email = Column(String(255), nullable=False)
    hashed_password = Column(String(255), nullable=False)
    sshkey = Column(String(1023), nullable=True)

def checkout_listener(dbapi_con, con_record, con_proxy):
    try:
        try:
            dbapi_con.ping(False)
        except TypeError:
            dbapi_con.ping()
    except dbapi_con.OperationalError as e:
        if e.args[0] in (2006,   # MySQL server has gone away
                         2013,   # Lost connection to server during query
                         2055):  # Lost connection to server
            # caught by pool, which will retry with a new connection
            raise exc.DisconnectionError()
        else:
            raise

class SFUser(Base):
    __tablename__ = 'SF_USERS'
    id = Column(Integer(), primary_key=True)
    username = Column(Unicode(255), nullable=False, unique=True)
    fullname = Column(Unicode(255), nullable=True)
    # Gerrit requires email unicity
    email = Column(String(255), nullable=False, unique=True)
    cauth_id = Column(Integer(), nullable=False)
    idp_sync = Column(Boolean(), default=True)

class SFUserServiceMapping(Base):
    __tablename__ = 'SF_USERS_SERVICES_MAPPING'
    # needed for constraint definition, not actually used
    id = Column(Integer(), primary_key=True)
    sf_user_id = Column(Integer(), ForeignKey('SF_USERS.id'),
                        nullable=False)
    # will simply store the plugin name
    service = Column(String(255), nullable=False)
    # for extended future compatibility, don't limit to integers
    service_user_id = Column(String(255), nullable=False)
    __table_args__ = (UniqueConstraint('sf_user_id',
                                       'service',
                                       'service_user_id',
                                       name='unique_service_user'), )

class SFUserCRUD:
    def set_service_mapping(self, sf_user_id, service, service_user_id):
        with session_scope() as session:
            r = SFUserServiceMapping(sf_user_id=sf_user_id,
                                     service=service,
                                     service_user_id=service_user_id)
            session.add(r)

    def get_service_mapping(self, service, sf_user_id):
        with session_scope() as session:
            filtering = {'service': service,
                         'sf_user_id': sf_user_id}
            try:
                r = session.query(SFUserServiceMapping).filter_by(**filtering)
                return r.one().service_user_id
            except MultipleResultsFound:
                msg = 'Too many mappings for user #%s on service %s'
                raise KeyError(msg % (sf_user_id, service))
            except NoResultFound:
                return None

    def get_user_mapping(self, service, service_user_id):
        with session_scope() as session:
            filtering = {'service': service,
                         'service_user_id': service_user_id}
            try:
                r = session.query(SFUserServiceMapping).filter_by(**filtering)
                return r.one().service_user_id
            except MultipleResultsFound:
                msg = 'Too many mappings for service %s\'s user #%s'
                raise KeyError(msg % (service_user_id, service))
            except NoResultFound:
                return None

    def delete_service_mapping(self, sf_user_id,
                               service=None, service_user_id=None):
        with session_scope() as session:
            filtering = {'sf_user_id': sf_user_id}
            if service:
                filtering['service'] = service
            if service_user_id:
                filtering['service_user_id'] = service_user_id
            m = session.query(SFUserServiceMapping).filter_by(**filtering)
            m.delete(synchronize_session=False)

    def get(self, id=None, username=None, email=None,
            fullname=None, cauth_id=None):
        with session_scope() as session:
            if (id or username or email or fullname or cauth_id):
                filtering = {}
                if id:
                    filtering['id'] = id
                if username:
                    filtering['username'] = username
                if email:
                    filtering['email'] = email
                if fullname:
                    filtering['fullname'] = fullname
                if cauth_id:
                    filtering['cauth_id'] = cauth_id
                try:
                    ret = session.query(SFUser).filter_by(**filtering).one()
                    return row2dict(ret)
                except MultipleResultsFound:
                    # TODO(mhu) find a better Error
                    raise KeyError('search returned more than one result')
                except NoResultFound:
                    return {}
            else:
                # all()
                all = [row2dict(ret) for ret in session.query(SFUser)]
                return all

    def update(self, id, username=None, email=None,
               fullname=None, cauth_id=None, idp_sync=None):
        with session_scope() as session:
            try:
                ret = session.query(SFUser).filter_by(id=id).one()
                if username:
                    ret.username = username
                if email:
                    ret.email = email
                if fullname:
                    ret.fullname = fullname
                if cauth_id:
                    ret.cauth_id = cauth_id
                if idp_sync is not None:
                    ret.idp_sync = idp_sync
                session.commit()
            except MultipleResultsFound:
                msg = 'SF_USERS table has multiple row with the same id!'
                logger.error(msg)
                raise KeyError(msg)
            except NoResultFound:
                logger.warn("Could not update user %s: not found" % id)
                return

    def create(self, username, email,
               fullname, cauth_id=None):
        with session_scope() as session:
            if username and email and fullname:
                # assign a dummy value in case we lack the information
                # as is likely to happen when migrating from a previous version
                # TODO(mhu) remove these for version n+2
                cid = cauth_id or -1
                user = SFUser(username=username,
                              email=email,
                              fullname=fullname,
                              cauth_id=cid)
                session.add(user)
                session.commit()
                return user.id
            else:
                msg = "Missing info required for user creation: %s|%s|%s"
                raise KeyError(msg % (username, email, fullname))

    def delete(self, id=None, username=None, email=None,
               fullname=None, cauth_id=None):
        with session_scope() as session:
            filtering = {}
            if id:
                filtering['id'] = id
            if username:
                filtering['username'] = username
            if email:
                filtering['email'] = email
            if fullname:
                filtering['fullname'] = fullname
            if cauth_id:
                filtering['cauth_id'] = cauth_id
            try:
                ret = session.query(SFUser).filter_by(**filtering).one()
                session.delete(ret)
                session.commit()
                return True
            except MultipleResultsFound:
                # TODO(mhu) find a better Error
                raise KeyError('Too many candidates for deletion')
            except NoResultFound:
                return False

class NodepoolImageUpdate(Base):
    __tablename__ = 'NODEPOOL_IMAGE_UPDATES'
    id = Column(Integer(), primary_key=True)
    status = Column(String(255), default="IN_PROGRESS")
    provider = Column(String(1024), nullable=False)
    image = Column(String(1024), nullable=False)
    exit_code = Column(Integer(), default=-1)
    stderr = Column(UnicodeText(), default="")
    output = Column(UnicodeText(4294967295), default="")

class ImageUpdatesCRUD():
    def create(self, provider, image):
        with session_scope() as session:
            if provider and image:
                img_update = NodepoolImageUpdate(
                              provider=provider,
                              image=image)
                session.add(img_update)
                session.commit()
                return img_update.id
            else:
                msg = "Missing info required for image update: %s|%s"
                raise KeyError(msg % (provider, image))

    def update(self, id, status=None, exit_code=None,
               output=None, stderr=None):
        with session_scope() as session:
            try:
                u = session.query(NodepoolImageUpdate).filter_by(id=id).one()
                if status:
                    u.status = status
                if exit_code:
                    u.exit_code = int(exit_code)
                if output:
                    u.output = output
                if stderr:
                    u.stderr = stderr
                session.commit()
            except NoResultFound:
                logger.warn("Could not update image-update %s: not found" % id)
                return

    def get(self, id):
        with session_scope() as session:
            # TODO(mhu) Lookup by images, providers, statuses if needed?
            try:
                u = session.query(NodepoolImageUpdate).filter_by(id=id).one()
                return row2dict(u)
            except NoResultFound:
                return {}

def init_model():
    c = dict(conf.sqlalchemy)
    url = c.pop('url')
    if url.startswith('mysql') and not url.endswith('?charset=utf8'):
        url += '?charset=utf8'
    globals()['engine'] = create_engine(url, pool_recycle=600, **c)
    if url.startswith('mysql'):
        event.listen(engine, 'checkout', checkout_listener)
    Base.metadata.create_all(engine)

def start_session():
    Base.metadata.bind = engine
    dbsession = sessionmaker(bind=engine)
    session = dbsession()
    return session

@contextmanager
def session_scope():
    session = start_session()
    try:
        yield session
        session.commit()
    except:
        session.rollback()
        raise
    finally:
        session.close()

def add_user(user):
    """ Add a user in the database
        return Boolean
    """
    try:
        with session_scope() as session:
            u = User(**user)
            session.add(u)
            return True, None
    except exc.IntegrityError as e:
        return False, unicode(e)

def get_user(username):
    """ Fetch a user by its username
        return user dict or False if not found
    """
    try:
        with session_scope() as session:
            ret = session.query(User).filter_by(username=username).one()
            return row2dict(ret)
    except NoResultFound:
        return False

def delete_user(username):
    """ Delete a user by its username
        return True if deleted or False if not found
    """
    with session_scope() as session:
        ret = session.query(User).filter_by(username=username).delete()
        return bool(ret)

def update_user(username, infos):
    """ Update a user by its username
        arg infos: Dict
        return True if deleted or False if not found
    """
    with session_scope() as session:
        user = session.query(User)
        ret = user.filter_by(username=username).update(infos)
        return bool(ret)


text:
package com.coolweather.app.db;

import java.util.ArrayList;
import java.util.List;

import com.coolweather.app.model.City;
import com.coolweather.app.model.County;
import com.coolweather.app.model.Province;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class CoolWeatherDB {

	/**
	* Êý¾Ý¿âÃû
	*/
	public static final String DB_NAME = "cool_weather";
	/**
	* Êý¾Ý¿â°æ±¾
	*/
	public static final int VERSION = 6;
	private static CoolWeatherDB coolWeatherDB;
	private SQLiteDatabase db;

	private CoolWeatherDB(Context context) {
		CoolWeatherOpenHelper dbHelper = new CoolWeatherOpenHelper(context,
		DB_NAME, null, VERSION);
		db = dbHelper.getWritableDatabase();

	}

	/**
	* »ñÈ¡CoolWeatherDBµÄʵÀý¡£
	*/
	public synchronized static CoolWeatherDB getInstance(Context context) {
			if (coolWeatherDB == null) {
			coolWeatherDB = new CoolWeatherDB(context);
			}
			return coolWeatherDB;
		}

	/**
	* ½«ProvinceʵÀý´æ´¢µ½Êý¾Ý¿â¡£
	*/
	public void saveProvince(Province province) {
		if (province != null) {
		ContentValues values = new ContentValues();
		values.put("id", province.getId());
		values.put("province", province.getProvinceName()) ;
		values.put("city", province.getCity());
		values.put("district", province.getDistrict());
		db.insert("Province", null, values);
		}
	}

	public List<Province> loadProvinces() {
		List<Province> list = new ArrayList<Province>();
		Cursor cursor = db.query(true,"Province", new String[]{"province"}, null,null, null, null, null, null);
		if (cursor.moveToFirst()) {
		do {
		Province province = new Province();
	//	province.setId(cursor.getInt(cursor.getColumnIndex("id")));
		province.setProvinceName(cursor.getString(cursor
		.getColumnIndex("province")));
	//	province.setCity(cursor.getString(cursor
	//			.getColumnIndex("city")));
//		province.setDistrict(cursor.getString(cursor
	//			.getColumnIndex("district")));
		list.add(province);
		} while (cursor.moveToNext());
		}
		return list;

	}

	/**
	* ½«CityʵÀý´æ´¢µ½Êý¾Ý¿â¡£
	*/
	public void saveCity(City city) {
		if (city != null) {
			ContentValues values = new ContentValues();
			values.put("city_name", city.getCityName());
			values.put("city_code", city.getCityCode());
			values.put("province_id", city.getProvinceId());
			db.insert("City", null, values);
		}
	}

	/**
	* ´ÓÊý¾Ý¿â¶ÁȡijʡÏÂËùÓеijÇÊÐÐÅÏ¢¡£
	*/
	public List<City> loadCities(String province_name) {
		List<City> list = new ArrayList<City>();
		Cursor cursor ;//= db.query("Province", null, "province = ?",
		//new String[] { province_name }, null, null, null);
		cursor = db.query(true,"Province", new String[]{"city"}, "province = ?",new String[] { province_name }, null, null, null, null);
		if (cursor.moveToFirst()) {
			do {
				City city = new City();
			//	city.setId(cursor.getInt(cursor.getColumnIndex("id")));
				city.setCityName(cursor.getString(cursor
				.getColumnIndex("city")));
			//	city.setCityCode(cursor.getString(cursor
			//	.getColumnIndex("city_code")));
			//	city.setProvinceId(province_name);
				list.add(city);
			} while (cursor.moveToNext());
		}
		return list;
	}

	/**
	* ½«CountyʵÀý´æ´¢µ½Êý¾Ý¿â¡£
	*/
	public void saveCounty(County county) {
		if (county != null) {
			ContentValues values = new ContentValues();
			values.put("county_name", county.getCountyName());
			values.put("county_code", county.getCountyCode());
			values.put("city_id", county.getCityId());
			db.insert("County", null, values);
		}
	}

	/**
	* ´ÓÊý¾Ý¿â¶Áȡij³ÇÊÐÏÂËùÓеÄÏØÐÅÏ¢¡£
	*/
	public List<County> loadCounties(String city) {
		List<County> list = new ArrayList<County>();
		Cursor cursor ;//= db.query("Province", null, "city = ?",
	//	new String[] { city }, null, null, null);
		cursor = db.query(true,"Province", new String[]{"id","district"}, "city = ?",new String[] { city }, null, null, null, null);

		if (cursor.moveToFirst()) {
			do {
				County county = new County();
				county.setId(cursor.getInt(cursor.getColumnIndex("id")));
				county.setCountyName(cursor.getString(cursor
				.getColumnIndex("district")));
			//	county.setCountyCode(cursor.getString(cursor
			//	.getColumnIndex("id")));
			//	county.setCityId(city	);
				list.add(county);
			} while (cursor.moveToNext());
		}
		return list;
	}

}


text:
using UnityEngine;
using System.Collections;

public class bulletMovement : MonoBehaviour {

	public float maxSpeed = 5f;

	// Update is called once per frame
	void Update () {
		Vector3 pos = transform.position;
		Vector3 velocity = new Vector3 (0, maxSpeed * Time.deltaTime, 0);
		pos += transform.rotation * velocity;
		transform.position = pos;
	}
}


text:
namespace Formo
{
    using System.Configuration;
    using System.Dynamic;

    internal class ConnectionStringsConfiguration : DynamicObject
    {
        private readonly ConnectionStringSettingsCollection _connectionStrings;

        internal ConnectionStringsConfiguration(ConnectionStringSettingsCollection connectionStrings)
        {
            _connectionStrings = connectionStrings;
        }

        public ConnectionStringSettings Get(string key) => _connectionStrings[key];

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            result = _connectionStrings[binder.Name] ?? new ConnectionStringSettings();
            return true;
        }
    }
}


text:
package com.lcw.one.weixin;

import com.lcw.one.util.filter.RequestInfoFilter;
import com.lcw.one.util.persistence.BaseRepositoryImpl;
import com.lcw.one.util.utils.SpringContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.bind.annotation.ControllerAdvice;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableAsync(proxyTargetClass = true)
@EnableCaching(proxyTargetClass = true)
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "com.lcw.one", repositoryBaseClass = BaseRepositoryImpl.class)
@EntityScan("com.lcw.one")
@ComponentScan("com.lcw.one")
@EnableSwagger2
@SpringBootApplication
@ControllerAdvice
public class OneWeixinApplication {

    private static final Logger logger = LoggerFactory.getLogger(OneWeixinApplication.class);

    public static void main(String[] args) {
        ApplicationContext applicationContext = SpringApplication.run(OneWeixinApplication.class, args);
        SpringContextHolder.setApplicationContext(applicationContext);
        logger.info("Registry ApplicationContext");
    }

    @Bean
    public FilterRegistrationBean requestInfoFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new RequestInfoFilter());
        registration.addUrlPatterns("/*");
        registration.setName("RequestInfoFilter");
        registration.setOrder(10);
        return registration;
    }
}


text:
package com.nanodegree.mdaniel.popularmovies1.ui.activities;

import android.support.design.widget.TabLayout;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

import com.nanodegree.mdaniel.popularmovies1.R;
import com.nanodegree.mdaniel.popularmovies1.services.QueryEvent;
import com.nanodegree.mdaniel.popularmovies1.ui.adapter.TabFragmentPagerAdapter;
import com.nanodegree.mdaniel.popularmovies1.ui.fragments.MovieFragment;

import de.greenrobot.event.EventBus;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        final ActionBar ab = getSupportActionBar();
        ab.setDisplayHomeAsUpEnabled(false);

        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
        if (viewPager != null) {
            setupViewPager(viewPager);
        }

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
    }

    private void setupViewPager(ViewPager viewPager) {
        TabFragmentPagerAdapter adapter = new TabFragmentPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(MovieFragment.newInstance("popularity.desc"), "Popular");
        adapter.addFragment(MovieFragment.newInstance("vote_average.desc"), "Highest Rated");
        viewPager.setAdapter(adapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);

        final MenuItem searchItem = menu.findItem(R.id.action_search);
        final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                EventBus.getDefault().post(new QueryEvent(query));
                //if you want to collapse the searchview
                invalidateOptionsMenu();
                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                return false;
            }
        });

        return true;
    }
}


text:
//
// HRPReporterViewController.h
//
// Copyright (c) 2013 Oleg Poyaganov (opedge@gmail.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#import <Foundation/Foundation.h>

#ifndef _DRPDRAWREPORT_
    #define _DRPDRAWREPORT_

    #import "DRPReporter.h"
    #import "DRPReporterViewController.h"

#endif /* _DRPDRAWREPORT_ */


text:
To hack on the plugin:

- run `npm install`
- run `webpack --config webpack.backend.js` in this directory
- run `webpack` or `webpack --watch` in this directory
- Go to `chrome://extensions`, check "developer mode", and click "Load
  unpacked extension", and select this directory
- Hack away!

Generally, changes to the UI will auto-propagate if you have `webpack --watch`
on (close devtools and re-open them). If you change the background script or
injector, you might have to reload the extension from the extensions page.

## Insulating the environment

React Devtools has part of the code (the backend + agent) running in the same
javascript context as the inspected page, which makes the code vulnerable to
environmental inconsistencies. For example, the backend uses the es6 `Map`
class and normally expects it to be available in the global scope. If a user
script has overridden this, the backend breaks.

To prevent this, the content script [`src/GlobalHook.js`](src/GlobalHook.js),
which runs before any user js, saves the native values we depend on to the
`__REACT_DEVTOOLS_GLOBAL_HOOK__` global. These are:

- Set
- Map
- WeakMap
- Object.create

Then in `webpack.backend.js`, these saved values are substituted for the
globally referenced name (e.g. `Map` gets replaced with
`window.__REACT_DEVTOOLS_GLOBAL_HOOK__.nativeMap`).

## Fixing document.create

React Native sets `document.createElement` to `null` in order to convince js
libs that they are not running in a browser environment while `debug in
chrome` is enabled.

To deal with this, [`src/inject.js`](src/inject.js) calls
`document.constructor.prototype.createElement` when it needs to create a
`<script>` tag.


text:
* `master`: [![Build Status](https://travis-ci.org/basho/riak_pb.svg?branch=master)](http://travis-ci.org/basho/riak_pb)
* `develop`: [![Build Status](https://travis-ci.org/basho/riak_pb.svg?branch=develop)](http://travis-ci.org/basho/riak_pb)

This repository contains the message definitions for the Protocol
Buffers-based interface to [Riak](https://github.com/basho/riak) and
various Erlang-specific utility modules for the message types.

This is distributed separately from the Riak server and clients,
allowing it to serve as an independent representation of the supported
messages. Additionally, the `.proto` descriptions are broken out by
functional area:

* `riak.proto` contains "global" messages like the error message and
  the "server info" calls.
* `riak_kv.proto` contains messages related to Riak KV.

Other specifications may arise as more features are exposed via the PB
interface.

## Protocol

The Riak PBC protocol encodes requests and responses as Protocol
Buffers messages.  Each request message results in one or more
response messages.  As message type and length are not encoded by PB,
they are sent on the wire as:

    <length:32> <msg_code:8> <pbmsg>

* `length` is the length of `msg_code` (1 byte) plus the message length
  in bytes encoded in network order (big endian).

* `msg_code` indicates what is encoded as `pbmsg`

* `pbmsg` is the encoded protocol buffer message

On connect, the client can make requests and will receive responses.
For each request message there is a corresponding response message, or
the server will respond with an error message if something has gone
wrong.

The client should be prepared to handle messages without any `pbmsg`
(i.e. `length == 1`) for requests where the response is simply an
acknowledgment.

In some cases, a client may receive multiple response messages for a
single request. The response message will typically include a boolean
`done` field that signifies the last message in a sequence.

### Registered Message Codes

[Message codes](http://docs.basho.com/riak/latest/dev/references/protocol-buffers/#Message-Codes) and documentation can be found in the protocol-buffers
[section](http://docs.basho.com/riak/latest/dev/references/protocol-buffers/) of the online docs.

## Contributing

Generally, you should not need to modify this repository unless you
are adding new client-facing features to Riak or fixing a
bug. Nevertheless, we encourage contributions to `riak_pb` from the
community.

1. Fork the [`riak_pb`](https://github.com/basho/riak_pb) repository
   on Github.
2. Clone your fork or add the remote if you already have a clone of
   the repository.

    ```
    git clone git@github.com:yourusername/riak_pb.git
    # or
    git remote add mine git@github.com:yourusername/riak_pb.git
    ```

3. Create a topic branch for your change.

    ```
    git checkout -b some-topic-branch
    ```

4. Make your change and commit. Use a clear and descriptive commit
   message, spanning multiple lines if detailed explanation is needed.
5. Push to your fork of the repository and then send a pull-request
   through Github.

    ```
    git push mine some-topic-branch
    ```

6. A Basho engineer or community maintainer will review your patch and
   merge it into the main repository or send you feedback.

## Build Prerequisites

* protoc v 2.5.0

On OSX the default version installed by brew is 2.6.x (Nov 2015)
this version is too new for the Maven protocol-buffers plugin.

You can install the correct version like so.

  ```
    brew tap homebrew/versions
    brew install homebrew/versions/protobuf250
  ```


text:
import path = require('path');
import PackageJsonFile from './package-json-file';
import JspmFile from './jspm-file';
import { default as globalConfig } from './global-config-file';
export { globalConfig };
import { Project } from '../project';

export default class ProjectConfig {
  pjson: PackageJsonFile;
  jspm: JspmFile;
  defaultRegistry: string;
  project: Project;

  constructor (projectPath: string, project: Project) {
    let pjsonPath = path.resolve(projectPath, 'package.json');

    this.project = project;
    const configFile = path.resolve(path.dirname(pjsonPath), 'jspm.json');
    this.jspm = new JspmFile(configFile);
    this.pjson = new PackageJsonFile(pjsonPath, project, this.jspm.exists());

    if (!this.jspm.exists()) {
      // check upgrade paths
    }
  }

  dispose () {
    this.pjson.dispose();
    this.jspm.dispose();
  }

  async checkCreatePrompts (force = false) {
    if (!this.pjson.exists()) {
      if (!await this.project.confirm('Package.json file does not exist, create it?', true))
        throw 'Operation aborted.';
    }

    if (!this.jspm.exists()) {
      if (!await this.project.confirm(`Configuration file %${path.relative(process.cwd(), this.pjson.configFile)}% does not exist, create it?`, true))
        throw 'Operation aborted.';
    }

    let existingJspmProject = this.pjson.exists() && this.pjson.jspmAware;

    if (!existingJspmProject || force)
      throw new Error('Init prompts yet to be implemented.');
      // await initPrompts(existingJspmProject);
  }

  save () {
    let pjsonChanged = this.pjson.write();
    let jspmChanged = this.jspm.write();
    return pjsonChanged || jspmChanged;
  }
}


text:
@class DrawerViewController;

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) DrawerViewController *drawerViewController;

@end


text:
var fs = require('fs');
var path = require('path');
var prompt = require('prompt-lite');

const FABRIC_GRADLE_TOOLS = '1.+'
const FABRIC_ANDROID_CRASHLYTICS = '2.9.1';
const FABRIC_ANDROID_ANSWERS = '1.4.1';
const FABRIC_IOS_CRASHLYTICS = '3.10.1';
const FABRIC_IOS_FABRIC = '1.7.6';

// Default settings for using ios and android with Fabric
var usingiOS = false,
    usingAndroid = false;

// The directories where the Podfile and include.gradle are stored
var directories = {
    ios: './platforms/ios',
    android: './platforms/android'
};

console.log('NativeScript Fabric Plugin Installation');

var appRoot = "../../";
var packageJsonPath = path.join(appRoot, "app", "package.json");

console.log('Applying to app package.json: ' + packageJsonPath);

var pluginConfigFile = "fabric.json";
var pluginConfigPath = path.join(appRoot, pluginConfigFile);
var config = {};

function mergeConfig(result) {
    for (var key in result) {
        config[key] = result[key];
    }
}

function saveConfig() {
    fs.writeFileSync(pluginConfigPath, JSON.stringify(config, null, 4));
}

function readConfig() {
    try {
        config = JSON.parse(fs.readFileSync(pluginConfigPath));
    } catch (e) {
        console.log("Failed reading " + pluginConfigFile);
        console.log(e);
        config = {};
    }
}

function isInteractive() {
    return process.stdin && process.stdin.isTTY && process.stdout && process.stdout.isTTY;
}

// workaround for https://github.com/NativeScript/nativescript-cli/issues/2521 (2.5.0 only)
var nativeScriptVersion = "";
try {
    nativeScriptVersion = __webpack_require__( /*! child_process */ 2).execSync('nativescript --version');
} catch (err) {
    // On some environments nativescript is not in the PATH
    // Ignore the error
}

var isNativeScriptCLI250 = nativeScriptVersion.indexOf("2.5.0") !== -1;

// note that for CI builds you want a pluginConfigFile, otherwise the build will fail
if (process.argv.indexOf("config") === -1 && fs.existsSync(pluginConfigPath)) {
    readConfig();
    if (config.apiKey) {
        config.api_key = config.apiKey;
        delete config.apiKey;
        saveConfig();
    }
    if (config.apiSecret) {
        config.api_secret = config.apiSecret;
        delete config.apiSecret;
        saveConfig();
    }
    console.log("Config file exists (" + pluginConfigFile + ")");
    askiOSPromptResult(config);
    askAndroidPromptResult(config);
    promptQuestionsResult(config);
} else if (isNativeScriptCLI250 && process.argv.indexOf("setup") === -1) {
    console.log("*******************************************************************");
    console.log("*******************************************************************");
    console.log("************************** IMPORTANT: *****************************");
    console.log("*******************  with nativescript 2.5.0  *********************");
    console.log("************** now execute 'npm run setup' manually ***************");
    console.log("***** in the node_modules/nativescript-plugin-fabric folder *****");
    console.log("*******************************************************************");
    console.log("*******************************************************************");
} else if (!isInteractive()) {
    console.log("No existing " + pluginConfigFile + " config file found and terminal is not interactive! Default configuration will be used.");
} else {
    console.log("No existing " + pluginConfigFile + " config file found, so let's configure the Fabric plugin!");
    prompt.start();
    askiOSPrompt();
}

/**
 * Prompt the user if they are integrating Fabric with iOS
 */
function askiOSPrompt() {
    prompt.get({
        name: 'using_ios',
        description: 'Are you using iOS (y/n)',
        default: 'y'
    }, function(err, result) {
        if (err) {
            return console.log(err);
        }
        mergeConfig(result);
        askiOSPromptResult(result);
        askAndroidPrompt();
    });
}

function askiOSPromptResult(result) {
    if (isSelected(result.using_ios)) {
        usingiOS = true;
    }
}

/**
 * Prompt the user if they are integrating Fabric with Android
 */
function askAndroidPrompt() {
    prompt.get({
        name: 'using_android',
        description: 'Are you using Android (y/n)',
        default: 'y'
    }, function(err, result) {
        if (err) {
            return console.log(err);
        }
        mergeConfig(result);
        askAndroidPromptResult(result);
        if (usingiOS || usingAndroid) {
            promptQuestions();
        } else {
            askSaveConfigPrompt();
        }
    });
}

function askAndroidPromptResult(result) {
    if (isSelected(result.using_android)) {
        usingAndroid = true;
    }
}

/**
 * Prompt the user through the configurable Fabric add-on services
 */
function promptQuestions() {
    prompt.get([{
        name: 'api_key',
        description: 'Your Fabric API Key',
        default: ''
    }, {
        name: 'api_secret',
        description: 'Your Fabric API Secret',
        default: ''
    }], function(err, result) {
        if (err) {
            return console.log(err);
        }
        mergeConfig(result);
        promptQuestionsResult(result);
        askSaveConfigPrompt();
    });
}

function promptQuestionsResult(result) {
    if (usingiOS) {
        writePodFile(result);
        writeXcodeData(result);
    }
    if (usingAndroid) {
        writeGradleFile();
        writeFabricServiceGradleHook(result);
    }
    console.log('Fabric post install completed. To re-run this script, navigate to the root directory of `nativescript-fabric` in your `node_modules` folder and run: `npm run config`.');
}

function writeXcodeData(config) {

    console.log("Install Fabric-build-xcode hook.");

    try {
        if (!fs.existsSync(path.join(appRoot, "hooks"))) {
            fs.mkdirSync(path.join(appRoot, "hooks"));
        }
        if (!fs.existsSync(path.join(appRoot, "hooks", "after-prepare"))) {
            fs.mkdirSync(path.join(appRoot, "hooks", "after-prepare"));
        }
        var scriptContent =
            `
var path = require("path");
var fs = require("fs");
var xcode;
var plist;

module.exports = function($logger, $projectData, hookArgs) {
    var platform = hookArgs.platform.toLowerCase();
    if (platform === 'ios') {
        // hack for node resolution not working in some cases
        try {
            xcode = require("xcode");
        } catch (ignored) {
            xcode = require("../../node_modules/nativescript-fabric/node_modules/xcode/index.js");
        }
        // hack for node resolution not working in some cases
        try {
            plist = require("simple-plist");
        } catch (ignored) {
            plist = require("../../node_modules/nativescript-fabric/node_modules/simple-plist/simple-plist.js");
        }

        var appName = path.basename($projectData.projectDir);
        var sanitizedName = appName.split('').filter(function(c) { return /[a-zA-Z0-9]/.test(c); }).join('');
        var apiKey = "${config.api_key}";
        var apiSecret = "${config.api_secret}";
        var projectPath = path.join(__dirname, "..", "..", "platforms", "ios", appName + ".xcodeproj", "project.pbxproj");
        var plistPath = path.join(__dirname, "..", "..", "platforms", "ios", appName, appName + "-Info.plist");
        var podsPath = path.join(__dirname, "..", "..", "platforms", "ios", "Pods");
        if (fs.existsSync(projectPath)) {
            var projectPathContent = fs.readFileSync(projectPath).toString();

            // already added
            if (projectPathContent.indexOf('Configure Fabric') != -1) {
                return;
            }
            $logger.info('Configure Fabric for iOS');

            var xcodeProject = xcode.project(projectPath);
            xcodeProject.parseSync();
            var options = { shellPath: '/bin/sh', shellScript: podsPath + '/Fabric/run ' + apiKey + ' ' + apiSecret };
            var buildPhase = xcodeProject.addBuildPhase([], 'PBXShellScriptBuildPhase', 'Configure Fabric', xcodeProject.getFirstTarget().uuid, options).buildPhase;
            fs.writeFileSync(projectPath, xcodeProject.writeSync());
            $logger.trace('Updated Xcode project');

            var appPlist = plist.readFileSync(plistPath);
            plist.Fabric = {
                APIKey: apiKey,
                Kits: [{
                    KitInfo: '',
                    KiteName: 'Crashlytics'
                }, {
                    KitInfo: '',
                    KiteName: 'Answers'
                }]
            }
            plist.writeFileSync(plistPath, appPlist);
            $logger.trace('Updated Plist');
        }
    }
};
`;
        console.log("Writing 'nativescript-fabric-xcode.js' to " + appRoot + "hooks/after-prepare");
        var scriptPath = path.join(appRoot, "hooks", "after-prepare", "nativescript-fabric-xcode.js");
        fs.writeFileSync(scriptPath, scriptContent);
    } catch (e) {
        console.log("Failed to install nativescript-fabric-xcode hook.");
        console.log(e);
        throw e;
    }
}

function askSaveConfigPrompt() {
    prompt.get({
        name: 'save_config',
        description: 'Do you want to save the selected configuration. Reinstalling the dependency will reuse the setup from: ' + pluginConfigFile + '. CI will be easier. (y/n)',
        default: 'y'
    }, function(err, result) {
        if (err) {
            return console.log(err);
        }
        if (isSelected(result.save_config)) {
            saveConfig();
        }
    });
}

/**
 * Create the iOS PodFile for installing the Fabric iOS dependencies and service dependencies
 *
 * @param {any} result The answers to the micro-service prompts
 */
function writePodFile(result) {
    if (!fs.existsSync(directories.ios)) {
        fs.mkdirSync(directories.ios);
    }
    try {
        fs.writeFileSync(directories.ios + '/Podfile',
            `use_frameworks!
pod 'Fabric', '${FABRIC_IOS_FABRIC}'
pod 'Crashlytics', '${FABRIC_IOS_CRASHLYTICS}'
# Crashlytics works best without bitcode
post_install do |installer|
    installer.pods_project.targets.each do |target|
        target.build_configurations.each do |config|
            config.build_settings['ENABLE_BITCODE'] = "NO"
        end
    end
end
`);
        console.log('Successfully created iOS (Pod) file.');
    } catch (e) {
        console.log('Failed to create iOS (Pod) file.');
        console.log(e);
        throw e;
    }
}

/**
 * Create the Android Gradle for installing the Fabric Android dependencies and service dependencies
 *
 * @param {any} result The answers to the micro-service prompts
 */
function writeGradleFile() {
    if (!fs.existsSync(directories.android)) {
        fs.mkdirSync(directories.android);
    }
    try {
        fs.writeFileSync(directories.android + '/include.gradle',
            `
android {

}

buildscript {
  repositories {
    maven { url 'https://maven.fabric.io/public' }
  }
}

repositories {
  mavenCentral()
  maven { url 'https://maven.fabric.io/public' }
}

dependencies {
  compile('com.crashlytics.sdk.android:crashlytics:${FABRIC_ANDROID_CRASHLYTICS}@aar') {
    transitive = true;
  }
  compile('com.crashlytics.sdk.android:answers:${FABRIC_ANDROID_ANSWERS}@aar') {
    transitive = true;
  }
}

`);
        console.log('Successfully created Android (include.gradle) file.');
    } catch (e) {
        console.log('Failed to create Android (include.gradle) file.');
        console.log(e);
        throw e;
    }
}

/**
 * Create dev tools gradle runtime entry
 */
function writeFabricServiceGradleHook(config) {
    console.log("Install Fabric-build-gradle hook.");
    try {
        if (!fs.existsSync(path.join(appRoot, "hooks"))) {
            fs.mkdirSync(path.join(appRoot, "hooks"));
        }
        if (!fs.existsSync(path.join(appRoot, "hooks", "after-prepare"))) {
            fs.mkdirSync(path.join(appRoot, "hooks", "after-prepare"));
        }
        var scriptContent =
            `
var path = require("path");
var fs = require("fs");
module.exports = function($logger, $projectData, hookArgs) {
  var platform = hookArgs.platform.toLowerCase();

  function updateAppGradleScript(file) {
    var appBuildGradleContent = fs.readFileSync(file).toString();
    if (!appBuildGradleContent.match(/.*fabric.*/)) {
      $logger.trace("Configuring Fabric for Android");
      var search = -1;

      search = appBuildGradleContent.indexOf("repositories {", 0);
      if (search == -1) {
          return;
      }
      appBuildGradleContent = appBuildGradleContent.substr(0, search + 14) + '	    maven { url "https://maven.fabric.io/public" }\\n' + appBuildGradleContent.substr(search + 14);

      // TODO add to buildTypes entry
      // appBuildGradleContent = appBuildGradleContent + '\\ndebug { \\n   ext.enableCrashlytics = false\\n}\\n';

      search = appBuildGradleContent.indexOf("apply plugin: \\"com.android.application\\"");
      if (search == -1) {
          return;
      }
      appBuildGradleContent = appBuildGradleContent.substr(0, search + 39) + '\\napply plugin: "io.fabric"\\n' + appBuildGradleContent.substr(search + 39);

      fs.writeFileSync(file, appBuildGradleContent);
      $logger.trace('Written build.gradle');

    }
    if (appBuildGradleContent.indexOf("buildMetadata.finalizedBy(copyMetadata)") === -1) {
      appBuildGradleContent = appBuildGradleContent.replace("ensureMetadataOutDir.finalizedBy(buildMetadata)", "ensureMetadataOutDir.finalizedBy(buildMetadata)\\n\\t\\tbuildMetadata.finalizedBy(copyMetadata)");
      appBuildGradleContent += \`
task copyMetadata {
  doLast {
    copy {
        from "$projectDir/src/main/assets/metadata"
        def toDir = project.hasProperty("release") ? "release" : "debug";
        if (new File("$projectDir/build/intermediates/assets").listFiles() != null) {
          toDir = new File("$projectDir/build/intermediates/assets").listFiles()[0].name
          if (toDir != 'debug' && toDir != 'release') {
            toDir += "/release"
          }
        }
        into "$projectDir/build/intermediates/assets/" + toDir + "/metadata"
    }
  }
}
\`;
      fs.writeFileSync(file, appBuildGradleContent);
      $logger.trace('Written build.gradle');
    }
  }

  function updateGradleScript(file) {
    var buildGradleContent = fs.readFileSync(file).toString();
    if (!buildGradleContent.match(/.*fabric.*/)) {
      $logger.trace("Configuring Fabric for Android");
      var search = -1;

      search = buildGradleContent.indexOf("repositories", 0);
      if (search == -1) {
          return;
      }
      search = buildGradleContent.indexOf("}", search);
      buildGradleContent = buildGradleContent.substr(0, search - 1) + '	    maven { url "https://maven.fabric.io/public" }\\n' + buildGradleContent.substr(search - 1);

      search = buildGradleContent.indexOf("dependencies", search);
      if (search == -1) {
          return;
      }
      search = buildGradleContent.indexOf("}", search);
      if (search == -1) {
          return;
      }
      buildGradleContent = buildGradleContent.substr(0, search - 1) + '	    classpath "io.fabric.tools:gradle:${FABRIC_GRADLE_TOOLS}"\\n' + buildGradleContent.substr(search - 1);

      fs.writeFileSync(file, buildGradleContent);
      $logger.trace('Written build.gradle');
    }
  }

  if (platform === 'android') {

      var apiKey = "${config.api_key}";
      var apiSecret = "${config.api_secret}";
      var androidPlatformDir = path.join(__dirname, "..", "..", 'platforms', 'android');
      var androidAppPlatformDir = path.join(__dirname, "..", "..", 'platforms', 'android', 'app');
      var gradleScript = path.join(androidPlatformDir, 'build.gradle');
      var gradleAppScript = path.join(androidAppPlatformDir, 'build.gradle');

      if (fs.existsSync(gradleAppScript)) {
        updateAppGradleScript(gradleAppScript);
        updateGradleScript(gradleScript);
      } else {
        updateGradleScript(gradleScript);
      }

      var settingsJson = path.join(__dirname, "..", "..", "platforms", "android", "app", "src", "main", "res", "fabric.properties");

      var propertiesContent = '# Contains API Secret used to validate your application. Commit to internal source control; avoid making secret public\\n';
      propertiesContent+='apiKey = ' + apiKey + '\\n';
      propertiesContent+='apiSecret = ' + apiSecret + '\\n';
      fs.writeFileSync(settingsJson, propertiesContent);
      $logger.trace('Written fabric.properties');

  }
};
`;
        console.log("Writing 'nativescript-fabric-gradle.js' to " + appRoot + "hooks/after-prepare");
        var scriptPath = path.join(appRoot, "hooks", "after-prepare", "nativescript-fabric-gradle.js");
        fs.writeFileSync(scriptPath, scriptContent);
    } catch (e) {
        console.log("Failed to install nativescript-fabric-gradle hook.");
        console.log(e);
        throw e;
    }
}

/**
 * Determines if the answer validates as selected
 *
 * @param {any} value The user input for a prompt
 * @returns {boolean} The answer is yes, {false} The answer is no
 */
function isSelected(value) {
    return value === true || (typeof value === "string" && value.toLowerCase() === 'y');
}

function isPresent(value) {
    return value !== undefined;
}


text:
from datetime import datetime, timedelta
import unittest
import os

from django.contrib.auth.models import User
from django.conf import settings

from models import Node, Subject, Period, Assignment, AssignmentGroup, \
        FileMeta, Candidate
from deliverystore import FileNotFoundError
from testhelper import TestHelper

def create_from_path(path):
    """ Create a Node, Subject, Period, Assignment or AssignmentGroup from
    ``path``.

    Examples::

        assignmentgroup = create_from_path(
                'ifi:inf1100.spring05.oblig1.student1,student2')
        oblig1 = create_from_path(
                'ifi:inf1100.spring05.oblig1')
    """
    split = path.split(':', 1)
    nodes = split[0].split('.')
    for nodename in nodes:
        node = Node(short_name=nodename, long_name=nodename.capitalize())
        try:
            node.clean()
            node.save()
        except:
            node = Node.objects.get(short_name=nodename)
        last = node

    if len(split) != 2:
        return last
    pathsplit = split[1].split('.')

    # Subject
    subjectname = pathsplit[0]
    subject = Subject(parentnode=node, short_name=subjectname,
            long_name=subjectname.capitalize())
    try:
        subject.clean()
        subject.save()
    except:
        subject = Subject.objects.get(short_name=subjectname)
    last = subject

    # Period
    if len(pathsplit) > 1:
        periodname = pathsplit[1]
        period = Period(parentnode=subject, short_name=periodname,
                long_name=periodname.capitalize(), start_time=datetime.now(),
                end_time=datetime.now() + timedelta(10))
        try:
            period.clean()
            period.save()
        except:
            period = Period.objects.get(parentnode=subject,
                    short_name=periodname)
        last = period

    # Assignment
    if len(pathsplit) > 2:
        assignmentname = pathsplit[2]
        assignment = Assignment(parentnode=period, short_name=assignmentname,
                long_name=assignmentname.capitalize(), publishing_time=datetime.now())

        assignment.clean()
        try:
            assignment.save()
        except:
            assignment = Assignment.objects.get(parentnode=period,
                    short_name=assignmentname)
        last = assignment

    # Candidates
    if len(pathsplit) > 3:
        usernames = pathsplit[3].split(',')
        users = []
        for u in usernames:
            user = User(username=u)
            try:
                user.save()
            except:
                user = User.objects.get(username=u)
            users.append(user)
        assignment_group = AssignmentGroup(parentnode=assignment)
        assignment_group.clean()
        assignment_group.save()
        for user in users:
            assignment_group.candidates.add(Candidate(student=user))
        last = assignment_group
    return last

class TestDeliveryStoreMixin(TestHelper):
    """ Mixin-class that tests if
    :class:`devilry.core.deliverystore.DeliveryStoreInterface` is
    implemented correctly.

    You only need to override
    :meth:`get_storageobj`, and maybe :meth:`setUp` and :meth:`tearDown`,
    but make sure you call ``super(..., self).setUp()`` if you override it.

    You **must** mixin this class before :class:`django.test.TestCase` like
    so::

        class TestMyDeliveryStore(TestDeliveryStoreMixin, django.test.TestCase):
            ...
    """

    def get_storageobj(self):
        """ Return a object implementing
        :class:`devilry.core.deliverystore.DeliveryStoreInterface` """
        raise NotImplementedError()

    def setUp(self):
        """ Make sure to call this if you override it in subclasses, or the
        tests **will fail**. """
        self.add(nodes="uio.ifi",
                 subjects=["inf1100"],
                 periods=["period"],
                 assignments=["assignment1"],
                 assignmentgroups=["g1:candidate(student1)"],
                 deadlines=['d1:ends(10)'])
        # file and verdict
        self.goodFile = {"good.py": "print awesome"}
        d = self.add_delivery("inf1100.period.assignment1.g1", self.goodFile)
        self.filemeta = FileMeta()
        self.filemeta.delivery = d
        self.filemeta.size = 0
        self.filemeta.filename = 'test.txt'

    def test_writemany(self):
        store = self.get_storageobj()
        w = store.write_open(self.filemeta)
        w.write('hello')
        w.write(' world')
        w.write('!')
        w.close()
        r = store.read_open(self.filemeta)
        self.assertEquals(r.read(), 'hello world!')

    def test_readwrite(self):
        store = self.get_storageobj()
        self.assertFalse(store.exists(self.filemeta))
        self.assertRaises(FileNotFoundError, store.read_open, self.filemeta)
        w = store.write_open(self.filemeta)
        w.write('hello')
        w.close()
        self.assertTrue(store.exists(self.filemeta))
        store.remove(self.filemeta)
        self.assertFalse(store.exists(self.filemeta))
        self.assertRaises(FileNotFoundError, store.remove, self.filemeta)

class SeleniumTestBase(unittest.TestCase):
    fixtures = []

    def clear_testdb(self):
        os.system('git checkout deliverystore.dbm.dat')
        os.system('git checkout deliverystore.dbm.dir')
        if os.path.exists(settings.DATABASE_NAME):
            os.remove(settings.DATABASE_NAME)
        os.system('python manage.py syncdb --noinput')

    def load_fixtures(self):
        if not self.fixtures:
            raise ValueError("No fixtures in testcase: %s." %
                    self.__class__.__name__)
        self.clear_testdb()
        os.system('python manage.py loaddata -v0 %s' % \
                ' '.join(self.fixtures))

    def assert403(self, f, *args, **kw):
        try:
            f(*args, **kw)
        except Exception, e:
            self.assertTrue("403" in str(e))
            self.assertTrue("FORBIDDEN" in str(e))
        else:
            self.fail("403 not raised for %s, %s, %s" % (f, args, kw))


text:
from __future__ import unicode_literals, print_function
import logging
import time

import pytest

from gcdt import utils
from gcdt.ramuda_wire import _add_event_source, _remove_event_source, \
    wire, wire_deprecated, unwire, unwire_deprecated, \
    _get_event_source_status, _lambda_add_time_schedule_event_source, _lambda_add_invoke_permission
from gcdt.sns import create_topic, delete_topic, send_message
from gcdt.kinesis import create_stream, describe_stream, delete_stream, \
    wait_for_stream_exists
from gcdt_testtools.helpers_aws import create_lambda_helper, \
    create_lambda_role_helper, check_preconditions
from gcdt_testtools.helpers_aws import temp_bucket, awsclient, \
    cleanup_roles  # fixtures!
from gcdt_testtools.helpers import cleanup_tempfiles, temp_folder  # fixtures!
from .test_ramuda_aws import vendored_folder, temp_lambda  # fixtures!
from .test_ramuda_aws import cleanup_lambdas, cleanup_lambdas_deprecated  # fixtures!
from . import here

log = logging.getLogger(__name__)

def _get_count(awsclient, function_name, alias_name='ACTIVE', version=None):
    """Send a count request to a lambda function.

    :param awsclient:
    :param function_name:
    :param alias_name:
    :param version:
    :return: count retrieved from lambda call
    """
    client_lambda = awsclient.get_client('lambda')
    payload = '{"ramuda_action": "count"}'

    if version:
        response = client_lambda.invoke(
            FunctionName=function_name,
            InvocationType='RequestResponse',
            Payload=payload,
            Qualifier=version
        )
    else:
        response = client_lambda.invoke(
            FunctionName=function_name,
            InvocationType='RequestResponse',
            Payload=payload,
            Qualifier=alias_name
        )

    results = response['Payload'].read()  # payload is a 'StreamingBody'
    return results

@pytest.mark.aws
@pytest.mark.slow
@check_preconditions
def test_wire_unwire_new_events_s3(
        awsclient, vendored_folder, temp_bucket, cleanup_lambdas, cleanup_roles):
    log.info('running test_wire_unwire_new_events_s3')

    # create a lambda function
    temp_string = utils.random_string()
    lambda_name = 'jenkins_test_%s' % temp_string
    role_name = 'unittest_%s_lambda' % temp_string
    role_arn = create_lambda_role_helper(awsclient, role_name)
    cleanup_roles.append(role_name)
    create_lambda_helper(awsclient, lambda_name, role_arn,
                         './resources/sample_lambda/handler_counter.py',
                         lambda_handler='handler_counter.handle')

    events = [
        {
            "event_source": {
                "arn": "arn:aws:s3:::" + temp_bucket,
                "events": ['s3:ObjectCreated:*'],
                "suffix": ".gz"
            }
        }
    ]
    cleanup_lambdas.append((lambda_name, events))

    # wire the function with the bucket
    exit_code = wire(awsclient, events, lambda_name)
    assert exit_code == 0

    # put a file into the bucket
    awsclient.get_client('s3').put_object(
        ACL='public-read',
        Body=b'this is some content',
        Bucket=temp_bucket,
        Key='test_file.gz',
    )

    # validate function call
    time.sleep(20)  # sleep till the event arrived
    assert int(_get_count(awsclient, lambda_name)) == 1

    # unwire the function
    exit_code = unwire(awsclient, events, lambda_name)
    assert exit_code == 0

    # put in another file
    awsclient.get_client('s3').put_object(
        ACL='public-read',
        Body=b'this is some content',
        Bucket=temp_bucket,
        Key='test_file_2.gz',
    )

    # validate function not called
    time.sleep(10)
    assert int(_get_count(awsclient, lambda_name)) == 1

@pytest.mark.aws
@pytest.mark.slow
@check_preconditions
def test_wire_unwire_new_events_sns(
        awsclient, vendored_folder, cleanup_lambdas, cleanup_roles, temp_sns_topic):
    log.info('running test_wire_unwire_new_events_sns')

    # create a lambda function
    temp_string = utils.random_string()
    lambda_name = 'jenkins_test_%s' % temp_string
    role_name = 'unittest_%s_lambda' % temp_string
    role_arn = create_lambda_role_helper(awsclient, role_name)
    cleanup_roles.append(role_name)
    create_lambda_helper(awsclient, lambda_name, role_arn,
                         './resources/sample_lambda/handler_counter.py',
                         lambda_handler='handler_counter.handle')

    # schedule expressions:
    # http://docs.aws.amazon.com/lambda/latest/dg/tutorial-scheduled-events-schedule-expressions.html
    events = [
        {
            "event_source": {
                "arn": temp_sns_topic[1],
                "events": [
                    "sns:Publish"
                ]
            }
        }
    ]

    cleanup_lambdas.append((lambda_name, events))

    # wire the function with the bucket
    exit_code = wire(awsclient, events, lambda_name)
    assert exit_code == 0

    assert int(_get_count(awsclient, lambda_name)) == 0

    # send message via sns
    send_message(awsclient, temp_sns_topic[1], {"foo": "bar"})

    time.sleep(10)  # give a little time for the message to arrive
    assert int(_get_count(awsclient, lambda_name)) == 1

    # unwire the function
    exit_code = unwire(awsclient, events, lambda_name)
    assert exit_code == 0

@pytest.mark.aws
@check_preconditions
def test_event_source_lifecycle_s3(awsclient, vendored_folder, temp_lambda, temp_bucket):
    log.info('running test_event_source_lifecycle_s3')

    lambda_name = temp_lambda[0]

    # lookup lambda arn
    lambda_client = awsclient.get_client('lambda')
    alias_name = 'ACTIVE'
    lambda_arn = lambda_client.get_alias(FunctionName=lambda_name,
                                         Name=alias_name)['AliasArn']

    # define event source
    bucket_arn = 'arn:aws:s3:::' + temp_bucket
    evt_source = {
        'arn': bucket_arn, 'events': ['s3:ObjectCreated:*'],
        "suffix": ".gz"
    }

    # event source lifecycle
    _add_event_source(awsclient, evt_source, lambda_arn)
    status = _get_event_source_status(awsclient, evt_source, lambda_arn)
    assert status['EventSourceArn']
    _remove_event_source(awsclient, evt_source, lambda_arn)

@pytest.fixture(scope='function')  # 'function' or 'module'
def temp_sns_topic(awsclient):
    # create a bucket
    temp_string = utils.random_string()
    arn = create_topic(awsclient, temp_string)
    yield temp_string, arn
    # cleanup
    delete_topic(awsclient, arn)

@pytest.mark.aws
@check_preconditions
def test_event_source_lifecycle_sns(awsclient, vendored_folder, temp_lambda, temp_sns_topic):
    log.info('running test_event_source_lifecycle_sns')

    lambda_name = temp_lambda[0]

    # lookup lambda arn
    lambda_client = awsclient.get_client('lambda')
    alias_name = 'ACTIVE'
    lambda_arn = lambda_client.get_alias(FunctionName=lambda_name,
                                         Name=alias_name)['AliasArn']

    # define event source
    evt_source = {
        #"arn":  "arn:aws:sns:::your-event-topic-arn",
        "arn": temp_sns_topic[1],
        "events": [
            "sns:Publish"
        ]
    }

    # event source lifecycle
    _add_event_source(awsclient, evt_source, lambda_arn)
    status = _get_event_source_status(awsclient, evt_source, lambda_arn)
    assert status['EventSourceArn']
    _remove_event_source(awsclient, evt_source, lambda_arn)

@pytest.fixture(scope='function')  # 'function' or 'module'
def temp_kinesis(awsclient):
    # create a bucket
    temp_string = utils.random_string()
    create_stream(awsclient, temp_string)
    arn = describe_stream(awsclient, temp_string)['StreamARN']
    wait_for_stream_exists(awsclient, temp_string)
    yield temp_string, arn
    # cleanup
    delete_stream(awsclient, temp_string)

@pytest.mark.aws
@check_preconditions
def test_event_source_lifecycle_kinesis(awsclient, vendored_folder, temp_lambda, temp_kinesis):
    log.info('running test_event_source_lifecycle_kinesis')

    lambda_name = temp_lambda[0]

    # lookup lambda arn
    lambda_client = awsclient.get_client('lambda')
    alias_name = 'ACTIVE'
    lambda_arn = lambda_client.get_alias(FunctionName=lambda_name,
                                         Name=alias_name)['AliasArn']

    # define event source
    evt_source = {
        #"arn":  "arn:aws:dynamodb:us-east-1:1234554:table/YourTable/stream/2016-05-11T00:00:00.000",
        "arn": temp_kinesis[1],
        "starting_position": "TRIM_HORIZON",  # Supported values: TRIM_HORIZON, LATEST
        "batch_size": 50,  # Max: 1000
        "enabled": True  # Default is false
    }

    # event source lifecycle
    _add_event_source(awsclient, evt_source, lambda_arn)
    status = _get_event_source_status(awsclient, evt_source, lambda_arn)
    assert status['EventSourceArn']
    _remove_event_source(awsclient, evt_source, lambda_arn)

# gcdt tests do not yet support multi-region lambda deployments
'''
@pytest.mark.aws
@check_preconditions
def test_event_source_lifecycle_cloudfront(
        awsclient, vendored_folder, cleanup_lambdas_deprecated, cleanup_roles):
    log.info('running test_event_source_lifecycle_cloudfront')

    lambda_folder = './resources/sample_lambda_edge/'

    temp_string = utils.random_string()
    lambda_name = 'jenkins_test_sample-lambda-edge_' + temp_string
    role_name = 'unittest_%s_lambda' % temp_string
    role_arn = create_lambda_role_helper(awsclient, role_name)

    # create the function
    create_lambda_helper(awsclient, lambda_name, role_arn,
                         here(lambda_folder + 'index.js'),
                         lambda_handler='index.handler',
                         folders_from_file=[],
                         runtime='nodejs6.10'
                         )

    cleanup_roles.append(role_name)
    cleanup_lambdas_deprecated.append(lambda_name)

    # lookup lambda arn
    # us-east-1 is the only region that implements lambda@edge
    lambda_client = awsclient.get_client('lambda', region='us-east-1')
    alias_name = 'ACTIVE'
    lambda_arn = lambda_client.get_alias(FunctionName=lambda_name,
                                         Name=alias_name)['AliasArn']

    # define event source
    evt_source = {
        "arn": "arn:aws:cloudfront::420189626185:distribution/E1V934UN4EJGJA",
        "cache_behavior": "*",
        "cloudfront_event": "origin-request"
    }

    # event source lifecycle
    _add_event_source(awsclient, evt_source, lambda_arn)
    status = _get_event_source_status(awsclient, evt_source, lambda_arn)
    assert status['EventSourceArn']
    _remove_event_source(awsclient, evt_source, lambda_arn)
'''

@pytest.mark.aws
@check_preconditions
def test_event_source_lifecycle_cloudwatch_pattern(
        awsclient, vendored_folder, cleanup_lambdas_deprecated, cleanup_roles):
    log.info('running test_event_source_lifecycle_cloudwatch_pattern')

    lambda_folder = './resources/sample_lambda_event_pattern/'

    temp_string = utils.random_string()
    lambda_name = 'jenkins_test_sample-lambda-event-pattern_' + temp_string
    role_name = 'unittest_%s_lambda' % temp_string
    role_arn = create_lambda_role_helper(awsclient, role_name)

    # create the function
    create_lambda_helper(awsclient, lambda_name, role_arn,
                         here(lambda_folder + 'handler.py'),
                         lambda_handler='handler.handler',
                         folders_from_file=[],
                         runtime='python2.7'
                         )

    cleanup_roles.append(role_name)
    cleanup_lambdas_deprecated.append(lambda_name)

    # lookup lambda arn
    # us-east-1 is the only region that implements lambda@edge
    lambda_client = awsclient.get_client('lambda')
    alias_name = 'ACTIVE'
    lambda_arn = lambda_client.get_alias(FunctionName=lambda_name,
                                         Name=alias_name)['AliasArn']

    # define event source
    evt_source = {
        "name": "ssm_parameter_changed",
        "input_path": "$.detail",
        "pattern": {
            "source": [
                "aws.ssm"
            ],
            "detail-type": [
                "Parameter Store Change"
            ]
        }
    }

    # event source lifecycle
    _add_event_source(awsclient, evt_source, lambda_arn)
    status = _get_event_source_status(awsclient, evt_source, lambda_arn)
    assert status['EventSourceArn']
    _remove_event_source(awsclient, evt_source, lambda_arn)

@pytest.mark.aws
@pytest.mark.slow
@check_preconditions
def test_wire_unwire_new_events_cloudwatch_schedule(
        awsclient, vendored_folder, cleanup_lambdas, cleanup_roles):
    log.info('running test_wire_unwire_new_events_cloudwatch_schedule')

    # create a lambda function
    temp_string = utils.random_string()
    lambda_name = 'jenkins_test_%s' % temp_string
    role_name = 'unittest_%s_lambda' % temp_string
    role_arn = create_lambda_role_helper(awsclient, role_name)
    cleanup_roles.append(role_name)
    create_lambda_helper(awsclient, lambda_name, role_arn,
                         './resources/sample_lambda/handler_counter.py',
                         lambda_handler='handler_counter.handle')

    # schedule expressions:
    # http://docs.aws.amazon.com/lambda/latest/dg/tutorial-scheduled-events-schedule-expressions.html
    events = [
        {
            "event_source": {
                "name": "execute_backup",
                "schedule": "rate(1 minute)"
            }
        }
    ]
    cleanup_lambdas.append((lambda_name, events))

    # wire the function with the bucket
    exit_code = wire(awsclient, events, lambda_name)
    assert exit_code == 0

    assert int(_get_count(awsclient, lambda_name)) == 0

    time.sleep(70)  # sleep till scheduled event
    assert int(_get_count(awsclient, lambda_name)) == 1

    # unwire the function
    exit_code = unwire(awsclient, events, lambda_name)
    assert exit_code == 0

    time.sleep(70)
    assert int(_get_count(awsclient, lambda_name)) == 1

@pytest.mark.aws
@check_preconditions
def test_event_source_lifecycle_cloudwatch_schedule(awsclient, vendored_folder, temp_lambda):
    log.info('running test_event_source_lifecycle_cloudwatch_schedule')

    lambda_name = temp_lambda[0]

    # lookup lambda arn
    lambda_client = awsclient.get_client('lambda')
    alias_name = 'ACTIVE'
    lambda_arn = lambda_client.get_alias(FunctionName=lambda_name,
                                         Name=alias_name)['AliasArn']

    # define event source
    evt_source = {
        "name": "unittest_execute_backup",
        "schedule": "rate(1 minute)"
    }

    # event source lifecycle
    _add_event_source(awsclient, evt_source, lambda_arn)
    status = _get_event_source_status(awsclient, evt_source, lambda_arn)
    assert status['EventSourceArn']
    assert status['State'] == 'ENABLED'
    _remove_event_source(awsclient, evt_source, lambda_arn)

################################################################################
### DEPRECATED
################################################################################
# all test code below is deprecated (related to old ramuda wire implementation)
# DEPRECATED!!
@pytest.mark.aws
@check_preconditions
def test_deprecated_schedule_event_source(
        awsclient, vendored_folder, cleanup_lambdas_deprecated, cleanup_roles):
    log.info('running test_schedule_event_source')
    # include reading config from settings file
    config = {
        "lambda": {
            "events": {
                "timeSchedules": [
                    {
                        "ruleName": "unittest-dev-lambda-schedule",
                        "ruleDescription": "run every 1 minute",
                        "scheduleExpression": "rate(1 minute)"
                    }
                ]
            }
        }
    }

    # for time_event in time_event_sources:
    time_event = config['lambda'].get('events', []).get('timeSchedules', [])[0]
    rule_name = time_event.get('ruleName')
    rule_description = time_event.get('ruleDescription')
    schedule_expression = time_event.get('scheduleExpression')

    # now, I need a lambda function that registers the calls!!
    temp_string = utils.random_string()
    lambda_name = 'jenkins_test_%s' % temp_string
    role_name = 'unittest_%s_lambda' % temp_string
    role_arn = create_lambda_role_helper(awsclient, role_name)
    cleanup_roles.append(role_name)
    create_lambda_helper(awsclient, lambda_name, role_arn,
                         './resources/sample_lambda/handler_counter.py',
                         lambda_handler='handler_counter.handle')
    cleanup_lambdas_deprecated.append(lambda_name)

    # lookup lambda arn
    lambda_client = awsclient.get_client('lambda')
    alias_name = 'ACTIVE'
    lambda_arn = lambda_client.get_alias(FunctionName=lambda_name,
                                         Name=alias_name)['AliasArn']
    # create scheduled event source
    rule_arn = _lambda_add_time_schedule_event_source(
        awsclient, rule_name, rule_description, schedule_expression,
        lambda_arn
    )
    _lambda_add_invoke_permission(
        awsclient, lambda_name, 'events.amazonaws.com', rule_arn)

    time.sleep(180)  # wait for at least 2 invocations

    count = _get_count(awsclient, lambda_name)
    assert int(count) >= 2

# DEPRECATED!!
@pytest.mark.aws
@pytest.mark.slow
@check_preconditions
def test_deprecated_wire_unwire_lambda_with_s3(
        awsclient, vendored_folder, cleanup_lambdas_deprecated, cleanup_roles,
        temp_bucket):
    log.info('running test_wire_unwire_lambda_with_s3')

    # create a lambda function
    temp_string = utils.random_string()
    lambda_name = 'jenkins_test_%s' % temp_string
    role_name = 'unittest_%s_lambda' % temp_string
    role_arn = create_lambda_role_helper(awsclient, role_name)
    cleanup_roles.append(role_name)
    create_lambda_helper(awsclient, lambda_name, role_arn,
                         './resources/sample_lambda/handler_counter.py',
                         lambda_handler='handler_counter.handle')
    cleanup_lambdas_deprecated.append(lambda_name)

    bucket_name = temp_bucket
    config = {
        "lambda": {
            "events": {
                "s3Sources": [
                    {
                        "bucket": bucket_name,
                        "type": "s3:ObjectCreated:*",
                        "suffix": ".gz"
                    }
                ]
            }
        }
    }

    # wire the function with the bucket
    s3_event_sources = config['lambda'].get('events', []).get('s3Sources', [])
    time_event_sources = config['lambda'].get('events', []).get('timeSchedules',
                                                                [])
    exit_code = wire_deprecated(awsclient, lambda_name, s3_event_sources,
                                time_event_sources)
    assert exit_code == 0

    # put a file into the bucket
    awsclient.get_client('s3').put_object(
        ACL='public-read',
        Body=b'this is some content',
        Bucket=bucket_name,
        Key='test_file.gz',
    )

    # validate function call
    time.sleep(20)  # sleep till the event arrived
    assert int(_get_count(awsclient, lambda_name)) == 1

    # unwire the function
    exit_code = unwire_deprecated(awsclient, lambda_name, s3_event_sources,
                                  time_event_sources)
    assert exit_code == 0

    # put in another file
    awsclient.get_client('s3').put_object(
        ACL='public-read',
        Body=b'this is some content',
        Bucket=bucket_name,
        Key='test_file_2.gz',
    )

    # validate function not called
    time.sleep(10)
    assert int(_get_count(awsclient, lambda_name)) == 1


text:
//
//  UIColor+TTExt.m
//  TTLightKit
//
//  Created by 天智慧启 on 2017/5/15.
//  Copyright © 2017年 天智慧启. All rights reserved.
//

#import "UIColor+TTExt.h"

CGFloat colorComponentFrom(NSString *string, NSUInteger start, NSUInteger length) {
    NSString *substring = [string substringWithRange:NSMakeRange(start, length)];
    NSString *fullHex = length == 2 ? substring : [NSString stringWithFormat: @"%@%@", substring, substring];

    unsigned hexComponent;
    [[NSScanner scannerWithString: fullHex] scanHexInt: &hexComponent];
    return hexComponent / 255.0;
}

@implementation UIColor (TTExt)

/**
 *   用HexString 生成 UIColor
 *
 *  @param hexString   #RGB  #ARGB   #RRGGBB  #AARRGGBB 或者不带#
 */
+ (UIColor *)tt_colorWithHexString:(NSString *)hexString {
    return [self tt_colorWithHexString:hexString alpha:1.0f];
}

/**
 *   用HexString 生成 UIColor
 *
 *  @param hexString   #RGB  #ARGB   #RRGGBB  #AARRGGBB 或者不带#
 *  @param alpha 透明度
 */
+ (UIColor *)tt_colorWithHexString:(NSString *)hexString alpha:(CGFloat)alpha {
    CGFloat red, blue, green;

    NSString *colorString = [[hexString stringByReplacingOccurrencesOfString:@"#" withString:@""] uppercaseString];
    switch ([colorString length]) {
        case 3: // #RGB
            red   = colorComponentFrom(colorString, 0, 1);
            green = colorComponentFrom(colorString, 1, 1);
            blue  = colorComponentFrom(colorString, 2, 1);
            break;

        case 4: // #ARGB
//            alpha = colorComponentFrom(colorString, 0, 1);
            red   = colorComponentFrom(colorString, 1, 1);
            green = colorComponentFrom(colorString, 2, 1);
            blue  = colorComponentFrom(colorString, 3, 1);
            break;

        case 6: // #RRGGBB
//            alpha = 1.0f;
            red   = colorComponentFrom(colorString, 0, 2);
            green = colorComponentFrom(colorString, 2, 2);
            blue  = colorComponentFrom(colorString, 4, 2);
            break;

        case 8: // #AARRGGBB
//            alpha = colorComponentFrom(colorString, 0, 2);
            red   = colorComponentFrom(colorString, 2, 2);
            green = colorComponentFrom(colorString, 4, 2);
            blue  = colorComponentFrom(colorString, 6, 2);
            break;

        default:
            return nil;
    }
    return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}
/**
 *  当前UIColor用的HexString
 */
- (NSString *)tt_hexString {
    UIColor* color = self;
    if (CGColorGetNumberOfComponents(color.CGColor) < 4) {
        const CGFloat *components = CGColorGetComponents(color.CGColor);
        color = [UIColor colorWithRed:components[0]
                                green:components[0]
                                 blue:components[0]
                                alpha:components[1]];
    }
    if (CGColorSpaceGetModel(CGColorGetColorSpace(color.CGColor)) != kCGColorSpaceModelRGB) {
        return [NSString stringWithFormat:@"#FFFFFF"];
    }
    return [NSString stringWithFormat:@"#%02X%02X%02X", (int)((CGColorGetComponents(color.CGColor))[0]*255.0),
            (int)((CGColorGetComponents(color.CGColor))[1]*255.0),
            (int)((CGColorGetComponents(color.CGColor))[2]*255.0)];
}

/**
 *  当前UIColor用的RGB(255,255,255,1.0) 用纯数字
 */
+ (UIColor *)tt_colorWithWholeRed:(CGFloat)red
                            green:(CGFloat)green
                             blue:(CGFloat)blue
                            alpha:(CGFloat)alpha {
    return [UIColor colorWithRed:red/255.f
                           green:green/255.f
                            blue:blue/255.f
                           alpha:alpha];
}

/**
 *  @brief  随机颜色
 *
 *  @return UIColor
 */
+ (UIColor *)tt_randomColor {
    NSInteger aRedValue = arc4random() % 255;
    NSInteger aGreenValue = arc4random() % 255;
    NSInteger aBlueValue = arc4random() % 255;
    UIColor *randColor = [UIColor colorWithRed:aRedValue / 255.0f green:aGreenValue / 255.0f blue:aBlueValue / 255.0f alpha:1.0f];
    return randColor;
}

/**
 *  @brief  渐变颜色
 *
 *  @param c1     开始颜色
 *  @param c2     结束颜色
 *  @param height 渐变高度
 *
 *  @return 渐变颜色
 */
+ (UIColor*)tt_gradientFromColor:(UIColor*)c1 toColor:(UIColor*)c2 withHeight:(int)height {
    CGSize size = CGSizeMake(1, height);
    UIGraphicsBeginImageContextWithOptions(size, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();

    NSArray* colors = [NSArray arrayWithObjects:(id)c1.CGColor, (id)c2.CGColor, nil];
    CGGradientRef gradient = CGGradientCreateWithColors(colorspace, (__bridge CFArrayRef)colors, NULL);
    CGContextDrawLinearGradient(context, gradient, CGPointMake(0, 0), CGPointMake(0, size.height), 0);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    CGGradientRelease(gradient);
    CGColorSpaceRelease(colorspace);
    UIGraphicsEndImageContext();

    return [UIColor colorWithPatternImage:image];
}

@end