text:
<?php

class FileValidatorProviderTests extends WP_UnitTestCase {
	public function test_canResolveFileValidator_registeredMimeType_noAdditionalRegistrations() {
		$provider = new Abp01_Transfer_Uploader_FileValidatorProvider();
		$this->_assertFileValidatorProviderCanResolveMimeTypes($provider, $this->_getRegisteredValidatorMimeTypes());
	}

	private function _assertFileValidatorProviderCanResolveMimeTypes(Abp01_Transfer_Uploader_FileValidatorProvider $provider, array $mimeTypeRegistrations) {
		foreach ($mimeTypeRegistrations as $mimeType => $validatorClass) {
			$validatorInstance = $provider->resolveValidator($mimeType);
			$this->assertNotNull($validatorInstance);
			$this->assertInstanceOf($validatorClass, $validatorInstance);
		}
	}

	public function test_tryResolveFileValidator_unregisteredMimeType() {
		$provider = new Abp01_Transfer_Uploader_FileValidatorProvider();
		foreach ($this->_getUnregisteredValidatorMimeTypes() as $mimeType) {
			$parserInstance = $provider->resolveValidator($mimeType);
			$this->assertNull($parserInstance);
		}
	}

	public function test_canCheckIfCanResolveMimeType_registeredMimeType_noAdditionalRegistrations() {
		$provider = new Abp01_Transfer_Uploader_FileValidatorProvider();
		$registeredMimeTypes = array_keys($this->_getRegisteredValidatorMimeTypes());
		$this->_assertFileValidatorProviderCanCheckIfCanResolveRegisteredMimeTypes($provider, $registeredMimeTypes);
	}

	private function _assertFileValidatorProviderCanCheckIfCanResolveRegisteredMimeTypes(Abp01_Transfer_Uploader_FileValidatorProvider $factory, array $mimeTypes) {
		foreach ($mimeTypes as $mimeType) {
			$this->assertTrue($factory->canResolveValidatorForMimeType($mimeType));
		}
	}

	public function test_canCheckIfCanresolveMimeType_unregisteredMimeType() {
		$provider = new Abp01_Transfer_Uploader_FileValidatorProvider();
		$unregisteredMimeTypes = $this->_getUnregisteredValidatorMimeTypes();
		foreach ($unregisteredMimeTypes as $mimeType) {
			$this->assertFalse($provider->canResolveValidatorForMimeType($mimeType));
		}
	}

	public function test_canRegisterValidatorForMimeTypes() {
		$factory = new Abp01_Transfer_Uploader_FileValidatorProvider();
		$newMimeTypeRegistrations = $this->_getNewFileValidatorMimeTypeRegistrations();

		$newMimeTypes = array_keys($newMimeTypeRegistrations);
		$factory->registerValidatorForMimeTypes(new MockFileValidator(),
			$newMimeTypes);

		$checkMimeTypeRegistrations = array_merge($this->_getRegisteredValidatorMimeTypes(),
			$newMimeTypeRegistrations);

		$this->_assertFileValidatorProviderCanResolveMimeTypes($factory,
			$checkMimeTypeRegistrations);

		$checkMimeTypes = array_keys($checkMimeTypeRegistrations);
		$this->_assertFileValidatorProviderCanCheckIfCanResolveRegisteredMimeTypes($factory,
			$checkMimeTypes);
	}

	private function _getNewFileValidatorMimeTypeRegistrations() {
		$newMimeTypeRegistrations = array();
		$mimeTypes = $this->_getUnregisteredValidatorMimeTypes();

		foreach ($mimeTypes as $mimeType) {
			$newMimeTypeRegistrations[$mimeType] = MockFileValidator::class;
		}

		return $newMimeTypeRegistrations;
	}

	private function _getRegisteredValidatorMimeTypes() {
		return array(
			'application/gpx' => Abp01_Validate_GpxDocument::class,
			'application/x-gpx+xml' => Abp01_Validate_GpxDocument::class,
			'application/xml-gpx' => Abp01_Validate_GpxDocument::class,
			'application/xml' => Abp01_Validate_GpxDocument::class,
			'application/gpx+xml' => Abp01_Validate_GpxDocument::class,
			'text/xml' => Abp01_Validate_GpxDocument::class,
			'application/json' => Abp01_Validate_GeoJsonDocument::class,
			'application/geo+json' => Abp01_Validate_GeoJsonDocument::class,
			'application/vnd.geo+json' => Abp01_Validate_GeoJsonDocument::class
		);
	}

	private function _getUnregisteredValidatorMimeTypes() {
		return array(
			'text/plain',
			'image/jpeg',
			'application/zip'
		);
	}
}


text:
Classes

        Posted on

        by

    No classes yet, why don't you create one?

redpajama_set_name: RedPajamaGithub


text:
class QResourceTreeWidget : public QTreeWidget
{
  Q_OBJECT

public:
  ResourceManager* manager;
  explicit QResourceTreeWidget(QWidget* parent=NULL);
  void setManager(ResourceManager* manager);
  void refresh();
  void addNotify(ResourceNode* node);
  void onAdd(ResourcePtr r);
  void onDeletePressed();
  void onDelete(QTreeWidgetItem* n);
  void onExpand(QTreeWidgetItem* n);
  QTreeWidgetItem* nodeToItem(ResourceNode* node);
  ResourceNode* itemToNode(QTreeWidgetItem* node);
  void updateAllDecorators();
  void updateDecorator(QTreeWidgetItem* item);
  void updateProperties(QTreeWidgetItem* item);

private:
  //for drag and drop
  QPoint startPos;
  ResourceNodePtr dragNode;
  virtual void mousePressEvent(QMouseEvent *event);
  virtual void mouseMoveEvent(QMouseEvent *event);
  virtual void dragEnterEvent(QDragEnterEvent *event);
  virtual void dragMoveEvent(QDragMoveEvent *event);
  virtual void dragLeaveEvent(QDragLeaveEvent *event);
  virtual void dropEvent(QDropEvent *event);

  //for delete
  virtual void keyPressEvent(QKeyEvent * event);

  //helpers
  QTreeWidgetItem* makeItem(ResourceNode* node);
};

#endif


text:
using System;
using System.Collections.Generic;
using System.Drawing;
using OsEngine.Entity;
using OsEngine.Indicators;

namespace CustomIndicators.Scripts
{
    public class RVI : Aindicator
    {
        private IndicatorParameterInt _p1;

        private IndicatorDataSeries _seriesOne;
        private IndicatorDataSeries _seriesTwo;

        public override void OnStateChange(IndicatorState state)
        {
            if (state == IndicatorState.Configure)
            {
                _p1 = CreateParameterInt("Period", 5);

                _seriesOne = CreateSeries("Value 1", Color.DarkRed, IndicatorChartPaintType.Line, true);
                _seriesTwo = CreateSeries("Value 2", Color.DodgerBlue, IndicatorChartPaintType.Line, true);
            }
            else if (state == IndicatorState.Dispose)
            {
                if (_moveAverage != null)
                {
                    _moveAverage = null;
                    _rangeAverage = null;
                    _rvi = null;
                }
            }
        }

        private List<decimal> _moveAverage;
        private List<decimal> _rangeAverage;
        private List<decimal> _rvi;

        public override void OnProcess(List<Candle> candles, int index)
        {
            if (_moveAverage == null || index == 1)
            {
                _moveAverage = new List<decimal>();
                _rangeAverage = new List<decimal>();
                _rvi = new List<decimal>();
            }

            if (index <= _p1.ValueInt)
            {
                return;
            }

            while (index >= _moveAverage.Count)
            { _moveAverage.Add(0); }

            while (index >= _rangeAverage.Count)
            { _rangeAverage.Add(0); }

            while (index >= _rvi.Count)
            { _rvi.Add(0); }

            _moveAverage[index] = GetMoveAverage(candles, index);
            _rangeAverage[index] = GetRangeAverage(candles, index);
            _rvi[_rvi.Count - 1] = (GetRvi(index));

            _seriesOne.Values[index] = GetRvi(index);
            _seriesTwo.Values[index] = GetValueSecond(index);
        }

        private decimal GetValueSecond(int index)
        {
            if (index >= _p1.ValueInt + 6)
            {
                return Math.Round((_rvi[index] + 2 * _rvi[index - 1] + 2 * _rvi[index - 2] + _rvi[index - 3]) / 6, 2);
            }
            else
            {
                return 0;
            }

        }

        private decimal GetMoveAverage(List<Candle> candles, int index)
        {
            if (index > 3)
            {
                return (candles[index].Close - candles[index].Open) +
                   2 * (candles[index - 1].Close - candles[index - 1].Open) +
                   2 * (candles[index - 2].Close - candles[index - 2].Open) +
                     (candles[index - 3].Close - candles[index - 3].Open);
            }
            else
            {
                return 0;
            }

        }

        private decimal GetRangeAverage(List<Candle> candles, int index)
        {
            if (index > 3)
            {
                return (candles[index].High - candles[index].Low) +
                   2 * (candles[index - 1].High - candles[index - 1].Low) +
                   2 * (candles[index - 2].High - candles[index - 2].Low) +
                     (candles[index - 3].High - candles[index - 3].Low);
            }
            else
            {
                return 0;
            }
        }

        private decimal GetRvi(int index)
        {

            if (index - _p1.ValueInt + 1<= 0)
            {
                return 0;
            }

            decimal sumMa = 0;
            decimal sumRa = 0;

            for (int i = index - _p1.ValueInt+1; i < index+1; i++)
            {
                sumMa = sumMa + _moveAverage[i];
                sumRa = sumRa + _rangeAverage[i];
            }

            if (sumRa == 0 || sumMa == 0)
            {
                return 0;
            }

            return Math.Round(sumMa / sumRa, 2);
        }
    }
}


text:
ActiveRecord::Schema.define do
  create_table :balloons, :force => true do |t|
    t.enum "color", :limit => ['red', 'gold'], :default => 'gold', :null => false
    t.column "size", :enum, :limit => ['small', 'medium', 'large']
  end
end


text:
import unittest
import random

from stanford_algoritms_part1.build_blocks import partioners

class TestSequenceFunctions(unittest.TestCase):
    def setUp(self):
        self.seq = range(10)

    def test_shuffle(self):
        # make sure the shuffled sequence does not lose any elements
        random.shuffle(self.seq)
        self.seq.sort()
        self.assertEqual(self.seq, range(10))

    def test_part(self):
        in_array = [3, 8, 2, 5, 1, 4, 7, 6]
        partitioner = partioners.Partitioner()
        partitioner.partition(in_array)
        self.assertEqual(3, in_array[2])
        self.assertTrue(min(in_array[3:]) > 3)


text:
(function (MML) {
  var MO = MML.mo.OPTYPES;
  var TEXCLASS = MML.TEXCLASS;

  MathJax.Hub.Insert(MML.mo.prototype,{
    OPTABLE: {
      prefix: {
        '\u2016': [0,0,TEXCLASS.ORD,{fence: true, stretchy: true}], // double vertical line
        '\u2018': [0,0,TEXCLASS.OPEN,{fence: true}], // left single quotation mark
        '\u201C': [0,0,TEXCLASS.OPEN,{fence: true}]  // left double quotation mark
      },
      postfix: {
        '\u2016': [0,0,TEXCLASS.ORD,{fence: true, stretchy: true}], // double vertical line
        '\u2019': [0,0,TEXCLASS.CLOSE,{fence: true}], // right single quotation mark
        '\u201D': [0,0,TEXCLASS.CLOSE,{fence: true}]  // right double quotation mark
      }
    }
  });

  MathJax.Ajax.loadComplete(MML.optableDir+"/GeneralPunctuation.js");

})(MathJax.ElementJax.mml);


text:
namespace Primelabs.Twingly.KestrelApi
{
    public interface IOpenMessage<T>
    {
        T Value { get; set;  }

        bool Close { get; set; }
    }
}


text:
/*
 Created on Aug 17, 2011 by mschilli

 ALMA - Atacama Large Millimiter Array
 (c) European Southern Observatory, 2011

 This library is free software; you can redistribute it and/or
 modify it under the terms of the GNU Lesser General Public
 License as published by the Free Software Foundation; either
 version 2.1 of the License, or (at your option) any later version.

 This library is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 Lesser General Public License for more details.

 You should have received a copy of the GNU Lesser General Public
 License along with this library; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 */
package alma.acs.gui.util;

import java.awt.Frame;
import java.awt.Rectangle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Helper methods for dealing with Java Windows.
 *
 * @since August 2011
 * @author M.Schilling, ESO
 */
public class WindowUtil {
	/*
	 * Code reviewed on 17 Aug 2011 by Rodrigo and Marcus.
	 */

	/**
	 * Assigns position and size to a desktop frame from a textual
	 * geometry definition. For allowed formats of geometry definition,
	 * see {@link #parseGeometry(String)}.
	 *
	 * If {@code geometry} is {@code null} or cannot be understood, this call
	 * will do nothing and return {@code false}.
	 *
	 * @param frame - a desktop frame to position and size
	 * @param geometry - a geometry definition string
	 * @return whether the geometry definition was valid and thus applied
	 */
	public static boolean applyGeometry (Frame frame, String geometry) {
		Rectangle rect = null;
		try {
			rect = parseGeometry(geometry);
		} catch (IllegalArgumentException exc) {
			return false;
		}

		if (rect.width <= 0 || rect.height <= 0) {
			frame.pack();
			frame.setLocation (rect.x, rect.y);
			return true;
		}

		frame.setBounds(rect);
		return true;
	}

	/**
	 * Parses a geometry string made up of positional parameters
	 * "width height xpos ypos" or "xpos ypos" (ie. X server format),
	 * or named parameters "x=...,y=...,w=...,h=...".
	 *

	 * Examples:

	 *
400x500+200+300
	 *
+200+300
	 *
x=200, y=300, w=400, h=500
	 *
x=200y=300w=400h=500
	 *
w=400;h=500;x=200;y=300;
	 *

	 *
	 * Note that negative x/y coordinates (ie. positioning leftwards from the
	 * screen's right border) are not supported.
	 *

	 * This method throws {@code IllegalArgumentException} if the geometry string is invalid.
	 * Using this method and catching that exception provides a simple way of testing a geometry
	 * string before use, e.g. when you are parsing command-line arguments.
	 *

	 * The returned rectangle will contain {@code 0} for any coordinate that was
	 * not defined in the geometry string. This can happen for strings specified in
	 * "X server short notation" (where only x and y are defined), and for strings
	 * specified in "named parameters" notation (if parameters were omitted).
	 *
	 * @param geometry - the geometry as text
	 * @return the geometry as a rectangle
	 * @throws IllegalArgumentException if the argument is null or cannot be parsed
	 */
	public static Rectangle parseGeometry (String geometry) throws IllegalArgumentException {

		/* msc 2011-08: for allowing negative x/y (ie. counting leftwards from the right border)
		 * it is necessary to change "PositiveNumber" below to become "SignedNumber", and
		 * to find out the real screen size in a multi-screen environment (GraphicsEnvironment).
		 * the latter seems to be unpredictable on some machines/platforms, so i'm skipping it.
		 */

		if (geometry == null)
			throw new IllegalArgumentException("Bad geometry: null");

		Rectangle r = new Rectangle();
		Matcher m;

		m = p1.matcher (geometry);
		if (m.matches()) {
			r.width = asInt(m.group(1));
			r.height = asInt(m.group(2));
			r.x = asInt(m.group(3));
			r.y = asInt(m.group(4));
			return r;
		}

		m = p2.matcher (geometry);
		if (m.matches()) {
			r.x = asInt(m.group(1));
			r.y = asInt(m.group(2));
			return r;
		}

		m = p3.matcher(geometry);
		if (m.matches()) {
			for (int i = 1; i <= m.groupCount(); i++) {
				if (m.group(i).equals("w"))
					r.width = asInt(m.group(++i));
				if (m.group(i).equals("h"))
					r.height = asInt(m.group(++i));
				if (m.group(i).equals("x"))
					r.x = asInt(m.group(++i));
				if (m.group(i).equals("y"))
					r.y = asInt(m.group(++i));
			}
			return r;
		}

		throw new IllegalArgumentException("Bad geometry "+geometry+". Must be "+hr1+" or "+hr2+" or "+hr3);
	}

	private final static String Number = "(\\d+)";
	private final static String AnyNaN = "\\D*";
	private final static String NamVal = "([whxy])=" + Number;
	private final static String Multiply  = "[xX]";
	private final static String PositiveNumber = "([\\+]\\d+)";

	private final static String hr1 = "WIDTHxHEIGHT+XPOS+YPOS";
	private final static Pattern p1 = Pattern.compile (Number + Multiply + Number + PositiveNumber + PositiveNumber);

	private final static String hr2 = "+XPOS+YPOS";
	private final static Pattern p2 = Pattern.compile (PositiveNumber + PositiveNumber);

	private final static String hr3 = "x=XPOS,y=YPOS,w=WIDTH,h=HEIGHT";
	private final static Pattern p3 = Pattern.compile(NamVal + AnyNaN + NamVal + AnyNaN + NamVal + AnyNaN + NamVal + AnyNaN);

	private static int asInt (String number) {
		if (number.charAt(0) == '+') // Integer class cannot parse "+" prefix
			number = number.substring(1);
		return Integer.parseInt (number);
	}

	// ============================================================================
}


text:
package pkg1;

public class A {
    public interface I {
        default void m() { A.m(this); }
    }

    public static void m(Object o) {}
}


text:
define([
	'jquery',
	'Global/SQ',
	'SQ/Broadcaster',
	'SQ/Util',
	'ThirdParty/jquery.validate'
], function(
	$,
	SQ,
	Broadcaster,
	Util
) {
	'use strict';

	return function EditClassroomGradeForm() {

		var _me = this;
		var _util = new Util();
		var _$edit_classroom_grade_form = null;
		var _edit_classroom_grade_data = {};

		SQ.mixin(_me, new Broadcaster(['edit_classroom_grade']));

		(function _init() {
		})();

		this.initialize = function($e) {
			_$edit_classroom_grade_form = $e;
			_$edit_classroom_grade_form.validate({
				rules: {
					name : {
						required: true,
						remote: {
							url: '/ajax/classroom_grade/editNameNotExist',
							type: 'post',
							data: {school_id: $e.find('[name="school_id"]').val(), classroom_grade_id: $e.find('[name="classroom_grade_id"]').val()}
						}
					}
				},
				messages: {
					name: {
						remote: 'This name has been taken'
					}
				},
				submitHandler: function(form) {
					_edit_classroom_grade_data = _util.serializeJSON($(form));
					_me.broadcast('edit_classroom_grade', _edit_classroom_grade_data);
				}
			});
		};
	}
});


text:
package xworker.swt.xwidgets.draw2d;

import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.widgets.Canvas;
import org.xmeta.ActionContext;
import org.xmeta.annotation.ActionParams;

import xworker.swt.xwidgets.SimpleShape;

public class Oval {
	@ActionParams(names="canvas,gc,shape")
	public static void draw(Canvas canvas, GC gc, SimpleShape shape, ActionContext actionContext) {
		if(shape.getThing().getBoolean("fill")) {
			gc.fillOval(0, 0, shape.getWidth(), shape.getHeight());
		}else {
			gc.drawOval(0, 0, shape.getWidth(), shape.getHeight());
		}
	}
}


text:
//Simple Lee's Routing Algorithm
//Author: IW

package org.deuce.benchmark.lee;

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

import org.deuce.Atomic;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

public class LeeRouterDeuceSTM implements ILeeRouter{
    final static int cyan = 0x00FFFF;

    public static final long MAX_SAMPLE_THRESHOLD = 60000;

    final static int magenta = 0xFF00FF;

    final static int yellow = 0xFFFF00;

    final static int green = 0x00FF00;

    final static int red = 0xFF0000;

    final static int blue = 0x0000FF;

    final int GRID_SIZE;

    final static int EMPTY = 0;

    final static int TEMP_EMPTY = 10000;

    final static int OCC = 5120;

    final static int VIA = 6000;

    final static int BVIA = 6001;

    final static int TRACK = 8192;

    final static int GOAL = 1024;

    final static int MAX_WEIGHT = 1;

    final Grid grid;

    final Object gridLock = new Object();

    private static Document doc;

    static int netNo = 0;

//	private static int printDest = 0; // 1 for file, 0 for screen.

    // note these very useful arrays
    final static int dx[][] = { { -1, 1, 0, 0 }, { 0, 0, -1, 1 } };

    // to help look NSEW.
    final static int dy[][] = { { 0, 0, -1, 1 }, { -1, 1, 0, 0 } };

    static Viewer view;

    static int failures = 0;

    static int num_vias = 0;

    static int forced_vias = 0;

    static BufferedReader inputFile;

    static String input_line;

    static int linepos = 0;

    final Object queueLock = new Object();

    final WorkQueue work;

    final WorkQueue debugQueue;

    public static boolean TEST = true;

    public static boolean DEBUG = false;

    private static final boolean XML_REPORT = true;

    public LeeRouterDeuceSTM(String file, boolean test, boolean debug, boolean rel) {
        TEST = test;
        DEBUG = debug;
        if(DEBUG) view = new Viewer();
        if (TEST) GRID_SIZE = 10;
        else GRID_SIZE = 600;
        if(DEBUG) System.out.println("Creating grid...");
        grid = new Grid(GRID_SIZE, GRID_SIZE, 2, rel); //the Lee 3D Grid;
        if(DEBUG) System.out.println("Done creating grid");
        work = new WorkQueue(); // empty
        if(DEBUG) System.out.println("Parsing data...");
        if (!TEST) parseDataFile(file);
        else fakeTestData(); //WARNING: Needs grid at least 10x10x2
        if(DEBUG) System.out.println("Done parsing data");
        if(DEBUG) System.out.println("Adding weights...");
        grid.addweights();
        if(DEBUG) System.out.println("Done adding weights");
        work.sort();
        if(DEBUG)
            debugQueue = new WorkQueue();
        else
            debugQueue = null;

    }

    public LeeRouterDeuceSTM(String file) {
        this(file, false, false, false);
    }

    public LeeRouterDeuceSTM(String file, boolean rel) {
        this(file, false, false, rel);
    }

    private void fakeTestData() {
        netNo++;
        grid.occupy(7, 3, 7, 3);grid.occupy(7, 7, 7, 7);
        work.next = work.enQueue(7, 3, 7, 7, netNo);

        netNo++;
        grid.occupy(3, 6, 3, 6);grid.occupy(8, 6, 8, 6);
        work.next = work.enQueue(3, 6, 8, 6, netNo);

        netNo++;
        grid.occupy(5, 3, 5, 3);grid.occupy(8, 5, 8, 5);
        work.next = work.enQueue(5, 3, 8, 5, netNo);

        netNo++;
        grid.occupy(8, 3, 8, 3);grid.occupy(2, 6, 2, 6);
        work.next = work.enQueue(8, 3, 2, 6, netNo);

        netNo++;
        grid.occupy(4, 3, 4, 3);grid.occupy(6, 7, 6, 7);
        work.next = work.enQueue(4, 3, 6, 7, netNo);

        netNo++;
        grid.occupy(3, 8, 3, 8);grid.occupy(8, 3, 8, 3);
        work.next = work.enQueue(3, 8, 8, 3, netNo);
    }

    private void parseDataFile(String fileName) {
        // Read very simple HDL file
        try {

            inputFile = new BufferedReader(new InputStreamReader(
                    new FileInputStream(fileName)));
            int i = 0;
            while (true) {
                nextLine();
                char c = readChar();
                if (c == 'E')
                    break; // end of file
                if (c == 'C') // chip bounding box
                {
                    int x0 = readInt();
                    int y0 = readInt();
                    int x1 = readInt();
                    int y1 = readInt();
                    grid.occupy(x0, y0, x1, y1);
                }
                if (c == 'P') // pad
                {
                    int x0 = readInt();
                    int y0 = readInt();
                    grid.occupy(x0, y0, x0, y0);
                }
                if (c == 'J') // join connection pts
                {
                    i++;
                    int x0 = readInt();
                    int y0 = readInt();
                    int x1 = readInt();
                    int y1 = readInt();
                    netNo++;
                    work.next = work.enQueue(x0, y0, x1, y1, netNo);
                }
            }
        } catch (FileNotFoundException exception) {
            System.out.println("Cannot open file: " + fileName);
            System.exit(1);
        } catch (IOException exception) {
            System.out.println(exception);
            exception.printStackTrace();
        }

    }

    public WorkQueue getNextTrack() {
//        synchronized(queueLock) {
            return atomic1();
//        }
//        return null;
    }

    @Atomic
	private WorkQueue atomic1() {
		if(work.next != null) {
		    return work.deQueue();
		}
		return null;
	}

    public boolean layNextTrack(WorkQueue q, int [][][]tempg) {
        // start transaction
        boolean done = false;
//        synchronized(gridLock) {
            done = atomicLayoutTrack(q, tempg);
//        }
        return done;
        // end transaction
    }

    @Atomic
	private boolean atomicLayoutTrack(WorkQueue q, int[][][] tempg) {
		boolean done;
		done = connect(q.x1, q.y1, q.x2, q.y2, q.nn, tempg, grid);
		if(DEBUG && done) {
		    debugQueue.next = debugQueue.enQueue(q);
		}
		return done;
	}

    private static void nextLine() throws IOException {
        input_line = inputFile.readLine();
        linepos = 0;
    }

    private static char readChar() {
        while ((input_line.charAt(linepos) == ' ')
        && (input_line.charAt(linepos) == '\t'))
            linepos++;
        char c = input_line.charAt(linepos);
        if (linepos < input_line.length() - 1)
            linepos++;
        return c;
    }

    private static int readInt() {
        while ((input_line.charAt(linepos) == ' ')
        || (input_line.charAt(linepos) == '\t'))
            linepos++;
        int fpos = linepos;
        while ((linepos < input_line.length())
        && (input_line.charAt(linepos) != ' ')
        && (input_line.charAt(linepos) != '\t'))
            linepos++;
        int n = Integer.parseInt(input_line.substring(fpos, linepos));
        return n;
    }

    public boolean ok(int x, int y) {
        // checks that point is actually within the bounds
        // of grid array
        return (x > 0 && x < GRID_SIZE - 1 && y > 0 && y < GRID_SIZE - 1);
    }

    public boolean expandFromTo(int x, int y, int xGoal, int yGoal,
            int num, int tempg[][][], Grid grid) {
        // this method should use Lee's expansion algorithm from
        // coordinate (x,y) to (xGoal, yGoal) for the num iterations
        // it should return true if the goal is found and false if it is not
        // reached within the number of iterations allowed.

        // g[xGoal][yGoal][0] = EMPTY; // set goal as empty
        // g[xGoal][yGoal][1] = EMPTY; // set goal as empty
        ArrayList<Frontier> front = new ArrayList<Frontier>();
        ArrayList<Frontier> tmp_front = new ArrayList<Frontier>();
        tempg[x][y][0] = 1; // set grid (x,y) as 1
        tempg[x][y][1] = 1; // set grid (x,y) as 1
        boolean trace1 = false;
        front.add(new Frontier(x, y, 0, 0));
        front.add(new Frontier(x, y, 1, 0)); // we can start from either
        // side
        if(DEBUG) System.out.println("Expanding " + x + " " + y + " " + xGoal + " "
                + yGoal);
        int extra_iterations = 50;
        boolean reached0 = false;
        boolean reached1 = false;
        while (!front.isEmpty()) {
            while (!front.isEmpty()) {
                int weight, prev_val;
                Frontier f = (Frontier) front.get(0);
                front.remove(0);
                if (f.dw > 0) {
                    tmp_front.add(new Frontier(f.x, f.y, f.z, f.dw - 1));
                } else {
                    if (trace1)
                        if(DEBUG)
                            System.out.println("X " + f.x + " Y " + f.y + " Z "
                                    + f.z + " DW " + f.dw + " processing - val "
                                    + tempg[f.x][f.y][f.z]);
//					int dir_weight = 1;
                    weight = grid.getPoint(f.x,f.y + 1,f.z) + 1;
                    prev_val = tempg[f.x][f.y + 1][f.z];
                    boolean reached = (f.x == xGoal) && (f.y + 1 == yGoal);
                    if ((prev_val > tempg[f.x][f.y][f.z] + weight)
                    && (weight < OCC) || reached) {
                        if (ok(f.x, f.y + 1)) {
                            tempg[f.x][f.y + 1][f.z] = tempg[f.x][f.y][f.z]
                                    + weight; // looking north
                            if (!reached)
                                tmp_front.add(new Frontier(f.x, f.y + 1,
                                        f.z, 0));
                        }
                    }
                    weight = grid.getPoint(f.x + 1,f.y,f.z) + 1;
                    prev_val = tempg[f.x + 1][f.y][f.z];
                    reached = (f.x + 1 == xGoal) && (f.y == yGoal);
                    if ((prev_val > tempg[f.x][f.y][f.z] + weight)
                    && (weight < OCC) || reached) {
                        if (ok(f.x + 1, f.y)) {
                            tempg[f.x + 1][f.y][f.z] = tempg[f.x][f.y][f.z]
                                    + weight; // looking east
                            if (!reached)
                                tmp_front.add(new Frontier(f.x + 1, f.y,
                                        f.z, 0));
                        }
                    }
                    weight = grid.getPoint(f.x,f.y - 1,f.z) + 1;
                    prev_val = tempg[f.x][f.y - 1][f.z];
                    reached = (f.x == xGoal) && (f.y - 1 == yGoal);
                    if ((prev_val > tempg[f.x][f.y][f.z] + weight)
                    && (weight < OCC) || reached) {
                        if (ok(f.x, f.y - 1)) {
                            tempg[f.x][f.y - 1][f.z] = tempg[f.x][f.y][f.z]
                                    + weight; // looking south
                            if (!reached)
                                tmp_front.add(new Frontier(f.x, f.y - 1,
                                        f.z, 0));
                        }
                    }
                    weight = grid.getPoint(f.x - 1,f.y,f.z) + 1;
                    prev_val = tempg[f.x - 1][f.y][f.z];
                    reached = (f.x - 1 == xGoal) && (f.y == yGoal);
                    if ((prev_val > tempg[f.x][f.y][f.z] + weight)
                    && (weight < OCC) || reached) {
                        if (ok(f.x - 1, f.y)) {
                            tempg[f.x - 1][f.y][f.z] = tempg[f.x][f.y][f.z]
                                    + weight; // looking west
                            if (!reached)
                                tmp_front.add(new Frontier(f.x - 1, f.y,
                                        f.z, 0));
                        }
                    }
                    if (f.z == 0) {
                        weight = grid.getPoint(f.x,f.y,1) + 1;
                        if ((tempg[f.x][f.y][1] > tempg[f.x][f.y][0])
                        && (weight < OCC)) {
                            tempg[f.x][f.y][1] = tempg[f.x][f.y][0];
                            tmp_front.add(new Frontier(f.x, f.y, 1, 0));
                        }
                    } else {
                        weight = grid.getPoint(f.x,f.y,0) + 1;
                        if ((tempg[f.x][f.y][0] > tempg[f.x][f.y][1])
                        && (weight < OCC)) {
                            tempg[f.x][f.y][0] = tempg[f.x][f.y][1];
                            tmp_front.add(new Frontier(f.x, f.y, 0, 0));
                        }
                    }
                    // must check if found goal, if so return TRUE
                    reached0 = tempg[xGoal][yGoal][0] != TEMP_EMPTY;
                    reached1 = tempg[xGoal][yGoal][1] != TEMP_EMPTY;
                    if ((reached0 && !reached1) || (!reached0 && reached1))
                        extra_iterations = 100;
                    if ((extra_iterations == 0) && (reached0 || reached1)
                    || (reached0 && reached1)) {
                        return true; // if (xGoal, yGoal) can be found in
                        // time
                    } else
                        extra_iterations--;
                }
            }
            ArrayList<Frontier> tf;
            tf = front;
            front = tmp_front;
            tmp_front = tf;
        }
//		 view.pad(x,y,red);
//		 view.pad(xGoal,yGoal,red);
        return false;
    }

    private boolean pathFromOtherSide(int[][][] g, int X, int Y, int Z) {
        boolean ok;
        int Zo;
        Zo = 1 - Z; // other side
        int sqval = g[X][Y][Zo];
        if ((sqval == VIA) || (sqval == BVIA))
            return false;
        ok = (g[X][Y][Zo] <= g[X][Y][Z]);
        if (ok)
            ok = (g[X - 1][Y][Zo] < sqval) || (g[X + 1][Y][Zo] < sqval)
            || (g[X][Y - 1][Zo] < sqval) || (g[X][Y + 1][Zo] < sqval);
        return ok;
    }

    private int tlength(int x1, int y1, int x2, int y2) {
        int sq = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
        return (int) Math.sqrt((double) sq);
    }

//	private static int ratio(int x1, int y1, int x2, int y2) {
//		int xdiff = x2 - x1;
//		int ydiff = y2 - y1;
//		if (xdiff < 0)
//			xdiff = -xdiff;
//		if (ydiff < 0)
//			ydiff = -ydiff;
//		if (xdiff > ydiff) {
//			if (ydiff == 0)
//				return 100000;
//			else
//				return xdiff / ydiff;
//		} else {
//			if (xdiff == 0)
//				return 100000;
//			else
//				return ydiff / xdiff;
//		}
//	}

    private static int deviation(int x1, int y1, int x2, int y2) {
        int xdiff = x2 - x1;
        int ydiff = y2 - y1;
        if (xdiff < 0)
            xdiff = -xdiff;
        if (ydiff < 0)
            ydiff = -ydiff;
        if (xdiff < ydiff)
            return xdiff;
        else
            return ydiff;
    }

    public void backtrackFrom(int xGoal, int yGoal, int xStart,
            int yStart, int trackNo, int[][][] tempg, Grid grid) {
        // this method should backtrack from the goal position (xGoal, yGoal)
        // back to the starting position (xStart, yStart) filling in the
        // grid array g with the specified track number trackNo ( + TRACK).

        // ***
        // CurrentPos = Goal
        // Loop
        // Find dir to start back from current position
        // Loop
        // Keep going in current dir and Fill in track (update currentPos)
        // Until box number increases in this current dir
        // Until back at starting point
        // ***
//		int count = 100;
        if(DEBUG)System.out.println("Track " + trackNo + " backtrack " + "Length "
                + tlength(xStart, yStart, xGoal, yGoal));
//		boolean trace = false;
        int zGoal;
        int distsofar = 0;
        if (Math.abs(xGoal - xStart) > Math.abs(yGoal - yStart))
            zGoal = 0;
        else
            zGoal = 1;
        if (tempg[xGoal][yGoal][zGoal] == TEMP_EMPTY) {
            if(DEBUG) System.out.println("Preferred Layer not reached " + zGoal);
            zGoal = 1 - zGoal;
        }
        int tempY = yGoal;
        int tempX = xGoal;
        int tempZ = zGoal;
        int lastdir = -10;
        while ((tempX != xStart) || (tempY != yStart)) { // PDL: until back

            // at starting point
            boolean advanced = false;
            int mind = 0;
            int dir = 0;
            int min_square = 100000;
            int d;
            for (d = 0; d < 4; d++) { // PDL: Find dir to start back from
                // current position
                if ((tempg[tempX + dx[tempZ][d]][tempY + dy[tempZ][d]][tempZ] < tempg[tempX][tempY][tempZ])
                && (tempg[tempX + dx[tempZ][d]][tempY + dy[tempZ][d]][tempZ] != TEMP_EMPTY)) {
                    if (tempg[tempX + dx[tempZ][d]][tempY + dy[tempZ][d]][tempZ] < min_square) {
                        min_square = tempg[tempX + dx[tempZ][d]][tempY
                                + dy[tempZ][d]][tempZ];
                        mind = d;
                        dir = dx[tempZ][d] * 2 + dy[tempZ][d]; // hashed dir
                        if (lastdir < -2)
                            lastdir = dir;
                        advanced = true;
                    }
                }
            }
            if (advanced)
                distsofar++;
            if(DEBUG)
                System.out.println("Backtracking "+tempX+" "+tempY+" "+tempZ+
                        " "+tempg[tempX][tempY][tempZ]+" "+advanced+" "+mind);
            if (pathFromOtherSide(tempg, tempX, tempY, tempZ)
            && ((mind > 1)
            && // not preferred dir for this layer
                    (distsofar > 15)
                    && (tlength(tempX, tempY, xStart, yStart) > 15) ||
                    // (deviation(tempX,tempY,xStart,yStart) > 3) ||
                    (!advanced && ((grid.getPoint(tempX,tempY,tempZ) != VIA)
                    && (grid.getPoint(tempX,tempY,tempZ) != BVIA))))) {
                int tZ = 1 - tempZ; // 0 if 1, 1 if 0
                int viat;
                if (advanced)
                    viat = VIA;
                else
                    viat = BVIA; // BVIA is nowhere else to go
                // mark via
                tempg[tempX][tempY][tempZ] = viat;
                grid.setPoint(tempX,tempY,tempZ,viat);
                if(DEBUG)grid.setDebugPoint(tempX,tempY,tempZ,trackNo);
                tempZ = tZ;
                // and the other side
                tempg[tempX][tempY][tempZ] = viat;
                grid.setPoint(tempX,tempY,tempZ,viat);
                if(DEBUG)grid.setDebugPoint(tempX,tempY,tempZ,trackNo);
                num_vias++;
                if (!advanced)
                    forced_vias++;
                if (advanced)
                    if(DEBUG)
                        System.out.println("Via " + distsofar + " "
                                + tlength(tempX, tempY, xStart, yStart) + " "
                                + deviation(tempX, tempY, xStart, yStart));
                distsofar = 0;
            } else {
                if (grid.getPoint(tempX,tempY,tempZ) < OCC) {
                    // PDL: fill in track unless connection point
                    grid.setPoint(tempX,tempY,tempZ,TRACK);
                    if(DEBUG)grid.setDebugPoint(tempX,tempY,tempZ,trackNo);
                } else if (grid.getPoint(tempX,tempY,tempZ) == OCC) {
                    if(DEBUG)grid.setDebugPoint(tempX,tempY,tempZ,OCC);
                    if(DEBUG)grid.setDebugPoint(tempX,tempY,1-tempZ,OCC);
                }
                tempX = tempX + dx[tempZ][mind]; // PDL: updating current
                // position on x axis
                tempY = tempY + dy[tempZ][mind]; // PDL: updating current
                // position on y axis
            }
            lastdir = dir;
        }
        if(DEBUG) System.out.println("Track " + trackNo + " completed");
    }

    public boolean connect(int xs, int ys, int xg, int yg, int netNo, int[][][] tempg,
            Grid grid) {
        // calls expandFrom and backtrackFrom to create connection
        // This is the only real change needed to make the program
        // transactional.
        // Instead of using the grid 'in place' to do the expansion, we take a
        // copy
        // but the backtrack writes to the original grid.
        // This is not a correctness issue. The transactions would still
        // complete eventually without it.
        // However the expansion writes are only temporary and do not logically
        // conflict.
        // There is a question as to whether a copy is really necessary as a
        // transaction will anyway create
        // its own copy. if we were then to distinguish between writes not to be
        // committed (expansion) and
        // those to be committed (backtrack), we would not need an explicit
        // copy.
        // Taking the copy is not really a computational(time) overhead because
        // it avoids the grid 'reset' phase
        // needed if we do the expansion in place.
        for (int x = 0; x < GRID_SIZE; x++) {
            for (int y = 0; y < GRID_SIZE; y++) {
                for (int z = 0; z < 2; z++)
                    tempg[x][y][z] = TEMP_EMPTY;
            }
        }
        // call the expansion method to return found/not found boolean
        boolean found = expandFromTo(xs, ys, xg, yg, GRID_SIZE * 5, tempg, grid);
        if (found) {
            if(DEBUG) System.out.println("Target (" + xg + ", " + yg + ")... FOUND!");
            backtrackFrom(xg, yg, xs, ys, netNo, tempg, grid); // call the
            // backtrack method
        } // print outcome of expansion method
        else {
            if(DEBUG) System.out.println("Failed to route " + xs + " " + ys + " to " + xg
                    + "  " + yg);
            failures++;
        }
        if(DEBUG) {
            dispGrid(grid, 0); // print the grid to screen
            dispGrid(grid, 1); // print the grid to screen
            view.repaint();
        }
        return found;
    }

    public void dispGrid(Grid g, int z) {
        int laycol;
        if (z==0) laycol = magenta; else laycol=green;
        for (int y = GRID_SIZE-1; y>=0; y--) {
            for (int x = 0; x<GRID_SIZE; x++) {
                int gg = g.getPoint(x, y, z);
                if (gg==OCC) { view.point(x,y,cyan); continue; }
                if (gg==VIA) { view.point(x,y,yellow); continue; }
                if (gg==BVIA) { view.point(x,y,red); continue; }
                if (gg==TRACK) {view.point(x,y,laycol); continue; } //
            }
        }
    }

    public LeeThread createThread() {
        return createThread(0);
    }
    public LeeThread createThread(int which) {
        try {
            LeeThread leeThread = new LeeThread(this);
            return leeThread;
        } catch (Exception e) {
            e.printStackTrace(System.out);
            return null;
        }
    }

    public void report() {
        //Open GUI view of PCB
        //view.display();
        //Print the PCB in ASCII, output to file
        //grid.printLayout(true);
        System.out.println("Total Tracks " + netNo + " Failures " + failures
                + " Vias " + num_vias + " Forced Vias " + forced_vias);
    }

    public void sanityCheck() {
        int found = 0, missing = 0;
        // Check debugGrid that the routes in debugQueue have been laid
        if(DEBUG) {
            System.out.println("DEBUG: Starting sanity check");
            while(debugQueue.next!=null) {
                WorkQueue n = debugQueue.deQueue();
                if(!grid.findTrack(n.x1, n.y1, n.x2, n.y2, n.nn)) {
                    System.out.println("ERROR: Missing track " +n.nn);
                    missing++;
                } else {
                    found++;
                }
            }
            System.out.println("DEBUG: found "+found+" missing "+missing);
        }

    }

    public static void xmlReport(Document doc) {
        Element root = doc.getDocumentElement();
        Element element = doc.createElement("BenchmarkSpecific");
        root.appendChild(element);

        Element total = doc.createElement("Tracks");
        total.setTextContent("0");
        element.appendChild(total);

        Element tracks = doc.createElement("Laid");
        tracks.setTextContent("0");
        element.appendChild(tracks);

        Element subnode = doc.createElement("Failures");
        subnode.setTextContent("0");
        element.appendChild(subnode);
    }

    public static void main(String [] args) {
        if(args.length!=2) {
            System.out.println("Params: [numthreads] [input-file]");
            System.exit(-1);
        }
        int numThreads = Integer.parseInt(args[0]);
        String filename = args[1];
        LeeRouterDeuceSTM lr = new LeeRouterDeuceSTM(filename, false, false, false);

        int numMillis = 600000;

//		 Set up the benchmark
        long startTime = 0;
        long currentTime = 0;
        long lastSample = 0;
        long maxSampleThreshold = MAX_SAMPLE_THRESHOLD;
        boolean waitingForSample = false;
        long watchdogInterval = 1000;
        boolean exitByTimeout = false;
        int sampleInterval = 10000;

        if (XML_REPORT) {
            XMLHelper.initializeXMLReport(numThreads, 100, sampleInterval, "0", "leeroutercoarse","0");
        } else {
           // System.out.println("Benchmark: " + benchmarkClassName);
           // System.out.println("Adapter: " + adapterClassName);
           // System.out.println("Contention manager: " + managerClassName);
           // System.out.println("Threads: " + numThreads);
           // System.out.println("Mix: " + experiment + "% updates");
        }

        LeeThread[] thread = new LeeThread[numThreads];

        try {
            for (int i = 0; i < numThreads; i++)
                thread[i] = lr.createThread();
            startTime = System.currentTimeMillis();
            lastSample = startTime;
            for (int i = 0; i < numThreads; i++)
                thread[i].start();
            currentTime = System.currentTimeMillis();
            exitByTimeout = monitorBenchmarkToEnd(numMillis, sampleInterval, startTime, currentTime, lastSample, maxSampleThreshold, watchdogInterval, exitByTimeout, waitingForSample, thread);

            LeeThread.stop = true; // notify threads to stop
            for (int i = 0; i < numThreads; i++) {
                thread[i].join();
            }
        } catch (Exception e) {
            e.printStackTrace(System.out);
            System.exit(0);
        }
        long elapsedTime = startTime - currentTime;
       // int throughput = (int) (LeeRouter.netNo / elapsedTime);
        System.out.println("Numthreads: " + numThreads);
        //System.out.println("Throughput:  " + throughput);
        System.out.println("ElapsedTime: " + elapsedTime);
        lr.report(startTime,exitByTimeout,true);
        lr.sanityCheck();
    }

    private static boolean monitorBenchmarkToEnd(int numMillis, int sampleInterval, long startTime, long currentTime, long lastSample, long maxSampleThreshold, long watchdogInterval, boolean exitByTimeout, boolean waitingForSample, LeeThread[] thread) throws InterruptedException {
        while (!exitByTimeout) {
            boolean exit = true;
            Thread.sleep(watchdogInterval);

            // Any threads with work left?
            for (LeeThread i : thread)
                if (i.finished != true) {
                exit = false;
                break;
                }
            if (!exit)
                currentTime = System.currentTimeMillis();
            else
                break;

            // Timeout?
            if (currentTime - startTime > numMillis) {
                exitByTimeout = true;
            }

            // Sample?
            // Warning: watchdogInterval should remain
            // short to prevent this figures going sloppy
            if (currentTime - lastSample > sampleInterval && !waitingForSample) {
                waitingForSample = true;
                for (LeeThread t : thread) {
                    t.resetMyStatistics();
                    t.doneSample = false;
                    t.sampleNow = true;
                }
            }
            // Get results from all threads
            // Note: avoiding synchronisation (costs), hence
            // poor method of waiting for sample updates from threads
            // and hoping they are done by the time we go to check
            if(waitingForSample) {
                boolean statsUpdated = true;
                for (LeeThread t : thread) {
                    if(!t.finished && !t.doneSample) {
                        statsUpdated = false;
                        break;
                    }
                }

                if(statsUpdated || currentTime - lastSample > maxSampleThreshold) {
                    waitingForSample = false;
                    lastSample = currentTime;
                    double elapsed = (double) (lastSample - startTime) / 1000.0;
                    obtainStats(thread, elapsed, XML_REPORT);
                }
            }
        }
        return exitByTimeout;
    }

    private static void report( long startTime,
            boolean timeout, boolean xmlreport) {

        long stopTime = System.currentTimeMillis();
        double elapsed = (double) (stopTime - startTime) / 1000.0;
        if (xmlreport) {
            XMLHelper.generateXMLReportSummary(timeout, xmlreport, elapsed);

        } else {

            //benchmark.report();
            System.out.println("Elapsed time: " + elapsed + " seconds.");
            System.out.println("----------------------------------------");
        }
    }

    public int getGridSize() {
    	return GRID_SIZE;
    }

    static void obtainStats(LeeThread[] thread, double time, boolean xmlreport) {
        //long commits = 0;
        //long transactions = 0;
        //long commitMemRefs = 0;
        //long totalMemRefs = 0;
        long laidTracks=0;
        //long totalTracks=0;
        String hardware = null;
        boolean finalStats = false;

        if (thread == null) {
            // This means we are going to exit
            finalStats = true;
            laidTracks=LeeThread.totalLaidTracks;
        } else {
            for (LeeThread t : thread) {
                //commits += t.myCommits;
                //transactions += t.myTransactions;
                //commitMemRefs += t.myCommitMemRefs;
                //totalMemRefs += t.myTotalMemRefs;
                hardware = t.hardware;
                laidTracks +=t.myLaidTracks;
                if (hardware == null)
                    hardware = "";
            }
        }

      //  if (xmlreport) {
            XMLHelper.generateXMLIntervalSample(time,laidTracks,0,0,0,hardware,finalStats);//generateXMLIntervalSampleCoarse(time,laidTracks, hardware, finalStats);
       // } else {
           // System.out.println("Timestamp: " + time);
           // if (transactions > 0) {
               // System.out.println("Committed: " + commits);
               // System.out.println("Total transactions: " + transactions);
               // System.out.println("Percent committed: " + (100 * commits)
               // / transactions);
               // System.out.println("Commit MemRefs: " + commitMemRefs);
          //      System.out.println("Total MemRefs " + totalMemRefs);
          //      System.out.println("laidTracks " + laidTracks);
           // } else {
           //     System.out.println("No transactions executed!");
           // }
       // }
    }
}


text:
<!DOCTYPE compass-core-mapping PUBLIC
    "-//Compass/Compass Core Mapping DTD 2.2//EN"
    "http://www.compass-project.org/dtd/compass-core-mapping-2.2.dtd">

<compass-core-mapping package="org.compass.core.test.indexmanager">

    <class name="A" alias="a1">

        <id name="id" />

        <property name="value">
            <meta-data term-vector="positions_offsets">mvalue1</meta-data>
        </property>

    </class>

    <class name="A" alias="a2">

        <id name="id" />

        <property name="value">
            <meta-data term-vector="positions_offsets">mvalue1</meta-data>
        </property>

    </class>

</compass-core-mapping>


text:
<?php

namespace NAD\CartBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

/**
 * NAD cart management bundle. Contains cart entity and API controller which communicative by JSON
 *
 * @author Mohammadreza Razzaghi <razzaghi229@gmail.com>
 */
class NADCartBundle extends Bundle
{
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:id="@+id/root"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <AutoCompleteTextView
        android:id="@+id/editTextMoviesSearch"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="@dimen/large_padding"
        android:layout_marginRight="@dimen/large_padding"
        android:paddingRight="48dp"
        android:layout_marginTop="@dimen/default_padding"
        android:layout_marginBottom="@dimen/inline_padding"
        android:hint="@string/movies_search_hint" />

    <ImageButton
        android:id="@+id/imageButtonClearSearch"
        android:layout_width="44dp"
        android:layout_height="44dp"
        android:layout_alignRight="@+id/editTextMoviesSearch"
        android:layout_marginTop="@dimen/inline_padding"
        android:background="?custom_list_selector"
        android:contentDescription="@string/clear"
        android:src="?attr/drawableCancel" />

    <TextView
        android:id="@+id/emptyViewMovieSearch"
        android:layout_width="@dimen/empty_view_width"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:drawableTop="?attr/drawableArrowUp"
        android:padding="10dp"
        android:text="@string/movies_empty"
        android:textAppearance="@style/TextAppearance.Light"
        android:visibility="gone" />

    <include
        layout="@layout/grid_movies"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/editTextMoviesSearch" />

    <TextView
        android:id="@+id/poweredby"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:background="@color/protection_dark"
        android:padding="@dimen/default_padding"
        android:text="@string/powered_by_tmdb"
        android:textAppearance="@style/TextAppearance.Caption.Narrow"
        android:textColor="@color/black_11" />

</RelativeLayout>


text:
layout: post
date: 2018-02-12
title: "Camille La Vie Two Piece Brocade Dress Sleeveless Short/Mini Aline/Princess"
category: Camille La Vie
tags: [Camille La Vie,Aline/Princess ,Sweetheart,Short/Mini,Sleeveless]
---
### Camille La Vie Two Piece Brocade Dress
Just **$289.99**
###   Sleeveless Short/Mini Aline/Princess

BRANDS	Camille La Vie

Silhouette	Aline/Princess

Neckline	Sweetheart

Hemline/Train	Short/Mini

Sleeve	Sleeveless

Buy it: [https://www.readybrides.com/en/camille-la-vie/10132-camille-la-vie-two-piece-brocade-dress.html](https://www.readybrides.com/en/camille-la-vie/10132-camille-la-vie-two-piece-brocade-dress.html)


text:
package edu.mit.spacenet.io.gson;

public class Element {
	public int id;
	public String name;

	public static Element createFrom(edu.mit.spacenet.domain.element.I_Element element) {
		if(element == null) {
			return null; // from mission-level demand model
		}
		Element e = new Element();
		e.id = element.getUid();
		e.name = element.getName();
		return e;
	}
}


text:
function [obj] = ft_convert_coordsys(obj, target, opt, template)

% FT_CONVERT_COORDSYS changes the coordinate system of the input object to
% the specified coordinate system. The coordinate system of the input
% object is determined from the structure field object.coordsys, or need to
% be determined interactively by the user.
%
% Use as
%   [object] = ft_convert_coordsys(object)
% to only determine the coordinate system, or
%   [object] = ft_convert_coordsys(object, target)
%   [object] = ft_convert_coordsys(object, target, opt)
%   [object] = ft_convert_coordsys(object, target, opt, template);
% to determine and convert the coordinate system.
%
% The optional input argument opt determines the behavior when converting
% to the spm coordinate system.
%
% The following input objects are supported
%   anatomical mri, see FT_READ_MRI
%   anatomical or functional atlas, see FT_PREPARE_ATLAS
%   (not yet) electrode definition
%   (not yet) gradiometer array definition
%   (not yet) volume conductor definition
%   (not yet) dipole grid definition
%
% Possible target coordinate systems are 'spm'.
%
% Note that the conversion will be an automatic one, which means that it
% will be an approximate conversion, not taking into account differences in
% individual anatomies/differences in conventions where to put the
% fiducials.
%
% See also FT_DETERMINE_COORDSYS

% Copyright (C) 2005-2011, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
%    FieldTrip 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 3 of the License, or
%    (at your option) any later version.
%
%    FieldTrip is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_convert_coordsys.m 7220 2012-12-18 08:40:18Z jansch $

if ~isfield(obj, 'coordsys') || isempty(obj.coordsys)
  % determine the coordinate system of the input object
  obj = ft_determine_coordsys(obj, 'interactive', 'yes');
end

% set default behavior to use an approximate alignment, followed by a call
% to spm_normalise for a better quality alignment
if nargin<3
  opt = 2;
end

if isdeployed && (opt==1 || opt==2)
  needtemplate = true;
else
  needtemplate = false;
end

if needtemplate && nargin<4
  error('you need to specify a template filename for the coregistration');
end

hastemplate = nargin>3;

if nargin>1 && ~strcmpi(target, obj.coordsys)
  % convert to the desired coordinate system
  switch target
    case {'spm' 'mni' 'tal'}
      switch obj.coordsys
        case {'ctf' 'bti' '4d'}
          fprintf('Converting the coordinate system from %s to %s\n', obj.coordsys, target);
          if hastemplate
            obj = align_ctf2spm(obj, opt, template);
          else
            obj = align_ctf2spm(obj, opt);
          end
        case {'itab' 'neuromag'}
          fprintf('Converting the coordinate system from %s to %s\n', obj.coordsys, target);
          if hastemplate
            obj = align_ctf2spm(obj, opt, template);
          else
            obj = align_itab2spm(obj, opt);
          end
        otherwise
      end %switch obj.coordsys
    otherwise
      error('conversion from %s to %s is not yet supported', obj.coordsys, target);
  end %switch target
end


text:
import time
import ssl
import logging

import irc.client

from django.utils.encoding import smart_text
from django.utils.translation import ugettext_lazy as _
from awx.main.notifications.base import AWXBaseEmailBackend

logger = logging.getLogger('awx.main.notifications.irc_backend')

class IrcBackend(AWXBaseEmailBackend):

    init_parameters = {"server": {"label": "IRC Server Address", "type": "string"},
                       "port": {"label": "IRC Server Port", "type": "int"},
                       "nickname": {"label": "IRC Nick", "type": "string"},
                       "password": {"label": "IRC Server Password", "type": "password"},
                       "use_ssl": {"label": "SSL Connection", "type": "bool"},
                       "targets": {"label": "Destination Channels or Users", "type": "list"}}
    recipient_parameter = "targets"
    sender_parameter = None

    def __init__(self, server, port, nickname, password, use_ssl, fail_silently=False, **kwargs):
        super(IrcBackend, self).__init__(fail_silently=fail_silently)
        self.server = server
        self.port = port
        self.nickname = nickname
        self.password = password if password != "" else None
        self.use_ssl = use_ssl
        self.connection = None

    def open(self):
        if self.connection is not None:
            return False
        if self.use_ssl:
            connection_factory = irc.connection.Factory(wrapper=ssl.wrap_socket)
        else:
            connection_factory = irc.connection.Factory()
        try:
            self.reactor = irc.client.Reactor()
            self.connection = self.reactor.server().connect(
                self.server,
                self.port,
                self.nickname,
                password=self.password,
                connect_factory=connection_factory,
            )
        except irc.client.ServerConnectionError as e:
            logger.error(smart_text(_("Exception connecting to irc server: {}").format(e)))
            if not self.fail_silently:
                raise
        return True

    def close(self):
        if self.connection is None:
            return
        self.connection = None

    def on_connect(self, connection, event):
        for c in self.channels:
            if irc.client.is_channel(c):
                connection.join(c)
            else:
                for m in self.channels[c]:
                    connection.privmsg(c, m.subject)
                self.channels_sent += 1

    def on_join(self, connection, event):
        for m in self.channels[event.target]:
            connection.privmsg(event.target, m.subject)
        self.channels_sent += 1

    def send_messages(self, messages):
        if self.connection is None:
            self.open()
        self.channels = {}
        self.channels_sent = 0
        for m in messages:
            for r in m.recipients():
                if r not in self.channels:
                    self.channels[r] = []
                self.channels[r].append(m)
        self.connection.add_global_handler("welcome", self.on_connect)
        self.connection.add_global_handler("join", self.on_join)
        start_time = time.time()
        process_time = time.time()
        while self.channels_sent < len(self.channels) and (process_time - start_time) < 60:
            self.reactor.process_once(0.1)
            process_time = time.time()
        self.reactor.disconnect_all()
        return self.channels_sent


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Jb. nassau. Ver. Naturk. 23-24: 122 (1870)

#### Original name
Gnomonia pruni Fuckel, 1870

### Remarks
null


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;

namespace Roslyn.Utilities
{
    /// <summary>
    /// Indicates that a code element is performance sensitive under a known scenario.
    /// </summary>
    /// <remarks>
    /// <para>When applying this attribute, only explicitly set the values for properties specifically indicated by the
    /// test/measurement technique described in the associated <see cref="Uri"/>.</para>
    /// </remarks>
    [Conditional("EMIT_CODE_ANALYSIS_ATTRIBUTES")]
    [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)]
    internal sealed class PerformanceSensitiveAttribute : Attribute
    {
        public PerformanceSensitiveAttribute(string uri)
        {
            Uri = uri;
        }

        /// <summary>
        /// Gets the location where the original problem is documented, likely with steps to reproduce the issue and/or
        /// validate performance related to a change in the method.
        /// </summary>
        public string Uri
        {
            get;
        }

        /// <summary>
        /// Gets or sets a description of the constraint imposed by the original performance issue.
        /// </summary>
        /// <remarks>
        /// <para>Constraints are normally specified by other specific properties that allow automated validation of the
        /// constraint. This property supports documenting constraints which cannot be described in terms of other
        /// constraint properties.</para>
        /// </remarks>
        public string Constraint
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets a value indicating whether captures are allowed.
        /// </summary>
        public bool AllowCaptures
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets a value indicating whether enumeration of a generic <see cref="IEnumerable{T}"/> is allowed.
        /// </summary>
        public bool AllowGenericEnumeration
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets a value indicating whether locks are allowed.
        /// </summary>
        public bool AllowLocks
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets a value indicating whether the asynchronous state machine typically completes synchronously.
        /// </summary>
        /// <remarks>
        /// <para>When <see langword="true"/>, validation of this performance constraint typically involves analyzing
        /// the method to ensure synchronous completion of the state machine does not require the allocation of a
        /// <see cref="Task"/>, either through caching the result or by using <see cref="ValueTask{TResult}"/>.</para>
        /// </remarks>
        public bool OftenCompletesSynchronously
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets a value indicating whether this is an entry point to a parallel algorithm.
        /// </summary>
        /// <remarks>
        /// <para>Parallelization APIs and algorithms, e.g. <c>Parallel.ForEach</c>, may be efficient for parallel entry
        /// points (few direct calls but large amounts of iterative work), but are problematic when called inside the
        /// iterations themselves. Performance-sensitive code should avoid the use of heavy parallelization APIs except
        /// for known entry points to the parallel portion of code.</para>
        /// </remarks>
        public bool IsParallelEntry
        {
            get;
            set;
        }
    }
}


text:
namespace Menu.API.Controllers
{
    using System;
    using System.Collections.Generic;
    using Menu.API.Models;
    using Menu.API.Providers;
    using Microsoft.AspNetCore.Mvc;

    [Produces("application/json")]
    [Route("api/v1/[controller]")]
    public class CurrencyController : Controller
    {
        private readonly ICurrencyProvider currencyProvider;

        public CurrencyController(ICurrencyProvider currencyProvider)
        {
            this.currencyProvider = currencyProvider;
        }

        [HttpGet]
        public IEnumerable<Currency> Get()
        {
            return currencyProvider.GetAll();
        }
    }
}


text:
import * as React from 'react';

type Loader = () => Promise<any>;

type ReactComponent<P> = React.ComponentClass<P> | React.SFC<P> | null;

interface IState<P> {
  Component: ReactComponent<P>;
  ErrorComponent: ReactComponent<any>;
  LoadingComponent: ReactComponent<any>;
  failed: boolean;
}

function createLazyContainer<P> (
  loader: Loader,
  loadingComponent?: ReactComponent<{}>,
  errorComponent?: ReactComponent<{}>,
  onLoad?: () => void
) {
  return class extends React.Component<{}, IState<P>> {
    private isComponentMounted: boolean = false;
    public static displayName: string = 'LazyContainer';
    public state: IState<P> = {
        Component: null,
        ErrorComponent: errorComponent || null,
        LoadingComponent: loadingComponent || null,
        failed: false
    };

    public componentWillMount () {
      this.isComponentMounted = true;

      if (!this.state.Component) {
        loader()
          .then(module => module.default || module)
          .then((Component: ReactComponent<P>) => {
            if (this.isComponentMounted) {
              this.setState({ Component }, onLoad);
            }
          }, () => {
            if (this.isComponentMounted) {
              this.setState({ failed: true });
            }
          });
      }
    }

    public componentWillUnmount () {
      this.isComponentMounted = false;
    }

    public render () {
      const { Component, LoadingComponent, ErrorComponent, failed } = this.state;

      if (Component) {
        return (
          <Component {...this.props} />
        );
      }

      if (failed && ErrorComponent) {
        return <ErrorComponent />;
      }

      if (LoadingComponent) {
        return <LoadingComponent />;
      }

      return null;
    }
  };
}

export default createLazyContainer;


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ JIPS - JIPS Image Processing Software
  ~ Copyright (C)  2006 - 2017  Markus Karnik (markus.karnik@gmail.com)
  ~
  ~ This file is licensed to you under the MIT license.
  ~ See the LICENSE file in the project root for more information.
  ~
  -->

<process plugin-version="1.0.0" plugin-api-version="@PLUGIN_API_VERSION@" jips-version="@JIPS_VERSION@">
  <name>maskprocess</name>
  <defaults>
  		<default id="swapRB" value="true" />
		<default id="swapGB" value="false" />
		<default id="swapRG" value="false" />
  </defaults>
  <inputmask>
    <input type="label" translate="false" bounds="0,0,2,1" id="label1">
      <text>Name:</text>
    </input>
    <input type="textfield" translate="false" bounds="2,0,4,1" id="name">
      <text>default</text>
      <length>15</length>
      <inputType>string</inputType>
    </input>
    <input type="label" translate="false" bounds="0,1,6,1" id="label4">
		<text>Choose Direction:</text>
	</input>
	<input type="radiobutton" translate="false" bounds="0,2,3,1" id="swapRB">
		<text>Swap Red/Blue</text>
		<group>bg1</group>
	</input>
	<input type="radiobutton" translate="false" bounds="0,3,3,1" id="swapGB">
		<text>Swap Green/Blue</text>
		<group>bg1</group>
	</input>
	<input type="radiobutton" translate="false" bounds="0,4,3,1" id="swapRG">
		<text>Swap Red/Green</text>
		<group>bg1</group>
	</input>
  </inputmask>
</process>


text:
package de.sulaco.bittorrent.service.intent;

import android.content.Intent;

public class DownloadProgressBroadcast {

    private String torrentFile;
    private int progress;

    public DownloadProgressBroadcast() {
    }

    public static Intent createProgressIntent(String torrentFile, int progress) {
        return new DownloadProgressBroadcast()
                .setTorrentFile(torrentFile)
                .setProgress(progress)
                .createIntent();
    }

    public DownloadProgressBroadcast setTorrentFile(String torrentFile) {
        this.torrentFile = torrentFile;
        return this;
    }

    public DownloadProgressBroadcast setProgress(int progress) {
        this.progress = progress;
        return this;
    }

    public Intent createIntent() {
        if (torrentFile == null) {
            throw new IllegalStateException("torrentFile must not be null");
        }
        if (progress < 0 || progress > 100) {
            throw new IllegalStateException("progress out of range");
        }
        Intent intent = new Intent(BitTorrentIntentConstants.ACTION_BROADCAST_PROGRESS);
        intent.putExtra(BitTorrentIntentConstants.EXTRA_TORRENT_FILE, torrentFile);
        intent.putExtra(BitTorrentIntentConstants.EXTRA_DOWNLOAD_PROGRESS, progress);
        return intent;
    }

}


text: .. include:: ../../roles/chronos/README.rst


text:
(function($) {
    // class $.jqplot.EnhancedPieLegendRenderer
    // Legend renderer which can specify the number of rows and/or columns in the legend
    // Similar to EnhancedLegendRenderer, but for pie charts
    $.jqplot.EnhancedPieLegendRenderer = function(){
        $.jqplot.TableLegendRenderer.call(this);
    };

    $.jqplot.EnhancedPieLegendRenderer.prototype = new $.jqplot.TableLegendRenderer();
    $.jqplot.EnhancedPieLegendRenderer.prototype.constructor = $.jqplot.EnhancedPieLegendRenderer;

    // called with scope of legend.
    $.jqplot.EnhancedPieLegendRenderer.prototype.init = function(options) {
        // prop: numberRows
        // Maximum number of rows in the legend.  0 or null for unlimited.
        this.numberRows = null;
        // prop: numberColumns
        // Maximum number of columns in the legend.  0 or null for unlimited.
        this.numberColumns = null;
        // prop: seriesToggle
        // false to not enable series on/off toggling on the legend.
        // true or a fadein/fadeout speed (number of milliseconds or 'fast', 'normal', 'slow')
        // to enable show/hide of series on click of legend item.
        this.seriesToggle = 'normal';
        // prop: seriesToggleReplot
        // True to replot the chart after toggling series on/off.
        // This will set the series show property to false.
        // This allows for rescaling or other maniplation of chart.
        // Set to an options object (e.g. {resetAxes: true}) for replot options.
        this.seriesToggleReplot = false;
        // prop: disableIEFading
        // true to toggle series with a show/hide method only and not allow fading in/out.
        // This is to overcome poor performance of fade in some versions of IE.
        this.disableIEFading = true;
        // prop: toolTips
        // optional array of toolTip text corresponding to each pie slice
        this.toolTips = [];
        $.extend(true, this, options);

        if (this.seriesToggle) {
            $.jqplot.postDrawHooks.push(postDraw);
        }
    };

    // called with scope of legend
    $.jqplot.EnhancedPieLegendRenderer.prototype.draw = function(offsets, plot) {
        var legend = this;
        if (this.show) {
            var series = this._series;
            var s;
            var ss = 'position:absolute;';
            ss += (this.background) ? 'background:'+this.background+';' : '';
            ss += (this.border) ? 'border:'+this.border+';' : '';
            ss += (this.fontSize) ? 'font-size:'+this.fontSize+';' : '';
            ss += (this.fontFamily) ? 'font-family:'+this.fontFamily+';' : '';
            ss += (this.textColor) ? 'color:'+this.textColor+';' : '';
            ss += (this.marginTop != null) ? 'margin-top:'+this.marginTop+';' : '';
            ss += (this.marginBottom != null) ? 'margin-bottom:'+this.marginBottom+';' : '';
            ss += (this.marginLeft != null) ? 'margin-left:'+this.marginLeft+';' : '';
            ss += (this.marginRight != null) ? 'margin-right:'+this.marginRight+';' : '';
            this._elem = $('

');
            if (this.seriesToggle) {
                this._elem.css('z-index', '3');
            }

            var pad = false,
                reverse = false,
                nr, nc;
            var s = series[0];
            var slen = s.data.length;
            var colorGenerator = new $.jqplot.ColorGenerator(s.seriesColors);

            if (this.numberRows) {
                nr = this.numberRows;
                if (!this.numberColumns){
                    nc = Math.ceil(slen/nr);
                }
                else{
                    nc = this.numberColumns;
                }
            }
            else if (this.numberColumns) {
                nc = this.numberColumns;
                nr = Math.ceil(slen/this.numberColumns);
            }
            else {
                nr = slen;
                nc = 1;
            }

            var i, j, tr, td1, td2, lt, rs, div, div0, div1;
            var idx = 0;
            // check to see if we need to reverse
            for (i=series.length-1; i>=0; i--) {
                if (nc == 1 && series[i]._stack || series[i].renderer.constructor == $.jqplot.BezierCurveRenderer){
                    reverse = true;
                }
            }

            for (i=0; i<nr; i++) {
                tr = $(document.createElement('tr'));
                tr.addClass('jqplot-table-legend');
                if (reverse){
                    tr.prependTo(this._elem);
                }
                else{
                    tr.appendTo(this._elem);
                }
                for (j=0; j<nc; j++) {
                    if (idx < slen){
                        lt = this.labels[idx] || s.data[idx][0].toString();
                        tt = this.toolTips[idx];
                        if (lt) {
                            var color = colorGenerator.next();
                            if (!reverse){
                                if (i>0){
                                    pad = true;
                                }
                                else{
                                    pad = false;
                                }
                            }
                            else{
                                if (i == nr -1){
                                    pad = false;
                                }
                                else{
                                    pad = true;
                                }
                            }
                            rs = (pad) ? this.rowSpacing : '0';

                            td1 = $(document.createElement('td'));
                            td1.addClass('jqplot-table-legend jqplot-table-legend-swatch');
                            td1.css({textAlign: 'center', paddingTop: rs});

                            div0 = $(document.createElement('div'));
                            div0.addClass('jqplot-table-legend-swatch-outline');
                            if (tt !== undefined) {
                                div0.attr("title", tt);
                            }

                            div1 = $(document.createElement('div'));
                            div1.addClass('jqplot-table-legend-swatch');
                            div1.css({backgroundColor: color, borderColor: color});

                            td1.append(div0.append(div1));

                            td2 = $(document.createElement('td'));
                            td2.addClass('jqplot-table-legend jqplot-table-legend-label');
                            td2.css('paddingTop', rs);
                            if (tt !== undefined) {
                                td2.attr("title", tt);
                            }

                            if (this.escapeHtml){
                                td2.text(lt);
                            }
                            else {
                                td2.html(lt);
                            }
                            if (reverse) {
                                if (this.showLabels) {td2.prependTo(tr);}
                                if (this.showSwatches) {td1.prependTo(tr);}
                            }
                            else {
                                if (this.showSwatches) {td1.appendTo(tr);}
                                if (this.showLabels) {td2.appendTo(tr);}
                            }

                            if (this.seriesToggle) {

                                var speed;
                                if (typeof(this.seriesToggle) === 'string' || typeof(this.seriesToggle) === 'number') {
                                    if (!$.jqplot.use_excanvas || !this.disableIEFading) {
                                        speed = this.seriesToggle;
                                    }
                                }
                                if (this.showSwatches) {
                                    td1.bind('click', {series:s, index:idx, speed:speed, plot: plot, replot:this.seriesToggleReplot}, handleToggle);
                                    td1.addClass('jqplot-seriesToggle');
                                }
                                if (this.showLabels)  {
                                    td2.bind('click', {series:s, index:idx, speed:speed, plot: plot, replot:this.seriesToggleReplot}, handleToggle);
                                    td2.addClass('jqplot-seriesToggle');
                                }

                                // for slices that are already hidden, add the hidden class
                                if (s.showSlice[idx] === false && s.showLabel) {
                                    td1.addClass('jqplot-series-hidden');
                                    td2.addClass('jqplot-series-hidden');
                                }
                            }

                            pad = true;
                        }
                    }
                    idx++;
                }

                td1 = td2 = div0 = div1 = null;
            }
        }
        return this._elem;
    };

    var handleToggle = function (ev) {
        var d = ev.data,
            replot = d.replot,
            plot = d.plot,
            idx = d.index;

        d.series.showSlice[idx] = (d.series.showSlice[idx] === false) ? true : false;

        var opts = {};

        if ($.isPlainObject(replot)) {
            $.extend(true, opts, replot);
        }

        plot.replot(opts);
    };

    // called with scope of plot.
    var postDraw = function () {
        if (this.legend.renderer.constructor == $.jqplot.EnhancedPieLegendRenderer && this.legend.seriesToggle) {
            var e = this.legend._elem.detach();
            this.eventCanvas._elem.after(e);
        }
    };
})(jQuery);


text:
Originally published: 2015-10-07 18:02:44
Last updated: 2015-10-07 18:02:46
Author: Vasudev Ram

This recipe shows the basics of how to generate invoices as PDF documents, using xtopdf, a Python toolkit for PDF creation. An example of creating a simple invoice through Python and xtopdf code is shown.

xtopdf is available on Bitbucket at:

https://bitbucket.org/vasudevram/xtopdf

and you can find many links with examples of using xtopdf, how to install it, etc., from this Google search:

https://google.com/search?q=xtopdf

This sub-feed of my blog:

http://jugad2.blogspot.com/search/label/xtopdf

gives access to all my blog posts labelled xtopdf.


text:
import pandas as pd
import json

def get_index_from_sheet(sheet):
    cols_to_use = [
        'Data variable as written on entry form',
        'Excel column header',
        'Data values as written on entry form',
        'Data values to enter into excel',
        'Which forms?',
    ]
    cols_to_join = [
        'Data variable as written on entry form',
        'Unnamed: 1', 'Unnamed: 2', 'Unnamed: 3'
    ]

    def joiner(row):
        bla = [s for s in row if isinstance(s, str) and s]
        return ' - '.join(bla) if bla else row.iloc[0]
    sheet['Data variable as written on entry form'] = sheet[cols_to_join].apply(joiner, axis=1)

    sheet = sheet[cols_to_use].reset_index()
    sheet.columns = ['group', 'form_variable', 'variable', 'form_value', 'value', 'used_on']
    # Drop all the lines with no values in the end of the file.
    sheet.dropna(subset=['value'], inplace=True)
    sheet.fillna(method='pad', inplace=True)
    return sheet

def get_definitions_from_index(index):
    definitions = index.groupby(['form_variable', 'variable']).apply(_grouper)
    definitions = definitions.reset_index(name='type_def')

    # Drop duplicates.
    variable_counts = definitions.variable.value_counts()
    duplicates = list(variable_counts[variable_counts > 1].index)
    if duplicates:
        print('⚠  {} duplicated variables {}'.format(len(duplicates), duplicates))
        print(' ==> Dropping those variables!')
    definitions = definitions.drop_duplicates(subset=['variable'])

    return {
        row.variable: row.type_def
        for (index, row) in definitions.iterrows()
    }

def _get_mandatory_string(title):
    return {
        'title': title,
        'type': 'string',
        'minLength': 1,
    }

def _get_date_definition(title):
    return {
        'title': title,
        'type': 'string',
        'format': 'date'
    }

def _get_number_string_definition(title):
    return {
        'title': title,
        'type': 'number',
    }

def _get_temperature_definition(title):
    return {
        'title': title,
        'type': 'string',
        'pattern': '(\d+(\.\d+)?\w?[CF])|Ø',
    }

def _get_enum_definition(title, form_values, values):
    form_values, values = list(form_values), list(values)
    enum_names = [
        str(name) if name != '[as written]' else values[i]
        for i, name in enumerate(form_values)]
    enum_type = 'optionalEnum' if '[as written]' in values else 'enum'
    return {
        'title': title,
        enum_type: values,
        enum_type + 'Names': enum_names,
        'type': 'string',
    }

def _grouper(g):
    title = str(g.form_variable.iloc[0])
    first_value = str(g.value.iloc[0])
    # Text or notgiven
    if set(g.value) == set(['[as written]', 'Ø']):
        return _get_mandatory_string(title)
    # Name field
    elif len(g.value) == 1 and first_value == '[name]':
        return _get_mandatory_string(title)
    # Date field
    elif 'dd-MMM-yyyy' in list(g.value):
        return _get_date_definition(title)
    # Number fields
    elif '#' in first_value and ':' not in first_value and 'Temperature' not in title:
        return _get_number_string_definition(title)
    # Temperature field
    elif 'Temperature' in title:
        return _get_temperature_definition(title)
    else:
        return _get_enum_definition(title, g.form_value, g.value)

if __name__ == '__main__':
    SHEET_PATH = '/Users/dedan/projects/monkey-db/data/OFI Care Book Data, 27-May.xls'
    OUT_PATH = '/Users/dedan/projects/monkey-db/test/test-forms/definitions.json'
    all_sheets = pd.read_excel(SHEET_PATH, sheetname=None)
    index = get_index_from_sheet(all_sheets['INDEX'])
    definitions = get_definitions_from_index(index)
    with open(OUT_PATH, 'w') as f:
        json.dump(definitions, f, indent=2)


text:
-- Related to https://app.camunda.com/jira/browse/CAM-10341
-- the script is valid for all databases
DELETE FROM ACT_RU_AUTHORIZATION
WHERE USER_ID_ = '*' AND RESOURCE_ID_ = '*';


text:
package com.cloudTop.starshare.been;

import java.util.ArrayList;

/**
 * Created by Administrator on 2017/7/26.
 */

public class StarDanMuNewInfo {

    private ArrayList<PositionsListBean> positionsList;

    public ArrayList<PositionsListBean> getPositionsList() {
        return positionsList;
    }

    public void setPositionsList(ArrayList<PositionsListBean> positionsList) {
        this.positionsList = positionsList;
    }

    public static class PositionsListBean {
        /**
         * trades : {"amount":600,"buySell":1,"handle":-2,"id":234,"openCharge":0,"openPrice":0,"positionId":1659566747246688867,"positionTime":1501061793,"rtAmount":0,"symbol":"10002"}
         * user : {"gender":0,"headUrl":"http://tva2.sinaimg.cn/crop.0.0.180.180.180/71bf6552jw1e8qgp5bmzyj2050050aa8.jpg","nickname":"123","uid":234}
         */

        private TradesBean trades;
        private UserBean user;

        public TradesBean getTrades() {
            return trades;
        }

        public void setTrades(TradesBean trades) {
            this.trades = trades;
        }

        public UserBean getUser() {
            return user;
        }

        public void setUser(UserBean user) {
            this.user = user;
        }

        public static class TradesBean {
            /**
             * amount : 600
             * buySell : 1
             * handle : -2
             * id : 234
             * openCharge : 0
             * openPrice : 0
             * positionId : 1659566747246688867
             * positionTime : 1501061793
             * rtAmount : 0
             * symbol : 10002
             */

            private int amount;
            private int buySell;
            private int handle;
            private long id;
            private float openCharge;
            private float openPrice;
            private long positionId;
            private long positionTime;
            private long rtAmount;
            private String symbol;

            public int getAmount() {
                return amount;
            }

            public void setAmount(int amount) {
                this.amount = amount;
            }

            public int getBuySell() {
                return buySell;
            }

            public void setBuySell(int buySell) {
                this.buySell = buySell;
            }

            public int getHandle() {
                return handle;
            }

            public void setHandle(int handle) {
                this.handle = handle;
            }

            public long getId() {
                return id;
            }

            public void setId(long id) {
                this.id = id;
            }

            public float getOpenCharge() {
                return openCharge;
            }

            public void setOpenCharge(float openCharge) {
                this.openCharge = openCharge;
            }

            public float getOpenPrice() {
                return openPrice;
            }

            public void setOpenPrice(float openPrice) {
                this.openPrice = openPrice;
            }

            public long getPositionId() {
                return positionId;
            }

            public void setPositionId(long positionId) {
                this.positionId = positionId;
            }

            public long getPositionTime() {
                return positionTime;
            }

            public void setPositionTime(long positionTime) {
                this.positionTime = positionTime;
            }

            public long getRtAmount() {
                return rtAmount;
            }

            public void setRtAmount(long rtAmount) {
                this.rtAmount = rtAmount;
            }

            public String getSymbol() {
                return symbol;
            }

            public void setSymbol(String symbol) {
                this.symbol = symbol;
            }
        }

        public static class UserBean {
            /**
             * gender : 0
             * headUrl : http://tva2.sinaimg.cn/crop.0.0.180.180.180/71bf6552jw1e8qgp5bmzyj2050050aa8.jpg
             * nickname : 123
             * uid : 234
             */

            private int gender;
            private String headUrl;
            private String nickname;
            private int uid;

            public int getGender() {
                return gender;
            }

            public void setGender(int gender) {
                this.gender = gender;
            }

            public String getHeadUrl() {
                return headUrl;
            }

            public void setHeadUrl(String headUrl) {
                this.headUrl = headUrl;
            }

            public String getNickname() {
                return nickname;
            }

            public void setNickname(String nickname) {
                this.nickname = nickname;
            }

            public int getUid() {
                return uid;
            }

            public void setUid(int uid) {
                this.uid = uid;
            }
        }
    }
}