text:
@interface StoryViewController ()<UIScrollViewDelegate,UIWebViewDelegate>

@property(nonatomic, strong)UIView *view1;
@property(nonatomic, strong)UIView *view2;
@property(nonatomic, strong)UIWebView *webView1;
@property(nonatomic, strong)UIWebView *webView2;
@property(nonatomic, strong)UILabel *lblDate;
@property(nonatomic, strong)UILabel *lblTitle;
@property(nonatomic, strong)UIButton *btnBack;
@property(nonatomic, strong)UIView *topView;

@end

@implementation StoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setBodyView];
}

- (void)setBodyView{
    UIScrollView *scrolleView = [[UIScrollView alloc] initWithFrame:self.view.frame];
    scrolleView.pagingEnabled = YES;
    scrolleView.contentSize = CGSizeMake(kWindowWidth * 4, kWindowHeight);
    scrolleView.showsHorizontalScrollIndicator = NO;
    scrolleView.delegate = self;
    scrolleView.bounces = NO;
    scrolleView.contentOffset = CGPointMake(kWindowWidth, 0);
    [self.view addSubview:scrolleView];
    UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(kWindowWidth * 1, 0, self.view.frame.size.width, self.view.frame.size.height)];
    view1.backgroundColor = RgbColor(231, 231, 231);
    self.webView1 = [[UIWebView alloc] initWithFrame:CGRectMake(0, 100, kWindowWidth, kWindowHeight - 100)];
    self.webView1.delegate = self;
    self.webView1.scrollView.bounces = NO;
    UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(kWindowWidth * 2, 0, kWindowWidth, kWindowHeight)];
    view2.backgroundColor = RgbColor(231, 231, 231);
    self.webView2 = [[UIWebView alloc] initWithFrame:CGRectMake(0, 100, kWindowWidth, kWindowHeight - 100)];
    self.webView2.delegate = self;
    self.webView2.scrollView.bounces = NO;
    UIView *view1_2 = [[UIView alloc] initWithFrame:CGRectMake(kWindowWidth * 3, 0, kWindowWidth, kWindowHeight)];
    view1_2.backgroundColor = RgbColor(231, 231, 231);
    UIView *view2_2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWindowWidth, kWindowHeight)];
    view2_2.backgroundColor = RgbColor(231, 231, 231);
    UIActivityIndicatorView *activityInd1 = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:(UIActivityIndicatorViewStyleGray)];
    activityInd1.center = CGPointMake(kWindowWidth / 2.0, kWindowHeight / 2.0);
    [activityInd1 startAnimating];
    [view1 addSubview:activityInd1];
    UIActivityIndicatorView *activityInd2 = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:(UIActivityIndicatorViewStyleGray)];
    activityInd2.center = CGPointMake(kWindowWidth / 2.0, kWindowHeight / 2.0);
    [activityInd2 startAnimating];
    [view2 addSubview:activityInd2];
    UIActivityIndicatorView *activityInd3 = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:(UIActivityIndicatorViewStyleGray)];
    activityInd3.center = CGPointMake(kWindowWidth / 2.0, kWindowHeight / 2.0);
    [activityInd3 startAnimating];
    [view1_2 addSubview:activityInd3];
    UIActivityIndicatorView *activityInd4 = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:(UIActivityIndicatorViewStyleGray)];
    activityInd4.center = CGPointMake(kWindowWidth / 2.0, kWindowHeight / 2.0);
    [activityInd4 startAnimating];
    [view2_2 addSubview:activityInd4];
    self.view1 = view1;
    self.view2 = view2;
    [scrolleView addSubview:view2_2];
    [scrolleView addSubview:_view1];
    [scrolleView addSubview:_view2];
    [scrolleView addSubview:view1_2];
    [self setTopView];
}

- (void)setTopView{
    self.topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWindowWidth, 120)];
    _topView.backgroundColor = RgbColor(255, 255, 255);
    self.btnBack = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _btnBack.frame = CGRectMake(0, 0, kWindowWidth, 40);
    [_btnBack setTitle:@"返回" forState:(UIControlStateNormal)];
    _btnBack.titleLabel.textAlignment = NSTextAlignmentLeft;
    _btnBack.titleEdgeInsets = UIEdgeInsetsMake(50, -_btnBack.frame.size.width/2.0-90, 50, 30);
    [_btnBack addTarget:self action:@selector(turnBack) forControlEvents:(UIControlEventTouchUpInside)];
    [_btnBack setTitleColor:RgbColor(255, 255, 255) forState:(UIControlStateNormal)];
    [_btnBack setBackgroundColor:RgbColor(96, 196, 253)];
    self.lblDate = [[UILabel alloc] initWithFrame:CGRectMake(5, 40, kWindowWidth - 10, 20)];
    _lblDate.textColor = RgbColor(50, 50, 50);
    _lblDate.font = [UIFont systemFontOfSize:15];
    self.lblTitle = [[UILabel alloc] initWithFrame:CGRectMake(5, 65, kWindowWidth - 10, 50)];
    _lblTitle.font = [UIFont systemFontOfSize:24];
    _lblTitle.numberOfLines = 0;
    [_topView addSubview:_btnBack];
    [_topView addSubview:_lblDate];
    [_topView addSubview:_lblTitle];
}

- (void)turnBack{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    int currentPage = (int)scrollView.contentOffset.x / kWindowWidth;
    if (currentPage == 0) {
        [scrollView setContentOffset:CGPointMake(kWindowWidth * 2, 0) animated:NO];
        currentPage = 2;
    }
    if (currentPage == 3) {
        [scrollView setContentOffset:CGPointMake(kWindowWidth * 1, 0) animated:NO];
        currentPage = 1;
    }
    [self loadWebView:currentPage];
}

int currentPage = 0;
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    currentPage = 0;
    [self loadWebView:1];
}
- (void)loadWebView:(int)page{
    if (currentPage == page) {
        return;
    }
    // 可以尝试去掉这两个文件看看效果
    NSString *headPath = [[NSBundle mainBundle] pathForResource:@"head" ofType:@"html"];
    NSString *footPath = [[NSBundle mainBundle] pathForResource:@"foot" ofType:@"html"];
    NSString *strHead = [NSString stringWithContentsOfFile:headPath encoding:NSUTF8StringEncoding error:nil];
    NSString *strFoot = [NSString stringWithContentsOfFile:footPath encoding:NSUTF8StringEncoding error:nil];
    if (page == 1) {
        [LCPNetWorking getNetWorkingData:@"http://api.yue.fm/articles/random" Method:@"get" Parameter:nil CallBack:^(id object, id error) {
            NSString *html = [NSString stringWithFormat:@"%@%@%@",strHead,object[@"body"],strFoot];
            NSArray *array = [self.view1 subviews];
            for (int i = 0; i< array.count; i++) {
                [array[i] removeFromSuperview];
            }
            self.lblDate.text = object[@"date_created"];
            self.lblTitle.text = object[@"title"];
            [self.webView1 loadHTMLString:html baseURL:nil];

        }];
    }else if (page == 2){
        [LCPNetWorking getNetWorkingData:@"http://api.yue.fm/articles/random" Method:@"get" Parameter:nil CallBack:^(id object, id error) {
            NSString *html = [NSString stringWithFormat:@"%@%@%@",strHead,object[@"body"],strFoot];
            NSArray *array = [self.view1 subviews];
            for (int i = 0; i< array.count; i++) {
                [array[i] removeFromSuperview];
            }
            self.lblDate.text = object[@"date_created"];
            self.lblTitle.text = object[@"title"];
            [self.webView2 loadHTMLString:html baseURL:nil];

        }];
    }
    currentPage = page;
}

- (BOOL)prefersStatusBarHidden{
    return YES;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    if ([webView isEqual:self.webView1]) {
        [self.view1 addSubview:self.webView1];
        [self.view1 addSubview:self.topView];
        [self.webView2 removeFromSuperview];
    }else{
        [self.view2 addSubview:self.webView2];
        [self.view2 addSubview:self.topView];
        [self.webView1 removeFromSuperview];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
<?php
/*
 *
 */

namespace RDF\JobDefinitionFormatBundle\Model\JDF\Resource\Link;

use Doctrine\OXM\Mapping as OXM;

/**
 * RDF\JobDefinitionFormatBundle\Model\JDF\Resource\Link\ShapeDef
 *
 * @OXM\XmlEntity(xml="ShapeDefLink")
 */
class ShapeDefLink extends ResourceLink
{

}

redpajama_set_name: RedPajamaGithub


text:
package io.github.Cnly.WowSuchCleaner.WowSuchCleaner.listeners;

import io.github.Cnly.WowSuchCleaner.WowSuchCleaner.Main;
import io.github.Cnly.WowSuchCleaner.WowSuchCleaner.data.auction.AuctionDataManager;

import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;

public class PlayerListener implements Listener
{

    private Main main = Main.getInstance();
    private AuctionDataManager auctionDataManager = main.getAuctionDataManager();

    @EventHandler
    public void onPlayerJoin(PlayerJoinEvent e)
    {
        auctionDataManager.returnDepositInVault(e.getPlayer().getUniqueId());
    }

}


text:
package org.apache.maven.wrapper;

import static org.junit.Assert.assertEquals;

import java.io.File;
import java.net.URI;

import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Test;

public class DownloaderTest {

  private DefaultDownloader download;

  private File testDir;

  private File downloadFile;

  private File rootDir;

  private URI sourceRoot;

  private File remoteFile;

  @Before
  public void setUp() throws Exception {
    download = new DefaultDownloader("mvnw", "aVersion");
    testDir = new File("target/test-files/DownloadTest");
    rootDir = new File(testDir, "root");
    downloadFile = new File(rootDir, "file");
    remoteFile = new File(testDir, "remoteFile");
    FileUtils.write(remoteFile, "sometext");
    sourceRoot = remoteFile.toURI();
  }

  @Test
  public void testDownload() throws Exception {
    assert !downloadFile.exists();
    download.download(sourceRoot, downloadFile);
    assert downloadFile.exists();
    assertEquals("sometext", FileUtils.readFileToString(downloadFile));
  }
}


text:
package org.eclipse.ceylon.compiler.java.wrapping;

import java.util.NoSuchElementException;

import org.eclipse.ceylon.compiler.java.wrapping.Wrapping;

import ceylon.language.Finished;

/**
 * A wrapper for ceylon Iterator that satisfies {@code java.util.Iterator}
 */
class WrappedCeylonIterator<Out, In> implements java.util.Iterator<Out> {

    private final ceylon.language.Iterator<? extends In> cIterator;
    private Object next;
    private final Wrapping<In, Out> elementWrapping;

    public WrappedCeylonIterator(ceylon.language.Iterable<In,?> cSet, Wrapping<In, Out> elementWrapping) {
        cIterator = cSet.iterator();
        next = cIterator.next();
        this.elementWrapping = elementWrapping;
    }

    @Override
    public boolean hasNext() {
        return !(next instanceof Finished);
    }

    @Override
    public Out next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        Object next = this.next;
        this.next = cIterator.next();
        return (Out)elementWrapping.wrap((In)next);
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException();
    }
}


text:
package org.primeframework.mvc.security;

/**
 * Encrypt and decrypt stuff.
 *
 * @author Daniel DeGroff
 */
public interface Encryptor {
  /**
   * Decrypt a set of bytes.
   *
   * @param bytes The bytes to decrypt.
   * @return The decrypted bytes.
   */
  byte[] decrypt(byte[] bytes) throws Exception;

  /**
   * Encrypt a set of bytes.
   *
   * @param bytes The bytes to encrypt.
   * @return The encrypted bytes.
   */
  byte[] encrypt(byte[] bytes) throws Exception;
}


text: gcc *.c -o main -I /usr/local/include -Wall -Wextra -Wno-unused-parameter -std=c11 -g


text:
package org.apache.logging.log4j.core.util.internal;

import java.io.File;
import java.net.URI;

import org.apache.logging.log4j.core.util.Source;

/**
 * A Source that includes the last modified time.
 */
public class LastModifiedSource extends Source {
    private volatile long lastModified;

    public LastModifiedSource(final File file) {
        super(file);
        lastModified = 0;
    }

    public LastModifiedSource(final URI uri) {
        this(uri, 0);
    }

    public LastModifiedSource(final URI uri, long lastModifiedMillis) {
        super(uri);
        lastModified = lastModifiedMillis;
    }

    public long getLastModified() {
        return lastModified;
    }

    public void setLastModified(long lastModified) {
        this.lastModified = lastModified;
    }
}


text:
cookie_current() {
    local cookiefile=$1
    [[ -f $cookiefile ]] || return 1

    # get expiration from cookiejar -- compare to current time
    exp=$(awk '/mojolicious/ {print $5}' $cookiefile | tail -n 1)
    cur=$(date +%s)

    # compare expiration with current time
    (( $exp > $cur ))
}

to-auth () {
    [[ -z $TO_URL ]] && read -p 'Traffic Ops URL: ' TO_URL
    [[ -z $TO_USER ]] && read -p 'Traffic Ops user: ' TO_USER
    [[ -z $TO_PASSWORD ]] && read -s -p "Traffic Ops password for $TO_USER: " TO_PASSWORD

    COOKIEJAR=/tmp/cookiejar.$(echo $TO_URL $TO_USER | md5sum | awk '{print $1}')
    cookie_current $COOKIEJAR && return
    local datadir=$(mktemp -d)
    local login="$datadir/login.json"
    local url=$TO_URL/api/1.2/user/login
    local datatype='Accept: application/json'
    cat > "$login"  <<-CREDS
        { "u" : "$TO_USER", "p" : "$TO_PASSWORD" }
CREDS

    res=$(curl -k -H "$datatype" --cookie "$COOKIEJAR" --cookie-jar "$COOKIEJAR" -X POST --data @"$login" "$url")

    # clean up creds
    rm -rf $datadir
    if [[ $res != *"Successfully logged in."* ]]; then
        echo $res
        return 1
    fi
}

to-get () {
    to-auth && curl -L -k -s --cookie "$COOKIEJAR" -X GET "$TO_URL/$1"
}

# Dump the postgres db to a file from traffic ops
dump_source_db() {
    local dumpfile="$1"
    to-get api/1.2/dbdump >"$dumpfile"
}

# Prepare the destination db by terminating any existing connections and then dropping and creating the db.
prep_destination() {
    local target_db=${1:-traffic_ops}
    # export TODB_TERMINATE_CONNECTIONS=y will terminate the connections without prompting
    local ans=$TODB_TERMINATE_CONNECTIONS

    while [[ $ans != y ]]; do
        read -p "Terminating connections to $target_db.  OK? (y/n) " ans
        case $ans in
            n)
                echo "Not terminating connections"
                exit
                ;;
            y)
                break
                ;;
            *)
                echo "Answer y or n"
                ;;
        esac
    done

    # Create the sql to terminate connections -- avoid using single-quotes
    read -d% termsql <<-EOF
    SELECT pg_terminate_backend(pg_stat_activity.pid)
        FROM pg_stat_activity
        WHERE pg_stat_activity.datname = \$\$$target_db\$\$
        AND pid <> pg_backend_pid();
EOF

    # terminate any connections to the destination db -- won't complete otherwise
    echo $termsql | psql -Upostgres -h localhost
    # drop and create destination db
    dropdb -h localhost -Upostgres $target_db && createdb -Upostgres -h localhost --owner traffic_ops $target_db
}

# write cr-config
write_crconfig() {
    to-get "tools/write_crconfig/$1" >/dev/null
}

#----------------------------------------------------------------
# main starts here
#
#

usage() {
   fmt <<-USAGE
 $0 [<sql file> ...]

 $0 copies a Traffic Ops postgresql database from an existing Traffic Ops installation
 into a postgresql installation.  This must be run from a server that has access to the
 db using the psql command with the postgres user.

 The script prompts for all needed information unless the corresponding env var is
 set for each piece:

     TO_URL       - Source URL for traffic_ops

     TO_USER      - User to authenticate (requires admin privileges for db dump)

     TO_PASSWORD  - Password for above user

     TO_DEST_URL  - Destination URL for traffic_ops on the local machine (the one to be overwritten)

     TODB_TERMINATE_CONNECTIONS - set to "y" for current database connections to be forced off (NOTE:
      this is required for the database to be replaced)

 To run this script from an automated system (e.g. Jenkins or some other CI system),  set each of the
 above variables.

 Any sql files listed on the command line are executed on the database once copied.  This allows for
 adjusting to a different set of servers, for example..
USAGE
    exit
}

while getopts ":h" opt; do
  case ${opt} in
    h ) usage ;;
  esac
done

target_db=traffic_ops

# Create a tmp path to collect the dump
dumpfile=$(mktemp --tmpdir=/tmp pg-XXX.dump)
cat >$dumpfile </dev/null
cleanup() {
    rm -f $dumpfile
}
trap cleanup EXIT

# Dump db to dump file
echo "Dumping db to $dumpfile"
dump_source_db "$dumpfile"

# Check validity of dump before proceeding
pg_restore -l "$dumpfile" > /dev/null
if [[ $? -ne 0 ]] ; then
	exit 1
fi

echo "Prepping destination $dumpfile"
prep_destination traffic_ops

echo "Restoring from $dumpfile"
pg_restore --verbose --clean --create -h localhost -U postgres -d traffic_ops <$dumpfile

if [[ $# > 0 ]]; then
        for a in "$@"; do
                [[ $a == *.sql ]] || continue
                echo "Loading $a"
                psql -h localhost -U postgres -d traffic_ops -f "$a"
        done
fi
(cd /opt/traffic_ops/app;  PATH=$PATH:/opt/traffic_ops/go/bin ./db/admin -env production upgrade)

TO_URL=$TO_DEST_URL
echo "Snapshotting CRConfigs on $TO_URL"

# get the list of cdns from the copied db
cdns=$(to-get api/1.3/cdns | jq -Sr '.response|.[]|.name' | grep -v ALL)

for c in $cdns; do
    write_crconfig "$c"
done


text:
package org.multibit.hd.ui.views.wizards.exit;

/**
 *
Enum to provide the following to exit wizard model:

 *

 *
State identification

 *

 *
 * @since 0.0.1
 *
 */
public enum ExitState {

  SELECT_RESET_OPTION,
  CONFIRM_EXIT,
  SWITCH_WALLET,

  // End of enum
  ;

}


text:
Function New-NgCrudServiceViaBoxTurtleNgTsToString($entity, [bool]$create, [bool]$read, [bool]$update, [bool]$delete, [bool]$list, [bool]$filter) {
	$entityCapital = (ConvertTo-CapitalCamelCase $entity)
	$entityLowerCamel = (ConvertTo-LowerCamelCase $entity)
	$entityLowerKebab = (ConvertTo-KebabCase $entity)

	# Give the box-turtle-ng method a list of comma delimited verbs
	# and let it deal with it
	[string]$verbList = ""
	if($create -eq $true) {
		$verbList += '"create",'
	}
	if($read -eq $true) {
		$verbList += '"get",'
	}
	if($update -eq $true) {
		$verbList += '"update",'
	}
	if($delete -eq $true) {
		$verbList += '"delete",'
	}
	if($list -eq $true) {
		$verbList += '"list",'
	}
	if($filter -eq $true) {
		$verbList += '"filter",'
	}
	#remove final comma
	$verbList = $verbList -replace ".$"

return @"
import { Injectable }    from '@angular/core';
import { Http } from '@angular/http';
import { GenericCrudService } from 'box-turtle-ng';
import { $entityCapital } from '../model/$($entityLowerKebab)';

@Injectable()
export class $($entityCapital)Service extends GenericCrudService<$($entityCapital)> {

    constructor(http: Http) {
        super(http, '/api/$($entityLowerCamel)', [$verbList]);
    }

}
"@;
}


text:
USE InsideTSQL2008;
GO

DECLARE @empid AS INT = 1;

SELECT
  custid,
  CASE WHEN custid IN (
      SELECT custid
      FROM Sales.Orders AS O
      WHERE O.empid = @empid
    ) THEN 1 ELSE 0 END AS charfun
FROM Sales.Customers AS C
GO


text:
/* Includes ------------------------------------------------------------------*/
#include "main.h"

/** @addtogroup STM32F4xx_StdPeriph_Examples
  * @{
  */

/** @addtogroup RTC_Tamper
  * @{
  */

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
#define RTC_BKP_DR_NUMBER              20  /* RTC Backup Data Register Number */

/* Uncomment the corresponding line to select the RTC Clock source */
#define RTC_CLOCK_SOURCE_LSE            /* LSE used as RTC source clock */
/* #define RTC_CLOCK_SOURCE_LSI */      /* LSI used as RTC source clock. The RTC Clock
                                           may varies due to LSI frequency dispersion. */

/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
uint32_t aRTC_BKP_DR[RTC_BKP_DR_NUMBER] =
  {
    RTC_BKP_DR0, RTC_BKP_DR1, RTC_BKP_DR2, RTC_BKP_DR3,
    RTC_BKP_DR4, RTC_BKP_DR5, RTC_BKP_DR6, RTC_BKP_DR7,
    RTC_BKP_DR8, RTC_BKP_DR9, RTC_BKP_DR10, RTC_BKP_DR11,
    RTC_BKP_DR12, RTC_BKP_DR13, RTC_BKP_DR14, RTC_BKP_DR15,
    RTC_BKP_DR16, RTC_BKP_DR17, RTC_BKP_DR18, RTC_BKP_DR19
  };

/* Private functions prototypes ----------------------------------------------*/
static void     RTC_Config(void);
static void     WriteToRTC_BKP_DR(uint32_t FirstRTCBackupData);
static uint32_t CheckRTC_BKP_DR(uint32_t FirstRTCBackupData);

/* Private functions ---------------------------------------------------------*/

/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  /*!< At this stage the microcontroller clock setting is already configured,
       this is done through SystemInit() function which is called from startup
       files (startup_stm32f40_41xxx.s/startup_stm32f427_437xx.s)
       before to branch to application main.
     */

  /* Initialize Leds mounted on EVAL board */
  STM_EVAL_LEDInit(LED1);
  STM_EVAL_LEDInit(LED2);
  STM_EVAL_LEDInit(LED3);
  STM_EVAL_LEDInit(LED4);

  /* RTC configuration */
  RTC_Config();

  /* Write To RTC Backup Data registers */
  WriteToRTC_BKP_DR(0xA53C);

  /* Check if the written data are correct */
  if(CheckRTC_BKP_DR(0xA53C) == 0)
  {
    /* Turn on LED1 */
    STM_EVAL_LEDOn(LED1);
  }
  else
  {
    /* Turn on LED3 */
    STM_EVAL_LEDOn(LED3);
  }

  while (1)
  {
  }
}

/**
  * @brief  Configure the RTC peripheral by selecting the clock source.
  * @param  None
  * @retval None
  */
void RTC_Config(void)
{
  NVIC_InitTypeDef NVIC_InitStructure;
  EXTI_InitTypeDef  EXTI_InitStructure;

  /* Enable the PWR clock */
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR, ENABLE);

  /* Allow access to RTC */
  PWR_BackupAccessCmd(ENABLE);

  /* Reset BKP Domain */
  RCC_BackupResetCmd(ENABLE);
  RCC_BackupResetCmd(DISABLE);

#if defined (RTC_CLOCK_SOURCE_LSI)  /* LSI used as RTC source clock*/
/* The RTC Clock may varies due to LSI frequency dispersion. */
  /* Enable the LSI OSC */
  RCC_LSICmd(ENABLE);

  /* Wait till LSI is ready */
  while(RCC_GetFlagStatus(RCC_FLAG_LSIRDY) == RESET)
  {
  }

  /* Select the RTC Clock Source */
  RCC_RTCCLKConfig(RCC_RTCCLKSource_LSI);

#elif defined (RTC_CLOCK_SOURCE_LSE) /* LSE used as RTC source clock */
  /* Enable the LSE OSC */
  RCC_LSEConfig(RCC_LSE_ON);

  /* Wait till LSE is ready */
  while(RCC_GetFlagStatus(RCC_FLAG_LSERDY) == RESET)
  {
  }

  /* Select the RTC Clock Source */
  RCC_RTCCLKConfig(RCC_RTCCLKSource_LSE);

#else
  #error Please select the RTC Clock source inside the main.c file
#endif /* RTC_CLOCK_SOURCE_LSI */

  /* Enable The external line21 interrupt */
  EXTI_ClearITPendingBit(EXTI_Line21);
  EXTI_InitStructure.EXTI_Line = EXTI_Line21;
  EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
  EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising;
  EXTI_InitStructure.EXTI_LineCmd = ENABLE;
  EXTI_Init(&EXTI_InitStructure);

  /* Enable TAMPER IRQChannel */
  NVIC_InitStructure.NVIC_IRQChannel = TAMP_STAMP_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);

  /* Disable the Tamper 1 detection */
  RTC_TamperCmd(RTC_Tamper_1, DISABLE);

  /* Clear Tamper 1 pin Event(TAMP1F) pending flag */
  RTC_ClearFlag(RTC_FLAG_TAMP1F);

  /* Configure the Tamper 1 Trigger */
  RTC_TamperTriggerConfig(RTC_Tamper_1, RTC_TamperTrigger_FallingEdge);

  /* Enable the Tamper interrupt */
  RTC_ITConfig(RTC_IT_TAMP, ENABLE);

  /* Clear Tamper 1 pin interrupt pending bit */
  RTC_ClearITPendingBit(RTC_IT_TAMP1);

  /* Enable the Tamper 1 detection */
  RTC_TamperCmd(RTC_Tamper_1, ENABLE);
}

/**
  * @brief  Writes data RTC Backup DRx registers.
  * @param  FirstRTCBackupData: data to be written to RTC Backup data registers.
  * @retval None
  */
static void WriteToRTC_BKP_DR(uint32_t FirstRTCBackupData)
{
  uint32_t index = 0;

  for (index = 0; index < RTC_BKP_DR_NUMBER; index++)
  {
    /* write To bkp data register */
    RTC_WriteBackupRegister(aRTC_BKP_DR[index], FirstRTCBackupData + (index * 0x5A));
  }
}

/**
  * @brief  Checks if the RTC Backup DRx registers values are correct or not.
  * @param  FirstRTCBackupData: data to be compared with RTC Backup data registers.
  * @retval - 0: All RTC Backup DRx registers values are correct
  *         - Value different from 0: Number of the first Backup register
  *           which value is not correct
  */
static uint32_t CheckRTC_BKP_DR(uint32_t FirstRTCBackupData)
{
  uint32_t index = 0;

  for (index = 0; index < RTC_BKP_DR_NUMBER; index++)
  {
    /* Read from data register */
    if (RTC_ReadBackupRegister(aRTC_BKP_DR[index]) != (FirstRTCBackupData + (index * 0x5A)))
    {
      return (index + 1);
    }
  }
    return 0;
}

/**
  * @brief  Checks if the RTC Backup DRx registers are reset or not.
  * @param  None
  * @retval - 0: All RTC Backup DRx registers are reset
  *         - Value different from 0: Number of the first Backup register
  *           not reset
  */
uint32_t IsBackupRegReset(void)
{
  uint32_t index = 0;

  for (index = 0; index < RTC_BKP_DR_NUMBER; index++)
  {
     /* Read from bkp Data Register */
    if (RTC_ReadBackupRegister(aRTC_BKP_DR[index]) != 0)
    {
      return (index + 1);
    }
  }
  return 0;
}

#ifdef  USE_FULL_ASSERT

/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t* file, uint32_t line)
{
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */

  /* Infinite loop */
  while (1)
  {
  }
}
#endif

/**
  * @}
  */

/**
  * @}
  */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/


text:
<?php

namespace Tests\EasySoapClient;

use EasySoapClient\Client;
use EasySoapClient\Context\StreamContext;
use EasySoapClient\Options\Options;
use EasySoapClient\Options\AuthOptions;
use EasySoapClient\Configuration;
use EasySoapClient\Options\OtherOptions;
use EasySoapClient\Options\ProxyOptions;
use PHPUnit\Framework\TestCase;

/**
 * Class SoapClientTest
 * @package Tests\EasySoapClient
 */
class SoapClientTest extends TestCase
{

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

    protected function setUp()
    {
        $this->config = new Configuration(
            'http://www.dneonline.com/calculator.asmx?WSDL'
        );
    }

    public function testSoapClientConfigurationInstance()
    {
        $this->assertInstanceOf('EasySoapClient\Configuration', $this->config);
    }

    public function testSoapClientInstance()
    {
        $client = (new Client($this->config))->getClient();
        $this->assertInstanceOf('SoapClient', $client);
    }

    public function testSoapClientOptionsInstance()
    {
        $proxy = (new ProxyOptions('localhost', 80, 'easy-soapclient', '123'))->get();
        $auth = (new AuthOptions('easy-soapclient', 1))->get();
        $options = (new Options($proxy, $auth));

        $this->assertInstanceOf('EasySoapClient\Options\Options', $options);
    }

    public function testSoapClientOptionsType()
    {
        $proxy = (new ProxyOptions('localhost', 80, 'easy-soapclient', '123'))->get();
        $auth = (new AuthOptions('easy-soapclient', 1))->get();
        $options = (new Options($proxy, $auth))->getOptions();
        $this->assertInternalType('array', $options);
    }

    public function testSoapClientProxyType()
    {
        $proxy = (new ProxyOptions('localhost', 80, 'easy-soapclient', '123'))->get();
        $this->assertInternalType('array', $proxy);
    }

    public function testSoapClientAuthType()
    {
        $auth = (new AuthOptions('easy-soapclient', 1))->get();
        $this->assertInternalType('array', $auth);
    }

    public function testSoapClientStreamContextIsNotEmpty()
    {
        $context = (new StreamContext())->get();
        $this->assertNotEmpty($context);
    }

    public function testSoapClientOptionsIsNotEmpty()
    {
        $options = (new Options([], []))->getOptions();
        $this->assertNotEmpty($options);
    }

    public function testSoapClientResult()
    {
        $consume = (new Client($this->config))->getClient();
        $this->assertNotEmpty($consume);
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage Url is empty
     */
    public function testSoapClientUrlConfigurationException()
    {
        $config = new Configuration(
            ''
        );

        (new Client($config));
    }

    public function testSoapClientOtherOptions()
    {
        $options = (new Options([], []))->getOptions();
        $this->assertEquals(SOAP_1_2, $options['soap_version']);

        $otherOptions = new OtherOptions(SOAP_1_1);
        $options = (new Options([], [], $otherOptions->get()))->getOptions();

        $this->assertEquals(SOAP_1_1, $options['soap_version']);
    }
}


text:
import React from 'react';
import CircularProgress from 'material-ui/CircularProgress';

export default function Loading ({ message }) {

  return (

{message}

      <CircularProgress style={{margin: 0}}/>

  );
}


text:
TimeoutWait::TimeoutWait(long long value) : m_remaining(value)
{
}

std::cv_status TimeoutWait::Wait(std::condition_variable& conditional, std::mutex& mutex)
{
  LogEvent(Trace, "Timer set for " << m_remaining << " milliseconds");
  std::unique_lock<std::mutex> lock(mutex);
  return conditional.wait_for(lock, std::chrono::milliseconds(m_remaining));
}

long long TimeoutWait::Remaining()
{
  return m_remaining;
}

std::cv_status TimeoutExpired::Wait(std::condition_variable& conditional, std::mutex& mutex)
{
  return std::cv_status::timeout;
}

long long TimeoutExpired::Remaining()
{
  LogEvent(Trace, "Timer has already expired");
  return -1;
}

std::cv_status NoTimeout::Wait(std::condition_variable& conditional, std::mutex& mutex)
{
  std::unique_lock<std::mutex> lock(mutex);
  conditional.wait(lock);
  return std::cv_status::no_timeout;
}

long long NoTimeout::Remaining()
{
  return 0;
}

TimeoutPtr TimeoutFactory::CreateTimeout(long long timeout)
{
  if (timeout > 0)
    return std::make_shared<TimeoutWait>(timeout);

  if (timeout < 0)
    return std::make_shared<TimeoutExpired>();

  return std::make_shared<NoTimeout>();
}


text:
kubectl.sh create -f $(dirname $0)/els-ctrl.yaml

# now add controller
kubectl.sh create -f $(dirname $0)/kibana-ctrl.yaml

# now add services
kubectl.sh create -f $(dirname $0)/els-service.yaml
kubectl.sh create -f $(dirname $0)/kibana-service.yaml


text:
#include "config.h"
#include "FindController.h"

#include "ShareableBitmap.h"
#include "WKPage.h"
#include "WebCoreArgumentCoders.h"
#include "WebPage.h"
#include "WebPageProxyMessages.h"
#include "WebProcess.h"
#include <WebCore/DocumentMarkerController.h>
#include <WebCore/FloatQuad.h>
#include <WebCore/FocusController.h>
#include <WebCore/Frame.h>
#include <WebCore/FrameView.h>
#include <WebCore/GraphicsContext.h>
#include <WebCore/Page.h>

using namespace std;
using namespace WebCore;

namespace WebKit {

static WebCore::FindOptions core(FindOptions options)
{
    return (options & FindOptionsCaseInsensitive ? CaseInsensitive : 0)
        | (options & FindOptionsAtWordStarts ? AtWordStarts : 0)
        | (options & FindOptionsTreatMedialCapitalAsWordStart ? TreatMedialCapitalAsWordStart : 0)
        | (options & FindOptionsBackwards ? Backwards : 0)
        | (options & FindOptionsWrapAround ? WrapAround : 0);
}

FindController::FindController(WebPage* webPage)
    : m_webPage(webPage)
    , m_findPageOverlay(0)
    , m_isShowingFindIndicator(false)
{
}

FindController::~FindController()
{
}

void FindController::countStringMatches(const String& string, FindOptions options, unsigned maxMatchCount)
{
    if (maxMatchCount == numeric_limits<unsigned>::max())
        --maxMatchCount;

    unsigned matchCount = m_webPage->corePage()->markAllMatchesForText(string, core(options), false, maxMatchCount + 1);
    m_webPage->corePage()->unmarkAllTextMatches();

    // Check if we have more matches than allowed.
    if (matchCount > maxMatchCount)
        matchCount = static_cast<unsigned>(kWKMoreThanMaximumMatchCount);

    m_webPage->send(Messages::WebPageProxy::DidCountStringMatches(string, matchCount));
}

static Frame* frameWithSelection(Page* page)
{
    for (Frame* frame = page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
        if (frame->selection()->isRange())
            return frame;
    }

    return 0;
}

void FindController::updateFindUIAfterPageScroll(bool found, const String& string, FindOptions options, unsigned maxMatchCount)
{
    Frame* selectedFrame = frameWithSelection(m_webPage->corePage());

    bool shouldShowOverlay = false;

    if (!found) {
        m_webPage->corePage()->unmarkAllTextMatches();

        // Clear the selection.
        if (selectedFrame)
            selectedFrame->selection()->clear();

        hideFindIndicator();

        m_webPage->send(Messages::WebPageProxy::DidFailToFindString(string));
    } else {
        shouldShowOverlay = options & FindOptionsShowOverlay;
        bool shouldShowHighlight = options & FindOptionsShowHighlight;
        unsigned matchCount = 1;

        if (shouldShowOverlay || shouldShowHighlight) {

            if (maxMatchCount == numeric_limits<unsigned>::max())
                --maxMatchCount;

            m_webPage->corePage()->unmarkAllTextMatches();
            matchCount = m_webPage->corePage()->markAllMatchesForText(string, core(options), shouldShowHighlight, maxMatchCount + 1);

            // Check if we have more matches than allowed.
            if (matchCount > maxMatchCount) {
                shouldShowOverlay = false;
                matchCount = static_cast<unsigned>(kWKMoreThanMaximumMatchCount);
            }
        }

        m_webPage->send(Messages::WebPageProxy::DidFindString(string, matchCount));

        if (!(options & FindOptionsShowFindIndicator) || !updateFindIndicator(selectedFrame, shouldShowOverlay)) {
            // Either we shouldn't show the find indicator, or we couldn't update it.
            hideFindIndicator();
        }
    }

    if (!shouldShowOverlay) {
        if (m_findPageOverlay) {
            // Get rid of the overlay.
            m_webPage->uninstallPageOverlay(m_findPageOverlay, false);
        }

        ASSERT(!m_findPageOverlay);
    } else {
        if (!m_findPageOverlay) {
            RefPtr<PageOverlay> findPageOverlay = PageOverlay::create(this);
            m_findPageOverlay = findPageOverlay.get();
            m_webPage->installPageOverlay(findPageOverlay.release());
        } else {
            // The page overlay needs to be repainted.
            m_findPageOverlay->setNeedsDisplay();
        }
    }
}

void FindController::findString(const String& string, FindOptions options, unsigned maxMatchCount)
{
    bool found = m_webPage->corePage()->findString(string, core(options));

    m_webPage->drawingArea()->dispatchAfterEnsuringUpdatedScrollPosition(WTF::bind(&FindController::updateFindUIAfterPageScroll, this, found, string, options, maxMatchCount));
}

void FindController::hideFindUI()
{
    if (m_findPageOverlay)
        m_webPage->uninstallPageOverlay(m_findPageOverlay, false);

    m_webPage->corePage()->unmarkAllTextMatches();
    hideFindIndicator();
}

bool FindController::updateFindIndicator(Frame* selectedFrame, bool isShowingOverlay, bool shouldAnimate)
{
    if (!selectedFrame)
        return false;

    IntRect selectionRect = enclosingIntRect(selectedFrame->selection()->bounds());

    // Selection rect can be empty for matches that are currently obscured from view.
    if (selectionRect.isEmpty())
        return false;

    // We want the selection rect in window coordinates.
    IntRect selectionRectInWindowCoordinates = selectedFrame->view()->contentsToWindow(selectionRect);

    Vector<FloatRect> textRects;
    selectedFrame->selection()->getClippedVisibleTextRectangles(textRects);

    IntSize backingStoreSize = selectionRect.size();
    backingStoreSize.scale(m_webPage->corePage()->deviceScaleFactor());

    // Create a backing store and paint the find indicator text into it.
    RefPtr<ShareableBitmap> findIndicatorTextBackingStore = ShareableBitmap::createShareable(backingStoreSize, ShareableBitmap::SupportsAlpha);
    if (!findIndicatorTextBackingStore)
        return false;

    OwnPtr<GraphicsContext> graphicsContext = findIndicatorTextBackingStore->createGraphicsContext();
    graphicsContext->scale(FloatSize(m_webPage->corePage()->deviceScaleFactor(), m_webPage->corePage()->deviceScaleFactor()));

    IntRect paintRect = selectionRect;
    paintRect.move(selectedFrame->view()->frameRect().x(), selectedFrame->view()->frameRect().y());
    paintRect.move(-selectedFrame->view()->scrollOffset());

    graphicsContext->translate(-paintRect.x(), -paintRect.y());
    selectedFrame->view()->setPaintBehavior(PaintBehaviorSelectionOnly | PaintBehaviorForceBlackText | PaintBehaviorFlattenCompositingLayers);
    selectedFrame->document()->updateLayout();

    selectedFrame->view()->paint(graphicsContext.get(), paintRect);
    selectedFrame->view()->setPaintBehavior(PaintBehaviorNormal);

    ShareableBitmap::Handle handle;
    if (!findIndicatorTextBackingStore->createHandle(handle))
        return false;

    // We want the text rects in selection rect coordinates.
    Vector<FloatRect> textRectsInSelectionRectCoordinates;

    for (size_t i = 0; i < textRects.size(); ++i) {
        IntRect textRectInSelectionRectCoordinates = selectedFrame->view()->contentsToWindow(enclosingIntRect(textRects[i]));
        textRectInSelectionRectCoordinates.move(-selectionRectInWindowCoordinates.x(), -selectionRectInWindowCoordinates.y());

        textRectsInSelectionRectCoordinates.append(textRectInSelectionRectCoordinates);
    }

    m_webPage->send(Messages::WebPageProxy::SetFindIndicator(selectionRectInWindowCoordinates, textRectsInSelectionRectCoordinates, m_webPage->corePage()->deviceScaleFactor(), handle, !isShowingOverlay, shouldAnimate));
    m_findIndicatorRect = selectionRectInWindowCoordinates;
    m_isShowingFindIndicator = true;

    return true;
}

void FindController::hideFindIndicator()
{
    if (!m_isShowingFindIndicator)
        return;

    ShareableBitmap::Handle handle;
    m_webPage->send(Messages::WebPageProxy::SetFindIndicator(FloatRect(), Vector<FloatRect>(), m_webPage->corePage()->deviceScaleFactor(), handle, false, true));
    m_isShowingFindIndicator = false;
}

void FindController::showFindIndicatorInSelection()
{
    Frame* selectedFrame = m_webPage->corePage()->focusController()->focusedOrMainFrame();
    if (!selectedFrame)
        return;

    updateFindIndicator(selectedFrame, false);
}

void FindController::deviceScaleFactorDidChange()
{
    ASSERT(isShowingOverlay());

    Frame* selectedFrame = frameWithSelection(m_webPage->corePage());
    if (!selectedFrame)
        return;

    updateFindIndicator(selectedFrame, true, false);
}

Vector<IntRect> FindController::rectsForTextMatches()
{
    Vector<IntRect> rects;

    for (Frame* frame = m_webPage->corePage()->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
        Document* document = frame->document();
        if (!document)
            continue;

        IntRect visibleRect = frame->view()->visibleContentRect();
        Vector<IntRect> frameRects = document->markers()->renderedRectsForMarkers(DocumentMarker::TextMatch);
        IntPoint frameOffset(-frame->view()->scrollOffset().width(), -frame->view()->scrollOffset().height());
        frameOffset = frame->view()->convertToContainingWindow(frameOffset);

        for (Vector<IntRect>::iterator it = frameRects.begin(), end = frameRects.end(); it != end; ++it) {
            it->intersect(visibleRect);
            it->move(frameOffset.x(), frameOffset.y());
            rects.append(*it);
        }
    }

    return rects;
}

void FindController::pageOverlayDestroyed(PageOverlay*)
{
}

void FindController::willMoveToWebPage(PageOverlay*, WebPage* webPage)
{
    if (webPage)
        return;

    // The page overlay is moving away from the web page, reset it.
    ASSERT(m_findPageOverlay);
    m_findPageOverlay = 0;
}

void FindController::didMoveToWebPage(PageOverlay*, WebPage*)
{
}

static const float shadowOffsetX = 0.0;
static const float shadowOffsetY = 1.0;
static const float shadowBlurRadius = 2.0;
static const float whiteFrameThickness = 1.0;

static const float overlayBackgroundRed = 0.1;
static const float overlayBackgroundGreen = 0.1;
static const float overlayBackgroundBlue = 0.1;
static const float overlayBackgroundAlpha = 0.25;

static Color overlayBackgroundColor(float fractionFadedIn)
{
    return Color(overlayBackgroundRed, overlayBackgroundGreen, overlayBackgroundBlue, overlayBackgroundAlpha * fractionFadedIn);
}

static Color holeShadowColor(float fractionFadedIn)
{
    return Color(0.0f, 0.0f, 0.0f, fractionFadedIn);
}

static Color holeFillColor(float fractionFadedIn)
{
    return Color(1.0f, 1.0f, 1.0f, fractionFadedIn);
}

void FindController::drawRect(PageOverlay* pageOverlay, GraphicsContext& graphicsContext, const IntRect& dirtyRect)
{
    float fractionFadedIn = pageOverlay->fractionFadedIn();

    Vector<IntRect> rects = rectsForTextMatches();

    // Draw the background.
    graphicsContext.fillRect(dirtyRect, overlayBackgroundColor(fractionFadedIn), ColorSpaceSRGB);

    {
        GraphicsContextStateSaver stateSaver(graphicsContext);

        graphicsContext.setShadow(FloatSize(shadowOffsetX, shadowOffsetY), shadowBlurRadius, holeShadowColor(fractionFadedIn), ColorSpaceSRGB);
        graphicsContext.setFillColor(holeFillColor(fractionFadedIn), ColorSpaceSRGB);

        // Draw white frames around the holes.
        for (size_t i = 0; i < rects.size(); ++i) {
            IntRect whiteFrameRect = rects[i];
            whiteFrameRect.inflate(1);

            graphicsContext.fillRect(whiteFrameRect);
        }
    }

    graphicsContext.setFillColor(Color::transparent, ColorSpaceSRGB);

    // Clear out the holes.
    for (size_t i = 0; i < rects.size(); ++i)
        graphicsContext.fillRect(rects[i]);

    if (!m_isShowingFindIndicator)
        return;

    if (Frame* selectedFrame = frameWithSelection(m_webPage->corePage())) {
        IntRect findIndicatorRect = selectedFrame->view()->contentsToWindow(enclosingIntRect(selectedFrame->selection()->bounds()));

        if (findIndicatorRect != m_findIndicatorRect)
            hideFindIndicator();
    }
}

bool FindController::mouseEvent(PageOverlay*, const WebMouseEvent& mouseEvent)
{
    // If we get a mouse down event inside the page overlay we should hide the find UI.
    if (mouseEvent.type() == WebEvent::MouseDown) {
        // Dismiss the overlay.
        hideFindUI();
    }

    return false;
}

} // namespace WebKit


text:
<?php

namespace OLAP4PHP\Provider\XMLA;

// Interfaces
use OLAP4PHP\Metadata\ILevel;
use OLAP4PHP\Metadata\INamed;

//Classes
use OLAP4PHP\Metadata\LevelType;
use OLAP4PHP\Provider\XMLA\Metadata\LazyMetadataList;
use OLAP4PHP\Provider\XMLA\Metadata\XMLAPropertyHandler;
use OLAP4PHP\Metadata\DimensionType;
use OLAP4PHP\Provider\XMLA\Metadata\XMLAMemberHandler;
use OLAP4PHP\Common\NamedList;
use OLAP4PHP\Metadata\StandardMemberProperty;
use OLAP4PHP\Provider\XMLA\Metadata\XMLAMeasureHandler;

/**
 * XMLA Implementation of ILevel Interface
 */
class XMLALevel extends XMLAElement implements ILevel, INamed
{
   public $hierarchy;
   private $depth;
   private $type;
   private $cardinality;
   private $propertyList;
   public $memberList;
   private $calculated;

   /**
    * Constructor
    *
    * @param XMLAHierarchy $hierarchy
    * @param string        $uniqueName  Unique name
    * @param string        $name        Name
    * @param string        $caption     Caption
    * @param string        $description Description
    * @param integer       $depth       Distance to root
    * @param LevelType     $type        Level type
    * @param boolean       $calculated  Whether level is calculated
    * @param integer       $cardinality Number of members in this level
    */
   public function __construct(
      XMLAHierarchy $hierarchy,
      $uniqueName,
      $name,
      $caption,
      $description,
      $depth,
      LevelType $type = NULL,
      $calculated,
      $cardinality
   )
   {
      parent::__construct( $uniqueName, $name, $caption, $description );
      assert( $hierarchy != null );
      $this->type        = $type;
      $this->calculated  = $calculated;
      $this->cardinality = $cardinality;
      $this->depth       = $depth;
      $this->hierarchy   = $hierarchy;

      $levelRestrictions = array(
         "CATALOG_NAME"          => $hierarchy->getDimension()->getCube()->getSchema()->getCatalog()->getName(),
         "SCHEMA_NAME"           => $hierarchy->getDimension()->getCube()->getSchema()->getName(),
         "CUBE_NAME"             => $hierarchy->getDimension()->getCube()->getName(),
         "DIMENSION_UNIQUE_NAME" => $hierarchy->getDimension()->getUniqueName(),
         "HIERARCHY_UNIQUE_NAME" => $hierarchy->getUniqueName(),
         "LEVEL_UNIQUE_NAME"     => $this->getUniqueName()
      );

      $this->propertyList = new LazyMetadataList (
         new XMLAMetadataRequest(XMLAMetadataRequest::MDSCHEMA_PROPERTIES),
         XMLAConnectionContext::createAtLevel( $this ),
         new XMLAPropertyHandler (),
         $levelRestrictions);

      try
      {
         if ( $hierarchy->getDimension()->getDimensionType() == DimensionType::getEnum( DimensionType::MEASURE ) )
         {
            $restrictions = array(
               "CATALOG_NAME"          => $hierarchy->getDimension()->getCube()->getSchema()->getCatalog()->getName(),
               "SCHEMA_NAME"           => $hierarchy->getDimension()->getCube()->getSchema()->getName(),
               "CUBE_NAME"             => $hierarchy->getDimension()->getCube()->getName()
            );

            $this->memberList =
               new LazyMetadataList (
                  new XMLAMetadataRequest(XMLAMetadataRequest::MDSCHEMA_MEASURES),
                  new XMLAConnectionContext (
                     $hierarchy->getDimension()->getCube()->getSchema()->getCatalog()->getMetadata()->getConnection(),
                     $hierarchy->getDimension()->getCube()->getSchema()->getCatalog()->getMetadata(),
                     $hierarchy->getDimension()->getCube()->getSchema()->getCatalog(),
                     $hierarchy->getDimension()->getCube()->getSchema(),
                     $hierarchy->getDimension()->getCube(),
                     $hierarchy->getDimension(),
                     $hierarchy,
                     $this),
                  new XMLAMeasureHandler (
                     $hierarchy->getDimension(),
                     $restrictions));
         }
         else
         {
            $this->memberList =
               new LazyMetadataList (
                  new XMLAMetadataRequest(XMLAMetadataRequest::MDSCHEMA_MEMBERS),
                  new XMLAConnectionContext (
                     $hierarchy->getDimension()->getCube()->getSchema()->getCatalog()->getMetadata()->getConnection(),
                     $hierarchy->getDimension()->getCube()->getSchema()->getCatalog()->getMetadata(),
                     $hierarchy->getDimension()->getCube()->getSchema()->getCatalog(),
                     $hierarchy->getDimension()->getCube()->getSchema(),
                     $hierarchy->getDimension()->getCube(),
                     $hierarchy->getDimension(),
                     $hierarchy,
                     $this),
                  new XMLAMemberHandler (),
                  $levelRestrictions);
         }
      }
      catch ( OlapException $e )
      {
         throw new RuntimeException ("Programming error", $e);
      }
   }

   public function getDepth()
   {
      return $this->depth;
   }

   public function getHierarchy()
   {
      return $this->hierarchy;
   }

   public function getDimension()
   {
      return $this->hierarchy->getDimension();
   }

   public function isCalculated()
   {
      return $this->calculated;
   }

   /**
    * return LevelType
    */
   public function getLevelType()
   {
      return $this->type;
   }

   /**
    * @return NamedList
    */
   public function getProperties()
   {
      // standard properties first
      $list = new NamedList (StandardMemberProperty::getEnumConstants());
      // then level-specific properties
      $list->addAll( $this->propertyList );

      return $list;
   }

   public function getMembers()
   {
      return $this->memberList;
   }

   public function getCardinality()
   {
      return $this->cardinality;
   }

   public function isVisible()
   {
      return TRUE;
   }
}


text:
module Outbox
  module DefineInheritableMethod
    # Similar to .define_method, but adds a dynamic module in the inheritance
    # change to attach the method to. See:
    #
    # http://thepugautomatic.com/2013/07/dsom/
    def define_inheritable_method(mod_name, *args, &block)
      mod = get_inheritable_module(mod_name)
      mod.module_eval do
        define_method(*args, &block)
      end
    end

    protected

    def get_inheritable_module(mod_name)
      if const_defined?(mod_name, false)
        const_get(mod_name)
      else
        include const_set(mod_name, Module.new)
      end
    end
  end
end


text:
<?php

/**
 * Client = Plugin
 * Client Server = API Methods the Plugin must respond to
 */
class Jetpack_Client_Server {

	function authorize() {
		$data = stripslashes_deep( $_GET );
		$redirect = isset( $data['redirect'] ) ? esc_url_raw( (string) $data['redirect'] ) : '';

		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
		// Checking if site has been active/connected previously before recording unique connection
		if ( ! $jetpack_unique_connection ) {
			// jetpack_unique_connection option has never been set
			$jetpack_unique_connection = array(
				'connected'     => 0,
				'disconnected'  => 0,
				'version'       => '3.6.1'
			);

			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );

			//track unique connection
			$jetpack = Jetpack::init();

			$jetpack->stat( 'connections', 'unique-connection' );
			$jetpack->do_stats( 'server_side' );
		}

		// increment number of times connected
		$jetpack_unique_connection['connected'] += 1;
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );

		do {
			$jetpack = $this->get_jetpack();
			$role = $jetpack->translate_current_user_to_role();

			if ( !$role ) {
				Jetpack::state( 'error', 'no_role' );
				break;
			}

			$cap = $jetpack->translate_role_to_cap( $role );
			if ( !$cap ) {
				Jetpack::state( 'error', 'no_cap' );
				break;
			}

			$this->check_admin_referer( "jetpack-authorize_{$role}_{$redirect}" );

			if ( !empty( $data['error'] ) ) {
				Jetpack::state( 'error', $data['error'] );
				break;
			}

			if ( empty( $data['state'] ) ) {
				Jetpack::state( 'error', 'no_state' );
				break;
			}

			if ( !ctype_digit( $data['state'] ) ) {
				Jetpack::state( 'error', 'invalid_state' );
				break;
			}

			$current_user_id = get_current_user_id();
			if ( $current_user_id != $data['state'] ) {
				Jetpack::state( 'error', 'wrong_state' );
				break;
			}

			if ( empty( $data['code'] ) ) {
				Jetpack::state( 'error', 'no_code' );
				break;
			}

			$token = $this->get_token( $data );

			if ( is_wp_error( $token ) ) {
				if ( $error = $token->get_error_code() )
					Jetpack::state( 'error', $error );
				else
					Jetpack::state( 'error', 'invalid_token' );

				Jetpack::state( 'error_description', $token->get_error_message() );

				break;
			}

			if ( !$token ) {
				Jetpack::state( 'error', 'no_token' );
				break;
			}

			$is_master_user = ! Jetpack::is_active();

			Jetpack::update_user_token( $current_user_id, sprintf( '%s.%d', $token, $current_user_id ), $is_master_user );

			if ( $is_master_user ) {
				Jetpack::state( 'message', 'authorized' );
			} else {
				Jetpack::state( 'message', 'linked' );
				// Don't activate anything since we are just connecting a user.
				break;
			}

			if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
				Jetpack_Options::delete_option( 'active_modules' );

				Jetpack::activate_default_modules( 999, 1, $active_modules );
			} else {
				Jetpack::activate_default_modules();
			}

			// Sync all registers options and constants
			/** This action is documented in class.jetpack.php */
			do_action( 'jetpack_sync_all_registered_options' );

			// Start nonce cleaner
			wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
		} while ( false );

		if ( wp_validate_redirect( $redirect ) ) {
			$this->wp_safe_redirect( $redirect );
		} else {
			$this->wp_safe_redirect( Jetpack::admin_url() );
		}

		$this->do_exit();
	}

	public static function deactivate_plugin( $probable_file, $probable_title ) {
		include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
		if ( is_plugin_active( $probable_file ) ) {
			deactivate_plugins( $probable_file );
			return 1;
		} else {
			// If the plugin is not in the usual place, try looking through all active plugins.
			$active_plugins = Jetpack::get_active_plugins();
			foreach ( $active_plugins as $plugin ) {
				$data = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin );
				if ( $data['Name'] == $probable_title ) {
					deactivate_plugins( $plugin );
					return 1;
				}
			}
		}

		return 0;
	}

	/**
	 * @return object|WP_Error
	 */
	function get_token( $data ) {
		$jetpack = $this->get_jetpack();
		$role = $jetpack->translate_current_user_to_role();

		if ( !$role ) {
			return new Jetpack_Error( 'role', __( 'An administrator for this blog must set up the Jetpack connection.', 'jetpack' ) );
		}

		$client_secret = Jetpack_Data::get_access_token();
		if ( !$client_secret ) {
			return new Jetpack_Error( 'client_secret', __( 'You need to register your Jetpack before connecting it.', 'jetpack' ) );
		}

		$redirect = isset( $data['redirect'] ) ? esc_url_raw( (string) $data['redirect'] ) : '';

		$body = array(
			'client_id' => Jetpack_Options::get_option( 'id' ),
			'client_secret' => $client_secret->secret,
			'grant_type' => 'authorization_code',
			'code' => $data['code'],
			'redirect_uri' => add_query_arg( array(
				'action' => 'authorize',
				'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
				'redirect' => $redirect ? urlencode( $redirect ) : false,
			), menu_page_url( 'jetpack', false ) ),
		);

		$args = array(
			'method' => 'POST',
			'body' => $body,
			'headers' => array(
				'Accept' => 'application/json',
			),
		);
		$response = Jetpack_Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'token' ) ), $args );

		if ( is_wp_error( $response ) ) {
			return new Jetpack_Error( 'token_http_request_failed', $response->get_error_message() );
		}

		$code = wp_remote_retrieve_response_code( $response );
		$entity = wp_remote_retrieve_body( $response );

		if ( $entity )
			$json = json_decode( $entity );
		else
			$json = false;

		if ( 200 != $code || !empty( $json->error ) ) {
			if ( empty( $json->error ) )
				return new Jetpack_Error( 'unknown', '', $code );

			$error_description = isset( $json->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->error_description ) : '';

			return new Jetpack_Error( (string) $json->error, $error_description, $code );
		}

		if ( empty( $json->access_token ) || !is_scalar( $json->access_token ) ) {
			return new Jetpack_Error( 'access_token', '', $code );
		}

		if ( empty( $json->token_type ) || 'X_JETPACK' != strtoupper( $json->token_type ) ) {
			return new Jetpack_Error( 'token_type', '', $code );
		}

		if ( empty( $json->scope ) ) {
			return new Jetpack_Error( 'scope', 'No Scope', $code );
		}
		@list( $role, $hmac ) = explode( ':', $json->scope );
		if ( empty( $role ) || empty( $hmac ) ) {
			return new Jetpack_Error( 'scope', 'Malformed Scope', $code );
		}
		if ( $jetpack->sign_role( $role ) !== $json->scope ) {
			return new Jetpack_Error( 'scope', 'Invalid Scope', $code );
		}

		if ( !$cap = $jetpack->translate_role_to_cap( $role ) )
			return new Jetpack_Error( 'scope', 'No Cap', $code );
		if ( !current_user_can( $cap ) )
			return new Jetpack_Error( 'scope', 'current_user_cannot', $code );

		return (string) $json->access_token;
	}

	public function get_jetpack() {
		return Jetpack::init();
	}

	public function check_admin_referer( $action ) {
		return check_admin_referer( $action );
	}

	public function wp_safe_redirect( $redirect ) {
		return wp_safe_redirect( $redirect );
	}

	public function do_exit() {
		exit;
	}

}


text:
package author.panels;

/**
 * This is an abstract class that is extended by AbstractTextPanel, AbstractToggleButtonPanel,
 * and ImagePanel.  It represents every type of input that our engine can write to a JSON file
 * including text, checkboxes, radio buttons, lists, matrices, Images, and numbers.
 *
 * @author weskpga
 *
 */

import java.util.Map;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;

public abstract class AbstractWizardPanel extends JPanel {

	private static final long serialVersionUID = -7974954435721491712L;

	protected UserInputDimension myDimensions;
    protected JLabel myTextLabel;
    private String myType;

    public AbstractWizardPanel (String type) {
        // Default dimension size is 1x1
        myDimensions = new UserInputDimension(3, 3);
        myType = type;
        this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
    }

    public AbstractWizardPanel (String type, int rows, int columns) {
        myDimensions = new UserInputDimension(rows, columns);
        myType = type;
    }

    public String getMyType () {
        return myType;
    }

    public void addRow () {
        myDimensions.addRow();
    }

    public void addColumn () {
        myDimensions.addColumn();
    }

    public void expandSquareMatrix () {
        addRow();
        addColumn();
    }

    public abstract Map<String, String> getUserInput ();

    protected class UserInputDimension {

        private int rowDimension;
        private int columnDimension;

        public UserInputDimension (int rows, int columns) {
            rowDimension = rows;
            columnDimension = columns;
        }

        public void addRow () {
            rowDimension += 1;
        }

        public void addColumn () {
            columnDimension += 1;
        }

        public int getRowDimension () {
            return rowDimension;
        }

        public int getColumnDimension () {
            return columnDimension;
        }

    }

}


text:
PlotSearch
============
An application to search for movies based on plot description. The user is provided with a text box where queries can be input in the form of sentences describing the scenes of what actually happened. Our system returns relevant movies that match the description.

### File structure

```
/
├───data
|    ├───movie_corpus.json  #main corpus file
|    ├───names.txt  #names to pronoun mapping file
|    ├───toy_corpus.json  #test corpus file
|    └───wn_s.pl  #wordnet synonyms file
├───doc
|    ├───PlotSearch.pdf
|    └───PlotSearch.tex
├───libs
|    ├───__init__.py
|    └───search_engine.py  #script for searching documents with elasticsearch
├───static
|    ├───images
|    |    └───background.jpg
|    ├───js
|    |    ├───bootstrap.min.js
|    |    ├───jquery.min.js
|    |    └───main.js
|    └───styles
|         ├───bootstrap.min.css
|         └───style.css
├───templates
|    ├───base.html
|    ├───index.html
|    ├───movie.html
|    └───results.html
├───app.py  # flask app main controller
├───create_corpus.py  #script for creating corpus
├───es_settings  # set up elasticsearch
├───README.md
└───requirements.txt
```

### Local Setup

To install dependencies:
```
pip install -r requirements.txt
```

To create corpus from scratch:
```
python create_corpus.py
```

It will go to themoviespoiler.com and omdbapi.com, fetch and clean movie data, and save it to `data/movie_corpus.json`.

To build elasticsearch index (it copies synonym files into elasticsearch config directory, therefore root access is required):
```
sudo <virtualenv_dir>/bin/python es_settings.py
```

Then the flask application can be kicked off by running:
```
python app.py
```


text:
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.SVGFESpecularLightingElement
       (js_getIn1, getIn1, js_getSurfaceScale, getSurfaceScale,
        js_getSpecularConstant, getSpecularConstant,
        js_getSpecularExponent, getSpecularExponent,
        SVGFESpecularLightingElement, castToSVGFESpecularLightingElement,
        gTypeSVGFESpecularLightingElement)
       where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSRef(..), JSString, castRef)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSRef(..), FromJSRef(..))
import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.Enums

foreign import javascript unsafe "$1[\"in1\"]" js_getIn1 ::
        JSRef SVGFESpecularLightingElement -> IO (JSRef SVGAnimatedString)

-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFESpecularLightingElement.in1 Mozilla SVGFESpecularLightingElement.in1 documentation>
getIn1 ::
       (MonadIO m) =>
         SVGFESpecularLightingElement -> m (Maybe SVGAnimatedString)
getIn1 self
  = liftIO
      ((js_getIn1 (unSVGFESpecularLightingElement self)) >>= fromJSRef)

foreign import javascript unsafe "$1[\"surfaceScale\"]"
        js_getSurfaceScale ::
        JSRef SVGFESpecularLightingElement -> IO (JSRef SVGAnimatedNumber)

-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFESpecularLightingElement.surfaceScale Mozilla SVGFESpecularLightingElement.surfaceScale documentation>
getSurfaceScale ::
                (MonadIO m) =>
                  SVGFESpecularLightingElement -> m (Maybe SVGAnimatedNumber)
getSurfaceScale self
  = liftIO
      ((js_getSurfaceScale (unSVGFESpecularLightingElement self)) >>=
         fromJSRef)

foreign import javascript unsafe "$1[\"specularConstant\"]"
        js_getSpecularConstant ::
        JSRef SVGFESpecularLightingElement -> IO (JSRef SVGAnimatedNumber)

-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFESpecularLightingElement.specularConstant Mozilla SVGFESpecularLightingElement.specularConstant documentation>
getSpecularConstant ::
                    (MonadIO m) =>
                      SVGFESpecularLightingElement -> m (Maybe SVGAnimatedNumber)
getSpecularConstant self
  = liftIO
      ((js_getSpecularConstant (unSVGFESpecularLightingElement self)) >>=
         fromJSRef)

foreign import javascript unsafe "$1[\"specularExponent\"]"
        js_getSpecularExponent ::
        JSRef SVGFESpecularLightingElement -> IO (JSRef SVGAnimatedNumber)

-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFESpecularLightingElement.specularExponent Mozilla SVGFESpecularLightingElement.specularExponent documentation>
getSpecularExponent ::
                    (MonadIO m) =>
                      SVGFESpecularLightingElement -> m (Maybe SVGAnimatedNumber)
getSpecularExponent self
  = liftIO
      ((js_getSpecularExponent (unSVGFESpecularLightingElement self)) >>=
         fromJSRef)


text:
'use strict';
var Notify = require( 'osg/Notify' );
var MACROUTILS = require( 'osg/Utils' );
var Timer = require( 'osg/Timer' );
var GLObject = require( 'osg/GLObject' );

/**
 * Shader manage shader for vertex and fragment, you need both to create a glsl program.
 * @class Shader
 */
var Shader = function ( type, text ) {
    GLObject.call( this );
    var t = type;
    if ( typeof ( type ) === 'string' ) {
        t = Shader[ type ];
    }
    this.type = t;
    this.setText( text );
};

Shader.VERTEX_SHADER = 0x8B31;
Shader.FRAGMENT_SHADER = 0x8B30;

// Debug Pink shader for when shader fails
Shader.VS_DBG = 'attribute vec3 Vertex;uniform mat4 ModelViewMatrix;uniform mat4 ProjectionMatrix;void main(void) {  gl_Position = ProjectionMatrix * ModelViewMatrix * vec4(Vertex, 1.0);}';
Shader.FS_DBG = 'precision lowp float; void main(void) { gl_FragColor = vec4(1.0, 0.6, 0.6, 1.0);}';

var debugName = '\n#define SHADER_NAME FailSafe\n';
Shader.VS_DBG += debugName;
Shader.FS_DBG += debugName;

// static cache of glShaders flagged for deletion, which will actually
// be deleted in the correct GL context.
Shader._sDeletedGLShaderCache = new window.Map();

// static method to delete Program
Shader.deleteGLShader = function ( gl, shader ) {
    if ( !Shader._sDeletedGLShaderCache.has( gl ) )
        Shader._sDeletedGLShaderCache.set( gl, [] );
    Shader._sDeletedGLShaderCache.get( gl ).push( shader );
};

// static method to flush all the cached glShaders which need to be deleted in the GL context specified
Shader.flushDeletedGLShaders = function ( gl, availableTime ) {
    // if no time available don't try to flush objects.
    if ( availableTime <= 0.0 ) return availableTime;
    if ( !Shader._sDeletedGLShaderCache.has( gl ) ) return availableTime;
    var elapsedTime = 0.0;
    var beginTime = Timer.instance().tick();
    var deleteList = Shader._sDeletedGLShaderCache.get( gl );
    var numShaders = deleteList.length;
    for ( var i = numShaders - 1; i >= 0 && elapsedTime < availableTime; i-- ) {
        gl.deleteShader( deleteList[ i ] );
        deleteList.splice( i, 1 );
        elapsedTime = Timer.instance().deltaS( beginTime, Timer.instance().tick() );
    }
    return availableTime -= elapsedTime;
};

Shader.flushAllDeletedGLShaders = function ( gl ) {
    if ( !Shader._sDeletedGLShaderCache.has( gl ) ) return;
    var deleteList = Shader._sDeletedGLShaderCache.get( gl );
    var numShaders = deleteList.length;
    for ( var i = numShaders - 1; i >= 0; i-- ) {
        gl.deleteShader( deleteList[ i ] );
        deleteList.splice( i, 1 );
    }
    return;
};

/** @lends Shader.prototype */
Shader.prototype = MACROUTILS.objectInherit( GLObject.prototype, {
    setText: function ( text ) {
        this.text = text;
    },
    getText: function () {
        return this.text;
    },
    // this is where it creates a fail safe shader that should work everywhere
    failSafe: function ( gl ) {
        this.shader = gl.createShader( this.type );
        gl.shaderSource( this.shader, this.type === Shader.VERTEX_SHADER ? Shader.VS_DBG : Shader.FS_DBG );
        gl.compileShader( this.shader );
    },
    // webgl shader compiler error to source contextualization
    // for better console log messages
    processErrors: function ( errors, source ) {
        // regex to extract error message and line from webgl compiler reporting
        var r = /ERROR: [\d]+:([\d]+): (.+)/gmi;
        // split sources in indexable per line array
        var lines = source.split( '\n' );
        var i, m;

        // IE reporting is not the same
        if ( r.exec( errors ) === null ) {
            r = /Shader compilation errors\n\((\d+)\, \d+\): (.+)/gmi;
        }

        // reset index to start.
        r.lastIndex = 0;

        while ( ( m = r.exec( errors ) ) != null ) {
            if ( m.index === r.lastIndex ) {
                r.lastIndex++; // moving between errors
            }
            // get error line
            var line = parseInt( m[ 1 ] );

            // webgl error report.
            Notify.error( 'ERROR ' + m[ 2 ] + ' in line ' + line, false, true );

            // for context
            // log surrounding line priori to error with bof check
            for ( i = 2; i < 7 && ( 0 < line - i ); i++ ) {
                Notify.log( lines[ line - i ].replace( /^[ \t]+/g, '' ), false, true );
            }

            // Warn adds a lovely /!\ icon in front of the culprit line
            Notify.warn( lines[ line - 1 ].replace( /^[ \t]+/g, '' ), false, true );

            // for context
            // surrounding line posterior to error (with eof check)
            for ( i = 0; i < 5 && ( lines.length > line + i ); i++ ) {
                Notify.log( lines[ line + i ].replace( /^[ \t]+/g, '' ), false, true );
            }
        }
    },
    compile: function ( gl ) {
        if ( !this._gl ) this.setGraphicContext( gl );
        this.shader = gl.createShader( this.type );
        gl.shaderSource( this.shader, this.text );
        MACROUTILS.timeStamp( 'osgjs.metrics:compileShader' );
        gl.compileShader( this.shader );
        if ( !gl.getShaderParameter( this.shader, gl.COMPILE_STATUS ) && !gl.isContextLost() ) {

            var err = gl.getShaderInfoLog( this.shader );
            this.processErrors( err, this.text );

            var tmpText = '\n' + this.text;
            var splittedText = tmpText.split( '\n' );
            var newText = '\n';
            for ( var i = 0, l = splittedText.length; i < l; ++i ) {
                newText += i + ' ' + splittedText[ i ] + '\n';
            }
            // still logging whole source but folded
            Notify.log( 'can\'t compile shader:\n' + newText, true );

            return false;
        }
        return true;
    },
    releaseGLObjects: function () {
        if ( this._gl !== undefined ) {
            Shader.deleteGLShader( this._gl, this.shader );
        }
        this.shader = undefined;
    }
} );

Shader.create = function ( type, text ) {
    Notify.log( 'Shader.create is deprecated, use new Shader with the same arguments instead' );
    return new Shader( type, text );
};

module.exports = Shader;


text:
#ifndef TABLES_H
#define TABLES_H

#include <stdint.h>

extern const int SYMTBL_NON_UNIQUE;
extern const int SYMTBL_UNIQUE_NAME;

/* Signature of the SymbolTable data structure. */

typedef struct {
    char *name;
    uint32_t addr;
} Symbol;

typedef struct {
    Symbol* tbl;
    uint32_t len;
    uint32_t cap;
    int mode;
} SymbolTable;

/* Helper functions: */

void allocation_failed();

void addr_alignment_incorrect();

void name_already_exists(const char* name);

void write_symbol(FILE* output, uint32_t addr, const char* name);

SymbolTable* create_table();

void free_table(SymbolTable* table);

int add_to_table(SymbolTable* table, const char* name, uint32_t addr);

int64_t get_addr_for_symbol(SymbolTable* table, const char* name);

void write_table(SymbolTable* table, FILE* output);

#endif


text:
use crate::{common::Author, quorum_cert::QuorumCert};
use anyhow::{ensure, Context};
use diem_crypto::ed25519::Ed25519Signature;
use diem_crypto_derive::{BCSCryptoHash, CryptoHasher};
use diem_types::{
    block_info::Round, validator_signer::ValidatorSigner, validator_verifier::ValidatorVerifier,
};
use serde::{Deserialize, Serialize};
use std::{
    collections::BTreeMap,
    fmt::{Display, Formatter},
};

/// This structure contains all the information necessary to construct a signature
/// on the equivalent of a DiemBFT v4 timeout message.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct TwoChainTimeout {
    /// Epoch number corresponds to the set of validators that are active for this round.
    epoch: u64,
    /// The consensus protocol executes proposals (blocks) in rounds, which monotonically increase per epoch.
    round: Round,
    /// The highest quorum cert the signer has seen.
    quorum_cert: QuorumCert,
}

impl TwoChainTimeout {
    pub fn new(epoch: u64, round: Round, quorum_cert: QuorumCert) -> Self {
        Self {
            epoch,
            round,
            quorum_cert,
        }
    }

    pub fn epoch(&self) -> u64 {
        self.epoch
    }

    pub fn round(&self) -> Round {
        self.round
    }

    pub fn hqc_round(&self) -> Round {
        self.quorum_cert.certified_block().round()
    }

    pub fn quorum_cert(&self) -> &QuorumCert {
        &self.quorum_cert
    }

    pub fn sign(&self, signer: &ValidatorSigner) -> Ed25519Signature {
        signer.sign(&self.signing_format())
    }

    pub fn signing_format(&self) -> TimeoutSigningRepr {
        TimeoutSigningRepr {
            epoch: self.epoch(),
            round: self.round(),
            hqc_round: self.hqc_round(),
        }
    }

    pub fn verify(&self, validators: &ValidatorVerifier) -> anyhow::Result<()> {
        ensure!(
            self.hqc_round() < self.round(),
            "Timeout round should be larger than the QC round"
        );
        self.quorum_cert.verify(validators)?;
        Ok(())
    }
}

impl Display for TwoChainTimeout {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        write!(
            f,
            "Timeout: [epoch: {}, round: {}, hqc_round: {}]",
            self.epoch,
            self.round,
            self.hqc_round(),
        )
    }
}

/// Validators sign this structure that allows the TwoChainTimeoutCertificate to store a round number
/// instead of a quorum cert per validator in the signatures field.
#[derive(Serialize, Deserialize, CryptoHasher, BCSCryptoHash)]
pub struct TimeoutSigningRepr {
    pub epoch: u64,
    pub round: Round,
    pub hqc_round: Round,
}

/// TimeoutCertificate is a proof that 2f+1 participants in epoch i
/// have voted in round r and we can now move to round r+1. DiemBFT v4 requires signature to sign on
/// the TimeoutSigningRepr and carry the TimeoutWithHighestQC with highest quorum cert among 2f+1.
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
pub struct TwoChainTimeoutCertificate {
    timeout: TwoChainTimeout,
    signatures: BTreeMap<Author, (Round, Ed25519Signature)>,
}

impl Display for TwoChainTimeoutCertificate {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        write!(
            f,
            "TimeoutCertificate[epoch: {}, round: {}, hqc_round: {}]",
            self.timeout.epoch(),
            self.timeout.round(),
            self.timeout.hqc_round(),
        )
    }
}

impl TwoChainTimeoutCertificate {
    /// Creates new TimeoutCertificate
    pub fn new(timeout: TwoChainTimeout) -> Self {
        Self {
            timeout,
            signatures: BTreeMap::new(),
        }
    }
    /// Verifies the signatures for each validator, the signature is on the TimeoutSigningRepr where the
    /// hqc_round is in the signature map.
    /// We verify the following:
    /// 1. the highest quorum cert is valid
    /// 2. all signatures are properly formed (timeout.epoch, timeout.round, round)
    /// 3. timeout.hqc_round == max(signed round)
    pub fn verify(&self, validators: &ValidatorVerifier) -> anyhow::Result<()> {
        // Verify the highest timeout validity.
        self.timeout.verify(validators)?;
        let hqc_round = self.timeout.hqc_round();
        let mut signed_round = 0;
        validators.check_voting_power(self.signatures.keys())?;
        for (author, (qc_round, signature)) in &self.signatures {
            let t = TimeoutSigningRepr {
                epoch: self.timeout.epoch(),
                round: self.timeout.round(),
                hqc_round: *qc_round,
            };
            validators
                .verify(*author, &t, signature)
                .with_context(|| format!("Failed to verify {}'s TimeoutSigningRepr", *author))?;
            signed_round = std::cmp::max(signed_round, *qc_round);
        }
        ensure!(
            hqc_round == signed_round,
            "Inconsistent hqc round, qc has round {}, highest signed round {}",
            hqc_round,
            signed_round
        );
        Ok(())
    }

    /// The epoch of the timeout.
    pub fn epoch(&self) -> u64 {
        self.timeout.epoch()
    }

    /// The round of the timeout.
    pub fn round(&self) -> Round {
        self.timeout.round()
    }

    /// The highest hqc round of the 2f+1 participants
    pub fn highest_hqc_round(&self) -> Round {
        self.timeout.hqc_round()
    }

    /// Returns the signatures certifying the round
    pub fn signers(&self) -> impl Iterator<Item = &Author> {
        self.signatures.iter().map(|(k, _)| k)
    }

    /// Add a new timeout message from author, the timeout should already be verified in upper layer.
    pub fn add(&mut self, author: Author, timeout: TwoChainTimeout, signature: Ed25519Signature) {
        debug_assert_eq!(
            self.timeout.epoch(),
            timeout.epoch(),
            "Timeout should have the same epoch as TimeoutCert"
        );
        debug_assert_eq!(
            self.timeout.round(),
            timeout.round(),
            "Timeout should have the same round as TimeoutCert"
        );
        let hqc_round = timeout.hqc_round();
        if timeout.hqc_round() > self.timeout.hqc_round() {
            self.timeout = timeout;
        }
        self.signatures.insert(author, (hqc_round, signature));
    }
}

#[test]
fn test_2chain_timeout_certificate() {
    use crate::vote_data::VoteData;
    use diem_crypto::hash::CryptoHash;
    use diem_types::{
        block_info::BlockInfo,
        ledger_info::{LedgerInfo, LedgerInfoWithSignatures},
        validator_verifier::random_validator_verifier,
    };

    let num_nodes = 4;
    let (signers, validators) = random_validator_verifier(num_nodes, None, false);
    let quorum_size = validators.quorum_voting_power() as usize;
    let generate_quorum = |round, num_of_signature| {
        let vote_data = VoteData::new(BlockInfo::random(round), BlockInfo::random(0));
        let mut ledger_info = LedgerInfoWithSignatures::new(
            LedgerInfo::new(BlockInfo::empty(), vote_data.hash()),
            BTreeMap::new(),
        );
        for signer in &signers[0..num_of_signature] {
            let signature = signer.sign(ledger_info.ledger_info());
            ledger_info.add_signature(signer.author(), signature);
        }
        QuorumCert::new(vote_data, ledger_info)
    };
    let generate_timeout =
        |round, qc_round| TwoChainTimeout::new(1, round, generate_quorum(qc_round, quorum_size));

    let timeouts: Vec<_> = (1..=3)
        .map(|qc_round| generate_timeout(4, qc_round))
        .collect();
    // timeout cert with (round, hqc round) = (4, 1), (4, 2), (4, 3)
    let mut valid_timeout_cert = TwoChainTimeoutCertificate::new(timeouts[0].clone());
    for (timeout, signer) in timeouts.iter().zip(&signers) {
        valid_timeout_cert.add(signer.author(), timeout.clone(), timeout.sign(signer));
    }
    valid_timeout_cert.verify(&validators).unwrap();

    // timeout round < hqc round
    let mut invalid_timeout_cert = valid_timeout_cert.clone();
    invalid_timeout_cert.timeout.round = 1;
    invalid_timeout_cert.verify(&validators).unwrap_err();

    // invalid signature
    let mut invalid_timeout_cert = valid_timeout_cert.clone();
    invalid_timeout_cert
        .signatures
        .get_mut(&signers[0].author())
        .unwrap()
        .1 = Ed25519Signature::dummy_signature();
    invalid_timeout_cert.verify(&validators).unwrap_err();

    // not enough signatures
    let mut invalid_timeout_cert = valid_timeout_cert.clone();
    invalid_timeout_cert
        .signatures
        .remove(&signers[0].author())
        .unwrap();
    invalid_timeout_cert.verify(&validators).unwrap_err();

    // hqc round does not match signed round
    let mut invalid_timeout_cert = valid_timeout_cert.clone();
    invalid_timeout_cert.timeout.quorum_cert = generate_quorum(2, quorum_size);
    invalid_timeout_cert.verify(&validators).unwrap_err();

    // invalid quorum cert
    let mut invalid_timeout_cert = valid_timeout_cert;
    invalid_timeout_cert.timeout.quorum_cert = generate_quorum(3, quorum_size - 1);
    invalid_timeout_cert.verify(&validators).unwrap_err();
}


text:
<?php

namespace Hifone\Handlers\Commands\Append;

use Carbon\Carbon;
use Hifone\Commands\Append\AddAppendCommand;
use Hifone\Events\Append\AppendWasAddedEvent;
use Hifone\Models\Append;
use Hifone\Services\Dates\DateFactory;

class AddAppendCommandHandler
{
    /**
     * The date factory instance.
     *
     * @var \Hifone\Services\Dates\DateFactory
     */
    protected $dates;

    /**
     * Create a new report issue command handler instance.
     *
     * @param \Hifone\Services\Dates\DateFactory $dates
     */
    public function __construct(DateFactory $dates)
    {
        $this->dates = $dates;
    }

    /**
     * Handle the report append command.
     *
     * @param \Hifone\Commands\Append\AddAppendCommand $command
     *
     * @return \Hifone\Models\Append
     */
    public function handle(AddAppendCommand $command)
    {
        $data = [
            'thread_id'         => $command->thread_id,
            'content'           => app('parser.markdown')->convertMarkdownToHtml($command->content),
            'created_at'        => Carbon::now()->toDateTimeString(),
        ];

        // Create the append
        $append = Append::create($data);

        event(new AppendWasAddedEvent($append));

        return $append;
    }
}


text:
<!DOCTYPE HTML PUBLIC  "-//W3C//DTD HTML 4.01 Transitional//EN"
       "http://www.w3.org/TR/html4/loose.dtd">

<title>Tradução do OpenBSD</title>
<link rev="made" href="mailto:www@openbsd.org">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="resource-type" content="document">
<meta name="description" content="the OpenBSD Translation page">
<meta name="keywords" content="openbsd,translation,documentation">
<meta name="distribution" content="global">
<meta name="copyright" content="This document copyright 2000-2009 by OpenBSD.">

Tradução da Documentação do OpenBSD

Índice

O que é isso?

Quem está fazendo isso?

Como isso funciona?

Quer contribuir?

O que é isso?

O projeto OpenBSD esforça-se para manter os altos
 padrões, um deles é fornecer aos usuários
excelente documentação na forma de páginas de manual e páginas Web.

Para tornar fácil o aprendizado a quem não fala inglês, o sítio Web
e a FAQ foram traduzidos e são atualizados por várias equipes.
Você pode ver os idiomas ativos na tabela abaixo.

Quem está fazendo isso?

Assim como todas as atividades do OpenBSD, este trabalho é realizado por
voluntários.

Apenas as traducões indexadas estão atualizadas e estão sendo mantidas ativamente.

  cs
  Tcheco

    Tomas Bodzar

  de
  Alemão

	Steffen Daode Nurpmeso

  es
  Espanhol

    Miguel Vidal

  fr
  Francês

    Antoine Jacoutot,
    Benoit Lecocq e
    Maxime Villard
    (Veja Informações de Tradução do OpenBSD [fr] para mais
    informações)

  hu
  Húngaro

    -

  it
  Italiano

    Giuseppe Reale

  ja
  Japonês

    -

  lt
  Lituano

    Henrikas Judickas

  nl
  Holandês

    Maurice Janssen

  pl
  Polonês

    Tomasz Kniaz

  pt
  Português

    Renato dos Santos

  ru
  Russo

    Alexander Naumov

  zh
  Chinês

    Dongsheng Song
    (veja Informações de Tradução do OpenBSD [zh]
    para mais informações)

Todo o trabalho é coordenado por
Antoine Jacoutot e
Benoit Lecocq.

Como isso funciona?

O sítio Web é formado por múltiplos subdiretórios que chamamos de
seções, onde para cada idioma existe um subdiretório extra em cada seção
caso exista uma tradução. Esse subdiretório possui um nome
que é um código de idioma de dois caracteres do

código de linguagem ISO 639-1,
sendo 'de' para Alemão ou 'fr' para Francês. Nesse diretório,
encontramos arquivos com os mesmos nomes de sua versão original [en],
mas traduzidos para seu idioma correto.

Por exemplo:

www/index.html
www/goals.html
www/security.html
www/de/index.html
www/de/goals.html
www/faq/index.html
www/faq/de/index.html

Se www/de/index.html contém um link para a página
traduzida goals.html, ele aponta para
www/de/goals.html. Se security.html
(ainda) não está traduzido, ele deve referenciar o
arquivo ../security.html, que aponta para
www/security.html.

Mantemos também, em cada arquivo traduzido e no original
[en], uma série de links para as páginas traduzidas.
Esses links devem estar em ordem alfabética! Você pode encontrá-los
no canto superior esquerdo da página de índice, por exemplo:
[cs]
[de]
[en]
[fr]
[nl]

Todos os contribuidores possuem uma conta CVS em um servidor
CVS dedicado steelix.bsdfrog.org.
Após as páginas serem finalizadas e atualizadas, elas são sincronizadas
com o repositório central do OpenBSD.

Nota: o repositório CVS steelix.bsdfrog.org
não é público.
É necessário ter uma conta CVS nesse servidor para acessar o
repositório.

O status atual do trabalho de tradução pode ser rastreado online
através da página

Status das
Traduções do OpenBSD, atualizada a cada hora.

Documentação mais detalhada sobre o processo de tradução está disponível
em Como contribuir no
esforço de tradução do OpenBSD.

Quer contribuir?

Siga as instruções contidas na página
Como contribuir no esforço
de tradução do OpenBSD.

www@openbsd.org

$OpenBSD$


text:
<?php
namespace Chamilo\Core\Repository\ContentObject\LearningPath\Display\Table\Activity;

/**
 * Table cell renderer for the schema
 *
 * @author Hans De Bisschop <hans.de.bisschop@ehb.be>
 */
class ActivityTableCellRenderer extends \Chamilo\Core\Repository\Integration\Chamilo\Core\Tracking\Table\Activity\ActivityTableCellRenderer
{
}


text:
namespace blink {

#if OS(WIN)
static_assert(sizeof(blink::PlatformThreadId) >= sizeof(DWORD),
              "size of platform thread id is too small");
#elif OS(POSIX)
static_assert(sizeof(blink::PlatformThreadId) >= sizeof(pid_t),
              "size of platform thread id is too small");
#else
#error Unexpected platform
#endif

base::SingleThreadTaskRunner* WebThread::getSingleThreadTaskRunner() {
  return getWebTaskRunner()->toSingleThreadTaskRunner();
}

}  // namespace blink


text:
require "uri"
require "oga"
require "httparty"
require "colorize"

class Spider
    MAX_URLS = 1000

    def initialize(options = {})
        @root = nil
        @visited_urls = Set.new
        @max_urls = options.fetch(:max_urls, MAX_URLS)
    end

    def results(start_url)
        return [] if start_url.nil? or start_url.empty?

        @root = URI.parse(start_url)
        urls = [@root]

        results = []
        while(urls.size > 0)
            url = urls.shift
            next if @visited_urls.include? "#{url.host}#{url.path}"
            puts "Crawling url: #{url}".colorize(:light_blue)
            page = get_page(url)
            results << {url: url.to_s, assets: get_assets(page)}
            urls.concat get_child_urls(page)
            @visited_urls.add "#{url.host}#{url.path}"
        end

        results
    end

    private

    def normalize_url(url)
        uri = URI.parse(url)
        return uri if uri.absolute?
        URI.join(@root, url)
    rescue URI::InvalidURIError => e
        puts "#{url} is invalid. #{e.message}".colorize(:red)
    rescue URI::InvalidComponentError => e
        puts "#{url} isn't crawlable. #{e.message}".colorize(:red)
    end

    def get_page(url)
        response = HTTParty.get(url)
        Oga.parse_html(response.body)
    rescue ArgumentError => e
        puts "Invalid content for #{url}: #{e.message}".colorize(:red)
    rescue StandardError => e
        puts "Could not parse response for #{url}: #{e.message}".colorize(:red)
    end

    def get_assets(page)
        return [] if page.nil?

        assets = []
        page.css('link').each do |l|
            next unless l['href']
            url = normalize_url(l['href'])
            assets << url.to_s if url and url.host == @root.host
        end

        page.css('script').each do |s|
            next unless s['src']
            url = normalize_url(s['src'])
            assets << url.to_s if url and url.host == @root.host
        end

        page.css('img').each do |i|
            next unless i['src']
            url = normalize_url(i['src'])
            assets << url.to_s if url and url.host == @root.host
        end

        assets
    end

    def get_child_urls(page)
        return [] if page.nil?

        urls = []
        page.css('a').each do |l|
            break if urls.size == @max_urls
            next unless l['href']
            next if l['href'].start_with? "#" #avoid anchors to same page
            url = normalize_url(l['href'])
            # remove query params
            urls << url if url and url.host == @root.host
        end
        urls
    end
end


text:
namespace AVDump3Lib.Processing.BlockBuffers;

public interface IMirroredBufferPool {
	int BufferSize { get; }
	IMirroredBuffer Take();
	void Release(IMirroredBuffer buffer);
}

public class MirroredBufferPool : IMirroredBufferPool {
	public int BufferSize { get; }

	private readonly Stack<IMirroredBuffer> slots = new();

	public MirroredBufferPool(int bufferSize) { BufferSize = bufferSize; }

	public IMirroredBuffer Take() {
		lock(slots) {
			if(slots.Count != 0) {
				return slots.Pop();
			} else {
				return new MirroredBuffer(BufferSize);
			}
		}
	}
	public void Release(IMirroredBuffer buffer) { lock(slots) slots.Push(buffer); }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res/vn.techplus.filmon"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/bg_splash" >

    <ImageView
        android:id="@+id/img_light_under"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:src="@drawable/img_light_under" />

    <ImageView
        android:id="@+id/imgLogo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_above="@+id/img_light_under"
        android:paddingLeft="50dp"
        android:paddingRight="50dp"
        android:scaleType="fitCenter"
        android:src="@drawable/logo_filmon" />

    <vn.techplus.filmon.customwidget.CustomTextView
        android:id="@id/txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:gravity="center"
        android:maxLines="2"
        android:paddingTop="5dp"
        android:text="@string/lb_instroduction"
        android:textColor="#62656E"
        android:textSize="15sp"
        android:textStyle="bold"
        custom:customTypeFace="Bank_Gothic_Medium_BT.ttf" />

    <LinearLayout
        android:id="@+id/progressView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/txt"
        android:layout_below="@+id/imgLogo"
        android:gravity="center"
        android:orientation="horizontal"
        android:visibility="gone" >

        <ProgressBar
            android:id="@+id/progressBar1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <vn.techplus.filmon.customwidget.CustomTextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:text="Loading ..."
            android:textColor="#FFFFFF"
            android:textSize="@dimen/name_channel"
            android:textStyle="bold"
            custom:customTypeFace="Bank_Gothic_Medium_BT.ttf" />
    </LinearLayout>

</RelativeLayout>


text:
'use strict';

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

var _mergeWith2 = require('lodash/mergeWith');

var _mergeWith3 = _interopRequireDefault(_mergeWith2);

var _isPlainObject2 = require('lodash/isPlainObject');

var _isPlainObject3 = _interopRequireDefault(_isPlainObject2);

var _isFunction2 = require('lodash/isFunction');

var _isFunction3 = _interopRequireDefault(_isFunction2);

var _cloneDeep2 = require('lodash/cloneDeep');

var _cloneDeep3 = _interopRequireDefault(_cloneDeep2);

exports.default = joinArrays;

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

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

var isArray = Array.isArray;

function joinArrays() {
  var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      customizeArray = _ref.customizeArray,
      customizeObject = _ref.customizeObject,
      key = _ref.key;

  return function _joinArrays(a, b, k) {
    var newKey = key ? key + '.' + k : k;

    if ((0, _isFunction3.default)(a) && (0, _isFunction3.default)(b)) {
      return function () {
        return _joinArrays(a.apply(undefined, arguments), b.apply(undefined, arguments), k);
      };
    }
    if (isArray(a) && isArray(b)) {
      var customResult = customizeArray && customizeArray(a, b, newKey);

      return customResult || [].concat(_toConsumableArray(a), _toConsumableArray(b));
    }

    if ((0, _isPlainObject3.default)(a) && (0, _isPlainObject3.default)(b)) {
      var _customResult = customizeObject && customizeObject(a, b, newKey);

      return _customResult || (0, _mergeWith3.default)({}, a, b, joinArrays({
        customizeArray: customizeArray,
        customizeObject: customizeObject,
        key: newKey
      }));
    }

    if ((0, _isPlainObject3.default)(b)) {
      return (0, _cloneDeep3.default)(b);
    }

    return b;
  };
}


text:
package com.treelogic.proteus.core.incops.statistics;

import java.util.List;
import com.treelogic.proteus.core.configuration.IncrementalConfiguration;
import com.treelogic.proteus.resources.model.DataSerie;
import com.treelogic.proteus.resources.states.Stateful;
import com.treelogic.proteus.resources.states.StatefulCovariance;

/**
 * Incremental covariance using the updating formula described in
 * http://prod.sandia.gov/techlib/access-control.cgi/2008/086212.pdf
 *
 * @param <IN>
 *            Pojo type that contains the field to be analysed
 */
public class IncrementalCovariance<IN> extends IncrementalOperation<IN> {

	private static final long serialVersionUID = 1L;

	public IncrementalCovariance(IncrementalConfiguration configuration) {
		super(configuration, new StatefulCovariance());
	}

	@Override
	protected int numberOfRequiredDataSeries() {
		return 2;
	}

	@Override
	protected void updateWindow(String field, List<DataSerie> dataSeries, Stateful status) {
		status.apply(dataSeries);
	}

}


text:
<?xml version="1.0"?>
<!--
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
-->

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

<!--
  Reference: http://wiki.eclipse.org/Jetty/Reference/jetty.xml_syntax
  http://wiki.eclipse.org/Jetty/Reference/jetty.xml
-->

<Configure id="Fuseki" class="org.eclipse.jetty.server.Server">
  <Call name="addConnector">
    <Arg>
      <!-- org.eclipse.jetty.server.nio.BlockingChannelConnector -->
      <!-- org.eclipse.jetty.server.nio.SelectChannelConnector -->
      <New class="org.eclipse.jetty.server.nio.SelectChannelConnector">
	<!-- BlockingChannelConnector specific:
	     <Set name="useDirectBuffer">false</Set>
	-->
	<!-- Only listen to interface ...
	<Set name="host">localhost</Set>
	-->
	<Set name="port">3535</Set>
	<Set name="maxIdleTime">0</Set>
	<!-- All connectors -->
	<Set name="requestHeaderSize">65536</Set>       <!-- 64*1024 -->
	<Set name="requestBufferSize">5242880</Set>     <!-- 5*1024*1024 -->
	<Set name="responseBufferSize">5242880</Set>    <!-- 5*1024*1024 -->
      </New>
    </Arg>
  </Call>
</Configure>


text:
title: Appium and Selenium Grid
---

TODO


text:
'use strict';

const EventEmitter = require('events').EventEmitter;
const stampit = require('stampit');
const omit = require('lodash/object/omit');

const EventEmittable = stampit.convertConstructor(EventEmitter)
  .static({
    static(staticProps) {
      return this.static(omit(staticProps, [
        'init',
        'props',
        'refs',
        'methods',
        'compose',
        'create'
      ]));
    },
    on(event, action) {
      return this.init(function () {
        this.on(event, action);
      });
    },
    once(event, action) {
      return this.init(function () {
        this.once(event, action);
      });
    }
  });

module.exports = EventEmittable;


text:
<?php
/**
 * Deactivate a FC Set
 *
 * @package modx
 * @subpackage processors.security.forms.set
 */
if (!$modx->hasPermission('customize_forms')) return $modx->error->failure($modx->lexicon('permission_denied'));
$modx->lexicon->load('formcustomization');

if (empty($scriptProperties['id'])) return $modx->error->failure($modx->lexicon('set_err_ns'));
$set = $modx->getObject('modFormCustomizationSet',$scriptProperties['id']);
if ($set == null) return $modx->error->failure($modx->lexicon('set_err_nf'));

$set->set('active',false);

if ($set->save() === false) {
    return $modx->error->failure($modx->lexicon('set_err_save'));
}

return $modx->error->success('',$set);


text:
package fi.jyffe.opentiku.integration.firealarm.kafka;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

/**
*
* @author Jyrki Rantonen
*
* Kafka message producer
*
* TODO: Separate this into a client library?
*
*/
public class KafkaMessageSender {

	private static final Logger LOGGER = LoggerFactory.getLogger(KafkaMessageSender.class);

	@Value(value = "${message.topic.name}")
	private String messageTopic;

	@Autowired
	private KafkaTemplate<String, KafkaEventMessageDTO> kafkaTemplate;

	public void send(KafkaEventMessageDTO eventMessage) {

		LOGGER.info("sending event='{}'", eventMessage.toString());

		kafkaTemplate.send(messageTopic, eventMessage);
	}
}