text:
/**
* *MMAttachment* is used for downloading attachments.
*/
@interface MMAttachment : NSObject

/**
 @name Properties
 */

/**
 The file URL for the attachment.

 While sending attachments, this is automatically populated by init(fileURL:mimeType:) and init(fileURL:mimeType:name:description:).
 On received attachments, this is automatically populated by downloadFileWithSuccess(_:failure:).
 */
@property (nonatomic, readonly, strong) NSURL * __nullable fileURL;

/**
 The data for the attachment.

 While sending attachments, this is automatically populated by init(data:mimeType:) and init(data:mimeType:name:description:).
 On received attachments, this is automatically populated by downloadDataWithSuccess(_:failure:).
 */
@property (nonatomic, readonly, strong) NSData * __nullable data;

/**
 The input stream for the attachment.

 While sending attachments, this is automatically populated by init(inputStream:length:mimeType:) and init(inputStream:length:mimeType:name:description:).
 On received attachments, this is automatically populated by downloadInputStreamWithSuccess(_:failure:).
 */
@property (nonatomic, readonly, strong) NSInputStream * __nullable inputStream;

/**
 The string content for the attachment.

 While sending attachments, this is automatically populated by init(content:mimeType:) and init(content:mimeType:).
 On received attachments, this is automatically populated by downloadStringWithSuccess(_:failure:).
 */
@property (nonatomic, readonly, copy) NSString * __nullable content;

/**
 The unique identifer for the attachment.
 */
@property (nonatomic, readonly, copy) NSString * __nullable attachmentID;

/**
 The name for the attachment.
 */
@property (nonatomic, readonly, copy) NSString * __nullable name;

/**
 The summary for the attachment.
 */
@property (nonatomic, readonly, copy) NSString * __nullable summary;

/**
 The attachmentID's hash value.
 */
@property (nonatomic, readonly) NSUInteger hash;

/**
 The mime type for the attachment.
 */
@property (nonatomic, readonly, copy) NSString * __nonnull mimeType;

/**
 The download URL for the attachment.
 */
@property (nonatomic, strong) NSURL * __nullable downloadURL;

/**
 @name Initializers
 */

/**
 Initialize attachment.

 @param fileURL The file URL.
 @param mimeType The mime type.

 @return *MMAttachment*
 */
- (nonnull instancetype)initWithFileURL:(NSURL * __nonnull)fileURL mimeType:(NSString * __nonnull)mimeType;

/**
 Initialize attachment.

 @param fileURL The file URL.
 @param mimeType The mime type.
 @param name The name.
 @param description The description.

 @return *MMAttachment*
 */
- (nonnull instancetype)initWithFileURL:(NSURL * __nonnull)fileURL mimeType:(NSString * __nonnull)mimeType name:(NSString * __nullable)name description:(NSString * __nullable)description;

/**
 Initialize attachment.

 @param data The data.
 @param mimeType The mime type.

 @return *MMAttachment*
 */
- (nonnull instancetype)initWithData:(NSData * __nonnull)data mimeType:(NSString * __nonnull)mimeType;

/**
 Initialize attachment.

 @param data The data.
 @param mimeType The mime type.
 @param name The name.
 @param description The description.

 @return *MMAttachment*
 */
- (nonnull instancetype)initWithData:(NSData * __nonnull)data mimeType:(NSString * __nonnull)mimeType name:(NSString * __nullable)name description:(NSString * __nullable)description;

/**
 Initialize attachment.

 @param inputStream The inputStream.
 @param length The length.
 @param mimeType The mime type.

 @return *MMAttachment*
 */
- (nonnull instancetype)initWithInputStream:(NSInputStream * __nonnull)inputStream length:(int64_t)length mimeType:(NSString * __nonnull)mimeType;

/**
 Initialize attachment.

 @param inputStream The inputStream.
 @param length The length.
 @param mimeType The mime type.
 @param name The name.
 @param description The description.

 @return *MMAttachment*
 */
- (nonnull instancetype)initWithInputStream:(NSInputStream * __nonnull)inputStream length:(int64_t)length mimeType:(NSString * __nonnull)mimeType name:(NSString * __nullable)name description:(NSString * __nullable)description;

/**
 Initialize attachment.

 @param content The string content.
 @param mimeType The mime type.

 @return *MMAttachment*
 */
- (nonnull instancetype)initWithContent:(NSString * __nonnull)content mimeType:(NSString * __nonnull)mimeType;

/**
 Initialize attachment.

 @param content The string content.
 @param mimeType The mime type.
 @param name The name.
 @param description The description.

 @return *MMAttachment*
 */
- (nonnull instancetype)initWithContent:(NSString * __nonnull)content mimeType:(NSString * __nonnull)mimeType name:(NSString * __nullable)name description:(NSString * __nullable)description;

/**
 Default Initializer.

 @param mimeType The mime type.
 @param name The name.
 @param description The description.

 @return *MMAttachment*
 */
- (nonnull instancetype)initWithMimeType:(NSString * __nonnull)mimeType name:(NSString * __nullable)name description:(NSString * __nullable)description OBJC_DESIGNATED_INITIALIZER;

/**
 @name Factory Methods
 */

/** Create an attachment instance given a JSON string.

 @param jsonString The JSON string representation.

 @return An attachment instance.
 */
+ (nullable instancetype)fromJSONString:(NSString * __nonnull)jsonString;

/**
 @name Other Methods
 */

/** Get JSON string representation of the attachment.
 @return The JSON string representation of the attachment.
 */
- (NSString * __nonnull)toJSONString;

/** Compare equality.

 @param object An object to compare to current instance.

 @return true or false based on equality.
 */
- (BOOL)isEqual:(id __nullable)object;

/**
 @name Methods for Downloading
 */

/** Download the attachment to a specified file.

 @param fileURL The file URL where the attachment should be downloaded to.

 @param success A block object to be executed when the download finishes successfully. This block has no return value and takes no arguments.

 @param failure A block object to be executed when the logout finishes with an error. This block has no return value and takes one argument: the error object.
 */
- (void)downloadToFile:(NSURL * __nonnull)fileURL success:(void (^ __nullable)(void))success failure:(void (^ __nullable)(NSError * __nonnull))failure;

/** Download the attachment to a file.

 @param success A block object to be executed when the download finishes successfully. This block has no return value and takes one argument: the downloaded file URL.

 @param failure A block object to be executed when the logout finishes with an error. This block has no return value and takes one argument: the error object.
 */
- (void)downloadFileWithSuccess:(void (^ __nullable)(NSURL * __nonnull))success failure:(void (^ __nullable)(NSError * __nonnull))failure;

/** Download the attachment as data.

@param success A block object to be executed when the download finishes successfully. This block has no return value and takes one argument: the downloaded data.

@param failure A block object to be executed when the logout finishes with an error. This block has no return value and takes one argument: the error object.
 */
- (void)downloadDataWithSuccess:(void (^ __nullable)(NSData * __nonnull))success failure:(void (^ __nullable)(NSError * __nonnull))failure;

/** Download the attachment as an input stream.

 @param success A block object to be executed when the download finishes successfully. This block has no return value and takes one argument: the input stream for the downloaded data.

 @param failure A block object to be executed when the logout finishes with an error. This block has no return value and takes one argument: the error object.
 */
- (void)downloadInputStreamWithSuccess:(void (^ __nullable)(NSInputStream * __nonnull, int64_t))success failure:(void (^ __nullable)(NSError * __nonnull))failure;

/** Download the attachment as a string.

 @param success A block object to be executed when the download finishes successfully. This block has no return value and takes one argument: the string representation of the downloaded data.

 @param failure A block object to be executed when the logout finishes with an error. This block has no return value and takes one argument: the error object.
 */
- (void)downloadStringWithSuccess:(void (^ __nullable)(NSString * __nonnull))success failure:(void (^ __nullable)(NSError * __nonnull))failure;

@end


text:
import Ember from 'ember';

const { computed, defineProperty } = Ember;
const { reads } = computed;

function spliceCapitalizedString(string) {
  string = string.replace(/([A-Z])/g, ' $1');
  string = string.toLowerCase();
  return string.charAt(0).toUpperCase() + string.slice(1);
}

function isValidComputedProperty() {
  const errorsPath     = this.get('errorsPath');
  const propertyErrors = this.get(errorsPath);
  return propertyErrors == null || propertyErrors.length === 0;
}

export default Ember.Component.extend({
  classNames: 'form-field',
  classNameBindings: [
    'isValid::form-field--invalid',
    'isChanged:form-field--changed',
    'isDifferent:form-field--different'],

  labelText: computed('label', 'propertyPath', function() {
    const propertyPath = this.get('propertyPath');
    let label          = this.get('label');

    if (typeof label === 'string') {
      return label;
    }

    if (label == null && propertyPath != null) {
      return spliceCapitalizedString(propertyPath);
    }

    return null;
  }),

  errorsPath: computed('propertyPath', function() {
    return `object.errors.${this.get('propertyPath')}`;
  }),

  didReceiveAttrs: function() {
    if (!this.attrs.updated) {
      throw new Error(`You must provide an 'update' action to '{{form-field}}.`);
    } else if (typeof this.attrs.updated !== 'function') {
      throw new Error(`The 'update' action on '{{form-field}} must be a function.`);
    }
    const originPath   = this.get('originPath');
    const propertyPath = this.get('propertyPath');
    const errorsPath   = this.get('errorsPath');
    const changedPath  = originPath || propertyPath;

    defineProperty(this, 'isValid', computed(errorsPath, isValidComputedProperty));
    defineProperty(this, 'isChanged', reads(`object.${changedPath}IsChanged`));
    defineProperty(this, 'isDifferent', reads(`object.${propertyPath}IsDifferent`));
  },

  actions: {
    update: function(value) {
      const object       = this.get('object');
      const propertyPath = this. get('propertyPath');

      if (!this.get('disabled') && typeof this.attrs.updated === 'function') {
        this.attrs.updated(object, propertyPath, value);
      }
    }
  }
});

redpajama_set_name: RedPajamaGithub


text:
class Eye::Trigger::StartingGuard < Eye::Trigger

  # check that process ready to start or not
  # by custom user condition
  # if not, process switched to :unmonitored, and then retry to start after :every interval
  #
  # trigger :starting_guard, every: 10.seconds, should: ->{ `cat /tmp/bla` == "bla" }

  param :every, [Float, Integer], false, 10
  param :times, [Integer]
  param :retry_in, [Float, Integer]
  param :retry_times, [Integer]
  param :should, [Proc, Symbol]

  def initialize(*args)
    super

    @retry_count = 0
    @reretry_count = 0
  end

  def check(transition)
    check_start if transition.to_name == :starting
  end

  def check_start
    @retry_count += 1
    condition = defer { exec_proc(:should) }

    if condition
      info "ok, process ready to start #{condition.inspect}"
      @retry_count = 0
      @reretry_count = 0
      return
    else
      info 'false executed condition'
    end

    new_time = nil
    if every
      if times
        if @retry_count < times
          new_time = Time.now + every
          process.schedule(in: every, command: :conditional_start,
                           by: :starting_guard, reason: 'starting_guard, retry start')
        else
          @retry_count = 0
          @reretry_count += 1
          if retry_in && (!retry_times || (@reretry_count < retry_times))
            new_time = Time.now + retry_in
            process.schedule(in: retry_in, command: :conditional_start,
                             by: :starting_guard, reason: 'restarting_guard, retry start')
          end
        end
      else
        new_time = Time.now + every
        process.schedule(in: every, command: :conditional_start,
                         by: :starting_guard, reason: 'starting_guard, retry start')
      end
    end

    retry_msg = new_time ? ", retry at '#{Eye::Utils.human_time2(new_time.to_i)}'" : ''
    process.switch :unmonitoring, by: :starting_guard, reason: "failed condition#{retry_msg}"

    raise Eye::Process::StateError, 'starting_guard, refused to start'
  end

end


text:
<?php
class add_article extends UnitTestCase
{
	var $CI = '';

	function add_article()
	{
		$this->CI =& get_instance();
		$this->CI->load->model('setup/install_model');
		$this->CI->load->model('article_model');
	}

	function setUp()
	{
		$this->CI->install_model->table_articles(TRUE);
		$data = array(
					'article_author' => 1,
					'article_title' => "Búsqueda's",
					'article_uri' => 'cat',
					'article_keywords' => 'cat',
					'article_short_desc' => 'Short Description',
					'article_description' => 'Long Description',
					'article_display' => 'Y'
				);
		$var = $this->CI->article_model->add_article($data);
    }

    function tearDown()
	{
        $this->CI->install_model->table_articles(TRUE);
    }

	function test_add_article()
	{
	   	$data = array(
					'article_author' => 1,
					'article_title' => "Búsqueda's",
					'article_uri' => 'cat',
					'article_keywords' => 'cat',
					'article_short_desc' => 'Short Description',
					'article_description' => 'Long Description',
					'article_display' => 'Y'
				);
		$var = $this->CI->article_model->add_article($data);
		$this->assertTrue($var);
	}

	function test_edit()
	{
		$data = array(
					'article_author' => 1,
					'article_title' => "Búsqueda's",
					'article_uri' => "Búsqueda's",
					'article_keywords' => 'cat',
					'article_short_desc' => 'Short Description',
					'article_description' => 'Example Long Description',
					'article_display' => 'Y'
				);
		$var = $this->CI->article_model->edit_article(1, $data);
		$this->assertTrue($var);
	}

	function test_delete()
	{
		$var = $this->CI->article_model->delete_article(1);
		$this->assertTrue($var);
		$var = $this->CI->article_model->delete_article(24);
		$this->assertFalse($var);
	}

	function test_hit()
	{
		$var = $this->CI->article_model->add_hit(1);
		$this->assertTrue($var);
		$var = $this->CI->article_model->add_hit(2);
		$this->assertFalse($var);
	}
	function test_foriegn_uri()
	{
		$var = $this->CI->article_model->format_uri('áéíóúàèìòùñäëïöü');
		$this->assertEqual($var, 'aeiouaeiounaeiou');
		$var = $this->CI->article_model->format_uri('áéíóúüñ');
		$this->assertEqual($var, 'aeiouun');
	}
}


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

var R = require('../source');
var eq = require('./shared/eq');

describe('takeWhile', function() {
  it('continues taking elements while the function reports `true`', function() {
    eq(R.takeWhile(function(x) {return x !== 5;}, [1, 3, 5, 7, 9]), [1, 3]);
  });

  it('starts at the right arg and acknowledges undefined', function() {
    eq(R.takeWhile(function() { assert(false); }, []), []);
    eq(R.takeWhile(function(x) {return x !== void 0;}, [1, 3, void 0, 5, 7]), [1, 3]);
  });

  it('can operate on strings', function() {
    eq(R.takeWhile(function(x) { return x !== 'd'; }, 'Ramda'), 'Ram');
  });

});


text:
<?php

namespace Drupal\Tests\Core\PathProcessor;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Config\ImmutableConfig;
use Drupal\Core\PathProcessor\PathProcessorFront;
use Drupal\Tests\UnitTestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Test front page path processing.
 *
 * @group PathProcessor
 * @coversDefaultClass \Drupal\Core\PathProcessor\PathProcessorFront
 */
class PathProcessorFrontTest extends UnitTestCase {

  /**
   * Tests basic inbound processing functionality.
   *
   * @covers ::processInbound
   * @dataProvider providerProcessInbound
   */
  public function testProcessInbound($frontpage_path, $path, $expected, array $expected_query = []) {
    $config_factory = $this->prophesize(ConfigFactoryInterface::class);
    $config = $this->prophesize(ImmutableConfig::class);
    $config_factory->get('system.site')
      ->willReturn($config->reveal());
    $config->get('page.front')
      ->willReturn($frontpage_path);
    $processor = new PathProcessorFront($config_factory->reveal());
    $request = new Request();
    $this->assertEquals($expected, $processor->processInbound($path, $request));
    $this->assertEquals($expected_query, $request->query->all());
  }

  /**
   * Inbound paths and expected results.
   */
  public function providerProcessInbound() {
    return [
      'accessing frontpage' => ['/node', '/', '/node'],
      'accessing non frontpage' => ['/node', '/user', '/user'],
      'accessing frontpage with query parameters' => ['/node?example=muh',
        '/',
        '/node',
        ['example' => 'muh'],
      ],
    ];
  }

  /**
   * Tests inbound failure with broken config.
   *
   * @covers ::processInbound
   */
  public function testProcessInboundBadConfig() {
    $config_factory = $this->prophesize(ConfigFactoryInterface::class);
    $config = $this->prophesize(ImmutableConfig::class);
    $config_factory->get('system.site')
      ->willReturn($config->reveal());
    $config->get('page.front')
      ->willReturn('');
    $processor = new PathProcessorFront($config_factory->reveal());
    $this->expectException(NotFoundHttpException::class);
    $processor->processInbound('/', new Request());
  }

}


text:
StreamTesting
=============

References:
-----------
http://serverfault.com/questions/288137/how-to-stream-live-video-from-a-linux-server
https://wiki.videolan.org/Stream_VLC_to_Website_with_asf_and_Flash#Method_2_H264_and_Flash_.flv
http://blog.morscad.com/code-snippets/creating-a-video-player-in-as3-using-netstream/

Sample videos:
--------------
http://www.divx.com/en/devices/profiles/video

TODO:
-----
StageVideo?


text:
package com.intellij.psi.impl.java.stubs.impl;

import com.intellij.psi.*;
import com.intellij.psi.impl.compiled.ClsJavaCodeReferenceElementImpl;
import com.intellij.psi.impl.java.stubs.JavaClassReferenceListElementType;
import com.intellij.psi.impl.java.stubs.PsiClassReferenceListStub;
import com.intellij.psi.impl.source.PsiClassReferenceType;
import com.intellij.psi.impl.source.PsiJavaCodeReferenceElementImpl;
import com.intellij.psi.stubs.StubBase;
import com.intellij.psi.stubs.StubElement;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.ObjectUtils;
import org.jetbrains.annotations.NotNull;

/**
 * @author max
 */
public class PsiClassReferenceListStubImpl extends StubBase<PsiReferenceList> implements PsiClassReferenceListStub {
  private final String[] myNames;
  private volatile PsiClassType[] myTypes;

  public PsiClassReferenceListStubImpl(@NotNull JavaClassReferenceListElementType type, StubElement parent, @NotNull String[] names) {
    super(parent, type);
    ObjectUtils.assertAllElementsNotNull(names);
    myNames = names;
  }

  @NotNull
  @Override
  public PsiClassType[] getReferencedTypes() {
    PsiClassType[] types = myTypes;
    if (types == null) {
      myTypes = types = createTypes();
    }
    return types.clone();
  }

  @NotNull
  private PsiClassType[] createTypes() {
    PsiClassType[] types = myNames.length == 0 ? PsiClassType.EMPTY_ARRAY : new PsiClassType[myNames.length];

    final boolean compiled = ((JavaClassReferenceListElementType)getStubType()).isCompiled(this);
    if (compiled) {
      for (int i = 0; i < types.length; i++) {
        types[i] = new PsiClassReferenceType(new ClsJavaCodeReferenceElementImpl(getPsi(), myNames[i]), null);
      }
    }
    else {
      final PsiElementFactory factory = JavaPsiFacade.getElementFactory(getProject());

      int nullCount = 0;
      final PsiReferenceList psi = getPsi();
      for (int i = 0; i < types.length; i++) {
        try {
          final PsiJavaCodeReferenceElement ref = factory.createReferenceFromText(myNames[i], psi);
          ((PsiJavaCodeReferenceElementImpl)ref).setKindWhenDummy(PsiJavaCodeReferenceElementImpl.Kind.CLASS_NAME_KIND);
          types[i] = factory.createType(ref);
        }
        catch (IncorrectOperationException e) {
          types[i] = null;
          nullCount++;
        }
      }

      if (nullCount > 0) {
        PsiClassType[] newTypes = new PsiClassType[types.length - nullCount];
        int cnt = 0;
        for (PsiClassType type : types) {
          if (type != null) newTypes[cnt++] = type;
        }
        types = newTypes;
      }
    }
    return types;
  }

  @NotNull
  @Override
  public String[] getReferencedNames() {
    return myNames.clone();
  }

  @NotNull
  @Override
  public PsiReferenceList.Role getRole() {
    return JavaClassReferenceListElementType.elementTypeToRole(getStubType());
  }

  @Override
  public String toString() {
    StringBuilder builder = new StringBuilder();
    builder.append("PsiRefListStub[").append(getRole()).append(':');
    for (int i = 0; i < myNames.length; i++) {
      if (i > 0) builder.append(", ");
      builder.append(myNames[i]);
    }
    builder.append(']');
    return builder.toString();
  }
}


text:
<?php

namespace Humweb\Features\Resolvers;

/**
 * ClassResolver.
 */
class ClassResolver
{
    protected $namespace = '';
    protected $suffix    = '';

    /**
     * @param string $class
     *
     * @return string
     */
    public function resolve($class)
    {
        $class = $this->formatClassName($class);

        $assembledClass = '\\'.trim($this->getNamespace(), '\\').'\\'.$class.$this->getSuffix();

        if (class_exists($assembledClass)) {
            return $assembledClass;
        }

        if (class_exists($class)) {
            return $class;
        }

        throw new \InvalidArgumentException('Unable to resolve class: '.$class.' or '.$assembledClass);
    }

    /**
     * Format class name to "studly case"
     *
     * @param string $name
     *
     * @return string
     */
    protected function formatClassName($name)
    {
        $name = ucwords(str_replace(['-', '_'], ' ', $name));

        return str_replace(' ', '', $name);
    }

    /**
     * @param mixed $namespace
     *
     * @return ClassResolver
     */
    public function setNamespace($namespace)
    {
        $this->namespace = $namespace;

        return $this;
    }

    /**
     * @return mixed
     */
    public function getNamespace()
    {
        return $this->namespace;
    }

    /**
     * @param string $suffix
     *
     * @return ClassResolver
     */
    public function setSuffix($suffix)
    {
        $this->suffix = $suffix;

        return $this;
    }

    /**
     * @return string
     */
    public function getSuffix()
    {
        return $this->suffix;
    }
}


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/**
 * @path ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-2-3.js
 * @description Object.isExtensible returns true for all built-in objects (Function)
 */

function testcase() {
  function foo() {}

  var e = Object.isExtensible(foo);
  if (e === true) {
    return true;
  }
 }
runTestCase(testcase);


text:
package lms.service.impl;

import lms.mapper.LmsOrderMapper;
import lms.model.LmsOrder;
import lms.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    LmsOrderMapper lmsOrderMapper;

    public List<LmsOrder> findAll() {
        return lmsOrderMapper.selectByExample(null);//findCustomerAndAdminMap
    }

    public LmsOrder findById(BigDecimal id) {
        return lmsOrderMapper.selectByPrimaryKey(id);
    }

    public void deleteOrder(BigDecimal id) {
        lmsOrderMapper.deleteByPrimaryKey(id);
    }

    public void addOrder(LmsOrder lmsOrder) {
        lmsOrderMapper.insert(lmsOrder);
    }

    public void updateOrder(LmsOrder lmsOrder) {
        lmsOrderMapper.updateByPrimaryKey(lmsOrder);
    }
}


text:
namespace CallMeMaybe
{
    public static class MaybeExtensions
    {
        public static Maybe<T> ToMaybe<T>(this T value)
        {
            return value;
        }
        public static Maybe<T> ToMaybe<T>(this T? value)
            where T : struct
        {
            return value ?? Maybe<T>.Nothing;
        }
    }
}


text:
package org.usfirst.frc.team4572.robot.subsystems;

import org.usfirst.frc.team4572.robot.RobotMap;
import org.usfirst.frc.team4572.robot.commands.ExtensionRunner;

import edu.wpi.first.wpilibj.Solenoid;
import edu.wpi.first.wpilibj.command.Subsystem;

/**
 *
 */
public class ExtensionSystem extends Subsystem {

	private Solenoid backSolenoid = new Solenoid(RobotMap.BACK_SOLENOID_PORT);
	private Solenoid frontSolenoid = new Solenoid(RobotMap.FRONT_SOLENOID_PORT);

    private boolean pistonOpen = true;

    public void initDefaultCommand() {
        // Set the default command for a subsystem here.
        //setDefaultCommand(new MySpecialCommand());
    	setPiston(pistonOpen);
    	setDefaultCommand(new ExtensionRunner());
    }

    public void togglePiston() {
		pistonOpen = !pistonOpen;
		setPiston(pistonOpen);
	}
    private void setPiston(boolean state) {
    	backSolenoid.set(state);
    	frontSolenoid.set(!state);
    }

//	private Solenoid pistonSolenoid = new Solenoid(RobotMap.BACK_SOLENOID_PORT);
//
//    private boolean pistonOpen = false;
//
//    public void initDefaultCommand() {
//        // Set the default command for a subsystem here.
//        //setDefaultCommand(new MySpecialCommand());
//    	setPiston(pistonOpen);
//    	setDefaultCommand(new ExtensionRunner());
//    }
//
//    public void togglePiston() {
//		pistonOpen = !pistonOpen;
//		pistonSolenoid.set(pistonOpen);
//	}
//
//    private void setPiston(boolean state) {
//    	pistonSolenoid.set(state);
//    }
}


text:
"""
Module to set up run time parameters for Clawpack.

The values set in the function setrun are then written out to data files
that will be read in by the Fortran code.

"""

from __future__ import absolute_import
from __future__ import print_function

import os
import datetime
import shutil
import gzip
import numpy as np

from clawpack.geoclaw.surge.storm import Storm
import clawpack.clawutil as clawutil

# Time Conversions
def days2seconds(days):
    return days * 60.0**2 * 24.0

# Scratch directory for storing topo and dtopo files:
data_dir = os.path.join(os.environ.get('datadir', os.getcwd()))

# ------------------------------
def setrun(claw_pkg='geoclaw'):

    """
    Define the parameters used for running Clawpack.

    INPUT:
        claw_pkg expected to be "geoclaw" for this setrun.

    OUTPUT:
        rundata - object of class ClawRunData

    """

    from clawpack.clawutil import data

    assert claw_pkg.lower() == 'geoclaw',  "Expected claw_pkg = 'geoclaw'"

    num_dim = 2
    rundata = data.ClawRunData(claw_pkg, num_dim)

    # ------------------------------------------------------------------
    # Standard Clawpack parameters to be written to claw.data:
    #   (or to amr2ez.data for AMR)
    # ------------------------------------------------------------------
    clawdata = rundata.clawdata  # initialized when rundata instantiated

    # Set single grid parameters first.
    # See below for AMR parameters.

    # ---------------
    # Spatial domain:
    # ---------------

    # Number of space dimensions:
    clawdata.num_dim = num_dim

    # Lower and upper edge of computational domain:
    clawdata.lower[0] = -90.0      # west longitude
    clawdata.upper[0] = -60.0       # east longitude

    clawdata.lower[1] = 15.0       # south latitude
    clawdata.upper[1] = 35.0       # north latitude

    # Number of grid cells:
    degree_factor = 4 # (0.25º,0.25º) ~ (25237.5 m, 27693.2 m) resolution
    clawdata.num_cells[0] = int(clawdata.upper[0] - clawdata.lower[0]) * degree_factor
    clawdata.num_cells[1] = int(clawdata.upper[1] - clawdata.lower[1]) * degree_factor

    # ---------------
    # Size of system:
    # ---------------

    # Number of equations in the system:
    clawdata.num_eqn = 3

    # Number of auxiliary variables in the aux array (initialized in setaux)
    # First three are from shallow GeoClaw, fourth is friction and last 3 are
    # storm fields
    clawdata.num_aux = 3 + 1 + 3

    # Index of aux array corresponding to capacity function, if there is one:
    clawdata.capa_index = 2

    # -------------
    # Initial time:
    # -------------

    clawdata.t0 = -days2seconds(4)

    # Restart from checkpoint file of a previous run?
    # If restarting, t0 above should be from original run, and the
    # restart_file 'fort.chkNNNNN' specified below should be in
    # the OUTDIR indicated in Makefile.

    clawdata.restart = False               # True to restart from prior results
    clawdata.restart_file = 'fort.chk00006'  # File to use for restart data

    # -------------
    # Output times:
    # --------------

    # Specify at what times the results should be written to fort.q files.
    # Note that the time integration stops after the final output time.
    # The solution at initial time t0 is always written in addition.

    clawdata.output_style = 1

    if clawdata.output_style == 1:
        # Output nout frames at equally spaced times up to tfinal:
        clawdata.tfinal = days2seconds(2)
        recurrence = 4
        clawdata.num_output_times = int((clawdata.tfinal - clawdata.t0) * recurrence / (60**2 * 24))
        clawdata.output_t0 = True  # output at initial (or restart) time?

    elif clawdata.output_style == 2:
        # Specify a list of output times.
        clawdata.output_times = [0.5, 1.0]

    elif clawdata.output_style == 3:
        # Output every iout timesteps with a total of ntot time steps:
        clawdata.output_step_interval = 1
        clawdata.total_steps = 1
        clawdata.output_t0 = True

    clawdata.output_format = 'ascii'      # 'ascii' or 'binary'
    clawdata.output_q_components = 'all'   # could be list such as [True,True]
    clawdata.output_aux_components = 'all'
    clawdata.output_aux_onlyonce = False    # output aux arrays only at t0

    # ---------------------------------------------------
    # Verbosity of messages to screen during integration:
    # ---------------------------------------------------

    # The current t, dt, and cfl will be printed every time step
    # at AMR levels <= verbosity.  Set verbosity = 0 for no printing.
    #   (E.g. verbosity == 2 means print only on levels 1 and 2.)
    clawdata.verbosity = 0

    # --------------
    # Time stepping:
    # --------------

    # if dt_variable==1: variable time steps used based on cfl_desired,
    # if dt_variable==0: fixed time steps dt = dt_initial will always be used.
    clawdata.dt_variable = True

    # Initial time step for variable dt.
    # If dt_variable==0 then dt=dt_initial for all steps:
    clawdata.dt_initial = 0.016

    # Max time step to be allowed if variable dt used:
    clawdata.dt_max = 1e+99

    # Desired Courant number if variable dt used, and max to allow without
    # retaking step with a smaller dt:
    clawdata.cfl_desired = 0.75
    clawdata.cfl_max = 1.0

    # Maximum number of time steps to allow between output times:
    clawdata.steps_max = 10000

    # ------------------
    # Method to be used:
    # ------------------

    # Order of accuracy:  1 => Godunov,  2 => Lax-Wendroff plus limiters
    clawdata.order = 1

    # Use dimensional splitting? (not yet available for AMR)
    clawdata.dimensional_split = 'unsplit'

    # For unsplit method, transverse_waves can be
    #  0 or 'none'      ==> donor cell (only normal solver used)
    #  1 or 'increment' ==> corner transport of waves
    #  2 or 'all'       ==> corner transport of 2nd order corrections too
    clawdata.transverse_waves = 1

    # Number of waves in the Riemann solution:
    clawdata.num_waves = 3

    # List of limiters to use for each wave family:
    # Required:  len(limiter) == num_waves
    # Some options:
    #   0 or 'none'     ==> no limiter (Lax-Wendroff)
    #   1 or 'minmod'   ==> minmod
    #   2 or 'superbee' ==> superbee
    #   3 or 'mc'       ==> MC limiter
    #   4 or 'vanleer'  ==> van Leer
    clawdata.limiter = ['mc', 'mc', 'mc']

    clawdata.use_fwaves = True    # True ==> use f-wave version of algorithms

    # Source terms splitting:
    #   src_split == 0 or 'none'
    #      ==> no source term (src routine never called)
    #   src_split == 1 or 'godunov'
    #      ==> Godunov (1st order) splitting used,
    #   src_split == 2 or 'strang'
    #      ==> Strang (2nd order) splitting used,  not recommended.
    clawdata.source_split = 'godunov'

    # --------------------
    # Boundary conditions:
    # --------------------

    # Number of ghost cells (usually 2)
    clawdata.num_ghost = 2

    # Choice of BCs at xlower and xupper:
    #   0 => user specified (must modify bcN.f to use this option)
    #   1 => extrapolation (non-reflecting outflow)
    #   2 => periodic (must specify this at both boundaries)
    #   3 => solid wall for systems where q(2) is normal velocity

    clawdata.bc_lower[0] = 'extrap'
    clawdata.bc_upper[0] = 'extrap'

    clawdata.bc_lower[1] = 'extrap'
    clawdata.bc_upper[1] = 'extrap'

    # Specify when checkpoint files should be created that can be
    # used to restart a computation.

    clawdata.checkpt_style = 0

    if clawdata.checkpt_style == 0:
        # Do not checkpoint at all
        pass

    elif np.abs(clawdata.checkpt_style) == 1:
        # Checkpoint only at tfinal.
        pass

    elif np.abs(clawdata.checkpt_style) == 2:
        # Specify a list of checkpoint times.
        clawdata.checkpt_times = [0.1, 0.15]

    elif np.abs(clawdata.checkpt_style) == 3:
        # Checkpoint every checkpt_interval timesteps (on Level 1)
        # and at the final time.
        clawdata.checkpt_interval = 5

    # ---------------
    # AMR parameters:
    # ---------------
    amrdata = rundata.amrdata

    # max number of refinement levels:
    amrdata.amr_levels_max = 7

    # List of refinement ratios at each level (length at least mxnest-1)
    amrdata.refinement_ratios_x = [2, 2, 2, 2, 6, 4]
    amrdata.refinement_ratios_y = [2, 2, 2, 2, 6, 4]
    amrdata.refinement_ratios_t = [2, 2, 2, 2, 6, 4]

    # Specify type of each aux variable in amrdata.auxtype.
    # This must be a list of length maux, each element of which is one of:
    #   'center',  'capacity', 'xleft', or 'yleft'  (see documentation).

    amrdata.aux_type = ['center', 'capacity', 'yleft', 'center', 'center', 'center', 'center']

    # Flag using refinement routine flag2refine rather than richardson error
    amrdata.flag_richardson = False    # use Richardson?
    amrdata.flag2refine = True

    # steps to take on each level L between regriddings of level L+1:
    amrdata.regrid_interval = 3

    # width of buffer zone around flagged points:
    # (typically the same as regrid_interval so waves don't escape):
    amrdata.regrid_buffer_width = 2

    # clustering alg. cutoff for (# flagged pts) / (total # of cells refined)
    # (closer to 1.0 => more small grids may be needed to cover flagged cells)
    amrdata.clustering_cutoff = 0.700000

    # print info about each regridding up to this level:
    amrdata.verbosity_regrid = 0

    #  ----- For developers -----
    # Toggle debugging print statements:
    amrdata.dprint = False      # print domain flags
    amrdata.eprint = False      # print err est flags
    amrdata.edebug = False      # even more err est flags
    amrdata.gprint = False      # grid bisection/clustering
    amrdata.nprint = False      # proper nesting output
    amrdata.pprint = False      # proj. of tagged points
    amrdata.rprint = False      # print regridding summary
    amrdata.sprint = False      # space/memory output
    amrdata.tprint = False      # time step reporting each level
    amrdata.uprint = False      # update/upbnd reporting

    # More AMR parameters can be set -- see the defaults in pyclaw/data.py

    # == setregions.data values ==
    regions = rundata.regiondata.regions

    # to specify regions of refinement append lines of the form
    #  [minlevel,maxlevel,t1,t2,x1,x2,y1,y2]

    # region for entire domain
    regions.append([1, 2, rundata.clawdata.t0, rundata.clawdata.tfinal, -90.0, -60.0, 15.0, 35.0])

    # regions of higher refinement around gauges
    regions.append([5, 7, rundata.clawdata.t0, rundata.clawdata.tfinal, -81.2, -80.9, 24.6, 24.8])
    regions.append([6, 7, rundata.clawdata.t0, rundata.clawdata.tfinal, -81.9, -81.65, 24.4, 24.7])
    regions.append([3, 7, rundata.clawdata.t0, rundata.clawdata.tfinal, -81.9, -81.5, 25.75, 26.25])
    regions.append([4, 7, rundata.clawdata.t0, rundata.clawdata.tfinal, -83.0, -82.0, 27.0, 28.0])
    regions.append([2, 7, rundata.clawdata.t0, rundata.clawdata.tfinal, -83.5, -82.5, 27.5, 28.5])
    regions.append([5, 7, rundata.clawdata.t0, rundata.clawdata.tfinal, -66.5, -65.5, 18.0, 19.0])

    # regions of lower refinement
    regions.append([1, 1, rundata.clawdata.t0, rundata.clawdata.tfinal, -75.0, -60.0, 25.0, 35.0])
    regions.append([1, 1, rundata.clawdata.t0, rundata.clawdata.tfinal, -90.0, -85.0, 17.5, 25.0])
    regions.append([1, 1, rundata.clawdata.t0, rundata.clawdata.tfinal, -90.0, -60.0, 15.0, 17.5])
    regions.append([1, 1, rundata.clawdata.t0, rundata.clawdata.tfinal, -90.0, -75.0, 32.5, 35.0])

    # ------------------------------------------ Gauges for Irma ----------------------------------------
    # Vaca Key, Florida Bay, FL (ID: 8723970) (Marathon)
    # https://tidesandcurrents.noaa.gov/waterlevels.html?id=8723970&units=standard&bdate=20170907&edate=20170913&timezone=GMT&datum=MLLW&interval=6&action=
    rundata.gaugedata.gauges.append([1, -81.1057, 24.7119, rundata.clawdata.t0, rundata.clawdata.tfinal])

    # Key West, FL (ID: 8724580)
    # https://tidesandcurrents.noaa.gov/waterlevels.html?id=8724580&units=standard&bdate=20170907&edate=20170913&timezone=GMT&datum=MLLW&interval=6&action=
    rundata.gaugedata.gauges.append([2, -81.7885, 24.5763, rundata.clawdata.t0, rundata.clawdata.tfinal])

    # Naples, Gulf of Mexico, FL (ID: 8725110)
    # https://tidesandcurrents.noaa.gov/waterlevels.html?id=8725110&units=standard&bdate=20170907&edate=20170913&timezone=GMT&datum=MLLW&interval=6&action=
    rundata.gaugedata.gauges.append([3, -81.8211, 26.1316, rundata.clawdata.t0, rundata.clawdata.tfinal])

    # Port Manatee, FL (ID: 8726384)
    # https://tidesandcurrents.noaa.gov/waterlevels.html?id=8726384&units=standard&bdate=20170907&edate=20170913&timezone=GMT&datum=MLLW&interval=6&action=
    rundata.gaugedata.gauges.append([4, -82.5678, 27.6382, rundata.clawdata.t0, rundata.clawdata.tfinal])

    # Clearwater Beach, FL (ID: 8726724)
    # https://tidesandcurrents.noaa.gov/waterlevels.html?id=8726724&units=standard&bdate=20170907&edate=20170913&timezone=GMT&datum=MLLW&interval=6&action=
    rundata.gaugedata.gauges.append([5, -82.8341, 27.9778, rundata.clawdata.t0, rundata.clawdata.tfinal])

    # San Juan, PR (ID: 9755371)
    # https://tidesandcurrents.noaa.gov/waterlevels.html?id=9755371&units=standard&bdate=20170907&edate=20170913&timezone=GMT&datum=MLLW&interval=6&action=
    rundata.gaugedata.gauges.append([6, -66.1165, 18.4570, rundata.clawdata.t0, rundata.clawdata.tfinal])

    # ----------------------------------------------------------------------------------------------------

    # Force the gauges to also record the wind and pressure fields
    rundata.gaugedata.aux_out_fields = [4, 5, 6]

    # ------------------------------------------------------------------
    # GeoClaw specific parameters:
    # ------------------------------------------------------------------
    rundata = setgeo(rundata)

    return rundata
    # end of function setrun
    # ----------------------

# -------------------
def setgeo(rundata):
    """
    Set GeoClaw specific runtime parameters.
    For documentation see ....
    """

    geo_data = rundata.geo_data

    # == Physics ==
    geo_data.gravity = 9.81
    geo_data.coordinate_system = 2
    geo_data.earth_radius = 6367.5e3
    geo_data.rho = 1025.0
    geo_data.rho_air = 1.15
    geo_data.ambient_pressure = 101.3e3

    # == Forcing Options
    geo_data.coriolis_forcing = True
    geo_data.friction_forcing = True
    geo_data.friction_depth = 1e10

    # == Algorithm and Initial Conditions ==
    # Due to seasonal swelling of gulf we set sea level higher
    geo_data.sea_level = 0.0
    geo_data.dry_tolerance = 1.e-2

    # Refinement Criteria
    refine_data = rundata.refinement_data
    refine_data.wave_tolerance = 1.0
    refine_data.speed_tolerance = [1.0, 2.0, 3.0, 4.0]
    refine_data.deep_depth = 300.0
    refine_data.max_level_deep = 4
    refine_data.variable_dt_refinement_ratios = True

    # == settopo.data values ==
    topo_data = rundata.topo_data
    topo_data.topofiles = []
    # for topography, append lines of the form:[topotype, minlevel, maxlevel, t1, t2, fname]
    # See regions for control over these regions, need better bathy data for the smaller domains
    # !!!!!!!!!!!!!!!!NEED TO MODIFY PATH HERE IF TESTING EXAMPLE!!!!!!!!!!!!!
    topo_path = os.path.join(data_dir, "gebco_irma_topo.asc")
    topo_data.topofiles.append([3, 1, 7, rundata.clawdata.t0, rundata.clawdata.tfinal, topo_path])

    # == setfixedgrids.data values ==
    rundata.fixed_grid_data.fixedgrids = []
    # for fixed grids append lines of the form
    # [t1,t2,noutput,x1,x2,y1,y2,xpoints,ypoints,ioutarrivaltimes,ioutsurfacemax]

    # ================
    #  Set Surge Data
    # ================
    data = rundata.surge_data

    # Source term controls
    data.wind_forcing = True
    data.drag_law = 1
    data.pressure_forcing = True
    data.display_landfall_time = True

    # AMR parameters, m/s and m respectively
    data.wind_refine = [20.0, 40.0, 60.0]
    data.R_refine = [60.0e3, 40e3, 20e3]

    # Storm parameters - Parameterized storm (Holland 1980)
    data.storm_specification_type = 'holland80'  # (type 1)
    data.storm_file = os.path.expandvars(os.path.join(os.getcwd(),'irma.storm'))

    # Convert ATCF data to GeoClaw format
    clawutil.data.get_remote_file("https://ftp.nhc.noaa.gov/atcf/archive/2017/bal112017.dat.gz")
    atcf_path = os.path.join(data_dir, "bal112017.dat")

    # Note that the get_remote_file function does not support gzip files which
    # are not also tar files.  The following code handles this
    with gzip.open(".".join((atcf_path, 'gz')), 'rb') as atcf_file, open(atcf_path, 'w') as atcf_unzipped_file:
        atcf_unzipped_file.write(atcf_file.read().decode('ascii'))

    # irma = Storm(path="old_irma.storm", file_format="ATCF")
    irma = Storm(path=atcf_path, file_format="ATCF")

    # Calculate landfall time - Need to specify as the file above does not
    # Irma landfall in Cudjoe Key: 9/10/2017 ~ 09:10 EDT, 13:10 UTC
    irma.time_offset = datetime.datetime(2017, 9, 10, 13)

    irma.write(data.storm_file, file_format='geoclaw')

    # =======================
    #  Set Variable Friction
    # =======================
    data = rundata.friction_data

    # Variable friction
    data.variable_friction = True

    # Region based friction
    # Entire domain
    data.friction_regions.append([rundata.clawdata.lower, rundata.clawdata.upper, [np.infty, 0.0, -np.infty], [0.030, 0.022]])

    # La-Tex Shelf
    data.friction_regions.append([(-98, 25.25), (-90, 30), [np.infty, -10.0, -200.0, -np.infty], [0.030, 0.012, 0.022]])

    return rundata
    # end of function setgeo
    # ----------------------

if __name__ == '__main__':
    # Set up run-time parameters and write all data files.
    import sys
    if len(sys.argv) == 2:
        rundata = setrun(sys.argv[1])
    else:
        rundata = setrun()

    rundata.write()


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

import java.io.File;
import java.util.Map;
import java.util.Random;

import org.apache.accumulo.core.cli.BatchWriterOpts;
import org.apache.accumulo.core.cli.ScannerOpts;
import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.client.Connector;
import org.apache.accumulo.core.conf.Property;
import org.apache.accumulo.minicluster.impl.MiniAccumuloClusterImpl;
import org.apache.accumulo.minicluster.impl.MiniAccumuloConfigImpl;
import org.apache.accumulo.test.util.CertUtils;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.junit.Rule;
import org.junit.rules.TestName;
import org.junit.rules.Timeout;

public abstract class AbstractMacIT {
  public static final Logger log = Logger.getLogger(AbstractMacIT.class);

  public static final String ROOT_PASSWORD = "testRootPassword1";
  public static final ScannerOpts SOPTS = new ScannerOpts();
  public static final BatchWriterOpts BWOPTS = new BatchWriterOpts();

  @Rule
  public TestName testName = new TestName();

  protected static void cleanUp(MiniAccumuloClusterImpl cluster) {
    if (cluster != null)
      try {
        cluster.stop();
      } catch (Exception e) {}
  }

  protected static File createSharedTestDir(String name) {
    File baseDir = new File(System.getProperty("user.dir") + "/target/mini-tests");
    baseDir.mkdirs();
    if (name != null)
      baseDir = new File(baseDir, name);
    File testDir = new File(baseDir, System.currentTimeMillis() + "_" + new Random().nextInt(Short.MAX_VALUE));
    FileUtils.deleteQuietly(testDir);
    testDir.mkdir();
    return testDir;
  }

  protected static File createTestDir(String name) {
    File baseDir = new File(System.getProperty("user.dir") + "/target/mini-tests");
    baseDir.mkdirs();
    if (name == null)
      return baseDir;
    File testDir = new File(baseDir, name);
    FileUtils.deleteQuietly(testDir);
    testDir.mkdir();
    return testDir;
  }

  public String[] getUniqueNames(int num) {
    String[] names = new String[num];
    for (int i = 0; i < num; i++)
      names[i] = this.getClass().getSimpleName() + "_" + testName.getMethodName() + i;
    return names;
  }

  protected static void configureForEnvironment(MiniAccumuloConfigImpl cfg, Class<?> testClass, File folder) {
    if ("true".equals(System.getProperty("org.apache.accumulo.test.functional.useSslForIT"))) {
      configureForSsl(cfg, folder);
    }
  }

  protected static void configureForSsl(MiniAccumuloConfigImpl cfg, File folder) {
    Map<String,String> siteConfig = cfg.getSiteConfig();
    if ("true".equals(siteConfig.get(Property.INSTANCE_RPC_SSL_ENABLED.getKey()))) {
      // already enabled; don't mess with it
      return;
    }

    File sslDir = new File(folder, "ssl");
    sslDir.mkdirs();
    File rootKeystoreFile = new File(sslDir, "root-" + cfg.getInstanceName() + ".jks");
    File localKeystoreFile = new File(sslDir, "local-" + cfg.getInstanceName() + ".jks");
    File publicTruststoreFile = new File(sslDir, "public-" + cfg.getInstanceName() + ".jks");
    try {
      new CertUtils(Property.RPC_SSL_KEYSTORE_TYPE.getDefaultValue(), "o=Apache Accumulo,cn=MiniAccumuloCluster", "RSA", 2048, "sha1WithRSAEncryption")
          .createAll(rootKeystoreFile, localKeystoreFile, publicTruststoreFile, cfg.getInstanceName(), cfg.getRootPassword());
    } catch (Exception e) {
      throw new RuntimeException("error creating MAC keystore", e);
    }

    siteConfig.put(Property.INSTANCE_RPC_SSL_ENABLED.getKey(), "true");
    siteConfig.put(Property.RPC_SSL_KEYSTORE_PATH.getKey(), localKeystoreFile.getAbsolutePath());
    siteConfig.put(Property.RPC_SSL_KEYSTORE_PASSWORD.getKey(), cfg.getRootPassword());
    siteConfig.put(Property.RPC_SSL_TRUSTSTORE_PATH.getKey(), publicTruststoreFile.getAbsolutePath());
    cfg.setSiteConfig(siteConfig);
  }

  /**
   * If a given IT test has a method that takes longer than a class-set default timeout, declare it failed.
   *
   * Note that this provides a upper bound on test times, even in the presence of Test annotations with
   * a timeout. That is, the Test annotatation can make the timing tighter but will not be able to allow
   * a timeout that takes longer.
   *
   * Defaults to no timeout and can be changed via two mechanisms
   *
   * 1) A given IT class can override the defaultTimeoutSeconds method if test methods in that class should
   *    have a timeout.
   * 2) The system property "timeout.factor" is used as a multiplier for the class provided default
   *
   * Note that if either of these values is '0' tests will run with no timeout. The default class level
   * timeout is set to 0.
   *
   */
  @Rule
  public Timeout testsShouldTimeout() {
    int waitLonger = 0;
    try {
      waitLonger = Integer.parseInt(System.getProperty("timeout.factor"));
    } catch (NumberFormatException exception) {
      log.warn("Could not parse timeout.factor, defaulting to no timeout.");
    }
    return new Timeout(waitLonger * defaultTimeoutSeconds() * 1000);
  }

  /**
   * time to wait per-method before declaring a timeout, in seconds.
   */
  protected int defaultTimeoutSeconds() {
    return 0;
  }

  public abstract Connector getConnector() throws AccumuloException, AccumuloSecurityException;

  public abstract String rootPath();
}


text:
function list_patients_per_feature
% List the patients that are common to all feature sets, and the ones that
% are unique to specific feature sets

% By Daniel Golden (dgolden1 at stanford dot edu) July 2012
% $Id$

%% Get patient ids for each feature type
[~, ~, patient_id_jj] = collect_features(...
  'jj_str', 'all', 'b_man_char_v1', false, 'b_man_char_v2', false, 'b_birads', false, 'b_glcm', false);

[~, ~, patient_id_man_char_v1] = collect_features(...
  'jj_str', 'none', 'b_man_char_v1', true, 'b_man_char_v2', false, 'b_birads', false, 'b_glcm', false);

[~, ~, patient_id_man_char_v2] = collect_features(...
  'jj_str', 'none', 'b_man_char_v1', false, 'b_man_char_v2', true, 'b_birads', false, 'b_glcm', false);

[~, ~, patient_id_birads] = collect_features(...
  'jj_str', 'none', 'b_man_char_v1', false, 'b_man_char_v2', false, 'b_birads', true, 'b_glcm', false);

[~, ~, patient_id_glcm] = collect_features(...
  'jj_str', 'none', 'b_man_char_v1', false, 'b_man_char_v2', false, 'b_birads', false, 'b_glcm', true);

%% Get patient ids that are common to all features
patient_id_common = multi_intersect(patient_id_jj, patient_id_man_char_v1, patient_id_man_char_v2, patient_id_birads, patient_id_glcm);

%% Get patient ids for each feature that are not in the list of common patient ids
names = {'jiajing''s features', 'man_char_v1', 'man_char_v2', 'birads', 'glcm'};
unique_patient_id_list = {setdiff(patient_id_jj, patient_id_common), ...
                          setdiff(patient_id_man_char_v1, patient_id_common), ...
                          setdiff(patient_id_man_char_v2, patient_id_common), ...
                          setdiff(patient_id_birads, patient_id_common), ...
                          setdiff(patient_id_glcm, patient_id_common)};

%% List them
for kk = 1:length(names)
  fprintf('Patients unique to %s: ', names{kk});
  fprintf('%03d ', unique_patient_id_list{kk});
  fprintf('\n');
end

1;

function out = multi_intersect(varargin)
%% Function: Intersect with an arbitrary number of inputs
out = varargin{1};
for kk = 1:(nargin - 1)
  out = intersect(out, varargin{kk+1});
end


text:
#ifndef RTTR_CREATE_TYPE_VISITOR_FUNC_IMPL_H_
#define RTTR_CREATE_TYPE_VISITOR_FUNC_IMPL_H_

#include "rttr/detail/base/core_prerequisites.h"
#include "rttr/visitor.h"
#include "rttr/detail/visitor/visitor_iterator.h"
#include "rttr/detail/visitor/type_visitor_invoker.h"

namespace rttr
{
namespace detail
{

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

template<typename T, typename Visitor_list, typename...Base_Classes>
RTTR_INLINE void visit_type_impl(type_of_visit visit_type, visitor& vi, const type& t, type_list<Base_Classes...>)
{
    auto obj = make_type_visitor_info<T, Base_Classes...>(t);
    visitor_iterator<Visitor_list>::visit(vi, make_type_visitor_invoker(obj, visit_type));
}

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

template<typename T, typename Visitor_list>
RTTR_INLINE
enable_if_t<has_base_class_list<T>::value, void>
visit_type(type_of_visit visit_type, visitor& vi, const type& t)
{
    visit_type_impl<T, Visitor_list>(visit_type, vi, t, typename T::base_class_list{});
}

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

template<typename T, typename Visitor_list>
RTTR_INLINE
enable_if_t<!has_base_class_list<T>::value, void>
visit_type(type_of_visit visit_type, visitor& vi, const type& t)
{
    auto obj = make_type_visitor_info<T>(t);
    visitor_iterator<Visitor_list>::visit(vi, make_type_visitor_invoker(obj, visit_type));
}

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

} // end namespace detail
} // end namespace rttr

#endif // RTTR_CREATE_TYPE_VISITOR_FUNC_H_


text:
'use strict';

/**
 * @ngdoc service
 * @name loopbackApp.AppAuth
 * @description
 * # AppAuth
 * Factory in the loopbackApp.
 */
angular.module('yoApp')
  .factory('Auth', function () {
    return {
      currentUser: null,

      // Note: we can't make the User a dependency of AppAuth
      // because that would create a circular dependency
      //   Auth <- $http <- $resource <- LoopBackResource <- User <- AppAuth
      ensureHasCurrentUser: function(User) {
        if (this.currentUser) {
          if (this.currentUser.id === 'social') {
            this.currentUser = User.getAccount(function(data) {
              // success
              console.log("Data User1 :", data);
            }, function () {
              console.log('User.getAccount() err', arguments);
            });
          } else {
            console.log('Using cached current user.');
          }
        } else {
          console.log('Fetching current user from the server.');
          this.currentUser = User.getCurrent(function(data) {
            // success
            console.log("Data User1 :", data);
          }, function(response) {
            console.log('User.getCurrent() err', arguments, response);
          });
        }
      }
    };
  });


text:
require 'faraday_middleware/response/parse_hal_json'

describe FaradayMiddleware::ParseHalJson, type: :response do
  context 'no type matching' do
    it "doesn't change nil body" do
      expect(process(nil).body).to be_nil
    end

    it 'nullifies empty body' do
      expect(process('').body).to be_nil
    end

    it 'parses json body' do
      response = process('{"a":1}')
      expect(response.body).to eq('a' => 1)
      expect(response.env[:raw_body]).to be_nil
    end
  end

  context 'with preserving raw' do
    let(:options) { { preserve_raw: true } }

    it 'parses json body' do
      response = process('{"a":1}')
      expect(response.body).to eq('a' => 1)
      expect(response.env[:raw_body]).to eq('{"a":1}')
    end

    it 'can opt out of preserving raw' do
      response = process('{"a":1}', nil, preserve_raw: false)
      expect(response.env[:raw_body]).to be_nil
    end
  end

  context 'with regexp type matching' do
    let(:options) { { content_type: /\bjson$/ } }

    it 'parses json body of correct type' do
      response = process('{"a":1}', 'application/x-json')
      expect(response.body).to eq('a' => 1)
    end

    it 'ignores json body of incorrect type' do
      response = process('{"a":1}', 'text/json-xml')
      expect(response.body).to eq('{"a":1}')
    end
  end

  context 'with array type matching' do
    let(:options) { { content_type: %w[a/b c/d] } }

    it 'parses json body of correct type' do
      expect(process('{"a":1}', 'a/b').body).to be_a(Hash)
      expect(process('{"a":1}', 'c/d').body).to be_a(Hash)
    end

    it 'ignores json body of incorrect type' do
      expect(process('{"a":1}', 'a/d').body).not_to be_a(Hash)
    end
  end

  it 'chokes on invalid json' do
    ['{!', '"a'].each do |data|
      expect { process(data) }.to raise_error(Faraday::ParsingError)
    end
  end

  context 'HEAD responses' do
    it "nullifies the body if it's only one space" do
      response = process(' ')
      expect(response.body).to be_nil
    end

    it "nullifies the body if it's two spaces" do
      response = process(' ')
      expect(response.body).to be_nil
    end
  end
end


text:
'use strict';

const jsongate = require('json-gate');
const clc = require('cli-color');

function Table (outStream) {
	this._out = outStream;
	this._width = outStream.isTTY ? outStream.columns : 80;
	this._x = 0;
}

Table.prototype.line = function (color) {
	if (!color) color = 'white';
	this.write('-'.repeat(this._width), { color: color });
	this.nl();
};

Table.prototype.write = function (str, opts) {
	// Parse options
	if (opts === undefined) opts = {};
	jsongate.createSchema({ type: 'object',
		properties: {
			pos: { type: 'integer', minimum: -this._width, maximum: this._width, default: 0 },
			align: { type: 'string', enum: ['left', 'right'], default: 'left' },
			color: { type: 'string',
				enum: [
					'black',
					'red',
					'green',
					'yellow',
					'blue',
					'magenta',
					'cyan',
					'white',
					'blackBright',
					'redBright',
					'greenBright',
					'yellowBright',
					'blueBright',
					'magentaBright',
					'cyanBright',
					'whiteBright'
				] }
		} }).validate(opts);

	// Create string
	str = str.toString();
	str = (opts.color) ? clc[opts.color](str) : str;
	const len = clc.getStrippedLength(str);

	// Move cursor
	if (opts.align === 'right') opts.pos -= len;
	if (opts.pos < 0) opts.pos += this._width;
	const diff = opts.pos - this._x;
	this._x += diff;
	if (diff < 0) {
		this._out.write(clc.move.left(diff));
	} else {
		this._out.write(clc.move.right(diff));
	}

	// Print field
	this._out.write(str);
	this._x += len;
};

Table.prototype.nl = function () {
	this._out.write('\n');
	this._x = 0;
};

module.exports = Table;


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Dematiaceous Hyphomycetes (Kew) 388 (1971)

#### Original name
Dichotomophthora portulacae var. portulacae Mehrl. & Fitzp. ex M.B. Ellis

### Remarks
null


text:
.class public final Landroid/support/v4/view/MarginLayoutParamsCompat;
.super Ljava/lang/Object;
.source "MarginLayoutParamsCompat.java"

# direct methods
.method private constructor <init>()V
    .locals 0

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method public static getMarginEnd(Landroid/view/ViewGroup$MarginLayoutParams;)I
    .locals 2

    sget v0, Landroid/os/Build$VERSION;->SDK_INT:I

    const/16 v1, 0x11

    if-lt v0, v1, :cond_0

    invoke-virtual {p0}, Landroid/view/ViewGroup$MarginLayoutParams;->getMarginEnd()I

    move-result v0

    return v0

    :cond_0
    iget v0, p0, Landroid/view/ViewGroup$MarginLayoutParams;->rightMargin:I

    return v0
.end method

.method public static getMarginStart(Landroid/view/ViewGroup$MarginLayoutParams;)I
    .locals 2

    sget v0, Landroid/os/Build$VERSION;->SDK_INT:I

    const/16 v1, 0x11

    if-lt v0, v1, :cond_0

    invoke-virtual {p0}, Landroid/view/ViewGroup$MarginLayoutParams;->getMarginStart()I

    move-result v0

    return v0

    :cond_0
    iget v0, p0, Landroid/view/ViewGroup$MarginLayoutParams;->leftMargin:I

    return v0
.end method


text:
using System;
using AzureFromTheTrenches.Commanding.Tests.Acceptance.Helpers;
using Xbehave;
using Xunit;

namespace AzureFromTheTrenches.Commanding.Tests.Acceptance.ErrorPaths
{
    public class ThrownExceptionFromHandlerPropagatesOut : AbstractDispatchTestBase
    {
        public ThrownExceptionFromHandlerPropagatesOut() : base((registry, customDispatcher) =>
        {
            registry.Register<SimpleCommandWithIntegerResultHandler>();
        })
        {

        }

        [Scenario]
        public void ExecuteTest(SimpleCommandWithIntegerResult command, Exception thrownException)
        {
            "Given a command whose handler throws an exception"
                .x(() => command = new SimpleCommandWithIntegerResult(new Exception("something went wrong")));
            "When I dispatch the command"
                .x(async () =>
                {
                    try
                    {
                        await Dispatcher.DispatchAsync(command);
                    }
                    catch (Exception ex)
                    {
                        thrownException = ex;
                    }
                });
            "Then the exception is propagated back to the caller"
                .x(() =>
                {
                    Assert.NotNull(thrownException);
                    Assert.IsType<CommandExecutionException>(thrownException);
                    CommandExecutionException commandExecutionException = (CommandExecutionException) thrownException;
                    Assert.NotNull(commandExecutionException.InnerException);
                    Assert.Equal("something went wrong", commandExecutionException.InnerException.Message);
                });
        }
    }
}


text:
layout: post
title: Blog presentation
cover: cover.jpg
date:   2015-04-16 12:00:00
categories: en posts
---

## A blog for Skillreso, why ?

This blog will be used for 2 objectives : to be a mean of communication for our website [SkillReso](http://skillreso.com) and publish technical posts about differents subjects : [Ember.js](http://emberjs.com/) and how to use it with Rails, Foundation or Simple Auth, [Docker](https://www.docker.com/)...

# Find us on the website [SkillReso](http://skillreso.com)


text:
// Copyright 2016 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.devtools.build.workspace.maven;

import static com.google.common.truth.Truth.assertThat;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * Tests for {@link Rule}.
 */
@RunWith(JUnit4.class)
public class RuleTest {

  @Test
  public void testUrl() throws Exception {
    Rule rule = new Rule(Resolver.getArtifact("foo:bar:1.2.3"));
    assertThat(rule.getUrl())
        .isEqualTo("https://repo1.maven.org/maven2/foo/bar/1.2.3/bar-1.2.3.pom");
    rule.setRepository("http://myrepo.com/foo/bar/1.2.3/bar-1.2.3.pom");
    assertThat(rule.getUrl()).isEqualTo("http://myrepo.com/foo/bar/1.2.3/bar-1.2.3.pom");
  }
}


text:
package org.citydb.core.database.adapter.postgis;

import org.citydb.config.geometry.GeometryObject;
import org.citydb.core.database.adapter.*;
import org.citydb.core.query.filter.selection.operator.spatial.SpatialOperatorName;
import org.citydb.sqlbuilder.expression.DoubleLiteral;
import org.citydb.sqlbuilder.expression.PlaceHolder;
import org.citydb.sqlbuilder.expression.StringLiteral;
import org.citydb.sqlbuilder.schema.Column;
import org.citydb.sqlbuilder.select.PredicateToken;
import org.citydb.sqlbuilder.select.operator.comparison.BinaryComparisonOperator;
import org.citydb.sqlbuilder.select.operator.comparison.ComparisonFactory;
import org.citydb.sqlbuilder.select.operator.logical.LogicalOperationFactory;
import org.citydb.sqlbuilder.select.projection.Function;

import java.sql.Connection;
import java.sql.SQLException;

public class SQLAdapter extends AbstractSQLAdapter {

    protected SQLAdapter(AbstractDatabaseAdapter databaseAdapter) {
        super(databaseAdapter);
    }

    @Override
    public String getInteger() {
        return "INTEGER";
    }

    @Override
    public String getSmallInt() {
        return "SMALLINT";
    }

    @Override
    public String getBigInt() {
        return "BIGINT";
    }

    @Override
    public String getNumeric() {
        return "NUMERIC";
    }

    @Override
    public String getNumeric(int precision) {
        return "NUMERIC(" + precision + ")";
    }

    @Override
    public String getNumeric(int precision, int scale) {
        return "NUMERIC(" + precision + "," + scale + ")";
    }

    @Override
    public String getReal() {
        return "REAL";
    }

    @Override
    public String getDoublePrecision() {
        return "DOUBLE PRECISION";
    }

    @Override
    public String getCharacter(int nrOfChars) {
        return "CHAR(" + nrOfChars + ")";
    }

    @Override
    public String getCharacterVarying(int nrOfChars) {
        return "VARCHAR(" + nrOfChars + ")";
    }

    @Override
    public String getPolygon2D() {
        return "GEOMETRY(POLYGON)";
    }

    @Override
    public String getCreateUnloggedTable(String tableName, String columns) {
        return "create unlogged table " + tableName + " " + columns;
    }

    @Override
    public String getCreateUnloggedTableAsSelect(String tableName, String select) {
        return "create unlogged table " + tableName + " as " + select;
    }

    @Override
    public String getNextSequenceValue(String sequence) {
        return "nextval('" + databaseAdapter.getConnectionDetails().getSchema() + "." + sequence + "')";
    }

    @Override
    public String getCurrentSequenceValue(String sequence) {
        return "currval('" + databaseAdapter.getConnectionDetails().getSchema() + "." + sequence + "')";
    }

    @Override
	public String getNextSequenceValuesQuery(String sequence) {
        boolean requiresSchema = databaseAdapter.getConnectionMetaData().getCityDBVersion().compareTo(4, 0, 0) < 0;
        StringBuilder query = new StringBuilder("select ")
                .append(resolveDatabaseOperationName("citydb_util.get_seq_values")).append("(");

        if (requiresSchema) {
            query.append("'").append(sequence).append("'").append(",")
                    .append("?,")
                    .append("'").append(databaseAdapter.getConnectionDetails().getSchema()).append("'");
        } else {
            query.append("'").append(databaseAdapter.getConnectionDetails().getSchema()).append(".")
                    .append(sequence).append("'").append(",")
                    .append("?");
        }

		return query.append(")").toString();
	}

    @Override
    public String getUnloggedIndexProperty() {
        return "";
    }

    @Override
    public boolean requiresPseudoTableInSelect() {
        return false;
    }

    @Override
    public String getPseudoTableName() {
        return "";
    }

    @Override
    public int getMaximumNumberOfItemsForInOperator() {
        return 1000;
    }

    @Override
    public boolean spatialPredicateRequiresNoIndexHint() {
        return false;
    }

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

    @Override
    public String getHierarchicalGeometryQuery() {
        String schema = databaseAdapter.getConnectionDetails().getSchema();
        return "WITH RECURSIVE geometry_rec (id, gmlid, parent_id, root_id, is_solid, is_composite, is_triangulated, is_xlink, is_reverse, geometry, implicit_geometry, solid_geometry, cityobject_id, level) " +
                "AS (SELECT sg.id, sg.gmlid, sg.parent_id, sg.root_id, sg.is_solid, sg.is_composite, sg.is_triangulated, sg.is_xlink, sg.is_reverse, sg.geometry, sg.implicit_geometry, sg.solid_geometry, sg.cityobject_id, 1 AS level " +
                "FROM " + schema + ".surface_geometry sg WHERE sg.id=? UNION ALL " +
                "SELECT sg.id, sg.gmlid, sg.parent_id, sg.root_id, sg.is_solid, sg.is_composite, sg.is_triangulated, sg.is_xlink, sg.is_reverse, sg.geometry, sg.implicit_geometry, sg.solid_geometry, sg.cityobject_id, g.level + 1 AS level " +
                "FROM " + schema + ".surface_geometry sg, geometry_rec g WHERE sg.parent_id=g.id) " +
                "SELECT id, gmlid, parent_id, root_id, is_solid, is_composite, is_triangulated, is_xlink, is_reverse, geometry, implicit_geometry, ST_AsEWKT(solid_geometry) as solid_geometry, cityobject_id, level FROM geometry_rec";
    }

    @Override
    public BlobImportAdapter getBlobImportAdapter(Connection connection, BlobType type) throws SQLException {
        return new BlobImportAdapter(connection, type, databaseAdapter.getConnectionDetails().getSchema());
    }

    @Override
    public BlobExportAdapter getBlobExportAdapter(Connection connection, BlobType type) {
        return new BlobExportAdapter(connection, type, databaseAdapter.getConnectionDetails().getSchema());
    }

    @Override
    public PredicateToken getBinarySpatialPredicate(SpatialOperatorName operator, Column targetColumn, GeometryObject geometry, boolean negate) {
        PlaceHolder<GeometryObject> placeHolder = new PlaceHolder<>(geometry);
        StringLiteral trueLiteral = new StringLiteral("TRUE");

        switch (operator) {
            case BBOX:
                return !negate ? new BinaryComparisonOperator(targetColumn, "&&", placeHolder) :
                        LogicalOperationFactory.NOT(new BinaryComparisonOperator(targetColumn, "&&", placeHolder));
            case INTERSECTS:
                return ComparisonFactory.equalTo(new Function("ST_Intersects", targetColumn, placeHolder), trueLiteral, negate);
            case EQUALS:
                return ComparisonFactory.equalTo(new Function("ST_Equals", targetColumn, placeHolder), trueLiteral, negate);
            case DISJOINT:
                return ComparisonFactory.equalTo(new Function("ST_Disjoint", targetColumn, placeHolder), trueLiteral, negate);
            case TOUCHES:
                return ComparisonFactory.equalTo(new Function("ST_Touches", targetColumn, placeHolder), trueLiteral, negate);
            case WITHIN:
                return ComparisonFactory.equalTo(new Function("ST_Within", targetColumn, placeHolder), trueLiteral, negate);
            case OVERLAPS:
                return ComparisonFactory.equalTo(new Function("ST_Overlaps", targetColumn, placeHolder), trueLiteral, negate);
            case CONTAINS:
                return ComparisonFactory.equalTo(new Function("ST_Contains", targetColumn, placeHolder), trueLiteral, negate);
            default:
                break;
        }

        return null;
    }

    @Override
    public PredicateToken getDistancePredicate(SpatialOperatorName operator, Column targetColumn, GeometryObject geometry, double distance, boolean negate) {
        PlaceHolder<GeometryObject> placeHolder = new PlaceHolder<>(geometry);
        StringLiteral trueLiteral = new StringLiteral("TRUE");
        DoubleLiteral distanceLiteral = new DoubleLiteral(distance);

        switch (operator) {
            case DWITHIN:
                return ComparisonFactory.equalTo(new Function("ST_DWithin", targetColumn, placeHolder, distanceLiteral), trueLiteral, negate);
            case BEYOND:
                return ComparisonFactory.equalTo(new Function("ST_DWithin", targetColumn, placeHolder, distanceLiteral), trueLiteral, !negate);
            default:
                break;
        }

        return null;
    }

    @Override
    public Function getAggregateExtentFunction(Column envelope) {
        return new Function("st_extent", envelope);
    }

}


text:
package net.java.bd.tools.logger;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;

public class Logger {

    private static final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss ");
    private static final String lineSep = System.getProperty("line.separator");
    private static File[] logFiles = null;

    /**
    private static String WORK_DIR = System.getProperty("bluray.bindingunit.root");
    private static File[] logFiles = {
        new File(WORK_DIR, "logA.txt"),
        new File(WORK_DIR, "logB.txt")
    };
     **/

    public static final int MAX_FILE_LENGTH = 5120; // in bytes

    /**
     * Sets the logging output file.
     */
    public static void setLogFile(String file) {

        File log = new File(file);
        /**
        if (!log.canWrite()) {
            log("ERROR: Log file " + file + " is not writable.");
            return;
        }
        **/

        String path = log.getPath();
        String backupFileName = log.getName().concat(".bak");
        logFiles = new File[] {
                log, new File(path, backupFileName)
        };

        Logger.log("Setting the log file to " + file);
    }

    /**
     * Returns log files in proper order: the recent one comes first
     * @return
     */
    public static File[] getLogFiles() {
        if (logFiles == null) {
            return null;
        }

        if (logFiles[0].lastModified() < logFiles[1].lastModified()) {
            File t = logFiles[0];
            logFiles[0] = logFiles[1];
            logFiles[1] = t;
        }

        return logFiles;
    }

    /**
     *
     * @param ff
     */
    private static synchronized void activateNextFile(File[] ff) {
        ff[1].delete();
        try {
            ff[1].createNewFile();
        } catch (IOException e) {
            System.out.println("Logger: Failed to create a file " + ff[1].getAbsolutePath());
            e.printStackTrace();
        }
        File t = ff[0];
        ff[0] = ff[1];
        ff[1] = t;
    }

    /**
     * Puts a string s into the log
     * @param s
     */
    public static synchronized void log(String s) {
        if (s == null || s.length() == 0) {
            return;
        }

        if (observers != null) {
            for (int i = 0; i < observers.size(); i++) {
               ((Observer)observers.elementAt(i)).output(s);
            }
        }

        File[] ff = getLogFiles();
        if (ff != null) {
            int freeSpace = MAX_FILE_LENGTH - (int) ff[0].length();

            String logRecord = sdf.format(new Date()) + s + lineSep;

            if (logRecord.length() <= freeSpace) {
                output(logRecord, ff[0]);
            } else {
                output(logRecord.substring(0, freeSpace), ff[0]);
                activateNextFile(ff);
                String tail = logRecord.substring(freeSpace);

                while (tail.length() > MAX_FILE_LENGTH) {
                    output(tail.substring(0, MAX_FILE_LENGTH), ff[0]);
                    activateNextFile(ff);
                    tail = tail.substring(MAX_FILE_LENGTH);
                }

                output(tail, ff[0]);
            }
        }
    }

    /**
     *
     * @param s
     * @param f
     */
    private static synchronized void output(String s, File f) {
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new FileWriter(f.getAbsolutePath(), true));
            bw.write(s);
        } catch (IOException e) {
            System.out.println("Logger: Failed to instantiate a FileWriter for " + f.getAbsolutePath());
            e.printStackTrace();
        } finally {
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    System.out.println("Logger: Failed to close the BufferedWriter for " + f.getAbsolutePath());
                }
            }
        }
    }

    /**
     * Puts a string s and a stack trace of t into the log
     * @param s
     * @param t
     */
    public static void log(String s, Throwable t) {
        StringWriter sw = null;
        PrintWriter pw = null;

        try {
            sw = new StringWriter();
            sw.write(s);
            sw.write(lineSep);

            if (t != null) {
                pw = new PrintWriter(sw);
                t.printStackTrace(pw);
                pw.flush();
            }

            sw.flush();
            log(sw.toString());
        } catch (Exception ex) {
            System.out.println("Exception while printing a stack trace to the log: " + ex.toString());
        } finally {
            try {
                if (pw != null) {
                    pw.close();
                }
            } catch (Exception e) {
                System.out.println("Exception while closing a PrintWriter: " + e.toString());
            }

            try {
                if (sw != null) {
                    sw.close();
                }
            } catch (Exception e) {
                System.out.println("Exception while closing a StringWriter: " + e.toString());
            }
        }
    }

    /**
     *
     */
    public static void clearLog() {
        File[] ff = getLogFiles();
        if (ff != null) {
            ff[0].delete();
            ff[1].delete();
        }

        if (observers != null) {
            for (int i = 0; i < observers.size(); i++) {
               ((Observer)observers.elementAt(i)).clearLog();
            }
        }
    }

    public static interface Observer {

        public void output(String s);

        public void clearLog();
    }

    private static Vector observers;
    public static void addObserver(Observer obs) {
        synchronized(Logger.class) {
           if (observers == null) {
              observers = new Vector();
           }
           observers.add(obs);
        }
    }

    public static void removeObserver(Observer obs) {
        synchronized(Logger.class) {
            if (observers != null) {
                observers.remove(obs);
            }
        }
    }
}


text:
package uk.ac.ngs.domain;

/**
 * Transfer bean for use in view layer.
 * This bean adds extra properties such as the checked that are not required
 * by the domain model, but are required by the view layer.
 *
 * @author Sam Worley
 * @author David Meredith
 */
public class RequestWrapper {
        private boolean checked;
        private RequestRow requestRow;

        /**
         * Create a new instance
         * @param checked
         * @param requestRow
         */
        public RequestWrapper(boolean checked, RequestRow requestRow) {
            this.checked = checked;
            this.requestRow = requestRow;
        }

        /**
         * Default constructor - required so Spring can auto-create/bind instances in view
         */
        public RequestWrapper(){
        }

        /**
         * @return the checked
         */
        public boolean isChecked() {
            return checked;
        }

        /**
         * @return the checked
         */
        public boolean getChecked() {
            return checked;
        }

        /**
         * Set the checked value
         * @param checked
         */
        public void setChecked(boolean checked) {
            this.checked = checked;
        }

        /**
         * @return the requestRow
         */
        public RequestRow getRequestRow() {
            return requestRow;
        }

        /**
         * Set the RequestRow
         * @param requestRow
         */
        public void setRequestRow(RequestRow requestRow) {
           this.requestRow = requestRow;
        }
}


text:
<?php

namespace Application\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

class Version20131223213301 extends AbstractMigration
{
    public function up(Schema $schema)
    {
        $this->addSql("ALTER TABLE users ADD timezone VARCHAR(30) DEFAULT 'America/Chicago' NOT NULL");
    }

    public function down(Schema $schema)
    {
        $this->addSql('ALTER TABLE users DROP timezone');
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>{% block title %}DB Stats{% endblock %}</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="{{ STATIC_URL }}css/bootstrap.min.css" rel="stylesheet">
    <link href="{{ STATIC_URL }}css/bootstrap-responsive.min.css" rel="stylesheet">
    <link rel="shortcut icon" href="{{ STATIC_URL }}img/favicon.ico">

{% block body %}

                DBStats

                        Home

                        Activity

                        Explain

                        Settings

                        Server: {{ server.name }}

                            {% for other in others %}

{{ other.name }}

                            {% endfor %}

Another action

                        {% firstof user.get_full_name user %}

Logout

        {#  The Django messages framework - bootstrap only handles info, error, success #}
        {% for message in messages %}

{{ message }}

        {% endfor %}

        {% block body_container %}{% endblock %}

    {% block extra_js %}{% endblock %}
{% endblock %}


text:
class CreateAssets < ActiveRecord::Migration
  def self.up
    create_table :assets do |t|
      t.string  :data_file_name, null: false
      t.string  :data_content_type
      t.integer :data_file_size

      t.integer :assetable_id, null: false
      t.string  :assetable_type, limit: 30, null: false
      t.string  :type, limit: 30

      t.string  :guid, limit: 20
      t.string  :public_token, limit: 20

      t.integer :user_id
      t.integer :sort_order, default: 0
      t.integer :width
      t.integer :height

      t.timestamps
    end

    add_index :assets, [:assetable_type, :type, :assetable_id]
    add_index :assets, :user_id
    add_index :assets, :guid
    add_index :assets, :public_token
  end

  def self.down
    drop_table :assets
  end
end


text:
class StudentRiskLevel < ActiveRecord::Base
  belongs_to :student
  delegate :student_assessments, :limited_english_proficiency, to: :student
  after_create :update_risk_level!

  # Use most recent assessments to calculate risk
  def mcas_math
    student.latest_result_by_family_and_subject("MCAS", "Mathematics") || MissingStudentAssessment.new
  end

  def star_math
    student.latest_result_by_family_and_subject("STAR", "Mathematics") || MissingStudentAssessment.new
  end

  def mcas_ela
    student.latest_result_by_family_and_subject("MCAS", "ELA") || MissingStudentAssessment.new
  end

  def star_reading
    student.latest_result_by_family_and_subject("STAR", "Reading") || MissingStudentAssessment.new
  end

  def mcas_or_star_at_level(this_level)
    student_assessment_factors.any? { |risk_level| risk_level == this_level }
  end

  def mcas_and_star_risk_nil?
    student_assessment_factors.all? { |risk_level| risk_level.nil? }
  end

  def student_assessment_factors
    [ mcas_math_risk_level, star_math_risk_level, mcas_ela_risk_level, star_reading_risk_level ]
  end

  def risk_level_factors
    student_assessment_factors << limited_english_proficiency_risk_level
  end

  def limited_english_proficiency_risk_level
    return 3 if limited_english_proficiency == "Limited"
  end

  def update_risk_level!
    update!(
      mcas_math_risk_level: mcas_math.risk_level,
      star_math_risk_level: star_math.risk_level,
      mcas_ela_risk_level: mcas_ela.risk_level,
      star_reading_risk_level: star_reading.risk_level,
      limited_english_proficiency_risk_level: limited_english_proficiency_risk_level
    )

    update!(level: calculate_level)
  end

  def calculate_level
    # As defined by Somerville Public Schools

    if student.school.school_type == "HS"
      #High School risk levels have not been defined
      level = nil
    elsif mcas_or_star_at_level(3) || limited_english_proficiency_risk_level == 3
      level = 3
    elsif mcas_or_star_at_level(2)
      level = 2
    elsif mcas_or_star_at_level(0)
      level = 0
    elsif mcas_and_star_risk_nil?
      level = nil
    else
      level = 1
    end
  end

  def level_as_string
    level.nil? ? "N/A" : level.to_s
  end

  def css_class_name
    "risk-" + level_as_string.downcase.gsub("/", "")
  end

  # Data for Risk Level explanation:

  def risk_factors_to_levels
    {
      mcas_math_risk_level: mcas_math_risk_level,
      star_math_risk_level: star_math_risk_level,
      mcas_ela_risk_level: mcas_ela_risk_level,
      star_reading_risk_level: star_reading_risk_level,
      limited_english_proficiency_risk_level: limited_english_proficiency_risk_level
    }
  end

  def relevant_risk_factors
    risk_factors_to_levels.delete_if do |key, value|
      value != level
    end
  end

  def explanation
    { intro: explanation_intro_html, reasons: explanations_array }
  end

  def explanation_intro_html
    "#{name} is at Risk #{level_as_string} because:"
  end

  def name
    student.first_name || "This student"
  end

  def explanations_array
    return ["There is not enough information to tell."] if level == nil

    relevant_risk_factors.to_a.map do |key_value_pair|
      factor_name = key_value_pair[0]
      factor_value = key_value_pair[1]
      explanation = risk_factor_names_to_explanations[factor_name][factor_value]

      "#{name}#{explanation}."
    end
  end

  def risk_factor_names_to_explanations
    {
      limited_english_proficiency_risk_level: {
        3 => " is limited English proficient"
      },
      mcas_math_risk_level: {
        3 => "'s MCAS Math performance level is Warning",
        2 => "'s MCAS Math performance level is Needs Improvement",
        1 => "'s MCAS Math performance level is Proficient",
        0 => "'s MCAS Math performance level is Advanced"
      },
      mcas_ela_risk_level: {
        3 => "'s MCAS English Language Arts performance level is Warning",
        2 => "'s MCAS English Language Arts performance level is Needs Improvement",
        1 => "'s MCAS English Language Arts performance level is Proficient",
        0 => "'s MCAS English Language Arts performance level is Advanced"
      },
      star_reading_risk_level: {
        3 => "'s STAR Reading performance is in the warning range (below 10)",
        2 => "'s STAR Reading performance is in the 10-30 range",
        1 => "'s STAR Reading performance is above 30",
        0 => "'s STAR Reading performance is above 85"
      }, star_math_risk_level: {
        3 => "'s STAR Math performance is in the warning range (below 10)",
        2 => "'s STAR Math performance is in the 10-30 range",
        1 => "'s STAR Math performance is above 30",
        0 => "'s STAR Math performance is above 85"
      }
    }
  end

  def as_json_with_explanation
    as_json.merge(explanation: explanation)
  end
end


text:
import {Db, Server} from "mongodb";
import * as request from "request";

const BASE_URL = "http://localhost:3000/api/users";

export default class Util {
    static deleteAllUsers():Promise<void> {
        var myDb = new Db("meantest", new Server("localhost", 27017));
        return myDb.open()
        .then(db => db.collection("users"))
        .then(collection => collection.remove({}))
        .then(docs =>myDb.close());
    }

    static createUser(name:string):Promise<string> {
        return new Promise(resolve => {
            request.post(BASE_URL, {
                form: {
                    name: name,
                    password: name,
                    email: `${name}@test.com`
                }
            },
            (err, res, body) => {
                let token = JSON.parse(res.body).token;
                resolve(token);
            });
        });
    }
}


text:
import pyglet
from pyglet.window.key import ENTER

from .levels import Level
from .game_piece import Problem
from .drawing import rectangle

class TheGame(Level):
  def __init__(self, window):
    self.user_answer = pyglet.text.Label('', x=10, y=window.height-30, font_size=20)
    self.score_text = pyglet.text.Label('0', x=window.width-100, y=window.height-30, font_size=20)
    self.difficulty_text = pyglet.text.Label('', x=window.width-200, y=window.height-300, font_size=20)
    self.score = 0
    self.difficulty_show = 0
    super(TheGame, self).__init__(window)
    self.game_piece = Problem(window)

  def key(self, symbol, mod):
    self.game_piece.speed = self.score / 10 + 1
    if 65457 <= symbol <= 65465:
        symbol -= 65408  # drop num pad to ascii 0-9 range
    num = set(range(ord("0"), ord("9") + 1))
    # If answer box, check to see if they were right
    if symbol == ENTER:
      score = self.game_piece.check(self.user_answer.text) # Get back time elapsed or None
      if score:
        # score is elapsed time on the answer. Give bonus on <2 seconds answers
        score = 2 - score
        if score < 0:
          score = 0
        self.score += self.game_piece.value + score
        self.score_text.text = "%.02f" % self.score
      self.user_answer.text = ''
    elif symbol in num:
      self.user_answer.text += chr(symbol)

  @property
  def difficulty(self):
    high_score = getattr(self, 'high_score', 0)
    return (high_score if high_score > self.score else self.score) / 10 + 1

  def draw(self):
    self.window.clear()
    if self.difficulty_show:
      self.difficulty_text.draw()
      self.difficulty_show -= 1
    self.game_piece.draw()
    rectangle(0, self.window.height-40, 40, self.window.width)
    self.user_answer.draw()
    self.score_text.draw()

  def clock(self, dt):
    self.game_piece.update(dt)
    if self.game_piece.fail():
      self.container.next()
      # Pass score to next "level"
      self.container.current.msg(score=self.score)

  def reset(self):
    print self.messages
    self.high_score = self.messages.get('high_score', 0)
    self.game_piece.reset(self.difficulty)
    self.score_text.text = ""
    self.difficulty_text.text = 'Difficulty: %s' % self.difficulty
    self.score = 0
    self.difficulty_show = 40


text:
package de.hpi.bpmn2xpdl;

import java.io.StringReader;
import java.io.StringWriter;

import org.json.JSONException;
import org.json.JSONObject;
import org.xmappr.Xmappr;

import junit.framework.TestCase;

public class XPDLScriptTest extends TestCase {

	private String json = "{" +
		"\"expressionlanguage\":\"Javascript\"" +
		"}";
	private String xpdl = "<Script Type=\"Javascript\" />";

	public void testParse() throws JSONException {
		XPDLScript script = new XPDLScript();
		script.parse(new JSONObject(json));

		StringWriter writer = new StringWriter();

		Xmappr xmappr = new Xmappr(XPDLScript.class);
		xmappr.setPrettyPrint(false);
		xmappr.toXML(script, writer);

		assertEquals(xpdl, writer.toString());
	}

	public void testWrite() {
		StringReader reader = new StringReader(xpdl);

		Xmappr xmappr = new Xmappr(XPDLScript.class);
		XPDLScript script = (XPDLScript) xmappr.fromXML(reader);

		JSONObject importObject = new JSONObject();
		script.write(importObject);

		assertEquals(json, importObject.toString());
	}
}


text: export * from './internalTransferInformation.component';


text:
@interface DetailViewController : LFNavViewController
@property (weak, nonatomic) IBOutlet UIImageView *appImageView;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *priceLabel;
@property (weak, nonatomic) IBOutlet UILabel *statusLabel;
@property (weak, nonatomic) IBOutlet UILabel *sizeLabel;
@property (weak, nonatomic) IBOutlet UILabel *typeLabel;
@property (weak, nonatomic) IBOutlet UIButton *favoriteBtn;
@property (weak, nonatomic) IBOutlet UILabel *rateLabel;
- (IBAction)shareAction:(id)sender;
- (IBAction)favoriteAction:(id)sender;
- (IBAction)downloadAction:(id)sender;
@property (weak, nonatomic) IBOutlet UIScrollView *imageScrollView;
@property (weak, nonatomic) IBOutlet UILabel *descLabel;
@property (weak, nonatomic) IBOutlet UIScrollView *nearbyScrollView;

@property (nonatomic,strong) NSString *applicationId;
@end


text:
package org.jetbrains.plugins.javaFX.fxml.codeInsight.inspections;

import com.intellij.codeInsight.AnnotationUtil;
import com.intellij.codeInsight.daemon.ImplicitUsageProvider;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.PsiSearchHelper;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.util.Query;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.javaFX.fxml.JavaFxCommonNames;
import org.jetbrains.plugins.javaFX.fxml.refs.JavaFxScopeEnlarger;
import org.jetbrains.plugins.javaFX.indexing.JavaFxControllerClassIndex;
import org.jetbrains.plugins.javaFX.indexing.JavaFxIdsIndex;

import java.util.Collection;
import java.util.List;

/**
 * User: anna
 * Date: 3/22/13
 * Checks that a non-public field is referenced in fx:id attribute or a non-public method is referenced as an event handler in FXML
 */
public class JavaFxImplicitUsageProvider implements ImplicitUsageProvider {

  @Override
  public boolean isImplicitUsage(PsiElement element) {
    if (element instanceof PsiMethod) {
      return isImplicitMethodUsage((PsiMethod)element);
    }
    return isImplicitWrite(element);
  }

  private static boolean isImplicitMethodUsage(@NotNull PsiMethod method) {
    if (!isImplicitFxmlAccess(method)) return false;
    if (isInvokedByFxmlLoader(method)) {
      return true;
    }
    final GlobalSearchScope projectScope = GlobalSearchScope.projectScope(method.getProject());
    final GlobalSearchScope fxmlScope = new JavaFxScopeEnlarger.GlobalFxmlSearchScope(projectScope);
    return isFxmlUsage(method, fxmlScope);
  }

  private static boolean isFxmlUsage(PsiMember member, GlobalSearchScope scope) {
    final String name = member.getName();
    if (name == null) return false;
    final Project project = member.getProject();
    final PsiSearchHelper searchHelper = PsiSearchHelper.SERVICE.getInstance(project);
    final PsiSearchHelper.SearchCostResult searchCost = RefResolveService.getInstance(project).isUpToDate()
                                                        ? PsiSearchHelper.SearchCostResult.FEW_OCCURRENCES
                                                        : searchHelper.isCheapEnoughToSearch(name, scope, null, null);
    if (searchCost == PsiSearchHelper.SearchCostResult.FEW_OCCURRENCES) {
      final Query<PsiReference> query = ReferencesSearch.search(member, scope);
      return query.findFirst() != null;
    }
    return false;
  }

  @Override
  public boolean isImplicitRead(PsiElement element) {
    return false;
  }

  @Override
  public boolean isImplicitWrite(PsiElement element) {
    if (element instanceof PsiField) {
      final PsiField field = (PsiField)element;
      if (!isImplicitFxmlAccess(field)) return false;
      final String fieldName = field.getName();
      if (fieldName == null) return false;

      final PsiClass containingClass = field.getContainingClass();
      if (containingClass == null) return false;
      final String qualifiedName = containingClass.getQualifiedName();
      if (qualifiedName == null) return false;
      final Project project = element.getProject();
      if (isInjectedByFxmlLoader(field)) {
        return true;
      }
      final Collection<VirtualFile> containingFiles = JavaFxIdsIndex.getContainingFiles(project, fieldName);
      if (containingFiles.isEmpty()) return false;
      // is the field declared in a controller class?
      final List<VirtualFile> fxmls = JavaFxControllerClassIndex.findFxmlsWithController(project, qualifiedName);
      for (VirtualFile fxml : fxmls) {
        if (containingFiles.contains(fxml)) return true;
      }
      // is the field declared in a superclass of a controller class?
      return isFxmlUsage(field, GlobalSearchScope.filesScope(project, containingFiles));
    }
    return false;
  }

  private static boolean isInvokedByFxmlLoader(@NotNull PsiMethod method) {
    return "initialize".equals(method.getName()) &&
           method.getParameterList().getParametersCount() == 0 &&
           isDeclaredInControllerClass(method);
  }

  private static boolean isInjectedByFxmlLoader(@NotNull PsiField field) {
    final String fieldName = field.getName();
    final PsiType fieldType = field.getType();
    return fieldName != null &&
           ("resources".equals(fieldName) && InheritanceUtil.isInheritor(fieldType, "java.util.ResourceBundle") ||
            "location".equals(fieldName) && InheritanceUtil.isInheritor(fieldType, "java.net.URL")) &&
           isDeclaredInControllerClass(field);
  }

  private static boolean isDeclaredInControllerClass(@NotNull PsiMember member) {
    final PsiClass containingClass = member.getContainingClass();
    final String qualifiedName = containingClass != null ? containingClass.getQualifiedName() : null;
    return qualifiedName != null && !JavaFxControllerClassIndex.findFxmlsWithController(member.getProject(), qualifiedName).isEmpty();
  }

  private static boolean isImplicitFxmlAccess(PsiModifierListOwner member) {
    return !member.hasModifierProperty(PsiModifier.PUBLIC) &&
           AnnotationUtil.isAnnotated(member, JavaFxCommonNames.JAVAFX_FXML_ANNOTATION, 0);
  }
}


text:
// © Oleksandr Kozlenko. Licensed under the MIT license.

#pragma warning disable CA1812

namespace Anemonis.RandomOrg.DataRpc;

internal sealed class RpcRandomResult<T> : RpcRandomResultObject<RpcRandom<T>, T>
{
}


text:
/**
 * Created by linfeiyang on 3/2/16.
 */
'use strict';
var request = require('request');
var async = require('async');
var config = require('../../config');

module.exports = (Client) => {

    /**
     * get login qrcode
     * @param callback
     */
    Client.qrcode = (callback) => {
        async.waterfall([
            (next) => {
                request(config.uuidUrl
                    , (error, response, body) => {
                        if (error) return next(error);
                        if (response.statusCode != 200) return next(new Error('获取uuid失败,返回状态码:' + response.statusCode));
                        if (!body) return next(new Error('获取uuid失败,body为空'));
                        var window = {QRLogin: {}};
                        eval(body);
                        if (window.QRLogin.code != 200) {
                            return next(new Error('获取uuid erroerror msg:' + window.QRLogin.error));
                        }
                        next(null, window.QRLogin.uuid);
                    })
            },
            (uuid, next) => {
                if (!uuid) return next(new Error('uuid is null'));
                Client.uuid = uuid;
                Client.qrcodeImage = config.qrcodeUrl + uuid + '?t=webwx';
                Client.qrcodeImageUrl = config.qrUrl + uuid;
                request(Client.qrcodeImage, () => {
                    next();
                });
            }
        ], (err) => {
            callback(err);
        });
    };

};