text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mbean PUBLIC "-//JBoss//DTD JBOSS XMBEAN 1.1//EN" "http://www.jboss.org/j2ee/dtd/jboss_xmbean_1_1.dtd">

<mbean>
   <description>IAN/SCN SCU Service. Used to notify DICOM peers about available instances for Instance Available Notifications and Study Content Notifications.</description>

   <descriptors>
      <persistence persistPolicy="OnUpdate"/>
      <persistence-manager value="org.jboss.mx.persistence.DelegatingPersistenceManager"/>
   </descriptors>

   <class>org.dcm4chex.archive.dcm.ianscu.IANScuService</class>

   <constructor>
      <description>The default constructor</description>
      <name>IanScuService</name>
   </constructor>

   <attribute access="read-write" getMethod="getNotifiedAETs" setMethod="setNotifiedAETs">
      <description>List of AE titles of notified application entities, separated by \(backslash).
      NONE = do not notify any application entity.
      </description>
      <name>NotifiedAETitles</name>
      <type>java.lang.String</type>
      <descriptors>
         <value value="NONE"/>
      </descriptors>
   </attribute>
   <attribute access="read-write" getMethod="getCallingAET" setMethod="setCallingAET">
      <description>Calling AE title used in the Association Request.
      </description>
      <name>CallingAETitle</name>
      <type>java.lang.String</type>
      <descriptors>
         <value value="PACS_TIANI"/>
      </descriptors>
   </attribute>
   <attribute access="read-write" getMethod="getRetryIntervalls" setMethod="setRetryIntervalls">
      <description>Number and intervals of retries for failed
      Instance Available or Study Content Notification requests.
Format:

Comma separated list of number x interval pairs.

The interval can be specified in seconds (##s),
      minutes (##m), hours (##h) or days (##d).

Example:

5x1m,10x10m means retry a total of 5 times, one minute
      apart for each retry; then retry a total of 10 times, 10 minutes
      apart for each retry.
      </description>
      <name>RetryIntervals</name>
      <type>java.lang.String</type>
      <descriptors>
         <value value="5x1m,12x5m,24x1h,7x1d"/>
      </descriptors>
   </attribute>
   <attribute access="read-write" getMethod="isOfferInstanceAvailableNotification" setMethod="setOfferInstanceAvailableNotification">
      <description>Enable the Offer Instance Available Notification Service in
      the Association Request.
      </description>
      <name>OfferInstanceAvailableNotification</name>
      <type>boolean</type>
      <descriptors>
         <value value="true"/>
      </descriptors>
   </attribute>
   <attribute access="read-write" getMethod="isOfferStudyContentNotification" setMethod="setOfferStudyContentNotification">
      <description>Enable the Offer Basic Study Content Notification Service in
      the Association Request.
      </description>
      <name>OfferStudyContentNotification</name>
      <type>boolean</type>
      <descriptors>
         <value value="true"/>
      </descriptors>
   </attribute>
   <attribute access="read-write" getMethod="isPreferInstanceAvailableNotification" setMethod="setPreferInstanceAvailableNotification">
      <description>Prefer the use of the Instance Available Notification Service if
      the Instance Available Notification and Basic Study Content Notification
      Service is supported by the remote application entity.
      </description>
      <name>PreferInstanceAvailableNotification</name>
      <type>boolean</type>
      <descriptors>
         <value value="true"/>
      </descriptors>
   </attribute>
   <attribute access="read-write" getMethod="getConcurrency" setMethod="setConcurrency">
      <description>Maximum number of concurrent sent notifications.
      </description>
      <name>Concurrency</name>
      <type>int</type>
      <descriptors>
         <value value="1"/>
      </descriptors>
   </attribute>
   <attribute access="read-write" getMethod="getScnPriority" setMethod="setScnPriority">
      <description>Priority used in Basic Study Content Notification Requests.
      0=medium, 1=high, 2=low.
      </description>
      <name>StudyContentNotificationPriority</name>
      <type>int</type>
      <descriptors>
         <value value="0"/>
      </descriptors>
   </attribute>
   <attribute access="read-write" getMethod="getAcTimeout" setMethod="setAcTimeout">
      <description>A-Associate accept timeout in milliseconds. 0 = no timeout.</description>
      <name>AcceptTimeout</name>
      <type>int</type>
      <descriptors>
         <value value="10000"/>
      </descriptors>
   </attribute>
   <attribute access="read-write" getMethod="getDimseTimeout" setMethod="setDimseTimeout">
      <description>DIMSE message timeout in ms. 0 = no timeout.
      </description>
      <name>DIMSETimeout</name>
      <type>int</type>
      <descriptors>
         <value value="60000"/>
      </descriptors>
   </attribute>
   <attribute access="read-write" getMethod="getSoCloseDelay" setMethod="setSoCloseDelay">
      <description>Socket close delay in milliseconds after an A-Release response.
      </description>
      <name>SocketCloseDelay</name>
      <type>int</type>
      <descriptors>
         <value value="50"/>
      </descriptors>
   </attribute>
   <attribute access="read-write" getMethod="getQueueName" setMethod="setQueueName">
      <description>Used internally. Do not modify.

      </description>
      <name>QueueName</name>
      <type>java.lang.String</type>
      <descriptors>
         <value value="IANScu"/>
      </descriptors>
   </attribute>
   <attribute access="read-write" getMethod="getStoreScpServiceName" setMethod="setStoreScpServiceName">
      <description>Used internally. Do not modify.
      </description>
      <name>StoreScpServiceName</name>
      <type>javax.management.ObjectName</type>
      <descriptors>
         <value value="tiani.archive:service=StoreScp"/>
      </descriptors>
   </attribute>
   <attribute access="read-write" getMethod="getFileSystemMgtServiceName" setMethod="setFileSystemMgtServiceName">
      <description>Used internally. Do not modify.
      </description>
      <name>FileSystemMgtServiceName</name>
      <type>javax.management.ObjectName</type>
      <descriptors>
         <value value="tiani.archive:service=FileSystemMgt"/>
      </descriptors>
   </attribute>
   <attribute access="read-write" getMethod="getTLSConfigName" setMethod="setTLSConfigName">
      <description>Used internally - do NOT modify.
      </description>
      <name>TLSConfigName</name>
      <type>javax.management.ObjectName</type>
      <descriptors>
         <value value="tiani.archive:service=TLSConfig"/>
      </descriptors>
   </attribute>
   &defaultAttributes;

   &defaultOperations;

</mbean>


text:
"""
Created on 2013-02-23
:author: Andreas Kaiser (disko)
"""

import os

from setuptools import find_packages
from setuptools import setup

version = '7.2.1dev'

def read(*rnames):
    return open(os.path.join(os.path.dirname(__file__), *rnames)).read()

long_description = (
    read('README.txt')
    + '\n' +
    read('js', 'jquery_file_upload', 'test_jquery_file_upload_plugin.txt')
    + '\n' +
    read('CHANGES.txt'))

setup(
    name='js.jquery_file_upload',
    version=version,
    description="Fanstatic packaging of jQuery File Upload Plugin",
    long_description=long_description,
    classifiers=[],
    keywords='',
    author='Andreas Kaiser',
    author_email='disko@binary-punks.com',
    url='https://github.com/Kotti/js.jquery_file_upload',
    license='BSD',
    packages=find_packages(),
    namespace_packages=['js'],
    include_package_data=True,
    zip_safe=False,
    install_requires=[
        'fanstatic',
        'js.jquery',
        'js.jqueryui',
        'setuptools',
        ],
    entry_points={
        'fanstatic.libraries': [
            'jquery_file_upload_plugin = js.jquery_file_upload:library',
            ],
        },
    )

redpajama_set_name: RedPajamaGithub


text:
title: Open House
author: Ben Weinstein-Raun
date: 2014-06-12
layout: post
---

We'll be having an open house on Sunday, June 22 from 1-7pm. There will be classes on 3D printing, soldering and how to use our equipment! Come see our robot arm and eat hot dogs!

If you've ever been interested in hackerspaces, DIY, or in turning your mad scientist ravings into reality, you don't want to miss this!

Here's our current schedule:
**1 PM:** Meet & Greet Board Members, 3D Printer Demo
**2 PM:** Learn to Solder
**3 PM:** CNC Router Demo, Robot Arm Unveiling and Brainstorm Session
**4 PM:** Learn to Solder, CNC Router Demo
**5 PM:** Dinner -- Dogs on the Grill
**6 PM:** 3D Printer Demo


text:
"""Documentation menu."""

import bits.pyfs
import os
import os.path

created_documentation_cfg = False

def grub_escape(s):
    return "'{}'".format("'\\''".join(s.split("'")))

def create_documentation_cfg():
    global created_documentation_cfg
    if created_documentation_cfg:
        return
    cfg = ""
    docpath = "/boot/Documentation"
    for basename in sorted(os.listdir(docpath)):
        assert '"' not in basename
        assert "'" not in basename
        filename = os.path.join(docpath, basename)
        title = file(filename).readline().strip()
        cfg += 'menuentry {} {{\n'.format(grub_escape("{}: {}".format(basename, title)))
        cfg += """    py 'import ttypager; ttypager.ttypager(file(r"{}").read())'\n""".format(filename)
        cfg += '}\n'
    bits.pyfs.add_static("documentation.cfg", cfg)
    created_documentation_config = True


text:
Advanced App Features
=====================

See ``corehq.apps.app_manager.suite_xml.SuiteGenerator`` and ``corehq.apps.app_manager.xform.XForm`` for code.

Child Modules
-------------
In principle child modules is very simple. Making one module a child of another
simply changes the ``menu`` elements in the *suite.xml* file. For example in the
XML below module ``m1`` is a child of module ``m0`` and so it has its ``root``
attribute set to the ID of its parent.

.. code-block:: xml

    <menu id="m0">
        <text>
            <locale id="modules.m0"/>
        </text>
        <command id="m0-f0"/>
    </menu>
    <menu id="m1" root="m0">
        <text>
            <locale id="modules.m1"/>
        </text>
        <command id="m1-f0"/>
    </menu>

Menu structure
~~~~~~~~~~~~~~
As described above the basic menu structure is quite simple however there is one property in particular
that affects the menu structure: *module.put_in_root*

This property determines whether the forms in a module should be shown under the module's own menu item or
under the parent menu item:

+-------------+-------------------------------------------------+
| put_in_root | Resulting menu                                  |
+=============+=================================================+
| True        | id="<parent menu id>"                           |
+-------------+-------------------------------------------------+
| False       | id="<module menu id>" root="<parent menu id>"   |
+-------------+-------------------------------------------------+

**Notes:**

- If the module has no parent then the parent is *root*.
- *root="root"* is equivalent to excluding the *root* attribute altogether.

Session Variables
~~~~~~~~~~~~~~~~~

This is all good and well until we take into account the way the
`Session <https://github.com/dimagi/commcare/wiki/Suite20#the-session>`_ works on the mobile
which "prioritizes the most relevant piece of information to be determined by the user at any given time".

This means that if all the forms in a module require the same case (actually just the same session IDs) then the
user will be asked to select the case before selecting the form. This is why when you build a module
where *all forms require a case* the case selection happens before the form selection.

From here on we will assume that all forms in a module have the same case management and hence require the same
session variables.

When we add a child module into the mix we need to make sure that the session variables for the child module forms match
those of the parent in two ways, matching session variable names and adding in any missing variables.

Matching session variable names
...............................

For example, consider the session variables for these two modules:

**module A**::

    case_id:            load mother case

**module B** child of module A::

    case_id_mother:     load mother case
    case_id_child:      load child case

You can see that they are both loading a mother case but are using different session variable names.

To fix this we need to adjust the variable name in the child module forms otherwise the user will be asked
to select the mother case again:

    *case_id_mother* -> *case_id*

**module B** final::

    case_id:            load mother case
    case_id_child:      load child case

Inserting missing variables
...........................
In this case imagine our two modules look like this:

**module A**::

    case_id:            load patient case
    case_id_new_visit:  id for new visit case ( uuid() )

**module B** child of module A::

    case_id:            load patient case
    case_id_child:      load child case

Here we can see that both modules load the patient case and that the session IDs match so we don't
have to change anything there.

The problem here is that forms in the parent module also add a ``case_id_new_visit`` variable to the session
which the child module forms do not. So we need to add it in:

**module B** final::

    case_id:            load patient case
    case_id_new_visit:  id for new visit case ( uuid() )
    case_id_child:      load child case

Note that we can only do this for session variables that are automatically computed and
hence does not require user input.

Shadow Modules
--------------

A shadow module is a module that piggybacks on another module's commands (the "source" module). The shadow module has its own name, case list configuration, and case detail configuration, but it uses the same forms as its source module.

This is primarily for clinical workflows, where the case detail is a list of patients and the clinic wishes to be able to view differently-filtered queues of patients that ultimately use the same set of forms.

Shadow modules are behind the feature flag **Shadow Modules**.

Scope
~~~~~

The shadow module has its own independent:

- Name
- Menu mode (display module & forms, or forms only)
- Media (icon, audio)
- Case list configuration (including sorting and filtering)
- Case detail configuration

The shadow module inherits from its source:

- case type
- commands (which forms the module leads to)
- end of form behavior

Limitations
~~~~~~~~~~~

A shadow module can neither **be** a parent module nor **have** a parent module

A shadow module's source can be a parent module (the shadow will include a copy of the children), or have a parent module (the shadow will appear as a child of that same parent)

Shadow modules are designed to be used with case modules. They may behave unpredictably if given an advanced module, reporting module, or careplan module as a source.

Shadow modules do not necessarily behave well when the source module uses custom case tiles. If you experience problems, make the shadow module's case tile configuration exactly matches the source module's.

Entries
~~~~~~~

A shadow module duplicates all of its parent's entries. In the example below, m1 is a shadow of m0, which has one form. This results in two unique entries, one for each module, which share several properties.

.. code-block:: xml

    <entry>
        <form>
            http://openrosa.org/formdesigner/86A707AF-3A76-4B36-95AD-FF1EBFDD58D8
        </form>
        <command id="m0-f0">
            <text>
                <locale id="forms.m0f0"/>
            </text>
        </command>
    </entry>
    <entry>
        <form>
            http://openrosa.org/formdesigner/86A707AF-3A76-4B36-95AD-FF1EBFDD58D8
        </form>
        <command id="m1-f0">
            <text>
                <locale id="forms.m0f0"/>
            </text>
        </command>
    </entry>

Menu structure
~~~~~~~~~~~~~~

In the simplest case, shadow module menus look exactly like other module menus. In the example below, m1 is a shadow of m0. The two modules have their own, unique menu elements.

.. code-block:: xml

    <menu id="m0">
        <text>
            <locale id="modules.m0"/>
        </text>
        <command id="m0-f0"/>
    </menu>
    <menu id="m1">
        <text>
            <locale id="modules.m1"/>
            </text>
        <command id="m1-f0"/>
    </menu>

Menus get more complex when shadow modules are mixed with parent/child modules. In the following example, m0 is a basic module, m1 is a child of m0, and m2 is a shadow of m0. All three modules have `put_in_root=false` (see **Child Modules > Menu structure** above).  The shadow module has its own menu and also a copy of the child module's menu. This copy of the child module's menu is given the id `m1.m2` to distinguish it from `m1`, the original child module menu.

.. code-block:: xml

    <menu id="m0">
        <text>
            <locale id="modules.m0"/>
        </text>
        <command id="m0-f0"/>
    </menu>
    <menu root="m0" id="m1">
        <text>
            <locale id="modules.m1"/>
        </text>
        <command id="m1-f0"/>
    </menu>
    <menu root="m2" id="m1.m2">                                                                                <text>
            <locale id="modules.m1"/>
        </text>                                                                                <command id="m1-f0"/>
    </menu>
    <menu id="m2">                                                                                <text>
            <locale id="modules.m2"/>
        </text>                                                                                <command id="m2-f0"/>
    </menu>


text:
/**
 * @module ol/layer/Heatmap
 */
import {listen} from '../events.js';
import {inherits} from '../index.js';
import BaseObject from '../Object.js';
import {createCanvasContext2D} from '../dom.js';
import VectorLayer from '../layer/Vector.js';
import {clamp} from '../math.js';
import {assign} from '../obj.js';
import RenderEventType from '../render/EventType.js';
import Icon from '../style/Icon.js';
import Style from '../style/Style.js';

/**
 * @enum {string}
 * @private
 */
const Property = {
  BLUR: 'blur',
  GRADIENT: 'gradient',
  RADIUS: 'radius'
};

/**
 * @const
 * @type {Array.<string>}
 */
const DEFAULT_GRADIENT = ['#00f', '#0ff', '#0f0', '#ff0', '#f00'];

/**
 * @classdesc
 * Layer for rendering vector data as a heatmap.
 * Note that any property set in the options is set as a {@link ol.Object}
 * property on the layer object; for example, setting `title: 'My Title'` in the
 * options means that `title` is observable, and has get/set accessors.
 *
 * @constructor
 * @extends {ol.layer.Vector}
 * @fires ol.render.Event
 * @param {olx.layer.HeatmapOptions=} opt_options Options.
 * @api
 */
const Heatmap = function(opt_options) {
  const options = opt_options ? opt_options : {};

  const baseOptions = assign({}, options);

  delete baseOptions.gradient;
  delete baseOptions.radius;
  delete baseOptions.blur;
  delete baseOptions.shadow;
  delete baseOptions.weight;
  VectorLayer.call(this, /** @type {olx.layer.VectorOptions} */ (baseOptions));

  /**
   * @private
   * @type {Uint8ClampedArray}
   */
  this.gradient_ = null;

  /**
   * @private
   * @type {number}
   */
  this.shadow_ = options.shadow !== undefined ? options.shadow : 250;

  /**
   * @private
   * @type {string|undefined}
   */
  this.circleImage_ = undefined;

  /**
   * @private
   * @type {Array.<Array.<ol.style.Style>>}
   */
  this.styleCache_ = null;

  listen(this,
    BaseObject.getChangeEventType(Property.GRADIENT),
    this.handleGradientChanged_, this);

  this.setGradient(options.gradient ? options.gradient : DEFAULT_GRADIENT);

  this.setBlur(options.blur !== undefined ? options.blur : 15);

  this.setRadius(options.radius !== undefined ? options.radius : 8);

  listen(this,
    BaseObject.getChangeEventType(Property.BLUR),
    this.handleStyleChanged_, this);
  listen(this,
    BaseObject.getChangeEventType(Property.RADIUS),
    this.handleStyleChanged_, this);

  this.handleStyleChanged_();

  const weight = options.weight ? options.weight : 'weight';
  let weightFunction;
  if (typeof weight === 'string') {
    weightFunction = function(feature) {
      return feature.get(weight);
    };
  } else {
    weightFunction = weight;
  }

  this.setStyle(function(feature, resolution) {
    const weight = weightFunction(feature);
    const opacity = weight !== undefined ? clamp(weight, 0, 1) : 1;
    // cast to 8 bits
    const index = (255 * opacity) | 0;
    let style = this.styleCache_[index];
    if (!style) {
      style = [
        new Style({
          image: new Icon({
            opacity: opacity,
            src: this.circleImage_
          })
        })
      ];
      this.styleCache_[index] = style;
    }
    return style;
  }.bind(this));

  // For performance reasons, don't sort the features before rendering.
  // The render order is not relevant for a heatmap representation.
  this.setRenderOrder(null);

  listen(this, RenderEventType.RENDER, this.handleRender_, this);
};

inherits(Heatmap, VectorLayer);

/**
 * @param {Array.<string>} colors A list of colored.
 * @return {Uint8ClampedArray} An array.
 * @private
 */
const createGradient = function(colors) {
  const width = 1;
  const height = 256;
  const context = createCanvasContext2D(width, height);

  const gradient = context.createLinearGradient(0, 0, width, height);
  const step = 1 / (colors.length - 1);
  for (let i = 0, ii = colors.length; i < ii; ++i) {
    gradient.addColorStop(i * step, colors[i]);
  }

  context.fillStyle = gradient;
  context.fillRect(0, 0, width, height);

  return context.getImageData(0, 0, width, height).data;
};

/**
 * @return {string} Data URL for a circle.
 * @private
 */
Heatmap.prototype.createCircle_ = function() {
  const radius = this.getRadius();
  const blur = this.getBlur();
  const halfSize = radius + blur + 1;
  const size = 2 * halfSize;
  const context = createCanvasContext2D(size, size);
  context.shadowOffsetX = context.shadowOffsetY = this.shadow_;
  context.shadowBlur = blur;
  context.shadowColor = '#000';
  context.beginPath();
  const center = halfSize - this.shadow_;
  context.arc(center, center, radius, 0, Math.PI * 2, true);
  context.fill();
  return context.canvas.toDataURL();
};

/**
 * Return the blur size in pixels.
 * @return {number} Blur size in pixels.
 * @api
 * @observable
 */
Heatmap.prototype.getBlur = function() {
  return (/** @type {number} */ this.get(Property.BLUR));
};

/**
 * Return the gradient colors as array of strings.
 * @return {Array.<string>} Colors.
 * @api
 * @observable
 */
Heatmap.prototype.getGradient = function() {
  return (/** @type {Array.<string>} */ this.get(Property.GRADIENT));
};

/**
 * Return the size of the radius in pixels.
 * @return {number} Radius size in pixel.
 * @api
 * @observable
 */
Heatmap.prototype.getRadius = function() {
  return (/** @type {number} */ this.get(Property.RADIUS));
};

/**
 * @private
 */
Heatmap.prototype.handleGradientChanged_ = function() {
  this.gradient_ = createGradient(this.getGradient());
};

/**
 * @private
 */
Heatmap.prototype.handleStyleChanged_ = function() {
  this.circleImage_ = this.createCircle_();
  this.styleCache_ = new Array(256);
  this.changed();
};

/**
 * @param {ol.render.Event} event Post compose event
 * @private
 */
Heatmap.prototype.handleRender_ = function(event) {
  const context = event.context;
  const canvas = context.canvas;
  const image = context.getImageData(0, 0, canvas.width, canvas.height);
  const view8 = image.data;
  for (let i = 0, ii = view8.length; i < ii; i += 4) {
    const alpha = view8[i + 3] * 4;
    if (alpha) {
      view8[i] = this.gradient_[alpha];
      view8[i + 1] = this.gradient_[alpha + 1];
      view8[i + 2] = this.gradient_[alpha + 2];
    }
  }
  context.putImageData(image, 0, 0);
};

/**
 * Set the blur size in pixels.
 * @param {number} blur Blur size in pixels.
 * @api
 * @observable
 */
Heatmap.prototype.setBlur = function(blur) {
  this.set(Property.BLUR, blur);
};

/**
 * Set the gradient colors as array of strings.
 * @param {Array.<string>} colors Gradient.
 * @api
 * @observable
 */
Heatmap.prototype.setGradient = function(colors) {
  this.set(Property.GRADIENT, colors);
};

/**
 * Set the size of the radius in pixels.
 * @param {number} radius Radius size in pixel.
 * @api
 * @observable
 */
Heatmap.prototype.setRadius = function(radius) {
  this.set(Property.RADIUS, radius);
};

export default Heatmap;


text:
"""
This file defines the various different objects that can be found in the world
"""

#--------------------------
# This file defines the objects in the world.  Best practice for naming an object follows: <region><Room><Name>, where the region is lowercase and every other word in the smashed string is capitalized
#--------------------------

import os

import World
import Globals

indexList = []
fromFileList = Globals.fromFileList
equipmentFromFile = Globals.equipmentFromFile

fileList = []
eqFileList = []
savedEqFileList = []

for region in Globals.RegionsList:
	directoryFiles = os.listdir('blueprints/obj/'+str(region)+'/')
	eqDirectoryFiles = os.listdir('blueprints/equip/'+str(region)+'/')
	if os.path.exists('data/world/' + str(region) + '/equip/'):
		savedEqFiles = os.listdir('data/world/' + str(region) + '/equip/')
	else:
		savedEqFiles = []
	for obj in directoryFiles:
		path = str(region)+'/'+obj
		fileList.append(path)
	for obj in eqDirectoryFiles:
		path = str(region)+'/'+obj
		eqFileList.append(path)
	for obj in savedEqFiles:
		path = str(region) + '/equip/' + obj
		savedEqFileList.append(path)

def setLocation(location):
	global room
	room = location

def loadSavedEq():
	'''
	loads equipment into rooms from equipment definition files after server restart
	'''
	for region in Globals.regionListDict:
		for room in Globals.regionListDict[region]:
			path='data/world/' + region + '/equip/' + room + '/'
			#shortPath='data/world' + region + '/equip/'

			if os.path.exists(path):
				Globals.regionListDict[region][room].equipment = {}
				dirList = os.listdir(path)
				for eqFile in dirList:
					if not eqFile.endswith('~'):
						newEq = buildEquipmentFromFile(eqFile, path)
						# Globals.regionListDict[region][room].items.append(newEq)

def saveEq():
	'''
	handles saving all equipment in the world (but not player equipment) into unique equipment definition files when the server is shutdown
	'''

	for region in Globals.regionListDict:
		for room in Globals.regionListDict[region]:
			path='data/world/'+region+'/equip/'+room+'/'
			shortPath='data/world/'+region+'/equip/'
			if not os.path.exists(shortPath):
				os.makedirs(shortPath)
			if not os.path.exists(path):
				os.makedirs(path)

			dirList = os.listdir(path)
			for eqFile in dirList:
				print eqFile
				os.remove(path+eqFile)

			for eq in Globals.regionListDict[region][room].equipment:
				saveEqToFile(eq, path)

def saveEqToFile(eq, path):
	'''
	handles saving a single bit of equipment to a unique equipment definition file when the server is shutdown
	'''
	eqType = ''
	if hasattr(eq.kind.equipment, 'weapon'):
		if eq.kind.equipment.weapon != None:
			eqType = 'weapon'
	if hasattr(eq.kind.equipment, 'armor'):
		if eq.kind.equipment.armor != None:
			eqType = 'armor'

	battleCommands = []
	if eq.kind.equipment.battleCommands != [''] and eq.kind.equipment.battleCommands != []:
		for command in eq.kind.equipment.battleCommands:
			battleCommands.append(command)
	if battleCommands == []:
		battleCommands = ''

	itemGrabHandler = 'False'
	if hasattr(eq.kind, 'itemGrabHandler'):
		if eq.kind.itemGrabHandler != None:
			itemGrabHandler = 'True'

	notDroppable = 'False'
	if hasattr(eq.kind, 'itemGrabHandler') and eq.kind.itemGrabHandler != None:
		if eq.kind.itemGrabHandler.notDroppable:
			notDroppable = 'True'

	objectSpawner = 'False'
	if hasattr(eq.kind, 'objectSpawner'):
		if eq.kind.objectSpawner != None:
			objectSpawner = 'True'

	filePath = path + str(eq)
	with open(filePath, 'w') as f:
		f.write('ID=%s\n' %str(eq))
		f.write('currentRoom=%s\n' %(str(eq.currentRoom.region)+ ":" +str(eq.currentRoom.name)))
		f.write('\n')
		f.write('name=%s\n' %eq.name)
		f.write('type=%s\n' %eqType)
		f.write('slot=%s\n' %eq.kind.equipment.slot)
		f.write('\n')
		f.write('durability=%s\n' %eq.kind.equipment.durability)
		f.write('maxDurability=%s\n' %eq.kind.equipment.maxDurability)
		f.write('worth=%s\n' %eq.kind.equipment.worth)
		f.write('\n')
		f.write('description=%s\n' %eq.description)
		f.write('\n')
		f.write('longDescription=%s\n' %eq.longDescription)
		f.write('\n')
		f.write('isVisible=%s\n' %eq.isVisible)
		f.write('\n')
		f.write('hp=%s\n' %eq.kind.equipment.hp)
		f.write('pp=%s\n' %eq.kind.equipment.pp)
		f.write('offense=%s\n' %eq.kind.equipment.offense)
		f.write('defense=%s\n' %eq.kind.equipment.defense)
		f.write('speed=%s\n' %eq.kind.equipment.speed)
		f.write('guts=%s\n' %eq.kind.equipment.guts)
		f.write('luck=%s\n' %eq.kind.equipment.luck)
		f.write('vitality=%s\n' %eq.kind.equipment.vitality)
		f.write('IQ=%s\n' %eq.kind.equipment.IQ)
		f.write('\n')
		f.write('battleCommands=%s\n' %battleCommands)
		f.write('\n')
		f.write('statusEffect=%s\n' %eq.kind.equipment.statusEffect)
		f.write('\n')
		f.write('onUse=%s\n' %eq.kind.equipment.onUse)
		f.write('\n\n')
		f.write('kind.isCarryable=%s\n' %eq.kind.isCarryable)
		f.write('kind.respawns=%s\n' %eq.kind.respawns)
		f.write('\n')
		f.write('kind.itemGrabHandler=%s\n' %itemGrabHandler)
		if itemGrabHandler == 'True':
			f.write('kind.itemGrabHandler.notDroppable=%s\n' %notDroppable)
		f.write('\n')
		f.write('kind.objectSpawner=%s\n' %objectSpawner)
		if objectSpawner == 'True':
			f.write('kind.objectSpawner.time=%s\n' %eq.kind.objectSpawner.time)
			f.write('kind.objectSpawner.spawnOdds=%s\n' %eq.kind.objectSpawner.spawnOdds)
			f.write('kind.objectSpawner.container=%s\n' %eq.kind.objectSpawner.container)
			f.write('kind.objectSpawner.cycles=%s\n' %eq.kind.objectSpawner.cycles)
			f.write('kind.objectSpawner.repeat=%s\n' %eq.kind.objectSpawner.repeat)
			f.write('kind.objectSpawner.active=%s\n' %eq.kind.objectSpawner.active)

def buildObjectFromFile(file):
	'''
	creates an object by constructing it out of details in a file
	'''
	print file

	if str(file).endswith('~'):
		print "\n"
		return

	path = 'blueprints/obj/' + file
	with open(path, 'r') as f:
		fileData = f.readlines()

	newObject = World.Object('none', 'none')

	print fileData

	kind = None
	isCarryable = None
	isVisible = None
	isLocked = False
	respawns = None
	objectSpawner = None
	itemGrabHandler = None
	repeat = None
	time = None
	spawnOdds = None
	container = None
	cycles = None
	repeat = None
	active = None
	notDroppable = None
	objectSpawnerComponent = None
	itemGrabHandlerComponent = None
	itemComponent = None
	mobActive = None
	mobCycles = None
	mobMode = None
	mobSpawnOdds = None
	mobTime = None
	mobFile = None
	mobSpawner = None
	onUse = None

	for Data in fileData:

		if Data.startswith('name='):
			newObject.name = Data[6:-2]
		if Data.startswith('description='):
			newObject.description = Data[13:-2]
		if Data.startswith('longDescription='):
			newObject.longDescription = Data[17:-2]
		if Data.startswith('isVisible='):
			text = Data[10:-1]
			if text == 'True':
				newObject.isVisible = True
			elif text == 'False':
				newObject.isVisible = False

		if Data.startswith('kind='):
			text = Data[5:-1]
			#print "kind:" + text
			if text == 'item':
				kind = 'item'
			elif text == 'container':
				kind = 'container'
		if Data.startswith('kind.isCarryable='):
			text = Data[17:-1]
			#print "isCarryable:" +text
			if text == 'True':
				isCarryable = True
			elif text == 'False':
				isCarryable = False
		if Data.startswith('kind.respawns='):
			text = Data[14:-1]
			if text == 'True':
				respawns = True
			elif text == 'False':
				respawns = False
		if Data.startswith('kind.isLocked='):
			text = Data[14:-1]
			if text == 'True':
				isLocked = True
			if text == 'False':
				isLocked = False
		if Data.startswith('kind.respawnContents='):
			text = Data[21:-1]
			if text == 'True':
				respawnContents = True
			elif text == 'False':
				respawnContents = False

		if Data.startswith('kind.objectSpawner='):
			text = Data[19:-1]
			if text == 'True':
				objectSpawner = True
			elif text == 'False':
				objectSpawner = False
		if Data.startswith('kind.objectSpawner.time='):
			time = int(Data[24:-1])
		if Data.startswith('kind.objectSpawner.spawnOdds='):
			text = Data[29:-1]
			oddsList = text.split(',')
			#print "oddsList:" + str(oddsList)
			nestedOddsList = []
			for odds in oddsList:
				nestedOddsList.append(odds.split(':'))
			for oddsEntry in nestedOddsList:
				oddsEntry[1] = int(oddsEntry[1])
				if oddsEntry[0] == 'True':
					oddsEntry[0] = True
				elif oddsEntry[0] == 'False':
					oddsEntry[0] = False
			#print nestedOddsList
			spawnOdds = nestedOddsList
		if Data.startswith('kind.objectSpawner.container='):
			text = Data[29:-1]
			if text == 'None':
				container = None
			else:
				container = text[1:-1]		# this should be a reference to another object
				container = container.split(', ')
		if Data.startswith('kind.objectSpawner.cycles='):
			cycles = int(Data[26:-1])
		if Data.startswith('kind.objectSpawner.repeat='):
			text = Data[26:-1]
			if text == 'True':
				repeat = True
			elif text == 'False':
				repeat = False
		if Data.startswith('kind.objectSpawner.active='):

			text = Data[26:-1]
			#print "***active:" + text

			if text == 'True':
				active = True
			elif text == 'False':
				active = False

		if Data.startswith('kind.itemGrabHandler='):
			text = Data[21:-1]
			#print "itemGrabHandler:" +text
			if text == 'True':
				itemGrabHandler = True
			elif text == 'False':
				itemGrabHandler = False
		if Data.startswith('kind.itemGrabHandler.notDroppable='):
			text = Data[34:-1]
			#print "*** notDroppabletext:" + text
			if text == 'True':
				notDroppable = True
			elif text == 'False':
				notDroppable = False

		if Data.startswith('kind.onUse='):
			text = Data[11:-1]
			onUse = text

		if Data.startswith('mobSpawner='):
			text = Data[11:-1]
			if text == 'True':
				mobSpawner = True
			elif text == 'False':
				mobSpawner = False
		if Data.startswith('mobSpawner.mobFile='):
			text = Data[19:-1]
			mobFile = text
		if Data.startswith('mobSpawner.time='):
			text = Data[16:-1]
			mobTime = int(text)
		if Data.startswith('mobSpawner.oddsList='):
			text = Data[20:-1]
			oddsList = text.split(',')
			#print "oddsList:" + str(oddsList)
			nestedOddsList = []
			for odds in oddsList:
				nestedOddsList.append(odds.split(':'))
			for oddsEntry in nestedOddsList:
				oddsEntry[1] = int(oddsEntry[1])
				if oddsEntry[0] == 'True':
					oddsEntry[0] = True
				elif oddsEntry[0] == 'False':
					oddsEntry[0] = False
			#print nestedOddsList
			mobSpawnOdds = nestedOddsList
		if Data.startswith('mobSpawner.mode='):
			text = Data[16:-1]
			print "mobModeff:" + text
			mobMode = text
		if Data.startswith('mobSpawner.cycles='):
			text = Data[18:-1]
			mobCycles = int(text)
		if Data.startswith('mobSpawner.active='):
			text = Data[18:-1]
			if text == 'True':
				mobActive = True
			elif text == 'False':
				mobActive = False
	#print kind
	if kind == 'item':
		# print itemGrabHandler
		# print objectSpawnerComponent
		# print isCarryable
		itemComponent = World.item()
		itemComponent.owner = newObject
	if kind == 'container':
		itemComponent = World.container(inventory=[])
		itemComponent.owner = newObject

	if objectSpawner:
		objectSpawnerComponent = World.objectSpawner(itemComponent, Globals.TIMERS, time, newObject, spawnOdds, container, cycles, repeat, active)
	else:
		objectSpawnerComponent = None

	if itemGrabHandler:
		itemGrabHandlerComponent = World.itemGrabHandler(notDroppable)
	else:
		itemGrabHandlerComponent = None

	if mobSpawner:
		mobFileMod = mobFile.split("/")
		# print mobFileMod
		# print Globals.mobsFromFile
		# for mob in Globals.mobsFromFile:
		# 	if mob.name == mobFileMod[1]:
		# 		mobref = mob
		#print mobMode
		mobSpawnerComponent = World.mobSpawner(newObject, Globals.TIMERS, mobTime, mobFileMod[1], mobSpawnOdds, mobCycles, mode=mobMode, active=mobActive)
	else:
		mobSpawnerComponent = None

	#print kind
	if kind == 'item':
		# print itemGrabHandler
		# print objectSpawnerComponent
		#print isCarryable
		itemComponent.isCarryable = isCarryable
		itemComponent.respawns = respawns
		itemComponent.itemGrabHandler = itemGrabHandlerComponent
		itemComponent.objectSpawner = objectSpawnerComponent
		itemComponent.onUse = onUse
		#itemComponent = World.item(isCarryable, respawns, itemGrabHandlerComponent, objectSpawnerComponent)
	if kind == 'container':
		itemComponent.isLocked = isLocked
		itemComponent.isCarryable = isCarryable
		itemComponent.respawns = respawns
		itemComponent.respawnContents = respawnContents
		itemComponent.itemGrabHandler = itemGrabHandlerComponent
		itemComponent.objectSpawner = objectSpawnerComponent
		itemComponent.inventory = []
		#itemComponent = World.container(isLocked, isCarryable, respawns, respawnContents, itemGrabHandlerComponent, objectSpawnerComponent)

	#print newObject.name

	if kind is not None:
		newObject.kind = itemComponent

	if mobSpawner:
		newObject.mobSpawner = mobSpawnerComponent
	else:
		newObject.mobSpawner = None

	#print newObject.kind
	fromFileList.append(newObject)

	# printing suite
	print "name:" + str(newObject.name)
	print "description:" + str(newObject.description)
	print "currentRoom:" + str(newObject.currentRoom)
	print "isVisible:" + str(newObject.isVisible)
	print "spawnContainer:" + str(newObject.spawnContainer)
	print "longDescription:" + str(newObject.longDescription)
	print "kind:" + str(newObject.kind)
	print "TIMERS:" + str(newObject.TIMERS)
	if newObject.kind is not None:
		if isinstance(newObject.kind, World.item):
			print "kind.isCarryable:" + str(newObject.kind.isCarryable)
			print "kind.respawns:" + str(newObject.kind.respawns)
			print "kind.itemGrabHandler:" + str(newObject.kind.itemGrabHandler)
			print "kind.objectSpawner:" + str(newObject.kind.objectSpawner)
			print "kind.onUse:" + str(newObject.kind.onUse)
		if isinstance(newObject.kind, World.container):
			print "kind.inventory:" + str(newObject.kind.inventory)
			print "kind.isLocked:" + str(newObject.kind.isLocked)
			print "kind.isCarryable:" + str(newObject.kind.isCarryable)
			print "kind.respawns:" + str(newObject.kind.respawns)
			print "kind.respawnContents:" + str(newObject.kind.respawnContents)
			print "kind.itemGrabHandler:" + str(newObject.kind.itemGrabHandler)
			print "kind.objectSpawner:" + str(newObject.kind.objectSpawner)
		if newObject.kind.itemGrabHandler is not None:
			print "kind.itemGrabHandler.notDroppable:" + str(newObject.kind.itemGrabHandler.notDroppable)
		if newObject.kind.objectSpawner is not None:
			print "kind.objectSpawner.owner:" + str(newObject.kind.objectSpawner.owner)
			print "kind.objectSpawner.TIMERS:" + str(newObject.kind.objectSpawner.TIMERS)
			print "kind.objectSpawner.time:" + str(newObject.kind.objectSpawner.time)
			print "kind.objectSpawner.obj:" + str(newObject.kind.objectSpawner.obj)
			print "kind.objectSpawner.oddsList:" + str(newObject.kind.objectSpawner.oddsList)
			print "kind.objectSpawner.container:" + str(newObject.kind.objectSpawner.container)
			print "kind.objectSpanwer.cycles:" + str(newObject.kind.objectSpawner.cycles)
			print "kind.objectSpawner.repeat:" + str(newObject.kind.objectSpawner.repeat)
			print "kind.objectSpawner.active:" + str(newObject.kind.objectSpawner.active)
			print "kind.objectSpawner.timer:" + str(newObject.kind.objectSpawner.timer)
			print "kind.objectSpawner.startingLocation:" + str(newObject.kind.objectSpawner.startingLocation)
	print "mobSpawner:" + str(newObject.mobSpawner)
	if newObject.mobSpawner is not None:
		#print "mobSpawner.mobFile:" + str(newObject.mobSpawner.mobFile)
		print "mobSpawner.time:" + str(newObject.mobSpawner.time)
		print "mobSpawner.oddsList:" + str(newObject.mobSpawner.oddsList)
		print "mobSpawner.mode:" + str(newObject.mobSpawner.mode)
		print "mobSpawner.cycles:" + str(newObject.mobSpawner.cycles)
		print "mobSpawner.active:" + str(newObject.mobSpawner.active)
	print "\n"

def buildEquipmentFromFile(file, location):

	print file

	if str(file).endswith('~'):
		print "\n"
		return

	path = location + file
	with open(path, 'r') as f:
		fileData = f.readlines()

	newWeapon = None
	newArmor = None
	equipmentType = None
	slot = None
	durability = None
	maxDurability = None
	worth = None
	description = None
	longDescription = None
	hp = None
	pp = None
	offense = None
	defense = None
	speed = None
	guts = None
	luck = None
	vitality = None
	IQ = None
	battleCommands = None
	statusEffect = None
	onUse = None
	isVisible = None
	spawnContainer = None
	isCarryable = None
	respawns = None
	itemGrabHandler = None
	objectSpawner = None
	notDroppable = None
	container = None
	spawnOdds = None
	time = None
	active = None
	repeat = None
	cycles = None

	for Data in fileData:
		if Data.startswith('type='):
			equipmentType = Data[5:-1]
		if Data.startswith('ID='):
			ID = Data[3:-1]
		if Data.startswith('name='):
			name = Data[5:-1]
		if Data.startswith('slot='):
			slot = Data[5:-1]
		if Data.startswith('durability='):
			durability = Data[11:-1]
		if Data.startswith('maxDurability='):
			maxDurability = Data[14:-1]
		if Data.startswith('worth='):
			worth = Data[6:-1]
		if Data.startswith('description='):
			description = Data[12:-1]
		if Data.startswith('longDescription='):
			longDescription = Data[16:-1]
		if Data.startswith('hp='):
			hp = int(Data[3:-1])
		if Data.startswith('pp='):
			pp = int(Data[3:-1])
		if Data.startswith('offense='):
			offense = int(Data[8:-1])
		if Data.startswith('defense='):
			defense = int(Data[8:-1])
		if Data.startswith('speed='):
			speed = int(Data[6:-1])
		if Data.startswith('guts='):
			guts = int(Data[5:-1])
		if Data.startswith('luck='):
			luck = int(Data[5:-1])
		if Data.startswith('vitality='):
			vitality = int(Data[9:-1])
		if Data.startswith('IQ='):
			IQ = int(Data[3:-1])
		if Data.startswith('battleCommands='):
			battleCommands = Data[15:-1]
			battleCommands = battleCommands.split(",")
		if Data.startswith('statusEffect='):
			statusEffect = Data[13:-1]
		if Data.startswith('onUse='):
			onUse = Data[6:-1]
		if Data.startswith('isVisible='):
			isVisible = Data[10:-1]
			if isVisible == 'True':
				isVisible = True
			elif isVisible == 'False':
				isVisible = False
		if Data.startswith('kind.isCarryable='):
			isCarryable = Data[17:-1]
			if isCarryable == "True":
				isCarryable = True
			elif isCarryable == "False":
				isCarryable = False
		if Data.startswith('kind.respawns='):
			respawns = Data[14:-1]
			if respawns == "True":
				respawns = True
			elif respawns == "False":
				respawns = False
		if Data.startswith('kind.itemGrabHandler='):
			itemGrabHandler = Data[21:-1]
			if itemGrabHandler == "True":
				itemGrabHandler = True
			elif itemGrabHandler == "False":
				itemGrabHandler = False
		if Data.startswith('kind.itemGrabHandler.notDroppable='):
			notDroppable = Data[34:-1]
			if notDroppable == "True":
				notDroppable = True
			elif notDroppable == "False":
				notDroppable = False
		if Data.startswith('kind.objectSpawner='):
			objectSpawner = Data[19:-1]
			if objectSpawner == 'True':
				objectSpawner = True
			elif objectSpawner == 'False':
				objectSpawner = False
		if Data.startswith('kind.objectSpawner.time='):
			time = int(Data[24:-1])
		if Data.startswith('kind.objectSpawner.spawnOdds='):
			text = Data[29:-1]
			oddsList = text.split(',')
			#print "oddsList:" + str(oddsList)
			nestedOddsList = []
			for odds in oddsList:
				nestedOddsList.append(odds.split(':'))
			for oddsEntry in nestedOddsList:
				oddsEntry[1] = int(oddsEntry[1])
				if oddsEntry[0] == 'True':
					oddsEntry[0] = True
				elif oddsEntry[0] == 'False':
					oddsEntry[0] = False
			#print nestedOddsList
			spawnOdds = nestedOddsList
		if Data.startswith('kind.objectSpawner.container='):
			text = Data[29:-1]
			if text == 'None':
				container = None
			else:
				container = text[1:-1]		# this should be a reference to another object
				container = container.split(', ')
		if Data.startswith('kind.objectSpawner.cycles='):
			cycles = int(Data[26:-1])
		if Data.startswith('kind.objectSpawner.repeat='):
			text = Data[26:-1]
			if text == 'True':
				repeat = True
			elif text == 'False':
				repeat = False
		if Data.startswith('kind.objectSpawner.active='):
			text = Data[26:-1]
			#print "***active:" + text
			if text == 'True':
				active = True
			elif text == 'False':
				active = False

	if equipmentType == 'weapon':
		newWeapon = World.weapon()
	elif equipmentType == 'armor':
		newArmor = World.armor()

	if itemGrabHandler == True:
		newItemGrabHandler = World.itemGrabHandler(notDroppable=notDroppable)
	else:
		newItemGrabHandler = None
	if objectSpawner == True:
		newObjectSpawner = World.objectSpawner(owner=None, TIMERS=Globals.TIMERS, time=time, obj=None, oddsList=oddsList, container=container, cycles=cycles, repeat=repeat, active=active)
	else:
		newObjectSpawner = None

	newEquipment = World.equipment(owner=None, weapon=newWeapon, armor=newArmor, slot=slot, durability=durability, maxDurability=maxDurability, worth=worth, hp=hp, pp=pp, offense=offense, defense=defense, speed=speed, guts=guts, luck=luck, vitality=vitality, IQ=IQ, battleCommands=battleCommands, statusEffect=statusEffect, onUse=onUse)
	newItem = World.item(isCarryable=isCarryable, respawns=respawns, itemGrabHandler=newItemGrabHandler, objectSpawner=newObjectSpawner, equipment=newEquipment, onUse=onUse)
	if newItem.itemGrabHandler:
		newItem.itemGrabHandler.owner = newItem
	if newItem.objectSpawner:
		newItem.objectSpawner.owner = newItem
	newEquipment.owner = newItem
	newObject = World.Object(name=name, description=description, isVisible=isVisible, spawnContainer=spawnContainer, longDescription=longDescription, kind=newItem)
	if newObject.kind.objectSpawner:
		newObject.kind.objectSpawner.obj = newObject
	newObject.ID = ID
	newItem.owner = newObject

	equipmentFromFile.append(newObject)

	print "\n"
	print "name:" + str(newObject.name)
	print "description:" + str(newObject.description)
	print "currentRoom:" + str(newObject.currentRoom)
	print "isVisible:" + str(newObject.isVisible)
	print "spawnContainer:" + str(newObject.spawnContainer)
	print "longDescription:" + str(newObject.longDescription)
	print "kind:" + str(newObject.kind)
	#print "TIMERS:" + str(newObject.TIMERS)
	if newObject.kind is not None:
		print "kind.owner:" + str(newObject.kind.owner)
		print "kind.equipment:" + str(newObject.kind.equipment)
		print "kind.equipment.owner" + str(newObject.kind.equipment.owner)
		if hasattr(newObject.kind.equipment, 'weapon'):
			if newObject.kind.equipment.weapon is not None:
				print "weapon:" + str(newObject.kind.equipment.weapon)
		if hasattr(newObject.kind.equipment, 'armor'):
			if newObject.kind.equipment.armor is not None:
				print "armor:" + str(newObject.kind.equipment.armor)
		print "slot:" + str(newObject.kind.equipment.slot)
		print "durability:" + str(newObject.kind.equipment.durability)
		print "maxDurability:" + str(newObject.kind.equipment.maxDurability)
		print "worth:" + str(newObject.kind.equipment.worth)
		if newObject.kind.equipment.hp != 0:
			print "hp:" + str(newObject.kind.equipment.hp)
		if newObject.kind.equipment.pp != 0:
			print "pp:" + str(newObject.kind.equipment.pp)
		if newObject.kind.equipment.offense != 0:
			print "offense:" + str(newObject.kind.equipment.offense)
		if newObject.kind.equipment.defense != 0:
			print "defense:" + str(newObject.kind.equipment.defense)
		if newObject.kind.equipment.speed != 0:
			print "speed:" + str(newObject.kind.equipment.speed)
		if newObject.kind.equipment.guts != 0:
			print "guts:" + str(newObject.kind.equipment.guts)
		if newObject.kind.equipment.luck != 0:
			print "luck:" + str(newObject.kind.equipment.luck)
		if newObject.kind.equipment.vitality != 0:
			print "vitality:" + str(newObject.kind.equipment.vitality)
		if newObject.kind.equipment.IQ != 0:
			print "IQ:" + str(newObject.kind.equipment.IQ)
		if newObject.kind.equipment.statusEffect is not None:
			if newObject.kind.equipment.statusEffect != '':
				print "statusEffect:" + str(newObject.kind.equipment.statusEffect)
		if newObject.kind.equipment.battleCommands is not None:
			if newObject.kind.equipment.battleCommands != ['']:
				print "battleCommands:" + str(newObject.kind.equipment.battleCommands)
		if newObject.kind.equipment.onUse is not None:
			if newObject.kind.equipment.onUse != '':
				print "onUse:" + str(newObject.kind.equipment.onUse)

		if newObject.kind.itemGrabHandler is not None:
			print "kind.itemGrabHandler:" + str(newObject.kind.itemGrabHandler)
			print "kind.itemGrabHandler.notDroppable:" + str(newObject.kind.itemGrabHandler.notDroppable)
		if newObject.kind.objectSpawner is not None:
			print "kind.objectSpawner:" + str(newObject.kind.objectSpawner)
			print "kind.objectSpawner.owner:" + str(newObject.kind.objectSpawner.owner)
			print "kind.objectSpawner.TIMERS:" + str(newObject.kind.objectSpawner.TIMERS)
			print "kind.objectSpawner.time:" + str(newObject.kind.objectSpawner.time)
			print "kind.objectSpawner.obj:" + str(newObject.kind.objectSpawner.obj)
			print "kind.objectSpawner.oddsList:" + str(newObject.kind.objectSpawner.oddsList)
			print "kind.objectSpawner.container:" + str(newObject.kind.objectSpawner.container)
			print "kind.objectSpanwer.cycles:" + str(newObject.kind.objectSpawner.cycles)
			print "kind.objectSpawner.repeat:" + str(newObject.kind.objectSpawner.repeat)
			print "kind.objectSpawner.active:" + str(newObject.kind.objectSpawner.active)
			print "kind.objectSpawner.timer:" + str(newObject.kind.objectSpawner.timer)
			print "kind.objectSpawner.startingLocation:" + str(newObject.kind.objectSpawner.startingLocation)

	print "\n"

	return newObject

for obj in fileList:
	buildObjectFromFile(obj)

print savedEqFileList
if savedEqFileList == []:
	for obj in eqFileList:
		buildEquipmentFromFile(obj, 'blueprints/equip/')
else:
	loadSavedEq()


text:
<bill session="110" type="h" number="5725" updated="2009-01-09T04:43:45-05:00">
	<status><introduced date="1207627200" datetime="2008-04-08"/></status>

	<introduced date="1207627200" datetime="2008-04-08"/>
	<titles>
		<title type="short" as="introduced">National Guard and Ready Reserves Employment Protection Act of 2008</title>
		<title type="official" as="introduced">To amend the Internal Revenue Code of 1986 to allow employers a credit against income tax for employing members of the Ready Reserve or National Guard.</title>
	</titles>
	<sponsor id="400006"/>
	<cosponsors>

	</cosponsors>
	<actions>
		<action date="1207627200" datetime="2008-04-08"><text>Referred to the House Committee on Ways and Means.</text></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>

	4/8/2008--Introduced.
National Guard and Ready Reserves Employment Protection Act of 2008 - Amends the Internal Revenue Code to allow employers a tax credit for 15% of the first $10,000 of wages paid to an employee who is a member of the National Guard or Ready Reserve. Terminates such credit after 2011.

</bill>


text:
<?php

declare(strict_types=1);

namespace LAG\AdminBundle\Field;

use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;

class ActionCollectionField extends AbstractField
{
    /**
     * @var FieldInterface[]
     */
    protected array $fields = [];

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver
            ->setDefaults([
                'template' => '@LAGAdmin/fields/action-collection.html.twig',
                'actions' => [],
            ])
            ->setNormalizer('actions', function (Options $options, $value) {
                if (!\is_array($value) || 0 === \count($value)) {
                    $value = [
                        'edit' => [],
                        'delete' => [],
                    ];
                }
                $data = [];

                foreach ($value as $name => $actionLinkConfiguration) {
                    if (null === $actionLinkConfiguration) {
                        $actionLinkConfiguration = [];
                    }
                    $data[$name] = $this->resolveActionLinkConfiguration(
                        $name,
                        $actionLinkConfiguration
                    );
                }

                return $data;
            })
        ;
    }

    protected function resolveActionLinkConfiguration(
        string $actionName,
        array $actionLinkConfiguration = []
    ): array {
        $resolver = new OptionsResolver();
        $field = new ActionField($actionName, 'action');

        $actionLinkConfiguration['class'] = 'btn btn-secondary';
        $field->configureOptions($resolver);
        $field->setOptions($resolver->resolve($actionLinkConfiguration));

        $this->fields[$actionName] = $field;

        return $field->getOptions();
    }
}


text:
package com.parse.ui;

public interface ParseOnLoadingListener {
  public void onLoadingStart(boolean showSpinner);

  public void onLoadingFinish();
}


text:
package com.rasterfoundry.database

import geotrellis.layer.ZoomedLayoutScheme
import geotrellis.proj4.WebMercator

object tiling {
  val tmsLevels = {
    val scheme = ZoomedLayoutScheme(WebMercator, 256)
    for (zoom <- 0 to 64) yield scheme.levelForZoom(zoom).layout
  }.toArray
}


text:
'use strict';

yeomanApp.factory('TriggerFactory'
  , [ '$rootScope', '$http', 'UIEvents', 'NinjaUtilities'
  , function($rootScope, $http, UIEvents, NinjaUtilities) {

    return function(options) {

      this.Zone = null; // Reference back to the associated Zone

      this.Options = {
        name: '',
        data: '',
        type: ''
      };

      this.Options = NinjaUtilities.ObjectMerge(this.Options, options);

      var normalize = function() {
        if (this.Options.id) {
          this.id = this.Options.id;
          delete this.Options.id;
        }

        if (this.Options.zone) {
          this.Zone = this.Options.zone;
          delete this.Options.zone;
        }

        if (this.Options.Zone) {
          this.Zone = this.Options.Zone;
          delete this.Options.Zone;
        }
      }.bind(this);
      normalize();

      /**
       * Checks if this trigger is a valid FQ trigger
       * ie: All options have been set and a Zone has been applied
       */
      this.IsValid = function() {
        var valid = true;
        if (!this.Options.type) { valid = false; }
        if (!this.Options.name) { valid = false; }
        if (!this.Options.data) { valid = false; }
        if (!this.Zone.id) { valid = false; }

        return valid;
      };

      /**
       * Saves this trigger to the database
       * @param {Function} callback Optional callback function
       */
      this.Save = function(callback) {
        if (DEBUG) console.log("Trigger.Save()", this);
        if (this.IsValid()) {
          var payload = this.Options;
          $http.put('/zone/' + this.Zone.id + '/trigger', payload).success(function(response) {
            $rootScope.$broadcast(UIEvents.TriggerAdded, this);
            if (callback) {
              callback(response);
            }
          }.bind(this)).error(function(response) {
            if (DEBUG) console.log("Error:", response);
            if (callback) {
              callback(response);
            }
          });
          return true;
        } else {
          if (DEBUG) console.log('Trigger not valid for saving')
          return false;
        }
      };

      /**
       * Delete a trigger
       * @param {Function} callback [description]
       */
      this.Delete = function(callback) {
        if (DEBUG) console.log("Trigger.Delete()", this);

        var removedTrigger = this;

        $http.delete('/zone/' + this.Zone.id + '/trigger/' + this.Options.data).success(function(response) {
          // console.log(response);
          $rootScope.$broadcast(UIEvents.TriggerRemoved, removedTrigger);
          if (callback) {
            callback(response);
          }
        }).error(function(response) {
          if (DEBUG) console.log('Error:', response);
          if (callback) {
            callback(response);
          }
        });
      };

    };

    }
  ]);


text:
import glob from 'glob';
import path from 'path';
import test from 'tape';
import load from 'load-json-file';
import { lineString, polygon } from '@turf/helpers';
import booleanParallel from '.';

test('turf-boolean-parallel', t => {
    // True Fixtures
    glob.sync(path.join(__dirname, 'test', 'true', '**', '*.geojson')).forEach(filepath => {
        const name = path.parse(filepath).name;
        const geojson = load.sync(filepath);
        const line1 = geojson.features[0];
        const line2 = geojson.features[1];
        const result = booleanParallel(line1, line2);

        t.true(result, '[true] ' + name);
    });
    // False Fixtures
    glob.sync(path.join(__dirname, 'test', 'false', '**', '*.geojson')).forEach(filepath => {
        const name = path.parse(filepath).name;
        const geojson = load.sync(filepath);
        const line1 = geojson.features[0];
        const line2 = geojson.features[1];
        const result = booleanParallel(line1, line2);

        t.false(result, '[false] ' + name);
    });
    t.end();
});

test('turf-boolean-parallel -- throws', t => {
    const line = lineString([[0, 0], [0, 1]]);
    const poly = polygon([[[0, 0], [0, 1], [1, 1], [0, 0]]]);

    t.throws(() => booleanParallel(null, line), /line1 is required/, 'missing line1');
    t.throws(() => booleanParallel(line, null), /line2 is required/, 'missing line2');
    t.throws(() => booleanParallel(poly, line), /line1 must be a LineString/, 'different types');
    t.throws(() => booleanParallel(line, poly), /line2 must be a LineString/, 'different types');
    t.throws(() => booleanParallel({}, line), /Invalid GeoJSON object for line1/, 'invalid types');
    t.throws(() => booleanParallel(line, {}), /Invalid GeoJSON object for line2/, 'invalid types');

    t.end();
});


text: If selected, source files are not included in the FPR file.


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" android:layout_gravity="center" android:gravity="center"
    android:background="#FFFFFF">

<TextView   android:layout_width="fill_parent" android:gravity="center" android:text="awra"  android:padding="10dp"
    android:layout_height="wrap_content" android:id="@+id/version_name"  android:textColor="#7f2352"
            android:textSize="18sp"/>
</LinearLayout>


text:
!
! This file is released under terms of BSD license
! See LICENSE file for more information
!

MODULE mo_column
  IMPLICIT NONE

  INTEGER, PARAMETER :: dp = selected_real_kind(13)
  INTEGER, PARAMETER :: sp = selected_real_kind(6)

END MODULE mo_column


text:
// MusicXML Class Library
// Copyright (c) by Matthew James Briggs
// Distributed under the MIT License

#pragma once

#include "mx/core/ForwardDeclare.h"
#include "mx/core/ElementInterface.h"

#include <iosfwd>
#include <memory>
#include <vector>

namespace mx
{
    namespace core
    {

        MX_FORWARD_DECLARE_ELEMENT( Distance )
        MX_FORWARD_DECLARE_ELEMENT( LineWidth )
        MX_FORWARD_DECLARE_ELEMENT( NoteSize )
        MX_FORWARD_DECLARE_ELEMENT( OtherAppearance )
        MX_FORWARD_DECLARE_ELEMENT( Appearance )

        inline AppearancePtr makeAppearance() { return std::make_shared<Appearance>(); }

        class Appearance : public ElementInterface
        {
        public:
            Appearance();

            virtual bool hasAttributes() const;
            virtual std::ostream& streamAttributes( std::ostream& os ) const;
            virtual std::ostream& streamName( std::ostream& os ) const;
            virtual bool hasContents() const;
            virtual std::ostream& streamContents( std::ostream& os, const int indentLevel, bool& isOneLineOnly ) const;

            /* _________ LineWidth minOccurs = 0, maxOccurs = unbounded _________ */
            const LineWidthSet& getLineWidthSet() const;
            void addLineWidth( const LineWidthPtr& value );
            void removeLineWidth( const LineWidthSetIterConst& value );
            void clearLineWidthSet();
            LineWidthPtr getLineWidth( const LineWidthSetIterConst& setIterator ) const;

            /* _________ NoteSize minOccurs = 0, maxOccurs = unbounded _________ */
            const NoteSizeSet& getNoteSizeSet() const;
            void addNoteSize( const NoteSizePtr& value );
            void removeNoteSize( const NoteSizeSetIterConst& value );
            void clearNoteSizeSet();
            NoteSizePtr getNoteSize( const NoteSizeSetIterConst& setIterator ) const;

            /* _________ Distance minOccurs = 0, maxOccurs = unbounded _________ */
            const DistanceSet& getDistanceSet() const;
            void addDistance( const DistancePtr& value );
            void removeDistance( const DistanceSetIterConst& value );
            void clearDistanceSet();
            DistancePtr getDistance( const DistanceSetIterConst& setIterator ) const;

            /* _________ OtherAppearance minOccurs = 0, maxOccurs = unbounded _________ */
            const OtherAppearanceSet& getOtherAppearanceSet() const;
            void addOtherAppearance( const OtherAppearancePtr& value );
            void removeOtherAppearance( const OtherAppearanceSetIterConst& value );
            void clearOtherAppearanceSet();
            OtherAppearancePtr getOtherAppearance( const OtherAppearanceSetIterConst& setIterator ) const;

            private:
            virtual bool fromXElementImpl( std::ostream& message, ::ezxml::XElement& xelement );

        private:
            LineWidthSet myLineWidthSet;
            NoteSizeSet myNoteSizeSet;
            DistanceSet myDistanceSet;
            OtherAppearanceSet myOtherAppearanceSet;
        };
    }
}


text:
import React from 'react';
import PropTypes from 'prop-types';

import { Query } from 'react-apollo';
import gql from 'graphql-tag';

import { calendarMonth, today } from 'couples-diary-core';

import Calendar from './component';

export const CALENDAR_GQL_QUERY = gql`
  query entries($year: Int!, $month: Int!) {
    myCouple {
      id
      me {
        id
        name
      }
      partner {
        id
        name
      }
    }
    me {
      id
      name
    }
    entries(year: $year, month: $month) {
      id
      year
      month
      date
      author {
        id
        name
        color
      }
    }
  }
`;

const getDateFromPath = match => ({
  year: parseFloat(match.params.year),
  month: parseFloat(match.params.month),
});

const hydrate = (year, month, entries) => {
  const dates = calendarMonth(year, month);

  return dates.map(date => {
    const authors = entries
      .filter(
        ({ year, month, date: entryDate }) =>
          year === date.year && month === date.month && entryDate === date.date
      )
      .map(({ author }) => author);

    return { ...date, authors };
  });
};

const renderCalendar = (year, month) => ({ data, loading }) => (
  <Calendar
    partner={partnerName(data)}
    today={today()}
    selectedYear={year}
    selectedMonth={month}
    entries={hydrate(year, month, entries(data))}
    loading={loading}
  />
);

function partnerName(graphQlData) {
  return (
    (graphQlData &&
      graphQlData.myCouple &&
      graphQlData.myCouple.partner.name) ||
    ''
  );
}

function entries(graphQlData) {
  return (graphQlData && graphQlData.entries) || [];
}

export const CalendarContainer = ({ match }) => {
  const { year, month } = getDateFromPath(match);
  return (
    <Query
      query={CALENDAR_GQL_QUERY}
      variables={{ year, month }}
      fetchPolicy="cache-and-network"
    >
      {renderCalendar(year, month)}
    </Query>
  );
};

CalendarContainer.propTypes = {
  match: PropTypes.object.isRequired,
};

export default CalendarContainer;


text:
<?php

namespace app\models\search;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Sindicatura;

/**
 * SindicaturaSearch represents the model behind the search form about `app\models\Sindicatura`.
 */
class SindicaturaSearch extends Sindicatura
{
    public $municipioName;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['sindicatura_id', 'municipio_id'], 'integer'],
            [['sindicatura_nombre'], 'safe'],
            [['municipioName'],'safe'],

        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Sindicatura::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $dataProvider->setSort([
                'attributes'=>[
                    'sindicatura_nombre',
                    'municipioName'=>[
                        'asc'=>['municipio.municipio_nombre'=>SORT_ASC],
                        'desc'=>['municipio.municipio_nombre'=>SORT_DESC],
                        'label'=>'Nombre del Municipio'

                    ],
                ]
            ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to any records when validation fails
            // $query->where('0=1');
            $query->joinWith('municipio');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'sindicatura_id' => $this->sindicatura_id,
            'municipio_id' => $this->municipio_id,
        ]);

        $query->andFilterWhere(['municipio_id' => $this->municipio_id]);
        $query->andFilterWhere(['like', 'sindicatura_nombre', $this->sindicatura_nombre]);

        $query->joinWith(['municipio'=>function ($q)
        {
            if(!empty($this->municipioName))
            $q->where('municipio.municipio_nombre LIKE "%' .
            $this->municipioName . '%"');
        }]);
        return $dataProvider;
    }
}


text:
package lifecycle

import (
	"fmt"
	"strings"
	"time"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	clientset "github.com/hyperhq/client-go/kubernetes"
	"k8s.io/kubernetes/test/e2e/common"
	"k8s.io/kubernetes/test/e2e/framework"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

const resizeNodeReadyTimeout = 2 * time.Minute

func resizeRC(c clientset.Interface, ns, name string, replicas int32) error {
	rc, err := c.CoreV1().ReplicationControllers(ns).Get(name, metav1.GetOptions{})
	if err != nil {
		return err
	}
	*(rc.Spec.Replicas) = replicas
	_, err = c.CoreV1().ReplicationControllers(rc.Namespace).Update(rc)
	return err
}

var _ = SIGDescribe("Nodes [Disruptive]", func() {
	f := framework.NewDefaultFramework("resize-nodes")
	var systemPodsNo int32
	var c clientset.Interface
	var ns string
	ignoreLabels := framework.ImagePullerLabels
	var group string

	BeforeEach(func() {
		c = f.ClientSet
		ns = f.Namespace.Name
		systemPods, err := framework.GetPodsInNamespace(c, ns, ignoreLabels)
		Expect(err).NotTo(HaveOccurred())
		systemPodsNo = int32(len(systemPods))
		if strings.Index(framework.TestContext.CloudConfig.NodeInstanceGroup, ",") >= 0 {
			framework.Failf("Test dose not support cluster setup with more than one MIG: %s", framework.TestContext.CloudConfig.NodeInstanceGroup)
		} else {
			group = framework.TestContext.CloudConfig.NodeInstanceGroup
		}
	})

	// Slow issue #13323 (8 min)
	Describe("Resize [Slow]", func() {
		var skipped bool

		BeforeEach(func() {
			skipped = true
			framework.SkipUnlessProviderIs("gce", "gke", "aws")
			framework.SkipUnlessNodeCountIsAtLeast(2)
			skipped = false
		})

		AfterEach(func() {
			if skipped {
				return
			}

			By("restoring the original node instance group size")
			if err := framework.ResizeGroup(group, int32(framework.TestContext.CloudConfig.NumNodes)); err != nil {
				framework.Failf("Couldn't restore the original node instance group size: %v", err)
			}
			// In GKE, our current tunneling setup has the potential to hold on to a broken tunnel (from a
			// rebooted/deleted node) for up to 5 minutes before all tunnels are dropped and recreated.
			// Most tests make use of some proxy feature to verify functionality. So, if a reboot test runs
			// right before a test that tries to get logs, for example, we may get unlucky and try to use a
			// closed tunnel to a node that was recently rebooted. There's no good way to framework.Poll for proxies
			// being closed, so we sleep.
			//
			// TODO(cjcullen) reduce this sleep (#19314)
			if framework.ProviderIs("gke") {
				By("waiting 5 minutes for all dead tunnels to be dropped")
				time.Sleep(5 * time.Minute)
			}
			if err := framework.WaitForGroupSize(group, int32(framework.TestContext.CloudConfig.NumNodes)); err != nil {
				framework.Failf("Couldn't restore the original node instance group size: %v", err)
			}
			if err := framework.WaitForReadyNodes(c, framework.TestContext.CloudConfig.NumNodes, 10*time.Minute); err != nil {
				framework.Failf("Couldn't restore the original cluster size: %v", err)
			}
			// Many e2e tests assume that the cluster is fully healthy before they start.  Wait until
			// the cluster is restored to health.
			By("waiting for system pods to successfully restart")
			err := framework.WaitForPodsRunningReady(c, metav1.NamespaceSystem, systemPodsNo, 0, framework.PodReadyBeforeTimeout, ignoreLabels)
			Expect(err).NotTo(HaveOccurred())
			By("waiting for image prepulling pods to complete")
			framework.WaitForPodsSuccess(c, metav1.NamespaceSystem, framework.ImagePullerLabels, framework.ImagePrePullingTimeout)
		})

		It("should be able to delete nodes", func() {
			// Create a replication controller for a service that serves its hostname.
			// The source for the Docker container kubernetes/serve_hostname is in contrib/for-demos/serve_hostname
			name := "my-hostname-delete-node"
			replicas := int32(framework.TestContext.CloudConfig.NumNodes)
			common.NewRCByName(c, ns, name, replicas, nil)
			err := framework.VerifyPods(c, ns, name, true, replicas)
			Expect(err).NotTo(HaveOccurred())

			By(fmt.Sprintf("decreasing cluster size to %d", replicas-1))
			err = framework.ResizeGroup(group, replicas-1)
			Expect(err).NotTo(HaveOccurred())
			err = framework.WaitForGroupSize(group, replicas-1)
			Expect(err).NotTo(HaveOccurred())
			err = framework.WaitForReadyNodes(c, int(replicas-1), 10*time.Minute)
			Expect(err).NotTo(HaveOccurred())

			By("waiting 1 minute for the watch in the podGC to catch up, remove any pods scheduled on " +
				"the now non-existent node and the RC to recreate it")
			time.Sleep(time.Minute)

			By("verifying whether the pods from the removed node are recreated")
			err = framework.VerifyPods(c, ns, name, true, replicas)
			Expect(err).NotTo(HaveOccurred())
		})

		// TODO: Bug here - testName is not correct
		It("should be able to add nodes", func() {
			// Create a replication controller for a service that serves its hostname.
			// The source for the Docker container kubernetes/serve_hostname is in contrib/for-demos/serve_hostname
			name := "my-hostname-add-node"
			common.NewSVCByName(c, ns, name)
			replicas := int32(framework.TestContext.CloudConfig.NumNodes)
			common.NewRCByName(c, ns, name, replicas, nil)
			err := framework.VerifyPods(c, ns, name, true, replicas)
			Expect(err).NotTo(HaveOccurred())

			By(fmt.Sprintf("increasing cluster size to %d", replicas+1))
			err = framework.ResizeGroup(group, replicas+1)
			Expect(err).NotTo(HaveOccurred())
			err = framework.WaitForGroupSize(group, replicas+1)
			Expect(err).NotTo(HaveOccurred())
			err = framework.WaitForReadyNodes(c, int(replicas+1), 10*time.Minute)
			Expect(err).NotTo(HaveOccurred())

			By(fmt.Sprintf("increasing size of the replication controller to %d and verifying all pods are running", replicas+1))
			err = resizeRC(c, ns, name, replicas+1)
			Expect(err).NotTo(HaveOccurred())
			err = framework.VerifyPods(c, ns, name, true, replicas+1)
			Expect(err).NotTo(HaveOccurred())
		})
	})
})


text:
import copy
import unittest
import os
import os.path
import shutil
import tempfile
import time

import chapter
from constants import *
import epub

class TestEpub(unittest.TestCase):

    def setUp(self):
        chapter_dir = os.path.join(TEST_DIR, 'test_chapters')
        chapter_factory = chapter.ChapterFactory()
        self.output_directory = os.path.join(TEST_DIR, 'epub_output')
        self.chapter_list = []
        file_list = [f for f in os.listdir(chapter_dir) if os.path.isfile(os.path.join(chapter_dir,f))]
        for index, f in enumerate(file_list):
            full_name = os.path.join(chapter_dir, f)
            c = chapter_factory.create_chapter_from_file(full_name)
            self.chapter_list.append(c)
        self.chapter_titles = [
                u'Quick Practical, Tactical Tips for Presentations',
                u'Venture capital - Wikipedia, the free encyclopedia',
                u"Ben's Blog",
                u"The capture of Mosul: Terror\u2019s new headquarters | The Economist",
                ]

    def test_TOCHTML(self):
        def create_TOC():
            self.test_toc = epub.TocHtml()
            self.test_toc.add_chapters(self.chapter_list)
            self.toc_element = self.test_toc.get_content_as_element()
        def check_titles():
            chapter_nodes = self.toc_element.get_element_by_id('chapters').getchildren()
            self.assertEqual(len(chapter_nodes), len(self.chapter_list))
            self.assertEqual(chapter_nodes[0][0].text,self.chapter_titles[0])
            self.assertEqual(chapter_nodes[1][0].text,self.chapter_titles[1])
            self.assertEqual(chapter_nodes[2][0].text,self.chapter_titles[2])
            self.assertEqual(chapter_nodes[3][0].text,self.chapter_titles[3])
        if epub.lxml_module_exists:
            create_TOC()
            check_titles()
            self.test_toc.write(os.path.join(TEST_DIR, 'epub_output', 'toc.html'))
        else:
            self.assertRaises(NotImplementedError, create_TOC)

    def test_TOCNCX(self):
        def createTOC():
            self.test_toc = epub.TocNcx()
            self.test_toc.add_chapters(self.chapter_list)
            self.toc_element = self.test_toc.get_content_as_element()
        def checkTitles():
            chapter_nodes = self.toc_element[2]
            self.assertEqual(len(chapter_nodes),len(self.chapter_list))
            for index, node in enumerate(chapter_nodes):
                self.assertEqual(node[0][0].text,self.chapter_titles[index])
        if epub.lxml_module_exists:
            createTOC()
            checkTitles()
            self.test_toc.write(os.path.join(TEST_DIR, 'epub_output', 'toc_ncx.xml'))
        else:
            self.assertRaises(NotImplementedError, createTOC)

    def test_ContentOPF(self):
        def createContentOPF():
            self.test_opf = epub.ContentOpf('Sample Title')
            self.test_opf.add_chapters(self.chapter_list)
            opf_file = os.path.join(TEST_DIR, 'epub_output', 'opf.xml')
            self.test_opf.write(opf_file)
            self.opf_element = self.test_opf.get_content_as_element()
            self.assertEqual(len(self.opf_element.getchildren()), 4)
        def check_encoding():
            pass
        def checkSpine():
            spine_nodes = self.opf_element[2].getchildren()
            self.assertEqual(len(spine_nodes),len(self.chapter_list) + 1)
        def checkManifest():
            manifest_nodes = self.opf_element[1].getchildren()
            self.assertEqual(len(manifest_nodes),len(self.chapter_list) + 2)
        if epub.lxml_module_exists:
            createContentOPF()
            check_encoding()
            checkSpine()
            checkManifest()
        else:
            self.assertRaises(NotImplementedError, createContentOPF)

    def test_create_epub(self):
        epub_dir_ending = time.strftime("%m%d%Y%H%M%S")
        epub_directory = os.path.join(TEST_DIR, 'epub_output', 'epub files' + epub_dir_ending)
        os.makedirs(epub_directory)
        e = epub.Epub('Test Epub', epub_dir=epub_directory)
        for index, c in enumerate(self.chapter_list[:3]):
            output_name = os.path.join(TEST_DIR,
                    'epub_output', str(index) + '.xhtml')
            c.write(output_name)
            e.add_chapter(c)
        e.create_epub('test_epub', epub_directory)

if __name__ == '__main__':
    unittest.main()


text:
define(function(require) {
  var module = require('./dist/zeroclipboard');
  describe('ZeroClipboard', function() {
    it('should has ZeroClipboard.detectFlashSupport method', function() {
      expect(module.detectFlashSupport).to.be.a('function');
    });
  });
});


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical" android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <TableLayout android:layout_height="wrap_content" android:layout_width="fill_parent">
    <TableRow android:gravity="center" android:layout_width="wrap_content" android:layout_height="wrap_content">
      <Button android:id="@+id/queryButton" android:text="@string/query_button" android:layout_height="wrap_content" android:layout_width="wrap_content" />
    </TableRow>
  </TableLayout>

  <TextView android:textSize="22sp" android:textStyle="bold"
    android:id="@+id/messageTextView" android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

  <TextView android:textSize="28sp" android:textStyle="bold"
    android:id="@+id/errorTextView" android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

</LinearLayout>