text:
// This is a bastardization of the true StyleObj type located in
// react-native/Libraries/StyleSheet/StyleSheetTypes. We unfortunately can't
// import that here, and it's too lengthy (and consequently too brittle) to
// copy-paste here either.
type StyleObj =
	| null
	| void
	| number
	| false
	| ''
	| $ReadOnlyArray<StyleObj>
	| { [name: string]: any };
type ViewStyleProp = StyleObj;
type TextStyleProp = StyleObj;
type AnimatedViewStyleProp = StyleObj;
type AnimatedTextStyleProp = StyleObj;

// This is copied from the Layout type in
// react-native-tab-view/src/TabViewTypeDefinitions
type TabViewLayout = {
	height: number,
	width: number,
};

// This is copied from react-native/Libraries/Image/ImageSource.js
type ImageURISource = {
	uri?: string,
	bundle?: string,
	method?: string,
	headers?: Object,
	body?: string,
	cache?: 'default' | 'reload' | 'force-cache' | 'only-if-cached',
	width?: number,
	height?: number,
	scale?: number,
};
type ImageSource = ImageURISource | number | Array<ImageURISource>;

// This one is too large to copy. Actual definition is in
// react-native/Libraries/Animated/src/nodes/AnimatedValue.js
type AnimatedValue = Object;

type HeaderForceInset = {
	horizontal?: string,
	vertical?: string,
	left?: string,
	right?: string,
	top?: string,
	bottom?: string,
};

declare module 'react-navigation' {

  /**
   * Navigation State + Action
   */

  declare type NavigationParams = {
    [key: string]: mixed,
  };

  declare type NavigationNavigateAction = {|
    type: 'Navigation/NAVIGATE',
    routeName: string,
    params?: NavigationParams,

    // The action to run inside the sub-router
    action?: NavigationNavigateAction,

    key?: string,
  |};

  declare type NavigationBackAction = {|
    type: 'Navigation/BACK',
    key?: ?string,
  |};

  declare type NavigationSetParamsAction = {|
    type: 'Navigation/SET_PARAMS',

    // The key of the route where the params should be set
    key: string,

    // The new params to merge into the existing route params
    params: NavigationParams,
  |};

  declare type NavigationInitAction = {|
    type: 'Navigation/INIT',
    params?: NavigationParams,
  |};

  declare type NavigationResetAction = {|
    type: 'Navigation/RESET',
    index: number,
    key?: ?string,
    actions: Array<NavigationNavigateAction>,
  |};

  declare type NavigationUriAction = {|
    type: 'Navigation/URI',
    uri: string,
  |};

  declare type NavigationReplaceAction = {|
    type: 'Navigation/REPLACE',
    key: string,
    routeName: string,
    params?: NavigationParams,
    action?: NavigationNavigateAction,
  |};
  declare type NavigationPopAction = {|
    type: 'Navigation/POP',
    n?: number,
    immediate?: boolean,
  |};
  declare type NavigationPopToTopAction = {|
    type: 'Navigation/POP_TO_TOP',
    immediate?: boolean,
  |};
  declare type NavigationPushAction = {|
    type: 'Navigation/PUSH',
    routeName: string,
    params?: NavigationParams,
    action?: NavigationNavigateAction,
    key?: string,
  |};

  declare type NavigationAction =
    | NavigationInitAction
    | NavigationNavigateAction
    | NavigationReplaceAction
    | NavigationPopAction
    | NavigationPopToTopAction
    | NavigationPushAction
    | NavigationBackAction
    | NavigationSetParamsAction
    | NavigationResetAction;

  /**
   * NavigationState is a tree of routes for a single navigator, where each
   * child route may either be a NavigationScreenRoute or a
   * NavigationRouterRoute. NavigationScreenRoute represents a leaf screen,
   * while the NavigationRouterRoute represents the state of a child navigator.
   *
   * NOTE: NavigationState is a state tree local to a single navigator and
   * its child navigators (via the routes field).
   * If we're in navigator nested deep inside the app, the state will only be
   * the state for that navigator.
   * The state for the root navigator of our app represents the whole navigation
   * state for the whole app.
   */
  declare type NavigationState = {
    /**
     * Index refers to the active child route in the routes array.
     */
    index: number,
    routes: Array<NavigationRoute>,
  };

  declare type NavigationRoute =
    | NavigationLeafRoute
    | NavigationStateRoute;

  declare type NavigationLeafRoute = {
    /**
     * React's key used by some navigators. No need to specify these manually,
     * they will be defined by the router.
     */
    key: string,
    /**
     * For example 'Home'.
     * This is used as a key in a route config when creating a navigator.
     */
    routeName: string,
    /**
     * Path is an advanced feature used for deep linking and on the web.
     */
    path?: string,
    /**
     * Params passed to this route when navigating to it,
     * e.g. `{ car_id: 123 }` in a route that displays a car.
     */
    params?: NavigationParams,
  };

  declare type NavigationStateRoute = NavigationLeafRoute &
    NavigationState;

  /**
   * Router
   */

  declare type NavigationScreenOptionsGetter<Options: {}> = (
    navigation: NavigationScreenProp<NavigationRoute>,
    screenProps?: {}
  ) => Options;

  declare type NavigationRouter<State: NavigationState, Options: {}> = {
    /**
     * The reducer that outputs the new navigation state for a given action,
     * with an optional previous state. When the action is considered handled
     * but the state is unchanged, the output state is null.
     */
    getStateForAction: (action: NavigationAction, lastState: ?State) => ?State,

    /**
     * Maps a URI-like string to an action. This can be mapped to a state
     * using `getStateForAction`.
     */
    getActionForPathAndParams: (
      path: string,
      params?: NavigationParams
    ) => ?NavigationAction,

    getPathAndParamsForState: (
      state: State
    ) => {
      path: string,
      params?: NavigationParams,
    },

    getComponentForRouteName: (routeName: string) => NavigationComponent,

    getComponentForState: (state: State) => NavigationComponent,

    /**
     * Gets the screen navigation options for a given screen.
     *
     * For example, we could get the config for the 'Foo' screen when the
     * `navigation.state` is:
     *
     *  {routeName: 'Foo', key: '123'}
     */
    getScreenOptions: NavigationScreenOptionsGetter<Options>,
  };

  declare type NavigationScreenDetails<T> = {
    options: T,
    state: NavigationRoute,
    navigation: NavigationScreenProp<NavigationRoute>,
  };

  declare type NavigationScreenOptions = {
    title?: string,
  };

  declare type NavigationScreenConfigProps = $Shape<{
    navigation: NavigationScreenProp<NavigationRoute>,
    screenProps: {},
  }>;

  declare type NavigationScreenConfig<Options> =
    | Options
    | (({
        ...$Exact<NavigationScreenConfigProps>,
        navigationOptions: Options,
      }) => Options);

  declare type NavigationComponent =
    | NavigationScreenComponent<NavigationRoute, *, *>
    | NavigationContainer<NavigationStateRoute, *, *>;

  declare type NavigationScreenComponent<
    Route: NavigationRoute,
    Options: {},
    Props: {}
  > = React$ComponentType<NavigationNavigatorProps<Options, Route> & Props> &
    ({} | { navigationOptions: NavigationScreenConfig<Options> });

  declare type NavigationNavigator<
    State: NavigationState,
    Options: {},
    Props: {}
  > = React$ComponentType<NavigationNavigatorProps<Options, State> & Props> & {
    router: NavigationRouter<State, Options>,
    navigationOptions?: ?NavigationScreenConfig<Options>,
  };

  declare type NavigationRouteConfig =
    | NavigationComponent
    | ({
        navigationOptions?: NavigationScreenConfig<*>,
        path?: string,
      } & NavigationScreenRouteConfig);

  declare type NavigationScreenRouteConfig =
    | {
        screen: NavigationComponent,
      }
    | {
        getScreen: () => NavigationComponent,
      };

  declare type NavigationPathsConfig = {
    [routeName: string]: string,
  };

  declare type NavigationRouteConfigMap = {
    [routeName: string]: NavigationRouteConfig,
  };

  /**
   * Header
   */

  declare type HeaderMode = 'float' | 'screen' | 'none';

  declare type HeaderProps = $Shape<
    NavigationSceneRendererProps & {
      mode: HeaderMode,
      router: NavigationRouter<NavigationState, NavigationStackScreenOptions>,
      getScreenDetails: NavigationScene => NavigationScreenDetails<
        NavigationStackScreenOptions
      >,
      leftInterpolator: (props: NavigationSceneRendererProps) => {},
      titleInterpolator: (props: NavigationSceneRendererProps) => {},
      rightInterpolator: (props: NavigationSceneRendererProps) => {},
    }
  >;

  /**
   * Stack Navigator
   */

  declare type NavigationStackScreenOptions = NavigationScreenOptions & {
    header?: ?(React$Node | (HeaderProps => React$Node)),
    headerTransparent?: boolean,
    headerTitle?: string | React$Node | React$ElementType,
    headerTitleStyle?: AnimatedTextStyleProp,
    headerTitleAllowFontScaling?: boolean,
    headerTintColor?: string,
    headerLeft?: React$Node | React$ElementType,
    headerBackTitle?: string,
    headerBackImage?: ImageSource,
    headerTruncatedBackTitle?: string,
    headerBackTitleStyle?: TextStyleProp,
    headerPressColorAndroid?: string,
    headerRight?: React$Node,
    headerStyle?: ViewStyleProp,
    headerForceInset?: HeaderForceInset,
    headerBackground?: React$Node | React$ElementType,
    gesturesEnabled?: boolean,
    gestureResponseDistance?: { vertical?: number, horizontal?: number },
    gestureDirection?: 'default' | 'inverted',
  };

  declare type NavigationStackRouterConfig = {|
    initialRouteName?: string,
    initialRouteParams?: NavigationParams,
    paths?: NavigationPathsConfig,
    navigationOptions?: NavigationScreenConfig<*>,
  |};

  declare type NavigationStackViewConfig = {|
    mode?: 'card' | 'modal',
    headerMode?: HeaderMode,
    headerTransitionPreset?: 'fade-in-place' | 'uikit',
    cardStyle?: ViewStyleProp,
    transitionConfig?: () => TransitionConfig,
    onTransitionStart?: () => void,
    onTransitionEnd?: () => void,
  |};

  declare type StackNavigatorConfig = {|
    ...NavigationStackViewConfig,
    ...NavigationStackRouterConfig,
  |};

  /**
   * Switch Navigator
   */

  declare type NavigationSwitchRouterConfig = {|
    initialRouteName?: string,
    initialRouteParams?: NavigationParams,
    paths?: NavigationPathsConfig,
    navigationOptions?: NavigationScreenConfig<*>,
    order?: Array<string>,
    backBehavior?: 'none' | 'initialRoute', // defaults to `'none'`
    resetOnBlur?: boolean, // defaults to `true`
  |};

  /**
   * Tab Navigator
   */

  declare type NavigationTabRouterConfig = {|
    initialRouteName?: string,
    initialRouteParams?: NavigationParams,
    paths?: NavigationPathsConfig,
    navigationOptions?: NavigationScreenConfig<*>,
    // todo: type these as the real route names rather than 'string'
    order?: Array<string>,
    // Does the back button cause the router to switch to the initial tab
    backBehavior?: 'none' | 'initialRoute', // defaults `initialRoute`
  |};

  declare type TabScene = {
    route: NavigationRoute,
    focused: boolean,
    index: number,
    tintColor?: ?string,
  };

  declare type NavigationTabScreenOptions = {|
    ...$Exact<NavigationScreenOptions>,
    tabBarIcon?:
      | React$Node
      | ((options: { tintColor: ?string, focused: boolean }) => ?React$Node),
    tabBarLabel?:
      | string
      | React$Node
      | ((options: { tintColor: ?string, focused: boolean }) => ?React$Node),
    tabBarVisible?: boolean,
    tabBarTestIDProps?: { testID?: string, accessibilityLabel?: string },
    tabBarOnPress?: (
      scene: TabScene,
      jumpToIndex: (index: number) => void
    ) => void,
  |};

  /**
   * Drawer
   */

  declare type NavigationDrawerScreenOptions = {|
    ...$Exact<NavigationScreenOptions>,
    drawerIcon?:
      | React$Node
      | ((options: { tintColor: ?string, focused: boolean }) => ?React$Node),
    drawerLabel?:
      | React$Node
      | ((options: { tintColor: ?string, focused: boolean }) => ?React$Node),
    drawerLockMode?: 'unlocked' | 'locked-closed' | 'locked-open',
  |};

  /**
   * Navigator Prop
   */

  declare type NavigationDispatch = (
    action: NavigationAction
  ) => boolean;

  declare type NavigationProp<S> = {
    +state: S,
    dispatch: NavigationDispatch,
  };

  declare type EventType =
    | 'willFocus'
    | 'didFocus'
    | 'willBlur'
    | 'didBlur'
    | 'action';

  declare type NavigationEventPayload = {
    type: EventType,
    action: NavigationAction,
    state: NavigationState,
    lastState: ?NavigationState,
  };

  declare type NavigationEventCallback = (
    payload: NavigationEventPayload
  ) => void;

  declare type NavigationEventSubscription = {
    remove: () => void,
  };

  declare type NavigationScreenProp<+S> = {
    +state: S,
    dispatch: NavigationDispatch,
    goBack: (routeKey?: ?string) => boolean,
    navigate: (
      routeName: string,
      params?: NavigationParams,
      action?: NavigationNavigateAction
    ) => boolean,
    setParams: (newParams: NavigationParams) => boolean,
    addListener: (
      eventName: string,
      callback: NavigationEventCallback
    ) => NavigationEventSubscription,
    push: (
      routeName: string,
      params?: NavigationParams,
      action?: NavigationNavigateAction
    ) => boolean,
    replace: (
      routeName: string,
      params?: NavigationParams,
      action?: NavigationNavigateAction
    ) => boolean,
    pop: (n?: number, params?: { immediate?: boolean }) => boolean,
    popToTop: (params?: { immediate?: boolean }) => boolean,
  };

  declare type NavigationNavigatorProps<O: {}, S: {}> = $Shape<{
    navigation: NavigationScreenProp<S>,
    screenProps?: {},
    navigationOptions?: O,
  }>;

  /**
   * Navigation container
   */

  declare type NavigationContainer<
    State: NavigationState,
    Options: {},
    Props: {}
  > = React$ComponentType<NavigationContainerProps<State, Options> & Props> & {
    router: NavigationRouter<State, Options>,
    navigationOptions?: ?NavigationScreenConfig<Options>,
  };

  declare type NavigationContainerProps<S: {}, O: {}> = $Shape<{
    uriPrefix?: string | RegExp,
    onNavigationStateChange?: ?(
      NavigationState,
      NavigationState,
      NavigationAction
    ) => void,
    navigation?: NavigationScreenProp<S>,
    screenProps?: *,
    navigationOptions?: O,
  }>;

  /**
   * Gestures, Animations, and Interpolators
   */

  declare type NavigationGestureDirection = 'horizontal' | 'vertical';

  declare type NavigationLayout = {
    height: AnimatedValue,
    initHeight: number,
    initWidth: number,
    isMeasured: boolean,
    width: AnimatedValue,
  };

  declare type NavigationScene = {
    index: number,
    isActive: boolean,
    isStale: boolean,
    key: string,
    route: NavigationRoute,
  };

  declare type NavigationTransitionProps = $Shape<{
    // The layout of the screen container
    layout: NavigationLayout,

    // The destination navigation state of the transition
    navigation: NavigationScreenProp<NavigationState>,

    // The progressive index of the transitioner's navigation state.
    position: AnimatedValue,

    // The value that represents the progress of the transition when navigation
    // state changes from one to another. Its numeric value will range from 0
    // to 1.
    //  progress.__getAnimatedValue() < 1 : transtion is happening.
    //  progress.__getAnimatedValue() == 1 : transtion completes.
    progress: AnimatedValue,

    // All the scenes of the transitioner.
    scenes: Array<NavigationScene>,

    // The active scene, corresponding to the route at
    // `navigation.state.routes[navigation.state.index]`. When rendering
    // NavigationSceneRendererPropsIndex, the scene does not refer to the active
    // scene, but instead the scene that is being rendered. The index always
    // is the index of the scene
    scene: NavigationScene,
    index: number,

    screenProps?: {},
  }>;

  // The scene renderer props are nearly identical to the props used for
  // rendering a transition. The exception is that the passed scene is not the
  // active scene but is instead the scene that the renderer should render
  // content for.
  declare type NavigationSceneRendererProps = NavigationTransitionProps;

  declare type NavigationTransitionSpec = {
    duration?: number,
    // An easing function from `Easing`.
    easing?: (t: number) => number,
    // A timing function such as `Animated.timing`.
    timing?: (value: AnimatedValue, config: any) => any,
  };

  /**
   * Describes a visual transition from one screen to another.
   */
  declare type TransitionConfig = {
    // The basics properties of the animation, such as duration and easing
    transitionSpec?: NavigationTransitionSpec,
    // How to animate position and opacity of the screen
    // based on the value generated by the transitionSpec
    screenInterpolator?: (props: NavigationSceneRendererProps) => {},
    // How to animate position and opacity of the header componetns
    // based on the value generated by the transitionSpec
    headerLeftInterpolator?: (props: NavigationSceneRendererProps) => {},
    headerTitleInterpolator?: (props: NavigationSceneRendererProps) => {},
    headerRightInterpolator?: (props: NavigationSceneRendererProps) => {},
    // The style of the container. Useful when a scene doesn't have
    // 100% opacity and the underlying container is visible.
    containerStyle?: ViewStyleProp,
  };

  declare type NavigationAnimationSetter = (
    position: AnimatedValue,
    newState: NavigationState,
    lastState: NavigationState
  ) => void;

  declare type NavigationSceneRenderer = () => React$Node;

  declare type NavigationStyleInterpolator = (
    props: NavigationSceneRendererProps
  ) => AnimatedViewStyleProp;

  declare type LayoutEvent = {
    nativeEvent: {
      layout: {
        x: number,
        y: number,
        width: number,
        height: number,
      },
    },
  };

  declare type SceneIndicesForInterpolationInputRange = {
    first: number,
    last: number,
  };

  /**
   * Now we type the actual exported module
   */

  declare function createNavigationContainer<S: NavigationState, O: {}>(
    Component: NavigationNavigator<S, O, *>
  ): NavigationContainer<S, O, *>;

  declare var StateUtils: {
    get: (state: NavigationState, key: string) => ?NavigationRoute,
    indexOf: (state: NavigationState, key: string) => number,
    has: (state: NavigationState, key: string) => boolean,
    push: (state: NavigationState, route: NavigationRoute) => NavigationState,
    pop: (state: NavigationState) => NavigationState,
    jumpToIndex: (state: NavigationState, index: number) => NavigationState,
    jumpTo: (state: NavigationState, key: string) => NavigationState,
    back: (state: NavigationState) => NavigationState,
    forward: (state: NavigationState) => NavigationState,
    replaceAt: (
      state: NavigationState,
      key: string,
      route: NavigationRoute
    ) => NavigationState,
    replaceAtIndex: (
      state: NavigationState,
      index: number,
      route: NavigationRoute
    ) => NavigationState,
    reset: (
      state: NavigationState,
      routes: Array<NavigationRoute>,
      index?: number
    ) => NavigationState,
  };

  declare function addNavigationHelpers<S: {}>(
    navigation: NavigationProp<S>
  ): NavigationScreenProp<S>;

  declare var NavigationActions: {
    BACK: 'Navigation/BACK',
    INIT: 'Navigation/INIT',
    NAVIGATE: 'Navigation/NAVIGATE',
    RESET: 'Navigation/RESET',
    SET_PARAMS: 'Navigation/SET_PARAMS',
    URI: 'Navigation/URI',
    back: {
      (payload?: { key?: ?string }): NavigationBackAction,
      toString: () => string,
    },
    init: {
      (payload?: { params?: NavigationParams }): NavigationInitAction,
      toString: () => string,
    },
    navigate: {
      (payload: {
        routeName: string,
        params?: ?NavigationParams,
        action?: ?NavigationNavigateAction,
      }): NavigationNavigateAction,
      toString: () => string,
    },
    reset: {
      (payload: {
        index: number,
        key?: ?string,
        actions: Array<NavigationNavigateAction>,
      }): NavigationResetAction,
      toString: () => string,
    },
    setParams: {
      (payload: {
        key: string,
        params: NavigationParams,
      }): NavigationSetParamsAction,
      toString: () => string,
    },
    uri: {
      (payload: { uri: string }): NavigationUriAction,
      toString: () => string,
    },
  };

  declare type _RouterProp<S: NavigationState, O: {}> = {
    router: NavigationRouter<S, O>,
  };
  declare type _NavigatorCreator<
    NavigationViewProps: {},
    S: NavigationState,
    O: {}
  > = (
    NavigationView: React$ComponentType<_RouterProp<S, O> & NavigationViewProps>
  ) => NavigationNavigator<S, O, NavigationViewProps>;
  declare function createNavigator<
    S: NavigationState,
    O: {},
    NavigatorConfig: {},
    NavigationViewProps: NavigationNavigatorProps<O, S>
  >(
    router: NavigationRouter<S, O>,
    routeConfigs?: NavigationRouteConfigMap,
    navigatorConfig?: NavigatorConfig
  ): _NavigatorCreator<NavigationViewProps, S, O>;

  declare function StackNavigator(
    routeConfigMap: NavigationRouteConfigMap,
    stackConfig?: StackNavigatorConfig
  ): NavigationContainer<*, *, *>;

  declare type _TabViewConfig = {|
    tabBarComponent?: React$ElementType,
    tabBarPosition?: 'top' | 'bottom',
    tabBarOptions?: {},
    swipeEnabled?: boolean,
    animationEnabled?: boolean,
    configureTransition?: (
      currentTransitionProps: Object,
      nextTransitionProps: Object
    ) => Object,
    initialLayout?: TabViewLayout,
  |};
  declare type _TabNavigatorConfig = {|
    ...NavigationTabRouterConfig,
    ..._TabViewConfig,
    lazy?: boolean,
    removeClippedSubviews?: boolean,
    containerOptions?: void,
  |};
  declare function TabNavigator(
    routeConfigs: NavigationRouteConfigMap,
    config?: _TabNavigatorConfig
  ): NavigationContainer<*, *, *>;
  declare type _SwitchNavigatorConfig = {|
    ...NavigationSwitchRouterConfig,
  |};
  declare function SwitchNavigator(
    routeConfigs: NavigationRouteConfigMap,
    config?: _SwitchNavigatorConfig
  ): NavigationContainer<*, *, *>;

  declare type _DrawerViewConfig = {|
    drawerLockMode?: 'unlocked' | 'locked-closed' | 'locked-open',
    drawerWidth?: number | (() => number),
    drawerPosition?: 'left' | 'right',
    drawerOpenRoute?: string,
    drawerCloseRoute?: string,
    drawerToggleRoute?: string,
    contentComponent?: React$ElementType,
    contentOptions?: {},
    style?: ViewStyleProp,
    useNativeAnimations?: boolean,
    drawerBackgroundColor?: string,
    screenProps?: {},
  |};
  declare type _DrawerNavigatorConfig = $Exact<{
    ...NavigationTabRouterConfig,
    ..._DrawerViewConfig,
    containerConfig?: void,
  }>;
  declare function DrawerNavigator(
    routeConfigs: NavigationRouteConfigMap,
    config?: _DrawerNavigatorConfig
  ): NavigationContainer<*, *, *>;

  declare function StackRouter(
    routeConfigs: NavigationRouteConfigMap,
    stackConfig?: NavigationStackRouterConfig
  ): NavigationRouter<*, NavigationStackScreenOptions>;

  declare function TabRouter(
    routeConfigs: NavigationRouteConfigMap,
    config?: NavigationTabRouterConfig
  ): NavigationRouter<*, *>;

  declare type _TransitionerProps = {
    configureTransition: (
      transitionProps: NavigationTransitionProps,
      prevTransitionProps: ?NavigationTransitionProps
    ) => NavigationTransitionSpec,
    navigation: NavigationScreenProp<NavigationState>,
    onTransitionEnd?: (...args: Array<mixed>) => void,
    onTransitionStart?: (...args: Array<mixed>) => void,
    render: (
      transitionProps: NavigationTransitionProps,
      prevTransitionProps: ?NavigationTransitionProps
    ) => React$Node,
  };
  declare var Transitioner: React$ComponentType<_TransitionerProps>;

  declare type _CardStackTransitionerProps = {
    headerMode: HeaderMode,
    mode: 'card' | 'modal',
    router: NavigationRouter<NavigationState, NavigationStackScreenOptions>,
    cardStyle?: ViewStyleProp,
    onTransitionStart?: () => void,
    onTransitionEnd?: () => void,
    /**
     * Optional custom animation when transitioning between screens.
     */
    transitionConfig?: () => TransitionConfig,
  } & NavigationNavigatorProps<NavigationStackScreenOptions, NavigationState>;
  declare var CardStackTransitioner: React$ComponentType<
    _CardStackTransitionerProps
  >;

  declare type _CardStackProps = {
    screenProps?: {},
    headerMode: HeaderMode,
    headerComponent?: React$ElementType,
    mode: 'card' | 'modal',
    router: NavigationRouter<NavigationState, NavigationStackScreenOptions>,
    cardStyle?: ViewStyleProp,
    onTransitionStart?: () => void,
    onTransitionEnd?: () => void,
    /**
     * Optional custom animation when transitioning between screens.
     */
    transitionConfig?: () => TransitionConfig,
    // NavigationTransitionProps:
    layout: NavigationLayout,
    navigation: NavigationScreenProp<NavigationState>,
    position: AnimatedValue,
    progress: AnimatedValue,
    scenes: Array<NavigationScene>,
    scene: NavigationScene,
    index: number,
  };
  declare var CardStack: React$ComponentType<_CardStackProps>;

  declare type _CardProps = {
    ...$Exact<NavigationSceneRendererProps>,
    children: React$Node,
    onComponentRef: React$Ref<*>,
    pointerEvents: string,
    style: any,
  };
  declare var Card: React$ComponentType<_CardProps>;

  declare type _SafeAreaViewForceInsetValue = 'always' | 'never' | number;
  declare type _SafeAreaViewProps = {
    forceInset?: {
      top?: _SafeAreaViewForceInsetValue,
      bottom?: _SafeAreaViewForceInsetValue,
      left?: _SafeAreaViewForceInsetValue,
      right?: _SafeAreaViewForceInsetValue,
      vertical?: _SafeAreaViewForceInsetValue,
      horizontal?: _SafeAreaViewForceInsetValue,
    },
    children?: React$Node,
    style?: AnimatedViewStyleProp,
  };
  declare var SafeAreaView: React$ComponentType<_SafeAreaViewProps>;

  declare var Header: React$ComponentType<HeaderProps> & {
    HEIGHT: number,
  };

  declare type _HeaderTitleProps = {
    children: React$Node,
    selectionColor?: string | number,
    style?: AnimatedTextStyleProp,
  };
  declare var HeaderTitle: React$ComponentType<_HeaderTitleProps>;

  declare type _HeaderBackButtonProps = {
    onPress?: () => void,
    pressColorAndroid?: string,
    title?: ?string,
    titleStyle?: ?TextStyleProp,
    tintColor?: ?string,
    truncatedTitle?: ?string,
    width?: ?number,
  };
  declare var HeaderBackButton: React$ComponentType<
    _HeaderBackButtonProps
  >;

  declare type _DrawerViewProps = {
    drawerLockMode?: 'unlocked' | 'locked-closed' | 'locked-open',
    drawerWidth: number | (() => number),
    drawerPosition: 'left' | 'right',
    drawerOpenRoute: string,
    drawerCloseRoute: string,
    drawerToggleRoute: string,
    contentComponent: React$ElementType,
    contentOptions?: {},
    style?: ViewStyleProp,
    useNativeAnimations: boolean,
    drawerBackgroundColor: string,
    screenProps?: {},
    navigation: NavigationScreenProp<NavigationState>,
    router: NavigationRouter<NavigationState, NavigationDrawerScreenOptions>,
  };
  declare var DrawerView: React$ComponentType<_DrawerViewProps>;

  declare type _DrawerScene = {
    route: NavigationRoute,
    focused: boolean,
    index: number,
    tintColor?: string,
  };
  declare type _DrawerItem = {
    route: NavigationRoute,
    focused: boolean,
  };
  declare type _DrawerItemsProps = {
    navigation: NavigationScreenProp<NavigationState>,
    items: Array<NavigationRoute>,
    activeItemKey?: ?string,
    activeTintColor?: string,
    activeBackgroundColor?: string,
    inactiveTintColor?: string,
    inactiveBackgroundColor?: string,
    getLabel: (scene: _DrawerScene) => ?(React$Node | string),
    renderIcon: (scene: _DrawerScene) => ?React$Node,
    onItemPress: (info: _DrawerItem) => void,
    itemsContainerForceInset?: Object,
    itemsContainerStyle?: ViewStyleProp,
    itemStyle?: ViewStyleProp,
    labelStyle?: TextStyleProp,
    iconContainerStyle?: ViewStyleProp,
    drawerPosition: 'left' | 'right',
  };
  declare var DrawerItems: React$ComponentType<_DrawerItemsProps>;

  declare type _TabViewProps = {
    tabBarComponent?: React$ElementType,
    tabBarPosition?: 'top' | 'bottom',
    tabBarOptions?: {},
    swipeEnabled?: boolean,
    animationEnabled?: boolean,
    configureTransition?: (
      currentTransitionProps: Object,
      nextTransitionProps: Object
    ) => Object,
    initialLayout: TabViewLayout,
    screenProps?: {},
    navigation: NavigationScreenProp<NavigationState>,
    router: NavigationRouter<NavigationState, NavigationTabScreenOptions>,
  };
  declare var TabView: React$ComponentType<_TabViewProps>;

  declare type _TabBarTopProps = {
    activeTintColor: string,
    inactiveTintColor: string,
    showIcon: boolean,
    showLabel: boolean,
    upperCaseLabel: boolean,
    allowFontScaling: boolean,
    position: AnimatedValue,
    tabBarPosition: string,
    navigation: NavigationScreenProp<NavigationState>,
    jumpToIndex: (index: number) => void,
    getLabel: (scene: TabScene) => ?(React$Node | string),
    getOnPress: (
      previousScene: NavigationRoute,
      scene: TabScene
    ) => ({
      previousScene: NavigationRoute,
      scene: TabScene,
      jumpToIndex: (index: number) => void,
    }) => void,
    renderIcon: (scene: TabScene) => React$Element<*>,
    labelStyle?: TextStyleProp,
    iconStyle?: ViewStyleProp,
  };
  declare var TabBarTop: React$ComponentType<_TabBarTopProps>;

  declare type _TabBarBottomProps = {
    activeTintColor: string,
    activeBackgroundColor: string,
    adaptive?: boolean,
    inactiveTintColor: string,
    inactiveBackgroundColor: string,
    showLabel: boolean,
    showIcon: boolean,
    allowFontScaling: boolean,
    position: AnimatedValue,
    navigation: NavigationScreenProp<NavigationState>,
    jumpToIndex: (index: number) => void,
    getLabel: (scene: TabScene) => ?(React$Node | string),
    getOnPress: (
      previousScene: NavigationRoute,
      scene: TabScene
    ) => ({
      previousScene: NavigationRoute,
      scene: TabScene,
      jumpToIndex: (index: number) => void,
    }) => void,
    getTestIDProps: (scene: TabScene) => (scene: TabScene) => any,
    renderIcon: (scene: TabScene) => React$Node,
    style?: ViewStyleProp,
    animateStyle?: ViewStyleProp,
    labelStyle?: TextStyleProp,
    tabStyle?: ViewStyleProp,
    showIcon?: boolean,
  };
  declare var TabBarBottom: React$ComponentType<_TabBarBottomProps>;

  declare type _NavigationInjectedProps = {
    navigation: NavigationScreenProp<NavigationStateRoute>,
  };
  declare function withNavigation<T: {}>(
    Component: React$ComponentType<T & _NavigationInjectedProps>
  ): React$ComponentType<T>;
  declare function withNavigationFocus<T: {}>(
    Component: React$ComponentType<T & _NavigationInjectedProps>
  ): React$ComponentType<T>;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PTrampert.CommandPattern
{
    public interface ICommand<TResult>
    {
    }
}

redpajama_set_name: RedPajamaGithub


text:
package google

import (
	"context"
	"log"

	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
)

// This will sweep both Standard and Flexible App Engine App Versions
func init() {
	resource.AddTestSweepers("AppEngineAppVersion", &resource.Sweeper{
		Name: "AppEngineAppVersion",
		F:    testSweepAppEngineAppVersion,
	})
}

// At the time of writing, the CI only passes us-central1 as the region
func testSweepAppEngineAppVersion(region string) error {
	resourceName := "AppEngineAppVersion"
	log.Printf("[INFO][SWEEPER_LOG] Starting sweeper for %s", resourceName)

	config, err := sharedConfigForRegion(region)
	if err != nil {
		log.Printf("[INFO][SWEEPER_LOG] error getting shared config for region: %s", err)
		return err
	}

	err = config.LoadAndValidate(context.Background())
	if err != nil {
		log.Printf("[INFO][SWEEPER_LOG] error loading: %s", err)
		return err
	}

	servicesUrl := "https://appengine.googleapis.com/v1/apps/" + config.Project + "/services"
	res, err := sendRequest(config, "GET", config.Project, servicesUrl, config.userAgent, nil)
	if err != nil {
		log.Printf("[INFO][SWEEPER_LOG] Error in response from request %s: %s", servicesUrl, err)
		return nil
	}

	resourceList, ok := res["services"]
	if !ok {
		log.Printf("[INFO][SWEEPER_LOG] Nothing found in response.")
		return nil
	}

	rl := resourceList.([]interface{})

	log.Printf("[INFO][SWEEPER_LOG] Found %d items in %s list response.", len(rl), resourceName)
	// Count items that weren't sweeped.
	nonPrefixCount := 0
	for _, ri := range rl {
		obj := ri.(map[string]interface{})
		if obj["id"] == nil {
			log.Printf("[INFO][SWEEPER_LOG] %s resource id was nil", resourceName)
			return nil
		}

		id := obj["id"].(string)
		// Increment count and skip if resource is not sweepable.
		if !isSweepableTestResource(id) {
			nonPrefixCount++
			continue
		}

		deleteUrl := servicesUrl + "/" + id
		// Don't wait on operations as we may have a lot to delete
		_, err = sendRequest(config, "DELETE", config.Project, deleteUrl, config.userAgent, nil)
		if err != nil {
			log.Printf("[INFO][SWEEPER_LOG] Error deleting for url %s : %s", deleteUrl, err)
		} else {
			log.Printf("[INFO][SWEEPER_LOG] Sent delete request for %s resource: %s", resourceName, id)
		}
	}

	if nonPrefixCount > 0 {
		log.Printf("[INFO][SWEEPER_LOG] %d items without tf_test prefix remain.", nonPrefixCount)
	}

	return nil
}


text:
package org.trustedanalytics.user.secure;

public class RuntimeEncryptionException extends RuntimeException {
    public RuntimeEncryptionException(String message) {
        super(message);
    }

    public RuntimeEncryptionException(String message, Throwable cause) {
        super(message, cause);
    }
}


text:
<?php

class PresupuestoController extends AppController
{
    public function index()
    {
        $this -> titulo = "Solicitar presupuesto";
        if(Input::hasPost('presupuesto'))
        {
            $datosIN = Input::post('presupuesto');
            $db = new Presupuestos($datosIN);
            if($db->create())
            {
                Redirect::to("/");
            } else {
                Flash::error("No se pudo tomar le pedido ahora, intente por las redes sociales");
            }
        }
    }
}

?>


text:
package org.redpill.alfresco.s3;

import com.amazonaws.services.s3.AmazonS3;
import io.findify.s3mock.S3Mock;
import java.util.Random;
import org.alfresco.repo.content.ContentContext;
import org.alfresco.repo.content.ContentStore;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.junit.After;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import org.redpill.alfresco.test.AbstractComponentIT;
import org.springframework.context.ApplicationContext;

/**
 *
 * @author Marcus Svartmark - Redpill Linpro AB
 */
public class S3ContentStoreIT extends AbstractComponentIT {

  private ContentStore s3ContentStore;
  private S3ContentStore s3ContentStoreImpl;
  private S3Mock api;
  private String bucket;

  static boolean isInitialized = false;

  @Before
  public void setUp() {
    ApplicationContext ctx = getApplicationContext();
    s3ContentStore = (ContentStore) ctx.getBean("redpill.defaultS3ContentStore");
    s3ContentStoreImpl = (S3ContentStore) ctx.getBean("redpill.defaultS3ContentStore");
    Random r = new Random();
    int randomPort = 20000 + r.nextInt(30000);
    //Start an s3 mock
    api = new S3Mock.Builder().withPort(randomPort).withInMemoryBackend().build();
    api.start();
    bucket = "alftestbucket" + System.currentTimeMillis();

    s3ContentStoreImpl.setBucketName(bucket);
    s3ContentStoreImpl.setEndpoint("http://localhost:" + randomPort);
    s3ContentStoreImpl.testInit();
    AmazonS3 s3Client = s3ContentStoreImpl.getS3Client();
    s3Client.createBucket(bucket);
  }

  @After
  public void tearDown() {
    AmazonS3 s3Client = s3ContentStoreImpl.getS3Client();
    s3Client.deleteBucket(bucket);
    api.stop();
  }

  @Test
  public void testSimpleTextContent() {
    for (int i = 0; i < 1000; i++) {
      doWrite();
    }
  }

  @Test
  public void testSimpleTextContent2() {

  }

  /*@Test
  public void testConcurrentThreadedWrite() throws InterruptedException {

    ExecutorService executorService = Executors.newFixedThreadPool(100);

    executorService.execute(() -> doWrite());

    executorService.shutdown();

  }*/
  public void doWrite() {
    final String TEST_TEXT_CONTENT = "test";
    ContentContext context = new ContentContext(null, null);
    ContentWriter writer = s3ContentStore.getWriter(context);
    writer.putContent(TEST_TEXT_CONTENT);
    String contentUrl = writer.getContentUrl();

    try {
      ContentReader reader = s3ContentStore.getReader(contentUrl);
      String contentString = reader.getContentString();
      assertEquals(TEST_TEXT_CONTENT, contentString);

    } finally {
      boolean delete = s3ContentStore.delete(contentUrl);
      assertTrue(delete);
    }
  }

}


text:
/**
 * Created by MIC on 2015/12/29.
 */

import ScriptedDanmaku from "./ScriptedDanmaku";
import ScriptedDanmakuLayoutManager from "./ScriptedDanmakuLayoutManager";
import ScriptedDanmakuProvider from "./ScriptedDanmakuProvider";
import ScriptedDanmakuLayer from "./ScriptedDanmakuLayer";
import * as dco from "./dco/index";

export {ScriptedDanmaku, ScriptedDanmakuLayoutManager, ScriptedDanmakuProvider, ScriptedDanmakuLayer};

export {dco};


text:
Quantum Coaster

CS 559 Fall 2007 - Project 2

priyananda shenoy ( shenoy@cs.wisc.edu )

This file describes the RollerCoaster project from the point of view of code and
implementation. For details regarding the user-interactions,
refer to readme.

Code Organization

  With a few exceptions, I have followed the one-file-one-class
rule: Each class is coded in one .h and one .cpp file, with the
file name same as the class name. Most of the classes have comments
describing them. The comments in the .h file usually tell what
the class/function does, and the comments in the .cpp file tell
how it is done.

The cpp/h files are separated into the following logical folders:

 command\ - classes which handle generic command processing

command\impl - classes for specific commands

tgalib\ - Targa-related code not written by me

state\ - environment during the execution

operations\ - code which does image operations like filters

Used Code ("honest plagiarism")

  The following specific pieces of code were not written by me:

 libtarga.h/libtarga.c - complete - unmodified
  from: Sample Solution for Project1 by Prof Gleicher

 TargaImage.h/.cpp - complete - unmodified
  from: Sample Solution for Project1 by Prof Gleicher

  I took ideas( not code or implementation ) from these sources:

http://www.poynton.com/notes/colour_and_gamma/ColorFAQ.html - Luminance calculation

Why does the project use Win32? Why not FLTK/GLUT?

	I'm not a masochist, I don't like programming in Win32. FLTK/Glut are much easier
to program against. But by the virtue of being simpler, they are also less powerful. I have
a few specific features in mind which I want to implement which I know can be done in Win32.

	The real reason I'm not using FLTK/Glut is because I'm lazy. Maybe the features I want can
	be implemented using FLTK/Glut but I'm too lazy to explore. I already know Win32, so there
	is nothing much to learn there. I'm better  off exploring things on the graphics side, than
	in exploring windowing systems.

	It isn't really a big deal. All windowing systems are wrappers over Win32 anyway, so all i'm
	doing is creating my own minimalistic wrapper on top of it.


text:
import unittest
import doctest
import jobs
import processing

class Fibonacci(processing.Process):
    """Compute a Fibonacci sequence up to n and store in 'results' list."""
    def __init__(self, n):
        super(Fibonacci, self).__init__()

        self.results = []
        self.n = n

    def run(self):
        a, b = 0, 1
        while b < self.n:
            self.results.append(b)
            a, b = b, a+b

class Empty(processing.Process):
    pass

class LocalJobRunnerTestCase(unittest.TestCase):
    def setUp(self):
        self.queue = []
        for i in xrange(0, 50):
            self.queue.append(Fibonacci(i))
        self.runner = jobs.LocalJobRunner(self.queue)

    def test_finished(self):
        self.assertFalse(self.runner.finished)
        self.runner.run()
        self.assertTrue(self.runner.finished)

    def test_time(self):
        self.runner.run()
        self.assertTrue(self.runner.runtime.elapsed > 0)
        self.assertEquals(50, len(self.runner.times))

    def test_queue_unaltered(self):
        self.assertEquals(50, len(self.queue))
        self.runner.run()
        self.assertEquals(50, len(self.queue))

def suite():
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(LocalJobRunnerTestCase))
    suite.addTest(doctest.DocTestSuite(jobs))
    return suite

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


text:
layout: post
title: EPEL primary.sqlite.bz2 404 Not Found errors
tags: [centos, epel]
---

I recently had an epic battle with yum and the [EPEL][1] repository. I wasted enough
time on it that I think it will be useful if others experience similar problems.

### The Problem ###

I recently installed a new VM with [CentOS 5.5 x86_64]. Like usual I add the EPEL
and [IUS Community][2] repositories so that I can have access to git 1.7, PHP 5.3,
MySQL 5.1, and Python 2.6 among other things. Everything was fine for 2 days until
I went to install a package today. A simple `yum install php53u-gd` resulted in a
wall of 404 error messages when it tried to fetch some cryptic bzipped file:

{% highlight text %}
http://nas1.itc.virginia.edu/fedora-epel/5/x86_64/repodata/bd1da...-primary.sqlite.bz2:
 [Errno 14] HTTP Error 404: Not Found
Trying other mirror.
Error: failure:
repodata/bd1dac3a3d6ad62385741a9d50273ec1b2bcbd76-primary.sqlite.bz2 from
epel: [Errno 256] No more mirrors to try.
{% endhighlight %}

I tried repeatedly to clean the yum metadata and cache, even `yum clean all` a few times. The problem persisted.

### Troubleshooting ###

My first step was to actually look at [one of the mirrors][3] returning 404 and verify that the file
truly wasn't there. Sure enough, it wasn't. I also noted that they had recently been updated on 09-Feb-2011.

![centos mirror repodata](/images/updatedrepo.png)

I checked several other mirrors that were 404'ing and saw the same thing. Where was my machine fetching
this information from? I asked around on IRC (#epel on freenode) and "nirik" suggested I try
`URLGRABBER_DEBUG=1 yum update` which gave me the following output:

{% highlight text %}
INFO:urlgrabber:attempt 1/10: http://mirrors.servercentral.net/fedora/epel/5/x86_64/repodata/repomd.xml
INFO:urlgrabber:creating new connection to mirrors.servercentral.net (405445232)
INFO:urlgrabber:STATUS: 200, OK
INFO:urlgrabber:success
{% endhighlight %}

Navigating to the [ServerCentral EPEL mirror][4] showed me the problem.

![servercentral repodata](/images/repodata.png)

The `bd1dac3a3d6ad62385741a9d50273ec1b2bcbd76-primary.sqlite.bz2` was not here either, but what really caught my
eye was that the repo hadn't been updated since 27-Jan-2011.

YUM keeps a cache of the EPEL RPM database and assorted metadata in `/var/cache/yum/epel`.
Checking this location on my system showed that I had the `bd1dac3a3d6ad62385741a9d50273ec1b2bcbd76-primary.sqlite.bz2`
file present. I also checked the contents of repomd.xml and found the root cause:

{% highlight xml %}
<data type="primary_db">
  <location href="repodata/bd1dac3a3d6ad62385741a9d50273ec1b2bcbd76-primary.sqlite.bz2"/>
  <checksum type="sha">bd1dac3a3d6ad62385741a9d50273ec1b2bcbd76</checksum>
  <timestamp>1296232850</timestamp>
  <size>3646557</size>
  <open-size>15332352</open-size>
  <open-checksum type="sha">b75a93c694f8cbfacca64e4d145a03595775f785</open-checksum>
  <database_version>10</database_version>
</data>
{% endhighlight %}

Aha! Not only was the mirror out of date, but the repomd.xml was out of sync with the mirror itself.

### The Solution ###

CentOS is configured to use the fastestmirror yum plugin by default. My machine had an affinity for the
ServerCentral mirror because it was the fastest. To fix this I simply edit `/etc/yum/pluginconf.d/fastestmirror.conf`
adding an exclude as shown:

{% highlight ini %}
[main]
enabled=1
verbose=0
socket_timeout=3
hostfilepath=/var/cache/yum/timedhosts.txt
maxhostfileage=10
maxthreads=15
exclude=servercentral.net
{% endhighlight %}

Follow this up with a simple `yum clean dbcache metadata` and you're golden!

[1]: http://fedoraproject.org/wiki/EPEL
[2]: http://iuscommunity.org
[3]: http://nas1.itc.virginia.edu/fedora-epel/5/x86_64/repodata/
[4]: http://mirrors.servercentral.net/fedora/epel/


text:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.eaw1805.data.model.NationsRelation" table="RELATIONS">
        <cache usage="read-write"/>
        <id name="id" column="RELATION_ID">
            <generator class="native"/>
        </id>

        <many-to-one name="game"
                     column="GAME_ID"
                     class="com.eaw1805.data.model.Game"
                     cascade="none"
                     lazy="false"/>

        <many-to-one name="nation"
                     column="NATION_ID"
                     class="com.eaw1805.data.model.Nation"
                     cascade="none"
                     lazy="false"/>

        <many-to-one name="target"
                     column="TARGET_NATION_ID"
                     class="com.eaw1805.data.model.Nation"
                     cascade="none"
                     lazy="false"/>

        <property name="relation"/>
        <property name="prisoners"/>
        <property name="turnCount"/>
        <property name="peaceCount"/>
        <property name="surrenderCount"/>
        <property name="visible" column="visibleToAlly"/>
        <property name="fixed"/>

    </class>
</hibernate-mapping>


text:
 0">

Networks

          Action
          Name
          Subnet
          IPv4 Address
          Mac Address

            Disconnect
            Connect

          {{:: net.Name }}
          {{:: config.Subnet }}
          {{ net.Containers[container.Id].IPv4Address }}
          {{ net.Containers[container.Id].MacAddress }}


text:
layout: attractions
title: Marlborough Sounds Attractions, Queen Charlotte Track, Tourist Attractions, walks, Fishing, Tours, Boating
keywords: Marlborough Sounds tourist attractions, Picton, walks, Queen Charlotte Track, Fishing, Tours, Boating
description: Marlborough Sounds Attractions including Queen Charlotte Track, tourist attractions Dolphin Watch Eco tours, Kayaking and Boating.

slug: banner-marlborough-sounds
banner-descr-main: Marlborough Sounds Bay

permalink: /marlborough-sounds-attractions.html

breadcrumbs: True
name: Marlborough Sounds
island: south
region: marlborough

side-nav:
- marlborough-sounds.html: About Marlborough Sounds
- marlborough-sounds-accommodation.html: Marlborough Sounds Accommodation
---

# Marlborough Sounds Attractions

A boat or Kayak trip is the best way to explore the natural beauty of the Marlborough Sounds. There are also many short and long walks around the shores of Queen Charlotte and other sounds. If you have a few days spare, we recommend walking the Queen Charlotte Track. There is no better way to experience the peace and tranquility of Queen Charlotte Sound. Another option is Steadfast Sail, who offer relaxing sailing cruises throughout the Sounds and beyond.


text:
namespace v8 {
namespace internal {

OBJECT_CONSTRUCTORS_IMPL(Oddball, HeapObject)

CAST_ACCESSOR(Oddball)

double Oddball::to_number_raw() const {
  return READ_DOUBLE_FIELD(*this, kToNumberRawOffset);
}

void Oddball::set_to_number_raw(double value) {
  WRITE_DOUBLE_FIELD(*this, kToNumberRawOffset, value);
}

void Oddball::set_to_number_raw_as_bits(uint64_t bits) {
  WRITE_UINT64_FIELD(*this, kToNumberRawOffset, bits);
}

ACCESSORS(Oddball, to_string, String, kToStringOffset)
ACCESSORS(Oddball, to_number, Object, kToNumberOffset)
ACCESSORS(Oddball, type_of, String, kTypeOfOffset)

byte Oddball::kind() const {
  return Smi::ToInt(READ_FIELD(*this, kKindOffset));
}

void Oddball::set_kind(byte value) {
  WRITE_FIELD(*this, kKindOffset, Smi::FromInt(value));
}

// static
Handle<Object> Oddball::ToNumber(Isolate* isolate, Handle<Oddball> input) {
  return Handle<Object>(input->to_number(), isolate);
}

bool HeapObject::IsBoolean() const {
  return IsOddball() &&
         ((Oddball::cast(*this)->kind() & Oddball::kNotBooleanMask) == 0);
}

}  // namespace internal
}  // namespace v8

#include "src/objects/object-macros-undef.h"

#endif  // V8_OBJECTS_ODDBALL_INL_H_


text:
package com.ilivoo.jdk.java.net;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory;

/**
 * 1. 该接口为 URL 流协议处理程序定义一个工厂。 URL 类使用它可为特定的协议创建 URLStreamHandler。
 * 2. 我们可以清楚的看见, 当我们需要创建自己的协议的时候, 就可以通过创建自己的协议工厂, 和具体的协议处理器, 再将其注册到URL
 *    当中, 其实我们可以看到URL中的static URLStreamHandlerFactory factory; 它是一个static的, 所以我们当我们注册之后, 它就
 *    在类存中保存起来, 是类的变量。这也是非常合理的。
 * @author 37.com
 *
 */
public class URLStreamHandlerFactoryTest {
	public static void main(String[] args) {

	}
}

/**
 * 创建自己的URLStreamHandlerFactory
 * @author 37.com
 *
 */
class MyURLStreamHandlerFactory implements URLStreamHandlerFactory{
	public static final String CLASS_PATH = "classpath:";

	public static final String URL_PROTOCAL = "jdbc://mysql";

	public URLStreamHandler createURLStreamHandler(String protocol) {
		if(CLASS_PATH.equalsIgnoreCase(protocol)){
			return new ClassPathURLStreamHandler();
		}
		if(URL_PROTOCAL.equalsIgnoreCase(protocol)){
			return new MySQLURLStreamHandler();
		}
		return new URLStreamHandler(){
			@Override
			protected URLConnection openConnection(URL u) throws IOException {
				return null;
			}
		};
	}
}

/**
 * 创建某种URLStreamHandler的具体的处理器
 * @author 37.com
 *
 */
class ClassPathURLStreamHandler extends URLStreamHandler{
	public static final String CLASS_PATH = "classpath:";
	@Override
	protected URLConnection openConnection(URL u) throws IOException {

		return null;
	}
}

class MySQLURLStreamHandler extends URLStreamHandler{
	public static final String URL_PROTOCAL = "jdbc://mysql";
	@Override
	protected URLConnection openConnection(URL u) throws IOException {
		return null;
	}
}


text:
package org.apache.eagle.alert.engine.sorter;

import org.apache.eagle.alert.engine.sorter.impl.StreamSortedWindowInMapDB;
import org.apache.eagle.alert.engine.sorter.impl.StreamSortedWindowOnHeap;
import com.google.common.base.Preconditions;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * ===== Benchmark Result Report =====

 *
 *
Num. Operation   Type                            Time

 * ---- ---------   ----                            ----

 * 1000    FlushTime    DIRECT_MEMORY                :    55

 * 1000    FlushTime    FILE_RAF                     :    63

 * 1000    FlushTime    MEMORY                       :    146

 * 1000    FlushTime    ONHEAP                       :    17

 * 1000    InsertTime    DIRECT_MEMORY               :    68

 * 1000    InsertTime    FILE_RAF                    :    223

 * 1000    InsertTime    MEMORY                      :    273

 * 1000    InsertTime    ONHEAP                      :    20

 * 10000    FlushTime    DIRECT_MEMORY               :    551

 * 10000    FlushTime    FILE_RAF                    :    668

 * 10000    FlushTime    MEMORY                      :    643

 * 10000    FlushTime    ONHEAP                      :    5

 * 10000    InsertTime    DIRECT_MEMORY              :    446

 * 10000    InsertTime    FILE_RAF                   :    2095

 * 10000    InsertTime    MEMORY                     :    784

 * 10000    InsertTime    ONHEAP                     :    29

 * 100000    FlushTime    DIRECT_MEMORY              :    6139

 * 100000    FlushTime    FILE_RAF                   :    6237

 * 100000    FlushTime    MEMORY                     :    6238

 * 100000    FlushTime    ONHEAP                     :    18

 * 100000    InsertTime    DIRECT_MEMORY             :    4499

 * 100000    InsertTime    FILE_RAF                  :    22343

 * 100000    InsertTime    MEMORY                    :    4962

 * 100000    InsertTime    ONHEAP                    :    107

 * 1000000    FlushTime    DIRECT_MEMORY             :    61356

 * 1000000    FlushTime    FILE_RAF                  :    63025

 * 1000000    FlushTime    MEMORY                    :    61380

 * 1000000    FlushTime    ONHEAP                    :    47

 * 1000000    InsertTime    DIRECT_MEMORY            :    43637

 * 1000000    InsertTime    FILE_RAF                 :    464481

 * 1000000    InsertTime    MEMORY                   :    44367

 * 1000000    InsertTime    ONHEAP                   :    2040

 *

 * @see StreamSortedWindowOnHeap
 * @see org.mapdb.DBMaker
 */
public class StreamWindowRepository {
    public enum StorageType {
        /**
         * Creates new in-memory database which stores all data on heap without serialization.
         * This mode should be very fast, but data will affect Garbage PartitionedEventCollector the same way as traditional Java Collections.
         */
        ONHEAP,

        /**
         * Creates new in-memory database. Changes are lost after JVM exits.
         * This option serializes data into {@code byte[]},
         * so they are not affected by Garbage PartitionedEventCollector.
         */
        MEMORY,

        /**
         *

         * Creates new in-memory database. Changes are lost after JVM exits.
         *

         * This will use {@code DirectByteBuffer} outside of HEAP, so Garbage Collector is not affected
         * You should increase ammount of direct memory with
         * {@code -XX:MaxDirectMemorySize=10G} JVM param
         *

         */
        DIRECT_MEMORY,

        /**
         * By default use File.createTempFile("streamwindows","temp")
         */
        FILE_RAF
    }

    private static final Logger LOG = LoggerFactory.getLogger(StreamWindowRepository.class);
    private final Map<StorageType, DB> dbPool;

    private StreamWindowRepository() {
        dbPool = new HashMap<>();
    }

    private static StreamWindowRepository repository;

    /**
     * Close automatically when JVM exists.
     *
     * @return StreamWindowRepository singletonInstance
     */
    public static StreamWindowRepository getSingletonInstance() {
        synchronized (StreamWindowRepository.class) {
            if (repository == null) {
                repository = new StreamWindowRepository();
                Runtime.getRuntime().addShutdownHook(new Thread() {
                    @Override
                    public void run() {
                        repository.close();
                    }
                });
            }
            return repository;
        }
    }

    private DB createMapDB(StorageType storageType) {
        synchronized (dbPool) {
            if (!dbPool.containsKey(storageType)) {
                DB db;
                switch (storageType) {
                    case ONHEAP:
                        db = DBMaker.heapDB().closeOnJvmShutdown().make();
                        LOG.info("Create ONHEAP mapdb");
                        break;
                    case MEMORY:
                        db = DBMaker.memoryDB().closeOnJvmShutdown().make();
                        LOG.info("Create MEMORY mapdb");
                        break;
                    case DIRECT_MEMORY:
                        db = DBMaker.memoryDirectDB().closeOnJvmShutdown().make();
                        LOG.info("Create DIRECT_MEMORY mapdb");
                        break;
                    case FILE_RAF:
                        try {
                            File file = File.createTempFile("window-", ".map");
                            file.delete();
                            file.deleteOnExit();
                            Preconditions.checkNotNull(file, "file is null");
                            db = DBMaker.fileDB(file).deleteFilesAfterClose().make();
                            LOG.info("Created FILE_RAF map file at {}", file.getAbsolutePath());
                        } catch (IOException e) {
                            throw new IllegalStateException(e);
                        }
                        break;
                    default:
                        throw new IllegalArgumentException("Illegal storage type: " + storageType);
                }
                dbPool.put(storageType, db);
                return db;
            }
            return dbPool.get(storageType);
        }
    }

    public StreamWindow createWindow(long start, long end, long margin, StorageType type) {
        StreamWindow ret;
        switch (type) {
            case ONHEAP:
                ret = new StreamSortedWindowOnHeap(start, end, margin);
                break;
            default:
                ret = new StreamSortedWindowInMapDB(
                    start, end, margin,
                    createMapDB(type),
                    UUID.randomUUID().toString()
                );
                break;
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Created new {}, type: {}", ret, type);
        }
        return ret;
    }

    public StreamWindow createWindow(long start, long end, long margin, StreamWindowStrategy strategy) {
        return strategy.createWindow(start, end, margin, this);
    }

    public StreamWindow createWindow(long start, long end, long margin) {
        return OnHeapStrategy.INSTANCE.createWindow(start, end, margin, this);
    }

    public void close() {
        for (Map.Entry<StorageType, DB> entry : dbPool.entrySet()) {
            entry.getValue().close();
        }
        dbPool.clear();
    }

    public interface StreamWindowStrategy {
        StreamWindow createWindow(long start, long end, long margin, StreamWindowRepository repository);
    }

    public static class OnHeapStrategy implements StreamWindowStrategy {
        public static final OnHeapStrategy INSTANCE = new OnHeapStrategy();

        @Override
        public StreamWindow createWindow(long start, long end, long margin, StreamWindowRepository repository) {
            return repository.createWindow(start, end, margin, StorageType.ONHEAP);
        }
    }

    public static class WindowSizeStrategy implements StreamWindowStrategy {
        private static final long ONE_HOUR = 3600 * 1000;
        private static final long FIVE_HOURS = 5 * 3600 * 1000;
        private final long onheapWindowSizeLimit;
        private final long offheapWindowSizeLimit;

        public static WindowSizeStrategy INSTANCE = new WindowSizeStrategy(ONE_HOUR, FIVE_HOURS);

        public WindowSizeStrategy(long onheapWindowSizeLimit, long offheapWindowSizeLimit) {
            this.offheapWindowSizeLimit = offheapWindowSizeLimit;
            this.onheapWindowSizeLimit = onheapWindowSizeLimit;

            if (this.offheapWindowSizeLimit < this.onheapWindowSizeLimit) {
                throw new IllegalStateException("offheapWindowSizeLimit " + this.offheapWindowSizeLimit + " < onheapWindowSizeLimit " + this.onheapWindowSizeLimit);
            }
        }

        @Override
        public StreamWindow createWindow(long start, long end, long margin, StreamWindowRepository repository) {
            long windowLength = end - start;
            if (windowLength <= onheapWindowSizeLimit) {
                return repository.createWindow(start, end, margin, StreamWindowRepository.StorageType.ONHEAP);
            } else if (windowLength > onheapWindowSizeLimit & windowLength <= offheapWindowSizeLimit) {
                return repository.createWindow(start, end, margin, StreamWindowRepository.StorageType.DIRECT_MEMORY);
            } else {
                return repository.createWindow(start, end, margin, StreamWindowRepository.StorageType.FILE_RAF);
            }
        }
    }
}


text:
<?php
/**
 * A specific strength in which a medical drug is available in a specific country.
 *
 * @see    http://schema.org/DrugStrength
*/
abstract class TypeDrugStrength extends TypeMedicalIntangible
{
	/**
	 * The Schema.org Type Scope
	 *
	 * @var string
	 */
	protected static $scope = 'https://schema.org/DrugStrength';

	/**
	 * An active ingredient, typically chemical compounds and/or biologic substances.
	 * Expected Type: Text
	 *
	 * @var	array
	 */
	protected static $activeIngredient = array('value' => 'activeIngredient',
		'expectedTypes' => array('Text')
	);

	/**
	 * The location in which the strength is available.
	 * Expected Type: AdministrativeArea
	 *
	 * @var	array
	 */
	protected static $availableIn = array('value' => 'availableIn',
		'expectedTypes' => array('AdministrativeArea')
	);

	/**
	 * The units of an active ingredient's strength, e.g. mg.
	 * Expected Type: Text
	 *
	 * @var	array
	 */
	protected static $strengthUnit = array('value' => 'strengthUnit',
		'expectedTypes' => array('Text')
	);

	/**
	 * The value of an active ingredient's strength, e.g. 325.
	 * Expected Type: Number
	 *
	 * @var	array
	 */
	protected static $strengthValue = array('value' => 'strengthValue',
		'expectedTypes' => array('Number')
	);

	/**
	 * Return the 'activeIngredient' Property value
	 *
	 * @return	string
	 */
	public static function pActiveIngredient()
	{
		return self::getValue(self::$activeIngredient);
	}

	/**
	 * Return the 'availableIn' Property value
	 *
	 * @return	string
	 */
	public static function pAvailableIn()
	{
		return self::getValue(self::$availableIn);
	}

	/**
	 * Return the 'strengthUnit' Property value
	 *
	 * @return	string
	 */
	public static function pStrengthUnit()
	{
		return self::getValue(self::$strengthUnit);
	}

	/**
	 * Return the 'strengthValue' Property value
	 *
	 * @return	string
	 */
	public static function pStrengthValue()
	{
		return self::getValue(self::$strengthValue);
	}
}


text:
package org.apache.shardingsphere.db.protocol.mysql.packet.binlog.management;

import com.google.common.base.Preconditions;
import lombok.Getter;
import lombok.ToString;
import org.apache.shardingsphere.db.protocol.mysql.constant.MySQLBinlogEventType;
import org.apache.shardingsphere.db.protocol.mysql.packet.binlog.AbstractMySQLBinlogEventPacket;
import org.apache.shardingsphere.db.protocol.mysql.packet.binlog.MySQLBinlogEventHeader;
import org.apache.shardingsphere.db.protocol.mysql.payload.MySQLPacketPayload;

/**
 * MySQL binlog format description event packet.
 *
 * @see FORMAT_DESCRIPTION_EVENT
 * @see WL#2540: Replication event checksums
 */
@Getter
@ToString
public final class MySQLBinlogFormatDescriptionEventPacket extends AbstractMySQLBinlogEventPacket {

    private final int binlogVersion = 4;

    private final byte[] mysqlServerVersion;

    private final int createTimestamp;

    private final int eventHeaderLength = 19;

    public MySQLBinlogFormatDescriptionEventPacket(final MySQLBinlogEventHeader binlogEventHeader, final MySQLPacketPayload payload) {
        super(binlogEventHeader);
        Preconditions.checkArgument(binlogVersion == payload.readInt2(), "Binlog version of FORMAT_DESCRIPTION_EVENT should always 4");
        mysqlServerVersion = payload.readStringFixByBytes(50);
        createTimestamp = payload.readInt4();
        Preconditions.checkArgument(eventHeaderLength == payload.readInt1(), "Length of the Binlog Event Header should always be 19.");
        skipTypeHeaderLength(payload);
        skipCheckSums(payload);
    }

    /**
     * Type header length is not fixed value, it depends on mysql server version.
     * Because the binlog event type may add in future version.
     * During test, the length in version 5.7.21, the length of FORMAT_DESCRIPTION_EVENT is 95 not 84.
     *
     * @param payload MySQL binlog packet payload
     */
    private void skipTypeHeaderLength(final MySQLPacketPayload payload) {
        payload.skipReserved(MySQLBinlogEventType.FORMAT_DESCRIPTION_EVENT.getValue() - 1);
        int eventLength = payload.readInt1();
        int remainLength = eventLength - 2 - 50 - 4 - 1 - (MySQLBinlogEventType.FORMAT_DESCRIPTION_EVENT.getValue() - 1) - 1;
        payload.skipReserved(remainLength);
    }

    private void skipCheckSums(final MySQLPacketPayload payload) {
        int checksumAlgorithmFlag = payload.readInt1();
        if (1 == checksumAlgorithmFlag) {
            payload.skipReserved(4);
        }
    }

    @Override
    protected void writeEvent(final MySQLPacketPayload payload) {
        // TODO
    }
}


text:
/*!
 * \file dnnl_eltwise-inl.h
 */

#ifndef MXNET_OPERATOR_NN_DNNL_DNNL_ELTWISE_INL_H_
#define MXNET_OPERATOR_NN_DNNL_DNNL_ELTWISE_INL_H_

#if MXNET_USE_ONEDNN == 1

#include "operator/nn/dnnl/dnnl_base-inl.h"
#include "operator/operator_common.h"

namespace mxnet {
namespace op {

using eltwise_fwd_t    = dnnl::eltwise_forward;
using eltwise_fwd_pd_t = dnnl::eltwise_forward::primitive_desc;

class DNNLEltwiseFwd {
 public:
  typedef OpSignature DNNLEltwiseSignature;

  static DNNLEltwiseFwd& GetCached(const NDArray& input,
                                   const NDArray& output,
                                   const dnnl::algorithm algorithm);

  explicit DNNLEltwiseFwd(const NDArray& input, const dnnl::algorithm algorithm);

  void Execute(const NDArray& input, const OpReqType& req, const NDArray& output);

 private:
  std::shared_ptr<eltwise_fwd_t> fwd;
  std::shared_ptr<eltwise_fwd_pd_t> fwd_pd;
};

template <dnnl::algorithm algorithm>
inline void DNNLEltwiseForward(const nnvm::NodeAttrs& attrs,
                               const OpContext& ctx,
                               const NDArray& input,
                               const OpReqType& req,
                               const NDArray& output) {
  DNNLEltwiseFwd& fwd = DNNLEltwiseFwd::GetCached(input, output, algorithm);
  fwd.Execute(input, req, output);
}

}  // namespace op
}  // namespace mxnet

#endif  // MXNET_USE_ONEDNN == 1
#endif  // MXNET_OPERATOR_NN_DNNL_DNNL_ELTWISE_INL_H_


text:
<?php
	function cleanConvert($str){
		return mb_convert_case($str, MB_CASE_TITLE, "UTF-8");
	}

	$filename="Export-CSV-File.csv";
	$list = array ();

    $header = array("Rankings", "Points", "Fullname", "Email", "Contact", "Address");
    array_push($list,  array_values($header));

	$row = array("1", "123", "John Smith", "johnsmith@yahoo.com", "09123", "Texas");
    array_push($list,  array_values($row));

	$row = array("2", "321", "Dhoe Lee", "dhoelee@yahoo.com", "0466123", "Korea");
    array_push($list,  array_values($row));

	$fopen = fopen('php://output', 'w');
	header('Content-Type: text/csv');
	header('Content-Disposition: attachment; filename="'.$filename.'"');
	header('Pragma: no-cache');
	header("Expires: 0");
	foreach ($list as $fopen_row) {
		fputcsv($fopen, $fopen_row);
	}

?>


text:
package com.velvetPearl.lottery.dataAccess.repositories;

import com.velvetPearl.lottery.dataAccess.models.LotteryNumber;
import com.velvetPearl.lottery.dataAccess.models.Ticket;

import java.util.ArrayList;
import java.util.concurrent.TimeoutException;

/**
 * Created by Stensig on 30-Sep-16.
 */
public interface ILotteryNumberRepository extends IFirebaseRepository {

    void startLotteryNumbersSyncForTicket(Object ticketId);

    void stopLotteryNumbersSyncForTicket(Object ticketId);

    void deleteLotteryNumber(LotteryNumber lotteryNumber);

    LotteryNumber saveLotteryNumber(LotteryNumber lotteryNumber);
}


text:
<?php

namespace Vich\TestBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

use Vich\TestBundle\Entity\Image;

class DefaultController extends Controller
{
    public function uploadAction()
    {
        $form = $this->getForm(new Image());

        return $this->render('VichTestBundle:Default:upload.html.twig', array(
            'form' => $form->createView(),
        ));
    }

    public function submitAction(Request $request)
    {
        $image = new Image();
        $form = $this->getForm($image);

        $form->submit($request);
        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();

            $em->persist($image);
            $em->flush();
        }

        return $this->render('VichTestBundle:Default:upload.html.twig', array(
            'form' => $form->createView(),
        ));
    }

    private function getForm(Image $image)
    {
        return $this->createFormBuilder($image)
            ->add('title', 'text')
            ->add('imageFile', 'vich_file', array(
                'mapping' => 'image_mapping',
            ))
            ->add('save', 'submit')
            ->getForm();
    }
}


text:
@implementation RJItemListViewController
#pragma makr - Life cycle
-(void) viewDidLoad{
    [super viewDidLoad];
    [self.view setBackgroundColor:RGBCOLOR(224, 224, 224)];
}
-(void) viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.title = @"全部记录";
}
@end


text:
<?php

namespace Drupal\hello_world\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\BlockPluginInterface;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides a 'Hello' Block.
 *
 * @Block(
 *   id = "hello_test_block",
 *   admin_label = @Translation("Hello test block"),
 *   category = @Translation("Hello test World"),
 * )
 */
class HelloTestBlock extends BlockBase implements BlockPluginInterface {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $config = $this->getConfiguration();

    if (!empty($config['hello_block_name'])) {
      $name = $config['hello_block_name'];
    }
    elseif (!empty($config['hello_block_abc'])) {
      $name = $config['hello_block_abc'];
    }
    else {
      $name = $this->t('to no one');
    }
    return array(
      '#markup' => $this->t('Hello @name! @test', array(
        '@name' => $name,
        '@test' => $config['hello_block_abc'],
      )),
    );
  }

   /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    $form = parent::blockForm($form, $form_state);

    $config = $this->getConfiguration();

    $form['hello_block_name'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Who'),
      '#description' => $this->t('Who do you want to say hello to?'),
      '#default_value' => isset($config['hello_block_name']) ? $config['hello_block_name'] : '',
    );
    $form['hello_block_abc'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Who me'),
      '#description' => $this->t('Who do you want to say hello to?'),
      '#default_value' => isset($config['hello_block_abc']) ? $config['hello_block_abc'] : '',
    );

    return $form;
  }

   /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    parent::blockSubmit($form, $form_state);
    $values = $form_state->getValues();
    $this->configuration['hello_block_abc'] = $values['hello_block_abc'];
    $this->configuration['hello_block_name'] = $values['hello_block_name'];
  }

   /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    $default_config = \Drupal::config('hello_world.settings');
    return array(
      'hello_block_name' => $default_config->get('hello.name'),
      'hello_block_abc' => $default_config->get('hello.wow'),
    );
  }

}


text:
package net.koofr.api.rest.v2;

import net.koofr.api.auth.Authenticator;
import net.koofr.api.http.Client;

public class Api extends Resource {

  public Api(String baseUrl, Authenticator auth, Client client) {
    super(auth, client, baseUrl);
  }

  public RSelf self() {
    return new RSelf(this);
  }

  public RGroups groups() {
    return new RGroups(this);
  }

  public RDevices devices() {
    return new RDevices(this);
  }

  public RMounts mounts() {
    return new RMounts(this);
  }

  public RShared shared() {
    return new RShared(this);
  }

  public RPlaces places() {
    return new RPlaces(this);
  }

  public RJobs jobs() {
    return new RJobs(this);
  }

  public RSearch search() {
    return new RSearch(this);
  }

  public RTrash trash() {
    return new RTrash(this);
  }

  public RUsers users() {
    return new RUsers(this);
  }

  public RLinkList links() {
    return new RLinkList(this);
  }

  public RReceiverList receivers() {
    return new RReceiverList(this);
  }

}


text:
<html>
<body>

Multipart resolution framework for handling file uploads.
Provides a PortletMultipartResolver strategy interface,
and a generic extension of the ActionRequest interface
for accessing multipart files in web application code.

</body>
</html>


text:
1.1.X.X changes
===============

- A proper fork of the Litecoin project on Github was made, incorporating all the changes that were in 1.1.3.0:
  - Reddcoin specific branding
  - Reddcoin specific block time, size, ...
  - Update of leveldb to version 1.15
  - Implemented KGW including the fix for problems at block 44877
  - Add spaces every 3 decimals in Qt client

- Following has been changed in comparison to the source of 1.1.3.0:
  - Restored information on automated testing
  - Fixed Github URL's in various places
  - Restored copyright for Litecoin Developers
  - Changed references to "Reddcoin Wiki" to Reddcoin website
  - Changed references to reddcoin.org to reddcoin.com
  - Fixed reference to .pro file in mac build
  - Source formatting
  - Any "unnecessary" changes to makefiles have been reverted. If Litecoin can build it like this, we should be able to do so too
  - Kept references to Litecoin Wiki for SSL setup instructions as we don't have any (yet)
  - Removed Litecoin addresses from Qt dialog box examples
  - Kept <defaultcodec> tags in translations
  - Reverted disabling of CLIENT_VERSION_BUILD in version.h
  - Used the commit from bitcoin repo to update leveldb to 1.15
  - Updated the addresses in Qt tests to a valid RDD address
  - Renamed litecoin.icns to reddcoin.icns according to config file


text:
require "spec_helper"

module Backup
  describe Logger::Console do
    let(:timestamp) { Time.now.utc.strftime("%Y/%m/%d %H:%M:%S") }

    before do
      expect_any_instance_of(Logger::Logfile).to receive(:log).never
      expect_any_instance_of(Logger::Syslog).to receive(:log).never
      Logger.configure do
        logfile.enabled = false
        syslog.enabled = false
        console.quiet = false
      end
    end

    describe "console logger configuration" do
      it "may be disabled via Logger.configure" do
        Logger.configure do
          console.quiet = true
        end
        Logger.start!

        expect_any_instance_of(Logger::Console).to receive(:log).never
        Logger.info "message"
      end

      it "may be forced enabled via the command line" do
        Logger.configure do
          # --no-quiet should set this to nil
          console.quiet = nil
        end
        Logger.configure do
          # attempt to disable once set to nil will be ignored
          console.quiet = true
        end
        Logger.start!

        expect_any_instance_of(Logger::Console).to receive(:log)
        Logger.info "message"
      end
    end

    describe "console logger usage" do
      before { Logger.start! }

      context "when IO is attached to a terminal" do
        before do
          allow($stdout).to receive(:tty?).and_return(true)
          allow($stderr).to receive(:tty?).and_return(true)
        end

        it "sends colorized, formatted :info message to $stdout" do
          expect($stderr).to receive(:puts).never
          Timecop.freeze do
            expect($stdout).to receive(:puts).with([
              "\e[32m[#{timestamp}][info] message line one\e[0m",
              "\e[32m[#{timestamp}][info] message line two\e[0m"
            ])
            Logger.info "message line one\nmessage line two"
          end
        end

        it "sends colorized, formatted :warn message to $stderr" do
          expect($stdout).to receive(:puts).never
          Timecop.freeze do
            expect($stderr).to receive(:puts).with([
              "\e[33m[#{timestamp}][warn] message line one\e[0m",
              "\e[33m[#{timestamp}][warn] message line two\e[0m"
            ])
            Logger.warn "message line one\nmessage line two"
          end
        end

        it "sends colorized, formatted :error message to $stderr" do
          expect($stdout).to receive(:puts).never
          Timecop.freeze do
            expect($stderr).to receive(:puts).with([
              "\e[31m[#{timestamp}][error] message line one\e[0m",
              "\e[31m[#{timestamp}][error] message line two\e[0m"
            ])
            Logger.error "message line one\nmessage line two"
          end
        end
      end # context 'when IO is attached to a terminal'

      context "when IO is not attached to a terminal" do
        before do
          allow($stdout).to receive(:tty?).and_return(false)
          allow($stderr).to receive(:tty?).and_return(false)
        end

        it "sends non-colorized, formatted :info message to $stdout" do
          expect($stderr).to receive(:puts).never
          Timecop.freeze do
            expect($stdout).to receive(:puts).with([
              "[#{timestamp}][info] message line one",
              "[#{timestamp}][info] message line two"
            ])
            Logger.info "message line one\nmessage line two"
          end
        end

        it "sends non-colorized, formatted :warn message to $stderr" do
          expect($stdout).to receive(:puts).never
          Timecop.freeze do
            expect($stderr).to receive(:puts).with([
              "[#{timestamp}][warn] message line one",
              "[#{timestamp}][warn] message line two"
            ])
            Logger.warn "message line one\nmessage line two"
          end
        end

        it "sends non-colorized, formatted :error message to $stderr" do
          expect($stdout).to receive(:puts).never
          Timecop.freeze do
            expect($stderr).to receive(:puts).with([
              "[#{timestamp}][error] message line one",
              "[#{timestamp}][error] message line two"
            ])
            Logger.error "message line one\nmessage line two"
          end
        end
      end # context 'when IO is not attached to a terminal'
    end
  end
end


text:
package edu.cmu.sv.modelinference.modeltool.handlers;

import edu.cmu.sv.modelinference.common.api.LogHandler;
import edu.cmu.sv.modelinference.common.api.LogProcessingException;
import edu.cmu.sv.modelinference.modeltool.mc.ModelCheckerAdapter;
import edu.cmu.sv.modelinference.modeltool.mc.uppaal.UppaalModelChecker;

/**
 * @author Kasper Luckow
 *
 */
public class UppaalLog2ModelHandler implements LogHandler<ModelCheckerAdapter<?, ?>> {

  private static UppaalLog2ModelHandler instance = null;

  public static UppaalLog2ModelHandler getInstance() {
    if(instance == null) {
      instance = new UppaalLog2ModelHandler();
    }
    return instance;
  }

  private UppaalLog2ModelHandler() {  }

  @Override
  public String getHandlerName() {
    return "uppaal";
  }

  @Override
  public ModelCheckerAdapter<?, ?> process(String logFile, String logType, String[] additionalCmdArgs) throws LogProcessingException {
    return new UppaalModelChecker();
  }

}


text:
package org.zsl.testmybatis;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.alibaba.fastjson.JSON;
import com.kindle.kinbook.bean.User;
import com.kindle.kinbook.service.IUserService;

@RunWith(SpringJUnit4ClassRunner.class)		//表示继承了SpringJUnit4ClassRunner类
@ContextConfiguration(locations = {"classpath:spring-mybatis.xml"})

public class TestMyBatis {
	private static Logger logger = Logger.getLogger(TestMyBatis.class);
//	private ApplicationContext ac = null;
	@Resource
	private IUserService userService = null;

//	@Before
//	public void before() {
//		ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//		userService = (IUserService) ac.getBean("userService");
//	}

	@Test
	public void test1() {
//		User user = userService.getUserById(1);
		// System.out.println(user.getUserName());
		// logger.info("值:"+user.getUserName());
//		logger.info(JSON.toJSONString(user));
	}
}


text:
"""
    Hbond extension

    Find all hydrogen bonds as determined by the cutoffs below.
    Uses PDB2PQR to determine donors and acceptors, and displays
    all available bonds to stdout.  Please read the "NOTE" comments
    within the code for additional important information.

    Authors:  Todd Dolinsky, Michael J Bradley
"""

__date__ = "17 February 2006"
__author__ = "Todd Dolinsky"
# NOTE: This extension edited and updated on 05 August 2008 by Michael J Bradley
# NOTE: The definitions for hbonds used below were utilized in the following study:
# Bradley MJ, Chivers PT, Baker NA. Molecular dynamics simulation of the Escherichia coli NikR protein: Equilibrium conformational fluctuations reveal inter-domain allosteric communication pathways. Journal of Molecular Biology, 378, 1155-1173, 2008.  http://dx.doi.org/10.1016/j.jmb.2008.03.010

import sys

from src.utilities import *
from src.routines import *

# NOTE: You should try different angle cutoffs and see how they affect your results
ANGLE_CUTOFF = 30.0       # A - D - H(D) angle
#ANGLE_CUTOFF = 20.0       # A - D - H(D) angle

# NOTE: This hbond extension uses a different distance definition (not the H(D) - A distance).  You should still try different values for this distance cutoff and see how it affects your results.
DIST_CUTOFF = 3.4         # D to A distance

# NOTE: If you wish to use the previous hbond.py defintiion, comment out "DIST_CUTOFF" above, uncomment the next line below, and change "ANGLE_CUTOFF" to 20.0
#DIST_CUTOFF = 3.3         # H(D) to A distance

def usage():
    str  = "        --hbond       :  Print a list of hydrogen bonds to\n"
    str += "                         {output-path}.hbond\n"
    return str

def hbond(routines, outroot):
    """
        Print a list of hydrogen bonds.

        Parameters
            routines:  A link to the routines object
            outroot:   The root of the output name
    """
    outname = outroot + ".hbond"
    file = open(outname, "w")

    routines.write("Printing hydrogen bond list...\n")

    sys.stderr.write("Warning: New H-bonding definition is being used- see hbond.py in extensions directory for details!\n")

    file.write("# Warning: New H-bonding definition is being used- see hbond.py in extensions directory for details!\n")

    # Initialize - set nearby cells, donors/acceptors
    # The cell size adds one for the D-H(D) bond, and rounds up

    cellsize = int(DIST_CUTOFF + 1.0 + 1.0)
    protein = routines.protein
    routines.setDonorsAndAcceptors()
    routines.cells = Cells(cellsize)
    routines.cells.assignCells(protein)

    for donor in protein.getAtoms():

        # Grab the list of donors
        if not donor.hdonor: continue
        donorhs = []
        for bond in donor.bonds:
            if bond.isHydrogen(): donorhs.append(bond)
        if donorhs == []: continue

        # For each donor, grab all acceptors

        closeatoms = routines.cells.getNearCells(donor)
        for acc in closeatoms:
            if not acc.hacceptor: continue
            if donor.residue == acc.residue: continue
            for donorh in donorhs:

                # Do distance and angle checks

                #NOTE: If you wish to use the previous hbond.py definition, toggle the "dist" variable comments below
				#dist = distance(donorh.getCoords(), acc.getCoords())
                dist = distance(donor.getCoords(), acc.getCoords())
                if dist > DIST_CUTOFF: continue
                angle = getAngle(acc.getCoords(), donor.getCoords(), donorh.getCoords())
                if angle > ANGLE_CUTOFF: continue
                routines.write("Donor: %s %s\tAcceptor: %s %s\tdist: %.2f\tAngle: %.2f\n" % \
                      (donor.residue, donor.name, acc.residue, acc.name, dist, angle))
                file.write("Donor: %s %s\tAcceptor: %s %s\tdist: %.2f\tAngle: %.2f\n" % \
                      (donor.residue, donor.name, acc.residue, acc.name, dist, angle))

    routines.write("\n")
    file.close()


text:
source /home/pi/.virtualenvs/cv/bin/activate
python /home/pi/motiontracker/facedetect.py -p 1


text:
#ifndef SEARCHENGINEUNITTESTS_H
#define SEARCHENGINEUNITTESTS_H

#include <QObject>
#include <QtTest/QtTest>
#include "searchengine.h"

class SearchEngineUnitTests: public QObject
{
    Q_OBJECT

private slots:
    void initTestCase();

    void cleanupTestCase();

    void init();
    void cleanup();

    void testNewPlaylist();
    void testDeletePlaylist();

    void testAddItem();
    void testDeleteItem();

    void testGetPlaylist();
    void testGetPlaylistItem();

    void testAddItems();
};

#endif //SEARCHENGINEUNITTESTS_H


text:
__version__ = '0.1b8'

import functools
import logging
import os
import sys
import shutil
import jinja2

import aiohttp
import aiohttp.web
import aiohttp_security
import aiohttp_session.redis_storage
import aioredis
import aiopg
import aiopg.sa
import sys
import json
import requests_oauthlib
import ssl
import modconf
import argparse
import asyncio
import pickle
import subprocess

import ws_sheets.tests.functions
import ws_sheets_server

import ws_web_aiohttp.server

logger = logging.getLogger(__name__)

BASE_DIR = os.path.dirname(__file__)

def runserver(args):
    ws_web_aiohttp.server.runserver(args)

def install(args):
    # copy systemd file
    shutil.copyfile(
            os.path.join(BASE_DIR, 'ws_web_aiohttp.service'),
            os.path.join('/lib/systemd/system', 'ws_web_aiohttp.service'))

    config_dir_dst = '/etc/ws_web_aiohttp/conf'

    # make etc directory
    try:
        os.makedirs(config_dir_dst)
    except: pass

    # copy default config file
    shutil.copyfile(
            os.path.join(BASE_DIR, 'tests/conf/simple_secure.py'),
            os.path.join(config_dir_dst, 'simple_secure.py'))
    shutil.copyfile(
            os.path.join(BASE_DIR, 'tests/conf/simple_console_secure.py'),
            os.path.join(config_dir_dst, 'simple_console_secure.py'))

    p = subprocess.Popen(('systemctl', 'daemon-reload'))
    p.communicate()
    p = subprocess.Popen(('systemctl', 'restart', 'ws_web_aiohttp.service'))
    p.communicate()

def main(argv):
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers()

    def help_(args):
        parser.print_help()

    parser.set_defaults(func=help_)

    parser_runserver = subparsers.add_parser('runserver')
    parser_runserver.add_argument('--conf_dir')
    parser_runserver.add_argument('conf_mod')
    parser_runserver.add_argument('-d', action='store_true')
    parser_runserver.add_argument('-p', type=int, help='port')
    parser_runserver.set_defaults(func=runserver)

    parser_install = subparsers.add_parser('install')
    parser_install.set_defaults(func=install)

    args = parser.parse_args(argv[1:])
    args.func(args)

if __name__=='__main__':
    main(sys.argv)


text:
define(["require", "exports", '../View', '../../util/ArrayList'], function (require, exports, View_1, ArrayList_1) {
    "use strict";
    var ViewManager = (function () {
        function ViewManager(di, views) {
            this.setDi(di);
            this._views = new ArrayList_1.ArrayList(views);
        }
        ViewManager.prototype.viewExists = function (index) {
            if (typeof index === 'number') {
                return this.getView(index) !== undefined;
            }
            if (typeof index === 'string') {
                return this.getViewByName(index) !== null;
            }
            if (typeof index === 'object' && index instanceof View_1.View) {
                var check = false;
                for (var _i = 0, _a = this.toArray(); _i < _a.length; _i++) {
                    var v = _a[_i];
                    if (v === index) {
                        check = true;
                        break;
                    }
                }
                return check;
            }
            return false;
        };
        ViewManager.prototype.getViewByName = function (name) {
            for (var _i = 0, _a = this.toArray(); _i < _a.length; _i++) {
                var v = _a[_i];
                if (v.getName() == name) {
                    return v;
                }
            }
            return null;
        };
        ViewManager.prototype.getView = function (index) {
            if (typeof index === 'number') {
                return this._views.get(index);
            }
            else if (typeof index === 'string') {
                return this.getViewByName(index);
            }
        };
        ViewManager.prototype.addView = function (view) {
            if (this._di.has('viewEngine')) {
                view.setViewEngine(this._di.get('viewEngine'));
            }
            this._views.add(view);
        };
        ViewManager.prototype.removeView = function (view) {
            this._views.remove(view);
        };
        ViewManager.prototype.renderView = function (index) {
            this.getView(index).render();
        };
        ViewManager.prototype.renderAll = function () {
            for (var _i = 0, _a = this.toArray(); _i < _a.length; _i++) {
                var v = _a[_i];
                v.render();
            }
        };
        ViewManager.prototype.parseView = function (index) {
            this.getView(index).parse();
        };
        ViewManager.prototype.parseAll = function () {
            for (var _i = 0, _a = this.toArray(); _i < _a.length; _i++) {
                var v = _a[_i];
                v.parse();
            }
        };
        ViewManager.prototype.toArray = function () {
            return this._views.toArray();
        };
        /**
         * Set the dependency injection container.
         * @param {object} di : The dependency injection container.
         */
        ViewManager.prototype.setDi = function (di) {
            this._di = di;
        };
        /**
         * Returns the dependecy injection container.
         * @return {object} : The dependency injection container.
         */
        ViewManager.prototype.getDi = function () {
            return this._di;
        };
        return ViewManager;
    }());
    exports.ViewManager = ViewManager;
});


text:
FROM base/archlinux

RUN pacman -Sy
RUN pacman-key --init && pacman-key --refresh-keys
# Il peut y avoir sous Archlinux une erreur de signature, la commande précédente résout le problème
RUN pacman -S --noconfirm php-cgi git curl gcc openssl sudo
RUN pacman -S --noconfirm base-devel
# Il faut installer sous Archlinux le paquet "openssl" lorsqu'on récupère un contenu avec GitHub ou avec CURL, sinon
# il y aura l'erreur : "git-remote-https: symbol lookup error: /usr/lib/libcurl.so.4: undefined symbol: SSL_CTX_set_alpn_protos"
# Sous Archlinux, pour que makepkg fonctionne pleinement il faut installer le paquet base-devel (qui installera notamment l'environnement fakeroot)
RUN pacman-db-upgrade
# Pour corriger l'erreur : failed to initialize alpm library (database is incorrect version: /var/lib/pacman/
RUN ls
RUN git clone https://github.com/CosyVerif/paquito
WORKDIR paquito/
RUN curl -sS https://getcomposer.org/installer | php -d extension=phar.so -c php.ini
RUN php -c php.ini composer.phar install --no-dev
RUN mkdir Paquito-src/

RUN git clone  https://github.com/CosyVerif/paquito
RUN cp -R paquito/* Paquito-src/
RUN rm -Rf paquito/
RUN php -c php.ini src/Main.php generate pconf_paquito.yml
RUN ls -l


text:
<?php
/**
 * This default controller automatically creates a REST Server for your MongoDB Database
 */

$defaultRestObj = new MongoRest ();

$this->_restData = $defaultRestObj;


text:
package uk.co.flax.biosolr.pdbe.fasta;

//import static org.mockito.Mockito.mock;
//import static org.mockito.Mockito.when;

import java.io.IOException;
//import java.nio.file.Files;
//import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.Set;

import javax.xml.rpc.ServiceException;

import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.search.xjoin.XJoinResults;
import org.apache.solr.search.xjoin.XJoinResultsFactory;

import uk.ac.ebi.webservices.axis1.stubs.fasta.InputParameters;
import uk.ac.ebi.webservices.axis1.stubs.fasta.JDispatcherService_PortType;
import uk.ac.ebi.webservices.axis1.stubs.fasta.JDispatcherService_Service;
import uk.ac.ebi.webservices.axis1.stubs.fasta.JDispatcherService_ServiceLocator;
//import uk.ac.ebi.webservices.axis1.stubs.fasta.WsResultType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Connect to FASTA service and generate a PDB id filter based on a user
 * supplied sequence.
 */
public class FastaXJoinResultsFactory implements XJoinResultsFactory<String> {

  private static final Logger LOG = LoggerFactory.getLogger(FastaXJoinResultsFactory.class);

  // initialisation parameters
  public static final String INIT_EMAIL = "email";
  public static final String INIT_PROGRAM = "program";
  public static final String INIT_DATABASE = "database";
  public static final String INIT_STYPE = "stype";
  public static final String INIT_DEBUG_FILE = "debug.file";

  // request parameters
  public static final String FASTA_EXPLOWLIM = "explowlim";
  public static final String FASTA_EXPUPPERLIM = "expupperlim";
  public static final String FASTA_SEQUENCE = "sequence";
  public static final String FASTA_SCORES = "scores";
  public static final String FASTA_ALIGNMENTS = "alignments";
  public static final String FASTA_UNIQUE_PDB_IDS = "unique_pdb_ids";

  private JDispatcherService_PortType fasta;
  private String email;
  private String program;
  private String database;
  private String sType;

  @Override
  @SuppressWarnings("rawtypes")
  public void init(NamedList args) {
    LOG.info("initialising FastaXJoinResultsFactory");

    String debugFile = (String) args.get(INIT_DEBUG_FILE);
    if (debugFile != null) {
//      try {
//        byte[] result = Files.readAllBytes(Paths.get(debugFile));
//        fasta = mock(JDispatcherService_PortType.class);
//        when(fasta.getStatus(null)).thenReturn(FastaStatus.DONE);
//        WsResultType[] types = new WsResultType[] { mock(WsResultType.class) };
//        when(fasta.getResultTypes(null)).thenReturn(types);
//        when(fasta.getResult(null, null, null)).thenReturn(result);
//      } catch (IOException e) {
//        throw new RuntimeException(e);
//      }
        throw new UnsupportedOperationException("debug file not supported");
    }
    else {
      JDispatcherService_Service service = new JDispatcherService_ServiceLocator();
      try {
        fasta = service.getJDispatcherServiceHttpPort();
      } catch (ServiceException e) {
        throw new RuntimeException(e);
      }
    }

    email = (String) args.get(INIT_EMAIL);
    if (email == null || email.isEmpty()) {
        throw new RuntimeException("external email parameter is required");
    }
    LOG.info("email=" + email);

    program = (String) args.get(INIT_PROGRAM);
    if (program == null || program.isEmpty()) {
        throw new RuntimeException("external program parameter is required");
    }
    LOG.info("program=" + program);

    database = (String) args.get(INIT_DATABASE);
    if (database == null || database.isEmpty()) {
        throw new RuntimeException("external database parameter is required");
    }
    LOG.info("database=" + database);

    sType = (String) args.get(INIT_STYPE);
    if (sType == null || sType.isEmpty()) {
        throw new RuntimeException("external stype parameter is required");
    }
    LOG.info("sType=" + sType);
  }

  private String getParam(SolrParams params, String name) {
    String value = params.get(name);
    if (value == null || value.length() == 0) {
      throw new RuntimeException("Missing or empty " + name);
    }
    return value;
  }

  /**
   * Call out to the FASTA service and add a filter query based on the response.
   */
  @Override
  public XJoinResults<String> getResults(SolrParams params) throws IOException {
    InputParameters input = new InputParameters();
    input.setProgram(program);
    input.setDatabase(new String[] { database });
    input.setStype(sType);
    input.setSequence(getParam(params, FASTA_SEQUENCE));
    input.setExplowlim(new Double(getParam(params, FASTA_EXPLOWLIM)));
    input.setExpupperlim(new Double(getParam(params, FASTA_EXPUPPERLIM)));
    input.setScores(new Integer(getParam(params, FASTA_SCORES)));
    input.setAlignments(new Integer(getParam(params, FASTA_ALIGNMENTS)));

    FastaJob job = new FastaJob(fasta, email, input);
    job.run();

    if (!job.resultsOk()) {
      if (job.getException() != null) {
        throw new RuntimeException(job.getException());
      }
      if (!FastaStatus.DONE.equals(job.getStatus())) {
        throw new RuntimeException("Unexpected FASTA job status: "
            + job.getStatus());
      }
      if (job.isInterrupted()) {
        throw new RuntimeException("FASTA job was interrupted");
      }
      throw new RuntimeException("No results");
    }

    return new Results(job.getResults());
  }

  public static class Results implements XJoinResults<String> {

    private FastaJobResults results;

    public Results(FastaJobResults results) {
      this.results = results;
    }

    @Override
    public Iterable<String> getJoinIds() {
      Set<PDb.Id> pdbIds = results.getAlignments().keySet();
      String[] entries = new String[pdbIds.size()];
      int i = 0;
      for (PDb.Id pdbId : pdbIds) {
        entries[i++] = pdbId.toString().toLowerCase();
      }
      Arrays.sort(entries);
      return Arrays.asList(entries);
    }

    @Override
    public Collection<PDb.Alignment> getResult(String joinId) {
      Map<String, PDb.Alignment> map = results.getAlignments().get(new PDb.Id(joinId.toUpperCase()));
      return map != null ? map.values() : null;
    }

    public int getNumChains() {
      return results.getNumChains();
    }

    public int getNumEntries() {
      return results.getNumEntries();
    }

  }

}