text:
package com.angcyo.uiview.design;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.LinearInterpolator;

import com.angcyo.library.utils.L;

public class StickBehavior<V extends View> extends CoordinatorLayout.Behavior<V> {
    View mTargetView;

    /**
     * 悬停区域的高度 px
     */
    int stickHeight = 0;

    /**
     * 为了保存已经偏移的距离
     */
    int lastTop = 0;

    public StickBehavior() {
    }

    public StickBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    /**
     * 当CoordinatorLayout在layout的时候, 会回调此方法, 告诉你,
     * 是否需要得到dependency View的位置大小改变的监听,如果你需要, 那么必须返回true
     */
    @Override
    public boolean layoutDependsOn(CoordinatorLayout parent, V child, View dependency) {
        if (mTargetView == null) {
            lastTop = 0;
        }
        if (dependency instanceof TestLayout) {
            //StickLayout只是用来判断是否是目标的标识, 没有任何不同支持,
            //你也可以通过getId判断id是否相等, 来处理
            mTargetView = dependency;
            stickHeight = (int) (40 * child.getContext().getResources().getDisplayMetrics().density);
            return true;
        }
        return super.layoutDependsOn(parent, child, dependency);
    }

    /**
     * 只有当layoutDependsOn返回true时, 才会回调.
     * 当dependency对应的View, 发生了改变, 就会回调此方法.
     * 你可以在此更新child的位置
     */
    @Override
    public boolean onDependentViewChanged(CoordinatorLayout parent, V child, View dependency) {
        lastTop = dependency.getTop();
        child.setTop(dependency.getBottom());
        return true;
    }

    /**
     * 测量child的大小, 和自定义view的套路一样
     */
    @Override
    public boolean onMeasureChild(CoordinatorLayout parent, V child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed) {
        child.measure(View.MeasureSpec.makeMeasureSpec(parent.getMeasuredWidth(), View.MeasureSpec.EXACTLY),
                View.MeasureSpec.makeMeasureSpec(parent.getMeasuredHeight() - stickHeight, View.MeasureSpec.EXACTLY));
        return true;
    }

    /**
     * 布局child的位置, 和自定义view的套路一样
     */
    @Override
    public boolean onLayoutChild(CoordinatorLayout parent, V child, int layoutDirection) {
        if (mTargetView != null) {
            ViewCompat.offsetTopAndBottom(mTargetView, lastTop);
            int top = mTargetView.getBottom();// - Math.abs(lastTop);
            child.layout(0, top, child.getMeasuredWidth(), top + child.getMeasuredHeight());
            return true;
        }
        return super.onLayoutChild(parent, child, layoutDirection);
    }

    /**
     * 必须返回true, 否则你收不到子View滚动的事件
     */
    @Override
    public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout, V child, View directTargetChild, View target, int nestedScrollAxes) {
        return true;
    }

    /**
     * 当子View开始滚动之前, 你可以通过此方法消耗掉滚动事件, 并偏移child的位置
     */
    @Override
    public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, V child, View target, int dx, int dy, int[] consumed) {
        if (dy == 0 || (dy < 0 && ViewCompat.canScrollVertically(target, -1))) {
            return;
        }

        int offsetMax = mTargetView.getMeasuredHeight() - stickHeight;

        int top = mTargetView.getTop();
        int offset = 0;
        if (dy > 0) {
            //上滑
            offset = Math.min(dy, offsetMax + top);
        } else if (dy < 0) {
            //下滑
            offset = Math.max(dy, top);
        }
        ViewCompat.offsetTopAndBottom(mTargetView, -offset);
        consumed[1] = offset;
    }

    /**
     * 用来处理快速滑动
     */
    @Override
    public boolean onNestedPreFling(CoordinatorLayout coordinatorLayout, V child, View target, float velocityX, float velocityY) {
        L.e("call: onNestedPreFling([coordinatorLayout, child, target, velocityX, velocityY])-> ");

        if (velocityY < 0 && ViewCompat.canScrollVertically(target, -1)) {
            return super.onNestedPreFling(coordinatorLayout, child, target, velocityX, velocityY);
        }

        int offsetMax = mTargetView.getMeasuredHeight() - stickHeight;

        if (velocityY > offsetMax) {
            mTargetView.setTop(-offsetMax);
            //mTargetView.setBottom(mTargetView.getMeasuredHeight() - offsetMax);
            animToBottom(mTargetView.getMeasuredHeight() - offsetMax);
        } else if (velocityY < -offsetMax) {
            mTargetView.setTop(0);
            //mTargetView.setBottom(mTargetView.getMeasuredHeight());
            animToBottom(mTargetView.getMeasuredHeight());
        }

        return super.onNestedPreFling(coordinatorLayout, child, target, velocityX, velocityY);
    }

    void animToBottom(int bottom) {
        ValueAnimator animator = ObjectAnimator.ofInt(mTargetView.getBottom(), bottom);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mTargetView.setBottom((Integer) animation.getAnimatedValue());
            }
        });
        animator.setInterpolator(new LinearInterpolator());
        animator.setDuration(100);
        animator.start();
    }
}


text:
<?php

namespace KungFu\NotificationBundle\Service;

use Doctrine\ORM\EntityManagerInterface;
use KungFu\NotificationBundle\Entity\NotificationSettingInterface;

/**
 * Class NotificationSettingFactory
 *
 * @package KungFu\NotificationBundle\Service
 * @author Chris Butcher <c.butcher@hotmail.com>
 */
class NotificationSettingFactory implements NotificationSettingFactoryInterface
{
    /**
     * @var string
     */
    protected $class;

    /**
     * @var array
     */
    protected $config;

    /**
     * @var \Doctrine\Common\Persistence\ObjectRepository
     */
    protected $repo;

    /**
     * @var EntityManagerInterface
     */
    protected $manager;

    /**
     * NotificationSettingFactory constructor.
     *
     * @param EntityManagerInterface $manager
     * @param array $config
     */
    public function __construct(EntityManagerInterface $manager, array $config)
    {
        $this->config  = $config;
        $this->class   = $config['settings']['class'];
        $this->manager = $manager;
        $this->repo    = $manager->getRepository($this->class);
    }

    /**
     * Returns all of the notification settings for a specific user.
     *
     * @param integer $userId
     *
     * @return array
     */
    public function getAllByUser($userId)
    {
        return $this->repo->findBy(array(
            'userId' => $userId
        ));
    }

    /**
     * Returns a specific notification setting for a specific user.
     *
     * @param integer $userId
     * @param string $key
     *
     * @return null|object
     */
    public function getByUserKey($userId, $key)
    {
        return $this->repo->findOneBy(array(
            'userId' => $userId,
            'key'    => $key,
        ));
    }

    /**
     * Creates a users notification setting.
     *
     * @param integer $userId
     * @param string $key
     *
     * @return null|NotificationSettingInterface
     *
     * @throws \Exception
     */
    public function create($userId, $key)
    {
        /** @var NotificationSettingInterface $setting */
        if (($setting = $this->getByUserKey($userId, $key)) !== null) {
            return $setting;
        }

        $setting = new $this->class();

        if (!($setting instanceof NotificationSettingInterface)) {
            throw new \Exception("The notification settings class must implement the NotificationSettingInterface.");
        }

        if (!isset($this->config['notifications'][$key])) {
            throw new \Exception(sprintf("The notification '%s' does not exist in the configuration file.", $key));
        }

        $setting->setUserId($userId);
        $setting->setKey($key);
        $setting->setEnabled($this->config['notifications'][$key]['enabled']);

        $this->manager->persist($setting);
        $this->manager->flush();

        return $setting;
    }

    /**
     * Updates a users notification setting.
     *
     * @param int $userId
     * @param string $key
     * @param bool $enabled
     *
     * @return NotificationSettingInterface|null|object
     */
    public function update($userId, $key, $enabled)
    {
        if (($setting = $this->getByUserKey($userId, $key)) === null) {
            $setting = $this->create($userId, $key);
        }

        $setting->setEnabled($enabled);

        $this->manager->flush();

        return $setting;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.cisco.ukidcv.spark.exceptions;

/**
 * Thrown if there are any spark report related problems.
 * <p>
 * Designed to be catchable if a spark report fails to be returned from the
 * server
 *
 * @author Matt Day
 *
 */
public class SparkReportException extends Exception {
	private static final long serialVersionUID = 1L;

	/**
	 * Throw new account exception
	 *
	 * @param args
	 */
	public SparkReportException(String args) {
		super(args);
	}
}


text:
<!doctype html>

	<title>inputImageHasAlt</title>

		<input type="image" src="../assets/finddogs.gif"
		style="display:none" />

		<form action="http://example.com/prog/text-read" method="post">

				<input type="image" name="submit"
				src="" class="quail-failed-element"/>

		</form>

		<form action="http://example.com/prog/text-read" method="post">

				<input type="image" name="submit"
				src="" alt="Find Dogs"/>

		</form>


text:
<?php

namespace Enhavo\Behat\Context;

/**
 * Defines application features from the specific context.
 */
class EmailContext extends KernelContext
{
    /**
     * @Then I will receive an email
     */
    public function iWillReceiveAnEmail()
    {

    }
}


text:
require 'jrubyfx'

class HTreeItem < Java::javafx::scene::control::TreeItem
  attr_accessor :kind, :id, :raw_item, :resources
  attr_accessor :is_leaf, :is_done

  def initialize
    @is_leaf = false
    @is_done = false
  end
end


text:
using namespace boost::intrusive;

typedef list_base_hook<link_mode<auto_unlink> > auto_unlink_hook;

class MyClass : public auto_unlink_hook
               //This hook removes the node in the destructor
{
   int int_;

   public:
   MyClass(int i = 0)   :  int_(i)  {}
   void unlink()     {  auto_unlink_hook::unlink();  }
   bool is_linked()  {  return auto_unlink_hook::is_linked();  }
};

//Define a list that will store values using the base hook
//The list can't have constant-time size!
typedef list< MyClass, constant_time_size<false> > List;

int main()
{
   //Create the list
   List l;
   {
      //Create myclass and check it's linked
      MyClass myclass;
      assert(myclass.is_linked() == false);

      //Insert the object
      l.push_back(myclass);

      //Check that we have inserted the object
      assert(l.empty() == false);
      assert(&l.front() == &myclass);
      assert(myclass.is_linked() == true);

      //Now myclass' destructor will unlink it
      //automatically
   }

   //Check auto-unlink has been executed
   assert(l.empty() == true);

   {
      //Now test the unlink() function

      //Create myclass and check it's linked
      MyClass myclass;
      assert(myclass.is_linked() == false);

      //Insert the object
      l.push_back(myclass);

      //Check that we have inserted the object
      assert(l.empty() == false);
      assert(&l.front() == &myclass);
      assert(myclass.is_linked() == true);

      //Now unlink the node
      myclass.unlink();

      //Check auto-unlink has been executed
      assert(l.empty() == true);
   }
   return 0;
}
//]


text:
#include <string>
#include <vector>
#include <map>
#include <set>
#include <utility>
using namespace std;

struct TwoKey
{
	 char * str;
	 long len;
};

struct FileNode
{
	 char * str;
	 long address;
	 FileNode * next;
};

class   Util
{
public:
	static vector<string> ReadFromFile( const char* fileDir);
    static vector<string> ReadFromFile(const char* fileDir, bool flag);
	static vector<string> StringTokenize(string line);
	static int TimeCompare(string t1, string t2);
	static vector<string> StringSplit(string line, char separator);
	static string Int2Str(int num);
	static int String2Int(string str);
	static long StringSplit(char *buffer, long  beginning, char separator);
	static void LineInsert(FileNode *head, FileNode* newNode);
	static long PosNext( char *buffer, long pos);
	static void SaveToFile(const char* fileDir, char *buffer, long len);
	static long StrToInt(const char * str, const long beg);
	static bool IfEnd(char *buffer, long pos);
    static double String2Double(string str);
};


text:
package pro.taskana.rest.security;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.jaas.AuthorityGranter;
import org.springframework.security.authentication.jaas.JaasAuthenticationCallbackHandler;
import org.springframework.security.authentication.jaas.JaasAuthenticationProvider;
import org.springframework.security.authentication.jaas.JaasNameCallbackHandler;
import org.springframework.security.authentication.jaas.JaasPasswordCallbackHandler;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.jaasapi.JaasApiIntegrationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/** Default basic configuration for taskana web example. */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

  @Value("${devMode:false}")
  private boolean devMode;

  @Bean
  public JaasAuthenticationProvider jaasAuthProvider() {
    JaasAuthenticationProvider authenticationProvider = new JaasAuthenticationProvider();
    authenticationProvider.setAuthorityGranters(new AuthorityGranter[] {new SampleRoleGranter()});
    authenticationProvider.setCallbackHandlers(
        new JaasAuthenticationCallbackHandler[] {
          new JaasNameCallbackHandler(), new JaasPasswordCallbackHandler()
        });
    authenticationProvider.setLoginContextName("taskana");
    authenticationProvider.setLoginConfig(new ClassPathResource("pss_jaas.config"));
    return authenticationProvider;
  }

  @Bean
  public WebMvcConfigurer corsConfigurer() {
    return new CorsWebMvcConfigurer();
  }

  @Bean
  public FilterRegistrationBean<CorsFilter> corsFilter() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    config.addAllowedMethod("POST");
    source.registerCorsConfiguration("/**", config);
    FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));
    bean.setOrder(0);
    return bean;
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests()
        .antMatchers("/css/**", "/img/**")
        .permitAll()
        .and()
        .csrf()
        .disable()
        .httpBasic()
        .and()
        .authenticationProvider(jaasAuthProvider())
        .authorizeRequests()
        .antMatchers(HttpMethod.GET, "/docs/**")
        .permitAll()
        .and()
        .addFilter(new JaasApiIntegrationFilter());

    if (devMode) {
      http.headers()
          .frameOptions()
          .sameOrigin()
          .and()
          .authorizeRequests()
          .antMatchers("/h2-console/**")
          .permitAll();
    } else {
      addLoginPageConfiguration(http);
    }
  }

  private void addLoginPageConfiguration(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .anyRequest()
        .fullyAuthenticated()
        .and()
        .formLogin()
        .loginPage("/login")
        .failureUrl("/login?error")
        .defaultSuccessUrl("/")
        .permitAll()
        .and()
        .logout()
        .invalidateHttpSession(true)
        .clearAuthentication(true)
        .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
        .logoutSuccessUrl("/login?logout")
        .deleteCookies("JSESSIONID")
        .permitAll();
  }

  private static class CorsWebMvcConfigurer implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
      registry.addMapping("/**").allowedOrigins("*");
    }
  }
}


text:
echo ""
echo "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX id; env; pwd"
id; env; pwd

echo ""
echo "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ls -lhrt"
ls -lhrt

echo ""
echo "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ls -lhrt *"
ls -lhrt *

echo ""
echo "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX find ./"
find ./

# Here is where our stuff happens

export      JOBID=$1
export    DATADIR=$2
export InputFiles=`head -$JOBID *.lfns_* | tail -1`

echo ""
echo "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
echo "Produce the input files: $InputFiles"
echo "  input files: $InputFiles"

echo " XXXXXXXXXXXXXXXXXXX"
cat pset.py
echo " XXXXXXXXXXXXXXXXXXX"
echo \
  python ./wCfg.py pset.py cmssw_ex.py
echo " XXXXXXXXXXXXXXXXXXX"

python ./wCfg.py pset.py cmssw_ex.py

echo ""
echo "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
echo "Python file: cmssw_ex.py"
## cat cmssw_ex.py

echo ""
echo "Start running at `date -u`"
echo ""
start_exe_time=`date +%s`
CPU_INFOS=-1

/usr/bin/time       \
  -f "%U %S %P"     \
  -o cpu_timing.txt \
  cmsRun            \
  -j ${RUNTIME_AREA}/crab_fjr_${JOBID}.xml \
  -p cmssw_ex.py

cmsrun_exit_status=$?

CPU_INFOS=`tail -n 1 cpu_timing.txt`
stop_exe_time=`date +%s`

echo "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
echo "Running ended at `date -u`"
echo "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
echo ""

echo "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
echo "Present working directory is `pwd`"
echo "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
echo ""

echo "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
echo "Directory content is `ls -l`"
echo "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
echo ""

exit 0


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title>2048 with mistake prevention</title>

	<link href="style/main.css" rel="stylesheet" type="text/css">
	<link rel="shortcut icon" href="favicon.ico">
	<link rel="apple-touch-icon" href="meta/apple-touch-icon.png">
	<meta name="apple-mobile-web-app-capable" content="yes">
	<meta name="apple-mobile-web-app-status-bar-style" content="black">

	<meta name="HandheldFriendly" content="True">
	<meta name="MobileOptimized" content="320">
	<meta name="viewport" content="width=device-width, target-densitydpi=160dpi, initial-scale=1.0, maximum-scale=1, user-scalable=no, minimal-ui">
	<meta name="format-detection" content="telephone=no" />

	<meta property="og:title" content="2048 game"/>
	<meta property="og:site_name" content="2048 game"/>
	<meta property="og:description" content="Join the numbers and get to the 2048 tile! Careful: this game is extremely addictive!"/>
	<meta property="og:image" content="http://gabrielecirulli.github.io/2048/meta/og_image.png"/>

2048mp

0

0

Join the numbers and get to the 2048 tile!

			New Game

						Keep going
					Try again

		Choose your playstyle

			How to play: Use your arrow keys to move the tiles. When two tiles with the same number touch, they merge into one!
			This version has mistake prevention mechanics which let you know if you're making a potentially dangerous move. The game assumes that the lower-right corner should have the best piece and, on the last line, the values should be decreasing right to left.
			To confirm a potentially dangerous move, hit Y. To abandon it, hit N or other directional keys.

How to select your playstyle: Click on the corner that you'd like to keep your best piece in. Click on one of the grey tiles on the edge to set the line on which the the values should be decreasing.
			If you try to set an invalid combination of line and corner (the corner doesn't belong to the line you picked), the background will turn red and you will not be able to save it.
			To save the settings, press the "Choose your playstyle button" again.

				2048 modification by TED_996. 2048 originated by Gabriele Cirulli and can be played here. Based on 1024 by Veewo Studio and conceptually similar to Threes by Asher Vollmer.


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

[System.Serializable]
public class SerializableGameState {
	public Dictionary<int, BaseState> roomStates = new Dictionary<int, BaseState> ();
	public Dictionary<int, int> scores = new Dictionary<int, int> ();

	public void print() {
		Debug.Log ("Aktuelle States");
		for (int i = 0; i < roomStates.Count; i++) {
			Debug.Log (i + " -> " + roomStates [i]);
		}
	}
}


text:
package org.ovirt.engine.core.bll;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.ovirt.engine.core.bll.context.CommandContext;
import org.ovirt.engine.core.bll.storage.disk.image.ImagesHandler;
import org.ovirt.engine.core.bll.utils.PermissionSubject;
import org.ovirt.engine.core.bll.utils.VmDeviceUtils;
import org.ovirt.engine.core.common.VdcObjectType;
import org.ovirt.engine.core.common.action.AttachDetachVmDiskParameters;
import org.ovirt.engine.core.common.action.CloneVmParameters;
import org.ovirt.engine.core.common.action.LockProperties;
import org.ovirt.engine.core.common.action.LockProperties.Scope;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.businessentities.GraphicsDevice;
import org.ovirt.engine.core.common.businessentities.GraphicsType;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VMStatus;
import org.ovirt.engine.core.common.businessentities.VmDevice;
import org.ovirt.engine.core.common.businessentities.VmDeviceGeneralType;
import org.ovirt.engine.core.common.businessentities.VmStatic;
import org.ovirt.engine.core.common.businessentities.VmWatchdog;
import org.ovirt.engine.core.common.businessentities.storage.Disk;
import org.ovirt.engine.core.common.businessentities.storage.DiskImage;
import org.ovirt.engine.core.common.businessentities.storage.DiskStorageType;
import org.ovirt.engine.core.common.errors.EngineMessage;
import org.ovirt.engine.core.common.locks.LockingGroup;
import org.ovirt.engine.core.common.queries.IdQueryParameters;
import org.ovirt.engine.core.common.queries.VdcQueryReturnValue;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.core.common.utils.Pair;
import org.ovirt.engine.core.common.utils.VmDeviceType;
import org.ovirt.engine.core.compat.Guid;

@DisableInPrepareMode
@NonTransactiveCommandAttribute(forceCompensation = true)
public class CloneVmCommand<T extends CloneVmParameters> extends AddVmAndCloneImageCommand<T> {

    private Collection<DiskImage> diskImagesFromConfiguration;

    private Guid oldVmId;

    private VM vm;

    private VM sourceVm;

    public CloneVmCommand(T parameters) {
        this(parameters, null);
    }

    protected CloneVmCommand(T params, CommandContext commandContext) {
        super(params);
    }

    @Override
    protected void init() {
        super.init();
        oldVmId = getParameters().getVmId();
        setVmName(getParameters().getNewName());

        // init the parameters only at first instantiation (not subsequent for end action)
        if (Guid.isNullOrEmpty(getParameters().getNewVmGuid())) {
            setupParameters();
        } else {
            // the VM id has to be the new VM id - same as the getVm is always the new VM
            setVmId(getParameters().getNewVmGuid());
        }
    }

    @Override
    protected LockProperties applyLockProperties(LockProperties lockProperties) {
        return lockProperties.withScope(Scope.Command);
    }

    @Override
    protected void logErrorOneOrMoreActiveDomainsAreMissing() {
        log.error("Can not found any default active domain for one of the disks of snapshot with id '{}'",
                oldVmId);
    }

    @Override
    protected Guid getStoragePoolIdFromSourceImageContainer() {
        return getVm().getStoragePoolId();
    }

    @Override
    protected Map<String, Pair<String, String>> getSharedLocks() {
        Map<String, Pair<String, String>> locks = new HashMap<>();

        for (DiskImage image: getImagesToCheckDestinationStorageDomains()) {
            locks.put(image.getId().toString(),
                    LockMessagesMatchUtil.makeLockingPair(LockingGroup.DISK, getDiskSharedLockMessage()));
        }

        locks.put(getSourceVmFromDb().getId().toString(),
                LockMessagesMatchUtil.makeLockingPair(LockingGroup.VM, EngineMessage.ACTION_TYPE_FAILED_VM_IS_BEING_CLONED));

        return locks;
    }

    @Override
    protected Collection<DiskImage> getAdjustedDiskImagesFromConfiguration() {
        VdcQueryReturnValue vdcReturnValue = runInternalQuery(
                VdcQueryType.GetAllDisksByVmId,
                new IdQueryParameters(oldVmId));

        List<Disk> loadedImages = vdcReturnValue.getReturnValue() != null ? (List<Disk>) vdcReturnValue.getReturnValue() : new ArrayList<>();

        if (diskImagesFromConfiguration == null) {
            diskImagesFromConfiguration =
                    ImagesHandler.filterImageDisks(loadedImages,
                            false,
                            true,
                            true);
            diskImagesFromConfiguration.addAll(ImagesHandler.filterDisksBasedOnCinder(loadedImages, true));
        }
        return diskImagesFromConfiguration;
    }

    @Override
    public Map<String, String> getJobMessageProperties() {
        if (jobProperties == null) {
            jobProperties = super.getJobMessageProperties();
            jobProperties.put(VdcObjectType.VM.name().toLowerCase(),
                    StringUtils.defaultString(getParameters().getNewName()));
            jobProperties.put("sourcevm",
                    StringUtils.defaultString(getSourceVmFromDb().getName()));
        }
        return jobProperties;
    }

    @Override
    protected Guid getSourceVmId() {
        return oldVmId;
    }

    @Override
    protected VM getVmFromConfiguration() {
        return getVm();
    }

    @Override
    protected VM getSourceVmFromDb() {
        if (sourceVm == null) {
            sourceVm = getVmDao().get(oldVmId);
        }

        return sourceVm;
    }

    @Override
    public VM getVm() {
        if (vm == null) {
            vm = getVmDao().get(oldVmId);
            VmDeviceUtils.setVmDevices(vm.getStaticData());
            VmHandler.updateDisksFromDb(vm);
            VmHandler.updateVmGuestAgentVersion(vm);
            VmHandler.updateNetworkInterfacesFromDb(vm);
            VmHandler.updateVmInitFromDB(vm.getStaticData(), true);

            vm.setName(getParameters().getNewName());
            vm.setId(getVmId());
        }

        return vm;
    }

    private void fillDisksToParameters() {

        for (Disk image : getAdjustedDiskImagesFromConfiguration()) {
                diskInfoDestinationMap.put(image.getId(), (DiskImage) image);
        }

        getParameters().setDiskInfoDestinationMap(diskInfoDestinationMap);
    }

    @Override
    protected void removeVmRelatedEntitiesFromDb() {
        detachDisks();
        super.removeVmRelatedEntitiesFromDb();
    }

    @Override
    protected boolean addVmImages() {
        if (super.addVmImages()) {
            attachDisks();
            return true;
        }

        return false;
    }

    private void detachDisks() {
        attachDetachDisks(VdcActionType.DetachDiskFromVm);
    }

    private void attachDisks() {
        attachDetachDisks(VdcActionType.AttachDiskToVm);
    }

    private void attachDetachDisks(VdcActionType actionType) {
        VdcQueryReturnValue vdcReturnValue = runInternalQuery(
                VdcQueryType.GetAllDisksByVmId,
                new IdQueryParameters(oldVmId));

        List<Disk> loadedImages = vdcReturnValue.getReturnValue() != null ? (List<Disk>) vdcReturnValue.getReturnValue() : new ArrayList<>();

        for (Disk disk : loadedImages) {
            if (disk.getDiskStorageType() == DiskStorageType.LUN || disk.isShareable()) {
                attachDetachDisk(disk, actionType);
            }
        }
    }

    private void attachDetachDisk(Disk disk, VdcActionType actionType) {
        runInternalAction(
                actionType,
                new AttachDetachVmDiskParameters(
                        getParameters().getNewVmGuid(),
                        disk.getId(),
                        disk.getPlugged(),
                        disk.getReadOnly()
                )
        );
    }

    private void setupParameters() {
        setVmId(Guid.newGuid());
        VM vmToClone = getVm();
        getParameters().setNewVmGuid(getVmId());
        getParameters().setVm(vmToClone);

        List<VmDevice> devices = getVmDeviceDao().getVmDeviceByVmId(oldVmId);
        getParameters().setSoundDeviceEnabled(containsDeviceWithType(devices, VmDeviceGeneralType.SOUND));
        getParameters().setConsoleEnabled(containsDeviceWithType(devices, VmDeviceGeneralType.CONSOLE));
        getParameters().setVirtioScsiEnabled(containsDeviceWithType(devices, VmDeviceGeneralType.CONTROLLER, VmDeviceType.VIRTIOSCSI));
        getParameters().setBalloonEnabled(containsDeviceWithType(devices, VmDeviceGeneralType.BALLOON));
        setGraphicsDevices(devices);

        VdcQueryReturnValue watchdogs = runInternalQuery(VdcQueryType.GetWatchdog, new IdQueryParameters(oldVmId));
        if (!((List<VmWatchdog>) watchdogs.getReturnValue()).isEmpty()) {
            VmWatchdog watchdog = ((List<VmWatchdog>) watchdogs.getReturnValue()).iterator().next();
            getParameters().setUpdateWatchdog(true);
            getParameters().setWatchdog(watchdog);
        }

        fillDisksToParameters();
    }

    private void setGraphicsDevices(List<VmDevice> devices) {
        for (GraphicsType graphicsType : GraphicsType.values()) {
            getParameters().getGraphicsDevices().put(graphicsType, null); // prevent copying from the template
        }

        for (VmDevice device : devices) {
            if (device.getType() == VmDeviceGeneralType.GRAPHICS) {
                GraphicsDevice graphicsDevice = new GraphicsDevice(device);
                getParameters().getGraphicsDevices().put(graphicsDevice.getGraphicsType(), graphicsDevice);
            }
        }
    }

    private boolean containsDeviceWithType(List<VmDevice> devices, VmDeviceGeneralType generalType, VmDeviceType deviceType) {
        for (VmDevice device : devices) {
            if (device.getType() == generalType) {
                if (deviceType == null || (deviceType.getName() != null && deviceType.getName().equals(device.getDevice()))) {
                    return true;
                }
            }
        }

        return false;
    }

    private boolean containsDeviceWithType(List<VmDevice> devices, VmDeviceGeneralType type) {
        return containsDeviceWithType(devices, type, null);
    }

    @Override
    public List<PermissionSubject> getPermissionCheckSubjects() {
        List<PermissionSubject> permissionList = new ArrayList<>();
        permissionList.add(new PermissionSubject(getParameters().getVmId(),
                VdcObjectType.VM,
                getActionType().getActionGroup()));

        return permissionList;
    }

    @Override
    protected boolean validate() {
        if (!(getSourceVmFromDb().getStatus() == VMStatus.Suspended || getSourceVmFromDb().isDown())) {
            return failValidation(EngineMessage.ACTION_TYPE_FAILED_VM_IS_NOT_DOWN);
        }

        return super.validate();
    }

    @Override
    protected void updateOriginalTemplate(VmStatic vmStatic) {
        vmStatic.setOriginalTemplateGuid(getVm().getOriginalTemplateGuid());
        vmStatic.setOriginalTemplateName(getVm().getOriginalTemplateName());
    }
}


text:
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.Network.Models
{
    public partial class AzureFirewallApplicationRule : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsDefined(Name))
            {
                writer.WritePropertyName("name");
                writer.WriteStringValue(Name);
            }
            if (Optional.IsDefined(Description))
            {
                writer.WritePropertyName("description");
                writer.WriteStringValue(Description);
            }
            if (Optional.IsCollectionDefined(SourceAddresses))
            {
                writer.WritePropertyName("sourceAddresses");
                writer.WriteStartArray();
                foreach (var item in SourceAddresses)
                {
                    writer.WriteStringValue(item);
                }
                writer.WriteEndArray();
            }
            if (Optional.IsCollectionDefined(Protocols))
            {
                writer.WritePropertyName("protocols");
                writer.WriteStartArray();
                foreach (var item in Protocols)
                {
                    writer.WriteObjectValue(item);
                }
                writer.WriteEndArray();
            }
            if (Optional.IsCollectionDefined(TargetFqdns))
            {
                writer.WritePropertyName("targetFqdns");
                writer.WriteStartArray();
                foreach (var item in TargetFqdns)
                {
                    writer.WriteStringValue(item);
                }
                writer.WriteEndArray();
            }
            if (Optional.IsCollectionDefined(FqdnTags))
            {
                writer.WritePropertyName("fqdnTags");
                writer.WriteStartArray();
                foreach (var item in FqdnTags)
                {
                    writer.WriteStringValue(item);
                }
                writer.WriteEndArray();
            }
            if (Optional.IsCollectionDefined(SourceIPGroups))
            {
                writer.WritePropertyName("sourceIpGroups");
                writer.WriteStartArray();
                foreach (var item in SourceIPGroups)
                {
                    writer.WriteStringValue(item);
                }
                writer.WriteEndArray();
            }
            writer.WriteEndObject();
        }

        internal static AzureFirewallApplicationRule DeserializeAzureFirewallApplicationRule(JsonElement element)
        {
            Optional<string> name = default;
            Optional<string> description = default;
            Optional<IList<string>> sourceAddresses = default;
            Optional<IList<AzureFirewallApplicationRuleProtocol>> protocols = default;
            Optional<IList<string>> targetFqdns = default;
            Optional<IList<string>> fqdnTags = default;
            Optional<IList<string>> sourceIPGroups = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("description"))
                {
                    description = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("sourceAddresses"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<string> array = new List<string>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(item.GetString());
                    }
                    sourceAddresses = array;
                    continue;
                }
                if (property.NameEquals("protocols"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<AzureFirewallApplicationRuleProtocol> array = new List<AzureFirewallApplicationRuleProtocol>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(AzureFirewallApplicationRuleProtocol.DeserializeAzureFirewallApplicationRuleProtocol(item));
                    }
                    protocols = array;
                    continue;
                }
                if (property.NameEquals("targetFqdns"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<string> array = new List<string>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(item.GetString());
                    }
                    targetFqdns = array;
                    continue;
                }
                if (property.NameEquals("fqdnTags"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<string> array = new List<string>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(item.GetString());
                    }
                    fqdnTags = array;
                    continue;
                }
                if (property.NameEquals("sourceIpGroups"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<string> array = new List<string>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(item.GetString());
                    }
                    sourceIPGroups = array;
                    continue;
                }
            }
            return new AzureFirewallApplicationRule(name.Value, description.Value, Optional.ToList(sourceAddresses), Optional.ToList(protocols), Optional.ToList(targetFqdns), Optional.ToList(fqdnTags), Optional.ToList(sourceIPGroups));
        }
    }
}


text:
package org.jetbrains.plugins.scala.annotator.template

import com.intellij.lang.annotation.AnnotationHolder
import org.jetbrains.plugins.scala.ScalaBundle
import org.jetbrains.plugins.scala.annotator.AnnotatorPart
import org.jetbrains.plugins.scala.extensions._
import org.jetbrains.plugins.scala.lang.psi.api.expr.ScNewTemplateDefinition
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.typedef.ScTemplateDefinition
import org.jetbrains.plugins.scala.lang.psi.types.ValueClassType

/**
 * Pavel Fatin
 */

object FinalClassInheritance extends AnnotatorPart[ScTemplateDefinition] {
  def kind: Class[ScTemplateDefinition] = classOf[ScTemplateDefinition]

  def annotate(definition: ScTemplateDefinition, holder: AnnotationHolder, typeAware: Boolean) {
    val newInstance = definition.isInstanceOf[ScNewTemplateDefinition]
    val hasBody = definition.extendsBlock.templateBody.isDefined

    if (newInstance && !hasBody) return

    AnnotatorPart.superRefs(definition).foreach {
      case (refElement, Some(psiClass)) if psiClass.hasFinalModifier =>
        holder.createErrorAnnotation(refElement,
          "Illegal inheritance from final %s %s".format(kindOf(psiClass).toLowerCase, psiClass.name))
      case (refElement, Some(cl)) if ValueClassType.extendsAnyVal(cl) =>
        holder.createErrorAnnotation(refElement, ScalaBundle.message("illegal.inheritance.from.value.class", cl.name))
      case _ =>
    }
  }
}


text:
{% load i18n apphooks_config_tags %}

            {% trans "All" %}

        {% for tag in tags %}

                    {{ tag.name }}
                    {{ tag.article_count }}

        {% endfor %}


text:
"""A web application that retrieves other websites for you.

To start serving the application on port 8088, type

  python webproxy.py

To start the server on some other interface/port, use

  python -m gevent.wsgi -p 8000 -i 0.0.0.0 webproxy.py

"""
from gevent import monkey; monkey.patch_all()
import sys
import re
import traceback
import urllib2
from urlparse import urlparse
from cgi import escape
from urllib import unquote

LISTEN = ":8088"

def application(env, start_response):
    proxy_url = 'http://%s/' % env['HTTP_HOST']
    method = env['REQUEST_METHOD']
    path = env['PATH_INFO']
    if env['QUERY_STRING']:
        path += '?' + env['QUERY_STRING']
    path = path.lstrip('/')
    if (method, path) == ('GET', ''):
        start_response('200 OK', [('Content-Type', 'text/html')])
        return [FORM]
    elif method == 'GET':
        return proxy(path, start_response, proxy_url)
    elif (method, path) == ('POST', ''):
        key, value = env['wsgi.input'].read().strip().split('=')
        assert key == 'url', repr(key)
        start_response('302 Found', [('Location', join(proxy_url, unquote(value)))])
    elif method == 'POST':
        start_response('404 Not Found', [])
    else:
        start_response('501 Not Implemented', [])
    return []

def proxy(path, start_response, proxy_url):
    if '://' not in path:
        path = 'http://' + path
    try:
        try:
            response = urllib2.urlopen(path)
        except urllib2.HTTPError:
            response = sys.exc_info()[1]
        print ('%s: %s %s' % (path, response.code, response.msg))
        headers = [(k, v) for (k, v) in response.headers.items() if k not in drop_headers]
        scheme, netloc, path, params, query, fragment = urlparse(path)
        host = (scheme or 'http') + '://' + netloc
    except Exception:
        ex = sys.exc_info()[1]
        sys.stderr.write('error while reading %s:\n' % path)
        traceback.print_exc()
        tb = traceback.format_exc()
        start_response('502 Bad Gateway', [('Content-Type', 'text/html')])
        error_str = escape(str(ex) or ex.__class__.__name__ or 'Error')
        return ['
%s

%s

%s
' % (error_str, escape(path), escape(tb))]
    else:
        start_response('%s %s' % (response.code, response.msg), headers)
        data = response.read()
        data = fix_links(data, proxy_url, host)
        return [data]

def join(url1, *rest):
    if not rest:
        return url1
    url2, rest = rest[0], rest[1:]
    if url1.endswith('/'):
        if url2.startswith('/'):
            return join(url1 + url2[1:], *rest)
        else:
            return join(url1 + url2, *rest)
    elif url2.startswith('/'):
        return join(url1 + url2, *rest)
    else:
        return join(url1 + '/' + url2, *rest)

def fix_links(data, proxy_url, host_url):
    """
    >>> fix_links("> %r' % (m.group(0), result)
        return result
    data = _link_re_1.sub(fix_link_cb, data)
    data = _link_re_2.sub(fix_link_cb, data)
    return data

_link_re_1 = re.compile('''(?P<before>(href|src|action)\s*=\s*)(?P<quote>['"])(?P<url>[^#].*?)(?P=quote)''')
_link_re_2 = re.compile('''(?P<before>(href|src|action)\s*=\s*)(?P<url>[^'"#>][^ >]*)''')

drop_headers = ['transfer-encoding', 'set-cookie']

FORM = """
<title>Web Proxy - gevent example</title>

Type in URL you want to visit and press Enter

<form action=/ method=post>
<input size=80 name=url value="http://www.gevent.org"/>
</form>

"""

if __name__ == '__main__':
    from gevent.pywsgi import WSGIServer
    print 'Serving on %s...' % LISTEN
    WSGIServer(LISTEN, application).serve_forever()


text:
<?php

namespace FoF\Split\Api\Commands;

use Flarum\User\User;

class SplitDiscussion
{
    /**
     * The post to start splitting from.
     *
     * @var int
     */
    public $start_post_id;

    /**
     * The post to end splitting on.
     *
     * @var int
     */
    public $end_post_number;

    /**
     * The title of the new discussion.
     *
     * @var string
     */
    public $title;

    /**
     * The user performing the action.
     *
     * @var User
     */
    public $actor;

    /**
     * SplitDiscussion constructor.
     *
     * @param string $title
     * @param int    $start_post_id
     * @param int    $end_post_number
     * @param User   $actor
     */
    public function __construct($title, $start_post_id, $end_post_number, User $actor)
    {
        $this->title = $title;
        $this->start_post_id = $start_post_id;
        $this->end_post_number = $end_post_number;
        $this->actor = $actor;
    }
}


text:
import unittest
import utils
from testbin import TestBin

class TestBinCobroker(TestBin, unittest.TestCase):

    def setUp(self):
        self.bin = 'co-broker'

    def tearDown(self):
        pass


text:
namespace pb {

	System::System(float const t0, float const dt)
		: t(t0), delta_t(dt) {}

	void System::addBody(BodyParticlesDiscretisation * const body) {
		bodies.push_back(body);
	}

	void System::computeForceAndTorque(float const time) const {
		// Compute forces between bodies using particles approximation
		for (auto body_1 = bodies.begin(); body_1 != bodies.end() - 1; body_1++) {
			for (auto body_2 = body_1 + 1; body_2 != bodies.end(); body_2++) {
				(*body_1)->colliding(*(*body_2));
			}
		}

		// Add gravity to all bodies and transfer partcile forces to them
		for (auto body = bodies.begin(); body != bodies.end(); body++) {
			(*body)->getBody()->resetForce();
			(*body)->getBody()->resetTorque();

			// Add gravity
			(*body)->getBody()->addForce(math::vec3f({0.f, -0.1f, 0.f}));

			// Transfer particle forces to body
			(*body)->transferForcesParticlesBody();
		}
	}

	void System::computeStep() {
		// Allocate space
		float * y0 = new float[PhysicalProperties::STATE_SIZE * bodies.size()];
		float * y_end = new float[PhysicalProperties::STATE_SIZE * bodies.size()];
		float * y_dot = new float[PhysicalProperties::STATE_SIZE * bodies.size()];

		computeForceAndTorque(t);

		// Insert body state to array
		for (size_t i = 0; i < bodies.size(); i++) {
			bodies[i]->getBody()->bodyStateToArray(&y0[i * PhysicalProperties::STATE_SIZE]);
			bodies[i]->getBody()->ddtBodyStateToArray(&y_dot[i * PhysicalProperties::STATE_SIZE]);
		}

		// Compute step
		EulerSolver::odeStep(y0, y_dot, y_end, PhysicalProperties::STATE_SIZE * bodies.size(), t, t + delta_t);

		// Update body state
		for (size_t i = 0; i < bodies.size(); i++) {
			bodies[i]->getBody()->arrayToBodyState(&y_end[i * PhysicalProperties::STATE_SIZE]);
		}

		// Update time
		t += delta_t;
	}

	void System::draw(GLuint const v_p, GLuint const i_p, GLuint const n_p,
					  GLuint const v_s, GLuint const i_s, GLuint const n_s) const {
		for (auto it = bodies.begin(); it != bodies.end(); it++) {
			// DEBUG draw particles
			//(*it)->drawParticles(v_p, i_p, n_p);
			// Draw body
			(*it)->getBody()->drawBody(v_s, i_s, n_s);
		}

		// Draw coordinate system
		glColor3f(0.f, 0.f, 0.f);
		glLineWidth(2.f);
		glBegin(GL_LINES);
		// X axis
		glVertex3f(0.f, 0.f, 0.f);
		glVertex3f(5.f, 0.f, 0.f);
		// Y axis
		glVertex3f(0.f, 0.f, 0.f);
		glVertex3f(0.f, 5.f, 0.f);
		// Z axis
		glVertex3f(0.f, 0.f, 0.f);
		glVertex3f(0.f, 0.f, 5.f);
		glEnd();
	}

} // pb namespace


text:
class CreateSupportTicketxIssues < ActiveRecord::Migration
  def change
    create_table :support_ticketx_issues do |t|
      t.string :subject
      t.text :description

      t.timestamps
    end
  end
end


text:
local utils = require 'utils'
local split = utils.split_string
local persistTable = require 'persist-table'

validArgs = validArgs or utils.invert({
 'help',
 'source',
 'target',
 'spell',
})
local args = utils.processArgs({...}, validArgs)

if args.help then -- Help declaration
 print([[spells/trigger
  arguments:
   -help
     print this help message
   -source id
   -target id
   -spell TOKEN
   -value
   -experience
   -cast_count
   -description
 ]])
 return
end

spell = persistTable.GlobalTable.roses.SpellTable[args.spell]
if not spell then
 print('No spell found in database')
 return
end
if args.source and tonumber(args.source) then
 source = args.source
 source_name = dfhack.unit.getVisibleName(df.unit.find(tonumber(source)))
end
if args.target and tonumber(args.target) then
 target = args.target
 target_name = dfhack.unit.getVisibleName(df.unit.find(tonumber(target)))
end

description = spell.description or ''
description:gsub('TARGET',target_name)
description:gsub('SOURCE',source_name)

script = spell.script or ''
script:gsub('SOURCE',source)
script:gsub('TARGET',target)
script:gsub('DESCRIPTION',description)


text:
project "zlib"
   targetname "zlib"
   language "C++"
   kind "StaticLib"
   targetdir (BUILD_LOCATION .. "/bin")

   includedirs {
      "../../engine/lib/zlib",
   }

   files {
      "../../engine/lib/zlib/**"
   }

   configuration "vs*"
      defines { "_CRT_SECURE_NO_WARNINGS" }
      flags   { "NoNativeWChar", "StaticRuntime" }

   configuration "Debug"
      flags   { "Symbols" }

   configuration "windows"
      links { "ole32" }

   configuration "linux"
      links { "dl" }

   configuration { "macosx", "gmake" }
      buildoptions {"-mmacosx-version-min=10.4" }
      linkoptions  {"-mmacosx-version-min=10.4" }


text:
package com.thoughtworks.workshop.book;

import android.os.Parcel;
import android.os.Parcelable;

import static android.text.TextUtils.join;

/**
 * Created by wxie on 9/18/14.
 */
public class Book implements Parcelable {

    private String title;
    private String image;
    private String author;
    private String publisher;
    private String publishDate;
    private String summary;
    private double rating;

    public Book() {
    }

    public Book(String title, String image, String author, String publisher, String publishDate, String summary, double rating) {
        this.title = title;
        this.image = image;
        this.author = author;
        this.publisher = publisher;
        this.publishDate = publishDate;
        this.summary = summary;
        this.rating = rating;
    }

    public String getTitle() {
        return title;
    }

    public String getImage() {
        return image;
    }

    public String getSummary() {
        return summary;
    }

    public String getInformation() {
        return join(" / ", new String[]{getAuthor(), getPublisher(), getPublishDate()});
    }

    public String getAuthor() {
        return author;
    }

    public String getPublisher() {
        return publisher;
    }

    public String getPublishDate() {
        return publishDate;
    }

    public double getRating() {
        return rating;
    }

    public static final Creator CREATOR = new Creator() {
        @Override
        public Book createFromParcel(Parcel source) {
            Book book = new Book();
            book.title = source.readString();
            book.image = source.readString();
            book.author = source.readString();
            book.publisher = source.readString();
            book.publishDate = source.readString();
            book.summary = source.readString();
            book.rating = source.readDouble();
            return book;
        }

        @Override
        public Book[] newArray(int size) {
            return new Book[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(title);
        dest.writeString(image);
        dest.writeString(author);
        dest.writeString(publisher);
        dest.writeString(publishDate);
        dest.writeString(summary);
        dest.writeDouble(rating);
    }
}


text:
package org.apache.accumulo.test.functional;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;

import org.apache.accumulo.core.Constants;
import org.apache.accumulo.core.client.BatchWriter;
import org.apache.accumulo.core.client.BatchWriterConfig;
import org.apache.accumulo.core.client.Connector;
import org.apache.accumulo.core.client.Scanner;
import org.apache.accumulo.core.client.admin.TimeType;
import org.apache.accumulo.core.data.Mutation;
import org.apache.accumulo.core.data.Range;
import org.apache.hadoop.io.Text;

public class LogicalTimeTest extends FunctionalTest {

  @Override
  public Map<String,String> getInitialConfig() {
    return Collections.emptyMap();
  }

  @Override
  public List<TableSetup> getTablesToCreate() {
    return Collections.emptyList();
  }

  @Override
  public void run() throws Exception {
    int tc = 0;

    runMergeTest("foo" + tc++, new String[] {"m"}, new String[] {"a"}, null, null, "b", 2l);
    runMergeTest("foo" + tc++, new String[] {"m"}, new String[] {"z"}, null, null, "b", 2l);
    runMergeTest("foo" + tc++, new String[] {"m"}, new String[] {"a", "z"}, null, null, "b", 2l);
    runMergeTest("foo" + tc++, new String[] {"m"}, new String[] {"a", "c", "z"}, null, null, "b", 3l);
    runMergeTest("foo" + tc++, new String[] {"m"}, new String[] {"a", "y", "z"}, null, null, "b", 3l);

    runMergeTest("foo" + tc++, new String[] {"g", "r"}, new String[] {"a"}, null, null, "b", 2l);
    runMergeTest("foo" + tc++, new String[] {"g", "r"}, new String[] {"h"}, null, null, "b", 2l);
    runMergeTest("foo" + tc++, new String[] {"g", "r"}, new String[] {"s"}, null, null, "b", 2l);
    runMergeTest("foo" + tc++, new String[] {"g", "r"}, new String[] {"a", "h", "s"}, null, null, "b", 2l);
    runMergeTest("foo" + tc++, new String[] {"g", "r"}, new String[] {"a", "c", "h", "s"}, null, null, "b", 3l);
    runMergeTest("foo" + tc++, new String[] {"g", "r"}, new String[] {"a", "h", "s", "i"}, null, null, "b", 3l);
    runMergeTest("foo" + tc++, new String[] {"g", "r"}, new String[] {"t", "a", "h", "s"}, null, null, "b", 3l);

    runMergeTest("foo" + tc++, new String[] {"g", "r"}, new String[] {"a"}, null, "h", "b", 2l);
    runMergeTest("foo" + tc++, new String[] {"g", "r"}, new String[] {"h"}, null, "h", "b", 2l);
    runMergeTest("foo" + tc++, new String[] {"g", "r"}, new String[] {"s"}, null, "h", "b", 1l);
    runMergeTest("foo" + tc++, new String[] {"g", "r"}, new String[] {"a", "h", "s"}, null, "h", "b", 2l);
    runMergeTest("foo" + tc++, new String[] {"g", "r"}, new String[] {"a", "c", "h", "s"}, null, "h", "b", 3l);
    runMergeTest("foo" + tc++, new String[] {"g", "r"}, new String[] {"a", "h", "s", "i"}, null, "h", "b", 3l);
    runMergeTest("foo" + tc++, new String[] {"g", "r"}, new String[] {"t", "a", "h", "s"}, null, "h", "b", 2l);

  }

  private void runMergeTest(String table, String[] splits, String[] inserts, String start, String end, String last, long expected) throws Exception {
    Connector conn = super.getConnector();
    conn.tableOperations().create(table, true, TimeType.LOGICAL);
    TreeSet<Text> splitSet = new TreeSet<Text>();
    for (String split : splits) {
      splitSet.add(new Text(split));
    }
    conn.tableOperations().addSplits(table, splitSet);

    BatchWriter bw = conn.createBatchWriter(table, new BatchWriterConfig());
    for (String row : inserts) {
      Mutation m = new Mutation(row);
      m.put("cf", "cq", "v");
      bw.addMutation(m);
    }

    bw.flush();

    conn.tableOperations().merge(table, start == null ? null : new Text(start), end == null ? null : new Text(end));

    Mutation m = new Mutation(last);
    m.put("cf", "cq", "v");
    bw.addMutation(m);
    bw.flush();

    Scanner scanner = conn.createScanner(table, Constants.NO_AUTHS);
    scanner.setRange(new Range(last));

    bw.close();

    long time = scanner.iterator().next().getKey().getTimestamp();
    if (time != expected)
      throw new RuntimeException("unexpected time " + time + " " + expected);
  }

  @Override
  public void cleanup() throws Exception {}

}


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--
Stackdriver appender logback configuration provided for import.
-->

<included>
  <property name="STACKDRIVER_LOG_NAME" value="${STACKDRIVER_LOG_NAME:-spring.log}"/>
  <property name="STACKDRIVER_LOG_FLUSH_LEVEL" value="${STACKDRIVER_LOG_FLUSH_LEVEL:-WARN}"/>

  <appender name="STACKDRIVER" class="org.springframework.cloud.gcp.logging.LoggingAppender">
    <log>${STACKDRIVER_LOG_NAME}</log> <!-- Optional : default java.log -->
    <enhancer>org.springframework.cloud.gcp.logging.TraceIdLoggingEnhancer</enhancer>
    <flushLevel>${STACKDRIVER_LOG_FLUSH_LEVEL}</flushLevel> <!-- Optional : default ERROR -->
  </appender>
</included>


text:
namespace starboard {
namespace android {
namespace shared {

const char* g_app_assets_dir = "/cobalt/assets";
const char* g_app_files_dir = NULL;
const char* g_app_cache_dir = NULL;
const char* g_app_lib_dir = NULL;

namespace {
jobject g_java_asset_manager;
AAssetManager* g_asset_manager;

// Copies the characters from a jstring and returns a newly allocated buffer
// with the result.
const char* DuplicateJavaString(JniEnvExt* env, jstring j_string) {
  SB_DCHECK(j_string);
  std::string utf_str = env->GetStringStandardUTFOrAbort(j_string);
  const char* result = SbStringDuplicate(utf_str.c_str());
  return result;
}

}  // namespace

void SbFileAndroidInitialize() {
  JniEnvExt* env = JniEnvExt::Get();

  SB_DCHECK(g_java_asset_manager == NULL);
  SB_DCHECK(g_asset_manager == NULL);
  ScopedLocalJavaRef<jstring> j_app(
      env->CallStarboardObjectMethodOrAbort(
          "getApplicationContext", "()Landroid/content/Context;"));
  g_java_asset_manager = env->ConvertLocalRefToGlobalRef(
      env->CallObjectMethodOrAbort(j_app.Get(),
          "getAssets", "()Landroid/content/res/AssetManager;"));
  g_asset_manager = AAssetManager_fromJava(env, g_java_asset_manager);

  SB_DCHECK(g_app_files_dir == NULL);
  ScopedLocalJavaRef<jstring> j_string(
      env->CallStarboardObjectMethodOrAbort("getFilesAbsolutePath",
                                           "()Ljava/lang/String;"));
  g_app_files_dir = DuplicateJavaString(env, j_string.Get());
  SB_DLOG(INFO) << "Files dir: " << g_app_files_dir;

  SB_DCHECK(g_app_cache_dir == NULL);
  j_string.Reset(
      env->CallStarboardObjectMethodOrAbort("getCacheAbsolutePath",
                                           "()Ljava/lang/String;"));
  g_app_cache_dir = DuplicateJavaString(env, j_string.Get());
  SB_DLOG(INFO) << "Cache dir: " << g_app_cache_dir;

  SB_DCHECK(g_app_lib_dir == NULL);
  ScopedLocalJavaRef<jobject> j_app_info(
      env->CallObjectMethodOrAbort(j_app.Get(), "getApplicationInfo",
                                   "()Landroid/content/pm/ApplicationInfo;"));
  j_string.Reset(env->GetStringFieldOrAbort(j_app_info.Get(),
                                            "nativeLibraryDir"));
  g_app_lib_dir = DuplicateJavaString(env, j_string.Get());
  SB_DLOG(INFO) << "Lib dir: " << g_app_lib_dir;
}

void SbFileAndroidTeardown() {
  JniEnvExt* env = JniEnvExt::Get();

  if (g_java_asset_manager) {
    env->DeleteGlobalRef(g_java_asset_manager);
    g_java_asset_manager = NULL;
    g_asset_manager = NULL;
  }

  if (g_app_files_dir) {
    SbMemoryDeallocate(const_cast<char*>(g_app_files_dir));
    g_app_files_dir = NULL;
  }

  if (g_app_cache_dir) {
    SbMemoryDeallocate(const_cast<char*>(g_app_cache_dir));
    g_app_cache_dir = NULL;
  }
}

bool IsAndroidAssetPath(const char* path) {
  size_t prefix_len = strlen(g_app_assets_dir);
  return path != NULL
      && strncmp(g_app_assets_dir, path, prefix_len) == 0
      && (path[prefix_len] == '/' || path[prefix_len] == '\0');
}

AAsset* OpenAndroidAsset(const char* path) {
  if (!IsAndroidAssetPath(path) || g_asset_manager == NULL) {
    return NULL;
  }
  const char* asset_path = path + strlen(g_app_assets_dir) + 1;
  return AAssetManager_open(g_asset_manager, asset_path, AASSET_MODE_RANDOM);
}

AAssetDir* OpenAndroidAssetDir(const char* path) {
  // Note that the asset directory will not be found if |path| points to a
  // specific file instead of a directory. |path| should also not end with '/'.
  if (!IsAndroidAssetPath(path) || g_asset_manager == NULL) {
    return NULL;
  }
  const char* asset_path = path + strlen(g_app_assets_dir);
  if (*asset_path == '/') {
    asset_path++;
  }
  AAssetDir* asset_directory =
      AAssetManager_openDir(g_asset_manager, asset_path);

  // AAssetManager_openDir() always returns a pointer to an initialized object,
  // even if the given directory does not exist. To determine if the directory
  // actually exists, AAssetDir_getNextFileName() is called to check for any
  // files in the given directory. However, when iterating the contents of a
  // directory, the NDK Asset Manager does not allow subdirectories to be seen.
  // So this is not a 100% accurate way to determine if a directory actually
  // exists and false negatives will be given for directories that contain
  // subdirectories but no files in their immediate directory.
  const char* file = AAssetDir_getNextFileName(asset_directory);
  if (file == NULL) {
    AAssetDir_close(asset_directory);
    return NULL;
  } else {
    AAssetDir_rewind(asset_directory);
    return asset_directory;
  }
}

}  // namespace shared
}  // namespace android
}  // namespace starboard


text:
name: Rule change request
about: Request a change to an existing rule

---

<!--
    ESLint adheres to the [JS Foundation Code of Conduct](https://js.foundation/community/code-of-conduct).

    This template is for requesting a rule change. If you are here for another reason, please see below:

    1. To report a bug: https://eslint.org/docs/developer-guide/contributing/reporting-bugs
    2. To propose a new rule: https://eslint.org/docs/developer-guide/contributing/new-rules
    3. To request a change that is not a bug fix, rule change, or new rule: https://eslint.org/docs/developer-guide/contributing/changes
    4. If you have any questions, please stop by our chatroom: https://gitter.im/eslint/eslint

    Note that leaving sections blank will make it difficult for us to troubleshoot and we may have to close the issue.
-->

**What rule do you want to change?**

**Does this change cause the rule to produce more or fewer warnings?**

**How will the change be implemented? (New option, new default behavior, etc.)?**

**Please provide some example code that this change will affect:**

<!-- Put your code examples here -->
```js

```

**What does the rule currently do for this code?**

**What will the rule do after it's changed?**


text:
<!--
Description: feed info type='text/plain'
Expect:      not bozo and feed['info_detail']['type'] == u'text/plain'
-->
<feed version="0.3" xmlns="http://purl.org/atom/ns#">
  <info type="text/plain">Example Atom</info>
</feed>


text:
from horizon import test

class PuppiesTests(test.TestCase):
    # Unit tests for puppies.
    def test_me(self):
        self.assertTrue(1 + 1 == 2)


text:
require_relative '../remi_spec'

describe Extractor::DataFrame do
  let(:extractor) { Extractor::DataFrame.new(data: data) }
  let(:data) { 'some_data' }

  context '#data' do
    it 'returns the raw data' do
      expect(extractor.extract.data).to eq data
    end
  end
end

describe Parser::DataFrame do
  let(:fields) do
    {
      brewer: { type: 'text' },
      style: { type: 'text' }
    }
  end
  let(:parser) { Parser::DataFrame.new(fields: fields) }
  let(:df_extract) { double('df_extract') }
  let(:data) {
    [
      [ 'Baerlic', 'IPA' ],
      [ 'Ex Novo', 'Red' ]
    ]
  }

  before do
    allow(df_extract).to receive(:data) { data }
  end

  it 'converts the data array into a dataframe' do
    expect(parser.parse df_extract).to be_a Remi::DataFrame::Daru
  end

  it 'converts the data array into the dataframe' do
    expected_df = Daru::DataFrame.new(
      :brewer => ['Baerlic', 'Ex Novo'],
      :style  => ['IPA', 'Red']
    )
    expect(parser.parse(df_extract).to_a).to eq expected_df.to_a
  end

end

describe Encoder::DataFrame, skip: 'todo' do
end

describe Loader::DataFrame, skip: 'todo' do
end


text:
/*	$NetBSD: client.c,v 1.4 2006/09/29 20:06:11 plunky Exp $	*/

/*-
 * Copyright (c) 2006 Itronix Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of Itronix Inc. may not be used to endorse
 *    or promote products derived from this software without specific
 *    prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY ITRONIX INC. ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL ITRONIX INC. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/cdefs.h>
__RCSID("$NetBSD: client.c,v 1.4 2006/09/29 20:06:11 plunky Exp $");

#include <sys/ioctl.h>
#include <sys/queue.h>
#include <sys/time.h>
#include <sys/un.h>
#include <bluetooth.h>
#include <errno.h>
#include <event.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <unistd.h>

#include "bthcid.h"

/*
 * A client is anybody who connects to our control socket to
 * receive PIN requests.
 */
struct client {
	struct event		ev;
	int			fd;		/* client descriptor */
	LIST_ENTRY(client)	next;
};

/*
 * PIN cache items are made when we have sent a client pin
 * request. The event is used to expire the item.
 */
struct item {
	struct event	 ev;
	bdaddr_t	 laddr;			/* local device BDADDR */
	bdaddr_t	 raddr;			/* remote device BDADDR */
	uint8_t		 pin[HCI_PIN_SIZE];	/* PIN */
	int		 hci;			/* HCI socket */
	LIST_ENTRY(item) next;
};

static struct event		control_ev;

static LIST_HEAD(,client)	client_list;
static LIST_HEAD(,item)		item_list;

static void process_control	(int, short, void *);
static void process_client	(int, short, void *);
static void process_item	(int, short, void *);

#define PIN_REQUEST_TIMEOUT	30	/* Request is valid */
#define PIN_TIMEOUT		300	/* PIN is valid */

int
init_control(const char *name, mode_t mode)
{
	struct sockaddr_un	un;
	int			ctl;

	LIST_INIT(&client_list);
	LIST_INIT(&item_list);

	if (name == NULL)
		return 0;

	if (unlink(name) < 0 && errno != ENOENT)
		return -1;

	ctl = socket(PF_LOCAL, SOCK_STREAM, 0);
	if (ctl < 0)
		return -1;

	memset(&un, 0, sizeof(un));
	un.sun_len = sizeof(un);
	un.sun_family = AF_LOCAL;
	strlcpy(un.sun_path, name, sizeof(un.sun_path));
	if (bind(ctl, (struct sockaddr *)&un, sizeof(un)) < 0) {
		close(ctl);
		return -1;
	}

	if (chmod(name, mode) < 0) {
		close(ctl);
		unlink(name);
		return -1;
	}

	if (listen(ctl, 10) < 0) {
		close(ctl);
		unlink(name);
		return -1;
	}

	event_set(&control_ev, ctl, EV_READ | EV_PERSIST, process_control, NULL);
	if (event_add(&control_ev, NULL) < 0) {
		close(ctl);
		unlink(name);
		return -1;
	}

	return 0;
}

/* Process control socket event */
static void
process_control(int sock, short ev, void *arg)
{
	struct sockaddr_un	un;
	socklen_t		n;
	int			fd;
	struct client		*cl;

	n = sizeof(un);
	fd = accept(sock, (struct sockaddr *)&un, &n);
	if (fd < 0) {
		syslog(LOG_ERR, "Could not accept PIN client connection");
		return;
	}

	n = 1;
	if (ioctl(fd, FIONBIO, &n) < 0) {
		syslog(LOG_ERR, "Could not set non blocking IO for client");
		close(fd);
		return;
	}

	cl = malloc(sizeof(struct client));
	if (cl == NULL) {
		syslog(LOG_ERR, "Could not malloc client");
		close(fd);
		return;
	}

	memset(cl, 0, sizeof(struct client));
	cl->fd = fd;

	event_set(&cl->ev, fd, EV_READ | EV_PERSIST, process_client, cl);
	if (event_add(&cl->ev, NULL) < 0) {
		syslog(LOG_ERR, "Could not add client event");
		free(cl);
		close(fd);
		return;
	}

	syslog(LOG_DEBUG, "New Client");
	LIST_INSERT_HEAD(&client_list, cl, next);
}

/* Process client response packet */
static void
process_client(int sock, short ev, void *arg)
{
	bthcid_pin_response_t	 rp;
	struct timeval		 tv;
	struct sockaddr_bt	 sa;
	struct client		*cl = arg;
	struct item		*item;
	int			 n;

	n = recv(sock, &rp, sizeof(rp), 0);
	if (n != sizeof(rp)) {
		if (n != 0)
			syslog(LOG_ERR, "Bad Client");

		close(sock);
		LIST_REMOVE(cl, next);
		free(cl);

		syslog(LOG_DEBUG, "Client Closed");
		return;
	}

	syslog(LOG_DEBUG, "Received PIN for %s", bt_ntoa(&rp.raddr, NULL));

	LIST_FOREACH(item, &item_list, next) {
		if (bdaddr_same(&rp.laddr, &item->laddr) == 0
		    || bdaddr_same(&rp.raddr, &item->raddr) == 0)
			continue;

		evtimer_del(&item->ev);
		if (item->hci != -1) {
			memset(&sa, 0, sizeof(sa));
			sa.bt_len = sizeof(sa);
			sa.bt_family = AF_BLUETOOTH;
			bdaddr_copy(&sa.bt_bdaddr, &item->laddr);

			send_pin_code_reply(item->hci, &sa, &item->raddr, rp.pin);
			LIST_REMOVE(item, next);
			free(item);
			return;
		}
		goto newpin;
	}

	item = malloc(sizeof(struct item));
	if (item == NULL) {
		syslog(LOG_ERR, "Item allocation failed");
		return;
	}

	memset(item, 0, sizeof(struct item));
	bdaddr_copy(&item->laddr, &rp.laddr);
	bdaddr_copy(&item->raddr, &rp.raddr);
	evtimer_set(&item->ev, process_item, item);
	LIST_INSERT_HEAD(&item_list, item, next);

newpin:
	syslog(LOG_DEBUG, "Caching PIN for %s", bt_ntoa(&rp.raddr, NULL));

	memcpy(item->pin, rp.pin, HCI_PIN_SIZE);
	item->hci = -1;

	tv.tv_sec = PIN_TIMEOUT;
	tv.tv_usec = 0;

	if (evtimer_add(&item->ev, &tv) < 0) {
		syslog(LOG_ERR, "Cannot add event timer for item");
		LIST_REMOVE(item, next);
		free(item);
	}
}

/* Send PIN request to client */
int
send_client_request(bdaddr_t *laddr, bdaddr_t *raddr, int hci)
{
	bthcid_pin_request_t	 cp;
	struct client		*cl;
	struct item		*item;
	int			 n = 0;
	struct timeval		 tv;

	memset(&cp, 0, sizeof(cp));
	bdaddr_copy(&cp.laddr, laddr);
	bdaddr_copy(&cp.raddr, raddr);
	cp.time = PIN_REQUEST_TIMEOUT;

	LIST_FOREACH(cl, &client_list, next) {
		if (send(cl->fd, &cp, sizeof(cp), 0) != sizeof(cp))
			syslog(LOG_ERR, "send PIN request failed");
		else
			n++;
	}

	if (n == 0)
		return 0;

	syslog(LOG_DEBUG, "Sent PIN requests to %d client%s.",
				n, (n == 1 ? "" : "s"));

	item = malloc(sizeof(struct item));
	if (item == NULL) {
		syslog(LOG_ERR, "Cannot allocate PIN request item");
		return 0;
	}

	memset(item, 0, sizeof(struct item));
	bdaddr_copy(&item->laddr, laddr);
	bdaddr_copy(&item->raddr, raddr);
	item->hci = hci;
	evtimer_set(&item->ev, process_item, item);

	tv.tv_sec = cp.time;
	tv.tv_usec = 0;

	if (evtimer_add(&item->ev, &tv) < 0) {
		syslog(LOG_ERR, "Cannot add request timer");
		free(item);
		return 0;
	}

	LIST_INSERT_HEAD(&item_list, item, next);
	return 1;
}

/* Process item event (by expiring it) */
static void
process_item(int fd, short ev, void *arg)
{
	struct item *item = arg;

	syslog(LOG_DEBUG, "PIN for %s expired", bt_ntoa(&item->raddr, NULL));
	LIST_REMOVE(item, next);
	evtimer_del(&item->ev);
	free(item);
}

/* lookup PIN in item cache */
uint8_t *
lookup_pin(bdaddr_t *laddr, bdaddr_t *raddr)
{
	static uint8_t pin[HCI_PIN_SIZE];
	struct item *item;

	LIST_FOREACH(item, &item_list, next) {
		if (bdaddr_same(raddr, &item->raddr) == 0)
			continue;

		if (bdaddr_same(laddr, &item->laddr) == 0
		    && bdaddr_any(&item->laddr) == 0)
			continue;

		if (item->hci >= 0)
			break;

		syslog(LOG_DEBUG, "Matched PIN from cache");
		memcpy(pin, item->pin, sizeof(pin));

		LIST_REMOVE(item, next);
		evtimer_del(&item->ev);
		free(item);

		return pin;
	}

	return NULL;
}


text:
import logging
import re
import uuid
from enum import Enum

from pyjob.cexec import cexec
from pyjob.exception import PyJobError, PyJobExecutableNotFoundError
from pyjob.script import Script
from pyjob.task import ClusterTask

logger = logging.getLogger(__name__)

RE_LINE_SPLIT = re.compile(r":\s+")
RE_PID_MATCH = re.compile(r"Your job.*has been submitted")

class SGEConfigParameter(Enum):
    ENVIRONMENT = 1
    QUEUE = 2

class SunGridEngineTask(ClusterTask):
    """SunGridEngine executable :obj:`~pyjob.task.Task`"""

    JOB_ARRAY_INDEX = "$SGE_TASK_ID"
    SCRIPT_DIRECTIVE = "#$"
    _sge_avail_configs_by_env = {}

    @property
    def info(self):
        """:obj:`~pyjob.sge.SunGridEngineTask` information"""
        if self.pid is None:
            return {}
        try:
            stdout = cexec(["qstat", "-j", str(self.pid)], permit_nonzero=True)
        except PyJobExecutableNotFoundError:
            return {}
        data = {}
        for line in stdout.splitlines():
            line = line.strip()
            if "jobs do not exist" in line:
                return data
            if not line or "=" * 30 in line:
                continue
            else:
                kv = RE_LINE_SPLIT.split(line, 1)
                if len(kv) == 2:
                    data[kv[0]] = kv[1]
        return data

    @classmethod
    def get_sge_avail_configs(cls, param):
        """Get the set of available configurations for a given SGE parameter

        Parameters
        ----------
        param : :obj:~SGEConfigParameter
            The parameter to be tested

        Returns
        -------
        set
            A set with the available configurations for the parameter of interest

        Raises
        ------
        :exc:`ValueError`
           Parameter is not found in :obj:~SGEConfigParameter

        """

        if param in cls._sge_avail_configs_by_env:
            return cls._sge_avail_configs_by_env[param]

        if SGEConfigParameter(param) == SGEConfigParameter.ENVIRONMENT:
            cmd = ["qconf", "-spl"]
        elif SGEConfigParameter(param) == SGEConfigParameter.QUEUE:
            cmd = ["qconf", "-sql"]
        else:
            raise ValueError("Requested SGE parameter is not supported!")

        stdout = cexec(cmd, permit_nonzero=True)
        config = []
        for line in stdout.splitlines():
            line = line.split()
            if len(line) > 1:
                break
            else:
                config.append(line[0].encode("utf-8"))

        cls._sge_avail_configs_by_env[param] = set(config)
        return cls._sge_avail_configs_by_env[param]

    def _check_requirements(self):
        """Check if the requirements for task execution are met"""

        self._ensure_exec_available("qstat")

        sge_config_by_env = self.get_sge_avail_configs(SGEConfigParameter.ENVIRONMENT)
        if self.environment and self.environment not in sge_config_by_env:
            raise PyJobError(
                f"Requested environment {self.environment} cannot be found. "
                f"List of available environments: {sge_config_by_env}"
            )

        sge_config_by_queue = self.get_sge_avail_configs(SGEConfigParameter.QUEUE)
        if self.queue and self.queue not in sge_config_by_queue:
            raise PyJobError(
                f"Requested queue {self.environment} cannot be found. "
                f"List of available queues: {sge_config_by_queue}"
            )

    def kill(self):
        """Immediately terminate the :obj:`~pyjob.sge.SunGridEngineTask`"""
        if self.pid is None:
            return
        cexec(["qdel", str(self.pid)])
        logger.debug("Terminated task: %d", self.pid)

    def _run(self):
        """Method to initialise :obj:`~pyjob.sge.SunGridEngineTask` execution"""
        self.runscript = self._create_runscript()
        self.runscript.write()
        stdout = cexec(["qsub", self.runscript.path], cwd=self.directory)
        for line in stdout.split("\n"):
            line = line.strip()
            if re.match(RE_PID_MATCH, line):
                if len(self.script) > 1:
                    self.pid = int(line.split()[2].split(".")[0])
                else:
                    self.pid = int(line.split()[2])
        logger.debug(
            "%s [%d] submission script is %s",
            self.__class__.__qualname__,
            self.pid,
            self.runscript.path,
        )

    def _create_runscript(self):
        """Utility method to create runscript"""
        runscript = Script(
            directory=self.directory,
            prefix="sge_",
            suffix=".script",
            stem=str(uuid.uuid1().int),
        )
        runscript.append(self.__class__.SCRIPT_DIRECTIVE + " -V")
        runscript.append(self.__class__.SCRIPT_DIRECTIVE + " -w e")
        runscript.append(self.__class__.SCRIPT_DIRECTIVE + " -j yes")
        runscript.append(self.__class__.SCRIPT_DIRECTIVE + f" -N {self.name}")
        if self.dependency:
            cmd = f'-hold_jid {",".join(map(str, self.dependency))}'
            runscript.append(self.__class__.SCRIPT_DIRECTIVE + " " + cmd)
        if self.priority:
            cmd = f"-p {self.priority}"
            runscript.append(self.__class__.SCRIPT_DIRECTIVE + " " + cmd)
        if self.queue:
            cmd = f"-q {self.queue}"
            runscript.append(self.__class__.SCRIPT_DIRECTIVE + " " + cmd)
        if self.runtime:
            cmd = f"-l h_rt={self.get_time(self.runtime)}"
            runscript.append(self.__class__.SCRIPT_DIRECTIVE + " " + cmd)
        if self.shell:
            cmd = f"-S {self.shell}"
            runscript.append(self.__class__.SCRIPT_DIRECTIVE + " " + cmd)
        if self.nprocesses and self.environment:
            cmd = f"-pe {self.environment} {self.nprocesses}"
            runscript.append(self.__class__.SCRIPT_DIRECTIVE + " " + cmd)
        if self.directory:
            cmd = f"-wd {self.directory}"
            runscript.append(self.__class__.SCRIPT_DIRECTIVE + " " + cmd)
        if self.extra:
            cmd = " ".join(map(str, self.extra))
            runscript.append(self.__class__.SCRIPT_DIRECTIVE + " " + cmd)
        if len(self.script) > 1:
            logf = runscript.path.replace(".script", ".log")
            jobsf = runscript.path.replace(".script", ".jobs")
            with open(jobsf, "w") as f_out:
                f_out.write("\n".join(self.script))
            cmd = f"-t 1-{len(self.script)} -tc {self.max_array_size}"
            runscript.append(self.__class__.SCRIPT_DIRECTIVE + " " + cmd)
            runscript.append(self.__class__.SCRIPT_DIRECTIVE + f" -o {logf}")
            runscript.extend(self.get_array_bash_extension(jobsf, 0))
        else:
            runscript.append(self.__class__.SCRIPT_DIRECTIVE + f" -o {self.log[0]}")
            runscript.append(self.script[0])
        return runscript


text:
class CreateLightSources < ActiveRecord::Migration
  def change
    create_table :light_sources do |t|
      t.string :name
    end
  end
end


text:
package org.jbpm.services.task.commands;

import org.kie.api.runtime.Context;
import org.kie.api.runtime.EnvironmentName;
import org.kie.internal.task.api.UserInfo;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="get-user-info-command")
@XmlAccessorType(XmlAccessType.NONE)
public class GetUserInfoCommand extends TaskCommand<UserInfo> {

	private static final long serialVersionUID = -5174631969130504959L;

	public GetUserInfoCommand() {
	}

	public UserInfo execute(Context cntxt) {
        TaskContext context = (TaskContext) cntxt;

    	return (UserInfo) context.get(EnvironmentName.TASK_USER_INFO);

    }
}


text:
import pykka
import serial
import logging
import pygame
import os
from time import sleep
from mopidy import core

logger = logging.getLogger(__name__)

class SerialPortFrontend(pykka.ThreadingActor, core.CoreListener):

    def __init__(self, config, core):
        super(SerialPortFrontend, self).__init__()
        self.config = config['serialport']
        self.core = core
        self.make_noise = self.config['enable_noise']
        pygame.mixer.init(frequency=22050, size=8)
        self.noise = pygame.mixer.Sound(os.path.join(os.path.dirname(__file__), 'noise2.wav'))
        self.running = False
        self.channels = self.config['channels']

    def on_start(self):
        self.connect()
        self.set_channel(0)
        self.loop()

    def on_stop(self):
        self.disconnect()

    def connect(self):
        try:
            self.arduino = serial.Serial(
                port=self.config['port'],
                baudrate=self.config['baud']
            )
            # signal we're ready
            sleep(3)
            self.arduino.write('OK\n\r')
            self.running = True
        except:
            logger.error('[serialport] Could not connect to serial port ' + self.config['port'])

    def disconnect(self):
        self.arduino.close()
        self.running = False

    def set_pause(self, on):
        if on:
            self.core.playback.pause()
        else:
            self.core.playback.resume()

    def set_volume(self, step):
        # normalize
        volume = self.core.mixer.get_volume().get() + step
        if step > 0:
            volume = min(volume, self.config['max_volume'])
        if step < 0:
            volume = max(volume, self.config['min_volume'])
        try:
            logger.info('[serialport] Setting volume to ' + str(volume))
            self.core.mixer.set_volume(volume)
        except:
            logger.error('[serialport] Failed to set volume to ' + str(volume))
            pass

    def set_channel(self, channel):
        try:
            # get channel uri from config
            channel_uri = self.channels[channel]
            logger.info('[serialport] Switching to channel: ' + channel_uri)

            self.core.playback.stop()
            if self.make_noise:
                self.noise.play(loops=-1, fade_ms=2000)

            refs = self.core.library.browse(channel_uri).get()
            tl_tracks = self.core.tracklist.add(at_position=0, uris=[ref.uri for ref in refs]).get()
            self.core.playback.play(tl_track=tl_tracks[0]).get()
            if self.make_noise:
                sleep(4)
                self.noise.fadeout(2000)

        except Exception as e:
            logger.error('Failed to set channel to %s: %s', channel, e)
            pass

    def handle_message(self, message):
        logger.debug('[serialport] incoming message "' + message + '"')
        volume_step = self.config['volume_step']
        try:
            if message == 'V+':
                self.set_volume(volume_step)
            if message == 'V-':
                self.set_volume(volume_step * -1)
            if message[0] == 'C':
                self.set_channel(int(message[1:]))
            if message[0] == 'P':
                self.set_pause(message[1] == '1')
        except BaseException as e:
            logger.error('[serialport] Could not handle serial message "%s": %s', message, e)
            pass

    def loop(self):
        message = 'noop';
        while self.running:
            message = self.arduino.readline()
            if len(message) > 0:
                # strip newline
                self.handle_message(message.rstrip())


text:
package io.github.opencubicchunks.cubicchunks.api.worldgen.structure.feature;

import io.github.opencubicchunks.cubicchunks.api.util.CubePos;
import io.github.opencubicchunks.cubicchunks.api.util.XYZAddressable;
import net.minecraft.world.World;

/**
 * Interface implemented by
 * {@link net.minecraft.world.gen.structure.StructureStart} class when cubic chunks is installed.
 * Allows to access CubicChunks-specific behavior of StructureStart
 */
public interface ICubicFeatureStart extends XYZAddressable {
    int getChunkPosY();

    /**
     * Called to mark this StructureStart as a part of cubic chunks structure,
     * and provide necessary cubic chunks specific data.
     * Must be called immediately after constructing the StructureStart.
     *
     * @param world world instance for initialization
     * @param cubeY cube Y coordinate of this structure start
     */
    void initCubic(World world, int cubeY);

    CubePos getCubePos();

    /**
     * @return {@code true} when instance has been initialized by initCubic(..) method called
     *         by one of cubic chunks structure generators.
     */
    boolean isCubic();
}


text:
<?php
/**
 * Template Name: Portfolio Two col
 *
 * This template is a full-width version of the page.php template file. It removes the sidebar area.
 *
 * @package WooFramework
 * @subpackage Template
 */
    get_header();
    global $woo_options;
?>

        <?php if ( have_posts() ) : $count = 0; ?>
            <article <?php post_class(); ?>>

               <?php $image_size = 454; $port_image_height = 269; $port_type = "one-two";// set thumb dimensions for 2 column portfolio ?>
                <?php get_template_part( 'loop', 'portfolio' ); ?>

                <?php edit_post_link( __( '{ Edit }', 'woothemes' ), '', '' ); ?>

        <?php else : ?>
            <article <?php post_class(); ?>>

<?php _e( 'Sorry, no posts matched your criteria.', 'woothemes' ); ?>

        <?php endif; ?>

        <?php woo_main_after(); ?>

<?php get_footer(); ?>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SushiProject.Model;
using System.IO;
using System.Collections.ObjectModel;

namespace SushiProject.Utilities
{
    class ProjectAS3Writer
    {
        public string path = "C:/sushigame/";

        public ProjectAS3Writer() { }

        public void WriteASFiles(GameProject project) {

            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            if (!Directory.Exists(path + "assets"))
            {
                Directory.CreateDirectory(path + "assets");
            }
            // move all images into here
            ProjectDirectoryManager.Instance.CopyAllImagesToFolder(path + "assets");

            WriteMain(project.Settings);
            WriteGameObjects(project.Objects);
            WriteLevels(project.Levels);
            WriteAssets(project);
            WriteHelperClasses(project);
        }

        private void WriteMain(GameSettings settings) {
            string mainText = System.IO.File.ReadAllText("../../Templates/MainTemplate");

            string bgcolorstring = settings.BackgroundColor.R.ToString("X") + settings.BackgroundColor.G.ToString("X") + settings.BackgroundColor.B.ToString("X");
            mainText = mainText.Replace("!BGCOLOR!", bgcolorstring);
            mainText = mainText.Replace("!WIDTH!", settings.ScreenWidth.ToString());
            mainText = mainText.Replace("!HEIGHT!", settings.ScreenHeight.ToString());
            mainText = mainText.Replace("!FRAMERATE!", settings.FrameRate.ToString());

            // WriteAllText creates a file, writes the specified string to the file,
            // and then closes the file.
            System.IO.File.WriteAllText(path + "Main.as", mainText);
        }
        private string ImageResourceName(string name)
        {
            string str = name.Replace(" ", "_");
            int extStart = str.IndexOf(".");
            if (extStart > 0) {
                str = str.Substring(0,extStart);
            }
            return String.Format("IMG_{0}", str);
        }

        private void WriteGameObjects(Collection<GameObject> gameObjects)
        {
            string templateText = System.IO.File.ReadAllText("../../Templates/GameObjectTemplate");

            foreach (GameObject go in gameObjects)
            {
                string gameObjectText = templateText.Replace("!NAME!", go.Name.Replace(" ", "_"));
                if (go.Sprite != null)
                {
                    gameObjectText = gameObjectText.Replace("!SPRITEFIELDS!", "public var img:Bitmap;");
                    gameObjectText = gameObjectText.Replace("!INITSPRITE!", String.Format("img = new Assets.{0}();", ImageResourceName(go.Sprite.FirstImage.Name)));
                    gameObjectText = gameObjectText.Replace("!ADDSPRITE!", "addChild(img);");
                }
                else
                {
                    gameObjectText = gameObjectText.Replace("!SPRITEFIELDS!", "");
                    gameObjectText = gameObjectText.Replace("!INITSPRITE!", "");
                    gameObjectText = gameObjectText.Replace("!ADDSPRITE!", "");
                }

                System.IO.File.WriteAllText(path + go.Name.Replace(" ", "_") + ".as", gameObjectText);
            }
        }

        private void WriteLevels(Collection<Level> levels)
        {
            string templateText = System.IO.File.ReadAllText("../../Templates/SceneTemplate");

            foreach (Level level in levels)
            {
                string levelText = templateText.Replace("!SCENECLASSNAME!", level.Name.Replace(" ", "_"));
                int counter = 0;
                string initgameobjects = "";

                foreach (LevelObject lo in level.levelObjects)
                {
                    initgameobjects += "\t\t\tvar go_"+counter.ToString() +":" + lo.Class.Name.Replace(" ", "_") + " = new "+ lo.Class.Name.Replace(" ", "_") +"(" + lo.X.ToString() + ", " + lo.Y.ToString() + ");\n";
                    initgameobjects += "\t\t\tgameObjectsList.push(go_"+counter.ToString()+");\n";
                    ++counter;
                }

                levelText = levelText.Replace("!INITGAMEOBJECTS!", initgameobjects);
                System.IO.File.WriteAllText(path + level.Name.Replace(" ", "_") + ".as", levelText);
            }

            string sceneManagerTemplateText = System.IO.File.ReadAllText("../../Templates/SceneManagerTemplate");
            string sceneManagerText = sceneManagerTemplateText;
            string levelsadded = "";
            foreach (Level level in levels)
            {
                levelsadded += "\t\t\tvar lvl_" + level.Name.Replace(" ", "_") + ":" + level.Name.Replace(" ", "_") + " = new " + level.Name.Replace(" ", "_") + "();\n";
                levelsadded += "\t\t\tscenes.push(lvl_" + level.Name.Replace(" ", "_") + ");\n";
            }
            sceneManagerText = sceneManagerText.Replace("!ADDLEVELS!", levelsadded);
            sceneManagerText = sceneManagerText.Replace("!FIRSTLEVEL!", "lvl_" + levels[0].Name.Replace(" ", "_"));
            System.IO.File.WriteAllText(path + "SceneManager.as", sceneManagerText);
        }

        private void WriteAssets(GameProject gameProject)
        {
            string templateText = System.IO.File.ReadAllText("../../Templates/AssetsTemplate");
            string assetsText = String.Empty,
                   graphicsList = String.Empty,
                   soundsList = String.Empty,
                   levelsList = String.Empty;

            foreach (Sprite sprite in gameProject.Sprites)
            {
                //[Embed(source = "assets/images/ball.png")] public static var IMG_BALL:Class;
                foreach (Image image in sprite.Images)
                {
                    graphicsList += "[Embed(source = \"assets/" + image.FileName + "\")] public static var " + ImageResourceName(image.Name) + ":Class;\n";
                }
            }
            foreach (Sound sound in gameProject.Sounds)
            {
                //soundsList += "[Embed(source = \"assets/" + sound.FileName + "\")] public static var SND_" + sound.Name.Replace(" ", "_") + ":Class;\n";
            }
            //[Embed(source = 'assets/levels/lvl1.xml', mimeType = "application/octet-stream")] public static const LEVEL1:Class;
            templateText = templateText.Replace("!GRAPHICS!", graphicsList);
            templateText = templateText.Replace("!SOUNDS!",   soundsList  );
            templateText = templateText.Replace("!XML!", levelsList);
            System.IO.File.WriteAllText(path + "Assets.as", templateText.Replace("!ASSETLIST!", assetsText));
        }

        private void WriteHelperClasses(GameProject gameProject)
        {
            string templateText = System.IO.File.ReadAllText("../../Templates/SceneBaseTemplate");
            System.IO.File.WriteAllText(path + "SceneBase.as", templateText);

        }
    }
}


text:
<?php

namespace ZendTest\Stdlib;
use Zend\EventManager\FilterChain,
    Zend\Stdlib\CallbackHandler;

/**
 * @category   Zend
 * @package    Zend_Stdlib
 * @subpackage UnitTests
 * @group      Zend_Stdlib
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class FilterChainTest extends \PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        if (isset($this->message)) {
            unset($this->message);
        }
        $this->filterchain = new FilterChain;
    }

    public function testSubscribeShouldReturnCallbackHandler()
    {
        $handle = $this->filterchain->attach(array( $this, __METHOD__ ));
        $this->assertTrue($handle instanceof CallbackHandler);
    }

    public function testSubscribeShouldAddCallbackHandlerToFilters()
    {
        $handler  = $this->filterchain->attach(array($this, __METHOD__));
        $handlers = $this->filterchain->getFilters();
        $this->assertEquals(1, count($handlers));
        $this->assertTrue($handlers->contains($handler));
    }

    public function testDetachShouldRemoveCallbackHandlerFromFilters()
    {
        $handle = $this->filterchain->attach(array( $this, __METHOD__ ));
        $handles = $this->filterchain->getFilters();
        $this->assertTrue($handles->contains($handle));
        $this->filterchain->detach($handle);
        $handles = $this->filterchain->getFilters();
        $this->assertFalse($handles->contains($handle));
    }

    public function testDetachShouldReturnFalseIfCallbackHandlerDoesNotExist()
    {
        $handle1 = $this->filterchain->attach(array( $this, __METHOD__ ));
        $this->filterchain->clearFilters();
        $handle2 = $this->filterchain->attach(array( $this, 'handleTestTopic' ));
        $this->assertFalse($this->filterchain->detach($handle1));
    }

    public function testRetrievingAttachedFiltersShouldReturnEmptyArrayWhenNoFiltersExist()
    {
        $handles = $this->filterchain->getFilters();
        $this->assertEquals(0, count($handles));
    }

    public function testFilterChainShouldReturnLastResponse()
    {
        $this->filterchain->attach(function($context, $params, $chain) {
            if (isset($params['string'])) {
                $params['string'] = trim($params['string']);
            }
            $return =  $chain->next($context, $params, $chain);
            return $return;
        });
        $this->filterchain->attach(function($context, array $params) {
            $string = isset($params['string']) ? $params['string'] : '';
            return str_rot13($string);
        });
        $value = $this->filterchain->run($this, array('string' => ' foo '));
        $this->assertEquals(str_rot13(trim(' foo ')), $value);
    }

    public function testFilterIsPassedContextAndArguments()
    {
        $this->filterchain->attach(array( $this, 'filterTestCallback1' ));
        $obj = (object) array('foo' => 'bar', 'bar' => 'baz');
        $value = $this->filterchain->run($this, array('object' => $obj));
        $this->assertEquals('filtered', $value);
        $this->assertEquals('filterTestCallback1', $this->message);
        $this->assertEquals('foobarbaz', $obj->foo);
    }

    public function testInterceptingFilterShouldReceiveChain()
    {
        $this->filterchain->attach(array($this, 'filterReceivalCallback'));
        $this->filterchain->run($this);
    }

    public function testFilteringStopsAsSoonAsAFilterFailsToCallNext()
    {
        $this->filterchain->attach(function($context, $params, $chain) {
            if (isset($params['string'])) {
                $params['string'] = trim($params['string']);
            }
            return $chain->next($context, $params, $chain);
        }, 10000);
        $this->filterchain->attach(function($context, array $params) {
            $string = isset($params['string']) ? $params['string'] : '';
            return str_rot13($string);
        }, 1000);
        $this->filterchain->attach(function($context, $params, $chain) {
            $string = isset($params['string']) ? $params['string'] : '';
            return hash('md5', $string);
        }, 100);
        $value = $this->filterchain->run($this, array('string' => ' foo '));
        $this->assertEquals(str_rot13(trim(' foo ')), $value);
    }

    public function handleTestTopic($message)
    {
        $this->message = $message;
    }

    public function filterTestCallback1($context, array $params)
    {
        $context->message = __FUNCTION__;
        if (isset($params['object']) && is_object($params['object'])) {
            $params['object']->foo = 'foobarbaz';
        }
        return 'filtered';
    }

    public function filterReceivalCallback($context, array $params, $chain)
    {
        $this->assertInstanceOf('Zend\EventManager\Filter\FilterIterator', $chain);
    }
}