text:
C Copyright(C) 2009-2017 National Technology & Engineering Solutions of
C Sandia, LLC (NTESS).  Under the terms of Contract DE-NA0003525 with
C NTESS, the U.S. Government retains certain rights in this software.
C
C Redistribution and use in source and binary forms, with or without
C modification, are permitted provided that the following conditions are
C met:
C
C     * Redistributions of source code must retain the above copyright
C       notice, this list of conditions and the following disclaimer.
C
C     * Redistributions in binary form must reproduce the above
C       copyright notice, this list of conditions and the following
C       disclaimer in the documentation and/or other materials provided
C       with the distribution.
C     * Neither the name of NTESS nor the names of its
C       contributors may be used to endorse or promote products derived
C       from this software without specific prior written permission.
C
C THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
C "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
C LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
C A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
C OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
C SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
C LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
C DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
C THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
C (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
C OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

C $Log: filhnd.f,v $
C Revision 1.4  2009/03/25 12:36:44  gdsjaar
C Add copyright and license notice to all files.
C Permission to assert copyright has been granted; blot is now open source, BSD
C
C Revision 1.3  2002/11/27 16:19:09  gdsjaar
C Fix filhnd calls to not pass partially uninitialized character strings to upcase.
C
C Revision 1.2  1997/11/11 14:55:55  gdsjaar
C Added 'external blkdat' to main program to ensure that the block data
C gets linked into the executable. Wasn't happening on dec alpha
C systems.
C
C Removed unreachable lines in several routines
C
C Fixed variable name spelling in contor.f
C
C Unsplit strings that were split across lines
C
C Removed old error variables left over from exodusIIv1
C
C Upped version number
C
C Revision 1.1  1994/04/07 20:00:47  gdsjaar
C Initial checkin of ACCESS/graphics/blotII2
C
c Revision 1.2  1990/12/14  08:50:32  gdsjaar
c Added RCS Id and Log to all files
c
c ======================================================================
c ======================================================================
c ======================================================================
c ======================================================================
c
c ROUTINE:              filhnd
c
c DESCRIPTION:          Opens and closes files.
c
c AUTHOR:               John H. Glick
c                       Sandia-2017 National Laboratories
c                       Division 1511
c
c DATE:                 December 20, 1988
c
c TYPE OF SUBPROGRAM:   subroutine
c
c USEAGE:               call filhnd (unit , fil1, ecodei, ecodeo,
c                                    type, fform, facces, frecl, *)
c
c PARAMETERS:
c
c        integer unit   -- (INPUT)
c                       If > 0, specifies the logical unit to be
c                          opened.
c                       If < 0, -unit specifies the logical unit to
c                          close.
c                       If = 0, all open logical units are to be
c                          closed.
c
c        character type -- (INPUT)
c                       'I' if input file (status = 'old')
c                       'O' if output file (status = 'new')
c                       'U' if unknown file type (status = 'unknown')
c                       'S' if scratch file (status = 'scratch')
c
c        character fform -- (INPUT)
c                       'F' if formatted file
c                       'U' if unformatted file
c
c CALLS:
c
c        prterr (BLOT) --     Prints an error message if one occurred
c                             during the execution of filhnd.
c        exname (SUPES)    -- Gets the filename associated with a unit
c                             number.
c        lenstr (strlib) --   Gets the length of a string (excluding
c                             trailing blanks).
c
c GLOBAL VARIABLES REFERENCED:
c
c CALLING ROUTINE(S):         getins (BLOT)
c
c SYSTEM DEPENDENCIES:        none
c
c ======================================================================
c ======================================================================
c
      subroutine filhnd (unit, filn, ecodei, ecodeo, type, fform,
     &   facces, frecl, *)
c
c
c        parameters
c
      integer unit
c          if > 0, the logical unit of the file to open.
c          if < 0, the logical unit of the file to close.
c          if = 0, close all files
      logical ecodei
c          On input, .TRUE., if program should abort
c          if an error on opening the file occured.
c          .FALSE. otherwise.
      logical ecodeo
c          On output, .TRUE. if the file opening occured successfully.
c          .FALSE. otherwise.
      integer frecl
c          If a file is to be opened and it is a direct access file,
c          the file's record length.
c          If a single file ( not all files ) is to be closed,
c          this parameter  = 1 to delete the file on closing.
c          Otherwise, the default status parameter is used on the close
c          call.
      character type
c          'o' if an old file,
c          'n' if a new file,
c          's' if a scratch file
c          'u' if unknown
      character fform
c          'u' if unformatted
c          'f' if formatted
      character facces
c          'd' if direct
c           s' if sequential
      character * (*) filn
c           Name of the file to open.  If ! = ' ', then filhnd calls
c           the SUPES routine EXNAME to get the filename associated
c           with the specified unit number.
c
c           if unit <= 0, then all other paramaters are ignored.
c
c
c        declarations
c
      character*132 filnam
c           filename associated with unit
      integer lname
c           length of string filnam (less trailing blanks)
      character*11 form
c           value of form keyword in open statement
      character*10 access
c           value of access keyword in open statement
      character*7 status
c           value of status keyword in open statement
      integer lform,lstat
c           length of form and status keywords  (less trailing blanks)
      integer lacces
c           length of access keyword (less trailing blanks)
      integer ios
c           integer indicating error status of the open call.
c           = 0 no error,
c           = error code otherwise.
      character*1 cparm
c           dummy argument for call to exparm
      character tform, ttype, tacces
c           Temporary variables for storing modified values of fform,
c           type, and facces
c
c *****************************************************************
c *****************************************************************

c
c        static declarations
c
      logical first
      save first

      integer maxunits
      parameter (maxunits=25)
c           maximum number of units that may be open at once.
      integer numopn
c            number of currently open files
      integer opnlst(maxunits)
c            array of currently open unit
c            numbers

      save numopn, opnlst

      data first / .TRUE. /

c *********************************************************************
c *********************************************************************

      if (first) then
        numopn = 0
        first = .FALSE.
      end if

c      print *, 'numopen = ',numopn
c      if ( numopn .gt. 0 )
c     &    print *, 'list is ',(opnlst(i),i=1,numopn)

      if ( unit .gt. 0 ) then
c
c           open file associated with unit
c

c                    set open keywords
c
         cparm = fform
         call upcase_bl ( cparm )
         tform = cparm(1:1)
         if ( tform .eq. 'U' ) then
            form = 'unformatted'
         else if (tform .eq. 'F' ) then
            form = 'formatted'
         else
            call prterr ('PROGRAM',
     &         'Bad value for fform parameter in filhnd routine.')
            return 1
         endif
         lform = lenstr ( form )

         cparm = type
         call upcase_bl ( cparm )
         ttype = cparm(1:1)
         if ( ttype .eq. 'O' ) then
            status = 'old'
         else if ( ttype .eq. 'N' ) then
            status = 'new'
         else if ( ttype .eq. 'U' ) then
            status = 'unknown'
         else if ( ttype .eq. 'S' ) then
            status = 'scratch'
         else
            call prterr ('PROGRAM',
     &         'Bad value for type parameter in filhnd.')
            return 1
         endif
         lstat = lenstr ( status )
c
c
         cparm = facces
         call upcase_bl ( cparm )
         tacces = cparm(1:1)
         if ( tacces .eq. 'D' ) then
            access = 'direct'
         else if ( tacces .eq. 'S' ) then
            access = 'sequential'
         else
            call prterr ('PROGRAM',
     &         'Bad value for access parameter in filhnd.')
            return 1
         endif
         lacces = lenstr ( access )
c
c
c                 open file
c
         if ( status .ne. 'scratch' ) then
c
c                    get file associated with unit
c
            filnam = filn
            call pack ( filnam, lname )
            if ( lname .eq. 0 ) then
               call exname ( unit, filnam, lname )
            endif
c
            if ( access .eq. 'direct' ) then
               open ( unit=unit, file=filnam(:lname),
     &            form=form(:lform),
     &            status=status(:lstat), access=access(:lacces),
     &            recl=frecl, iostat=ios )
            else
c               print *,'filename=',filnam(:lname),'='
c               print *,'form=',form(:lform),'='
c               print *,'status=',status(:lstat),'='
               open ( unit=unit, file=filnam(:lname),
     &            form=form(:lform),
     &            status=status(:lstat), iostat=ios)
            endif

            if ( ios .ne. 0 ) then
               if ( ecodei ) then
                  call prterr ('FATAL',
     &               'Error opening file in filhnd')
                  return 1
               else
                  call prterr ('ERROR',
     &               'Error opening file in filhnd')
                  ecodeo = .FALSE.
               endif
            else
               ecodeo = .TRUE.
            endif

         else

            if ( access .eq. 'direct' ) then
               open ( unit=unit, form=form(:lform),
     &            status=status(:lstat), access=access(:lacces),
     &            recl=frecl, iostat=ios )
            else
               open ( unit=unit, form=form(:lform),
     &            status=status(:lstat), iostat=ios)
            endif

            if ( ios .ne. 0 ) then
               if ( ecodei ) then
                  call prterr ('FATAL',
     &               'Error opening file in filhnd')
                  return 1
               else
                  call prterr ('ERROR',
     &               'Error opening file in filhnd')
                  ecodeo = .FALSE.
               endif
            else
               ecodeo = .TRUE.
            endif

         endif

c
c
c                 update list of open files
c
         if ( ecodeo ) then
            numopn = numopn + 1
            opnlst(numopn) = unit
         endif
c
c

      else if ( unit .lt. 0 ) then
c
c
c           close file

         unit = -unit
         if ( frecl .eq. 1 ) then
            close ( unit=unit, status='delete', iostat=ios )
         else
            close ( unit=unit, iostat=ios )
         endif
         if ( ios .ne. 0 ) then
            call exname ( unit, filnam, lname )
            if ( ecodei ) then
               call prterr ('PROGRAM',
     &            'Error closing file in filhnd')
               return 1
            else
               call prterr ('PROGRAM',
     &            'Error closing file in filhnd')
               ecodeo = .FALSE.
            endif
         else
            ecodeo = .TRUE.
         endif
c
c           update list of open files
c
         if ( ecodeo ) then
            i = 1
  100       continue
            if ( (i .le. numopn) .and. (unit .ne. opnlst(i)) ) then
               i = i + 1
               go to 100
            endif

            if ( i .gt. numopn ) then
               call prterr ('PROGRAM',
     &'Closed a file in filhnd that was not on the list of open files')
               return 1
            else
               numopn = numopn - 1
               do 110 j = i, numopn
                  opnlst(j) = opnlst(j+1)
  110          continue
            endif

         endif
      else

c           close all open files
c
         ecodeo = .TRUE.
         do 120 i = 1, numopn

            close ( unit=opnlst(i), iostat=ios )
            if ( ios .ne. 0 ) then
               call exname ( opnlst(i), filnam, lname )
               if ( ecodei ) then
                  call prterr ('PROGRAM',
     &               'Error closing file in filhnd')
                  return 1
               else
                  call prterr ('PROGRAM',
     &               'Error closing file in filhnd')
                  ecodeo = .FALSE.
               endif
            endif
  120    continue

      endif

c      print *, 'about to exit filhnd'
c      print *, 'numopen = ',numopn
c      if ( numopn .gt. 0 )
c     &    print *, 'list is ',(opnlst(i),i=1,numopn)

      return
      end


text:
import URating from './URating.js'

export {
  URating
}

redpajama_set_name: RedPajamaGithub


text:
package net.sourceforge.plantuml.syntax;

import java.io.PrintStream;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;

import net.sourceforge.plantuml.SkinParam;
import net.sourceforge.plantuml.ugraphic.color.HColorSet;
import net.sourceforge.plantuml.utils.Cypher;

public class LanguageDescriptor {

	private final Set<String> type = new TreeSet<>();
	private final Set<String> keyword = new TreeSet<>();
	private final Set<String> preproc = new TreeSet<>();

	public LanguageDescriptor() {

		type.add("actor");
		type.add("participant");
		type.add("usecase");
		type.add("class");
		type.add("interface");
		type.add("abstract");
		type.add("enum");
		type.add("component");
		type.add("state");
		type.add("object");
		type.add("artifact");
		type.add("folder");
		type.add("rectangle");
		type.add("node");
		type.add("frame");
		type.add("cloud");
		type.add("database");
		type.add("storage");
		type.add("agent");
		type.add("stack");
		type.add("boundary");
		type.add("control");
		type.add("entity");
		type.add("card");
		type.add("file");
		type.add("package");
		type.add("queue");
		type.add("archimate");
		type.add("diamond");
		type.add("collections");
		type.add("hexagon");
		type.add("label");
		type.add("person");
		type.add("annotation");

		keyword.add("@startwire");
		keyword.add("@startbpm");
		keyword.add("@startuml");
		keyword.add("@startdot");
		keyword.add("@startjcckit");
		keyword.add("@startditaa");
		keyword.add("@startproject");
		keyword.add("@startsalt");
		keyword.add("@startflow");
		keyword.add("@startcreole");
		keyword.add("@starttree");
		keyword.add("@startcute");
		keyword.add("@startmath");
		keyword.add("@startlatex");
		keyword.add("@startdef");
		keyword.add("@startgantt");
		keyword.add("@startnwdiag");
		keyword.add("@startmindmap");
		keyword.add("@startwbs");
		keyword.add("@startjson");
		keyword.add("@startgit");
		keyword.add("@startboard");
		keyword.add("@startyaml");
		keyword.add("@endwire");
		keyword.add("@endbpm");
		keyword.add("@enduml");
		keyword.add("@enddot");
		keyword.add("@endjcckit");
		keyword.add("@endditaa");
		keyword.add("@endproject");
		keyword.add("@endsalt");
		keyword.add("@endflow");
		keyword.add("@endcreole");
		keyword.add("@endtree");
		keyword.add("@endcute");
		keyword.add("@endmath");
		keyword.add("@endlatex");
		keyword.add("@enddef");
		keyword.add("@endgantt");
		keyword.add("@endnwdiag");
		keyword.add("@endmindmap");
		keyword.add("@endwbs");
		keyword.add("@endjson");
		keyword.add("@endgit");
		keyword.add("@endboard");
		keyword.add("@endyaml");
		keyword.add("as");
		keyword.add("also");
		keyword.add("autonumber");
		keyword.add("caption");
		keyword.add("title");
		keyword.add("newpage");
		keyword.add("box");
		keyword.add("alt");
		keyword.add("else");
		keyword.add("opt");
		keyword.add("loop");
		keyword.add("par");
		keyword.add("break");
		keyword.add("critical");
		keyword.add("note");
		keyword.add("rnote");
		keyword.add("hnote");
		keyword.add("legend");
		keyword.add("group");
		keyword.add("left");
		keyword.add("right");
		keyword.add("of");
		keyword.add("on");
		keyword.add("link");
		keyword.add("over");
		keyword.add("end");
		keyword.add("activate");
		keyword.add("deactivate");
		keyword.add("destroy");
		keyword.add("create");
		keyword.add("footbox");
		keyword.add("hide");
		keyword.add("show");
		keyword.add("skinparam");
		keyword.add("skin");
		keyword.add("top");
		keyword.add("bottom");
		keyword.add("top to bottom direction");
		keyword.add("left to right direction");
		keyword.add("package");
		keyword.add("namespace");
		keyword.add("page");
		keyword.add("up");
		keyword.add("down");
		keyword.add("if");
		keyword.add("then");
		keyword.add("else");
		keyword.add("elseif");
		keyword.add("endif");
		keyword.add("partition");
		keyword.add("footer");
		keyword.add("header");
		keyword.add("center");
		keyword.add("rotate");
		keyword.add("ref");
		keyword.add("return");
		keyword.add("is");
		keyword.add("repeat");
		keyword.add("start");
		keyword.add("stop");
		keyword.add("while");
		keyword.add("endwhile");
		keyword.add("fork");
		keyword.add("again");
		keyword.add("kill");
		keyword.add("detach");
		keyword.add("order");
		keyword.add("allow_mixing");
		keyword.add("allowmixing");
		keyword.add("mainframe");
		keyword.add("across");
		keyword.add("stereotype");
		keyword.add("split");
		keyword.add("style");
		keyword.add("sprite");
		keyword.add("circle");
		keyword.add("empty");
		keyword.add("members");
		keyword.add("description");
		keyword.add("true");
		keyword.add("false");
		keyword.add("normal");
		keyword.add("italic");
		keyword.add("bold");
		keyword.add("plain");
		keyword.add("color");
		keyword.add("dotted");
		keyword.add("dashed");
		keyword.add("bold");
		keyword.add("map");

		preproc.add("!exit");
		preproc.add("!include");
		preproc.add("!theme");
		preproc.add("!pragma");
		preproc.add("!define");
		preproc.add("!undef");
		preproc.add("!if");
		preproc.add("!ifdef");
		preproc.add("!endif");
		preproc.add("!ifndef");
		preproc.add("!else");
		preproc.add("!definelong");
		preproc.add("!enddefinelong");
		preproc.add("!function");
		preproc.add("!procedure");
		preproc.add("!endfunction");
		preproc.add("!endprocedure");
		preproc.add("!unquoted");
		preproc.add("!return");
		preproc.add("!startsub");
		preproc.add("!endsub");
		preproc.add("!assert");
		preproc.add("!log");
		preproc.add("!local");
		preproc.add("!dump_memory");
		preproc.add("!import");
	}

	public Cypher getCypher() {
		final Cypher cypher = new Cypher();
		for (String s : type) {
			cypher.addException(s);
		}
		for (String s : keyword) {
			cypher.addException(s.replace("@", ""));
		}
		for (String s : preproc) {
			cypher.addException(s.substring(1));
		}
		for (String s : SkinParam.getPossibleValues()) {
			cypher.addException(s);
		}
		for (String s : HColorSet.instance().names()) {
			cypher.addException(s);
		}
		cypher.addException("o");
		return cypher;
	}

	public void print(PrintStream ps) {
		print(ps, "type", type);
		print(ps, "keyword", keyword);
		print(ps, "preprocessor", preproc);
		print(ps, "skinparameter", SkinParam.getPossibleValues());
		print(ps, "color", HColorSet.instance().names());
		ps.println(";EOF");
	}

	private static void print(PrintStream ps, String name, Collection<String> data) {
		ps.println(";" + name);
		ps.println(";" + data.size());
		for (String k : data) {
			ps.println(k);
		}
		ps.println();
	}

	public final Set<String> getType() {
		return Collections.unmodifiableSet(type);
	}

	public final Set<String> getKeyword() {
		return Collections.unmodifiableSet(keyword);
	}

	public final Set<String> getPreproc() {
		return Collections.unmodifiableSet(preproc);
	}

}


text:
"""This is the GSoC Models module.
"""


text:
User Profile:

    General

    Avatar

    Password

@if(\Session::has('zombie_user_id'))

    Restore My Login

@endif

    Logout


text:
using SRFS.Model.Data;
using System.Collections.Generic;

namespace SRFS {

    public class DirectoryHandle : IHandle {

        public DirectoryHandle(int id, DokanDirectory directory, DokanNet.FileAccess access) {
            ID = id;
            Directory = directory;
            Access = access;
        }

        public override string ToString() {
            return ID.ToString();
        }

        public bool IsSynchronize { get; set; }

        IDokanFileSystemObject IHandle.FileSystemObject => Directory;
        public DokanDirectory Directory { get; }

        public int ID { get; private set; }

        public void Close() { Directory.Close(ID); }

        public DokanNet.FileAccess Access { get; private set; }

        public List<string> Messages => _messages;
        private List<string> _messages = new List<string>();
    }
}


text:
package jcuda;
import java.nio.*;
import java.util.Arrays;

/**
 * A Java representation of a void pointer.
 */
public class Pointer extends NativePointerObject
{
    /**
     * The offset from the nativePointer, in bytes
     */
    private long byteOffset;

    /**
     * The buffer the pointer points to
     */
    private Buffer buffer;

    /**
     * The array of NativePointerObjects this pointer points to
     */
    private NativePointerObject pointers[];

    /**
     * Creates a new Pointer to the given values.
     *
     * @param values The values the pointer should point to
     * @return The pointer
     */
    public static Pointer to(byte values[])
    {
        return new Pointer(ByteBuffer.wrap(values));
    }

    /**
     * Creates a new Pointer to the given values.
     * The values may not be null.
     *
     * @param values The values the pointer should point to
     * @return The pointer
     */
    public static Pointer to(char values[])
    {
        return new Pointer(CharBuffer.wrap(values));
    }

    /**
     * Creates a new Pointer to the given values.
     * The values may not be null.
     *
     * @param values The values the pointer should point to
     * @return The pointer
     */
    public static Pointer to(short values[])
    {
        return new Pointer(ShortBuffer.wrap(values));
    }

    /**
     * Creates a new Pointer to the given values.
     * The values may not be null.
     *
     * @param values The values the pointer should point to
     * @return The pointer
     */
    public static Pointer to(int values[])
    {
        return new Pointer(IntBuffer.wrap(values));
    }

    /**
     * Creates a new Pointer to the given values.
     * The values may not be null.
     *
     * @param values The values the pointer should point to
     * @return The pointer
     */
    public static Pointer to(float values[])
    {
        return new Pointer(FloatBuffer.wrap(values));
    }

    /**
     * Creates a new Pointer to the given values.
     * The values may not be null.
     *
     * @param values The values the pointer should point to
     * @return The pointer
     */
    public static Pointer to(long values[])
    {
        return new Pointer(LongBuffer.wrap(values));
    }

    /**
     * Creates a new Pointer to the given values.
     * The values may not be null.
     *
     * @param values The values the pointer should point to
     * @return The pointer
     */
    public static Pointer to(double values[])
    {
        return new Pointer(DoubleBuffer.wrap(values));
    }

    /**
     * NOTE: This method does not take into account the position
     * and array offset of the given buffer. In order to create a
     * pointer that takes the position and array offset into account,
     * use the {@link #toBuffer(Buffer)} method.

     *

     *
     * If the given buffer has a backing array, then the returned
     * pointer will in any case point to the start of the array,
     * even if the buffer has been created using the slice
     * method (like {@link ByteBuffer#slice()}). If the buffer is
     * direct, then this method will return a Pointer to the address
     * of the direct buffer. If the buffer has been created using the
     * slice method, then this will be the actual start
     * of the slice. Although this implies a different treatment of
     * direct- and non direct buffers, the method is kept for
     * backward compatibility.

     *

     * In both cases, for direct and array-based buffers, this method
     * does not take into account the position of the given buffer.

     *

     * The buffer must not be null, and either be a direct buffer, or
     * have a backing array
     *
     * @param buffer The buffer the pointer should point to
     * @return The pointer
     * @throws IllegalArgumentException If the given buffer
     * is null or is neither direct nor has a backing array
     */
    public static Pointer to(Buffer buffer)
    {
        if (buffer == null || (!buffer.isDirect() && !buffer.hasArray()))
        {
            throw new IllegalArgumentException(
                "Buffer may not be null and must have an array or be direct");
        }
        return new Pointer(buffer);
    }

    /**
     * Creates a new Pointer to the given buffer.

     *

     * Note that this method takes into account the array offset and position
     * of the given buffer, in contrast to the {@link #to(Buffer)} method.
     *
     * @param buffer The buffer
     * @return The new pointer
     * @throws IllegalArgumentException If the given buffer
     * is null or is neither direct nor has a backing array
     */
    public static Pointer toBuffer(Buffer buffer)
    {
        if (buffer == null || (!buffer.isDirect() && !buffer.hasArray()))
        {
            throw new IllegalArgumentException(
                "Buffer may not be null and must have an array or be direct");
        }
        if (buffer instanceof ByteBuffer)
        {
            return computePointer((ByteBuffer)buffer);
        }
        if (buffer instanceof ShortBuffer)
        {
            return computePointer((ShortBuffer)buffer);
        }
        if (buffer instanceof IntBuffer)
        {
            return computePointer((IntBuffer)buffer);
        }
        if (buffer instanceof LongBuffer)
        {
            return computePointer((LongBuffer)buffer);
        }
        if (buffer instanceof FloatBuffer)
        {
            return computePointer((FloatBuffer)buffer);
        }
        if (buffer instanceof DoubleBuffer)
        {
            return computePointer((DoubleBuffer)buffer);
        }
        throw new IllegalArgumentException(
            "Unknown buffer type: "+buffer);

    }

    /**
     * Creates a new Pointer to the given buffer, taking into
     * account the position and array offset of the given buffer.
     * The buffer is assumed to be non-null, and
     * be either direct or have a backing array.
     *
     * @param buffer The buffer
     * @return The pointer
     */
    private static Pointer computePointer(ByteBuffer buffer)
    {
        Pointer result = null;
        if (buffer.isDirect())
        {
            int oldPosition = buffer.position();
            buffer.position(0);
            result = Pointer.to(buffer.slice()).withByteOffset(
                oldPosition * Sizeof.BYTE);
            buffer.position(oldPosition);
        }
        else if (buffer.hasArray())
        {
            ByteBuffer t = ByteBuffer.wrap(buffer.array());
            int elementOffset = buffer.position() + buffer.arrayOffset();
            result = Pointer.to(t).withByteOffset(
                elementOffset * Sizeof.BYTE);
        }
        return result;
    }

    /**
     * Creates a new Pointer to the given buffer, taking into
     * account the position and array offset of the given buffer.
     * The buffer is assumed to be non-null, and
     * be either direct or have a backing array.
     *
     * @param buffer The buffer
     * @return The pointer
     */
    private static Pointer computePointer(ShortBuffer buffer)
    {
        Pointer result = null;
        if (buffer.isDirect())
        {
            int oldPosition = buffer.position();
            buffer.position(0);
            result = Pointer.to(buffer.slice()).withByteOffset(
                oldPosition * Sizeof.SHORT);
            buffer.position(oldPosition);
        }
        else if (buffer.hasArray())
        {
            ShortBuffer t = ShortBuffer.wrap(buffer.array());
            int elementOffset = buffer.position() + buffer.arrayOffset();
            result = Pointer.to(t).withByteOffset(
                elementOffset * Sizeof.SHORT);
        }
        return result;
    }

    /**
     * Creates a new Pointer to the given buffer, taking into
     * account the position and array offset of the given buffer.
     * The buffer is assumed to be non-null, and
     * be either direct or have a backing array.
     *
     * @param buffer The buffer
     * @return The pointer
     */
    private static Pointer computePointer(IntBuffer buffer)
    {
        Pointer result = null;
        if (buffer.isDirect())
        {
            int oldPosition = buffer.position();
            buffer.position(0);
            result = Pointer.to(buffer.slice()).withByteOffset(
                oldPosition * Sizeof.INT);
            buffer.position(oldPosition);
        }
        else if (buffer.hasArray())
        {
            IntBuffer t = IntBuffer.wrap(buffer.array());
            int elementOffset = buffer.position() + buffer.arrayOffset();
            result = Pointer.to(t).withByteOffset(
                elementOffset * Sizeof.INT);
        }
        return result;
    }

    /**
     * Creates a new Pointer to the given buffer, taking into
     * account the position and array offset of the given buffer.
     * The buffer is assumed to be non-null, and
     * be either direct or have a backing array.
     *
     * @param buffer The buffer
     * @return The pointer
     */
    private static Pointer computePointer(LongBuffer buffer)
    {
        Pointer result = null;
        if (buffer.isDirect())
        {
            int oldPosition = buffer.position();
            buffer.position(0);
            result = Pointer.to(buffer.slice()).withByteOffset(
                oldPosition * Sizeof.LONG);
            buffer.position(oldPosition);
        }
        else if (buffer.hasArray())
        {
            LongBuffer t = LongBuffer.wrap(buffer.array());
            int elementOffset = buffer.position() + buffer.arrayOffset();
            result = Pointer.to(t).withByteOffset(
                elementOffset * Sizeof.LONG);
        }
        return result;
    }

    /**
     * Creates a new Pointer to the given buffer, taking into
     * account the position and array offset of the given buffer.
     * The buffer is assumed to be non-null, and
     * be either direct or have a backing array.
     *
     * @param buffer The buffer
     * @return The pointer
     */
    private static Pointer computePointer(FloatBuffer buffer)
    {
        Pointer result = null;
        if (buffer.isDirect())
        {
            int oldPosition = buffer.position();
            buffer.position(0);
            result = Pointer.to(buffer.slice()).withByteOffset(
                oldPosition * Sizeof.FLOAT);
            buffer.position(oldPosition);
        }
        else if (buffer.hasArray())
        {
            FloatBuffer t = FloatBuffer.wrap(buffer.array());
            int elementOffset = buffer.position() + buffer.arrayOffset();
            result = Pointer.to(t).withByteOffset(
                elementOffset * Sizeof.FLOAT);
        }
        return result;
    }

    /**
     * Creates a new Pointer to the given buffer, taking into
     * account the position and array offset of the given buffer.
     * The buffer is assumed to be non-null, and
     * be either direct or have a backing array.
     *
     * @param buffer The buffer
     * @return The pointer
     */
    private static Pointer computePointer(DoubleBuffer buffer)
    {
        Pointer result = null;
        if (buffer.isDirect())
        {
            int oldPosition = buffer.position();
            buffer.position(0);
            result = Pointer.to(buffer.slice()).withByteOffset(
                oldPosition * Sizeof.DOUBLE);
            buffer.position(oldPosition);
        }
        else if (buffer.hasArray())
        {
            DoubleBuffer t = DoubleBuffer.wrap(buffer.array());
            int elementOffset = buffer.position() + buffer.arrayOffset();
            result = Pointer.to(t).withByteOffset(
                elementOffset * Sizeof.DOUBLE);
        }
        return result;
    }

    /**
     * Creates a new Pointer to the given Pointers. The array
     * of pointers may not be null, and may not
     * contain null elements.
     *
     * @param pointers The pointers the pointer should point to
     * @return The new pointer
     * @throws IllegalArgumentException If the given array
     * is null
     */
    public static Pointer to(NativePointerObject ... pointers)
    {
        if (pointers == null)
        {
            throw new IllegalArgumentException(
                "Pointer may not point to null objects");
        }
        return new Pointer(pointers);
    }

    /**
     * Creates a new (null) Pointer
     */
    public Pointer()
    {
        buffer = null;
        pointers = null;
        byteOffset = 0;
    }

    /**
     * Constructor which accepts a constant value as the pointer value.
     * Solely for the constant pointer instances in the JCudaDriver
     * class, to create the CU_LAUNCH_PARAM_END,
     * CU_LAUNCH_PARAM_BUFFER_POINTER, and CU_LAUNCH_PARAM_BUFFER_SIZE
     * pointer constants.
     *
     * @param nativePointerValue The native pointer value
     */
    protected Pointer(long nativePointerValue)
    {
        super(nativePointerValue);
        buffer = null;
        pointers = null;
        byteOffset = 0;
    }

    /**
     * Creates a Pointer to the given Buffer
     *
     * @param buffer The buffer to point to
     */
    private Pointer(Buffer buffer)
    {
        this.buffer = buffer;
        pointers = null;
        byteOffset = 0;
    }

    /**
     * Creates a Pointer to the given array of pointers
     *
     * @param pointers The array the pointer points to
     */
    private Pointer(NativePointerObject pointers[])
    {
        buffer = null;
        this.pointers = pointers;
        byteOffset = 0;
    }

    /**
     * Copy constructor
     *
     * @param other The other Pointer
     */
    protected Pointer(Pointer other) {
        super(other.getNativePointer());
        this.buffer = other.buffer;
        this.pointers = other.pointers;
        this.byteOffset = other.byteOffset;
    }

    /**
     * Creates a copy of the given pointer, with an
     * additional byte offset
     *
     * @param other The other pointer
     * @param byteOffset The additional byte offset
     */
    protected Pointer(Pointer other, long byteOffset)
    {
        this(other);
        this.byteOffset += byteOffset;
    }

    /**
     * Returns a new pointer with an offset of the given number
     * of bytes
     *
     * @param byteOffset The byte offset for the pointer
     * @return The new pointer with the given byte offset
     */
    public Pointer withByteOffset(long byteOffset)
    {
        return new Pointer(this, byteOffset);
    }

    /**
     * Returns a ByteBuffer that corresponds to the specified
     * segment of the memory that this pointer points to.

     *

     * This function may only be applied to pointers that
     * have been set to point to a region of host memory
     * using either of the methods
     * {@link jcuda.driver.JCudaDriver#cuMemAllocHost(Pointer, long)},
     * {@link jcuda.driver.JCudaDriver#cuMemHostAlloc(Pointer, long, int)},
     * {@link jcuda.runtime.JCuda#cudaMallocHost(Pointer, long)} or
     * {@link jcuda.runtime.JCuda#cudaHostAlloc(Pointer, long, int)},
     * or pointers that have been created with
     * {@link Pointer#to(byte[])}.

     *

     * For other pointer types, null is returned.
     *
     * @param byteOffset The offset in bytes
     * @param byteSize The size of the byte buffer, in bytes
     * @return The byte buffer
     */
    public ByteBuffer getByteBuffer(long byteOffset, long byteSize)
    {
        if (buffer == null)
        {
            return null;
        }
        if (!(buffer instanceof ByteBuffer))
        {
            return null;
        }
        ByteBuffer byteBuffer = (ByteBuffer)buffer;
        byteBuffer.limit((int)(byteOffset + byteSize));
        byteBuffer.position((int)byteOffset);
        return byteBuffer.slice();
    }

    /**
     * Returns the byte offset
     *
     * @return The byte offset
     */
    protected long getByteOffset()
    {
        return byteOffset;
    }

    /**
     * Returns a String representation of this object.
     *
     * @return A String representation of this object.
     */
    @Override
    public String toString()
    {
        if (buffer != null)
        {
            return "Pointer["+
                "buffer="+buffer+","+
                "byteOffset="+byteOffset+"]";

        }
        else if (pointers != null)
        {
            return "Pointer["+
                "pointers="+Arrays.toString(pointers)+","+
                "byteOffset="+byteOffset+"]";
        }
        else
        {
            return "Pointer["+
                "nativePointer=0x"+Long.toHexString(getNativePointer())+","+
                "byteOffset="+byteOffset+"]";
        }
    }
}


text:
import json
from django import http
from django.utils.translation import ugettext_lazy as _
from urllib import parse

from functools import reduce
from trix.trix_core import models
from trix.trix_student.views import base

class AssignmentListViewBase(base.TrixListViewBase):
    paginate_by = 100
    context_object_name = 'assignment_list'
    already_selected_tags = []

    def get(self, request, **kwargs):
        self.selected_tags = self._get_selected_tags()
        self.selectable_tags = self._get_selectable_tags()
        self.non_removeable_tags = self.get_nonremoveable_tags()
        if self.request.GET.get('progressjson'):
            return self._progressjson()
        else:
            return super(AssignmentListViewBase, self).get(request, **kwargs)

    def get_queryset(self):
        assignments = self.get_all_available_assignments()
        if self.selected_tags:
            exclude_list = [tag.lstrip('-') for tag in self.selected_tags if tag.startswith('-')]
            filter_list = [tag for tag in self.selected_tags if not tag.startswith('-')]
            if filter_list:
                # Get only assignments which match exactly the tags in the list
                assignments = reduce(lambda qs, pk: qs.filter(tags__tag=pk),
                                     filter_list, assignments)
            if exclude_list:
                # Exclude any assignment that has an excluded tag
                assignments = assignments.exclude(tags__tag__in=exclude_list)
        # Exclude hidden tasks from those that are not admin
        if not self._get_user_is_admin():
            assignments = assignments.exclude(hidden=True)
        assignments = assignments.order_by('title')
        return assignments

    def _get_progress(self):
        """
        Gets the progress a user has made. Hidden tasks are not counted unless user is an admin.
        """
        assignments = self.get_queryset()
        how_solved = models.HowSolved.objects.filter(assignment__in=assignments)\
            .filter(user=self.request.user.id)
        num_solved = how_solved.count()
        num_total = assignments.count()
        if num_total == 0:
            percent = 0
        else:
            percent = round(num_solved / float(num_total) * 100, 0)
        return {
            'num_total': num_total,
            'num_solved': num_solved,
            'percent': percent
        }

    def _progressjson(self):
        return http.HttpResponse(
            json.dumps(self._get_progress()),
            content_type='application/json'
        )

    def _get_selectable_tags(self):
        already_selected_tags = self.get_already_selected_tags() + self.selected_tags

        tags = (models.Tag.objects
                .filter(assignment__in=self.get_queryset())
                .exclude(tag__in=already_selected_tags)
                .order_by('tag')
                .distinct()
                .values_list('tag', flat=True))
        return tags

    def _get_selected_tags(self):
        tags_string = self.request.GET.get('tags', None)
        tags = []
        if tags_string:
            tags = tags_string.split(',')
            tags.sort()
        return tags

    def _get_assignmentlist_with_howsolved(self, assignment_list):
        """
        Expand the given list of Assignment objects with information
        about how ``request.user`` solved the assignment.

        Returns:
            A list with ``(assignment, howsolved)`` tuples where ``howsolved``
            is one of the valid values for the ``howsolved`` field in
            :class:`trix.trix_core.models.HowSolved``, or empty string if there is no
            HowSolved object for ``request.user`` for the assignment.
        """
        howsolvedmap = {}  # Map of assignment ID to HowSolved.howsolved for request.user
        if self.request.user.is_authenticated and assignment_list:
            howsolvedquery = (models.HowSolved.objects
                              .filter(user=self.request.user, assignment__in=assignment_list))
            howsolvedmap = dict(howsolvedquery.values_list('assignment_id', 'howsolved'))
        return [
            (assignment, howsolvedmap.get(assignment.id, ''))
            for assignment in assignment_list]

    def get_context_data(self, **kwargs):
        context = super(AssignmentListViewBase, self).get_context_data(**kwargs)

        context['non_removeable_tags'] = self.non_removeable_tags
        context['selected_tags'] = self.selected_tags
        context['selectable_tags'] = self.selectable_tags
        context['user_is_admin'] = self._get_user_is_admin()
        context['urlencoded_success_url'] = parse.urlencode({
            'success_url': self.request.get_full_path()})

        context['assignmentlist_with_howsolved'] = self._get_assignmentlist_with_howsolved(
            context['assignment_list'])
        context['progresstext'] = _(
            'You have completed {{ solvedPercentage }} percent of assignments matching the '
            'currently selected tags.')
        return context

    def _get_user_is_admin(self):
        raise NotImplementedError()

    def get_all_available_assignments(self):
        raise NotImplementedError()

    def get_nonremoveable_tags(self):
        raise NotImplementedError()

    def get_already_selected_tags(self):
        raise NotImplementedError()


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

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

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

=cut

=head1 CONTACT

  Please email comments or questions to the public Ensembl
  developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.

  Questions may also be sent to the Ensembl help desk at
  <http://www.ensembl.org/Help/Contact>.

=head1 NAME

Bio::EnsEMBL::Compara::DBSQL::GeneTreeAdaptor

=head1 DESCRIPTION

Adaptor for a GeneTree object (individual nodes will be internally retrieved
with the GeneTreeNodeAdaptor).

=head1 INHERITANCE TREE

  Bio::EnsEMBL::Compara::DBSQL::GeneTreeAdaptor
  +- Bio::EnsEMBL::Compara::DBSQL::BaseAdaptor
  `- Bio::EnsEMBL::Compara::DBSQL::TagAdaptor

=head1 AUTHORSHIP

Ensembl Team. Individual contributions can be found in the GIT log.

=head1 APPENDIX

The rest of the documentation details each of the object methods.
Internal methods are usually preceded with an underscore (_)

=cut

package Bio::EnsEMBL::Compara::DBSQL::GeneTreeAdaptor;

use strict;
use warnings;

use Data::Dumper;
use Bio::EnsEMBL::Utils::Argument qw(rearrange);
use Bio::EnsEMBL::Utils::Scalar qw(:assert);

use Bio::EnsEMBL::Compara::Utils::Scalar qw(:assert);

use Bio::EnsEMBL::Compara::GeneTree;
use DBI qw(:sql_types);

use base ('Bio::EnsEMBL::Compara::DBSQL::BaseAdaptor', 'Bio::EnsEMBL::Compara::DBSQL::TagAdaptor');

#
# FETCH methods
###########################

=head2 fetch_all

  Arg [-TREE_TYPE] (opt)
             : string: the type of trees that have to be fetched
               Currently one of 'clusterset', 'supertree', 'tree'
  Arg [-MEMBER_TYPE] (opt)
             : string: the type of the members that are part of the tree
               Currently 'protein' or 'ncrna'
  Arg [-METHOD_LINK_SPECIES_SET] (opt)
             : MethodLinkSpeciesSet or int: either the object or its dbID
               NB: It currently gives the same partition of the data as member_type
  Arg [-CLUSTERSET_ID] (opt)
             : string: the name of the clusterset (use "default" to get the default
               trees). Currently, there is a clusterset for the default trees, one for
               each phylogenetic model used in the protein tree pipeline
  Example    : $all_trees = $genetree_adaptor->fetch_all();
  Description: Fetches from the database all the gene trees
  Returntype : arrayref of Bio::EnsEMBL::Compara::GeneTree
  Exceptions : none
  Caller     : general

=cut

sub fetch_all {
    my ($self, @args) = @_;
    my ($clusterset_id, $mlss, $tree_type, $member_type)
        = rearrange([qw(CLUSTERSET_ID METHOD_LINK_SPECIES_SET TREE_TYPE MEMBER_TYPE)], @args);
    my @constraint = ();

    if (defined $tree_type) {
        push @constraint, '(gtr.tree_type = ?)';
        $self->bind_param_generic_fetch($tree_type, SQL_VARCHAR);
    }

    if (defined $member_type) {
        push @constraint, '(gtr.member_type = ?)';
        $self->bind_param_generic_fetch($member_type, SQL_VARCHAR);
    }

    if (defined $mlss) {
        assert_ref_or_dbID($mlss, 'Bio::EnsEMBL::Compara::MethodLinkSpeciesSet', 'mlss');
        my $mlss_id = (ref($mlss) ? $mlss->dbID : $mlss);
        push @constraint, '(gtr.method_link_species_set_id = ?)';
        $self->bind_param_generic_fetch($mlss_id, SQL_INTEGER);
    }

    if (defined $clusterset_id) {
        push @constraint, '(gtr.clusterset_id = ?)';
        $self->bind_param_generic_fetch($clusterset_id, SQL_VARCHAR);
    }

    return $self->generic_fetch(join(' AND ', @constraint));
}

=head2 fetch_by_stable_id

  Arg[1]     : string $tree_stable_id
  Example    : $tree = $genetree_adaptor->fetch_by_stable_id("ENSGT00590000083078");
  Description: Fetches from the database the gene tree for that stable ID
  Returntype : Bio::EnsEMBL::Compara::GeneTree
  Exceptions : returns undef if $stable_id is not found.
  Caller     : general

=cut

sub fetch_by_stable_id {
    my ($self, $stable_id) = @_;

    $self->bind_param_generic_fetch($stable_id, SQL_VARCHAR);
    return $self->generic_fetch_one('gtr.stable_id = ?');
}

=head2 fetch_by_root_id

  Arg[1]     : int $tree_root_id
  Example    : $tree = $genetree_adaptor->fetch_by_root_id(3);
  Description: Fetches from the database the gene tree for that root ID
               This is equivalent to fetch_by_dbID
  Returntype : Bio::EnsEMBL::Compara::GeneTree
  Exceptions : returns undef if $root_id is not found.
  Caller     : general

=cut

sub fetch_by_root_id {
    my ($self, $root_id) = @_;

    $self->bind_param_generic_fetch($root_id, SQL_INTEGER);
    return $self->generic_fetch_one('gtr.root_id = ?');
}

=head2 fetch_by_dbID

  Arg[1]     : int $tree_root_id
  Example    : $tree = $genetree_adaptor->fetch_by_dbID(3);
  Description: Fetches from the database the gene tree for that root ID
               This is equivalent to fetch_by_root_id
  Returntype : Bio::EnsEMBL::Compara::GeneTree
  Exceptions : returns undef if $root_id is not found.
  Caller     : general

=cut

sub fetch_by_dbID {
    my ($self, $root_id) = @_;

    $self->bind_param_generic_fetch($root_id, SQL_INTEGER);
    return $self->generic_fetch_one('gtr.root_id = ?');
}

=head2 fetch_by_node_id

  Arg[1]     : int $tree_node_id
  Example    : $tree = $genetree_adaptor->fetch_by_node_id(3);
  Description: Fetches from the database the gene tree that contains
               this node
  Returntype : Bio::EnsEMBL::Compara::GeneTree
  Exceptions : returns undef if $node_id is not found.
  Caller     : general

=cut

sub fetch_by_node_id {
    my ($self, $node_id) = @_;

    $self->bind_param_generic_fetch($node_id, SQL_INTEGER);
    my $join = [[['gene_tree_node', 'gtn'], 'gtn.root_id = gtr.root_id']];
    return $self->generic_fetch_one('gtn.node_id = ?', $join);
}

=head2 fetch_all_by_Member

  Arg[1]     : GeneMember, SeqMember or seq_member_id
  Arg [-METHOD_LINK_SPECIES_SET] (opt)
             : MethodLinkSpeciesSet or int: either the object or its dbID
  Arg [-CLUSTERSET_ID] (opt)
             : string: the name of the clusterset (default is "default")
  Example    : $all_trees = $genetree_adaptor->fetch_all_by_Member($member);
  Description: Fetches from the database all the gene trees that contains this member
               If the member is a non-canonical SeqMember, returns an empty list
  Returntype : arrayref of Bio::EnsEMBL::Compara::GeneTree
  Exceptions : none
  Caller     : general

=cut

sub fetch_all_by_Member {
    my ($self, $member, @args) = @_;
    my ($clusterset_id, $mlss) = rearrange([qw(CLUSTERSET_ID METHOD_LINK_SPECIES_SET)], @args);

    assert_ref_or_dbID($member, 'Bio::EnsEMBL::Compara::Member', 'member');

    my $join = [[['gene_tree_node', 'gtn'], 'gtn.root_id = gtr.root_id']];
    my $constraint = '(gtn.seq_member_id = ?)';

    my $seq_member_id = (ref($member) ? ($member->isa('Bio::EnsEMBL::Compara::GeneMember') ? $member->canonical_member_id : $member->dbID) : $member);
    $self->bind_param_generic_fetch($seq_member_id, SQL_INTEGER);

    if (defined $mlss) {
        assert_ref_or_dbID($mlss, 'Bio::EnsEMBL::Compara::MethodLinkSpeciesSet', 'mlss');
        my $mlss_id = (ref($mlss) ? $mlss->dbID : $mlss);
        $constraint .= ' AND (gtr.method_link_species_set_id = ?)';
        $self->bind_param_generic_fetch($mlss_id, SQL_INTEGER);
    }
    if (defined $clusterset_id) {
        $constraint .= ' AND (gtr.clusterset_id = ?)';
        $self->bind_param_generic_fetch($clusterset_id, SQL_VARCHAR);
    }

    return $self->generic_fetch($constraint, $join);
}

=head2 fetch_default_for_Member

  Arg[1]     : GeneMember, SeqMember or seq_member_id
  Example    : $trees = $genetree_adaptor->fetch_default_for_Member($member);
  Description: Fetches from the database the default gene tree that contains this member
               If the member is a non-canonical SeqMember, returns undef
  Returntype : Bio::EnsEMBL::Compara::GeneTree
  Exceptions : none
  Caller     : general

=cut

sub fetch_default_for_Member {
    my ($self, $member) = @_;

    return $self->fetch_all_by_Member($member, -CLUSTERSET_ID => 'default')->[0];
}

=head2 fetch_by_Gene

  Arg[1]     : Bio::EnsEMBL::Gene $gene
  Example    : $tree = $genetree_adaptor->fetch_by_Gene($gene);
  Description: Fetches from the database the default gene tree that contains this gene
  Returntype : Bio::EnsEMBL::Compara::GeneTree
  Exceptions : none
  Caller     : general

=cut

sub fetch_by_Gene {
    my ($self, $gene) = @_;

    assert_ref($gene, 'Bio::EnsEMBL::Gene', 'gene');
    my $gene_member = $self->db->get_GeneMemberAdaptor->fetch_by_Gene($gene);
    return $gene_member ? $self->fetch_default_for_Member($gene_member) : undef;
}

=head2 fetch_parent_tree

  Arg[1]     : GeneTree $tree or its root_id
  Example    : $parent = $genetree_adaptor->fetch_parent_tree($tree);
  Description: Fetches from the database the parent (tree) of the argument tree
  Returntype : Bio::EnsEMBL::Compara::GeneTree
  Exceptions : returns undef if called on a 'clusterset' tree
  Caller     : general

=cut

sub fetch_parent_tree {
    my ($self, $tree) = @_;

    assert_ref_or_dbID($tree, 'Bio::EnsEMBL::Compara::GeneTree', 'tree');
    my $tree_id = (ref($tree) ? $tree->root_id : $tree);

    my $join = [[['gene_tree_node', 'gtn1'], 'gtn1.root_id = gtr.root_id'], [['gene_tree_node', 'gtn2'], 'gtn1.node_id = gtn2.parent_id']];
    my $constraint = "(gtn2.root_id = gtn2.node_id) AND (gtn2.root_id = ?)";

    $self->bind_param_generic_fetch($tree_id, SQL_INTEGER);
    return $self->generic_fetch_one($constraint, $join);
}

=head2 fetch_subtrees

  Arg[1]     : GeneTree $tree or its root_id
  Example    : $subtrees = $genetree_adaptor->fetch_subtrees($tree);
  Description: Fetches from the database the trees that are children of the argument tree
  Returntype : arrayref of Bio::EnsEMBL::Compara::GeneTree
  Exceptions : the array is empty if called on a 'tree' tree
  Caller     : general

=cut

sub fetch_subtrees {
    my ($self, $tree) = @_;

    assert_ref_or_dbID($tree, 'Bio::EnsEMBL::Compara::GeneTree', 'tree');
    my $tree_id = (ref($tree) ? $tree->root_id : $tree);

    my $join = [[['gene_tree_node', 'gtn2'], 'gtn2.node_id = gtr.root_id', ['gtn2.parent_id']], [['gene_tree_node', 'gtn1'], 'gtn1.node_id = gtn2.parent_id']];
    my $constraint = "(gtn1.root_id = ?) AND (gtn2.root_id != gtn1.root_id)";

    $self->bind_param_generic_fetch($tree_id, SQL_INTEGER);
    return $self->generic_fetch($constraint, $join);
}

=head2 fetch_all_linked_trees

  Arg[1]     : GeneTree $tree or its root_id
  Example    : $othertrees = $genetree_adaptor->fetch_all_linked_trees($tree);
  Description: Fetches from the database all trees that are associated to the argument tree.
                The other trees generally contain the same members, but are either build
                with a different phylogenetic model, or have a different multiple alignment.
  Returntype : arrayref of Bio::EnsEMBL::Compara::GeneTree
  Caller     : general

=cut

sub fetch_all_linked_trees {
    my ($self, $tree) = @_;

    # Currently, all linked trees are accessible in 1 hop
    if ($tree->ref_root_id) {
        # Trees that share the same reference
        $self->bind_param_generic_fetch($tree->ref_root_id, SQL_INTEGER);
        $self->bind_param_generic_fetch($tree->root_id, SQL_INTEGER);
        $self->bind_param_generic_fetch($tree->ref_root_id, SQL_INTEGER);
        return $self->generic_fetch('(ref_root_id = ? AND root_id != ?) OR (root_id = ?)');
    } else {
        # The given tree is the reference
        $self->bind_param_generic_fetch($tree->root_id, SQL_INTEGER);
        return $self->generic_fetch('ref_root_id = ?');
    }
}

#
# STORE/DELETE methods
###########################

sub store {
    my ($self, $tree) = @_;

    # Firstly, store the nodes
    my $has_root_id = (exists $tree->{'_root_id'} ? 1 : 0);
    my $root_id = $self->db->get_GeneTreeNodeAdaptor->store_nodes_rec($tree->root);
    $tree->{'_root_id'} = $root_id;

    # Secondly, the tree itself
    my $sth;
    # Make sure that the variables are in the same order
    if ($has_root_id) {
        $sth = $self->prepare('UPDATE gene_tree_root SET tree_type=?, member_type=?, clusterset_id=?, gene_align_id=?, method_link_species_set_id=?, stable_id=?, version=?, ref_root_id=? WHERE root_id=?'),
    } else {
        $sth = $self->prepare('INSERT INTO gene_tree_root (tree_type, member_type, clusterset_id, gene_align_id, method_link_species_set_id, stable_id, version, ref_root_id, root_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)');
    }
    $sth->execute($tree->tree_type, $tree->member_type, $tree->clusterset_id, $tree->gene_align_id, $tree->method_link_species_set_id, $tree->stable_id, $tree->version, $tree->ref_root_id, $root_id);

    $tree->adaptor($self);

    return $root_id;
}

sub delete_tree {
    my ($self, $tree) = @_;

    assert_ref($tree, 'Bio::EnsEMBL::Compara::GeneTree');

    # Remove all the nodes but the root
    my $gene_tree_node_Adaptor = $tree->root->adaptor;
    for my $node (@{$tree->get_all_nodes}) {
        next if ($node->node_id() == $tree->root->node_id());
        $gene_tree_node_Adaptor->delete_node($node);
    }

    # Only for "default" trees
    unless ($tree->ref_root_id) {

        # Linked trees must be removed as well as they refer to the default tree
        foreach my $other_tree (@{$self->fetch_all_linked_trees($tree)}) {
            $other_tree->preload();
            $self->delete_tree($other_tree);
            $other_tree->release_tree();
        }
    }

    # Finally remove the root node
    $gene_tree_node_Adaptor->delete_node($tree->root);

    # Only for "default" trees
    unless ($tree->ref_root_id) {
        # The alignment only if it exists (In NCRecoverEPO we don't have an alignment yet)
        $gene_tree_node_Adaptor->db->get_GeneAlignAdaptor->delete($tree->gene_align_id) if (defined $tree->gene_align_id);

        # The HMM profile
        my $root_id = $tree->root->node_id;
        $self->dbc->db_handle->do('DELETE FROM hmm_profile WHERE model_id = ?', undef, $root_id);
    }

}

#
# Virtual methods from TagAdaptor
###################################

sub _tag_capabilities {
    return ('gene_tree_root_tag', undef, 'root_id', 'root_id');
}

#
# Virtual methods from BaseAdaptor
####################################

sub _tables {

    return (['gene_tree_root', 'gtr'], ['gene_align', 'ga'])
}

sub _left_join {
    return (
        ['gene_align', 'gtr.gene_align_id = ga.gene_align_id'],
    );
}

sub _columns {

    return qw (
        gtr.root_id
        gtr.tree_type
        gtr.member_type
        gtr.clusterset_id
        gtr.gene_align_id
        gtr.method_link_species_set_id
        gtr.stable_id
        gtr.version
        gtr.ref_root_id
        ga.seq_type
        ga.aln_length
        ga.aln_method
    );
}

sub _objs_from_sth {
  my ($self, $sth) = @_;
  my @tree_list = ();

  while(my $rowhash = $sth->fetchrow_hashref) {
    #my $tree = new Bio::EnsEMBL::Compara::GeneTree(-adaptor => $self, %$rowhash);
    my $tree = Bio::EnsEMBL::Compara::GeneTree->new_fast({
        adaptor                     => $self,
        _root_id                    => $rowhash->{root_id},
        _tree_type                  => $rowhash->{tree_type},
        _member_type                => $rowhash->{member_type},
        _clusterset_id              => $rowhash->{clusterset_id},
        _gene_align_id              => $rowhash->{gene_align_id},
        _method_link_species_set_id => $rowhash->{method_link_species_set_id},
        _stable_id                  => $rowhash->{stable_id},
        _version                    => $rowhash->{version},
        _ref_root_id                => $rowhash->{ref_root_id},
        _parent_id                  => $rowhash->{parent_id},
        _seq_type                   => $rowhash->{seq_type},
        _aln_length                 => $rowhash->{aln_length},
        _aln_method                 => $rowhash->{aln_method},
    });
    push @tree_list, $tree;
  }

  return \@tree_list;
}

1;


text:
#ifndef _CHARMAP_H
#define _CHARMAP_H

#include <obstack.h>
#include <stdbool.h>

#include "repertoire.h"
#include "simple-hash.h"

struct width_rule
{
  struct charseq *from;
  struct charseq *to;
  unsigned int width;
};

struct charmap_t
{
  const char *code_set_name;
  const char *repertoiremap;
  int mb_cur_min;
  int mb_cur_max;

  struct width_rule *width_rules;
  size_t nwidth_rules;
  size_t nwidth_rules_max;
  unsigned int width_default;

  struct obstack mem_pool;
  hash_table char_table;
  hash_table byte_table;
  hash_table ucs4_table;
};

/* This is the structure used for entries in the hash table.  It represents
   the sequence of bytes used for the coded character.  */
struct charseq
{
  const char *name;
  uint32_t ucs4;
  int nbytes;
  unsigned char bytes[0];
};

/* True if the encoding is not ASCII compatible.  */
extern bool enc_not_ascii_compatible;

/* Prototypes for charmap handling functions.  */
extern struct charmap_t *charmap_read (const char *filename, int verbose,
				       int error_not_found, int be_quiet,
				       int use_default);

/* Return the value stored under the given key in the hashing table.  */
extern struct charseq *charmap_find_value (const struct charmap_t *charmap,
					   const char *name, size_t len);

/* Return symbol for given multibyte sequence.  */
extern struct charseq *charmap_find_symbol (const struct charmap_t *charmap,
					    const char *name, size_t len);

#endif /* charmap.h */


text:
import { NativeScriptModule } from "nativescript-angular/nativescript.module";
import { NgModule } from "@angular/core";
import { NativeScriptFormsModule } from "nativescript-angular/forms";

import { moveALCreateRouting } from "./moveALCreate.routes";
import { MoveALCreateComponent } from "./moveALCreate.component";
import { DropDownModule } from "nativescript-drop-down/angular";

@NgModule({
  imports: [
    NativeScriptModule,
    NativeScriptFormsModule,
    DropDownModule,
    moveALCreateRouting
  ],
  declarations: [
    MoveALCreateComponent
  ]
})
export class MoveALCreateModule {}


text:
!SLIDE bullets incremental transition=turnDown

# History #

* 1999 - RubyUnit
* 2001 - Lapidary
* 2001 - test/unit
* 2006 - minitest


text:
<?php

namespace Modules\Base\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Database\Eloquent\Factory;

class BaseServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Boot the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerTranslations();
        $this->registerConfig();
        $this->registerViews();
        $this->registerFactories();
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
          //$this->app->bind('name', name::class);
    }

    /**
     * Register config.
     *
     * @return void
     */
    protected function registerConfig()
    {
        $this->publishes([
            __DIR__.'/../Config/config.php' => config_path('base.php'),
        ], 'config');
        $this->mergeConfigFrom(
            __DIR__.'/../Config/config.php', 'base'
        );
    }

    /**
     * Register views.
     *
     * @return void
     */
    public function registerViews()
    {
        $viewPath = resource_path('views/modules/base');

        $sourcePath = __DIR__.'/../Resources/views';

        $this->publishes([
            $sourcePath => $viewPath
        ]);

        $this->loadViewsFrom(array_merge(array_map(function ($path) {
            return $path . '/modules/base';
        }, \Config::get('view.paths')), [$sourcePath]), 'base');
    }

    /**
     * Register translations.
     *
     * @return void
     */
    public function registerTranslations()
    {
        $langPath = resource_path('lang/modules/base');

        if (is_dir($langPath)) {
            $this->loadTranslationsFrom($langPath, 'base');
        } else {
            $this->loadTranslationsFrom(__DIR__ .'/../Resources/lang', 'base');
        }
    }

    /**
     * Register an additional directory of factories.
     * @source https://github.com/sebastiaanluca/laravel-resource-flow/blob/develop/src/Modules/ModuleServiceProvider.php#L66
     */
    public function registerFactories()
    {
        if (! app()->environment('production')) {
            app(Factory::class)->load(__DIR__ . '/Database/factories');
        }
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return [];
    }
}


text:
@interface FMProjectionUpdater()

@property (assign, nonatomic) CGFloat srcMinValue;
@property (assign, nonatomic) CGFloat srcMaxValue;

@end

@implementation FMProjectionUpdater

- (instancetype)initWithTarget:(FMDimensionalProjection * _Nullable)target
{
	self = [super self];
	if(self) {
		_srcMinValue = +CGFLOAT_MAX;
		_srcMaxValue = -CGFLOAT_MAX;
		_filters = [NSArray array];
		_target = target;
	}
	return self;
}

- (instancetype)init
{
	return[self initWithTarget:nil];
}

- (const CGFloat *)sourceMinValue { return (_srcMinValue != +CGFLOAT_MAX) ? &_srcMinValue : nil; }
- (const CGFloat *)sourceMaxValue { return (_srcMaxValue != -CGFLOAT_MAX) ? &_srcMaxValue : nil; }

- (void)addSourceValue:(CGFloat)value update:(BOOL)update
{
	BOOL needsUpdate = NO;
	if(_srcMinValue > value) {
		_srcMinValue = value;
		needsUpdate |= update;
	}
	if(_srcMaxValue < value) {
		_srcMaxValue = value;
		needsUpdate |= update;
	}
	if(needsUpdate) {
		[self updateTarget];
	}
}

- (void)clearSourceValues:(BOOL)update
{
	_srcMinValue = +CGFLOAT_MAX;
	_srcMaxValue = -CGFLOAT_MAX;
	if(update) {
		[self updateTarget];
	}
}

- (void)addFilterToLast:(id<FMRangeFilter>)object
{
	@synchronized(self) {
		if(![_filters containsObject:object]) {
			_filters = [_filters arrayByAddingObject:object];
		}
	}
}

- (void)addFilterToFirst:(id<FMRangeFilter>)object
{
	@synchronized(self) {
		if(![_filters containsObject:object]) {
			NSMutableArray *ar = _filters.mutableCopy;
			[ar insertObject:object atIndex:0];
			_filters = ar.copy;
		}
	}
}

- (void)removeFilter:(id<FMRangeFilter>)object
{
	@synchronized(self) {
		if([_filters containsObject:object]) {
			NSMutableArray *newRestrictions = [_filters mutableCopy];
			[newRestrictions removeObject:object];
			_filters = [newRestrictions copy];
		}
	}
}

- (void)replaceFilter:(id<FMRangeFilter>)oldRestriction
		   withFilter:(id<FMRangeFilter>)newRestriction
{
	@synchronized(self) {
		if([_filters containsObject:oldRestriction]) {
			NSMutableArray *newRestrictions = [_filters mutableCopy];
			NSUInteger idx = [newRestrictions indexOfObject:oldRestriction];
			[newRestrictions replaceObjectAtIndex:idx withObject:newRestriction];
			_filters = [newRestrictions copy];
		}
	}
}

- (void)updateTarget
{
	FMDimensionalProjection *projection = _target;
	NSArray<id<FMRangeFilter>> *restrictions = _filters;
	if(projection && restrictions.count > 0) {
		CGFloat min = _srcMinValue;
		CGFloat max = _srcMaxValue;
		for(id<FMRangeFilter> restriction in restrictions.objectEnumerator) {
			[restriction updater:self minValue:&min maxValue:&max];
		}

		[projection setMin:min max:max];
	}
}

@end


text:
'use strict';

angular.module('mean.doctors').factory('Doctors', [
  function() {
    return {
      name: 'doctors'
    };
  }
]);


text:
<?php

namespace Ds\Bundle\PortalBundle\Event\Listener;

use Oro\Bundle\NavigationBundle\Event\ConfigureMenuEvent;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * Class NavigationListener
 */
class NavigationListener
{
    /**
     * @var \Symfony\Component\HttpFoundation\RequestStack
     */
    protected $stack;

    /**
     * Constructor
     *
     * @param \Symfony\Component\HttpFoundation\RequestStack $stack
     */
    public function __construct(RequestStack $stack)
    {
        $this->stack = $stack;
    }

    /**
     * Configure navigation callback
     *
     * @param ConfigureMenuEvent $event
     */
    public function onNavigationConfigure(ConfigureMenuEvent $event)
    {
        // @todo This is a quick solution. Ideal solution is to pass a routeParameter before route rendering.
        $menu = $event->getMenu();

        foreach ($menu as $item) {
            $locale = $this->stack->getCurrentRequest()->getLocale();
            $item->setUri(preg_replace('/\/en\//', '/' . $locale . '/', $item->getUri()));
        }
    }
}


text:
//
//  RegisterViewController.m
//  BirdFight
//
//  Created by 聚米 on 16/10/11.
//  Copyright © 2016年 聚米. All rights reserved.
//

#import "RegisterViewController.h"
#import "MBProgressHUD+Bird.h"
#import "UIButton+Bird.h"
#import "NSString+Bird.h"
#import "RegisterAgreeViewController.h"

@interface RegisterViewController ()
{
    NSTimer * _timer; // 计时器
    int _second;
}
/** 手机号视图 */
@property (weak, nonatomic) IBOutlet UIView *view1;
/** 密码视图 */
@property (weak, nonatomic) IBOutlet UIView *view2;
/** 验证码视图 */
@property (weak, nonatomic) IBOutlet UIView *view3;
/** 手机号输入 */
@property (weak, nonatomic) IBOutlet UITextField *phoneTF;
/** 密码输入 */
@property (weak, nonatomic) IBOutlet UITextField *passwordTF;
/** 验证码输入 */
@property (weak, nonatomic) IBOutlet UITextField *yanzhengTF;
/** 获取验证码按钮 */
@property (weak, nonatomic) IBOutlet UIButton *getYanZhengBtn;
/** 注册协议按钮 */
@property (weak, nonatomic) IBOutlet UIButton *agreeBtn;
/** 注册按钮 */
@property (weak, nonatomic) IBOutlet UIButton *registerBtn;
/** 获取验证码label */
@property (weak, nonatomic) IBOutlet UILabel *label;

@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    // 设置标题
    self.title = @"注册";
    //设置背景色
    self.view.backgroundColor = [UIColor colorWithRed:246/255.0 green:246/255.0 blue:246/255.0 alpha:1];

    // 设置视图圆角
    [self viewLayerCornerRadius:_view1];
    [self viewLayerCornerRadius:_view2];
    UIImage * backImage = [UIImage imageNamed:@"view_2"];
    _view3.layer.contents = (id)backImage.CGImage;
    _view3.backgroundColor = [UIColor colorWithPatternImage:backImage];

    // 设置输入框
    _phoneTF.borderStyle = UITextBorderStyleNone;
    _yanzhengTF.borderStyle = UITextBorderStyleNone;
    _passwordTF.borderStyle = UITextBorderStyleNone;

    // 设置获取验证码按钮
    _getYanZhengBtn.backgroundColor = [UIColor clearColor];
    _label.backgroundColor = [UIColor colorWithRed:246/255.0 green:246/255.0 blue:246/255.0 alpha:1];
    _label.hidden = YES;
    _label.textColor = [UIColor colorWithRed:249/255.0 green:83/255.0 blue:100/255.0 alpha:1];

    // 默认60秒
    _second = 60;

    // 设置注册协议按钮
    [_agreeBtn setTitle:@"《注册协议》" forState:UIControlStateNormal];
    [_agreeBtn setTitleColor:[UIColor colorWithRed:249/255.0 green:83/255.0 blue:100/255.0 alpha:1] forState:UIControlStateNormal];

    // 设置确认按钮
    [self.registerBtn setTitle:@"注册" forState:UIControlStateNormal];
    [_registerBtn diyStyle];

}

#pragma mark 设置view的圆角
-(void)viewLayerCornerRadius:(UIView *)view
{
    view.layer.cornerRadius = 20;

    view.layer.masksToBounds = YES;
}

#pragma mark 点击获取验证码按钮
- (IBAction)tapGetYanZhengBtn:(UIButton *)sender
{
    // 先判断电话号码是否输入 再判断是否正确
    if (!self.phoneTF.text.length) {
        [MBProgressHUD showError:@"请输入电话号码"];
    }else if (self.phoneTF.text.length){
        BOOL isTel = [self.phoneTF.text isMobilePhoneNumber];
        if (!isTel) {
            [MBProgressHUD showError:@"请输入正确的手机号"];
        }else{

            // 发送方法  成功提示  失败提示  开启定时器

            _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];

        }
    }
}

#pragma mark 点击协议按钮
- (IBAction)tapAgreeBtn:(UIButton *)sender
{
    // 跳转注册协议界面
    RegisterAgreeViewController * vc = [[RegisterAgreeViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark 点击注册按钮
- (IBAction)tapRegisterBtn:(UIButton *)sender
{
    if (!self.phoneTF.text.length) {
        [MBProgressHUD showError:@"请输入电话号码"];
    }
    else if (!self.passwordTF.text.length) {
        [MBProgressHUD showError:@"请输入密码"];
    }
    else if (!self.yanzhengTF.text.length) {
        [MBProgressHUD showError:@"请输入验证码"];
    }
    else{

        // 发送方法  成功提示  失败提示  停止定时器

        [self releaseTimer];

        [self.navigationController popViewControllerAnimated:YES];

    }
}

#pragma mark 倒计时方法验证码实现倒计时60秒,60秒后按钮变换开始的样子
- (void)timerFireMethod:(NSTimer *)timer
{
    if (_second == 1) {
        [timer invalidate];
        _second = 60;
        [_getYanZhengBtn setEnabled:YES];
        _label.hidden = YES;

    }else{
        _second--;
        [_getYanZhengBtn setEnabled:NO];
        NSString * text = [NSString stringWithFormat:@"%ds后重试",_second];
        _label.hidden = NO;
        _label.text = text;
    }
}

#pragma mark 如果确认完成,停止验证码倒数
- (void)releaseTimer
{
    if (_timer) {
        if ([_timer respondsToSelector:@selector(isValid)]) {
            if ([_timer isValid]) {
                [_timer invalidate];
                _second = 60;
            }
        }
    }
}

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

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
package intellij.haskell.psi.impl;

import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import static intellij.haskell.psi.HaskellTypes.*;
import intellij.haskell.psi.*;

public class HaskellKindSignatureImpl extends HaskellCompositeElementImpl implements HaskellKindSignature {

  public HaskellKindSignatureImpl(ASTNode node) {
    super(node);
  }

  public void accept(@NotNull HaskellVisitor visitor) {
    visitor.visitKindSignature(this);
  }

  public void accept(@NotNull PsiElementVisitor visitor) {
    if (visitor instanceof HaskellVisitor) accept((HaskellVisitor)visitor);
    else super.accept(visitor);
  }

  @Override
  @NotNull
  public HaskellQName getQName() {
    return notNullChild(PsiTreeUtil.getChildOfType(this, HaskellQName.class));
  }

  @Override
  @NotNull
  public HaskellTtype getTtype() {
    return notNullChild(PsiTreeUtil.getChildOfType(this, HaskellTtype.class));
  }

}


text:
import pyodbc

def _get_connector(dbtype=None):
    connector = None
    if not dbtype:
        connector = pyodbc
    if dbtype == 'exasol':
        # todo need to document and extend this
        connector = __import__('exasol')
    return connector

class AnyDB(object):
    def __init__(self, connection_string, dbtype=None):
        self._db_connection_string = connection_string
        self._db_type = dbtype
        self._db_connection = None
        self._db_cursor = None

    def get_cursor(self):
        connection_library = _get_connector(self._db_type)
        self._db_connection = connection_library.connect(self._db_connection_string)
        self._db_cursor = self._db_connection.cursor()
        return self._db_cursor

    def close(self):
        self._db_connection.close()


text:
from msrest.serialization import Model

class Usage(Model):
    """Describes network resource usage.

    Variables are only populated by the server, and will be ignored when
    sending a request.

    :ivar unit: An enum describing the unit of measurement. Default value:
     "Count" .
    :vartype unit: str
    :param current_value: The current value of the usage.
    :type current_value: long
    :param limit: The limit of usage.
    :type limit: long
    :param name: The name of the type of usage.
    :type name: ~azure.mgmt.network.v2017_06_01.models.UsageName
    """

    _validation = {
        'unit': {'required': True, 'constant': True},
        'current_value': {'required': True},
        'limit': {'required': True},
        'name': {'required': True},
    }

    _attribute_map = {
        'unit': {'key': 'unit', 'type': 'str'},
        'current_value': {'key': 'currentValue', 'type': 'long'},
        'limit': {'key': 'limit', 'type': 'long'},
        'name': {'key': 'name', 'type': 'UsageName'},
    }

    unit = "Count"

    def __init__(self, current_value, limit, name):
        super(Usage, self).__init__()
        self.current_value = current_value
        self.limit = limit
        self.name = name


text:
<!DOCTYPE html>

    <title>Oracle Joins – Ant Beck – Research Fellow (Nottingham University), Director (GeoLytics Ltd.)</title>

        <meta charset="utf-8" />
    <meta content='text/html; charset=utf-8' http-equiv='Content-Type'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0'>

    <meta name="description" content="Metadata
" />
    <meta property="og:description" content="Metadata
" />

    <meta name="author" content="Ant Beck" />

    <meta property="og:title" content="Oracle Joins" />
    <meta property="twitter:title" content="Oracle Joins" />

    <link rel="stylesheet" type="text/css" href="/style.css" />
    <link rel="alternate" type="application/rss+xml" title="Ant Beck - Research Fellow (Nottingham University), Director (GeoLytics Ltd.)" href="/feed.xml" />

Ant Beck

Research Fellow (Nottingham University), Director (GeoLytics Ltd.)

            Blog
            About

Oracle Joins

Metadata

This document is formatted using MarkDown

This work was done by Anthony Beck, OrcID: 0000-0002-2991-811X.

Part of the series of hating Oracle but having to work with it

Cross joins

Essentially the dot product.

I need to create a cross join to see what combination of products I have based on tables in an Oracle Schema.

Currently I want to compare all things which are prefixed as

BUILDINGPOLYGON_

ROADNETWORK_

select
    a.TABLE_NAME as CLASS1,
        b.TABLE_NAME as CLASS2
    from
        user_tables a
    CROSS JOIN
        user_tables b
    where
        a.TABLE_NAME LIKE 'BUILDINGPOLYGON_%'
        AND a.TABLE_NAME NOT LIKE '%_O'
        AND b.TABLE_NAME LIKE 'ROADNETWORK_%'
        AND b.TABLE_NAME NOT LIKE '%_O';

If I add in new address elements I may want to add in an extra component:

ADDRESSPOINT_

BUILDINGPOLYGON_

ROADNETWORK_

select
    a.TABLE_NAME as CLASS1,
        b.TABLE_NAME as CLASS2,
        c.TABLE_NAME as CLASS3
    from
        user_tables a
    CROSS JOIN
        user_tables b
    CROSS JOIN
        user_tables c
    where
        a.TABLE_NAME LIKE 'ADDRESSPOINT_%'
        AND a.TABLE_NAME NOT LIKE '%_O'
        AND b.TABLE_NAME LIKE 'BUILDINGPOLYGON_%'
        AND b.TABLE_NAME NOT LIKE '%_O'
        and c.TABLE_NAME LIKE 'ROADNETWORK_%'
        AND c.TABLE_NAME NOT LIKE '%_O';

select
    a.TABLE_NAME as CLASS1,
        b.TABLE_NAME as CLASS2,
        c.TABLE_NAME as CLASS3
    from
        user_tables a
        CROSS JOIN user_tables b
        CROSS JOIN user_tables c
    where
        a.TABLE_NAME LIKE 'BLD_PLY_%'
        AND a.TABLE_NAME NOT LIKE '%_O'
        AND b.TABLE_NAME LIKE 'ROD_NET_%'
        AND b.TABLE_NAME NOT LIKE '%_O'
        and c.TABLE_NAME LIKE 'ADD_CNT_%'
        AND c.TABLE_NAME NOT LIKE '%_O';

This means I can produce a table, METADATA_CLASSPAIR with 3 tuples:

CLASSSOURCE|CLASSNAME
----|----
BUILDING SOURCE|CLASS1
ROADNETWORK_SOURCE|CLASS2
ADDRESS SOURCE|CLASS3

This table is used when calling RadiusStudio. By doing it like this I can essentially call a template Radius Studio action and iterate directly over my CROSS JOIN rows. This means everything is generic.

ABP in the ABP schema

It looks like the ingest sequence for ABP embeds the geomtry as 81989. 81989 is an old oracle name for OSGB projection (srid 27700)

To fix this I did the following:

drop the index

update ABPREMBLPU p set p.geometry.sdosrid=27700;

COMMIT;

Recreate the index

ABP in the postaldeliveryinput schema

Radius Studio converts the UPRN (number) to a string (either natively or using the built in function) as an exponential string

Nearest Neighbour

set serveroutput on;
begin
  declare
    lt2 number :=0;
    lt1 number :=0;
    lt5 number :=0;
    lt10 number :=0;
    lt25 number :=0;
    lt50 number :=0;
    gt50 number :=0;
    counter number := 0;

begin

  for recs in
    (
    select
        street_intrstn_id,
            new_geom
        from
            t_street_intersection
        where
            rownum < 100
    ) loop

        for recs2 in
            (select
                recs.street_intrstn_id,
                    r.toid,
                    sdo_nn_distance(1) dist
                from
                    itn.ITNRDND r
                where
                    sdo_nn
                        (
                        r.new_geom,
                        recs.new_geom,
                        'sdo_batch_size=5',
                        1
                        ) = 'TRUE'
                    and rownum < 2
            ) Loop

                if recs2.dist <= 1 then
                    lt1 := lt1 + 1;
                    elsif recs2.dist <= 2 then
                        lt2 := lt2 + 1;
                    elsif recs2.dist <= 5 then
                        lt5 := lt5 + 1;
                    elsif recs2.dist <= 10 then
                        lt10 := lt10 + 1;
                    elsif recs2.dist <= 25 then
                        lt25 := lt25 + 1;
                    elsif recs2.dist <= 50 then
                        lt50 := lt50 + 1;
                    else
                        gt50 := gt50 + 1;
                end if;

                counter := counter+1;

            end loop;

    end loop;

  dbms_output.put_line('Less than     1m '||to_char(lt1,'99999')||'   '||to_char(lt1/counter*100,'999.0')||'%');

  dbms_output.put_line('Less than     2m '||to_char(lt2,'99999')||'   '||to_char(lt2/counter*100,'999.0')||'%');

  dbms_output.put_line('Less than     5m '||to_char(lt5,'99999')||'   '||to_char(lt5/counter*100,'999.0')||'%');

  dbms_output.put_line('Less than    10m '||to_char(lt10,'99999')||'   '||to_char(lt10/counter*100,'999.0')||'%');

  dbms_output.put_line('Less than    25m '||to_char(lt25,'99999')||'   '||to_char(lt25/counter*100,'999.0')||'%');

  dbms_output.put_line('Less than    50m '||to_char(lt50,'99999')||'   '||to_char(lt50/counter*100,'999.0')||'%');

  dbms_output.put_line('Greater Than 50m '||to_char(gt50,'99999')||'   '||to_char(gt50/counter*100,'999.0')||'%');

  dbms_output.put_line('TOTAL            '||to_char(counter,'99999'));

  end;

end;

/

    Written on May 12, 2014


text:
/**
 * @file FTP_IOStream.h
 *
 * @author Martin Corino <mcorino@remedy.nl>
 */

#ifndef ACE_FTP_IOSTREAM_H
#define ACE_FTP_IOSTREAM_H

#include /**/ "ace/pre.h"

#include /**/ "ace/config-all.h"

#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */

#include "ace/INet/INet_Export.h"
#include "ace/INet/BufferedStreamBuffer.h"
#include <ostream>
#include <istream>

ACE_BEGIN_VERSIONED_NAMESPACE_DECL

namespace ACE
  {
    namespace FTP
      {

        /**
        * @class ACE_FTP_StreamBuffer
        *
        * @brief
        *
        */
        class ACE_INET_Export StreamBuffer
          : public ACE::IOS::BufferedStreamBuffer
          {
            public:
              StreamBuffer (std::iostream * stream);
              virtual ~StreamBuffer ();

              virtual int sync ();

              std::iostream* set_stream (std::iostream * stream);

            protected:
              enum
                {
                  BUFFER_SIZE = 4096
                };

              virtual int read_from_stream (char* buffer, std::streamsize length);

              virtual int write_to_stream (const char* buffer, std::streamsize length);

            private:
              std::iostream * stream_;
          };

        /**
        * @class ACE_FTP_IOS
        *
        * @brief
        *
        */
        class ACE_INET_Export IOS
          : public virtual std::ios
          {
            public:
              IOS (std::iostream* stream);
              ~IOS ();

              StreamBuffer* rdbuf ();

              std::iostream* set_stream (std::iostream* stream);

            protected:
              StreamBuffer streambuf_;
          };

        /**
        * @class ACE_FTP_OStream
        *
        * @brief
        *
        */
        class ACE_INET_Export OStream
          : public IOS, public std::ostream
          {
            public:
              explicit OStream(std::iostream* stream);
              ~OStream();

              void set_interceptor (StreamBuffer::interceptor_type& interceptor);
          };

        /**
        * @class ACE_FTP_IStream
        *
        * @brief
        *
        */
        class ACE_INET_Export IStream
          : public IOS, public std::istream
          {
            public:
              explicit IStream(std::iostream* stream);
              ~IStream();

              void set_interceptor (StreamBuffer::interceptor_type& interceptor);
          };

      }
  }

ACE_END_VERSIONED_NAMESPACE_DECL

#if defined (__ACE_INLINE__)
#include "ace/INet/FTP_IOStream.inl"
#endif

#include /**/ "ace/post.h"
#endif /* ACE_FTP_IOSTREAM_H */


text:
<?php

namespace Sabre\WebFinger;

interface ResourceInterface
{
    /**
     * The value of the subject is a URI that describes the entity.
     *
     * It may be different from the actual resource being requested, in cases
     * where the canonical resource URI changed.
     *
     * @return string
     */
    public function getSubject();

    /**
     * The "aliases" array is an array of zero or more URI strings that
     * identify the same entity as the "subject" URI.
     *
     * @return array
     */
    public function getAliases();

    /**
     * The "properties" object comprises zero or more name/value pairs whose
     * names are URIs (referred to as "property identifiers") and whose values
     * are strings or null.  Properties are used to convey additional
     * information about the subject.
     *
     * @return array
     */
    public function getProperties();

    /**
     * The links array has a number of member objects, each representing a
     * single link or relation from the subject.
     *
     * return LinkInterface[]
     */
    public function getLinks();
}


text:
require('./angular-locale_lkt-us');
module.exports = 'ngLocale';


text:
function handles = disableDataLoaded(hObject, handles)

set(handles.btnClusterData, 'Enable', 'off');
set(handles.btnClusterSave, 'Enable', 'off');
set(handles.btnSimGraphSave, 'Enable', 'off');

handles = togglePlotSimGraph(hObject, handles, 'off');
handles = togglePlotSilhouette(hObject, handles, 'off');
handles = togglePlotClusteredData(hObject, handles, 'off');

guidata(hObject, handles);