text: ALTER TABLE groups ADD COLUMN sudo_cmds varchar(2000);

redpajama_set_name: RedPajamaGithub


text:
import datetime

from django.utils import timezone
from django_simon import Model, simonize

simonize()

class Poll(Model):
    class Meta:
        required_fields = ('question', 'pub_date')

    def __unicode__(self):
        return self.question

    def was_published_recently(self):
        now = timezone.now()
        return now - datetime.timedelta(days=1) <= self.pub_date < now


text:
function [n,xhist] = FindTimeHistOfEvents(R,event_types,xhist);

% [n,xhist] = FindTimeHistOfEvents(R,event_types,xhist);
%
% Multi-subject saccade time histogram.
%
% Created 1/28/13 by DJ for one-time use.

if nargin<3 || isempty(xhist)
    xhist = 25:50:4000;
end
nEvents = numel(event_types);

% clear n
for iSubj = 1:numel(R) % subject
    for i=1:nEvents % square
        % get
        tb = FindTimeBetweenEvents(R(iSubj).EEG,'TrialStart-D',event_types{i});
        tb2 = FindTimeBetweenEvents(R(iSubj).EEG,'TrialStart-T',event_types{i});
        % combine
        tb(~isnan(tb2)) = tb2(~isnan(tb2));
        % histogram
        n(i,:,iSubj)=hist(tb,xhist)/sum(~isnan(tb));
        % store mean
        meantime(i,iSubj) = nanmean(tb);
    end
end
% average across subjects
n_avg = mean(n,3);

%% Plot
plot(xhist,n_avg'*100)
xlabel('time from Trial Start (ms)');
ylabel('% of trials');
title(sprintf('Histogram of event times in trial\n(mean across %d subjects)',numel(R)))
legend(event_types);
hold on
PlotVerticalLines(mean(meantime,2),'k--');

% %% LSaccade vs. RSaccade
% xhist = 25:50:4000;
% clear n
% for iSubj = 1:9 % subject
%     % get LSaccade
%     tb = FindTimeBetweenEvents(R(iSubj).EEG,'TrialStart-D','LSaccade');
%     tb2 = FindTimeBetweenEvents(R(iSubj).EEG,'TrialStart-T','LSaccade');
%     % combine
%     tb(~isnan(tb2)) = tb2(~isnan(tb2));
%     % histogram
%     n(1,:,iSubj)=hist(tb,xhist)/sum(~isnan(tb));
%
%     % get RSaccade
%     tb = FindTimeBetweenEvents(R(iSubj).EEG,'TrialStart-D','RSaccade');
%     tb2 = FindTimeBetweenEvents(R(iSubj).EEG,'TrialStart-T','RSaccade');
%     % combine
%     tb(~isnan(tb2)) = tb2(~isnan(tb2));
%     % histogram
%     n(2,:,iSubj)=hist(tb,xhist)/sum(~isnan(tb));
% end
% % average across subjects
% n_avg = mean(n,3);
%
% %% Plot
% plot(xhist,n_avg'*100)
% xlabel('time from Trial Start (ms)');
% ylabel('% of trials');
% title(sprintf('Histogram of saccade times in trial\n(mean across 9 subjects)'))
% legend('LSaccade','RSaccade');


text:
<?php

namespace Magestudy\LogRepository\Api;

use Magestudy\LogRepository\Api\Data\LogInterface as ItemInterface;

Interface LogRepositoryInterface
{
    /**
     * Save record.
     *
     * @param ItemInterface $object
     * @return ItemInterface
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function save(ItemInterface $object);

    /**
     * Retrieve record.
     *
     * @param int $id
     * @return ItemInterface
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function getById($id);

    /**
     * Delete record.
     *
     * @param ItemInterface $object
     * @return bool true on success
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function delete(ItemInterface $object);

    /**
     * Delete record by ID.
     *
     * @param int $id
     * @return bool true on success
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function deleteById($id);
}


text:
import React from 'react';
import {connect} from 'react-redux'
import {bindActionCreators} from 'redux';
import callsActions from '../../actions/callsList';

@connect(
  state => ({
    // callsList: state.callsList
  }),
  dispatch => ({
    // actions: bindActionCreators({...callsActions}, dispatch)
  })
)
export default class Page404 extends React.Component {

  render() {

    return (

Error 404

    )
  };
}


text:
package com.forsrc.cxf.server.interceptor;

import com.forsrc.springmvc.restful.login.service.LoginService;
import org.apache.cxf.binding.soap.saaj.SAAJInInterceptor;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.Map;

/**
 * The type Cxf interceptor.
 */
public class CxfInterceptor extends AbstractPhaseInterceptor<Message> {

    private SAAJInInterceptor saajInInterceptor;
    @Autowired
    @Resource(name = "loginService")
    private LoginService loginService;

    /**
     * Instantiates a new Cxf interceptor.
     */
    public CxfInterceptor() {
        super(Phase.PRE_PROTOCOL);
        saajInInterceptor = new SAAJInInterceptor();
        super.getAfter().add(SAAJInInterceptor.class.getName());
    }

    @Override
    public void handleMessage(Message message) {

        System.out.println();
        Iterator<Map.Entry<String, Object>> it = message.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = it.next();
            System.out.println(entry.getKey() + " --> " + (entry.getValue() == null ? "null" : entry.getValue().toString()));
        }

        System.out.println();
        System.out.println();

    }

}


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

namespace WXR
{
	public class Category
	{
		public string NiceName { get; set; }
		public string Parent { get; set; }
		public string Name { get; set; }
	}
}


text:
package com.impos.helpers;

import org.lwjgl.Sys;

/**
 * @author pldmacikowski
 */
public class Clock {

	public static long lastFrame;
	public static long totalTime;
	public static float d = 0;
	public static float multiplier = 1;
	public static boolean paused = false;

	public static long getTime() {
		return Sys.getTime() * 1000 / Sys.getTimerResolution();
	}

	public static float delta() {
		if (paused) {
			return 0;
		} else {
			return d * multiplier;
		}
	}

	public static float TotalTime() {
		return totalTime;
	}

	public static float getMultiplier() {
		return multiplier;
	}

	public static void changeMultiplier(float change) {
		if (multiplier + change > -1 && multiplier + change < 7) {
			multiplier += change;
		}
	}

	public static void setPause(boolean isPause) {
		paused = isPause;
	}

	public static void update() {
		d = getDelta();
		totalTime += d;
	}

	/**
	 * Get Time elapsed from last frame
	 */
	private static float getDelta() {
		long currentTime = getTime();
		int delta = (int) (currentTime - lastFrame);
		lastFrame = getTime();
		//Windows OS issue hotfix - moving a windows does freezes
		if(delta * 0.001f > 0.05f) {
			return 0.05f;
		}
		return delta * 0.001f;
	}

}


text:
package com.iluwatar.facade.service;

/**
 *
 * DwarvenTunnelDigger is one of the goldmine subsystems.
 *
 */
public class DwarvenTunnelDigger extends AbsDwarvenMineWorker {

	@Override
	public void work() {
		System.out.println(name() + " creates another promising tunnel.");
	}

	@Override
	public String name() {
		return "Dwarven tunnel digger";
	}

}


text:
identifier: MIR:00000357
name: SUPFAM
description: SUPERFAMILY provides structural, functional and evolutionary information for proteins from all completely sequenced genomes, and large sequence collections such as UniProt.
prefix: supfam
pattern: ^\w+$
prefixed: 0
local_id: SSF57615
synonyms:
 - SUPERFAMILY
resources:
 - identifier: MIR:00100454
   accessurl: http://supfam.org/SUPERFAMILY/cgi-bin/scop.cgi?ipid=${lid}
   keyword: cellulose binding domain
   description: SUPFAM at MRC and University of Bristol
   homepage: http://supfam.org/SUPERFAMILY/
   institution: MRC Laboratory of Molecular Biology, Cambridge
   location: UK
   official: false
---


text:
package haki

import (
	"errors"
	"github.com/rjansen/l"
)

const (
	ContentTypeHeader    = "Content-Type"
	ContentLengthHeader  = "Content-Length"
	AcceptHeader         = "Accept"
	RequestContextHeader = "X-Request-Context"
	RequestIDHeader      = "X-Request-Id"
	AuthorizationHeader  = "Authorization"
)

var (
	ErrInvalidContentType = errors.New("Invalid ContentType. Only: aplication/json, application/octet-stream are valid")
	ErrInvalidAccept      = errors.New("Invalid Accept. Only: aplication/json, application/octet-stream are valid")
)

//SetupAll calls all provided setup functions and return all raised errors
func SetupAll(setupFuncs ...SetupFunc) []error {
	var errs []error
	for i, v := range setupFuncs {
		if err := v(); err != nil {
			l.Warn("contex.SetupSilent",
				l.Int("index", i),
				l.Struct("func", v),
				l.Err(err),
			)
			errs = append(errs, err)
		}
	}
	return errs
}

//Setup calls the provided setup functions and return at the first raised error
func Setup(setupFuncs ...SetupFunc) error {
	for i, v := range setupFuncs {
		if err := v(); err != nil {
			l.Error("contex.Setup",
				l.Int("index", i),
				l.Struct("func", v),
				l.Err(err),
			)
			return err
		}
	}
	return nil
}


text:
<include file="Public/header"/>

			<include file="Public/left"/>

				<include file="Public/headernav"/>

{$msgtitle}

									菜单信息

<form action="" role="form" id="form2" novalidate="novalidate" method="post">

			该缺货用户的ID

		<input type="text" placeholder="填写该缺货用户的ID" class="form-control" value="{$data.user_id}" id="user_id" name="user_id">

			用户邮箱

		<input type="text" placeholder="填写用户邮箱" class="form-control" value="{$data.email}" id="email" name="email">

			用户姓名

		<input type="text" placeholder="填写用户姓名" class="form-control" value="{$data.link_man}" id="link_man" name="link_man">

			用户电话

		<input type="text" placeholder="填写用户电话" class="form-control" value="{$data.tel}" id="tel" name="tel">

			商品描述

		<input type="text" placeholder="填写商品描述" class="form-control" value="{$data.goods_desc}" id="goods_desc" name="goods_desc">

			商品数量

		<input type="text" placeholder="填写商品数量" class="form-control" value="{$data.goods_number}" id="goods_number" name="goods_number">

			缺货时间

		<input type="text" placeholder="填写缺货时间" class="form-control" value="{$data.booking_time}" id="booking_time" name="booking_time">

			是否处理

		<input type="radio" value="1" name="is_dispose" id="id_yes" <if condition="$data.is_dispose eq 1">checked="checked"</if> >

				是

		<input type="radio" value="0" name="is_dispose" id="id_no" <if condition="$data.is_dispose eq 0">checked="checked"</if> >

				否

			登记缺货的管理员

		<input type="text" placeholder="填写登记缺货的管理员" class="form-control" value="{$data.dispose_user}" id="dispose_user" name="dispose_user">

			处理时间

		<input type="text" placeholder="填写处理时间" class="form-control" value="{$data.dispose_time}" id="dispose_time" name="dispose_time">

			管理员的备注

		<input type="text" placeholder="填写处理时间" class="form-control" value="{$data.dispose_note}" id="dispose_note" name="dispose_note">

	<input type="hidden"  value="{$data.id}" name="id">
	<button class="btn btn-primary btn-wide pull-left" type="submit">
		提交
	</button>

</form>

           <include file="Public/footer"/>

         <include file="Public/javascript"/>


text:
/*	$NetBSD: ieee80211_amrr.c,v 1.2 2007/12/11 12:40:10 lukem Exp $	*/
/*	$OpenBSD: ieee80211_amrr.c,v 1.1 2006/06/17 19:07:19 damien Exp $	*/

/*-
 * Copyright (c) 2006
 *	Damien Bergamini <damien.bergamini@free.fr>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: ieee80211_amrr.c,v 1.2 2007/12/11 12:40:10 lukem Exp $");

#include <sys/param.h>
#include <sys/kernel.h>
#include <sys/socket.h>
#include <sys/sysctl.h>

#include <net/if.h>
#include <net/if_media.h>

#ifdef INET
#include <netinet/in.h>
#include <netinet/if_ether.h>
#endif

#include <net80211/ieee80211.h>
#include <net80211/ieee80211_var.h>
#include <net80211/ieee80211_amrr.h>

#define is_success(amn)	\
	((amn)->amn_retrycnt < (amn)->amn_txcnt / 10)
#define is_failure(amn)	\
	((amn)->amn_retrycnt > (amn)->amn_txcnt / 3)
#define is_enough(amn)		\
	((amn)->amn_txcnt > 10)
#define is_min_rate(ni)		\
	((ni)->ni_txrate == 0)
#define is_max_rate(ni)		\
	((ni)->ni_txrate == (ni)->ni_rates.rs_nrates - 1)
#define increase_rate(ni)	\
	((ni)->ni_txrate++)
#define decrease_rate(ni)	\
	((ni)->ni_txrate--)
#define reset_cnt(amn)		\
	do { (amn)->amn_txcnt = (amn)->amn_retrycnt = 0; } while (0)

void
ieee80211_amrr_node_init(struct ieee80211_amrr *amrr,
    struct ieee80211_amrr_node *amn)
{
	amn->amn_success = 0;
	amn->amn_recovery = 0;
	amn->amn_txcnt = amn->amn_retrycnt = 0;
	amn->amn_success_threshold = amrr->amrr_min_success_threshold;
}

/*
 * Update ni->ni_txrate.
 */
void
ieee80211_amrr_choose(struct ieee80211_amrr *amrr, struct ieee80211_node *ni,
    struct ieee80211_amrr_node *amn)
{
	int need_change = 0;

	if (is_success(amn) && is_enough(amn)) {
		amn->amn_success++;
		if (amn->amn_success >= amn->amn_success_threshold &&
		    !is_max_rate(ni)) {
			amn->amn_recovery = 1;
			amn->amn_success = 0;
			increase_rate(ni);
			IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_DEBUG,
			    "AMRR increasing rate %d (txcnt=%d retrycnt=%d)\n",
			    ni->ni_rates.rs_rates[ni->ni_txrate] &
				IEEE80211_RATE_VAL,
			    amn->amn_txcnt, amn->amn_retrycnt);
			need_change = 1;
		} else {
			amn->amn_recovery = 0;
		}
	} else if (is_failure(amn)) {
		amn->amn_success = 0;
		if (!is_min_rate(ni)) {
			if (amn->amn_recovery) {
				amn->amn_success_threshold *= 2;
				if (amn->amn_success_threshold >
				    amrr->amrr_max_success_threshold)
					amn->amn_success_threshold =
					    amrr->amrr_max_success_threshold;
			} else {
				amn->amn_success_threshold =
				    amrr->amrr_min_success_threshold;
			}
			decrease_rate(ni);
			IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_DEBUG,
			    "AMRR decreasing rate %d (txcnt=%d retrycnt=%d)\n",
			    ni->ni_rates.rs_rates[ni->ni_txrate] &
				IEEE80211_RATE_VAL,
			    amn->amn_txcnt, amn->amn_retrycnt);
			need_change = 1;
		}
		amn->amn_recovery = 0;
	}

	if (is_enough(amn) || need_change)
		reset_cnt(amn);
}


text:
//
//  AppDelegate.m
//  ExampleOktyPod
//
//  Created by Mathias on 12/3/14.
//  Copyright (c) 2014 Mathias. All rights reserved.
//

#import "AppDelegate.h"

#import "InitialViewController.h"
#import "RootViewController.h"
#import "SFUserAccountManager.h"
#import "SFAuthenticationManager.h"
#import "SFPushNotificationManager.h"
#import "SFDefaultUserManagementViewController.h"
#import "SFOAuthInfo.h"
#import "SFLogger.h"

// Fill these in when creating a new Connected Application on Force.com
static NSString * const RemoteAccessConsumerKey = @"3MVG9Iu66FKeHhINkB1l7xt7kR8czFcCTUhgoA8Ol2Ltf1eYHOU4SqQRSEitYFDUpqRWcoQ2.dBv_a1Dyu5xa";
static NSString * const OAuthRedirectURI        = @"testsfdc:///mobilesdk/detect/oauth/done";

@interface AppDelegate() <SFAuthenticationManagerDelegate, SFUserAccountManagerDelegate>
/**
 * Success block to call when authentication completes.
 */
@property (nonatomic, copy) SFOAuthFlowSuccessCallbackBlock initialLoginSuccessBlock;

/**
 * Failure block to calls if authentication fails.
 */
@property (nonatomic, copy) SFOAuthFlowFailureCallbackBlock initialLoginFailureBlock;

/**
 * Convenience method for setting up the main UIViewController and setting self.window's rootViewController
 * property accordingly.
 */
- (void)setupRootViewController;

/**
 * (Re-)sets the view state when the app first loads (or post-logout).
 */
- (void)initializeAppViewState;
@end

@implementation AppDelegate

@synthesize window = _window;
@synthesize initialLoginSuccessBlock = _initialLoginSuccessBlock;
@synthesize initialLoginFailureBlock = _initialLoginFailureBlock;

- (id)init
{
    self = [super init];
    if (self) {
        [SFLogger setLogLevel:SFLogLevelDebug];

        // These SFAccountManager settings are the minimum required to identify the Connected App.
        [SFUserAccountManager sharedInstance].oauthClientId = RemoteAccessConsumerKey;
        [SFUserAccountManager sharedInstance].oauthCompletionUrl = OAuthRedirectURI;
        [SFUserAccountManager sharedInstance].scopes = [NSSet setWithObjects:@"web", @"api", nil];

        // Auth manager delegate, for receiving logout and login host change events.
        [[SFAuthenticationManager sharedManager] addDelegate:self];
        [[SFUserAccountManager sharedInstance] addDelegate:self];

        // Blocks to execute once authentication has completed.  You could define these at the different boundaries where
        // authentication is initiated, if you have specific logic for each case.
        __weak AppDelegate *weakSelf = self;
        self.initialLoginSuccessBlock = ^(SFOAuthInfo *info) {
            [weakSelf setupRootViewController];
        };
        self.initialLoginFailureBlock = ^(SFOAuthInfo *info, NSError *error) {
            [[SFAuthenticationManager sharedManager] logout];
        };
    }

    return self;
}

- (void)dealloc
{
    [[SFAuthenticationManager sharedManager] removeDelegate:self];
    [[SFUserAccountManager sharedInstance] removeDelegate:self];
}

#pragma mark - App delegate lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self initializeAppViewState];

    //
    // If you wish to register for push notifications, uncomment the line below.  Note that,
    // if you want to receive push notifications from Salesforce, you will also need to
    // implement the application:didRegisterForRemoteNotificationsWithDeviceToken: method (below).
    //
    //[[SFPushNotificationManager sharedInstance] registerForRemoteNotifications];
    //

    [[SFAuthenticationManager sharedManager] loginWithCompletion:self.initialLoginSuccessBlock failure:self.initialLoginFailureBlock];

    return YES;
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    //
    // Uncomment the code below to register your device token with the push notification manager
    //
    //[[SFPushNotificationManager sharedInstance] didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
    //if ([SFAccountManager sharedInstance].credentials.accessToken != nil) {
    //    [[SFPushNotificationManager sharedInstance] registerForSalesforceNotifications];
    //}
    //
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    // Respond to any push notification registration errors here.
}

#pragma mark - Private methods

- (void)initializeAppViewState
{
    self.window.rootViewController = [[InitialViewController alloc] initWithNibName:nil bundle:nil];
    [self.window makeKeyAndVisible];
}

- (void)setupRootViewController
{
    RootViewController *rootVC = [[RootViewController alloc] initWithNibName:nil bundle:nil];
    UINavigationController *navVC = [[UINavigationController alloc] initWithRootViewController:rootVC];
    self.window.rootViewController = navVC;
}

#pragma mark - SFAuthenticationManagerDelegate

- (void)authManagerDidLogout:(SFAuthenticationManager *)manager
{
    [self log:SFLogLevelDebug msg:@"SFAuthenticationManager logged out.  Resetting app."];
    [self initializeAppViewState];

    // Multi-user pattern:
    // - If there are two or more existing accounts after logout, let the user choose the account
    //   to switch to.
    // - If there is one existing account, automatically switch to that account.
    // - If there are no further authenticated accounts, present the login screen.
    //
    // Alternatively, you could just go straight to re-initializing your app state, if you know
    // your app does not support multiple accounts.  The logic below will work either way.
    NSArray *allAccounts = [SFUserAccountManager sharedInstance].allUserAccounts;
    if ([allAccounts count] > 1) {
        SFDefaultUserManagementViewController *userSwitchVc = [[SFDefaultUserManagementViewController alloc] initWithCompletionBlock:^(SFUserManagementAction action) {
            [self.window.rootViewController dismissViewControllerAnimated:YES completion:NULL];
        }];
        [self.window.rootViewController presentViewController:userSwitchVc animated:YES completion:NULL];
    } else if ([[SFUserAccountManager sharedInstance].allUserAccounts count] == 1) {
        [SFUserAccountManager sharedInstance].currentUser = [[SFUserAccountManager sharedInstance].allUserAccounts objectAtIndex:0];
        [[SFAuthenticationManager sharedManager] loginWithCompletion:self.initialLoginSuccessBlock
                                                             failure:self.initialLoginFailureBlock];
    } else {
        [[SFAuthenticationManager sharedManager] loginWithCompletion:self.initialLoginSuccessBlock
                                                             failure:self.initialLoginFailureBlock];
    }
}

#pragma mark - SFUserAccountManagerDelegate

- (void)userAccountManager:(SFUserAccountManager *)userAccountManager
         didSwitchFromUser:(SFUserAccount *)fromUser
                    toUser:(SFUserAccount *)toUser
{
    [self log:SFLogLevelDebug format:@"SFUserAccountManager changed from user %@ to %@.  Resetting app.",
     fromUser.userName, toUser.userName];
    [self initializeAppViewState];
    [[SFAuthenticationManager sharedManager] loginWithCompletion:self.initialLoginSuccessBlock failure:self.initialLoginFailureBlock];
}

@end


text:
using System;
using System.Text;

#if PORTABLE
using EncoderReplacementFallback = Portable.Text.EncoderReplacementFallback;
using DecoderReplacementFallback = Portable.Text.DecoderReplacementFallback;
using EncoderExceptionFallback = Portable.Text.EncoderExceptionFallback;
using DecoderExceptionFallback = Portable.Text.DecoderExceptionFallback;
using EncoderFallbackException = Portable.Text.EncoderFallbackException;
using DecoderFallbackException = Portable.Text.DecoderFallbackException;
using DecoderFallbackBuffer = Portable.Text.DecoderFallbackBuffer;
using DecoderFallback = Portable.Text.DecoderFallback;
using Encoding = Portable.Text.Encoding;
using Encoder = Portable.Text.Encoder;
using Decoder = Portable.Text.Decoder;
#endif

namespace MimeKit.Utils {
	static class ParseUtils
	{
		public static void ValidateArguments (ParserOptions options, byte[] buffer, int startIndex, int length)
		{
			if (options == null)
				throw new ArgumentNullException ("options");

			if (buffer == null)
				throw new ArgumentNullException ("buffer");

			if (startIndex < 0 || startIndex > buffer.Length)
				throw new ArgumentOutOfRangeException ("startIndex");

			if (length < 0 || length > (buffer.Length - startIndex))
				throw new ArgumentOutOfRangeException ("length");
		}

		public static void ValidateArguments (ParserOptions options, byte[] buffer, int startIndex)
		{
			if (options == null)
				throw new ArgumentNullException ("options");

			if (buffer == null)
				throw new ArgumentNullException ("buffer");

			if (startIndex < 0 || startIndex > buffer.Length)
				throw new ArgumentOutOfRangeException ("startIndex");
		}

		public static void ValidateArguments (ParserOptions options, byte[] buffer)
		{
			if (options == null)
				throw new ArgumentNullException ("options");

			if (buffer == null)
				throw new ArgumentNullException ("buffer");
		}

		public static void ValidateArguments (ParserOptions options, string text)
		{
			if (options == null)
				throw new ArgumentNullException ("options");

			if (text == null)
				throw new ArgumentNullException ("text");
		}

		public static void ValidateArguments (byte[] buffer, int startIndex, int length)
		{
			if (buffer == null)
				throw new ArgumentNullException ("buffer");

			if (startIndex < 0 || startIndex > buffer.Length)
				throw new ArgumentOutOfRangeException ("startIndex");

			if (length < 0 || length > (buffer.Length - startIndex))
				throw new ArgumentOutOfRangeException ("length");
		}

		public static bool TryParseInt32 (byte[] text, ref int index, int endIndex, out int value)
		{
			int startIndex = index;

			value = 0;

			while (index < endIndex && text[index] >= (byte) '0' && text[index] <= (byte) '9') {
				int digit = text[index] - (byte) '0';

				if (value > int.MaxValue / 10) {
					// integer overflow
					return false;
				}

				if (value == int.MaxValue / 10 && digit > int.MaxValue % 10) {
					// integer overflow
					return false;
				}

				value = (value * 10) + digit;
				index++;
			}

			return index > startIndex;
		}

		public static bool SkipWhiteSpace (byte[] text, ref int index, int endIndex)
		{
			int startIndex = index;

			while (index < endIndex && text[index].IsWhitespace ())
				index++;

			return index > startIndex;
		}

		public static bool SkipComment (byte[] text, ref int index, int endIndex)
		{
			bool escaped = false;
			int depth = 1;

			index++;

			while (index < endIndex && depth > 0) {
				if (text[index] == (byte) '\\') {
					escaped = !escaped;
				} else if (!escaped) {
					if (text[index] == (byte) '(')
						depth++;
					else if (text[index] == (byte) ')')
						depth--;
					escaped = false;
				} else {
					escaped = false;
				}

				index++;
			}

			return depth == 0;
		}

		public static bool SkipCommentsAndWhiteSpace (byte[] text, ref int index, int endIndex, bool throwOnError)
		{
			SkipWhiteSpace (text, ref index, endIndex);

			while (index < endIndex && text[index] == (byte) '(') {
				int startIndex = index;

				if (!SkipComment (text, ref index, endIndex)) {
					if (throwOnError)
						throw new ParseException (string.Format ("Incomplete comment token at offset {0}", startIndex), startIndex, index);

					return false;
				}

				SkipWhiteSpace (text, ref index, endIndex);
			}

			return true;
		}

		public static bool SkipQuoted (byte[] text, ref int index, int endIndex, bool throwOnError)
		{
			int startIndex = index;
			bool escaped = false;

			// skip over leading '"'
			index++;

			while (index < endIndex) {
				if (text[index] == (byte) '\\') {
					escaped = !escaped;
				} else if (!escaped) {
					if (text[index] == (byte) '"')
						break;
				} else {
					escaped = false;
				}

				index++;
			}

			if (index >= endIndex || text[index] != (byte) '"') {
				if (throwOnError)
					throw new ParseException (string.Format ("Incomplete quoted-string token at offset {0}", startIndex), startIndex, index);

				return false;
			}

			index++;

			return true;
		}

		public static bool SkipAtom (byte[] text, ref int index, int endIndex)
		{
			int start = index;

			while (index < endIndex && text[index].IsAtom ())
				index++;

			return index > start;
		}

		public static bool SkipToken (byte[] text, ref int index, int endIndex)
		{
			int start = index;

			while (index < endIndex && text[index].IsToken ())
				index++;

			return index > start;
		}

		public static bool SkipWord (byte[] text, ref int index, int endIndex, bool throwOnError)
		{
			if (text[index] == (byte) '"')
				return SkipQuoted (text, ref index, endIndex, throwOnError);

			if (text[index].IsAtom ())
				return SkipAtom (text, ref index, endIndex);

			return false;
		}

		static bool IsSentinel (byte c, byte[] sentinels)
		{
			for (int i = 0; i < sentinels.Length; i++) {
				if (c == sentinels[i])
					return true;
			}

			return false;
		}

		static bool TryParseDotAtom (byte[] text, ref int index, int endIndex, byte[] sentinels, bool throwOnError, string tokenType, out string dotatom)
		{
			var token = new StringBuilder ();
			int startIndex = index;
			int comment;

			dotatom = null;

			do {
				if (!text[index].IsAtom ()) {
					if (throwOnError)
						throw new ParseException (string.Format ("Invalid {0} token at offset {1}", tokenType, startIndex), startIndex, index);

					return false;
				}

				int start = index;
				while (index < endIndex && text[index].IsAtom ())
					index++;

				try {
					token.Append (CharsetUtils.UTF8.GetString (text, start, index - start));
				} catch (DecoderFallbackException ex) {
					if (throwOnError)
						throw new ParseException ("Internationalized domains may only contain UTF-8 characters.", start, start, ex);

					return false;
				}

				comment = index;
				if (!SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
					return false;

				if (index >= endIndex || text[index] != (byte) '.') {
					index = comment;
					break;
				}

				// skip over the '.'
				index++;

				if (!SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
					return false;

				// allow domains to end with a '.', but strip it off
				if (index >= endIndex || IsSentinel (text[index], sentinels))
					break;

				token.Append ('.');
			} while (true);

			dotatom = token.ToString ();

			return true;
		}

		static bool TryParseDomainLiteral (byte[] text, ref int index, int endIndex, bool throwOnError, out string domain)
		{
			var token = new StringBuilder ("[");
			int startIndex = index++;

			domain = null;

			SkipWhiteSpace (text, ref index, endIndex);

			do {
				while (index < endIndex && text[index].IsDomain ()) {
					token.Append ((char) text[index]);
					index++;
				}

				SkipWhiteSpace (text, ref index, endIndex);

				if (index >= endIndex) {
					if (throwOnError)
						throw new ParseException (string.Format ("Incomplete domain literal token at offset {0}", startIndex), startIndex, index);

					return false;
				}

				if (text[index] == (byte) ']')
					break;

				if (!text[index].IsDomain ()) {
					if (throwOnError)
						throw new ParseException (string.Format ("Invalid domain literal token at offset {0}", startIndex), startIndex, index);

					return false;
				}
			} while (true);

			token.Append (']');
			index++;

			domain = token.ToString ();

			return true;
		}

		public static bool TryParseDomain (byte[] text, ref int index, int endIndex, byte[] sentinels, bool throwOnError, out string domain)
		{
			if (text[index] == (byte) '[')
				return TryParseDomainLiteral (text, ref index, endIndex, throwOnError, out domain);

			return TryParseDotAtom (text, ref index, endIndex, sentinels, throwOnError, "domain", out domain);
		}
	}
}


text:
package com.hazelcast.jet.elastic;

import com.hazelcast.function.SupplierEx;
import com.hazelcast.jet.JetInstance;
import com.hazelcast.jet.JetTestInstanceFactory;
import com.hazelcast.jet.config.JetConfig;
import com.hazelcast.jet.elastic.CommonElasticSinksTest.TestItem;
import com.hazelcast.jet.pipeline.Pipeline;
import com.hazelcast.jet.pipeline.Sink;
import com.hazelcast.jet.pipeline.test.TestSources;
import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.support.WriteRequest.RefreshPolicy;
import org.elasticsearch.client.RestClientBuilder;
import org.junit.After;
import org.junit.Test;
import org.testcontainers.elasticsearch.ElasticsearchContainer;

import java.io.IOException;

import static com.hazelcast.jet.elastic.ElasticClients.client;
import static com.hazelcast.jet.elastic.ElasticSupport.PORT;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

public class AuthElasticSinksTest extends BaseElasticTest {

    private final JetTestInstanceFactory factory = new JetTestInstanceFactory();

    @After
    public void afterClass() throws Exception {
        factory.terminateAll();
    }

    @Override
    protected SupplierEx<RestClientBuilder> elasticClientSupplier() {
        return ElasticSupport.secureElasticClientSupplier();
    }

    @Override
    protected JetInstance createJetInstance() {
        return factory.newMember(new JetConfig());
    }

    @Test
    public void given_authenticatedClient_whenWriteToElasticSink_thenFinishSuccessfully() throws IOException {
        Sink<TestItem> elasticSink = new ElasticSinkBuilder<>()
                .clientFn(elasticClientSupplier())
                .bulkRequestFn(() -> new BulkRequest().setRefreshPolicy(RefreshPolicy.IMMEDIATE))
                .mapToRequestFn((TestItem item) -> new IndexRequest("my-index").source(item.asMap()))
                .build();

        Pipeline p = Pipeline.create();
        p.readFrom(TestSources.items(new TestItem("id", "Frantisek")))
         .writeTo(elasticSink);

        submitJob(p);

        assertSingleDocument();
    }

    @Test
    public void given_clientWithWrongPassword_whenWriteToElasticSink_thenFailWithAuthenticationException() {
        ElasticsearchContainer container = ElasticSupport.secureElastic.get();
        String containerIp = container.getContainerIpAddress();
        Integer port = container.getMappedPort(PORT);

        Sink<TestItem> elasticSink = new ElasticSinkBuilder<>()
                .clientFn(() -> client("elastic", "WrongPassword", containerIp, port))
                .bulkRequestFn(() -> new BulkRequest().setRefreshPolicy(RefreshPolicy.IMMEDIATE))
                .mapToRequestFn((TestItem item) -> new IndexRequest("my-index").source(item.asMap()))
                .retries(0)
                .build();

        Pipeline p = Pipeline.create();
        p.readFrom(TestSources.items(new TestItem("id", "Frantisek")))
         .writeTo(elasticSink);

        assertThatThrownBy(() -> submitJob(p))
                .hasRootCauseInstanceOf(ElasticsearchStatusException.class)
                .hasStackTraceContaining("failed to authenticate user [elastic]");
    }

    @Test
    public void given_clientWithoutAuthentication_whenWriteToElasticSink_thenFailWithAuthenticationException() {
        ElasticsearchContainer container = ElasticSupport.secureElastic.get();
        String containerIp = container.getContainerIpAddress();
        Integer port = container.getMappedPort(PORT);

        Sink<TestItem> elasticSink = new ElasticSinkBuilder<>()
                .clientFn(() -> client(containerIp, port))
                .bulkRequestFn(() -> new BulkRequest().setRefreshPolicy(RefreshPolicy.IMMEDIATE))
                .mapToRequestFn((TestItem item) -> new IndexRequest("my-index").source(item.asMap()))
                .retries(0)
                .build();

        Pipeline p = Pipeline.create();
        p.readFrom(TestSources.items(new TestItem("id", "Frantisek")))
         .writeTo(elasticSink);

        assertThatThrownBy(() -> submitJob(p))
                .hasRootCauseInstanceOf(ElasticsearchStatusException.class)
                .hasStackTraceContaining("missing authentication credentials");
    }

}


text:
FROM gazebo:gzserver4-trusty
# install gazebo packages
RUN apt-get update && apt-get install -q -y \
    libgazebo4-dev=4.1.3-1* \
    && rm -rf /var/lib/apt/lists/*


text:
package bftsmart.demo.bftmapjunit;

import static org.junit.Assert.*;

import java.io.IOException;
import java.util.HashMap;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import bftsmart.demo.bftmap.BFTMap;

/**
 *
 * @author Marcel Santos
 *
 */
public class KVClientTest {

	private static Process replica0;
	private static Process replica1;
	private static Process replica2;
	private static Process replica3;
	private static String[] command = new String[5];

	@BeforeClass
	public static void startServers() {
		try {
			System.out.println("Starting the servers");
			command[0] = "java";
			command[1] = "-cp";
			command[2] = "bin/BFT-SMaRt.jar:lib/slf4j-api-1.5.8.jar:lib/slf4j-jdk14-1.5.8.jar:lib/netty-3.1.1.GA.jar:lib/commons-codec-1.5.jar";
			command[3] = "bftsmart.demo.bftmap.BFTMapServer";
			command[4] = "0";

			replica0 = new ProcessBuilder(command).redirectErrorStream(true).start();
			ConsoleLogger log0 = new ConsoleLogger();;
			log0.setIn(replica0.getInputStream());
			log0.setOut(System.out);
			log0.setIndex("0");
			log0.start();
			Thread.sleep(2000);
			command[4] = "1";
			replica1 = new ProcessBuilder(command).redirectErrorStream(true).start();
			ConsoleLogger log1 = new ConsoleLogger();;
			log1.setIn(replica1.getInputStream());
			log1.setOut(System.out);
			log1.setIndex("1");
			log1.start();
			Thread.sleep(2000);
			command[4] = "2";
			replica2 = new ProcessBuilder(command).redirectErrorStream(true).start();
			ConsoleLogger log2 = new ConsoleLogger();;
			log2.setIn(replica2.getInputStream());
			log2.setOut(System.out);
			log2.setIndex("2");
			log2.start();
			Thread.sleep(2000);
			command[4] = "3";
			replica3 = new ProcessBuilder(command).redirectErrorStream(true).start();
			ConsoleLogger log3 = new ConsoleLogger();;
			log3.setIn(replica3.getInputStream());
			log3.setOut(System.out);
			log3.setIndex("3");
			log3.start();
		    System.out.println("Servers started");

		} catch(IOException ioe) {
			System.out.println("Exception during BFTMapInteractiveClient test: ");
			System.out.println(ioe.getMessage());
		} catch(InterruptedException ie) {
			System.out.println("Exception during Thread sleep: " + ie.getMessage());
		}
	}

	@AfterClass
	public static void stopServers() throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, IOException  {
		System.out.println("Stopping servers");
		replica0.destroy();
		replica1.destroy();
		replica2.destroy();
		replica3.destroy();
		System.out.println("Servers stopped");
	}

	/**
	 * Test regular case where there is the creation of a table, insert of
	 * data and search for size of the table.
	 * No servers are killed nor behaves different than expected.
	 */
	@Test
	public void testRegularCase() {
		try{
			Thread.sleep(1000);
			BFTMap bftMap = new BFTMap(1001);
			bftMap.put("TestTable1", new HashMap<String,byte[]>());
			bftMap.putEntry("TestTable1", "key1", "value1".getBytes());
			assertEquals("Main table size should be 1", 1, bftMap.size1("TestTable1"));

			for(int i = 0; i < 100; i++) {
				String key = "key" + (2+i);
				String value = "value" + (2+i);
				bftMap.putEntry("TestTable1", key, value.getBytes());
			}
			assertEquals("Main table size should be 101", 101, bftMap.size1("TestTable1"));

			bftMap.putEntry("TestTable1", "key102", "value102".getBytes());
			assertEquals("Main table size should be 102", 102, bftMap.size1("TestTable1"));

		} catch(InterruptedException ie) {
			System.out.println("Exception during Thread sleep: " + ie.getMessage());
		}
	}

	/**
	 * - Crate table;
	 * - Insert data;
	 * - Kills a replica that is not a leader;
	 * - Insert data;
	 * - Verify if the size of the table is correct.
	 */
	@Test
	public void testStopNonLeader() {
		try{
			Thread.sleep(1000);
			BFTMap bftMap = new BFTMap(1001);
			bftMap.put("TestTable2", new HashMap<String,byte[]>());
			bftMap.putEntry("TestTable2", "key1", "value1".getBytes());
			assertEquals("Main table size should be 1", 1, bftMap.size1("TestTable2"));

			for(int i = 0; i < 200; i++) {
				String key = "key" + (2+i);
				String value = "value" + (2+i);
				bftMap.putEntry("TestTable2", key, value.getBytes());
			}
			assertEquals("Main table size should be 201", 201, bftMap.size1("TestTable2"));

			replica2.destroy(); // Killing a non-leader replica, replica2
			for(int i = 0; i < 200; i++) {
				String key = "key" + (202+i);
				String value = "value" + (202+i);
				bftMap.putEntry("TestTable2", key, value.getBytes());
			}
			assertEquals("Main table size should be 401", 401, bftMap.size1("TestTable2"));

		} catch(InterruptedException ie) {
			System.out.println("Exception during Thread sleep: " + ie.getMessage());
		}
	}

	/**
	 * This test insert and retrieve data.
	 * During this process a replica that is not the leader is killed.
	 * After that the replica is started back.
	 * During the whole process messages keep being sent, to test if
	 * the application works as expected.
	 */
	@Test
	public void testStopAndStartNonLeader() {
		try{
			Thread.sleep(5000);
			BFTMap bftMap = new BFTMap(1001);
			Thread.sleep(1000);
			bftMap.put("TestTable3", new HashMap<String,byte[]>());

			for(int i = 0; i < 65; i++) {
				String key = "key" + (1+i);
				String value = "value" + (1+i);
				System.out.println(bftMap.putEntry("TestTable3", key, value.getBytes()));
			}
			assertEquals("Main table size should be 65", 65, bftMap.size1("TestTable3"));

			replica1.destroy(); // Killing a non-leader replica, replica2
			for(int i = 0; i < 35; i++) {
				String key = "key" + (66+i);
				String value = "value" + (66+i);
				System.out.println(bftMap.putEntry("TestTable3", key, value.getBytes()));
			}
			assertEquals("Main table size should be 100", 100, bftMap.size1("TestTable3"));

			command[4] = "1";
			replica1 = new ProcessBuilder(command).redirectErrorStream(true).start(); // Starting replica2 back
			ConsoleLogger log1 = new ConsoleLogger();;
			log1.setIn(replica1.getInputStream());
			log1.setOut(System.out);
			log1.setIndex("11");
			log1.start();

			System.out.println("---------Sleep1: " + new java.util.Date());
			Thread.sleep(20000);
			System.out.println("---------Wakeup1: " + new java.util.Date());

			for(int i = 0; i < 35; i++) {
				String key = "key" + (101+i);
				String value = "value" + (101+i);
				System.out.println(bftMap.putEntry("TestTable3", key, value.getBytes()));
			}
			assertEquals("Main table size should be 135", 135, bftMap.size1("TestTable3"));

			System.out.println("---------Sleep2: " + new java.util.Date());
			Thread.sleep(10000);
			System.out.println("---------Wakeup2: " + new java.util.Date());

			replica2.destroy(); // Killing another non-leader replica, replica3

			for(int i = 0; i < 35; i++) {
				String key = "key" + (136+i);
				String value = "value" + (136+i);
				System.out.println(bftMap.putEntry("TestTable3", key, value.getBytes()));
			}
			assertEquals("Main table size should be 170", 170, bftMap.size1("TestTable3"));

		} catch(InterruptedException ie) {
			System.out.println("Exception during Thread sleep: " + ie.getMessage());
		} catch(IOException ioe) {
			System.out.println("Exception when starting replica 2: " + ioe.getMessage());
		}
	}

	/**
	 * - Crate table;
	 * - Insert data;
	 * - Kills the leader replica;
	 * - Insert data;
	 * - Verify if the size of the table is correct.
	 */
	@Test
	public void testStopLeader() {
		try{
			Thread.sleep(1000);
			BFTMap bftMap = new BFTMap(1001);
			Thread.sleep(1000);
			bftMap.put("TestTable4", new HashMap<String,byte[]>());
			bftMap.putEntry("TestTable4", "key1", "value1".getBytes());
			assertEquals("Main table size should be 1", 1, bftMap.size1("TestTable4"));

			for(int i = 0; i < 200; i++) {
				String key = "key" + (2+i);
				String value = "value" + (2+i);
				bftMap.putEntry("TestTable4", key, value.getBytes());
			}
			assertEquals("Main table size should be 201", 201, bftMap.size1("TestTable4"));

			replica0.destroy(); // Killing the leader, replica 0

			for(int i = 0; i < 200; i++) {
				String key = "key" + (202+i);
				String value = "value" + (202+i);
				bftMap.putEntry("TestTable4", key, value.getBytes());
			}
			assertEquals("Main table size should be 401", 401, bftMap.size1("TestTable4"));

		} catch(InterruptedException ie) {
			System.out.println("Exception during Thread sleep: " + ie.getMessage());
		}
	}

	/**
	 * - Crate table;
	 * - Insert data;
	 * - Kills the leader replica;
	 * - Insert data;
	 * - Verify if the size of the table is correct;
	 * - Start the replica again;
	 * - Insert data;
	 * - Verify if the size of the table is correct;
	 * - Kills a second leader;
	 * - Insert data;
	 * - Verify if the size of the table is correct.
	 */
	@Test
	public void testStopLeaders() {
		try{
			Thread.sleep(1000);
			BFTMap bftMap = new BFTMap(1001);
			Thread.sleep(1000);
			bftMap.put("TestTable5", new HashMap<String,byte[]>());

			for(int i = 0; i < 130; i++) {
				String key = "key" + (1+i);
				String value = "value" + (1+i);
				bftMap.putEntry("TestTable5", key, value.getBytes());
			}
			assertEquals("Main table size should be 130", 130, bftMap.size1("TestTable5"));

			replica0.destroy(); // Killing the leader, replica 0

			for(int i = 0; i < 60; i++) {
				String key = "key" + (131+i);
				String value = "value" + (131+i);
				bftMap.putEntry("TestTable5", key, value.getBytes());
			}
			assertEquals("Main table size should be 190", 190, bftMap.size1("TestTable5"));

			command[4] = "0";
			replica0 = new ProcessBuilder(command).redirectErrorStream(true).start(); // Starting replica0 back
			ConsoleLogger log0 = new ConsoleLogger();;
			log0.setIn(replica0.getInputStream());
			log0.setOut(System.out);
			log0.setIndex("01");
			log0.start();
			System.out.println("---------Sleep1: " + new java.util.Date());
			Thread.sleep(20000);
			System.out.println("---------Wakeup1: " + new java.util.Date());

			for(int i = 0; i < 20; i++) {
				String key = "key" + (191+i);
				String value = "value" + (191+i);
				System.out.println(bftMap.putEntry("TestTable5", key, value.getBytes()));
			}
			assertEquals("Main table size should be 210", 210, bftMap.size1("TestTable5"));

			System.out.println("---------Sleep2: " + new java.util.Date());
			Thread.sleep(10000);
			System.out.println("---------Wakeup2: " + new java.util.Date());

			replica1.destroy(); // Killing another leader replica, replica1

			for(int i = 0; i < 60; i++) {
				String key = "key" + (211+i);
				String value = "value" + (211+i);
				System.out.println(bftMap.putEntry("TestTable5", key, value.getBytes()));
			}
			assertEquals("Main table size should be 270", 270, bftMap.size1("TestTable5"));

			command[4] = "1";
			replica1 = new ProcessBuilder(command).redirectErrorStream(true).start(); // Starting replica0 back
			ConsoleLogger log1 = new ConsoleLogger();;
			log1.setIn(replica1.getInputStream());
			log1.setOut(System.out);
			log1.setIndex("11");
			log1.start();
			System.out.println("---------Sleep3: " + new java.util.Date());
			Thread.sleep(20000);
			System.out.println("---------Wakeup3: " + new java.util.Date());

			for(int i = 0; i < 20; i++) {
				String key = "key" + (271+i);
				String value = "value" + (271+i);
				System.out.println(bftMap.putEntry("TestTable5", key, value.getBytes()));
			}
			assertEquals("Main table size should be 290", 290, bftMap.size1("TestTable5"));

			System.out.println("---------Sleep4: " + new java.util.Date());
			Thread.sleep(10000);
			System.out.println("---------Wakeup4: " + new java.util.Date());

			replica2.destroy(); // Killing another leader replica, replica1

			for(int i = 0; i < 40; i++) {
				String key = "key" + (291+i);
				String value = "value" + (291+i);
				System.out.println(bftMap.putEntry("TestTable5", key, value.getBytes()));
			}
			assertEquals("Main table size should be 330", 330, bftMap.size1("TestTable5"));

			command[4] = "2";
			replica2 = new ProcessBuilder(command).redirectErrorStream(true).start(); // Starting replica0 back
			ConsoleLogger log2 = new ConsoleLogger();;
			log2.setIn(replica2.getInputStream());
			log2.setOut(System.out);
			log2.setIndex("21");
			log2.start();
			System.out.println("---------Sleep5: " + new java.util.Date());
			Thread.sleep(20000);
			System.out.println("---------Wakeup5: " + new java.util.Date());

			for(int i = 0; i < 40; i++) {
				String key = "key" + (331+i);
				String value = "value" + (331+i);
				System.out.println(bftMap.putEntry("TestTable5", key, value.getBytes()));
			}
			assertEquals("Main table size should be 370", 370, bftMap.size1("TestTable5"));

			System.out.println("---------Sleep6: " + new java.util.Date());
			Thread.sleep(10000);
			System.out.println("---------Wakeup6: " + new java.util.Date());

			replica3.destroy(); // Killing another leader replica, replica1

			for(int i = 0; i < 40; i++) {
				String key = "key" + (371+i);
				String value = "value" + (371+i);
				System.out.println(bftMap.putEntry("TestTable5", key, value.getBytes()));
			}
			assertEquals("Main table size should be 410", 410, bftMap.size1("TestTable5"));

			command[4] = "3";
			replica3 = new ProcessBuilder(command).redirectErrorStream(true).start(); // Starting replica0 back
			ConsoleLogger log3 = new ConsoleLogger();;
			log3.setIn(replica3.getInputStream());
			log3.setOut(System.out);
			log3.setIndex("31");
			log3.start();
			System.out.println("---------Sleep7: " + new java.util.Date());
			Thread.sleep(20000);
			System.out.println("---------Wakeup7: " + new java.util.Date());

			for(int i = 0; i < 20; i++) {
				String key = "key" + (411+i);
				String value = "value" + (411+i);
				System.out.println(bftMap.putEntry("TestTable5", key, value.getBytes()));
			}
			assertEquals("Main table size should be 430", 430, bftMap.size1("TestTable5"));

			System.out.println("---------Sleep8: " + new java.util.Date());
			Thread.sleep(10000);
			System.out.println("---------Wakeup8: " + new java.util.Date());

			replica0.destroy(); // Killing another leader replica, replica1

			for(int i = 0; i < 40; i++) {
				String key = "key" + (431+i);
				String value = "value" + (431+i);
				System.out.println(bftMap.putEntry("TestTable5", key, value.getBytes()));
			}
			assertEquals("Main table size should be 470", 470, bftMap.size1("TestTable5"));

		} catch(InterruptedException ie) {
			System.out.println("Exception during Thread sleep: " + ie.getMessage());
		} catch(IOException ioe) {
			System.out.println("Exception when starting replica 2: " + ioe.getMessage());
		}
	}

}


text:
package models

import common.enums.VatRegStatus
import play.api.libs.functional.syntax._
import play.api.libs.json._

case class CurrentProfile(registrationId: String,
                          vatRegistrationStatus: VatRegStatus.Value,
                          agentReferenceNumber: Option[String] = None)

object CurrentProfile {
  val reads: Reads[CurrentProfile] = (
    (__ \ "registrationID").read[String] and
      (__ \ "vatRegistrationStatus").read[VatRegStatus.Value] and
      (__ \ "agentReferenceNumber").readNullable[String]
    ) (CurrentProfile.apply _)

  val writes: Writes[CurrentProfile] = (
    (__ \ "registrationID").write[String] and
      (__ \ "vatRegistrationStatus").write[VatRegStatus.Value] and
      (__ \ "agentReferenceNumber").writeNullable[String]
    ) (unlift(CurrentProfile.unapply))

  implicit val format: Format[CurrentProfile] = Format(reads, writes)
}


text:
<?php

namespace Laravel\Passport\Bridge;

use League\OAuth2\Server\Entities\ClientEntityInterface;
use League\OAuth2\Server\Entities\Traits\ClientTrait;

class Client implements ClientEntityInterface
{
    use ClientTrait;

    /**
     * The client identifier.
     *
     * @var string
     */
    protected $identifier;

    /**
     * The client's provider.
     *
     * @var string
     */
    public $provider;

    /**
     * Create a new client instance.
     *
     * @param  string  $identifier
     * @param  string  $name
     * @param  string  $redirectUri
     * @param  bool  $isConfidential
     * @param  string|null  $provider
     * @return void
     */
    public function __construct($identifier, $name, $redirectUri, $isConfidential = false, $provider = null)
    {
        $this->setIdentifier((string) $identifier);

        $this->name = $name;
        $this->isConfidential = $isConfidential;
        $this->redirectUri = explode(',', $redirectUri);
        $this->provider = $provider;
    }

    /**
     * Get the client's identifier.
     *
     * @return string
     */
    public function getIdentifier()
    {
        return (string) $this->identifier;
    }

    /**
     * Set the client's identifier.
     *
     * @param  string  $identifier
     * @return void
     */
    public function setIdentifier($identifier)
    {
        $this->identifier = $identifier;
    }
}


text:
require "hisaichibot/version"
require 'hisaichibot/ping_pong'
require 'hisaichibot/clockwork'
require 'hisaichibot/tweet_stream'
require 'hisaichibot/tumblr_lgtm'


text:
package ua.com.fielden.platform.entity.query.generation;

import java.util.Map;

import ua.com.fielden.platform.entity.query.fluent.enums.TokenCategory;
import ua.com.fielden.platform.entity.query.generation.elements.GroupBy;
import ua.com.fielden.platform.entity.query.generation.elements.ISingleOperand;
import ua.com.fielden.platform.utils.Pair;

public class GroupBuilder extends AbstractTokensBuilder {

    protected GroupBuilder(final AbstractTokensBuilder parent, final EntQueryGenerator queryBuilder, final Map<String, Object> paramValues) {
        super(parent, queryBuilder, paramValues);
    }

    @Override
    public boolean isClosing() {
        return getSize() == 1;
    }

    @Override
    public Pair<TokenCategory, Object> getResult() {
        final ISingleOperand operand = getModelForSingleOperand(firstCat(), firstValue());
        return new Pair<>(TokenCategory.QRY_GROUP, new GroupBy(operand));
    }
}


text:
/*
 * This software is distributed under BSD 3-clause license (see LICENSE file).
 *
 * Authors: Soeren Sonnenburg, Weijie Lin, Thoralf Klein, Fernando Iglesias
 */
#include <shogun/lib/Compressor.h>
#include <shogun/io/SGIO.h>
#include <string.h>

#ifdef USE_LZO
#include <lzo/lzoconf.h>
#include <lzo/lzoutil.h>
#include <lzo/lzo1x.h>
#endif

#ifdef USE_GZIP
#include <zlib.h>
#endif

#ifdef USE_BZIP2
#include <bzlib.h>
#endif

#ifdef USE_LZMA
#include <lzma.h>
#endif

#ifdef USE_SNAPPY
#include <snappy.h>
#endif

using namespace shogun;

CCompressor::CCompressor()
	:CSGObject(), compression_type(UNCOMPRESSED)
{
	SG_UNSTABLE("CCompressor::CCompressor()", "\n")
}

void CCompressor::compress(uint8_t* uncompressed, uint64_t uncompressed_size,
		uint8_t* &compressed, uint64_t &compressed_size, int32_t level)
{
	uint64_t initial_buffer_size=0;

	if (uncompressed_size==0)
	{
		compressed=NULL;
		compressed_size=0;
		return;
	}

	switch (compression_type)
	{
		case UNCOMPRESSED:
			{
				initial_buffer_size=uncompressed_size;
				compressed_size=uncompressed_size;
				compressed=SG_MALLOC(uint8_t, compressed_size);
				sg_memcpy(compressed, uncompressed, uncompressed_size);
				break;
			}
#ifdef USE_LZO
		case LZO:
			{
				if (lzo_init() != LZO_E_OK)
					SG_ERROR("Error initializing LZO Compression\n")

				lzo_bytep lzo_wrkmem = (lzo_bytep) lzo_malloc(LZO1X_999_MEM_COMPRESS);
				if (!lzo_wrkmem)
					SG_ERROR("Error allocating LZO workmem\n")

				initial_buffer_size=uncompressed_size +
					uncompressed_size / 16+ 64 + 3;

				compressed_size=initial_buffer_size;
				compressed=SG_MALLOC(uint8_t, initial_buffer_size);

				lzo_uint lzo_size=compressed_size;

				int ret;
				if (level<9)
				{
					ret=lzo1x_1_15_compress(uncompressed, uncompressed_size,
								compressed, &lzo_size, lzo_wrkmem);
				}
				else
				{
					ret=lzo1x_999_compress(uncompressed, uncompressed_size,
								compressed, &lzo_size, lzo_wrkmem);
				}

				compressed_size=lzo_size;
				lzo_free(lzo_wrkmem);

				if (ret!= LZO_E_OK)
					SG_ERROR("Error lzo-compressing data\n")

				break;
			}
#endif
#ifdef USE_GZIP
		case GZIP:
			{
				initial_buffer_size=1.001*uncompressed_size + 12;
				compressed_size=initial_buffer_size;
				compressed=SG_MALLOC(uint8_t, initial_buffer_size);
				uLongf gz_size=compressed_size;

				if (compress2(compressed, &gz_size, uncompressed,
							uncompressed_size, level) != Z_OK)
				{
					SG_ERROR("Error gzip-compressing data\n")
				}
				compressed_size=gz_size;
				break;
			}
#endif
#ifdef USE_BZIP2
		case BZIP2:
			{
				bz_stream strm;
				strm.bzalloc=NULL;
				strm.bzfree=NULL;
				strm.opaque=NULL;
				initial_buffer_size=1.01*uncompressed_size + 600;
				compressed_size=initial_buffer_size;
				compressed=SG_MALLOC(uint8_t, initial_buffer_size);
				if (BZ2_bzCompressInit(&strm, level, 0, 0)!=BZ_OK)
					SG_ERROR("Error initializing bzip2 compressor\n")

				strm.next_in=(char*) uncompressed;
				strm.avail_in=(unsigned int) uncompressed_size;
				strm.next_out=(char*) compressed;
				strm.avail_out=(unsigned int) compressed_size;
				if (BZ2_bzCompress(&strm, BZ_RUN) != BZ_RUN_OK)
					SG_ERROR("Error bzip2-compressing data (BZ_RUN)\n")

				int ret=0;
				while (true)
				{
					ret=BZ2_bzCompress(&strm, BZ_FINISH);
					if (ret==BZ_FINISH_OK)
						continue;
					if (ret==BZ_STREAM_END)
						break;
					else
						SG_ERROR("Error bzip2-compressing data (BZ_FINISH)\n")
				}
				BZ2_bzCompressEnd(&strm);
				compressed_size=(((uint64_t) strm.total_out_hi32) << 32) + strm.total_out_lo32;
				break;
			}
#endif
#ifdef USE_LZMA
		case LZMA:
			{
				lzma_stream strm = LZMA_STREAM_INIT;
				initial_buffer_size = lzma_stream_buffer_bound(uncompressed_size);
				compressed_size=initial_buffer_size;
				compressed=SG_MALLOC(uint8_t, initial_buffer_size);
				strm.next_in=uncompressed;
				strm.avail_in=(size_t) uncompressed_size;
				strm.next_out=compressed;
				strm.avail_out=(size_t) compressed_size;

				if (lzma_easy_encoder(&strm, level, LZMA_CHECK_CRC32) != LZMA_OK)
					SG_ERROR("Error initializing lzma compressor\n")
				if (lzma_code(&strm, LZMA_RUN) != LZMA_OK)
					SG_ERROR("Error lzma-compressing data (LZMA_RUN)\n")

				lzma_ret ret;
				while (true)
				{
					ret=lzma_code(&strm, LZMA_FINISH);
					if (ret==LZMA_OK)
						continue;
					if (ret==LZMA_STREAM_END)
						break;
					else
						SG_ERROR("Error lzma-compressing data (LZMA_FINISH)\n")
				}
				lzma_end(&strm);
				compressed_size=strm.total_out;
				break;
			}
#endif
#ifdef USE_SNAPPY
		case SNAPPY:
			{
				compressed=SG_MALLOC(uint8_t, snappy::MaxCompressedLength((size_t) uncompressed_size));
				size_t output_length;
				snappy::RawCompress((char*) uncompressed, size_t(uncompressed_size), (char*) compressed, &output_length);
				compressed_size=(uint64_t) output_length;
				break;
			}
#endif
		default:
			SG_ERROR("Unknown compression type\n")
	}

	if (compressed)
		compressed = SG_REALLOC(uint8_t, compressed, initial_buffer_size, compressed_size);
}

void CCompressor::decompress(uint8_t* compressed, uint64_t compressed_size,
		uint8_t* uncompressed, uint64_t& uncompressed_size)
{
	if (compressed_size==0)
	{
		uncompressed_size=0;
		return;
	}

	switch (compression_type)
	{
		case UNCOMPRESSED:
			{
				ASSERT(uncompressed_size>=compressed_size)
				uncompressed_size=compressed_size;
				sg_memcpy(uncompressed, compressed, uncompressed_size);
				break;
			}
#ifdef USE_LZO
		case LZO:
			{
				if (lzo_init() != LZO_E_OK)
					SG_ERROR("Error initializing LZO Compression\n")

				lzo_bytep lzo_wrkmem = (lzo_bytep) lzo_malloc(LZO1X_999_MEM_COMPRESS);
				if (!lzo_wrkmem)
					SG_ERROR("Error allocating LZO workmem\n")

				lzo_uint lzo_size=uncompressed_size;
				if (lzo1x_decompress(compressed, compressed_size, uncompressed,
							&lzo_size, NULL) != LZO_E_OK)
				{
					SG_ERROR("Error uncompressing lzo-data\n")
				}
				uncompressed_size=lzo_size;

				lzo_free(lzo_wrkmem);
				break;
			}
#endif
#ifdef USE_GZIP
		case GZIP:
			{
				uLongf gz_size=uncompressed_size;
				if (uncompress(uncompressed, &gz_size, compressed,
							compressed_size) != Z_OK)
				{
					SG_ERROR("Error uncompressing gzip-data\n")
				}
				uncompressed_size=gz_size;
				break;
			}
#endif
#ifdef USE_BZIP2
		case BZIP2:
			{
				bz_stream strm;
				strm.bzalloc=NULL;
				strm.bzfree=NULL;
				strm.opaque=NULL;
				if (BZ2_bzDecompressInit(&strm, 0, 0)!=BZ_OK)
					SG_ERROR("Error initializing bzip2 decompressor\n")
				strm.next_in=(char*) compressed;
				strm.avail_in=(unsigned int) compressed_size;
				strm.next_out=(char*) uncompressed;
				strm.avail_out=(unsigned int) uncompressed_size;
				if (BZ2_bzDecompress(&strm) != BZ_STREAM_END || strm.avail_in!=0)
					SG_ERROR("Error uncompressing bzip2-data\n")
				BZ2_bzDecompressEnd(&strm);
				break;
			}
#endif
#ifdef USE_LZMA
		case LZMA:
			{
				lzma_stream strm = LZMA_STREAM_INIT;
				strm.next_in=compressed;
				strm.avail_in=(size_t) compressed_size;
				strm.next_out=uncompressed;
				strm.avail_out=(size_t) uncompressed_size;

				uint64_t memory_limit=lzma_easy_decoder_memusage(9);

				if (lzma_stream_decoder(&strm, memory_limit, 0)!= LZMA_OK)
					SG_ERROR("Error initializing lzma decompressor\n")
				if (lzma_code(&strm, LZMA_RUN) != LZMA_STREAM_END)
					SG_ERROR("Error decompressing lzma data\n")
				lzma_end(&strm);
				break;
			}
#endif
#ifdef USE_SNAPPY
		case SNAPPY:
			{
				size_t uncompressed_length;
				if (!snappy::GetUncompressedLength( (char*) compressed,
						(size_t) compressed_size, &uncompressed_length))
					SG_ERROR("Error obtaining uncompressed length\n")

				ASSERT(uncompressed_length<=uncompressed_size)
				uncompressed_size=uncompressed_length;
				if (!snappy::RawUncompress((char*) compressed,
							(size_t) compressed_size,
							(char*) uncompressed))
					SG_ERROR("Error uncompressing snappy data\n")

				break;
			}
#endif
		default:
			SG_ERROR("Unknown compression type\n")
	}
}


text:
'use strict';

base.require('base.unittest');
base.require('tracing.test_utils');
base.require('tracing.filter');

base.unittest.testSuite('tracing.filter', function() {
  var TitleFilter = tracing.TitleFilter;
  var CategoryFilter = tracing.CategoryFilter;

  test('titleFilter', function() {
    var s0 = tracing.test_utils.newSliceNamed('a', 1, 3);
    assertFalse(new TitleFilter('').matchSlice(s0));

    assertTrue(new TitleFilter('a').matchSlice(s0));
    assertFalse(new TitleFilter('x').matchSlice(s0));

    var s1 = tracing.test_utils.newSliceNamed('ba', 1, 3);
    assertTrue(new TitleFilter('a').matchSlice(s1));
    assertTrue(new TitleFilter('ba').matchSlice(s1));
    assertFalse(new TitleFilter('x').matchSlice(s1));

    var s2 = tracing.test_utils.newSliceNamed('Ca', 1, 3);
    assertTrue(new TitleFilter('A').matchSlice(s2));
    assertTrue(new TitleFilter('cA').matchSlice(s2));
    assertFalse(new TitleFilter('X').matchSlice(s2));

    var c0 = tracing.test_utils.newCounterNamed(null, 'a');
    assertFalse(new TitleFilter('').matchCounter(c0));

    assertTrue(new TitleFilter('a').matchCounter(c0));
    assertFalse(new TitleFilter('x').matchCounter(c0));

    var c1 = tracing.test_utils.newCounterNamed(null, 'ba');
    assertTrue(new TitleFilter('a').matchCounter(c1));
    assertTrue(new TitleFilter('ba').matchCounter(c1));
    assertFalse(new TitleFilter('x').matchCounter(c1));

    var c2 = tracing.test_utils.newCounterNamed(null, 'cA');
    assertTrue(new TitleFilter('a').matchCounter(c2));
    assertTrue(new TitleFilter('Ca').matchCounter(c2));
    assertFalse(new TitleFilter('X').matchCounter(c2));
  });

  test('categoryFilter', function() {
    var sNoCategory = tracing.test_utils.newSliceNamed('a', 1, 3);
    sNoCategory.category = undefined;
    assertTrue(new CategoryFilter(['x']).matchSlice(sNoCategory));

    var s0 = tracing.test_utils.newSlice(1, 3);
    s0.category = 'x';
    assertFalse(new CategoryFilter(['x']).matchSlice(s0));

    var s1 = tracing.test_utils.newSliceNamed('ba', 1, 3);
    s1.category = 'y';
    assertTrue(new CategoryFilter(['x']).matchSlice(s1));
    assertFalse(new CategoryFilter(['y']).matchSlice(s1));
    assertFalse(new CategoryFilter(['x', 'y']).matchSlice(s1));

    var cNoCategory = tracing.test_utils.newCounterCategory(
        null, undefined, 'a');
    assertTrue(new CategoryFilter(['x']).matchCounter(cNoCategory));

    var c0 = tracing.test_utils.newCounterCategory(null, 'x', 'a');
    assertFalse(new CategoryFilter(['x']).matchCounter(c0));

    var c1 = tracing.test_utils.newCounterCategory(null, 'y', 'ba');
    assertTrue(new CategoryFilter(['x']).matchCounter(c1));
    assertFalse(new CategoryFilter(['y']).matchCounter(c1));
    assertFalse(new CategoryFilter(['x', 'y']).matchCounter(c1));
  });

  test('filterSliceArray', function() {
    var slices = [
      tracing.test_utils.newSliceNamed('ba', 1, 3),
      tracing.test_utils.newSliceNamed('ab', 1, 3),
      tracing.test_utils.newSliceNamed('x', 1, 3),
      tracing.test_utils.newSliceNamed('axa', 1, 3)
    ];
    var filter = new TitleFilter('a');
    var matched = tracing.filterSliceArray(filter, slices);
    assertEquals(3, matched.length);
    assertEquals('ba', matched[0].title);
    assertEquals('ab', matched[1].title);
    assertEquals('axa', matched[2].title);
  });

  test('filterCounterArray', function() {
    var counters = [
      tracing.test_utils.newCounterNamed(null, 'ba'),
      tracing.test_utils.newCounterNamed(null, 'ab'),
      tracing.test_utils.newCounterNamed(null, 'x'),
      tracing.test_utils.newCounterNamed(null, 'axa')
    ];
    var filter = new TitleFilter('a');
    var matched = tracing.filterCounterArray(filter, counters);
    assertEquals(3, matched.length);
    assertEquals('ba', matched[0].name);
    assertEquals('ab', matched[1].name);
    assertEquals('axa', matched[2].name);
  });
});


text:
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
import util

@login_required
def status(request):
    exception = None
    process_id = None
    process_pidfile = None
    server_version = None

    try:
        process_id = util.get_process_id_from_server()
        process_pidfile = util.get_process_pidfile_path_from_server()
        server_version = util.get_server_version()
    except Exception as e:
        exception = str(e)

    return render_to_response("general/status.html", {'exception' : exception,
                                                      'process_id' : process_id,
                                                      'process_pidfile' : process_pidfile,
                                                      'server_version' : server_version,
                                                      })


text:
<?php

namespace Magento\DesignEditor\Block\Adminhtml\Editor\Form\Element;

/**
 * Form element button
 */
class Button extends \Magento\Framework\Data\Form\Element\AbstractElement
{
    /**
     * Additional html attributes
     *
     * @var string[]
     */
    protected $_htmlAttributes = ['data-mage-init'];

    /**
     * Generate button html
     *
     * @return string
     */
    public function getElementHtml()
    {
        $html = '';
        if ($this->getBeforeElementHtml()) {
            $html .= sprintf(
                '%s',
                $this->getHtmlId(),
                $this->getBeforeElementHtml()
            );
        }
        $html .= sprintf(
            '<button id="%s" %s %s>%s</button>',
            $this->getHtmlId(),
            $this->_getUiId(),
            $this->serialize($this->getHtmlAttributes()),
            $this->getEscapedValue()
        );

        if ($this->getAfterElementHtml()) {
            $html .= sprintf(
                '%s',
                $this->getHtmlId(),
                $this->getBeforeElementHtml()
            );
        }
        return $html;
    }

    /**
     * Html attributes
     *
     * @return string[]
     */
    public function getHtmlAttributes()
    {
        $attributes = parent::getHtmlAttributes();
        return array_merge($attributes, $this->_htmlAttributes);
    }
}


text:
package cn.jimmyshi.beanquery.selectors;

import java.beans.PropertyDescriptor;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Selector that use the bean properties as the key and the property values as
 * the value. Because every object has a "class" property which is not required
 * in most scenario, it will be excluded from the result. If you really want it,
 * you can use the {@link #add(String...)} method to add it in the result map.
 */
public class ClassSelector extends KeyValueMapSelector {
  private transient Logger logger = LoggerFactory.getLogger(ClassSelector.class);
  private List<PropertySelector> propertySelectors = new LinkedList<PropertySelector>();
  private CompositeSelector compositeSelector = new CompositeSelector();

  /**
   * @param clazz
   *          null will cause the select methods returning an empty Map or a
   *          list of Empty map as the result.
   */
  public ClassSelector(Class<?> clazz) {
    if (null == clazz) {
      logger.warn("Input class is null");
      return;
    }
    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(clazz);
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
      boolean propertyReadable = propertyDescriptor.getReadMethod() != null;
      String propertyName = propertyDescriptor.getName();
      // ignore the class property
      if ("class".equals(propertyName)) {
        continue;
      }

      if (propertyReadable) {
        PropertySelector propertySelector = new PropertySelector(propertyDescriptor.getName());
        propertySelectors.add(propertySelector);
        compositeSelector.addSubSelector(propertySelector);
      }
    }
  }

  /**
   * Exclude properties from the result map.
   */
  public ClassSelector except(String... propertyNames) {
    if(ArrayUtils.isEmpty(propertyNames)){
      return this;
    }

    boolean updated = false;
    for (String propertyToRemove : propertyNames) {
      if (removePropertySelector(propertyToRemove)) {
        updated = true;
      }
    }

    if (updated) {
      compositeSelector = new CompositeSelector(this.propertySelectors);
    }
    return this;
  }

  private boolean removePropertySelector(String propertyName) {
    if (StringUtils.isBlank(propertyName)) {
      return false;
    }

    for (PropertySelector selector : propertySelectors) {
      if (selector.getProperty().equals(propertyName)) {
        propertySelectors.remove(selector);
        return true;
      }
    }
    return false;
  }

  /**
   * Include properties in the result map.
   */
  public ClassSelector add(String... propertyNames) {
    if (ArrayUtils.isNotEmpty(propertyNames)) {
      for (String propertyNameToAdd : propertyNames) {
        addPropertySelector(propertyNameToAdd);
      }
    }
    return this;
  }

  private void addPropertySelector(String propertyNameToAdd) {
    if (StringUtils.isBlank(propertyNameToAdd)) {
      return;
    }

    for (PropertySelector propertySelector : propertySelectors) {
      if (propertySelector.getProperty().equals(propertyNameToAdd)) {
        return;
      }
    }

    PropertySelector newPropertySelector = new PropertySelector(propertyNameToAdd);
    propertySelectors.add(newPropertySelector);
    compositeSelector.addSubSelector(newPropertySelector);
  }

  @Override
  protected Map<String, Object> doSelect(Object item) {
    return this.compositeSelector.select(item);
  }

}


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">
    <parent>
        <artifactId>pro</artifactId>
        <groupId>xuan.pro</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>commom_module_models</artifactId>
    <packaging>jar</packaging>

</project>


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
Syll. fung. (Abellini) 19: 994 (1910)

#### Original name
Patellaria myriocarpa DC.

### Remarks
null


text:
package at.c02.tempus.auth.api;

import at.c02.tempus.auth.model.UserData;
import io.reactivex.Observable;
import retrofit2.http.GET;
import retrofit2.http.Headers;

/**
 * Created by Daniel Hartl on 08.05.2017.
 */

public interface AuthApi {

    @GET("/connect/userinfo")
    public Observable<UserData> getUserInfo();
}


text:
import requests

class Query(object):

    _metadata = None

    def __init__(self, client, url, objtype, page_size=100):
        super(Query, self).__init__()
        self.client = client
        self.url = url.set_query_param("page_size", str(page_size))
        self.objtype = objtype
        self.page_size = page_size
        self._objects = None

    def _fetch_page(self, page_index):
        assert page_index > 0
        result = requests.get(self.url.set_query_param("page", str(page_index)))
        result.raise_for_status()
        result_json = result.json()
        if self._objects is None:
            self._objects = [None] * int(result_json["metadata"]["total_num_objects"])
        for index, obj in enumerate(result_json["result"]):
            self._objects[index + ((page_index - 1) * self.page_size)] = obj

    def __iter__(self):
        for obj in self.get_json_objects():
            yield self.objtype.from_query_json(self.client, obj)

    def get_json_objects(self):
        for i in range(len(self)):
            obj = self._objects[i]
            if self._objects[i] is None:
                self._fetch_page((i // self.page_size) + 1)
            assert self._objects[i] is not None
            yield self._objects[i]

    def __len__(self):
        if self._objects is None:
            self._fetch_page(1)
        return len(self._objects)


text:
        {{vm.user.displayName}}

        Usuario desde: {{vm.user.created | date: 'dd/MM/yyyy'}}

    <md-tabs md-dynamic-height md-border-bottom>
      <md-tab label="JUGANDO">

{{ game.name }}

      </md-tab>
      <md-tab label="FINALIZADOS">

{{ game.name }}

      </md-tab>
      <md-tab label="PENDIENTES">

{{ game.name }}

      </md-tab>
    </md-tabs>

    <button ng-if="!vm.isOwnUser && !vm.isFriend" ng-click="vm.follow()" type="button" class="btn btn-success">Seguir</button>
    <button ng-if="!vm.isOwnUser && vm.isFriend" ng-click="vm.unfollow()" type="button" class="btn btn-warning">Dejar de seguir</button>


text:
package com.intellij.openapi.roots.ui.configuration.artifacts.nodes;

import com.intellij.openapi.roots.ui.configuration.artifacts.ArtifactEditorEx;
import com.intellij.openapi.roots.ui.configuration.artifacts.ComplexElementSubstitutionParameters;
import com.intellij.packaging.artifacts.ArtifactType;
import com.intellij.packaging.ui.ArtifactEditorContext;

import java.util.Collections;

/**
 * @author nik
 */
public class ArtifactRootNode extends CompositePackagingElementNode {
  public ArtifactRootNode(ArtifactEditorEx artifactEditor, ArtifactEditorContext context,
                          ComplexElementSubstitutionParameters substitutionParameters, ArtifactType artifactType) {
    super(artifactEditor.getRootElement(), context, null, null, substitutionParameters, Collections.emptyList(),
          artifactType);
  }

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


text:
<?php

namespace Borobudur\Broadcasting;

use ReflectionObject;
use ReflectionProperty;

/**
 * @author      Iqbal Maulana <iq.bluejack@gmail.com>
 * @created     9/16/15
 */
trait BroadcastEventTrait
{
    /**
     * @var string
     * @internal
     */
    private $broadcastName;

    /**
     * @var array
     * @internal
     */
    private $broadcastChannels;

    /**
     * Set broadcast name.
     *
     * @param string $name
     */
    public function setBroadcastName($name)
    {
        $this->broadcastName = $name;
    }

    /**
     * Get broadcast name.
     *
     * @return string
     */
    public function getBroadcastName()
    {
        if (null === $this->broadcastName) {
            return get_called_class();
        }

        return $this->broadcastName;
    }

    /**
     * Set broadcast channel.
     *
     * @param array $channels
     */
    public function setBroadcastChannel(array $channels)
    {
        $this->broadcastChannels = $channels;
    }

    /**
     * Get broadcast channel.
     *
     * @return array
     */
    public function getBroadcastChannels()
    {
        if (null === $this->broadcastChannels) {
            return array(BroadcastEventInterface::DEFAULT_CHANNEL);
        }

        return $this->broadcastChannels;
    }

    /**
     * @return array|null
     */
    public function getBroadcastPayload()
    {
        if (!method_exists($this, 'serialize')) {
            $reflection = new ReflectionObject($this);
            $properties = $reflection->getProperties(ReflectionProperty::IS_PUBLIC);
            $data = array();

            foreach ($properties as $prop) {
                $data[$prop->getName()] = $prop->getValue($this);
            }

            return $data;
        }

        return $this->{'serialize'}();
    }
}


text:
namespace MassTransit
{
    public interface IGroupKeyProvider<in TMessage, TKey>
        where TMessage : class
    {
        bool TryGetKey(ConsumeContext<TMessage> context, out TKey key);
    }
}


text:
package test.com.sasbury.sting.operations;

import com.sasbury.sting.*;
import com.sasbury.sting.types.*;
import junit.framework.*;

public class SimpleLoopTest extends TestCase
{
	public SimpleLoopTest(String name)
	{
		super(name);
	}

    public void testOperation() throws Exception
    {
        String program = "0 0 4 {index plus} loop";

        StingProgram sprogram = new StingProgram(program);
        ExecutionContext context = sprogram.execute();
        StingStack correct = new StingStack();
        correct.push(new StingNumber(10));
        assertTrue(correct.equals(context.getStack()));
    }
}


text:
import Eleven from '../../../../../src/eleven';
const $ = Eleven.query;

describe('$.fn.prepend + $.fn.prependTo', () => {
  it('should prepend an
 to the container element', () => {
    var element = $('

World

');

    element.prepend('
Hello
');

    expect(element.first().text()).toMatch('Hello');
    expect(element.last().text()).toMatch('World');
  });

  it('should prepend an
 as the first child in the container element', () => {
    const h1 = $('
prependTo
');
    $('body').append('

World

');

    expect(h1.prependTo('#test').parent().first().text()).toMatch('prependTo');
  });
});


text:
#include <mupnp/Action.h>
#include <uhttp/util/Debug.h>
#include <mupnp/Service.h>

#include <string>

using namespace std;
using namespace uHTTP;
using namespace mUPnP;

////////////////////////////////////////////////
// Constants
////////////////////////////////////////////////

const char *Action::ELEM_NAME = "action";
const char *Action::NAME = "name";

////////////////////////////////////////////////
// Constructor
////////////////////////////////////////////////

Action::Action(mupnp_shared_ptr<uXML::Node> serviceNode, mupnp_shared_ptr<uXML::Node> actionNode) {
  this->serviceNode = serviceNode;
  this->actionNode = actionNode;

  initArgumentList();
}

Action::Action(Action *action) {
  this->serviceNode = action->getServiceNode();
  this->actionNode = action->getActionNode();

  initArgumentList();
}

Action::~Action() {
  delete argumentList;
  delete argumentInList;
  delete argumentOutList;
}

////////////////////////////////////////////////
// getService
////////////////////////////////////////////////

Service *Action::getService() {
  mupnp_shared_ptr<uXML::Node> node = getServiceNode();
  ServiceData *data = dynamic_cast<ServiceData *>(node->getUserData());
  if (!data)
    return nullptr;
  return data->getService();
}

////////////////////////////////////////////////
// argumentList
////////////////////////////////////////////////

void Action::initArgumentList() {
  argumentList = new ArgumentList(true);
  argumentInList = new ArgumentList(false);
  argumentOutList = new ArgumentList(false);

  mupnp_shared_ptr<uXML::Node> serviceNode = getServiceNode();
  mupnp_shared_ptr<uXML::Node> argumentListNode = getActionNode()->getNode(ArgumentList::ELEM_NAME);
  if (!serviceNode || !argumentListNode)
    return;

  size_t nodeCnt = argumentListNode->getNNodes();
  for (size_t n = 0; n < nodeCnt; n++) {
    mupnp_shared_ptr<uXML::Node> argNode = argumentListNode->getNode(n);
    if (Argument::isArgumentNode(argNode.get()) == false)
      continue;
    Argument *arg = new Argument(serviceNode, argNode);
    argumentList->add(arg);
    if (arg->isInDirection() == true)
      argumentInList->add(arg);
    if (arg->isOutDirection() == true)
      argumentOutList->add(arg);
  }
}

Argument *Action::getArgument(const std::string &name) {
  ArgumentList *argList = getArgumentList();
  size_t nArgs = argList->size();
  for (size_t n = 0; n < nArgs; n++) {
    Argument *arg = argList->getArgument(n);
    const char *argName = arg->getName();
    if (!argName)
      continue;
    string argNameStr = argName;
    if (argNameStr.compare(name) == 0)
      return arg;
  }
  return nullptr;
}

void Action::clearOutputAgumentValues() {
  ArgumentList *outArgList = getOutputArgumentList();
  size_t nArgs = outArgList->size();
  for (size_t n = 0; n < nArgs; n++) {
    Argument *arg = outArgList->getArgument(n);
    arg->setValue("");
  }
}

////////////////////////////////////////////////
// controlAction
////////////////////////////////////////////////

bool Action::performActionListener(ActionRequest *actionReq) {
  ActionListener *listener = (ActionListener *)getActionListener();
  if (!listener)
    return false;
  ActionResponse actionRes;
  setStatus(UPnP::INVALID_ACTION);
  clearOutputAgumentValues();
  if (listener->actionControlReceived(this) == true) {
    actionRes.setResponse(this);
  }
  else {
    UPnPStatus *upnpStatus = getStatus();
    actionRes.setFaultResponse(upnpStatus->getCode(), upnpStatus->getDescription());
  }
  if (Debug::isOn() == true)
    actionRes.print();
  ControlRequest *ctrlReq = actionReq;
  ctrlReq->post(&actionRes);
  return true;
}

////////////////////////////////////////////////
// postControlAction
////////////////////////////////////////////////

bool Action::postControlAction() {
  ArgumentList *actionArgList = getArgumentList();
  ArgumentList *actionInputArgList = getInputArgumentList();
  ActionRequest ctrlReq;
  ctrlReq.setRequest(this, actionInputArgList);
  if (Debug::isOn() == true)
    ctrlReq.print();
  ActionResponse *ctrlRes = new ActionResponse();
  ctrlReq.post(ctrlRes);
  if (Debug::isOn() == true)
    ctrlRes->print();
  setControlResponse(ctrlRes);
  // Thanks for Dimas <cyberrate@users.sourceforge.net> and Stefano Lenzi <kismet-sl@users.sourceforge.net> (07/09/04)
  int statCode = ctrlRes->getStatusCode();
  setStatus(statCode);
  if (ctrlRes->isSuccessful() == false)
    return false;
  ArgumentList *outArgList = ctrlRes->getResponse();
  actionArgList->set(outArgList);
  return true;
}


text:
package xsp.extlib.designer.test.visualizations.dojoform;

import xsp.extlib.designer.test.visualizations.AbstractVisualizationTest;

import com.ibm.xsp.extlib.designer.tooling.visualizations.dojoform.DjHorizontalSliderVisualizer;

public class DjHorizontalSliderVisualizerTest extends AbstractVisualizationTest {

	/*
	 * (non-Javadoc)
	 * @see xsp.extlib.designer.test.visualizations.AbstractVisualizationTest#getTagName()
	 */
	@Override
	public String getTagName() {
		return "djHorizontalSlider";
	}

	/*
	 * (non-Javadoc)
	 * @see xsp.extlib.designer.test.visualizations.AbstractVisualizationTest#getTagName()
	 */
	@Override
	public String getNamespaceURI() {
		return EXT_LIB_NAMESPACE_URI;
	}

	/*
	 * (non-Javadoc)
	 * @see xsp.extlib.designer.test.visualizations.AbstractVisualizationTest#setUp()
	 */
	@Override
	protected void setUp() throws Exception {
		super.setUp();
		_visualizationFactory = new DjHorizontalSliderVisualizer();
	}

	/*
	 * (non-Javadoc)
	 * @see xsp.extlib.designer.test.visualizations.AbstractVisualizationTest#isRenderMarkupStatic()
	 */
	@Override
	public boolean isRenderMarkupStatic(){
		return true;
	}

	/*
	 * (non-Javadoc)
	 * @see xsp.extlib.designer.test.visualizations.AbstractVisualizationTest#getExectedXSPMarkup()
	 */
	@Override
	public String getExpectedXSPMarkup() {
		StringBuilder strBuilder = new StringBuilder();
		strBuilder.append("<xp:image url=\"/extlib/designer/markup/dojoform/horizSlider.png\">");
		strBuilder.append("</xp:image>");
		return strBuilder.toString();
	}

	/*
	 * (non-Javadoc)
	 * @see xsp.extlib.designer.test.visualizations.AbstractVisualizationTest#getExpectedFullXSPMarkup()
	 */
	@Override
	public String getExpectedFullXSPMarkup() {
		StringBuilder strBuilder = new StringBuilder();
		strBuilder.append(getDefaultXPageHeader());
		strBuilder.append(getExpectedXSPMarkup());
		strBuilder.append(getDefaultXPageFooter());
		return strBuilder.toString();
	}

	/*
	 * (non-Javadoc)
	 * @see xsp.extlib.designer.test.visualizations.AbstractVisualizationTest#getExpectedProcessedFullXSPMarkup()
	 */
	@Override
	public String getExpectedProcessedFullXSPMarkup() {
		return getExpectedFullXSPMarkup();
	}

}


text:
author: victor
excerpt: ''
categories:
    - PHP
tags:
    - 'open source'
    - packagist
permalink: /yosymfonytoml-parser-php-para-el-formato-toml-de-ficheros-de-configuracion
no_html_extension: true
layout: post
title: 'yosymfony/toml: Parser PHP para el formato TOML de ficheros de configuración'

---
Tras varias semanas de desarrollo he publicado el primer componente para PHP bajo el nombre de YoSymfony en Github. Y es que la idea de este blog no es solo publicar noticias sino también aportar código a la comunidad PHP.

yomsymfony/toml es un parser del formato de ficheros de configuración TOML creado por Tom Preston-Werner, cofundador de Github. La idea que subyace en este formato es la sencillez. Permitir crear ficheros de configuración intuitivos gracias a una semántica sencilla. En esencia, el fichero se forma por conjuntos de datos clave-valor que se pueden organizar en "namespaces". Un ejemplo:

[database] # namespace
server = "192.168.1.1"
ports = [ 8001, 8001, 8002 ]
connection_max = 5000
enabled = true

[database.querys] # Namespace. Se usa el '.' para separar
max_size_cache: 10 # expresado en MB

TOML soporta un conjunto de datos simples como string, booleanos, enteros, flotantes, arrays y fechas con formato ISO8601. Para facilitar la comprensión, en los arrays no se permiten mezclar varios tipos de datos.

En cuanto a las claves, existe gran libertad para definirlas puesto que una clave comienza con el primer caracter distinto del espacio y finaliza con el último caracter distinto de espacio antes del igual:

~!@#$^&*()_+-`1234567890[]\|/?><.,;:' = 1 # esto es correcto

Implementación

El parser lo he implementado con la típica estructura de analizador léxico (lexer.php) - analizador sintáctico (parser.php). El primero se encarga de obtener tokens mientras que el segundo comprueba que estén en el orden correcto.

La forma de usarlo es sencilla:

use Yosymfony\Toml\Toml;

$array = Toml::Parse('example.toml'); // fichero

print_r($array);

$array = Toml::Parse('key = [1,2,3]'); // en línea

print_r($array);

Para incorporar yosymfony/toml a cualquier proyecto basta con incluir la dependencia en composer.json y ejecutar composer update:

"require": {
    "yosymfony/toml": "dev-master"
}

Github: yosymfony/toml. Licencia: MIT.

Packagist: Información del paquete.

TOML:  especificación v0.1.0.


text:
<?php

/**
 * PHP version 7.3
 *
 * @category CustomerInterface
 * @package  RetailCrm\Api\Interfaces\Orders
 */

namespace RetailCrm\Api\Interfaces\Orders;

/**
 * Interface CustomerInterface
 *
 * @category CustomerInterface
 * @package  RetailCrm\Api\Interfaces\Orders
 */
interface CustomerInterface
{
}


text:
apt_update 'update' if platform_family?('debian')

include_recipe 'perl::default'

unless platform?('windows')
  include_recipe 'build-essential::default' # required to compile modules

  cpan_module 'Test::MockModule' do
    version '>= 0.05'
    action [:install]
  end

  cpan_module 'Test::MockModule' do
    action [:uninstall]
  end

  # cpan_module 'Test::MockModule' do
  #   version '>= 0.05'
  #   action [:install]
  # end
end


text:
package com.vangent.hieos.xutil.soap;

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

/**
 * Used by SOAP utility to return proper SOAP action responses.
 *
 * @author Bernie Thuman
 */
public class SoapActionFactory {

    // XCPD IG SOAP actions:
    public final static String XCPD_IG_PIXV3PIDFEED_ACTION = "urn:hl7-org:v3:PRPA_IN201301UV02";
    public final static String XCPD_IG_PIXV3PIDFEED_ACTION_RESPONSE = "urn:hl7-org:v3:MCCI_IN000002UV01";
    public final static String XCPD_IG_PIXV3QUERY_ACTION = "urn:hl7-org:v3:PRPA_IN201309UV02";
    public final static String XCPD_IG_PIXV3QUERY_ACTION_RESPONSE = "urn:hl7-org:v3:PRPA_IN201310UV02";
    public final static String XCPD_IG_PDQQUERY_ACTION = "urn:hl7-org:v3:PRPA_IN201305UV02";
    public final static String XCPD_IG_PDQQUERY_ACTION_RESPONSE = "urn:hl7-org:v3:PRPA_IN201306UV02";

    // XCPD RG SOAP actions:
    public final static String XCPD_RG_CGPD_ACTION = "urn:hl7-org:v3:PRPA_IN201305UV02:CrossGatewayPatientDiscovery";
    public final static String XCPD_RG_CGPD_ACTION_RESPONSE = "urn:hl7-org:v3:PRPA_IN201306UV02:CrossGatewayPatientDiscovery";
    public final static String XCPD_RG_PLQ_ACTION = "urn:ihe:iti:2009:PatientLocationQuery";
    public final static String XCPD_RG_PLQ_ACTION_RESPONSE = "urn:ihe:iti:2009:PatientLocationQueryResponse";

    /**
     * SOAP action / response pairs.
     */
    private static final Map<String, String> actions =
            new HashMap<String, String>() {

                {
                    // XCPD IG SOAP actions:
                    put(XCPD_IG_PIXV3PIDFEED_ACTION, XCPD_IG_PIXV3PIDFEED_ACTION_RESPONSE);
                    put(XCPD_IG_PIXV3QUERY_ACTION, XCPD_IG_PIXV3QUERY_ACTION_RESPONSE);
                    put(XCPD_IG_PDQQUERY_ACTION, XCPD_IG_PDQQUERY_ACTION_RESPONSE);

                    // XCPD RG SOAP actions:
                    put(XCPD_RG_CGPD_ACTION, XCPD_RG_CGPD_ACTION_RESPONSE);
                    put(XCPD_RG_PLQ_ACTION, XCPD_RG_PLQ_ACTION_RESPONSE);
                }
            };

    /**
     * Return the SOAP "response" action given a SOAP "request" action.
     *
     * @param requestAction The SOAP request action.
     * @return The SOAP response action.
     */
    static public String getResponseAction(String requestAction) {
        if (requestAction == null) {
            return null;
        }
        return actions.get(requestAction);
    }
}


text:
package io.katharsis.jpa.annotations;

import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

/**
 * Allows a JPA entity to include related entities in the exposed JSON API resource.
 * For a consumer it looks like a single (large) resource that can be inserted, updated
 * and deleted with a single request and, as such, in a single transaction.
 */
@Retention(RUNTIME)
@Target(TYPE)
public @interface JpaMergeRelations {

	/**
	 * Defines set of relationship attributes that should be merged
	 * into this resource and treated as regular attribute of this resource.
	 */
	String[] attributes();
}


text:
using Newtonsoft.Json;

namespace Nest
{
	[JsonObject]
	public interface IStartWatcherResponse : IAcknowledgedResponse {}

	public class StartWatcherResponse : AcknowledgedResponseBase, IStartWatcherResponse {}
}


text:
package eu.livotov.labs.androidappskeleton.core.err;

import java.io.IOException;

/**
 * (c) Livotov Labs Ltd. 2012
 * Date: 31/01/2018
 */
public class NoConnectivityException extends IOException
{

}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _ScrollWrapper = require('./js/components/ScrollWrapper');

var _ScrollWrapper2 = _interopRequireDefault(_ScrollWrapper);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

exports.default = _ScrollWrapper2.default;


text:
package com.websudos.phantom.example

import com.websudos.phantom.Manager._
import com.websudos.phantom.connectors.RootConnector
import com.websudos.phantom.example.advanced.RecipesDatabase
import com.websudos.util.lift.{DateTimeSerializer, UUIDSerializer}
import org.scalatest.concurrent.{PatienceConfiguration, ScalaFutures}
import org.scalatest._

import scala.concurrent.Await
import scala.concurrent.duration._

trait BaseSuite extends Suite with Matchers
  with BeforeAndAfterAll
  with RootConnector
  with ScalaFutures
  with OptionValues {

  implicit val defaultTimeout: PatienceConfiguration.Timeout = timeout(10 seconds)

  implicit val formats = net.liftweb.json.DefaultFormats + new UUIDSerializer + new DateTimeSerializer
}

class ExampleSuite extends FreeSpec with BaseSuite with RecipesDatabase.connector.Connector {

  override def beforeAll(): Unit = {
    super.beforeAll()
    Await.ready(RecipesDatabase.autocreate().future(), 5.seconds)
  }

  override def afterAll(): Unit = {
    super.afterAll()
    Await.ready(RecipesDatabase.autotruncate().future(), 8.seconds)
  }
}


text:
using OKHOSTING.Data.Validation;
using System;

namespace OKHOSTING.Broadcasting
{
	/// <summary>
	/// An episode in a show
	/// </summary>
	public class Episode: Content
	{
		[RequiredValidator]
		public Show Show { get; set; }
	}
}


text:
import ToggleElement from './element'

customElements.define('shaf-toggle', ToggleElement)


text:
import collections
import math
class WordDistance:

    def __init__(self, words: List[str]):
        self.table = collections.defaultdict(list)
        for i, word in enumerate(words):
            self.table[word].append(i)

    def shortest(self, word1: str, word2: str) -> int:
        minDist = math.inf
        index1, index2 = self.table[word1], self.table[word2]
        p1 = p2 = 0
        while p1 < len(index1) and p2 < len(index2):
            minDist = min(minDist, abs(index1[p1] - index2[p2]))
            if index1[p1] < index2[p2]:
                p1 += 1
            else:
                p2 += 1

        return minDist

# Your WordDistance object will be instantiated and called as such:
# obj = WordDistance(words)
# param_1 = obj.shortest(word1,word2)


text:
<?php

namespace crawler;

/**
 * @link https://github.com/FriendsOfPHP/Goutte
 * @link http://api.symfony.com/2.7/Symfony/Component/DomCrawler.html
 *
 * @author nadar
 */
class Module extends \luya\base\Module
{
    public $baseUrl = null;
}


text:
{% extends 'layout.html' %}

{% block pageTitle %}
State Pension Activation
{% endblock %}

{% block content %}

  {% include 'includes/parts/phase-banner.html' %}

Have you ever lived outside the UK?

      <form action="have-you-lived-abroad" method="post">
        <fieldset class="inline">

            <legend class="visuallyhidden">Have you ever lived outside of the UK?</legend>

                You do not need to provide any details if you have served overseas with the British armed forces.

              <input id="lived-outside-yes" type="radio" name="lived-outside-select" value="Yes">
              Yes

              <input id="lived-outside-no" type="radio" name="lived-outside-select" value="No">
              No

        </fieldset>

        <input type="submit" class="button" value="Continue">
      </form>

      {% include 'includes/parts/help.html' %}

{% endblock %}