text:
* [
      mobileplayer
      /
      mobileplayer-ios
](https://github.com/mobileplayer/mobileplayer-ios):
      A powerful and completely customizable media player for iOS

* [
      jakarmy
      /
      swift-summary
](https://github.com/jakarmy/swift-summary):
      A summary of Apple's Swift language written on Playgrounds

* [
      delba
      /
      JASON
](https://github.com/delba/JASON):
      Fast JSON parsing for Swift

* [
      kciter
      /
      GlitchLabel
](https://github.com/kciter/GlitchLabel):
      G..lit...c...hing UILa..bel fo..r iO...S

* [
      soyersoyer
      /
      SwCrypt
](https://github.com/soyersoyer/SwCrypt):
      RSA public/private key generation, RSA, AES encryption/decryption, SEM encryption in Swift with CommonCrypto in iOS and OS X

* [
      vsouza
      /
      awesome-ios
](https://github.com/vsouza/awesome-ios):
      A curated list of awesome iOS ecosystem, including Objective-C and Swift Projects

* [
      Alamofire
      /
      Alamofire
](https://github.com/Alamofire/Alamofire):
      Elegant HTTP Networking in Swift

* [
      kirualex
      /
      SwiftyGif
](https://github.com/kirualex/SwiftyGif):
      High performance GIF engine

* [
      Polidea
      /
      RxBluetoothKit
](https://github.com/Polidea/RxBluetoothKit):
      iOS & OSX Bluetooth library for RxSwift

* [
      producthunt
      /
      producthunt-osx
](https://github.com/producthunt/producthunt-osx):
      The best new products, every day on Mac.

* [
      BradLarson
      /
      GPUImage2
](https://github.com/BradLarson/GPUImage2):
      GPUImage 2 is a BSD-licensed Swift framework for GPU-accelerated video and image processing.

* [
      caiobzen
      /
      MessageBalloon
](https://github.com/caiobzen/MessageBalloon):
      A message balloon animation made with CoreAnimation

* [
      KevinCoble
      /
      AIToolbox
](https://github.com/KevinCoble/AIToolbox):
      A toolbox of AI modules written in Swift: Graphs/Trees, Support Vector Machines, Neural Networks, PCA, K-Means, Genetic Algorithms

* [
      liu044100
      /
      Smile-Lock
](https://github.com/liu044100/Smile-Lock):
      A library for make a beautiful Passcode Lock View

* [
      shaps80
      /
      Peek
](https://github.com/shaps80/Peek):
      Take a Peek at your application.

* [
      delba
      /
      TextAttributes
](https://github.com/delba/TextAttributes):
      An easier way to compose attributed strings

* [
      DianQK
      /
      LearnRxSwift
](https://github.com/DianQK/LearnRxSwift):
* [
      danielgindi
      /
      Charts
](https://github.com/danielgindi/Charts):
      Beautiful charts for iOS/tvOS/OSX! The Apple side of the crossplatform MPAndroidChart.

* [
      SwiftyJSON
      /
      SwiftyJSON
](https://github.com/SwiftyJSON/SwiftyJSON):
      The better way to deal with JSON data in Swift

* [
      JakeLin
      /
      IBAnimatable
](https://github.com/JakeLin/IBAnimatable):
      Design and prototype UI, interaction, navigation, transition and animation for App Store ready Apps in Interface Builder with IBAnimatable.

* [
      yannickl
      /
      DynamicButton
](https://github.com/yannickl/DynamicButton):
      Yet another animated flat buttons in Swift

* [
      aaaron7
      /
      SwiftyDown
](https://github.com/aaaron7/SwiftyDown):
      SwiftyDown - Simple, Elegant, Powerful markdown parser written in swift.

* [
      ipader
      /
      SwiftGuide
](https://github.com/ipader/SwiftGuide):
      这份指南汇集了Swift语言主流学习资源,并以开发者的视角整理编排。http://dev.swiftguide.cn

* [
      matteocrippa
      /
      awesome-swift
](https://github.com/matteocrippa/awesome-swift):
      A collaborative list of awesome swift resources. Feel free to contribute!

* [
      Carthage
      /
      Carthage
](https://github.com/Carthage/Carthage):
      A simple, decentralized dependency manager for Cocoa

####objective-c
* [
      Draveness
      /
      iOS-Source-Code-Analyze
](https://github.com/Draveness/iOS-Source-Code-Analyze):
      关于 iOS 开源项目源代码解析的文章

* [
      kasper
      /
      phoenix
](https://github.com/kasper/phoenix):
      A lightweight OS X window and app manager scriptable with JavaScript

* [
      AFNetworking
      /
      AFNetworking
](https://github.com/AFNetworking/AFNetworking):
      A delightful networking framework for iOS, OS X, watchOS, and tvOS.

* [
      bang590
      /
      JSPatch
](https://github.com/bang590/JSPatch):
      JSPatch bridge Objective-C and Javascript using the Objective-C runtime. You can call any Objective-C class and method in JavaScript by just including a small engine. JSPatch is generally use for hotfix iOS App.

* [
      facebook
      /
      FBMemoryProfiler
](https://github.com/facebook/FBMemoryProfiler):
      iOS tool that helps with profiling iOS Memory usage.

* [
      ResearchKit
      /
      ResearchKit
](https://github.com/ResearchKit/ResearchKit):
      ResearchKit is an open source software framework that makes it easy to create apps for medical research or for other research projects.

* [
      Tuccuay
      /
      RuntimeSummary
](https://github.com/Tuccuay/RuntimeSummary):
      一个集合了常用 Objective-C Runtime 使用方法的 Playground。

* [
      CoderMJLee
      /
      MJRefresh
](https://github.com/CoderMJLee/MJRefresh):
      An easy way to use pull-to-refresh.

* [
      577528249
      /
      TTNews
](https://github.com/577528249/TTNews):
      一个集新闻与娱乐于一体的iOS新闻客户端 。(为增大搜索概率的关键词:News client,新浪新闻客户端,网易新闻,搜狐新闻,搜狐新闻,腾讯新闻,今日头条,百思不得姐,摇一摇夜间模式,视频播放)新手项目,多多包涵,谢谢!

* [
      mwaterfall
      /
      MWPhotoBrowser
](https://github.com/mwaterfall/MWPhotoBrowser):
      A simple iOS photo and video browser with grid view, captions and selections.

* [
      chenyk0317
      /
      YKLineChartView
](https://github.com/chenyk0317/YKLineChartView):
       iOS 股票的K线图 分时图 Kline

* [
      manuelescrig
      /
      MEVFloatingButton
](https://github.com/manuelescrig/MEVFloatingButton):
      An iOS drop-in UITableView, UICollectionView and UIScrollView superclass category for showing a customizable floating button on top of it.

* [
      BradLarson
      /
      GPUImage
](https://github.com/BradLarson/GPUImage):
      An open source iOS framework for GPU-based image and video processing

* [
      rs
      /
      SDWebImage
](https://github.com/rs/SDWebImage):
      Asynchronous image downloader with cache support as a UIImageView category

* [
      ChenYilong
      /
      CYLTabBarController
](https://github.com/ChenYilong/CYLTabBarController):
      最低只需传两个数组即可完成主流App框架搭建

* [
      ChenYilong
      /
      iOSInterviewQuestions
](https://github.com/ChenYilong/iOSInterviewQuestions):
      iOS面试题集锦(附答案)--学习交流群541317935

* [
      ibireme
      /
      YYKit
](https://github.com/ibireme/YYKit):
      A collection of iOS components.

* [
      ReactiveCocoa
      /
      ReactiveCocoa
](https://github.com/ReactiveCocoa/ReactiveCocoa):
      Streams of values over time

* [
      YouXianMing
      /
      YoCelsius
](https://github.com/YouXianMing/YoCelsius):
      A weather app that uses animation to give you an at-a-glance look at the weather.

* [
      ChenYilong
      /
      iOS9AdaptationTips
](https://github.com/ChenYilong/iOS9AdaptationTips):
      iOS9适配系列教程(iOS9开发学习交流群:541317935)

* [
      facebook
      /
      AsyncDisplayKit
](https://github.com/facebook/AsyncDisplayKit):
      Smooth asynchronous user interfaces for iOS apps.

* [
      waynezxcv
      /
      Gallop
](https://github.com/waynezxcv/Gallop):
      Asynchronous display and layout engine for Cocoa and Cocoa Touch.

* [
      facebook
      /
      FBRetainCycleDetector
](https://github.com/facebook/FBRetainCycleDetector):
      iOS library to help detecting retain cycles in runtime.

* [
      jessesquires
      /
      JSQMessagesViewController
](https://github.com/jessesquires/JSQMessagesViewController):
      An elegant messages UI library for iOS

* [
      gsdios
      /
      SDAutoLayout
](https://github.com/gsdios/SDAutoLayout):
      One line of code to implement automatic layout. 一行代码搞定自动布局!支持Cell和Tableview高度自适应,Label和ScrollView内容自适应,致力于做最简单易用的AutoLayout库。The most easy way for autoLayout. Based Runtime.Auto Layout .

####go
* [
      getlantern
      /
      lantern
](https://github.com/getlantern/lantern):

 Open Internet for everyone. Lantern is a free desktop application that delivers fast, reliable and secure access to the open Internet for users in censored regions. It uses a variety of techniques to stay unblocked, including P2P and domain fronting. Lantern relies on users in uncensored regions acting as access points to the open Internet.

* [
      nlf
      /
      dlite
](https://github.com/nlf/dlite):
      The simplest way to use Docker on OS X

* [
      schollz
      /
      find
](https://github.com/schollz/find):
      High-precision indoor positioning framework for most wifi-enabled devices.

* [
      docker
      /
      docker
](https://github.com/docker/docker):
      Docker - the open-source application container engine

* [
      pkg
      /
      errors
](https://github.com/pkg/errors):
      Functions for manipulating errors

* [
      zyedidia
      /
      micro
](https://github.com/zyedidia/micro):
      A modern and intuitive terminal-based text editor

* [
      golang
      /
      go
](https://github.com/golang/go):
      The Go programming language

* [
      gogits
      /
      gogs
](https://github.com/gogits/gogs):
      Gogs (Go Git Service) is a painless self-hosted Git service.

* [
      kubernetes
      /
      kubernetes
](https://github.com/kubernetes/kubernetes):
      Container Cluster Manager from Google

* [
      spf13
      /
      hugo
](https://github.com/spf13/hugo):
      A Fast and Flexible Static Site Generator built with love in GoLang

* [
      avelino
      /
      awesome-go
](https://github.com/avelino/awesome-go):
      A curated list of awesome Go frameworks, libraries and software

* [
      dinever
      /
      dingo
](https://github.com/dinever/dingo):
      Blog engine written in Go (Looking for contributors)

* [
      llgcode
      /
      draw2d
](https://github.com/llgcode/draw2d):
      draw2d

* [
      grafana
      /
      grafana
](https://github.com/grafana/grafana):
      Gorgeous metric viz, dashboards & editors for Graphite, InfluxDB & OpenTSDB

* [
      syncthing
      /
      syncthing
](https://github.com/syncthing/syncthing):
      Open Source Continuous File Synchronization

* [
      convox
      /
      rack
](https://github.com/convox/rack):
      Open-source PaaS on AWS

* [
      coreos
      /
      etcd
](https://github.com/coreos/etcd):
      Distributed reliable key-value store for the most critical data of a distributed system

* [
      hashicorp
      /
      terraform
](https://github.com/hashicorp/terraform):
      Terraform is a tool for building, changing, and combining infrastructure safely and efficiently.

* [
      qor
      /
      qor
](https://github.com/qor/qor):
      QOR is a set of libraries written in Go that abstracts common features needed for business applications, CMSs, and E-commerce systems.

* [
      elastic
      /
      beats
](https://github.com/elastic/beats):
      Beats - Lightweight shippers for Elasticsearch & Logstash

* [
      rs
      /
      rest-layer
](https://github.com/rs/rest-layer):
      REST Layer, Go (golang) REST API framework

* [
      cockroachdb
      /
      cockroach
](https://github.com/cockroachdb/cockroach):
      A Scalable, Survivable, Strongly-Consistent SQL Database

* [
      gin-gonic
      /
      gin
](https://github.com/gin-gonic/gin):
      Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.

* [
      chrislonng
      /
      starx
](https://github.com/chrislonng/starx):
      Lightweight golang game server framework, inspired by pomelo

* [
      vmware
      /
      harbor
](https://github.com/vmware/harbor):
      An enterprise-class container registry server based on Docker Distribution

####javascript
* [
      chartjs
      /
      Chart.js
](https://github.com/chartjs/Chart.js):
      Simple HTML5 Charts using the <canvas> tag

* [
      FreeCodeCamp
      /
      FreeCodeCamp
](https://github.com/FreeCodeCamp/FreeCodeCamp):
      The https://FreeCodeCamp.com open source codebase and curriculum. Learn to code and help nonprofits.

* [
      grafijs
      /
      grafi
](https://github.com/grafijs/grafi):
* [
      devbridge
      /
      Styleguide
](https://github.com/devbridge/Styleguide):
* [
      nareix
      /
      mama-hd
](https://github.com/nareix/mama-hd):
      妈妈再也不用担心我的 MacBook 发热了计划之 1080P

* [
      dleitee
      /
      strman
](https://github.com/dleitee/strman):
      A Javascript string manipulation library without npm dependences.

* [
      typicode
      /
      hotel
](https://github.com/typicode/hotel):
      Local domains for everyone and more!

* [
      Raathigesh
      /
      Dazzle
](https://github.com/Raathigesh/Dazzle):
      Dashboards made easy in React JS

* [
      usablica
      /
      intro.js
](https://github.com/usablica/intro.js):
      A better way for new feature introduction and step-by-step users guide for your website and project.

* [
      airbnb
      /
      javascript
](https://github.com/airbnb/javascript):
      JavaScript Style Guide

* [
      facebook
      /
      react
](https://github.com/facebook/react):
      A declarative, efficient, and flexible JavaScript library for building user interfaces.

* [
      vuejs
      /
      vue
](https://github.com/vuejs/vue):
      Simple yet powerful library for building modern web interfaces.

* [
      nodejs
      /
      node
](https://github.com/nodejs/node):
      Node.js JavaScript runtime

* [
      k-vyn
      /
      framer-ios-kit
](https://github.com/k-vyn/framer-ios-kit):
* [
      getify
      /
      You-Dont-Know-JS
](https://github.com/getify/You-Dont-Know-JS):
      A book series on JavaScript. @YDKJS on twitter.

* [
      maierfelix
      /
      PokeMMO
](https://github.com/maierfelix/PokeMMO):

 2d Pokémon MMO Engine with Realtime Editor

* [
      skellock
      /
      reactotron
](https://github.com/skellock/reactotron):
      Control, monitor, and instrument your React and React Native apps from the comfort of your TTY.

* [
      mbostock
      /
      d3
](https://github.com/mbostock/d3):
      A JavaScript visualization library for HTML and SVG.

* [
      angular
      /
      angular.js
](https://github.com/angular/angular.js):
      HTML enhanced for web apps

* [
      ParsePlatform
      /
      parse-server
](https://github.com/ParsePlatform/parse-server):
      Parse-compatible API server module for Node/Express

* [
      reactjs
      /
      redux
](https://github.com/reactjs/redux):
      Predictable state container for JavaScript apps

* [
      ruanyf
      /
      react-demos
](https://github.com/ruanyf/react-demos):
      a collection of simple demos of React.js

* [
      majodev
      /
      google-webfonts-helper
](https://github.com/majodev/google-webfonts-helper):
      A Hassle-Free Way to Self-Host Google Fonts. Get eot, ttf, svg, woff and woff2 files + CSS snippets

* [
      FezVrasta
      /
      popper.js
](https://github.com/FezVrasta/popper.js):
      A kickass library to manage your poppers

* [
      webpack
      /
      webpack
](https://github.com/webpack/webpack):
      A bundler for javascript and friends. Packs many modules into a few bundled assets. Code Splitting allows to load parts for the application on demand. Through "loaders" modules can be CommonJs, AMD, ES6 modules, CSS, Images, JSON, Coffeescript, LESS, ... and your custom stuff.

####ruby
* [
      Homebrew
      /
      brew
](https://github.com/Homebrew/brew):

 The missing package manager for OS X

* [
      httprb
      /
      http
](https://github.com/httprb/http):
      HTTP (The Gem! a.k.a. http.rb) - a fast Ruby HTTP client with a chainable API, streaming support, and timeouts

* [
      rails
      /
      rails
](https://github.com/rails/rails):
      Ruby on Rails

* [
      jekyll
      /
      jekyll
](https://github.com/jekyll/jekyll):

 Jekyll is a blog-aware, static site generator in Ruby

* [
      jondot
      /
      awesome-react-native
](https://github.com/jondot/awesome-react-native):
      An "awesome" type curated list of React Native components, news, tools, and learning material

* [
      fastlane
      /
      fastlane
](https://github.com/fastlane/fastlane):
      Connect all iOS and Android deployment tools into one streamlined workflow

* [
      gitlabhq
      /
      gitlabhq
](https://github.com/gitlabhq/gitlabhq):
      GitLab is version control for your server

* [
      helpyio
      /
      helpy
](https://github.com/helpyio/helpy):
      Helpy is a modern, "mobile-first" helpdesk application built in Ruby. Features include multi-lingual knowledgebase, community discussions and private tickets integrated with email.

* [
      cantino
      /
      huginn
](https://github.com/cantino/huginn):
      Build agents that monitor and act on your behalf. Your agents are standing by!

* [
      Homebrew
      /
      homebrew-core
](https://github.com/Homebrew/homebrew-core):

 Core formulae for the Homebrew package manager

* [
      discourse
      /
      discourse
](https://github.com/discourse/discourse):
      A platform for community discussion. Free, open, simple.

* [
      thredded
      /
      thredded
](https://github.com/thredded/thredded):
      The best Rails forums engine ever.

* [
      rapid7
      /
      metasploit-framework
](https://github.com/rapid7/metasploit-framework):
      Metasploit Framework

* [
      kilimchoi
      /
      engineering-blogs
](https://github.com/kilimchoi/engineering-blogs):
      A curated list of engineering blogs

* [
      Thibaut
      /
      devdocs
](https://github.com/Thibaut/devdocs):
      API Documentation Browser

* [
      mitchellh
      /
      vagrant
](https://github.com/mitchellh/vagrant):
      Vagrant is a tool for building and distributing development environments.

* [
      plataformatec
      /
      devise
](https://github.com/plataformatec/devise):
      Flexible authentication solution for Rails with Warden.

* [
      steveluscher
      /
      zero-to-graphql
](https://github.com/steveluscher/zero-to-graphql):
      Examples of GraphQL endpoints created using various languages/frameworks.

* [
      caskroom
      /
      homebrew-cask
](https://github.com/caskroom/homebrew-cask):
      A CLI workflow for the administration of Mac applications distributed as binaries

* [
      ruby
      /
      ruby
](https://github.com/ruby/ruby):
      The Ruby Programming Language

* [
      Linuxbrew
      /
      linuxbrew
](https://github.com/Linuxbrew/linuxbrew):

 The Homebrew package manager for Linux

* [
      thoughtbot
      /
      administrate
](https://github.com/thoughtbot/administrate):
      A Rails engine that helps you put together a super-flexible admin dashboard.

* [
      brigade
      /
      scss-lint
](https://github.com/brigade/scss-lint):
      Configurable tool for writing clean and consistent SCSS

* [
      sass
      /
      sass
](https://github.com/sass/sass):
      Sass makes CSS fun again.

* [
      Homebrew
      /
      legacy-homebrew
](https://github.com/Homebrew/legacy-homebrew):

 The former home of  the missing package manager for OS X


text:
import os
from multiprocessing import Queue, Event
from subprocess import PIPE
from threading import Thread
from mozprocess import ProcessHandlerMixin

from . import chrome_spki_certs
from .base import Browser, ExecutorBrowser
from .base import get_timeout_multiplier   # noqa: F401
from ..executors import executor_kwargs as base_executor_kwargs
from ..executors.executorcontentshell import (ContentShellRefTestExecutor,  # noqa: F401
                                              ContentShellCrashtestExecutor,  # noqa: F401
                                              ContentShellTestharnessExecutor)  # noqa: F401

__wptrunner__ = {"product": "content_shell",
                 "check_args": "check_args",
                 "browser": "ContentShellBrowser",
                 "executor": {"reftest": "ContentShellRefTestExecutor",
                     "crashtest": "ContentShellCrashtestExecutor",
                     "testharness": "ContentShellTestharnessExecutor"},
                 "browser_kwargs": "browser_kwargs",
                 "executor_kwargs": "executor_kwargs",
                 "env_extras": "env_extras",
                 "env_options": "env_options",
                 "update_properties": "update_properties",
                 "timeout_multiplier": "get_timeout_multiplier",}

def check_args(**kwargs):
    pass

def browser_kwargs(logger, test_type, run_info_data, config, **kwargs):
    args = kwargs["binary_args"]

    args.append("--ignore-certificate-errors-spki-list=%s" %
        ','.join(chrome_spki_certs.IGNORE_CERTIFICATE_ERRORS_SPKI_LIST))

    webtranport_h3_port = config.ports.get('webtransport-h3')
    if webtranport_h3_port is not None:
        args.append(
            f"--origin-to-force-quic-on=web-platform.test:{webtranport_h3_port[0]}")

    # These flags are specific to content_shell - they activate web test protocol mode.
    args.append("--run-web-tests")
    args.append("-")

    return {"binary": kwargs["binary"],
            "binary_args": args}

def executor_kwargs(logger, test_type, test_environment, run_info_data,
                    **kwargs):
    executor_kwargs = base_executor_kwargs(test_type, test_environment, run_info_data,
                                           **kwargs)
    return executor_kwargs

def env_extras(**kwargs):
    return []

def env_options():
    return {"server_host": "127.0.0.1",
            "testharnessreport": "testharnessreport-content-shell.js"}

def update_properties():
    return (["debug", "os", "processor"], {"os": ["version"], "processor": ["bits"]})

class ContentShellBrowser(Browser):
    """Class that represents an instance of content_shell.

    Upon startup, the stdout, stderr, and stdin pipes of the underlying content_shell
    process are connected to multiprocessing Queues so that the runner process can
    interact with content_shell through its protocol mode.
    """

    def __init__(self, logger, binary="content_shell", binary_args=[], **kwargs):
        super().__init__(logger)

        self._args = [binary] + binary_args
        self._proc = None

    def start(self, group_metadata, **kwargs):
        self.logger.debug("Starting content shell: %s..." % self._args[0])

        # Unfortunately we need to use the Process class directly because we do not
        # want mozprocess to do any output handling at all.
        self._proc = ProcessHandlerMixin.Process(self._args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
        if os.name == "posix":
            self._proc.pgid = ProcessHandlerMixin._getpgid(self._proc.pid)
            self._proc.detached_pid = None

        self._stdout_queue = Queue()
        self._stderr_queue = Queue()
        self._stdin_queue = Queue()
        self._io_stopped = Event()

        self._stdout_reader = self._create_reader_thread(self._proc.stdout, self._stdout_queue)
        self._stderr_reader = self._create_reader_thread(self._proc.stderr, self._stderr_queue)
        self._stdin_writer = self._create_writer_thread(self._proc.stdin, self._stdin_queue)

        # Content shell is likely still in the process of initializing. The actual waiting
        # for the startup to finish is done in the ContentShellProtocol.
        self.logger.debug("Content shell has been started.")

    def stop(self, force=False):
        self.logger.debug("Stopping content shell...")

        if self.is_alive():
            kill_result = self._proc.kill(timeout=5)
            # This makes sure any left-over child processes get killed.
            # See http://bugzilla.mozilla.org/show_bug.cgi?id=1760080
            if force and kill_result != 0:
                self._proc.kill(9, timeout=5)

        # We need to shut down these queues cleanly to avoid broken pipe error spam in the logs.
        self._stdout_reader.join(2)
        self._stderr_reader.join(2)

        self._stdin_queue.put(None)
        self._stdin_writer.join(2)

        for thread in [self._stdout_reader, self._stderr_reader, self._stdin_writer]:
            if thread.is_alive():
                self.logger.warning("Content shell IO threads did not shut down gracefully.")
                return False

        stopped = not self.is_alive()
        if stopped:
            self.logger.debug("Content shell has been stopped.")
        else:
            self.logger.warning("Content shell failed to stop.")

        return stopped

    def is_alive(self):
        return self._proc is not None and self._proc.poll() is None

    def pid(self):
        return self._proc.pid if self._proc else None

    def executor_browser(self):
        """This function returns the `ExecutorBrowser` object that is used by other
        processes to interact with content_shell. In our case, this consists of the three
        multiprocessing Queues as well as an `io_stopped` event to signal when the
        underlying pipes have reached EOF.
        """
        return ExecutorBrowser, {"stdout_queue": self._stdout_queue,
                                 "stderr_queue": self._stderr_queue,
                                 "stdin_queue": self._stdin_queue,
                                 "io_stopped": self._io_stopped}

    def check_crash(self, process, test):
        return not self.is_alive()

    def _create_reader_thread(self, stream, queue):
        """This creates (and starts) a background thread which reads lines from `stream` and
        puts them into `queue` until `stream` reports EOF.
        """
        def reader_thread(stream, queue, stop_event):
            while True:
                line = stream.readline()
                if not line:
                    break

                queue.put(line)

            stop_event.set()
            queue.close()
            queue.join_thread()

        result = Thread(target=reader_thread, args=(stream, queue, self._io_stopped), daemon=True)
        result.start()
        return result

    def _create_writer_thread(self, stream, queue):
        """This creates (and starts) a background thread which gets items from `queue` and
        writes them into `stream` until it encounters a None item in the queue.
        """
        def writer_thread(stream, queue):
            while True:
                line = queue.get()
                if not line:
                    break

                stream.write(line)
                stream.flush()

        result = Thread(target=writer_thread, args=(stream, queue), daemon=True)
        result.start()
        return result

redpajama_set_name: RedPajamaGithub


text:
package com.jd.mvc.core.proxy;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

class BytecodePrimitive {
	static final BytecodePrimitive BOOLEAN = new BytecodePrimitive("boolean", "Z", Boolean.class, Boolean.TYPE, "booleanValue");

	static final BytecodePrimitive CHAR = new BytecodePrimitive("char", "C", Character.class, Character.TYPE, "charValue");

	static final BytecodePrimitive BYTE = new BytecodePrimitive("byte", "B", Byte.class, Byte.TYPE, "byteValue");

	static final BytecodePrimitive SHORT = new BytecodePrimitive("short", "S", Short.class, Short.TYPE, "shortValue");

	static final BytecodePrimitive INT = new BytecodePrimitive("int", "I", Integer.class, Integer.TYPE, "intValue");

	static final BytecodePrimitive LONG = new BytecodePrimitive("long", "J", Long.class, Long.TYPE, "longValue");

	static final BytecodePrimitive FLOAT = new BytecodePrimitive("float", "F", Float.class, Float.TYPE, "floatValue");

	static final BytecodePrimitive DOUBLE = new BytecodePrimitive("double", "D", Double.class, Double.TYPE, "doubleValue");

	static final BytecodePrimitive VOID = new BytecodePrimitive("void", "V", Void.class, Void.TYPE, null);

	static final Map<String, BytecodePrimitive> primitives;
	static {
		Map<String, BytecodePrimitive> map = new HashMap<String, BytecodePrimitive>();
		map.put(BOOLEAN.getName(), BOOLEAN);
		map.put(BOOLEAN.getArrayComponentName(), BOOLEAN);
		map.put(CHAR.getName(), CHAR);
		map.put(CHAR.getArrayComponentName(), CHAR);
		map.put(BYTE.getName(), BYTE);
		map.put(BYTE.getArrayComponentName(), BYTE);
		map.put(SHORT.getName(), SHORT);
		map.put(SHORT.getArrayComponentName(), SHORT);
		map.put(INT.getName(), INT);
		map.put(INT.getArrayComponentName(), INT);
		map.put(LONG.getName(), LONG);
		map.put(LONG.getArrayComponentName(), LONG);
		map.put(FLOAT.getName(), FLOAT);
		map.put(FLOAT.getArrayComponentName(), FLOAT);
		map.put(DOUBLE.getName(), DOUBLE);
		map.put(DOUBLE.getArrayComponentName(), DOUBLE);
		map.put(VOID.getName(), VOID);
		map.put(VOID.getArrayComponentName(), VOID);
		primitives = Collections.unmodifiableMap(map);
	}

	private final String name;

	private final Class<?> wrapperClass;

	private final Class<?> primitiveClass;

	private final String arrayComponentName;

	private final String wrapperClassName;

	private final String valueMethodName;

	private BytecodePrimitive(String name, String arrayComponentName, Class<?> wrapperClass, Class<?> primitiveClass, String valueMethodName) {
		this.name = name;
		this.arrayComponentName = arrayComponentName;
		this.wrapperClass = wrapperClass;
		this.primitiveClass = primitiveClass;
		this.wrapperClassName = wrapperClass.getName();
		this.valueMethodName = valueMethodName;
	}

	static BytecodePrimitive valueOf(String name) {
		return primitives.get(name);
	}

	String getName() {
		return name;
	}

	String getArrayComponentName() {
		return arrayComponentName;
	}

	String getWrapperClassName() {
		return wrapperClassName;
	}

	String getValueMethodName() {
		return valueMethodName;
	}

	Class<?> getWrapperClass() {
		return wrapperClass;
	}

	Class<?> getPrimitiveClass() {
		return primitiveClass;
	}
}


text:
package org.apache.geronimo.connector.outbound.security;

import org.apache.geronimo.gbean.GBeanInfo;
import org.apache.geronimo.gbean.GBeanInfoBuilder;
import org.apache.geronimo.j2ee.j2eeobjectnames.NameFactory;
import org.apache.geronimo.security.jaas.LoginModuleGBean;
import org.apache.geronimo.connector.outbound.ManagedConnectionFactoryWrapper;

/**
 * @version $Rev$ $Date$
 */
public class PasswordCredentialLoginModuleWrapperGBean {

    private static final GBeanInfo GBEAN_INFO;

    static {
        GBeanInfoBuilder infoFactory = GBeanInfoBuilder.createStatic(PasswordCredentialLoginModuleWrapper.class, LoginModuleGBean.GBEAN_INFO, NameFactory.LOGIN_MODULE);

        infoFactory.addReference("ManagedConnectionFactoryWrapper", ManagedConnectionFactoryWrapper.class, NameFactory.JCA_MANAGED_CONNECTION_FACTORY);

        GBEAN_INFO = infoFactory.getBeanInfo();
    }

    public static GBeanInfo getGBeanInfo() {
        return GBEAN_INFO;
    }

}


text:
package org.kaazing.gateway.service.update.check;

import static org.junit.Assert.*;
import static org.kaazing.gateway.service.update.check.GatewayVersion.parseGatewayVersion;

import org.junit.Before;
import org.junit.Test;

public class GatewayVersionTest {

    private GatewayVersion middle;
    private GatewayVersion high1;
    private GatewayVersion high2;
    private GatewayVersion high3;
    private GatewayVersion low1;
    private GatewayVersion low2;
    private GatewayVersion low3;
    private GatewayVersion equal;
    private GatewayVersion rc1;
    private GatewayVersion rc2;
    private GatewayVersion equalrc1;

    @Before
    public void init() throws Exception {
        middle = new GatewayVersion(3, 1, 3);
        high1 = parseGatewayVersion("4.1.3");
        high2 = parseGatewayVersion("3.2.3");
        high3 = parseGatewayVersion("3.1.4");
        low1 = parseGatewayVersion("2.1.3");
        low2 = parseGatewayVersion("3.0.3");
        low3 = parseGatewayVersion("3.1.2");
        equal = parseGatewayVersion("3.1.3");
        rc1 = new GatewayVersion(3, 1, 3, "RC001");
        rc2 = parseGatewayVersion("3.1.3-RC002");
        equalrc1 = parseGatewayVersion("3.1.3-RC001");
    }

    @Test
    public void testVersioncompareTo() {
        assertTrue(middle.compareTo(high1) < 0);
        assertTrue(middle.compareTo(high2) < 0);
        assertTrue(middle.compareTo(high3) < 0);
        assertTrue(middle.compareTo(low1) > 0);
        assertTrue(middle.compareTo(low2) > 0);
        assertTrue(middle.compareTo(low3) > 0);
        assertTrue(middle.compareTo(equal) == 0);
        assertTrue(middle.compareTo(middle) == 0);
        assertTrue(rc1.compareTo(middle) < 0);
        assertTrue(rc2.compareTo(middle) < 0);
        assertTrue(rc2.compareTo(rc1) > 0);
        assertTrue(rc2.compareTo(low3) > 0);
    }

    @Test
    public void testEqual() {
        assertFalse(middle.equals(high1));
        assertFalse(middle.equals(high2));
        assertFalse(middle.equals(high3));
        assertFalse(middle.equals(low1));
        assertFalse(middle.equals(low2));
        assertFalse(middle.equals(low3));
        assertFalse(middle.equals(null));
        assertTrue(middle.equals(middle));
        assertTrue(middle.equals(equal));
        assertTrue(rc1.equals(equalrc1));
    }
}


text:
package com.forum.web.test.parse;

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

import javax.sql.DataSource;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.forum.web.dao.ChannelDao;
import com.forum.web.dao.FeedDao;
import com.forum.web.parse.Article;
import com.forum.web.parse.Stream;
import com.forum.web.parse.WebCrawler;
import com.forum.web.service.StreamService;

// All tests based on xml data found in ~/Dan/Documents/forum_test_rss
// nyt.xml is the new york times rss feed, and tr.rss is the tech republic rss feed

@ActiveProfiles("dev")
@ContextConfiguration(locations={"classpath:com/forum/web/config/dao-context.xml",
		"classpath:com/forum/web/test/config/datasource.xml",
		"classpath:com/forum/web/config/dao-context.xml",
		"classpath:com/forum/web/config/service-context.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class RssParserTest {

	private static final String NYT_LOCAL = "http://localhost:8080/nyt.xml";
	private static final String TECH_REPUB_LOCAL = "http://localhost:8080/tr.rss";
	private static final String VOX_LOCAL = "http://localhost:8080/vox.xml";

	private List<String> rssLinks;
	private List<String> atomLinks;
	private StreamService streamService;
	private WebCrawler crawler;

	@Autowired
	private ChannelDao channelDao;

	@Autowired
	private FeedDao feedDao;

	@Autowired
	private DataSource dataSource;

	private JdbcTemplate jdbc;

	@Before
	public void init() {
		jdbc = new JdbcTemplate(dataSource);
		jdbc.execute("delete from channels");
		jdbc.execute("delete from images");
		jdbc.execute("delete from items");
		jdbc.execute("delete from users");
		jdbc.execute("delete from images");
		jdbc.execute("delete from textinputs");
		jdbc.execute("delete from skipdays");

		jdbc.execute("delete from feeds");
		jdbc.execute("delete from authors");
		jdbc.execute("delete from entries");
		jdbc.execute("delete from categories");
		jdbc.execute("delete from contributors");

		rssLinks = new ArrayList<String>();
		rssLinks.add(NYT_LOCAL);
		rssLinks.add(TECH_REPUB_LOCAL);
		atomLinks = new ArrayList<String>();
		atomLinks.add(VOX_LOCAL);

		streamService = new StreamService();
		crawler = new WebCrawler(rssLinks, atomLinks);

	}

	@Test
	public void testParseLinks() {
		List<Stream> streams = crawler.parseLinks();
		for (Stream s: streams) {
			System.out.println("++++++++++++++++++++++++++++++++++++ " + s.title() + " ++++++++++++++++++++++++++++++++++++");
			List<Article> articles = s.articles();
			for (Article a: articles) {
				System.out.println(a.title());
			}
		}
		streamService.setChannelDao(channelDao);
		streamService.setFeedDao(feedDao);
		streamService.createStreams(streams);

	}

}


text:
using System.Runtime.CompilerServices;

namespace System.Html.Media.Graphics.SVG {
	[IgnoreNamespace, Imported(ObeysTypeSystem = true)]
	public partial class SVGFEGaussianBlurElement : SVGElement {
		internal SVGFEGaussianBlurElement() {
		}

		public void AddEventListener(string type, HtmlEventHandlerWithTarget<SVGFEGaussianBlurElement> listener) {
		}

		public void AddEventListener(string type, HtmlEventHandlerWithTarget<SVGFEGaussianBlurElement> listener, bool capture) {
		}

		public void AddEventListener(SVGFEGaussianBlurElementEvents type, Action listener) {
		}

		public void AddEventListener(SVGFEGaussianBlurElementEvents type, Action listener, bool capture) {
		}

		public void AddEventListener(SVGFEGaussianBlurElementEvents type, HtmlEventHandler listener) {
		}

		public void AddEventListener(SVGFEGaussianBlurElementEvents type, HtmlEventHandler listener, bool capture) {
		}

		public void AddEventListener(SVGFEGaussianBlurElementEvents type, HtmlEventHandlerWithTarget<SVGFEGaussianBlurElement> listener) {
		}

		public void AddEventListener(SVGFEGaussianBlurElementEvents type, HtmlEventHandlerWithTarget<SVGFEGaussianBlurElement> listener, bool capture) {
		}

		public void AddEventListener(SVGFEGaussianBlurElementEvents type, IEventListener listener) {
		}

		public void AddEventListener(SVGFEGaussianBlurElementEvents type, IEventListener listener, bool capture) {
		}

		[IntrinsicProperty]
		public SVGAnimatedLength Height {
			get {
				return default(SVGAnimatedLength);
			}
		}

		[IntrinsicProperty]
		public SVGAnimatedString In1 {
			get {
				return default(SVGAnimatedString);
			}
		}

		public void RemoveEventListener(string type, HtmlEventHandlerWithTarget<SVGFEGaussianBlurElement> listener) {
		}

		public void RemoveEventListener(string type, HtmlEventHandlerWithTarget<SVGFEGaussianBlurElement> listener, bool capture) {
		}

		public void RemoveEventListener(SVGFEGaussianBlurElementEvents type, Action listener) {
		}

		public void RemoveEventListener(SVGFEGaussianBlurElementEvents type, Action listener, bool capture) {
		}

		public void RemoveEventListener(SVGFEGaussianBlurElementEvents type, HtmlEventHandler listener) {
		}

		public void RemoveEventListener(SVGFEGaussianBlurElementEvents type, HtmlEventHandler listener, bool capture) {
		}

		public void RemoveEventListener(SVGFEGaussianBlurElementEvents type, HtmlEventHandlerWithTarget<SVGFEGaussianBlurElement> listener) {
		}

		public void RemoveEventListener(SVGFEGaussianBlurElementEvents type, HtmlEventHandlerWithTarget<SVGFEGaussianBlurElement> listener, bool capture) {
		}

		public void RemoveEventListener(SVGFEGaussianBlurElementEvents type, IEventListener listener) {
		}

		public void RemoveEventListener(SVGFEGaussianBlurElementEvents type, IEventListener listener, bool capture) {
		}

		[IntrinsicProperty]
		public SVGAnimatedString Result {
			get {
				return default(SVGAnimatedString);
			}
		}

		public void SetStdDeviation(double stdDeviationX, double stdDeviationY) {
		}

		[IntrinsicProperty]
		public SVGAnimatedNumber StdDeviationX {
			get {
				return default(SVGAnimatedNumber);
			}
		}

		[IntrinsicProperty]
		public SVGAnimatedNumber StdDeviationY {
			get {
				return default(SVGAnimatedNumber);
			}
		}

		[IntrinsicProperty]
		public SVGAnimatedLength Width {
			get {
				return default(SVGAnimatedLength);
			}
		}

		[IntrinsicProperty]
		public SVGAnimatedLength X {
			get {
				return default(SVGAnimatedLength);
			}
		}

		[IntrinsicProperty]
		public SVGAnimatedLength Y {
			get {
				return default(SVGAnimatedLength);
			}
		}
	}
}


text:
<html>
<body>
This intention swaps the operands of a comparison in method call expression.
</body>
</html>


text:
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure.dtd">
<Configure class="org.eclipse.jetty.webapp.WebAppContext">

  <Get name="securityHandler">
    <Set name="realmName">apiman</Set>
  </Get>

  <Set name="serverClasses">
    <Array type="java.lang.String">
      <Item>-org.eclipse.jetty.servlet.ServletContextHandler.Decorator</Item>
    </Array>
  </Set>

</Configure>


text:
import { Injectable, Output, EventEmitter, Inject } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';

import { Observable } from 'rxjs';
import { map, catchError } from 'rxjs/operators';

import { IUserLogin } from '../../shared/interfaces';

@Injectable()
export class AuthService {

    // Can use /api/auth below when running locally
    // Full domain/port is included for Docker example or if it were to run in the cloud
    port = '8080';
    baseUrl = `${this.window.location.protocol}//${this.window.location.hostname}:${this.port}`;
    authUrl = this.baseUrl + '/api/auth';
    isAuthenticated = false;
    redirectUrl: string;
    @Output() authChanged: EventEmitter<boolean> = new EventEmitter<boolean>();

    constructor(private http: HttpClient, @Inject('Window') private window: Window) { }

    private userAuthChanged(status: boolean) {
       this.authChanged.emit(status); // Raise changed event
    }

    login(userLogin: IUserLogin): Observable<boolean> {
        return this.http.post<boolean>(this.authUrl + '/login', userLogin)
            .pipe(
                map(loggedIn => {
                    this.isAuthenticated = loggedIn;
                    this.userAuthChanged(loggedIn);
                    return loggedIn;
                }),
                catchError(this.handleError)
            );
    }

    logout(): Observable<boolean> {
        return this.http.post<boolean>(this.authUrl + '/logout', null)
            .pipe(
                map(loggedOut => {
                    this.isAuthenticated = !loggedOut;
                    this.userAuthChanged(!loggedOut); // Return loggedIn status
                    return loggedOut;
                }),
                catchError(this.handleError)
            );
    }

    private handleError(error: HttpErrorResponse) {
        console.error('server error:', error);
        if (error.error instanceof Error) {
          const errMessage = error.error.message;
          return Observable.throw(errMessage);
          // Use the following instead if using lite-server
          // return Observable.throw(err.text() || 'backend server error');
        }
        return Observable.throw(error || 'Server error');
    }

}


text:
// ----------------------------------------------------------------------------------
// Microsoft Developer & Platform Evangelism
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// ----------------------------------------------------------------------------------
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
// ----------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace MyHybridSite
{

    public partial class Contact
    {
    }
}


text:
class Quest_Mages final : public Quest_Dungeon
{
public:
	enum Progress
	{
		None,
		Started,
		Finished,
		EncounteredGolem
	};

	void Start() override;
	GameDialog* GetDialog(int type2) override;
	void SetProgress(int prog2) override;
	cstring FormatString(const string& str) override;
	bool IfNeedTalk(cstring topic) const override;
	bool Special(DialogContext& ctx, cstring msg) override;
	bool SpecialIf(DialogContext& ctx, cstring msg) override;
	LoadResult Load(GameReader& f) override;
};

//-----------------------------------------------------------------------------
// After some time there are golems on road that demand gold from players.
// Talking with guard captain will lead to drunk mage.
// Visiting mage tower will reveal that he forget everything.
// Need to create alchemic potion to recover his memory.
// After that we can go to enemy mage tower and kill him.
//-----------------------------------------------------------------------------
// start_loc = location with guard captain
// mage_loc = location with drunk mage
// target_loc = drunk mage tower, evil mage tower
class Quest_Mages2 final : public Quest_Dungeon, public UnitEventHandler
{
public:
	enum Progress
	{
		None,
		Started,
		MageWantsBeer,
		MageWantsVodka,
		GivenVodka,
		GotoTower,
		MageTalkedAboutTower,
		TalkedWithCaptain,
		BoughtPotion,
		MageDrinkPotion,
		NotRecruitMage,
		RecruitMage,
		KilledBoss,
		TalkedWithMage,
		Finished
	};

	enum class State
	{
		None,
		GeneratedScholar,
		ScholarWaits,
		Counting,
		Encounter,
		EncounteredGolem,
		TalkedWithCaptain,
		GeneratedOldMage,
		OldMageJoined,
		OldMageRemembers,
		BuyPotion,
		MageCured,
		MageLeaving,
		MageLeft,
		MageGeneratedInCity,
		MageRecruited,
		Completed
	};

	enum class Talked
	{
		No,
		AboutHisTower,
		AfterEnter,
		BeforeBoss
	};

	void Init() override;
	void Start() override;
	GameDialog* GetDialog(int type2) override;
	void SetProgress(int prog2) override;
	cstring FormatString(const string& str) override;
	bool IfNeedTalk(cstring topic) const override;
	bool SpecialIf(DialogContext& ctx, cstring msg) override;
	void HandleUnitEvent(UnitEventHandler::TYPE event_type, Unit* unit) override;
	int GetUnitEventHandlerQuestId() override { return id; }
	void Save(GameWriter& f) override;
	LoadResult Load(GameReader& f) override;
	void Update(float dt);
	void OnProgress(int days);
	void OnEncounter(EncounterSpawn& spawn);

	Talked talked;
	State mages_state;
	Unit* scholar;
	string evil_mage_name, good_mage_name;
	HumanData hd_mage;
	int mage_loc, days;
	float timer;
	bool paid;
};


text:
<?php

namespace Oro\Bundle\CalendarBundle\Tests\Unit\Twig;

use Oro\Bundle\CalendarBundle\Twig\DateFormatExtension;
use Oro\Bundle\OrganizationBundle\Tests\Unit\Fixture\Entity\Organization;

class DateFormatExtensionTest extends \PHPUnit_Framework_TestCase
{
    /** @var \PHPUnit_Framework_MockObject_MockObject */
    protected $formatter;

    /** @var DateFormatExtension */
    protected $extension;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $configManager;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $localeSettings;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $translator;

    protected function setUp()
    {
        $this->markTestSkipped('CRM-5745');
        $this->configManager = $this->getMockBuilder('Oro\Bundle\ConfigBundle\Config\ConfigManager')
            ->disableOriginalConstructor()
            ->getMock();
        $this->localeSettings = $this->getMockBuilder('Oro\Bundle\LocaleBundle\Model\LocaleSettings')
            ->disableOriginalConstructor()
            ->getMock();
        $this->translator = $this->getMockBuilder('Symfony\Bundle\FrameworkBundle\Translation\Translator')
            ->disableOriginalConstructor()
            ->getMock();
        $this->formatter = $this->getMockBuilder('Oro\Bundle\LocaleBundle\Formatter\DateTimeFormatter')
            ->disableOriginalConstructor()
            ->getMock();
        $this->extension = new DateFormatExtension($this->formatter, $this->configManager);
    }

    /**
     * @param string $start
     * @param string|bool $end
     * @param string|bool $skipTime
     * @param string $expected
     *
     * @dataProvider formatCalendarDateRangeProvider
     */
    public function testFormatCalendarDateRange($start, $end, $skipTime, $expected)
    {
        $this->formatter->expects($this->any())
            ->method('format')
            ->will($this->returnValue('DateTime'));
        $this->formatter->expects($this->any())
            ->method('formatDate')
            ->will($this->returnValue('Date'));
        $this->formatter->expects($this->any())
            ->method('formatTime')
            ->will($this->returnValue('Time'));
        $startDate = new \DateTime($start);
        $endDate = $end === null ? null : new \DateTime($end);
        $result = $this->extension->formatCalendarDateRange($startDate, $endDate, $skipTime);
        $this->assertEquals($expected, $result);
    }

    public function formatCalendarDateRangeProvider()
    {
        return array(
            array('2010-05-01T10:30:15+00:00', null, false, 'DateTime'),
            array('2010-05-01T10:30:15+00:00', null, true, 'Date'),
            array('2010-05-01T10:30:15+00:00', '2010-05-01T10:30:15+00:00', false, 'DateTime'),
            array('2010-05-01T10:30:15+00:00', '2010-05-01T10:30:15+00:00', true, 'Date'),
            array('2010-05-01T10:30:15+00:00', '2010-05-01T11:30:15+00:00', false, 'Date Time - Time'),
            array('2010-05-01T10:30:15+00:00', '2010-05-01T11:30:15+00:00', true, 'Date'),
            array('2010-05-01T10:30:15+00:00', '2010-05-02T10:30:15+00:00', false, 'DateTime - DateTime'),
            array('2010-05-01T10:30:15+00:00', '2010-05-02T10:30:15+00:00', true, 'Date - Date'),
        );
    }

    /**
     * @param string $start
     * @param string $end
     * @param array $config
     * @param string|null $locale
     * @param string|null $timeZone
     * @param Organization $organization
     *
     * @dataProvider formatCalendarDateRangeOrganizationProvider
     */
    public function testFormatCalendarDateRangeOrganization(
        $start,
        $end,
        array $config,
        $locale,
        $timeZone,
        $organization
    ) {
        $startDate = new \DateTime($start);
        $endDate = $end === null ? null : new \DateTime($end);
        $this->configManager->expects($this->any())
            ->method('get')
            ->will(
                $this->returnValueMap(
                    [
                        ['oro_locale.locale', false, false, $config['locale']],
                        ['oro_locale.timezone', false, false, $config['timeZone']],
                    ]
                )
            );
        $this->extension->formatCalendarDateRangeOrganization(
            $startDate,
            $endDate,
            false,
            null,
            null,
            $locale,
            $timeZone,
            $organization
        );
        $this->configManager->expects($this->never())
            ->method('get');
        $this->extension->formatCalendarDateRangeOrganization(
            $startDate,
            $endDate,
            false,
            null,
            null,
            $locale,
            $timeZone
        );
    }

    public function formatCalendarDateRangeOrganizationProvider()
    {
        $organization = new Organization(1);
        return [
            'Localization settings from global scope' => [
                '2016-05-01T10:30:15+00:00',
                '2016-05-01T11:30:15+00:00',
                ['locale' => 'en_US', 'timeZone' => 'UTC'], // config global scope
                null,
                null,
                $organization
            ],
            'Localization settings from params values' => [
                '2016-05-01T10:30:15+00:00',
                '2016-05-01T11:30:15+00:00',
                ['locale' => 'en_US', 'timeZone' => 'UTC'], // config global scope
                'en_US',
                'Europe/Athens',
                null
            ]
        ];
    }
}


text:
package filter;

import javax.servlet.*;
import java.io.IOException;

public class EncodeFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}


text:
motion_require 'base'

module Formotion
  module RowType
    class ImageRow < Base
      TAKE = BW.localized_string("Take", nil)
      DELETE = BW.localized_string("Delete", nil)
      CHOOSE = BW.localized_string("Choose", nil)
      CANCEL = BW.localized_string("Cancel", nil)

      include BW::KVO

      IMAGE_VIEW_TAG=1100

      def build_cell(cell)
        cell.selectionStyle = self.row.selection_style || UITableViewCellSelectionStyleBlue
        # only show the "plus" when editable
        add_plus_accessory(cell) if row.editable? && (row.value == nil)

        observe(self.row, "value") do |old_value, new_value|
          if old_value and new_value
            @image_view.image = new_value
            if new_value
              self.row.row_height = 200
              cell.accessoryView = cell.editingAccessoryView = nil
            else
              self.row.row_height = 44
              # only show the "plus" when editable
              add_plus_accessory(cell) if row.editable? && (row.value == nil)
            end
            row.form.reload_data
          end
        end

        @image_view = UIImageView.alloc.init
        @image_view.image = row.value if row.value
        @image_view.tag = IMAGE_VIEW_TAG
        @image_view.contentMode = UIViewContentModeScaleAspectFit
        @image_view.backgroundColor = UIColor.clearColor
        cell.addSubview(@image_view)

        cell.swizzle(:layoutSubviews) do
          def layoutSubviews
            old_layoutSubviews

            # viewWithTag is terrible, but I think it's ok to use here...
            formotion_field = self.viewWithTag(IMAGE_VIEW_TAG)

            field_frame = formotion_field.frame
            field_frame.origin.y = 10
            field_frame.origin.x = self.textLabel.frame.origin.x + self.textLabel.frame.size.width + Formotion::RowType::Base.field_buffer
            field_frame.size.width  = self.frame.size.width - field_frame.origin.x - Formotion::RowType::Base.field_buffer
            field_frame.size.height = self.frame.size.height - Formotion::RowType::Base.field_buffer
            formotion_field.frame = field_frame
          end
        end

	nil
      end

      def on_select(tableView, tableViewDelegate)
        if !row.editable?
          return
        end
        @action_sheet = UIActionSheet.alloc.init
        @action_sheet.delegate = self

        @action_sheet.destructiveButtonIndex = (@action_sheet.addButtonWithTitle DELETE) if row.value
        @action_sheet.addButtonWithTitle TAKE if BW::Device.camera.front? or BW::Device.camera.rear?
        @action_sheet.addButtonWithTitle CHOOSE
        @action_sheet.cancelButtonIndex = (@action_sheet.addButtonWithTitle CANCEL)

        @action_sheet.showInView @image_view
      end

      def actionSheet actionSheet, didDismissWithButtonIndex: index
        source = nil

        if index == actionSheet.destructiveButtonIndex
          row.value = nil
          return
        end

        case actionSheet.buttonTitleAtIndex(index)
        when TAKE
          source = :camera
        when CHOOSE
          source = :photo_library
        when CANCEL
        else
          p "Unrecognized button title #{actionSheet.buttonTitleAtIndex(index)}"
        end

        if source
          @camera = BW::Device.camera.send((source == :camera) ? :rear : :any)
          @camera.picture(source_type: source, media_types: [:image]) do |result|
            if result[:original_image]
              #-Resize image when requested (no image upscale)
              if result[:original_image].respond_to?(:resize_image_to_size) and row.max_image_size
                result[:original_image]=result[:original_image].resize_image_to_size(row.max_image_size, false)
              end
              row.value = result[:original_image]
            end
          end
        end
      end

      def add_plus_accessory(cell)
        @add_button ||= begin
          button = UIButton.buttonWithType(UIButtonTypeContactAdd)
          button.accessibilityLabel = BW.localized_string("add image", nil)
          button.when(UIControlEventTouchUpInside) do
            self._on_select(nil, nil)
          end
          button
        end
        cell.accessoryView = cell.editingAccessoryView = @add_button
      end
    end
  end
end


text:
namespace EmployeeData
{
    using System;

    class EmployeeData
    {
        static void Main()
        {
            string firstName = "Ivan";
            string lastName = "Ivanov";
            byte age = 31;
            char gender = 'm';
            long idNum = 8306112507;
            int uniqeEmployeeNumber = 27560000;

            Console.WriteLine("First Name: {0}\nLast Name: {1}\nAge: {2}\nGender: {3}\nId Num: {4}\nEmployee Number: {5}", firstName, lastName, age, gender, idNum, uniqeEmployeeNumber);
        }
    }
}


text:
import argparse
import redislite
from redis_collections import List, Dict
from datetime import datetime

import processor

host = '192.168.10.150'
port = '8002'

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Speedtest quicktest")
    parser.add_argument('-t', '--host', help='Remote host address')
    parser.add_argument('-p', '--port', help='Remote port')

    args = parser.parse_args()

    if args.host:
        host = args.host

    if args.port:
        port = args.port

    slave = '{} {}'.format(host, port)
    print slave
    #rc = redislite.StrictRedis(serverconfig={'slaveof': slave})
    rc = redislite.StrictRedis(host = host, port = port)
    lst = List(redis=rc, key='speed')

    print "Keys in redis: ", rc.keys()
    print "No of items in redis['speed']: ", len(lst)
    print "Weekly speed\n", processor.average_speed_weekly(lst)

    settings = Dict(redis=rc, key='settings')
    if settings.get('last_test'):
        print 'Last test: ', settings['last_test']
    else:
        print 'No last run'

    settings['last_test'] = datetime.now()

    print "Last hour aggr: ", settings.get('last_hour') if settings.get('last_hour') else 'not yet'
    print "Last day aggr: ", settings.get('last_hour') if settings.get('last_day') else 'not yet'
    print lst[-2:]


text:
package frostillicus.couchbase;

import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Map;

import javax.faces.context.FacesContext;

import com.ibm.xsp.FacesExceptionEx;
import com.ibm.xsp.model.AbstractDataContainer;
import com.ibm.xsp.model.AbstractDataSource;
import com.ibm.xsp.model.DataContainer;

public class CouchbaseViewData extends AbstractDataSource {

	private String connectionName_;
	private String designDoc_;
	private String viewName_;

	public CouchbaseViewData() {

	}

	public String getConnectionName() {
		return connectionName_;
	}

	public void setConnectionName(final String connectionName) {
		this.connectionName_ = connectionName;
	}

	public String getDesignDoc() {
		return designDoc_;
	}

	public void setDesignDoc(final String designDoc) {
		this.designDoc_ = designDoc;
	}

	public String getViewName() {
		return viewName_;
	}

	public void setViewName(final String viewName) {
		this.viewName_ = viewName;
	}

	@Override
	public CouchbaseView getDataObject() {
		return ((CouchbaseViewDataContainer) getDataContainer()).getData();
	}

	@Override
	public Object saveState(final FacesContext facesContext) {
		Object[] state = new Object[4];
		state[0] = super.saveState(facesContext);
		state[1] = connectionName_;
		state[2] = designDoc_;
		state[3] = viewName_;
		return state;
	}

	@Override
	public void restoreState(final FacesContext facesContext, final Object state) {
		Object[] values = (Object[]) state;
		super.restoreState(facesContext, values[0]);
		connectionName_ = (String) values[1];
		designDoc_ = (String) values[2];
		viewName_ = (String) values[3];
	}

	@Override
	protected String composeUniqueId() {
		return getClass().getName();
	}

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

	@Override
	public DataContainer load(final FacesContext facesContext) throws IOException {
		CouchbaseView data = new CouchbaseView(connectionName_, designDoc_, viewName_);
		return new CouchbaseViewDataContainer(getBeanId(), getUniqueId(), data);
	}

	@Override
	public void readRequestParams(final FacesContext facesContext, final Map<String, Object> requestMap) {
		// Never.
	}

	@Override
	public boolean save(final FacesContext facesContext, final DataContainer container) throws FacesExceptionEx {
		// Not applicable
		return false;
	}

	protected static class CouchbaseViewDataContainer extends AbstractDataContainer {

		private transient CouchbaseView data_;

		public CouchbaseViewDataContainer() {

		}

		public CouchbaseViewDataContainer(final String beanId, final String id, final CouchbaseView data) {
			super(beanId, id);
			data_ = data;
		}

		public CouchbaseView getData() {
			return data_;
		}

		public void deserialize(final ObjectInput in) throws IOException {
			try {
				data_ = (CouchbaseView) in.readObject();
			} catch (ClassNotFoundException e) {
				throw new RuntimeException(e);
			}
		}

		public void serialize(final ObjectOutput out) throws IOException {
			out.writeObject(data_);
		}
	}
}


text:
<?php

namespace Classroom\RepositoryBundle\Tests\Build\VersionStrategy;

use Classroom\ProjectBundle\DataDir;
use Classroom\RepositoryBundle\VersionStrategy\IncrementalVersionStrategy;
use org\bovigo\vfs\vfsStream;

class IncrementalVersionStrategyTest extends \PHPUnit_Framework_TestCase
{
    public function testCreateVersionWithNonexistantVersionFile()
    {
        vfsStream::setup('root');

        $dataDir = new DataDir(vfsStream::url('root'));
        $strategy = new IncrementalVersionStrategy();
        $version = $strategy->determineVersion($dataDir);

        $this->assertEquals(1, $version);
    }

    public function testCreateVersionWithExistantVersionFile()
    {
        vfsStream::setup('root', 0777, array('version' => '5'));

        $dataDir = new DataDir(vfsStream::url('root'));
        $strategy = new IncrementalVersionStrategy();
        $version = $strategy->determineVersion($dataDir);

        $this->assertEquals(6, $version);
    }
}


text:
import scala.collection.mutable.HashMap

class IniReader(filename:String) {
	var sections = new HashMap[String, HashMap[String, String]]

	val lines = scala.io.Source.fromFile(filename).getLines
	var current = "default"

	for (line <- lines) {
		val text = line.trim
		if (text.indexOf('[') == 0 && text.indexOf(']') == text.length - 1) {
			current = text.substring(1, text.length - 1)
		}
		else if (text.indexOf('=') >= 0) {
			val pos:Int = text.indexOf('=')
			val key:String = text.substring(0, pos).trim
			val dat:String = text.substring(pos + 1).trim
			if (!sections.contains(current)) {
				sections.put(current, new HashMap[String, String])
			}
			sections(current) += key -> dat
			//println("key: " + key + " val:" + dat)
		}
	}

	def get(section:String, name:String, default:String):String = {
		if (!sections.contains(section)) {
			return default
		}
		val item = sections(section)
		if (!item.contains(name)) {
			return default
		}
		return item(name)
	}

	def display {
		sections.foreach { sect =>
			println("[" + sect._1 + "]")
			sect._2.foreach { item =>
				println("    " + item._1 + "=" + item._2)
			}
		}
	}
}

val ini = new IniReader("../data/win.ini")

println(ini.get("Mail", "MAPIXVER", ""))

println

ini.display


text:
. end_to_end.sh "It runs 'bmark' functions from the bmark/ directory"

EXPECTED_OUTPUT=results/example.runner.results

function main() {
  cd ../../
  cleanup
  run_example
  verify
}

function cleanup() {
  rm -f $EXPECTED_OUTPUT
}

function run_example() {
  mix bmark example | grep ":runner test is running" > /dev/null || fail "Did not run test"
}

function verify() {
  [ -f $EXPECTED_OUTPUT ] || fail "No results file $EXPECTED_OUTPUT"
  wc -l $EXPECTED_OUTPUT | grep "20" > /dev/null || fail "Wrong number of results"
  pass
}

main


text:
#region

using System.ComponentModel;

#endregion

namespace Rijkshuisstijl.UrlProtector.Models
{
    public enum UrlFilterReturnActionsEnum
    {
        [Description("No action")] NoAction = 0,
        [Description("Page not found")] NotFound = 1,
        [Description("Access denied")] AccessDenied = 2,
        [Description("In maintenance")] InMaintenance = 3,
        [Description("Redirect")] Redirect = 4
    }
}


text:
package com.asakusafw.compiler.flow.stage;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.asakusafw.compiler.common.Precondition;
import com.asakusafw.compiler.flow.Compilable;
import com.asakusafw.compiler.flow.FlowElementProcessor;
import com.asakusafw.compiler.flow.FlowElementProcessor.Kind;
import com.asakusafw.compiler.flow.RendezvousProcessor;
import com.asakusafw.compiler.flow.plan.FlowBlock;
import com.asakusafw.compiler.flow.plan.StageBlock;
import com.asakusafw.runtime.core.Result;
import com.asakusafw.runtime.flow.Rendezvous;
import com.asakusafw.utils.collections.Lists;
import com.asakusafw.vocabulary.flow.graph.FlowElement;
import com.asakusafw.vocabulary.flow.graph.FlowElementInput;
import com.asakusafw.vocabulary.flow.graph.FlowElementOutput;
import com.asakusafw.vocabulary.flow.graph.FlowResourceDescription;
import com.asakusafw.vocabulary.flow.graph.InputDescription;

/**
 * Represents detail of MapReduce job stages.
 * @see ShuffleModel
 */
public class StageModel {

    private final StageBlock stageBlock;

    private final List<MapUnit> mapUnits;

    private final ShuffleModel shuffleModel;

    private final List<ReduceUnit> reduceUnits;

    private final List<Sink> sinks;

    /**
     * Creates a new instance.
     * @param stageBlock the target stage block
     * @param mapUnits the map units in the target stage
     * @param shuffleModel the shuffle model of the target stage (nullable)
     * @param reduceUnits the reduce units in the target stage
     * @param sinks the outputs in the target stage
     * @throws IllegalArgumentException if some parameters are {@code null}
     */
    public StageModel(
            StageBlock stageBlock,
            List<MapUnit> mapUnits,
            ShuffleModel shuffleModel,
            List<ReduceUnit> reduceUnits,
            List<Sink> sinks) {
        Precondition.checkMustNotBeNull(stageBlock, "stageBlock"); //$NON-NLS-1$
        Precondition.checkMustNotBeNull(mapUnits, "mapUnits"); //$NON-NLS-1$
        Precondition.checkMustNotBeNull(reduceUnits, "reduceUnits"); //$NON-NLS-1$
        Precondition.checkMustNotBeNull(sinks, "sinks"); //$NON-NLS-1$
        this.stageBlock = stageBlock;
        this.shuffleModel = shuffleModel;
        int unitSerial = 1;
        for (MapUnit unit : mapUnits) {
            unit.renumberUnit(unitSerial++);
        }
        for (ReduceUnit unit : reduceUnits) {
            unit.renumberUnit(unitSerial++);
        }
        this.mapUnits = mapUnits;
        this.reduceUnits = reduceUnits;
        this.sinks = sinks;
    }

    /**
     * Returns the target stage block.
     * @return the target stage block
     */
    public StageBlock getStageBlock() {
        return stageBlock;
    }

    /**
     * Returns the map units of this stage.
     * @return the map units
     */
    public List<MapUnit> getMapUnits() {
        return mapUnits;
    }

    /**
     * Returns the shuffle model of this stage.
     * @return the shuffle model, or {@code null} if this stage does not require shuffle operations
     */
    public ShuffleModel getShuffleModel() {
        return shuffleModel;
    }

    /**
     * Returns the reduce units of this stage.
     * @return the reduce units, or an empty list if this stage does not require reduce operations
     */
    public List<ReduceUnit> getReduceUnits() {
        return reduceUnits;
    }

    /**
     * Returns input descriptions which will be used for external resources in this stage.
     * @return input description of the external resources
     */
    public Set<InputDescription> getSideDataInputs() {
        Set<ResourceFragment> resources = new HashSet<>();
        List<Unit<?>> units = new ArrayList<>();
        units.addAll(getMapUnits());
        units.addAll(getReduceUnits());
        for (Unit<?> unit : units) {
            for (Fragment fragment : unit.getFragments()) {
                resources.addAll(fragment.getResources());
            }
        }
        Set<InputDescription> results = new HashSet<>();
        for (ResourceFragment resource : resources) {
            results.addAll(resource.getDescription().getSideDataInputs());
        }
        return results;
    }

    /**
     * Returns the outputs of this stage.
     * @return the outputs
     */
    public List<Sink> getStageResults() {
        return sinks;
    }

    @Override
    public String toString() {
        return MessageFormat.format(
                "Stage(map={0}, shuffle={1}, reduce={2})", //$NON-NLS-1$
                getMapUnits(),
                getShuffleModel(),
                getReduceUnits());
    }

    /**
     * An abstract super class of map/reduce operation units.
     * @param <T> the compiled model type
     */
    public abstract static class Unit<T> extends Compilable.Trait<T> {

        private final List<FlowBlock.Input> inputs;

        private final List<Fragment> fragments;

        private int serialNumber = -1;

        /**
         * Creates a new instance.
         * @param inputs the input ports of this operation unit
         * @param fragments the operation fragments
         * @throws IllegalArgumentException if the parameters are {@code null}
         */
        public Unit(List<FlowBlock.Input> inputs, List<Fragment> fragments) {
            Precondition.checkMustNotBeNull(inputs, "inputs"); //$NON-NLS-1$
            Precondition.checkMustNotBeNull(fragments, "fragments"); //$NON-NLS-1$
            this.inputs = inputs;
            this.fragments = fragments;
        }

        /**
         * Returns the serial number of this stage.
         * @return the stage number
         * @throws IllegalStateException if the stage number has been not set
         */
        public int getSerialNumber() {
            if (serialNumber < 0) {
                throw new IllegalStateException();
            }
            return serialNumber;
        }

        /**
         * Returns the input ports of this unit.
         * @return the input ports
         */
        public List<FlowBlock.Input> getInputs() {
            return inputs;
        }

        /**
         * Returns the operation fragments.
         * @return the operation fragments
         */
        public List<Fragment> getFragments() {
            return fragments;
        }

        boolean hasSerialNumber() {
            return serialNumber >= 0;
        }

        void renumberUnit(int serial) {
            this.serialNumber = serial;
        }
    }

    /**
     * Represents a map operation unit.
     */
    public static class MapUnit extends Unit<CompiledType> {

        /**
         * Creates a new instance.
         * @param inputs the input ports of this operation unit
         * @param fragments the operation fragments
         * @throws IllegalArgumentException if the parameters are {@code null}
         */
        public MapUnit(List<FlowBlock.Input> inputs, List<Fragment> fragments) {
            super(inputs, fragments);
        }

        @Override
        public String toString() {
            return MessageFormat.format(
                    "MapUnit({2})'{'inputs={0}, fragments={1}'}'", //$NON-NLS-1$
                    getInputs(),
                    getFragments(),
                    hasSerialNumber() ? String.valueOf(getSerialNumber()) : "?"); //$NON-NLS-1$
        }
    }

    /**
     * Represents a reduce operation unit.
     */
    public static class ReduceUnit extends Unit<CompiledReduce> {

        /**
         * Creates a new instance.
         * @param inputs the input ports of this operation unit
         * @param fragments the operation fragments
         * @throws IllegalArgumentException if the parameters are {@code null}
         */
        public ReduceUnit(List<FlowBlock.Input> inputs, List<Fragment> fragments) {
            super(inputs, fragments);
        }

        /**
         * Returns whether this unit allows combine operations or not.
         * @return {@code true} if this unit allows combine operations, otherwise {@code false}
         */
        public boolean canCombine() {
            List<Fragment> fragments = getFragments();
            if (fragments.isEmpty()) {
                return false;
            }
            Fragment headFragment = fragments.get(0);
            return headFragment.canCombine();
        }

        @Override
        public String toString() {
            return MessageFormat.format(
                    "ReduceUnit({2})'{'inputs={0}, fragments={1}'}'", //$NON-NLS-1$
                    getInputs(),
                    getFragments(),
                    hasSerialNumber() ? String.valueOf(getSerialNumber()) : "?"); //$NON-NLS-1$
        }
    }

    /**
     * Represents an operation fragment.
     */
    public static class Fragment extends Compilable.Trait<CompiledType> {

        private final int serialNumber;

        private final List<Factor> factors;

        private final List<ResourceFragment> resources;

        /**
         * Creates a new instance.
         * @param serialNumber the serial number
         * @param factors operation factors in this fragment
         * @param resources external resources in this fragment
         * @throws IllegalArgumentException if the parameters are {@code null}
         */
        public Fragment(int serialNumber, List<Factor> factors, List<ResourceFragment> resources) {
            Precondition.checkMustNotBeNull(factors, "factors"); //$NON-NLS-1$
            Precondition.checkMustNotBeNull(resources, "resources"); //$NON-NLS-1$
            if (factors.isEmpty()) {
                throw new IllegalArgumentException();
            }
            Factor first = factors.get(0);
            if (first.getElement().getInputPorts().size() != 1 && first.isRendezvous() == false) {
                throw new IllegalArgumentException();
            }
            if (factors.size() >= 2 && first.isRendezvous()) {
                throw new IllegalArgumentException();
            }
            this.serialNumber = serialNumber;
            this.factors = Lists.from(factors);
            this.resources = resources;
        }

        /**
         * Returns the serial number of this fragment.
         * @return the serial number
         */
        public int getSerialNumber() {
            return serialNumber;
        }

        /**
         * Returns whether this fragment allows combine operations or not.
         * @return {@code true} if this fragment allows combine operations, otherwise {@code false}
         */
        public boolean canCombine() {
            if (isRendezvous() == false) {
                return false;
            }
            Factor first = factors.get(0);
            assert first.isRendezvous();
            RendezvousProcessor processor = (RendezvousProcessor) first.getProcessor();
            return processor.isPartial(first.getElement().getDescription());
        }

        /**
         * Returns the operation factors in this fragment.
         * @return the operation factors
         */
        public List<Factor> getFactors() {
            return factors;
        }

        /**
         * Returns the original input ports.
         * @return the original input ports
         */
        public List<FlowElementInput> getInputPorts() {
            if (factors.isEmpty()) {
                return Collections.emptyList();
            }
            Factor first = factors.get(0);
            return first.getElement().getInputPorts();
        }

        /**
         * Returns the original output ports.
         * @return the original output ports
         */
        public List<FlowElementOutput> getOutputPorts() {
            if (factors.isEmpty()) {
                return Collections.emptyList();
            }
            Factor last = factors.get(factors.size() - 1);
            return last.getElement().getOutputPorts();
        }

        /**
         * Returns the external resources used in this fragment.
         * @return the external resources
         */
        public List<ResourceFragment> getResources() {
            return resources;
        }

        /**
         * Returns whether this is a rendezvous fragment or not.
         * If so, this fragment will be compiled into {@link Rendezvous}, otherwise {@link Result}.
         * @return {@code true} if this is a rendezvous fragment, otherwise {@code false}
         */
        public boolean isRendezvous() {
            if (factors.isEmpty()) {
                return false;
            }
            Factor first = factors.get(0);
            return first.isRendezvous();
        }

        @Override
        public String toString() {
            return MessageFormat.format(
                    "Fragment{0}", //$NON-NLS-1$
                    getInputPorts());
        }
    }

    /**
     * Represents an operation factor.
     * This holds only one {@link FlowElement}.
     */
    public static class Factor {

        private final FlowElement element;

        private final FlowElementProcessor processor;

        /**
         * Creates a new instance.
         * @param element the corresponding flow element
         * @param processor the processor that can process the {@code element}
         * @throws IllegalArgumentException if the parameters are {@code null}
         */
        public Factor(FlowElement element, FlowElementProcessor processor) {
            Precondition.checkMustNotBeNull(element, "element"); //$NON-NLS-1$
            Precondition.checkMustNotBeNull(processor, "processor"); //$NON-NLS-1$
            this.element = element;
            this.processor = processor;
        }

        /**
         * Returns whether this operation is kind of rendezvous or not.
         * @return {@code true} if this operation is kind of rendezvous, otherwise {@code false}
         */
        public boolean isRendezvous() {
            return processor.getKind() == Kind.RENDEZVOUS;
        }

        /**
         * Returns whether this operation must be put on the end of {@link Fragment} or not.
         * @return {@code true} if this operation must be put on the end of {@link Fragment}, otherwise {@code false}
         */
        public boolean isLineEnd() {
            return processor.getKind() == Kind.LINE_END;
        }

        /**
         * Returns the corresponding flow element.
         * @return the corresponding flow element
         */
        public FlowElement getElement() {
            return element;
        }

        /**
         * Returns the processor which can process {@link #getElement() the holding flow element}.
         * @return the suitable flow processor
         */
        public FlowElementProcessor getProcessor() {
            return processor;
        }

        @Override
        public String toString() {
            return MessageFormat.format(
                    "Factor({0})", //$NON-NLS-1$
                    element);
        }
    }

    /**
     * Represents an external resources.
     */
    public static class ResourceFragment extends Compilable.Trait<CompiledType> {

        private final FlowResourceDescription description;

        /**
         * Creates a new instance.
         * @param description the target description
         * @throws IllegalArgumentException if the parameter is {@code null}
         */
        public ResourceFragment(FlowResourceDescription description) {
            Precondition.checkMustNotBeNull(description, "description"); //$NON-NLS-1$
            this.description = description;
        }

        /**
         * Returns the description of this external resource.
         * @return the description of this external resource
         */
        public FlowResourceDescription getDescription() {
            return description;
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + description.hashCode();
            return result;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }
            if (obj == null) {
                return false;
            }
            if (getClass() != obj.getClass()) {
                return false;
            }
            ResourceFragment other = (ResourceFragment) obj;
            if (description.equals(other.description) == false) {
                return false;
            }
            return true;
        }
    }

    /**
     * Represents an output of MapReduce stage.
     */
    public static class Sink {

        private final Set<FlowBlock.Output> outputs;

        private final String name;

        /**
         * Creates a new instance.
         * @param outputs the original output ports
         * @param name the output name
         * @throws IllegalArgumentException if the parameters are {@code null}
         */
        public Sink(Set<FlowBlock.Output> outputs, String name) {
            Precondition.checkMustNotBeNull(outputs, "outputs"); //$NON-NLS-1$
            Precondition.checkMustNotBeNull(name, "name"); //$NON-NLS-1$
            this.outputs = outputs;
            this.name = name;
        }

        /**
         * Returns the original output ports.
         * @return the original output ports
         */
        public Set<FlowBlock.Output> getOutputs() {
            return outputs;
        }

        /**
         * Returns the data model type of this output.
         * @return the data model type
         */
        public java.lang.reflect.Type getType() {
            return outputs.iterator().next().getElementPort().getDescription().getDataType();
        }

        /**
         * Returns the name of this output.
         * @return the name
         */
        public String getName() {
            return name;
        }

        @Override
        public String toString() {
            return MessageFormat.format("Sink({0})", getName()); //$NON-NLS-1$
        }
    }
}


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

#import <Foundation/Foundation.h>
#import <ViperMcFlurry.h>

@protocol TagModuleOutput;
@class TagModuleConfig;

@protocol TagModuleInput <RamblerViperModuleInput>

/**
 @author Golovko Mikhail

 Метод инициирует стартовую конфигурацию текущего модуля
 */
- (void)configureModuleWithModuleConfig:(TagModuleConfig *)moduleConfig
                           moduleOutput:(id <TagModuleOutput>)moduleOutput;
/**
 @author Konstantin Zinovyev

 Метод для получения высоты модуля тэгов

 @param moduleConfig Информация о модуле тэгов.
 @return Высота модуля тэгов
 */
- (CGFloat)obtainHeightTagModuleViewWithModuleConfig:(TagModuleConfig *)moduleConfig;

@end


text:
require "test_helper"

class AppProxyVerificationController < ActionController::Base
  self.allow_forgery_protection = true
  protect_from_forgery with: :exception

  include ShopifyApp::AppProxyVerification

  def basic
    head(:ok)
  end
end

class AppProxyVerificationTest < ActionController::TestCase
  tests AppProxyVerificationController

  setup do
    ShopifyApp.configure do |config|
      config.secret = "secret"
    end
  end

  test "no_signature" do
    assert_not query_string_valid?("shop=some-random-store.myshopify.com&"\
      "path_prefix=%2Fapps%2Fmy-app&timestamp=1466106083")
  end

  test "basic_query_string" do
    assert query_string_valid?("shop=some-random-store.myshopify.com&path_prefix=%2Fapps%2Fmy-app&timestamp="\
      "1466106083&signature=f5cd7233558b1c50102a6f33c0b63ad1e1072a2fc126cb58d4500f75223cefcd")
    assert_not query_string_valid?("shop=some-random-store.myshopify.com&path_prefix=%2Fapps%2Fmy-app&timestamp="\
      "1466106083&evil=1&signature=f5cd7233558b1c50102a6f33c0b63ad1e1072a2fc126cb58d4500f75223cefcd")
    assert_not query_string_valid?("shop=some-random-store.myshopify.com&path_prefix=%2Fapps%2Fmy-"\
      "app&timestamp=1466106083&evil=1&signature=wrongwrong8b1c50102a6f33c0b63ad1e1072a2fc126cb58d4500f75223cefcd")
  end

  test "query_string_complex_args" do
    assert query_string_valid?("shop=some-random-store.myshopify.com&path_prefix=%2Fapps%2Fmy-app&timestamp"\
      "=1466106083&signature=bbf3aa60e098f08919a2ea4c64a388414f164e6a117a63b03479ac7aa9464b4f&foo=bar&baz[1]"\
      "&baz[2]=b&baz[c[0]]=whatup&baz[c[1]]=notmuch")
    assert query_string_valid?("shop=some-random-store.myshopify.com&path_prefix=%2Fapps%2Fmy-app&"\
      "timestamp=1466106083&foo=bar&baz[1]&baz[2]=b&baz[c[0]]=whatup&baz[c[1]]=notmuch&signature"\
      "=bbf3aa60e098f08919a2ea4c64a388414f164e6a117a63b03479ac7aa9464b4f")
  end

  test "request with invalid signature should fail with 403" do
    with_test_routes do
      invalid_params = {
        shop: "some-random-store.myshopify.com",
        path_prefix: "/apps/my-app",
        timestamp: "1466106083",
        signature: "wrong233558b1c50102a6f33c0b63ad1e1072a2fc126cb58d4500f75223cefcd",
      }
      get :basic, params: invalid_params
      assert_response :forbidden
    end
  end

  test "request with a valid signature should pass" do
    with_test_routes do
      valid_params = {
        shop: "some-random-store.myshopify.com",
        path_prefix: "/apps/my-app",
        timestamp: "1466106083",
        signature: "f5cd7233558b1c50102a6f33c0b63ad1e1072a2fc126cb58d4500f75223cefcd",
      }
      get :basic, params: valid_params
      assert_response :ok
    end
  end

  private

  def query_string_valid?(query_string)
    AppProxyVerificationController.new.send(:query_string_valid?, query_string)
  end

  def with_test_routes
    with_routing do |set|
      set.draw do
        get "/app_proxy/basic" => "app_proxy_verification#basic"
      end
      yield
    end
  end
end