text:
import React, { Component } from 'react';
import shouldPureComponentUpdate from 'react-pure-render/function';
import { connect } from 'react-redux';
import immutableChildrenToJS from 'binary-utils/lib/immutableChildrenToJS';

import FullTradeCard from './FullTradeCard';
import singleTradeSelectors from '../trades/singleTradeSelectors';

@connect(singleTradeSelectors)
export default class FullTradeContainer extends Component {

	shouldComponentUpdate = shouldPureComponentUpdate;

	render() {
		return (
			<FullTradeCard
				index={0}
                {...immutableChildrenToJS(this.props)}
			/>
		);
	}
}


text:
import React, { PropTypes } from 'react'

import Base from '../Base'

const propTypes = {
  children: PropTypes.node,
  className: PropTypes.string
}

export default function Frame(props) {
  return <Base type='grid-frame' {...props} />
}

Frame.propTypes = propTypes

redpajama_set_name: RedPajamaGithub


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

<TITLE>
A-Index
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A B C D E F G O P Q R T U V

A

addCacheToDataURL(String) -
Static method in class com.fusioncharts.FusionChartsHelper

Adds additional string to the url to and encodes the parameters,

 so as to disable caching of data.

addParameterValue(String, String) -
Method in class com.fusioncharts.helper.FCParameters

Adds the parameter key-value pair given to the already existing params
 HashMap.

addParameterValues(HashMap<String, String>) -
Method in class com.fusioncharts.helper.FCParameters

Adds the parameter values given in the HashMap to the already existing
 params HashMap.

arr_FCColors -
Variable in class com.fusioncharts.FusionChartsHelper

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A B C D E F G O P Q R T U V


text:
#ifndef _BENCODE_H_
#define _BENCODE_H_
// #define DEBUG

typedef enum {
  B_INTEGER = 1,
  B_STRING,
  B_LIST,
  B_DICT
} b_type;

typedef long long b_size;
struct b_encode;

typedef struct b_list{
  struct b_encode* item;
  struct b_list* next;
} b_list;

typedef struct b_dict{
  char* key;
  struct b_encode* value;
  struct b_dict* next;
} b_dict;

typedef struct b_encode{
  b_type type;
  char* begin;
  unsigned int len;
  union {
    b_size iv;
    char* cpv;
    b_list* lpv;
    b_dict* dpv;
  } data;
} b_encode;

b_encode* b_encode_init(const char* file_name);
b_encode* b_encode_init_with_string (const char* string, long len);
void b_encode_print(b_encode* bp);
void b_encode_free(b_encode* bp);

#endif /* end of include guard: _BENCODE_H_ */


text:
{{totalAccepted[_selectedOrderLineIndex]}} {{line.requiredItemLocationQuantity.price.baseQuantity.unitCode}}

 0 ? 'col-3' : 'col-6'}} borderless">

{{totalRejected[_selectedOrderLineIndex]}} {{line.requiredItemLocationQuantity.price.baseQuantity.unitCode}}

 0" class="card col-3 borderless">

{{totalWaitingResponse[_selectedOrderLineIndex]}} {{line.requiredItemLocationQuantity.price.baseQuantity.unitCode}}

{{totalToBeShipped[_selectedOrderLineIndex]}} {{line.requiredItemLocationQuantity.price.baseQuantity.unitCode}}

<ng-container *ngIf="line && !isLoading()">
    <dispatch-advice *ngIf="!showReceiptAdvice()" [waitingQuantityValues]="totalToBeShipped" [orderLineItemHjids]="orderLineItemHjids">
    </dispatch-advice>
    <receipt-advice *ngIf="showReceiptAdvice()">
    </receipt-advice>
</ng-container>


text:
package servenv

import (
	"flag"
	"net/url"
	"os"
	"runtime"
	"sync"
	"syscall"
	"time"

	// register the HTTP handlers for profiling
	_ "net/http/pprof"

	log "github.com/golang/glog"
	"github.com/youtube/vitess/go/event"
	"github.com/youtube/vitess/go/netutil"
	"github.com/youtube/vitess/go/stats"

	// register the proper init and shutdown hooks for logging
	_ "github.com/youtube/vitess/go/vt/logutil"
)

var (
	// Port is part of the flags used when calling RegisterDefaultFlags.
	Port *int

	// Flags to alter the behavior of the library.
	lameduckPeriod = flag.Duration("lameduck-period", 50*time.Millisecond, "keep running at least this long after SIGTERM before stopping")
	onTermTimeout  = flag.Duration("onterm_timeout", 10*time.Second, "wait no more than this for OnTermSync handlers before stopping")
	memProfileRate = flag.Int("mem-profile-rate", 512*1024, "profile every n bytes allocated")

	// mutex used to protect the Init function
	mu sync.Mutex

	onInitHooks     event.Hooks
	onTermHooks     event.Hooks
	onTermSyncHooks event.Hooks
	onRunHooks      event.Hooks
	inited          bool

	// ListeningURL is filled in when calling Run, contains the server URL.
	ListeningURL url.URL
)

// Init is the first phase of the server startup.
func Init() {
	mu.Lock()
	defer mu.Unlock()
	if inited {
		log.Fatal("servenv.Init called second time")
	}
	inited = true

	// Once you run as root, you pretty much destroy the chances of a
	// non-privileged user starting the program correctly.
	if uid := os.Getuid(); uid == 0 {
		log.Fatalf("servenv.Init: running this as root makes no sense")
	}

	runtime.MemProfileRate = *memProfileRate

	// We used to set this limit directly, but you pretty much have to
	// use a root account to allow increasing a limit reliably. Dropping
	// privileges is also tricky. The best strategy is to make a shell
	// script set up the limits as root and switch users before starting
	// the server.
	fdLimit := &syscall.Rlimit{}
	if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, fdLimit); err != nil {
		log.Errorf("max-open-fds failed: %v", err)
	}
	fdl := stats.NewInt("MaxFds")
	fdl.Set(int64(fdLimit.Cur))

	onInitHooks.Fire()
}

func populateListeningURL() {
	host, err := netutil.FullyQualifiedHostname()
	if err != nil {
		host, err = os.Hostname()
		if err != nil {
			log.Fatalf("os.Hostname() failed: %v", err)
		}
	}
	ListeningURL = url.URL{
		Scheme: "http",
		Host:   netutil.JoinHostPort(host, int32(*Port)),
		Path:   "/",
	}
}

// onInit registers f to be run at the beginning of the app
// lifecycle. It should be called in an init() function.
func onInit(f func()) {
	onInitHooks.Add(f)
}

// OnTerm registers a function to be run when the process receives a SIGTERM.
// This allows the program to change its behavior during the lameduck period.
//
// All hooks are run in parallel, and there is no guarantee that the process
// will wait for them to finish before dying when the lameduck period expires.
//
// See also: OnTermSync
func OnTerm(f func()) {
	onTermHooks.Add(f)
}

// OnTermSync registers a function to be run when the process receives SIGTERM.
// This allows the program to change its behavior during the lameduck period.
//
// All hooks are run in parallel, and the process will do its best to wait
// (up to -onterm_timeout) for all of them to finish before dying.
//
// See also: OnTerm
func OnTermSync(f func()) {
	onTermSyncHooks.Add(f)
}

// fireOnTermSyncHooks returns true iff all the hooks finish before the timeout.
func fireOnTermSyncHooks(timeout time.Duration) bool {
	log.Infof("Firing synchronous OnTermSync hooks and waiting up to %v for them", timeout)

	timer := time.NewTimer(timeout)
	defer timer.Stop()

	done := make(chan struct{})
	go func() {
		onTermSyncHooks.Fire()
		close(done)
	}()

	select {
	case <-done:
		log.Infof("OnTermSync hooks finished")
		return true
	case <-timer.C:
		log.Infof("OnTermSync hooks timed out")
		return false
	}
}

// OnRun registers f to be run right at the beginning of Run. All
// hooks are run in parallel.
func OnRun(f func()) {
	onRunHooks.Add(f)
}

// FireRunHooks fires the hooks registered by OnHook.
// Use this in a non-server to run the hooks registered
// by servenv.OnRun().
func FireRunHooks() {
	onRunHooks.Fire()
}

// RegisterDefaultFlags registers the default flags for
// listening to a given port for standard connections.
// If calling this, then call RunDefault()
func RegisterDefaultFlags() {
	Port = flag.Int("port", 0, "port for the server")
}

// RunDefault calls Run() with the parameters from the flags.
func RunDefault() {
	Run(*Port)
}


text:
/**
 * main app class
 */
import { Component } from '@angular/core';
import { Routes, ROUTER_DIRECTIVES, Router } from '@angular/router';
import {HomeComponent} from './app/home/home.component';
import {LoginFormComponent} from './app/auth/login-form.component';
import {UserService}    from './app/user/user.service';
import {ChatComponent} from "./app/chat/chat.component";
import {RegisterFormComponent} from "./app/auth/register-form.component";
import {AuthService} from "./app/auth/auth.service";

@Component({
    selector: 'my-app',
    template: `

Ultra cool chat

{{errorMessage}}

Sign up

Sign in

Chat

Sign out

                <router-outlet></router-outlet>

    `,
    directives: [<any> ROUTER_DIRECTIVES]
})
@Routes([
    {path: '/', component: <any> HomeComponent},
    {path: '/signin', component: <any> LoginFormComponent},
    {path: '/signup', component: <any> RegisterFormComponent},
    {path: '/chat', component: <any> ChatComponent}
])
export class AppComponent {
    user:any;
    error:boolean;
    errorMessage:string;

    constructor(private _userService:UserService
        , private _authService:AuthService
        , private _router:Router) {
        this.user = this._userService.getUser();
    }

    onSignOut() {
        this._authService.logout()
            .then(isLogged=> {
                this.error = false;
                this._userService.removeUser();
                this.user = this._userService.getUser();
                this._router.navigate(['/signin'])
            })
            .catch(error=> {
                this.error = true;
                this.errorMessage = error.message;
            })
    }
}


text:
package com.ibm.streamsx.topology.internal.functional.ops;

import java.net.MalformedURLException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;

import com.ibm.streams.operator.OperatorContext;
import com.ibm.streamsx.topology.function.FunctionContainer;
import com.ibm.streamsx.topology.function.FunctionContext;

class FunctionOperatorContext implements FunctionContext {

    private final OperatorContext context;
    private final FunctionContainer container;

    FunctionOperatorContext( OperatorContext context) {
        this.context = context;
        container = new FunctionPEContainer(context.getPE());
    }

    @Override
    public FunctionContainer getContainer() {
        return container;
    }

    @Override
    public ScheduledExecutorService getScheduledExecutorService() {
        return context.getScheduledExecutorService();
    }

    @Override
    public ThreadFactory getThreadFactory() {
        return context.getThreadFactory();
    }

    @Override
    public int getChannel() {
        return context.getChannel();
    }

    @Override
    public int getMaxChannels() {
        return context.getMaxChannels();
    }

    @Override
    public void addClassLibraries(String[] libraries)
            throws MalformedURLException {
        context.addClassLibraries(libraries);
    }
}


text:
<title>Log In</title>

<link rel="stylesheet" type="text/css" href="chatroom_style.css"></style>

<form id = "loginForm" class = "general">

Welcome!

Username:  <input type="text" id="username">

Password:  <input type="password" id="password">

<input style = "margin-left:300px" type="submit" class ="button" id = "login" value = "Log In">

Not a member? Sign up now!

</form>


text:
package com.banking.emprestimos.model;

import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@DataJpaTest
public class TestCliente {

}


text:
package com.google.security.zynamics.binnavi.disassembly.types;

import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import java.util.Objects;

/**
 * Represents raw database records which correspond to TypeMember objects. This class is only used
 * when loading members from the database and shouldn't be used elsewhere.
 */
public final class RawTypeMember {
  private final int id;
  private final String name;
  private final int baseTypeId;
  private final Optional<Integer> numberOfElements;
  private final Integer parentId;
  private final Optional<Integer> offset;
  private final Optional<Integer> argument;

  public RawTypeMember(final int id, final String name, final int baseTypeId,
      final Integer parentId, final Integer offset, final Integer argument,
      final Integer numberOfElements) {
    this.id = id;
    this.name = Preconditions.checkNotNull(name, "Error: name can not be null");
    this.baseTypeId = baseTypeId;
    this.parentId = parentId;
    Preconditions.checkArgument(offset == null || offset >= 0, "Error: offset must be positive.");
    this.offset = Optional.fromNullable(offset);
    this.argument = Optional.fromNullable(argument);
    Preconditions.checkArgument(numberOfElements == null || numberOfElements >= 0,
        "Error: number of elements must be null or greater than zero.");
    Preconditions.checkArgument(
        !Objects.equals(numberOfElements, offset) ^ this.argument.isPresent(),
        "Error: Either this is a struct member or a array member, or a prototype argument.");
    this.numberOfElements = Optional.fromNullable(numberOfElements);
  }

  public Optional<Integer> getArgumentIndex() {
    return argument;
  }

  public int getBaseTypeId() {
    return baseTypeId;
  }

  public int getId() {
    return id;
  }

  public String getName() {
    return name;
  }

  public Optional<Integer> getNumberOfElements() {
    return numberOfElements;
  }

  public Optional<Integer> getOffset() {
    return offset;
  }

  public Integer getParentId() {
    return parentId;
  }

  @Override
  public String toString() {
    return String.format(
        "name=%s, id=%d, offset=%d, numberOfElements=%d, parentId=%d, baseTypeId=%d, argument=%d",
        name, id, offset, numberOfElements, parentId, baseTypeId, argument);
  }
}


text:
var ReactTools = require('react-tools');
module.exports = {
  process: function(src) {
    'use strict';
    return ReactTools.transform(src);
  }
};


text:
package com.google.jenkins.plugins.cloudbackup.volume.zip;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import com.google.jenkins.plugins.cloudbackup.scope.Scopes;
import com.google.jenkins.plugins.cloudbackup.volume.Volume;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

/**
 * Tests for {@link ZipVolume}.
 */
public class ZipVolumeTest {
  private static final Logger logger = Logger.getLogger(ZipVolumeTest.class.getName());
  private static final String NEW_FILE_ZIPPED_CONTENT  = "newFile new content";
  private static final String NEW_FILE_CHANGED_CONTENT  = "newFile changed content";
  private static final String EXISTING_FILE_ZIPPED_CONTENT  = "existingFile new content";
  private static final String EXISTING_FILE_CHANGED_CONTENT  = "existingFile changed content";
  private static final String NEW_FILE  = "newFile";
  private static final String EXISTING_FILE  = "existingFile";

  private Path tempDirectory;
  private Path nonEmptyDir;
  private Path emptyDir;
  private Path fileInRoot;
  private Path fileInDir;
  private Path validSymlink;
  private Path invalidSymlink;
  private Path existingFile;
  private Path newFile;
  private ZipVolume zipVolume;

  @Before
  public void setUp() throws Exception {
    tempDirectory = Files.createTempDirectory(ZipVolumeTest.class.getSimpleName());
    nonEmptyDir = tempDirectory.resolve("nonEmptyDir");
    Files.createDirectory(nonEmptyDir);
    emptyDir = tempDirectory.resolve("emptyDir");
    Files.createDirectory(emptyDir);
    fileInRoot = tempDirectory.resolve("fileInRoot");
    Files.write(fileInRoot, Collections.singleton("fileInRoot content"), StandardCharsets.UTF_8,
        StandardOpenOption.CREATE_NEW);
    fileInDir = tempDirectory.resolve("nonEmptyDir/fileInDir");
    Files.write(fileInDir, Collections.singleton("fileInDir content"), StandardCharsets.UTF_8,
        StandardOpenOption.CREATE_NEW);
    validSymlink = tempDirectory.resolve("validSymlink");
    Files.createSymbolicLink(validSymlink, tempDirectory.relativize(nonEmptyDir));
    invalidSymlink = tempDirectory.resolve("invalidSymlink");
    // invalid symlink in the fashion jenkins creates them
    Files.createSymbolicLink(invalidSymlink, Paths.get("-1"));
    existingFile = tempDirectory.resolve(EXISTING_FILE);
    Files.write(existingFile, Collections.singleton(EXISTING_FILE_ZIPPED_CONTENT),
        StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW);
    newFile = tempDirectory.resolve(NEW_FILE);
    Files.write(newFile, Collections.singleton(NEW_FILE_ZIPPED_CONTENT), StandardCharsets.UTF_8,
        StandardOpenOption.CREATE_NEW);
    zipVolume = new ZipVolume();
  }

  @After
  public void tearDown() throws Exception {
    deleteDirectory(tempDirectory);
    tempDirectory = null;
    zipVolume = null;
  }

  @Test
  public void testCreateAndExtractZipArchive() throws Exception {
    // create
    Path volumePath = tempDirectory.resolve("test.zip");
    Map<String, Boolean> existingFilesMap = new HashMap<>();
    existingFilesMap.put("nonEmptyDir", false);
    existingFilesMap.put("emptyDir", false);
    existingFilesMap.put("fileInRoot", false);
    existingFilesMap.put("nonEmptyDir/fileInDir", false);
    existingFilesMap.put("validSymlink", false);
    existingFilesMap.put("invalidSymlink", false);

    try (Volume.Creator creator = zipVolume.createNew(volumePath)) {
      creator.addFile(nonEmptyDir, "nonEmptyDir", null);
      creator.addFile(emptyDir, "emptyDir", null);
      creator.addFile(fileInRoot, "fileInRoot", null);
      creator.addFile(fileInDir, "nonEmptyDir/fileInDir", null);
      creator.addFile(validSymlink, "validSymlink",
          Files.readAttributes(validSymlink, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS));
      creator.addFile(invalidSymlink, "invalidSymlink",
          Files.readAttributes(
              invalidSymlink, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS));
    } // auto-close creator
    assertTrue(Files.exists(volumePath));

    // extract
    Path extractPath = tempDirectory.resolve("extracted");
    Files.createDirectory(extractPath);
    try (Volume.Extractor extractor = zipVolume.extract(volumePath)) {
      Scopes.extractAllFilesTo(extractPath, extractor, true, existingFilesMap);
    } // auto-close extractor

    // verify
    assertTrue(Files.exists(extractPath.resolve("nonEmptyDir")));
    assertTrue(Files.exists(extractPath.resolve("emptyDir")));
    assertTrue(Files.exists(extractPath.resolve("fileInRoot")));
    assertTrue(Files.exists(extractPath.resolve("nonEmptyDir/fileInDir")));
    // ensure the link itself exists
    assertTrue(Files.exists(extractPath.resolve("validSymlink"), LinkOption.NOFOLLOW_LINKS));
    // ensure the link target exists
    assertTrue(Files.exists(extractPath.resolve("validSymlink")));
    // ensure the link itself exists
    assertTrue(Files.exists(extractPath.resolve("invalidSymlink"), LinkOption.NOFOLLOW_LINKS));
    // ensure the link target does not exist
    assertTrue(Files.notExists(extractPath.resolve("invalidSymlink")));
  }

  @Test
  public void testOverwriteSet() throws Exception {
    // create
    Path volumePath = tempDirectory.resolve("test.zip");
    try (Volume.Creator creator = zipVolume.createNew(volumePath)) {
      creator.addFile(existingFile, EXISTING_FILE, null);
    } // auto-close creator
    assertTrue(Files.exists(volumePath));

    // extract
    Map<String, Boolean> existingFilesMap = new HashMap<>();
    existingFilesMap.put(EXISTING_FILE, false);
    Path extractPath = tempDirectory.resolve("extracted");
    Files.createDirectory(extractPath);
    // create pre-existing file
    Path extractedExistingFile = extractPath.resolve(EXISTING_FILE);
    Files.write(extractedExistingFile, Collections.singleton(EXISTING_FILE_CHANGED_CONTENT),
        StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW);
    try (Volume.Extractor extractor = zipVolume.extract(volumePath)) {
      Scopes.extractAllFilesTo(extractPath, extractor, true, existingFilesMap);
    } // auto-close extractor

    // verify
    assertTrue(Files.exists(extractedExistingFile));
    List<String> existingFileText =
        Files.readAllLines(extractedExistingFile, StandardCharsets.UTF_8);
    assertEquals(1, existingFileText.size());
    assertEquals(EXISTING_FILE_ZIPPED_CONTENT, existingFileText.get(0));
  }

  @Test
  public void testNothingAddedForDeletedFile() throws Exception {
    // create
    Path volumePath = tempDirectory.resolve("test.zip");
    // Add new file and existing file to the backup
    try (Volume.Creator creator = zipVolume.createNew(volumePath)) {
      creator.addFile(existingFile, EXISTING_FILE, null);
      creator.addFile(newFile, NEW_FILE, null);
    } // auto-close creator
    assertTrue(Files.exists(volumePath));

    // extract
    //Add only existing file to the map. This means new file was deleted at some point
    Map<String, Boolean> existingFilesMap = new HashMap<>();
    existingFilesMap.put(EXISTING_FILE, false);
    Path extractPath = tempDirectory.resolve("extracted");
    Path extractedExistingFile = extractPath.resolve(EXISTING_FILE);
    Path extractedNewFile = extractPath.resolve(NEW_FILE);
    try (Volume.Extractor extractor = zipVolume.extract(volumePath)) {
      Scopes.extractAllFilesTo(extractPath, extractor, true, existingFilesMap);
    } // auto-close extractor

    // verify
    assertFalse(Files.exists(extractedNewFile));
    assertTrue(Files.exists(extractedExistingFile));
    List<String> existingFileText =
        Files.readAllLines(extractedExistingFile, StandardCharsets.UTF_8);
    assertEquals(1, existingFileText.size());
    assertEquals(EXISTING_FILE_ZIPPED_CONTENT, existingFileText.get(0));
  }

  @Test
  public void testCreateAndExtractZipArchiveWithConflict() throws Exception {
    // create
    Path volumePath = tempDirectory.resolve("test.zip");
    try (Volume.Creator creator = zipVolume.createNew(volumePath)) {
      creator.addFile(existingFile, EXISTING_FILE, null);
      creator.addFile(newFile, NEW_FILE, null);
    } // auto-close creator
    assertTrue(Files.exists(volumePath));

    // extract
    Map<String, Boolean> existingFilesMap = new HashMap<>();
    existingFilesMap.put(EXISTING_FILE, false);
    existingFilesMap.put(NEW_FILE, false);
    Path extractPath = tempDirectory.resolve("extracted");
    Files.createDirectory(extractPath);
    // create pre-existing file
    Path extractedExistingFile = extractPath.resolve(EXISTING_FILE);
    Path extractedNewFile = extractPath.resolve(NEW_FILE);
    Files.write(extractedExistingFile, Collections.singleton(EXISTING_FILE_CHANGED_CONTENT),
        StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW);
    try (Volume.Extractor extractor = zipVolume.extract(volumePath)) {
      Scopes.extractAllFilesTo(extractPath, extractor, false, existingFilesMap);
    } // auto-close extractor

    // verify
    assertTrue(Files.exists(extractedExistingFile));
    assertTrue(Files.exists(extractedNewFile));
    List<String> existingFileText =
        Files.readAllLines(extractedExistingFile, StandardCharsets.UTF_8);
    List<String> newFileText = Files.readAllLines(extractedNewFile, StandardCharsets.UTF_8);
    assertEquals(1, existingFileText.size());
    assertEquals(1, newFileText.size());
    assertEquals(EXISTING_FILE_CHANGED_CONTENT, existingFileText.get(0));
    assertEquals(NEW_FILE_ZIPPED_CONTENT, newFileText.get(0));
  }

  @Test
  public void testCreateAndExtractZipArchiveWithIncrementalUpdates() throws Exception {
    // create
    Path volumePath = tempDirectory.resolve("test.zip");
    try (Volume.Creator creator = zipVolume.createNew(volumePath)) {
      creator.addFile(existingFile, EXISTING_FILE, null);
      creator.addFile(newFile, NEW_FILE, null);
    }
    assertTrue(Files.exists(volumePath));

    // extract
    Map<String, Boolean> existingFilesMap = new HashMap<>();
    existingFilesMap.put(EXISTING_FILE, null);
    existingFilesMap.put(NEW_FILE, null);
    Path extractPath = tempDirectory.resolve("extracted");
    Files.createDirectory(extractPath);
    // create pre-existing file
    Path extractedExistingFile = extractPath.resolve(EXISTING_FILE);
    Path extractedNewFile = extractPath.resolve(NEW_FILE);
    Files.write(extractedExistingFile, Collections.singleton(EXISTING_FILE_CHANGED_CONTENT),
        StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW);
    try (Volume.Extractor extractor = zipVolume.extract(volumePath)) {
      Scopes.extractAllFilesTo(extractPath, extractor, false, existingFilesMap);
    } // auto-close extractor

    // check that the map is updated. Manipulate the content of this file
    assertTrue(existingFilesMap.get(NEW_FILE));
    Files.write(extractedNewFile, Collections.singleton(NEW_FILE_CHANGED_CONTENT),
        StandardCharsets.UTF_8, StandardOpenOption.WRITE);
    List<String> newFileText = Files.readAllLines(extractedNewFile, StandardCharsets.UTF_8);
    assertEquals(NEW_FILE_CHANGED_CONTENT, newFileText.get(0));

    // New file should be overwritten because it was restored from backup
    try (Volume.Extractor extractor = zipVolume.extract(volumePath)) {
      Scopes.extractAllFilesTo(extractPath, extractor, false, existingFilesMap);
    }

    // verify
    assertTrue(Files.exists(extractedExistingFile));
    assertTrue(Files.exists(extractedNewFile));
    List<String> existingFileText =
        Files.readAllLines(extractedExistingFile, StandardCharsets.UTF_8);
    newFileText = Files.readAllLines(extractedNewFile, StandardCharsets.UTF_8);
    assertEquals(1, existingFileText.size());
    assertEquals(1, newFileText.size());
    assertEquals(EXISTING_FILE_CHANGED_CONTENT, existingFileText.get(0));
    assertEquals(NEW_FILE_ZIPPED_CONTENT, newFileText.get(0));
  }

  @Test
  public void testExistingFileMetadataIsEmpty() throws Exception {
    // create
    Path volumePath = tempDirectory.resolve("test.zip");
    try (Volume.Creator creator = zipVolume.createNew(volumePath)) {
      creator.addFile(existingFile, EXISTING_FILE, null);
    } // auto-close creator
    assertTrue(Files.exists(volumePath));

    // extract
    Path extractPath = tempDirectory.resolve("extracted");
    Files.createDirectory(extractPath);
    // create pre-existing file
    Path extractedExistingFile = extractPath.resolve(EXISTING_FILE);
    Files.write(extractedExistingFile, Collections.singleton(EXISTING_FILE_CHANGED_CONTENT),
        StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW);
    try (Volume.Extractor extractor = zipVolume.extract(volumePath)) {
      Scopes.extractAllFilesTo(extractPath, extractor, false, new HashMap<String,Boolean>());
    } // auto-close extractor

    // verify
    assertTrue(Files.exists(extractedExistingFile));
    List<String> existingFileText =
        Files.readAllLines(extractedExistingFile, StandardCharsets.UTF_8);
    assertEquals(1, existingFileText.size());
    assertEquals(EXISTING_FILE_CHANGED_CONTENT, existingFileText.get(0));
  }

  private static void deleteDirectory(Path dir) throws IOException {
    Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
      @Override
      public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
        logger.finer("deleting file " + file.toString());
        Files.delete(file);
        return FileVisitResult.CONTINUE;
      }

      @Override
      public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {
        if (e == null) {
          logger.finer("deleting dir " + dir.toString());
          Files.delete(dir);
          return FileVisitResult.CONTINUE;
        } else {
          throw e;
        }
      }
    });
  }
}


text:
This repository contains servers to help test the [MultiMail gem](https://github.com/jpmckinney/multi_mail) in real environments.

## Rails

    cd rails
    rails server

You can now send requests to `http://0.0.0.0:3000`. For example, if from within your `multi_mail` directory, you run:

    bundle exec rake http_post[http://0.0.0.0:3000,spec/fixtures/mailgun/parsed/valid.txt]

You will get [this response](https://gist.github.com/jpmckinney/5399865).

## Rack

    cd rack
    rackup

You can now send requests to `http://0.0.0.0:9292`. For example, if from within your `multi_mail` directory, you run:

    bundle exec rake http_post[http://0.0.0.0:9292,spec/fixtures/mailgun/parsed/valid.txt]

You will get [this response](https://gist.github.com/jpmckinney/5399854).

Copyright (c) 2012 James McKinney, released under the MIT license


text:
package com.sushe.controller;

import com.sushe.entity.Department;
import com.sushe.entity.School;
import com.sushe.entity.User;
import com.sushe.service.DepartMentService;
import com.sushe.service.FileUploadUtil;
import com.sushe.service.SchoolService;
import com.sushe.service.UserService;
import com.sushe.util.ImageCut;
import com.sushe.util.JsonUtilTemp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * Created by jiangbin on 15/4/13.
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private SchoolService schoolService;
    @Resource
    private DepartMentService departMentService;
    @Resource
    private FileUploadUtil fileUploadUtil;
    private String uploadPath; // 上传路径
    private String downloadPath; // 下载(显示)路径
    private String uploadPathTemp;// 上传临时路径
    private String downloadPathTemp; // 下载(显示)临时路径路径

    public String getUploadPathTemp() {
        return uploadPathTemp;
    }

    @Value(value = "#{public.annexUserTempPath}")
    public void setUploadPathTemp(String uploadPathTemp) {
        this.uploadPathTemp = uploadPathTemp;
    }

    public String getDownloadPathTemp() {
        return downloadPathTemp;
    }

    @Value(value = "#{public.annexUserTempUrl}")
    public void setDownloadPathTemp(String downloadPathTemp) {
        this.downloadPathTemp = downloadPathTemp;
    }

    @Value(value = "#{public.annexUserPath}")
    public void setUploadPath(String uploadPath) {
        this.uploadPath = uploadPath;
    }

    @Value(value = "#{public.annexUserUrl}")
    public void setDownloadPath(String downloadPath) {
        this.downloadPath = downloadPath;
    }

    public String getDownloadPath() {
        return downloadPath;
    }
    //private static Logger logger= LoggerFactory.getLogger(UserController.class);

    @SuppressWarnings("finally")
    @RequestMapping(value = "/selectUserById",method = RequestMethod.GET)
    public void selectByPrimaryKey(String id,HttpServletResponse response){
        User user=new User();
        user= userService.selectByPrimaryKey(id);
        JsonUtilTemp.returnJson(user, response);
        //return user;
    }
    @SuppressWarnings("finally")
    @RequestMapping(value = "/insertSimple")
    @ResponseBody
    public void insertSimple(HttpServletRequest request,HttpServletResponse response, User user){
        try{
            user.setId(UUID.randomUUID().toString());
            request.getSession().setAttribute("user",user);
            int userId= userService.insertSimple(user);
            JsonUtilTemp.returnSucessJson(response,"会员注册成功");
        }catch (Exception e){
            e.printStackTrace();
            JsonUtilTemp.returnFailJson(response, "会员注册失败");
        }

    }

    @SuppressWarnings("finally")
    @RequestMapping(value = "/selectSchool")
    public void selectSchool(HttpServletResponse response){

        List<School> moreSchool=new ArrayList<School>();
        try{
            moreSchool=schoolService.selectAll();
            JsonUtilTemp.returnJson(moreSchool,response);
        }catch (Exception e){
            e.printStackTrace();
            JsonUtilTemp.returnFailJson(response, "插入失败");
        }

    }
    @SuppressWarnings("finally")
    @RequestMapping(value = "/selectSchoolDepartment")
    public void selectSchoolDepartment(HttpServletResponse response,HttpServletRequest request){
        List<Department> departments=new ArrayList<Department>();
        try{
            departments=departMentService.selectDepartmentBySchool("1");
            JsonUtilTemp.returnJson(departments,response);
        }catch (Exception e){
            e.printStackTrace();
            JsonUtilTemp.returnFailJson(response, "插入失败");
        }
    }
    @SuppressWarnings("finally")
    @RequestMapping(value = "/regiestUser")
    public void regiestUser(HttpServletResponse response,HttpServletRequest request){
        String account=request.getParameter("account");
        User validateUser=null;
        User loginUser=null;
        try{
                loginUser=userService.selectByAccount(account);
                if(loginUser!=null){
                    //logger.debug("......................用户已存在");
                    JsonUtilTemp.returnFailJson(response,"用户已存在!");
                }else{
                    //logger.debug("......................用户没有被注册");
                    JsonUtilTemp.returnSucessJson(response, "注册用户成功!");
                }
            } catch (Exception e){
            e.printStackTrace();
            JsonUtilTemp.returnExceptionJson(response, "查询数据失败,接口异常");
        }

    }

    @SuppressWarnings("finally")
    @RequestMapping(value = "/login")
    public void selectByAccount(HttpServletResponse response,HttpServletRequest request,User user){
        User loginUser=null;
        User validateUser=null;
        try{
            validateUser=userService.selectByAccount(user.getAccount());
            if(validateUser==null){
                JsonUtilTemp.returnFailJson(response,"账号不存在");
            }else{
                loginUser=userService.selectByAccountAndPassword(user.getAccount(), user.getPassword());
                if(loginUser!=null){
                    request.getSession().setAttribute("user",loginUser);
                    request.getSession().setAttribute("downloadPath",downloadPath);
                    JsonUtilTemp.returnSucessJson(response, "登录系统成功");

                    //return new ModelAndView("module/main/index","user",user);

                }else{
                    //logger.debug("......................用户没有被注册");
                    JsonUtilTemp.returnFailJson(response, ",用户名或密码错误,登录系统失败!");
                }
            }

        } catch (Exception e){
            e.printStackTrace();
            JsonUtilTemp.returnExceptionJson(response, "查询数据失败,接口异常");
        }
    }

    /**
     * 上传头像图片
     */
    @SuppressWarnings("finally")
    @RequestMapping(value = "/uploadSticker")
    public void uploadSticker(@RequestParam("file") MultipartFile file,HttpServletResponse response){
        if(file.isEmpty()){
            JsonUtilTemp.returnFailJson(response,"上传文件不能为空");
        }else{
            try {
                byte[] bytes = file.getBytes();
                String fileName=file.getOriginalFilename();
                String size= String.valueOf(file.getSize());
                Map<String,String> map=new HashMap<String, String>();
                //复制文件到临时目录
                String newName=fileUploadUtil.SaveFileFromInputStream(file.getInputStream(),uploadPath,fileName);
                map.put("filename",newName);
                map.put("size",size);
                map.put("upload",downloadPath);
                JsonUtilTemp.returnJson(map,response);
            } catch (Exception e) {
                e.printStackTrace();
                JsonUtilTemp.returnFailJson(response,"上传文件异常");
            }

        }
    }

    /**
     * 上传裁剪头像
     * @param id
     * @param sticker
     * @param account
     * @param x1
     * @param y1
     * @param cw
     * @param ch
     * @param request
     * @param response
     */
    @SuppressWarnings("finally")
    @RequestMapping(value = "/updateUserSticker")
    public void updateUserSticker(@RequestParam("id") String id,
                                  @RequestParam("sticker") String sticker,
                                  @RequestParam("account") String account,
                                  @RequestParam("x1") String x1,
                                  @RequestParam("y1") String y1,
                                  @RequestParam("cw") String cw,
                                  @RequestParam("ch") String ch,
                                  HttpServletRequest request,
                                  HttpServletResponse response){
            // 将文件复制到指定目录下
        String oldPath =uploadPath+"/"+sticker;
        String newFilePath=uploadPath+"/"+account;
        // 创建文件目录
        File savedir140 = new File(newFilePath);
        int bytesum = 0;
        int byteread = 0;
        File oldfile = new File(oldPath);
        // 如果目录不存在就创建
        if (!savedir140.exists()) {
            savedir140.mkdirs();
        }
        try {
            if (!x1.equals("") && !("0").equals(x1)) {
                int intx1 = Integer.parseInt(x1);
                int inty1 = Integer.parseInt(y1);
                int intcw = Integer.parseInt(cw);
                int intch = Integer.parseInt(ch);
                String dirPath = oldPath;
                String toPath = newFilePath + "/" + sticker;
                ImageCut.cut(intx1, inty1, intcw, intch, dirPath, toPath);
            } else {
                InputStream inStream = null; // 读入原文件
                inStream = new FileInputStream(oldPath);
                FileOutputStream fs = new FileOutputStream(newFilePath + "/" + sticker);
                byte[] buffer = new byte[1444];
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; // 字节数 文件大小
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            JsonUtilTemp.returnFailJson(response,"文件操作异常");
        }

        //保存头像到用户
        User user=new User();
        user.setId(id);
        user.setSticker(sticker);

        try{
            //更新session的user
            HashMap<String,Object> obj=new HashMap<>();
            User tmpUser=(User)request.getSession().getAttribute("user");
            tmpUser.setSticker(sticker);
            obj.put("user",tmpUser);
            obj.put("status","success");
            JsonUtilTemp.returnJson(obj,response);
            userService.updateSticker(user);
        }catch (Exception e){
            e.printStackTrace();
            JsonUtilTemp.returnFailJson(response,"更新头像接口出错");
        }

    }

}


text:
package pruefungsvorbereitung;

class Donkey2 {
	public void assert2() {
		boolean assertsOn = true;
		//assertsOn = false;
		//assert (assertsOn) : assertsOn = true;
		assert (assertsOn);
		if(assertsOn) {
			System.out.println("assert is on");
		}
	}
}

public class VCE2014ExamCQuestion037 {

	public static void main(String[] args) {
		Donkey2 donkey2 = new Donkey2();
		donkey2.assert2();
	}

}


text:
package com.nflabs.zeppelin.server;

import java.util.ArrayList;

import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response.ResponseBuilder;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * Json response builder.
 *
 * @author Leemoonsoo
 *
 * @param <T>
 */
public class JsonResponse<T> {
  private javax.ws.rs.core.Response.Status status;
  private String message;
  private T body;
  transient ArrayList<NewCookie> cookies;
  transient boolean pretty = false;

  public JsonResponse(javax.ws.rs.core.Response.Status status) {
    this.status = status;
    this.message = null;
    this.body = null;

  }

  public JsonResponse(javax.ws.rs.core.Response.Status status, String message) {
    this.status = status;
    this.message = message;
    this.body = null;
  }

  public JsonResponse(javax.ws.rs.core.Response.Status status, T body) {
    this.status = status;
    this.message = null;
    this.body = body;
  }

  public JsonResponse(javax.ws.rs.core.Response.Status status, String message, T body) {
    this.status = status;
    this.message = message;
    this.body = body;
  }

  public JsonResponse<T> setPretty(boolean pretty) {
    this.pretty = pretty;
    return this;
  }

  /**
   * Add cookie for building.
   *
   * @param newCookie
   * @return
   */
  public JsonResponse<T> addCookie(NewCookie newCookie) {
    if (cookies == null) {
      cookies = new ArrayList<NewCookie>();
    }
    cookies.add(newCookie);

    return this;
  }

  /**
   * Add cookie for building.
   *
   * @param name
   * @param value
   * @return
   */
  public JsonResponse<?> addCookie(String name, String value) {
    return addCookie(new NewCookie(name, value));
  }

  public String toString() {
    Gson gson = null;
    if (pretty) {
      gson = new GsonBuilder().setPrettyPrinting().create();
    } else {
      gson = new Gson();
    }
    return gson.toJson(this);
  }

  public javax.ws.rs.core.Response.Status getCode() {
    return status;
  }

  public void setCode(javax.ws.rs.core.Response.Status status) {
    this.status = status;
  }

  public String getMessage() {
    return message;
  }

  public void setMessage(String message) {
    this.message = message;
  }

  public T getBody() {
    return body;
  }

  public void setBody(T body) {
    this.body = body;
  }

  public javax.ws.rs.core.Response build() {
    ResponseBuilder r = javax.ws.rs.core.Response.status(status).entity(this.toString());
    if (cookies != null) {
      for (NewCookie nc : cookies) {
        r.cookie(nc);
      }
    }
    r.header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true")
        .header("Access-Control-Allow-Headers", "authorization,Content-Type")
        .header("Access-Control-Allow-Methods", "POST, GET, OPTIONS , PUT, HEAD, DELETE");
    return r.build();
  }
}


text:
namespace syncer {

void ApplyControlDataUpdates(syncable::Directory* dir) {
  syncable::WriteTransaction trans(FROM_HERE, syncable::SYNCER, dir);

  std::vector<int64_t> handles;
  dir->GetUnappliedUpdateMetaHandles(
      &trans, ToFullModelTypeSet(ControlTypes()), &handles);

  // First, go through and manually apply any new top level datatype nodes (so
  // that we don't have to worry about hitting a CONFLICT_HIERARCHY with an
  // entry because we haven't applied its parent yet).
  // TODO(sync): if at some point we support control datatypes with actual
  // hierarchies we'll need to revisit this logic.
  ModelTypeSet control_types = ControlTypes();
  for (ModelTypeSet::Iterator iter = control_types.First(); iter.Good();
       iter.Inc()) {
    ModelType type = iter.Get();
    syncable::MutableEntry entry(&trans, syncable::GET_TYPE_ROOT, type);
    if (!entry.good())
      continue;

    if (!entry.GetIsUnappliedUpdate()) {
      // If this is a type with client generated root, the root node has been
      // created locally and might never be updated by the server. In that case
      // it has to be marked as having the initial download completed (which is
      // done by changing the root's base version to a value other than
      // CHANGES_VERSION). This does nothing if the root's base version is
      // already other than CHANGES_VERSION.
      if (IsTypeWithClientGeneratedRoot(type)) {
        dir->MarkInitialSyncEndedForType(&trans, type);
      }
      continue;
    }

    DCHECK_EQ(type, entry.GetServerModelType());
    if (type == NIGORI) {
      // Nigori node applications never fail.
      ApplyNigoriUpdate(&trans,
                        &entry,
                        dir->GetCryptographer(&trans));
    } else {
      ApplyControlUpdate(&trans,
                         &entry,
                         dir->GetCryptographer(&trans));
    }
  }

  // Go through the rest of the unapplied control updates, skipping over any
  // top level folders.
  for (std::vector<int64_t>::const_iterator iter = handles.begin();
       iter != handles.end(); ++iter) {
    syncable::MutableEntry entry(&trans, syncable::GET_BY_HANDLE, *iter);
    CHECK(entry.good());
    ModelType type = entry.GetServerModelType();
    CHECK(ControlTypes().Has(type));
    if (!entry.GetUniqueServerTag().empty()) {
      // We should have already applied all top level control nodes.
      DCHECK(!entry.GetIsUnappliedUpdate());
      continue;
    }

    ApplyControlUpdate(&trans,
                       &entry,
                       dir->GetCryptographer(&trans));
  }
}

// Update the nigori handler with the server's nigori node.
//
// If we have a locally modified nigori node, we merge them manually. This
// handles the case where two clients both set a different passphrase. The
// second client to attempt to commit will go into a state of having pending
// keys, unioned the set of encrypted types, and eventually re-encrypt
// everything with the passphrase of the first client and commit the set of
// merged encryption keys. Until the second client provides the pending
// passphrase, the cryptographer will preserve the encryption keys based on the
// local passphrase, while the nigori node will preserve the server encryption
// keys.
void ApplyNigoriUpdate(syncable::WriteTransaction* const trans,
                       syncable::MutableEntry* const entry,
                       Cryptographer* cryptographer) {
  DCHECK(entry->GetIsUnappliedUpdate());

  // We apply the nigori update regardless of whether there's a conflict or
  // not in order to preserve any new encrypted types or encryption keys.
  // TODO(zea): consider having this return a bool reflecting whether it was a
  // valid update or not, and in the case of invalid updates not overwrite the
  // local data.
  const sync_pb::NigoriSpecifics& nigori =
      entry->GetServerSpecifics().nigori();
  trans->directory()->GetNigoriHandler()->ApplyNigoriUpdate(nigori, trans);

  // Make sure any unsynced changes are properly encrypted as necessary.
  // We only perform this if the cryptographer is ready. If not, these are
  // re-encrypted at SetDecryptionPassphrase time (via ReEncryptEverything).
  // This logic covers the case where the nigori update marked new datatypes
  // for encryption, but didn't change the passphrase.
  if (cryptographer->is_ready()) {
    // Note that we don't bother to encrypt any data for which IS_UNSYNCED
    // == false here. The machine that turned on encryption should know about
    // and re-encrypt all synced data. It's possible it could get interrupted
    // during this process, but we currently reencrypt everything at startup
    // as well, so as soon as a client is restarted with this datatype marked
    // for encryption, all the data should be updated as necessary.

    // If this fails, something is wrong with the cryptographer, but there's
    // nothing we can do about it here.
    DVLOG(1) << "Received new nigori, encrypting unsynced changes.";
    syncable::ProcessUnsyncedChangesForEncryption(trans);
  }

  if (!entry->GetIsUnsynced()) {  // Update only.
    UpdateLocalDataFromServerData(trans, entry);
  } else {  // Conflict.
    const sync_pb::EntitySpecifics& server_specifics =
        entry->GetServerSpecifics();
    const sync_pb::NigoriSpecifics& server_nigori = server_specifics.nigori();
    const sync_pb::EntitySpecifics& local_specifics =
        entry->GetSpecifics();
    const sync_pb::NigoriSpecifics& local_nigori = local_specifics.nigori();

    // We initialize the new nigori with the server state, and will override
    // it as necessary below.
    sync_pb::EntitySpecifics new_specifics = entry->GetServerSpecifics();
    sync_pb::NigoriSpecifics* new_nigori = new_specifics.mutable_nigori();

    // If the cryptographer is not ready, another client set a new encryption
    // passphrase. If we had migrated locally, we will re-migrate when the
    // pending keys are provided. If we had set a new custom passphrase locally
    // the user will have another chance to set a custom passphrase later
    // (assuming they hadn't set a custom passphrase on the other client).
    // Therefore, we only attempt to merge the nigori nodes if the cryptographer
    // is ready.
    // Note: we only update the encryption keybag if we're sure that we aren't
    // invalidating the keystore_decryptor_token (i.e. we're either
    // not migrated or we copying over all local state).
    if (cryptographer->is_ready()) {
      if (local_nigori.has_passphrase_type() &&
          server_nigori.has_passphrase_type()) {
        // They're both migrated, preserve the local nigori if the passphrase
        // type is more conservative.
        if (server_nigori.passphrase_type() ==
                sync_pb::NigoriSpecifics::KEYSTORE_PASSPHRASE &&
            local_nigori.passphrase_type() !=
                sync_pb::NigoriSpecifics::KEYSTORE_PASSPHRASE) {
          DCHECK(local_nigori.passphrase_type() ==
                     sync_pb::NigoriSpecifics::FROZEN_IMPLICIT_PASSPHRASE ||
                 local_nigori.passphrase_type() ==
                     sync_pb::NigoriSpecifics::CUSTOM_PASSPHRASE);
          new_nigori->CopyFrom(local_nigori);
          cryptographer->GetKeys(new_nigori->mutable_encryption_keybag());
        }
      } else if (!local_nigori.has_passphrase_type() &&
                 !server_nigori.has_passphrase_type()) {
        // Set the explicit passphrase based on the local state. If the server
        // had set an explict passphrase, we should have pending keys, so
        // should not reach this code.
        // Because neither side is migrated, we don't have to worry about the
        // keystore decryptor token.
        new_nigori->set_keybag_is_frozen(local_nigori.keybag_is_frozen());
        cryptographer->GetKeys(new_nigori->mutable_encryption_keybag());
      } else if (local_nigori.has_passphrase_type()) {
        // Local is migrated but server is not. Copy over the local migrated
        // data.
        new_nigori->CopyFrom(local_nigori);
        cryptographer->GetKeys(new_nigori->mutable_encryption_keybag());
      }  // else leave the new nigori with the server state.
    }

    // Always update to the safest set of encrypted types.
    trans->directory()->GetNigoriHandler()->UpdateNigoriFromEncryptedTypes(
        new_nigori,
        trans);

    entry->PutSpecifics(new_specifics);
    DVLOG(1) << "Resolving simple conflict, merging nigori nodes: "
             << entry;

    conflict_util::OverwriteServerChanges(entry);

    UMA_HISTOGRAM_ENUMERATION("Sync.ResolveSimpleConflict",
                              ConflictResolver::NIGORI_MERGE,
                              ConflictResolver::CONFLICT_RESOLUTION_SIZE);
  }
}

void ApplyControlUpdate(syncable::WriteTransaction* const trans,
                        syncable::MutableEntry* const entry,
                        Cryptographer* cryptographer) {
  DCHECK_NE(entry->GetServerModelType(), NIGORI);
  DCHECK(entry->GetIsUnappliedUpdate());
  if (entry->GetIsUnsynced()) {
      // We just let the server win all conflicts with control types.
    DVLOG(1) << "Ignoring local changes for control update.";
    conflict_util::IgnoreLocalChanges(entry);
    UMA_HISTOGRAM_ENUMERATION("Sync.ResolveSimpleConflict",
                              ConflictResolver::OVERWRITE_LOCAL,
                              ConflictResolver::CONFLICT_RESOLUTION_SIZE);
  }

  UpdateAttemptResponse response = AttemptToUpdateEntry(
      trans, entry, cryptographer);
  DCHECK_EQ(SUCCESS, response);
}

}  // namespace syncer


text:
Chartled.NumberChartle = function(definition, el, baseUrl) {
  Chartled.DashingChartle.call( this, definition, el, baseUrl );
};

Chartled.inheritPrototype(Chartled.NumberChartle, Chartled.DashingChartle, {
  initialize: function( definition ) {
    if( typeof(definition.backgroundColorClass) == 'undefined' ) definition.backgroundColorClass= 'chartled-color-2';
    if( typeof(definition.backgroundIcon) == 'undefined' ) definition.backgroundIcon= 'heart';
    if( typeof(definition.displayUpdatedAt) == 'undefined' ) definition.displayUpdatedAt= true;
    if( typeof(definition.metric) == 'undefined' ) definition.metric= "";

    Chartled.DashingChartle.prototype.initialize.call(this, definition);
  }
});


text:
package io.opentelemetry.api.trace;

import io.opentelemetry.api.internal.ImmutableSpanContext;
import io.opentelemetry.api.internal.OtelEncodingUtils;
import javax.annotation.concurrent.Immutable;

/**
 * A class that represents a span context. A span context contains the state that must propagate to
 * child {@link Span}s and across process boundaries. It contains the identifiers (a {@link TraceId
 * trace_id} and {@link SpanId span_id}) associated with the {@link Span} and a set of options
 * (currently only whether the context is sampled or not), as well as the {@link TraceState
 * traceState} and the {@link boolean remote} flag.
 *
 *
Implementations of this interface *must* be immutable and have well-defined value-based
 * equals/hashCode implementations. If an implementation does not strictly conform to these
 * requirements, behavior of the OpenTelemetry APIs and default SDK cannot be guaranteed. It is
 * strongly suggested that you use the implementation that is provided here via {@link
 * #create(String, String, TraceFlags, TraceState)} or {@link #createFromRemoteParent(String,
 * String, TraceFlags, TraceState)}.
 */
@Immutable
public interface SpanContext {

  /**
   * Returns the invalid {@code SpanContext} that can be used for no-op operations.
   *
   * @return the invalid {@code SpanContext}.
   */
  static SpanContext getInvalid() {
    return ImmutableSpanContext.INVALID;
  }

  /**
   * Creates a new {@code SpanContext} with the given identifiers and options.
   *
   *
If the traceId or the spanId are invalid (ie. do not conform to the requirements for
   * hexadecimal ids of the appropriate lengths), both will be replaced with the standard "invalid"
   * versions (i.e. all '0's). See {@link SpanId#isValid(CharSequence)} and {@link
   * TraceId#isValid(CharSequence)} for details.
   *
   * @param traceIdHex the trace identifier of the {@code SpanContext}.
   * @param spanIdHex the span identifier of the {@code SpanContext}.
   * @param traceFlags the trace flags of the {@code SpanContext}.
   * @param traceState the trace state for the {@code SpanContext}.
   * @return a new {@code SpanContext} with the given identifiers and options.
   */
  static SpanContext create(
      String traceIdHex, String spanIdHex, TraceFlags traceFlags, TraceState traceState) {
    return ImmutableSpanContext.create(
        traceIdHex,
        spanIdHex,
        traceFlags,
        traceState,
        /* remote=*/ false,
        /* skipIdValidation=*/ false);
  }

  /**
   * Creates a new {@code SpanContext} that was propagated from a remote parent, with the given
   * identifiers and options.
   *
   *
If the traceId or the spanId are invalid (ie. do not conform to the requirements for
   * hexadecimal ids of the appropriate lengths), both will be replaced with the standard "invalid"
   * versions (i.e. all '0's). See {@link SpanId#isValid(CharSequence)} and {@link
   * TraceId#isValid(CharSequence)} for details.
   *
   * @param traceIdHex the trace identifier of the {@code SpanContext}.
   * @param spanIdHex the span identifier of the {@code SpanContext}.
   * @param traceFlags the trace flags of the {@code SpanContext}.
   * @param traceState the trace state for the {@code SpanContext}.
   * @return a new {@code SpanContext} with the given identifiers and options.
   */
  static SpanContext createFromRemoteParent(
      String traceIdHex, String spanIdHex, TraceFlags traceFlags, TraceState traceState) {
    return ImmutableSpanContext.create(
        traceIdHex,
        spanIdHex,
        traceFlags,
        traceState,
        /* remote=*/ true,
        /* skipIdValidation=*/ false);
  }

  /**
   * Returns the trace identifier associated with this {@link SpanContext} as 32 character lowercase
   * hex String.
   *
   * @return the trace identifier associated with this {@link SpanContext} as lowercase hex.
   */
  String getTraceId();

  /**
   * Returns the trace identifier associated with this {@link SpanContext} as 16-byte array.
   *
   * @return the trace identifier associated with this {@link SpanContext} as 16-byte array.
   */
  default byte[] getTraceIdBytes() {
    return OtelEncodingUtils.bytesFromBase16(getTraceId(), TraceId.getLength());
  }

  /**
   * Returns the span identifier associated with this {@link SpanContext} as 16 character lowercase
   * hex String.
   *
   * @return the span identifier associated with this {@link SpanContext} as 16 character lowercase
   *     hex (base16) String.
   */
  String getSpanId();

  /**
   * Returns the span identifier associated with this {@link SpanContext} as 8-byte array.
   *
   * @return the span identifier associated with this {@link SpanContext} as 8-byte array.
   */
  default byte[] getSpanIdBytes() {
    return OtelEncodingUtils.bytesFromBase16(getSpanId(), SpanId.getLength());
  }

  /** Whether the span in this context is sampled. */
  default boolean isSampled() {
    return getTraceFlags().isSampled();
  }

  /**
   * Returns the trace flags associated with this {@link SpanContext}.
   *
   * @return the trace flags associated with this {@link SpanContext}.
   */
  TraceFlags getTraceFlags();

  /**
   * Returns the {@code TraceState} associated with this {@code SpanContext}.
   *
   * @return the {@code TraceState} associated with this {@code SpanContext}.
   */
  TraceState getTraceState();

  /**
   * Returns {@code true} if this {@code SpanContext} is valid.
   *
   * @return {@code true} if this {@code SpanContext} is valid.
   */
  default boolean isValid() {
    return TraceId.isValid(getTraceId()) && SpanId.isValid(getSpanId());
  }

  /**
   * Returns {@code true} if the {@code SpanContext} was propagated from a remote parent.
   *
   * @return {@code true} if the {@code SpanContext} was propagated from a remote parent.
   */
  boolean isRemote();
}


text:
package im.actor.core.entity;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import im.actor.core.api.ApiAvatarImage;
import im.actor.runtime.bser.BserValues;
import im.actor.runtime.bser.BserWriter;

public class AvatarImage extends WrapperEntity<ApiAvatarImage> {

    private static final int RECORD_ID = 10;

    private int width;
    private int height;
    @NotNull
    @SuppressWarnings("NullableProblems")
    private FileReference fileReference;

    public AvatarImage(@NotNull ApiAvatarImage wrapped) {
        super(RECORD_ID, wrapped);
    }

    public AvatarImage(@NotNull byte[] data) throws IOException {
        super(RECORD_ID, data);
    }

    public int getWidth() {
        return width;
    }

    public int getHeight() {
        return height;
    }

    @NotNull
    public FileReference getFileReference() {
        return fileReference;
    }

    @Override
    public void parse(BserValues values) throws IOException {
        // Is Wrapper layout
        if (values.getBool(5, false)) {
            // Parse wrapper layout
            super.parse(values);
        } else {
            // Convert old layout
            throw new IOException("Unsupported obsolete format");
        }
    }

    @Override
    public void serialize(BserWriter writer) throws IOException {
        // Mark as wrapper layout
        writer.writeBool(5, true);
        // Serialize wrapper layout
        super.serialize(writer);
    }

    @Override
    protected void applyWrapped(@NotNull ApiAvatarImage wrapped) {
        this.width = wrapped.getWidth();
        this.height = wrapped.getHeight();
        this.fileReference = new FileReference(wrapped.getFileLocation(),
                "avatar.jpg", wrapped.getFileSize());
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        AvatarImage that = (AvatarImage) o;

        if (height != that.height) return false;
        if (width != that.width) return false;
        if (!fileReference.equals(that.fileReference)) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = width;
        result = 31 * result + height;
        result = 31 * result + fileReference.hashCode();
        return result;
    }

    @Override
    @NotNull
    protected ApiAvatarImage createInstance() {
        return new ApiAvatarImage();
    }
}


text:
let mix = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix
        .js('resources/assets/js/app.js', 'public/js')
        .copy('node_modules/jquery/dist/jquery.min.js', 'public/js')
        .copy('node_modules/toastr/build/toastr.min.js', 'public/js')
        .copy('node_modules/select2/dist/js/select2.min.js', 'public/js')
        .sass('resources/assets/sass/app.scss', 'public/css')
        .sass('node_modules/toastr/toastr.scss', 'public/css')
        .copy('node_modules/select2/dist/css/select2.min.css', 'public/css');


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

class Brand_model extends CI_Model
{
    function __construct()
    {
        // Call the Model constructor
        parent::__construct();
		$this->load->database();
    }

	public function index(){

	  $this->db->select('*');
	  $this->db->from('brand_strength_from_price');
	  $this->db->join('brand', 'brand_strength_from_price.brand_name = brand.brand_id');
	  $this->db->join('brand_generic', 'brand.brand_generic = brand_generic.brand_generic_id');
	  $this->db->join('brand_dosage_form', 'brand_strength_from_price.brand_dosage_form = brand_dosage_form.brand_dosage_form_id');
	  $this->db->join('brand_manufacturer', 'brand.brand_manufacturer = brand_manufacturer.manufacturer_id');
	  $this->db->join('brand_strength', 'brand_strength_from_price.brand_strength = brand_strength.brand_strength_id');
	  $query = $this->db->get();
	  return $query->result();

	}

	public function getBrands(){
	  $this->db->select('*');
	  $this->db->from('brand_strength_from_price');
	  $this->db->join('brand', 'brand_strength_from_price.brand_name = brand.brand_id');
	  $this->db->join('brand_generic', 'brand.brand_generic = brand_generic.brand_generic_id');
	  $this->db->join('brand_dosage_form', 'brand_strength_from_price.brand_dosage_form = brand_dosage_form.brand_dosage_form_id');
	  $this->db->join('brand_manufacturer', 'brand.brand_manufacturer = brand_manufacturer.manufacturer_id');
	  $this->db->join('brand_strength', 'brand_strength_from_price.brand_strength = brand_strength.brand_strength_id');
	  $query = $this->db->get();
	  return $query->result();

	}

	public function get_shop_based_on_thana_and_brand(){
		$this->db->select('brand.brand_name,manufacturer_name,brand_dosage_form_name,brand_dosage_amount.brand_dosage_amount,brand_strength_name,brand_quantity,brand_price,brand_price_ppp');
		$this->db->from('brand_strength_from_price');
		$this->db->join('brand','brand_strength_from_price.brand_name = brand.brand_id');
		//$this->db->join('brand_generic','brand.brand_generic = brand_generic.brand_generic_id');
		$this->db->join('brand_dosage_form','brand_strength_from_price.brand_dosage_form = brand_dosage_form.brand_dosage_form_id');
		$this->db->join('brand_dosage_amount','brand_strength_from_price.brand_dosage_amount = brand_dosage_amount.brand_dosage_amount_id');
		$this->db->join('brand_strength','brand_strength_from_price.brand_strength = brand_strength.brand_strength_id');
		$this->db->join('brand_manufacturer','brand.brand_manufacturer = brand_manufacturer.manufacturer_name');
		$query = $this->db->get();
		return $query->result();

	}

	//get department table to populate the department name dropdown
    function get_doctors_specility()
    {
        $this->db->select('doctor_category_id');
        $this->db->select('doctor_category_name');
        $this->db->from('doctors_category');
        $query = $this->db->get();
        $result = $query->result();

        //array to store department id & department name
        $doc_cat_id = array('-SELECT-');
        $doc_cat_name = array('-SELECT-');

        for ($i = 0; $i < count($result); $i++)
        {
            array_push($doc_cat_id, $result[$i]->doctor_category_id);
            array_push($doc_cat_name, $result[$i]->doctor_category_name);
        }
        return $doc_specility_result = array_combine($doc_cat_id, $doc_cat_name);
    }

	//get department table to populate the department name dropdown
    function get_district()
    {
        $this->db->select('district_id');
        $this->db->select('district_name');
        $this->db->from('district');
        $query = $this->db->get();
        $result = $query->result();

        //array to store department id & department name
        $dist_id = array('-SELECT-');
        $dist_name = array('-SELECT-');

        for ($i = 0; $i < count($result); $i++)
        {
            array_push($dist_id, $result[$i]->district_id);
            array_push($dist_name, $result[$i]->district_name);
        }
        return $dist_result = array_combine($dist_id, $dist_name);
    }

	//get department table to populate the department name dropdown
    function get_company_category()
    {
        $this->db->select('company_cat_id');
        $this->db->select('company_cat_name');
        $this->db->from('company_category');
        $query = $this->db->get();
        $result = $query->result();

        //array to store department id & department name
        $company_cat_id = array('-SELECT-');
        $company_cat_name = array('-SELECT-');

        for ($i = 0; $i < count($result); $i++)
        {
            array_push($company_cat_id, $result[$i]->company_cat_id);
            array_push($company_cat_name, $result[$i]->company_cat_name);
        }
        return $company_cat_result = array_combine($company_cat_id, $company_cat_name);
    }

	/**
	 * create_user function.
	 *
	 * @access public
	 * @param mixed $username
	 * @param mixed $email
	 * @param mixed $password
	 * @return bool true on success, false on failure
	 */
	public function create_user($username, $email, $password) {

		$data = array(
			'username'   => $username,
			'email'      => $email,
			'password'   => $this->hash_password($password),
			'created_at' => date('Y-m-j H:i:s'),
		);

		return $this->db->insert('users', $data);

	}

	/**
	 * resolve_user_login function.
	 *
	 * @access public
	 * @param mixed $username
	 * @param mixed $password
	 * @return bool true on success, false on failure
	 */
	public function resolve_user_login($username, $password) {

		$this->db->select('password');
		$this->db->from('users');
		$this->db->where('username', $username);
		$hash = $this->db->get()->row('password');

		return $this->verify_password_hash($password, $hash);

	}

	/**
	 * get_user_id_from_username function.
	 *
	 * @access public
	 * @param mixed $username
	 * @return int the user id
	 */
	public function get_user_id_from_username($username) {

		$this->db->select('id');
		$this->db->from('users');
		$this->db->where('username', $username);

		return $this->db->get()->row('id');

	}

	/**
	 * get_user function.
	 *
	 * @access public
	 * @param mixed $user_id
	 * @return object the user object
	 */
	public function get_user($user_id) {

		$this->db->from('users');
		$this->db->where('id', $user_id);
		return $this->db->get()->row();

	}

	/**
	 * hash_password function.
	 *
	 * @access private
	 * @param mixed $password
	 * @return string|bool could be a string on success, or bool false on failure
	 */
	private function hash_password($password) {

		return password_hash($password, PASSWORD_BCRYPT);

	}

	/**
	 * verify_password_hash function.
	 *
	 * @access private
	 * @param mixed $password
	 * @param mixed $hash
	 * @return bool
	 */
	private function verify_password_hash($password, $hash) {

		return password_verify($password, $hash);

	}

	// Read data using username and password
	public function login($data) {

	$condition = "user_name =" . "'" . $data['username'] . "' AND " . "user_password =" . "'" . $data['password'] . "'";
	$this->db->select('*');
	$this->db->from('user_login');
	$this->db->where($condition);
	$this->db->limit(1);
	$query = $this->db->get();

	if ($query->num_rows() == 1) {
	return true;
	} else {
	return false;
	}
	}

}


text:
'use strict';

// Fire me up!

module.exports = {
  implements: 'wrongConfig/factoryAndConstructor'
};

module.exports.factory = function () {};
module.exports._constructor = function () {};


text:
int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    qmlRegisterType<QMLDebugger>("MyDemoLibrary", 1, 0, "QMLDebugger");

    QtQuick2ApplicationViewer viewer;
    viewer.setMainQmlFile(QStringLiteral("qml/MyDemoProject/main.qml"));
    viewer.showExpanded();

    return app.exec();
}


text:
<?php

?>

<?php echo $title; ?>

<?php
if(preg_match('/Edit/',$title))
{
 	echo form_open('history_c/update/'.$pid."/".$hid, array('name' => 'myform','id' => 'myform'));
}else
{
	echo form_open('history_c/save/'.$pid."/".$visitid, array('name' => 'myform','id' => 'myform'));
}
 ?>

		<?php
			if($status !== 0){
				if((!preg_match('/Edit/',$title)) &  $status == "True"){
		 ?>

			<button type="button" class="close" data-dismiss="alert">×</button>
			Successful!   Record Added Successfully

		<?php }else if(  preg_match('/Edit/',$title)  &  $status == "True"){  ?>

			<button type="button" class="close" data-dismiss="alert">×</button>
			Successful!   Record updated Successfully

		<?php } ?>

		<?php if((!preg_match('/Edit/',$title)) &  $status == "False"){ ?>

				<button type="button" class="close" data-dismiss="alert">×</button>
				Fail ! Failed to add the Record

		<?php }else if(  preg_match('/Edit/',$title) &  $status == "False"){  ?>

				<button type="button" class="close" data-dismiss="alert">×</button>
				Fail ! Failed to update the Record

		<?php } ?>
	<?php } ?>

      Record Type*

      <select id="rectype" class="form-control" name="rectype" required="required" style="width: 200px;">
             <option <?php if (preg_match('/Edit/', $title) && $record[0]->recordType == "0") echo "selected"; ?> value="0">Note</option>
             <option  <?php if (preg_match('/Edit/', $title) && $record[0]->recordType == "1") echo "selected"; ?> value="1">To Do</option>
         </select>

     Record*

     <textarea type="text" class="form-control" style="min-width: 200px;max-width: 200px;min-height: 60px;height:auto" id="RecordText"  required name="RecordText" placeholder=""><?php if (preg_match('/Edit/', $title)) echo $record[0]->recordText; ?></textarea>

     Visible To*

     <select id="recvisible" class="form-control" name="recvisible" required="required" style="width: 200px;">
             <option <?php if (preg_match('/Edit/', $title) && $record[0]->recordVisibility == "all") echo "selected"; ?> value="all">For all</option>
             <option  <?php if (preg_match('/Edit/', $title) && $record[0]->recordVisibility == "me") echo "selected"; ?> value="me">Only Me</option>
         </select>

 <div id="rectypedev" class="form-group input-group" style="margin-top: 10px" <?php if (preg_match('/Edit/', $title) && $record[0]->recordType == '1') echo "style='visibility:visible'";
 else echo "style='visibility:hidden'"; ?> >
      Completed

         <select id="completed" name="completed" class="form-control" style="width: 200px;">
             <option  <?php if (preg_match('/Edit/', $title) && $record[0]->recordCompleted == '1') echo 'selected'; ?>   value="1">Yes</option>
             <option   <?php if (preg_match('/Edit/', $title) && $record[0]->recordCompleted == '0') echo 'selected'; ?>  value="0">No</option>
         </select>

	<?php if(preg_match('/Edit/',$title)) {?>

			Last edit by <?php  echo $record[0]->recordLastUpdateUser->hrEmployee->firstName." ".$record[0]->recordLastUpdateUser->hrEmployee->lastName." on ". date('Y-m-d', $record[0]->recordLastUpdate/1000); ?>

	<?php } ?>

         <button type="submit" class="btn btn-primary"><?php if (preg_match('/Edit/', $title)) echo "Update";
 else echo "Save"; ?></button>

         <button type="reset" class='btn' onclick="document.location.href='<?php if ($this->session->userdata ( 'userlevel' ) == 1) {echo site_url ( '/patient_overview_c/view/' . $pid );} else {echo site_url ( 'operator_home_c/view/1' );} ?>'">Back</button>


text:
const m = require('mithril')
const app = require('./app')
const vent = require('./vent')

require('./session')

require('./domevents')
require('./commands')

const panels = require('./components/panels')
const TilesetPanel = require('./components/tilesetpanel')
const AnimPanel = require('./components/animpanel')
const LayerPanel = require('./components/layerpanel')
const Renderer = require('./renderer')

const AboutDialog = require('./components/dialogs/about')
const PreferencesDialog = require('./components/dialogs/preferences')
const LayerPropertiesDialog = require('./components/dialogs/layerproperties')
const AnimPropertiesDialog = require('./components/dialogs/animproperties')
const LevelPropertiesDialog = require('./components/dialogs/levelproperties')

const columns = [
  {
    panels: [
      {
        panel: new TilesetPanel(),
        fluid: true
      },
      {
        panel: new AnimPanel()
      }
    ]
  },
  {
    panels: [
      {panel: new LayerPanel(), fluid: true}
    ],
    fluid: true
  }
]

m.mount(document.getElementById('app'), {
  view: () => {
    const R = m(
      '#editor',
      m(Renderer, m(panels, {columns: columns})),
      m(AboutDialog),
      m(PreferencesDialog),
      m(LevelPropertiesDialog),
      m(LayerPropertiesDialog),
      m(AnimPropertiesDialog)
    )
    if (IS_ELECTRON) {
      return R
    } else {
      return m(require('./components/menu'), R)
    }
  }
})

require.ensure([], () => {
  if (DEVELOPMENT) {
    const levelBuffer = require('buffer-loader!../../data/ab17btl06.j2l')
    const tilesetBuffer = require('buffer-loader!../../data/DiambGarden.j2t')

    app.j2l.loadFromBuffer(levelBuffer).then(() => {
      console.log('Level loaded')
      vent.publish('level.load')

      return app.j2t.loadFromBuffer(tilesetBuffer).then(() => {
        console.log('Tileset loaded')
        vent.publish('tileset.load')
      }).catch((err) => {
        console.error(err)
        alert(err)
      })
    }).catch((err) => {
      console.error(err)
      alert(err)
    })
  } else {
    app.j2l.newLevel()
    vent.publish('level.load')
  }
})

/*
const ModPlayer = require('./modplayer')

let modplayer = new ModPlayer({repeatCount: 1})

require.ensure([], () => {
  modplayer.play(require('buffer-loader!../../data/NWK-LAST.XM'))
})
*/


text:
var Lab = require('lab');
var Items = require('../');

// Declare internals

var internals = {};

// Test shortcuts

var lab = exports.lab = Lab.script();
var describe = lab.experiment;
var it = lab.test;
var expect = Lab.expect;

describe('Items', function () {

    describe('serial()', function () {

        it('calls methods in serial', function (done) {

            var called = [];
            var array = [1, 2, 3, 4, 5];
            var method = function (item, next) {

                called.push(item);
                setTimeout(next, 5);
            };

            Items.serial(array, method, function (err) {

                expect(err).to.not.exist;
                expect(called).to.deep.equal(array);
                done();
            });
        });

        it('skips on empty array', function (done) {

            var called = [];
            var array = [];
            var method = function (item, next) {

                called.push(item);
                setTimeout(next, 5);
            };

            Items.serial(array, method, function (err) {

                expect(err).to.not.exist;
                expect(called).to.deep.equal(array);
                done();
            });
        });

        it('aborts with error', function (done) {

            var called = [];
            var array = [1, 2, 3, 4, 5];
            var method = function (item, next) {

                called.push(item);
                if (item === 3) {
                    return next('error')
                }

                setTimeout(next, 5);
            };

            Items.serial(array, method, function (err) {

                expect(err).to.equal('error');
                expect(called).to.deep.equal([1, 2, 3]);
                done();
            });
        });
    });

    describe('parallel()', function () {

        it('calls methods in parallel', function (done) {

            var called = [];
            var array = [[1, 1], [2, 4], [3, 2], [4, 3], [5, 5]];
            var method = function (item, next) {

                setTimeout(function () {

                    called.push(item[0]);
                    next();
                }, item[1]);
            };

            Items.parallel(array, method, function (err) {

                expect(err).to.not.exist;
                expect(called).to.deep.equal([1, 3, 4, 2, 5]);
                done();
            });
        });

        it('skips on empty array', function (done) {

            var called = [];
            var array = [];
            var method = function (item, next) {

                setTimeout(function () {

                    called.push(item[0]);
                    next();
                }, item[1]);
            };

            Items.parallel(array, method, function (err) {

                expect(err).to.not.exist;
                expect(called).to.deep.equal([]);
                done();
            });
        });

        it('aborts with error', function (done) {

            var called = [];
            var array = [[1, 1], [2, 4], [3, 2], [4, 3], [5, 5]];
            var method = function (item, next) {

                setTimeout(function () {

                    if (item[0] === 3) {
                        return next('error')
                    }

                    called.push(item[0]);
                    next();
                }, item[1]);
            };

            Items.parallel(array, method, function (err) {

                expect(err).to.equal('error');
                expect(called).to.deep.equal([1]);

                setTimeout(function () {

                    expect(called).to.deep.equal([1, 4, 2, 5]);
                    done();
                }, 6);
            });
        });
    });

    describe('parallel.execute()', function () {

        it('calls methods in parallel and returns the result', function (done) {

            var fns = {
                fn1: function (next) {

                    next(null, 'bye');
                },
                fn2: function (next) {

                    next(null, 'hi');
                }
            };

            Items.parallel.execute(fns, function (err, result) {

                expect(err).to.not.exist;
                expect(result.fn1).to.equal('bye');
                expect(result.fn2).to.equal('hi');
                done();
            });
        });

        it('returns an empty object to the callback when passed an empty object', function (done) {

            var fns = {};

            Items.parallel.execute(fns, function (err, result) {

                expect(err).to.not.exist;
                expect(Object.keys(result).length).to.equal(0);
                done();
            });
        });

        it('returns an empty object to the callback when passed a null object', function (done) {

            Items.parallel.execute(null, function (err, result) {

                expect(err).to.not.exist;
                expect(Object.keys(result).length).to.equal(0);
                done();
            });
        });

        it('exits early and result object is missing when an error is passed to callback', function (done) {

            var fns = {
                fn1: function (next) {

                    setImmediate(function () {

                        next(null, 'hello');
                    });
                },
                fn2: function (next) {

                    setImmediate(function () {

                        next(new Error('This is my error'));
                    });

                },
                fn3: function (next) {

                    setImmediate(function () {

                        next(null, 'bye');
                    });
                }
            };

            Items.parallel.execute(fns, function (err, result) {

                expect(err).to.exist;
                expect(result).to.not.exist;
                done();
            });
        });

        it('exits early and doesn\'t execute other functions on an error', function (done) {

            var fn2Executed = false;
            var fns = {
                fn1: function (next) {

                    next(new Error('This is my error'));
                },
                fn2: function (next) {

                    setImmediate(function () {

                        fn2Executed = true;
                        next();
                    });
                }
            };

            Items.parallel.execute(fns, function (err, result) {

                expect(err).to.exist;
                expect(result).to.not.exist;
                expect(fn2Executed).to.equal(false);
                done();
            });
        });

        it('handles multiple errors being returned by sending first error', function (done) {

            var fns = {
                fn1: function (next) {

                    next(new Error('fn1'));
                },
                fn2: function (next) {

                    next(new Error('fn2'));

                },
                fn3: function (next) {

                    next(new Error('fn3'));
                }
            };

            Items.parallel.execute(fns, function (err, result) {

                expect(err).to.exist;
                expect(result).to.not.exist;
                expect(err.message).to.equal('fn1');
                done();
            });
        });
    });
});