text:
package com.shyyko.zxing.quick.camera;

import android.hardware.Camera;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.google.zxing.*;
import com.google.zxing.common.HybridBinarizer;
import com.shyyko.zxing.quick.R;

/**
 * Camera preview callback
 */
public class PreviewCallback implements Camera.PreviewCallback {
    private static final String TAG = PreviewCallback.class.getSimpleName();
    /**
     * Xzing multi format reader
     */
    private final MultiFormatReader multiFormatReader = new MultiFormatReader();
    /**
     * Handler to send messages
     *
     * @see CaptureHandler
     */
    private Handler handler;
    /**
     * Camera manager
     */
    private CameraManager cameraManager;

    public PreviewCallback(Handler handler, CameraManager cameraManager) {
        this.handler = handler;
        this.cameraManager = cameraManager;
    }

    @Override
    public void onPreviewFrame(byte[] bytes, Camera camera) {
        Camera.Size previewSize = camera.getParameters().getPreviewSize();
        new DecodeAsyncTask(previewSize.width, previewSize.height).execute(bytes);
    }

    /**
     * Asynchronous task for decoding and finding barcode
     */
    private class DecodeAsyncTask extends AsyncTask<byte[], Void, Result> {
        /**
         * Width of image
         */
        private int width;
        /**
         * Height of image
         */
        private int height;

        /**
         * @param width  Width of image
         * @param height Height of image
         */
        private DecodeAsyncTask(int width, int height) {
            this.width = width;
            this.height = height;
        }

        @Override
        protected void onPostExecute(Result result) {
            if (result != null) {
                Log.i(TAG, "Decode success.");
                if (handler != null) {
                    Message message = Message.obtain(handler, R.id.decoded);
                    Bundle bundle = new Bundle();
                    bundle.putString(CaptureHandler.DECODED_DATA, result.toString());
                    message.setData(bundle);
                    message.sendToTarget();
                }
            } else {
                Log.i(TAG, "Decode fail.");
                if (handler != null) {
                    Message message = Message.obtain(handler, R.id.decode_failed);
                    message.sendToTarget();
                }
            }
        }

        @Override
        protected Result doInBackground(byte[]... datas) {
            if (!cameraManager.hasCamera()) {
                return null;
            }
            Result rawResult = null;
            final PlanarYUVLuminanceSource source =
                    cameraManager.buildLuminanceSource(datas[0], width,
                            height, cameraManager.getBoundingRect());
            if (source != null) {
                BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
                try {
                    rawResult = multiFormatReader.decodeWithState(bitmap);
                } catch (ReaderException re) {
                    // continue
                } finally {
                    multiFormatReader.reset();
                }
            }

            return rawResult;
        }
    }
}


text:
#ifdef __cplusplus
extern "C" {
#endif

#ifndef _MCIMAGE_H
#include <mcimage.h>
#endif

#define CARRE(i,j) ((i%2)+(j%2)==2)
#define INTER(i,j) ((i%2)+(j%2)==1)
#define INTERH(i,j) ((i%2)&&(!(j%2)))
#define INTERV(i,j) ((!(i%2))&&(j%2))
#define SINGL(i,j) ((i%2)+(j%2)==0)
#define DIM2D(i,j) ((i%2)+(j%2))
#define NDG_CARRE 255
#define NDG_INTER 200
#define NDG_SINGL 128
#define GRS2D 3
#define GCS2D 3

#define VAL_NULLE    0
#define VAL_OBJET  255
#define VAL_MARQUE   1

extern void InitPileGrilles2d();
extern void TerminePileGrilles2d();
extern struct xvimage * Khalimskize2d(struct xvimage *o);
extern struct xvimage * KhalimskizeNDG2d(struct xvimage *o);
extern struct xvimage * DeKhalimskize2d(struct xvimage *o);
extern void Khalimskize2d_noalloc(struct xvimage *o, struct xvimage *k);
extern void KhalimskizeNDG2d_noalloc(struct xvimage *o, struct xvimage *k);
extern void DeKhalimskize2d_noalloc(struct xvimage *o, struct xvimage *r);
extern void ndgmin2d(struct xvimage *k);
extern void ndgminbeta2d(struct xvimage *k);
extern void ndgmax2d(struct xvimage *k);
extern void ndgmaxbeta2d(struct xvimage *k);
extern void ndgmoy2d(struct xvimage *k);
extern void ndg2grad2d(struct xvimage *k);
extern void ndg4grad2d(struct xvimage *k);
extern void Connex8Obj2d(struct xvimage *o);
extern void Connex4Obj2d(struct xvimage *o);
extern void Betapoint2d(index_t rs, index_t cs, index_t i, index_t j, index_t *tab, int32_t *n);
extern void Alphapoint2d(index_t rs, index_t cs, index_t i, index_t j, index_t *tab, int32_t *n);
extern void Betacarre2d(index_t rs, index_t cs, index_t i, index_t j, index_t *tab, int32_t *n);
extern void Alphacarre2d(index_t rs, index_t cs, index_t i, index_t j, index_t *tab, int32_t *n);
extern void Thetacarre2d(index_t rs, index_t cs, index_t i, index_t j, index_t *tab, int32_t *n);
extern int32_t CardBetapoint2d(uint8_t *K, index_t rs, index_t cs, index_t i, index_t j);
extern int32_t CardThetaCarre2d(struct xvimage *k, index_t i, index_t j, uint8_t val);
extern int32_t BetaTerminal2d(uint8_t *K, index_t rs, index_t cs, index_t i, index_t j);
extern int32_t ExactementUnBetaTerminal2d(uint8_t *K, index_t rs, index_t cs);
extern void SatureAlphacarre2d(struct xvimage *k);
extern void AjouteAlphacarre2d(struct xvimage *k);
extern void AjouteBetacarre2d(struct xvimage *k);
extern void MaxAlpha2d(struct xvimage *k);
extern void MaxBeta2d(struct xvimage *k);
extern void ColorieKh2d(struct xvimage *k);
extern void EffaceLiensLibres2d(struct xvimage *k);
extern void CopieAlphacarre2d(uint8_t *G,uint8_t *K,index_t rs,index_t cs,index_t i,index_t j);
extern index_t EffaceBetaTerminauxSimples2d(struct xvimage *k);
extern int32_t EnsembleSimple2d(struct xvimage *k);
extern int32_t Ensemble2Contractile2d(struct xvimage *b);
extern void Htkern2d(struct xvimage *b, int32_t n);
extern int32_t AlphaSimple2d(struct xvimage *b, index_t i, index_t j);
extern int32_t BetaSimple2d(struct xvimage *b, index_t i, index_t j);
extern int32_t Alpha2Simple2d(struct xvimage *b, index_t i, index_t j);
extern int32_t Beta2Simple2d(struct xvimage *b, index_t i, index_t j);
extern index_t EulerKh2d(struct xvimage *b);
extern int32_t FaceLibre2d(struct xvimage *b, index_t i, index_t j);
extern int32_t PaireLibre2d(struct xvimage *b, index_t i, index_t j);
extern int32_t Collapse2d(struct xvimage *b, index_t i, index_t j);
#ifdef __cplusplus
}
#endif

redpajama_set_name: RedPajamaGithub


text:
"""VideoCapture.py

by Markus Gritsch <gritsch@iue.tuwien.ac.at>

"""

import vidcap
from PIL import Image, ImageFont, ImageDraw
import time, string

default_textpos = 'bl' # t=top, b=bottom;   l=left, c=center, r=right
textcolor = 0xffffff
shadowcolor = 0x000000

def now():
    """Returns a string containing the current date and time.

    This function is used internally by VideoCapture to generate the timestamp
    with which a snapshot can optionally be marked.

    """
    weekday = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')
    #weekday = ('Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So')
    #weekday = ('-', '-', '-', '-', '-', '-', '-')
    y, m, d, hr, min, sec, wd, jd, dst = time.localtime(time.time())
    return '%s:%s:%s %s %s.%s.%s' % (string.zfill(hr, 2), string.zfill(min, 2), string.zfill(sec, 2), weekday[wd], d, m, y)

class Device:
    """Create instances of this class which will then represent video devices.

    For the lifetime of the instance, the device is blocked, so it can not be
    used by other applications (which is quite normal Windows behavior).
    If you want to access the device from another program, you have to delete
    the instance first (e.g. del cam).

    """
    def __init__(self, devnum=0, showVideoWindow=0):
        """devnum:  VideoCapture enumerates the available video capture devices
                    on your system.  If you have more than one device, specify
                    the desired one here.  The device number starts from 0.

           showVideoWindow: 0 ... do not display a video window (the default)
                            1 ... display a video window

                            Mainly used for debugging, since the video window
                            can not be closed or moved around.

        """
        self.dev = vidcap.new_Dev(devnum, showVideoWindow)
        self.normalfont = ImageFont.load_path('helvetica-10.pil')
        self.boldfont = ImageFont.load_path('helvB08.pil')
        self.font = None

    def displayPropertyPage(self):
        """deprecated

        Use the methods displayCaptureFilterProperties() and
        displayCapturePinProperties() instead.

        """
        print 'WARNING: displayPropertyPage() is deprecated.'
        print '         Use displayCaptureFilterProperties() and displayCapturePinProperties()'
        print '         instead!'
        self.dev.displaypropertypage()

    def displayCaptureFilterProperties(self):
        """Displays a dialog containing the property page of the capture filter.

        For VfW drivers you may find the option to select the resolution most
        likele here.

        """
        self.dev.displaycapturefilterproperties()

    def displayCapturePinProperties(self):
        """Displays a dialog containing the property page of the capture pin.

        For WDM drivers you may find the option to select the resolution most
        likele here.

        """
        self.dev.displaycapturepinproperties()

    def setResolution(self, width, height):
        """Sets the capture resolution. (without dialog)

        (contributed by Don Kimber <kimber@fxpal.com>)

        """
        self.dev.setresolution(width, height)

    def getDisplayName(self):
        """ Gets the Windows "friendly name" for the device (for example "Microsoft LifeCam VX-1000")

        (contributed by Jeremy Mortis (mortis@tansay.ca)
        """
        return self.dev.getdisplayname()

    def getBuffer(self):
        """Returns a string containing the raw pixel data.

        You probably don't want to use this function, but rather getImage() or
        saveSnapshot().

        """
        return self.dev.getbuffer()

    def getImage(self, timestamp=0, boldfont=0, textpos=default_textpos):
        """Returns a PIL Image instance.

        timestamp:  0 ... no timestamp (the default)
                    1 ... simple timestamp
                    2 ... timestamp with shadow
                    3 ... timestamp with outline

        boldfont:   0 ... normal font (the default)
                    1 ... bold font

        textpos:    The position of the timestamp can be specified by a string
                    containing a combination of two characters.  One character
                    must be either t or b, the other one either l, c or r.

                    t ... top
                    b ... bottom

                    l ... left
                    c ... center
                    r ... right

                    The default value is 'bl'

        """
        if timestamp:
            #text = now()
            text = time.asctime(time.localtime(time.time()))
        buffer, width, height = self.getBuffer()
        if buffer:
            im = Image.fromstring('RGB', (width, height), buffer, 'raw', 'BGR', 0, -1)
            if timestamp:
                if boldfont:
                    self.font = self.boldfont
                else:
                    self.font = self.normalfont
                tw, th = self.font.getsize(text)
                tw -= 2
                th -= 2
                if 't' in textpos:
                    y = -1
                elif 'b' in textpos:
                    y = height - th - 2
                else:
                    raise ValueError, "textpos must contain exactly one out of 't', 'b'"
                if 'l' in textpos:
                    x = 2
                elif 'c' in textpos:
                    x = (width - tw) / 2
                elif 'r' in textpos:
                    x = (width - tw) - 2
                else:
                    raise ValueError, "textpos must contain exactly one out of 'l', 'c', 'r'"
                draw = ImageDraw.Draw(im)
                if timestamp == 2: # shadow
                    draw.text((x+1, y), text, font=self.font, fill=shadowcolor)
                    draw.text((x, y+1), text, font=self.font, fill=shadowcolor)
                    draw.text((x+1, y+1), text, font=self.font, fill=shadowcolor)
                else:
                    if timestamp >= 3: # thin border
                        draw.text((x-1, y), text, font=self.font, fill=shadowcolor)
                        draw.text((x+1, y), text, font=self.font, fill=shadowcolor)
                        draw.text((x, y-1), text, font=self.font, fill=shadowcolor)
                        draw.text((x, y+1), text, font=self.font, fill=shadowcolor)
                    if timestamp == 4: # thick border
                        draw.text((x-1, y-1), text, font=self.font, fill=shadowcolor)
                        draw.text((x+1, y-1), text, font=self.font, fill=shadowcolor)
                        draw.text((x-1, y+1), text, font=self.font, fill=shadowcolor)
                        draw.text((x+1, y+1), text, font=self.font, fill=shadowcolor)
                draw.text((x, y), text, font=self.font, fill=textcolor)
            return im

    def saveSnapshot(self, filename, timestamp=0, boldfont=0, textpos=default_textpos, **keywords):
        """Saves a snapshot to the harddisk.

        The filetype depends on the filename extension.  Everything that PIL
        can handle can be specified (foo.jpg, foo.gif, foo.bmp, ...).

        filename:   String containing the name of the resulting file.

        timestamp:  see getImage()

        boldfont:   see getImage()

        textpos:    see getImage()

        Additional keyword arguments can be give which are just passed to the
        save() method of the Image class.  For example you can specify the
        compression level of a JPEG image by quality=75 (which is the default
        value anyway).

        """
        self.getImage(timestamp, boldfont, textpos).save(filename, **keywords)

if __name__ == '__main__':
    import shutil
    #shutil.copy('VideoCapture.py', 'C:\Python20\Lib')
    #shutil.copy('VideoCapture.py', 'C:\Python21\Lib')
    #shutil.copy('VideoCapture.py', 'C:\Python22\Lib')
    #shutil.copy('VideoCapture.py', 'C:\Python23\Lib')
    #shutil.copy('VideoCapture.py', 'C:\Python24\Lib')
    #shutil.copy('VideoCapture.py', 'C:\Python25\Lib')
    cam = Device(devnum=0)
    #~ #cam.displayPropertyPage() ## deprecated
    #~ #cam.displayCaptureFilterProperties()
    #~ #cam.displayCapturePinProperties()
    #~ #cam.setResolution(768, 576) ## PAL
    #~ #cam.setResolution(352, 288) ## CIF
    #~ cam.saveSnapshot('test.jpg', quality=75, timestamp=3, boldfont=1)
    print "Friendly name: ", cam.getDisplayName()


text:
package org.devgateway.toolkit.forms.wicket.components.table;

import org.apache.wicket.Component;
import org.apache.wicket.ajax.markup.html.navigation.paging.AjaxPagingNavigator;
import org.apache.wicket.markup.html.link.AbstractLink;
import org.apache.wicket.markup.html.navigation.paging.IPageable;
import org.apache.wicket.markup.html.navigation.paging.IPagingLabelProvider;
import org.apache.wicket.markup.html.navigation.paging.PagingNavigation;

/**
 * @author idobre
 * @since 11/25/14
 */

public class AjaxBootstrapNavigator extends AjaxPagingNavigator {
    private static final long serialVersionUID = -5572869834775798502L;

    private boolean hideFastPagination;

    private Component first;
    private Component next;
    private Component prev;
    private Component last;

    public AjaxBootstrapNavigator(final String id, final IPageable pageable) {
        this(id, pageable, null);
    }

    public AjaxBootstrapNavigator(final String id, final IPageable pageable, final boolean hideFastPagination) {
        this(id, pageable, null, hideFastPagination);
    }

    public AjaxBootstrapNavigator(final String id, final IPageable pageable, final IPagingLabelProvider labelProvider,
                                  final boolean hideFastPagination) {
        this(id, pageable, labelProvider);

        this.hideFastPagination = hideFastPagination;
    }

    public AjaxBootstrapNavigator(final String id, final IPageable pageable, final IPagingLabelProvider labelProvider) {
        super(id, pageable, labelProvider);
    }

    @Override
    protected void onInitialize() {
        super.onInitialize();

        // hide the first/next/prev/last links
        if (hideFastPagination) {
            first = get("first");
            first.setVisibilityAllowed(false);

            next = get("next");
            next.setVisibilityAllowed(false);

            prev = get("prev");
            prev.setVisibilityAllowed(false);

            last = get("last");
            last.setVisibilityAllowed(false);
        }
    }

    @Override
    protected PagingNavigation newNavigation(final String id, final IPageable pageable,
                                             final IPagingLabelProvider labelProvider) {
        return new BootstrapPagingNavigation(id, pageable, labelProvider);
    }

    @Override
    protected AbstractLink newPagingNavigationIncrementLink(final String id, final IPageable pageable,
                                                            final int increment) {
        final AbstractLink link = super.newPagingNavigationIncrementLink(id, pageable, increment);
        return link;
    }

    @Override
    protected AbstractLink newPagingNavigationLink(final String id, final IPageable pageable, final int pageNumber) {
        final AbstractLink link = super.newPagingNavigationLink(id, pageable, pageNumber);
        return link;
    }
}


text:
package com.oculusinfo.tile.rendering.color;

import java.awt.Color;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.oculusinfo.factory.ConfigurableFactory;
import com.oculusinfo.factory.ConfigurationException;
import com.oculusinfo.factory.JSONNode;
import com.oculusinfo.factory.properties.IntegerProperty;
import com.oculusinfo.factory.properties.JSONArrayProperty;
import com.oculusinfo.factory.properties.StringProperty;

/**
 * @author djonker
 *
 */
public class ThemedGradientFactory extends ConfigurableFactory<ThemedGradient> {
	private static final Logger LOGGER = LoggerFactory.getLogger(ColorRampFactory.class);

	/*
	 * Color properties
	 */
	public static final JSONArrayProperty COLORS = new JSONArrayProperty("colors",
			"An array of hues for a theme in a hue ramp.", "[]");

	/*
	 * Alpha properties, currently specified separately from color.
	 */
	public static final JSONArrayProperty ALPHAS = new JSONArrayProperty("alpha",
			"An array of alpha values in a hue ramp.", "[]");

	/*
	 * The theme this gradient belongs to.
	 */
	public static final StringProperty THEME = new StringProperty("theme", "The theme that this gradient belongs to.", "dark");

	// used for reading only
	private static final StringProperty COLOR_READER = new StringProperty("", "", "0xffffff");
	private static final IntegerProperty ALPHA_READER = new IntegerProperty("", "", 255);
	static private final List<Color> DEFAULT_LIGHT = Arrays.asList(new Color[]{Color.WHITE, Color.BLACK});
	static private final List<Color> DEFAULT_DARK = Arrays.asList(new Color[]{Color.BLACK, Color.WHITE});

	/**
	 * Constructs a new factory.
	 */
	public ThemedGradientFactory (ConfigurableFactory<?> parent, List<String> path) {
		super(ThemedGradient.class, parent, path);

		addProperty(THEME);
		addProperty(COLORS);
		addProperty(ALPHAS);
	}

	@Override
	public void readConfiguration (JSONObject rootNode) throws ConfigurationException {

		// read the predictable
	    super.readConfiguration(rootNode);
	}

	/**
	 * Returns the theme name.
	 * @return
	 */
	public String getTheme() {
		return getPropertyValue(THEME);
	}

	/* (non-Javadoc)
	 * @see com.oculusinfo.factory.ConfigurableFactory#create()
	 */
	@Override
	protected ThemedGradient create() {

		final String theme = getTheme();
		final List<Color> colors = new ArrayList<Color>();
		final JSONArray jcolors = getPropertyValue(COLORS);
		final JSONArray jalphas = getPropertyValue(ALPHAS);

		final int n = Math.max(jcolors.length(), jalphas.length());

		for (int i=0; i< n; i++) {
			String color = COLOR_READER.getDefaultValue();
			int alpha = ALPHA_READER.getDefaultValue();

			if (i < jcolors.length()) {
				try {
					color = COLOR_READER.unencodeJSON(new JSONNode(jcolors, i));
				} catch (Exception e) {
					LOGGER.warn("Error reading one of the color gradient values. Using default...");
				}
			}
			if (i < jalphas.length()) {
				try {
					alpha = ALPHA_READER.unencodeJSON(new JSONNode(jalphas, i));
				} catch (Exception e) {
					LOGGER.warn("Error reading one of the color gradient values. Using default...");
				}
			}

			colors.add(ColorRampParameter.getColorWithAlpha(color, alpha));
		}

		if (colors.size() < 1) {
			LOGGER.warn("Color gradient configuration has too few values. Added black and red.");
			colors.add(new Color(0,0,0,255));
			colors.add(new Color(255,0,0,255));
		} else if (colors.size() < 2) {
			LOGGER.warn("Color gradient configuration has too few values. Added red.");
			colors.add(new Color(255,0,0,255));
		}

		return new ThemedGradient() {

			@Override
			public String getTheme() {
				return theme;
			}

			@Override
			public List<Color> getColors() {
				return colors;
			}
		};
	}

	/**
	 * Creates a default grayscale gradient.
	 * @param theme
	 * @return
	 */
	public static List<Color> createDefault(String theme) {
		return "light".equalsIgnoreCase(theme)? DEFAULT_LIGHT : DEFAULT_DARK;
	}
}


text:
code to learn from noisy labels
An EM algorithm is used to deal with unobserved true labels [1].
(There are some differences from [1]. See source codes.)

## demo
test data (noise-free)

### symmetric noise
p(y_noisy=1| y_clean=0) = p(y_noisy=0| y_clean=1) = 0.3

### asymmetric noise
p(y_noisy=1| y_clean=0) = 0.05, p(y_noisy=0| y_clean=1) = 0.4

## references
[1] Rayker et al., "Learning From Crowds", 2010, http://www.jmlr.org/papers/volume11/raykar10a/raykar10a.pdf


text:
package hdfs.mapreduce;

import java.io.IOException;
import java.util.*;
import java.io.*;

import org.apache.hadoop.conf.*;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.*;
import org.apache.hadoop.util.*;

import com.gemstone.gemfire.cache.Operation;

import com.gemstone.gemfire.cache.hdfs.internal.PersistedEventImpl;
import com.gemstone.gemfire.cache.hdfs.internal.hoplog.mapreduce.GFInputFormat;
import com.gemstone.gemfire.cache.hdfs.internal.hoplog.mapreduce.GFOutputFormat;
import com.gemstone.gemfire.cache.hdfs.internal.hoplog.mapreduce.GFKey;

import hydra.*;
import util.*;

public class KnownKeysMRv2 extends Configured implements Tool {

  public static class KnownKeysMRv2Mapper extends Mapper<GFKey, PersistedEventImpl, GFKey, PEIWritable> {

    // Identity mapper (log and write out processed key/value pairs, the value is the PersistedEventImpl)
    public void map(GFKey key, PersistedEventImpl value, Context context) throws IOException, InterruptedException {

      String keyStr = (String)key.getKey();
      Operation op = value.getOperation();
      ValueHolder entryValue = null;
      System.out.println("map method invoked with " + keyStr + " " + op.toString());
      try {
        entryValue = (ValueHolder)value.getDeserializedValue();
      } catch (ClassNotFoundException e) {
        System.out.println("KnownKeysMRv2.map() caught " + e + " : " + TestHelper.getStackTrace(e));
      }
      context.write(key, new PEIWritable(value));
    }
  }

  public static class KnownKeysMRv2Reducer extends Reducer<GFKey, PEIWritable, Object, Object> {
    public void reduce(GFKey key, Iterable<PEIWritable> values, Context context) throws IOException, InterruptedException {
      // For a particular key ... process all records and output what we would have expected in this concKnownKeys test
      // Note that we either
      // 1. do a single create
      // 2. create + update
      // 3. create + destroy
      // look at all ops ... and output either
      // 1. create
      // 2. create (with value from update)
      // 3. do nothing (overall result is destroy, so do not create the entry in the gemfire validation region
      String keyStr = (String)key.getKey();
      ValueHolder updateValue = null;
      ValueHolder createValue = null;
      boolean destroyed = false;
      System.out.println("KnownKeysMRv2.reduce() invoked with " + keyStr);
      for (PEIWritable value:values) {
        PersistedEventImpl event = value.getEvent();
        Operation op = event.getOperation();

        ValueHolder vh = null;
        if (op.isDestroy()) {
          destroyed = true;
        } else {
          try {
            vh = (ValueHolder)event.getDeserializedValue();
          } catch (ClassNotFoundException e) {
            System.out.println("KnownKeysMRv2.map() caught " + e + " : " + TestHelper.getStackTrace(e));
          }
          if (op.isUpdate()) {
            updateValue = vh;
          } else {
            createValue = vh;
          }
        }
        System.out.println("KnownKeysMRv2.reduce() record: " + op.toString() + ": key = " + keyStr + " and op " + op.toString());
      }
      if (!destroyed) {
        if (updateValue != null) {
          context.write(key.getKey(), updateValue);
        } else {
          context.write(key.getKey(), createValue);
        }
      }
    }
  }

  @Override
  public int run(String[] args) throws Exception {

    String locatorHost = args[0];
    int locatorPort = Integer.parseInt(args[1]);
    String hdfsHomeDir = args[2];

    System.out.println("KnownKeysMRv2 invoked with args (locatorHost = " + locatorHost + " locatorPort = " + locatorPort + " hdfsHomeDir = " + hdfsHomeDir);

    Configuration conf = getConf();
    conf.set(GFInputFormat.INPUT_REGION, "partitionedRegion");
    conf.set(GFInputFormat.HOME_DIR, hdfsHomeDir);
    conf.setBoolean(GFInputFormat.CHECKPOINT, false);
    conf.set(GFOutputFormat.REGION, "validationRegion");
    conf.set(GFOutputFormat.LOCATOR_HOST, locatorHost);
    conf.setInt(GFOutputFormat.LOCATOR_PORT, locatorPort);

    Job job = Job.getInstance(conf, "knownKeysMRv2");
    job.setInputFormatClass(GFInputFormat.class);
    job.setOutputFormatClass(GFOutputFormat.class);

    job.setMapperClass(KnownKeysMRv2Mapper.class);
    job.setMapOutputKeyClass(GFKey.class);
    job.setMapOutputValueClass(PEIWritable.class);

    job.setReducerClass(KnownKeysMRv2Reducer.class);
    //job.setOutputKeyClass(String.class);
    //job.setOutputValueClass(ValueHolder.class);

    return job.waitForCompletion(false) ? 0 : 1;

  }

  public static void main(String[] args) throws Exception {
    int rc = ToolRunner.run(new Configuration(), new KnownKeysMRv2(), args);
    System.exit(rc);
  }
}


text:
package com.vk.api.sdk.actions;

import com.vk.api.sdk.client.AbstractAction;
import com.vk.api.sdk.client.VkApiClient;
import com.vk.api.sdk.client.actors.UserActor;
import com.vk.api.sdk.queries.leads.LeadsCheckUserQuery;
import com.vk.api.sdk.queries.leads.LeadsCompleteQuery;
import com.vk.api.sdk.queries.leads.LeadsGetStatsQuery;
import com.vk.api.sdk.queries.leads.LeadsGetUsersQuery;
import com.vk.api.sdk.queries.leads.LeadsMetricHitQuery;
import com.vk.api.sdk.queries.leads.LeadsStartQuery;

/**
 * List of Leads methods
 */
public class Leads extends AbstractAction {

    /**
     * Constructor
     *
     * @param client vk api client
     */
    public Leads(VkApiClient client) {
        super(client);
    }

    /**
     * Completes the lead started by user.
     */
    public LeadsCompleteQuery complete(String vkSid, String secret) {
        return new LeadsCompleteQuery(getClient(), vkSid, secret);
    }

    /**
     * Completes the lead started by user.
     */
    public LeadsCompleteQuery complete(UserActor actor, String vkSid, String secret) {
        return new LeadsCompleteQuery(getClient(), actor, vkSid, secret);
    }

    /**
     * Creates new session for the user passing the offer.
     */
    public LeadsStartQuery start(int leadId, String secret) {
        return new LeadsStartQuery(getClient(), leadId, secret);
    }

    /**
     * Creates new session for the user passing the offer.
     */
    public LeadsStartQuery start(UserActor actor, int leadId, String secret) {
        return new LeadsStartQuery(getClient(), actor, leadId, secret);
    }

    /**
     * Returns lead stats data.
     */
    public LeadsGetStatsQuery getStats(UserActor actor, int leadId) {
        return new LeadsGetStatsQuery(getClient(), actor, leadId);
    }

    /**
     * Returns a list of last user actions for the offer.
     */
    public LeadsGetUsersQuery getUsers(int offerId, String secret) {
        return new LeadsGetUsersQuery(getClient(), offerId, secret);
    }

    /**
     * Returns a list of last user actions for the offer.
     */
    public LeadsGetUsersQuery getUsers(UserActor actor, int offerId, String secret) {
        return new LeadsGetUsersQuery(getClient(), actor, offerId, secret);
    }

    public LeadsCheckUserQuery checkUser(UserActor actor, int leadId) {
        return new LeadsCheckUserQuery(getClient(), actor, leadId);
    }

    public LeadsMetricHitQuery metricHit(String data) {
        return new LeadsMetricHitQuery(getClient(), data);
    }

    public LeadsMetricHitQuery metricHit(UserActor actor, String data) {
        return new LeadsMetricHitQuery(getClient(), actor, data);
    }
}


text:
import repl, { Recoverable } from 'repl'
import vm from 'vm'
import { transform } from 'babel-core'
import pkg from '../../package'
import _debug from 'debug'
const debug = _debug('app:bin:repl')

debug(`Environment is set to: ${process.env.NODE_ENV || 'default'}`)

repl.start({
  prompt: `${pkg.name}> `,
  useGlobal: true,
  eval: evalCode,
  input: process.stdin,
  output: process.stdout
})

function evalCode(code, context, filename, cb) {
  let result
  try {
    result = vm.runInThisContext(transform(code).code)
  } catch (e) {
    if (isRecoverableError(e)) {
      return cb(new Recoverable(e))
    }
  }
  cb(null, result)
}

function isRecoverableError(error) {
  if (error.name === 'SyntaxError') {
    return /^(Unexpected end of input|Unexpected token)/.test(error.message)
  }
  return false
}


text:
//
//  AXProcessorArchitecture.h
//  AXFoundation
//
//  Created by Jean-François CONTART on 13/07/2015.
//
//

/*!
 * @header      AXProcessorArchitecture
 * @abstract    All functions for AXProcessorArchitecture
 * @discussion  This file contains all declarations for basic Processor Architecture.
 * @author		Jean-François CONTART
 * @updated     2015-06-22
 */

#import <Foundation/Foundation.h>
/**
 *  Type defintion to reccord architecture type
 */
typedef NS_ENUM(NSUInteger, AXProcessorArchitectureType){
	/**
	 *  32 bits architecture
	 */
	AXProcessorArchitecture32bits,
	/**
	 *  64 bits architecture
	 */
	AXProcessorArchitecture64bits,
	/**
	 *  unknow architecture
	 */
	AXProcessorArchitectureUnknow
};

/*!
 *	@author Jean-François CONTART, 2015-09-20
 *
 *	@brief Class to determinate architecture of processor, compile and running mode. Can test if code is running on iOS Simulator
 */
@interface AXProcessorArchitecture : NSObject {
	BOOL mLoadedInstance;
	/**
	 *  architecture of processor
	 */
	AXProcessorArchitectureType mArchitectureOfProcessor;
	/**
	 *  architecture using to running main
	 */
	AXProcessorArchitectureType mRunningMode;
	/**
	 *  architecture used to compile code
	 */
	AXProcessorArchitectureType mCompileMode;
}
/*!
 *	@author Jean-François CONTART, 2015-09-20
 *
 *	@brief The singleton of this class
 *
 *  @return return the singleton
 */
+(instancetype)singleton;

/*!
 *	@author Jean-François CONTART, 2015-09-20
 *
 *	@brief return if main run on iOS simulator or not
 *
 *  @return return boolean value
 */
+(BOOL)isIOSSimulator;

/*!
 *	@author Jean-François CONTART, 2015-09-20
 *
 *	@brief return type of architecture compilation (64 or 32 bits)
 *
 *  @return return AXProcessorArchitectureType
 */
+(AXProcessorArchitectureType)compileMode;

/*!
 *	@author Jean-François CONTART, 2015-09-20
 *
 *	@brief simple method to test if code was compile in 64 bits
 *
 *  @return return boolean value
 */
+(BOOL)compileIn64bit;

/*!
 *	@author Jean-François CONTART, 2015-09-20
 *
 *	@brief simple method to test if code was compile in 32 bits
 *
 *  @return return boolean value
 */
+(BOOL)compileIn32bit;

/*!
 *	@author Jean-François CONTART, 2015-09-20
 *
 *	@brief return architecture's code running mode (64 or 32 bits)
 *
 *  @return return AXProcessorArchitectureType
 */
+(AXProcessorArchitectureType)runningMode;

/*!
 *	@author Jean-François CONTART, 2015-09-20
 *
 *	@brief simple method to test if code is running in 64 bits
 *
 *  @return return boolean value
 */
+(BOOL)runIn64bit;

/*!
 *	@author Jean-François CONTART, 2015-09-20
 *
 *	@brief simple method to test if code is running in 32 bits
 *
 *  @return return boolean value
 */
+(BOOL)runIn32bit;

/*!
 *	@author Jean-François CONTART, 2015-09-20
 *
 *	@brief return type of architecture processor (64 or 32 bits)
 *
 *  @return return AXProcessorArchitectureType
 */
+(AXProcessorArchitectureType)architectureType;

/*!
 *	@author Jean-François CONTART, 2015-09-20
 *
 *	@brief simple method to test if processor is 64 bits
 *
 *  @return return boolean value
 */
+(BOOL)isArchitectureType64bit;

/*!
 *	@author Jean-François CONTART, 2015-09-20
 *
 *	@brief simple method to test if processor is 32 bits
 *
 *  @return return boolean value
 */
+(BOOL)isArchitectureType32bit;

@end


text:
package com.github.dreamhead.moco;

import com.github.dreamhead.moco.helper.MocoTestHelper;
import com.github.dreamhead.moco.runner.JsonRunner;
import com.google.common.collect.ImmutableList;
import com.google.common.io.Resources;
import org.junit.After;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

import static com.github.dreamhead.moco.bootstrap.arg.HttpArgs.httpArgs;
import static com.github.dreamhead.moco.helper.RemoteTestUtils.port;
import static com.github.dreamhead.moco.runner.JsonRunner.newJsonRunnerWithStreams;
import static com.google.common.collect.ImmutableList.toImmutableList;

public class AbstractMocoStandaloneTest {
    protected final MocoTestHelper helper = new MocoTestHelper();
    protected JsonRunner runner;

    @After
    public void teardown() {
        if (runner != null) {
            runner.stop();
        }
    }

    protected void runWithConfiguration(final String... resourceNames) {
        runner = newRunner(resourceNames);
        runner.run();
    }

    private JsonRunner newRunner(final String[] resourceNames) {
        final ImmutableList<InputStream> streams = Arrays.stream(resourceNames)
                .map(this::resourceAsStream)
                .collect(toImmutableList());
        return newJsonRunnerWithStreams(streams, httpArgs().withPort(port()).build());
    }

    private InputStream resourceAsStream(String resourceName) {
        try {
            return Resources.getResource(resourceName).openStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}


text:
set -x

echo "Starting Open edX multiserver install on pid $$"
date
ps axjf

#############
# Parameters
#############

AZUREUSER=$1
PASSWORD=$2
HOMEDIR="/home/$AZUREUSER"
VMNAME=`hostname`
echo "User: $AZUREUSER"
echo "User home dir: $HOMEDIR"
echo "vmname: $VMNAME"

###################
# Common Functions
###################

ensureAzureNetwork()
{
  # ensure the host name is resolvable
  hostResolveHealthy=1
  for i in {1..120}; do
    host $VMNAME
    if [ $? -eq 0 ]
    then
      # hostname has been found continue
      hostResolveHealthy=0
      echo "the host name resolves"
      break
    fi
    sleep 1
  done
  if [ $hostResolveHealthy -ne 0 ]
  then
    echo "host name does not resolve, aborting install"
    exit 1
  fi

  # ensure the network works
  networkHealthy=1
  for i in {1..12}; do
    wget -O/dev/null http://bing.com
    if [ $? -eq 0 ]
    then
      # hostname has been found continue
      networkHealthy=0
      echo "the network is healthy"
      break
    fi
    sleep 10
  done
  if [ $networkHealthy -ne 0 ]
  then
    echo "the network is not healthy, aborting install"
    ifconfig
    ip a
    exit 2
  fi
}
ensureAzureNetwork

###################################################
# Configure SSH keys
###################################################
time sudo apt-get -y update && sudo apt-get -y upgrade
sudo apt-get -y install sshpass
ssh-keygen -f $HOMEDIR/.ssh/id_rsa -t rsa -N ''

#copy so ansible can ssh localhost if it decides to
cat $HOMEDIR/.ssh/id_rsa.pub >> $HOMEDIR/.ssh/authorized_keys && echo "Key copied to localhost"
#terrible hack for getting keys onto db server
cat $HOMEDIR/.ssh/id_rsa.pub | sshpass -p $PASSWORD ssh -o "StrictHostKeyChecking no" $AZUREUSER@10.0.0.20 'cat >> .ssh/authorized_keys && echo "Key copied MySQL"'
cat $HOMEDIR/.ssh/id_rsa.pub | sshpass -p $PASSWORD ssh -o "StrictHostKeyChecking no" $AZUREUSER@10.0.0.30 'cat >> .ssh/authorized_keys && echo "Key copied MongoDB"'

#make sure premissions are correct
sudo chown -R $AZUREUSER:$AZUREUSER $HOMEDIR/.ssh/

###################################################
# Update Ubuntu and install prereqs
###################################################

time sudo apt-get -y update && sudo apt-get -y upgrade
time sudo apt-get install -y build-essential software-properties-common python-software-properties curl git-core libxml2-dev libxslt1-dev libfreetype6-dev python-pip python-apt python-dev libxmlsec1-dev swig
time sudo pip install --upgrade pip
time sudo pip install --upgrade virtualenv

###################################################
# Pin specific version of Open edX (named-release/cypress for now)
###################################################
export OPENEDX_RELEASE='named-release/cypress'
cat >/tmp/extra_vars.yml <<EOL
---
edx_platform_version: "$OPENEDX_RELEASE"
certs_version: "$OPENEDX_RELEASE"
forum_version: "$OPENEDX_RELEASE"
xqueue_version: "$OPENEDX_RELEASE"
configuration_version: "appsembler/azureDeploy"
edx_ansible_source_repo: "https://github.com/appsembler/configuration"

EOL

###################################################
# Set database vars
###################################################
cat >/tmp/db_vars.yml <<EOL
---
EDXAPP_MYSQL_USER_HOST: "%"
EDXAPP_MYSQL_HOST: "10.0.0.20"
EDXLOCAL_MYSQL_BIND_IP: "0.0.0.0"
XQUEUE_MYSQL_HOST: "10.0.0.20"
ORA_MYSQL_HOST: "10.0.0.20"
MONGO_BIND_IP: "0.0.0.0"
FORUM_MONGO_HOSTS: ["10.0.0.30"]
EDXAPP_MONGO_HOSTS: ["10.0.0.30"]
EDXAPP_MEMCACHE: ["10.0.0.20:11211"]
MEMCACHED_BIND_IP: "0.0.0.0"

EOL

###################################################
# Download configuration repo and start ansible
###################################################

cd /tmp
time git clone https://github.com/appsembler/configuration.git
cd configuration
time git checkout appsembler/azureDeploy
time sudo pip install -r requirements.txt
cd playbooks/appsemblerPlaybooks

#create inventory.ini file
echo "[mongo-server]" > inventory.ini
echo "10.0.0.30" >> inventory.ini
echo "" >> inventory.ini
echo "[mysql-server]" >> inventory.ini
echo "10.0.0.20" >> inventory.ini
echo "" >> inventory.ini
echo "[edxapp-primary-server]" >> inventory.ini
echo "localhost" >> inventory.ini

curl https://raw.githubusercontent.com/tkeemon/openedx-azure-multiserver/master/server-vars.yml > /tmp/server-vars.yml

sudo ansible-playbook -i inventory.ini -u $AZUREUSER --private-key=$HOMEDIR/.ssh/id_rsa multiserver_deploy.yml -e@/tmp/server-vars.yml -e@/tmp/extra_vars.yml -e@/tmp/db_vars.yml

date
echo "Completed Open edX multiserver provision on pid $$"


text:
'use strict';

var chai = require('chai');
var expect = chai.expect;
var User = require('../../../../').models.User;
var Promise = require('bluebird');

require('../../settings');

var user = new User({
  username: 'test',
  email: 'email@test.com',
  password: '$2a$10$Bd4I9p6xSuphD3gSPk006.fMR5/Dr9LjJD7JhvJcm7hpDaS0wJruq'
  // the hash refers to 'test'
});

describe('User', function () {

  it('has attributes', function () {
    expect(user).to.have.property('username');
    expect(user).to.have.property('email');
    expect(user).to.have.property('password');
  });

  it('#authenticate', function () {
    var promises = [
      user.authenticate('wrong_password').then(function (res) {
        expect(res).to.equal(false);
      }),
      user.authenticate('test').then(function (res) {
        expect(res).to.equal(true);
      })
    ];
    return Promise.all(promises);
  });
});


text:
layout: page
title: agriculture machine learning
description: machine leanring
img: /assets/img/3.jpg
year: 2018
importance: 2
category: none
---


text:
module Superhosting
  module Cli
    module Helper
      module Options
        module NotRequiredContainer
          extend ActiveSupport::Concern

          included do
            option :container_name,
                   short: '-c NAME',
                   long: '--container NAME'
          end
        end
      end
    end
  end
end


text:
package com.github.mizool.core.validation;

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Constraint(validatedBy = CheckLanguageTagValue.class)
@Documented
public @interface LanguageTagValue
{
    String message() default "{com.github.mizool.core.validation.LanguageTagValue.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    boolean mandatory();
}


text:
<!DOCTYPE html>

		<meta charset="UTF-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>INTERESTELEGRAM</title>
		<meta name="description" content="Juega con tus amigos y conquista la galaxia." />
		<meta name="keywords" content="app, showcase, css transitions, perspective, 3d, grid, overlay, css3, jquery" />
		<meta name="author" content="Codrops" />
		<link rel="shortcut icon" href="../favicon.ico">
		<link rel="stylesheet" type="text/css" href="/css/default.css" />
		<link rel="stylesheet" type="text/css" href="/css/landing.css" />
		<link href="/css/bootstrap.min.css" rel="stylesheet">

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

						Inicio
						Jugar
						Ranking
						Contacto

¡Bienvenidos a interestelegram!


text:
namespace blink {

CompositorTransformKeyframe::CompositorTransformKeyframe(
    double time,
    CompositorTransformOperations value,
    const TimingFunction& timing_function)
    : transform_keyframe_(
          cc::TransformKeyframe::Create(base::TimeDelta::FromSecondsD(time),
                                        value.ReleaseCcTransformOperations(),
                                        timing_function.CloneToCC())) {}

CompositorTransformKeyframe::~CompositorTransformKeyframe() = default;

double CompositorTransformKeyframe::Time() const {
  return transform_keyframe_->Time().InSecondsF();
}

const cc::TimingFunction* CompositorTransformKeyframe::CcTimingFunction()
    const {
  return transform_keyframe_->timing_function();
}

std::unique_ptr<cc::TransformKeyframe> CompositorTransformKeyframe::CloneToCC()
    const {
  return transform_keyframe_->Clone();
}

}  // namespace blink


text:
describe RubyOnRun::VM::VirtualMachine do

  context 'instance variables' do

    let(:file){ File.expand_path("../bytecode_samples/scope.bytecode", __FILE__) }
    let(:stream){ File.open(file).read }

    specify do
      expect(STDOUT).to receive(:puts).with(1, 1)

      expect(STDOUT).to receive(:puts).with(2, 2)

      expect(STDOUT).to receive(:puts).with(2, 2)

      expect(STDOUT).to receive(:puts).with(1, 1)

      expect(STDOUT).to receive(:puts).with(3, 3)

      expect(STDOUT).to receive(:puts).with(3, 3)

      expect(STDOUT).to receive(:puts).with(1, 1)

      expect(RubyOnRun::VM::VirtualMachine.new(stream).run).to eq true
    end
  end

end


text:
#ifndef WINDOW_H
#define WINDOW_H

#include <QWidget>
#include "message.h"

class QTextEdit;

//! [Window class definition]
class Window : public QWidget
{
    Q_OBJECT

public:
    Window();

signals:
    void messageSent(const Message &message);

public slots:
    void setMessage(const Message &message);

private slots:
    void sendMessage();

private:
    Message thisMessage;
    QTextEdit *editor;
};
//! [Window class definition]

#endif


text:
import connect from 'STORE/connect'
import { selectMenu } from 'REDUCER/common/menu'
import SidebarView from './SidebarView'

export default connect(

  state => ({
  }),

  {
    selectMenu
  },

  SidebarView
)


text:
#pragma once

#include "Common.h"
#include "Player.h"

namespace SparCraft
{
/*----------------------------------------------------------------------
 | Attack HighestDPS Player No Overkill
 |----------------------------------------------------------------------
 | Chooses an action with following priority:
 | 1) If it can attack, ATTACK highest DPS/HP enemy unit to overkill
 | 2) If it cannot attack:
 |    a) If it is in range to attack an enemy, WAIT until attack
 |    b) If it is not in range of enemy, MOVE towards closest
 `----------------------------------------------------------------------*/
class Player_NOKDPS : public Player
{
public:
	Player_NOKDPS (const IDType & playerID);
	void getMoves(GameState & state, const MoveArray & moves, std::vector<UnitAction> & moveVec);
	IDType getType() { return PlayerModels::NOKDPS; }
};
}


text:
#ifndef CMOCK_TEST_MATH_H_
#define CMOCK_TEST_MATH_H_

#ifdef __cplusplus
extern "C" {
#endif

int add(int a1, int a2);
int substract(int a1, int a2);

/* This function isn't implemented, but still can be mocked. */
int negate(int n);

#ifdef __cplusplus
}
#endif

#endif /* CMOCK_TEST_MATH_H_ */


text:
solo-app
========

Базовая структура приложения для Solo Framework.


text:
package com.ycsoft.business.dto.config;

import com.ycsoft.beans.config.TAddress;
import com.ycsoft.commons.tree.Tree;
import com.ycsoft.commons.tree.TreeNode;

/**
 * <p> 扩展地址实体类 </p>
 * @author hh
 * @date Dec 29, 2009 3:52:34 PM
 */
public class TAddressDto extends TAddress implements Tree {

	/**
	 *
	 */
	private static final long serialVersionUID = -8492116133830244486L;

	private Integer num;
	private String addr_p_name;

	public void transform(TreeNode node){
		node.setId( getAddr_id());
		node.setPid( getAddr_pid());
		node.setText( getAddr_name());
		node.setLeaf(true);
		node.setCls("file");
		node.setIs_leaf( getIs_leaf());
		node.getOthers().put("fullName", getAddr_full_name());
		node.getOthers().put("tree_level", String.valueOf(getTree_level()));
		node.getOthers().put("area_id", getArea_id());
		node.getOthers().put("county_id", getCounty_id());
		node.getOthers().put("status", getStatus());
		node.getOthers().put("net_type", getNet_type());
	}

	public Integer getNum() {
		return num;
	}

	public void setNum(Integer num) {
		this.num = num;
	}

	public String getAddr_p_name() {
		return addr_p_name;
	}

	public void setAddr_p_name(String addrPName) {
		addr_p_name = addrPName;
	}

}


text:
'use strict';

describe('farmbuild.soilSampleImporter module', function() {

    // instantiate service
    var $log;
    beforeEach(module('farmbuild.soilSampleImporter', function($provide) {
        $provide.value('$log', console)
    }));
    var soilClassificationTypes, h2O = 'pH H2O (Water)', collections;

    beforeEach(inject(function (_$log_, _soilClassificationTypes_, _collections_) {
        $log = _$log_;
        soilClassificationTypes = _soilClassificationTypes_;
        collections = _collections_;
    }));

    describe('soilClassificationTypes factory', function(){
        it('soilClassificationTypes should be defined', inject(function() {
            expect(soilClassificationTypes).toBeDefined();
        }));
    });

    describe('types.byName', function(){
        it('byName should find ' + h2O, inject(function() {
            var found = soilClassificationTypes.byName(h2O);
            expect(found.name).toEqual(h2O);
        }));
    });
});


text:
<?php

/**
 * Event Renderer
 *
 * @package			Todoyu
 * @subpackage		Calendar
*/
class TodoyuCalendarEventRenderer {

	/**
	 * Prepare event rendering data array
	 *
	 * @param	Integer		$mode			CALENDAR_MODE_DAY / ..WEEK / ..MONTH
	 * @param	Array		$data			event parameters
	 * @return	Array
	 * @deprecated
	 * @todo	Use event model for this
	 */
	public static function getEventRenderData($mode = CALENDAR_MODE_MONTH, array $data) {
		$idEvent			= intval($data['id']);
		$assignedPersons	= TodoyuCalendarEventStaticManager::getAssignedPersonsOfEvent($idEvent, true, true);

		$data['calendarMode']	= TodoyuCalendarManager::getModeName($mode);
		$data['titleCropLength']= $mode != CALENDAR_MODE_WEEK || TodoyuCalendarPreferences::isWeekendDisplayed() ? 16 : 24;
		$data['assignedPersons']= $assignedPersons;
		$data['timeStart']		= TodoyuCalendarEventStaticManager::getEvent($idEvent)->getStartTime();
		$data['color']			= TodoyuCalendarEventStaticManager::getEventColorData($idEvent);
		$data['eventtypeKey']	= TodoyuCalendarEventTypeManager::getTypeKey($data['eventtype']);

		$assignedPersonIDs	= array_keys($assignedPersons);

			// Hide visible data if event is private and current user not assigned
		$isPrivate	= intval($data['is_private']) === 1;
		if( $isPrivate && ! in_array(Todoyu::personid(), $assignedPersonIDs) ) {
			$data	= self::hidePrivateData($data);
			$data['class'] .= ' noAccess';
		} else {
			if( ! TodoyuCalendarEventRights::isEditAllowed($idEvent) ) {
				$data['class'] .= ' noEdit';
			}
		}

		return $data;
	}

	/**
	 * Render event details view for display inside expanded event in list mode
	 *
	 * @param	Integer		$idEvent
	 * @return	String
	 */
	public static function renderEventDetailsInList($idEvent) {
		$idEvent	= intval($idEvent);
		$event		= TodoyuCalendarEventStaticManager::getEvent($idEvent);
		$eventData	= $event->getTemplateData(true, false, true);
		$eventData	= self::getEventRenderData('list', $eventData);

		$eventData['person_create']	= $event->getPersonCreate()->getTemplateData();
		$eventData['persons']		= TodoyuCalendarEventStaticManager::getAssignedPersonsOfEvent($idEvent, true, true);

		$tmpl	= 'ext/calendar/view/event-listmode.tmpl';
		$data	= array(
			'event'	=> $eventData,
		);

		return Todoyu::render($tmpl, $data);
	}

	/**
	 * Render create event form popup
	 *
	 * @param	Integer		$timestamp
	 * @param	Boolean		$isAllDayEvent
	 * @return	String		Form
	 */
	public static function renderCreateQuickEvent($timestamp = 0, $isAllDayEvent = false) {
		$timestamp	= intval($timestamp);
		$timestamp	= TodoyuTime::getRoundedTime($timestamp, 15);

			// Get form object
		$form	= TodoyuCalendarEventStaticManager::getQuickCreateForm();

			// Set event start and ending timestamps
		if( $isAllDayEvent ) {
			$dayRange	= TodoyuTime::getDayRange($timestamp);

			$timeStart	= $dayRange['start'];
			$timeEnd	= $dayRange['end'];
		} else {
			$timeStart	= $timestamp;
			$timeEnd	= $timeStart + TodoyuTime::SECONDS_MIN * 30;
		}

			// Set form data
		$formData	= array(
			'date_start'	=> $timeStart,
			'date_end'		=> $timeEnd,
			'is_dayevent'	=> $isAllDayEvent,
			'persons'		=> array(TodoyuAuth::getPerson()->getTemplateData())
		);

		$form->setFormData($formData);
		$form->setUseRecordID(false);

		return $form->render();
	}

	/**
	 * Hide private data out from event attributes
	 *
	 * @param	Array	$data
	 * @return	Array
	 */
	private static function hidePrivateData(array $data) {
		$data['title']			= '<' . Todoyu::Label('calendar.event.privateEvent.info') . '>';
		$data['description']	= '';

		return $data;
	}

	/**
	 * Render event tabs, including detail viewing tab
	 *
	 * @param	Integer	$idEvent
	 * @return	String
	 */
	public static function renderEventViewTabs($idEvent) {
		$idEvent	= intval($idEvent);
		$activeTab	= 'detail';
		$name		= 'calendar';
		$jsHandler	= 'Todoyu.Ext.calendar.Tabs.onSelect.bind(Todoyu.Ext.calendar.Tabs)';
		$tabs		= TodoyuCalendarManager::getCalendarTabsConfig();

		$event		= TodoyuCalendarEventStaticManager::getEvent($idEvent);

		$detailTab	= array(
			'id'		=> 'detail',
			'label'		=> 'Detail: ' . $event->getTitle()
		);

		array_unshift($tabs, $detailTab);

		return TodoyuTabheadRenderer::renderTabs($name, $tabs, $jsHandler, $activeTab);
	}

	/**
	 * Render event view
	 *
	 * @param	Integer	$idEvent
	 * @return	String
	 */
	public static function renderEventView($idEvent) {
		$idEvent	= intval($idEvent);
		$event		= TodoyuCalendarEventStaticManager::getEvent($idEvent);

		$tmpl	= 'ext/calendar/view/event-view.tmpl';
		$data	= array(
			'event'	=> $event->getTemplateData(true, true, true),
			'tabs'	=> self::renderEventViewTabs($idEvent)
		);

		return Todoyu::render($tmpl, $data);
	}

	/**
	 * @param	Array	$personIDs
	 * @return	String
	 */
	public static function renderAutoMailComment(array $personIDs) {
		$tmpl	= 'ext/calendar/view/infocomment-autonotification.tmpl';
		$data	= array(
			'personIDs'	=> $personIDs
		);

		return Todoyu::render($tmpl, $data);
	}

	/**
	 * Render URL pointing to event in todoyu calendar
	 *
	 * @param	Integer		$idEvent
	 * @param	Boolean		$absolute
	 * @param	Boolean		$encode		Encode HTML entities (use & instead of & as argument separator)
	 * @return	String
	 */
	public static function renderEventLinkURL($idEvent, $absolute = true, $encode = false) {
		$idEvent	= intval($idEvent);

		$urlParams	= array(
			'ext'	=> 'calendar',
			'event'	=> $idEvent
		);

		return TodoyuString::buildUrl($urlParams, '', $absolute, !$encode);
	}

}

?>