text:
//
//  GKAuthorizationTool.m
//  GKAuthorizationTool
//
//  Created by 高坤 on 16/8/23.
//  Copyright © 2016年 高坤. All rights reserved.
//  由于有些类型模拟器不支持,建议使用真机进行测试

#import "GKAuthorizationTool.h"

#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
#import <AVFoundation/AVFoundation.h>
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>

@implementation GKAuthorizationTool

/**
 *  获取相册授权状态
 */
+ (GKAuthorizationStatus)getPhotoAuthorizationStatus
{
    ALAuthorizationStatus status = [ALAssetsLibrary authorizationStatus];
    switch (status) {
        case ALAuthorizationStatusNotDetermined:
            return GKAuthorizationStatusNotDetermined;
            break;
        case ALAuthorizationStatusAuthorized:
            return GKAuthorizationStatusAuthorized;
            break;
        case ALAuthorizationStatusDenied:
            return GKAuthorizationStatusDenied;
            break;
        case ALAuthorizationStatusRestricted:
            return GKAuthorizationStatusAuthorized;
            break;
        default:
            return GKAuthorizationStatusNotSupport;
            break;
    }
}

/**
 *  获取相机授权状态
 */
+ (GKAuthorizationStatus)getCameraAuthorizationStatus
{
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    switch (status) {
        case AVAuthorizationStatusNotDetermined:
            return GKAuthorizationStatusNotDetermined;
            break;
        case AVAuthorizationStatusAuthorized:
            return GKAuthorizationStatusAuthorized;
            break;
        case AVAuthorizationStatusDenied:
            return GKAuthorizationStatusDenied;
            break;
        case AVAuthorizationStatusRestricted:
            return GKAuthorizationStatusRestricted;
            break;

        default:
            return GKAuthorizationStatusNotSupport;
            break;
    }
}

/**
 *  获取麦克风授权状态(在模拟器中系统默认有麦克风权限,不知道为什么)
 */
+ (GKAuthorizationStatus)getAudioAuthorizationStatus
{
    AVAudioSessionRecordPermission permission = [AVAudioSession sharedInstance].recordPermission;
    switch (permission) {
        case AVAudioSessionRecordPermissionUndetermined:
            return GKAuthorizationStatusNotDetermined;
            break;
        case AVAudioSessionRecordPermissionGranted:
            return GKAuthorizationStatusAuthorized;
            break;
        case AVAudioSessionRecordPermissionDenied:
            return GKAuthorizationStatusDenied;
            break;
        default:
            return GKAuthorizationStatusNotSupport;
            break;
    }
}

/**
 *  检测某一授权类型是否授权成功
 *
 *  @param type 需要授权的类型
 *
 *  @return 授权是否成功
 */
+ (BOOL)checkAuthorizationWithType:(GKAuthorizationType)type
{
    GKAuthorizationStatus status;
    switch (type) {
        case GKAuthorizationTypePhoto:
            status = [self getPhotoAuthorizationStatus];
            break;
        case GKAuthorizationTypeCamera:
            status = [self getCameraAuthorizationStatus];
            break;
        case GKAuthorizationTypeAudio:
            status = [self getAudioAuthorizationStatus];
            break;

        default:
            status = -1;
            break;
    }
    if (status == GKAuthorizationStatusAuthorized) { // 可以访问
        return YES;
    }else{ // 不可访问
        return NO;
    }
}

#pragma mark - 相册授权
+ (void)requestPhotoAuthorizationCallback:(requestCallback)callback
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera] || [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        ALAuthorizationStatus authorStatus = [ALAssetsLibrary authorizationStatus];
        if (authorStatus == ALAuthorizationStatusNotDetermined) {
            if ([UIDevice currentDevice].systemVersion.doubleValue < 8.0) {
                [self executerCallback:callback status:GKAuthorizationStatusAuthorized];
            }else{ // ios8以后
                [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                    if (status == PHAuthorizationStatusAuthorized) { // 授权成功
                        [self executerCallback:callback status:GKAuthorizationStatusAuthorized];
                    }else if (status == PHAuthorizationStatusDenied){
                        [self executerCallback:callback status:GKAuthorizationStatusDenied];
                    }else if (status == PHAuthorizationStatusRestricted){
                        [self executerCallback:callback status:GKAuthorizationStatusRestricted];
                    }
                }];
            }
        }else if (authorStatus == ALAuthorizationStatusAuthorized){
            [self executerCallback:callback status:GKAuthorizationStatusAuthorized];
        }else if (authorStatus == ALAuthorizationStatusDenied){
            [self executerCallback:callback status:GKAuthorizationStatusDenied];
        }else if (authorStatus == ALAuthorizationStatusRestricted){
            [self executerCallback:callback status:GKAuthorizationStatusRestricted];
        }
    }else{
        [self executerCallback:callback status:GKAuthorizationStatusNotSupport];
    }
}

#pragma mark - 相册授权
+ (void)requestCameraAuthorizationCallback:(requestCallback)callback
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        AVAuthorizationStatus authorStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (authorStatus == AVAuthorizationStatusNotDetermined) {
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (granted) {
                    [self executerCallback:callback status:GKAuthorizationStatusAuthorized];
                }else{
                    [self executerCallback:callback status:GKAuthorizationStatusDenied];
                }
            }];
        }else if (authorStatus == AVAuthorizationStatusAuthorized){
            [self executerCallback:callback status:GKAuthorizationStatusAuthorized];
        }else if (authorStatus == AVAuthorizationStatusDenied){
            [self executerCallback:callback status:GKAuthorizationStatusDenied];
        }else if (authorStatus == AVAuthorizationStatusRestricted){
            [self executerCallback:callback status:GKAuthorizationStatusRestricted];
        }
    }else{
        [self executerCallback:callback status:GKAuthorizationStatusNotSupport];
    }
}

#pragma mark - 麦克风权限
+ (void)requestAudioAuthorizationCallback:(requestCallback)callback
{
    AVAudioSessionRecordPermission audioStatus = [AVAudioSession sharedInstance].recordPermission;
    if (audioStatus == AVAudioSessionRecordPermissionUndetermined) {
        [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
            if (granted) {
                [self executerCallback:callback status:GKAuthorizationStatusAuthorized];
            }else{
                [self executerCallback:callback status:GKAuthorizationStatusDenied];
            }
        }];
    }else if (audioStatus == AVAudioSessionRecordPermissionGranted){
        [self executerCallback:callback status:GKAuthorizationStatusAuthorized];
    }else if (audioStatus == AVAudioSessionRecordPermissionDenied){
        [self executerCallback:callback status:GKAuthorizationStatusDenied];
    }
}

#pragma mark - 回调函数
+ (void)executerCallback:(void(^)(GKAuthorizationStatus))callback status:(GKAuthorizationStatus)status
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (callback) {
            callback(status);
        }
    });
}

@end


text:
\chapter{Modal Interface of Vim}

\input{./vim/chapter3/normal}
\input{./vim/chapter3/insert}
\input{./vim/chapter3/visual}
\input{./vim/chapter3/command}

redpajama_set_name: RedPajamaGithub


text:
import { BWebPage } from './app.po';

describe('b-web App', () => {
  let page: BWebPage;

  beforeEach(() => {
    page = new BWebPage();
  });

  it('should display message saying app works', () => {
    page.navigateTo();
    expect(page.getParagraphText()).toEqual('app works!');
  });
});


text:
<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Inventory_errors extends CI_Controller {

	function __construct()
    {
        parent::__construct();

        //LOAD GLOBAL INVENTORY CONFIG
        $this->config->load('inventory');

        $this->load->helper('url');
   		$this->load->library('session');

		$params = array('model' => "inventory_ion_auth_model");
		$this->load->library('ion_auth',$params);

        //Localization:
        $this->lang->load('inventory', 'catalan');
        $this->load->helper('language');

    }

    function _get_rolename_byId($id){

		$roles = (array) $this->config->item('roles');
		return $roles[(int) $id];
	}

	public function load_header($not_show_header = true){

        $data['not_show_header2']=$not_show_header;

        $data['current_role_id']   = $this->session->userdata('role');

        $show_maintenace_menu=true;

        if ($data['current_role_id'] == "") {
			$show_maintenace_menu=false;
		} else {
			$data['current_role_name'] = $this->_get_rolename_byId($data['current_role_id']);
			if ($data['current_role_name'] == $this->config->item('organizationalunit_group') )
				$show_maintenace_menu=false;
		}

        $data['show_maintenace_menu'] =$show_maintenace_menu;

        $data['inventory_js_files'] = array(
            '/javascript/jquery/jquery.min.js',
            base_url('assets/js/bootstrap.min.js')
            );
        $data['inventory_css_files'] = array(
            base_url('assets/css/bootstrap.min.css'),
            base_url('assets/css/bootstrap-responsive.min.css'),
            base_url('assets/css/font-awesome.css')
            );

        $data['institution_name'] = $this->config->item('institution_name');
        //TODO: use real user name

        $data['usuari']=$this->session->userdata('session_id');

        $this->load->view('include/header',array_merge($data));

    }

	function error404()	{
		if (!$this->ion_auth->logged_in())
		{
			//redirect them to the login page
			redirect($this->login_page, 'refresh');
		}
		$this->load_header();
        $this->load->view('404.php');
        $this->load->view('include/footer');
	}

	function tablenotfound()	{
		$this->load_header();
        $this->load->view('tablenotfound.php');
        $this->load->view('include/footer');
	}

}


text:
package edu.upc.eetac.dsa.beeter.client.entity;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by root on 7/05/16.
 */
public class StingCollection {
    private List<Link> links;
    private long newestTimestamp;
    private long oldestTimestamp;
    private List<Sting> stings = new ArrayList<>();

    public List<Link> getLinks() {
        return links;
    }

    public void setLinks(List<Link> links) {
        this.links = links;
    }

    public long getNewestTimestamp() {
        return newestTimestamp;
    }

    public void setNewestTimestamp(long newestTimestamp) {
        this.newestTimestamp = newestTimestamp;
    }

    public long getOldestTimestamp() {
        return oldestTimestamp;
    }

    public void setOldestTimestamp(long oldestTimestamp) {
        this.oldestTimestamp = oldestTimestamp;
    }

    public List<Sting> getStings() {
        return stings;
    }

    public void setStings(List<Sting> stings) {
        this.stings = stings;
    }
}


text:
import React from 'react';
import Formsy from 'formsy-react';

var RecordTypeSwitchField = React.createClass({
  mixins: [Formsy.Mixin],

  componentWillReceiveProps(nextProps) {
    if (this.props.value !== nextProps.value) {
      this.setValue(nextProps.value);
      let marginLeft = (nextProps.value == 'income') ? '0px' : '-50px';
      this.setState({marginLeft: marginLeft});
    }
  },

  componentDidMount() {
    let value = this.getValue();
    let marginLeft = (value == 'income') ? '0px' : '-50px';
    this.setState({marginLeft: marginLeft});
  },

  changeValue(value) {
    this.setValue(value);
  },

  toggleSwitch() {
    let value = this.getValue();
    if (value == 'income') {
      value = 'expense';
      this.setValue(value);
      this.setState({marginLeft: '-50px'}, () => {
        this.props.onChange(value);
      });
    } else {
      value = 'income';
      this.setValue(value);
      this.setState({marginLeft: '0px'}, () => {
        this.props.onChange(value);
      });
    }
  },

  render() {
    return (

            <input id="switch-state" type="checkbox" checked="" />

    );
  }
});

export default RecordTypeSwitchField;


text:
<?php

namespace Phlexible\Bundle\MediaCacheBundle;

use Phlexible\Bundle\MediaCacheBundle\DependencyInjection\Compiler\AddWorkersPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;

/**
 * Media cache bundle
 *
 * @author Stephan Wentz <sw@brainbits.net>
 */
class PhlexibleMediaCacheBundle extends Bundle
{
    const RESOURCE_MEDIA_CACHE = 'mediacache';

    /**
     * {@inheritdoc}
     */
    public function build(ContainerBuilder $container)
    {
        $container->addCompilerPass(new AddWorkersPass());
    }
}


text:
readonly root=$(dirname "$0")
cd "$root"/.git/hooks
ln -fs ../../hooks/* .


text:
package androidx.media3.session;

import static com.google.common.truth.Truth.assertThat;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.assertThrows;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import androidx.media3.test.utils.TestUtil;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.google.common.util.concurrent.ListenableFuture;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okio.Buffer;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;

/**
 * Tests for {@link CacheBitmapLoader}.
 *
 * <p>This test needs to run as an androidTest because robolectric's {@link BitmapFactory} is not
 * fully functional.
 */
@RunWith(AndroidJUnit4.class)
public class CacheBitmapLoaderTest {

  private static final String TEST_IMAGE_PATH = "media/jpeg/non-motion-photo-shortened.jpg";

  private static final String SECOND_TEST_IMAGE_PATH = "media/jpeg/ss-motion-photo-shortened.jpg";

  @Rule public final TemporaryFolder tempFolder = new TemporaryFolder();

  @Test
  public void decodeBitmap_requestWithSameDataTwice_success() throws Exception {
    CacheBitmapLoader cacheBitmapLoader = new CacheBitmapLoader(new SimpleBitmapLoader());
    byte[] imageData =
        TestUtil.getByteArray(ApplicationProvider.getApplicationContext(), TEST_IMAGE_PATH);

    // First request, no cached bitmap load request.
    ListenableFuture<Bitmap> future1 = cacheBitmapLoader.decodeBitmap(imageData);

    assertThat(
            future1
                .get(10, SECONDS)
                .sameAs(
                    BitmapFactory.decodeByteArray(imageData, /* offset= */ 0, imageData.length)))
        .isTrue();

    // Second request, has cached bitmap load request.
    ListenableFuture<Bitmap> future2 = cacheBitmapLoader.decodeBitmap(imageData);

    assertThat(future1).isSameInstanceAs(future2);
  }

  @Test
  public void decodeBitmap_requestWithDifferentData_success() throws Exception {
    CacheBitmapLoader cacheBitmapLoader = new CacheBitmapLoader(new SimpleBitmapLoader());
    byte[] imageData1 =
        TestUtil.getByteArray(ApplicationProvider.getApplicationContext(), TEST_IMAGE_PATH);
    byte[] imageData2 =
        TestUtil.getByteArray(ApplicationProvider.getApplicationContext(), SECOND_TEST_IMAGE_PATH);

    // First request.
    ListenableFuture<Bitmap> future1 = cacheBitmapLoader.decodeBitmap(imageData1);

    assertThat(
            future1
                .get(10, SECONDS)
                .sameAs(
                    BitmapFactory.decodeByteArray(imageData1, /* offset= */ 0, imageData1.length)))
        .isTrue();

    // Second request.
    ListenableFuture<Bitmap> future2 = cacheBitmapLoader.decodeBitmap(imageData2);

    assertThat(
            future2
                .get(10, SECONDS)
                .sameAs(
                    BitmapFactory.decodeByteArray(imageData2, /* offset= */ 0, imageData2.length)))
        .isTrue();
    assertThat(future1).isNotSameInstanceAs(future2);
  }

  @Test
  public void decodeBitmap_requestWithSameDataTwice_throwsException() {
    CacheBitmapLoader cacheBitmapLoader = new CacheBitmapLoader(new SimpleBitmapLoader());

    // First request, no cached bitmap load request.
    ListenableFuture<Bitmap> future1 = cacheBitmapLoader.decodeBitmap(new byte[0]);

    // Second request, has cached bitmap load request.
    ListenableFuture<Bitmap> future2 = cacheBitmapLoader.decodeBitmap(new byte[0]);

    assertThat(future1).isSameInstanceAs(future2);
    ExecutionException executionException =
        assertThrows(ExecutionException.class, () -> future1.get(10, SECONDS));
    assertThat(executionException).hasCauseThat().isInstanceOf(IllegalArgumentException.class);
    assertThat(executionException).hasMessageThat().contains("Could not decode image data");
  }

  @Test
  public void loadBitmap_httpUri_requestWithSameUriTwice_success() throws Exception {
    CacheBitmapLoader cacheBitmapLoader = new CacheBitmapLoader(new SimpleBitmapLoader());
    byte[] imageData =
        TestUtil.getByteArray(ApplicationProvider.getApplicationContext(), TEST_IMAGE_PATH);
    Buffer responseBody = new Buffer().write(imageData);
    MockWebServer mockWebServer = new MockWebServer();
    mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody(responseBody));
    Uri uri = Uri.parse(mockWebServer.url("test_path").toString());

    // First request, no cached bitmap load request.
    Bitmap bitmap = cacheBitmapLoader.loadBitmap(uri).get(10, SECONDS);

    assertThat(
            bitmap.sameAs(
                BitmapFactory.decodeByteArray(imageData, /* offset= */ 0, imageData.length)))
        .isTrue();

    // Second request, has cached bitmap load request.
    bitmap = cacheBitmapLoader.loadBitmap(uri).get(10, SECONDS);

    assertThat(
            bitmap.sameAs(
                BitmapFactory.decodeByteArray(imageData, /* offset= */ 0, imageData.length)))
        .isTrue();
    assertThat(mockWebServer.getRequestCount()).isEqualTo(1);
  }

  @Test
  public void loadBitmap_httpUri_requestWithDifferentUri_success() throws Exception {
    CacheBitmapLoader cacheBitmapLoader = new CacheBitmapLoader(new SimpleBitmapLoader());
    byte[] imageData1 =
        TestUtil.getByteArray(ApplicationProvider.getApplicationContext(), TEST_IMAGE_PATH);
    byte[] imageData2 =
        TestUtil.getByteArray(ApplicationProvider.getApplicationContext(), SECOND_TEST_IMAGE_PATH);
    Buffer responseBody1 = new Buffer().write(imageData1);
    Buffer responseBody2 = new Buffer().write(imageData2);
    MockWebServer mockWebServer = new MockWebServer();
    mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody(responseBody1));
    mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody(responseBody2));
    Uri uri1 = Uri.parse(mockWebServer.url("test_path_1").toString());
    Uri uri2 = Uri.parse(mockWebServer.url("test_path_2").toString());

    // First request.
    Bitmap bitmap = cacheBitmapLoader.loadBitmap(uri1).get(10, SECONDS);

    assertThat(
            bitmap.sameAs(
                BitmapFactory.decodeByteArray(imageData1, /* offset= */ 0, imageData1.length)))
        .isTrue();

    // Second request.
    bitmap = cacheBitmapLoader.loadBitmap(uri2).get(10, SECONDS);

    assertThat(
            bitmap.sameAs(
                BitmapFactory.decodeByteArray(imageData2, /* offset= */ 0, imageData2.length)))
        .isTrue();
    assertThat(mockWebServer.getRequestCount()).isEqualTo(2);
  }

  @Test
  public void loadBitmap_httpUri_requestWithSameUriTwice_throwsException() throws Exception {
    CacheBitmapLoader cacheBitmapLoader = new CacheBitmapLoader(new SimpleBitmapLoader());
    MockWebServer mockWebServer = new MockWebServer();
    mockWebServer.enqueue(new MockResponse().setResponseCode(404));
    Uri uri = Uri.parse(mockWebServer.url("test_path").toString());

    // First request, no cached bitmap load request.
    ListenableFuture<Bitmap> future1 = cacheBitmapLoader.loadBitmap(uri);

    // Second request, has cached bitmap load request.
    ListenableFuture<Bitmap> future2 = cacheBitmapLoader.loadBitmap(uri);

    ExecutionException executionException1 =
        assertThrows(ExecutionException.class, () -> future1.get(10, SECONDS));
    ExecutionException executionException2 =
        assertThrows(ExecutionException.class, () -> future2.get(10, SECONDS));
    assertThat(executionException1).hasCauseThat().isInstanceOf(IOException.class);
    assertThat(executionException2).hasCauseThat().isInstanceOf(IOException.class);
    assertThat(executionException1).hasMessageThat().contains("Invalid response status");
    assertThat(executionException2).hasMessageThat().contains("Invalid response status");
    assertThat(mockWebServer.getRequestCount()).isEqualTo(1);
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
 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 Test SYSTEM "test.dtd">
<Test
	ID="EventTest016"
	date-of-creation="2006-08-22"
	timeout="1"
	>
    <!--
    Author:  Anatoly Bondarenko
    Version: $Revision: 1.3 $
    -->
		<Copyright value="apache"/>
		<Author value="Anatoly Bondarenko"/>
		<Description>
         This test case exercises the JDWP agent when very big number of event
         requests for THREAD_START event are sent.
         The stage 1:
          - Debuggee - creates some 'tested' threads.
          - Test - sends requests for THREAD_START events for 'checked' threads,
            which are the part of all 'tested' threads. For each 'checked' thread
            big number of requests are sent.
          - Debuggee - starts all 'tested' threads.
          - Test - checks that all expected THREAD_START events for all requests
            are received from JDWP agent: for each 'checked' thread big number
            of THREAD_START events should be received. No any THREAD_START event
            should be received for 'tested' threads, for which requests were not sent.
          - Test - clear all requests for THREAD_START events for all 'checked' threads.
         The stage 2:
          - Debuggee - finishes all 'tested' threads and creates them again.
          - Test - sends requests for THREAD_START events for all 'checked' threads,
            then cleares all sent requests for the some part of 'checked' threads.
          - Debuggee - starts all 'tested' threads.
          - Test - checks that only expected THREAD_START events for all active requests
            are received from JDWP agent.
          - Test - clear all active requests for THREAD_START events.
         The stage 3:
          - Debuggee - finishes all 'tested' threads and creates them again.
          - Test - sends requests for THREAD_START events for all 'checked' threads,
            then cleares all sent requests for all 'checked' threads.
          - Debuggee - starts all 'tested' threads.
          - Test - checks that no any events except VM_DEATH event
            are received from JDWP agent.
   		</Description>

		<Keyword name="stress"/>
		<Keyword name="jpda"/>
		<Source name="EventTest016.java"/>
		<Source name="EventDebuggee016.java"/>
		<Modification date="2006-08-22" author="Anatoly Bondarenko"/>

		<Runner ID="Runtime">
			<Option name="-Djpda.settings.timeout=300000"/>
			<Param name="toRun" value="org.apache.harmony.test.stress.jpda.jdwp.scenario.EVENT016.EventTest016">
			</Param>
		</Runner>
</Test>


text:
<?php

namespace JumpGate\Core\View;

use Illuminate\Config\Repository;
use Illuminate\View\Factory;
use Illuminate\Http\Request;

class Layout
{

    public $layout;

    protected $view;

    protected $request;

    protected $config;

    protected $layoutOptions;

    public function __construct(Factory $view, Request $request, Repository $config)
    {
        $this->view    = $view;
        $this->request = $request;
        $this->config  = $config;
    }

    public function setUp($layoutOptions)
    {
        $this->layoutOptions = $this->verifyLayoutOptions($layoutOptions);
        $this->layout        = $this->determineLayout(null);
        $this->setPageTitle();
        $this->layout->content = null;

        return $this;
    }

    public function change($view)
    {
        $this->layout = $this->determineLayout($view);
        $this->setPageTitle();
        $this->layout->content = null;

        return $this;
    }

    public function setPageTitle()
    {
        $area     = $this->request->segment(1);
        $location = ($this->request->segment(2) != null ? ': ' . ucwords($this->request->segment(2)) : '');

        if ($area != null) {
            $pageTitle = ucwords($area) . $location;
        } else {
            $pageTitle = $this->config->get('core::siteName') . ($this->request->segment(1) != null ? ': ' . ucwords($this->request->segment(1)) : '');
        }

        $this->view->share('pageTitle', $pageTitle);
    }

    public function getLayout()
    {
        return $this->layout;
    }

    protected function determineLayout($layout)
    {
        if (! is_null($layout)) {
            return $this->view->make($layout);
        }

        if (is_string($this->layout)) {
            return $this->view->make($this->layout);
        }

        if (is_null($this->layout) && $this->request->ajax()) {
            return $this->view->make($this->layoutOptions['ajax']);
        }

        if (is_null($this->layout)) {
            return $this->view->make($this->layoutOptions['default']);
        }

        return $this->layout;
    }

    private function verifyLayoutOptions($layoutOptions)
    {
        if (! is_array($layoutOptions)) {
            throw new \InvalidArgumentException('The layoutOptions must be an array.');
        }
        if (! isset($layoutOptions['default'])) {
            throw new \InvalidArgumentException('The layoutOptions must have a default layout view.');
        }
        if (! isset($layoutOptions['ajax'])) {
            throw new \InvalidArgumentException('The layoutOptions must have a ajax layout view.');
        }

        return $layoutOptions;
    }
}


text:
import { Component, Input, OnInit } from '@angular/core';
import { FavoriteService } from '../providers/favorite.service';
import { AuthService } from '../providers/auth.service';

@Component({
  selector: 'favorite',
  templateUrl: './favorite.component.html',
  styleUrls: ['./favorite.component.scss']
})
export class FavoriteComponent implements OnInit {
  @Input() recipeId: string;
  isActive: boolean;
  iconClass = 'none';
  private currentUser;

  constructor(private favoriteSvc: FavoriteService, private authSvc: AuthService) { }

  ngOnInit() {
    this.authSvc.authState.subscribe(user => {
      this.currentUser = user;
    });

    // is this one of my favorites
    if (this.currentUser) {
      this.favoriteSvc.get(this.recipeId).subscribe(x => {
        if (x.$exists()) {
          this.setIconClass(true);
        }
      });
    }
  }

  setIconClass(isActive: boolean) {
    if (isActive) {
      this.iconClass = 'active';
    } else {
      this.iconClass = '';
    }
  }

  toggle() {
    if (!this.currentUser) {
      return null;
    }

    this.isActive = !this.isActive;
    this.setIconClass(this.isActive);

    if (this.isActive) {
      this.favoriteSvc.add(this.recipeId);
    } else {
      this.favoriteSvc.remove(this.recipeId);
    }
  }
}


text:
'use strict';

const isNil = require('lodash.isnil');

const {
    util: { invalidParam },
    consts: { EXECUTION_HINT_SET }
} = require('../../core');

const BucketAggregationBase = require('./bucket-aggregation-base');

const ES_REF_URL =
    'https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-diversified-sampler-aggregation.html';

const invalidExecutionHintParam = invalidParam(
    ES_REF_URL,
    'execution_hint',
    EXECUTION_HINT_SET
);

/**
 * A filtering aggregation used to limit any sub aggregations' processing
 * to a sample of the top-scoring documents. Diversity settings
 * are used to limit the number of matches that share a common value such as an "author".
 *
 * [Elasticsearch reference](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-diversified-sampler-aggregation.html)
 *
 * @example
 * const reqBody = esb.requestBodySearch()
 *     .query(esb.queryStringQuery('tags:elasticsearch'))
 *     .agg(
 *         esb.diversifiedSamplerAggregation('my_unbiased_sample', 'author')
 *             .shardSize(200)
 *             .agg(
 *                 esb.significantTermsAggregation(
 *                     'keywords',
 *                     'tags'
 *                 ).exclude(['elasticsearch'])
 *             )
 *     );
 *
 * @example
 * // Use a script to produce a hash of the multiple values in a tags field
 * // to ensure we don't have a sample that consists of the same repeated
 * // combinations of tags
 * const reqBody = esb.requestBodySearch()
 *     .query(esb.queryStringQuery('tags:kibana'))
 *     .agg(
 *         esb.diversifiedSamplerAggregation('my_unbiased_sample')
 *             .shardSize(200)
 *             .maxDocsPerValue(3)
 *             .script(esb.script('inline', "doc['tags'].values.hashCode()"))
 *             .agg(
 *                 esb.significantTermsAggregation(
 *                     'keywords',
 *                     'tags'
 *                 ).exclude(['kibana'])
 *             )
 *     );
 *
 * @param {string} name The name which will be used to refer to this aggregation.
 * @param {string=} field The field to aggregate on
 *
 * @extends BucketAggregationBase
 */
class DiversifiedSamplerAggregation extends BucketAggregationBase {
    // eslint-disable-next-line require-jsdoc
    constructor(name, field) {
        super(name, 'diversified_sampler', field);
    }

    /**
     * The shard_size parameter limits how many top-scoring documents
     * are collected in the sample processed on each shard. The default value is 100.
     *
     * @param {number} size Maximum number of documents to return from each shard(Integer)
     * @returns {DiversifiedSamplerAggregation} returns `this` so that calls can be chained
     */
    shardSize(size) {
        this._aggsDef.shard_size = size;
        return this;
    }

    /**
     * Used to control the maximum number of documents collected
     * on any one shard which share a common value.
     * Applies on a per-shard basis only for the purposes of shard-local sampling.
     *
     * @param {number} maxDocsPerValue Default 1.(Integer)
     * @returns {DiversifiedSamplerAggregation} returns `this` so that calls can be chained
     */
    maxDocsPerValue(maxDocsPerValue) {
        this._aggsDef.max_docs_per_value = maxDocsPerValue;
        return this;
    }

    /**
     * This setting can influence the management of the values used
     * for de-duplication. Each option will hold up to shard_size
     * values in memory while performing de-duplication but
     * the type of value held can be controlled
     *
     * @param {string} hint the possible values are `map`, `global_ordinals`,
     * `global_ordinals_hash` and `global_ordinals_low_cardinality`
     * @returns {DiversifiedSamplerAggregation} returns `this` so that calls can be chained
     * @throws {Error} If Execution Hint is outside the accepted set.
     */
    executionHint(hint) {
        if (isNil(hint)) invalidExecutionHintParam(hint);

        const hintLower = hint.toLowerCase();
        if (!EXECUTION_HINT_SET.has(hintLower)) {
            invalidExecutionHintParam(hint);
        }

        this._aggsDef.execution_hint = hintLower;
        return this;
    }
}

module.exports = DiversifiedSamplerAggregation;


text:
(function() {
	/**
	 * @ngdoc controller
	 * @name app.guild.controller:RaidCtrl
	 * @description < description placeholder >
	 */

	angular
		.module('app.guild')
		.controller('RaidCtrl', RaidCtrl);

	RaidCtrl.$inject = ['$http', 'toastr'];
	/* @ngInject */
	function RaidCtrl($http, toastr) {

		/*jshint validthis: true */
		var vm = this;
		vm.formData = {};
		vm.addRaid = function() {
			// funcation assignmen
			$http.post('/api/raids', vm.formData).success(function() {
				toastr
				.success('Goodluck, you\'re going to need it', 'Recruitment Updated');
			}).error(function(error) {
				toastr.error('There was a problem with the server' +
					error.message, 'Something broke');
			});
		};

		$http.get('/api/raids').success(function(data) {
			vm.raids = data;
		});
	}

})();


text:
template<typename T>
static T* npc(T* t)
{
    if(!t) throw new ::java::lang::NullPointerException();
    return t;
}

poi::ss::formula::functions::Countif_CmpOp::Countif_CmpOp(const ::default_init_tag&)
    : super(*static_cast< ::default_init_tag* >(0))
{
    clinit();
}

poi::ss::formula::functions::Countif_CmpOp::Countif_CmpOp(::java::lang::String* representation, int32_t code)
    : Countif_CmpOp(*static_cast< ::default_init_tag* >(0))
{
    ctor(representation,code);
}

constexpr int32_t poi::ss::formula::functions::Countif_CmpOp::NONE;

constexpr int32_t poi::ss::formula::functions::Countif_CmpOp::EQ;

constexpr int32_t poi::ss::formula::functions::Countif_CmpOp::NE;

constexpr int32_t poi::ss::formula::functions::Countif_CmpOp::LE;

constexpr int32_t poi::ss::formula::functions::Countif_CmpOp::LT;

constexpr int32_t poi::ss::formula::functions::Countif_CmpOp::GT;

constexpr int32_t poi::ss::formula::functions::Countif_CmpOp::GE;

poi::ss::formula::functions::Countif_CmpOp*& poi::ss::formula::functions::Countif_CmpOp::OP_NONE()
{
    clinit();
    return OP_NONE_;
}
poi::ss::formula::functions::Countif_CmpOp* poi::ss::formula::functions::Countif_CmpOp::OP_NONE_;

poi::ss::formula::functions::Countif_CmpOp*& poi::ss::formula::functions::Countif_CmpOp::OP_EQ()
{
    clinit();
    return OP_EQ_;
}
poi::ss::formula::functions::Countif_CmpOp* poi::ss::formula::functions::Countif_CmpOp::OP_EQ_;

poi::ss::formula::functions::Countif_CmpOp*& poi::ss::formula::functions::Countif_CmpOp::OP_NE()
{
    clinit();
    return OP_NE_;
}
poi::ss::formula::functions::Countif_CmpOp* poi::ss::formula::functions::Countif_CmpOp::OP_NE_;

poi::ss::formula::functions::Countif_CmpOp*& poi::ss::formula::functions::Countif_CmpOp::OP_LE()
{
    clinit();
    return OP_LE_;
}
poi::ss::formula::functions::Countif_CmpOp* poi::ss::formula::functions::Countif_CmpOp::OP_LE_;

poi::ss::formula::functions::Countif_CmpOp*& poi::ss::formula::functions::Countif_CmpOp::OP_LT()
{
    clinit();
    return OP_LT_;
}
poi::ss::formula::functions::Countif_CmpOp* poi::ss::formula::functions::Countif_CmpOp::OP_LT_;

poi::ss::formula::functions::Countif_CmpOp*& poi::ss::formula::functions::Countif_CmpOp::OP_GT()
{
    clinit();
    return OP_GT_;
}
poi::ss::formula::functions::Countif_CmpOp* poi::ss::formula::functions::Countif_CmpOp::OP_GT_;

poi::ss::formula::functions::Countif_CmpOp*& poi::ss::formula::functions::Countif_CmpOp::OP_GE()
{
    clinit();
    return OP_GE_;
}
poi::ss::formula::functions::Countif_CmpOp* poi::ss::formula::functions::Countif_CmpOp::OP_GE_;

poi::ss::formula::functions::Countif_CmpOp* poi::ss::formula::functions::Countif_CmpOp::op(::java::lang::String* rep, int32_t code)
{
    clinit();
    return new Countif_CmpOp(rep, code);
}

void poi::ss::formula::functions::Countif_CmpOp::ctor(::java::lang::String* representation, int32_t code)
{
    super::ctor();
    _representation = representation;
    _code = code;
}

int32_t poi::ss::formula::functions::Countif_CmpOp::getLength()
{
    return npc(_representation)->length();
}

int32_t poi::ss::formula::functions::Countif_CmpOp::getCode()
{
    return _code;
}

poi::ss::formula::functions::Countif_CmpOp* poi::ss::formula::functions::Countif_CmpOp::getOperator(::java::lang::String* value)
{
    clinit();
    auto len = npc(value)->length();
    if(len < 1) {
        return OP_NONE_;
    }
    auto firstChar = npc(value)->charAt(int32_t(0));
    switch (firstChar) {
    case u'=':
        return OP_EQ_;
    case u'>':
        if(len > 1) {
            switch (npc(value)->charAt(int32_t(1))) {
            case u'=':
                return OP_GE_;
            }

        }
        return OP_GT_;
    case u'<':
        if(len > 1) {
            switch (npc(value)->charAt(int32_t(1))) {
            case u'=':
                return OP_LE_;
            case u'>':
                return OP_NE_;
            }

        }
        return OP_LT_;
    }

    return OP_NONE_;
}

bool poi::ss::formula::functions::Countif_CmpOp::evaluate(bool cmpResult)
{
    switch (_code) {
    case NONE:
    case EQ:
        return cmpResult;
    case NE:
        return !cmpResult;
    }

    throw new ::java::lang::RuntimeException(::java::lang::StringBuilder().append(u"Cannot call boolean evaluate on non-equality operator '"_j)->append(_representation)
        ->append(u"'"_j)->toString());
}

bool poi::ss::formula::functions::Countif_CmpOp::evaluate(int32_t cmpResult)
{
    switch (_code) {
    case NONE:
    case EQ:
        return cmpResult == 0;
    case NE:
        return cmpResult != 0;
    case LT:
        return cmpResult < 0;
    case LE:
        return cmpResult <= 0;
    case GT:
        return cmpResult > 0;
    case GE:
        return cmpResult >= 0;
    }

    throw new ::java::lang::RuntimeException(::java::lang::StringBuilder().append(u"Cannot call boolean evaluate on non-equality operator '"_j)->append(_representation)
        ->append(u"'"_j)->toString());
}

java::lang::String* poi::ss::formula::functions::Countif_CmpOp::toString()
{
    auto sb = new ::java::lang::StringBuffer(int32_t(64));
    npc(sb)->append(npc(getClass())->getName());
    npc(npc(npc(sb)->append(u" ["_j))->append(_representation))->append(u"]"_j);
    return npc(sb)->toString();
}

java::lang::String* poi::ss::formula::functions::Countif_CmpOp::getRepresentation()
{
    return _representation;
}

extern java::lang::Class *class_(const char16_t *c, int n);

java::lang::Class* poi::ss::formula::functions::Countif_CmpOp::class_()
{
    static ::java::lang::Class* c = ::class_(u"org.apache.poi.ss.formula.functions.Countif.CmpOp", 49);
    return c;
}

void poi::ss::formula::functions::Countif_CmpOp::clinit()
{
    super::clinit();
    static bool in_cl_init = false;
struct clinit_ {
    clinit_() {
        in_cl_init = true;
        OP_NONE_ = op(u""_j, NONE);
        OP_EQ_ = op(u"="_j, EQ);
        OP_NE_ = op(u"<>"_j, NE);
        OP_LE_ = op(u"<="_j, LE);
        OP_LT_ = op(u"<"_j, LT);
        OP_GT_ = op(u">"_j, GT);
        OP_GE_ = op(u">="_j, GE);
    }
};

    if(!in_cl_init) {
        static clinit_ clinit_instance;
    }
}

java::lang::Class* poi::ss::formula::functions::Countif_CmpOp::getClass0()
{
    return class_();
}


text:
<?php

use yii\web\View;

//use yii\helpers\Html;

/* @var $this View */
?>

 404

 Oops! Page not found.

            We could not find the page you were looking for.

            Please contact us if you think this is a server error. Thank you.


text:
<?xml version="1.0"?>
<!--
 Project: OBEOS METADATA EDITOR
 Authors: Natascha Neumaerker, Siemens Convergence Creators, Prague (CZ)
          Milan Novacek, Siemens Convergence Creators, Prague (CZ)
          Radim Zajonc, Siemens Convergence Creators, Prague (CZ)
          Stanislav Kascak, Siemens Convergence Creators

 Copyright (C) 2017 Siemens Convergence Creators, Prague (CZ)
    ===============================================================
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies of this Software or works derived from this Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>esa.obes.metadataeditor</groupId>
	<artifactId>esa.obes.metadataeditor.jsf.portlet.test.receiver</artifactId>
	<packaging>war</packaging>
	<name>esa.obes.metadataeditor.jsf.portlet.test.receiver Portlet</name>
	<version>0.1.0-SNAPSHOT</version>
	<build>
		<plugins>
			<plugin>
				<groupId>com.liferay.maven.plugins</groupId>
				<artifactId>liferay-maven-plugin</artifactId>
				<version>${liferay.maven.plugin.version}</version>
				<executions>
					<execution>
						<phase>generate-sources</phase>
						<goals>
							<goal>build-css</goal>
						</goals>
					</execution>
				</executions>
				<configuration>
					<autoDeployDir>${liferay.auto.deploy.dir}</autoDeployDir>
					<appServerDeployDir>${liferay.app.server.deploy.dir}</appServerDeployDir>
					<appServerLibGlobalDir>${liferay.app.server.lib.global.dir}</appServerLibGlobalDir>
					<appServerPortalDir>${liferay.app.server.portal.dir}</appServerPortalDir>
					<liferayVersion>${liferay.version}</liferayVersion>
					<pluginType>portlet</pluginType>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.5</version>
				<configuration>
					<encoding>UTF-8</encoding>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-resources-plugin</artifactId>
				<version>2.5</version>
				<configuration>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
		</plugins>
	</build>
	<dependencies>
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.2.2</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>1.3.2</version>
		</dependency>
		<dependency>
			<groupId>com.liferay.faces</groupId>
			<artifactId>liferay-faces-bridge-impl</artifactId>
			<version>3.2.4-ga5</version>
		</dependency>
		<dependency>
			<groupId>com.liferay.faces</groupId>
			<artifactId>liferay-faces-portal</artifactId>
			<version>3.2.4-ga5</version>
		</dependency>
		<dependency>
			<groupId>com.liferay.portal</groupId>
			<artifactId>portal-service</artifactId>
			<version>${liferay.version}</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>com.liferay.portal</groupId>
			<artifactId>util-java</artifactId>
			<version>${liferay.version}</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>com.sun.faces</groupId>
			<artifactId>jsf-api</artifactId>
			<version>2.1.21</version>
		</dependency>
		<dependency>
			<groupId>com.sun.faces</groupId>
			<artifactId>jsf-impl</artifactId>
			<version>2.1.21</version>
		</dependency>
		<dependency>
			<groupId>javax.el</groupId>
			<artifactId>el-api</artifactId>
			<version>1.0</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.portlet</groupId>
			<artifactId>portlet-api</artifactId>
			<version>2.0</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.jboss.seam</groupId>
			<artifactId>jboss-el</artifactId>
			<version>2.0.0.GA</version>
			<exclusions>
				<exclusion>
					<artifactId>el-api</artifactId>
					<groupId>javax.el</groupId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.primefaces</groupId>
			<artifactId>primefaces</artifactId>
			<version>3.5</version>
		</dependency>
	</dependencies>
	<repositories>
		<repository>
			<id>maven2-repository.dev.java.net</id>
			<name>Java.net Repository for Maven</name>
			<url>http://download.java.net/maven/2/</url>
		</repository>
		<repository>
			<id>maven2-repository.jboss.org</id>
			<name>JBoss Maven Repository</name>
			<url>http://repository.jboss.org/nexus/content/groups/public-jboss</url>
		</repository>
		<repository>
			<id>maven2-repository.primefaces.org</id>
			<name>PrimeFaces Maven Repository</name>
			<url>http://repository.primefaces.org</url>
		</repository>
	</repositories>
</project>


text:
import os, json, tempfile, filecmp
from nose.tools import assert_raises, assert_equal, assert_in
from mock import MagicMock, patch
import unit
import synapseclient
from synapseclient import File
from synapseclient.exceptions import *
from synapseclient import Evaluation

def setup(module):
    print('\n')
    print('~' * 60)
    print(os.path.basename(__file__))
    print('~' * 60)
    module.syn = unit.syn

@patch('synapseclient.Synapse._loggedIn')
@patch('synapseclient.Synapse.restDELETE')
@patch('synapseclient.Synapse._readSessionCache')
@patch('synapseclient.Synapse._writeSessionCache')
def test_logout(*mocks):
    mocks = [item for item in mocks]
    logged_in_mock     = mocks.pop()
    delete_mock        = mocks.pop()
    read_session_mock  = mocks.pop()
    write_session_mock = mocks.pop()

    # -- Logging out while not logged in shouldn't do anything --
    logged_in_mock.return_value = False
    syn.username = None
    syn.logout()
    syn.logout()

    assert not delete_mock.called
    assert not write_session_mock.called

@patch('synapseclient.Synapse._downloadFileEntity')
def test_getWithEntityBundle(download_file_mock):

    ## Note: one thing that remains unexplained is why the previous version of
    ## this test worked if you had a .cacheMap file of the form:
    ## {"/Users/chris/.synapseCache/663/-1337/anonymous": "2014-09-15T22:54:57.000Z",
    ##  "/var/folders/ym/p7cr7rrx4z7fw36sxv04pqh00000gq/T/tmpJ4nz8U": "2014-09-15T23:27:25.000Z"}
    ## ...but failed if you didn't.

    ## TODO: Uncomment failing asserts after SYNR-790 and SYNR-697 are fixed

    bundle = {
        'entity': {
            'id': 'syn10101',
            'name': 'anonymous',
            'dataFileHandleId': '-1337',
            'concreteType': 'org.sagebionetworks.repo.model.FileEntity',
            'parentId': 'syn12345'},
        'fileHandles': [{
            'concreteType': 'org.sagebionetworks.repo.model.file.S3FileHandle',
            'fileName': 'anonymous',
            'contentType': 'application/flapdoodle',
            'contentMd5': '1698d26000d60816caab15169efcd23a',
            'id': '-1337'}],
        'annotations': {}}

    fileHandle = bundle['fileHandles'][0]['id']
    cacheDir = syn.cache.get_cache_dir(fileHandle)
    print("cacheDir=", cacheDir)

    # Make sure the .cacheMap file does not already exist
    cacheMap = os.path.join(cacheDir, '.cacheMap')
    if os.path.exists(cacheMap):
        print("removing cacheMap file: ", cacheMap)
        os.remove(cacheMap)

    def _downloadFileEntity(entity, path, submission, file_handle_id):
        print("mock downloading file to:", path)
        ## touch file at path
        with open(path, 'a'):
            os.utime(path, None)
        dest_dir, filename = os.path.split(path)
        return {"path": path,
                "files": [filename],
                "cacheDir": dest_dir}
    download_file_mock.side_effect = _downloadFileEntity

    # 1. ----------------------------------------------------------------------
    # download file to an alternate location

    temp_dir1 = tempfile.mkdtemp()
    print("temp_dir1=", temp_dir1)

    e = syn._getWithEntityBundle(entityBundle=bundle,
                                 downloadLocation=temp_dir1,
                                 ifcollision="overwrite.local")
    print(e)

    assert e.name == bundle["entity"]["name"]
    assert e.parentId == bundle["entity"]["parentId"]
    assert e.cacheDir == temp_dir1
    assert bundle["fileHandles"][0]["fileName"] in e.files
    assert e.path == os.path.join(temp_dir1, bundle["fileHandles"][0]["fileName"])

    # 2. ----------------------------------------------------------------------
    # get without specifying downloadLocation
    e = syn._getWithEntityBundle(entityBundle=bundle, ifcollision="overwrite.local")

    print(e)

    assert e.name == bundle["entity"]["name"]
    assert e.parentId == bundle["entity"]["parentId"]
    assert bundle["fileHandles"][0]["fileName"] in e.files

    # 3. ----------------------------------------------------------------------
    # download to another location
    temp_dir2 = tempfile.mkdtemp()
    assert temp_dir2 != temp_dir1
    e = syn._getWithEntityBundle(entityBundle=bundle,
                                 downloadLocation=temp_dir2,
                                 ifcollision="overwrite.local")
    print("temp_dir2=", temp_dir2)
    print(e)

    assert_in(bundle["fileHandles"][0]["fileName"], e.files)
    assert e.path is not None
    assert utils.equal_paths( os.path.dirname(e.path), temp_dir2 )

    # 4. ----------------------------------------------------------------------
    ## test preservation of local state
    url = 'http://foo.com/secretstuff.txt'
    e = File(name='anonymous', parentId="syn12345", synapseStore=False, externalURL=url)
    e.local_state({'zap':'pow'})
    e = syn._getWithEntityBundle(entityBundle=bundle, entity=e)
    assert e.local_state()['zap'] == 'pow'
    assert e.synapseStore == False
    assert e.externalURL == url

    ## TODO: add more test cases for flag combination of this method
    ## TODO: separate into another test?

@patch('synapseclient.Synapse.restGET')
@patch('synapseclient.Synapse.restPOST')
@patch('synapseclient.Synapse.getEvaluation')
def test_submit(*mocks):
    mocks = [item for item in mocks]
    GET_mock        = mocks.pop()
    POST_mock       = mocks.pop()
    getEvaluation_mock = mocks.pop()

    # -- Unmet access rights --
    GET_mock.return_value = {'totalNumberOfResults': 2,
                             'results': [
                                {'accessType': 'Foo',
                                 'termsOfUse': 'Bar'},
                                {'accessType': 'bat',
                                 'termsOfUse': 'baz'}]}
    getEvaluation_mock.return_value = Evaluation(**{u'contentSource': u'syn1001',
                                                    u'createdOn': u'2013-11-06T06:04:26.789Z',
                                                    u'etag': u'86485ea1-8c89-4f24-a0a4-2f63bc011091',
                                                    u'id': u'9090',
                                                    u'name': u'test evaluation',
                                                    u'ownerId': u'1560252',
                                                    u'status': u'OPEN',
                                                    u'submissionReceiptMessage': u'mmmm yummy!'})

    assert_raises(SynapseAuthenticationError, syn.submit, "9090", "syn1001")
    GET_mock.assert_called_once_with('/evaluation/9090/accessRequirementUnfulfilled')

    # -- Normal submission --
    # Pretend the user has access rights
    GET_mock.return_value = {'totalNumberOfResults': 0, 'results': []}

    # insert a shim that returns the dictionary it was passed after adding a bogus id
    def shim(*args):
        assert args[0] == '/evaluation/submission?etag=Fake eTag'
        submission = json.loads(args[1])
        submission['id'] = 1234
        return submission
    POST_mock.side_effect = shim

    submission = syn.submit('9090', {'versionNumber': 1337, 'id': "Whee...", 'etag': 'Fake eTag'}, name='George', submitterAlias='Team X')
    assert GET_mock.call_count == 2

    assert submission.id == 1234
    assert submission.evaluationId == '9090'
    assert submission.name == 'George'
    assert submission.submitterAlias == 'Team X'

    print(submission)

def test_send_message():
    with patch("synapseclient.multipart_upload._multipart_upload") as up_mock, patch("synapseclient.client.Synapse.restPOST") as post_mock:
            up_mock.return_value = {
                'startedOn': '2016-01-22T00:00:00.000Z',
                'state': 'COMPLETED',
                'uploadId': '1234',
                'updatedOn': '2016-01-22T00:00:00.000Z',
                'partsState': '11',
                'startedBy': '377358',
                'resultFileHandleId': '7365905' }
            syn.sendMessage(
                userIds=[1421212],
                messageSubject="Xanadu",
                messageBody=   ("In Xanadu did Kubla Khan\n"
                                "A stately pleasure-dome decree:\n"
                                "Where Alph, the sacred river, ran\n"
                                "Through caverns measureless to man\n"
                                "Down to a sunless sea.\n"))
            msg = json.loads(post_mock.call_args_list[0][1]['body'])
            assert msg["fileHandleId"] == "7365905", msg
            assert msg["recipients"] == [1421212], msg
            assert msg["subject"] == "Xanadu", msg


text:
<?xml version="1.0" encoding="utf-8"?>
<defaultsMap>
    <entry>
        <key>showing_image</key>
        <value>false</value>
    </entry>
    <entry>
        <key>next_button_black</key>
        <value>false</value>
    </entry>
</defaultsMap>


text:
extern crate cfg_if;
extern crate hqx;
extern crate wasm_bindgen;

mod utils;

use cfg_if::cfg_if;
use wasm_bindgen::prelude::*;

cfg_if! {
    // When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
    // allocator.
    if #[cfg(feature = "wee_alloc")] {
        extern crate wee_alloc;
        #[global_allocator]
        static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
    }
}

#[wasm_bindgen]
#[no_mangle]
pub fn resize(
    input_image: Vec<u32>,
    input_width: usize,
    input_height: usize,
    factor: usize,
) -> Vec<u32> {
    let num_output_pixels = input_width * input_height * factor * factor;
    let mut output_image = Vec::<u32>::with_capacity(num_output_pixels * 4);
    output_image.resize(num_output_pixels, 0);

    match factor {
        2 => hqx::hq2x(
            input_image.as_slice(),
            output_image.as_mut_slice(),
            input_width,
            input_height,
        ),
        3 => hqx::hq3x(
            input_image.as_slice(),
            output_image.as_mut_slice(),
            input_width,
            input_height,
        ),
        4 => hqx::hq4x(
            input_image.as_slice(),
            output_image.as_mut_slice(),
            input_width,
            input_height,
        ),
        _ => unreachable!(),
    };

    return output_image;
}


text:
package tests

import (
	"plivo/plivo.sms/model"
	"plivo/plivo.sms/validator"
	"testing"
)

var fromNumberTests = []struct {
	FromNumber string
	IsValid    bool
}{
	{"", false},
	{"123", false},
	{"123456", true},
	{"1234567891234567", true},
	{"12345678912345678", false},
}

func TestFromNumberInSMS(t *testing.T) {
	fromNumberValidator := validator.FromNumberValidator{}

	for _, testCase := range fromNumberTests {
		validationResult := fromNumberValidator.Validate(model.NewSMS(testCase.FromNumber, "", ""))

		if testCase.IsValid != validationResult.IsSuccess {
			t.Errorf("From Number : %s, expected validation result is %t, actual is %t", testCase.FromNumber, testCase.IsValid, validationResult.IsSuccess)
			t.Fail()
		}
	}
}


text:
package org.bitj;

import org.bitj.logging.LoggersRegistrar;
import org.bitj.utils.Debug;
import org.bitj.wire.BitcoinInputStream;
import org.bitj.wire.Wire;
import org.bitj.wire.messages.Msg;
import org.testng.annotations.BeforeSuite;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.ThreadLocalRandom;
import java.util.logging.Level;

public class BaseTest {

  @BeforeSuite
  public void registerLoggers() throws Exception {
    LoggersRegistrar.registerEventLogger(Level.FINEST);
  }

  public static byte[] bytes(int... iBytes) {
    byte[] bBytes = new byte[iBytes.length];
    for (int i = 0; i < iBytes.length; i++) {
      int iByte = iBytes[i];
      if (iByte < 0 || iByte > 255)
        throw new IllegalArgumentException("Is not a byte: " + iByte);
      bBytes[i] = (byte) iByte;
    }
    return bBytes;
  }

  public static byte[] bytes(String hex) {
    return Debug.hexToBytes(hex);
  }

  public static byte[] reversedBytes(String hex) {
    return Wire.reverseBytes(Debug.hexToBytes(hex));
  }

  public static byte[] randomBytes(int n) {
    byte[] b = new byte[n];
    rng().nextBytes(b);
    return b;
  }

  public static BitcoinInputStream bitcoinStream(int... iBytes) {
    return new BitcoinInputStream(byteStream(iBytes));
  }

  public static BitcoinInputStream bitcoinStream(byte[] bytes) {
    return new BitcoinInputStream(new ByteArrayInputStream(bytes));
  }

  public static BitcoinInputStream bitcoinStream(String hexes) {
    return bitcoinStream(Debug.hexToBytes(hexes));
  }

  public static ByteArrayInputStream byteStream(int... iBytes) {
    return new ByteArrayInputStream(bytes(iBytes));
  }

  public static byte[] serializeToBytes(Msg msg) throws IOException {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    msg.serialize(os);
    return os.toByteArray();
  }

  public static ThreadLocalRandom rng() {
    return ThreadLocalRandom.current();
  }

}


text:
file(REMOVE_RECURSE
  "CMakeFiles/compile_Cwise_square.dir/compile_Cwise_square.cpp.o"
  "compile_Cwise_square.pdb"
  "compile_Cwise_square"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/compile_Cwise_square.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()


text:
<?php

declare(strict_types = 1);

use PHPUnit\Framework\TestCase;
use Sop\ASN1\Element;
use Sop\ASN1\Type\Constructed\Sequence;
use Sop\ASN1\Type\Primitive\BitString;
use Sop\ASN1\Type\Tagged\ImplicitlyTaggedType;
use Sop\CryptoTypes\AlgorithmIdentifier\Signature\SHA1WithRSAEncryptionAlgorithmIdentifier;
use Sop\X509\AttributeCertificate\AttCertIssuer;
use Sop\X509\AttributeCertificate\IssuerSerial;
use Sop\X509\AttributeCertificate\ObjectDigestInfo;
use Sop\X509\AttributeCertificate\V2Form;
use Sop\X509\GeneralName\DirectoryName;
use Sop\X509\GeneralName\GeneralNames;

/**
 * @group ac
 *
 * @internal
 */
class V2FormTest extends TestCase
{
    private static $_issuerName;

    public static function setUpBeforeClass(): void
    {
        self::$_issuerName = new GeneralNames(
            DirectoryName::fromDNString('cn=Test'));
    }

    public static function tearDownAfterClass(): void
    {
        self::$_issuerName = null;
    }

    public function testCreate()
    {
        $issuer = new V2Form(self::$_issuerName);
        $this->assertInstanceOf(AttCertIssuer::class, $issuer);
        return $issuer;
    }

    /**
     * @depends testCreate
     *
     * @param V2Form $issuer
     */
    public function testEncode(V2Form $issuer)
    {
        $el = $issuer->toASN1();
        $this->assertInstanceOf(ImplicitlyTaggedType::class, $el);
        return $el->toDER();
    }

    /**
     * @depends testEncode
     *
     * @param string $data
     */
    public function testDecode($data)
    {
        $issuer = V2Form::fromASN1(Element::fromDER($data)->asUnspecified());
        $this->assertInstanceOf(V2Form::class, $issuer);
        return $issuer;
    }

    /**
     * @depends testCreate
     * @depends testDecode
     *
     * @param V2Form $ref
     * @param V2Form $new
     */
    public function testRecoded(V2Form $ref, V2Form $new)
    {
        $this->assertEquals($ref, $new);
    }

    /**
     * @depends testCreate
     *
     * @param V2Form $issuer
     */
    public function testIssuerName(V2Form $issuer)
    {
        $this->assertEquals(self::$_issuerName, $issuer->issuerName());
    }

    public function testNoIssuerNameFail()
    {
        $issuer = new V2Form();
        $this->expectException(\LogicException::class);
        $issuer->issuerName();
    }

    /**
     * @depends testCreate
     *
     * @param V2Form $issuer
     */
    public function testName(V2Form $issuer)
    {
        $this->assertEquals('cn=Test', $issuer->name());
    }

    public function testDecodeWithAll()
    {
        $iss_ser = new IssuerSerial(self::$_issuerName, 1);
        $odi = new ObjectDigestInfo(ObjectDigestInfo::TYPE_PUBLIC_KEY,
            new SHA1WithRSAEncryptionAlgorithmIdentifier(), new BitString(''));
        $el = new ImplicitlyTaggedType(0,
            new Sequence(self::$_issuerName->toASN1(),
                new ImplicitlyTaggedType(0, $iss_ser->toASN1()),
                new ImplicitlyTaggedType(1, $odi->toASN1())));
        $issuer = V2Form::fromASN1($el->asUnspecified());
        $this->assertInstanceOf(V2Form::class, $issuer);
        return $issuer;
    }

    /**
     * @depends testDecodeWithAll
     *
     * @param V2Form $issuer
     */
    public function testEncodeWithAll(V2Form $issuer)
    {
        $el = $issuer->toASN1();
        $this->assertInstanceOf(ImplicitlyTaggedType::class, $el);
    }
}


text:
package net.qldarch.relationship;

import java.sql.Timestamp;

import lombok.Data;

@Data
public class TranscriptRelationship implements Comparable<TranscriptRelationship> {

  private Long id;

  private String relationship;

  private String note;

  private Integer from;

  private Integer until;

  private Long subject;

  private String subjectlabel;

  private String subjecttype;

  private boolean subjectarchitect;

  private Long object;

  private String objectlabel;

  private String objecttype;

  private boolean objectarchitect;

  private Long utterance;

  private Timestamp created;

  @Override
  public int compareTo(TranscriptRelationship tr1) {
    if((this.created != null) && (tr1.created != null)) {
      return this.created.compareTo(tr1.created);
    } else if((this.created == null) && (tr1.created == null)) {
      return 0;
    } else if((this.created == null)) {
      return -1;
    } else {
      return 1;
    }
  }

}


text:
template<typename T>
struct RemoveVolatile
{
   typedef T type;
};

template<typename T>
struct RemoveVolatile<volatile T>
{
   typedef T type;
};

//
// VolatileLoad loads a T from a pointer to T.  It is guaranteed that this load will not be optimized
// away by the compiler, and that any operation that occurs after this load, in program order, will
// not be moved before this load.  In general it is not guaranteed that the load will be atomic, though
// this is the case for most aligned scalar data types.  If you need atomic loads or stores, you need
// to consult the compiler and CPU manuals to find which circumstances allow atomicity.
//
// Starting at version 3.8, clang errors out on initializing of type int * to volatile int *. To fix this, we add two templates to cast away volatility
// Helper structures for casting away volatileness

template<typename T>
inline
T VolatileLoad(T const * pt)
{
    STATIC_CONTRACT_SUPPORTS_DAC_HOST_ONLY;

#ifndef DACCESS_COMPILE
#if defined(_ARM64_) && defined(__GNUC__)
    T val;
    static const unsigned lockFreeAtomicSizeMask = (1 << 1) | (1 << 2) | (1 << 4) | (1 << 8);
    if((1 << sizeof(T)) & lockFreeAtomicSizeMask)
    {
        __atomic_load((T const *)pt, const_cast<typename RemoveVolatile<T>::type *>(&val), __ATOMIC_ACQUIRE);
    }
    else
    {
        val = *(T volatile const *)pt;
        asm volatile ("dmb ishld" : : : "memory");
    }
#else
    T val = *(T volatile const *)pt;
    VOLATILE_MEMORY_BARRIER();
#endif
#else
    T val = *pt;
#endif
    return val;
}

template<typename T>
inline
T VolatileLoadWithoutBarrier(T const * pt)
{
    STATIC_CONTRACT_SUPPORTS_DAC_HOST_ONLY;

#ifndef DACCESS_COMPILE
    T val = *(T volatile const *)pt;
#else
    T val = *pt;
#endif
    return val;
}

template <typename T> class Volatile;

template<typename T>
inline
T VolatileLoad(Volatile<T> const * pt)
{
    STATIC_CONTRACT_SUPPORTS_DAC;
    return pt->Load();
}

//
// VolatileStore stores a T into the target of a pointer to T.  Is is guaranteed that this store will
// not be optimized away by the compiler, and that any operation that occurs before this store, in program
// order, will not be moved after this store.  In general, it is not guaranteed that the store will be
// atomic, though this is the case for most aligned scalar data types.  If you need atomic loads or stores,
// you need to consult the compiler and CPU manuals to find which circumstances allow atomicity.
//
template<typename T>
inline
void VolatileStore(T* pt, T val)
{
    STATIC_CONTRACT_SUPPORTS_DAC_HOST_ONLY;

#ifndef DACCESS_COMPILE
#if defined(_ARM64_) && defined(__GNUC__)
    static const unsigned lockFreeAtomicSizeMask = (1 << 1) | (1 << 2) | (1 << 4) | (1 << 8);
    if((1 << sizeof(T)) & lockFreeAtomicSizeMask)
    {
        __atomic_store((T volatile *)pt, &val, __ATOMIC_RELEASE);
    }
    else
    {
        VOLATILE_MEMORY_BARRIER();
        *(T volatile *)pt = val;
    }
#else
    VOLATILE_MEMORY_BARRIER();
    *(T volatile *)pt = val;
#endif
#else
    *pt = val;
#endif
}

template<typename T>
inline
void VolatileStoreWithoutBarrier(T* pt, T val)
{
    STATIC_CONTRACT_SUPPORTS_DAC_HOST_ONLY;

#ifndef DACCESS_COMPILE
    *(T volatile *)pt = val;
#else
    *pt = val;
#endif
}

//
// Volatile<T> implements accesses with our volatile semantics over a variable of type T.
// Wherever you would have used a "volatile Foo" or, equivalently, "Foo volatile", use Volatile<Foo>
// instead.  If Foo is a pointer type, use VolatilePtr.
//
// Note that there are still some things that don't work with a Volatile<T>,
// that would have worked with a "volatile T".  For example, you can't cast a Volatile<int> to a float.
// You must instead cast to an int, then to a float.  Or you can call Load on the Volatile<int>, and
// cast the result to a float.  In general, calling Load or Store explicitly will work around
// any problems that can't be solved by operator overloading.
//
// @TODO: it's not clear that we actually *want* any operator overloading here.  It's in here primarily
// to ease the task of converting all of the old uses of the volatile keyword, but in the long
// run it's probably better if users of this class are forced to call Load() and Store() explicitly.
// This would make it much more clear where the memory barriers are, and which operations are actually
// being performed, but it will have to wait for another cleanup effort.
//
template <typename T>
class Volatile
{
private:
    //
    // The data which we are treating as volatile
    //
    T m_val;

public:
    //
    // Default constructor.  Results in an unitialized value!
    //
    inline Volatile()
    {
        STATIC_CONTRACT_SUPPORTS_DAC;
    }

    //
    // Allow initialization of Volatile<T> from a T
    //
    inline Volatile(const T& val)
    {
        STATIC_CONTRACT_SUPPORTS_DAC;
        ((volatile T &)m_val) = val;
    }

    //
    // Copy constructor
    //
    inline Volatile(const Volatile<T>& other)
    {
        STATIC_CONTRACT_SUPPORTS_DAC;
        ((volatile T &)m_val) = other.Load();
    }

    //
    // Loads the value of the volatile variable.  See code:VolatileLoad for the semantics of this operation.
    //
    inline T Load() const
    {
        STATIC_CONTRACT_SUPPORTS_DAC;
        return VolatileLoad(&m_val);
    }

    //
    // Loads the value of the volatile variable atomically without erecting the memory barrier.
    //
    inline T LoadWithoutBarrier() const
    {
        STATIC_CONTRACT_SUPPORTS_DAC;
        return ((volatile T &)m_val);
    }

    //
    // Stores a new value to the volatile variable.  See code:VolatileStore for the semantics of this
    // operation.
    //
    inline void Store(const T& val)
    {
        STATIC_CONTRACT_SUPPORTS_DAC;
        VolatileStore(&m_val, val);
    }

    //
    // Stores a new value to the volatile variable atomically without erecting the memory barrier.
    //
    inline void StoreWithoutBarrier(const T& val) const
    {
        STATIC_CONTRACT_SUPPORTS_DAC;
        ((volatile T &)m_val) = val;
    }

    //
    // Gets a pointer to the volatile variable.  This is dangerous, as it permits the variable to be
    // accessed without using Load and Store, but it is necessary for passing Volatile<T> to APIs like
    // InterlockedIncrement.
    //
    inline volatile T* GetPointer() { return (volatile T*)&m_val; }

    //
    // Gets the raw value of the variable.  This is dangerous, as it permits the variable to be
    // accessed without using Load and Store
    //
    inline T& RawValue() { return m_val; }

    //
    // Allow casts from Volatile<T> to T.  Note that this allows implicit casts, so you can
    // pass a Volatile<T> directly to a method that expects a T.
    //
    inline operator T() const
    {
        STATIC_CONTRACT_SUPPORTS_DAC;
        return this->Load();
    }

    //
    // Assignment from T
    //
    inline Volatile<T>& operator=(T val) {Store(val); return *this;}

    //
    // Get the address of the volatile variable.  This is dangerous, as it allows the value of the
    // volatile variable to be accessed directly, without going through Load and Store, but it is
    // necessary for passing Volatile<T> to APIs like InterlockedIncrement.  Note that we are returning
    // a pointer to a volatile T here, so we cannot accidentally pass this pointer to an API that
    // expects a normal pointer.
    //
    inline T volatile * operator&() {return this->GetPointer();}
    inline T volatile const * operator&() const {return this->GetPointer();}

    //
    // Comparison operators
    //
    template<typename TOther>
    inline bool operator==(const TOther& other) const {return this->Load() == other;}

    template<typename TOther>
    inline bool operator!=(const TOther& other) const {return this->Load() != other;}

    //
    // Miscellaneous operators.  Add more as necessary.
    //
	inline Volatile<T>& operator+=(T val) {Store(this->Load() + val); return *this;}
	inline Volatile<T>& operator-=(T val) {Store(this->Load() - val); return *this;}
    inline Volatile<T>& operator|=(T val) {Store(this->Load() | val); return *this;}
    inline Volatile<T>& operator&=(T val) {Store(this->Load() & val); return *this;}
    inline bool operator!() const { STATIC_CONTRACT_SUPPORTS_DAC; return !this->Load();}

    //
    // Prefix increment
    //
    inline Volatile& operator++() {this->Store(this->Load()+1); return *this;}

    //
    // Postfix increment
    //
    inline T operator++(int) {T val = this->Load(); this->Store(val+1); return val;}

    //
    // Prefix decrement
    //
    inline Volatile& operator--() {this->Store(this->Load()-1); return *this;}

    //
    // Postfix decrement
    //
    inline T operator--(int) {T val = this->Load(); this->Store(val-1); return val;}
};

//
// A VolatilePtr builds on Volatile<T> by adding operators appropriate to pointers.
// Wherever you would have used "Foo * volatile", use "VolatilePtr<Foo>" instead.
//
// VolatilePtr also allows the substution of other types for the underlying pointer.  This
// allows you to wrap a VolatilePtr around a custom type that looks like a pointer.  For example,
// if what you want is a "volatile DPTR<Foo>", use "VolatilePtr<Foo, DPTR<Foo>>".
//
template <typename T, typename P = T*>
class VolatilePtr : public Volatile<P>
{
public:
    //
    // Default constructor.  Results in an uninitialized pointer!
    //
    inline VolatilePtr()
    {
        STATIC_CONTRACT_SUPPORTS_DAC;
    }

    //
    // Allow assignment from the pointer type.
    //
    inline VolatilePtr(P val) : Volatile<P>(val)
    {
        STATIC_CONTRACT_SUPPORTS_DAC;
    }

    //
    // Copy constructor
    //
    inline VolatilePtr(const VolatilePtr& other) : Volatile<P>(other)
    {
        STATIC_CONTRACT_SUPPORTS_DAC;
    }

    //
    // Cast to the pointer type
    //
    inline operator P() const
    {
        STATIC_CONTRACT_SUPPORTS_DAC;
        return (P)this->Load();
    }

    //
    // Member access
    //
    inline P operator->() const
    {
        STATIC_CONTRACT_SUPPORTS_DAC;
        return (P)this->Load();
    }

    //
    // Dereference the pointer
    //
    inline T& operator*() const
    {
        STATIC_CONTRACT_SUPPORTS_DAC;
        return *(P)this->Load();
    }

    //
    // Access the pointer as an array
    //
    template <typename TIndex>
    inline T& operator[](TIndex index)
    {
        STATIC_CONTRACT_SUPPORTS_DAC;
        return ((P)this->Load())[index];
    }
};

//
// Warning: workaround
//
// At the bottom of this file, we are going to #define the "volatile" keyword such that it is illegal
// to use it.  Unfortunately, VC++ uses the volatile keyword in stddef.h, in the definition of "offsetof".
// GCC does not use volatile in its definition.
//
// To get around this, we include stddef.h here (even if we're on GCC, for consistency).  We then need
// to redefine offsetof such that it does not use volatile, if we're building with VC++.
//
#include <stddef.h>
#ifdef _MSC_VER
#undef offsetof
#ifdef  _WIN64
#define offsetof(s,m)   (size_t)( (ptrdiff_t)&reinterpret_cast<const char&>((((s *)0)->m)) )
#else
#define offsetof(s,m)   (size_t)&reinterpret_cast<const char&>((((s *)0)->m))
#endif //_WIN64

// These also use volatile, so we'll include them here.
//#include <intrin.h>
//#include <memory>

#endif //_MSC_VER

//
// From here on out, we ban the use of the "volatile" keyword.  If you found this while trying to define
// a volatile variable, go to the top of this file and start reading.
//
#ifdef volatile
#undef volatile
#endif
// ***** Temporarily removing this to unblock integration with new VC++ bits
//#define volatile (DoNotUseVolatileKeyword) volatile

// The substitution for volatile above is defined in such a way that we can still explicitly access the
// volatile keyword without error using the macros below. Use with care.
//#define REMOVE_DONOTUSE_ERROR(x)
//#define RAW_KEYWORD(x) REMOVE_DONOTUSE_ERROR x
#define RAW_KEYWORD(x) x

#ifdef DACCESS_COMPILE
// No need to use volatile in DAC builds - DAC is single-threaded and the target
// process is suspended.
#define VOLATILE(T) T
#else

// Disable use of Volatile<T> for GC/HandleTable code except on platforms where it's absolutely necessary.
#if defined(_MSC_VER) && !defined(_ARM_) && !defined(_ARM64_)
#define VOLATILE(T) T RAW_KEYWORD(volatile)
#else
#define VOLATILE(T) Volatile<T>
#endif

#endif // DACCESS_COMPILE

// VolatilePtr-specific clr::SafeAddRef and clr::SafeRelease
namespace clr
{
    template < typename ItfT, typename PtrT > inline
    #ifdef __checkReturn // Volatile.h is used in corunix headers, which don't define/nullify SAL.
        __checkReturn
    #endif
    VolatilePtr<ItfT, PtrT>&
    SafeAddRef(VolatilePtr<ItfT, PtrT>& pItf)
    {
        STATIC_CONTRACT_LIMITED_METHOD;
        SafeAddRef(pItf.Load());
        return pItf;
    }

    template < typename ItfT, typename PtrT > inline
    ULONG
    SafeRelease(VolatilePtr<ItfT, PtrT>& pItf)
    {
        STATIC_CONTRACT_LIMITED_METHOD;
        return SafeRelease(pItf.Load());
    }
}

#endif //_VOLATILE_H_


text:
define([

  'backbone',
  'App.config',
  'App.models.Candidate'

], function(Backbone, config, CandidateModel) {

  'use strict';

  return Backbone.Collection.extend({

    model : CandidateModel,
    url   : config.data.candidates

  });
});


text:
        <title>Validating form fields using CodeIgniter</title>

        <?php echo form_open('login/submit_login_form'); ?>

Validating form fields using CodeIgniter

        <?php echo form_label('User Name :'); ?>

        <?php echo form_input(array('id' => 'user_name', 'name' => 'user_name')); ?>

        <?php echo form_label('User Password :'); ?>

        <?php echo form_input(array('id' => 'user_password', 'name' => 'user_password')); ?>

        <?php echo form_submit(array('id' => 'submit', 'name' => 'submit', 'value' => 'Submit')); ?>

        <?php echo form_close(); ?>


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

    <groupId>j-key-pass</groupId>
    <artifactId>j-key-pass</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>com.dropbox.core</groupId>
            <artifactId>dropbox-core-sdk</artifactId>
            <version>[1.7,1.8)</version>
        </dependency>
    </dependencies>

</project>


text:
"""Auto-generated file, do not edit by hand. SH metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata

PHONE_METADATA_SH = PhoneMetadata(id='SH', country_code=None, international_prefix=None,
    general_desc=PhoneNumberDesc(national_number_pattern='[19]\\d{2,3}', possible_number_pattern='\\d{3,4}', possible_length=(3, 4)),
    toll_free=PhoneNumberDesc(),
    premium_rate=PhoneNumberDesc(),
    emergency=PhoneNumberDesc(national_number_pattern='9(?:11|99)', possible_number_pattern='\\d{3}', example_number='999', possible_length=(3,)),
    short_code=PhoneNumberDesc(national_number_pattern='1\\d{2,3}|9(?:11|99)', possible_number_pattern='\\d{3,4}', example_number='1234', possible_length=(3, 4)),
    standard_rate=PhoneNumberDesc(),
    carrier_specific=PhoneNumberDesc(),
    short_data=True)


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

<title>ModelAttribute (Spring Framework 4.3.3.RELEASE API)</title>
<meta name="date" content="2016-09-19">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Spring Framework

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Field |

Required |

Optional

Detail:

Field |

Element

org.springframework.web.bind.annotation

Annotation Type ModelAttribute

@Target(value={PARAMETER,METHOD})
 @Retention(value=RUNTIME)
 @Documented
public @interface ModelAttribute

Annotation that binds a method parameter or method return value
 to a named model attribute, exposed to a web view. Supported
 for controller classes with @RequestMapping
 methods.

Can be used to expose command objects to a web view, using
 specific attribute names, through annotating corresponding
 parameters of an @RequestMapping method.

Can also be used to expose reference data to a web view
 through annotating accessor methods in a controller class with
 @RequestMapping methods. Such accessor
 methods are allowed to have any arguments that
 @RequestMapping methods support, returning
 the model attribute value to expose.

Note however that reference data and all other model content is
 not available to web views when request processing results in an
 Exception since the exception could be raised at any time
 making the content of the model unreliable. For this reason
 @ExceptionHandler methods do not provide
 access to a Model argument.

Since:

2.5

Author:

Juergen Hoeller, Rossen Stoyanchev

Optional Element Summary

Optional Elements

Modifier and Type
Optional Element and Description

boolean
binding

Allows declaring data binding disabled directly on an @ModelAttribute
 method parameter or on the attribute returned from an @ModelAttribute
 method, both of which would prevent data binding for that attribute.

String
name

The name of the model attribute to bind to.

String
value

Alias for name().

Element Detail

value

@AliasFor(value="name")
public abstract String value

Alias for name().

Default:

""

name

@AliasFor(value="value")
public abstract String name

The name of the model attribute to bind to.

The default model attribute name is inferred from the declared
 attribute type (i.e. the method parameter type or method return type),
 based on the non-qualified class name:
 e.g. "orderAddress" for class "mypackage.OrderAddress",
 or "orderAddressList" for "List<mypackage.OrderAddress>".

Since:

4.3

Default:

""

binding

public abstract boolean binding

Allows declaring data binding disabled directly on an @ModelAttribute
 method parameter or on the attribute returned from an @ModelAttribute
 method, both of which would prevent data binding for that attribute.

By default this is set to true in which case data binding applies.
 Set this to false to disable data binding.

Since:

4.3

Default:

true

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Spring Framework

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Field |

Required |

Optional

Detail:

Field |

Element


text:
Pile::Pile()
{

}

QString Pile::name() const
{
    auto resources = component<InventoryComponent>();
	if(!resources)
		return "pile";
	if(resources->isEmpty())
		return "pile";//should not happen though
    QMap<QString, int> content = resources->resourceContent();
	QList<QString> keys = content.keys();
	qSort(keys);
	if(keys.count() == 1)
	{
		int count = content[keys[0]];
		if(count == 1)
		{
			auto resource = world::resource(keys[0]);
			if(resource)
				// a single resource piece
				return resource->pieceSingular();
		}
	}

	//otherwise we just enumerate resources
	//a pile of wooden logs
	//a pile of malachite
	//a pile of wooden logs, sugar, coal and tree branches
	QStringList resourceNames;
	for(QString key : keys)
	{
		auto resource = world::resource(key);
		if(resource)
			resourceNames.append(resource->namePlural());
	}
	QString list = Utils::listFragments(resourceNames);
	return "pile of " + list;
}

void Pile::put(const QString &aResource, int aAmount)
{
    auto resources = component<InventoryComponent>();
	if(resources)
        resources->putResource(aResource, aAmount);
}

void Pile::remove(const QString &aResource, int aAmount)
{
    auto resources = component<InventoryComponent>();
	if(resources)
		resources->remove(aResource, aAmount);
}

int Pile::amount(const QString &aResource) const
{
    auto resources = component<InventoryComponent>();
	if(resources)
		return resources->amount(aResource);
	return 0;
}

bool Pile::isEmpty() const
{
    auto resources = component<InventoryComponent>();
	if(resources)
		return resources->isEmpty();
	return true;
}

QString Pile::roomDescription() const
{
	QString description = Utils::prependAArticle(name() + " is here.");
	return Utils::capitalizeText(description);
}

QString Pile::getFirstSentenceOfDescription()
{
	return "This is a storage location for bulk materials.";
}

void Pile::printListItem(Client &aClient, const Person &) const
{
	//should something to be highlighted?
    aClient.sendFormattedText(name(), "", "look " + QString::number(uid_));
}

QString Pile::listItemText(const Person &) const
{
	return name();
}


text:
namespace AssetPackage
{
    using System;

    /// <summary>
    /// Interface for data storage.
    /// </summary>
    public interface IDataStorage
    {
        #region Methods

        /// <summary>
        /// Deletes the given fileId.
        /// </summary>
        ///
        /// <param name="fileId"> The file identifier to delete. </param>
        ///
        /// <returns>
        /// true if it succeeds, false if it fails.
        /// </returns>
        Boolean Delete(String fileId);

        /// <summary>
        /// Check if exists the file with the given identifier.
        /// </summary>
        ///
        /// <param name="fileId"> The file identifier to delete. </param>
        ///
        /// <returns>
        /// true if it succeeds, false if it fails.
        /// </returns>
        Boolean Exists(String fileId);

        /// <summary>
        /// Gets the files.
        /// </summary>
        ///
        /// <remarks>
        /// A List<String> gave problems when compiled as PCL and added to a
        /// Xamarin Forms project containing iOS, Android and WinPhone subprojects.
        /// </remarks>
        ///
        /// <returns>
        /// An array of filenames.
        /// </returns>
        String[] Files();

        /// <summary>
        /// Loads the given file.
        /// </summary>
        ///
        /// <param name="fileId"> The file identifier to load. </param>
        ///
        /// <returns>
        /// A String with with the file contents.
        /// </returns>
        String Load(String fileId);

        /// <summary>
        /// Saves the given file.
        /// </summary>
        ///
        /// <param name="fileId">   The file identifier to delete. </param>
        /// <param name="fileData"> Information describing the file. </param>
        void Save(String fileId, String fileData);

        #endregion Methods
    }
}


text:
<?php namespace Fisharebest\Localization\Territory;

class TerritoryMa extends AbstractTerritory implements TerritoryInterface {
	public function code() {
		return 'MA';
	}

	public function firstDay() {
		return 6;
	}

	public function weekendStart() {
		return 5;
	}

	public function weekendEnd() {
		return 6;
	}
}


text:
import React from 'react';
import { storiesOf } from '@storybook/react';
import { text, boolean } from '@storybook/addon-knobs';
import InputField from './';

const errorMeta = { touched: true, error: 'This Field has an error' };
const warningMeta = { touched: true, warning: 'This Field has an warning' };

storiesOf('InputField', module)
    .add('default', () => (
        <InputField type="text" label="InputField Example" />
    ))
    .add('with error', () => (
        <InputField type="text" label="InputField Example" meta={errorMeta} />
    ))
    .add('with warning', () => (
        <InputField type="text" label="InputField Example" meta={warningMeta} />
    ))
    .add('with props', () => (
        <InputField
            type={text('type', 'text')}
            label={text('label', 'InputField')}
            required={boolean('required', false)}
        />
    ));


text:
@echo off
REM SetNFRoot - Find/Create and return short path for current directory
REM DAV 01APR19
setlocal

if %1.==. goto :set_path

:check_opts
if /I %1==-h  goto :help
if /I %1==-d set rmsubst=-d

:set_path
set _mypath=%~dp0
call :setshortpath %_mypath%
rem pushd %shortpath%
if [%rmsubst%]==[-d] goto :remsubst
goto :end

:remsubst
set v=%shortpath:~0,2%
echo Remove subst of %mypath% on %v%
if [%rmsubst%]==[-d] subst /D %v%
endlocal & set "nfRoot=%_mypath%"
setx nfRoot %nfRoot% >nul
echo %nfRoot%
goto :eof

:end
:: Clear %errorlevel%
call set _a=a > nul
endlocal & set "nfRoot=%shortpath%"
setx nfRoot %nfRoot% >nul
echo %nfRoot%
rem  popd
::exit
goto :eof

:: ============ Utility commands =====

:: === Help
:help
echo:
echo Usage: %0 [opt]
echo:
echo opt = -d    Delete subst if exists
echo opt = -h    Display this help message
echo:
echo Command line tool to find or create a short directory path
echo for the current directory using the subst command
echo:
goto :eof

REM  ==========================================================
REM Utility Functions
REM
REM Call to set a short path to try avoid overflowing 250 char file path limit
:setshortpath
set "mypath=%~1"
set shortpath=%mypath%
rem echo mypath = %_mypath%

REM Are we already on short path?
set t=%mypath:~0,3%
if /I %t%==%mypath% goto :haveshortpath

REM Not on short path -  is there already a subst for it?
FOR /F "tokens=1,3" %%G IN ('subst') DO (
	if /I "%%H\"=="%mypath%" (
		set sdg=%%G
		goto :foundsubst
	)
)
REM No subst short path found - create one
call :freedrive driveletter && goto :cont
echo ERROR: No free drive letter found, staying on original path
goto :haveshortpath

:cont
echo Found free drive letter: %driveletter% 1>&2
pushd %mypath%
subst %driveletter% .
popd
set shortpath=%driveletter%\
echo Created new  subst for %mypath% on %driveletter% 1>&2
echo You can remove it with subst %driveletter% /D 1>&2
goto :haveshortpath

:foundsubst
set shortpath=%sdg:~0,3%
echo Using existing subst for %mypath% on %shortpath% 1>&2
goto :haveshortpath

:haveshortpath
echo Using short path %shortpath% for %mypath% 1>&2
REM So now we have a short path if it was possible
goto :eof

rem Finds a free drive letter.
rem
rem Parameters:
rem     %1 = Output variable name.
rem
rem Example:
rem     call :freedrive mydriveletter && goto :cont
rem     echo ERROR: No free drive letter found.
rem     goto :EOF
rem     :cont
rem     echo Found drive letter: %mydriveletter%
:freedrive
setlocal EnableDelayedExpansion
set exitcode=0
set "output_var=%~1"
for %%i in (B,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z) do (
    set "drive=%%i:"
    rem If 'subst' fails, the drive letter is already in use.
    rem This way we can even detect optical drives that have a drive
    rem letter but no media in them, a case that goes undetected when
    rem using 'if exist'.
	subst !drive! %SystemDrive%\ >nul
    if !errorlevel! == 0 (
        subst !drive! /d >nul
        goto :freedrive0
    )
)
set exitcode=1
set drive=
:freedrive0
endlocal & set "%output_var%=%drive%" & exit /b %exitcode%

:exit

:eof


text:
"use strict";

require("core-js/modules/es.object.to-string");

require("core-js/modules/es.regexp.to-string");

Handlers.watch_reload();

function incr() {
  var node = id("the_count");
  var new_total = parseInt(node.innerText) + 1;
  update_text(node, new_total.toString());
  console.log("Updated.");
  body(para(a_href("http://www.lewrockwell.com", "New: ", new Date().getSeconds().toString())));
  Handlers.run("incr", {
    amount: 1
  });
  return null;
} // func

Handlers.add("on page load", function () {
  body(para({
    id: "init_p"
  }, span("Page has loaded.")));
});
Handlers.add("on page load", function set_button_incr() {
  id("incr_btn").onclick = incr;
});
Handlers.add("incr", function (data) {
  body(div({
    'class': 'skyblue'
  }, "Number increased by: " + data.amount));
});
Handlers.run("on page load");


text:
class Harbor::File::Checksum

  class FileNotFoundError < StandardError
    def initialize(path)
      super("File Not Found @ #{path}, cannot compute checksum")
    end
  end

  def self.generators
    @generators ||= Harbor::Container.new
  end

  def self.register(algorithm, generator_class, &block)
    generators.set("#{algorithm}_checksum_generator", generator_class, &block)
  end

  def initialize(algorithm, file)
    @algorithm = algorithm
    @file = file
  end

  def hex
    raise FileNotFoundError unless File.file?(@file.path)

    @generator ||= self.class.generators.get("#{@algorithm}_checksum_generator")
    @generator.compute(@file.path.to_s)
  end

  alias :to_s :hex

  def to_i
    hex.to_i(16)
  end

  def inspect
    "#<#{self.class}: \"#{to_s}\">"
  end

end

require "harbor/checksum/zlib"


text:
@(resetForm: Form[controllers.account.Reset.ResetForm], token: String)

@import helper._
@implicitFieldConstructor = @{
FieldConstructor(twitterBootstrapInput.render)
}

@scripts = {

    }

@main(null, scripts) {

@Messages("signup.reset.password")

    @wflash()

        @Messages("resetpassword.new.password")

        @form(controllers.account.routes.Reset.runReset(token)) {

                @inputPassword(
                    resetForm("inputPassword"),
                    'placeholder -> Messages("password"),
                    '_label -> null,
                    'class -> "form-control"
                )

@Messages("signup.generate.password")

                <input type="text" name="passwordGenerated" class="form-control">

            <input type="submit" class="btn btn-primary" value="@Messages("validate")">
            @Messages("goback")

        }

}


text:
from handlers.page import PageAnalytic
from page import Page

page = Page()
page.url = "http://globoesporte.globo.com"
pg = PageAnalytic(page.url)
page.length = pg.get_page_size()

print (page.length)


text:
namespace pythonic
{
  namespace numpy
  {
    namespace linalg
    {
      template <class Array>
      auto norm(Array &&array, types::none_type ord, types::none_type axis)
          -> decltype(pythonic::numpy::proxy::sqrt{}(
              pythonic::numpy::proxy::sum{}(pythonic::numpy::proxy::square{}(
                  pythonic::numpy::proxy::abs{}(
                      pythonic::numpy::proxy::asfarray{}(
                          std::forward<Array>(array)))))))
      {
        return pythonic::numpy::proxy::sqrt{}(pythonic::numpy::proxy::sum{}(
            pythonic::numpy::proxy::square{}(pythonic::numpy::proxy::abs{}(
                pythonic::numpy::proxy::asfarray{}(
                    std::forward<Array>(array))))));
      }

      template <class Array>
      norm_t<Array> norm(Array &&x, double ord, types::none_type)
      {
        switch (std::decay<Array>::type::value) {
        case 1:
          return norm(std::forward<Array>(x), ord, 0L);
        case 2:
          return norm(std::forward<Array>(x), ord,
                      types::array<long, 2>{{0L, 1L}});
        default:
          throw pythonic::__builtin__::NotImplementedError(
              "Invalid norm order for matrices.");
        }
      }

      template <class Array>
      norm_t<Array> norm(Array &&x, double ord, long axis)
      {
        auto &&y = pythonic::numpy::proxy::asfarray{}(x);
        if (ord == inf)
          return pythonic::numpy::proxy::max{}(pythonic::numpy::proxy::abs{}(y),
                                               axis);
        else if (ord == -inf)
          return pythonic::numpy::proxy::min{}(pythonic::numpy::proxy::abs{}(y),
                                               axis);
        else if (ord == 0.)
          return pythonic::numpy::proxy::sum{}(y != 0., axis);
        else if (ord == 1.)
          return pythonic::numpy::proxy::sum{}(pythonic::numpy::proxy::abs{}(y),
                                               axis);
        else if (ord == 2.)
          return pythonic::numpy::proxy::sqrt{}(pythonic::numpy::proxy::sum{}(
              pythonic::numpy::proxy::real{}(
                  pythonic::numpy::proxy::conj{}(y)*y),
              axis));
        else {
          return pythonic::numpy::proxy::power{}(
              pythonic::numpy::proxy::sum{}(
                  pythonic::numpy::proxy::power{}(
                      pythonic::numpy::proxy::abs{}(y), ord),
                  axis),
              1. / ord);
        }
      }
      template <class Array>
      norm_t<Array> norm(Array &&x, types::none_type ord, double axis)
      {
        return norm(std::forward<Array>(x), 2., axis);
      }
      template <class Array>
      norm_t<Array> norm(Array &&x, double ord, types::array<long, 1> axis)
      {
        return norm(std::forward<Array>(x), ord, axis[0]);
      }
      template <class Array>
      norm_t<Array> norm(Array &&array, double ord, types::array<long, 2> axis)
      {
        throw pythonic::__builtin__::NotImplementedError("We need more dev!");
      }

      PROXY_IMPL(pythonic::numpy::linalg, norm);
    }
  }
}

#endif


text:
package dregex.impl

case class UnicodeChar(codePoint: Int) extends Ordered[UnicodeChar] {

  if (!Character.isValidCodePoint(codePoint)) {
    throw new IllegalArgumentException(s"Illegal code point: $codePoint")
  }

  def compare(that: UnicodeChar): Int = this.codePoint compare that.codePoint

  /**
    * Only for debugging
    */
  override def toString() = {
    if (Character.isLetterOrDigit(codePoint))
      s"'${new String(Character.toChars(codePoint))}'"
    else
      f"$codePoint%X₁₆"
  }

  def +(that: Int): UnicodeChar = UnicodeChar(codePoint + that)
  def -(that: Int): UnicodeChar = UnicodeChar(codePoint - that)

  def toRegex = {
    if (Character.isLetterOrDigit(codePoint))
      new String(Character.toChars(codePoint))
    else
      f"\\x{$codePoint%X}"
  }

  def toJavaString = new String(Character.toChars(codePoint))

}

object UnicodeChar {

  def fromChar(char: Char) = {
    UnicodeChar(char)
  }

  def fromSingletonString(str: String) = {
    if (Character.codePointCount(str, 0, str.size) > 1)
      throw new IllegalAccessException("String is no char: " + str)
    UnicodeChar(Character.codePointAt(str, 0))
  }

  val min = UnicodeChar(Character.MIN_CODE_POINT)
  val max = UnicodeChar(Character.MAX_CODE_POINT)

  implicit class FromCharConversion(val char: Char) extends AnyVal {
    def u = UnicodeChar.fromChar(char)
  }

  implicit class FromIntConversion(val int: Int) extends AnyVal {
    def u = UnicodeChar(int)
  }

}


text:
Ext.Loader.setConfig({
  enabled: true,
  paths: {'Cs': 'src'},
  disableCaching: false
});

Ext.require(['Cs.file.data.FileManager',
             'Ext.container.Container',
             'Cs.file.ui.UglyFileUploader'
            ]);

Ext.onReady(function() {
  var mgr = Ext.create('Cs.file.data.FileManager');

  Ext.create('Ext.container.Container', {
    renderTo: Ext.getBody(),
    layout: {type: 'vbox', align: 'stretch' },
    width: 300,
    height: 300,
    style: { background: "#eee" },
    items: [{
      xtype: 'uglyfileuploader',
      mgr: mgr,
      width: 300,
      height: 100,
      layout: Ext.create('Ext.layout.container.VBox', {align: 'stretch'})
    }]
  });
});