text:
package com.github.maven_nar;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

import org.apache.bcel.classfile.ClassParser;
import org.apache.bcel.classfile.JavaClass;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.cli.Commandline;

/**
 * @author Mark Donszelmann
 */
public final class NarUtil {
  private static final class StreamGobbler extends Thread {
    private final InputStream is;

    private final TextStream ts;

    private StreamGobbler(final InputStream is, final TextStream ts) {
      this.is = is;
      this.ts = ts;
    }

    @Override
    public void run() {
      try {
        final BufferedReader reader = new BufferedReader(new InputStreamReader(this.is));
        String line = null;
        while ((line = reader.readLine()) != null) {
          this.ts.println(line);
        }
        reader.close();
      } catch (final IOException e) {
        // e.printStackTrace()
        final StackTraceElement[] stackTrace = e.getStackTrace();
        for (final StackTraceElement element : stackTrace) {
          this.ts.println(element.toString());
        }
      }
    }
  }

  public static final String DEFAULT_EXCLUDES = "**/*~,**/#*#,**/.#*,**/%*%,**/._*,"
      + "**/CVS,**/CVS/**,**/.cvsignore," + "**/SCCS,**/SCCS/**,**/vssver.scc," + "**/.svn,**/.svn/**,**/.DS_Store";

  public static String addLibraryPathToEnv(final String path, final Map environment, final String os) {
    String pathName = null;
    char separator = ' ';
    if (os.equals(OS.WINDOWS)) {
      pathName = "PATH";
      separator = ';';
    } else if (os.equals(OS.MACOSX)) {
      pathName = "DYLD_LIBRARY_PATH";
      separator = ':';
    } else {
      pathName = "LD_LIBRARY_PATH";
      separator = ':';
    }

    String value = environment != null ? (String) environment.get(pathName) : null;
    if (value == null) {
      value = NarUtil.getEnv(pathName, pathName, null);
    }

    String libPath = path;
    libPath = libPath.replace(File.pathSeparatorChar, separator);
    if (value != null) {
      value += separator + libPath;
    } else {
      value = libPath;
    }
    if (environment != null) {
      environment.put(pathName, value);
    }
    return pathName + "=" + value;
  }

  /**
   * (Darren) this code lifted from mvn help:active-profiles plugin Recurses
   * into the project's parent poms to find the active profiles of the
   * specified project and all its parents.
   *
   * @param project
   *          The project to start with
   * @return A list of active profiles
   */
  static List collectActiveProfiles(final MavenProject project) {
    final List profiles = project.getActiveProfiles();

    if (project.hasParent()) {
      profiles.addAll(collectActiveProfiles(project.getParent()));
    }

    return profiles;
  }

  public static int copyDirectoryStructure(final File sourceDirectory, final File destinationDirectory,
      final String includes, final String excludes) throws IOException {
    if (!sourceDirectory.exists()) {
      throw new IOException("Source directory doesn't exists (" + sourceDirectory.getAbsolutePath() + ").");
    }

    final List files = FileUtils.getFiles(sourceDirectory, includes, excludes);
    final String sourcePath = sourceDirectory.getAbsolutePath();

    int copied = 0;
    for (final Iterator i = files.iterator(); i.hasNext();) {
      final File file = (File) i.next();
      String dest = file.getAbsolutePath();
      dest = dest.substring(sourcePath.length() + 1);
      final File destination = new File(destinationDirectory, dest);
      if (file.isFile()) {
        // destination = destination.getParentFile();
        // use FileUtils from commons-io, because it preserves timestamps
        org.apache.commons.io.FileUtils.copyFile(file, destination);
        copied++;

        // copy executable bit
        try {
          // 1.6 only so coded using introspection
          // destination.setExecutable( file.canExecute(), false );
          final Method canExecute = file.getClass().getDeclaredMethod("canExecute", new Class[] {});
          final Method setExecutable = destination.getClass().getDeclaredMethod("setExecutable", new Class[] {
              boolean.class, boolean.class
          });
          setExecutable.invoke(destination, new Object[] {
              (Boolean) canExecute.invoke(file, new Object[] {}), Boolean.FALSE
          });
        } catch (final SecurityException e) {
          // ignored
        } catch (final NoSuchMethodException e) {
          // ignored
        } catch (final IllegalArgumentException e) {
          // ignored
        } catch (final IllegalAccessException e) {
          // ignored
        } catch (final InvocationTargetException e) {
          // ignored
        }
      } else if (file.isDirectory()) {
        if (!destination.exists() && !destination.mkdirs()) {
          throw new IOException("Could not create destination directory '" + destination.getAbsolutePath() + "'.");
        }
        copied += copyDirectoryStructure(file, destination, includes, excludes);
      } else {
        throw new IOException("Unknown file type: " + file.getAbsolutePath());
      }
    }
    return copied;
  }

  static Set findInstallNameToolCandidates(final File[] files, final Log log)
      throws MojoExecutionException, MojoFailureException {
    final HashSet candidates = new HashSet();

    for (final File file2 : files) {
      final File file = file2;

      if (!file.exists()) {
        continue;
      }

      if (file.isDirectory()) {
        candidates.addAll(findInstallNameToolCandidates(file.listFiles(), log));
      }

      final String fileName = file.getName();
      if (file.isFile() && file.canWrite()
          && (fileName.endsWith(".so") || fileName.endsWith(".dylib") || fileName.endsWith(".jnilib"))) {
        candidates.add(file);
      }
    }

    return candidates;
  }

  // FIXME, should go to AOL.
  /*
   * NOT USED ?
   * public static String getAOLKey( String architecture, String os, Linker
   * linker )
   * throws MojoFailureException, MojoExecutionException
   * {
   * // construct AOL key prefix
   * return getArchitecture( architecture ) + "." + getOS( os ) + "." +
   * getLinkerName( architecture, os, linker )
   * + ".";
   * }
   */

  public static AOL getAOL(final MavenProject project, final String architecture, final String os, final Linker linker,
      final String aol, final Log log) throws MojoFailureException, MojoExecutionException {
    // adjust aol
    return aol == null ? new AOL(getArchitecture(architecture), getOS(os), getLinkerName(project, architecture, os,
        linker, log)) : new AOL(aol);
  }

  public static String getAOLKey(final String aol) {
    // FIXME, this may not always work correctly
    return replace("-", ".", aol);
  }

  public static String getArchitecture(final String architecture) {
    if (architecture == null) {
      return System.getProperty("os.arch");
    }
    return architecture;
  }

  /**
   * Returns the Bcel Class corresponding to the given class filename
   *
   * @param filename
   *          the absolute file name of the class
   * @return the Bcel Class.
   * @throws IOException
   */
  public static JavaClass getBcelClass(final String filename) throws IOException {
    final ClassParser parser = new ClassParser(filename);
    return parser.parse();
  }

  public static String getEnv(final String envKey, final String alternateSystemProperty, final String defaultValue) {
    String envValue = null;
    try {
      envValue = System.getenv(envKey);
      if (envValue == null && alternateSystemProperty != null) {
        envValue = System.getProperty(alternateSystemProperty);
      }
    } catch (final Error e) {
      // JDK 1.4?
      if (alternateSystemProperty != null) {
        envValue = System.getProperty(alternateSystemProperty);
      }
    }

    if (envValue == null) {
      envValue = defaultValue;
    }

    return envValue;
  }

  /**
   * Returns the header file name (javah) corresponding to the given class file
   * name
   *
   * @param filename
   *          the absolute file name of the class
   * @return the header file name.
   */
  public static String getHeaderName(final String basename, final String filename) {
    final String base = basename.replaceAll("\\\\", "/");
    final String file = filename.replaceAll("\\\\", "/");
    if (!file.startsWith(base)) {
      throw new IllegalArgumentException("Error " + file + " does not start with " + base);
    }
    String header = file.substring(base.length() + 1);
    header = header.replaceAll("/", "_");
    header = header.replaceAll("\\.class", ".h");
    return header;
  }

  public static File getJavaHome(final File javaHome, final String os) {
    File home = javaHome;
    // adjust JavaHome
    if (home == null) {
      home = new File(System.getProperty("java.home"));
      if (home.getName().equals("jre")) {
        // we want the JDK base directory, not the JRE subfolder
        home = home.getParentFile();
      }
    }
    return home;
  }

  public static Linker getLinker(final Linker linker, final Log log) {
    Linker link = linker;
    if (link == null) {
      link = new Linker(log);
    }
    return link;
  }

  public static String getLinkerName(final MavenProject project, final String architecture, final String os,
      final Linker linker, final Log log) throws MojoFailureException, MojoExecutionException {
    return getLinker(linker, log).getName(NarProperties.getInstance(project),
        getArchitecture(architecture) + "." + getOS(os) + ".");
  }

  public static String getOS(final String defaultOs) {
    String os = defaultOs;
    // adjust OS if not given
    if (os == null) {
      os = System.getProperty("os.name");
      final String name = os.toLowerCase();
      if (name.startsWith("windows")) {
        os = OS.WINDOWS;
      }
      if (name.startsWith("linux")) {
        os = OS.LINUX;
      }
      if (name.startsWith("freebsd")) {
        os = OS.FREEBSD;
      }
      if (name.equals("mac os x")) {
        os = OS.MACOSX;
      }
    }
    return os;
  }

  public static boolean isWindows() {
    return getOS(null) == OS.WINDOWS;
  }

  public static void makeExecutable(final File file, final Log log) throws MojoExecutionException, MojoFailureException {
    if (!file.exists()) {
      return;
    }

    if (file.isDirectory()) {
      final File[] files = file.listFiles();
      for (final File file2 : files) {
        makeExecutable(file2, log);
      }
    }
    if (file.isFile() && file.canRead() && file.canWrite() && !file.isHidden()) {
      // chmod +x file
      final int result = runCommand("chmod", new String[] {
          "+x", file.getPath()
      }, null, null, log);
      if (result != 0) {
        throw new MojoExecutionException("Failed to execute 'chmod +x " + file.getPath() + "'" + " return code: \'"
            + result + "\'.");
      }
    }
  }

  public static void makeLink(final File file, final Log log) throws MojoExecutionException, MojoFailureException {
    if (!file.exists()) {
      return;
    }

    if (file.isDirectory()) {
      final File[] files = file.listFiles();
      for (final File file2 : files) {
        makeLink(file2, log);
      }
    }
    if (file.isFile() && file.canRead() && file.canWrite() && !file.isHidden()
        && file.getName().matches(".*\\.so(\\.\\d+)+$")) {
      final File sofile = new File(file.getParent(), file.getName().substring(0, file.getName().indexOf(".so") + 3));
      if (!sofile.exists()) {
        // ln -s lib.so.xx lib.so
        final int result = runCommand("ln", new String[] {
            "-s", file.getName(), sofile.getPath()
        }, null, null, log);
        if (result != 0) {
          throw new MojoExecutionException("Failed to execute 'ln -s " + file.getName() + " " + sofile.getPath() + "'"
              + " return code: \'" + result + "\'.");
        }
      }
    }
  }

  /* for jdk 1.4 */
  private static String quote(final String s) {
    final String escQ = "\\Q";
    final String escE = "\\E";

    int slashEIndex = s.indexOf(escE);
    if (slashEIndex == -1) {
      return escQ + s + escE;
    }

    final StringBuffer sb = new StringBuffer(s.length() * 2);
    sb.append(escQ);
    slashEIndex = 0;
    int current = 0;
    while ((slashEIndex = s.indexOf(escE, current)) != -1) {
      sb.append(s.substring(current, slashEIndex));
      current = slashEIndex + 2;
      sb.append(escE);
      sb.append("\\");
      sb.append(escE);
      sb.append(escQ);
    }
    sb.append(s.substring(current, s.length()));
    sb.append(escE);
    return sb.toString();
  }

  /* for jdk 1.4 */
  private static String quoteReplacement(final String s) {
    if (s.indexOf('\\') == -1 && s.indexOf('$') == -1) {
      return s;
    }
    final StringBuffer sb = new StringBuffer();
    for (int i = 0; i < s.length(); i++) {
      final char c = s.charAt(i);
      if (c == '\\') {
        sb.append('\\');
        sb.append('\\');
      } else if (c == '$') {
        sb.append('\\');
        sb.append('$');
      } else {
        sb.append(c);
      }
    }
    return sb.toString();
  }

  static void removeNulls(final Collection<?> collection) {
    for (final Iterator<?> iter = collection.iterator(); iter.hasNext();) {
      if (iter.next() == null) {
        iter.remove();
      }
    }
  }

  /**
   * Replaces target with replacement in string. For jdk 1.4 compatiblity.
   *
   * @param target
   * @param replacement
   * @param string
   * @return
   */
  public static String replace(final CharSequence target, final CharSequence replacement, final String string) {
    return Pattern.compile(quote(target.toString())/*
                                                    * , Pattern.LITERAL jdk 1.4
                                                    */).matcher(string).replaceAll(
    /* Matcher. jdk 1.4 */quoteReplacement(replacement.toString()));
  }

  public static int runCommand(final String cmd, final String[] args, final File workingDirectory, final String[] env,
      final Log log) throws MojoExecutionException, MojoFailureException {
    if (log.isInfoEnabled()) {
      final StringBuilder argLine = new StringBuilder();
      if (args != null) {
        for (final String arg : args) {
          argLine.append(" " + arg);
        }
      }
      if (workingDirectory != null) {
        log.info("+ cd " + workingDirectory.getAbsolutePath());
      }
      log.info("+ " + cmd + argLine);
    }
    return runCommand(cmd, args, workingDirectory, env, new TextStream() {
      @Override
      public void println(final String text) {
        log.info(text);
      }
    }, new TextStream() {
      @Override
      public void println(final String text) {
        log.error(text);
      }

    }, new TextStream() {
      @Override
      public void println(final String text) {
        log.debug(text);
      }
    }, log);
  }

  public static int runCommand(final String cmd, final String[] args, final File workingDirectory, final String[] env,
      final TextStream out, final TextStream err, final TextStream dbg, final Log log)
      throws MojoExecutionException, MojoFailureException {
    return runCommand(cmd, args, workingDirectory, env, out, err, dbg, log, false);
  }

  public static int runCommand(final String cmd, final String[] args, final File workingDirectory, final String[] env,
      final TextStream out, final TextStream err, final TextStream dbg, final Log log, final boolean expectFailure)
      throws MojoExecutionException, MojoFailureException {
    final Commandline cmdLine = new Commandline();

    try {
      dbg.println("RunCommand: " + cmd);
      cmdLine.setExecutable(cmd);
      if (args != null) {
        for (final String arg : args) {
          dbg.println("  '" + arg + "'");
        }
        cmdLine.addArguments(args);
      }
      if (workingDirectory != null) {
        dbg.println("in: " + workingDirectory.getPath());
        cmdLine.setWorkingDirectory(workingDirectory);
      }

      if (env != null) {
        dbg.println("with Env:");
        for (final String element : env) {
          final String[] nameValue = element.split("=", 2);
          if (nameValue.length < 2) {
            throw new MojoFailureException("   Misformed env: '" + element + "'");
          }
          dbg.println("   '" + nameValue[0] + "=" + nameValue[1] + "'");
          cmdLine.addEnvironment(nameValue[0], nameValue[1]);
        }
      }

      final Process process = cmdLine.execute();
      final StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(), err);
      final StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream(), out);

      errorGobbler.start();
      outputGobbler.start();
      process.waitFor();
      final int exitValue = process.exitValue();
      dbg.println("ExitValue: " + exitValue);
      final int timeout = 5000;
      errorGobbler.join(timeout);
      outputGobbler.join(timeout);
      if (exitValue != 0 ^ expectFailure) {
        if (log == null) {
          System.err.println(err.toString());
          System.err.println(out.toString());
          System.err.println(dbg.toString());
        } else {
          log.warn(err.toString());
          log.warn(out.toString());
          log.warn(dbg.toString());
        }
        throw new MojoExecutionException("exit code: " + exitValue);
      }
      return exitValue;
    } catch (final MojoExecutionException e) {
      throw e;
    } catch (final Exception e) {
      throw new MojoExecutionException("Could not launch " + cmdLine, e);
    }
  }

  static void runInstallNameTool(final File[] files, final Log log) throws MojoExecutionException, MojoFailureException {
    final Set libs = findInstallNameToolCandidates(files, log);

    for (final Iterator i = libs.iterator(); i.hasNext();) {
      final File subjectFile = (File) i.next();
      final String subjectName = subjectFile.getName();
      final String subjectPath = subjectFile.getPath();

      final int idResult = runCommand("install_name_tool", new String[] {
          "-id", subjectPath, subjectPath
      }, null, null, log);

      if (idResult != 0) {
        throw new MojoExecutionException("Failed to execute 'install_name_tool -id " + subjectPath + " " + subjectPath
            + "'" + " return code: \'" + idResult + "\'.");
      }

      for (final Iterator j = libs.iterator(); j.hasNext();) {
        final File dependentFile = (File) j.next();
        final String dependentPath = dependentFile.getPath();

        if (dependentPath == subjectPath) {
          continue;
        }

        final int changeResult = runCommand("install_name_tool", new String[] {
            "-change", subjectName, subjectPath, dependentPath
        }, null, null, log);

        if (changeResult != 0) {
          throw new MojoExecutionException("Failed to execute 'install_name_tool -change " + subjectName + " "
              + subjectPath + " " + dependentPath + "'" + " return code: \'" + changeResult + "\'.");
        }
      }
    }
  }

  public static void runRanlib(final File file, final Log log) throws MojoExecutionException, MojoFailureException {
    if (!file.exists()) {
      return;
    }

    if (file.isDirectory()) {
      final File[] files = file.listFiles();
      for (final File file2 : files) {
        runRanlib(file2, log);
      }
    }
    if (file.isFile() && file.canWrite() && !file.isHidden() && file.getName().endsWith(".a")) {
      // ranlib file
      final int result = runCommand("ranlib", new String[] {
        file.getPath()
      }, null, null, log);
      if (result != 0) {
        throw new MojoExecutionException("Failed to execute 'ranlib " + file.getPath() + "'" + " return code: \'"
            + result + "\'.");
      }
    }
  }

  private NarUtil() {
    // never instantiate
  }
}


text:
classdef hgwrapperlink < hgsetgetex
%HGWRAPPERLINK   To link HGWRAPPER objects
%   HGWRAPPERLINK implements a mechanism to link multiple HGWRAPPER
%   objects. HGWRAPPERLINK is intended to be inherited along with HGWRAPPER
%   (or its derived class):
%
%      classdef MyClass < HGWRAPPER & HGWRAPPERLINK
%
%   Otherwise, the linking mechanism will not function properly.
%
%   Only public entity of HGWRAPPERLINK is link() method and LinkedObjects
%   property.
%
%
%   HGWRAPPERLINK properties.
%      LinkedObjects      - Simultaneous deletion of HG object [{'on'}|'off']
%
%   HGWRAPPERLINK methods:
%   HGWRAPPERLINK object construction:
%      @HGWRAPPERLINK/HGWRAPPERLINK - Construct HGWRAPPERLINK object.
%      delete                       - Delete HGWRAPPERLINK object.
%
%   Object Linking:
%      link - Link HG object.
%
%   Getting and setting parameters:
%      get              - Get value of HGWRAPPERLINK object property.
%      set              - Set value of HGWRAPPERLINK object property.
%
%   See also: hgwrapperlink/hgwrapperlink, hgwrapperlink/link, hgwrapper,
%   hgsetgetex, handle

   properties
      LinkedObjects % Array of linked objects (empty double if not linked)
   end
   properties (Access=protected)
      links       % array of linked objects (empty hgwrapper if not linked)
   end
   properties (Access=private)
      link_master % true if the object can lead or is leading the change
                  % among linked objects
   end
   methods
      link(obj,opt) % link HGWRAPPER-based objects

      function obj = hgwrapperlink(varargin)
         %HGWRAPPERLINK/HGWRAPPERLINK   HGWRAPPERLINK constructor
         %   HGWRAPPERLINK - scalar object
         %
         %   HGWRAPPERLINK(H) creates HGWRAPPERLINK objects for the HG handle
         %   objects given in H and the created object has the same dimension as H.
         %
         %   HGWRAPPERLINK(N) creates an N-by-N matrix of detached HGWRAPPERLINK
         %   objects
         %
         %   HGWRAPPERLINK(M,N) creeates an M-by-N matrix of detached HGWRAPPERLINK
         %   objects
         %
         %   HGWRAPPERLINK(M,N,P,...) or HGWRAPPERLINK([M N P ....]) creates an
         %   M-by-N-by-P-by-... array of detached HGWRAPPERLINK objects.
         %
         %   HGWRAPPERLINK(SIZE(A)) creates detached HGWRAPPERLINK objects with the
         %   same size as A.
         %
         %   HGWRAPPERLINK(...,'Prop1Name',Prop1Value,'Prop2Name',Prop2Value,...)
         %   sets the properties of the created HGWRAPPERLINK objects. All objects
         %   are set to the same property values.
         %
         %   HGWRAPPERLINK(...,pn,pv) sets the named properties specified in the
         %   cell array of strings pn to the corresponding values in the cell array
         %   pv for all objects created .  The cell array pn must be 1-by-N, but the
         %   cell array pv can be M-by-N where M is equal to numel(OBJ) so that each
         %   object will be updated with a different set of values for the list of
         %   property names contained in pn.

         obj = obj@hgsetgetex(varargin{:});
      end

      function val = get.LinkedObjects(obj)
         if isempty(obj.links)
            val = [];
         else
            val = obj.links;
         end
      end

      function set.LinkedObjects(obj,val)
         obj.validatepropery('LinkedObjects',val);
         link([obj;val(:)]);
      end
   end

   methods (Access=protected)
      init(obj)
      tf = set_master_se(obj) % obj must be scalar (unchecked)
      clr_master_se(obj) % obj must be scalar (unchecked)
      tf = isslave_se(obj)    % true if obj is a slave
   end
end

redpajama_set_name: RedPajamaGithub


text:
var DebugClass = (function () {
    function DebugClass() {
    }
    DebugClass.debugFunc = function () {
        // Start Debugger Test Code
        var i = 0;

        // End Debugger Test Code
        return true;
    };
    return DebugClass;
})();


text:
package gotype

import (
	"errors"
	"fmt"
	"reflect"
	"unsafe"

	structform "github.com/urso/go-structform"
	stunsafe "github.com/urso/go-structform/internal/unsafe"
)

type userFoldFn func(unsafe.Pointer, structform.ExtVisitor) error

func makeUserFoldFn(fn reflect.Value) (userFoldFn, error) {
	t := fn.Type()

	if fn.Kind() != reflect.Func {
		return nil, errors.New("function type required")
	}

	if t.NumIn() != 2 {
		return nil, fmt.Errorf("function '%v' must accept 2 arguments", t.Name())
	}
	if t.NumOut() != 1 || t.Out(0) != tError {
		return nil, fmt.Errorf("function '%v' does not return errors", t.Name())
	}

	ta0 := t.In(0)
	if ta0.Kind() != reflect.Ptr {
		return nil, fmt.Errorf("first argument in function '%v' must be a pointer", t.Name())
	}

	ta1 := t.In(1)
	if ta1 != tExtVisitor {
		return nil, fmt.Errorf("second arument in function '%v' must be structform.ExtVisitor", t.Name())
	}

	fptr := *((*userFoldFn)(stunsafe.UnsafeFnPtr(fn)))
	return fptr, nil
}

func liftUserPtrFn(f userFoldFn) reFoldFn {
	return func(c *foldContext, v reflect.Value) error {
		if v.IsNil() {
			return f(nil, c.visitor)
		}
		return f(stunsafe.ReflValuePtr(v.Elem()), c.visitor)
	}
}

func liftUserValueFn(f userFoldFn) reFoldFn {
	return func(c *foldContext, v reflect.Value) error {
		return f(stunsafe.ReflValuePtr(v), c.visitor)
	}
}


text:
New Item

		<form name="itemForm" class="form-horizontal" data-ng-submit="create()" novalidate>
			<fieldset>

					Brand

						<input name="brand" type="text" data-ng-model="brand" id="brand" class="form-control" placeholder="Brand" required>

					category1

						<input name="category1" type="text" data-ng-model="category1" id="category1" class="form-control" placeholder="category1" required>

					category2

						<input name="category2" type="text" data-ng-model="category2" id="category2" class="form-control" placeholder="category2" required>

					short_description

						<input name="short_description" type="text" data-ng-model="short_description" id="short_description" class="form-control" placeholder="This is a good soothing cream product" required>

					long_description

						<input name="long_description" type="text" data-ng-model="long_description" id="long_description" class="form-control" placeholder="It has 80% mineral 20% water. It is very popular in Korea. blah blah" required>

					price

						<input name="price" type="text" data-ng-model="price" id="price" class="form-control" placeholder="10" required>

					<input type="submit" class="btn btn-default">

			</fieldset>
		</form>


text:
local meta = FindMetaTable("Player")

/*---------------------------------------------------------------------------
Pooled networking strings
---------------------------------------------------------------------------*/
util.AddNetworkString("DarkRP_InitializeVars")
util.AddNetworkString("DarkRP_PlayerVar")
util.AddNetworkString("DarkRP_PlayerVarRemoval")
util.AddNetworkString("DarkRP_DarkRPVarDisconnect")

/*---------------------------------------------------------------------------
Player vars
---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------
Remove a player's DarkRPVar
---------------------------------------------------------------------------*/
function meta:removeDarkRPVar(var, target)
    hook.Call("DarkRPVarChanged", nil, self, var, (self.DarkRPVars and self.DarkRPVars[var]) or nil, nil)
    target = target or player.GetAll()
    self.DarkRPVars = self.DarkRPVars or {}
    self.DarkRPVars[var] = nil

    net.Start("DarkRP_PlayerVarRemoval")
        net.WriteUInt(self:UserID(), 16)
        DarkRP.writeNetDarkRPVarRemoval(var)
    net.Send(target)
end

/*---------------------------------------------------------------------------
Set a player's DarkRPVar
---------------------------------------------------------------------------*/
function meta:setDarkRPVar(var, value, target)
    if not IsValid(self) then return end
    target = target or player.GetAll()

    if value == nil then return self:removeDarkRPVar(var, target) end
    hook.Call("DarkRPVarChanged", nil, self, var, (self.DarkRPVars and self.DarkRPVars[var]) or nil, value)

    self.DarkRPVars = self.DarkRPVars or {}
    self.DarkRPVars[var] = value

    net.Start("DarkRP_PlayerVar")
        net.WriteUInt(self:UserID(), 16)
        DarkRP.writeNetDarkRPVar(var, value)
    net.Send(target)
end

/*---------------------------------------------------------------------------
Set a private DarkRPVar
---------------------------------------------------------------------------*/
function meta:setSelfDarkRPVar(var, value)
    self.privateDRPVars = self.privateDRPVars or {}
    self.privateDRPVars[var] = true

    self:setDarkRPVar(var, value, self)
end

/*---------------------------------------------------------------------------
Get a DarkRPVar
---------------------------------------------------------------------------*/
function meta:getDarkRPVar(var)
    self.DarkRPVars = self.DarkRPVars or {}
    return self.DarkRPVars[var]
end

/*---------------------------------------------------------------------------
Send the DarkRPVars to a client
---------------------------------------------------------------------------*/
function meta:sendDarkRPVars()
    if self:EntIndex() == 0 then return end

    local plys = player.GetAll()

    net.Start("DarkRP_InitializeVars")
        net.WriteUInt(#plys, 8)
        for _, target in pairs(plys) do
            net.WriteUInt(target:UserID(), 16)

            local DarkRPVars = {}
            for var, value in pairs(target.DarkRPVars) do
                if self ~= target and (target.privateDRPVars or {})[var] then continue end
                table.insert(DarkRPVars, var)
            end

            net.WriteUInt(#DarkRPVars, DarkRP.DARKRP_ID_BITS + 2) -- Allow for three times as many unknown DarkRPVars than the limit
            for i = 1, #DarkRPVars, 1 do
                DarkRP.writeNetDarkRPVar(DarkRPVars[i], target.DarkRPVars[DarkRPVars[i]])
            end
        end
    net.Send(self)
end
concommand.Add("_sendDarkRPvars", function(ply)
    if ply.DarkRPVarsSent and ply.DarkRPVarsSent > (CurTime() - 3) then return end -- prevent spammers
    ply.DarkRPVarsSent = CurTime()
    ply:sendDarkRPVars()
end)

/*---------------------------------------------------------------------------
Admin DarkRPVar commands
---------------------------------------------------------------------------*/
local function setRPName(ply, args)
    if not args[2] or string.len(args[2]) < 2 or string.len(args[2]) > 30 then
        DarkRP.notify(ply, 1, 4, DarkRP.getPhrase("invalid_x", DarkRP.getPhrase("arguments"), "<2/>30"))
        return
    end

    local name = table.concat(args, " ", 2)

    local target = DarkRP.findPlayer(args[1])

    if target then
        local oldname = target:Nick()

        DarkRP.storeRPName(target, name)
        target:setDarkRPVar("rpname", name)

        DarkRP.notify(ply, 0, 4, DarkRP.getPhrase("you_set_x_name", oldname, name))

        local nick = ""
        if ply:EntIndex() == 0 then
            nick = "Console"
        else
            nick = ply:Nick()
        end
        DarkRP.notify(target, 0, 4, DarkRP.getPhrase("x_set_your_name", nick, name))
        if ply:EntIndex() == 0 then
            DarkRP.log("Console set " .. target:SteamName() .. "'s name to " .. name, Color(30, 30, 30))
        else
            DarkRP.log(ply:Nick() .. " (" .. ply:SteamID() .. ") set " .. target:SteamName() .. "'s name to " .. name, Color(30, 30, 30))
        end
    else
        DarkRP.notify(ply, 1, 4, DarkRP.getPhrase("could_not_find", args[1]))
    end
end
DarkRP.definePrivilegedChatCommand("forcerpname", "DarkRP_AdminCommands", setRPName)

local function freerpname(ply, args)
    local name = args ~= "" and args or IsValid(ply) and ply:Nick() or ""

    MySQLite.query(("UPDATE darkrp_player SET rpname = NULL WHERE rpname = %s"):format(MySQLite.SQLStr(name)))

    local nick = IsValid(ply) and ply:Nick() or "Console"
    DarkRP.log(("%s has freed the rp name '%s'"):format(nick, name), Color(30, 30, 30))
    DarkRP.notify(ply, 0, 4, ("'%s' has been freed"):format(name))
end
DarkRP.definePrivilegedChatCommand("freerpname", "DarkRP_AdminCommands", freerpname)

local function RPName(ply, args)
    if ply.LastNameChange and ply.LastNameChange > (CurTime() - 5) then
        DarkRP.notify(ply, 1, 4, DarkRP.getPhrase("have_to_wait",  math.ceil(5 - (CurTime() - ply.LastNameChange)), "/rpname"))
        return ""
    end

    if not GAMEMODE.Config.allowrpnames then
        DarkRP.notify(ply, 1, 6, DarkRP.getPhrase("disabled", "RPname", ""))
        return ""
    end

    args = args:find"^%s*$" and '' or args:match'^%s*(.*%S)'

    local canChangeName, reason = hook.Call("CanChangeRPName", GAMEMODE, ply, args)
    if canChangeName == false then
        DarkRP.notify(ply, 1, 4, DarkRP.getPhrase("unable", "RPname", reason or ""))
        return ""
    end

    ply:setRPName(args)
    ply.LastNameChange = CurTime()
    return ""
end
DarkRP.defineChatCommand("rpname", RPName)
DarkRP.defineChatCommand("name", RPName)
DarkRP.defineChatCommand("nick", RPName)

/*---------------------------------------------------------------------------
Setting the RP name
---------------------------------------------------------------------------*/
function meta:setRPName(name, firstRun)
    -- Make sure nobody on this server already has this RP name
    local lowername = string.lower(tostring(name))
    DarkRP.retrieveRPNames(name, function(taken)
        if string.len(lowername) < 2 and not firstrun then return end
        -- If we found that this name exists for another player
        if taken then
            if firstRun then
                -- If we just connected and another player happens to be using our steam name as their RP name
                -- Put a 1 after our steam name
                DarkRP.storeRPName(self, name .. " 1")
                DarkRP.notify(self, 0, 12, DarkRP.getPhrase("someone_stole_steam_name"))
            else
                DarkRP.notify(self, 1, 5, DarkRP.getPhrase("unable", "RPname", DarkRP.getPhrase("already_taken")))
                return ""
            end
        else
            if not firstRun then -- Don't save the steam name in the database
                DarkRP.notifyAll(2, 6, DarkRP.getPhrase("rpname_changed", self:SteamName(), name))
                DarkRP.storeRPName(self, name)
            end
        end
    end)
end

/*---------------------------------------------------------------------------
Maximum entity values
---------------------------------------------------------------------------*/
local maxEntities = {}
function meta:addCustomEntity(entTable)
    if not entTable then return end

    maxEntities[self] = maxEntities[self] or {}
    maxEntities[self][entTable.cmd] = maxEntities[self][entTable.cmd] or 0
    maxEntities[self][entTable.cmd] = maxEntities[self][entTable.cmd] + 1
end

function meta:removeCustomEntity(entTable)
    if not entTable.cmd then return end

    maxEntities[self] = maxEntities[self] or {}
    maxEntities[self][entTable.cmd] = maxEntities[self][entTable.cmd] or 0
    maxEntities[self][entTable.cmd] = maxEntities[self][entTable.cmd] - 1
end

function meta:customEntityLimitReached(entTable)
    maxEntities[self] = maxEntities[self] or {}
    maxEntities[self][entTable.cmd] = maxEntities[self][entTable.cmd] or 0

    return maxEntities[self][entTable.cmd] >= (entTable.getMax and entTable.getMax(self) or entTable.max)
end

hook.Add("PlayerDisconnected", "removeLimits", function(ply)
    maxEntities[ply] = nil
    net.Start("DarkRP_DarkRPVarDisconnect")
        net.WriteUInt(ply:UserID(), 16)
    net.Broadcast()
end)


text:
This repository contains a code sample for Vault that generates a report on Mail
holds and copies them for Hangouts Chat.

Documentation is available on the
[Google Developers site](https://developers.google.com/vault/guides/chat).


text:
#include "mirtk/Common.h"
#include "mirtk/Options.h"

#include "mirtk/Vtk.h"
#include "mirtk/IOConfig.h"
#include "mirtk/GenericImage.h"
#include "mirtk/PointSetIO.h"
#include "mirtk/Transformation.h"

#include "vtkSmartPointer.h"
#include "vtkDataSetReader.h"
#include "vtkXMLGenericDataObjectReader.h"
#include "vtkDataSet.h"
#include "vtkImageData.h"
#include "vtkPointSet.h"
#include "vtkPoints.h"
#include "vtkPointData.h"
#include "vtkCellData.h"
#include "vtkPolyDataNormals.h"
#include "vtkImageDataToPointSet.h"

using namespace mirtk;

// =============================================================================
// Help
// =============================================================================

// -----------------------------------------------------------------------------
void PrintHelp(const char *name)
{
  cout << endl;
  cout << "Usage: " << name << " [options]" << endl;
  cout << "       " << name << " <input> <output> [options]" << endl;
  cout << endl;
  cout << "Description:" << endl;
  cout << "  Applies one or more transformations to a set of points. Input point" << endl;
  cout << "  x, y, and z coordinates are either read from STDIN (space separated) or from a" << endl;
  cout << "  point set file. The corresponding transformed coordinates are then written" << endl;
  cout << "  either to STDOUT or an output point set file, respectively. If multiple" << endl;
  cout << "  transformations are specified, these are applied in the order as they appear" << endl;
  cout << "  on the command line." << endl;
  cout << endl;
  cout << "Optional arguments:" << endl;
  cout << "  -dofin <file>...   Transformation file. (default: identity)" << endl;
  cout << "  -invert            Invert preceding transformation. (default: no)" << endl;
  cout << "  -source <image>    Reference source image. (default: none)" << endl;
  cout << "  -target <image>    Reference target image. (default: none)" << endl;
  cout << "  -partial <n>       Transform the first n points and copy the rest. (default: #points)" << endl;
  cout << "  -normals           Whether to recompute normals of input surface mesh. (default: off)" << endl;
  cout << "  -point-normals     Whether to recompute point normals of input surface mesh. (default: off)" << endl;
  cout << "  -cell-normals      Whether to recompute cell  normals of input surface mesh. (default: off)" << endl;
  cout << "  -[no]compress      Enable/disable compression of XML VTK file. (default: on)" << endl;
  cout << "  -ascii             Set file type of output legacy VTK file to ASCII.  (default: input file type)" << endl;
  cout << "  -binary            Set file type of output legacy VTK file to BINARY. (default: input file type)" << endl;
  PrintStandardOptions(cout);
  cout << endl;
}

// =============================================================================
// Main
// =============================================================================

// -----------------------------------------------------------------------------
int main(int argc, char **argv)
{
  REQUIRES_POSARGS(0);

  // Nevertheless, show help if called without arguments
  if (argc == 1) {
    PrintHelp(EXECNAME);
    exit(1);
  }

  // Initialize image I/O library
  InitializeIOLibrary();

  vtkSmartPointer<vtkPointSet> pointset;
  PointSet                     points;

  // Positional arguments
  const char *input_name  = NULL;
  const char *output_name = NULL;

  if (NUM_POSARGS == 2) {
    input_name  = POSARG(1);
    output_name = POSARG(2);
  } else if (NUM_POSARGS != 0) {
    PrintHelp(EXECNAME);
    exit(1);
  }

  // Optional arguments
  Array<const char *> dofin_name;
  Array<bool>         dofin_invert;
  GreyImage           target, source;
  FileOption          fopt = FO_Default;

  bool compute_point_normals = false;
  bool compute_cell_normals  = false;
  int  pnumber               = 0;

  double tt = 0., ts = 1.; // Temporal origin, used by velocity based transformations

  for (ALL_OPTIONS) {
    if (OPTION("-dofin")) {
      do {
        dofin_name.push_back(ARGUMENT);
      } while (HAS_ARGUMENT);
      while (dofin_invert.size() < dofin_name.size()) {
        dofin_invert.push_back(false);
      }
    }
    else if (OPTION("-invert")) {
      if (dofin_invert.empty()) dofin_invert.push_back(true);
      else dofin_invert.back() = true;
    }
    else if (OPTION("-Tt")) tt = atof(ARGUMENT);
    else if (OPTION("-St")) ts = atof(ARGUMENT);
    else if (OPTION("-source")) source.Read(ARGUMENT);
    else if (OPTION("-target")) target.Read(ARGUMENT);
    else if (OPTION("-partial")) {
      const char *arg = ARGUMENT;
      if (!FromString(arg, pnumber)) {
        cerr << "Failed to convert -partial argument " << arg << " to integer" << endl;
        exit(1);
      }
    }
    else if (OPTION("-normals")) compute_point_normals = compute_cell_normals = true;
    else if (OPTION("-point-normals")) compute_point_normals = true;
    else if (OPTION("-cell-normals")) compute_cell_normals = true;
    else HANDLE_POINTSETIO_OPTION(fopt);
    else HANDLE_STANDARD_OR_UNKNOWN_OPTION();
  }
  dofin_invert.resize(dofin_name.size(), false);

  // Read input points
  double p[3];
  if (input_name) {
    const bool exit_on_failure = false;
    pointset = ReadPointSet(input_name, exit_on_failure);
    if (!pointset) {
      vtkSmartPointer<vtkDataSet> dataset;
      const string ext = Extension(input_name);
      if (ext == ".vtk") {
        vtkNew<vtkDataSetReader> reader;
        reader->SetFileName(input_name);
        reader->Update();
        dataset = reader->GetOutput();
        if (fopt == FO_Default) {
          fopt = (reader->GetFileType() == VTK_ASCII ? FO_ASCII : FO_Binary);
        }
      } else {
        vtkNew<vtkXMLGenericDataObjectReader> reader;
        reader->SetFileName(input_name);
        reader->Update();
        dataset = vtkDataSet::SafeDownCast(reader->GetOutput());
      }
      vtkImageData *image = vtkImageData::SafeDownCast(dataset);
      if (!image) {
        FatalError("Input VTK dataset must be either of type vtkPointSet or vtkImageData");
      }
      vtkNew<vtkImageDataToPointSet> converter;
      SetVTKInput(converter, image);
      converter->Update();
      pointset = converter->GetOutput();
    }
    if (pointset->GetNumberOfPoints() == 0) {
      FatalError("Input VTK data set has no points");
    }
    points.Resize(pointset->GetNumberOfPoints());
    for (vtkIdType i = 0; i < pointset->GetNumberOfPoints(); ++i) {
      pointset->GetPoint(i, points(i));
    }
  } else {
    while (cin) {
      cin >> p[0] >> p[1] >> p[2];
      if (!cin) break;
      points.Add(p);
    }
    points.ShrinkToFit();
  }
  if (pnumber <= 0) pnumber = points.Size();

  // Map all points from target world to source world
  if (!target.IsEmpty() && !source.IsEmpty()) {
    for (int i = 0; i < points.Size(); ++i) {
      Point &pt = points(i);
      target.WorldToImage(pt);
      source.ImageToWorld(pt);
    }
  }

  // Transform first pnumber points
  for (size_t i = 0; i < dofin_name.size(); ++i) {
    UniquePtr<Transformation> dofin(Transformation::New(dofin_name[i]));
    if (dofin_invert[i]) {
      if (verbose) cout << "Apply inverse of " << dofin_name[i] << endl;
      for (int i = 0; i < pnumber; ++i) dofin->Inverse(points(i), ts, tt);
    } else {
      if (verbose) cout << "Apply " << dofin_name[i] << endl;
      for (int i = 0; i < pnumber; ++i) dofin->Transform(points(i), ts, tt);
    }
  }

  if (pointset) {

    // Set output points
    vtkPoints *output_points = pointset->GetPoints();
    for (int i = 0; i < pnumber; ++i) {
      const Point &pt = points(i);
      output_points->SetPoint(i, pt._x, pt._y, pt._z);
    }

    // Generate surface normals
    if (pointset->GetPointData()->HasArray("Normals")) compute_point_normals = true;
    if (pointset->GetCellData ()->HasArray("Normals")) compute_cell_normals  = true;

    if (compute_point_normals || compute_cell_normals) {
      vtkSmartPointer<vtkPolyDataNormals> normals;
      normals = vtkSmartPointer<vtkPolyDataNormals>::New();
      SetVTKInput(normals, pointset);
      normals->SplittingOff();
      normals->ConsistencyOn();
      normals->SetComputePointNormals(compute_point_normals);
      normals->SetComputeCellNormals (compute_cell_normals);
      normals->Update();
      pointset = normals->GetOutput();
    }

    // Write the final dataset
    WritePointSet(output_name, pointset, fopt);

  } else {

    // Print transformed points
    for (int i = 0; i < points.Size(); ++i) {
      const Point &pt = points(i);
      cout << pt._x << " " << pt._y << " " << pt._z << endl;
    }

  }

  return 0;
}


text:
Write a program that will take a year and report if it is a leap year.

The tricky thing here is that a leap year in the Gregorian calendar occurs:

```plain
on every year that is evenly divisible by 4
  except every year that is evenly divisible by 100
    unless the year is also evenly divisible by 400
```

For example, 1997 is not a leap year, but 1996 is.  1900 is not a leap
year, but 2000 is.

If your language provides a method in the standard library that does
this look-up, pretend it doesn't exist and implement it yourself.

## Notes

Though our exercise adopts some very simple rules, there is more to
learn!

For a delightful, four minute explanation of the whole leap year
phenomenon, go watch [this youtube video][video].

[video]: http://www.youtube.com/watch?v=xX96xng7sAE

## Running tests

Execute the tests with:

```bash
$ elixir bob_test.exs
```

(Replace `bob_test.exs` with the name of the test file.)

### Pending tests

In the test suites, all but the first test have been skipped.

Once you get a test passing, you can unskip the next one by
commenting out the relevant `@tag :pending` with a `#` symbol.

For example:

```elixir
# @tag :pending
test "shouting" do
  assert Bob.hey("WATCH OUT!") == "Whoa, chill out!"
end
```

Or, you can enable all the tests by commenting out the
`ExUnit.configure` line in the test suite.

```elixir
# ExUnit.configure exclude: :pending, trace: true
```

For more detailed information about the Elixir track, please
see the [help page](http://exercism.io/languages/elixir).

## Source

JavaRanch Cattle Drive, exercise 3 [http://www.javaranch.com/leap.jsp](http://www.javaranch.com/leap.jsp)


text:
package com.haskforce;

import com.intellij.ide.util.projectWizard.JavaModuleBuilder;
import com.intellij.ide.util.projectWizard.ModuleBuilderListener;
import com.intellij.ide.util.projectWizard.ModuleWizardStep;
import com.intellij.ide.util.projectWizard.SettingsStep;
import com.intellij.ide.util.projectWizard.SourcePathsBuilder;
import com.intellij.ide.util.projectWizard.WizardContext;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleType;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.projectRoots.SdkTypeId;
import com.intellij.openapi.roots.ModifiableRootModel;
import com.intellij.openapi.util.text.StringUtil;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class HaskellModuleBuilder extends JavaModuleBuilder implements SourcePathsBuilder, ModuleBuilderListener {
    @Override
    public void setupRootModel(ModifiableRootModel rootModel) throws ConfigurationException {
        addListener(this);
        super.setupRootModel(rootModel);
    }

    /**
     * Returns the Haskell module type.
     */
    @Override
    public ModuleType getModuleType() {
        return HaskellModuleType.getInstance();
    }

    /**
     * Ensures that SDK type is a Haskell SDK.
     */
    @Override
    public boolean isSuitableSdkType(SdkTypeId sdkType) {
        return sdkType == HaskellSdkType.getInstance();
    }

    /**
     * Called after module is created.
     */
    @Override
    public void moduleCreated(@NotNull Module module) {
        // TODO - We should probably do some project initialization here as well...

        // Update the ignored files and folders to avoid file search showing compiled files.
        FileTypeManager fileTypeManager = FileTypeManager.getInstance();
        StringBuilder builder = new StringBuilder(fileTypeManager.getIgnoredFilesList());
        // Ensure the ignored file list ends with a semicolon.
        if (builder.charAt(builder.length() - 1) != ';') {
            builder.append(';');
        }
        for (String ignore : new String[]{"*.dyn_hi", "*.dyn_hi", "*.dyn_o", "*.hi", "*.o"}) {
            if (builder.indexOf(';' + ignore + ';') == -1) {
                builder.append(ignore).append(';');
            }
        }
        fileTypeManager.setIgnoredFilesList(builder.toString());
    }

    /**
     * Hook into the new project creation and set dist to the compiler output
     * directory.
     */
    @Override
    @Nullable
    public ModuleWizardStep modifySettingsStep(@NotNull SettingsStep settingsStep) {
        if (settingsStep.getContext().isCreatingNewProject() &&
                settingsStep.getContext().isProjectFileDirectorySet()) {
            WizardContext c = settingsStep.getContext();
            String path = c.getProjectFileDirectory();
            String out = StringUtil.endsWithChar(path, '/') ? path + "dist" : path + "/dist";
            c.setCompilerOutputDirectory(out);
        }
        return super.modifySettingsStep(settingsStep);
    }

    @Override
    public int hashCode() {
        return HashCodeBuilder.reflectionHashCode(this);
    }
}


text:
PublicBodyCategories.add(:en, [
    "Silly ministries",
        [ "useless_agency", "Useless ministries", "a useless ministry" ],
        [ "lonely_agency", "Lonely agencies", "a lonely agency"],
    "Popular agencies",
        [ "popular_agency", "Popular agencies", "a lonely agency"]
])


text:
import { skipUntil } from '../../operator/skipUntil';
declare module '../../Observable' {
    interface Observable<T> {
        skipUntil: typeof skipUntil;
    }
}


text:
import React, { Component } from 'react';

export default class Image extends Component {
	constructor(props){
		super(props);
		this.state = {
			select: [],
			fadeIndex: 0
		}
	}

	componentWillMount() {
		if(this.props.selectClass !== "no-display"){
		  const number = this.props.sources.length;
		  const select = new Array(number);
		  select.fill("fade-out");
		  select[0] = "fade-in";
		  this.setState({ select });
		}
	}

	_handleClick(i, o){
		if(this.state.select.length > 1){
			i = i < 0 ? this.state.select.length - 1 : i;
			i = i >= this.state.select.length ? 0 : i;
			const odd = this.state.select[i] === "fade-out" ? "fade-in" : "fade-out";
			const even = this.state.select[o] === "fade-out" ? "fade-in" : "fade-out";
			const select = this.state.select;
			const fadeIndex = i;
			select.fill("fade-out");
			select[i] = odd; select[o] = even;
			this.setState({ select, fadeIndex });
		}
	}

  render() {
  	return(

  			{
			   	this.props.sources.map((img, i)=>{
			   		return (

			   		)
			   	})
			  }

			  	{let i = this.state.fadeIndex++, o = i--; this._handleClick(i, o)}} />
			  	{let i = this.state.fadeIndex--, o = i++; this._handleClick(i, o)}} />

	  )
   }
}


text:
package com.mikepenz.crossfader.util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.util.DisplayMetrics;
import android.view.View;

/**
 * Created by mikepenz on 15.03.14.
 */
@SuppressLint("InlinedApi")
public class UIUtils {
    /**
     * This method converts dp unit to equivalent pixels, depending on device density.
     *
     * @param dp      A value in dp (density independent pixels) unit. Which we need to convert into pixels
     * @param context Context to get resources and device specific display metrics
     * @return A float value to represent px equivalent to dp depending on device density
     */
    public static float convertDpToPixel(float dp, Context context) {
        Resources resources = context.getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        float px = dp * (metrics.densityDpi / 160f);
        return px;
    }

    /**
     * This method converts device specific pixels to density independent pixels.
     *
     * @param px      A value in px (pixels) unit. Which we need to convert into db
     * @param context Context to get resources and device specific display metrics
     * @return A float value to represent dp equivalent to px value
     */
    public static float convertPixelsToDp(float px, Context context) {
        Resources resources = context.getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        float dp = px / (metrics.densityDpi / 160f);
        return dp;
    }

    /**
     * Determines if given points are inside view
     *
     * @param x    - x coordinate of point
     * @param y    - y coordinate of point
     * @param view - view object to compare
     * @return true if the points are within view bounds, false otherwise
     */
    public static boolean isPointInsideView(float x, float y, View view) {
        int location[] = new int[2];
        view.getLocationOnScreen(location);
        int viewX = location[0];
        int viewY = location[1];

        //point is inside view bounds
        if ((viewX < x && x < (viewX + view.getWidth())) &&
                (viewY < y && y < (viewY + view.getHeight()))) {
            return true;
        } else {
            return false;
        }
    }
}


text:
package org.apache.druid.server.coordinator;

import com.fasterxml.jackson.annotation.JacksonInject;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.google.common.util.concurrent.ListeningExecutorService;
import org.apache.druid.client.ServerInventoryView;
import org.apache.druid.client.ServerView;
import org.apache.druid.java.util.common.concurrent.Execs;
import org.apache.druid.java.util.common.lifecycle.Lifecycle;
import org.apache.druid.java.util.common.lifecycle.LifecycleStart;
import org.apache.druid.java.util.common.lifecycle.LifecycleStop;
import org.apache.druid.java.util.emitter.EmittingLogger;
import org.apache.druid.server.coordination.DruidServerMetadata;
import org.apache.druid.server.coordinator.cost.ClusterCostCache;
import org.apache.druid.timeline.DataSegment;

import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;

public class CachingCostBalancerStrategyFactory implements BalancerStrategyFactory
{
  private static final EmittingLogger LOG = new EmittingLogger(CachingCostBalancerStrategyFactory.class);

  /** Must be single-threaded, because {@link ClusterCostCache.Builder} and downstream builders are not thread-safe */
  private final ExecutorService executor = Execs.singleThreaded("CachingCostBalancerStrategy-executor");
  private final ClusterCostCache.Builder clusterCostCacheBuilder = ClusterCostCache.builder();
  /**
   * Atomic is needed to use compareAndSet(true, true) construction below, that is linearizable with the write made from
   * callback, that ensures visibility of the write made from callback. Neither plain field nor volatile field read
   * ensure such visibility
   */
  private final AtomicBoolean initialized = new AtomicBoolean(false);

  @JsonCreator
  public CachingCostBalancerStrategyFactory(
      @JacksonInject ServerInventoryView serverInventoryView,
      @JacksonInject Lifecycle lifecycle
  ) throws Exception
  {
    // Adding to lifecycle dynamically because couldn't use @ManageLifecycle on the class,
    // see https://github.com/apache/incubator-druid/issues/4980
    lifecycle.addMaybeStartManagedInstance(this);

    serverInventoryView.registerSegmentCallback(
        executor,
        new ServerView.SegmentCallback()
        {
          @Override
          public ServerView.CallbackAction segmentAdded(DruidServerMetadata server, DataSegment segment)
          {
            if (server.segmentReplicatable()) {
              clusterCostCacheBuilder.addSegment(server.getName(), segment);
            }
            return ServerView.CallbackAction.CONTINUE;
          }

          @Override
          public ServerView.CallbackAction segmentRemoved(DruidServerMetadata server, DataSegment segment)
          {
            if (server.segmentReplicatable()) {
              clusterCostCacheBuilder.removeSegment(server.getName(), segment);
            }
            return ServerView.CallbackAction.CONTINUE;
          }

          @Override
          public ServerView.CallbackAction segmentViewInitialized()
          {
            initialized.set(true);
            return ServerView.CallbackAction.CONTINUE;
          }
        }
    );

    serverInventoryView.registerServerRemovedCallback(
        executor,
        server -> {
          if (server.segmentReplicatable()) {
            clusterCostCacheBuilder.removeServer(server.getName());
          }
          return ServerView.CallbackAction.CONTINUE;
        }
    );
  }

  @LifecycleStart
  public void start()
  {
    // do nothing
  }

  @LifecycleStop
  public void stop()
  {
    executor.shutdownNow();
  }

  @Override
  public BalancerStrategy createBalancerStrategy(final ListeningExecutorService exec)
  {
    if (initialized.compareAndSet(true, true)) {
      try {
        // Calling clusterCostCacheBuilder.build() in the same thread (executor's sole thread) where
        // clusterCostCacheBuilder is updated, to avoid problems with concurrent updates
        CompletableFuture<CachingCostBalancerStrategy> future = CompletableFuture.supplyAsync(
            () -> new CachingCostBalancerStrategy(clusterCostCacheBuilder.build(), exec),
            executor
        );
        try {
          return future.get();
        }
        catch (CancellationException e) {
          LOG.error("CachingCostBalancerStrategy creation has been cancelled");
        }
        catch (ExecutionException e) {
          LOG.error(e, "Failed to create CachingCostBalancerStrategy");
        }
        catch (InterruptedException e) {
          LOG.error("CachingCostBalancerStrategy creation has been interrupted");
          Thread.currentThread().interrupt();
        }
      }
      catch (RejectedExecutionException e) {
        LOG.error("CachingCostBalancerStrategy creation has been rejected");
      }
    } else {
      LOG.error("CachingCostBalancerStrategy could not be created as serverView is not initialized yet");
    }
    LOG.info("Fallback to CostBalancerStrategy");
    return new CostBalancerStrategy(exec);
  }
}


text:
import {getTodos, createTodo, updateTodo, destroyTodo} from '../lib/todoServices'
import {showMessage} from './messages'

const initialState = {
  todos: [],
  currentTodo: ''
}
//ACTIONS TYPES
export const TODO_ADD = 'TODO_ADD'
export const TODOS_LOAD = 'TODOS_LOAD'
const CURRENT_UPDATE = 'CURRENT_UPDATE'
export const TODO_REPLACE = 'TODO_REPLACE'
export const TODO_REMOVE = 'TODO_REMOVE'
//ACTIONS
export default (state = initialState, action) => {
  switch (action.type) {
    case TODO_ADD:
      return {...state, currentTodo: '', todos:[...state.todos, action.payload]}
    case TODOS_LOAD:
      return {...state, todos: action.payload}
    case CURRENT_UPDATE:
      return {...state, currentTodo: action.payload}
    case TODO_REPLACE:
      return {...state, todos: state.todos.map(t => t.id === action.payload.id ? action.payload : t)}
    case TODO_REMOVE:
      return {...state, todos: state.todos.filter(t => t.id !== action.payload)}
    default:
      return state
  }
}

//ACTIONS CREATORS
export const updateCurrent = (val) => ({type: 'CURRENT_UPDATE', payload: val});
export const loadTodos = (todos) => ({type:TODOS_LOAD, payload: todos});
export const addTodo = (todo) => ({type: TODO_ADD, payload: todo})
export const replaceTodo = (todo) => ({type: TODO_REPLACE, payload: todo})
export const removeTodo = (id) => ({type: TODO_REMOVE, payload: id})

export const fetchTodos = () => {
  return (dispatch) => {
    dispatch(showMessage('Loading Todos'))
    getTodos().then(todos => dispatch(loadTodos(todos)))
  }
}

export const saveTodo = (name) => {
  return (dispatch) => {
    dispatch(showMessage('Saving Todo'))
    createTodo(name).then(res=>dispatch(addTodo(res)))
  }
}

export const toggleTodo = (id) => {
  return (dispatch, getState)=>{
    dispatch(showMessage('Saving todo update'))
    const {todos} = getState().todo
    const todo = todos.find(t => t.id === id)
    const toggled = {...todo, isComplete: !todo.isComplete }
    updateTodo(toggled).then(res => dispatch(replaceTodo(res)))
  }
}

export const deleteTodo = (id) => {
  return (dispatch) => {
    dispatch(showMessage('Removing Todo'))
    destroyTodo(id).then(()=> dispatch(removeTodo(id)))
  }
}
export const getVisibleTodos = (todos, filter) => {
  switch (filter) {
    case 'active':
      return todos.filter(t => !t.isComplete)
    case 'completed':
      return todos.filter(t => t.isComplete)
    default:
      return todos
  }
}


text:
package federation

import (
	"fmt"
	"log"
	"net/http"

	"github.com/justinas/alice"
	"github.com/rs/cors"
	"github.com/stellar/federation/db"
	"github.com/stellar/federation/db/drivers/mysql"
	"github.com/stellar/federation/db/drivers/postgres"
	"github.com/stellar/federation/db/drivers/sqlite3"
)

type Database interface {
	Get(dest interface{}, query string, args ...interface{}) error
}

type App struct {
	config Config
	driver db.Driver
}

// NewApp constructs an new App instance from the provided config.
func NewApp(config Config) (*App, error) {
	var driver db.Driver
	switch config.Database.Type {
	case "mysql":
		driver = &mysql.MysqlDriver{}
	case "postgres":
		driver = &postgres.PostgresDriver{}
	case "sqlite3":
		driver = &sqlite3.Sqlite3Driver{}
	default:
		return nil, fmt.Errorf("%s database has no driver.", config.Database.Type)
	}

	err := driver.Init(config.Database.Url)
	if err != nil {
		return nil, err
	}

	result := &App{config: config, driver: driver}
	return result, nil
}

func (a *App) Serve() {
	requestHandler := &RequestHandler{config: &a.config, driver: a.driver}

	c := cors.New(cors.Options{
		AllowedOrigins: []string{"*"},
		AllowedHeaders: []string{"*"},
		AllowedMethods: []string{"GET"},
	})

	handler := alice.New(
		c.Handler,
		headersMiddleware(),
	).Then(http.HandlerFunc(requestHandler.Main))

	http.Handle("/federation", handler)
	http.Handle("/federation/", handler)

	portString := fmt.Sprintf(":%d", a.config.Port)

	log.Println("Starting server on port: ", a.config.Port)

	var err error
	if a.config.Tls.CertificateFile != "" && a.config.Tls.PrivateKeyFile != "" {
		err = http.ListenAndServeTLS(
			portString,
			a.config.Tls.CertificateFile,
			a.config.Tls.PrivateKeyFile,
			nil,
		)
	} else {
		err = http.ListenAndServe(portString, nil)
	}

	if err != nil {
		log.Fatal(err)
	}
}


text:
module Tmdb
  class List < Struct
  end
end


text:
This is a collection of workflows for automating text processing. I can't stand working with things like MS Word or Powerpoint. Even Libreoffice, despite being open source, its a pain, and I'm sorry to say that. The only "office productivity" system I can tolerate to some extent is Google Drive apps because it's great when there is a team that don't know (and don't want to know) about GIT. But the term "office productivity" is offending when applied to those systems. That's how I feel about them. No offense intended and no beligerance against other's way of doing things. Use the tool that makes the work done. It just happen that those are not my tools of choice.

>>>> Talk about Adobe's stack

Seventie's flavored __LaTeX__ philosophy is my way to go. But LaTeX itself is too cumbersome too. Although there are out there great tools for writing __TeX__, like for example __LyX__, I don't like this kind of WYSIWYG tools either. Call me stubborn, but I'd like to stick to my Emacs.

Emacs has powerfull modes for working with LaTeX, but the problem is LaTeX itself. For 95% of the time I'm writing just text, not complicated math formulas or whatever. So I'd like to have a tool for handling plain text in a comfortable and easy fashion whilst allowing me to insert custom LaTeX if needs be.

This tool exists, is awesome and is open source. It's name is [Pandoc](http://pandoc.org/), is brougth to us by the great [John MacFarlane](http://johnmacfarlane.net/), a Philosophy Professor at Berkeley. As he likes to put it, "Pandoc is your swiss-army knife" for text processing workflows.

Pandoc is great in a way that lets you create content in, say, Markdown (my format of choice) or ReStructured text and it puts together the necessary workflow to convert them to PDF, presentations or whatever the format you need. Pandoc can be teamed up with other great tools, like for example [ImageMagick](http://www.imagemagick.org) for image processing, or [Jinja2](http://jinja.pocoo.org/) for templating, and create from a single set of source text files a book in PDF, a summary on Word's Doc, a set of slides for presentations, or a nice static HTML set of pages.

So this is what this repository is all about: different workflows I'm been using, testing, and/or investigating to streamline my writing process and set me free of this kind of things like "a couple of newly inserted images completely screwed up my ~250 pages thesis in Word".

# General Workflow

A _pandoc_ build call looks like this:

```Shell
pandoc src/Chapter00.md src/Chapter01.md templates/Memoir/Memoir.yaml -s --chapters --table-of-contents --number-sections --template="templates/Memoir/Memoir.tex" -o out/Book.pdf
```

which means:

- after the __pandoc__ executable comes the string of source __.md__ files to build. The last one of them must be the configured __YAML__ file for the template being used;

- __-s__ means to create a standalone document;

- __--chapters__ tells pandoc to honor chapters. Not all document types honor chapters;

- __--table-of-contents__ creates a table of contents;

- __--number-sections__ asks pandoc to number sections;

- __--template__ tells pandoc which template to use to render the document. A compatible __YAML__ configuration file must be specified, as explained earlier;

- __-o__ finally tells pandoc where to put the final result.

This pandoc calls may vary from case to case, depending on the LaTeX template being used. Some switches may not have sense with all templates. Refer to each template documentation for more details.

When writing, is nice to have a __Makefile__ with the most used operations at hand, something like this:

```Makefile
# Makefile for building the project into PDF

# Pandoc executable
PANDOC=pandoc

# Build all
all: all-pdf all-latex chapter00-pdf chapter01-pdf

# A single PDF with all contents
all-pdf:
	$(PANDOC) src/00-Intro_PostGIS.md src/01-Another_chapter.md templates/metadata.yaml -s --chapters --table-of-contents --number-sections --template="templates/malkab-template.tex" -o out/Book.pdf

# A single LaTeX with all contents
all-latex:
	$(PANDOC) src/00-Intro_PostGIS.md src/01-Another_chapter.md templates/metadata.yaml -s --chapters --table-of-contents --number-sections --template="templates/malkab-template.tex" -o out/Book.tex

# Chapter 00 PDF
chapter00-pdf:
	$(PANDOC) src/00-Intro_PostGIS.md templates/metadata.yaml -s --chapters --table-of-contents --number-sections --template="templates/malkab-template.tex" -o out/Chapter00.pdf

# Chapter 01 PDF
chapter01-pdf:
	$(PANDOC) src/01-Another_chapter.md templates/metadata.yaml -s --chapters --table-of-contents --number-sections --template="templates/malkab-template.tex" -o out/Chapter01.pdf
```

# Metadata Configuration File

The configuration file is a YAML file that configures the template being used in the building process. Each LaTeX template should have its unique configuration file, because different templates can be configured in different ways.

# How to Create a New Template

Just take one of the existing ones and modify, or start from scratch. Try not to create a too broad template. For example, restrict to a single \documentclass to make things easy. A template must have the LaTeX template itself (_.tex_), a configuration file (_.yaml_), and a documentation _README.md_ to describe configuration capabilities.

A real project layout should be very similar to this one.


text:
import "../../styles/main.scss";

import React, { Component } from "react";

import Header from "./Header";

export default class App extends Component {
    render() {
        return (

                        Holder de ord er avviklet. Styret har
                        en dialog med en interessent om mulig overtagelse av
                        tjenestene.

                            Spørsmål? Ta{" "}

                                kontakt

                            .

        );
    }
}


text:
"use strict";

var invariant = require(`invariant`);
var regex = new RegExp(`[^a-zA-Z0-9_]`, `g`);

/**
 * GraphQL field names must be a string and cannot contain anything other than
 * alphanumeric characters and `_`. They also can't start with `__` which is
 * reserved for internal fields (`___foo` doesn't work either).
 */
module.exports = function (key) {
  // Check if the key is really a string otherwise GraphQL will throw.
  invariant(typeof key === `string`, `Graphql field name (key) is not a string -> ${key}`);

  return key.replace(regex, `_`);
};
//# sourceMappingURL=create-key.js.map


text:
require "spec_helper"

describe Dhis2::Api::Version226::ReportTable do
  it_behaves_like "a DHIS2 listable resource",  version: "2.26"
  it_behaves_like "a DHIS2 findable resource",  version: "2.26"
  it_behaves_like "a DHIS2 creatable resource", version: "2.26", nil_id: true
  it_behaves_like "a DHIS2 updatable resource", version: "2.26"
  it_behaves_like "a DHIS2 deletable resource", version: "2.26"
end


text:
""" The instance type extra specs extension"""

from webob import exc

from nova.api.openstack import wsgi
from nova.api.openstack import xmlutil
from nova.api.openstack import extensions
from nova import db
from nova import exception

authorize = extensions.extension_authorizer('compute', 'flavorextraspecs')

class ExtraSpecsTemplate(xmlutil.TemplateBuilder):
    def construct(self):
        return xmlutil.MasterTemplate(xmlutil.make_flat_dict('extra_specs'), 1)

class FlavorExtraSpecsController(object):
    """ The flavor extra specs API controller for the Openstack API """

    def _get_extra_specs(self, context, flavor_id):
        extra_specs = db.instance_type_extra_specs_get(context, flavor_id)
        specs_dict = {}
        for key, value in extra_specs.iteritems():
            specs_dict[key] = value
        return dict(extra_specs=specs_dict)

    def _check_body(self, body):
        if body is None or body == "":
            expl = _('No Request Body')
            raise exc.HTTPBadRequest(explanation=expl)

    @wsgi.serializers(xml=ExtraSpecsTemplate)
    def index(self, req, flavor_id):
        """ Returns the list of extra specs for a givenflavor """
        context = req.environ['nova.context']
        authorize(context)
        return self._get_extra_specs(context, flavor_id)

    @wsgi.serializers(xml=ExtraSpecsTemplate)
    def create(self, req, flavor_id, body):
        context = req.environ['nova.context']
        authorize(context)
        self._check_body(body)
        specs = body.get('extra_specs')
        try:
            db.instance_type_extra_specs_update_or_create(context,
                                                              flavor_id,
                                                              specs)
        except exception.QuotaError as error:
            self._handle_quota_error(error)
        return body

    @wsgi.serializers(xml=ExtraSpecsTemplate)
    def update(self, req, flavor_id, id, body):
        context = req.environ['nova.context']
        authorize(context)
        self._check_body(body)
        if not id in body:
            expl = _('Request body and URI mismatch')
            raise exc.HTTPBadRequest(explanation=expl)
        if len(body) > 1:
            expl = _('Request body contains too many items')
            raise exc.HTTPBadRequest(explanation=expl)
        try:
            db.instance_type_extra_specs_update_or_create(context,
                                                               flavor_id,
                                                               body)
        except exception.QuotaError as error:
            self._handle_quota_error(error)

        return body

    @wsgi.serializers(xml=ExtraSpecsTemplate)
    def show(self, req, flavor_id, id):
        """ Return a single extra spec item """
        context = req.environ['nova.context']
        authorize(context)
        specs = self._get_extra_specs(context, flavor_id)
        if id in specs['extra_specs']:
            return {id: specs['extra_specs'][id]}
        else:
            raise exc.HTTPNotFound()

    def delete(self, req, flavor_id, id):
        """ Deletes an existing extra spec """
        context = req.environ['nova.context']
        authorize(context)
        db.instance_type_extra_specs_delete(context, flavor_id, id)

    def _handle_quota_error(self, error):
        """Reraise quota errors as api-specific http exceptions."""
        if error.code == "MetadataLimitExceeded":
            raise exc.HTTPBadRequest(explanation=error.message)
        raise error

class Flavorextraspecs(extensions.ExtensionDescriptor):
    """Instance type (flavor) extra specs"""

    name = "FlavorExtraSpecs"
    alias = "os-flavor-extra-specs"
    namespace = "http://docs.openstack.org/compute/ext/" \
                "flavor_extra_specs/api/v1.1"
    updated = "2011-06-23T00:00:00+00:00"

    def get_resources(self):
        resources = []

        res = extensions.ResourceExtension(
                'os-extra_specs',
                FlavorExtraSpecsController(),
                parent=dict(member_name='flavor', collection_name='flavors'))

        resources.append(res)
        return resources


text:
<?php

namespace BlazeTest;
use \BlazePHP\Session as S;
use \BlazePHP\SessionConfig;
use \BlazePHP\Struct;
use \BlazePHP\Debug   as D;
use BlazeTest\TestCase;

final class SessionTest extends TestCase
{
	public function testInstanceCreates()
	{
		$this->assertInstanceOf(S::class, new S());
	}

	public function testSetVariable()
	{
		$session = new S();
		$session->test = 'test';
		$this->assertValueEquals($session->test, 'test');
	}

	public function testGetVariable()
	{
		$session = new S();
		$this->assertValueEquals($session->test, 'test');
	}

	public function testGetURLToken()
	{
		$session = new S();
		$urlToken = $session->URLToken();
		$match = preg_match('/PHPSESSID\=[a-z0-9]+$/', $urlToken);
		$this->assertValueEquals(1, $match);
	}

}


text:
<?php
namespace frontend\components;

use Yii;
use yii\base\Component;

class ImagePlaceholder extends Component
{
    private $_placeholder = 'http://placehold.it/';

    public function get($dimensions = '200x150')
    {
        return $this->_placeholder . $dimensions;
    }
}


text:
<?php
declare(strict_types=1);

namespace Zelenin\Zend\Expressive\Config\Test\Resources;

use Zelenin\Zend\Expressive\Config\Provider\Annotation\Factory;

/**
 * @Factory(id="serviceId")
 */
final class FactoryWithAnnotation
{
    public function __invoke()
    {
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>sfilist</title>
    <link rel="stylesheet" type="text/css" href="csound.css" />
    <meta name="generator" content="DocBook XSL Stylesheets V1.78.1" />
    <link rel="home" href="index.html" title="The Canonical Csound Reference Manual" />
    <link rel="up" href="OpcodesTop.html" title="Orchestra Opcodes and Operators" />
    <link rel="prev" href="setscorepos.html" title="setscorepos" />
    <link rel="next" href="sfinstr3.html" title="sfinstr3" />

          sfilist

          Prev
          Orchestra Opcodes and Operators
           Next

          sfilist

sfilist —
      Prints a list of all instruments of a previously loaded SoundFont2 (SF2) file.

Description

      Prints a list of all instruments of a previously loaded SoundFont2 (SF2) sample file. These opcodes allow management the sample-structure of SF2 files. In order to understand the usage of these opcodes, the user must have some knowledge of the SF2 format, so a brief description of this format can be found in the SoundFont2 File Format Appendix.

Syntax

sfilist ifilhandle

Initialization

      ifilhandle -- unique number generated by sfload opcode to be used as an identifier for a SF2 file. Several SF2 files can be loaded and activated at the same time.

Performance

      sfilist prints a list of all instruments of a previously loaded SF2 file to the console.

      These opcodes only support the sample structure of SF2 files. The modulator structure of the SoundFont2 format is not supported in Csound. Any modulation or processing to the sample data is left to the Csound user, bypassing all restrictions forced by the SF2 standard.

Examples

      Here is an example of the sfilist opcode. It uses the file sfilist.csd.

            Example 836. Example of the sfilist opcode.

See the sections Real-time Audio and Command Line Flags for more information on using command line flags.

<CsoundSynthesizer>
<CsOptions>
; Select audio/midi flags here according to platform
-odac -+rtmidi=virtual -M0   ;;;realtime audio out, virtual midi in
;-iadc    ;;;uncomment -iadc if RT audio input is needed too
; For Non-realtime ouput leave only the line below:
; -o sfilist.wav -W ;;; for file output any platform
</CsOptions>
<CsInstruments>

sr = 44100
ksmps = 32
nchnls = 2
0dbfs  = 1

gisf	sfload	"sf_GMbank.sf2"
	sfilist	gisf						;list all instruments

instr 1	; play from score and midi keyboard

	mididefault	60, p3
	midinoteonkey	p4, p5
inum	init	p4
ivel	init	p5
ivel	init	ivel/127					;make velocity dependent
kamp	linsegr	1, 1, 1, .1, 0
kamp	= kamp/3000						;scale amplitude
kfreq	init	1						;do not change freq from sf
a1, a2	sfinstr3 ivel, inum, kamp*ivel, kfreq, 100, gisf		;choose Halo Pad
	outs	a1, a2

endin

</CsInstruments>
<CsScore>
f0  60				; stay active for 1 minute

i1 0 1 60 127
i1 + 1 62 <
i1 + 1 65 <
i1 + 1 69 10

e
</CsScore>
</CsoundSynthesizer>

      Its output should include lines like this:

Instrument list of "sf_GMbank.sf2"
  0) Piano 1
  1) Piano 2
  2) CP 70
  3) EP 1 layer 1
  4) EP 1 layer 2
  5) E.Piano 2
  6) Harpsichord
  .......
  100) Halo Pad
  .......

See Also

      sfinstr,
      sfinstrm,
      sfload,
      sfpassign,
      sfplay,
      sfplaym,
      sfplist,
      sfpreset

Credits

            Author: Gabriel Maldonado

            Italy

            May 2000

New in Csound Version 4.07

          Prev

            Up

           Next

          setscorepos

            Home

           sfinstr3


text:
package vaco.conditions.numbers;

import vaco.conditions.AbstractPassableCondition;
import vaco.conditions.ConditionResult;

/**
 * Try to parse injected value as if it was a {@link Double} number and return
 * {@code TRUE} if the parsing was a success. Otherwise return {@code FALSE}.
 *
 * @author lokutus
 */
public class IsNumber extends AbstractPassableCondition<Double> {

    /** The potential number value that is being evaluated */
    private String possibleNumber;

    /**
     * @param possibleNumber
     */
    public IsNumber(String possibleNumber) {
        this.possibleNumber = possibleNumber;
    }

    public IsNumber() {
    }

    @Override
    public Double getValue() {
        if (value == null)
            value = getNumber();

        return value;
    }

    @Override
    protected boolean eval() {
        conditionResult = ConditionResult.FALSE;

        if (value == null) {
            value = getNumber();
            if (value == null)
                return false;
        }

        conditionResult = ConditionResult.TRUE;
        return true;
    }

    /**
     * @return a number parsed out from possible number value
     */
    private Double getNumber() {
        double number;

        try {
            number = Double.parseDouble(possibleNumber);
        } catch (Exception e) {
            if (possibleNumber.contains(","))
                possibleNumber = possibleNumber.replace(",", ".");
            else
                possibleNumber = possibleNumber.replace(".", ",");
            try {
                number = Double.parseDouble(possibleNumber);
            } catch (Exception e2) {
                return null;
            }
        }

        return number;
    }
}


text:
import setuptools, os, sys
import os.path

import build_manifest

PACKAGE_NAME = 'celerid'

isSourceDist = 'sdist' in [arg.lower() for arg in sys.argv]

f = open('MANIFEST', 'w')
try:
    build_manifest.buildManifest(f, True)
finally:
    f.close()

includedPaths, excludedPaths = build_manifest.listFiles(isSourceDist)

allFiles = [
    build_manifest.convertPathToDistutilsStandard(path)
    for path in includedPaths
]

# Only Python code files *within the celerid package* should go into
# packageFiles (Python code files in examples shouldn't).  A module named
# 'X.py' should later appear in packageModules as 'celerid.X'.
packageCodeFiles = [f for f in allFiles if f.endswith('.py') and '/' not in f]
packageDataFiles = [f for f in allFiles if f not in packageCodeFiles]

packageModules = [
    PACKAGE_NAME + '.' + os.path.splitext(f)[0]
    for f in packageCodeFiles
]

setuptools.setup(
    name=PACKAGE_NAME,
    package_dir={PACKAGE_NAME: os.curdir},
    packages=[PACKAGE_NAME],

    version=open('version.txt').read().strip(),
    url='https://bitbucket.org/ariovistus/pyd',
    maintainer='Ellery Newcomer',
    maintainer_email='ellery-newcomer@utulsa.edu',
    py_modules=packageModules,
    package_data={PACKAGE_NAME: packageDataFiles},
)


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Turbocharged.NSQ;

namespace TestClient
{
    public partial class ConsumerForm : Form
    {
        BindingList<string> _messages = new BindingList<string>();
        NsqTcpConnection _nsq;

        public ConsumerForm(string host, int port)
        {
            InitializeComponent();
            Host.Text = host;
            Port.Text = port.ToString();
            ReceivedMessages.DataSource = _messages;
        }

        void _nsq_InternalMessages(object s, InternalMessageEventArgs e)
        {
            PostMessage("INTERNAL: " + e.Message);
        }

        void ConnectButton_Click(object sender, EventArgs e)
        {
            var host = Host.Text;
            var port = int.Parse(Port.Text);

            var options = ConsumerOptions.Parse(string.Format("nsqd={0}:{1}", host, port));
            options.Topic = TopicTextBox.Text;
            options.Channel = ChannelTextBox.Text;
            _nsq = new NsqTcpConnection(new DnsEndPoint(host, port), options);
            _nsq.InternalMessages += _nsq_InternalMessages;
            _nsq.Connect(async msg =>
            {
                await c_MessageReceived(msg);
                await msg.FinishAsync();
            });

        }

        Task c_MessageReceived(Turbocharged.NSQ.Message obj)
        {
            var data = BitConverter.ToString(obj.Body, 0);
            var message = string.Format("RECEIVED MESSAGE. Id = {0}, Msg = {1}", obj.Id, data);
            PostMessage(message);
            return Task.FromResult(0);
        }

        void ConsumerForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_nsq != null)
                _nsq.Dispose();
        }

        void PostMessage(string obj)
        {
            var threadId = Thread.CurrentThread.ManagedThreadId;
            Invoke((Action)(() =>
            {
                _messages.Add(obj + " (ThreadId = " + threadId + ")");
                ReceivedMessages.SelectedIndex = ReceivedMessages.Items.Count - 1;
            }));
        }

        void DisconnectButton_Click(object sender, EventArgs e)
        {
            _nsq.Dispose();
        }

        async void ReadyButton_Click(object sender, EventArgs e)
        {
            var maxInFlight = int.Parse(ReadyTextBox.Text);
            await _nsq.SetMaxInFlightAsync(maxInFlight);
        }
    }
}


text:
import sys
sys.path.append('../..')
# Libraries
# Standard library
from random import choice, randint, shuffle
from string import ascii_lowercase, ascii_uppercase, digits

# Local
from lemur import models as m
from lemur.utility_generate_and_convert import (generate_lab_id,
                                                generate_experiment_id,
                                                generate_observation_id,
                                                generate_class_id)
from lemur.utility_find_and_get import (get_power,
                                        get_role)

# --- Some helper functions used to add randomness into our tests ---
# generate a random combination of letters(both upper and lower) and digits
# with a random length within the interval
def randlength_word(min_len=5, max_len=10):
    return ''.join(choice(ascii_lowercase + ascii_uppercase +
                   digits) for i in range(randint(min_len, max_len)))

# generate a random lab status
def rand_lab_status(status=('Activated', 'Unactivated', 'Downloadable')):
    return status[randint(0, len(status)-1)]

# generate a random experiment order
def rand_order(min=1, max=100):
    return randint(min, max)

# generate a random value type
def rand_value_type(value_types=('Text', 'Number')):
    return value_types[randint(0, len(value_types)-1)]

# generate a random value range in required format
def rand_value_range(min=0, max=10000):
    return (str(randint(min, max))+'.'+str(randint(min, max)) +
            '-'+str(randint(min, max))+'.'+str(randint(min, max)))

# generate a list of random value candidates(the number of which is random)
# in required format
def rand_value_candidates(min_number=1, max_number=10):
    candidates = randlength_word()
    for _ in range(randint(min_number-1, max_number-1)):
        candidates += (randlength_word()+',')
    return candidates

# generate a random lab id in the required format
def rand_lab_id():
    return randlength_word()+':'+randlength_word()

# generate a random experiment id in the required format
def rand_experiment_id():
    return rand_lab_id()+':'+randlength_word()

# generate a random value for classTime attribute in Class class
def rand_classtime(classtime_list=['FALL2016', 'SPRING2017', 'FALL2017']):
    return classtime_list[randint(0, len(classtime_list)-1)]

def rand_classid():
    return randlength_word()+'_'+rand_classtime()

# generate a power lists
def rand_powers():
    m.Role.insert_roles()
    permission_list = [m.Permission.DATA_ENTRY,
                       m.Permission.DATA_EDIT,
                       m.Permission.LAB_SETUP,
                       m.Permission.ADMIN,
                       m.Permission.LAB_MANAGE,
                       m.Permission.USER_MANAGE,
                       m.Permission.SUPERADMIN]
    shuffle(permission_list)
    return [get_power(p) for p in
            permission_list[0:randint(1, len(permission_list))]]

# Generate a random value for role_name attribute in User class
def rand_role(roles=['SuperAdmin', 'Admin', 'Student']):
    return roles[randint(0, len(roles)-1)]

# Generate a random value for role_name attribute in User class
# among all the possible admin role names
def rand_admin(roles=['SuperAdmin', 'Admin']):
    return roles[randint(0, len(roles)-1)]

# Generate a random integer which is the number of a loop in many testing
# functions
def rand_round(min_round=1, max_round=5):
    return randint(min_round, max_round)

# Generate a random list of students in string format with comma as delimitor
def rand_student_names(number=5):
    s = ''
    for _ in range(number):
        username = randlength_word()
        # Avoid repetition of username
        while s.find(username) != -1:
            username = randlength_word()
        s += (username+',')
    s = s.rstrip(',')
    return s

def rand_observations_group_by_experiment_name():
    observations_group_by_experiment_name = []
    lab_id = rand_lab_id()
    student_num = rand_round()
    student_name_list = [randlength_word() for _ in range(student_num)]
    for i in range(rand_round()):
        experiment_name = randlength_word()
        experiment_id = generate_experiment_id(lab_id, experiment_name)
        experiment = {'experiment_id': experiment_id, 'experiment_name': experiment_name,'observations':[]}
        for i in range(student_num):
            student_name = student_name_list[i]
            observation_id = generate_observation_id(experiment_id, student_name)
            observation_datum = randlength_word()
            observation = {'observation_id': observation_id,
                           'student_name': student_name,
                           'observation_data': observation_datum,
                           'lab_id': lab_id,
                           'experiment_id': experiment_id}
            experiment['observations'].append(observation)
        observations_group_by_experiment_name.append(experiment)
    return observations_group_by_experiment_name

# - A list of helper functions for creating a random object in database -
def create_class(db):
    name = randlength_word()
    time = randlength_word()
    class_id = generate_class_id(name, time)
    while db.session.query(m.Class).filter(m.Class.id == class_id).count() != 0:
        name = randlength_word()
        time = randlength_word()
        class_id = generate_class_id(name, time)
    the_class = m.Class(id=class_id, name=name, time=time)
    db.session.add(the_class)
    db.session.commit()
    class_query = db.session.query(m.Class).filter(m.Class.id == class_id).first()
    return class_query

def create_lab(db):
    the_class = create_class(db)
    name = randlength_word()
    class_id = the_class.id
    description = randlength_word()
    status = 'Activated'
    lab_id = generate_lab_id(name, class_id)
    while db.session.query(m.Lab).filter(m.Lab.id == lab_id).count() != 0:
        class_id = rand_classid()
        description = randlength_word()
        lab_id = generate_lab_id(name, class_id)

    lab = m.Lab(id=lab_id, name=name, the_class=the_class,
                description=description, status=status)
    db.session.add(lab)
    db.session.commit()
    lab_query = db.session.query(m.Lab).filter(m.Lab.id == lab_id).first()
    return lab_query

def create_experiment(db, lab_id=rand_lab_id()):
    name = randlength_word()
    description = randlength_word()
    order = rand_order()
    value_type = rand_value_type()
    value_range = rand_value_range()
    value_candidates = rand_value_candidates()
    experiment_id = generate_experiment_id(lab_id, name)
    while db.session.query(m.Experiment).filter(m.Experiment.id == experiment_id).count() != 0:
        name = randlength_word()
        lab_id = rand_lab_id()
        experiment_id = generate_experiment_id(lab_id, name)
    experiment = m.Experiment(id=experiment_id, name=name,
                              description=description, order=order,
                              value_type=value_type,
                              value_range=value_range,
                              value_candidates=value_candidates)
    db.session.add(experiment)
    db.session.commit()
    experiment_query = db.session.query(m.Experiment).filter(m.Experiment.id == experiment_id).first()
    return experiment_query

def create_observation(db, experiment_id=rand_experiment_id()):
    student_name = randlength_word()
    datum = randlength_word()
    observation_id = generate_observation_id(experiment_id, student_name)
    while db.session.query(m.Observation).filter(m.Observation.id == observation_id).count() != 0:
        student_name = randlength_word()
        experiment_id = rand_experiment_id()
        observation_id = generate_observation_id(experiment_id,
                                                 student_name)
    observation = m.Observation(id=observation_id,
                                student_name=student_name,
                                datum=datum)

    db.session.add(observation)
    db.session.commit()
    observation_query = db.session.query(m.Observation).filter(m.Observation.id == observation_id).first()
    return observation_query

def create_user(db):
    username = randlength_word()
    while db.session.query(m.User).filter(m.User.id == username).count() != 0:
        username = randlength_word()
    name = randlength_word()
    user = m.User(id=username,
                  name=name)
    db.session.add(user)
    db.session.commit()
    user_query = db.session.query(m.User).filter(m.User.id == username).first()
    return user_query

def create_role(db):
    name = randlength_word()
    while db.session.query(m.Role).filter(m.Role.name == name).count() != 0:
        name = randlength_word()
    powers = rand_powers()
    role = m.Role(name=name, powers=powers)
    db.session.add(role)
    db.session.commit()
    role_query = get_role(name)
    return role_query

def create_power(db):
    id = randlength_word()
    while db.session.query(m.Power).filter(m.Power.id == id).count() != 0:
        id = randlength_word()
    power = m.Power(id=id)
    db.session.add(power)
    db.session.commit()
    power_query = get_power(id)
    return power_query