text:
package com.nowellpoint.client.model;

public class Callback {

	private String object;

	private String queryString;

	public Callback() {

	}

	public String getObject() {
		return object;
	}

	public void setObject(String object) {
		this.object = object;
	}

	public String getQueryString() {
		return queryString;
	}

	public void setQueryString(String queryString) {
		this.queryString = queryString;
	}
}

redpajama_set_name: RedPajamaGithub


text:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;

// Animation frame event params
[Serializable]
public class Uni2DAnimationFrameInfos
{
	// Use this to pass a string during the animation event
	public string stringInfo;

	// Use this to pass int during the animation event
	public int intInfo;

	// Use this to pass a float during the animation event
	public float floatInfo;

	// Use this to pass a custom object during the animation event
	public UnityEngine.Object objectInfo;

	// Is this event params is different from an event params
	public bool IsDifferentFrom(Uni2DAnimationFrameInfos a_rOtherEventParams)
	{
		return stringInfo != a_rOtherEventParams.stringInfo
			|| intInfo != a_rOtherEventParams.intInfo
			|| floatInfo != a_rOtherEventParams.floatInfo
			|| objectInfo != a_rOtherEventParams.objectInfo;
	}

	// Copy this event params to an other event params
	public void CopyTo(Uni2DAnimationFrameInfos a_rOtherEventParams)
	{
		a_rOtherEventParams.stringInfo = stringInfo;
		a_rOtherEventParams.intInfo = intInfo;
		a_rOtherEventParams.floatInfo = floatInfo;
		a_rOtherEventParams.objectInfo = objectInfo;
	}
}


text:
module.exports = {
    keywords: ["await","async","wait","task","inq","bound"],
    nonTerminalKeywords: ["task","wait","await"]
};


text:
@implementation CMSettingsCell

- (void)awakeFromNib {
    [super awakeFromNib];
}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)setCellType:(CMSettingsCellType)cellType
{
    switch (cellType)
    {
        case CMSettingsCellTypeSwitch:
        {
            self.settingsSwitch.hidden = NO;
        }
            break;

        case CMSettingsCellTypeSlider:
        {
            self.settingsSlider.minimumTrackTintColor = UIColorFromRGB(0x7961aa);
            self.settingsSlider.hidden = NO;
        }
            break;

        case CMSettingsCellTypeButton:
        {
            self.settingsButton.hidden = NO;
            if (self.buttonTitle)
            {
                [self.settingsButton setTitle:self.buttonTitle forState:UIControlStateNormal];
            }
        }
            break;

        case CMSettingsCellTypeLabel:
        {
            self.settingsLabel.hidden = NO;
            self.settingsLabel.textColor = UIColorFromRGB(0x7961aa);
        }
            break;

        default:
            break;
    }
}

@end


text:
//
//  SBTool.h
//  areaSelectionDemo
//
//  Created by 中海智融 on 2017/9/6.
//  Copyright © 2017年 sunny. All rights reserved.
//

#ifndef SBTool_h
#define SBTool_h

#import "UIView+FrameExtension.h"

#define CELL_DEFAULT_HEIGHT (45)
// CELL的ROW的文字起始位置
#define CELL_START_X (15.f)

/// 通过RGBA设置颜色,使用0x格式,如:RGBAAllColor(0xAABBCC, 0.5);
#define RGBAAllColor(rgb, a) [UIColor colorWithRed:((float)((rgb & 0xFF0000) >> 16))/255.0  \
green:((float)((rgb & 0xFF00) >> 8))/255.0     \
blue:((float)(rgb & 0xFF))/255.0              \
alpha:(a)/1.0]

/// 通过RGB设置颜色,使用0x格式,如:RGBAAllColor(0xAABBCC);
#define RGBAllColor(rgb) RGBAAllColor(rgb, 1.0)

#if __has_feature(objc_instancetype)

#undef	AS_SINGLETON
#define AS_SINGLETON

#undef	AS_SINGLETON
#define AS_SINGLETON( ... ) \
- (instancetype)sharedInstance; \
+ (instancetype)sharedInstance;

#undef	DEF_SINGLETON
#define DEF_SINGLETON \
- (instancetype)sharedInstance \
{ \
return [[self class] sharedInstance]; \
} \
+ (instancetype)sharedInstance \
{ \
static dispatch_once_t once; \
static id __singleton__; \
dispatch_once( &once, ^{ __singleton__ = [[self alloc] init]; } ); \
return __singleton__; \
}

#undef	DEF_SINGLETON
#define DEF_SINGLETON( ... ) \
- (instancetype)sharedInstance \
{ \
return [[self class] sharedInstance]; \
} \
+ (instancetype)sharedInstance \
{ \
static dispatch_once_t once; \
static id __singleton__; \
dispatch_once( &once, ^{ __singleton__ = [[self alloc] init]; } ); \
return __singleton__; \
}

#else	// #if __has_feature(objc_instancetype)

#undef	AS_SINGLETON
#define AS_SINGLETON( __class ) \
- (__class *)sharedInstance; \
+ (__class *)sharedInstance;

#undef	DEF_SINGLETON
#define DEF_SINGLETON( __class ) \
- (__class *)sharedInstance \
{ \
return [__class sharedInstance]; \
} \
+ (__class *)sharedInstance \
{ \
static dispatch_once_t once; \
static __class * __singleton__; \
dispatch_once( &once, ^{ __singleton__ = [[[self class] alloc] init]; } ); \
return __singleton__; \
}

#endif	// #if __has_feature(objc_instancetype)

// 判断obj是否为className类型
#define GMK_Object_Is_Class(obj,className) [obj isKindOfClass:[className class]]

/// 是否为NSString类型(单独处理NSMutableString)
#define GMK_Str_Class(str) [str isKindOfClass:[NSString class]]
#define GMK_mStr_Class(mstr) [mstr isKindOfClass:[NSMutableString class]]

/// 是否有效,不为空,且是NSString类型,且count值大于0(单独处理NSMutableString)
#define GMK_Str_Is_Valid(str) ((str) && (GMK_Str_Class(str)) && ([str length] > 0))
#define GMK_mStr_Is_Valid(mstr) ((mstr) && (GMK_mStr_Class(mstr)) && ([mstr length] > 0))

/// 是否无效,或为空,或不是NSString类型,或count值小于等于0(单独处理NSMutableString)
#define GMK_Str_Not_Valid(str) ((!str) || (!GMK_Str_Class(str)) || ([str length] <= 0))
#define GMK_mStr_Not_Valid(mstr) ((!mstr) || (!GMK_mStr_Class(mstr)) || ([mstr length] <= 0))

/// 格式化字符串
#define GMK_Str_Format(...) [NSString stringWithFormat:__VA_ARGS__]

/// nil保护,当为nil时,返回@"",避免一些Crash
#define GMK_Str_Protect(str) ((str) && (![str isKindOfClass:[NSNull class]]) ? (str) : (@""))

/// 是否NSArray类型(单独处理NSMutableArray)
#define GMK_Ary_Class(ary)   GMK_Object_Is_Class(ary, NSArray)
#define GMK_mAry_Class(mary) GMK_Object_Is_Class(mary,NSMutableArray)

/// 是否有效,不为空,且是NSArray类型,且count值大于0(单独处理NSMutableArray)
#define GMK_Ary_Is_Valid(ary) ((ary) && (GMK_Ary_Class(ary)) && ([ary count] > 0))
#define GMK_mAry_Is_Valid(mary) ((mary) && (GMK_mAry_Class(mary)) && ([mary count] > 0))

/// 是否无效,或为空,或不是NSArray类型,或count值小于等于0(单独处理NSMutableArray)
#define GMK_Ary_Not_Valid(ary) ((!ary) || (!GMK_Ary_Class(ary)) || ([ary count] <= 0))
#define GMK_mAry_Not_Valid(mary) ((!mary) || !(GMK_mAry_Class(mary)) || ([mary count] <= 0))

/// 是否NSDictionary类型(单独处理NSMutableDictionary)
#define GMK_Dic_Class(dic) [dic isKindOfClass:[NSDictionary class]]
#define GMK_mDic_Class(mdic) [mdic isKindOfClass:[NSMutableDictionary class]]

/// 是否有效,不为空,且是NSDictionary类型,且count值大于0(单独处理NSMutableDictionary)
#define GMK_Dic_Is_Valid(dic) ((dic) && (GMK_Dic_Class(dic)) && ([dic count] > 0))
#define GMK_mDic_Is_Valid(mdic) ((mdic) && (GMK_mDic_Class(mdic)) && (mdic.count > 0))

/// 是否无效,或为空,或不是NSDictionary类型,或count值小于等于0(单独处理NSMutableDictionary)
#define GMK_Dic_Not_Valid(dic) ((!dic) || (!GMK_Dic_Class(dic)) || ([dic count] <= 0))
#define GMK_mDic_Not_Valid(mdic) ((!mdic) || (!GMK_mDic_Class(mdic)) || (mdic.count <= 0))

#define GMK_AllocObj(cls)   [[cls alloc] init]

// releaseObj
#define GMK_Release(obj)          if(obj) { obj = nil;}
#define GMK_Release_View(v)       if(v) {[v removeFromSuperview]; v = nil;}

/** Weak--Strong**/
#define WeakSelf(weakSelf)                __weak __typeof(&*self)weakSelf = self;
#define WEAKSELF   WeakSelf(weakSelf)
//  weak--Obj
#define GMK_Weak_Obj(obj)         __weak typeof(obj) weak##obj = obj;

// instanceObj
#define GMK_Instance(obj , cls)   if(!obj) obj = [cls new];
#define GMK_Instance_GetObj(_obj , cls)  {GMK_Instance(_obj,cls); return _obj;}
#define GMK_Instance_Cell(cls ,identi) [[cls alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identi];

#define GMK_Color_Main_BG_White [UIColor whiteColor]
/// 主要背景色,所有页面,包括空页面,背景颜色
#define GMK_Color_Main_BG RGBAllColor(0xF2F2F2)

#define GMK_Color_Red_BiaoZhun RGBAllColor(0xff5c5c)
#define GMK_Color_333333 RGBAllColor(0x333333)
#define GMK_Color_666666 RGBAllColor(0x666666)
#define GMK_Color_999999 RGBAllColor(0x999999)

#define FONT_QuanJiao(fontSize) [UIFont systemFontOfSize:(fontSize)]

#define IMG_Name(name) [UIImage imageNamed:name]

#define screenW [[UIScreen mainScreen] bounds].size.width
#define screenH [[UIScreen mainScreen] bounds].size.height
#define kScreenOneScale (1.0 / [UIScreen mainScreen].scale)

#define kScreenWidth screenW
#define kScreenHeight screenH

// X、Y最大值
#define kMaxX(frame)  CGRectGetMaxX(frame)
#define kMaxY(frame)  CGRectGetMaxY(frame)

#define GMK_StringFromClass(cls)  NSStringFromClass([cls class])

#endif /* SBTool_h */


text:
package spark.embeddedserver.jetty.websocket;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.StatusCode;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;

@WebSocket
public class WebSocketTestClient {
    private final CountDownLatch closeLatch;

    public WebSocketTestClient() {
        closeLatch = new CountDownLatch(1);
    }

    public boolean awaitClose(int duration, TimeUnit unit) throws InterruptedException {
        return closeLatch.await(duration, unit);
    }

    @OnWebSocketClose
    public void onClose(int statusCode, String reason) {
        closeLatch.countDown();
    }

    @OnWebSocketConnect
    public void onConnect(Session session) throws IOException{
	session.getRemote().sendString("Hi Spark!");
	session.close(StatusCode.NORMAL, "Bye!");
    }
}


text:
class Profile;

// The delegate to fetch bookmarks information for the Android native
// bookmark page. This fetches the bookmarks, title, urls, folder
// hierarchy.
class BookmarksBridge : public BaseBookmarkModelObserver,
                        public ManagedBookmarksShim::Observer,
                        public PartnerBookmarksShim::Observer {
 public:
  BookmarksBridge(JNIEnv* env, jobject obj, jobject j_profile);
  void Destroy(JNIEnv*, jobject);

  static bool RegisterBookmarksBridge(JNIEnv* env);

  void GetBookmarksForFolder(JNIEnv* env,
                             jobject obj,
                             jobject j_folder_id_obj,
                             jobject j_callback_obj,
                             jobject j_result_obj);

  void GetCurrentFolderHierarchy(JNIEnv* env,
                                 jobject obj,
                                 jobject j_folder_id_obj,
                                 jobject j_callback_obj,
                                 jobject j_result_obj);

  void DeleteBookmark(JNIEnv* env,
                      jobject obj,
                      jobject j_bookmark_id_obj);

  void MoveBookmark(JNIEnv* env,
                    jobject obj,
                    jobject j_bookmark_id_obj,
                    jobject j_parent_id_obj,
                    jint index);

 private:
  virtual ~BookmarksBridge();

  base::android::ScopedJavaLocalRef<jobject> CreateJavaBookmark(
      const BookmarkNode* node);
  void ExtractBookmarkNodeInformation(
      const BookmarkNode* node,
      jobject j_result_obj);
  const BookmarkNode* GetNodeByID(long node_id, int type);
  const BookmarkNode* GetFolderWithFallback(long folder_id, int type);
  // Returns true if |node| can be modified by the user.
  bool IsEditable(const BookmarkNode* node) const;
  const BookmarkNode* GetParentNode(const BookmarkNode* node);
  int GetBookmarkType(const BookmarkNode* node);
  base::string16 GetTitle(const BookmarkNode* node) const;
  bool IsReachable(const BookmarkNode* node) const;
  bool IsLoaded() const;
  bool IsFolderAvailable(const BookmarkNode* folder) const;
  void NotifyIfDoneLoading();

  // Override BaseBookmarkModelObserver.
  // Called when there are changes to the bookmark model that don't trigger
  // any of the other callback methods. For example, this is called when
  // managed or partner bookmarks change.
  virtual void BookmarkModelChanged() OVERRIDE;
  virtual void BookmarkModelLoaded(BookmarkModel* model,
                                   bool ids_reassigned) OVERRIDE;
  virtual void BookmarkModelBeingDeleted(BookmarkModel* model) OVERRIDE;
  virtual void BookmarkNodeMoved(BookmarkModel* model,
                                 const BookmarkNode* old_parent,
                                 int old_index,
                                 const BookmarkNode* new_parent,
                                 int new_index) OVERRIDE;
  virtual void BookmarkNodeAdded(BookmarkModel* model,
                                 const BookmarkNode* parent,
                                 int index) OVERRIDE;
  virtual void BookmarkNodeRemoved(BookmarkModel* model,
                                   const BookmarkNode* parent,
                                   int old_index,
                                   const BookmarkNode* node) OVERRIDE;
  virtual void BookmarkNodeChanged(BookmarkModel* model,
                                   const BookmarkNode* node) OVERRIDE;
  virtual void BookmarkNodeChildrenReordered(BookmarkModel* model,
                                             const BookmarkNode* node) OVERRIDE;
  virtual void ExtensiveBookmarkChangesBeginning(BookmarkModel* model) OVERRIDE;
  virtual void ExtensiveBookmarkChangesEnded(BookmarkModel* model) OVERRIDE;

  // Override ManagedBookmarksShim::Observer
  virtual void OnManagedBookmarksChanged() OVERRIDE;

  // Override PartnerBookmarksShim::Observer
  virtual void PartnerShimChanged(PartnerBookmarksShim* shim) OVERRIDE;
  virtual void PartnerShimLoaded(PartnerBookmarksShim* shim) OVERRIDE;
  virtual void ShimBeingDeleted(PartnerBookmarksShim* shim) OVERRIDE;

  Profile* profile_;
  JavaObjectWeakGlobalRef weak_java_ref_;
  BookmarkModel* bookmark_model_;  // weak

  scoped_ptr<ManagedBookmarksShim> managed_bookmarks_shim_;

  // Information about the Partner bookmarks (must check for IsLoaded()).
  // This is owned by profile.
  PartnerBookmarksShim* partner_bookmarks_shim_;

  DISALLOW_COPY_AND_ASSIGN(BookmarksBridge);
};

#endif  // CHROME_BROWSER_ANDROID_BOOKMARKS_BOOKMARKS_BRIDGE_H_


text:
<doxygenlayout version="1.0">
  <!-- Generated by doxygen 1.8.3.1 -->
  <!-- Navigation index tabs for HTML output -->
  <navindex>
    <tab type="mainpage" visible="yes" title=""/>
    <tab type="user" url="@ref tutorial" title="Tutorial"/>
    <tab type="user" url="@ref devel" title="Development"/>
    <tab type="classlist" visible="yes" title="Reference Manual" intro=""/>
    <tab type="user" url="https://github.com/OpenGP/OpenGP/issues" visible="yes" title="Report Bug" intro=""/>
    <!-- Disabled -->
    <tab type="pages" visible="no" title="Related Pages" intro=""/>
    <tab type="modules" visible="no" title="" intro=""/>
    <tab type="namespaces" visible="no" title="">
      <tab type="namespacelist" visible="yes" title="" intro=""/>
      <tab type="namespacemembers" visible="yes" title="" intro=""/>
    </tab>
    <tab type="files" visible="no" title="">
      <tab type="filelist" visible="no" title="" intro=""/>
      <tab type="globals" visible="no" title="" intro=""/>
    </tab>
    <tab type="examples" visible="no" title="" intro=""/>
  </navindex>

  <!-- Layout definition for a class page -->
  <class>
    <briefdescription visible="yes"/>
    <includes visible="$SHOW_INCLUDE_FILES"/>
    <inheritancegraph visible="$CLASS_GRAPH"/>
    <collaborationgraph visible="$COLLABORATION_GRAPH"/>
    <memberdecl>
      <nestedclasses visible="yes" title=""/>
      <publictypes title=""/>
      <publicslots title=""/>
      <signals title=""/>
      <publicmethods title=""/>
      <publicstaticmethods title=""/>
      <publicattributes title=""/>
      <publicstaticattributes title=""/>
      <protectedtypes title=""/>
      <protectedslots title=""/>
      <protectedmethods title=""/>
      <protectedstaticmethods title=""/>
      <protectedattributes title=""/>
      <protectedstaticattributes title=""/>
      <packagetypes title=""/>
      <packagemethods title=""/>
      <packagestaticmethods title=""/>
      <packageattributes title=""/>
      <packagestaticattributes title=""/>
      <properties title=""/>
      <events title=""/>
      <privatetypes title=""/>
      <privateslots title=""/>
      <privatemethods title=""/>
      <privatestaticmethods title=""/>
      <privateattributes title=""/>
      <privatestaticattributes title=""/>
      <friends title=""/>
      <related title="" subtitle=""/>
      <membergroups visible="yes"/>
    </memberdecl>
    <detaileddescription title=""/>
    <memberdef>
      <inlineclasses title=""/>
      <typedefs title=""/>
      <enums title=""/>
      <constructors title=""/>
      <functions title=""/>
      <related title=""/>
      <variables title=""/>
      <properties title=""/>
      <events title=""/>
    </memberdef>
    <allmemberslink visible="yes"/>
    <usedfiles visible="$SHOW_USED_FILES"/>
    <authorsection visible="yes"/>
  </class>

  <!-- Layout definition for a namespace page -->
  <namespace>
    <briefdescription visible="yes"/>
    <memberdecl>
      <nestednamespaces visible="yes" title=""/>
      <classes visible="yes" title=""/>
      <typedefs title=""/>
      <enums title=""/>
      <functions title=""/>
      <variables title=""/>
      <membergroups visible="yes"/>
    </memberdecl>
    <detaileddescription title=""/>
    <memberdef>
      <inlineclasses title=""/>
      <typedefs title=""/>
      <enums title=""/>
      <functions title=""/>
      <variables title=""/>
    </memberdef>
    <authorsection visible="yes"/>
  </namespace>

  <!-- Layout definition for a file page -->
  <file>
    <briefdescription visible="yes"/>
    <includes visible="$SHOW_INCLUDE_FILES"/>
    <includegraph visible="$INCLUDE_GRAPH"/>
    <includedbygraph visible="$INCLUDED_BY_GRAPH"/>
    <sourcelink visible="yes"/>
    <memberdecl>
      <classes visible="yes" title=""/>
      <namespaces visible="yes" title=""/>
      <defines title=""/>
      <typedefs title=""/>
      <enums title=""/>
      <functions title=""/>
      <variables title=""/>
      <membergroups visible="yes"/>
    </memberdecl>
    <detaileddescription title=""/>
    <memberdef>
      <inlineclasses title=""/>
      <defines title=""/>
      <typedefs title=""/>
      <enums title=""/>
      <functions title=""/>
      <variables title=""/>
    </memberdef>
    <authorsection/>
  </file>

  <!-- Layout definition for a group page -->
  <group>
    <briefdescription visible="yes"/>
    <groupgraph visible="$GROUP_GRAPHS"/>
    <memberdecl>
      <nestedgroups visible="yes" title=""/>
      <dirs visible="yes" title=""/>
      <files visible="yes" title=""/>
      <namespaces visible="yes" title=""/>
      <classes visible="yes" title=""/>
      <defines title=""/>
      <typedefs title=""/>
      <enums title=""/>
      <enumvalues title=""/>
      <functions title=""/>
      <variables title=""/>
      <signals title=""/>
      <publicslots title=""/>
      <protectedslots title=""/>
      <privateslots title=""/>
      <events title=""/>
      <properties title=""/>
      <friends title=""/>
      <membergroups visible="yes"/>
    </memberdecl>
    <detaileddescription title=""/>
    <memberdef>
      <pagedocs/>
      <inlineclasses title=""/>
      <defines title=""/>
      <typedefs title=""/>
      <enums title=""/>
      <enumvalues title=""/>
      <functions title=""/>
      <variables title=""/>
      <signals title=""/>
      <publicslots title=""/>
      <protectedslots title=""/>
      <privateslots title=""/>
      <events title=""/>
      <properties title=""/>
      <friends title=""/>
    </memberdef>
    <authorsection visible="yes"/>
  </group>

  <!-- Layout definition for a directory page -->
  <directory>
    <briefdescription visible="yes"/>
    <directorygraph visible="yes"/>
    <memberdecl>
      <dirs visible="yes"/>
      <files visible="yes"/>
    </memberdecl>
    <detaileddescription title=""/>
  </directory>
</doxygenlayout>


text:
@interface Project_RootViewController ()
@property (strong, nonatomic) XTSegmentControl *mySegmentControl;
@property (strong, nonatomic) iCarousel *myCarousel;
@property (strong, nonatomic) NSMutableDictionary *myProjectsDict;
@property (assign, nonatomic) NSInteger oldSelectedIndex;
@end

@implementation Project_RootViewController

#pragma mark TabBar
- (void)tabBarItemClicked{
    if (_myCarousel.currentItemView && [_myCarousel.currentItemView isKindOfClass:[ProjectListView class]]) {
        ProjectListView *listView = (ProjectListView *)_myCarousel.currentItemView;
        [listView tabBarItemClicked];
    }
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [[UnReadManager shareManager] addObserver:self forKeyPath:kUnReadKey_project_update_count options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
    }
    return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"项目";

    _myProjectsDict = [[NSMutableDictionary alloc] initWithCapacity:3];
    //添加myCarousel
    _myCarousel = ({
        iCarousel *icarousel = [[iCarousel alloc] init];
        icarousel.dataSource = self;
        icarousel.delegate = self;
        icarousel.decelerationRate = 1.0;
        icarousel.scrollSpeed = 1.0;
        icarousel.type = iCarouselTypeLinear;
        icarousel.pagingEnabled = YES;
        icarousel.clipsToBounds = YES;
        icarousel.bounceDistance = 0.2;
        [self.view addSubview:icarousel];
        [icarousel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(kMySegmentControl_Height, 0, 0, 0));
        }];
        icarousel;
    });

    //添加滑块
    __weak typeof(_myCarousel) weakCarousel = _myCarousel;
    _mySegmentControl = [[XTSegmentControl alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, kMySegmentControl_Height) Items:@[@"全部项目", @"我参与的", @"我创建的"] selectedBlock:^(NSInteger index) {
        if (index == _oldSelectedIndex) {
            return;
        }
        _oldSelectedIndex = index;
        [weakCarousel scrollToItemAtIndex:index animated:NO];
    }];
    [self.view addSubview:_mySegmentControl];

    _oldSelectedIndex = 0;
    [self refreshBadgeTip];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (_myCarousel) {
        ProjectListView *listView = (ProjectListView *)_myCarousel.currentItemView;
        if (listView) {
            [listView refreshToQueryData];
        }
    }
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [[UnReadManager shareManager] updateUnRead];
}

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

- (void)dealloc{
    [[UnReadManager shareManager] removeObserver:self forKeyPath:kUnReadKey_project_update_count];
}

#pragma mark iCarousel M
- (NSUInteger)numberOfItemsInCarousel:(iCarousel *)carousel{
    return 3;
}
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view{
    Projects *curPros = [_myProjectsDict objectForKey:[NSNumber numberWithUnsignedInteger:index]];
    if (!curPros) {
        curPros = [Projects projectsWithType:index];
        [_myProjectsDict setObject:curPros forKey:[NSNumber numberWithUnsignedInteger:index]];
    }
    ProjectListView *listView = (ProjectListView *)view;
    if (listView) {
        [listView setProjects:curPros];
    }else{
        __weak Project_RootViewController *weakSelf = self;
        listView = [[ProjectListView alloc] initWithFrame:carousel.bounds projects:curPros block:^(Project *project) {
            ProjectViewController *vc = [[ProjectViewController alloc] init];
            vc.myProject = project;
            [weakSelf.navigationController pushViewController:vc animated:YES];

            [[Coding_NetAPIManager sharedManager] request_Project_UpdateVisit_WithObj:project andBlock:^(id data, NSError *error) {
                if (data) {
                    project.un_read_activities_count = [NSNumber numberWithInteger:0];
                    [listView refreshUI];
                }
            }];
            NSLog(@"\n=====%@", project.name);
        } tabBarHeight:CGRectGetHeight(self.rdv_tabBarController.tabBar.frame)];
    }

    return listView;
}

- (void)carouselDidScroll:(iCarousel *)carousel{
    [self.view endEditing:YES];
    if (_mySegmentControl) {
        float offset = carousel.scrollOffset;
        if (offset > 0) {
            [_mySegmentControl moveIndexWithProgress:offset];
        }
    }
}

- (void)carouselDidEndScrollingAnimation:(iCarousel *)carousel
{
    if (_mySegmentControl) {
        [_mySegmentControl endMoveIndex:carousel.currentItemIndex];
    }
    if (_oldSelectedIndex != carousel.currentItemIndex) {
        _oldSelectedIndex = carousel.currentItemIndex;
        ProjectListView *curView = (ProjectListView *)carousel.currentItemView;
        [curView refreshToQueryData];
    }
}

#pragma mark KVO_UnRead
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if([keyPath isEqualToString:kUnReadKey_project_update_count]){
        [self refreshBadgeTip];
    }
}

- (void)refreshBadgeTip{
    NSString *badgeTip = @"";
    NSNumber *project_update_count = [UnReadManager shareManager].project_update_count;
    if (project_update_count.integerValue > 0) {
        badgeTip = kBadgeTipStr;
//        if (project_update_count.integerValue > 99) {
//            badgeTip = @"99+";
//        }else{
//            badgeTip = project_update_count.stringValue;
//        }
    }
    [self.rdv_tabBarItem setBadgeValue:badgeTip];
}

@end


text:
import numpy as np
import os.path as op
import datetime
import calendar

from .utils import _load_mne_locs, _read_pos
from ...utils import logger, warn, verbose, _check_fname
from ..utils import _read_segments_file
from ..base import BaseRaw
from ..meas_info import _empty_info
from .._digitization import _make_dig_points, DigPoint
from ..constants import FIFF
from ...transforms import get_ras_to_neuromag_trans, apply_trans, Transform

@verbose
def read_raw_artemis123(input_fname, preload=False, verbose=None,
                        pos_fname=None, add_head_trans=True):
    """Read Artemis123 data as raw object.

    Parameters
    ----------
    input_fname : str
        Path to the data file (extension ``.bin``). The header file with the
        same file name stem and an extension ``.txt`` is expected to be found
        in the same directory.
    %(preload)s
    %(verbose)s
    pos_fname : str or None (default None)
        If not None, load digitized head points from this file.
    add_head_trans : bool (default True)
        If True attempt to perform initial head localization. Compute initial
        device to head coordinate transform using HPI coils. If no
        HPI coils are in info['dig'] hpi coils are assumed to be in canonical
        order of fiducial points (nas, rpa, lpa).

    Returns
    -------
    raw : instance of Raw
        A Raw object containing the data.

    See Also
    --------
    mne.io.Raw : Documentation of attribute and methods.
    """
    return RawArtemis123(input_fname, preload=preload, verbose=verbose,
                         pos_fname=pos_fname, add_head_trans=add_head_trans)

def _get_artemis123_info(fname, pos_fname=None):
    """Generate info struct from artemis123 header file."""
    fname = op.splitext(fname)[0]
    header = fname + '.txt'

    logger.info('Reading header...')

    # key names for artemis channel info...
    chan_keys = ['name', 'scaling', 'FLL_Gain', 'FLL_Mode', 'FLL_HighPass',
                 'FLL_AutoReset', 'FLL_ResetLock']

    header_info = dict()
    header_info['filter_hist'] = []
    header_info['comments'] = ''
    header_info['channels'] = []

    with open(header, 'r') as fid:
        # section flag
        # 0 - None
        # 1 - main header
        # 2 - channel header
        # 3 - comments
        # 4 - length
        # 5 - filtering History
        sectionFlag = 0
        for line in fid:
            # skip emptylines or header line for channel info
            if ((not line.strip()) or
               (sectionFlag == 2 and line.startswith('DAQ Map'))):
                continue

            # set sectionFlag
            if line.startswith('<end'):
                sectionFlag = 0
            elif line.startswith("<start main header>"):
                sectionFlag = 1
            elif line.startswith("<start per channel header>"):
                sectionFlag = 2
            elif line.startswith("<start comments>"):
                sectionFlag = 3
            elif line.startswith("<start length>"):
                sectionFlag = 4
            elif line.startswith("<start filtering history>"):
                sectionFlag = 5
            else:
                # parse header info lines
                # part of main header - lines are name value pairs
                if sectionFlag == 1:
                    values = line.strip().split('\t')
                    if len(values) == 1:
                        values.append('')
                    header_info[values[0]] = values[1]
                # part of channel header - lines are Channel Info
                elif sectionFlag == 2:
                    values = line.strip().split('\t')
                    if len(values) != 7:
                        raise IOError('Error parsing line \n\t:%s\n' % line +
                                      'from file %s' % header)
                    tmp = dict()
                    for k, v in zip(chan_keys, values):
                        tmp[k] = v
                    header_info['channels'].append(tmp)
                elif sectionFlag == 3:
                    header_info['comments'] = '%s%s' \
                        % (header_info['comments'], line.strip())
                elif sectionFlag == 4:
                    header_info['num_samples'] = int(line.strip())
                elif sectionFlag == 5:
                    header_info['filter_hist'].append(line.strip())

    for k in ['Temporal Filter Active?', 'Decimation Active?',
              'Spatial Filter Active?']:
        if(header_info[k] != 'FALSE'):
            warn('%s - set to but is not supported' % k)
    if(header_info['filter_hist']):
        warn('Non-Empty Filter history found, BUT is not supported' % k)

    # build mne info struct
    info = _empty_info(float(header_info['DAQ Sample Rate']))

    # Attempt to get time/date from fname
    # Artemis123 files saved from the scanner observe the following
    # naming convention 'Artemis_Data_YYYY-MM-DD-HHh-MMm_[chosen by user].bin'
    try:
        date = datetime.datetime.strptime(
            op.basename(fname).split('_')[2], '%Y-%m-%d-%Hh-%Mm')
        meas_date = (calendar.timegm(date.utctimetuple()), 0)
    except Exception:
        meas_date = None

    # build subject info must be an integer (as per FIFF)
    try:
        subject_info = {'id': int(header_info['Subject ID'])}
    except ValueError:
        subject_info = {'id': 0}

    # build description
    desc = ''
    for k in ['Purpose', 'Notes']:
        desc += '{} : {}\n'.format(k, header_info[k])
    desc += 'Comments : {}'.format(header_info['comments'])

    info.update({'meas_date': meas_date,
                 'description': desc,
                 'subject_info': subject_info,
                 'proj_name': header_info['Project Name']})

    # Channel Names by type
    ref_mag_names = ['REF_001', 'REF_002', 'REF_003',
                     'REF_004', 'REF_005', 'REF_006']

    ref_grad_names = ['REF_007', 'REF_008', 'REF_009',
                      'REF_010', 'REF_011', 'REF_012']

    # load mne loc dictionary
    loc_dict = _load_mne_locs()
    info['chs'] = []
    info['bads'] = []

    for i, chan in enumerate(header_info['channels']):
        # build chs struct
        t = {'cal': float(chan['scaling']), 'ch_name': chan['name'],
             'logno': i + 1, 'scanno': i + 1, 'range': 1.0,
             'unit_mul': FIFF.FIFF_UNITM_NONE,
             'coord_frame': FIFF.FIFFV_COORD_DEVICE}
        # REF_018 has a zero cal which can cause problems. Let's set it to
        # a value of another ref channel to make writers/readers happy.
        if t['cal'] == 0:
            t['cal'] = 4.716e-10
            info['bads'].append(t['ch_name'])
        t['loc'] = loc_dict.get(chan['name'], np.zeros(12))

        if (chan['name'].startswith('MEG')):
            t['coil_type'] = FIFF.FIFFV_COIL_ARTEMIS123_GRAD
            t['kind'] = FIFF.FIFFV_MEG_CH
            # While gradiometer units are T/m, the meg sensors referred to as
            # gradiometers report the field difference between 2 pick-up coils.
            # Therefore the units of the measurements should be T
            # *AND* the baseline (difference between pickup coils)
            # should not be used in leadfield / forwardfield computations.
            t['unit'] = FIFF.FIFF_UNIT_T
            t['unit_mul'] = FIFF.FIFF_UNITM_F

        # 3 axis referance magnetometers
        elif (chan['name'] in ref_mag_names):
            t['coil_type'] = FIFF.FIFFV_COIL_ARTEMIS123_REF_MAG
            t['kind'] = FIFF.FIFFV_REF_MEG_CH
            t['unit'] = FIFF.FIFF_UNIT_T
            t['unit_mul'] = FIFF.FIFF_UNITM_F

        # reference gradiometers
        elif (chan['name'] in ref_grad_names):
            t['coil_type'] = FIFF.FIFFV_COIL_ARTEMIS123_REF_GRAD
            t['kind'] = FIFF.FIFFV_REF_MEG_CH
            # While gradiometer units are T/m, the meg sensors referred to as
            # gradiometers report the field difference between 2 pick-up coils.
            # Therefore the units of the measurements should be T
            # *AND* the baseline (difference between pickup coils)
            # should not be used in leadfield / forwardfield computations.
            t['unit'] = FIFF.FIFF_UNIT_T
            t['unit_mul'] = FIFF.FIFF_UNITM_F

        # other reference channels are unplugged and should be ignored.
        elif (chan['name'].startswith('REF')):
            t['coil_type'] = FIFF.FIFFV_COIL_NONE
            t['kind'] = FIFF.FIFFV_MISC_CH
            t['unit'] = FIFF.FIFF_UNIT_V
            info['bads'].append(t['ch_name'])

        elif (chan['name'].startswith(('AUX', 'TRG', 'MIO'))):
            t['coil_type'] = FIFF.FIFFV_COIL_NONE
            t['unit'] = FIFF.FIFF_UNIT_V
            if (chan['name'].startswith('TRG')):
                t['kind'] = FIFF.FIFFV_STIM_CH
            else:
                t['kind'] = FIFF.FIFFV_MISC_CH
        else:
            raise ValueError('Channel does not match expected' +
                             ' channel Types:"%s"' % chan['name'])

        # incorporate multiplier (unit_mul) into calibration
        t['cal'] *= 10 ** t['unit_mul']
        t['unit_mul'] = FIFF.FIFF_UNITM_NONE

        # append this channel to the info
        info['chs'].append(t)
        if chan['FLL_ResetLock'] == 'TRUE':
            info['bads'].append(t['ch_name'])

    # reduce info['bads'] to unique set
    info['bads'] = list(set(info['bads']))

    # HPI information
    # print header_info.keys()
    hpi_sub = dict()
    # Don't know what event_channel is don't think we have it HPIs are either
    # always on or always off.
    # hpi_sub['event_channel'] = ???
    hpi_sub['hpi_coils'] = [dict(), dict(), dict(), dict()]
    hpi_coils = [dict(), dict(), dict(), dict()]
    drive_channels = ['MIO_001', 'MIO_003', 'MIO_009', 'MIO_011']
    key_base = 'Head Tracking %s %d'

    # set default HPI frequencies
    if info['sfreq'] == 1000:
        default_freqs = [140, 150, 160, 40]
    else:
        default_freqs = [700, 750, 800, 40]

    for i in range(4):
        # build coil structure
        hpi_coils[i]['number'] = i + 1
        hpi_coils[i]['drive_chan'] = drive_channels[i]
        this_freq = header_info.pop(key_base % ('Frequency', i + 1),
                                    default_freqs[i])
        hpi_coils[i]['coil_freq'] = this_freq

        # check if coil is on
        if header_info[key_base % ('Channel', i + 1)] == 'OFF':
            hpi_sub['hpi_coils'][i]['event_bits'] = [0]
        else:
            hpi_sub['hpi_coils'][i]['event_bits'] = [256]

    info['hpi_subsystem'] = hpi_sub
    info['hpi_meas'] = [{'hpi_coils': hpi_coils}]

    # read in digitized points if supplied
    if pos_fname is not None:
        info['dig'] = _read_pos(pos_fname)
    else:
        info['dig'] = []

    info._update_redundant()
    return info, header_info

class RawArtemis123(BaseRaw):
    """Raw object from Artemis123 file.

    Parameters
    ----------
    input_fname : str
        Path to the Artemis123 data file (ending in ``'.bin'``).
    %(preload)s
    %(verbose)s

    See Also
    --------
    mne.io.Raw : Documentation of attribute and methods.
    """

    @verbose
    def __init__(self, input_fname, preload=False, verbose=None,
                 pos_fname=None, add_head_trans=True):  # noqa: D102
        from scipy.spatial.distance import cdist
        from ...chpi import (compute_chpi_amplitudes, compute_chpi_locs,
                             _fit_coil_order_dev_head_trans)
        input_fname = _check_fname(input_fname, 'read', True, 'input_fname')
        fname, ext = op.splitext(input_fname)
        if ext == '.txt':
            input_fname = fname + '.bin'
        elif ext != '.bin':
            raise RuntimeError('Valid artemis123 files must end in "txt"' +
                               ' or ".bin".')

        if not op.exists(input_fname):
            raise RuntimeError('%s - Not Found' % input_fname)

        info, header_info = _get_artemis123_info(input_fname,
                                                 pos_fname=pos_fname)

        last_samps = [header_info.get('num_samples', 1) - 1]

        super(RawArtemis123, self).__init__(
            info, preload, filenames=[input_fname], raw_extras=[header_info],
            last_samps=last_samps, orig_format=np.float32,
            verbose=verbose)

        if add_head_trans:
            n_hpis = 0
            for d in info['hpi_subsystem']['hpi_coils']:
                if d['event_bits'] == [256]:
                    n_hpis += 1
            if n_hpis < 3:
                warn('%d HPIs active. At least 3 needed to perform' % n_hpis +
                     'head localization\n *NO* head localization performed')
            else:
                # Localized HPIs using the 1st 250 milliseconds of data.
                info['hpi_results'] = [
                    dict(
                        dig_points=[dict(
                            r=np.zeros(3), coord_frame=FIFF.FIFFV_COORD_DEVICE,
                            ident=ii + 1) for ii in range(n_hpis)],
                        coord_trans=Transform('meg', 'head'))]
                coil_amplitudes = compute_chpi_amplitudes(
                    self, tmin=0, tmax=0.25, t_window=0.25, t_step_min=0.25)
                assert len(coil_amplitudes['times']) == 1
                coil_locs = compute_chpi_locs(self.info, coil_amplitudes)
                info['hpi_results'] = None
                hpi_g = coil_locs['gofs'][0]
                hpi_dev = coil_locs['rrs'][0]

                # only use HPI coils with localizaton goodness_of_fit > 0.98
                bad_idx = []
                for i, g in enumerate(hpi_g):
                    msg = 'HPI coil %d - location goodness of fit (%0.3f)'
                    if g < 0.98:
                        bad_idx.append(i)
                        msg += ' *Removed from coregistration*'
                    logger.info(msg % (i + 1, g))
                hpi_dev = np.delete(hpi_dev, bad_idx, axis=0)
                hpi_g = np.delete(hpi_g, bad_idx, axis=0)

                if pos_fname is not None:
                    # Digitized HPI points are needed.
                    hpi_head = np.array([d['r']
                                         for d in self.info.get('dig', [])
                                         if d['kind'] == FIFF.FIFFV_POINT_HPI])

                    if (len(hpi_head) != len(hpi_dev)):
                        mesg = ("number of digitized (%d) and " +
                                "active (%d) HPI coils are " +
                                "not the same.")
                        raise RuntimeError(mesg % (len(hpi_head),
                                                   len(hpi_dev)))

                    # compute initial head to dev transform and hpi ordering
                    head_to_dev_t, order, trans_g = \
                        _fit_coil_order_dev_head_trans(hpi_dev, hpi_head)

                    # set the device to head transform
                    self.info['dev_head_t'] = \
                        Transform(FIFF.FIFFV_COORD_DEVICE,
                                  FIFF.FIFFV_COORD_HEAD, head_to_dev_t)

                    # add hpi_meg_dev to dig...
                    for idx, point in enumerate(hpi_dev):
                        d = {'r': point, 'ident': idx + 1,
                             'kind': FIFF.FIFFV_POINT_HPI,
                             'coord_frame': FIFF.FIFFV_COORD_DEVICE}
                        self.info['dig'].append(DigPoint(d))

                    dig_dists = cdist(hpi_head[order], hpi_head[order])
                    dev_dists = cdist(hpi_dev, hpi_dev)
                    tmp_dists = np.abs(dig_dists - dev_dists)
                    dist_limit = tmp_dists.max() * 1.1

                    msg = 'HPI-Dig corrregsitration\n'
                    msg += '\tGOF : %0.3f\n' % trans_g
                    msg += '\tMax Coil Error : %0.3f cm\n' % (100 *
                                                              tmp_dists.max())
                    logger.info(msg)

                else:
                    logger.info('Assuming Cardinal HPIs')
                    nas = hpi_dev[0]
                    lpa = hpi_dev[2]
                    rpa = hpi_dev[1]
                    t = get_ras_to_neuromag_trans(nas, lpa, rpa)
                    self.info['dev_head_t'] = \
                        Transform(FIFF.FIFFV_COORD_DEVICE,
                                  FIFF.FIFFV_COORD_HEAD, t)

                    # transform fiducial points
                    nas = apply_trans(t, nas)
                    lpa = apply_trans(t, lpa)
                    rpa = apply_trans(t, rpa)

                    hpi = apply_trans(self.info['dev_head_t'], hpi_dev)
                    self.info['dig'] = _make_dig_points(nasion=nas, lpa=lpa,
                                                        rpa=rpa, hpi=hpi)
                    order = np.array([0, 1, 2])
                    dist_limit = 0.005

                # fill in hpi_results
                hpi_result = dict()

                # add HPI points in device coords...
                dig = []
                for idx, point in enumerate(hpi_dev):
                    dig.append({'r': point, 'ident': idx + 1,
                                'kind': FIFF.FIFFV_POINT_HPI,
                                'coord_frame': FIFF.FIFFV_COORD_DEVICE})
                hpi_result['dig_points'] = dig

                # attach Transform
                hpi_result['coord_trans'] = self.info['dev_head_t']

                # 1 based indexing
                hpi_result['order'] = order + 1
                hpi_result['used'] = np.arange(3) + 1
                hpi_result['dist_limit'] = dist_limit
                hpi_result['good_limit'] = 0.98

                # Warn for large discrepancies between digitized and fit
                # cHPI locations
                if hpi_result['dist_limit'] > 0.005:
                    warn('Large difference between digitized geometry' +
                         ' and HPI geometry. Max coil to coil difference' +
                         ' is %0.2f cm\n' % (100. * tmp_dists.max()) +
                         'beware of *POOR* head localization')

                # store it
                self.info['hpi_results'] = [hpi_result]

    def _read_segment_file(self, data, idx, fi, start, stop, cals, mult):
        """Read a chunk of raw data."""
        _read_segments_file(
            self, data, idx, fi, start, stop, cals, mult, dtype='>f4')


text:
import chai = require('chai');
var expect = chai.expect;

import Print = require('../../src/util/print');
import MemStore = require('../../src/store/mem-store');
import MemTable = require('../../src/store/mem-table');
import Query = require('../../src/store/query');

describe('Util', ()=> {
    var store, author;
    it('can print', ()=> {
        store = new MemStore();
        author = new MemTable({
            name: 'author',
            identity: 'name'
        });
        store.createTable(author);
        var insertQ = new Query();
        insertQ.setTable('author');
        for (var i = 0; i < 10; i++) {
            insertQ.insert({
                name: 'jack' + i,
                age: i
            });
        }
        store.insert(insertQ);
        Print.table(store.getTable('author'));
    });
});


text:
package org.apache.falcon.regression;

import org.apache.falcon.entity.v0.EntityType;
import org.apache.falcon.regression.core.bundle.Bundle;
import org.apache.falcon.regression.core.helpers.ColoHelper;
import org.apache.falcon.regression.core.response.ServiceResponse;
import org.apache.falcon.regression.core.util.AssertUtil;
import org.apache.falcon.regression.core.util.BundleUtil;
import org.apache.falcon.regression.core.util.Util;
import org.apache.falcon.regression.testHelper.BaseTestClass;
import org.apache.log4j.Logger;
import org.apache.oozie.client.Job;
import org.apache.oozie.client.OozieClient;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

/**
 * Feed status tests. Checks getStatus functionality.
 */
@Test(groups = "embedded")
public class FeedStatusTest extends BaseTestClass {

    private ColoHelper cluster = servers.get(0);
    private OozieClient clusterOC = serverOC.get(0);
    private String feed;
    private static final Logger LOGGER = Logger.getLogger(FeedStatusTest.class);

    @BeforeMethod(alwaysRun = true)
    public void setUp() throws Exception {
        bundles[0] = BundleUtil.readELBundle();
        bundles[0].generateUniqueBundle(this);
        bundles[0] = new Bundle(bundles[0], cluster);

        //submit the cluster
        ServiceResponse response =
            prism.getClusterHelper().submitEntity(bundles[0].getClusters().get(0));
        AssertUtil.assertSucceeded(response);
        feed = bundles[0].getInputFeedFromBundle();
    }

    @AfterMethod(alwaysRun = true)
    public void tearDown() {
        removeTestClassEntities();
    }

    /**
     * Schedules feed. Queries a feed status and checks the response
     * correctness and a feed status correspondence.
     *
     * @throws Exception
     */
    @Test(groups = {"singleCluster"})
    public void getStatusForScheduledFeed() throws Exception {
        ServiceResponse response = prism.getFeedHelper().submitAndSchedule(feed);
        LOGGER.info("Feed: " + Util.prettyPrintXml(feed));
        AssertUtil.assertSucceeded(response);

        response = prism.getFeedHelper().getStatus(feed);

        AssertUtil.assertSucceeded(response);

        String colo = prism.getFeedHelper().getColo();
        Assert.assertTrue(response.getMessage().contains(colo + "/RUNNING"));
        AssertUtil.checkStatus(clusterOC, EntityType.FEED, feed, Job.Status.RUNNING);
    }

    /**
     * Schedules and suspends feed. Queries a feed status and checks the response
     * correctness and a feed status correspondence.
     *
     * @throws Exception
     */
    @Test(groups = {"singleCluster"})
    public void getStatusForSuspendedFeed() throws Exception {
        ServiceResponse response = prism.getFeedHelper().submitAndSchedule(feed);

        AssertUtil.assertSucceeded(response);

        response = prism.getFeedHelper().suspend(feed);
        AssertUtil.assertSucceeded(response);

        response = prism.getFeedHelper().getStatus(feed);

        AssertUtil.assertSucceeded(response);
        String colo = prism.getFeedHelper().getColo();
        Assert.assertTrue(response.getMessage().contains(colo + "/SUSPENDED"));
        AssertUtil.checkStatus(clusterOC, EntityType.FEED, feed, Job.Status.SUSPENDED);
    }

    /**
     * Submits feed. Queries a feed status and checks the response
     * correctness and a feed status correspondence.
     *
     * @throws Exception
     */
    @Test(groups = {"singleCluster"})
    public void getStatusForSubmittedFeed() throws Exception {
        ServiceResponse response = prism.getFeedHelper().submitEntity(feed);

        AssertUtil.assertSucceeded(response);

        response = prism.getFeedHelper().getStatus(feed);

        AssertUtil.assertSucceeded(response);
        String colo = prism.getFeedHelper().getColo();
        Assert.assertTrue(response.getMessage().contains(colo + "/SUBMITTED"));
        AssertUtil.checkNotStatus(clusterOC, EntityType.FEED, feed, Job.Status.RUNNING);
    }

    /**
     * Removes feed. Queries a feed status. Checks that the response correctness.
     *
     * @throws Exception
     */
    @Test(groups = {"singleCluster"})
    public void getStatusForDeletedFeed() throws Exception {
        ServiceResponse response = prism.getFeedHelper().submitEntity(feed);
        AssertUtil.assertSucceeded(response);

        response = prism.getFeedHelper().delete(feed);
        AssertUtil.assertSucceeded(response);

        response = prism.getFeedHelper().getStatus(feed);
        AssertUtil.assertFailed(response);

        Assert.assertTrue(
            response.getMessage().contains(Util.readEntityName(feed) + " (FEED) not found"));
        AssertUtil.checkNotStatus(clusterOC, EntityType.FEED, feed, Job.Status.KILLED);
    }

    /**
     * Queries a status of feed which wasn't submitted and checks the response.
     *
     * @throws Exception
     */
    @Test(groups = {"singleCluster"})
    public void getStatusForNonExistentFeed() throws Exception {
        ServiceResponse response = prism.getFeedHelper().getStatus(feed);
        AssertUtil.assertFailed(response);
        Assert.assertTrue(
            response.getMessage().contains(Util.readEntityName(feed) + " (FEED) not found"));

    }
}


text:
#include "XnJpegCodec.h"
#include <XnCodecIDs.h>
#include <XnLog.h>

/***************/
/* XnJpegCodec */
/***************/
XnJpegCodec::XnJpegCodec() :
	m_bRGB(FALSE),
	m_nXRes(0),
	m_nYRes(0),
	m_nQuality(0),
	m_bValid(FALSE),
	m_hOutputModeCallback(NULL),
	m_hCroppingCallback(NULL),
	m_image(NULL),
	m_context(NULL)
{
	m_strNodeName[0] = '\0';
	xnOSMemSet(&m_CompJPEGContext, 0, sizeof(m_CompJPEGContext));
	xnOSMemSet(&m_UncompJPEGContext, 0, sizeof(m_UncompJPEGContext));
}

XnJpegCodec::~XnJpegCodec()
{
	XnStreamFreeCompressImageJ(&m_CompJPEGContext);
	XnStreamFreeUncompressImageJ(&m_UncompJPEGContext);

	// we can assume context still exists, but we'll have to check node still exists
	ImageGenerator imageGen;
	if (XN_STATUS_OK == m_context.GetProductionNodeByName(m_strNodeName, imageGen))
	{
		if (m_hOutputModeCallback)
		{
			imageGen.UnregisterFromMapOutputModeChange(m_hOutputModeCallback);
		}

		if (m_hCroppingCallback)
		{
			imageGen.GetCroppingCap().UnregisterFromCroppingChange(m_hCroppingCallback);
		}
	}
}

XnCodecID XnJpegCodec::GetCodecID() const
{
	return XN_CODEC_JPEG;
}

XnStatus XnJpegCodec::Init(const ProductionNode& node)
{
	XnStatus nRetVal = XN_STATUS_OK;

	nRetVal = XnCodec::Init(node);
	XN_IS_STATUS_OK(nRetVal);

	if (node.GetInfo().GetDescription().Type != XN_NODE_TYPE_IMAGE)
	{
		XN_LOG_ERROR_RETURN(XN_STATUS_BAD_PARAM, XN_MASK_OPEN_NI, "Codec JPEG requires an image node!");
	}

	strcpy(m_strNodeName, node.GetName());

	ImageGenerator image(node);
	image.GetContext(m_context);

	// register for changes in resolution or cropping
	nRetVal = image.RegisterToMapOutputModeChange(NodeConfigurationChangedCallback, this, m_hOutputModeCallback);
	XN_IS_STATUS_OK_LOG_ERROR("Register to map output mode change", nRetVal);

	if (image.IsCapabilitySupported(XN_CAPABILITY_CROPPING))
	{
		nRetVal = image.GetCroppingCap().RegisterToCroppingChange(NodeConfigurationChangedCallback, this, m_hCroppingCallback);
		XN_IS_STATUS_OK_LOG_ERROR("Register to cropping change", nRetVal);
	}

	// now init
	nRetVal = XnStreamInitCompressImageJ(&m_CompJPEGContext);
	XN_IS_STATUS_OK_LOG_ERROR("Init image compressor", nRetVal);

	nRetVal = XnStreamInitUncompressImageJ(&m_UncompJPEGContext);
	if (nRetVal != XN_STATUS_OK)
	{
		xnLogError(XN_MASK_OPEN_NI, "Init image uncompressor");
		XnStreamFreeCompressImageJ(&m_CompJPEGContext);
		return (nRetVal);
	}

	m_image = image;

	nRetVal = OnNodeConfigurationChanged();
	XN_IS_STATUS_OK_LOG_ERROR("Handle node configuration change", nRetVal);

	m_bValid = TRUE;

	return (XN_STATUS_OK);
}

XnFloat XnJpegCodec::GetWorseCompressionRatio() const
{
	return XN_STREAM_COMPRESSION_IMAGEJ_WORSE_RATIO;
}

XnUInt32 XnJpegCodec::GetOverheadSize() const
{
	return 0;
}

XnStatus XnJpegCodec::CompressImpl(const XnUChar* pData, XnUInt32 /*nDataSize*/, XnUChar* pCompressedData, XnUInt32* pnCompressedDataSize) const
{
	if (!m_bValid)
	{
		xnLogError(XN_MASK_OPEN_NI, "Codec is not valid");
		return XN_STATUS_ERROR;
	}

	if (m_bRGB)
	{
		return XnStreamCompressImage24J(&m_CompJPEGContext, pData, pCompressedData, pnCompressedDataSize, m_nXRes, m_nYRes, m_nQuality);
	}
	else
	{
		return XnStreamCompressImage8J(&m_CompJPEGContext, pData, pCompressedData, pnCompressedDataSize, m_nXRes, m_nYRes, m_nQuality);
	}
}

XnStatus XnJpegCodec::DecompressImpl(const XnUChar* pCompressedData, XnUInt32 nCompressedDataSize, XnUChar* pData, XnUInt32* pnDataSize) const
{
	if (!m_bValid)
	{
		return XN_STATUS_ERROR;
	}

	return XnStreamUncompressImageJ(&m_UncompJPEGContext, pCompressedData, nCompressedDataSize, pData, pnDataSize);
}

XnStatus XnJpegCodec::OnNodeConfigurationChanged()
{
	XnStatus nRetVal = XN_STATUS_OK;

	m_bValid = FALSE;

	XnMapOutputMode outputMode;
	nRetVal = m_image.GetMapOutputMode(outputMode);
	XN_IS_STATUS_OK_LOG_ERROR("Get map output mode", nRetVal);

	m_nXRes = outputMode.nXRes;
	m_nYRes = outputMode.nYRes;

	if (m_image.IsCapabilitySupported(XN_CAPABILITY_CROPPING))
	{
		XnCropping cropping;
		nRetVal = m_image.GetCroppingCap().GetCropping(cropping);
		XN_IS_STATUS_OK_LOG_ERROR("Get cropping", nRetVal);

		if (cropping.bEnabled)
		{
			m_nXRes = cropping.nXSize;
			m_nYRes = cropping.nYSize;
		}
	}

	XnPixelFormat pixelFormat = m_image.GetPixelFormat();

	switch (pixelFormat)
	{
		case XN_PIXEL_FORMAT_RGB24:
			m_bRGB = TRUE;
			break;
		case XN_PIXEL_FORMAT_GRAYSCALE_8_BIT:
			m_bRGB = FALSE;
			break;
		case XN_PIXEL_FORMAT_YUV422:
		case XN_PIXEL_FORMAT_GRAYSCALE_16_BIT:
		default:
			XN_LOG_ERROR_RETURN(XN_STATUS_ERROR, XN_MASK_OPEN_NI, "Jpeg currently supports only RGB24 and Grayscale8 pixel formats!");
	}

	m_nQuality = XN_STREAM_COMPRESSION_JPEG_DEFAULT_QUALITY;

	m_bValid = TRUE;

	return (XN_STATUS_OK);
}

void XN_CALLBACK_TYPE XnJpegCodec::NodeConfigurationChangedCallback(ProductionNode& /*node*/, void* pCookie)
{
	XnJpegCodec* pThis = (XnJpegCodec*)pCookie;
	pThis->OnNodeConfigurationChanged();
}

/*********************/
/* ExportedJpegCodec */
/*********************/
ExportedJpegCodec::ExportedJpegCodec() : ExportedCodec(XN_CODEC_JPEG)
{

}

XnCodec* ExportedJpegCodec::CreateCodec()
{
	return XN_NEW(XnJpegCodec);
}


text:
typedef HRESULT (*CommandFunc)(ILLDBServices* services, const char *args);

extern char *g_coreclrDirectory;
extern ULONG g_currentThreadIndex;
extern ULONG g_currentThreadSystemId;

bool
sosCommandInitialize(lldb::SBDebugger debugger);

bool
setsostidCommandInitialize(lldb::SBDebugger debugger);

bool
setclrpathCommandInitialize(lldb::SBDebugger debugger);

bool
corerunCommandInitialize(lldb::SBDebugger debugger);


text:
require 'chef/platform/provider_priority_map'

require 'poise_javascript/javascript_providers/dummy'
require 'poise_javascript/javascript_providers/iojs'
require 'poise_javascript/javascript_providers/nodejs'
require 'poise_javascript/javascript_providers/scl'
require 'poise_javascript/javascript_providers/system'

module PoiseJavascript
  # Inversion providers for the javascript_runtime resource.
  #
  # @since 1.0.0
  module JavascriptProviders
    autoload :Base, 'poise_javascript/javascript_providers/base'

    Chef::Platform::ProviderPriorityMap.instance.priority(:javascript_runtime, [
      PoiseJavascript::JavascriptProviders::IOJS,
      PoiseJavascript::JavascriptProviders::NodeJS,
      PoiseJavascript::JavascriptProviders::Scl,
      PoiseJavascript::JavascriptProviders::System,
    ])
  end
end


text:
<?php

namespace Propel\Generator\Builder\Om\Component\EntityMap;

use gossi\docblock\tags\TagFactory;
use Propel\Generator\Builder\Om\Component\BuildComponent;
use Propel\Generator\Builder\Om\Component\NamingTrait;

/**
 * Adds getPropUnsetter method.
 *
 * @author Marc J. Schmidt <marc@marcjschmidt.de>
 */
class GetPropUnsetterMethod extends BuildComponent
{
    use NamingTrait;

    public function process()
    {
        $className = $this->getObjectClassName(true);

        $body = "
return \$this->getClassPropUnsetter('$className');
        ";

        $this->addMethod('getPropUnsetter')
            ->setBody($body);
    }
}


text:
Fortune Speak
=============

Fortune Speak is a Python sample app for Managed VMs that synthesize and display a random fortune sound everytime you load the page.

[Demo](http://fortunespeak.appspot.com/)

It extends a traditional Python App Engine application with new
functionalities that are unlocked by Managed VMs
- *Get more CPU and RAM* by running your App Engine module on Google Compute Engine VMs
    - set GCE machine type in `app.yaml` ([view sources](https://github.com/GoogleCloudPlatform/appengine-vm-fortunespeak-python/blob/0c65d79e278dd31df837f70d85c563e4dc15e52b/app.yaml#L10))
- *Escape the sandbox* by writing to files and launching subprocess
    - cache wave file to local disk ([view sources](https://github.com/GoogleCloudPlatform/appengine-vm-fortunespeak-python/blob/0c65d79e278dd31df837f70d85c563e4dc15e52b/main.py#L43))
    - launch the `fortune` executable ([view sources](https://github.com/GoogleCloudPlatform/appengine-vm-fortunespeak-python/blob/0c65d79e278dd31df837f70d85c563e4dc15e52b/main.py#L36))
- *Customize your runtime* by installing third party packages
    - install the `fortune` package with `apt-get` ([view sources](https://github.com/GoogleCloudPlatform/appengine-vm-fortunespeak-python/blob/0c65d79e278dd31df837f70d85c563e4dc15e52b/Dockerfile#L5))
    - install `pyttsx` and `flask` from [`requirements.txt`](https://github.com/GoogleCloudPlatform/appengine-vm-fortunespeak-python/blob/0c65d79e278dd31df837f70d85c563e4dc15e52b/requirements.txt) with `pip` ([view sources](https://github.com/GoogleCloudPlatform/appengine-vm-fortunespeak-python/blob/0c65d79e278dd31df837f70d85c563e4dc15e52b/Dockerfile#L7))
- *Call into native* Python C extensions
    - import and call `_speak` `pyttsx` driver ([view sources](https://github.com/GoogleCloudPlatform/appengine-vm-fortunespeak-python/blob/0c65d79e278dd31df837f70d85c563e4dc15e52b/synth.py#L11))

Below is a tutorial that will guide you on how to build, run and deploy this application step by step.

## Prerequisites

During this step you will
- create a new Managed VMs project
- provision your local development environments
- run the final application locally and deploy it to production

### Create your project

1. Go to [Google Developers Console](//cloud.google.com/console) and create a new project.
2. Enable billing
3. Open `https://preview.appengine.google.com/settings?&app_id=s~<project>`
4. Click `Setup Google APIs project for VM Runtime...`

### Setup Docker

1. Install boot2docker
    - [MacOSX](http://docs.docker.io/installation/mac/) instructions
    - [Windows](http://docs.docker.io/installation/windows/) instructions
    - [Linux](https://github.com/boot2docker/boot2docker-cli/releases) releases
2. Setup and start boot2docker

        boot2docker init
        boot2docker up

### Setup the Cloud SDK

1. Get and install the SDK preview release
2. Setup the Managed VMs components:
        gcloud components update appengine-managed-vms
        gcloud auth login
        gcloud set project <project>
        gcloud preview app setup-managed-vms

### Run the application locally

1. Get the application code

        git clone https://github.com/GoogleCloudPlatform/appengine-vm-fortunespeak-python
        cd appengine-vm-fortunespeak-python
        git fetch --all

2. Run the application locally

        gcloud preview app run .

3. After seeing a request to `/_ah/start` in the logs open [http://localhost:8080](http://localhost:8080)

### Deploy the application to your project

1. Build and deploy the application image

        gcloud preview app deploy . --server preview.appengine.google.com

2. After the command complete succesfully open `https://<project>.appspot.com`

## Hello World!

During this step you will:
- create a simple Python hello world application

0. First switch to `step0` branch

        git checkout step0

1. Create a `app.yaml` file w/ the default App Engine configuration
2. Create a `main.py` file using `webapp2` w/ a `RequestHandler` that print `hello: <Country the HTTP request is coming from>`
3. Run locally and deploy it to production.

### Solution

- Review the [solution](https://github.com/GoogleCloudPlatform/appengine-vm-fortunespeak-python/compare/proppy:step0...step1)
- Compare with your working directory

        git diff step1 -R

- If stuck, stash your working directory and switch to the solution branch

        git stash
        git checkout step1

## Hello Managed VMs

During this step you will:
- enable Managed VMs in your application configuration
- select a bigger instance class

1. Modify `app.yaml` to add `vm: true`
2. Modify `app.yaml` to select a bigger instance class
3. Run locally
4. Notice that a Dockerfile has been created in your application directory
5. Deploy to production

### Solution

- Review the [solution](https://github.com/GoogleCloudPlatform/appengine-vm-fortunespeak-python/compare/proppy:step1...step2)
- Compare with your working directory

        git diff step2 -R

- If stuck, stash your working directory and  switch to the solution branch

        git stash
        git checkout step2

## Escape the sandbox

During this step you will:
- perform system operation: write to the local filesystem

1. Modify `main.py` to log the greetings to a file called 'messages.txt'
2. Modify `main.py` to add a new `RequestHandler` that display the content of this file.
3. Run locally and deploy it to production

### Solution

- Review the [solution](https://github.com/GoogleCloudPlatform/appengine-vm-fortunespeak-python/compare/proppy:step2...step3)
- Compare with your working directory

        git diff step3 -R

- If stuck, stash your working directory and switch to the solution branch

        git stash
        git checkout step3

## Customize the Runtime Environment

During this step you will:
- add native dependencies to your application with `apt-get`
- perform system operattion: launch an external process

1. Modify `Dockerfile` to `RUN apt-get install -y fortunes`
2. Modify `main.py` to launch `/usr/games/fortunes`  with the `subprocess` module in the main `RequestHandler`, capture the standard output and display it back in the response.
3. Run it locally and deploy to production

### Solution

- Review the [solution](https://github.com/GoogleCloudPlatform/appengine-vm-fortunespeak-python/compare/proppy:step3...step4)
- Compare with your working directory

        git diff step4 -R

- If stuck, stash your working directory and switch to the solution branch

        git stash
        git checkout step4

## Manage Python dependencies

During this step you will:
- managed your application dependencies with `pip` and `requirements.txt`
- rewrite your web application handler using a modern python framework `Flask`

1. Create a `requirements.txt` with `Flask` listed as a dependency
2. Modify `Dockerfile` to `RUN pip install -r requirements.txt -t .`
3. Edit `main.py` to use `flask.route` instead of `webapp2.RequestHandler`
4. Run it locally and deploy to production

### Solution

- Review the [solution](https://github.com/GoogleCloudPlatform/appengine-vm-fortunespeak-python/compare/proppy:step4...step5)
- Compare with your working directory

        git diff step5 -R

- If stuck, stash your working directory and switch to the solution branch

        git stash
        git checkout step5

## Use Python C extensions

During this step you will:
- add `pyttsx` C extensions as a dependency of your application
- call into native code to perform text to speech.

1. Modify `requirements.txt` to list `pyttsx` as a depdency
2. Copy the file `synth.py` from the master branch

        git checkout master synth.py

3. Call `synth.Say` from you main request handler and return the wavform data with the `audio-x/wav` content type
4. Run it locally and deploy to production

### Solution

- Review the [solution](https://github.com/GoogleCloudPlatform/appengine-vm-fortunespeak-python/compare/proppy:step5...step6)
- Compare with your working directory

        git diff step6 -R

- If stuck, stash your working directory and switch to the solution branch

        git stash
        git checkout step6


text:
var step=1;
var image1=new Image();
var image2=new Image();
var image3=new Image();
var image4=new Image();
var image5=new Image();
var image6=new Image();
var image7=new Image();
var image8=new Image();
var image9=new Image();

function slideit(){
    document.images.slide.src=eval("image"+step+".src");
    if(step<9) {
        step++;
    } else {
        step=1;
    }
    setTimeout("slideit()",3500);
}

$(document).ready(function(){
    image1.src="img/our-school/image1.jpg";
    image2.src="img/our-school/image2.jpg";
    image3.src="img/our-school/image3.jpg";
    image4.src="img/our-school/image4.jpg";
    image5.src="img/our-school/image5.jpg";
    image6.src="img/our-school/image6.jpg";
    image7.src="img/our-school/image7.jpg";
    image8.src="img/our-school/image8.jpg";
    image9.src="img/our-school/image9.png";

    slideit();
});


text:
function [out] = LinearRepresentation(values,vectorwidth,lo, hi, inverseFlag, binaryFlag)
%
% wrapper function  around scalar2icecubetray that provides binary version
% function instead of  [1 1 1 1 1 1 .21 0 0 0]
% with binaryflag      [1 1 1 1 1 1  1  0 0 0]
%
% what happens when you invert this.. (ah now you're asking)
%  we pick the maximum column over a threshold and use that.
%

if nargin < 6, binaryFlag = false; end

out = Scalar2ThermometerCode(values,vectorwidth,lo,hi,inverseFlag);

if ~inverseFlag && binaryFlag
    out = ceil(out);
end


text:
var five     = require("johnny-five");
var Spark    = require("spark-io");
var keypress = require('keypress');

keypress(process.stdin);

var board = new five.Board({
  io: new Spark({
    token: process.env.SPARK_TOKEN,
    deviceId: process.env.SPARK_DEVICE_ID
  })
});

board.on("ready", function() {

  console.log("Welcome to Sumobot Jr, powered wirelessly with the Spark Core!")
  console.log("Control the bot with the arrow keys, and SPACE to stop.")

  var left_wheel  = new five.Servo({ pin: "D0", type: 'continuous' }).stop();
  var right_wheel = new five.Servo({ pin: "D1", type: 'continuous' }).stop();

  process.stdin.resume();
  process.stdin.setEncoding('utf8');
  process.stdin.setRawMode(true);

  process.stdin.on('keypress', function (ch, key) {

    if ( !key ) return;

    if ( key.name == 'q' ) {

      console.log('Quitting');
      process.exit();

    } else if ( key.name == 'down' ) {

      console.log('Forward');
      left_wheel.ccw(0.9);
      right_wheel.cw(0.9);

    } else if ( key.name == 'up' ) {

      console.log('Backward');
      left_wheel.cw(0.9);
      right_wheel.ccw(0.9);

    } else if ( key.name == 'left' ) {

      console.log('Left');
      left_wheel.ccw(0.9);
      right_wheel.ccw(0.9);

    } else if ( key.name == 'right' ) {

      console.log('Right');
      left_wheel.cw(0.9);
      right_wheel.cw(0.9);

    } else if ( key.name == 'space' ) {

      console.log('Stopping');
      left_wheel.stop();
      right_wheel.stop();

    }

  });

});


text:
import unittest
import datetime
import time

import ipa_db
import ipa_config

class TestDb(unittest.TestCase):
    @classmethod
    def setUpClass(self):
        self.db = ipa_db.Db(ipa_config.db['test'])

    def setUp(self):
        self.db.remove_schema()
        self.db.create_schema()

    def test_adding_trains(self):
        name = ['train', 'other train']

        self.assertEqual(list(self.db.get_train_id(name[0])), [])
        self.assertEqual(list(self.db.get_train_id(name[1])), [])

        self.db.add_train(name[0])
        self.db.add_train(name[1])
        self.db.commit()

        self.assertEqual(list(self.db.get_train_id(name[0])), [{'train_name': name[0], 'train_id': 1}])
        self.assertEqual(list(self.db.get_train_id(name[1])), [{'train_name': name[1], 'train_id': 2}])

    def test_train_name_uniqueness(self):
        name = 'train'
        self.db.add_train(name)
        with self.assertRaises(ipa_db.DbError):
            self.db.add_train(name)
        self.db.commit()
        self.assertEqual(list(self.db.get_train_id(name)), [{'train_name': name, 'train_id': 1}])

    def test_adding_stations(self):
        name = ['station', 'other station']

        self.assertEqual(list(self.db.get_station_id(name[0])), [])
        self.assertEqual(list(self.db.get_station_id(name[1])), [])

        self.db.add_station(name[0])
        self.db.add_station(name[1])
        self.db.commit()

        self.assertEqual(list(self.db.get_station_id(name[0])), [{'station_id': 1}])
        self.assertEqual(list(self.db.get_station_id(name[1])), [{'station_id': 2}])

    def test_station_name_uniqueness(self):
        name = 'station'
        self.db.add_station(name)
        with self.assertRaises(ipa_db.DbError):
            self.db.add_station(name)
        self.db.commit()
        self.assertEqual(list(self.db.get_station_id(name)), [{'station_id': 1}])

    def test_updating_schedules(self):
        schedule_id = 123
        schedule_date = datetime.date(2010, 12, 21)
        train_id = 1
        train_name = "train name"
        expected_schedule = {'schedule_id': schedule_id, 'schedule_date': schedule_date}

        self.assertEqual(list(self.db.get_schedules(train_id)), [])

        self.db.add_train(train_name)
        self.db.update_schedule(schedule_id, str(schedule_date), train_id)
        self.db.commit()

        self.assertEqual(list(self.db.get_schedules(train_id)), [expected_schedule])

    def test_active_schedules(self):
        schedule_id = 123
        schedule_date = datetime.date(2010, 12, 21)
        train_id = 10

        self.db.update_schedule(schedule_id, str(schedule_date), train_id)
        self.db.commit()
        self.assertEqual(list(self.db.get_active_schedules()), [{'schedule_id': schedule_id}])

        self.db.set_active(schedule_id, False)
        self.db.commit()
        self.assertEqual(list(self.db.get_active_schedules()), [])

        self.db.set_active(schedule_id, True)
        self.db.commit()
        self.assertEqual(list(self.db.get_active_schedules()), [{'schedule_id': schedule_id}])

    def test_updating_schedule_infos(self):
        schedule_id = 222

        info = [
            {'arrival_time': None, 'arrival_delay': None,
             'departure_time': '2016-12-21 12:01:30', 'departure_delay': 3},
            {'arrival_time': '2016-12-21 12:05:00', 'arrival_delay': -10,
             'departure_time': '2016-12-21 12:08:00', 'departure_delay': 0},
            {'arrival_time': '2016-12-21 12:10:10', 'arrival_delay': 0,
             'departure_time': None, 'departure_delay': None},
        ]

        self.assertEqual(list(self.db.get_schedule_infos(schedule_id)), [])

        self.db.add_station('station 1')
        self.db.add_station('station 2')
        self.db.add_station('station 3')

        self.db.update_schedule_info(schedule_id, 0, 1, info[0])
        self.db.update_schedule_info(schedule_id, 2, 3, info[2])
        self.db.update_schedule_info(schedule_id, 1, 2, info[1])
        self.db.commit()

        self.assertEqual(list(self.db.get_schedule_infos(schedule_id)),
                         [{'arrival_delay': None,
                           'arrival_time': None,
                           'departure_delay': 3,
                           'departure_time': datetime.datetime(2016, 12, 21, 12, 1, 30),
                           'station_name': 'station 1'},
                          {'arrival_delay': -10,
                           'arrival_time': datetime.datetime(2016, 12, 21, 12, 5, 0),
                           'departure_delay': 0,
                           'departure_time': datetime.datetime(2016, 12, 21, 12, 8, 0),
                           'station_name': 'station 2'},
                          {'arrival_delay': 0,
                           'arrival_time': datetime.datetime(2016, 12, 21, 12, 10, 10),
                           'departure_delay': None,
                           'departure_time': None,
                           'station_name': 'station 3'}])

if __name__ == '__main__':
    unittest.main()


text:
function Get-SSApitest {

param
    (
    [Parameter(Mandatory=$true)]
    $serv,
    $targ,
    [Parameter(Mandatory=$true)]
    [ValidateSet('Start','Stop','Restart')]
    $state
    )

$json_data = @{
        'key1' = 'value1'
        'key2' = $serv
        'key3' = $state
    } | ConvertTo-Json # Test connection

$postParams =  @{'St2-Api-Key'='[ADD STACKSTORM API KEY HERE]';"Content-Type"='application/json'} # Test connection

$server = "https://$targ"
$url = "/api/v1/webhooks/sample"

$ris = Invoke-WebRequest -Uri $server$url -Headers $postParams -Body $json_data -Method Post

$script:objects = $ris.Content
}


text:
package org.springframework.social.linkedin.api.impl.json;

import java.util.Date;

import org.springframework.social.linkedin.api.LinkedInProfile;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

@JsonIgnoreProperties(ignoreUnknown = true)
abstract class PostCommentMixin extends LinkedInObjectMixin {

	@JsonCreator
	PostCommentMixin(
		@JsonProperty("creationTimestamp") Date creationTimestamp,
		@JsonProperty("creator") LinkedInProfile creator,
		@JsonProperty("id") String id,
		@JsonProperty("text") String text) {}

}


text:
// Copyright (c) Umbraco.
// See LICENSE for more details.

using Microsoft.Extensions.Logging;
using Umbraco.Cms.Core.IO;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Serialization;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Strings;

namespace Umbraco.Cms.Core.PropertyEditors
{
    [DataEditor(
        Constants.PropertyEditors.Aliases.DropDownListFlexible,
        "Dropdown",
        "dropdownFlexible",
        Group = Constants.PropertyEditors.Groups.Lists,
        Icon = "icon-indent")]
    public class DropDownFlexiblePropertyEditor : DataEditor
    {
        private readonly ILocalizedTextService _textService;
        private readonly IIOHelper _ioHelper;

        public DropDownFlexiblePropertyEditor(
            IDataValueEditorFactory dataValueEditorFactory,
            ILocalizedTextService textService,
            IIOHelper ioHelper)
            : base(dataValueEditorFactory)
        {
            _textService = textService;
            _ioHelper = ioHelper;
        }

        protected override IDataValueEditor CreateValueEditor()
        {
            return DataValueEditorFactory.Create<MultipleValueEditor>(Attribute);
        }

        protected override IConfigurationEditor CreateConfigurationEditor() => new DropDownFlexibleConfigurationEditor(_textService, _ioHelper);
    }
}


text:
<!DOCTYPE html>

    <link data-require="bootstrap-css@3.1.1" data-semver="3.1.1" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />

    <link rel="stylesheet" href="style.css" />

        Online Class Scheduler

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            Toggle navigation

          </button>

              Class List

              Students


text:
/*+++++++++++++ NOT USED ANY MORE +++++++++++++
* Responsible for interfacing Models With configured Physical Data Store & performing common data preprocessing operations
* NR: Done => Add provision for Triggers/Event-Listeners[Before/After(Save,insert,Delete, etc)]
*/

app.classes.data.DataStore = new Class({
    initialize: function (config) {
        this.dataStoreName = (config.dataStoreName)? config.dataStoreName: app.log.error("DataStore Name cannot be empty"),
		this.dataAdapter = (config.dataAdapter)? config.dataAdapter: "pouchDB",
		this.adapterConfig = (config.adapterConfig)? config.adapterConfig: "";
		this.dataStoreAdapter = null;
    },
    getDataStore: function () {
        if (!this.dataStoreAdapter) {
            this.dataStoreAdapter = DataAdapterFactory.getAdapter(this.dataAdapter, this.adapterConfig);
            this.dataStoreAdapter.openDataStore(this.dataStoreName);
		}
        return this.dataStoreAdapter;
    },
    /* Add a event trigger [Supports multiple Actions for a single trigger event, just call method
     *   multiple times]
     *   @params : trigger : {string} event trigger eg. "before-save","after-delete ...etc."
     *             triggerName : unique name for the trigger.
     *             action : {function} Callback function to be executed when event triggers
     *   @example : dataStoreObject.addTrigger("before-save", "log_evt_before_save", function(evtData) {
     *                console.log("Trigger=" + evtData.trigger + " TriggerName=" + evtData.triggerName + "Data=" + evtData.data );
     *              });
     */
    addTrigger: function (trigger, triggerName, action) {
        this.getDataStore().addTrigger(trigger, triggerName, action);
    },
    /* Removes a trigger
     *   @params : trigger : {string} event trigger eg. "before-save","after-delete ...etc."
     *             triggerName : unique name of the trigger to be removed [ skipping this argument will delete all triggers]
     *   @example :  dataStoreObject.removeTrigger("before-save", "log_evt_before_save");
     */
    removeTrigger: function (trigger, triggerName) {
        this.getDataStore().removeTrigger(trigger, triggerName);
    },
	/*
    * Saves Data object into DB
    * If data contains a id, existing is updated, else a new entry is created with autogenerated ID
    */
    save : function (data,config) {
        return this.getDataStore().save(data,config);
    },
    remove: function (id) {
        return this.getDataStore().deleteByID(id);
    },
	query: function() {
	},
	getDataByID: function(id) {
		return this.getDataStore().getDataByID(id);
	},
	getRowsCount: function() {
		return this.getDataStore().getRowsCount();
	},
	getAllRows: function() {
		return this.getDataStore().getAllRows();
	},
	search : function (query) {
		return this.getDataStore().search(query);
    },
    find : function (query) {
		return this.getDataStore().find(query);
    }

});

//Define an Alias for Data Store for quick Access.
var DataStore = app.classes.data.DataStore;


text:
title: Intel ends an era with Xeon and loves Tulsa
author: TQuizzle
layout: post
permalink: /archive/intel-ends-an-era-with-xeon-and-loves-tulsa/
bitly_url:
  - http://bit.ly/154qijT
bitly_hash:
  - 154qijT
bitly_long_url:
  - http://www.tquizzle.com/archive/intel-ends-an-era-with-xeon-and-loves-tulsa/
categories:
  - Asides
---
Intel loves my hometown so much, they named this “beast of a chip”, Tulsa. Good Lookin’ Intel.
ArsTechnica

      Share this:

          Twitter

          Google

          Facebook

          repost

          More

              LinkedIn

              Reddit

              Digg

              StumbleUpon

              Email

              Print


text:
package fr.vidal.webservices.interactionservice;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for interactionCouple complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="interactionCouple">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="drugInteractionClassA" type="{urn:Vidal}drugInteractionClass"/>
 *         <element name="drugInteractionClassB" type="{urn:Vidal}drugInteractionClass"/>
 *         <element name="interactionId" type="{http://www.w3.org/2001/XMLSchema}int"/>
 *         <element name="precautionComment" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="productA" type="{urn:Vidal}product"/>
 *         <element name="productB" type="{urn:Vidal}product"/>
 *         <element name="riskComment" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="severity" type="{urn:Vidal}InteractionSeverityType"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "interactionCouple", propOrder = {
    "drugInteractionClassA",
    "drugInteractionClassB",
    "interactionId",
    "precautionComment",
    "productA",
    "productB",
    "riskComment",
    "severity"
})
public class InteractionCouple {

    @XmlElement(required = true, nillable = true)
    protected DrugInteractionClass drugInteractionClassA;
    @XmlElement(required = true, nillable = true)
    protected DrugInteractionClass drugInteractionClassB;
    @XmlElement(required = true, type = Integer.class, nillable = true)
    protected Integer interactionId;
    @XmlElement(required = true, nillable = true)
    protected String precautionComment;
    @XmlElement(required = true, nillable = true)
    protected Product productA;
    @XmlElement(required = true, nillable = true)
    protected Product productB;
    @XmlElement(required = true, nillable = true)
    protected String riskComment;
    @XmlElement(required = true, nillable = true)
    protected InteractionSeverityType severity;

    /**
     * Gets the value of the drugInteractionClassA property.
     *
     * @return
     *     possible object is
     *     {@link DrugInteractionClass }
     *
     */
    public DrugInteractionClass getDrugInteractionClassA() {
        return drugInteractionClassA;
    }

    /**
     * Sets the value of the drugInteractionClassA property.
     *
     * @param value
     *     allowed object is
     *     {@link DrugInteractionClass }
     *
     */
    public void setDrugInteractionClassA(DrugInteractionClass value) {
        this.drugInteractionClassA = value;
    }

    /**
     * Gets the value of the drugInteractionClassB property.
     *
     * @return
     *     possible object is
     *     {@link DrugInteractionClass }
     *
     */
    public DrugInteractionClass getDrugInteractionClassB() {
        return drugInteractionClassB;
    }

    /**
     * Sets the value of the drugInteractionClassB property.
     *
     * @param value
     *     allowed object is
     *     {@link DrugInteractionClass }
     *
     */
    public void setDrugInteractionClassB(DrugInteractionClass value) {
        this.drugInteractionClassB = value;
    }

    /**
     * Gets the value of the interactionId property.
     *
     * @return
     *     possible object is
     *     {@link Integer }
     *
     */
    public Integer getInteractionId() {
        return interactionId;
    }

    /**
     * Sets the value of the interactionId property.
     *
     * @param value
     *     allowed object is
     *     {@link Integer }
     *
     */
    public void setInteractionId(Integer value) {
        this.interactionId = value;
    }

    /**
     * Gets the value of the precautionComment property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getPrecautionComment() {
        return precautionComment;
    }

    /**
     * Sets the value of the precautionComment property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setPrecautionComment(String value) {
        this.precautionComment = value;
    }

    /**
     * Gets the value of the productA property.
     *
     * @return
     *     possible object is
     *     {@link Product }
     *
     */
    public Product getProductA() {
        return productA;
    }

    /**
     * Sets the value of the productA property.
     *
     * @param value
     *     allowed object is
     *     {@link Product }
     *
     */
    public void setProductA(Product value) {
        this.productA = value;
    }

    /**
     * Gets the value of the productB property.
     *
     * @return
     *     possible object is
     *     {@link Product }
     *
     */
    public Product getProductB() {
        return productB;
    }

    /**
     * Sets the value of the productB property.
     *
     * @param value
     *     allowed object is
     *     {@link Product }
     *
     */
    public void setProductB(Product value) {
        this.productB = value;
    }

    /**
     * Gets the value of the riskComment property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getRiskComment() {
        return riskComment;
    }

    /**
     * Sets the value of the riskComment property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setRiskComment(String value) {
        this.riskComment = value;
    }

    /**
     * Gets the value of the severity property.
     *
     * @return
     *     possible object is
     *     {@link InteractionSeverityType }
     *
     */
    public InteractionSeverityType getSeverity() {
        return severity;
    }

    /**
     * Sets the value of the severity property.
     *
     * @param value
     *     allowed object is
     *     {@link InteractionSeverityType }
     *
     */
    public void setSeverity(InteractionSeverityType value) {
        this.severity = value;
    }

}


text:
package org.cleandroid.core.validation.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface NotNull {

	String message() default "This value must not ne null";
}


text:
package org.apache.hadoop.hive.ql.io.orc;

import java.io.EOFException;
import java.io.IOException;

import org.apache.hadoop.hive.ql.io.orc.NewRunLengthIntegerWriter.EncodingType;

/**
 * A reader that reads a sequence of integers.
 */
class NewRunLengthIntegerReader {
	private final InStream input;
	private final boolean signed;
	private final long[] literals = new long[NewRunLengthIntegerWriter.MAX_SCOPE];
	private int numLiterals = 0;
	private int used = 0;

	NewRunLengthIntegerReader(InStream input, boolean signed) throws IOException {
		this.input = input;
		this.signed = signed;
	}

	private void readValues() throws IOException {
		// read the first 2 bits and determine the encoding type
		int firstByte = input.read();
		if (firstByte < 0) {
			throw new EOFException("Read past end of RLE integer from " + input);
		} else {
			int enc = (firstByte >>> 6) & 0x03;
			if (EncodingType.SHORT_REPEAT.ordinal() == enc) {
				readShortRepeatValues(firstByte);
			} else if (EncodingType.DIRECT.ordinal() == enc) {
				readDirectValues(firstByte);
			} else if (EncodingType.PATCHED_BASE.ordinal() == enc) {
				readPatchedBaseValues(firstByte);
			} else {
				readDeltaValues(firstByte);
			}
		}
	}

	private void readDeltaValues(int firstByte) throws IOException {

		// extract the number of fixed bits
		int fb = (firstByte >>> 1) & 0x1f;
		if (fb != 0) {
			fb = FixedBitSizes.ordinalToFixedBits(fb);
		}

		// extract the blob run length
		int len = (firstByte & 0x01) << 8;
		len |= input.read();

		// read the first value stored as vint
		long firstVal = SerializationUtils.readVslong(input);

		// store first value to result buffer
		long prevVal = firstVal;
		literals[numLiterals++] = firstVal;

		// if fixed bits is 0 then all values have fixed delta
		if (fb == 0) {
			// read the fixed delta value stored as vint
			long fd = SerializationUtils.readVslong(input);

			// add fixed deltas to adjacent values
			for (int i = 0; i < len; i++) {
				literals[numLiterals++] = literals[numLiterals - 2] + fd;
			}
		} else {
			// number of bytes of data blob
			int bytesToRead = BitPackWriter.getTotalBytesRequired(len, fb);

			// create buffer space to fill up the blob and unpack the bit packed
			// values
			byte[] buffer = new byte[bytesToRead];
			for (int i = 0; i < bytesToRead; i++) {
				buffer[i] = (byte) input.read();
			}

			// write the unpacked values, zigzag decode the delta values, add
			// it to previous value and store final value to result buffer
			long[] adjDeltas = BitPackReader.unpack(buffer, len, fb);
			for (int i = 0; i < adjDeltas.length; i++) {
				long zzDelta = Utils.zigzagDecode(adjDeltas[i]);
				literals[numLiterals++] = prevVal + zzDelta;
				prevVal = literals[numLiterals - 1];
			}
		}

	}

	private void readPatchedBaseValues(int firstByte) throws IOException {

		// extract the number of fixed bits
		int fbo = (firstByte >>> 1) & 0x1f;
		int fb = FixedBitSizes.ordinalToFixedBits(fbo);

		// extract the run length of data blob
		int len = (firstByte & 0x01) << 8;
		len |= input.read();
		// runs are always one off
		len += 1;

		// extract the number of bytes occupied by base
		int thirdByte = input.read();
		int bw = (thirdByte >>> 5) & 0x07;
		// base width is one off
		bw += 1;

		// extract patch width
		int pwo = thirdByte & 0x1f;
		int pw = FixedBitSizes.ordinalToFixedBits(pwo);

		// read fourth byte and extract patch gap width
		int fourthByte = input.read();
		int pgw = (fourthByte >>> 5) & 0x07;
		// patch gap width is one off
		pgw += 1;

		// extract the length of the patch list
		int pl = fourthByte & 0x1f;

		// read the next base width number of bytes to extract base value
		byte[] buffer = new byte[bw];
		for (int i = 0; i < bw; i++) {
			buffer[i] = (byte) input.read();
		}

		long base = Utils.bytesToLongBE(buffer);

		// calculate the total bytes of data blob and patch blob
		// data blob length = fixed width bits (fb) * run length (len)
		// patch blob length = patch length * (patch width + patch gap width)
		int blobBytes = BitPackWriter.getTotalBytesRequired(len, fb);
		int patchBlobBytes = BitPackWriter.getTotalBytesRequired(pl, pw + pgw);

		// create buffer space and unpack the bit packed data blob
		buffer = new byte[blobBytes];
		for (int i = 0; i < blobBytes; i++) {
			buffer[i] = (byte) input.read();
		}

		// create buffer space and unpack the bit packed patch blob
		byte[] patchBuffer = new byte[patchBlobBytes];
		for (int i = 0; i < patchBlobBytes; i++) {
			patchBuffer[i] = (byte) input.read();
		}

		// unpack the patch blob
		long[] unpackedPatch = BitPackReader.unpack(patchBuffer, pl, pw + pgw);

		// apply the patch directly when decoding the packed data
		int patchIdx = 0;
		long currGap = 0;
		long currPatch = 0;
		currGap = unpackedPatch[patchIdx] >>> pw;
		currPatch = unpackedPatch[patchIdx] & ((1 << pw) - 1);
		long actualGap = 0;

		// special case: gap is >255 then patch value will be 0.
		// if gap is <=255 then patch value cannot be 0
		while (currGap == 255 && currPatch == 0) {
			actualGap += 255;
			patchIdx++;
			currGap = unpackedPatch[patchIdx] >>> pw;
			currPatch = unpackedPatch[patchIdx] & ((1 << pw) - 1);
		}
		// add the left over gap
		actualGap += currGap;

		// unpack data blob, patch it (if required), add base and the zigzag
		// decode the value to get final result
		long[] unpacked = BitPackReader.unpack(buffer, len, fb);
		for (int i = 0; i < unpacked.length; i++) {
			if (i == actualGap) {
				// apply patch
				long patchedVal = unpacked[i] | (currPatch << fb);

				// add base to patched value and zigzag decode it
				literals[numLiterals++] = Utils.zigzagDecode(base + patchedVal);

				// increment the patch to point to next entry in patch list
				patchIdx++;

				if (patchIdx < pl) {
					// read the next gap and patch
					currGap = unpackedPatch[patchIdx] >>> pw;
					currPatch = unpackedPatch[patchIdx] & ((1 << pw) - 1);
					actualGap = 0;

					// special case: gap is >255 then patch will be 0. if gap is
					// <=255 then patch cannot be 0
					while (currGap == 255 && currPatch == 0) {
						actualGap += 255;
						patchIdx++;
						currGap = unpackedPatch[patchIdx] >>> pw;
						currPatch = unpackedPatch[patchIdx] & ((1 << pw) - 1);
					}
					// add the left over gap
					actualGap += currGap;

					// next gap is relative to the current gap
					actualGap += i;
				}
			} else {
				// no patching required. add base to unpacked value and zigzag
				// decode to get final value
				literals[numLiterals++] = Utils.zigzagDecode(base + unpacked[i]);
			}
		}

	}

	private void readDirectValues(int firstByte) throws IOException {

		// extract the number of fixed bits
		int fbo = (firstByte >>> 1) & 0x1f;
		int fb = FixedBitSizes.ordinalToFixedBits(fbo);

		// extract the run length
		int len = (firstByte & 0x01) << 8;
		len |= input.read();
		// runs are one off
		len += 1;

		// read the bit packed data blob
		int bytesToRead = BitPackWriter.getTotalBytesRequired(len, fb);

		// create buffer space to fill up the blob and unpack the values
		byte[] buffer = new byte[bytesToRead];
		for (int i = 0; i < bytesToRead; i++) {
			buffer[i] = (byte) input.read();
		}

		// write the unpacked values and zigzag decode to result buffer
		long[] unpacked = BitPackReader.unpack(buffer, len, fb);
		for (int i = 0; i < unpacked.length; i++) {
			literals[numLiterals++] = Utils.zigzagDecode(unpacked[i]);
		}
	}

	private void readShortRepeatValues(int firstByte) throws IOException {

		// read the number of bytes occupied by the value
		int size = (firstByte >>> 3) & 0x07;
		// #bytes are one off
		size += 1;

		// read the run length
		int len = firstByte & 0x07;
		// run lengths values are stored only after MIN_REPEAT value is met
		len += NewRunLengthIntegerWriter.MIN_REPEAT;

		// read the repeated value which is store using fixed bytes
		byte[] buffer = new byte[size];
		for (int i = 0; i < size; i++) {
			buffer[i] = (byte) input.read();
		}

		long val = Utils.bytesToLongBE(buffer);
		val = Utils.zigzagDecode(val);

		// repeat the value for length times
		for (int i = 0; i < len; i++) {
			literals[numLiterals++] = val;
		}
	}

	boolean hasNext() throws IOException {
		return used != numLiterals || input.available() > 0;
	}

	long next() throws IOException {
		long result;
		if (used == numLiterals) {
			numLiterals = 0;
			used = 0;
			readValues();
		}
		result = literals[used++];
		return result;
	}

	void seek(PositionProvider index) throws IOException {
		input.seek(index);
		int consumed = (int) index.getNext();
		if (consumed != 0) {
			// a loop is required for cases where we break the run into two
			// parts
			while (consumed > 0) {
				numLiterals = 0;
				readValues();
				used = consumed;
				consumed -= numLiterals;
			}
		} else {
			used = 0;
			numLiterals = 0;
		}
	}

	void skip(long numValues) throws IOException {
		while (numValues > 0) {
			if (used == numLiterals) {
				numLiterals = 0;
				used = 0;
				readValues();
			}
			long consume = Math.min(numValues, numLiterals - used);
			used += consume;
			numValues -= consume;
		}
	}
}


text:
class AddImportsToVersions < ActiveRecord::Migration
  def self.up
    add_column :version, :imports, :string
  end

  def self.down
    remove_column :version, :imports
  end
end


text:
var pg = require('pg');

exports.query = function(queryString, values, callback) {
    pg.connect(process.env.DATABASE_URL, function(err, client, done) {
        var handleError = function(err) {
            if (!err) {
                return false;
            } else {
                if (client) {
                    done(client); // remove client from connection pool.
                }

                return true;
            }
        };

        if (handleError(err)) {
            throw 'Error connecting to database. ' + err;
        } else {
            client.query(queryString, values, function(err, result) {
                done();
                callback(err, result);
            });
        }
    });
};