text:
. /etc/profile.d/modules.sh
module add ci
module add gcc/${GCC_VERSION}
module add cmake
module add lapack/3.6.0-gcc-${GCC_VERSION}
module add openblas/0.2.15-gcc-${GCC_VERSION}
module add openmpi/${OPENMPI_VERSION}-gcc-${GCC_VERSION}
module add fftw/3.3.4-gcc-${GCC_VERSION}-mpi-${OPENMPI_VERSION}
module add boost/1.62.0-gcc-${GCC_VERSION}-mpi-${OPENMPI_VERSION}
module add gsl/2.0

# gromacs testing requires libxml2
# module  add  libxml2

export OMP_NUM_THREADS=1
echo ""
cd ${WORKSPACE}/${NAME}-${VERSION}/build-${BUILD_NUMBER}
# echo "Making check with ${OMP_NUM_THREADS} threads"
# export CTEST_TEST_TIMEOUT=3600
# make check
# echo $?
echo "Running Make Install"
make install

mkdir -p modules

echo "Making CI module"

(
cat <<MODULE_FILE
#%Module1.0
## $NAME modulefile
##
proc ModulesHelp { } {
    puts stderr "       This module does nothing but alert the user"
    puts stderr "       that the [module-info name] module is not available"
}

module-whatis   "$NAME $VERSION. Compiled for GCC ${GCC_VERSION} with OpenMPI version ${OPENMPI_VERSION}"
setenv       GMX_VERSION       $VERSION
setenv       GMX_DIR           /data/ci-build/$::env(SITE)/$::env(OS)/$::env(ARCH)/$NAME/$VERSION/${VERSION}-gcc-${GCC_VERSION}-mpi-${OPENMPI_VERSION}
setenv       GMXPREFIX         $::env(GMX_DIR)
setenv       GMXBIN            $::env(GMX_DIR)/bin
prepend-path PATH              $::env(GMXBIN)
setenv       GMXLDLIB          $::env(GMXPREFIX)/lib
setenv       GMXMAN            $::env(GMXPREFIX)/share/man
setenv       GMXDATA           $::env(GMXPREFIX)/share/gromacs
setenv       GROMACS_DIR       $::env(GMXPREFIX)
prepend-path LD_LIBRARY_PATH   $::env(GMXPREFIX)/lib
setenv GMX_INCLUDE_DIR   $::env(GMX_DIR)/include
setenv GMX_LIB_DIR      $::env(GMX_DIR)/lib
prepend-path CPATH             $::env(GMX_INCLUDE_DIR)
append-path CFLAGS             "-I$::env(GMX_INCLUDE_DIR) -L$::env(GMX_DIR)/lib"
MODULE_FILE
) > modules/${VERSION}-gcc-${GCC_VERSION}-mpi-${OPENMPI_VERSION}

mkdir -p ${CHEMISTRY}/${NAME}
cp modules/${VERSION}-gcc-${GCC_VERSION}-mpi-${OPENMPI_VERSION} ${CHEMISTRY}/${NAME}
#  check if we can use it.
echo "is the module available ?"
module avail ${NAME}
echo "Testing the module"
module add ${NAME}/${VERSION}-gcc-${GCC_VERSION}-mpi-${OPENMPI_VERSION}

echo "Binaries available : "
ls ${GMXPREFIX}/bin
env

#  the rest comes from http://www.bevanlab.biochem.vt.edu/Pages/Personal/justin/gmx-tutorials/lysozyme/
# Get the pdb file
wget --no-check-certificate https://files.rcsb.org/view/1AKI.pdb
echo 15 | gmx_mpi_d pdb2gmx -f 1AKI.pdb -o 1AKI_processed.gro -water spce
gmx_mpi_d editconf -f 1AKI_processed.gro -o 1AKI_newbox.gro -c -d 1.0 -bt cubic
gmx_mpi_d solvate -cp 1AKI_newbox.gro -cs spc216.gro -o 1AKI_solv.gro -p topol.top
wget http://www.bevanlab.biochem.vt.edu/Pages/Personal/justin/gmx-tutorials/lysozyme/Files/ions.mdp
gmx_mpi_d grompp -f ions.mdp -c 1AKI_solv.gro -p topol.top -o ions.tpr
echo 13 | gmx_mpi_d genion -s ions.tpr -o 1AKI_solv_ions.gro -p topol.top -pname NA -nname CL -nn 8
wget http://www.bevanlab.biochem.vt.edu/Pages/Personal/justin/gmx-tutorials/lysozyme/Files/minim.mdp
gmx_mpi_d grompp -f minim.mdp -c 1AKI_solv_ions.gro -p topol.top -o em.tpr
# mpirun gmx_mpi_d  mdrun -v -deffnm em
# wget http://www.bevanlab.biochem.vt.edu/Pages/Personal/justin/gmx-tutorials/lysozyme/Files/nvt.mdp
# gmx_mpi_d grompp -f nvt.mdp -c em.gro -p topol.top -o nvt.tpr
# This takes ALL the CPUS
# mpirun gmx_mpi_d mdrun -deffnm nvt


text:
package androidx.leanback.system;

import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP_PREFIX;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.os.Build;
import android.util.Log;

import androidx.annotation.RestrictTo;
import androidx.leanback.widget.ShadowOverlayContainer;

/**
 * Provides various preferences affecting Leanback runtime behavior.
 * <p>Note this class is not thread safe and its methods should only
 * be invoked from the UI thread
 * </p>
 */
public class Settings {
    static private final String TAG = "Settings";
    static private final boolean DEBUG = false;

    // The intent action that must be provided by a broadcast receiver
    // in a customization package.
    private static final String ACTION_PARTNER_CUSTOMIZATION =
            "android.support.v17.leanback.action.PARTNER_CUSTOMIZATION";

    public static final String PREFER_STATIC_SHADOWS = "PREFER_STATIC_SHADOWS";

    public static final String OUTLINE_CLIPPING_DISABLED = "OUTLINE_CLIPPING_DISABLED";

    static private Settings sInstance;

    private boolean mPreferStaticShadows;
    private boolean mOutlineClippingDisabled;

    /**
     * Returns the singleton Settings instance.
     */
    static public Settings getInstance(Context context) {
        if (sInstance == null) {
            sInstance = new Settings(context);
        }
        return sInstance;
    }

    private Settings(Context context) {
        if (DEBUG) Log.v(TAG, "generating preferences");
        Customizations customizations = getCustomizations(context);
        generateSetting(customizations, context);
    }

    /**
     * Returns true if static shadows are recommended.
     *
     * @hide
     */
    @RestrictTo(LIBRARY_GROUP_PREFIX)
    public boolean preferStaticShadows() {
        return mPreferStaticShadows;
    }

    /**
     * Returns true if view outline is disabled on low power chipset.
     *
     * @hide
     */
    @RestrictTo(LIBRARY_GROUP_PREFIX)
    public boolean isOutlineClippingDisabled() {
        return mOutlineClippingDisabled;
    }

    /**
     * Returns the boolean preference for the given key.
     */
    public boolean getBoolean(String key) {
        return getOrSetBoolean(key, false, false);
    }

    /**
     * Sets the boolean preference for the given key.  If an app uses this api to override
     * a default preference, it must do so on every activity create.
     */
    public void setBoolean(String key, boolean value) {
        getOrSetBoolean(key, true, value);
    }

    boolean getOrSetBoolean(String key, boolean set, boolean value) {
        if (key.compareTo(PREFER_STATIC_SHADOWS) == 0) {
            return set ? (mPreferStaticShadows = value) : mPreferStaticShadows;
        } else if (key.compareTo(OUTLINE_CLIPPING_DISABLED) == 0) {
            return set ? (mOutlineClippingDisabled = value) : mOutlineClippingDisabled;
        }
        throw new IllegalArgumentException("Invalid key");
    }

    private void generateSetting(Customizations customizations, Context context) {
        if (ShadowOverlayContainer.supportsDynamicShadow()) {
            mPreferStaticShadows = false;
            if (customizations != null) {
                mPreferStaticShadows = customizations.getBoolean(
                        "leanback_prefer_static_shadows", mPreferStaticShadows);
            }
        } else {
            mPreferStaticShadows = true;
        }

        if (Build.VERSION.SDK_INT >= 21) {
            ActivityManager activityManager = (ActivityManager)
                    context.getSystemService(Context.ACTIVITY_SERVICE);
            mOutlineClippingDisabled = activityManager.isLowRamDevice();
            if (customizations != null) {
                mOutlineClippingDisabled = customizations.getBoolean(
                        "leanback_outline_clipping_disabled", mOutlineClippingDisabled);
            }
        } else {
            mOutlineClippingDisabled = true;
        }
        if (DEBUG) Log.v(TAG, "generated preference " + PREFER_STATIC_SHADOWS + ": "
                + mPreferStaticShadows + " "
                + OUTLINE_CLIPPING_DISABLED + " : " + mOutlineClippingDisabled);
    }

    static class Customizations {
        Resources mResources;
        String mPackageName;

        public Customizations(Resources resources, String packageName) {
            mResources = resources;
            mPackageName = packageName;
        }

        public boolean getBoolean(String resourceName, boolean defaultValue) {
            int resId = mResources.getIdentifier(resourceName, "bool", mPackageName);
            return resId > 0 ? mResources.getBoolean(resId) : defaultValue;
        }
    };

    private Customizations getCustomizations(Context context) {
        final PackageManager pm = context.getPackageManager();
        final Intent intent = new Intent(ACTION_PARTNER_CUSTOMIZATION);
        if (DEBUG) {
            Log.v(TAG, "getting oem customizations by intent: " + ACTION_PARTNER_CUSTOMIZATION);
        }

        Resources resources = null;
        String packageName = null;
        for (ResolveInfo info : pm.queryBroadcastReceivers(intent, 0)) {
            packageName = info.activityInfo.packageName;
            if (DEBUG) Log.v(TAG, "got package " + packageName);
            if (packageName != null && isSystemApp(info)) try {
                resources = pm.getResourcesForApplication(packageName);
            } catch (PackageManager.NameNotFoundException ex) {
                // Do nothing
            }
            if (resources != null) {
                if (DEBUG) Log.v(TAG, "found customization package: " + packageName);
                break;
            }
        }
        return resources == null ? null : new Customizations(resources, packageName);
    }

    private static boolean isSystemApp(ResolveInfo info) {
        return (info.activityInfo != null
                && (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
    }
}

redpajama_set_name: RedPajamaGithub


text:
GLWars is a personal test game I'm making on my free time. I will be focusing
most on a GPU particle system and multiplayer part.

##Install
1. Download the repository and extract the archive.
2. Run start.cmd, two cmd boxes should open one for the web server and one for the game server.
3. Browse your local ip: 127.0.0.1
4. Other clients should be able to reach you on your external ip.

##libraries:
* THREE.js
* jQuery
* Box2d js-port
* Webaudio.js


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

    <title>ActiveSupport::JSON::Encoding::Encoder</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" href="../../../../css/reset.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../../css/main.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../../css/github.css" type="text/css" media="screen" />

            Ruby on Rails 4.0.0

            Class
            ActiveSupport::JSON::Encoding::Encoder

                <

                    Object

/home/jude/.gem/ruby/2.0.0/gems/activesupport-4.0.0/lib/active_support/json/encoding.rb

Methods

A

                as_json

E

                encode,

                escape

N

                new

O

                options_for

Attributes

              [R]

            options

Class Public methods

              new(options = nil)

            Link

                Source:
                show

# File /home/jude/.gem/ruby/2.0.0/gems/activesupport-4.0.0/lib/active_support/json/encoding.rb, line 43
def initialize(options = nil)
  @options = options || {}
  @seen = Set.new
end

Instance Public methods

              as_json(value, use_options = true)

            Link

like encode, but only calls #as_json, without encoding to
string.

                Source:
                show

# File /home/jude/.gem/ruby/2.0.0/gems/activesupport-4.0.0/lib/active_support/json/encoding.rb, line 56
def as_json(value, use_options = true)
  check_for_circular_references(value) do
    use_options ? value.as_json(options_for(value)) : value.as_json
  end
end

              encode(value, use_options = true)

            Link

                Source:
                show

# File /home/jude/.gem/ruby/2.0.0/gems/activesupport-4.0.0/lib/active_support/json/encoding.rb, line 48
def encode(value, use_options = true)
  check_for_circular_references(value) do
    jsonified = use_options ? value.as_json(options_for(value)) : value.as_json
    jsonified.encode_json(self)
  end
end

              escape(string)

            Link

                Source:
                show

# File /home/jude/.gem/ruby/2.0.0/gems/activesupport-4.0.0/lib/active_support/json/encoding.rb, line 72
def escape(string)
  Encoding.escape(string)
end

              options_for(value)

            Link

                Source:
                show

# File /home/jude/.gem/ruby/2.0.0/gems/activesupport-4.0.0/lib/active_support/json/encoding.rb, line 62
def options_for(value)
  if value.is_a?(Array) || value.is_a?(Hash)
    # hashes and arrays need to get encoder in the options, so that
    # they can detect circular references.
    options.merge(:encoder => self)
  else
    options.dup
  end
end


text:
#pragma once
#include <kernel_headers/approx1.hpp>
#include <kernel_headers/approx2.hpp>
#include <program.hpp>
#include <traits.hpp>
#include <string>
#include <mutex>
#include <map>
#include <dispatch.hpp>
#include <Param.hpp>
#include <debug_opencl.hpp>
#include <type_util.hpp>
#include <math.hpp>
#include "config.hpp"

using cl::Buffer;
using cl::Program;
using cl::Kernel;
using cl::make_kernel;
using cl::EnqueueArgs;
using cl::NDRange;
using std::string;

namespace opencl
{
    namespace kernel
    {
        static const int TX = 16;
        static const int TY = 16;

        static const int THREADS = 256;

        ///////////////////////////////////////////////////////////////////////////
        // Wrapper functions
        ///////////////////////////////////////////////////////////////////////////
        template <typename Ty, typename Tp, af_interp_type method>
        void approx1(Param out, const Param in, const Param pos, const float offGrid)
        {
            try {
                static std::once_flag compileFlags[DeviceManager::MAX_DEVICES];
                static std::map<int, Program*>  approxProgs;
                static std::map<int, Kernel*> approxKernels;

                int device = getActiveDeviceId();

                std::call_once( compileFlags[device], [device] () {
                    ToNum<Ty> toNum;
                    std::ostringstream options;
                    options << " -D Ty="        << dtype_traits<Ty>::getName()
                            << " -D Tp="        << dtype_traits<Tp>::getName()
                            << " -D ZERO="      << toNum(scalar<Ty>(0));

                    if((af_dtype) dtype_traits<Ty>::af_type == c32 ||
                       (af_dtype) dtype_traits<Ty>::af_type == c64) {
                        options << " -D CPLX=1";
                    } else {
                        options << " -D CPLX=0";
                    }
                    if (std::is_same<Ty, double>::value ||
                        std::is_same<Ty, cdouble>::value) {
                        options << " -D USE_DOUBLE";
                    }

                    switch(method) {
                        case AF_INTERP_NEAREST: options << " -D INTERP=NEAREST";
                            break;
                        case AF_INTERP_LINEAR:  options << " -D INTERP=LINEAR";
                            break;
                        default:
                            break;
                    }
                    Program prog;
                    buildProgram(prog, approx1_cl, approx1_cl_len, options.str());
                    approxProgs[device] = new Program(prog);

                    approxKernels[device] = new Kernel(*approxProgs[device], "approx1_kernel");
                });

                auto approx1Op = make_kernel<Buffer, const KParam, const Buffer, const KParam,
                                       const Buffer, const KParam, const float, const int>
                                      (*approxKernels[device]);

                NDRange local(THREADS, 1, 1);
                int blocksPerMat = divup(out.info.dims[0], local[0]);
                NDRange global(blocksPerMat * local[0] * out.info.dims[1],
                               out.info.dims[2] * out.info.dims[3] * local[0],
                               1);

                approx1Op(EnqueueArgs(getQueue(), global, local),
                          *out.data, out.info, *in.data, in.info,
                          *pos.data, pos.info, offGrid, blocksPerMat);

                CL_DEBUG_FINISH(getQueue());
            } catch (cl::Error err) {
                CL_TO_AF_ERROR(err);
                throw;
            }
        }

        template <typename Ty, typename Tp, af_interp_type method>
        void approx2(Param out, const Param in, const Param pos, const Param qos, const float offGrid)
        {
            try {
                static std::once_flag compileFlags[DeviceManager::MAX_DEVICES];
                static std::map<int, Program*>       approxProgs;
                static std::map<int, Kernel*>      approxKernels;

                int device = getActiveDeviceId();

                std::call_once( compileFlags[device], [device] () {
                    ToNum<Ty> toNum;
                    std::ostringstream options;
                    options << " -D Ty="        << dtype_traits<Ty>::getName()
                            << " -D Tp="        << dtype_traits<Tp>::getName()
                            << " -D ZERO="      << toNum(scalar<Ty>(0));

                    if((af_dtype) dtype_traits<Ty>::af_type == c32 ||
                       (af_dtype) dtype_traits<Ty>::af_type == c64) {
                        options << " -D CPLX=1";
                    } else {
                        options << " -D CPLX=0";
                    }
                    if (std::is_same<Ty, double>::value ||
                        std::is_same<Ty, cdouble>::value) {
                        options << " -D USE_DOUBLE";
                    }

                    switch(method) {
                        case AF_INTERP_NEAREST: options << " -D INTERP=NEAREST";
                            break;
                        case AF_INTERP_LINEAR:  options << " -D INTERP=LINEAR";
                            break;
                        default:
                            break;
                    }
                    Program prog;
                    buildProgram(prog, approx2_cl, approx2_cl_len, options.str());
                    approxProgs[device] = new Program(prog);

                    approxKernels[device] = new Kernel(*approxProgs[device], "approx2_kernel");
                });

                auto approx2Op = make_kernel<Buffer, const KParam, const Buffer, const KParam,
                                       const Buffer, const KParam, const Buffer, const KParam,
                                       const float, const int, const int>
                                       (*approxKernels[device]);

                NDRange local(TX, TY, 1);
                int blocksPerMatX = divup(out.info.dims[0], local[0]);
                int blocksPerMatY = divup(out.info.dims[1], local[1]);
                NDRange global(blocksPerMatX * local[0] * out.info.dims[2],
                               blocksPerMatY * local[1] * out.info.dims[3],
                               1);

                approx2Op(EnqueueArgs(getQueue(), global, local),
                          *out.data, out.info,
                          *in.data, in.info,
                          *pos.data, pos.info,
                          *qos.data, qos.info,
                          offGrid, blocksPerMatX, blocksPerMatY);
                CL_DEBUG_FINISH(getQueue());
            } catch (cl::Error err) {
                CL_TO_AF_ERROR(err);
                throw;
            }
        }
    }
}


text:
package each

import (
	"reflect"
	"sync"
)

func init() {
	MakeEach(&Each)
	MakeEach(&EachInt)
	// MakeEach(&EachString)
	MakeEach(&EachStringInt)
	MakeEachP(&EachP)
}

var Each func(fn interface{}, slice_or_map interface{})
var EachP func(fn interface{}, slice_or_map interface{})
var EachInt func(func(value, i int), []int)
var EachStringInt func(func(value int, key string), map[string]int)

func Maker(fn interface{}, impl func(args []reflect.Value) (results []reflect.Value)) {
	fnV := reflect.ValueOf(fn).Elem()
	fnI := reflect.MakeFunc(fnV.Type(), impl)
	fnV.Set(fnI)
}

func interfaceToValue(v reflect.Value) reflect.Value {
	if v.Kind() == reflect.Interface {
		return reflect.ValueOf(v.Interface())
	}
	return v
}

func extractArgs(values []reflect.Value) (reflect.Value, reflect.Value) {
	fn := interfaceToValue(values[0])
	col := interfaceToValue(values[1])
	return fn, col
}

func MakeEach(fn interface{}) {
	Maker(fn, each)
}

func MakeEachP(fn interface{}) {
	Maker(fn, eachP)
}

func each(values []reflect.Value) []reflect.Value {
	fn, col := extractArgs(values)

	if col.Kind() == reflect.Map {
		eachMap(fn, col)
	}

	if col.Kind() == reflect.Slice {
		eachSlice(fn, col)
	}

	return nil
}

func eachSlice(fn, s reflect.Value) {
	for i := 0; i < s.Len(); i++ {
		v := s.Index(i)
		eachCall(fn, v, reflect.ValueOf(i))
	}
}

func eachMap(fn, m reflect.Value) {
	for _, k := range m.MapKeys() {
		v := m.MapIndex(k)
		eachCall(fn, v, k)
	}
}

func eachCall(fn, v, i reflect.Value) {
	args := []reflect.Value{v}
	if in := fn.Type().NumIn(); in == 2 {
		args = append(args, i)
	}
	fn.Call(args)
}

func eachP(values []reflect.Value) []reflect.Value {

	fn, col := extractArgs(values)

	if col.Kind() == reflect.Map {
		eachMapP(fn, col)
	}

	if col.Kind() == reflect.Slice {
		eachSliceP(fn, col)
	}

	return nil
}

func eachSliceP(fn, s reflect.Value) {
	var done sync.WaitGroup
	for i := 0; i < s.Len(); i++ {
		v := s.Index(i)
		done.Add(1)
		go func() {
			eachCall(fn, v, reflect.ValueOf(i))
			done.Done()
		}()
	}
	done.Wait()
}

func eachMapP(fn, m reflect.Value) {
	var done sync.WaitGroup
	keys := m.MapKeys()
	done.Add(len(keys))

	for _, k := range keys {
		v := m.MapIndex(k)
		go func(fn, v, k reflect.Value) {
			eachCall(fn, v, k)
			done.Done()
		}(fn, v, k)
	}
	done.Wait()
}

func refEach(slice []string, fn func(string)) {
	for i := 0; i < len(slice); i++ {
		fn(slice[i])
	}
}

func refPEach(slice []string, fn func(string)) {
	var done sync.WaitGroup

	for _, s := range slice {
		s := s
		done.Add(1)
		go func() {
			fn(s)
			done.Done()
		}()
	}

	done.Wait()
}


text:
<control>

	<command>content.default</command>
	<viewheader>content.header</viewheader>
	<viewfooter>content.footer</viewfooter>
	<view>content.index</view>
	<view status="CMD_ERROR">content.error</view>
	<view status="CMD_INSUFFICIENT_DATA">content.error</view>

	<uri name="/content/notfound">
		<command>content.static</command>
		<viewheader>content.header</viewheader>
		<viewfooter>content.footer</viewfooter>
		<view>content.404</view>
	</uri>

	<uri name="/content/error">
		<command>content.static</command>
		<viewheader>content.header</viewheader>
		<viewfooter>content.footer</viewfooter>
		<view>content.error</view>
	</uri>

</control>


text:
package org.oep.core.processmgt.service;

import com.liferay.portal.service.ServiceWrapper;

/**
 * Provides a wrapper for {@link StepTransitionService}.
 *
 * @author trungdk
 * @see StepTransitionService
 * @generated
 */
public class StepTransitionServiceWrapper implements StepTransitionService,
	ServiceWrapper<StepTransitionService> {
	public StepTransitionServiceWrapper(
		StepTransitionService stepTransitionService) {
		_stepTransitionService = stepTransitionService;
	}

	/**
	* Returns the Spring bean ID for this bean.
	*
	* @return the Spring bean ID for this bean
	*/
	@Override
	public java.lang.String getBeanIdentifier() {
		return _stepTransitionService.getBeanIdentifier();
	}

	/**
	* Sets the Spring bean ID for this bean.
	*
	* @param beanIdentifier the Spring bean ID for this bean
	*/
	@Override
	public void setBeanIdentifier(java.lang.String beanIdentifier) {
		_stepTransitionService.setBeanIdentifier(beanIdentifier);
	}

	@Override
	public java.lang.Object invokeMethod(java.lang.String name,
		java.lang.String[] parameterTypes, java.lang.Object[] arguments)
		throws java.lang.Throwable {
		return _stepTransitionService.invokeMethod(name, parameterTypes,
			arguments);
	}

	/**
	 * @deprecated As of 6.1.0, replaced by {@link #getWrappedService}
	 */
	public StepTransitionService getWrappedStepTransitionService() {
		return _stepTransitionService;
	}

	/**
	 * @deprecated As of 6.1.0, replaced by {@link #setWrappedService}
	 */
	public void setWrappedStepTransitionService(
		StepTransitionService stepTransitionService) {
		_stepTransitionService = stepTransitionService;
	}

	@Override
	public StepTransitionService getWrappedService() {
		return _stepTransitionService;
	}

	@Override
	public void setWrappedService(StepTransitionService stepTransitionService) {
		_stepTransitionService = stepTransitionService;
	}

	private StepTransitionService _stepTransitionService;
}


text:
package genericSwapMethodStrings;

import java.util.List;

public class Box<T> {
    private T element;
    //private List<T> elements;

    public Box(T element) {
        this.element = element;
    }

    public static <T> void swapElements(List<T> list, int firstIndex, int secondIndex) {
        //T tempElement = list.remove(firstIndex);
        list.add(firstIndex, list.get(secondIndex));
        T tempElement = list.remove(firstIndex + 1);
        list.add(secondIndex, tempElement);
        list.remove(secondIndex + 1);
    }

    @Override
    public String toString() {
        return String.format("%s: %s", this.element.getClass().getCanonicalName(), this.element);
    }
}


text:
#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_MOBILE_SUBSCRIBE_BUTTON_RESPONSE_H_
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_MOBILE_SUBSCRIBE_BUTTON_RESPONSE_H_

#include "application_manager/commands/command_response_impl.h"
#include "utils/macro.h"

namespace application_manager {

namespace commands {

/**
 * @brief SubscribeButtonResponse command class
 **/
class SubscribeButtonResponse : public CommandResponseImpl {
 public:
  /**
   * @brief SubscribeButtonResponse class constructor
   *
   * @param message Incoming SmartObject message
   **/
  SubscribeButtonResponse(const MessageSharedPtr& message,
                          ApplicationManager& application_manager);

  /**
   * @brief SubscribeButtonResponse class destructor
   **/
  virtual ~SubscribeButtonResponse();

  /**
   * @brief Execute command
   **/
  virtual void Run();

 private:
  DISALLOW_COPY_AND_ASSIGN(SubscribeButtonResponse);
};

}  // namespace commands
}  // namespace application_manager

#endif  // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_MOBILE_SUBSCRIBE_BUTTON_RESPONSE_H_


text:
<?php namespace SeBuDesign\BuckarooJson\Parts;

class ContinueOnIncomplete
{
    const No = 0;
    const RedirectToHTML = 1;
}


text:
module Distribunaut # :nodoc:
  class Tuple

    attr_accessor :app_name
    attr_accessor :space
    attr_accessor :object
    attr_accessor :description
    attr_accessor :timeout

    def initialize(values = {})
      values.each do |k, v|
        self.send("#{k}=", v)
      end
    end

    def to_array
      [self.app_name, self.space, self.object, self.description]
    end

    def to_search_array
      [self.app_name, self.space, nil, nil]
    end

    def to_s
      self.to_array.inspect
    end

    class << self

      def from_array(ar)
        tuple = Distribunaut::Tuple.new
        tuple.app_name = ar[0]
        tuple.space = ar[1]
        tuple.object = ar[2]
        tuple.description = ar[3]
        return tuple
      end

    end

  end # Tuple
end # Distribunaut


text:
<?php

namespace PHPExiftool\Driver\Tag\FLIR;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class GPSMapDatum extends AbstractTag
{

    protected $Id = 88;

    protected $Name = 'GPSMapDatum';

    protected $FullName = 'FLIR::GPSInfo';

    protected $GroupName = 'FLIR';

    protected $g0 = 'APP1';

    protected $g1 = 'FLIR';

    protected $g2 = 'Image';

    protected $Type = 'string';

    protected $Writable = false;

    protected $Description = 'GPS Map Datum';

    protected $MaxLength = 16;

}


text:
package com.puzzletimer.gui;

import static com.puzzletimer.Internationalization._;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.text.DateFormat;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.KeyStroke;

import net.miginfocom.swing.MigLayout;

import com.puzzletimer.models.Solution;
import com.puzzletimer.models.Timing;
import com.puzzletimer.util.SolutionUtils;

@SuppressWarnings("serial")
public class SolutionEditingDialog extends JDialog {
    public static class SolutionEditingDialogListener {
        public void solutionEdited(Solution solution) {
        }
    }

    private JTextField textFieldStart;
    private JTextField textFieldTime;
    private JComboBox comboBoxPenalty;
    private JTextField textFieldScramble;
    private JButton buttonOk;
    private JButton buttonCancel;

    public SolutionEditingDialog(
            JFrame owner,
            boolean modal,
            final Solution solution,
            final SolutionEditingDialogListener listener) {
        super(owner, modal);

        setTitle(_("solution_editing.solution_editor"));
        setMinimumSize(new Dimension(480, 200));
        setPreferredSize(getMinimumSize());

        createComponents();

        // start
        DateFormat dateFormat =
            DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
        this.textFieldStart.setText(
            dateFormat.format(solution.getTiming().getStart()));

        // time
        this.textFieldTime.setText(
            SolutionUtils.formatMinutes(solution.getTiming().getElapsedTime()));
        this.addWindowFocusListener(new WindowAdapter() {
            @Override
            public void windowGainedFocus(WindowEvent e) {
                // text selection
                SolutionEditingDialog.this.textFieldTime.setSelectionStart(0);
                SolutionEditingDialog.this.textFieldTime.setSelectionEnd(Integer.MAX_VALUE);

                // focus
                SolutionEditingDialog.this.textFieldTime.requestFocusInWindow();
            }
        });

        // penalty
        this.comboBoxPenalty.addItem("");
        this.comboBoxPenalty.addItem("+2");
        this.comboBoxPenalty.addItem("DNF");
        this.comboBoxPenalty.setSelectedItem(solution.getPenalty());

        // scramble
        this.textFieldScramble.setText(solution.getScramble().getRawSequence());
        this.textFieldScramble.setCaretPosition(0);

        // ok button
        this.buttonOk.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                // timing
                long time =
                    SolutionUtils.parseTime(
                        SolutionEditingDialog.this.textFieldTime.getText());
                Timing timing =
                    new Timing(
                        solution.getTiming().getStart(),
                        new Date(solution.getTiming().getStart().getTime() + time));

                // penalty
                String penalty =
                    (String) SolutionEditingDialog.this.comboBoxPenalty.getSelectedItem();

                listener.solutionEdited(
                    solution
                        .setTiming(timing)
                        .setPenalty(penalty));

                SolutionEditingDialog.this.dispose();
            }
        });
        this.getRootPane().setDefaultButton(this.buttonOk);

        // cancel button
        this.buttonCancel.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                SolutionEditingDialog.this.dispose();
            }
        });

        // esc key closes window
        this.getRootPane().registerKeyboardAction(
            new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent arg0) {
                    SolutionEditingDialog.this.dispose();
                }
            },
            KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
            JComponent.WHEN_IN_FOCUSED_WINDOW);
    }

    private void createComponents() {
        setLayout(
            new MigLayout(
                "fill, wrap",
                "[pref!][fill]",
                "[pref!]8[pref!]8[pref!]8[pref!]16[bottom]"));

        // labelStart
        add(new JLabel(_("solution_editing.start")));

        // textFieldStart
        this.textFieldStart = new JTextField();
        this.textFieldStart.setEditable(false);
        this.textFieldStart.setFocusable(false);
        add(this.textFieldStart);

        // labelTime
        add(new JLabel(_("solution_editing.time")));

        // textFieldTime
        this.textFieldTime = new JTextField();
        add(this.textFieldTime);

        // labelPenalty
        add(new JLabel(_("solution_editing.penalty")));

        // comboBoxPenalty
        this.comboBoxPenalty = new JComboBox();
        add(this.comboBoxPenalty);

        // labelScramble
        add(new JLabel(_("solution_editing.scramble")));

        // textFieldScramble
        this.textFieldScramble = new JTextField();
        this.textFieldScramble.setEditable(false);
        this.textFieldScramble.setFocusable(false);
        add(this.textFieldScramble);

        // buttonOk
        this.buttonOk = new JButton(_("solution_editing.ok"));
        add(this.buttonOk, "tag ok, span 2, split");

        // buttonCancel
        this.buttonCancel = new JButton(_("solution_editing.cancel"));
        add(this.buttonCancel, "tag cancel");
    }
}


text:
// ==========================================================================
//  Squidex Headless CMS
// ==========================================================================
//  Copyright (c) Squidex UG (haftungsbeschränkt)
//  All rights reserved. Licensed under the MIT license.
// ==========================================================================

using FakeItEasy;
using Orleans;
using Squidex.Infrastructure.Orleans;
using Xunit;

namespace Squidex.Infrastructure.EventSourcing.Grains
{
    public class OrleansEventNotifierTests
    {
        private readonly IEventConsumerManagerGrain manager = A.Fake<IEventConsumerManagerGrain>();
        private readonly OrleansEventNotifier sut;

        public OrleansEventNotifierTests()
        {
            var factory = A.Fake<IGrainFactory>();

            A.CallTo(() => factory.GetGrain<IEventConsumerManagerGrain>(SingleGrain.Id, null))
                .Returns(manager);

            sut = new OrleansEventNotifier(factory);
        }

        [Fact]
        public void Should_wakeup_manager_with_stream_name()
        {
            sut.NotifyEventsStored("my-stream");

            A.CallTo(() => manager.ActivateAsync("my-stream"))
                .MustHaveHappened();
        }
    }
}


text:
namespace RDKit {

  //! a hierarchical catalog for holding molecules
  typedef RDCatalog::HierarchCatalog<MolCatalogEntry, MolCatalogParams, int> MolCatalog;
}

#endif


text:
{% extends path1+"/_manage-centre-layout.html" %}

{% block citizen_content %}

			  {{ totalAvailableAppointments }}
			  Avaialble Appointments

			   {{totalAppointments}}
			  Booked appointments

			  {{ staffTotals.available }}
			  Available Staff

			  {{ (totalAppointments / (staffTotals.available * slots.length) * 100) | round }}%
			  Used capacity

August 2018

	                MON
	                TUE
	                WED
	                THU
	                FRI
	                SAT
	                SUN

	                26
	                27
	                28
	                29
	                30
	                31
	                1

	                2
	                3
	                4 Today
	                5
	                6
	                7
	                8

	                9
	                10
	                11
	                12
	                13
	                14
	                15

	                16
	                17
	                18
	                19
	                20

	                21
	                22

	                23
	                24
	                25
	                26
	                27
	                28
	                29

	                30
	                1
	                2
	                3
	                4
	                5
	                6

Available appointments

		            {% for slot in slots %}
		            <li class="time-slot__list
				            {% if staffTotals.available - slot.usedSlots < 0 %}
				            	time-slot__list--overbooked
				            {% elseif staffTotals.available - slot.usedSlots == 0 %}
				                time-slot__list--full
				            {% else %}
				                time-slot__list--available
				            {% endif %}
				            ">

{{ slot.time }}

					            {% if staffTotals.available - slot.usedSlots < 0 %}
					            Overbooked by {{ 0 - (staffTotals.available - slot.usedSlots) }}
					            {% elseif staffTotals.available - slot.usedSlots == 0 %}
					            full
					            {% else %}
					            {{ staffTotals.available - slot.usedSlots }} slots
					            {% endif %}

		                		{{slot.complex}} Complex Neuro

		                		{{slot.groundFloor}} Ground floor

		            {% endfor %}

Available staff

						Name
						Skill
						Available times
						Assigned to

					{% for person in staff %}
						{% if person.days[query.day].available %}

							{{person.name}}
							{{person.skill}}
							{{person.days[query.day].start}} - {{person.days[query.day].end}}

			                    {% if person.days[query.day].scrutiny and person.scrutinyPaperwork %}
			                        Scrutiny filework
			                    {% else %}
			                        Appointments
			                    {% endif %}

						{% endif %}
					{% endfor %}

{% endblock %}
{% block footer_top %}
{{ super() }}
{# {% include path1+"/footer_links.html" %} #}
{% endblock %}


text:
package com.osc.tweet.app.fragments;

import java.io.IOException;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.os.AsyncTaskCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.ViewGroup;

import com.astuetz.PagerSlidingTabStrip;
import com.chopping.application.BasicPrefs;
import com.chopping.fragments.BaseFragment;
import com.google.gson.JsonSyntaxException;
import com.osc.tweet.R;
import com.osc.tweet.app.App;
import com.osc.tweet.app.adapters.NoticesListViewPagerAdapter;
import com.osc.tweet.events.ClearAtMeNoticesEvent;
import com.osc.tweet.events.ClearCommentsEvent;
import com.osc.tweet.events.ClearNoticeEvent;
import com.osc.tweet.events.GetMyInformationEvent;
import com.osc.tweet.events.OperatingEvent;
import com.osc.tweet.events.RefreshMyInfoEvent;
import com.osc.tweet.utils.Prefs;
import com.osc4j.OscApi;
import com.osc4j.ds.common.NoticeType;
import com.osc4j.ds.common.StatusResult;
import com.osc4j.ds.personal.MyInformation;
import com.osc4j.exceptions.OscTweetException;

import de.greenrobot.event.EventBus;
import fr.castorflex.android.smoothprogressbar.SmoothProgressBar;
import fr.castorflex.android.smoothprogressbar.SmoothProgressBarUtils;
import fr.castorflex.android.smoothprogressbar.SmoothProgressDrawable;

import static com.osc4j.ds.common.NoticeType.AtMe;
import static com.osc4j.ds.common.NoticeType.Comments;

/**
 * A container shows all my new notices.
 *
 * @author Xinyue Zhao
 */
public final class NoticesListPagesFragment extends BaseFragment {
	/**
	 * Main layout for this component.
	 */
	private static final int LAYOUT = R.layout.fragment_notices_list_pages;
	/**
	 * Tabs.
	 */
	private PagerSlidingTabStrip mTabs;

	/**
	 * The pagers
	 */
	private ViewPager mViewPager;

	/**
	 * My personal information .
	 */
	private MyInformation myInfo;

	/**
	 * Main {@link MenuItem}.
	 */
	private MenuItem mClearMi;
	/**
	 * The {@link MenuItem} to clear all new notices of new "@Me".
	 */
	private MenuItem mClearAtMi;
	/**
	 * The {@link MenuItem} to clear all new notices of new comments.
	 */
	private MenuItem mClearCommentsMi;
	/**
	 * The {@link MenuItem} to get my newest personal information.
	 */
	private MenuItem mRefreshMi;
	/**
	 * Progress indicator.
	 */
	private SmoothProgressBar mPbV;

	/**
	 * Network action in progress if {@code true}.
	 */
	private boolean mInProgress;
	//------------------------------------------------
	//Subscribes, event-handlers
	//------------------------------------------------

	/**
	 * Handler for {@link com.osc.tweet.events.GetMyInformationEvent}.
	 *
	 * @param e
	 * 		Event {@link com.osc.tweet.events.GetMyInformationEvent}.
	 */
	public void onEvent(GetMyInformationEvent e) {
		myInfo = e.getMyInformation();
		showMyNotices();
	}

	/**
	 * Handler for {@link com.osc.tweet.events.ClearAtMeNoticesEvent}.
	 *
	 * @param e
	 * 		Event {@link com.osc.tweet.events.ClearAtMeNoticesEvent}.
	 */
	public void onEvent(ClearAtMeNoticesEvent e) {
		clearAtMe();
	}

	/**
	 * Handler for {@link com.osc.tweet.events.ClearCommentsEvent}.
	 *
	 * @param e
	 * 		Event {@link com.osc.tweet.events.ClearCommentsEvent}.
	 */
	public void onEvent(ClearCommentsEvent e) {
		clearNewComments();
	}

	//------------------------------------------------

	/**
	 * Initialize an {@link  NoticesListPagesFragment}.
	 *
	 * @param context
	 * 		A {@link android.content.Context} object.
	 *
	 * @return An instance of {@link NoticesListPagesFragment}.
	 */
	public static NoticesListPagesFragment newInstance(Context context) {
		return (NoticesListPagesFragment) Fragment.instantiate(context, NoticesListPagesFragment.class.getName());
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return inflater.inflate(LAYOUT, container, false);
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putSerializable("myinfo", myInfo);
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		mViewPager = (ViewPager) view.findViewById(R.id.my_notices_vp);
		// Bind the tabs to the ViewPager
		mTabs = (PagerSlidingTabStrip) view.findViewById(R.id.my_notices_tabs);
		mTabs.setIndicatorColorResource(R.color.common_white);

		if (savedInstanceState != null) {
			myInfo = (MyInformation) savedInstanceState.getSerializable("myinfo");
		}
		mPbV = (SmoothProgressBar) view.findViewById(R.id.clear_pb);
		mPbV.setSmoothProgressDrawableBackgroundDrawable(SmoothProgressBarUtils.generateDrawableWithColors(
				getResources().getIntArray(R.array.pocket_background_colors),
				((SmoothProgressDrawable) mPbV.getIndeterminateDrawable()).getStrokeWidth()));
		mPbV.progressiveStart();

		Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
		toolbar.inflateMenu(R.menu.menu_notices);
		Menu menu = toolbar.getMenu();
		mClearMi = menu.findItem(R.id.action_clear_notices);
		mClearAtMi = menu.findItem(R.id.action_clear_at_me);
		mClearAtMi.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				mPbV.setVisibility(View.VISIBLE);
				mClearMi.setEnabled(false);
				clearAtMe();
				return true;
			}
		});
		mClearCommentsMi = menu.findItem(R.id.action_clear_comments);
		mClearCommentsMi.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				mPbV.setVisibility(View.VISIBLE);
				mClearMi.setEnabled(false);
				clearNewComments();
				return true;
			}
		});
		mRefreshMi = menu.findItem(R.id.action_refresh);
		mRefreshMi.setOnMenuItemClickListener(new OnMenuItemClickListener() {
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				mPbV.setVisibility(View.VISIBLE);
				mRefreshMi.setEnabled(false);
				EventBus.getDefault().post(new RefreshMyInfoEvent());
				return true;
			}
		});
		showMyNotices();

	}

	/**
	 * Show all my current new notices.
	 */
	private void showMyNotices() {
		mPbV.setVisibility(View.GONE);
		mPbV.progressiveStop();

		if (myInfo != null && myInfo.getPeople() != null) {
			mViewPager.setAdapter(new NoticesListViewPagerAdapter(App.Instance, getChildFragmentManager(), myInfo));
			mTabs.setViewPager(mViewPager);

			//Menu shows dynamically according to the count of list-items.
			int atMeCount = myInfo.getNotices() == null ? 0 : myInfo.getNotices().size();
			int cmmCount = myInfo.getComments() == null ? 0 : myInfo.getComments().size();

			mClearMi.setVisible(atMeCount != 0 || cmmCount != 0);
			mClearAtMi.setVisible(atMeCount > 0);
			mClearCommentsMi.setVisible(cmmCount > 0);

			if (atMeCount < cmmCount) {
				mViewPager.setCurrentItem(1);
			}
		} else {
			mViewPager.setAdapter(new NoticesListViewPagerAdapter(App.Instance, getChildFragmentManager(), null));
			mTabs.setViewPager(mViewPager);

			//Menu shows dynamically according to the count of list-items.
			mClearMi.setVisible(false);
			mClearAtMi.setVisible(false);
			mClearCommentsMi.setVisible(false);
		}

		mRefreshMi.setEnabled(true);

	}

	/**
	 * Clear all new "@me".
	 */
	private void clearAtMe() {
		clear(AtMe);
	}

	/**
	 * Clear all new comments.
	 */
	private void clearNewComments() {
		clear(Comments);
	}

	/**
	 * Clear different notices.
	 *
	 * @param type
	 * 		{@link NoticeType} The type of notice.
	 */
	private void clear(NoticeType type) {
		if (!mInProgress) {
			AsyncTaskCompat.executeParallel(new AsyncTask<NoticeType, Void, StatusResult>() {
				NoticeType mNoticeType;

				@Override
				protected void onPreExecute() {
					super.onPreExecute();
					mInProgress = true;
					mPbV.setVisibility(View.VISIBLE);
				}

				@Override
				protected StatusResult doInBackground(NoticeType... params) {
					mNoticeType = params[0];
					try {
						return OscApi.clearNotice(App.Instance, mNoticeType);
					}  catch (IOException  | OscTweetException | JsonSyntaxException e) {
						return null;
					}
				}

				@Override
				protected void onPostExecute(StatusResult res) {
					super.onPostExecute(res);
					try {
						OperatingEvent event = new OperatingEvent(
								res != null && res.getStatus() == com.osc4j.ds.common.Status.STATUS_OK && res.getResult() != null && Integer.valueOf(res.getResult().getCode()) ==
										com.osc4j.ds.common.Status.STATUS_OK);
						EventBus.getDefault().post(event);
						if (event.isSuccess()) {
							EventBus.getDefault().post(new ClearNoticeEvent(mNoticeType));
							switch (mNoticeType) {
							case AtMe:
								mClearAtMi.setVisible(false);
								break;
							case Comments:
								mClearCommentsMi.setVisible(false);
								break;
							}
							if (!mClearAtMi.isVisible() && !mClearCommentsMi.isVisible()) {
								mClearMi.setVisible(false);
							}
						}
					} catch (IllegalStateException e) {
						//Activity has been destroyed
					}
					mPbV.setVisibility(View.GONE);
					mPbV.progressiveStop();
					mClearMi.setEnabled(true);
					mInProgress = false;
				}
			}, type);
		}
	}

	@Override
	protected BasicPrefs getPrefs() {
		return Prefs.getInstance();
	}
}


text:
package com.vividsolutions.jts.operation.distance;

import java.util.*;
import com.vividsolutions.jts.geom.*;
import com.vividsolutions.jts.geom.util.*;
import com.vividsolutions.jts.algorithm.*;

/**
 * Find two points on two {@link Geometry}s which lie
 * within a given distance, or else are the nearest points
 * on the geometries (in which case this also
 * provides the distance between the geometries).
 *

 * The distance computation also finds a pair of points in the input geometries
 * which have the minimum distance between them.
 * If a point lies in the interior of a line segment,
 * the coordinate computed is a close
 * approximation to the exact point.
 *

 * The algorithms used are straightforward O(n^2)
 * comparisons.  This worst-case performance could be improved on
 * by using Voronoi techniques or spatial indexes.
 *
 * @version 1.7
 */
public class DistanceOp
{
  /**
   * Compute the distance between the nearest points of two geometries.
   * @param g0 a {@link Geometry}
   * @param g1 another {@link Geometry}
   * @return the distance between the geometries
   */
  public static double distance(Geometry g0, Geometry g1)
  {
    DistanceOp distOp = new DistanceOp(g0, g1);
    return distOp.distance();
  }

  /**
   * Test whether two geometries lie within a given distance of each other.
   * @param g0 a {@link Geometry}
   * @param g1 another {@link Geometry}
   * @param distance the distance to test
   * @return true if g0.distance(g1) <= distance
   */
  public static boolean isWithinDistance(Geometry g0, Geometry g1, double distance)
  {
    DistanceOp distOp = new DistanceOp(g0, g1, distance);
    return distOp.distance() <= distance;
  }

  /**
   * Compute the the nearest points of two geometries.
   * The points are presented in the same order as the input Geometries.
   *
   * @param g0 a {@link Geometry}
   * @param g1 another {@link Geometry}
   * @return the nearest points in the geometries
   */
  public static Coordinate[] nearestPoints(Geometry g0, Geometry g1)
  {
    DistanceOp distOp = new DistanceOp(g0, g1);
    return distOp.nearestPoints();
  }

  /**
   * Compute the the closest points of two geometries.
   * The points are presented in the same order as the input Geometries.
   *
   * @param g0 a {@link Geometry}
   * @param g1 another {@link Geometry}
   * @return the closest points in the geometries
   * @deprecated renamed to nearestPoints
   */
  public static Coordinate[] closestPoints(Geometry g0, Geometry g1)
  {
    DistanceOp distOp = new DistanceOp(g0, g1);
    return distOp.nearestPoints();
  }

  // input
  private Geometry[] geom;
  private double terminateDistance = 0.0;
  // working
  private PointLocator ptLocator = new PointLocator();
  private GeometryLocation[] minDistanceLocation;
  private double minDistance = Double.MAX_VALUE;

  /**
   * Constructs a DistanceOp that computes the distance and nearest points between
   * the two specified geometries.
   * @param g0 a Geometry
   * @param g1 a Geometry
   */
  public DistanceOp(Geometry g0, Geometry g1)
  {
    this(g0, g1, 0.0);
  }

  /**
   * Constructs a DistanceOp that computes the distance and nearest points between
   * the two specified geometries.
   * @param g0 a Geometry
   * @param g1 a Geometry
   * @param terminateDistance the distance on which to terminate the search
   */
  public DistanceOp(Geometry g0, Geometry g1, double terminateDistance)
  {
    this.geom = new Geometry[2];
    geom[0] = g0;
    geom[1] = g1;
    this.terminateDistance = terminateDistance;
  }

  /**
   * Report the distance between the nearest points on the input geometries.
   *
   * @return the distance between the geometries
   * or 0 if either input geometry is empty
   * @throws IllegalArgumentException if either input geometry is null
   */
  public double distance()
  {
  	if (geom[0] == null || geom[1] == null)
  		throw new IllegalArgumentException("null geometries are not supported");
  	if (geom[0].isEmpty() || geom[1].isEmpty())
  		return 0.0;

    computeMinDistance();
    return minDistance;
  }

  /**
   * Report the coordinates of the nearest points in the input geometries.
   * The points are presented in the same order as the input Geometries.
   *
   * @return a pair of {@link Coordinate}s of the nearest points
   */
  public Coordinate[] nearestPoints()
  {
    computeMinDistance();
    Coordinate[] nearestPts
        = new Coordinate[] {
          minDistanceLocation[0].getCoordinate(),
          minDistanceLocation[1].getCoordinate() };
    return nearestPts;
  }

  /**
   *
   * @return a pair of {@link Coordinate}s of the nearest points
   * @deprecated renamed to nearestPoints
   */
  public Coordinate[] closestPoints()
  {
    return nearestPoints();
  }

  /**
   * Report the locations of the nearest points in the input geometries.
   * The locations are presented in the same order as the input Geometries.
   *
   * @return a pair of {@link GeometryLocation}s for the nearest points
   */
  public GeometryLocation[] nearestLocations()
  {
    computeMinDistance();
    return minDistanceLocation;
  }

  /**
   *
   * @return a pair of {@link GeometryLocation}s for the nearest points
   * @deprecated renamed to nearestLocations
   */
  public GeometryLocation[] closestLocations()
  {
    return nearestLocations();
  }

  private void updateMinDistance(GeometryLocation[] locGeom, boolean flip)
  {
    // if not set then don't update
    if (locGeom[0] == null) return;

    if (flip) {
      minDistanceLocation[0] = locGeom[1];
      minDistanceLocation[1] = locGeom[0];
    }
    else {
      minDistanceLocation[0] = locGeom[0];
      minDistanceLocation[1] = locGeom[1];
    }
  }

  private void computeMinDistance()
  {
    // only compute once!
    if (minDistanceLocation != null) return;

    minDistanceLocation = new GeometryLocation[2];
    computeContainmentDistance();
    if (minDistance <= terminateDistance) return;
    computeFacetDistance();
  }

  private void computeContainmentDistance()
  {
    GeometryLocation[] locPtPoly = new GeometryLocation[2];
    // test if either geometry has a vertex inside the other
    computeContainmentDistance(0, locPtPoly);
    if (minDistance <= terminateDistance) return;
    computeContainmentDistance(1, locPtPoly);
  }

  private void computeContainmentDistance(int polyGeomIndex, GeometryLocation[] locPtPoly)
  {
  	int locationsIndex = 1 - polyGeomIndex;
    List polys = PolygonExtracter.getPolygons(geom[polyGeomIndex]);
    if (polys.size() > 0) {
      List insideLocs = ConnectedElementLocationFilter.getLocations(geom[locationsIndex]);
      computeContainmentDistance(insideLocs, polys, locPtPoly);
      if (minDistance <= terminateDistance) {
      	// this assigment is determined by the order of the args in the computeInside call above
        minDistanceLocation[locationsIndex] = locPtPoly[0];
        minDistanceLocation[polyGeomIndex] 	= locPtPoly[1];
        return;
      }
    }
  }

  private void computeContainmentDistance(List locs, List polys, GeometryLocation[] locPtPoly)
  {
    for (int i = 0; i < locs.size(); i++) {
      GeometryLocation loc = (GeometryLocation) locs.get(i);
      for (int j = 0; j < polys.size(); j++) {
      	computeContainmentDistance(loc, (Polygon) polys.get(j), locPtPoly);
        if (minDistance <= terminateDistance) return;
      }
    }
  }

  private void computeContainmentDistance(GeometryLocation ptLoc,
      Polygon poly,
      GeometryLocation[] locPtPoly)
  {
    Coordinate pt = ptLoc.getCoordinate();
    // if pt is not in exterior, distance to geom is 0
    if (Location.EXTERIOR != ptLocator.locate(pt, poly)) {
      minDistance = 0.0;
      locPtPoly[0] = ptLoc;
      locPtPoly[1] = new GeometryLocation(poly, pt);;
      return;
    }
  }

  /**
   * Computes distance between facets (lines and points)
   * of input geometries.
   *
   */
  private void computeFacetDistance()
  {
    GeometryLocation[] locGeom = new GeometryLocation[2];

    /**
     * Geometries are not wholely inside, so compute distance from lines and points
     * of one to lines and points of the other
     */
    List lines0 = LinearComponentExtracter.getLines(geom[0]);
    List lines1 = LinearComponentExtracter.getLines(geom[1]);

    List pts0 = PointExtracter.getPoints(geom[0]);
    List pts1 = PointExtracter.getPoints(geom[1]);

    // exit whenever minDistance goes LE than terminateDistance
    computeMinDistanceLines(lines0, lines1, locGeom);
    updateMinDistance(locGeom, false);
    if (minDistance <= terminateDistance) return;

    locGeom[0] = null;
    locGeom[1] = null;
    computeMinDistanceLinesPoints(lines0, pts1, locGeom);
    updateMinDistance(locGeom, false);
    if (minDistance <= terminateDistance) return;

    locGeom[0] = null;
    locGeom[1] = null;
    computeMinDistanceLinesPoints(lines1, pts0, locGeom);
    updateMinDistance(locGeom, true);
    if (minDistance <= terminateDistance) return;

    locGeom[0] = null;
    locGeom[1] = null;
    computeMinDistancePoints(pts0, pts1, locGeom);
    updateMinDistance(locGeom, false);
  }

  private void computeMinDistanceLines(List lines0, List lines1, GeometryLocation[] locGeom)
  {
    for (int i = 0; i < lines0.size(); i++) {
      LineString line0 = (LineString) lines0.get(i);
      for (int j = 0; j < lines1.size(); j++) {
        LineString line1 = (LineString) lines1.get(j);
        computeMinDistance(line0, line1, locGeom);
        if (minDistance <= terminateDistance) return;
      }
    }
  }

  private void computeMinDistancePoints(List points0, List points1, GeometryLocation[] locGeom)
  {
    for (int i = 0; i < points0.size(); i++) {
      Point pt0 = (Point) points0.get(i);
      for (int j = 0; j < points1.size(); j++) {
        Point pt1 = (Point) points1.get(j);
        double dist = pt0.getCoordinate().distance(pt1.getCoordinate());
        if (dist < minDistance) {
          minDistance = dist;
          locGeom[0] = new GeometryLocation(pt0, 0, pt0.getCoordinate());
          locGeom[1] = new GeometryLocation(pt1, 0, pt1.getCoordinate());
        }
        if (minDistance <= terminateDistance) return;
      }
    }
  }

  private void computeMinDistanceLinesPoints(List lines, List points,
      GeometryLocation[] locGeom)
  {
    for (int i = 0; i < lines.size(); i++) {
      LineString line = (LineString) lines.get(i);
      for (int j = 0; j < points.size(); j++) {
        Point pt = (Point) points.get(j);
        computeMinDistance(line, pt, locGeom);
        if (minDistance <= terminateDistance) return;
      }
    }
  }

  private void computeMinDistance(LineString line0, LineString line1,
                                  GeometryLocation[] locGeom)
  {
    if (line0.getEnvelopeInternal().distance(line1.getEnvelopeInternal())
        > minDistance)
          return;
    Coordinate[] coord0 = line0.getCoordinates();
    Coordinate[] coord1 = line1.getCoordinates();
      // brute force approach!
    for (int i = 0; i < coord0.length - 1; i++) {
      for (int j = 0; j < coord1.length - 1; j++) {
        double dist = CGAlgorithms.distanceLineLine(
                                        coord0[i], coord0[i + 1],
                                        coord1[j], coord1[j + 1] );
        if (dist < minDistance) {
          minDistance = dist;
          LineSegment seg0 = new LineSegment(coord0[i], coord0[i + 1]);
          LineSegment seg1 = new LineSegment(coord1[j], coord1[j + 1]);
          Coordinate[] closestPt = seg0.closestPoints(seg1);
          locGeom[0] = new GeometryLocation(line0, i, closestPt[0]);
          locGeom[1] = new GeometryLocation(line1, j, closestPt[1]);
        }
        if (minDistance <= terminateDistance) return;
      }
    }
  }

  private void computeMinDistance(LineString line, Point pt,
                                  GeometryLocation[] locGeom)
  {
    if (line.getEnvelopeInternal().distance(pt.getEnvelopeInternal())
        > minDistance)
          return;
    Coordinate[] coord0 = line.getCoordinates();
    Coordinate coord = pt.getCoordinate();
      // brute force approach!
    for (int i = 0; i < coord0.length - 1; i++) {
        double dist = CGAlgorithms.distancePointLine(
            coord, coord0[i], coord0[i + 1] );
        if (dist < minDistance) {
          minDistance = dist;
          LineSegment seg = new LineSegment(coord0[i], coord0[i + 1]);
          Coordinate segClosestPoint = seg.closestPoint(coord);
          locGeom[0] = new GeometryLocation(line, i, segClosestPoint);
          locGeom[1] = new GeometryLocation(pt, 0, coord);
        }
        if (minDistance <= terminateDistance) return;

    }
  }

}


text:
<button type="button" class="navbar-toggle menu-toggler pull-left" id="menu-toggler">
    Toggle sidebar

</button>

            Spider Admin

									Welcome,
									{{ session.user }}

                Settings

                Profile

                Logout


text:
namespace am {
namespace game {

	class Component : public am::base::IManaged {
	public:

		Component();
		~Component();

		virtual const char *getCompName() const = 0;
		virtual void update(float dt) {}

	};

}
}


text:
package schema;

public class AIRLOCK000023
    extends Schematic
{

    public AIRLOCK000023(){
        super("AIRLOCK000023","EVA","ARL_BCA1_CH1","event","64","enum","0=No History - a charge has not been initiated yet|1=Presently charging|2=Task completed normally|3=Task terminated due to stop switch being toggled|4=Task terminated due to an open circuit error|5=Task terminated due to Wrong Batt or Hi-imp|6=Task terminated due to an over-temperature error|7=Amp-hour capacity test result OK|8=Amp-hour capacity test error|9=Task terminated due to low charge slope error|10=Task terminated due to power error|11=Task terminated due to reverse-polarity error|12=Task terminated due to a short-circuit error|13=Task terminated due to a time-out error|14=Task terminated due to an external-temperature error|15=Discharge|16=Wait on Discharge|17=Wait on Charge","Battery Charger Assembly (BCA) 1 Channel 1 Status","Battery Charger Assembly (BCA) 1 Channel 1 Status");
    }

    public Object parse(String string){
        try {
            int iv = Integer.parseInt(string);
            switch(iv){
            case 0:
                return "No History - a charge has not been initiated yet";
            case 1:
                return "Presently charging";
            case 2:
                return "Task completed normally";
            case 3:
                return "Task terminated due to stop switch being toggled";
            case 4:
                return "Task terminated due to an open circuit error";
            case 5:
                return "Task terminated due to Wrong Batt or Hi-imp";
            case 6:
                return "Task terminated due to an over-temperature error";
            case 7:
                return "Amp-hour capacity test result OK";
            case 8:
                return "Amp-hour capacity test error";
            case 9:
                return "Task terminated due to low charge slope error";
            case 10:
                return "Task terminated due to power error";
            case 11:
                return "Task terminated due to reverse-polarity error";
            case 12:
                return "Task terminated due to a short-circuit error";
            case 13:
                return "Task terminated due to a time-out error";
            case 14:
                return "Task terminated due to an external-temperature error";
            case 15:
                return "Discharge";
            case 16:
                return "Wait on Discharge";
            case 17:
                return "Wait on Charge";
            default:
                return string;
            }
        }
        catch (NumberFormatException exc){
            return string;
        }
    }

}


text:
%% Copyright (C) 2000 Paul Kienzle
%% Copyright (C) 2008 Alois Schloegl
%% $Id: strtok.m,v 1.2 2008-01-19 20:31:52 schloegl Exp $
%% This function is part of BioSig http://biosig.sf.net
%% Originally, it was part of Octave. It was modified for the use with FreeMat
%%
%%
%% This program is free software; you can redistribute it and/or modify
%% it under the terms of the GNU General Public License as published by
%% the Free Software Foundation; either version 2 of the License, or
%% (at your option) any later version.
%%

%% usage: [tok, rem] = strtok(str, delim)
%%
%% Find all characters up to but not including the first character which
%% is in the string delim.  If rem is requested, it contains the
%% remainder of the string, starting at the first deliminator. Leading
%% delimiters are ignored.  If delim is not specified, space is assumed.

%% TODO: check what to do for a null delimiter
function [tok, rem] = strtok(str, delim)

  if nargin<1 || nargin > 2
    usage('[tok, rem] = strtok(str, delim)');
  end
  if nargin < 2 || isempty(delim), delim = " "; end

  if isempty(str)
    tok = '';rem = '';
  elseif length(delim) > 3
    start = 1;
    len = length(str);
    while start<=len
      if all(str(start) ~= delim), break; end
      start=start+1;
    end
    stop = start;
    while stop<=len
      if any(str(stop) == delim), break; end
      stop=stop+1;
    end
    tok = str(start:stop-1);
    rem = str(stop:len);
  else
    if length(delim)==1
      idx = find(str == delim);
    elseif length(delim)==2
      idx = find(str == delim(1) | str==delim(2));
    else
      idx = find(str == delim(1) | str==delim(2) | str==delim(3));
    end
    if isempty(idx)
      tok = str;
      rem = "";
    else
      skip = find(idx(:)' ~= 1:length(idx)); %% find first non-leading delimiter
      if isempty(skip)
      	tok = str(idx(length(idx))+1:length(str));
      	rem = '';
      else
      	tok = str(skip(1):idx(skip(1))-1);
      	rem = str(idx(skip(1)):length(str));
      end
    end
  end

end

%!demo
%! strtok("this is the life")
%! % split at the first space, returning "this"

%!demo
%! s = "14*27+31"
%! while 1
%!   [t,s] = strtok(s, "+-*/");
%!   printf("<%s>", t);
%!   if isempty(s), break; end
%!   printf("<%s>", s(1));
%! end
%! printf("\n");
%! % ----------------------------------------------------
%! % Demonstrates processing of an entire string split on
%! % a variety of delimiters. Tokens and delimiters are
%! % printed one after another in angle brackets.  The
%! % string is:

%!# test the tokens for all cases
%!assert(strtok(""), "");             # no string
%!assert(strtok("this"), "this");     # no delimiter in string
%!assert(strtok("this "), "this");    # delimiter at end
%!assert(strtok("this is"), "this");  # delimiter in middle
%!assert(strtok(" this"), "this");    # delimiter at start
%!assert(strtok(" this "), "this");   # delimiter at start and end
%!assert(strtok(" "), ""(1:0));            # delimiter only

%!# test the remainder for all cases
%!test [t,r] = strtok(""); assert(r, "");
%!test [t,r] = strtok("this"); assert(r, "");
%!test [t,r] = strtok("this "); assert(r, " ");
%!test [t,r] = strtok("this is"); assert(r, " is");
%!test [t,r] = strtok(" this"); assert(r, "");
%!test [t,r] = strtok(" this "); assert(r, " ");
%!test [t,r] = strtok(" "); assert(r, "");

%!# simple check with 2 and 3 delimeters
%!assert(strtok("this is", "i "), "th");
%!assert(strtok("this is", "ij "), "th");

%!# test all cases for 4 delimiters since a different
%!# algorithm is used when more than 3 delimiters
%!assert(strtok("","jkl "), "");
%!assert(strtok("this","jkl "), "this");
%!assert(strtok("this ","jkl "), "this");
%!assert(strtok("this is","jkl "), "this");
%!assert(strtok(" this","jkl "), "this");
%!assert(strtok(" this ","jkl "), "this");
%!assert(strtok(" ","jkl "), ""(1:0));

%!# test 'bad' string orientations
%!assert(strtok(" this "'), "this"');   # delimiter at start and end
%!assert(strtok(" this "',"jkl "), "this"');


text:
{
 "title": "Opensource Projects - Part 1: jitt.li",
 "metaTitle": "Opensource Projects - Part 1: jitt.li",
 "description": "",
 "date" : "2014-09-24",
 "slug" : "opensource-projects-part1-jittli",
 "author" : "Simon",
 "categories": "News"
}

::METAEND::

I'll make it short: Open source is great.

This is why I decided to publish the sourcecode of some projects I did in the past on github. Additonally there will be a blogpost like this one containing some background information regarding the project and the used technology. This way everyone who is interested may learn things, get new ideas or even reuse some of the code.

The first project in this series is: [jitt.li](http://jitt.li) ([Sourcecode at Github](https://github.com/nekudo/jitt.li/))

## What is jitt.li?

jitt.li is a twitterwall. It fetches tweets from the twitter streaming api and displays them in the browser. This happens in realtime using a websocket server.

The first version started as an experiment to test a [PHP based webserver](https://github.com/lemmingzshadow/php-websocket) I was working on. Later I switched to [Ratchet](http://socketo.me/) as websocket server.

## Technical details

### The frontend

The website is based on the [Kohana framework](http://kohanaframework.org/). It uses the default bootstrap theme. The interesting part is the [jitt.js javascript file](https://github.com/nekudo/jitt.li/blob/master/www/js/jitt.js). This file contains all the logic of connecting to the websocket server and updating the twitterwall as soon as new tweets arrive.

### The backend

The main application running on the server is separated into three parts: The websocket application, a tweet-pull script and a tweet-push script. Additionally there is a simple management-script to start/stop/restart the script on the server.

#### Websocket application

As mentioned earlier the Ratchet project is used for the websocket server. In the file ["jittli_server.php"](https://github.com/nekudo/jitt.li/blob/master/cli/jittli_server.php) all the necessary objcts are created and passed to the websocket server which than runs in and endless loop.

The [Twitterwall application](https://github.com/nekudo/jitt.li/blob/master/cli/Jittli/Twitterwall.php) uses Redis to store information like e.g. the currently active walls so this information can be accessed by the pull and push scripts.

#### Tweet pull script ([sourcecode](https://github.com/nekudo/jitt.li/blob/master/cli/pull_tweets.php))

The tweet pull script connects to the twitter steaming api using the [phirehose library](https://github.com/fennb/phirehose). It sets the currently active walls (as requested on the website) as filers so only relevant tweets will be received. These tweets are than simply "queued" into a redis list. Every X seconds updates the filters to be set according to the walls currently requested on the website.

#### Tweet push script ([sourcecode](https://github.com/nekudo/jitt.li/blob/master/cli/push_tweets.php))

The push script ready tweets from the redis queue prepares the data and pushes them into the websocket server using a ZeroMQ socket. The websocket server than triggers a method in the Twitterwall application so the tweets can be send to the browser. Here the are handled by the javascript mention in the frontend part.

## Summary

When putting it all together this project does the following:

*	On the jitt.li website visitors can "open" new twitterwalls (stored in redis).
*	The pull-script uses these walls as filters for the Twitter streaming api. Received tweets are stored into a redis queue.
*	The push-script reads tweets from the queue and pushes them into the websocket server. (ZeroMQ)
*	The websocket server triggers the Twitterwall application which sends the data to the browser (using the websocket connection).
*	The javascript loaded in the browser displays new tweets received from the websocket server.

Got questions? Feel free to [open an issue](https://github.com/nekudo/jitt.li/issues) at the Github repository.


text:
package uk.ac.ebi.quickgo.annotation.service.comm.rest.ontology.transformer.annotation;

import uk.ac.ebi.quickgo.annotation.model.Annotation;
import uk.ac.ebi.quickgo.annotation.service.comm.rest.ontology.model.BasicTaxonomyNode;
import uk.ac.ebi.quickgo.rest.search.request.FilterRequest;
import uk.ac.ebi.quickgo.rest.search.request.converter.ConvertedFilter;
import uk.ac.ebi.quickgo.rest.search.results.transformer.AbstractValueInjector;

/**
 * This class is responsible for supplementing an {@link Annotation} instance, which contains
 * a taxonomy identifier, with a taxonomy name, through the use of a RESTful service.
 *
 * Created 07/04/17
 * @author Edd
 */
public class TaxonomyNameInjector extends AbstractValueInjector<BasicTaxonomyNode, Annotation> {

    static final String TAXON_NAME = "taxonName";
    static final String TAXON_ID = "taxonId";

    @Override
    public String getId() {
        return TAXON_NAME;
    }

    @Override
    public FilterRequest buildFilterRequest(Annotation annotation) {
        return FilterRequest.newBuilder()
                .addProperty(getId())
                .addProperty(TAXON_ID, String.valueOf(annotation.taxonId))
                .build();
    }

    @Override
    public void injectValueFromResponse(ConvertedFilter<BasicTaxonomyNode> convertedRequest, Annotation annotation) {
        annotation.taxonName = convertedRequest.getConvertedValue().getScientificName();
    }
}


text:
<?php
return array (
  'Password changed' => 'Passwort geändert',
  'Your password has been successfully changed!' => 'Dein Passwort wurde erfolgreich geändert!',
);


text:
\documentclass{article}
\usepackage[utf8x]{inputenc}
\usepackage[T1, T2A]{fontenc}
\usepackage[russian]{babel}
\usepackage{amsmath}
\usepackage{amssymb}
\setlength\parindent{0pt}
\usepackage[parfill]{parskip}
\pagenumbering{gobble}

\begin{document}
Требуется отгадать число от $1$ до $n$ $(n>10)$, задавая лишь вопросы, на которые можно отвечать <<да>> или <<нет>>, при этом отвечающий
может один раз солгать. Придумайте алгоритм, гарантированно позволяющий сделать это быстрее, чем за $2\lceil \log_2 n \rceil + 1$ шагов.
\end{document}


text:
//
//  FOObject.h
//  FOMapping
//
//  Created by tradevan on 2015/7/17.
//  Copyright (c) 2015年 tradevan. All rights reserved.
//

#import <FMDB/FMDB.h>

@protocol FOObject

/*!
 Override this method to indicate the corresponding table name.
 */
+(NSString *)tableName;

@end

/*!
 Subclass this class and add properties to map to a table. The table must define its primary key(s).
 The type or class can be determined according to the following rules:

 1. INTEGER: NSInteger

 2. REAL: double

 3. TEXT: NSString *

 4. BLOB: NSData *

 5. DATE: NSDate *

 If you don't set the date formatter of the FMDatabase object, FOObject will assume you store a date in REAL, which means the number of seconds since 1970-01-01 00:00:00 UTC. Otherwise FOObject will use the date formatter to parse a date in TEXT.
 */
@interface FOObject : NSObject<FOObject, NSCopying>

/*!
 Create an instance of FOObject by using an FMResultSet object.
 @code
 FMDatabase *db = [FMDatabase databaseWithPath:dbPath];
 if ([db open]) {
    FMResultSet *rs = [db executeQuery:@"SELECT * from aTable"];
    while ([rs next]) {
        FOObject *anObj = [FOObject objectWithResultSet:rs];
    }
 }
 @endcode
 @param rs
 An array of containing the query result with type FOObjects.
 @return An instance of FOObject.
 */
+(NSArray *)objectsFromResultSet:(FMResultSet *)rs;

+(NSArray *)customObjectsFromResultSet:(FMResultSet *)rs class:(Class)objClass;

/*!
 Create an instance of NSDictionary to store a temporary query result which does not have a corresponding class by using an FMResultSet object. This dictionary will not contain any NSDate object because there is no way to learn whether a column value is for date or not.
 @code
 FMDatabase *db = [FMDatabase databaseWithPath:dbPath];
 if ([db open]) {
    FMResultSet *rs = [db executeQuery:@"SELECT col1 as temp1, col2 as temp2 from aTable"];
    while ([rs next]) {
        NSDictionary *aDic = [FOObject dictionaryWithResultSet:rs];
    }
 }
 @endcode
 @param rs
 An array of containing the query result with type NSDictionary.
 @return An instance of FOObject.
 */
+(NSArray *)dictionariesFromResultSet:(FMResultSet *)rs;

/*!
 Persists a row with the receiver's properties in the corresponding table in a given database connection.
 @see -(BOOL)remove:(FMDatabase *)db;
 @param db
 An FMDatabase connection.
 @return YES upon success; NO upon failure.
 */
-(BOOL)persist:(FMDatabase *)db;

/*!
 Delete the row in the corresponding table in a given database connection.
 @see -(BOOL)save:(FMDatabase *)db;
 @see -(BOOL)update:(FMDatabase *)db;
 @param db
 An FMDatabase connection.
 @return YES upon success; NO upon failure.
 */
-(BOOL)remove:(FMDatabase *)db;

@end


text:
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.silicanote</groupId>
        <artifactId>server</artifactId>
        <version>1.3-SNAPSHOT</version>
    </parent>
    <groupId>org.silicanote</groupId>
    <artifactId>silicanote-engine</artifactId>
    <version>1.3-SNAPSHOT</version>
    <name>silicanote-engine</name>
    <url>http://maven.apache.org</url>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <packaging>jar</packaging>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.silicanote</groupId>
            <artifactId>silicanote-model</artifactId>
            <version>1.3-SNAPSHOT</version>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk</artifactId>
            <version>1.6.5</version>
        </dependency>
        <dependency>
            <groupId>org.jongo</groupId>
            <artifactId>jongo</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>2.12.2</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>17.0</version>
        </dependency>
    </dependencies>
</project>


text:
import ConfigParser
from gettext import gettext as _
import os
import shutil
import subprocess
from TurtleArt.tapalette import (palette_names, help_strings)

def cancel_plugin_install(self, tmp_dir):
    ''' If we cancel, just cleanup '''
    shutil.rmtree(tmp_dir)

def complete_plugin_install(self, tmp_dir, tmp_path, plugin_path,
                            plugin_name, file_info):
    ''' We complete the installation directly or from ConfirmationAlert '''
    status = subprocess.call(['cp', '-r', tmp_path, plugin_path + '/'])
    if status == 0:
        # Save the plugin.info file in the plugin directory
        subprocess.call(['cp', os.path.join(tmp_dir, 'plugin.info'),
                         os.path.join(plugin_path, plugin_name) + '/'])
        if self.has_toolbarbox:
            palette_name_list = []
            if file_info.has_option('Plugin', 'palette'):
                palette_name_list = file_info.get(
                    'Plugin', 'palette').split(',')
                create_palette = []
                for palette_name in palette_name_list:
                    if not palette_name.strip() in palette_names:
                        create_palette.append(True)
                    else:
                        create_palette.append(False)
            self.tw.init_plugin(plugin_name)
            self.tw.turtleart_plugins[-1].setup()
            self.tw.load_media_shapes()
            for i, palette_name in enumerate(palette_name_list):
                if create_palette[i]:
                    j = len(self.palette_buttons)
                    self.palette_buttons.append(
                        self._radio_button_factory(
                            palette_name.strip() + 'off',
                            self._palette_toolbar,
                            self.do_palette_buttons_cb,
                            j - 1,
                            help_strings[palette_name.strip()],
                            self.palette_buttons[0]))
                    self._overflow_buttons.append(
                        self._add_button(
                            palette_name.strip() + 'off',
                            None,
                            self.do_palette_buttons_cb,
                            None,
                            arg=j - 1))
                    self._overflow_box.pack_start(
                        self._overflow_buttons[j - 1])
                    self.tw.palettes.insert(j - 1, [])
                    self.tw.palette_sprs.insert(j - 1, [None, None])
                else:
                    # We need to change the index associated with the
                    # Trash Palette Button.
                    j = len(palette_names)
                    pidx = palette_names.index(palette_name.strip())
                    self.palette_buttons[pidx].connect(
                        'clicked', self.do_palette_buttons_cb, j - 1)
                    self._overflow_buttons[pidx].connect(
                        'clicked', self.do_palette_buttons_cb, j - 1)
                    self._setup_palette_toolbar()
        else:
            self.tw.showlabel('status', label=_('Please restart Turtle Art \
in order to use the plugin.'))
    else:
        self.tw.showlabel('status', label=_('Plugin could not be installed.'))
    status = subprocess.call(['rm', '-r', tmp_path])
    shutil.rmtree(tmp_dir)

def load_a_plugin(self, tmp_dir):
    ''' Load a plugin from the Journal and initialize it '''
    plugin_path = os.path.join(tmp_dir, 'plugin.info')
    file_info = ConfigParser.ConfigParser()
    if len(file_info.read(plugin_path)) == 0:
        self.tw.showlabel('status',
                          label=_('Plugin could not be installed.'))
    elif not file_info.has_option('Plugin', 'name'):
        self.tw.showlabel(
            'status', label=_('Plugin could not be installed.'))
    else:
        plugin_name = file_info.get('Plugin', 'name')
        tmp_path = os.path.join(tmp_dir, plugin_name)
        plugin_path = os.path.join(self.bundle_path, 'plugins')
        if os.path.exists(os.path.join(plugin_path, plugin_name)):
            self._reload_plugin_alert(tmp_dir, tmp_path, plugin_path,
                                      plugin_name, file_info)
        else:
            complete_plugin_install(self, tmp_dir, tmp_path, plugin_path,
                                    plugin_name, file_info)


text:
package de.heikoseeberger.akkahttpcirce

import akka.http.scaladsl.marshalling.{ Marshaller, ToEntityMarshaller }
import akka.http.scaladsl.model.{ ContentType, ContentTypeRange, HttpEntity }
import akka.http.scaladsl.model.MediaType
import akka.http.scaladsl.model.MediaTypes.`application/json`
import akka.http.scaladsl.unmarshalling.{ FromEntityUnmarshaller, Unmarshaller }
import akka.util.ByteString
import cats.data.NonEmptyList
import cats.syntax.show.toShow
import io.circe.{ Decoder, DecodingFailure, Encoder, Json, Printer, jawn }
import scala.collection.immutable.Seq

/**
  * Automatic to and from JSON marshalling/unmarshalling using an in-scope circe protocol.
  * The unmarshaller fails fast, throwing the first `Error` encountered.
  *
  * To use automatic codec derivation, user needs to import `io.circe.generic.auto._`.
  */
object FailFastCirceSupport extends FailFastCirceSupport

/**
  * Automatic to and from JSON marshalling/unmarshalling using an in-scope circe protocol.
  * The unmarshaller fails fast, throwing the first `Error` encountered.
  *
  * To use automatic codec derivation import `io.circe.generic.auto._`.
  */
trait FailFastCirceSupport extends BaseCirceSupport with FailFastUnmarshaller

/**
  * Automatic to and from JSON marshalling/unmarshalling using an in-scope circe protocol.
  * The unmarshaller accumulates all errors in the exception `Errors`.
  *
  * To use automatic codec derivation, user needs to import `io.circe.generic.auto._`.
  */
object ErrorAccumulatingCirceSupport extends ErrorAccumulatingCirceSupport {
  final case class DecodingFailures(failures: NonEmptyList[DecodingFailure]) extends Exception {
    override def getMessage = failures.toList.map(_.show).mkString("\n")
  }
}

/**
  * Automatic to and from JSON marshalling/unmarshalling using an in-scope circe protocol.
  * The unmarshaller accumulates all errors in the exception `Errors`.
  *
  * To use automatic codec derivation import `io.circe.generic.auto._`.
  */
trait ErrorAccumulatingCirceSupport extends BaseCirceSupport with ErrorAccumulatingUnmarshaller

/**
  * Automatic to and from JSON marshalling/unmarshalling using an in-scope circe protocol.
  */
trait BaseCirceSupport {

  def unmarshallerContentTypes: Seq[ContentTypeRange] =
    mediaTypes.map(ContentTypeRange.apply)

  def mediaTypes: Seq[MediaType.WithFixedCharset] =
    List(`application/json`)

  /**
    * `Json` => HTTP entity
    *
    * @return marshaller for JSON value
    */
  implicit final def jsonMarshaller(
      implicit printer: Printer = Printer.noSpaces
  ): ToEntityMarshaller[Json] =
    Marshaller.oneOf(mediaTypes: _*) { mediaType =>
      Marshaller.withFixedContentType(ContentType(mediaType)) { json =>
        HttpEntity(mediaType, printer.pretty(json))
      }
    }

  /**
    * `A` => HTTP entity
    *
    * @tparam A type to encode
    * @return marshaller for any `A` value
    */
  implicit final def marshaller[A: Encoder](
      implicit printer: Printer = Printer.noSpaces
  ): ToEntityMarshaller[A] =
    jsonMarshaller(printer).compose(Encoder[A].apply)

  /**
    * HTTP entity => `Json`
    *
    * @return unmarshaller for `Json`
    */
  implicit final val jsonUnmarshaller: FromEntityUnmarshaller[Json] =
    Unmarshaller.byteStringUnmarshaller
      .forContentTypes(unmarshallerContentTypes: _*)
      .map {
        case ByteString.empty => throw Unmarshaller.NoContentException
        case data             => jawn.parseByteBuffer(data.asByteBuffer).fold(throw _, identity)
      }

  /**
    * HTTP entity => `A`
    *
    * @tparam A type to decode
    * @return unmarshaller for `A`
    */
  implicit def unmarshaller[A: Decoder]: FromEntityUnmarshaller[A]
}

/**
  * Mix-in this trait to fail on the first error during unmarshalling.
  */
trait FailFastUnmarshaller { this: BaseCirceSupport =>

  override implicit final def unmarshaller[A: Decoder]: FromEntityUnmarshaller[A] = {
    def decode(json: Json) = Decoder[A].decodeJson(json).fold(throw _, identity)
    jsonUnmarshaller.map(decode)
  }
}

/**
  * Mix-in this trait to accumulate all errors during unmarshalling.
  */
trait ErrorAccumulatingUnmarshaller { this: BaseCirceSupport =>

  override implicit final def unmarshaller[A: Decoder]: FromEntityUnmarshaller[A] = {
    def decode(json: Json) =
      Decoder[A]
        .accumulating(json.hcursor)
        .fold(failures => throw ErrorAccumulatingCirceSupport.DecodingFailures(failures), identity)
    jsonUnmarshaller.map(decode)
  }
}


text:
declare namespace jsrsasign.KJUR.asn1.csr {
    interface PEMInfo {
        subject: {
            name: string;
            hex: string;
        };
        pubkey: {
            obj: RSAKey | crypto.DSA | crypto.ECDSA;
            hex: string;
        };
    }

    /**
     * Certification Request (CSR/PKCS#10) utilities class
     * @description
     * This class provides utility static methods for CSR/PKCS#10.
     * Here is a list of methods:
     *
     * - `KJUR.asn1.csr.CSRUtil.newCSRPEM`
     * - `KJUR.asn1.csr.CSRUtil.getInfo`
     */
    namespace CSRUtil {
        /**
         * generate a PEM format of CSR/PKCS#10 certificate signing request
         * @param param parameter to generate CSR
         * @description
         * This method can generate a CSR certificate signing
         * request by a simple JSON object which has following parameters:
         *
         * - subject - parameter to be passed to `KJUR.asn1.x509.X500Name`
         * - sbjpubkey - parameter to be passed to `KEYUTIL.getKey`
         * - sigalg - signature algorithm name (ex. SHA256withRSA)
         * - sbjprvkey - parameter to be passed to `KEYUTIL.getKey`
         *
         *
         * @example
         * // 1) by key object
         * pem = KJUR.asn1.csr.CSRUtil.newCSRPEM({
         *   subject: {str: '/C=US/O=Test/CN=example.com'},
         *   sbjpubkey: pubKeyObj,
         *   sigalg: "SHA256withRSA",
         *   sbjprvkey: prvKeyObj
         * });
         *
         * // 2) by private/public key PEM
         * pem = KJUR.asn1.csr.CSRUtil.newCSRPEM({
         *   subject: {str: '/C=US/O=Test/CN=example.com'},
         *   sbjpubkey: pubKeyPEM,
         *   sigalg: "SHA256withRSA",
         *   sbjprvkey: prvKeyPEM
         * });
         *
         * // 3) with generateKeypair
         * kp = KEYUTIL.generateKeypair("RSA", 2048);
         * pem = KJUR.asn1.csr.CSRUtil.newCSRPEM({
         *   subject: {str: '/C=US/O=Test/CN=example.com'},
         *   sbjpubkey: kp.pubKeyObj,
         *   sigalg: "SHA256withRSA",
         *   sbjprvkey: kp.prvKeyObj
         * });
         *
         * // 4) by private/public key PEM with extension
         * pem = KJUR.asn1.csr.CSRUtil.newCSRPEM({
         *   subject: {str: '/C=US/O=Test/CN=example.com'},
         *   ext: [
         *     {subjectAltName: {array: [{dns: 'example.net'}]}
         *   ],
         *   sbjpubkey: pubKeyPEM,
         *   sigalg: "SHA256withRSA",
         *   sbjprvkey: prvKeyPEM
         * });
         */
        function newCSRPEM(param?: {
            subject:
                | StringParam & { certissuer?: string; certsubject?: string }
                | x509.X500NameParam & { certissuer?: string; certsubject?: string }
                | { ldapstr: string } & { certissuer?: string; certsubject?: string };
            ext?: Array<{
                subjectAltName: ArrayParam<{ dns: string }>;
            }>;
            sbjpubkey: RSAKey | crypto.ECDSA | crypto.DSA | jws.JWS.JsonWebKey | { n: string; e: string } | string;
            sigalg: string;
            sbjprvkey: RSAKey | crypto.ECDSA | crypto.DSA | jws.JWS.JsonWebKey | { n: string; e: string } | string;
        }): string;

        /**
         * get field values from CSR/PKCS#10 PEM string
         * @param sPEM PEM string of CSR/PKCS#10
         * @returns JSON object with parsed parameters such as name or public key
         * @description
         * This method parses PEM CSR/PKCS#1 string and retrieves
         * subject name and public key. Following parameters are available in the
         * resulted JSON object.
         *
         * - subject.name - subject name string (ex. /C=US/O=Test)
         * - subject.hex - hexadecimal string of X.500 Name of subject
         * - pubkey.obj - subject public key object such as RSAKey, KJUR.crypto.{ECDSA,DSA}
         * - pubkey.hex - hexadecimal string of subject public key
         *
         *
         * @example
         * o = KJUR.asn1.csr.CSRUtil.getInfo("-----BEGIN CERTIFICATE REQUEST...");
         * console.log(o.subject.name) → "/C=US/O=Test"
         */
        function getInfo(sPEM: string): PEMInfo;
    }
}


text:
@implementation JASlider

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    UIView *view = [touch view];
    CGPoint point = [touch locationInView:view];
    if (point.x > self.w) { point.x = self.w; }

    float progressValue = point.x / self.w;
    [self setValue:progressValue animated:true];
    if (self.moveBlock) {
        self.moveBlock(progressValue);
    }
}

- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self commonWithTouches:touches event:event];
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self commonWithTouches:touches event:event];
}

- (void)commonWithTouches:(NSSet<UITouch *> *)touches event:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    UIView *view = [touch view];
    CGPoint point = [touch locationInView:view];
    if (point.x > self.w) { point.x = self.w; }

    float progressValue = point.x / self.w;
    [self setValue:progressValue animated:true];
    if (self.refreshBlock) {
        self.refreshBlock(progressValue);
    }
}

@end


text:
@interface NSTimer (Category)

+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti repeats:(BOOL)yesOrNo block:(void (^)())block;
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti repeats:(BOOL)yesOrNo block:(void (^)())block;

@end


text:
require "capistrano/immutable_task"
include Capistrano::DSL

namespace :load do
  task :defaults do
    load "capistrano/defaults.rb"
  end
end

require "airbrussh/capistrano"
# We don't need to show the "using Airbrussh" banner announcement since
# Airbrussh is now the built-in formatter. Also enable command output by
# default; hiding the output might be confusing to users new to Capistrano.
Airbrussh.configure do |airbrussh|
  airbrussh.banner = false
  airbrussh.command_output = true
end

stages.each do |stage|
  Rake::Task.define_task(stage) do
    set(:stage, stage.to_sym)

    invoke "load:defaults"
    Rake.application["load:defaults"].extend(Capistrano::ImmutableTask)
    load deploy_config_path
    load stage_config_path.join("#{stage}.rb")
    load "capistrano/#{fetch(:scm)}.rb"
    I18n.locale = fetch(:locale, :en)
    configure_backend
  end
end

require "capistrano/dotfile"


text:
'use strict';

Package.describe({
  name: 'useraccounts:flow-routing',
  summary: 'UserAccounts package providing routes configuration capability via kadira:flow-router.',
  version: '1.12.3',
  git: 'https://github.com/meteor-useraccounts/flow-routing.git'
});

Package.onUse(function(api) {
  api.versionsFrom('METEOR@1.0.3');

  api.use([
    'check',
    'kadira:blaze-layout',
    'kadira:flow-router',
    'underscore',
    'useraccounts:core'
  ], ['client', 'server']);

  api.imply([
    'kadira:blaze-layout@2.0.0',
    'kadira:flow-router@2.1.1',
    'useraccounts:core@1.12.3'
  ], ['client', 'server']);

  api.addFiles([
    'lib/core.js',
  ], ['client', 'server']);

  api.addFiles([
    'lib/client/client.js',
    'lib/client/templates_helpers/at_input.js'
  ], ['client']);
});


text:
{% extends "sentry/partial/client_config/python_base.html" %}

{% load i18n %}

{% block inner %}

{% trans "You'll also need blinker if you do not have it already:" %}

pip install blinker

{% trans "Blinker is required for signals to work within Flask." %}

{% trans "Add the required configuration in your application setup:" %}

from raven.contrib.flask import Sentry

app.config['SENTRY_DSN'] = '{% if dsn %}{{ dsn }}{% else %}SENTRY_DSN{% endif %}'
sentry = Sentry(app)

{% trans "That's it! Raven automatically installs an error handling hook to pipe all uncaught exceptions to Sentry." %}

{% endblock %}


text:
package io.vehiclehistory.api.method;

import io.vehiclehistory.api.exception.VehicleHistoryApiException;

/**
 * Created by dudvar on 2015-03-13.
 */
public interface ResponseListener<T> {
    void onSuccess(T response);
    void onApiError(VehicleHistoryApiException exception);
    void onConnectionError(String message);
}