text:
FROM biocontainers/biocontainers:vdebian-buster-backports_cv1
MAINTAINER biocontainers <biodocker@gmail.com>
LABEL    software="maqview" \
    base_image="biocontainers/biocontainers:vdebian-buster-backports_cv1" \
    container="maqview" \
    about.summary="graphical read alignment viewer for short gene sequences" \
    about.home="http://maq.sourceforge.net/maqview.shtml" \
    software.version="0.2.5-9-deb" \
    upstream.version="0.2.5" \
    version="1" \
    extra.identifiers.biotools="maqview" \
    about.copyright="2007-2008, Jue Ruan <ruanjue@genomics.org.cn>" \
    about.license="GPL-2" \
    about.license_file="/usr/share/doc/maqview/copyright" \
    extra.binaries="/usr/bin/maqindex,/usr/bin/maqindex_socks,/usr/bin/maqview,/usr/bin/zrio" \
    about.tags=""

USER root
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update && (apt-get install -t buster-backports -y maqview || apt-get install -y maqview) && apt-get clean && apt-get purge && rm -rf /var/lib/apt/lists/* /tmp/*
USER biodocker


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Nextier</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="css/universal.css" rel="stylesheet">

    <link href="css/work-projects.css" rel="stylesheet">

    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">

        NEXTIER
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">

        </button>

              Home

              About

              Work

              Contact

Application Development

RedeemerCDC

Redeemer Lutheran Child Development Center underwent a major construction project that increased Redeemer's capacity from 95-student enrollment to 160, and expanded the curriculum to include 6-week-olds to age 13. The expansion of the property is monumental and Redeemer sought after an app to pair with their growing environment.

            The objective of the Redeemer Lutheran Child Development Center mobile application is to provide the parents with an informative and valuable app to supplement their relationship with Redeemer. After understanding Redeemer's needs, Nextier got to work.

            The first step was understanding the needs of the parents. After conducting a survey with 58 responses, the parents and staff were able to provide feedback for desired features and sign up to join our Beta Testing Program. Once the app was ready to test, Nextier created effective communication materials to encourage enrollment in our Beta Testing Program, including a step-by-step guide for anyone needing assistance. The app was completed in August 2017 and included features like social media integration, form submission, and upcoming event information.

Visit the website:

            www.redeemercdc.org

              <address id="address-style">

10 E. Franklin Street

Suite 500

Richmond, Virginia 23219

 Careers

              </address>

NEXTIER

              (804) 729-8650

              info@nextiergroup.com

              CONTACT US

Copyright © Nextier 2017

redpajama_set_name: RedPajamaGithub


text:
package virtualmachineimage

import (
	"encoding/xml"
	"testing"
)

const xml1 = `
<VMImage>
	<Name>imgName</Name>
	PackerMade_Ubuntu_Serv14
	<Category>User</Category>
	<Description>packer made image</Description>
	<OSDiskConfiguration>
		<Name>OSDisk</Name>
		<HostCaching>ReadWrite</HostCaching>
		<OSState>Generalized</OSState>
		<OS>Linux</OS>
		<MediaLink>https://sa.blob.core.windows.net/images/PackerMade_Ubuntu_Serv14_2015-12-12.vhd</MediaLink>
		<LogicalDiskSizeInGB>30</LogicalDiskSizeInGB>
		<IOType>Standard</IOType>
	</OSDiskConfiguration>
	<DataDiskConfigurations/>
	<ServiceName>PkrSrvf3mz03u4mi</ServiceName>
	<DeploymentName>PkrVMf3mz03u4mi</DeploymentName>
	<RoleName>PkrVMf3mz03u4mi</RoleName>
	<Location>Central US</Location>
	<CreatedTime>2015-12-12T08:59:29.1936858Z</CreatedTime>
	<ModifiedTime>2015-12-12T08:59:29.1936858Z</ModifiedTime>
	<ImageFamily>PackerMade</ImageFamily>
	<RecommendedVMSize>Small</RecommendedVMSize>
	<IsPremium>false</IsPremium>
	<VMImageState>VMImageReadyForUse</VMImageState>
	<RoleStateOnCapture>StoppedVM</RoleStateOnCapture>
	<RoleSizeOnCapture>Small</RoleSizeOnCapture>
</VMImage>`
const xml2 = `
<VMImage>
	<Name>imgName</Name>
	PackerMade_Ubuntu_Serv14
	<Category>User</Category>
	<Description>packer made image</Description>
	<OSDiskConfiguration>
		<Name>OSDisk</Name>
		<HostCaching>ReadWrite</HostCaching>
		<OSState>Generalized</OSState>
		<OS>Linux</OS>
		<MediaLink>https://sa.blob.core.windows.net/images/PackerMade_Ubuntu_Serv14_2015-12-12.vhd</MediaLink>
		<LogicalDiskSizeInGB>30</LogicalDiskSizeInGB>
		<IOType>Standard</IOType>
	</OSDiskConfiguration>
	<DataDiskConfigurations>
		<DataDiskConfiguration>
			<Name>DataDisk1</Name>
			<HostCaching>ReadWrite</HostCaching>
			<MediaLink>https://sa.blob.core.windows.net/images/PackerMade_Ubuntu_Serv14_2015-12-12-dd1.vhd</MediaLink>
			<LogicalDiskSizeInGB>31</LogicalDiskSizeInGB>
			<IOType>Standard</IOType>
		</DataDiskConfiguration>
		<DataDiskConfiguration>
			<Name>DataDisk2</Name>
			<HostCaching>ReadWrite</HostCaching>
			<MediaLink>https://sa.blob.core.windows.net/images/PackerMade_Ubuntu_Serv14_2015-12-12-dd2.vhd</MediaLink>
			<LogicalDiskSizeInGB>32</LogicalDiskSizeInGB>
			<IOType>Standard</IOType>
		</DataDiskConfiguration>
	</DataDiskConfigurations>
	<ServiceName>PkrSrvf3mz03u4mi</ServiceName>
	<DeploymentName>PkrVMf3mz03u4mi</DeploymentName>
	<RoleName>PkrVMf3mz03u4mi</RoleName>
	<Location>Central US</Location>
	<CreatedTime>2015-12-12T08:59:29.1936858Z</CreatedTime>
	<ModifiedTime>2015-12-12T08:59:29.1936858Z</ModifiedTime>
	<ImageFamily>PackerMade</ImageFamily>
	<RecommendedVMSize>Small</RecommendedVMSize>
	<IsPremium>false</IsPremium>
	<VMImageState>VMImageReadyForUse</VMImageState>
	<RoleStateOnCapture>StoppedVM</RoleStateOnCapture>
	<RoleSizeOnCapture>Small</RoleSizeOnCapture>
</VMImage>`

func Test_NoDataDisksUnmarshal(t *testing.T) {
	var image VMImage
	if err := xml.Unmarshal([]byte(xml1), &image); err != nil {
		t.Fatal(err)
	}

	check := checker{t}
	check.Equal(0, len(image.DataDiskConfigurations))
}

func Test_DataDiskCountUnmarshal(t *testing.T) {
	var image VMImage
	if err := xml.Unmarshal([]byte(xml2), &image); err != nil {
		t.Fatal(err)
	}

	check := checker{t}
	check.Equal(2, len(image.DataDiskConfigurations))
	check.Equal("DataDisk1", image.DataDiskConfigurations[0].Name)
	check.Equal("DataDisk2", image.DataDiskConfigurations[1].Name)
}

type checker struct{ *testing.T }

func (a *checker) Equal(expected, actual interface{}) {
	if expected != actual {
		a.T.Fatalf("Expected %q, but got %q", expected, actual)
	}
}


text:
package org.jetbrains.jps.javac;

import com.intellij.openapi.util.io.FileUtilRt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.PathUtils;
import org.jetbrains.jps.builders.java.JavaSourceTransformer;

import javax.tools.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.*;

/**
 * @author Eugene Zhuravlev
 */
class JavacFileManager extends ForwardingJavaFileManager<StandardJavaFileManager> implements StandardJavaFileManager{

  private final Context myContext;
  private final Collection<JavaSourceTransformer> mySourceTransformers;
  private Map<File, Set<File>> myOutputsMap = Collections.emptyMap();
  @Nullable
  private String myEncodingName;

  interface Context {
    boolean isCanceled();

    StandardJavaFileManager getStandardFileManager();

    void consumeOutputFile(@NotNull OutputFileObject obj);

    void reportMessage(final Diagnostic.Kind kind, String message);
  }

  public JavacFileManager(Context context, Collection<JavaSourceTransformer> transformers) {
    super(context.getStandardFileManager());
    myContext = context;
    mySourceTransformers = transformers;
  }

  public void setOutputDirectories(final Map<File, Set<File>> outputDirToSrcRoots) throws IOException{
    for (File outputDir : outputDirToSrcRoots.keySet()) {
      // this will validate output dirs
      setLocation(StandardLocation.CLASS_OUTPUT, Collections.singleton(outputDir));
    }
    myOutputsMap = outputDirToSrcRoots;
  }

  @Override
  public boolean handleOption(String current, final Iterator<String> remaining) {
    if ("-encoding".equalsIgnoreCase(current) && remaining.hasNext()) {
      final String encoding = remaining.next();
      myEncodingName = encoding;
      return super.handleOption(current, new Iterator<String>() {
        private boolean encodingConsumed = false;
        @Override
        public boolean hasNext() {
          return !encodingConsumed || remaining.hasNext();
        }

        @Override
        public String next() {
          if (!encodingConsumed) {
            encodingConsumed = true;
            return encoding;
          }
          return remaining.next();
        }

        @Override
        public void remove() {
          if (encodingConsumed) {
            remaining.remove();
          }
        }
      });
    }
    return super.handleOption(current, remaining);
  }

  @Override
  public String inferBinaryName(Location location, JavaFileObject file) {
    return super.inferBinaryName(location, unwrapFileObject(file));
  }

  public void setLocation(Location location, Iterable<? extends File> path) throws IOException{
    getStdManager().setLocation(location, path);
  }

  public Iterable<? extends JavaFileObject> getJavaFileObjectsFromFiles(Iterable<? extends File> files) {
    return wrapJavaFileObjects(getStdManager().getJavaFileObjectsFromFiles(files));
  }

  public Iterable<? extends JavaFileObject> getJavaFileObjects(File... files) {
    return wrapJavaFileObjects(getStdManager().getJavaFileObjects(files));
  }

  public Iterable<? extends JavaFileObject> getJavaFileObjectsFromStrings(Iterable<String> names) {
    return wrapJavaFileObjects(getStdManager().getJavaFileObjectsFromStrings(names));
  }

  public Iterable<? extends JavaFileObject> getJavaFileObjects(String... names) {
    return wrapJavaFileObjects(getStdManager().getJavaFileObjects(names));
  }

  public Iterable<? extends File> getLocation(Location location) {
    return getStdManager().getLocation(location);
  }

  public boolean isSameFile(FileObject a, FileObject b) {
    if (a instanceof OutputFileObject || b instanceof OutputFileObject) {
      return a.equals(b);
    }
    return super.isSameFile(unwrapFileObject(a), unwrapFileObject(b));
  }

  private static FileObject unwrapFileObject(FileObject a) {
    return a instanceof TransformableJavaFileObject ? ((TransformableJavaFileObject)a).getOriginal() : a;
  }

  private static JavaFileObject unwrapFileObject(JavaFileObject a) {
    return a instanceof TransformableJavaFileObject ? ((TransformableJavaFileObject)a).getOriginal() : a;
  }

  @Override
  public FileObject getFileForInput(Location location, String packageName, String relativeName) throws IOException {
    checkCanceled();
    final FileObject fo = super.getFileForInput(location, packageName, relativeName);
    if (fo == null) {
      // workaround javac bug (missing null-check): throwing exception here instead of returning null
      throw new FileNotFoundException("Resource does not exist : " + location + '/' + packageName + '/' + relativeName);
    }
    return fo;
  }

  @Override
  public Iterable<JavaFileObject> list(Location location, String packageName, Set<JavaFileObject.Kind> kinds, boolean recurse) throws IOException {
    final Iterable<JavaFileObject> objects = super.list(location, packageName, kinds, recurse);
    //noinspection unchecked
    return kinds.contains(JavaFileObject.Kind.SOURCE)? (Iterable<JavaFileObject>)wrapJavaFileObjects(objects) : objects;
  }

  private Iterable<? extends JavaFileObject> wrapJavaFileObjects(Iterable<? extends JavaFileObject> originalObjects) {
    if (mySourceTransformers.isEmpty()) {
      return originalObjects;
    }
    List<JavaFileObject> wrapped = null;
    for (JavaFileObject fo : originalObjects) {
      if (wrapped == null) {
        wrapped = new ArrayList<JavaFileObject>(); // lazy init
      }
      wrapped.add(JavaFileObject.Kind.SOURCE.equals(fo.getKind())? new TransformableJavaFileObject(fo, mySourceTransformers) : fo);
    }
    return wrapped != null? wrapped : originalObjects;
  }

  @Override
  public JavaFileObject getJavaFileForInput(Location location, String className, JavaFileObject.Kind kind) throws IOException {
    checkCanceled();
    final JavaFileObject fo = super.getJavaFileForInput(location, className, kind);
    if (fo == null && !"module-info".equals(className)) {
      // workaround javac bug (missing null-check): throwing exception here instead of returning null
      throw new FileNotFoundException("Java resource does not exist : " + location + '/' + kind + '/' + className);
    }
    return mySourceTransformers.isEmpty()? fo : new TransformableJavaFileObject(fo, mySourceTransformers);
  }

  public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling) throws IOException {
    if (kind != JavaFileObject.Kind.SOURCE && kind != JavaFileObject.Kind.CLASS) {
      throw new IllegalArgumentException("Invalid kind " + kind);
    }
    return getFileForOutput(location, kind, externalizeFileName(className, kind), className, sibling);
  }

  public FileObject getFileForOutput(Location location, String packageName, String relativeName, FileObject sibling) throws IOException {
    final StringBuilder name = new StringBuilder();
    if (packageName.isEmpty()) {
      name.append(relativeName);
    }
    else {
      name.append(externalizeFileName(packageName)).append(File.separatorChar).append(relativeName);
    }
    final String fileName = name.toString();
    return getFileForOutput(location, getKind(fileName), fileName, null, sibling);
  }

  private OutputFileObject getFileForOutput(Location location, JavaFileObject.Kind kind, String fileName, @Nullable String className, FileObject sibling) throws IOException {
    checkCanceled();

    JavaFileObject src = null;
    if (sibling instanceof JavaFileObject) {
      final JavaFileObject javaFileObject = (JavaFileObject)sibling;
      if (javaFileObject.getKind() == JavaFileObject.Kind.SOURCE) {
        src = javaFileObject;
      }
    }

    File dir = getSingleOutputDirectory(location, src);

    if (location == StandardLocation.CLASS_OUTPUT) {
      if (dir == null) {
        throw new IOException("Output directory is not specified");
      }
    }
    else if (location == StandardLocation.SOURCE_OUTPUT) {
      if (dir == null) {
        dir = getSingleOutputDirectory(StandardLocation.CLASS_OUTPUT, src);
        if (dir == null) {
          throw new IOException("Neither class output directory nor source output are specified");
        }
      }
    }
    final File file = (dir == null? new File(fileName).getAbsoluteFile() : new File(dir, fileName));
    return new OutputFileObject(myContext, dir, fileName, file, kind, className, src != null? src.toUri() : null, myEncodingName);
  }

  @Override
  public ClassLoader getClassLoader(Location location) {
    final Iterable<? extends File> path = getLocation(location);
    if (path == null) {
      return null;
    }
    final List<URL> urls = new ArrayList<URL>();
    for (File f: path) {
      try {
        urls.add(f.toURI().toURL());
      }
      catch (MalformedURLException e) {
        throw new AssertionError(e);
      }
    }
    // ensure processor's loader will not resolve against JPS classes and libraries used in JPS
    return new URLClassLoader(urls.toArray(new URL[0]), myContext.getStandardFileManager().getClass().getClassLoader());
  }

  private File getSingleOutputDirectory(final Location loc, final JavaFileObject sourceFile) {
    if (loc == StandardLocation.CLASS_OUTPUT) {
      if (myOutputsMap.size() > 1 && sourceFile != null) {
        // multiple outputs case
        final File outputDir = findOutputDir(PathUtils.convertToFile(sourceFile.toUri()));
        if (outputDir != null) {
          return outputDir;
        }
      }
    }

    final Iterable<? extends File> location = getStdManager().getLocation(loc);
    if (location != null) {
      final Iterator<? extends File> it = location.iterator();
      if (it.hasNext()) {
        return it.next();
      }
    }
    return null;
  }

  private File findOutputDir(File src) {
    File file = FileUtilRt.getParentFile(src);
    while (file != null) {
      for (Map.Entry<File, Set<File>> entry : myOutputsMap.entrySet()) {
        if (entry.getValue().contains(file)) {
          return entry.getKey();
        }
      }
      file = FileUtilRt.getParentFile(file);
    }
    return null;
  }

  @NotNull
  private StandardJavaFileManager getStdManager() {
    return fileManager;
  }

  @Override
  public void close() {
    try {
      super.close();
    }
    catch (IOException e) {
      throw new RuntimeException(e);
    }
    finally {
      myOutputsMap = Collections.emptyMap();
    }
  }

  private static JavaFileObject.Kind getKind(String name) {
    if (name.endsWith(JavaFileObject.Kind.CLASS.extension)){
      return JavaFileObject.Kind.CLASS;
    }
    if (name.endsWith(JavaFileObject.Kind.SOURCE.extension)) {
      return JavaFileObject.Kind.SOURCE;
    }
    if (name.endsWith(JavaFileObject.Kind.HTML.extension)) {
      return JavaFileObject.Kind.HTML;
    }
    return JavaFileObject.Kind.OTHER;
  }

  private static String externalizeFileName(CharSequence cs, JavaFileObject.Kind kind) {
    return externalizeFileName(cs) + kind.extension;
  }

  private static String externalizeFileName(CharSequence name) {
    return name.toString().replace('.', File.separatorChar);
  }

  private int myChecksCounter = 0;

  private void checkCanceled() {
    final int counter = (myChecksCounter + 1) % 10;
    myChecksCounter = counter;
    if (counter == 0 && myContext.isCanceled()) {
      throw new CompilationCanceledException();
    }
  }

  public Context getContext() {
    return myContext;
  }

  private static Map<Method, Boolean> ourImplStatus = Collections.synchronizedMap(new HashMap<Method, Boolean>());

  JavaFileManager getApiCallHandler(Method method) {
    Boolean isImplemented = ourImplStatus.get(method);
    if (isImplemented == null) {
      try {
        JavacFileManager.class.getDeclaredMethod(method.getName(), method.getParameterTypes());
        isImplemented = Boolean.TRUE;
      }
      catch (NoSuchMethodException e) {
        isImplemented = Boolean.FALSE;
      }
      ourImplStatus.put(method, isImplemented);
    }
    return isImplemented? this : getStdManager();
  }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

//
/*=============================================================================
**
**
**
** Purpose: Synchronizes access to a shared resource or region of code in a multi-threaded
**             program.
**
**
=============================================================================*/

using System.Runtime.CompilerServices;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Diagnostics.CodeAnalysis;

namespace System.Threading
{
    public static class Monitor
    {
        /*=========================================================================
        ** Obtain the monitor lock of obj. Will block if another thread holds the lock
        ** Will not block if the current thread holds the lock,
        ** however the caller must ensure that the same number of Exit
        ** calls are made as there were Enter calls.
        **
        ** Exceptions: ArgumentNullException if object is null.
        =========================================================================*/
        [MethodImpl(MethodImplOptions.InternalCall)]
        public static extern void Enter(object obj);

        // Use a ref bool instead of out to ensure that unverifiable code must
        // initialize this value to something.  If we used out, the value
        // could be uninitialized if we threw an exception in our prolog.
        // The JIT should inline this method to allow check of lockTaken argument to be optimized out
        // in the typical case. Note that the method has to be transparent for inlining to be allowed by the VM.
        public static void Enter(object obj, ref bool lockTaken)
        {
            if (lockTaken)
                ThrowLockTakenException();

            ReliableEnter(obj, ref lockTaken);
            Debug.Assert(lockTaken);
        }

        [DoesNotReturn]
        private static void ThrowLockTakenException()
        {
            throw new ArgumentException(SR.Argument_MustBeFalse, "lockTaken");
        }

        [MethodImpl(MethodImplOptions.InternalCall)]
        private static extern void ReliableEnter(object obj, ref bool lockTaken);

        /*=========================================================================
        ** Release the monitor lock. If one or more threads are waiting to acquire the
        ** lock, and the current thread has executed as many Exits as
        ** Enters, one of the threads will be unblocked and allowed to proceed.
        **
        ** Exceptions: ArgumentNullException if object is null.
        **             SynchronizationLockException if the current thread does not
        **             own the lock.
        =========================================================================*/
        [MethodImpl(MethodImplOptions.InternalCall)]
        public static extern void Exit(object obj);

        /*=========================================================================
        ** Similar to Enter, but will never block. That is, if the current thread can
        ** acquire the monitor lock without blocking, it will do so and TRUE will
        ** be returned. Otherwise FALSE will be returned.
        **
        ** Exceptions: ArgumentNullException if object is null.
        =========================================================================*/
        public static bool TryEnter(object obj)
        {
            bool lockTaken = false;
            TryEnter(obj, 0, ref lockTaken);
            return lockTaken;
        }

        // The JIT should inline this method to allow check of lockTaken argument to be optimized out
        // in the typical case. Note that the method has to be transparent for inlining to be allowed by the VM.
        public static void TryEnter(object obj, ref bool lockTaken)
        {
            if (lockTaken)
                ThrowLockTakenException();

            ReliableEnterTimeout(obj, 0, ref lockTaken);
        }

        /*=========================================================================
        ** Version of TryEnter that will block, but only up to a timeout period
        ** expressed in milliseconds. If timeout == Timeout.Infinite the method
        ** becomes equivalent to Enter.
        **
        ** Exceptions: ArgumentNullException if object is null.
        **             ArgumentException if timeout < -1 (Timeout.Infinite).
        =========================================================================*/
        // The JIT should inline this method to allow check of lockTaken argument to be optimized out
        // in the typical case. Note that the method has to be transparent for inlining to be allowed by the VM.
        public static bool TryEnter(object obj, int millisecondsTimeout)
        {
            bool lockTaken = false;
            TryEnter(obj, millisecondsTimeout, ref lockTaken);
            return lockTaken;
        }

        private static int MillisecondsTimeoutFromTimeSpan(TimeSpan timeout)
        {
            long tm = (long)timeout.TotalMilliseconds;
            if (tm < -1 || tm > (long)int.MaxValue)
                throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
            return (int)tm;
        }

        public static bool TryEnter(object obj, TimeSpan timeout)
        {
            return TryEnter(obj, MillisecondsTimeoutFromTimeSpan(timeout));
        }

        // The JIT should inline this method to allow check of lockTaken argument to be optimized out
        // in the typical case. Note that the method has to be transparent for inlining to be allowed by the VM.
        public static void TryEnter(object obj, int millisecondsTimeout, ref bool lockTaken)
        {
            if (lockTaken)
                ThrowLockTakenException();

            ReliableEnterTimeout(obj, millisecondsTimeout, ref lockTaken);
        }

        public static void TryEnter(object obj, TimeSpan timeout, ref bool lockTaken)
        {
            if (lockTaken)
                ThrowLockTakenException();

            ReliableEnterTimeout(obj, MillisecondsTimeoutFromTimeSpan(timeout), ref lockTaken);
        }

        [MethodImpl(MethodImplOptions.InternalCall)]
        private static extern void ReliableEnterTimeout(object obj, int timeout, ref bool lockTaken);

        public static bool IsEntered(object obj)
        {
            if (obj == null)
                throw new ArgumentNullException(nameof(obj));

            return IsEnteredNative(obj);
        }

        [MethodImpl(MethodImplOptions.InternalCall)]
        private static extern bool IsEnteredNative(object obj);

        /*========================================================================
    ** Waits for notification from the object (via a Pulse/PulseAll).
    ** timeout indicates how long to wait before the method returns.
    ** This method acquires the monitor waithandle for the object
    ** If this thread holds the monitor lock for the object, it releases it.
    ** On exit from the method, it obtains the monitor lock back.
    ** If exitContext is true then the synchronization domain for the context
    ** (if in a synchronized context) is exited before the wait and reacquired
    **
        ** Exceptions: ArgumentNullException if object is null.
    ========================================================================*/
        [MethodImpl(MethodImplOptions.InternalCall)]
        private static extern bool ObjWait(bool exitContext, int millisecondsTimeout, object obj);

        public static bool Wait(object obj, int millisecondsTimeout, bool exitContext)
        {
            if (obj == null)
                throw (new ArgumentNullException(nameof(obj)));
            return ObjWait(exitContext, millisecondsTimeout, obj);
        }

        public static bool Wait(object obj, TimeSpan timeout, bool exitContext)
        {
            return Wait(obj, MillisecondsTimeoutFromTimeSpan(timeout), exitContext);
        }

        public static bool Wait(object obj, int millisecondsTimeout)
        {
            return Wait(obj, millisecondsTimeout, false);
        }

        public static bool Wait(object obj, TimeSpan timeout)
        {
            return Wait(obj, MillisecondsTimeoutFromTimeSpan(timeout), false);
        }

        public static bool Wait(object obj)
        {
            return Wait(obj, Timeout.Infinite, false);
        }

        /*========================================================================
        ** Sends a notification to a single waiting object.
        * Exceptions: SynchronizationLockException if this method is not called inside
        * a synchronized block of code.
        ========================================================================*/
        [MethodImpl(MethodImplOptions.InternalCall)]
        private static extern void ObjPulse(object obj);

        public static void Pulse(object obj)
        {
            if (obj == null)
            {
                throw new ArgumentNullException(nameof(obj));
            }

            ObjPulse(obj);
        }
        /*========================================================================
        ** Sends a notification to all waiting objects.
        ========================================================================*/
        [MethodImpl(MethodImplOptions.InternalCall)]
        private static extern void ObjPulseAll(object obj);

        public static void PulseAll(object obj)
        {
            if (obj == null)
            {
                throw new ArgumentNullException(nameof(obj));
            }

            ObjPulseAll(obj);
        }

        /// <summary>
        /// Gets the number of times there was contention upon trying to take a <see cref="Monitor"/>'s lock so far.
        /// </summary>
        public static long LockContentionCount => GetLockContentionCount();

        [DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
        private static extern long GetLockContentionCount();
    }
}


text:
HmdDriver::HmdDriver(vr::IServerDriverHost * pDriverHost) :
  DeviceDriver(pDriverHost)
{
  serialNumber = "CogsVR1";
  modelNumber = "Cogs Virtual HMD";

  windowX = 100;
  windowY = 100;
  windowWidth = 1920;
  windowHeight = 1080;
  renderWidth = 1344;
  renderHeight = 1512;
  secondsFromVsyncToPhotons = 0.01111111f;
  displayFrequency = 90.0;
  ipd = 0.065f;
}

EVRInitError HmdDriver::Activate(uint32_t unObjectId)
{
  logTrace("HmdDriver::Activate()");

  objectId = unObjectId;

  return VRInitError_None;
}

void HmdDriver::RunFrame()
{
  logTrace("HmdDriver::RunFrame()");

  if (objectId != vr::k_unTrackedDeviceIndexInvalid) {
    host->TrackedDevicePoseUpdated(objectId, GetPose());
  }
}

void HmdDriver::Deactivate()
{
  logTrace("HmdDriver::Deactivate()");

  objectId = vr::k_unTrackedDeviceIndexInvalid;
}

void HmdDriver::EnterStandby()
{
  logTrace("HmdDriver::EnterStandby()");
}

void * HmdDriver::GetComponent(const char * pchComponentNameAndVersion)
{
  logTrace("HmdDriver::GetComponent()");

  if (!_stricmp(pchComponentNameAndVersion, vr::IVRDisplayComponent_Version))
  {
    return (vr::IVRDisplayComponent*)this;
  }

  return nullptr;
}

void HmdDriver::DebugRequest(const char * pchRequest, char * pchResponseBuffer, uint32_t unResponseBufferSize)
{
  logTrace("HmdDriver::DebugRequest()");
}

bool HmdDriver::GetBoolTrackedDeviceProperty(ETrackedDeviceProperty prop, ETrackedPropertyError * pError)
{
  *pError = vr::TrackedProp_Success;

  switch (prop)
  {
  case vr::Prop_IsOnDesktop_Bool:
    // Avoid "not fullscreen" warnings from vrmonitor
    return false;
  }

  *pError = vr::TrackedProp_ValueNotProvidedByDevice;

  return false;
}

float HmdDriver::GetFloatTrackedDeviceProperty(ETrackedDeviceProperty prop, ETrackedPropertyError * pError)
{
  logTrace("HmdDriver::GetFloatTrackedDeviceProperty(%d)", prop);

  vr::ETrackedPropertyError error = vr::TrackedProp_ValueNotProvidedByDevice;
  float fRetVal = 0;
  switch (prop)
  {
  case vr::Prop_UserIpdMeters_Float:
    fRetVal = ipd;
    error = TrackedProp_Success;
    break;

  case vr::Prop_UserHeadToEyeDepthMeters_Float:
    error = vr::TrackedProp_Success;
    fRetVal = 0.f;
    break;

  case vr::Prop_DisplayFrequency_Float:
    error = vr::TrackedProp_Success;
    fRetVal = displayFrequency;
    break;

  case vr::Prop_SecondsFromVsyncToPhotons_Float:
    error = vr::TrackedProp_Success;
    fRetVal = secondsFromVsyncToPhotons;
    break;

  }

  if (pError)
  {
    *pError = error;
  }

  return fRetVal;
}

int32_t HmdDriver::GetInt32TrackedDeviceProperty(ETrackedDeviceProperty prop, ETrackedPropertyError * pError)
{
  int32_t nRetVal = 0;
  vr::ETrackedPropertyError error = vr::TrackedProp_UnknownProperty;

  switch (prop)
  {
  case vr::Prop_DeviceClass_Int32:
    nRetVal = vr::TrackedDeviceClass_HMD;
    error = vr::TrackedProp_Success;
    break;
  }

  if (pError)
  {
    *pError = error;
  }

  return nRetVal;
}

uint64_t HmdDriver::GetUint64TrackedDeviceProperty(ETrackedDeviceProperty prop, ETrackedPropertyError * pError)
{
  *pError = vr::TrackedProp_Success;

  switch (prop)
  {
  case vr::Prop_CurrentUniverseId_Uint64:
    // return a constant that's not 0 (invalid) or 1 (reserved for Oculus)
    return 2;
  }

  *pError = vr::TrackedProp_ValueNotProvidedByDevice;
  return 0;
}

HmdMatrix34_t HmdDriver::GetMatrix34TrackedDeviceProperty(ETrackedDeviceProperty prop, ETrackedPropertyError * pError)
{
  *pError = vr::TrackedProp_ValueNotProvidedByDevice;
  HmdMatrix34_t matIdentity;
  HmdMatrix_SetIdentity(&matIdentity);
  return matIdentity;
}

uint32_t HmdDriver::GetStringTrackedDeviceProperty(ETrackedDeviceProperty prop, char * pchValue, uint32_t unBufferSize, ETrackedPropertyError * pError)
{
  std::string sValue = GetStringTrackedDeviceProperty(prop, pError);

  if (*pError == vr::TrackedProp_Success) {
    if (sValue.size() + 1 > unBufferSize) {
      *pError = vr::TrackedProp_BufferTooSmall;
    } else {
      strcpy_s(pchValue, unBufferSize, sValue.c_str());
    }

    return (uint32_t)sValue.size() + 1;
  }

  return 0;
}

std::string HmdDriver::GetStringTrackedDeviceProperty(vr::ETrackedDeviceProperty prop, vr::ETrackedPropertyError * pError)
{
  *pError = vr::TrackedProp_ValueNotProvidedByDevice;
  std::string sRetVal;

  switch (prop) {
  case vr::Prop_ModelNumber_String:
    sRetVal = modelNumber;
    *pError = vr::TrackedProp_Success;
    break;

  case vr::Prop_SerialNumber_String:
    sRetVal = serialNumber;
    *pError = vr::TrackedProp_Success;
    break;
  }

  return sRetVal;
}

void HmdDriver::GetWindowBounds(int32_t * pnX, int32_t * pnY, uint32_t * pnWidth, uint32_t * pnHeight)
{
  *pnX = windowX;
  *pnY = windowY;
  *pnWidth = windowWidth;
  *pnHeight = windowHeight;
}

void HmdDriver::GetRecommendedRenderTargetSize(uint32_t * pnWidth, uint32_t * pnHeight)
{
  *pnWidth = renderWidth;
  *pnHeight = renderHeight;
}

void HmdDriver::GetEyeOutputViewport(EVREye eEye, uint32_t * pnX, uint32_t * pnY, uint32_t * pnWidth, uint32_t * pnHeight)
{
  *pnY = 0;
  *pnWidth = windowWidth / 2;
  *pnHeight = windowHeight;

  if (eEye == Eye_Left) {
    *pnX = 0;
  } else {
    *pnX = windowWidth / 2;
  }
}

void HmdDriver::GetProjectionRaw(EVREye eEye, float * pfLeft, float * pfRight, float * pfTop, float * pfBottom)
{
  *pfLeft = -1.0;
  *pfRight = 1.0;
  *pfTop = -1.0;
  *pfBottom = 1.0;
}

DistortionCoordinates_t HmdDriver::ComputeDistortion(EVREye eEye, float fU, float fV)
{
  DistortionCoordinates_t coordinates = {};
  coordinates.rfBlue[0] = fU;
  coordinates.rfBlue[1] = fV;
  coordinates.rfGreen[0] = fU;
  coordinates.rfGreen[1] = fV;
  coordinates.rfRed[0] = fU;
  coordinates.rfRed[1] = fV;
  return coordinates;
}

DriverPose_t HmdDriver::GetPose()
{
  DriverPose_t pose = {};
  pose.poseIsValid = true;
  pose.result = TrackingResult_Running_OK;
  pose.deviceIsConnected = true;

  auto t = timer.elapsedSeconds();

  glm::quat headRotation = glm::angleAxis(glm::sin((float)t * 0.5f) * 0.3f, glm::vec3(0, 1, 0)) *
    glm::angleAxis(-0.2f + glm::sin((float)t * 0.3f) * 0.1f, glm::vec3(1, 0, 0));

  pose.qRotation = toHmd(headRotation);

  pose.qWorldFromDriverRotation = toHmd(glm::quat());
  pose.qDriverFromHeadRotation = toHmd(glm::quat());

  if (!hasMessage) {
    pose.vecPosition[0] = 0.1 * sin(t * 1.76);
  } else {
    pose.vecPosition[0] = message.position.x;
  }

  pose.vecPosition[1] = 1.8 + 0.1 * sin(t * 0.2);
  pose.vecPosition[2] = 0;

  return pose;
}


text:
/**
 * Packaging utilities.
 */
@aQute.bnd.annotation.Version("1.8.1")
package com.adobe.acs.commons.packaging;


text:
<tru-label label="{{label}}" field="field">
    <input data-ng-model="field.value.$"
           data-ng-disabled="!field.editor.isEditing || !field.type.canEdit"
           maxlength="{{field.type.property.maxLength}}"
           data-ng-trim="false"
           data-z-validate
           type="text"
           />
</tru-label>


text:
/* @test
   @bug 4098742
   @summary Test biginteger modpow method
   @author Michael McCloskey
   @run main/othervm ModPowPowersof2
*/

import java.math.BigInteger;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.File;
import java.io.IOException;

/**
 * This class tests to see if using modPow on a power
 * of two crashes the vm
 *
 */
public class ModPowPowersof2 {

      public static void main(String args[]) throws Exception {
          // Construct a command that runs the test in other vm
          String[] command = new String[4];
          int n = 0;

          command[n++] = System.getProperty("java.home") + File.separator +
              "bin" + File.separator + "java";
          if (System.getProperty("java.class.path") != null) {
              command[n++] = "-classpath";
              command[n++] = System.getProperty("java.class.path");
          }

          command[n++] = "ModPowPowersof2$ModTester";

          // Exec another vm to run test in
          Process p = null;
          p = Runtime.getRuntime().exec(command);

          // Read the result to determine if test failed
          BufferedReader in = new BufferedReader(new InputStreamReader(
                                             p.getInputStream()));
          String s;
          s = in.readLine();
          if (s == null)
              throw new RuntimeException("ModPow causes vm crash");

     }

    public static class ModTester {
        public static void main(String [] args) {
            BigInteger two = BigInteger.valueOf(2);
            BigInteger four = BigInteger.valueOf(4);

            two.modPow(two, BigInteger.valueOf(4));
            two.modPow(two, BigInteger.valueOf(8));
            two.modPow(four, BigInteger.valueOf(8));

            System.out.println("success");
        }
    }

}


text:
Puts prints something out to the console with a new line. It also returns nil.

## What is an integer? What is a float?

An integer is a whole number, without a decimal. A float is number with a decimal.

## What is the difference between float and integer division? How would you explain the difference to someone who doesn't know anything about programming?

Integers are whole numbers. When dealing with integer division, the computer only sees integers and can only produce an integer. That means the computer can only return the integer value. This becomes a problem if you are dividing two numbers, say 3 and 2, that cannot result in an integer. In this case, the computer returns the nearest integer rounded down. For 3 / 2, that would be 1.

For float division, the computer would see 3.0 and 2.0. The computer now understands past that decimal point! That means, when the computer divides 3.0 / 2.0, it can include the 5 for 1.5.

## Calculate the number of hours in a year
```
valueNotEntered = true;

while valueNotEntered do
  puts "Is it a leap year? Y/N"
  isLeapYear = gets.chomp

  if isLeapYear == "N"
    puts "There are #{365*24} hours in a year."
    valueNotEntered = false;
  elsif isLeapYear == "Y"
    puts "There are #{366*24} hours in a leap year."
    valueNotEntered = false;
  else
    puts "Invalid input. Answer must be Y/N. Is it a leap year? Y/N"
  end
end
```

## How does Ruby handle addition, subtraction, multiplication, and division of numbers?

Ruby

## What is the difference between integers and floats?

Integers are whole numbers. Floats have decimals.

## What is the difference between integer and float division?

Integer division returns only integers, and rounds down to the nearest integer if the technical answer is a float. Float division can return a number with as many decimal values as the programmer allows!

## What are strings? Why and when would you use them?

Strings are characters strung together. You cannot use strings for math, although math can sometimes be used on strings. (e.g. puts "multiply me by 5" * 5 would result in "multiply me by 5" displayed 5 times.) You use strings a lot as output!

## What are local variables? Why and when would you use them?

Local variables are identified as something assigned to point at a value, whether that be an integer, float, string, or boolean. You use variables when you have a value being used more than once.

## How was this challenge? Did you get a good review of some of the basics?

This challenge was useful for reviewing the basics!


text:
using System;
using Arch.CMessaging.Client.Core.Ioc;

namespace Arch.CMessaging.Client.Consumer.Engine.Bootstrap.Strategy
{
    [Named(ServiceType = typeof(IConsumingStrategy), ServiceName = "STRICTLY_ORDERING")]
    public class StrictlyOrderedConsumingStrategy : BaseConsumingStrategy
    {
        protected override IConsumerTask GetConsumerTask(ConsumerContext context, int partitionId, int localCacheSize)
        {
            return new StrictlyOrderedConsumingStrategyConsumerTask(context, partitionId, localCacheSize);
        }
    }
}


text: Contains code for teaching experience map for CT Voices unequal schools project.


text:
using System;
using System.ComponentModel;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Linq;
using STEP;

namespace IFC
{
	/// <summary>
	/// <see href="http://www.buildingsmart-tech.org/ifc/IFC4/final/html/link/ifcunitassignment.htm"/>
	/// </summary>
	public  partial class IfcUnitAssignment : BaseIfc
	{
		public List<IfcUnit> Units{get;set;}

		/// <summary>
		/// Construct a IfcUnitAssignment with all required attributes.
		/// </summary>
		[JsonConstructor]
		public IfcUnitAssignment(List<IfcUnit> units):base()
		{

			Units = units;

		}
		public static  IfcUnitAssignment FromJSON(string json){ return JsonConvert.DeserializeObject<IfcUnitAssignment>(json); }

        public override string GetStepParameters()
        {
            var parameters = new List<string>();
			parameters.Add(Units != null ? Units.ToStepValue() : "$");

            return string.Join(", ", parameters.ToArray());
        }
	}
}


text:
using System.Reactive.Linq;
using Akavache;
using Android.App;
using Gitter;
using Gitter.Android;
using Gitter.ViewModels;
using ReactiveUI;
using Splat;
using Xamarin.Auth;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer(typeof(LoginPage), typeof(LoginPageRenderer))]

namespace Gitter.Android
{
    public class LoginPageRenderer : PageRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
        {
            base.OnElementChanged(e);

            var activity = (Activity)this.Context;

            var auth = new GitterAuth();
            auth.Completed += (sender, eventArgs) =>
            {
                if (eventArgs.IsAuthenticated)
                {
                    BlobCache.Secure.SaveLogin("Gitter", eventArgs.Account.Properties["access_token"], "Gitter").Wait();

                    var screen = Locator.Current.GetService<IScreen>();
                    screen.Router.NavigateAndReset.Execute(new RoomsViewModel());
                }
                else
                {
                    // The user cancelled
                }
            };

            activity.StartActivity(auth.GetUI(activity));
        }
    }
}


text:
/* See license.txt for terms of usage */

"use strict";

module.metadata = {
  "stability": "stable"
};

const self = require("sdk/self");

const { Cu, Ci, Cc, CC } = require("chrome");
const { Trace, TraceError } = require("firebug.sdk/lib/core/trace.js").get(module.id);
const { getMostRecentBrowserWindow } = require("sdk/window/utils");
const { Content } = require("firebug.sdk/lib/core/content");
const { Class } = require("sdk/core/heritage");
const { defer, resolve } = require("sdk/core/promise");
const { emit } = require("sdk/event/core");
const { setTimeout, clearTimeout } = require("sdk/timers");
const base64 = require("sdk/base64");

// DevTools
const { devtools, makeInfallible } = require("firebug.sdk/lib/core/devtools.js");

// File Services
const { FileUtils } = Cu.import("resource://gre/modules/FileUtils.jsm", {});
const nsIFilePicker = Ci.nsIFilePicker;
const ioService = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);

// Platform
Cu.importGlobalProperties(["btoa"]);

// Constants
const XHTML_NS = "http://www.w3.org/1999/xhtml";
const dataFileName = "data.json";
const asyncSaveDelay = 250;

/**
 * This object represents persistent storage for registered layers. Layers
 * and all their properties are stored into a JSON file that is located
 * within the current browser profile.
 *
 * Existing platform API could be utilized (introduced in Fx 39):
 * https://dxr.mozilla.org/mozilla-central/source/toolkit/devtools/shared/async-storage.js
 */
var PixelPerfectStore = Class(
/** @lends PixelPerfectStore */
{
  // Initialization

  initialize: function() {
    this.layers = [];
    this.version = 1;
    this.layers = this.loadLayers();

    // Generate imageDataURLs. These are sent to the backend
    // as well as to the popup window that runs with type 'content'.
    // Both these scopes don't have access to the local file system.
    if (this.layers) {
      this.layers.forEach(layer => {
        this.updateImageDataURL(layer);
      });
    } else {
      this.layers = [];
      this.save();
    }
  },

  destroy: function() {
  },

  // Public Layer API

  add: function(files) {
    files = files ? files : this.getImageFiles();
    if (!files) {
      return;
    }

    // Make sure we deal with an array.
    files = Array.isArray(files) ? files : [files];

    // Iterate over all selected files
    let result = [];
    files.forEach(file => {
      result.push(this.createLayer(file));
    });

    return result;
  },

  remove: function(id) {
    for (var i=0; i<this.layers.length; i++) {
      let layer = this.layers[i];
      if (layer.id == id) {
        this.layers.splice(i, 1);
        break;
      }
    }

    this.save();

    emit(this, "remove", id);
  },

  modify: function(id, props) {
    let layer = this.getLayer(id);
    for (let p in props) {
      layer[p] = props[p];
    }

    this.save();

    emit(this, "modify", id, props);
  },

  move: function(from, to) {
    var removed = this.layers.splice(from, 1)[0];
    this.layers.splice(to, 0, removed);

    emit(this, "move", from, to);
  },

  // Layers

  createLayer: function(imageFile) {
    let id = "layer-" + (new Date()).getTime();
    let layer = {
      id: id,
      opacity: 50,
      x: 0,
      y: 0,
      scale: 1,
      visible: true,
      lock: false,
      invert: false,
      url: this.getURLFromLocalFile(imageFile)
    };

    this.layers.push(layer);

    this.updateImageDataURL(layer);

    emit(this, "add", layer);

    this.save();

    return layer;
  },

  getLayer: function(id) {
    for (let i=0; i<this.layers.length; i++) {
      let layer = this.layers[i];
      if (layer.id == id) {
        return layer;
      }
    }
  },

  cloneLayer: function(layer) {
    let result = {};
    for (let p in layer) {
      result[p] = layer[p];
    }
    return result;
  },

  forEachLayer: function(callback) {
    this.layers.forEach(layer => {
      callback(layer);
    });
  },

  // Persistence

  getStorageFile: function(fileName) {
    return FileUtils.getFile("ProfD", ["pixel-perfect", fileName]);
  },

  loadLayers: function() {
    try {
      let json = this.load();
      let data = JSON.parse(json);

      // Check existence of image files and remove layers
      // with invalid image URL.
      return this.checkImageFiles(data.layers);
    } catch (err) {
    }
  },

  checkImageFiles: function(layers) {
    // Remove all layers that are not associated with
    // an existing image file.
    return layers.filter(layer => this.imageFileExists(layer.url));
  },

  load: makeInfallible(function() {
    let file = this.getStorageFile(dataFileName);
    if (!file.exists()) {
      return;
    }

    let inputStream = Cc["@mozilla.org/network/file-input-stream;1"]
      .createInstance(Ci.nsIFileInputStream);
    let cstream = Cc["@mozilla.org/intl/converter-input-stream;1"]
      .createInstance(Ci.nsIConverterInputStream);

    // Initialize input stream (read, create)
    let permFlags = parseInt("0666", 8);
    inputStream.init(file, 0x01 | 0x08, permFlags, 0);
    cstream.init(inputStream, "UTF-8", 0, 0);

    // Load JSON data
    let json = "";
    let data = {};
    while (cstream.readString(-1, data) != 0) {
      json += data.value;
    }

    inputStream.close();

    return json;
  }),

  save: makeInfallible(function() {
    if (this.saveTimeout) {
      return;
    }

    // Save on timeout to avoid slow disk performance penalties when
    // performing several save operations in a row.
    this.saveTimeout = setTimeout(() => {
      this.saveAsync();
      this.saveTimeout = null;
    }, asyncSaveDelay);
  }),

  saveAsync: makeInfallible(function() {
    let data = {
      version: this.version,
      layers: this.layers
    }

    // Generated data URLs aren't stored into a file.
    data.layers = data.layers.map(layer => {
      let clone = this.cloneLayer(layer);
      delete clone.dataUrl;
      return clone;
    });

    let json = JSON.stringify(data, 2, 2);
    let file = this.getStorageFile(dataFileName);

    // Initialize output stream.
    var outputStream = Cc["@mozilla.org/network/file-output-stream;1"]
      .createInstance(Ci.nsIFileOutputStream);

    // write, create, truncate
    let permFlags = parseInt("0666", 8);
    outputStream.init(file, 0x02 | 0x08 | 0x20, permFlags, 0);

    // Store JSON
    outputStream.write(json, json.length);
    outputStream.close();
  }),

  // Image Files Picker

  getImageFiles: function() {
    let browser = getMostRecentBrowserWindow();

    let fp = Cc["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
    fp.init(browser, null, nsIFilePicker.modeOpen | nsIFilePicker.modeOpenMultiple);
    fp.appendFilters(nsIFilePicker.filterAll | nsIFilePicker.filterImages);
    fp.filterIndex = 1;

    let rv = fp.show();
    if (rv == nsIFilePicker.returnOK || rv == nsIFilePicker.returnReplace) {
      // Convert simple enumerator to an array.
      let result = [];
      let files = fp.files;
      while (files.hasMoreElements()) {
        result.push(files.getNext());
      }
      return result;
    }

    return null;
  },

  getURLFromLocalFile: function(file) {
    let fileHandler = ioService.getProtocolHandler("file")
      .QueryInterface(Ci.nsIFileProtocolHandler);
    let url = fileHandler.getURLSpecFromFile(file);
    return url;
  },

  imageFileExists: function(layerUrl) {
    if (layerUrl.startsWith("data:")) {
      return true;
    }

    let url = ioService.newURI(layerUrl, null, null);
    if (!url || !url.schemeIs("file")) {
      return false;
    }

    let imageFile = url.QueryInterface(Ci.nsIFileURL).file;
    return imageFile.exists();
  },

  // Image Data URL

  updateImageDataURL: function(layer) {
    layer.dataUrl = this.getImageDataURL(layer.id);
  },

  getImageDataURL: makeInfallible(function(id) {
    let layer = this.getLayer(id);
    if (layer.url.startsWith("data:")) {
      return layer.url;
    }

    if (layer.dataUrl) {
      return layer.dataUrl;
    }

    let url = ioService.newURI(layer.url, null, null);
    if (!url || !url.schemeIs("file")) {
      return null;
    }

    let imageFile = url.QueryInterface(Ci.nsIFileURL).file;
    if (!imageFile.exists()) {
      return null;
    }

    let inputStream = Cc["@mozilla.org/network/file-input-stream;1"].
      createInstance(Ci.nsIFileInputStream);

    inputStream.init(imageFile, -1, -1, false);
    let binaryStream = Cc["@mozilla.org/binaryinputstream;1"].
      createInstance(Ci.nsIBinaryInputStream);
    binaryStream.setInputStream(inputStream);

    let bytes = binaryStream.readBytes(binaryStream.available());
    let encodedData = btoa(bytes);

    let lastDot = layer.url.lastIndexOf(".");
    let fileExt = layer.url.substr(lastDot + 1);
    let mimeType = (fileExt == "svg") ? "image/svg+xml" : "image/png";

    return "data:" + mimeType + ";base64," + encodedData;
  })
});

// Exports from this module
exports.PixelPerfectStore = PixelPerfectStore;


text:
#include <rttr/registration>

using namespace rttr;
using namespace std;

#include <iostream>
#include <memory>
#include <functional>

#include <catch/catch.hpp>

enum class access_t : int
{
    read = 1,
    write = 2,
    exec = 4
};

/////////////////////////////////////////////////////////////////////////////////////////

RTTR_REGISTRATION
{
    registration::enumeration<access_t>("access_t")
    (
        value("read",   access_t::read),
        value("write",  access_t::write),
        value("exec",   access_t::exec)
    );
}

/////////////////////////////////////////////////////////////////////////////////////////

TEST_CASE("enumeration - value_to_name()", "[enumeration]")
{
    enumeration e = type::get_by_name("access_t").get_enumeration();

    // normal
    CHECK(e.value_to_name(access_t::read)     == "read");
    CHECK(e.value_to_name(access_t::write)    == "write");
    CHECK(e.value_to_name(access_t::exec)     == "exec");

    // implicit
    CHECK(e.value_to_name(4)                  == "exec");

    // invalid
    CHECK(e.value_to_name("test")             == "");
    CHECK(e.value_to_name(42)                 == "");

    // negative
    e = type::get_by_name("access_unknown").get_enumeration();
    CHECK(e.value_to_name(access_t::read).empty() == true);
}

/////////////////////////////////////////////////////////////////////////////////////////

TEST_CASE("enumeration - name_to_value()", "[enumeration]")
{
    enumeration e = type::get_by_name("access_t").get_enumeration();

    REQUIRE(e.name_to_value("read").is_type<access_t>()   == true);
    REQUIRE(e.name_to_value("write").is_type<access_t>()  == true);
    REQUIRE(e.name_to_value("write").is_type<access_t>()  == true);

    CHECK(e.name_to_value("read").get_value<access_t>()   == access_t::read);
    CHECK(e.name_to_value("write").get_value<access_t>()  == access_t::write);
    CHECK(e.name_to_value("exec").get_value<access_t>()   == access_t::exec);

    // invalid
    CHECK(e.name_to_value("some name").is_valid()   == false);

    // negative
    e = type::get_by_name("access_unknown").get_enumeration();
    REQUIRE(e.name_to_value("write").is_type<access_t>() == false);
}

/////////////////////////////////////////////////////////////////////////////////////////


text:
/* $This file is distributed under the terms of the license in LICENSE$ */

package edu.cornell.mannlib.vitro.webapp.utils.developer.loggers;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Records and process the stack trace so a developer's logger can (1) test
 * against it, and (2) display it.
 *
 * If the "enabled" flag is not set, no processing is done, and the stack trace
 * is empty. That way, there is essentially no overhead in creating a disabled
 * instance.
 */
public class StackTraceUtility {
	private static final Log log = LogFactory.getLog(StackTraceUtility.class);

	private final Class<?> lowestClassInStackTrace;
	private final List<StackTraceElement> stackTrace;
	private final String methodName;

	public StackTraceUtility(Class<?> lowestClassInStackTrace, boolean enabled) {
		this.lowestClassInStackTrace = lowestClassInStackTrace;

		this.stackTrace = enabled ? loadStackTrace() : Collections
				.<StackTraceElement> emptyList();

		this.methodName = (this.stackTrace.isEmpty()) ? "UNKNOWN"
				: this.stackTrace.get(0).getMethodName();

	}

	private List<StackTraceElement> loadStackTrace() {
		StackTraceElement[] stack = Thread.currentThread().getStackTrace();
		List<StackTraceElement> list = new ArrayList<StackTraceElement>(
				Arrays.asList(stack));

		trimStackTraceAtBeginning(list);
		trimStackTraceAtEnd(list);
		removeJenaClassesFromStackTrace(list);

		log.debug("Stack array: " + Arrays.toString(stack));
		log.debug("Stack trace: " + list);
		return Collections.unmodifiableList(list);
	}

	private void trimStackTraceAtBeginning(List<StackTraceElement> list) {
		ListIterator<StackTraceElement> iter = list.listIterator();
		while (iter.hasNext()) {
			StackTraceElement ste = iter.next();
			if (ste.getClassName().equals(lowestClassInStackTrace.getName())) {
				break;
			} else {
				iter.remove();
			}
		}
	}

	private void trimStackTraceAtEnd(List<StackTraceElement> list) {
		ListIterator<StackTraceElement> iter = list.listIterator();
		boolean trimming = false;
		while (iter.hasNext()) {
			StackTraceElement ste = iter.next();
			if (trimming) {
				iter.remove();
			} else if (ste.getClassName().contains("ApplicationFilterChain")) {
				trimming = true;
			}
		}
	}

	private void removeJenaClassesFromStackTrace(List<StackTraceElement> list) {
		ListIterator<StackTraceElement> iter = list.listIterator();
		while (iter.hasNext()) {
			StackTraceElement ste = iter.next();
			if (ste.getClassName().startsWith("org.apache.jena.")) {
				iter.remove();
			}
		}
	}

	public boolean passesStackRestriction(String restriction) {
		if (StringUtils.isEmpty(restriction)) {
			return true;
		} else {
			try {
				return passesStackRestriction(Pattern.compile(restriction));
			} catch (Exception e) {
				log.warn("Failed when testing stack restriction: '"
						+ restriction + "'");
				return true;
			}
		}

	}

	public boolean passesStackRestriction(Pattern restriction) {
		if (restriction == null) {
			return true;
		}
		String q = assembleCallStackString();
		return restriction.matcher(q).find();
	}

	private String assembleCallStackString() {
		StringBuilder stack = new StringBuilder();
		for (StackTraceElement ste : stackTrace) {
			stack.append(ste.getClassName()).append(" ")
					.append(ste.getMethodName()).append(" ");
		}
		return stack.deleteCharAt(stack.length() - 1).toString();
	}

	public String format(boolean requested) {
		StringBuilder sb = new StringBuilder();
		if (requested) {
			for (StackTraceElement ste : stackTrace) {
				sb.append(String.format("   %s.%s(%s:%d) \n",
						ste.getClassName(), ste.getMethodName(),
						ste.getFileName(), ste.getLineNumber()));
			}
			sb.append("   ...\n");
		}
		return sb.toString();
	}

	public String getMethodName() {
		return this.methodName;
	}

}


text:
GPS-Playground
==============

Basic GPS Visualization And Testing


text:
<!DOCTYPE HTML>

<meta http-equiv='X-UA-Compatible' content='IE=edge' />
<meta http-equiv='Content-Type' content='text/html;charset=UTF-8' />
<title>Additional Properties</title>

<link rel="stylesheet" type="text/css" href="org.scn.community.generic.PropertyPage.css">


text:
package manifest_test

import (
	"io/ioutil"
	"os"
	"strings"

	. "github.com/cloudfoundry/cli/cf/manifest"
	. "github.com/cloudfoundry/cli/testhelpers/matchers"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

type outputs struct {
	contents []string
	cursor   int
}

var _ = Describe("generate_manifest", func() {
	var (
		m   AppManifest
		err error
	)

	BeforeEach(func() {
		_, err = os.Stat("./output.yml")
		Ω(err).To(HaveOccurred())

		m = NewGenerator()
		m.FileSavePath("./output.yml")
	})

	AfterEach(func() {
		err = os.Remove("./output.yml")
		Ω(err).ToNot(HaveOccurred())
	})

	It("creates a new file at a given path", func() {
		m.Save()

		_, err = os.Stat("./output.yml")
		Ω(err).ToNot(HaveOccurred())
	})

	It("starts the manifest with 3 dashes (---), followed by 'applications'", func() {
		m.Save()

		contents := getYamlContent("./output.yml")

		Ω(contents[0]).To(Equal("---"))
		Ω(contents[1]).To(Equal("applications:"))
	})

	It("creates entry under the given app name", func() {
		m.Memory("app1", 128)
		m.Memory("app2", 64)
		m.Save()

		//outputs.ContainSubstring assert orders
		cmdOutput := &outputs{
			contents: getYamlContent("./output.yml"),
			cursor:   0,
		}

		Ω(cmdOutput.ContainsSubstring("- name: app1")).To(BeTrue())
		Ω(cmdOutput.ContainsSubstring("  memory: 128M")).To(BeTrue())

		Ω(cmdOutput.ContainsSubstring("- name: app2")).To(BeTrue())
		Ω(cmdOutput.ContainsSubstring("  memory: 64M")).To(BeTrue())
	})

	It("prefixes each service with '-'", func() {
		m.Service("app1", "service1")
		m.Service("app1", "service2")
		m.Service("app1", "service3")
		m.Save()

		contents := getYamlContent("./output.yml")

		Ω(contents).To(ContainSubstrings(
			[]string{"  services:"},
			[]string{"- service1"},
			[]string{"- service2"},
			[]string{"- service3"},
		))
	})

	It("generates a manifest containing all the attributes", func() {
		m.Memory("app1", 128)
		m.StartupCommand("app1", "run main.go")
		m.Service("app1", "service1")
		m.EnvironmentVars("app1", "foo", "boo")
		m.HealthCheckTimeout("app1", 100)
		m.Instances("app1", 3)
		m.Domain("app1", "foo", "blahblahblah.com")
		err := m.Save()
		Ω(err).NotTo(HaveOccurred())

		Ω(getYamlContent("./output.yml")).To(ContainSubstrings(
			[]string{"- name: app1"},
			[]string{"  memory: 128M"},
			[]string{"  command: run main.go"},
			[]string{"  services:"},
			[]string{"  - service1"},
			[]string{"  env:"},
			[]string{"    foo: boo"},
			[]string{"  timeout: 100"},
			[]string{"  instances: 3"},
			[]string{"  host: foo"},
			[]string{"  domain: blahblahblah.com"},
		))
	})

})

func getYamlContent(path string) []string {
	b, err := ioutil.ReadFile(path)
	Ω(err).ToNot(HaveOccurred())

	return strings.Split(string(b), "\n")
}

func (o *outputs) ContainsSubstring(str string) bool {
	for i := o.cursor; i < len(o.contents)-1; i++ {
		if strings.Contains(o.contents[i], str) {
			o.cursor = i
			return true
		}
	}
	return false
}


text:
package org.sakaiproject.sdata.tool.util;

import com.google.inject.Inject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.kernel.api.authz.AuthzResolverService;
import org.sakaiproject.kernel.api.authz.PermissionQuery;
import org.sakaiproject.sdata.tool.api.SDataException;
import org.sakaiproject.sdata.tool.api.SecurityAssertion;

import java.util.Map;

import javax.servlet.http.HttpServletResponse;

/**
 *

 * An implementation of the Security Assertion that uses the http method, the
 * path and the sakai security service for perform the assertion. On check it
 * will throw SDataExceptions indicating forbidden if the path is outside its
 * configured range, or it is denied by the the Sakai security service.
 *

 *

 *
 * It accepts paths starting with basePath, and then replaces basePath with
 * baseResource before checking for the method with the resulting path and the
 * PermissionQuery associated with the method.
 *

 *
 * @author ieb
 */
public class PathSecurityAssertion implements SecurityAssertion {

  private static final Log LOG = LogFactory.getLog(PathSecurityAssertion.class);

  /**
   * The base location that is Security Advisor applies to. Only paths that
   * start with this are allowed all others are denied regardless of the method.
   * If the path starts with baseLocation, baseLocation is removed from the path
   * and baseResource is prepended to the patch to generate a full resource
   * location suitable for using with the security service.
   */
  private String basePath;

  /**
   * A map mapping http methods to locks
   */
  private Map<String, PermissionQuery> locks;

  /**
   * this is prepended to the resource path, after normalizing (ie removing
   * baseLocation) and before sending to the Sakai security service.
   */
  private String baseResource;

  /**
   * The AuthzResolverService performs the resolution of security assertions
   * once the path and method have been translated into a permissions query and
   * a resource path.
   */
  private AuthzResolverService authzResolverService;

  /**
   */
  @Inject
  public PathSecurityAssertion(AuthzResolverService authzResolverService) {
    this.authzResolverService = authzResolverService;
  }

  /**
   * @param basePath
   *          the baseUrl to set, this it the stub of the url coming into the
   *          assertion that will be handled by this assertion
   */
  public void setBasePath(String basePath) {
    this.basePath = basePath;
  }

  /**
   * @param baseResource
   *          the baseResource, having remove the base URL from the url coming
   *          in, the base resource is added to generate the path in the
   *          repository on which the assertion is made.
   */
  public void setBaseResource(String baseResource) {
    this.baseResource = baseResource;
  }

  /**
   * @param locks
   *          locks provide a translation between the method being used on the
   *          url GET, POST, PUT etc and the permission that will be required to
   *          pass the assertion. Against each method there is a PermissionQuery
   *          that, if matching should be satisfied for the permission to be
   *          granted.
   */
  public void setLocks(Map<String, PermissionQuery> locks) {
    this.locks = locks;
  }

  /**
   * Performs the security assertion based on the resourceLocation, from the
   * original request and the method begin attempted. Will throw a
   * SDataException with Forbidden if the resource location is outside the
   * configured range, or if permission is denied.
   *
   * @param method
   *          the http method being used
   * @param urlPath
   *          the path of the url, excluding host, protocol, port and query
   *          string, but including everything else.
   * @see org.sakaiproject.sdata.tool.api.SecurityAssertion#check(java.lang.String,java.lang.String,
   *      java.lang.String)
   */
  public void check(String method, String resourcePath) throws SDataException {

    if (!(basePath.length() == 0)
        && (resourcePath == null || !resourcePath.startsWith(basePath))) {
      LOG.info("Denied " + method + " on [" + resourcePath
          + "] base mismatch [" + basePath + "]");
      throw new SDataException(HttpServletResponse.SC_FORBIDDEN,
          "Access Forbidden");
    }
    String resourceReference = baseResource
        + resourcePath.substring(basePath.length());
    PermissionQuery permissionQuery = getResourceLock(method);

    if ( permissionQuery == null ) {
      throw new SDataException(HttpServletResponse.SC_METHOD_NOT_ALLOWED,"Method "+method+" is not allowed");
    } else {
      authzResolverService.check(resourceReference, permissionQuery);
    }
  }

  /**
   * Convert the HTTP Method into a lock.
   *
   * @param method
   * @return
   */
  protected PermissionQuery getResourceLock(String method) {
    return locks.get(method);
  }

}


text:
Often you want some default nodes to be created (or updated) when your extension is started.

Both the dynamic module registry as the workflow registry deploy resources from your extension to the repository upon startup.

They use the `BootstrapService` for this. This service takes a strategy for determining if a resource should be updated when it already exists as a node.

Here is example of deploying some xml files:

```java
@Component
public class MyBootstrap implements InitializingBean {
  @Autowired
  protected ResourceHelper resourceHelper;

  @Autowired
  protected BootstrapService bootstrapService;

  public void afterPropertiesSet() {
    bootstrapService.deployResources(
          "osgibundle:/META-INF/alfresco/bootstrap/*.xml",
          new RepositoryLocation(
              StoreRef.STORE_REF_WORKSPACE_SPACESSTORE,
              "/app:company_home/app:dictionary",
              SearchService.LANGUAGE_XPATH
          ),
          new ContentCompareStrategy(resourceHelper),
          null, null, ContentModel.TYPE_CONTENT
    );
  }
}
```

First, we specify the source: you can use a Spring resource pattern here: `osgibundle:` is used to reference the extension scope. In this case the jar of the extension.
All xml files in `/META-INF/alfresco/bootstrap` will be copied to the repository.

Next, specify a target location: XPATH makes a good candidate here.

Now decide on a strategy. To update nodes when the content has changed, use `ContentCompareStrategy`. To always update, use `StaticUpdateStrategy`.

The encoding and mimetype will be autodetected if left blank.

And finally you need to specify the type for any newly created nodes.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using GRA.Domain.Model;
using GRA.Domain.Report.Abstract;
using GRA.Domain.Report.Attribute;
using GRA.Domain.Repository;
using Microsoft.Extensions.Logging;

namespace GRA.Domain.Report
{
    [ReportInformation(6,
        "Top Scores Report",
        "Top 30 scoring participants filterable by program, system, and branch",
        "Participants")]
    public class TopScoresReport : BaseReport
    {
        private const int TopToShow = 30;
        private readonly IUserRepository _userRepository;

        public TopScoresReport(ILogger<TopScoresReport> logger,
            Domain.Report.ServiceFacade.Report serviceFacade,
            IUserRepository userRepository) : base(logger, serviceFacade)
        {
            _userRepository = userRepository
                ?? throw new ArgumentNullException(nameof(userRepository));
        }

        public override async Task ExecuteAsync(ReportRequest request,
            CancellationToken token,
            IProgress<OperationStatus> progress = null)
        {
            #region Reporting initialization
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            request = await StartRequestAsync(request);

            var criterion
                = await _serviceFacade.ReportCriterionRepository.GetByIdAsync(request.ReportCriteriaId)
                ?? throw new GraException($"Report criteria {request.ReportCriteriaId} for report request id {request.Id} could not be found.");

            if (criterion.SiteId == null)
            {
                throw new ArgumentNullException(nameof(criterion.SiteId));
            }

            var report = new StoredReport
            {
                Title = ReportAttribute?.Name,
                AsOf = _serviceFacade.DateTimeProvider.Now
            };
            var reportData = new List<object[]>();
            #endregion Reporting initialization

            #region Collect data
            UpdateProgress(progress, 1, "Starting report...", request.Name);

            // header row
            report.HeaderRow = new object[] {
                "Rank",
                "System Name",
                "Branch Name",
                "Program",
                "Participant",
                "Points Earned"
            };

            int count = 0;
            int total = TopToShow;

            IEnumerable<User> users = await _userRepository.GetTopScoresAsync(criterion, total);

            // TODO establish why this isn't sorting properly in production
            foreach (var user in users.OrderByDescending(_ => _.PointsEarned))
            {
                UpdateProgress(progress,
                    ++count * 100 / users.Count(),
                    $"Processing: {count}/{users.Count()}",
                    request.Name);

                if (token.IsCancellationRequested)
                {
                    break;
                }

                var name = new StringBuilder(user.FirstName);
                if(!string.IsNullOrEmpty(user.LastName))
                {
                    name.Append($" {user.LastName}");
                }
                if(!string.IsNullOrEmpty(user.Username))
                {
                    name.Append($" ({user.Username})");
                }

                reportData.Add(new object[] {
                        count,
                        user.SystemName,
                        user.BranchName,
                        user.ProgramName,
                        name.ToString(),
                        user.PointsEarned
                    });
            }

            report.Data = reportData.ToArray();
            #endregion Collect data

            #region Finish up reporting
            _logger.LogInformation($"Report {GetType().Name} with criterion {criterion.Id} ran in {StopTimer()}");

            request.Success = !token.IsCancellationRequested;

            if (request.Success == true)
            {
                ReportSet.Reports.Add(report);
                request.Finished = _serviceFacade.DateTimeProvider.Now;
                request.ResultJson = Newtonsoft.Json.JsonConvert.SerializeObject(ReportSet);
            }
            await _serviceFacade.ReportRequestRepository.UpdateSaveNoAuditAsync(request);
            #endregion Finish up reporting
        }
    }
}


text:
package fr.openwide.maven.artifact.notifier.core.business.user.dao;

import fr.openwide.core.jpa.business.generic.dao.IGenericEntityDao;
import fr.openwide.maven.artifact.notifier.core.business.user.model.EmailAddress;

public interface IEmailAddressDao extends IGenericEntityDao<Long, EmailAddress> {

}