text:
<?php

namespace Amp\Parallel\Test\Sync;

use Amp\Parallel\Sync\ChannelException;
use Amp\Parallel\Sync\ChannelParser;
use Amp\Parallel\Sync\SerializationException;
use Amp\PHPUnit\AsyncTestCase;

class ChannelParserTest extends AsyncTestCase
{
    public function testCorruptedData()
    {
        $this->expectException(SerializationException::class);
        $this->expectExceptionMessage('Exception thrown when unserializing data');

        $data = "Invalid serialized data";
        $data = \pack("CL", 0, \strlen($data)) . $data;
        $parser = new ChannelParser($this->createCallback(0));
        $parser->push($data);
    }

    public function testInvalidHeaderData()
    {
        $this->expectException(ChannelException::class);
        $this->expectExceptionMessage('Invalid packet received: Invalid packet');

        $data = "Invalid packet";
        $parser = new ChannelParser($this->createCallback(0));
        $parser->push($data);
    }

    public function testInvalidHeaderBinaryData()
    {
        $this->expectException(ChannelException::class);
        $this->expectExceptionMessage('Invalid packet received: B \xf3\xf2\x0\x1');

        $data = "\x42\x20\xf3\xf2\x00\x01";
        $parser = new ChannelParser($this->createCallback(0));
        $parser->push($data);
    }
}


text:
namespace ui {
class Event;
}

namespace aura {
class RootWindow;
class Window;

namespace client {
class FocusChangeObserver;

// An interface implemented by an object that manages window focus.
class AURA_EXPORT FocusClient {
 public:
  virtual ~FocusClient() {}

  // TODO(beng): these methods will be OBSOLETE by FocusChangeEvent.
  virtual void AddObserver(FocusChangeObserver* observer) = 0;
  virtual void RemoveObserver(FocusChangeObserver* observer) = 0;

  // Focuses |window|. Passing NULL clears focus.
  virtual void FocusWindow(Window* window) = 0;

  // Sets focus to |window| if it's within the active window. Not intended as a
  // general purpose API, use FocusWindow() instead.
  virtual void ResetFocusWithinActiveWindow(Window* window) = 0;

  // Retrieves the focused window, or NULL if there is none.
  virtual Window* GetFocusedWindow() = 0;

  // TODO(beng): temporary compat until FocusController is on.
  // Called when |window|'s disposition in |root_window| changes such that
  // focus must be shifted away from it. |destroyed| is true if the disposition
  // change is that |window| is being destroyed.
  virtual void OnWindowHiddenInRootWindow(aura::Window* window,
                                          aura::RootWindow* root_window,
                                          bool destroyed) = 0;
};

// Sets/Gets the focus client on the RootWindow.
AURA_EXPORT void SetFocusClient(RootWindow* root_window, FocusClient* client);
AURA_EXPORT FocusClient* GetFocusClient(Window* window);
AURA_EXPORT FocusClient* GetFocusClient(const Window* window);

}  // namespace clients
}  // namespace aura

#endif  // UI_AURA_CLIENT_FOCUS_CLIENT_H_

redpajama_set_name: RedPajamaGithub


text:
import database from '../../../database'

export default todo => {
  database.splice (database.indexOf (database.filter (val => val.id === todo.id)[0]), 1, todo)
  return database
}


text:
<?php

namespace OG\Account\Domain\Identity\Services;

use OG\Account\Domain\Identity\Model\Email;

/**
 * Thrown when an activation could not be found.
 */
class ActivationIsNotFound extends ActivationOfAccountFailed
{
    public static function withAlias(Email $alias)
    {
        $message = sprintf('Activation for the alias `%s` could not be found', $alias->toString());

        return new self($message);
    }
}


text:
#
# mergeSegToCtm.py
#
# Enhance the CTM file by adding extra fields with the diarisation
# information
#
# First argument is the seg file
# Second argument is the ctm file
#
import sys
import codecs

segFile = sys.argv[1]
ctmFile = sys.argv[2]
outFile = sys.argv[3]

with open(segFile, 'r', encoding='iso-8859-1') as seg:
    with open(ctmFile, 'r', encoding='iso-8859-1') as ctm:
        with codecs.open(outFile, 'w', 'iso-8859-1') as output:

            # For each frame, we will create an entry in a dictionnary
            # It will help the lookup later on
            # We don't really care about memory issues here, should we?
            frames = {}

            for line in seg:
                values = line.split()
                start = int(values[2])
                duration = int(values[3])

                for i in range(start, start + duration):
                    frames[i] = values[4], values[5], values[7]

            for line in ctm:
                values = line.split()
                # Use the same start format than in the .seg file
                start = int(float(values[2])*100)
                print(line.strip(), end="", file=output)
                if start in frames:
                    print(" " + frames[start][0] + " " + frames[start][1] + " " + frames[start][2], file=output)
                else:
                    print(" N/A N/A N/A", file=output)


text:
<?php

namespace DCarbone\PHPFHIRGenerated\R4\PHPFHIRTests\FHIRElement;

use PHPUnit\Framework\TestCase;
use DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRIdentityAssuranceLevel;

/**
 * Class FHIRIdentityAssuranceLevelTest
 * @package \DCarbone\PHPFHIRGenerated\R4\PHPFHIRTests\FHIRElement
 */
class FHIRIdentityAssuranceLevelTest extends TestCase
{
    public function testCanConstructTypeNoArgs()
    {
        $type = new FHIRIdentityAssuranceLevel();
        $this->assertInstanceOf('\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRIdentityAssuranceLevel', $type);
    }
}


text:
/*
 * TriangleMesh.cpp
 *
 *  Created on: Dec 1, 2008
 *      Author: yamokosk
 */

#include "TriangleMesh.h"
#include <plugin_framework/Plugin.h>
#include <mesh/MeshImport.h>
#include <boost/foreach.hpp>
#include <api/Services.h>

const std::string TriangleMesh::Type("ODETriangleMesh");

void* TriangleMesh::create(PF_ObjectParams* params)
{
	TriangleMesh* ptr = new TriangleMesh();
	ptr->services = params->platformServices;
	return ptr;
}

int TriangleMesh::destroy(void *p)
{
	if (!p) return -1;

	delete static_cast<TriangleMesh*>(p);

	return 0;
}

TriangleMesh::TriangleMesh() :
	Geometry(),
	mesh_(NULL)
{

}

TriangleMesh::~TriangleMesh()
{

}

void TriangleMesh::getInfo( ObjectInfo& info ) const
{
	info.type = Type;
	info.addProperty( getProperty("filename") );

	// Have parent class deal with generic ODE properties
	Geometry::getInfo(info);

#ifdef BUG_trimesh_filename
	std::cout << info.name << ": filename - " << filename_ << std::endl;
#endif
}

void TriangleMesh::notifyMoved( const float* translation, const float* rotation )
{
#ifdef BUG_dGeomSetPosition
	std::cout << "In TriangleMesh::notifyMoved()" << std::endl;
#endif
	if ( mesh_ != NULL )
	{
		dGeomSetPosition(odeobj, (dReal)translation[0], (dReal)translation[1], (dReal)translation[2]);

		dQuaternion q = {0};
		for(unsigned int n=0; n < 4; ++n) q[n] = (dReal)rotation[n];
		dGeomSetQuaternion(odeobj, q);
	}
}

void TriangleMesh::initImpl(const ObjectInfo& info)
{
#ifdef BUG_dGeomSetPosition
	std::cout << "In TriangleMesh::initImpl()" << std::endl;
#endif
	// Set object name
	name = info.name;

	BOOST_FOREACH(Property prop, info.parameters)
	{
		if (prop.name_str() == "filename")
		{
			filename_ = boost::any_cast<std::string>(prop.value());
			break;
		}
	}

	// Load mesh from file
	std::string errmsg;
#ifdef BUG_dGeomSetPosition
	std::cout << "Loading mesh from: " << filename_ << std::endl;
#endif
	mesh_ = createTriMesh(filename_, 1.0, 1.0, 1.0, errmsg);
	if ( mesh_ == NULL )
	{
#ifdef BUG_dGeomSetPosition
		std::cout << "mesh_ was NULL: " << errmsg << std::endl;
#endif
		LOG_ERROR(services, errmsg);
		return;
	}

	// Create ODE trimesh object
	dTriMeshDataID Data = dGeomTriMeshDataCreate();
	dGeomTriMeshDataBuildSingle(Data,
								(void*)mesh_->vertexData(), mesh_->vertexStride(), mesh_->numVertices(),
								(void*)mesh_->faceData(), mesh_->numFaces(), mesh_->faceStride());
	odeobj = dCreateTriMesh (NULL, Data, NULL, NULL, NULL);

	// Save a pointer back to this adapter class inside the ODE object
	dGeomSetData(odeobj, this);

	// If there are any applicable parameters, set them now
	BOOST_FOREACH(Property p, info.parameters)
	{
		setProperty(p);
	}
}

Property TriangleMesh::getPropertyImpl(const std::string& name) const
{
#ifdef BUG_trimesh_filename
	std::cout << "In TriangleMesh::getPropertyImpl(): name = " << name << std::endl;
#endif
	// To get here, it must be a geom specific property
	if ( name == "filename" )
	{
		Property p(name, std::string(filename_));
#ifdef BUG_trimesh_filename
		std::cout << "** " << p.name_str() << ": " << boost::any_cast<std::string>(p.value()) << std::endl;
#endif
		return p;
	}

	// Have parent class deal with generic ODE properties
	return Geometry::getPropertyImpl(name);
}

void TriangleMesh::setPropertyImpl(const Property& p)
{
	// Have parent class deal with generic ODE properties
	Geometry::setPropertyImpl(p);
}


text:
package me.coley.recaf;

import me.coley.recaf.util.RecafClassLoader;

import java.lang.instrument.Instrumentation;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * Recaf loader.
 *
 * @author xxDark
 */
public final class Agent {
    /**
     * Start Recaf as a launch-argument Java agent.
     *
     * @param agentArgs
     * 		Agent arguments to pass to Recaf.
     * @param inst
     * 		Instrumentation instance.
     *
     * @throws Exception if any error occur.
     */
    public static void premain(String agentArgs, Instrumentation inst) throws Exception {
        agent(agentArgs, inst);
    }

    /**
     * Start Recaf as a dynamically attached Java agent.
     *
     * @param agentArgs
     * 		Agent arguments to pass to Recaf.
     * @param inst
     * 		Instrumentation instance.
     *
     * @throws Exception if any error occur.
     */
    public static void agentmain(String agentArgs, Instrumentation inst) throws Exception {
        agent(agentArgs, inst);
    }

    private static void agent(String args, Instrumentation inst) throws Exception {
        // Can't use any API here.
        URL source = Agent.class.getProtectionDomain().getCodeSource().getLocation();
        URLClassLoader loader = new RecafClassLoader(new URL[]{source});
        Class<?> recaf = loader.loadClass("me.coley.recaf.Recaf");
        Method m = recaf.getDeclaredMethod("agent", String.class, Instrumentation.class);
        m.setAccessible(true);
        m.invoke(null,  args, inst);
    }
}


text:
package com.desklampstudios.thyroxine.eighth.sync;

import android.accounts.Account;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;

import com.desklampstudios.thyroxine.iodine.IodineAuthException;
import com.desklampstudios.thyroxine.iodine.IodineAuthUtils;
import com.desklampstudios.thyroxine.eighth.io.EighthSignupException;
import com.desklampstudios.thyroxine.eighth.io.IodineEighthApi;
import com.desklampstudios.thyroxine.eighth.provider.EighthContract;
import com.desklampstudios.thyroxine.eighth.model.EighthActv;
import com.desklampstudios.thyroxine.eighth.model.EighthActvInstance;

import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;

public class SignupActvTask extends AsyncTask<Object, Void, Void> {
    private static final String TAG = SignupActvTask.class.getSimpleName();

    private final Activity mActivity;
    private final Account mAccount;
    private final SignupResultListener mResultListener;

    @Nullable private Exception mException = null;

    public SignupActvTask(Activity activity, Account account, SignupResultListener listener) {
        mActivity = activity;
        mAccount = account;
        mResultListener = listener;
    }

    @Nullable
    @Override
    protected Void doInBackground(Object... params) {
        final int blockId = (Integer) params[0];
        final EighthActv actv = (EighthActv) params[1];
        final EighthActvInstance actvInstance = (EighthActvInstance) params[2];
        final int actvId = actv.actvId;

        try {
            IodineAuthUtils.withAuthTokenBlocking(mActivity, mAccount, new IodineAuthUtils.AuthTokenOperation<Void>() {
                @Override
                public Void performOperation(String authToken)
                        throws IodineAuthException, IOException, XmlPullParserException, EighthSignupException {
                    IodineEighthApi.doSignup(mActivity, blockId, actvId, authToken);
                    return null;
                }
            });
        } catch (EighthSignupException e) {
            Log.d(TAG, "Signup failed", e);
            mException = e;
            return null;
        } catch (IOException e) {
            Log.e(TAG, "Connection error", e);
            mException = e;
            return null;
        } catch (OperationCanceledException e) {
            Log.e(TAG, "Operation canceled", e);
            mException = e;
            return null;
        } catch (AuthenticatorException e) {
            Log.e(TAG, "Authenticator error", e);
            mException = e;
            return null;
        } catch (IodineAuthException e) {
            Log.e(TAG, "Auth error", e);
            mException = e;
            return null;
        } catch (XmlPullParserException e) {
            Log.e(TAG, "XML error", e);
            mException = e;
            return null;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // Update database
        updateDatabase(blockId, actv, actvInstance);

        return null;
    }

    // TODO: make less hacky
    private void updateDatabase(int blockId, @NonNull EighthActv actv, @NonNull EighthActvInstance actvInstance) {
        // push to db, or something
        final ContentResolver resolver = mActivity.getContentResolver();

        // Update schedule
        ContentValues scheduleValues = new ContentValues();
        scheduleValues.put(EighthContract.Schedule.KEY_BLOCK_ID, blockId);
        scheduleValues.put(EighthContract.Schedule.KEY_ACTV_ID, actv.actvId);
        Uri scheduleUri = resolver.insert(EighthContract.Schedule.CONTENT_URI, scheduleValues);
        Log.d(TAG, "updated schedule: inserted with uri " + scheduleUri);

        // Update EighthActv
        ContentValues actvValues = EighthContract.Actvs.toContentValues(actv);
        Uri actvUri = resolver.insert(EighthContract.Actvs.CONTENT_URI, actvValues);
        Log.d(TAG, "updated actv: inserted with uri " + actvUri);

        // Update EighthActvInstance
        ContentValues actvInstanceValues = EighthContract.ActvInstances.toContentValues(actvInstance);
        Uri actvInstanceUri = resolver.insert(EighthContract.ActvInstances.CONTENT_URI, actvInstanceValues);
        Log.d(TAG, "updated actvInstance: inserted with uri " + actvInstanceUri);

        // notify changes
        resolver.notifyChange(EighthContract.Blocks.buildBlockUri(blockId), null, false);
    }

    @Override
    protected void onPostExecute(@Nullable Void result) {
        if (mException != null) {
            mResultListener.onError(mException);
            return;
        }

        Log.i(TAG, "Got signup result: " + result);
        mResultListener.onSignupResult();
    }

    public interface SignupResultListener {
        void onSignupResult();
        void onError(@NonNull Exception e);
    }
}


text:
from flask.ext.wtf import Form
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import Required, Length, Email, Regexp, EqualTo
from wtforms import ValidationError
from ..models import User

class LoginForm(Form):
    email = StringField('Email', validators=[Required(), Length(1, 64), Email()])
    password = PasswordField(u'密码', validators=[Required()])
    remember_me = BooleanField(u'记住我')
    submit = SubmitField('登录')

class RegistrationForm(Form):
    email = StringField('Email', validators=[Required(), Length(1, 64),
                                           Email()])
    username = StringField(u'用户名', validators=[
        Required(), Length(1, 64), Regexp('^[A-Za-z][A-Za-z0-9_.]*$', 0,
                                          '用户名必须以字母开头, '
                                          '可由字母, 数字, 下划线组成')])
    password = PasswordField(u'密码', validators=[
        Required(), EqualTo('password2', message='Passwords must match.')])
    password2 = PasswordField(u'确认密码', validators=[Required()])
    submit = SubmitField(u'注册')

    def validate_email(self, field):
        if User.query.filter_by(email=field.data).first():
            raise ValidationError(u'Email已经被注册')

    def validate_username(self, field):
        if User.query.filter_by(username=field.data).first():
            raise ValidationError(u'用户名已经被注册')


text:
<!DOCTYPE html>

	<title>Java Web Starter Application</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<link rel="stylesheet" href="style.css" />

 UPDATES MADE Liberty for Java Starter Application. To get started see the Start Coding guide under your app in your dashboard.


text: Der Datensatz wurde erfolgreich hinzugefügt!


text:
'use strict';

var expect = require('chai').expect,
	checks = requireLib('registry')().checks;

describe('Number validation checks:', function() {

	describe('int validation', function() {

		it('should pass', function() {
			var result = checks.isInt(1);
			expect(result).to.be.true;
		});

		it('should pass with string', function() {
			var result = checks.isInt('' + 1);
			expect(result).to.be.true;
		});

		it('should not pass with a random string', function() {
			var result = checks.isInt('XXX');
			expect(result).to.be.false;
		});

		it('should not pass with a float string', function() {
			var result = checks.isInt('1.5');
			expect(result).to.be.false;
		});

		it('should not pass with a float', function() {
			var result = checks.isInt(1.5);
			expect(result).to.be.false;
		});

	});

	describe('float validation', function() {

		it('should pass with int', function() {
			var result = checks.isFloat(1);
			expect(result).to.be.true;
		});

		it('should pass with int string', function() {
			var result = checks.isFloat('' + 1);
			expect(result).to.be.true;
		});

		it('should pass with float', function() {
			var result = checks.isFloat(1.5);
			expect(result).to.be.true;
		});

		it('should pass with float string', function() {
			var result = checks.isFloat('' + 1.5);
			expect(result).to.be.true;
		});

		it('should not pass with a random string', function() {
			var result = checks.isFloat('XXX');
			expect(result).to.be.false;
		});

	});

	describe('number validation', function() {

		it('should pass with int', function() {
			var result = checks.isFloat(1);
			expect(result).to.be.true;
		});

		it('should pass with int string', function() {
			var result = checks.isFloat('' + 1);
			expect(result).to.be.true;
		});

		it('should pass with float', function() {
			var result = checks.isFloat(1.5);
			expect(result).to.be.true;
		});

		it('should pass with float string', function() {
			var result = checks.isFloat('' + 1.5);
			expect(result).to.be.true;
		});

		it('should not pass with a random string', function() {
			var result = checks.isFloat('XXX');
			expect(result).to.be.false;
		});

	});

});


text:
#region S# License

#endregion S# License
namespace StockSharp.Studio.Core.Commands
{
	using System;

	using StockSharp.BusinessEntities;

	public class PositionEditCommand : BaseStudioCommand
	{
		public BasePosition Position { get; private set; }

		public PositionEditCommand(BasePosition position)
		{
			if (position == null)
				throw new ArgumentNullException(nameof(position));

			Position = position;
		}
	}
}


text:
/// <reference path="chutzpahRunner.js" />
/*globals phantom, chutzpah, window, mocha*/

(function () {
    'use strict';

    phantom.injectJs('chutzpahRunner.js');
    phantom.injectJs('../mochaFunctions.js');

    try {
        chutzpah.runner(onInitialized, onPageLoaded, isMochaLoaded, onMochaLoaded, isTestingDone);
    } catch (e) {
        phantom.exit(2); // Unkown error
    }
}());


text:
<?php defined('SYSPATH') OR die('No direct access allowed.');
/**
 * @package  Pagination
 *
 * Pagination configuration is defined in groups which allows you to easily switch
 * between different pagination settings for different website sections.
 * Note: all groups inherit and overwrite the default group.
 *
 * Group Options:
 *  directory      - Views folder in which your pagination style templates reside
 *  style          - Pagination style template (matches view filename)
 *  uri_segment    - URI segment (int or 'label') in which the current page number can be found
 *  query_string   - Alternative to uri_segment: query string key that contains the page number
 *  items_per_page - Number of items to display per page
 *  auto_hide      - Automatically hides pagination for single pages
 */
$config['default'] = array
(
	'directory'      => 'pagination',
	'style'          => 'classic',
	'uri_segment'    => 3,
	'query_string'   => '',
	'items_per_page' => 4,
	'auto_hide'      => FALSE,
);


text:
module Weaver
  # Base element class for all HTML elements
  class Elements
    def initialize(page, anchors)
      @inner_content = []
      @anchors = anchors
      @page = page
    end

    def method_missing(name, *args, &block)
      tag = "<#{name} />"

      inner = args.shift if args[0].is_a? String
      if block
        elem = Elements.new(@page, @anchors)
        elem.instance_eval(&block)
        inner = elem.generate
      end

      if !inner
        options = args[0] || []
        opts = options.map { |key, value| "#{key}=\"#{value}\"" }.join ' '

        tag = "<#{name} #{opts} />"
      elsif args.empty?
        tag = "<#{name}>#{inner}</#{name}>"
      elsif (args.length == 1) && args[0].is_a?(Hash)
        options = args[0]
        opts = options.map { |key, value| "#{key}=\"#{value}\"" }.join ' '
        tag = "<#{name} #{opts}>#{inner}</#{name}>"
      end

      @inner_content << tag
      tag
    end

    def root
      @page.root
    end

    def request_js(path)
      @page.request_js(path)
    end

    def request_css(path)
      @page.request_css(path)
    end

    def on_page_load(script)
      @page.on_page_load(script)
    end

    def write_script_once(script)
      @page.write_script_once(script)
    end

    def background(&block)
      @page.background(block)
    end

    def on_page_load(script)
      @page.on_page_load(script)
    end

    def icon(type)
      iconname = type.to_s.tr('_', '-')
      if type.is_a? Symbol
        i class: "fa fa-#{iconname}" do
        end
      else
        i class: 'fa' do
          text type
        end
      end
    end

    def wform(options = {}, &block)
      theform = Form.new(@page, @anchors, options, &block)
      @inner_content << theform.generate
      @page.scripts << theform.generate_script
    end

    def ibox(options = {}, &block)
      panel = Panel.new(@page, @anchors, options)
      panel.instance_eval(&block)
      @inner_content << panel.generate
    end

    def center(content = nil, options = {}, &block)
      options[:style] = '' unless options[:style]

      options[:style] += '; text-align: center;'
      if !content
        div options, &block
      else
        div content, options, &block
      end
    end

    def panel(title, &block)
      div class: 'panel panel-default' do
        div class: 'panel-heading' do
          h5 title
        end
        div class: 'panel-body', &block
      end
    end

    def tabs(&block)
      tabs = Tabs.new(@page, @anchors)
      tabs.instance_eval(&block)

      @inner_content << tabs.generate
    end

    def syntax(lang = :javascript, options = {}, &block)
      code = Code.new(@page, @anchors, lang, options)
      code.instance_eval(&block)

      @inner_content << code.generate

      @page.scripts << code.generate_script
    end

    def image(name, options = {})
      style = (options[:style]).to_s
      if options[:rounded_corners] == true
        style += ' border-radius: 8px'
      elsif options[:rounded_corners] == :top
        style += ' border-radius: 8px 8px 0px 0px'
      else
        if options[:rounded_corners]
          style += " border-radius: #{options[:rounded_corners]}px"
        end

      end

      img_options = {
        class: "img-responsive #{options[:class]}",
        src: "#{@page.root}images/#{name}",
        style: style
      }
      img_options[:id] = options[:id] if options[:id]

      img img_options
    end

    def crossfade_image(image_normal, image_hover)
      div class: 'crossfade' do
        image image_hover, class: 'bottom'
        image image_normal, class: 'top'
      end
      image image_hover
      @page.request_css 'css/crossfade_style.css'
    end

    def gallery(images, thumbnails = images, options = {})
      @page.request_css 'css/plugins/blueimp/css/blueimp-gallery.min.css'

      div class: 'lightBoxGallery' do
        (0...images.length).to_a.each do |index|
          title = options[:titles][index] if options[:titles]

          a href: (images[index]).to_s, title: title.to_s, "data-gallery": '' do
            img src: (thumbnails[index]).to_s, style: 'margin: 5px;'
          end
        end

        div id: 'blueimp-gallery', class: 'blueimp-gallery' do
          div class: 'slides' do end
          h3 class: 'title' do end
          a class: 'prev' do end
          a class: 'next' do end
          a class: 'close' do end
          a class: 'play-pause' do end
          ol class: 'indicator' do end
        end
      end

      @page.request_js 'js/plugins/blueimp/jquery.blueimp-gallery.min.js'
    end

    def breadcrumb(patharray)
      ol class: 'breadcrumb' do
        patharray.each do |path|
          li path
        end
      end
    end

    def p(*args, &block)
      method_missing(:p, *args, &block)
    end

    def text(theText)
      @inner_content << theText
    end

    def badge(label, options = {})
      options[:type] ||= 'plain'

      kind = 'label'
      kind = 'badge' if options[:rounded]
      tag_options = options.clone
      tag_options[:class] = "#{kind} #{kind}-#{options[:type]}"

      span tag_options do
        text label
      end
    end

    def hyperlink(url, title = nil, &block)
      url = url.dup
      title ||= url

      if url.start_with? '/'
        url.sub!(%r{^/}, @page.root)
        if block
          a href: url, &block
        else
          a title, href: url
        end
      else

        if block
          a href: url, target: '_blank' do
            span do
              span &block
              icon :external_link
            end
          end
        else
          a href: url, target: '_blank' do
            span do
              text title
              text ' '
              icon :external_link
            end
          end
        end
      end
    end

    def widget(options = {}, &block)
      # gray-bg
      # white-bg
      # navy-bg
      # blue-bg
      # lazur-bg
      # yellow-bg
      # red-bg
      # black-bg

      color = "#{options[:color]}-bg" || 'navy-bg'

      div class: "widget style1 #{color}", &block
    end

    def jumbotron(options = {}, &block)
      additional_style = ''

      if options[:background]
        additional_style += " background-image: url('#{@page.root}images/#{options[:background]}'); background-position: center center; background-size: cover;"
      end

      additional_style += " height: #{options[:height]}px;" if options[:height]

      if options[:min_height]
        additional_style += " min-height: #{options[:min_height]}px;"
      end

      if options[:max_height]
        additional_style += " max-height: #{options[:max_height]}px;"
      end

      div class: 'jumbotron', style: additional_style, &block
    end

    def _button(options = {}, &block)
      anIcon = options[:icon]
      title = options[:title]

      if title.is_a? Hash
        options.merge! title
        title = anIcon
        anIcon = nil
      end

      style = options[:style] || :primary
      size = "btn-#{options[:size]}" if options[:size]
      blockstyle = 'btn-block' if options[:block]
      outline = 'btn-outline' if options[:outline]
      dim = 'dim' if options[:threedee]
      dim = 'dim btn-large-dim' if options[:bigthreedee]
      dim = 'btn-rounded' if options[:rounded]
      dim = 'btn-circle' if options[:circle]

      buttonOptions = {
        type: options[:type] || 'button',
        class: "btn btn-#{style} #{size} #{blockstyle} #{outline} #{dim}",
        id: options[:id]
      }

      if block
        closer = ''

        closer = '; return false;' if options[:nosubmit]

        action = Action.new(@page, @anchors, &block)
        buttonOptions[:onclick] = "#{action.name}(this)"
        if options[:data]
          buttonOptions[:onclick] = "#{action.name}(this, #{options[:data]})#{closer}"
        end
        @page.scripts << action.generate
      end

      type = :button

      buttonOptions[:"data-toggle"] = 'button' if options[:toggle]
      type = :a if options[:toggle]

      method_missing type, buttonOptions do
        if title.is_a? Symbol
          icon title
        else
          icon anIcon if anIcon
          text ' ' if anIcon
          text title
        end
      end
    end

    def normal_button(anIcon, title = {}, options = {}, &block)
      options[:icon] = anIcon
      options[:title] = title
      _button(options, &block)
    end

    def block_button(anIcon, title = {}, options = {}, &block)
      options[:block] = true
      options[:icon] = anIcon
      options[:title] = title
      _button(options, &block)
    end

    def outline_button(anIcon, title = {}, options = {}, &block)
      options[:outline] = true
      options[:icon] = anIcon
      options[:title] = title
      _button(options, &block)
    end

    def big_button(anIcon, title = {}, options = {}, &block)
      options[:size] = :lg
      options[:icon] = anIcon
      options[:title] = title
      _button(options, &block)
    end

    def small_button(anIcon, title = {}, options = {}, &block)
      options[:size] = :sm
      options[:icon] = anIcon
      options[:title] = title
      _button(options, &block)
    end

    def tiny_button(anIcon, title = {}, options = {}, &block)
      options[:size] = :xs
      options[:icon] = anIcon
      options[:title] = title
      _button(options, &block)
    end

    def embossed_button(anIcon, title = {}, options = {}, &block)
      options[:threedee] = true
      options[:icon] = anIcon
      options[:title] = title
      _button(options, &block)
    end

    def big_embossed_button(anIcon, title = {}, options = {}, &block)
      options[:bigthreedee] = true
      options[:icon] = anIcon
      options[:title] = title
      _button(options, &block)
    end

    def rounded_button(anIcon, title = {}, options = {}, &block)
      options[:rounded] = true
      options[:icon] = anIcon
      options[:title] = title
      _button(options, &block)
    end

    def circle_button(anIcon, title = {}, options = {}, &block)
      options[:circle] = true
      options[:icon] = anIcon
      options[:title] = title
      _button(options, &block)
    end

    def math(string)
      text "$$$MATH$$$#{string}$$$ENDMATH$$$"
    end

    def generate
      @inner_content.join
    end
  end
end


text:
=[zID/00/Entity/0.md]

Sign.=[U/id/geraldine_graber]

Sign.Title=Founder

=[U/at/US/MA/Middlesex/Cambridge/Broadway/1/Geo]

Name.Full=Gerry's Grapes, LLC

Entity.a=a Massachusetts LLC

Adr.Type=business

Contact.Name.Ms=Ms. Graber

Claim.Response.Delay=two business days from the date of the Claim

PageName=U/id/gerrys_grapes_llc


text:
import json
import time
import nose.tools
from datetime import datetime, timedelta
from world import world
from bigml.api import HTTP_CREATED
from bigml.api import FINISHED, FAULTY
from bigml.api import get_status

from read_prediction_steps import i_get_the_prediction

def i_create_a_prediction(step, data=None):
    if data is None:
        data = "{}"
    model = world.model['resource']
    data = json.loads(data)
    resource = world.api.create_prediction(model, data)
    world.status = resource['code']
    assert world.status == HTTP_CREATED, "Wrong status: %s" % world.status
    world.location = resource['location']
    world.prediction = resource['object']
    world.predictions.append(resource['resource'])

def i_create_a_centroid(step, data=None):
    if data is None:
        data = "{}"
    cluster = world.cluster['resource']
    data = json.loads(data)
    resource = world.api.create_centroid(cluster, data)
    world.status = resource['code']
    assert world.status == HTTP_CREATED
    world.location = resource['location']
    world.centroid = resource['object']
    world.centroids.append(resource['resource'])

def i_create_a_proportional_prediction(step, data=None):
    if data is None:
        data = "{}"
    model = world.model['resource']
    data = json.loads(data)
    resource = world.api.create_prediction(model, data,
                                           args={'missing_strategy': 1})
    world.status = resource['code']
    assert world.status == HTTP_CREATED
    world.location = resource['location']
    world.prediction = resource['object']
    world.predictions.append(resource['resource'])

def check_prediction(got, expected):
    if not isinstance(got, basestring):
        nose.tools.assert_almost_equals(got, float(expected), 10)
    else:
        nose.tools.assert_equals(got, expected)

def the_prediction_is(step, objective, prediction):
    check_prediction(world.prediction['prediction'][objective], prediction)

def the_median_prediction_is(step, objective, prediction):
    check_prediction(world.prediction['prediction_path'][
        'objective_summary']['median'], prediction)

def the_centroid_is_with_distance(step, centroid, distance):
    check_prediction(world.centroid['centroid_name'], centroid)
    check_prediction(world.centroid['distance'], distance)

def the_centroid_is(step, centroid):
    check_prediction(world.centroid['centroid_name'], centroid)

def the_centroid_is_ok(step):
    assert world.api.ok(world.centroid)

def the_confidence_is(step, confidence):
    local_confidence = round(float(world.prediction['confidence']), 4)
    confidence = round(float(confidence), 4)
    assert local_confidence == confidence

def i_create_an_ensemble_prediction(step, data=None):
    if data is None:
        data = "{}"
    ensemble = world.ensemble['resource']
    data = json.loads(data)
    resource = world.api.create_prediction(ensemble, data)
    world.status = resource['code']
    assert world.status == HTTP_CREATED
    world.location = resource['location']
    world.prediction = resource['object']
    world.predictions.append(resource['resource'])

def wait_until_prediction_status_code_is(step, code1, code2, secs):
    start = datetime.utcnow()
    i_get_the_prediction(step, world.prediction['resource'])
    status = get_status(world.prediction)
    while (status['code'] != int(code1) and
           status['code'] != int(code2)):
        time.sleep(3)
        assert datetime.utcnow() - start < timedelta(seconds=int(secs))
        i_get_the_prediction(step, world.prediction['resource'])
        status = get_status(world.prediction)
    assert status['code'] == int(code1)

def the_prediction_is_finished_in_less_than(step, secs):
    wait_until_prediction_status_code_is(step, FINISHED, FAULTY, secs)

def create_local_ensemble_prediction_add_confidence(step, input_data):
    world.local_prediction = world.local_ensemble.predict(
        json.loads(input_data), add_confidence=True)

def create_local_ensemble_prediction(step, input_data):
    world.local_prediction = world.local_ensemble.predict(json.loads(input_data))

def create_local_ensemble_prediction_with_confidence(step, input_data):
    world.local_prediction = world.local_ensemble.predict(
        json.loads(input_data), with_confidence=True)

def create_local_ensemble_prediction_using_median_with_confidence(step, input_data):
    world.local_prediction = world.local_ensemble.predict(
        json.loads(input_data), with_confidence=True, median=True)

def i_create_an_anomaly_score(step, data=None):
    if data is None:
        data = "{}"
    anomaly = world.anomaly['resource']
    data = json.loads(data)
    resource = world.api.create_anomaly_score(anomaly, data)
    world.status = resource['code']
    assert world.status == HTTP_CREATED
    world.location = resource['location']
    world.anomaly_score = resource['object']
    world.anomaly_scores.append(resource['resource'])

def the_anomaly_score_is(step, score):
    check_prediction(world.anomaly_score['score'], score)


text:
drop DATABASE IF EXISTS foodQuest;

CREATE DATABASE foodQuest;

USE foodQuest;

CREATE TABLE users (
  id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  username varchar(64) NOT NULL,
  password varchar(64) NOT NULL,
  location varchar(5) NOT NULL,
  preferences varchar(100) NOT NULL,
  PRIMARY KEY (id),
  UNIQUE KEY (username)
);

--  NOTE: Add imageUrl field to restaurants table
CREATE TABLE restaurants (
  id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  name varchar(64) NOT NULL,
  yelpId varchar(200) NOT NULL,
  price varchar(4) NOT NULL,
  rating tinyint(5) unsigned NOT NULL,
  address varchar(100) NOT NULL,
  zip_code varchar(5) NOT NULL,
  PRIMARY KEY (id),
  UNIQUE KEY (yelpId)
);

CREATE TABLE quests (
  id bigint(20) unsigned NOT NULL AUTO_INCREMENT,

  creator bigint(20) unsigned NOT NULL,
  task1 bigint(20) unsigned NOT NULL,
  task1Completed tinyint(1) unsigned NOT NULL,
  task2 bigint(20) unsigned NOT NULL,
  task2Completed tinyint(1) unsigned NOT NULL,
  task3 bigint(20) unsigned NOT NULL,
  task3Completed tinyint(1) unsigned NOT NULL,

  PRIMARY KEY (id),
  FOREIGN KEY (creator) REFERENCES users(id),

  FOREIGN KEY (task1) REFERENCES restaurants(id),
  FOREIGN KEY (task2) REFERENCES restaurants(id),
  FOREIGN KEY (task3) REFERENCES restaurants(id)
);

CREATE TABLE preferences (
  id bigint(20) unsigned NOT NULL AUTO_INCREMENT,

  cuisine varchar(64) NOT NULL,
  PRIMARY KEY (id)
);

INSERT INTO users (username, password, location, preferences) VALUES ("Hungry Johnny", "secret", "94131", "Vegetarian");

-- NOTE: This table & seed data are not actually used in the current implementation of the app, but they give an idea of where we were headed.
INSERT INTO preferences (cuisine) VALUES ("Chinese");
INSERT INTO preferences (cuisine) VALUES ("German");
INSERT INTO preferences (cuisine) VALUES ("Japanese");
INSERT INTO preferences (cuisine) VALUES ("Vegetarian");
INSERT INTO preferences (cuisine) VALUES ("Italian");
INSERT INTO preferences (cuisine) VALUES ("Cajun");
INSERT INTO preferences (cuisine) VALUES ("American");
INSERT INTO preferences (cuisine) VALUES ("French");
INSERT INTO preferences (cuisine) VALUES ("Brunch");
INSERT INTO preferences (cuisine) VALUES ("Ice Cream");


text:
{extend "session"}

{* Get latest products *}
{$featured_products = "/products"|get:[
	is_active => true,
	limit => 8
]}

	{* Render featured products *}
	{render "product-list" with=$featured_products}


text:
oneview_volume 'VOL1' do
  client node['oneview_test']['client']
  delete_from_appliance_only true
  action :delete
end


text:
require 'test_helper'

class PdfTest < ActiveSupport::TestCase
  test 'raise exception when use a variable undefined' do
    assert_raise(ActionView::Template::Error) do
      Pdf.generate '<%= var %>'
    end
  end

  test 'generate string with pdf using bootstrap, locals and options' do
    pdf_string = Pdf.generate '<%= 2 + 2 %>:<%= var %>',
                              locals: { var: 'test' },
                              options: { orientation: 'Landscape' }

    assert_instance_of String, pdf_string
  end

  test 'raise exception when not find pdf template' do
    assert_raise(ActiveRecord::RecordNotFound) do
      Pdf.generate_from_template 'not exists'
    end
  end

  test 'raise exception when use a variable undefined in pdf template' do
    assert_raise(ActionView::Template::Error) do
      Pdf.generate_from_template 'First pdf template'
    end
  end

  test 'generate string with pdf using pdf template, locals and options' do
    pdf_string = Pdf.generate_from_template 'First pdf template',
                                            locals: { var: 'test' },
                                            options: { orientation: 'Landscape' }

    assert_instance_of String, pdf_string
  end
end


text:
angular
    .module('baseline-ui')
    .component('baselineModule', {
        controller: BaselineModuleController,
        bindings: {
            aliveResponse: '<'
        },
        templateUrl: 'app/modules/index/index.html'
    });

function BaselineModuleController(BaseService, RestService, $log) {
    var ctrl = this;

    // Communication example with backend
    var echoUrl = BaseService.api.echo;

    RestService.getResponse(echoUrl, {params: {message: 'Echoed via GET'}}).then(function (response) {
        $log.debug(response);
    });

    RestService.getResponse(echoUrl, {data: {message: 'Echoed via POST'}}).then(function (response) {
        $log.debug(response);
    });
}


text:
namespace GZSTREAM_NAMESPACE {
#endif

// ----------------------------------------------------------------------------
// Internal classes to implement gzstream. See header file for user classes.
// ----------------------------------------------------------------------------

// --------------------------------------
// class gzstreambuf:
// --------------------------------------

gzstreambuf* gzstreambuf::open( const char* name, int open_mode) {
    if ( is_open())
        return (gzstreambuf*)0;
    mode = open_mode;
    // no append nor read/write mode
    if ((mode & std::ios::ate) || (mode & std::ios::app)
        || ((mode & std::ios::in) && (mode & std::ios::out)))
        return (gzstreambuf*)0;
    char  fmode[10];
    char* fmodeptr = fmode;
    if ( mode & std::ios::in)
        *fmodeptr++ = 'r';
    else if ( mode & std::ios::out)
        *fmodeptr++ = 'w';
    *fmodeptr++ = 'b';
    *fmodeptr = '\0';
    file = gzopen( name, fmode);
    if (file == 0)
        return (gzstreambuf*)0;
    opened = 1;
    return this;
}

gzstreambuf * gzstreambuf::close() {
    if ( is_open()) {
        sync();
        opened = 0;
        if ( gzclose( file) == Z_OK)
            return this;
    }
    return (gzstreambuf*)0;
}

int gzstreambuf::underflow() { // used for input buffer only
    if ( gptr() && ( gptr() < egptr()))
        return * reinterpret_cast<unsigned char *>( gptr());

    if ( ! (mode & std::ios::in) || ! opened)
        return EOF;
    // Josuttis' implementation of inbuf
    int n_putback = gptr() - eback();
    if ( n_putback > 4)
        n_putback = 4;
    memcpy( buffer + (4 - n_putback), gptr() - n_putback, n_putback);

    int num = gzread( file, buffer+4, bufferSize-4);
    if (num <= 0) // ERROR or EOF
        return EOF;

    // reset buffer pointers
    setg( buffer + (4 - n_putback),   // beginning of putback area
          buffer + 4,                 // read position
          buffer + 4 + num);          // end of buffer

    // return next character
    return * reinterpret_cast<unsigned char *>( gptr());
}

int gzstreambuf::flush_buffer() {
    // Separate the writing of the buffer from overflow() and
    // sync() operation.
    int w = pptr() - pbase();
    if ( gzwrite( file, pbase(), w) != w)
        return EOF;
    pbump( -w);
    return w;
}

int gzstreambuf::overflow( int c) { // used for output buffer only
    if ( ! ( mode & std::ios::out) || ! opened)
        return EOF;
    if (c != EOF) {
        *pptr() = c;
        pbump(1);
    }
    if ( flush_buffer() == EOF)
        return EOF;
    return c;
}

int gzstreambuf::sync() {
    // Changed to use flush_buffer() instead of overflow( EOF)
    // which caused improper behavior with std::endl and flush(),
    // bug reported by Vincent Ricard.
    if ( pptr() && pptr() > pbase()) {
        if ( flush_buffer() == EOF)
            return -1;
    }
    return 0;
}

// --------------------------------------
// class gzstreambase:
// --------------------------------------

gzstreambase::gzstreambase( const char* name, int mode) {
    init( &buf);
    open( name, mode);
}

gzstreambase::~gzstreambase() {
    buf.close();
}

void gzstreambase::open( const char* name, int open_mode) {
    if ( ! buf.open( name, open_mode))
        clear( rdstate() | std::ios::badbit);
}

void gzstreambase::close() {
    if ( buf.is_open())
        if ( ! buf.close())
            clear( rdstate() | std::ios::badbit);
}

#ifdef GZSTREAM_NAMESPACE
} // namespace GZSTREAM_NAMESPACE
#endif

// ============================================================================
// EOF //


text:
pigeon
======

Fluent email builder for golang


text:
{% extends "base.html" %}

{% block title %}Registration complete{% endblock %}

{% block content %}

Registration complete!

An activation email has been sent.

{% endblock %}


text:
These files files can be added to a fail2ban installment so that the relevant FileMaker Server logs will be included.

To install the fail2ban core files, you can use the source at fail2ban.org, or a Mac OS package manager like MacPorts or Homebrew.

#### Installation

For MacPorts, the install looks like this:

`sudo port install fail2ban`

To install from  source, the process is along these lines:

* open the Terminal
* fetch source (currently 0.9.3): `curl -O https://codeload.github.com/fail2ban/fail2ban/zip/master`
* unzip the archive: `tar xf master`
* `cd fail2ban-master`
* run the installer script: `sudo python setup.py install`
* create the run directory (may already be present): `sudo mkdir /var/run/fail2ban/`
* create the file at /Library/LaunchDaemons/org.fail2ban.plist with content from below:
```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
        <key>Disabled</key>
        <false/>
        <key>Label</key>
        <string>fail2ban</string>
        <key>ProgramArguments</key>
        <array>
                <string>/usr/local/bin/fail2ban-client</string>
                <string>start</string>
        </array>
        <key>RunAtLoad</key>
        <true/>
</dict>
</plist>
```
* load the launchctl .plist: `sudo launchctl load -w /Library/LaunchDaemons/org.fail2ban.plist`

#### Configuration

Since fail2ban version 0.9x, paths can no longer containg spaces.

To work around this, run the following command:
```
sudo ln -s "/Library/FileMaker Server/" /Library/FileMakerServer
```

Next, to enable the FileMaker filter, you'll need to add something like the following into your jail.local file (which you may need to create):

```
[filemaker-client]

enabled  = true
action   = pf[name=filemake-client, port=5003,16001,http,https]
dest     = youremail@domain.com
filter   = filemaker-client
logpath  = /Library/FileMakerServer/Logs/Event.log
maxretry = 6
```

If using the Ubuntu style macros this could be written more simply as:

```
[filemaker-client]

enabled  = true
port     = 5003,16001,http,https
filter   = filemaker-client
logpath  = /Library/FileMakerServer/Logs/Event.log
maxretry = 6
```

Make sure the following values are defined in the [DEFAULT] section of the jail.conf file or at beginning of jail.local:

```
# email to receive start, stop, ban, and unban notifications
destemail = notifications@domain.com

# This is servername, not servername.domain.com
hostname = `hostname -s`

banaction = pf
```

The following must be added to the end of the /etc/pf.conf file to enable the fail2ban's ability to block addresses:
```
table <fail2ban> persist
block drop log quick from <fail2ban> to any
```

Reload the settings for PF:

`sudo pfctl -f /etc/pf.conf`

If not already enabled (likely), you'll need to enable PF to start filtering connections:

`sudo pfctl -e`

Create a script at /etc/periodic/800.fail2ban-rotate-log to rotate log file in case it starts getting big:

```
#!/bin/sh

# 2017-04-06 simon_b: created file

logPath="/var/log/fail2ban.log"
macPortsFail2ban="/opt/local/bin/fail2ban-client"

apache_version=$(/usr/sbin/httpd -version | head -1 | cut -d "/" -f 2 | cut -d "." -f 1,2)

if [ "$apache_version" == "2.2" ]; then
   # Older systems can use newsyslog, but this will rotate log file regardless of size.
   /usr/sbin/newsyslog -F "$logPath"
else
   # Rotate out the log if bigger than 40 MB, keeping current log at same file name. Requires Apache 2.4+ (Yosemite or better).
   /usr/sbin/rotatelogs -L "$logPath" 40M
fi

if [ -s ${macPortsFail2ban} ]; then
   # Using MacPorts:
   "$macPortsFail2ban" set logtarget "$logPath" >/dev/null
else
   # Make fail2ban start using the new log file.
   /usr/local/bin/fail2ban-client set logtarget "$logPath" >/dev/null
fi
```

Use `sudo chmod ug+x /etc/periodic/800.fail2ban-rotate-log` to make the script executable.

#### Yosemite+ Configuration

If using 10.10 or better, we can make an additional improvement. This however requires making a change to how FileMaker Server writes out the web server logs. Follow the directions at https://blog.beezwax.net/2015/06/30/keep-filemaker-server-web-logs-at-fixed-paths/ for details.

Once done, add the following to your jail.local file:

```
# Giving multiple log files in logpath would generate errors. Because there is
# a space in the path? So instead, we are creating separate entries for each log file.

[apache-badbots-1]

enabled  = true
filter   = apache-badbots
logpath  = /Library/FileMakerServer/HTTPServer/logs/access_log
action   = pf[name=apache-badbots, port="http,https"]
           sendmail-whois[name=%(hostname)s, dest=%(destemail)s, sender=%(hostname)s]
maxretry = 2

[apache-badbots-2]

enabled  = true
filter   = apache-badbots
logpath  = /Library/FileMakerServer/HTTPServer/logs/ssl_access_log
action   = pf[name=apache-badbots, port="http,https"]
           sendmail-whois[name=%(hostname)s, dest=%(destemail)s, sender=%(hostname)s]
maxretry = 2

[apache-badbots-3]

enabled  = true
filter   = apache-badbots
logpath  = /Library/FileMakerServer/HTTPServer/logs/fmsadminserver_access_log
action   = pf[name=apache-badbots, port="http,https"]
           sendmail-whois[name=%(hostname)s, dest=%(destemail)s, sender=%(hostname)s]
maxretry = 2

[apache-auth-1]

enabled  = true
filter   = apache-auth
logpath  = /Library/FileMakerServer/HTTPServer/logs/error_log
action   = pf[name=apache-auth, port="http,https"]
           sendmail-whois[name=%(hostname)s, dest=%(destemail)s, sender=%(hostname)s]
maxretry = 4

[apache-auth-2]

enabled  = true
filter   = apache-auth
logpath  = /Library/FileMakerServer/HTTPServer/logs/ssl_error_log
action   = pf[name=apache-auth, port="http,https"]
           sendmail-whois[name=%(hostname)s, dest=%(destemail)s, sender=%(hostname)s]
maxretry = 4

[apache-noscript-1]

enabled  = true
action   = pf[name=apache-noscript, port="http,https,16000"]
           sendmail-whois[name=%(hostname)s, dest=%(destemail)s, sender=%(hostname)s]
filter   = apache-noscript
logpath  = /Library/FileMakerServer/HTTPServer/logs/error_log

[apache-noscript-2]

enabled  = true
action   = pf[name=apache-noscript, port="http,https,16000"]
           sendmail-whois[name=%(hostname)s, dest=%(destemail)s, sender=%(hostname)s]
filter   = apache-noscript
logpath  = /Library/FileMakerServer/HTTPServer/logs/ssl_error_log
```

#### fail2ban logs

Fail2ban keeps a log file at /var/log/fail2ban. This will list the jail name (the part in brackets in configuration file) and the IP address that triggered the entry.

Here's an example (with IP addresses obfuscated):

```
$ tail /var/log/fail2ban.log
2016-05-17 10:29:29,420 fail2ban.filter         [21867]: INFO    [postfix] Found 176.218.x.x
2016-05-17 10:30:00,468 fail2ban.filter         [21867]: INFO    Log rotation detected for /var/log/mail.log
2016-05-17 10:32:35,989 fail2ban.filter         [21867]: INFO    [postfix] Found 77.247.x.x
2016-05-17 10:36:52,351 fail2ban.filter         [21867]: INFO    [postfix] Found 167.0.x.x
2016-05-17 10:38:20,473 fail2ban.filter         [21867]: INFO    [postfix] Found 91.92.x.x
2016-05-17 10:38:20,474 fail2ban.filter         [21867]: INFO    [postfix] Found 91.92.x.x
2016-05-17 10:38:42,528 fail2ban.filter         [21867]: INFO    [postfix] Found 91.92.x.x
2016-05-17 10:38:42,529 fail2ban.filter         [21867]: INFO    [postfix] Found 91.92.x.x
2016-05-17 10:38:42,883 fail2ban.actions        [21867]: NOTICE  [postfix] Ban 91.92.x.x
2016-05-17 10:38:43,533 fail2ban.filter         [21867]: INFO    [postfix] Found 74.63.x.x
```

#### Listing IPs that are currently blocked

```
sudo pfctl -t fail2ban -T show
````

This should give some output similar to this (IP addresses obfuscated):

```
No ALTQ support in kernel
ALTQ related functions disabled
   176.218.x.x/32
   167.0.x.x/32
   91.92.x.x/32
```

#### Reference

For fail2ban documentation, see http://www.fail2ban.org.

Our original blog post is at http://blog.beezwax.net/2013/05/06/fail2ban-with-filemaker-server/ and provides some background on the initial implementation.
One recent change that dates the blog however is that ipfw is no longer available as of Mac OS 10.10 (Yosemite), so you must use pf as your action/banaction.


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.github.groovylabs</groupId>
    <artifactId>lyre</artifactId>
    <version>1.0.0-RC</version>
    <packaging>jar</packaging>

    <name>Lyre</name>
    <description>A development tool to mock REST services</description>
    <url>https://github.com/groovylabs/lyre</url>
    <licenses>
        <license>
            <name>MIT License</name>
            <url>http://www.opensource.org/licenses/mit-license.php</url>
        </license>
    </licenses>
    <organization>
        <name>Groovylabs</name>
        <url>https://github.com/groovylabs</url>
    </organization>
    <developers>
        <developer>
            <name>Kaio Cesar</name>
            <email>kaio.cesarbs@gmail.com</email>
            <organization>Groovylabs</organization>
            <organizationUrl>https://github.com/groovylabs</organizationUrl>
        </developer>
        <developer>
            <name>Jose Neto</name>
            <email>jose.slneto@gmail.com</email>
            <organization>Groovylabs</organization>
            <organizationUrl>https://github.com/groovylabs</organizationUrl>
        </developer>
    </developers>

    <properties>
        <spring.version>1.5.6.RELEASE</spring.version>
        <springfox-swagger2.version>2.7.0</springfox-swagger2.version>
        <jackson.version>2.8.9</jackson.version>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <maven.version>3.5.0</maven.version>
    </properties>
    <scm>
        <url>https://github.com/groovylabs/lyre</url>
        <connection>scm:git:git://github.com/groovylabs/lyre.git</connection>
        <developerConnection>scm:git:ssh://git@github.com/groovylabs/lyre.git</developerConnection>
    </scm>
    <issueManagement>
        <system>Github</system>
        <url>https://github.com/groovylabs/lyre/issues</url>
    </issueManagement>
    <ciManagement>
        <system>Travis</system>
        <url>https://travis-ci.org/groovylabs/lyre</url>
    </ciManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <version>${spring.version}</version>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jersey</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-inflector</artifactId>
            <version>1.0.14</version>
            <exclusions>
                <exclusion>
                    <groupId>ch.qos.logback</groupId>
                    <artifactId>logback-classic</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>ch.qos.logback</groupId>
                    <artifactId>logback-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${springfox-swagger2.version}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${springfox-swagger2.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-yaml</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>23.0</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                        <configuration>
                            <classifier>standalone</classifier>
                            <mainClass>
                                com.github.groovylabs.lyre.Lyre
                            </mainClass>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <proc>none</proc>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
package org.apache.hadoop.hive.metastore.events;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.hive.metastore.IHMSHandler;
import org.apache.hadoop.hive.metastore.api.Partition;
import org.apache.hadoop.hive.metastore.api.Table;

import java.util.Collections;
import java.util.Iterator;

@InterfaceAudience.Public
@InterfaceStability.Stable
public class DropPartitionEvent extends ListenerEvent {

  private final Table table;
  private final Iterable<Partition> partitions;
  private final boolean deleteData;

  public DropPartitionEvent (Table table,
      Partition partition, boolean status, boolean deleteData, IHMSHandler handler) {
    super (status, handler);
    this.table = table;
    this.partitions = Collections.singletonList(partition);
    // In HiveMetaStore, the deleteData flag indicates whether DFS data should be
    // removed on a drop.
    this.deleteData = deleteData;
  }

  /**
   * @return the partitions
   */
  public Iterator<Partition> getPartitionIterator() {
    return partitions.iterator();
  }

  /**
   * @return the table
   */
  public Table getTable() {

    return table;
  }

  /**
   * @return the deleteData flag
   */
  public boolean getDeleteData() {

    return deleteData;
  }
}


text:
namespace Volante
{
    using System;

    public class TestFieldIndex : ITest
    {
        public class RecordAuto : Persistent
        {
            public int IntAuto;
            public long LongAuto { get; set; }
            public bool BoolNoAuto;
        }

        public class Root : Persistent
        {
            public IFieldIndex<bool, RecordFullWithProperty> idxBool;
            public IFieldIndex<byte, RecordFullWithProperty> idxByte;
            public IFieldIndex<sbyte, RecordFullWithProperty> idxSByte;
            public IFieldIndex<short, RecordFullWithProperty> idxShort;
            public IFieldIndex<ushort, RecordFullWithProperty> idxUShort;
            public IFieldIndex<int, RecordFullWithProperty> idxInt;
            public IFieldIndex<uint, RecordFullWithProperty> idxUInt;
            public IFieldIndex<long, RecordFullWithProperty> idxLong;
            public IFieldIndex<long, RecordFullWithProperty> idxLongProp;
            public IFieldIndex<ulong, RecordFullWithProperty> idxULong;
            // TODO: Btree.allocateRootPage() doesn't support tpChar even though
            // FieldIndex does support it as a key and OldBtree supports it.
            //public IFieldIndex<char, RecordFullWithProperty> idxChar;
            public IFieldIndex<float, RecordFullWithProperty> idxFloat;
            public IFieldIndex<double, RecordFullWithProperty> idxDouble;
            public IFieldIndex<DateTime, RecordFullWithProperty> idxDate;
            public IFieldIndex<decimal, RecordFullWithProperty> idxDecimal;
            public IFieldIndex<Guid, RecordFullWithProperty> idxGuid;
            public IFieldIndex<string, RecordFullWithProperty> idxString;
            // TODO: Btree.allocateRootPage() doesn't support tpEnum even though
            // FieldIndex does support it as a key and OldBtree supports it.
            //public IFieldIndex<RecordFullWithPropertyEnum, RecordFullWithProperty> idxEnum;
            // TODO: OldBtree doesn't support oid as an index
            //public IFieldIndex<object, RecordFullWithProperty> idxObject;
            public IFieldIndex<int, RecordFullWithProperty> idxOid;

            public IFieldIndex<int, RecordAuto> idxIntAuto;
            public IFieldIndex<long, RecordAuto> idxLongAuto;
        }

        public void Run(TestConfig config)
        {
            int count = config.Count;
            var res = new TestResult();
            config.Result = res;

            IDatabase db = config.GetDatabase();
            Tests.Assert(db.Root == null);
            Root root = new Root();
            Tests.AssertDatabaseException(() =>
                { root.idxBool = db.CreateFieldIndex<bool, RecordFullWithProperty>("NonExistent", IndexType.NonUnique); },
                DatabaseException.ErrorCode.INDEXED_FIELD_NOT_FOUND);

            Tests.AssertDatabaseException(() =>
                { root.idxBool = db.CreateFieldIndex<bool, RecordFullWithProperty>("CharVal", IndexType.NonUnique); },
                DatabaseException.ErrorCode.INCOMPATIBLE_KEY_TYPE);

            root.idxBool = db.CreateFieldIndex<bool, RecordFullWithProperty>("BoolVal", IndexType.NonUnique);
            root.idxByte = db.CreateFieldIndex<byte, RecordFullWithProperty>("ByteVal", IndexType.NonUnique);
            root.idxSByte = db.CreateFieldIndex<sbyte, RecordFullWithProperty>("SByteVal", IndexType.NonUnique);
            root.idxShort = db.CreateFieldIndex<short, RecordFullWithProperty>("Int16Val", IndexType.NonUnique);
            root.idxUShort = db.CreateFieldIndex<ushort, RecordFullWithProperty>("UInt16Val", IndexType.NonUnique);
            root.idxInt = db.CreateFieldIndex<int, RecordFullWithProperty>("Int32Val", IndexType.NonUnique);
            root.idxUInt = db.CreateFieldIndex<uint, RecordFullWithProperty>("UInt32Val", IndexType.NonUnique);
            root.idxLong = db.CreateFieldIndex<long, RecordFullWithProperty>("Int64Val", IndexType.Unique);
            root.idxLongProp = db.CreateFieldIndex<long, RecordFullWithProperty>("Int64Prop", IndexType.Unique);
            root.idxULong = db.CreateFieldIndex<ulong, RecordFullWithProperty>("UInt64Val", IndexType.NonUnique);
            //root.idxChar = db.CreateFieldIndex<char, RecordFullWithProperty>("CharVal", IndexType.NonUnique);
            root.idxFloat = db.CreateFieldIndex<float, RecordFullWithProperty>("FloatVal", IndexType.NonUnique);
            root.idxDouble = db.CreateFieldIndex<double, RecordFullWithProperty>("DoubleVal", IndexType.NonUnique);
            root.idxDate = db.CreateFieldIndex<DateTime, RecordFullWithProperty>("DateTimeVal", IndexType.NonUnique);
            root.idxDecimal = db.CreateFieldIndex<Decimal, RecordFullWithProperty>("DecimalVal", IndexType.NonUnique);
            root.idxGuid = db.CreateFieldIndex<Guid, RecordFullWithProperty>("GuidVal", IndexType.NonUnique);
            root.idxString = db.CreateFieldIndex<String, RecordFullWithProperty>("StrVal", IndexType.NonUnique);
            //root.idxEnum = db.CreateFieldIndex<RecordFullWithPropertyEnum, RecordFullWithProperty>("EnumVal", IndexType.NonUnique);
            //root.idxObject = db.CreateFieldIndex<object, RecordFullWithProperty>("ObjectVal", IndexType.NonUnique);
            root.idxOid = db.CreateFieldIndex<int, RecordFullWithProperty>("Oid", IndexType.NonUnique);

            root.idxIntAuto = db.CreateFieldIndex<int, RecordAuto>("IntAuto", IndexType.Unique);
            root.idxLongAuto = db.CreateFieldIndex<long, RecordAuto>("LongAuto", IndexType.Unique);
            db.Root = root;

            Tests.Assert(root.idxString.IndexedClass == typeof(RecordFullWithProperty));
            Tests.Assert(root.idxString.KeyField.Name == "StrVal");

            int i = 0;
            RecordFullWithProperty rfFirst = null;
            RecordAuto raFirst = null;
            long firstKey = 0;
            foreach (long key in Tests.KeySeq(count))
            {
                var r = new RecordFullWithProperty(key);
                root.idxBool.Put(r);
                root.idxByte.Put(r);
                root.idxSByte.Put(r);
                root.idxShort.Put(r);
                root.idxUShort.Put(r);
                root.idxInt.Put(r);
                root.idxUInt.Put(r);
                root.idxLong.Put(r);
                root.idxLongProp.Put(r);
                root.idxULong.Put(r);
                //root.idxChar.Put(r);
                root.idxFloat.Put(r);
                root.idxDouble.Put(r);
                root.idxDate.Put(r);
                root.idxDecimal.Put(r);
                root.idxGuid.Put(r);
                root.idxString.Put(r);
                //root.idxEnum.Put(r);
                //root.idxObject.Put(r);
                root.idxOid.Put(r);

                var ra = new RecordAuto();
                root.idxIntAuto.Append(ra);
                root.idxLongAuto.Append(ra);
                Tests.Assert(ra.IntAuto == i);
                Tests.Assert(ra.LongAuto == i);
                i++;
                if (null == rfFirst)
                {
                    rfFirst = r;
                    raFirst = ra;
                    firstKey = key;
                }
            }
            db.Commit();
            var r2 = new RecordFullWithProperty(firstKey);
            // Contains for unique index
            Tests.Assert(root.idxLong.Contains(rfFirst));
            Tests.Assert(!root.idxLong.Contains(r2));

            // Contains() for non-unique index
            Tests.Assert(root.idxInt.Contains(rfFirst));
            Tests.Assert(!root.idxInt.Contains(r2));

            Tests.Assert(false == root.idxLongProp.Put(r2));
            root.idxLongProp.Set(r2);

            Tests.AssertDatabaseException(() =>
                { root.idxString.Append(rfFirst); },
                DatabaseException.ErrorCode.UNSUPPORTED_INDEX_TYPE);

            Tests.Assert(root.idxBool.Remove(rfFirst));
            Tests.Assert(root.idxByte.Remove(rfFirst));
            Tests.Assert(root.idxSByte.Remove(rfFirst));
            Tests.Assert(root.idxShort.Remove(rfFirst));
            Tests.Assert(root.idxUShort.Remove(rfFirst));
            Tests.Assert(root.idxInt.Remove(rfFirst));
            Tests.Assert(root.idxUInt.Remove(rfFirst));
            Tests.Assert(root.idxLong.Remove(rfFirst));
            Tests.Assert(root.idxULong.Remove(rfFirst));
            Tests.Assert(root.idxFloat.Remove(rfFirst));
            Tests.Assert(root.idxDouble.Remove(rfFirst));
            Tests.Assert(root.idxDate.Remove(rfFirst));
            Tests.Assert(root.idxDecimal.Remove(rfFirst));
            Tests.Assert(root.idxGuid.Remove(rfFirst));
            Tests.Assert(root.idxString.Remove(rfFirst));
            db.Commit();
            Tests.Assert(!root.idxBool.Remove(rfFirst));
            Tests.Assert(!root.idxByte.Remove(rfFirst));
            Tests.Assert(!root.idxSByte.Remove(rfFirst));
            Tests.Assert(!root.idxShort.Remove(rfFirst));
            Tests.Assert(!root.idxUShort.Remove(rfFirst));
            Tests.Assert(!root.idxInt.Remove(rfFirst));
            Tests.Assert(!root.idxUInt.Remove(rfFirst));
            Tests.Assert(!root.idxLong.Remove(rfFirst));
            Tests.Assert(!root.idxLongProp.Remove(rfFirst));
            Tests.Assert(!root.idxULong.Remove(rfFirst));
            Tests.Assert(!root.idxFloat.Remove(rfFirst));
            Tests.Assert(!root.idxDouble.Remove(rfFirst));
            Tests.Assert(!root.idxDate.Remove(rfFirst));
            Tests.Assert(!root.idxDecimal.Remove(rfFirst));
            Tests.Assert(!root.idxGuid.Remove(rfFirst));
            Tests.Assert(!root.idxString.Remove(rfFirst));
            db.Commit();
            var e = root.idxLong.GetEnumerator();
            Tests.Assert(e.MoveNext());
            r2 = e.Current;
            Tests.Assert(root.idxLongProp.Remove(r2));
            db.Commit();
            Tests.Assert(!root.idxLongProp.Remove(r2));
        }
    }
}


text:
package org.grobid.service.utils;

import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

public class ErrorHandler {

	public static Response print(String message) {
		System.err.println("Error : "+message);
		return Response.status(Status.INTERNAL_SERVER_ERROR).entity("{\"error\": \""+message+"\"}").build();
	}
}


text:
var browserConfig = require('./browserConfig');
// Select which search module you want
var createSearch = require('./searchModules/google');
// Select which locale module you want
var gc2i18n = require('./localModules/en_US');


text:
package org.fcrepo.camel.examples.osgi;

/**
 * Header constant values
 *
 * @author Aaron Coburn
 */
public final class MessageHeaders {

    public static final String REST_PREFIX = "org.fcrepo.camel.examples.osgi.restPrefix";

    public static final String BASE_URL = "org.fcrepo.camel.examples.osgi.baseUrl";

}


text:
using System;

using Bytes2you.Validation;

using WebFormsMvp;

using WhenItsDone.Services.Contracts;

namespace WhenItsDone.MVP.AccountPages.ManageMVP.UploadProfilePictureMVP
{
    public class UploadProfilePicturePresenter : Presenter<IUploadProfilePictureView>, IUploadProfilePicturePresenter
    {
        private const string UserNotFoundErrorText = "User with Username: {0} was not found.";

        private IUsersAsyncService usersService;

        public UploadProfilePicturePresenter(IUploadProfilePictureView view, IUsersAsyncService usersService)
            : base(view)
        {
            Guard.WhenArgument(usersService, nameof(IUsersAsyncService)).IsNull().Throw();

            this.usersService = usersService;

            base.View.OnInitialState += this.OnInitialState;
            base.View.OnUploadProfilePicture += this.OnUploadProfilePicture;
            base.View.OnUploadProfilePictureFromUrl += this.OnUploadProfilePictureFromUrl;
        }

        public void OnInitialState(object sender, UploadProfilePictureInitialStateEventArgs args)
        {
            Guard.WhenArgument(args, nameof(UploadProfilePictureEventArgs)).IsNull().Throw();
            Guard.WhenArgument(args.LoggedUserUsername, nameof(args.LoggedUserUsername)).IsNullOrEmpty().Throw();

            try
            {
                var foundUserView = this.usersService.GetCurrentUserProfilePicture(args.LoggedUserUsername);
                if (foundUserView != null)
                {
                    base.View.Model.IsSuccessful = true;
                    base.View.Model.CurrentProfilePictureBase64 = foundUserView.ProfilePictureBase64;
                    base.View.Model.CurrentProfilePictureMimeType = foundUserView.ProfilePictureExtension;
                }
                else
                {
                    base.View.Model.IsSuccessful = false;
                    base.View.Model.ResultText = string.Format(UploadProfilePicturePresenter.UserNotFoundErrorText, args.LoggedUserUsername);
                }
            }
            catch (Exception ex)
            {
                base.View.Model.IsSuccessful = false;
                base.View.Model.ResultText = ex.Message;
            }
        }

        public void OnUploadProfilePicture(object sender, UploadProfilePictureEventArgs args)
        {
            Guard.WhenArgument(args, nameof(args)).IsNull().Throw();
            Guard.WhenArgument(args.LoggedUserUsername, nameof(args.LoggedUserUsername)).IsNullOrEmpty().Throw();
            Guard.WhenArgument(args.UploadedFileName, nameof(args.UploadedFileName)).IsNullOrEmpty().Throw();
            Guard.WhenArgument(args.UploadedFile, nameof(args.UploadedFile)).IsNull().Throw();

            try
            {
                var updatedUser = this.usersService.UpdateUserProfilePicture(args.LoggedUserUsername, args.UploadedFileName, args.UploadedFile);
                if (updatedUser == null)
                {
                    throw new ArgumentException("User could not be found.");
                }
                else
                {
                    base.View.Model.IsSuccessful = true;
                    base.View.Model.CurrentProfilePictureBase64 = updatedUser.ProfilePicture.PictureBase64;
                    base.View.Model.CurrentProfilePictureMimeType = updatedUser.ProfilePicture.MimeType;
                    base.View.Model.ResultText = "Successfully updated profile picture";
                }
            }
            catch (Exception ex)
            {
                base.View.Model.IsSuccessful = false;
                base.View.Model.ResultText = ex.Message;
            }
        }

        public void OnUploadProfilePictureFromUrl(object sender, UploadProfilePictureFromUrlEventArgs args)
        {
            Guard.WhenArgument(args, nameof(args)).IsNull().Throw();
            Guard.WhenArgument(args.LoggedUserUsername, nameof(args.LoggedUserUsername)).IsNullOrEmpty().Throw();
            Guard.WhenArgument(args.ProfilePictureUrl, nameof(args.ProfilePictureUrl)).IsNullOrEmpty().Throw();

            try
            {
                var updatedUser = this.usersService.UpdateUserProfilePictureFromUrl(args.LoggedUserUsername, args.ProfilePictureUrl);
                if (updatedUser == null)
                {
                    throw new ArgumentException("User could not be found.");
                }
                else
                {
                    base.View.Model.IsSuccessful = true;
                    base.View.Model.CurrentProfilePictureBase64 = updatedUser.ProfilePicture.PictureBase64;
                    base.View.Model.CurrentProfilePictureMimeType = updatedUser.ProfilePicture.MimeType;
                    base.View.Model.ResultText = "Successfully updated profile picture";
                }
            }
            catch (Exception ex)
            {
                base.View.Model.IsSuccessful = false;
                base.View.Model.ResultText = ex.Message;
            }
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
  ~ Copyright (c) 2010-2017 Evolveum and contributors
  ~
  ~ This work is dual-licensed under the Apache License 2.0
  ~ and European Union Public License. See LICENSE file for details.
  -->

<s:search xmlns:s="http://midpoint.evolveum.com/xml/ns/public/model/scripting-3"
          xmlns:c="http://midpoint.evolveum.com/xml/ns/public/common/common-3">
    <s:type>c:UserType</s:type>
    <s:searchFilter>
        <equal xmlns="http://prism.evolveum.com/xml/ns/public/query-3">
            <path>c:name</path>
            <value>jack</value>
        </equal>
    </s:searchFilter>
    <s:action>
        <s:type>enable</s:type>
    </s:action>
</s:search>