text:
// Copyright (c) 2008  INRIA Sophia-Antipolis (France).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org).
// 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.
//
// Licensees holding a valid commercial license may use this file in
// accordance with the commercial license agreement provided with the software.
//
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
//
// $URL$
// $Id$
//
//
// Author(s) : Camille Wormser, Pierre Alliez, Stephane Tayeb

#ifndef CGAL_AABB_NODE_H
#define CGAL_AABB_NODE_H

#include <CGAL/Profile_counter.h>
#include <CGAL/Cartesian_converter.h>
#include <CGAL/intersections.h>
#include <CGAL/Bbox_3.h>
#include <vector>

namespace CGAL {

/**
 * @class AABB_node
 *
 *
 */
template<typename AABBTraits>
class AABB_node
{
public:
  typedef typename AABBTraits::Bounding_box Bounding_box;

  /// Constructor
  AABB_node()
    : m_bbox()
    , m_p_left_child(NULL)
    , m_p_right_child(NULL)      { };

  /// Non virtual Destructor
  /// Do not delete children because the tree hosts and delete them
  ~AABB_node() { };

  /// Returns the bounding box of the node
  const Bounding_box& bbox() const { return m_bbox; }

  /**
   * @brief Builds the tree by recursive expansion.
   * @param first the first primitive to insert
   * @param last the last primitive to insert
   * @param range the number of primitive of the range
   *
   * [first,last[ is the range of primitives to be added to the tree.
   */
  template<typename ConstPrimitiveIterator>
  void expand(ConstPrimitiveIterator first,
              ConstPrimitiveIterator beyond,
              const std::size_t range,
              const AABBTraits&);

  /**
   * @brief General traversal query
   * @param query the query
   * @param traits the traversal traits that define the traversal behaviour
   * @param nb_primitives the number of primitive
   *
   * General traversal query. The traits class allows using it for the various
   * traversal methods we need: listing, counting, detecting intersections,
   * drawing the boxes.
   */
  template<class Traversal_traits, class Query>
  void traversal(const Query& query,
                 Traversal_traits& traits,
                 const std::size_t nb_primitives) const;

private:
  typedef AABBTraits AABB_traits;
  typedef AABB_node<AABB_traits> Node;
  typedef typename AABB_traits::Primitive Primitive;

  /// Helper functions
  const Node& left_child() const
                     { return *static_cast<Node*>(m_p_left_child); }
  const Node& right_child() const
                     { return *static_cast<Node*>(m_p_right_child); }
  const Primitive& left_data() const
                     { return *static_cast<Primitive*>(m_p_left_child); }
  const Primitive& right_data() const
                     { return *static_cast<Primitive*>(m_p_right_child); }

  Node& left_child() { return *static_cast<Node*>(m_p_left_child); }
  Node& right_child() { return *static_cast<Node*>(m_p_right_child); }
  Primitive& left_data() { return *static_cast<Primitive*>(m_p_left_child); }
  Primitive& right_data() { return *static_cast<Primitive*>(m_p_right_child); }

private:
  /// node bounding box
  Bounding_box m_bbox;

  /// children nodes, either pointing towards children (if children are not leaves),
  /// or pointing toward input primitives (if children are leaves).
  void *m_p_left_child;
  void *m_p_right_child;

private:
  // Disabled copy constructor & assignment operator
  typedef AABB_node<AABBTraits> Self;
  AABB_node(const Self& src);
  Self& operator=(const Self& src);

};  // end class AABB_node

template<typename Tr>
template<typename ConstPrimitiveIterator>
void
AABB_node<Tr>::expand(ConstPrimitiveIterator first,
                      ConstPrimitiveIterator beyond,
                      const std::size_t range,
                      const Tr& traits)
{
  m_bbox = traits.compute_bbox_object()(first, beyond);

  // sort primitives along longest axis aabb
  traits.sort_primitives_object()(first, beyond, m_bbox);

  switch(range)
  {
  case 2:
    m_p_left_child = &(*first);
    m_p_right_child = &(*(++first));
    break;
  case 3:
    m_p_left_child = &(*first);
    m_p_right_child = static_cast<Node*>(this)+1;
    right_child().expand(first+1, beyond, 2,traits);
    break;
  default:
    const std::size_t new_range = range/2;
    m_p_left_child = static_cast<Node*>(this) + 1;
    m_p_right_child = static_cast<Node*>(this) + new_range;
    left_child().expand(first, first + new_range, new_range,traits);
    right_child().expand(first + new_range, beyond, range - new_range,traits);
  }
}

template<typename Tr>
template<class Traversal_traits, class Query>
void
AABB_node<Tr>::traversal(const Query& query,
                         Traversal_traits& traits,
                         const std::size_t nb_primitives) const
{
  // Recursive traversal
  switch(nb_primitives)
  {
  case 2:
    traits.intersection(query, left_data());
    if( traits.go_further() )
    {
      traits.intersection(query, right_data());
    }
    break;
  case 3:
    traits.intersection(query, left_data());
    if( traits.go_further() && traits.do_intersect(query, right_child()) )
    {
      right_child().traversal(query, traits, 2);
    }
    break;
  default:
    if( traits.do_intersect(query, left_child()) )
    {
      left_child().traversal(query, traits, nb_primitives/2);
      if( traits.go_further() && traits.do_intersect(query, right_child()) )
      {
        right_child().traversal(query, traits, nb_primitives-nb_primitives/2);
      }
    }
    else if( traits.do_intersect(query, right_child()) )
    {
      right_child().traversal(query, traits, nb_primitives-nb_primitives/2);
    }
  }
}

} // end namespace CGAL

#endif // CGAL_AABB_NODE_H


text:
var tipotemaView = function (strClase) {
    this.clase = strClase;
};
tipotemaView.prototype = new view('tipotema');
tipotemaView.prototype.getClassNameTipotema = function () {
    return this.getClassName() + "Vista";
};
var oTipotemaView = new tipotemaView('tipotema');

tipotemaView.prototype.printValue = function (value, valor, recortar) {
    var thisObject = this;
    var strResult = "";
    if (/obj_/.test(valor)) {
        if (value[valor].id > 0) {
            strResult = '' + value[valor].id + ":" + util().getForeign(value[valor]) + '';
        } else {
            strResult = '???';
        }
    } else {
        switch (value[valor]) {
            case true:
                strResult = '';
                break;
            case false:
                strResult = '';
                break;
            default:
                strResult = decodeURIComponent(value[valor]);

                if (recortar)
                    if (strResult.length > 50) //don't show too long fields
                        strResult = strResult.substr(0, 20) + " ...";

                if (/nombre/.test(valor)) {
                    strResult = '' + decodeURIComponent(value[valor]) + '';
                }
            };
    };
    return strResult;
};

redpajama_set_name: RedPajamaGithub


text:
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response
from nssrc.com.citrix.netscaler.nitro.service.options import options
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception

from nssrc.com.citrix.netscaler.nitro.util.nitro_util import nitro_util

class appfwprofile_binding(base_resource):
	""" Binding class showing the resources that can be bound to appfwprofile_binding.
	"""
	def __init__(self) :
		self._name = ""
		self.appfwprofile_excluderescontenttype_binding = []
		self.appfwprofile_xmlattachmenturl_binding = []
		self.appfwprofile_crosssitescripting_binding = []
		self.appfwprofile_xmlwsiurl_binding = []
		self.appfwprofile_xmldosurl_binding = []
		self.appfwprofile_fieldconsistency_binding = []
		self.appfwprofile_safeobject_binding = []
		self.appfwprofile_sqlinjection_binding = []
		self.appfwprofile_denyurl_binding = []
		self.appfwprofile_trustedlearningclients_binding = []
		self.appfwprofile_csrftag_binding = []
		self.appfwprofile_cookieconsistency_binding = []
		self.appfwprofile_starturl_binding = []
		self.appfwprofile_xmlsqlinjection_binding = []
		self.appfwprofile_contenttype_binding = []
		self.appfwprofile_xmlxss_binding = []
		self.appfwprofile_fieldformat_binding = []
		self.appfwprofile_xmlvalidationurl_binding = []

	@property
	def name(self) :
		ur"""Name of the application firewall profile.
Minimum length =  1.
		"""
		try :
			return self._name
		except Exception as e:
			raise e

	@name.setter
	def name(self, name) :
		ur"""Name of the application firewall profile.
Minimum length =  1
		"""
		try :
			self._name = name
		except Exception as e:
			raise e

	@property
	def appfwprofile_csrftag_bindings(self) :
		ur"""csrftag that can be bound to appfwprofile.
		"""
		try :
			return self._appfwprofile_csrftag_binding
		except Exception as e:
			raise e

	@property
	def appfwprofile_starturl_bindings(self) :
		ur"""starturl that can be bound to appfwprofile.
		"""
		try :
			return self._appfwprofile_starturl_binding
		except Exception as e:
			raise e

	@property
	def appfwprofile_xmlvalidationurl_bindings(self) :
		ur"""xmlvalidationurl that can be bound to appfwprofile.
		"""
		try :
			return self._appfwprofile_xmlvalidationurl_binding
		except Exception as e:
			raise e

	@property
	def appfwprofile_xmlattachmenturl_bindings(self) :
		ur"""xmlattachmenturl that can be bound to appfwprofile.
		"""
		try :
			return self._appfwprofile_xmlattachmenturl_binding
		except Exception as e:
			raise e

	@property
	def appfwprofile_safeobject_bindings(self) :
		ur"""safeobject that can be bound to appfwprofile.
		"""
		try :
			return self._appfwprofile_safeobject_binding
		except Exception as e:
			raise e

	@property
	def appfwprofile_cookieconsistency_bindings(self) :
		ur"""cookieconsistency that can be bound to appfwprofile.
		"""
		try :
			return self._appfwprofile_cookieconsistency_binding
		except Exception as e:
			raise e

	@property
	def appfwprofile_fieldconsistency_bindings(self) :
		ur"""fieldconsistency that can be bound to appfwprofile.
		"""
		try :
			return self._appfwprofile_fieldconsistency_binding
		except Exception as e:
			raise e

	@property
	def appfwprofile_xmlwsiurl_bindings(self) :
		ur"""xmlwsiurl that can be bound to appfwprofile.
		"""
		try :
			return self._appfwprofile_xmlwsiurl_binding
		except Exception as e:
			raise e

	@property
	def appfwprofile_xmlsqlinjection_bindings(self) :
		ur"""xmlsqlinjection that can be bound to appfwprofile.
		"""
		try :
			return self._appfwprofile_xmlsqlinjection_binding
		except Exception as e:
			raise e

	@property
	def appfwprofile_sqlinjection_bindings(self) :
		ur"""sqlinjection that can be bound to appfwprofile.
		"""
		try :
			return self._appfwprofile_sqlinjection_binding
		except Exception as e:
			raise e

	@property
	def appfwprofile_trustedlearningclients_bindings(self) :
		ur"""trustedlearningclients that can be bound to appfwprofile.
		"""
		try :
			return self._appfwprofile_trustedlearningclients_binding
		except Exception as e:
			raise e

	@property
	def appfwprofile_crosssitescripting_bindings(self) :
		ur"""crosssitescripting that can be bound to appfwprofile.
		"""
		try :
			return self._appfwprofile_crosssitescripting_binding
		except Exception as e:
			raise e

	@property
	def appfwprofile_excluderescontenttype_bindings(self) :
		ur"""excluderescontenttype that can be bound to appfwprofile.
		"""
		try :
			return self._appfwprofile_excluderescontenttype_binding
		except Exception as e:
			raise e

	@property
	def appfwprofile_contenttype_bindings(self) :
		ur"""contenttype that can be bound to appfwprofile.
		"""
		try :
			return self._appfwprofile_contenttype_binding
		except Exception as e:
			raise e

	@property
	def appfwprofile_denyurl_bindings(self) :
		ur"""denyurl that can be bound to appfwprofile.
		"""
		try :
			return self._appfwprofile_denyurl_binding
		except Exception as e:
			raise e

	@property
	def appfwprofile_xmlxss_bindings(self) :
		ur"""xmlxss that can be bound to appfwprofile.
		"""
		try :
			return self._appfwprofile_xmlxss_binding
		except Exception as e:
			raise e

	@property
	def appfwprofile_fieldformat_bindings(self) :
		ur"""fieldformat that can be bound to appfwprofile.
		"""
		try :
			return self._appfwprofile_fieldformat_binding
		except Exception as e:
			raise e

	@property
	def appfwprofile_xmldosurl_bindings(self) :
		ur"""xmldosurl that can be bound to appfwprofile.
		"""
		try :
			return self._appfwprofile_xmldosurl_binding
		except Exception as e:
			raise e

	def _get_nitro_response(self, service, response) :
		ur""" converts nitro response into object and returns the object array in case of get request.
		"""
		try :
			result = service.payload_formatter.string_to_resource(appfwprofile_binding_response, response, self.__class__.__name__)
			if(result.errorcode != 0) :
				if (result.errorcode == 444) :
					service.clear_session(self)
				if result.severity :
					if (result.severity == "ERROR") :
						raise nitro_exception(result.errorcode, str(result.message), str(result.severity))
				else :
					raise nitro_exception(result.errorcode, str(result.message), str(result.severity))
			return result.appfwprofile_binding
		except Exception as e :
			raise e

	def _get_object_name(self) :
		ur""" Returns the value of object identifier argument
		"""
		try :
			if self.name is not None :
				return str(self.name)
			return None
		except Exception as e :
			raise e

	@classmethod
	def get(self, service, name) :
		ur""" Use this API to fetch appfwprofile_binding resource.
		"""
		try :
			if type(name) is not list :
				obj = appfwprofile_binding()
				obj.name = name
				response = obj.get_resource(service)
			else :
				if name and len(name) > 0 :
					obj = [appfwprofile_binding() for _ in range(len(name))]
					for i in range(len(name)) :
						obj[i].name = name[i];
						response[i] = obj[i].get_resource(service)
			return response
		except Exception as e:
			raise e

class appfwprofile_binding_response(base_response) :
	def __init__(self, length=1) :
		self.appfwprofile_binding = []
		self.errorcode = 0
		self.message = ""
		self.severity = ""
		self.sessionid = ""
		self.appfwprofile_binding = [appfwprofile_binding() for _ in range(length)]


text:
/**
 * Created by Administrator on 2017/5/31.
 */
let express = require('express');
let router = express.Router();
let URL = require('url');
/* GET home page. */
router.get('/', function(req, res, next) {

    let FAKLimitOrderReq = URL.parse(req.url, true).query;
    let contractName=FAKLimitOrderReq.contractName.replace(" ","+");
    let direction=FAKLimitOrderReq.direction;
    if(direction==="buy")
        direction=Direction.Buy;
    else if(direction==="sell")
        direction=Direction.Sell;

    let openclose=FAKLimitOrderReq.openclose;
    if(openclose==="open")
        openclose=OpenCloseFlagType.Open;
    else if(openclose==="close")
        openclose=OpenCloseFlagType.Close;
    else if(openclose==="closeToday")
        openclose=OpenCloseFlagType.CloseToday;
    else if(openclose==="closeYesterday")
        openclose=OpenCloseFlagType.CloseYesterday;

    let volume=parseInt(FAKLimitOrderReq.volume);

    let limitPrice=parseFloat(FAKLimitOrderReq.limitPrice);

    let DemoStrategy=global.NodeQuant.StrategyEngine.GetStrategy("Demo");
    if(DemoStrategy)
    {
        let lastTick = global.NodeQuant.StrategyEngine.Symbol_LastTickDic[contractName];
        DemoStrategy.SendOrder(lastTick.clientName,contractName,limitPrice,volume,direction,openclose,OrderType.FAK);
    }

    res.render('index', { title: 'FiveMAStrategy Send FAK Order'});

});

module.exports = router;


text:
#include <iostream>
#include <vector>
#include <string>
#include <map>

#include "Operator.h"
#include "Envelope.h"

typedef struct param_struct
{
	std::string parameterId;
	double value;
} Parameter;

class Note
{
	int _key; // key from 0 (C) to 11 (B), negative if unassigned (rest)
	int _octave; // octave, no boundaries
	double _duration; // duration in seconds

	unsigned long _positionPpqn; // position in ppqn
	unsigned long _durationPpqn; // duration in ppqn
	unsigned long _releasePointPpqn; // release point in ppqn

	std::string _patchId; // patch id
	std::map<std::string, std::vector<Parameter> > _parameters; // parameters

public:
	Note(void);
	~Note(void);

	int getKey() const;
	void setKey(int key);

	int getOctave() const;
	void setOctave(int octave);

	double getDuration() const;
	void setDuration(double duration);

	unsigned long getPositionPpqn() const;
	void setPositionPpqn(unsigned long position);

	unsigned long getDurationPpqn() const;
	void setDurationPpqn(unsigned long duration);

	unsigned long getReleasePointPpqn() const;
	void setReleasePointPpqn(unsigned long releasePoint);

	std::string getPatchId() const;
	void setPatchId(std::string patchId);

	std::map<std::string, std::vector<Parameter> > getParameters() const;
	void addParameter(std::string path, Parameter param);

	unsigned int getSampleCountFor(unsigned long sampleRate) const;

};


text:
.class Lcom/android/systemui/qs/tiles/HotspotTile$5;
.super Ljava/lang/Object;
.source "HotspotTile.java"

# interfaces
.implements Landroid/content/DialogInterface$OnCancelListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/android/systemui/qs/tiles/HotspotTile;->showWifiSharingFirstTimeDialog()V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/systemui/qs/tiles/HotspotTile;

.field final synthetic val$cr:Landroid/content/ContentResolver;

# direct methods
.method constructor <init>(Lcom/android/systemui/qs/tiles/HotspotTile;Landroid/content/ContentResolver;)V
    .locals 0

    iput-object p1, p0, Lcom/android/systemui/qs/tiles/HotspotTile$5;->this$0:Lcom/android/systemui/qs/tiles/HotspotTile;

    iput-object p2, p0, Lcom/android/systemui/qs/tiles/HotspotTile$5;->val$cr:Landroid/content/ContentResolver;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public onCancel(Landroid/content/DialogInterface;)V
    .locals 3

    iget-object v0, p0, Lcom/android/systemui/qs/tiles/HotspotTile$5;->val$cr:Landroid/content/ContentResolver;

    const-string/jumbo v1, "wifi_ap_wifi_sharing"

    const/4 v2, 0x0

    invoke-static {v0, v1, v2}, Landroid/provider/Settings$Secure;->putInt(Landroid/content/ContentResolver;Ljava/lang/String;I)Z

    iget-object v0, p0, Lcom/android/systemui/qs/tiles/HotspotTile$5;->this$0:Lcom/android/systemui/qs/tiles/HotspotTile;

    invoke-virtual {v0}, Lcom/android/systemui/qs/tiles/HotspotTile;->refreshState()V

    return-void
.end method


text:
package org.apache.hadoop.hdfs.server.datanode;

import java.io.IOException;

import org.apache.hadoop.hdfs.server.datanode.DataNode.BPOfferService;
import org.apache.hadoop.hdfs.server.protocol.DatanodeProtocol;
import org.apache.hadoop.hdfs.server.protocol.DatanodeRegistration;
import org.apache.hadoop.hdfs.server.protocol.NamespaceInfo;

/**
 * Utility class for accessing package-private DataNode information during tests.
 *
 */
public class DataNodeTestUtils {
  public static DatanodeRegistration
  getDNRegistrationByMachineName(DataNode dn, String mName) {
    return dn.getDNRegistrationByMachineName(mName);
  }

  public static DatanodeRegistration
  getDNRegistrationForBP(DataNode dn, String bpid) throws IOException {
    return dn.getDNRegistrationForBP(bpid);
  }

  /**
   * manually setup datanode to testing
   * @param dn - datanode
   * @param nsifno - namenode info
   * @param bpid - block pool id
   * @param nn - namenode object
   * @throws IOException
   */
  public static void setBPNamenodeByIndex(DataNode dn,
      NamespaceInfo nsifno, String bpid, DatanodeProtocol nn)
  throws IOException {
    // setup the right BPOS..
    BPOfferService [] bposs = dn.getAllBpOs();
    if(bposs.length<0) {
      throw new IOException("Datanode wasn't initializes with at least one NN");
    }
    for(BPOfferService bpos : bposs) {
      bpos.setNamespaceInfo(nsifno);

      dn.setBPNamenode(bpid, nn);
      bpos.setupBPStorage();
    }
  }
}


text:
package sbahjsic.runtime;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

import sbahjsic.core.Author;
import sbahjsic.core.ErrorHandler;
import sbahjsic.core.Main;
import sbahjsic.core.Version;
import sbahjsic.core.Warnings;
import sbahjsic.core.Warnings.Level;
import sbahjsic.interpreter.compiler.Instruction;
import sbahjsic.interpreter.lexer.Lexer;
import sbahjsic.interpreter.parser.SyntaxTree;
import sbahjsic.runtime.RuntimeContext.RuntimeType;
import sbahjsic.runtime.type.JavaBox;
import sbahjsic.runtime.type.SArray;
import sbahjsic.runtime.type.SBool;
import sbahjsic.runtime.type.SFloat;
import sbahjsic.runtime.type.SFunc;
import sbahjsic.runtime.type.SInt;
import sbahjsic.runtime.type.SLong;
import sbahjsic.runtime.type.SNull;
import sbahjsic.runtime.type.SRef;
import sbahjsic.runtime.type.SString;
import sbahjsic.runtime.type.SType;
import sbahjsic.runtime.type.SUndefined;
import sbahjsic.runtime.type.SVoid;
import sbahjsic.util.FuncUtils;

/** Contains functions that are in the memory at startup.*/
public final class DefaultFunctions {

	private final static Map<String, String> HELP = new HashMap<>();

	private DefaultFunctions() {
		throw new AssertionError();
	}

	private static void setHelp(String value, String help) {
		HELP.put(value, help);
	}

	/** Returns a {@code Map} that contains the default functions.*/
	public static Map<String, SValue> get(RuntimeType runtimeType) {
		Map<String, SValue> map = new HashMap<>();

		map.put("null", SNull.NULL);
		map.put("true", SBool.TRUE);
		map.put("false", SBool.FALSE);
		map.put("_void", SVoid.VOID);
		map.put("_undefined", SUndefined.UNDEFINED);

		setHelp("print", "Prints something.");
		map.put("print", new SFunc((con, args) -> {
			FuncUtils.requireArguments(1, args.length);
			System.out.println(args[0]);
			return SVoid.VOID;
		}));

		setHelp("typeof", "Returns the type of its argument.");
		map.put("typeof", new SFunc((con, args) -> {
			FuncUtils.requireArguments(1, args.length);
			return new SType(args[0].getType());
		}));

		setHelp("_getType", "Returns the type represented by its argument.");
		map.put("_getType", new SFunc((con, args) -> {
			return new SType(con.types().getType(args[0].asAddress()));
		}));

		setHelp("_string", "Converts its argument to string.");
		map.put("_string", new SFunc((con, args) -> {
			FuncUtils.requireArguments(1, args.length);
			return new SString(args[0].asString());
		}));

		setHelp("_bool", "Converts its argument to bool.");
		map.put("_bool", new SFunc((con, args) -> {
			FuncUtils.requireArguments(1, args.length);
			return args[0].asBool() ? SBool.TRUE : SBool.FALSE;
		}));

		setHelp("_int", "Converts its argument to int.");
		map.put("_int", new SFunc((con, args) -> {
			FuncUtils.requireArguments(1, args.length);
			return new SInt(args[0].asInt());
		}));

		setHelp("_long", "Converts its argument to long.");
		map.put("_long", new SFunc((con, args) -> {
			FuncUtils.requireArguments(1, args.length);
			return new SLong(args[0].asLong());
		}));

		setHelp("_float", "Converts its argument to float.");
		map.put("_float", new SFunc((con, args) -> {
			FuncUtils.requireArguments(1, args.length);
			return SFloat.sfloat(args[0].asFloat());
		}));

		setHelp("setHelp", "Sets the help text of some value.");
		map.put("setHelp", new SFunc((con, args) -> {
			FuncUtils.requireArguments(2, args.length);
			setHelp(args[0].asAddress(), args[1].asString());
			return SVoid.VOID;
		}));

		setHelp("help", "Returns the help text of some value.");
		map.put("help", new SFunc((con, args) -> {
			FuncUtils.requireArguments(1, args.length);
			System.out.println(HELP.get(args[0].asAddress()));
			return SVoid.VOID;
		}));

		setHelp("list", "Prints all defined variables.");
		map.put("list", new SFunc((con, args) -> {
			FuncUtils.requireMaxArguments(1, args.length);

			boolean printHidden = args.length == 1 ? args[0].asBool() : false;

			con.forMemoryValues((string, val) -> {
				if(val.refersTo() instanceof JavaBox && !printHidden) { return; }
				System.out.println("  ["+string+"] -> [" +
						(HELP.containsKey(string) ? HELP.get(string)
						: val.asString()) + "]");
			});
			return SVoid.VOID;
		}));

		setHelp("list_types", "Lists all types and their defined operators.");
		map.put("list_types", new SFunc((con, args) -> {
			FuncUtils.requireArguments(0, args.length);

			for(Type type : con.types().listTypes()) {
				Set<Type> supertypes = type.getSupertypes();
				System.out.println(type.getName() + " : " + supertypes);

				StringBuilder ops = new StringBuilder();

				for(Iterator<String> iter = type.getDefinedOperators().iterator()
						; iter.hasNext() ;) {
					ops.append(iter.next());
					if(!iter.hasNext()) { break; }
					ops.append(", ");
				}

				System.out.println("\tOPERATORS: " + ops);

				StringBuilder fields = new StringBuilder();
				for(Iterator<String> iter = type.getFields().iterator()
						; iter.hasNext() ;) {
					fields.append(iter.next());
					if(!iter.hasNext()) { break; }
					fields.append(", ");
				}

				System.out.println("\tFIELDS: " + fields);

				StringBuilder methods = new StringBuilder();
				for(Iterator<String> iter = type.getMethods().iterator()
						; iter.hasNext() ;) {
					methods.append(iter.next());
					if(!iter.hasNext()) { break; }
					methods.append(", ");
				}

				System.out.println("\tMETHODS: " + methods);
			}

			return SVoid.VOID;
		}));

		setHelp("del", "Deletes something from the memory.");
		map.put("del", new SFunc((con, args) -> {
			FuncUtils.requireArguments(1, args.length);
			con.scope().remove(args[0].asAddress());
			return SVoid.VOID;
		}));

		setHelp("ParseInt", "Parses its argument as an int. Returns undefined if failure.");
		map.put("ParseInt", new SFunc((con, args) -> {
			FuncUtils.requireArguments(1, args.length);
			try {
				return new SInt(Integer.parseInt(args[0].asString()));
			} catch(Exception e) {
				return SUndefined.UNDEFINED;
			}
		}));

		setHelp("ParseDec", "Parses a decimal. Returns undefined if failure.");
		map.put("ParseDec", new SFunc((con, args) -> {
			FuncUtils.requireArguments(1, args.length);
			try {
				return SFloat.sfloat(Float.parseFloat(args[0].asString()));
			} catch(Exception e) {
				return SUndefined.UNDEFINED;
			}
		}));

		setHelp("dependency", "Loads a native library if it has never been loaded before.");
		map.put("dependency", new SFunc((con, args) -> {
			FuncUtils.requireArguments(1, args.length);
			Warnings.warn(Level.ERROR, "Deprecated");
			return SVoid.VOID;
		}));

		setHelp("ref", "Creates a reference to the variable with the same name as its argument.");
		map.put("ref", new SFunc((con, args) -> {
			FuncUtils.requireArguments(1, args.length);
			return new SRef(args[0].asString(), con.scope().get(args[0].asString()));
		}));

		setHelp("target", "Indicates that this script is designed for a specific sbahjsic version.");
		map.put("target", new SFunc((con, args) -> {
			FuncUtils.requireArguments(1, args.length);
			Version version = null;
			try {
				version = Version.parse(args[0].asString());
			} catch(Exception e) {
				Warnings.warn("Invalid version number " + args[0].asString());
				return SVoid.VOID;
			}

			if(Version.NOW.compareTo(version) > 0) {
				Warnings.warn("Outdated library, targets " + version);
			} else if(Version.NOW.compareTo(version) < 0) {
				Warnings.warn("Outdated Sbahjsic, library targets " + version);
			}

			return SVoid.VOID;
		}));

		setHelp("array", "Creates an array with as many elements as the argument.");
		map.put("array", new SFunc((con, args) -> {
			FuncUtils.requireArguments(1, args.length);
			return new SArray(args[0].asInt());
		}));

		setHelp("version", "The current version as a string.");
		map.put("version", new SString(Version.NOW.toString()));

		setHelp("exit", "Exits the interpreter.");
		map.put("exit", new SFunc((con, args) -> { System.exit(0); return null; }));

		setHelp("sbahjsic", "Launches a Sbahjsic interpreter with the given arguments.");
		map.put("sbahjsic", new SFunc((con, args) -> {
			Main.main(Arrays.stream(args)
					.map(Object::toString)
					.toArray(String[]::new));
			return SVoid.VOID;
		}));

		setHelp("SET_FATAL", "Sets the error level that leads to termination. Returns the old value.");
		map.put("SET_FATAL", new SFunc((con, args) -> {
			FuncUtils.requireArguments(1, args.length);
			String level = args[0].asString();
			String oldLevel = Warnings.TERMINATION_LEVEL.toString();
			try {
				Warnings.TERMINATION_LEVEL = Warnings.Level.valueOf(level);
			} catch(Exception e) {
				Warnings.TERMINATION_LEVEL = Warnings.Level.NONE;
			}
			return new SString(oldLevel);
		}));

		setHelp("fatalLvl", "Returns the error level that leads to termination.");
		map.put("fatalLvl", new SFunc((con, args) -> {
			return new SString(Warnings.TERMINATION_LEVEL.toString());
		}));

		setHelp("eval", "Evaluates Sbahjsic code.");
		map.put("eval", new SFunc((con, args) -> {
			FuncUtils.requireArguments(1, args.length);
			String evalString = args[0].asString();

			Instruction[] ins = new SyntaxTree(Lexer.toTokens(evalString)).mainNode().toInstructions();

			Optional<SValue> returnValue = new ExecutionEnvironment(con).executeInstructions("eval", ins);

			return returnValue.orElse(SVoid.VOID);
		}));

		setHelp("REG_ERRH", "Adds an error handler. The first argument is the handler which takes "
				+ "the warning level and the error message.");
		map.put("REG_ERRH", new SFunc((con, args) -> {
			FuncUtils.requireArguments(1, args.length);
			Warnings.addErrorHandler(ErrorHandler.sbahjsicExecutor(args[0], con));
			return SVoid.VOID;
		}));

		setHelp("Credits_Names", "Returns an array containing the credited developers.");
		map.put("Credits_Names", new SFunc((con, args) -> {
			return new SArray(con.authors().stream()
					.map(Author::name)
					.map(SString::new)
					.toArray(SValue[]::new));
		}));

		setHelp("__ARGS", "The program arguments in executable mode.");
		map.put("__ARGS", new SArray(Arrays.stream(Main.ARGS.SBAHJSIC_ARGS)
				.map(SString::new)
				.toArray(SValue[]::new)));

		setHelp("main", "Only in buildscript mode: sets the main library.");
		setHelp("lib", "Only in buildscript mode: adds a library to be packed into the binary.");
		setHelp("name", "Only in buildscript mode: sets the executable file name.");

		if(runtimeType == RuntimeType.BUILDSCRIPT) {

			map.put("main", new SFunc((con, args) -> {
				FuncUtils.requireArguments(1, args.length);
				con.buildscriptMetadata().main = args[0].asString();
				return SVoid.VOID;
			}));

			map.put("lib", new SFunc((con, args) -> {
				for(SValue arg : args) {
					con.buildscriptMetadata().libs.add(arg.asString());
				}
				return SVoid.VOID;
			}));

			map.put("name", new SFunc((con, args) -> {
				FuncUtils.requireArguments(1, args.length);
				con.buildscriptMetadata().name = args[0].asString();
				return SVoid.VOID;
			}));
		}

		return map;
	}
}


text:
package org.foxlabs.etk;

import java.io.Serializable;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.foxlabs.etk.io.NodeInputStream;
import org.foxlabs.etk.io.NodeOutputStream;
import org.foxlabs.etk.node.Node;
import org.foxlabs.etk.node.NodeVisitor;

public class Expression implements Serializable {
    private static final long serialVersionUID = 5608323719628721515L;

    private transient Node root;
    private transient int hash = 0;

    private String source;

    public Expression(Node root) {
        this(root, null);
    }

    public Expression(Node root, String source) {
        if (root == null)
            throw new NullPointerException();
        this.root = root;
        setSource(source);
    }

    public final Node getRootNode() {
        return root;
    }

    public final Class<?> getType() {
        return root.getType();
    }

    public Object evaluate(Environment context) throws EvaluationException {
        try {
            return root.evaluate(context);
        } catch (EvaluationException e) {
            e.setOwner(this);
            throw e;
        }
    }

    public final <T extends Throwable> void accept(NodeVisitor<T> visitor) throws T {
        root.accept(visitor);
    }

    public String getSource() {
        return source;
    }

    public void setSource(String source) {
        this.source = source;
    }

    public int hashCode() {
        if (hash == 0)
            hash = root.hashCode();
        return hash;
    }

    public boolean equals(Object obj) {
        return obj instanceof Expression &&
               ((Expression) obj).root.equals(root);
    }

    public String toString() {
        return source == null ? root.toString() : source;
    }

    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        in.defaultReadObject();
        Environment context = DefaultEnvironment.getGlobalContext();
        try (NodeInputStream stream = new NodeInputStream(in)) {
            root = stream.readNode(context);
        }
    }

    private void writeObject(ObjectOutputStream out) throws IOException {
        out.defaultWriteObject();
        NodeOutputStream nout = out instanceof NodeOutputStream
            ? (NodeOutputStream) out
            : new NodeOutputStream(out);
        nout.writeNode(root);
        nout.flush();
    }

}


text:
import schunk
import serial
import argparse
from sys import stderr
import configparser

def arg_options():

    # init options
    parser = argparse.ArgumentParser(
        description='''A simple programm for moving the varisphear by using cmd-line.
                    It support you by determine the nodalpoint ''')

    parser.add_argument(
        '-l',
        type=float,
        nargs=1,
        dest='left',
        default=None,
        metavar=('DEGREE'),
        help='Rotate DEGREE steps anticlockwise ')

    parser.add_argument(
        '-r',
        type=float,
        nargs=1,
        dest='right',
        default=None,
        metavar=('DEGREE'),
        help='Rotate DEGREE steps clockwise ')

    parser.add_argument(
        '--down',
        dest='down',
        action='store_true',
        help='Drive the top.modul to the -90 degree position')

    parser.add_argument(
        '--up',
        dest='up',
        action='store_true',
        help='Drive the top.modul to the 0 degree position')

    parser.add_argument(
        '--init',
        dest='init',
        action='store_true',
        help='Drive both moduls to the 0 degree position ')

    parser.add_argument(
        '--config',
        dest='config',
        default=None,
        metavar=('CONFIGFILE'),
        help='''Specifies the realtive path to "panorama.cfg"
        ( default: panorama.cfg ) ''')

    # return arguments
    return parser.parse_args()

def main():

    # get arguments
    args = arg_options()

    # set path to panorama.cfg
    path_cfg = args.config
    if(not path_cfg):
        path_cfg = 'panorama.cfg'

    # get values from 'path_cfg'
    config = configparser.ConfigParser()
    try:
        config.read(path_cfg)
        test = config['camera']['vertical_angle']
    except:
        stderr.write("\n ERROR: Can´t open file: %s !\n exit \n" % path_cfg)
        exit()

    # Get Interfaces / Ports to VariSphear
    port_top = config['varisphear']['serialport_top']
    port_base = config['varisphear']['serialport_base']

    # Init motor
    try:
        # "top" indicate the motor,
        #   which is responsible for the vertical rotation

        top = schunk.Module(schunk.SerialConnection(
            0x0B, serial.Serial, port=port_top, baudrate=9600, timeout=None))

        if(not top.toggle_impulse_message()):
            top.toggle_impulse_message()
    except:
        stderr.write("\nERROR @takingPicture by connecting to top schunkModul")
        exit()

    try:
        # "base" indicate the motor,
        #   which is responsible for the horizontal rotation
        base = schunk.Module(schunk.SerialConnection(
            0x0B, serial.Serial, port=port_base, baudrate=9600, timeout=None))

        if(not base.toggle_impulse_message()):
            base.toggle_impulse_message()
    except:
        stderr.write(
            "\nERROR @takingPicture by connecting to base schunkModul")
        exit()

    if(args.left):
        print("left: " + str(args.left[0] % 360.0))
        base.move_pos_rel_blocking(args.left[0] % 360.0)
    elif(args.right):
        print("right: " + str(-(args.right[0] % 360.0)))
        base.move_pos_rel_blocking(-(args.right[0] % 360.0))

    if(args.init):
        print("init")
        top.move_pos_blocking(0)
        base.move_pos_blocking(0)
    elif(args.up):
        print("up")
        top.move_pos_blocking(0)
    elif(args.down):
        print("down")
        top.move_pos_blocking(90)

if __name__ == '__main__':

    main()


text:
package proc.dualprocess;

import reward.Reward;
import reward.RewardValue;
import action.PrimitiveAction;
import agent.Agent;

public class FoodTask extends EpisodicLeverMagazineTask {

	private static final long serialVersionUID = -8779191727418587216L;

	public FoodTask(Agent agent, RewardValue rewardValue, int maxNumberOfTrials) {
		super(agent, rewardValue, maxNumberOfTrials);
	}

	@Override
	public Reward nextState(PrimitiveAction action) {
		return nextState(action, rewardValue.getR1(), rewardValue.zero());
	}
}


text:
@implementation DTAttributedTextCell
{
	NSAttributedString *_attributedString;
	DTAttributedTextContentView *_attributedTextContextView;

	NSUInteger _htmlHash; // preserved hash to avoid relayouting for same HTML
}

- (id)initWithReuseIdentifier:(NSString *)reuseIdentifier accessoryType:(UITableViewCellAccessoryType)accessoryType
{
    self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
    if (self)
	{
		// don't know size jetzt because there's no string in it
		_attributedTextContextView = [[DTAttributedTextContentView alloc] initWithFrame:CGRectZero];
		_attributedTextContextView.edgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);
		[self.contentView addSubview:_attributedTextContextView];
    }
    return self;
}

- (void)layoutSubviews
{
	[super layoutSubviews];

	CGFloat neededContentHeight = [self requiredRowHeightInTableView:(UITableView *)self.superview];

	// after the first call here the content view size is correct
	CGRect frame = CGRectMake(0, 0, self.contentView.bounds.size.width, neededContentHeight);

	// only change frame if width has changed to avoid extra layouting
	if (_attributedTextContextView.frame.size.width != frame.size.width)
	{
		_attributedTextContextView.frame = frame;
	}
}

- (void)willMoveToSuperview:(UIView *)newSuperview
{
	UITableView *tableView = (UITableView *)newSuperview;

	if (tableView.style == UITableViewStyleGrouped)
	{
		// need no background because otherwise this would overlap the rounded corners
		_attributedTextContextView.backgroundColor = [DTColor clearColor];
	}

	[super willMoveToSuperview:newSuperview];
}

- (CGFloat)requiredRowHeightInTableView:(UITableView *)tableView
{

	CGFloat contentWidth = tableView.frame.size.width;

	// reduce width for accessories
	switch (self.accessoryType)
	{
		case UITableViewCellAccessoryDisclosureIndicator:
		case UITableViewCellAccessoryCheckmark:
			contentWidth -= 20.0f;
			break;
		case UITableViewCellAccessoryDetailDisclosureButton:
			contentWidth -= 33.0f;
			break;
		case UITableViewCellAccessoryNone:
			break;
	}

	// reduce width for grouped table views
	if (tableView.style == UITableViewStyleGrouped)
	{
		contentWidth -= 19;
	}

	CGSize neededSize = [_attributedTextContextView suggestedFrameSizeToFitEntireStringConstraintedToWidth:contentWidth];

	// note: non-integer row heights caused trouble < iOS 5.0
	return neededSize.height;
}

#pragma mark Properties

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)setHTMLString:(NSString *)html
{
	// we don't preserve the html but compare it's hash
	NSUInteger newHash = [html hash];

	if (newHash == _htmlHash)
	{
		return;
	}

	_htmlHash = newHash;

	NSData *data = [html dataUsingEncoding:NSUTF8StringEncoding];
	NSAttributedString *string = [[NSAttributedString alloc] initWithHTML:data documentAttributes:NULL];
	self.attributedString = string;
}

- (void)setAttributedString:(NSAttributedString *)attributedString
{
	if (_attributedString != attributedString)
	{
		_attributedString = attributedString;

		// passthrough
		_attributedTextContextView.attributedString = _attributedString;
	}
}

@synthesize attributedString = _attributedString;
@synthesize attributedTextContextView = _attributedTextContextView;

@end


text:
rakefile = File.expand_path 'Rakefile'
`/usr/bin/osascript reveal_in_finder.scpt "#{rakefile}"`


text:
var fs = require('fs');

var fileData = fs.readFile('../resource/file/readTest.txt',
 function (err, data) {
  if (err) {
    console.log('ERROR');
    console.log(err);
  }

  console.log('CallBack Data = ' + data);
});
console.log('Out of Callback Data = ' + fileData);
console.log('sync = ' + fs.readFileSync('../resource/file/readTest.txt'));


text:
package org.w3c.domts.level1.core;

import org.w3c.dom.*;

import org.w3c.domts.DOMTestCase;
import org.w3c.domts.DOMTestDocumentBuilderFactory;

/**
 * Attempt to append a text node from another document to an attribute which should result
 * in a WRONG_DOCUMENT_ERR.
* @author Curt Arnold
* @see http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-637646024
* @see http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-952280727
*/
public final class hc_attrinsertbefore6 extends DOMTestCase {

   /**
    * Constructor.
    * @param factory document factory, may not be null
    * @throws org.w3c.domts.DOMTestIncompatibleException Thrown if test is not compatible with parser configuration
    */
   public hc_attrinsertbefore6(final DOMTestDocumentBuilderFactory factory)  throws org.w3c.domts.DOMTestIncompatibleException {
      super(factory);

    //
    //   check if loaded documents are supported for content type
    //
    String contentType = getContentType();
    preload(contentType, "hc_staff", true);
    preload(contentType, "hc_staff", true);
    }

   /**
    * Runs the test case.
    * @throws Throwable Any uncaught exception causes test to fail
    */
   public void runTest() throws Throwable {
      Document doc;
      NodeList acronymList;
      Node testNode;
      NamedNodeMap attributes;
      Attr titleAttr;
      String value;
      Node textNode;
      Node retval;
      Node refChild = null;

      Document otherDoc;
      doc = (Document) load("hc_staff", true);
      otherDoc = (Document) load("hc_staff", true);
      acronymList = doc.getElementsByTagName("acronym");
      testNode = acronymList.item(3);
      attributes = testNode.getAttributes();
      titleAttr = (Attr) attributes.getNamedItem("title");
      textNode = otherDoc.createTextNode("terday");

      {
         boolean success = false;
         try {
            retval = titleAttr.insertBefore(textNode, refChild);
          } catch (DOMException ex) {
            success = (ex.code == DOMException.WRONG_DOCUMENT_ERR);
         }
         assertTrue("throw_WRONG_DOCUMENT_ERR", success);
      }
}
   /**
    *  Gets URI that identifies the test.
    *  @return uri identifier of test
    */
   public String getTargetURI() {
      return "http://www.w3.org/2001/DOM-Test-Suite/level1/core/hc_attrinsertbefore6";
   }
   /**
    * Runs this test from the command line.
    * @param args command line arguments
    */
   public static void main(final String[] args) {
        DOMTestCase.doMain(hc_attrinsertbefore6.class, args);
   }
}


text:
Features
--------

- Documentation: https://pureyaml.readthedocs.org
- Open Source: https://github.com/bionikspoon/pureyaml
- MIT license

- YAML encoder/decoder written in pure python


text:
HyperLogLog-based set cardinality estimation library

This library estimates the number of unique elements in a set, in a quick and memory-efficient manner.  It's based on the following:

1. Flajolet et al., "HyperLogLog: the analysis of a near-optimal cardinality estimation algorithm", DMTCS proc. AH 2007, http://algo.inria.fr/flajolet/Publications/FlFuGaMe07.pdf
2. Heule, Nunkesser and Hall 2013, "HyperLogLog in Practice: Algorithmic Engineering of a State of The Art Cardinality Estimation Algorithm", http://static.googleusercontent.com/external_content/untrusted_dlcp/research.google.com/en/us/pubs/archive/40671.pdf

The accuracy/memory usage are user-selectable.  Typically, a cardinality estimator will give a perfect estimate of small cardinalities (up to 100 unique elements), and 97% accuracy or better (usually much better) for any cardinality up to near 2^64, while consuming several KB of memory (no more than 16KB).

## Usage
Usage is very simple:
```
ICardinalityEstimator<string> estimator = new CardinalityEstimator();

estimator.Add("Alice");
estimator.Add("Bob");
estimator.Add("Alice");
estimator.Add("George Michael");

ulong numberOfuniqueElements = estimator.Count(); // will be 3
```

## Nuget Package
This code is available as the Nuget package [`CardinalityEstimation`](https://www.nuget.org/packages/CardinalityEstimation/).  To install, run the following command in the Package Manager Console:
```
Install-Package CardinalityEstimation
```


text:
<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="rectangle"
  xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient android:startColor="@color/SplashBgTopColor" android:endColor="@color/SplashBgBotColor" android:angle="-90.0" />
</shape>


text:
module AccountTransactionsHelper
end


text:
"""
Test `EnvironmentError` reporting.

In some locales, the `errstr` argument of IOError and OSError contains
non-ASCII chars.

In Python 2, converting an exception instance to `str` or `unicode`
might fail, with non-ASCII chars in arguments and the default encoding
and errors ('ascii', 'strict').

Therefore, Docutils must not use string interpolation with exception
instances like, e.g., ::

  try:
    something
  except IOError, error:
    print 'Found %s' % error

unless the minimal required Python version has this problem fixed.
"""

import unittest
import sys, os
import codecs
try: # from standard library module `io`
    from io import StringIO, BytesIO
except ImportError: # new in Python 2.6
    from StringIO import StringIO
    BytesIO = StringIO

import DocutilsTestSupport              # must be imported before docutils
from docutils import core, parsers, frontend, utils
from docutils.utils.error_reporting import SafeString, ErrorString, ErrorOutput
from docutils._compat import b, bytes

oldlocale = None
if sys.version_info < (3,0): # problems solved in py3k
    try:
        import locale # module missing in Jython
        oldlocale = locale.getlocale()
        # Why does getlocale return the defaultlocale in Python 3.2 ????
        # oldlocale = (None, None) # test suite runs without locale
    except ImportError:
        print ('cannot test error reporting with problematic locales,\n'
            '`import locale` failed.')

# locales confirmed to use non-ASCII chars in the IOError message
# for a missing file (https://bugs.gentoo.org/show_bug.cgi?id=349101)
# TODO: add more confirmed problematic locales
problematic_locales = ['cs_CZ', 'cs_CZ.UTF8',
                       'el_GR', 'el_GR.UTF-8',
                       # 'fr_FR.UTF-8', # only OSError
                       'ja_JP.UTF-8',
                       'ru_RU', 'ru_RU.KOI8-R',
                       'ru_RU.UTF-8',
                       '',  # default locale: might be non-problematic
                       ]

if oldlocale is not None:
    # find a supported problematic locale:
    for testlocale in problematic_locales:
        try:
            locale.setlocale(locale.LC_ALL, testlocale)
        except locale.Error:
            testlocale = None
        else:
            break
    locale.setlocale(locale.LC_ALL, oldlocale) # reset
else:
    testlocale = None

class SafeStringTests(unittest.TestCase):
    # the error message in EnvironmentError instances comes from the OS
    # and in some locales (e.g. ru_RU), contains high bit chars.
    # -> see the test in test_error_reporting.py

    # test data:
    bs = b('\xfc')     # unicode(bs) fails, str(bs) in Python 3 return repr()
    us = u'\xfc'       # bytes(us) fails; str(us) fails in Python 2
    be = Exception(bs) # unicode(be) fails
    ue = Exception(us) # bytes(ue) fails, str(ue) fails in Python 2;
                       # unicode(ue) fails in Python < 2.6 (issue2517_)
                       # .. _issue2517: http://bugs.python.org/issue2517
    # wrapped test data:
    wbs = SafeString(bs)
    wus = SafeString(us)
    wbe = SafeString(be)
    wue = SafeString(ue)

    def test_7bit(self):
        # wrapping (not required with 7-bit chars) must not change the
        # result of conversions:
        bs7 = b('foo')
        us7 = u'foo'
        be7 = Exception(bs7)
        ue7 = Exception(us7)
        self.assertEqual(str(42), str(SafeString(42)))
        self.assertEqual(str(bs7), str(SafeString(bs7)))
        self.assertEqual(str(us7), str(SafeString(us7)))
        self.assertEqual(str(be7), str(SafeString(be7)))
        self.assertEqual(str(ue7), str(SafeString(ue7)))
        self.assertEqual(unicode(7), unicode(SafeString(7)))
        self.assertEqual(unicode(bs7), unicode(SafeString(bs7)))
        self.assertEqual(unicode(us7), unicode(SafeString(us7)))
        self.assertEqual(unicode(be7), unicode(SafeString(be7)))
        self.assertEqual(unicode(ue7), unicode(SafeString(ue7)))

    def test_ustr(self):
        """Test conversion to a unicode-string."""
        # unicode(self.bs) fails
        self.assertEqual(unicode, type(unicode(self.wbs)))
        self.assertEqual(unicode(self.us), unicode(self.wus))
        # unicode(self.be) fails
        self.assertEqual(unicode, type(unicode(self.wbe)))
        # unicode(ue) fails in Python < 2.6 (issue2517_)
        self.assertEqual(unicode, type(unicode(self.wue)))
        self.assertEqual(self.us, unicode(self.wue))

    def test_str(self):
        """Test conversion to a string (bytes in Python 2, unicode in Python 3)."""
        self.assertEqual(str(self.bs), str(self.wbs))
        self.assertEqual(str(self.be), str(self.be))
        # str(us) fails in Python 2
        self.assertEqual(str, type(str(self.wus)))
        # str(ue) fails in Python 2
        self.assertEqual(str, type(str(self.wue)))

class ErrorStringTests(unittest.TestCase):
    bs = b('\xfc')     # unicode(bs) fails, str(bs) in Python 3 return repr()
    us = u'\xfc'       # bytes(us) fails; str(us) fails in Python 2

    def test_str(self):
        self.assertEqual('Exception: spam',
                         str(ErrorString(Exception('spam'))))
        self.assertEqual('IndexError: '+str(self.bs),
                         str(ErrorString(IndexError(self.bs))))
        self.assertEqual('ImportError: %s' % SafeString(self.us),
                         str(ErrorString(ImportError(self.us))))

    def test_unicode(self):
        self.assertEqual(u'Exception: spam',
                         unicode(ErrorString(Exception(u'spam'))))
        self.assertEqual(u'IndexError: '+self.us,
                         unicode(ErrorString(IndexError(self.us))))
        self.assertEqual(u'ImportError: %s' % SafeString(self.bs),
                         unicode(ErrorString(ImportError(self.bs))))

# ErrorOutput tests
# -----------------

# Stub: Buffer with 'strict' auto-conversion of input to byte string:
class BBuf(BytesIO, object): # super class object required by Python <= 2.5
    def write(self, data):
        if isinstance(data, unicode):
            data.encode('ascii', 'strict')
        super(BBuf, self).write(data)

# Stub: Buffer expecting unicode string:
class UBuf(StringIO, object): # super class object required by Python <= 2.5
    def write(self, data):
        # emulate Python 3 handling of stdout, stderr
        if isinstance(data, bytes):
            raise TypeError('must be unicode, not bytes')
        super(UBuf, self).write(data)

class ErrorOutputTests(unittest.TestCase):
    def test_defaults(self):
        e = ErrorOutput()
        self.assertEqual(e.stream, sys.stderr)

    def test_bbuf(self):
        buf = BBuf() # buffer storing byte string
        e = ErrorOutput(buf, encoding='ascii')
        # write byte-string as-is
        e.write(b('b\xfc'))
        self.assertEqual(buf.getvalue(), b('b\xfc'))
        # encode unicode data with backslashescape fallback replacement:
        e.write(u' u\xfc')
        self.assertEqual(buf.getvalue(), b('b\xfc u\\xfc'))
        # handle Exceptions with Unicode string args
        # unicode(Exception(u'e\xfc')) # fails in Python < 2.6
        e.write(AttributeError(u' e\xfc'))
        self.assertEqual(buf.getvalue(), b('b\xfc u\\xfc e\\xfc'))
        # encode with `encoding` attribute
        e.encoding = 'utf8'
        e.write(u' u\xfc')
        self.assertEqual(buf.getvalue(), b('b\xfc u\\xfc e\\xfc u\xc3\xbc'))

    def test_ubuf(self):
        buf = UBuf() # buffer only accepting unicode string
        # decode of binary strings
        e = ErrorOutput(buf, encoding='ascii')
        e.write(b('b\xfc'))
        self.assertEqual(buf.getvalue(), u'b\ufffd') # use REPLACEMENT CHARACTER
        # write Unicode string and Exceptions with Unicode args
        e.write(u' u\xfc')
        self.assertEqual(buf.getvalue(), u'b\ufffd u\xfc')
        e.write(AttributeError(u' e\xfc'))
        self.assertEqual(buf.getvalue(), u'b\ufffd u\xfc e\xfc')
        # decode with `encoding` attribute
        e.encoding = 'latin1'
        e.write(b(' b\xfc'))
        self.assertEqual(buf.getvalue(), u'b\ufffd u\xfc e\xfc b\xfc')

class SafeStringTests_locale(unittest.TestCase):
    """
    Test docutils.SafeString with 'problematic' locales.

    The error message in `EnvironmentError` instances comes from the OS
    and in some locales (e.g. ru_RU), contains high bit chars.
    """
    if testlocale:
        locale.setlocale(locale.LC_ALL, testlocale)
    # test data:
    bs = b('\xfc')
    us = u'\xfc'
    try:
        open(b('\xfc'))
    except IOError, e: # in Python 3 the name for the exception instance
        bioe = e       # is local to the except clause
    try:
        open(u'\xfc')
    except IOError, e:
        uioe = e
    except UnicodeEncodeError:
        try:
            open(u'\xfc'.encode(sys.getfilesystemencoding(), 'replace'))
        except IOError, e:
            uioe = e
    try:
        os.chdir(b('\xfc'))
    except OSError, e:
        bose = e
    try:
        os.chdir(u'\xfc')
    except OSError, e:
        uose = e
    except UnicodeEncodeError:
        try:
            os.chdir(u'\xfc'.encode(sys.getfilesystemencoding(), 'replace'))
        except OSError, e:
            uose = e
    # wrapped test data:
    wbioe = SafeString(bioe)
    wuioe = SafeString(uioe)
    wbose = SafeString(bose)
    wuose = SafeString(uose)
    # reset locale
    if testlocale:
        locale.setlocale(locale.LC_ALL, oldlocale)

    def test_ustr(self):
        """Test conversion to a unicode-string."""
        # unicode(bioe) fails with e.g. 'ru_RU.utf8' locale
        self.assertEqual(unicode, type(unicode(self.wbioe)))
        self.assertEqual(unicode, type(unicode(self.wuioe)))
        self.assertEqual(unicode, type(unicode(self.wbose)))
        self.assertEqual(unicode, type(unicode(self.wuose)))

    def test_str(self):
        """Test conversion to a string (bytes in Python 2, unicode in Python 3)."""
        self.assertEqual(str(self.bioe), str(self.wbioe))
        self.assertEqual(str(self.uioe), str(self.wuioe))
        self.assertEqual(str(self.bose), str(self.wbose))
        self.assertEqual(str(self.uose), str(self.wuose))

class ErrorReportingTests(unittest.TestCase):
    """
    Test cases where error reporting can go wrong.

    Do not test the exact output (as this varies with the locale), just
    ensure that the correct exception is thrown.
    """

    # These tests fail with a 'problematic locale',
    # Docutils revision < 7035, and Python 2:

    parser = parsers.rst.Parser()
    """Parser shared by all ParserTestCases."""

    option_parser = frontend.OptionParser(components=(parsers.rst.Parser,))
    settings = option_parser.get_default_values()
    settings.report_level = 1
    settings.halt_level = 1
    settings.warning_stream = ''
    document = utils.new_document('test data', settings)

    def setUp(self):
        if testlocale:
            locale.setlocale(locale.LC_ALL, testlocale)

    def tearDown(self):
        if testlocale:
            locale.setlocale(locale.LC_ALL, oldlocale)

    def test_include(self):
        source = ('.. include:: bogus.txt')
        self.assertRaises(utils.SystemMessage,
                          self.parser.parse, source, self.document)

    def test_raw_file(self):
        source = ('.. raw:: html\n'
                  '   :file: bogus.html\n')
        self.assertRaises(utils.SystemMessage,
                          self.parser.parse, source, self.document)

    def test_csv_table(self):
        source = ('.. csv-table:: external file\n'
                  '   :file: bogus.csv\n')
        self.assertRaises(utils.SystemMessage,
                          self.parser.parse, source, self.document)

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


text:
<?php

class BandForm extends Page {

}

class BandForm_Controller extends Page_Controller {

	function Form() {

		return new Form($this, "Form", new FieldSet(
			// List your fields here
			new LiteralField("primaryInfo", "
add a band

"),
			new TextareaField("bandMembers", "Band Members", "3", "37"),
			new TextField("bandName", "Band Name"),
			new EmailField("Email", "Email Address *"),
			new TextField("Facebook", "Facebook Page"),
			new TextField("Youtube", "Youtube Link"),
			new TextareaField("otherLink", "Other Links", "3", "37"),
			new TextareaField("Description", "Description", "3", "37"),
			new FileField(
				"ProfilePhoto",
				"Profile Photo",
				"Upload your profile photo
"
				/*array (
					'file_upload_limit' => '1',
					'required' => 'false'
				)*/
			),
			new LiteralField("endInfo", "
")),
			new FieldSet(
				new FormAction("SubmitEnquiry", "Submit")
 			),
 			new RequiredFields(
 				"Name", "Email", "bandName"
			));
	}

	function SubmitEnquiry($data, $form) {

		// $MemberProfile = new MemberProfile();
		// $form->saveInto($MemberProfile);

		$form->makeReadonly();
		$email = new Email;
		$email->to = 'digital.pollution.net@gmail.com';
		$email->from = 'digital.pollution.net@gmail.com';
		$email->subject = 'Band Profile submission';
		$email->body = $form->forTemplate();
		$data = $form->getData();
		if (isset($data['ProfilePhoto'])) {
			$file = $data['ProfilePhoto'];
			if (file_exists($file['tmp_name'])) {
		 		// TODO: Attempt to check the mime type or extension, size, etc. before just sending on.
				$email->attachFile($file['tmp_name'], $file['name']);
			}
		}
		$email->send();
		$MemberProfile->write();
		Session::set('FileUploaded', true);

			// Redirect to a page thanking people for registering
			Director::redirect('thanks-for-your-submission/');

	}}

?>


text:
SYNONYM

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

#### Published in
Proc. 2nd. Symp. Invest. Myco-Lichens Fl. Baltic Reps 117 (1963)

#### Original name
Plasmopara megasperma Savul., 1941

### Remarks
null


text:
#pragma once

#include "RetroTypes.hpp"
#include "zeus/CColor.hpp"
#include "CFactoryMgr.hpp"
#include "CToken.hpp"
#include "zeus/CAABox.hpp"
#include "DNACommon/CMDL.hpp"
#include "DNAMP1/CMDLMaterials.hpp"
#include "Shaders/CModelShaders.hpp"
#include "hecl/HMDLMeta.hpp"
#include "boo/graphicsdev/IGraphicsDataFactory.hpp"

namespace urde {
class IObjectStore;
class CTexture;
class CLight;
class CSkinRules;
class CPoseAsTransforms;
class CModel;

struct CModelFlags {
  u8 x0_blendMode = 0; /* 2: add color, >6: additive, >4: blend, else opaque */
  u8 x1_matSetIdx = 0;
  EExtendedShader m_extendedShader = EExtendedShader::Lighting;
  bool m_noCull = false;
  bool m_noZWrite = false;
  bool m_depthGreater = false;
  u16 x2_flags = 0;      /* Flags */
  zeus::CColor x4_color; /* Set into kcolor slot specified by material */
  zeus::CColor addColor = zeus::skClear;
  zeus::CAABox mbShadowBox;

  CModelFlags() = default;
  CModelFlags(u8 blendMode, u8 shadIdx, u16 flags, const zeus::CColor& col)
  : x0_blendMode(blendMode), x1_matSetIdx(shadIdx), x2_flags(flags), x4_color(col) {
    /* Blend mode will override this if the surface's original material is opaque */
    m_noZWrite = !(x2_flags & 0x2);
    m_depthGreater = (x2_flags & 0x8);
  }

  /* Flags
      0x1: depth equal
      0x2: depth update
      0x4: render without texture lock
      0x8: depth greater
      0x10: depth non-inclusive
   */

  bool operator==(const CModelFlags& other) const {
    return x0_blendMode == other.x0_blendMode && x1_matSetIdx == other.x1_matSetIdx && x2_flags == other.x2_flags &&
           x4_color == other.x4_color;
  }

  bool operator!=(const CModelFlags& other) const {
    return x0_blendMode != other.x0_blendMode || x1_matSetIdx != other.x1_matSetIdx || x2_flags != other.x2_flags ||
           x4_color != other.x4_color;
  }
};

/* urde addition: doesn't require hacky stashing of
 * pointers within loaded CMDL buffer */
struct CBooSurface {
  DataSpec::DNACMDL::SurfaceHeader_2 m_data;
  size_t selfIdx;
  class CBooModel* m_parent = nullptr;
  CBooSurface* m_next = nullptr;

  zeus::CAABox GetBounds() const {
    if (!m_data.aabbSz)
      return zeus::CAABox(m_data.centroid, m_data.centroid);
    else
      return zeus::CAABox(m_data.aabb[0], m_data.aabb[1]);
  }
};

using MaterialSet = DataSpec::DNAMP1::HMDLMaterialSet;

struct GeometryUniformLayout {
  mutable std::vector<boo::ObjToken<boo::IGraphicsBufferD>> m_sharedBuffer;
  size_t m_geomBufferSize = 0;
  size_t m_skinBankCount = 0;
  size_t m_weightVecCount = 0;

  std::vector<size_t> m_skinOffs;
  std::vector<size_t> m_skinSizes;

  std::vector<size_t> m_uvOffs;
  std::vector<size_t> m_uvSizes;

  GeometryUniformLayout(const CModel* model, const MaterialSet* matSet);
  void Update(const CModelFlags& flags, const CSkinRules* cskr, const CPoseAsTransforms* pose,
              const MaterialSet* matSet, const boo::ObjToken<boo::IGraphicsBufferD>& buf,
              const CBooModel* parent) const;

  void ReserveSharedBuffers(boo::IGraphicsDataFactory::Context& ctx, int size);
  boo::ObjToken<boo::IGraphicsBufferD> GetSharedBuffer(int idx) const;
};

struct SShader {
  std::unordered_map<CAssetId, TCachedToken<CTexture>> x0_textures;
  std::unordered_map<int, CModelShaders::ShaderPipelines> m_shaders;
  MaterialSet m_matSet;
  std::optional<GeometryUniformLayout> m_geomLayout;
  int m_matSetIdx;
  SShader(int idx) : m_matSetIdx(idx) {
    x0_textures.clear();
    m_shaders.clear();
  }
  void InitializeLayout(const CModel* model) { m_geomLayout.emplace(model, &m_matSet); }
  void UnlockTextures();
  CModelShaders::ShaderPipelines BuildShader(const hecl::HMDLMeta& meta, const MaterialSet::Material& mat);
  void BuildShaders(const hecl::HMDLMeta& meta, std::unordered_map<int, CModelShaders::ShaderPipelines>& shaders);
  void BuildShaders(const hecl::HMDLMeta& meta) { BuildShaders(meta, m_shaders); }
};

class CBooModel {
  friend class CModel;
  friend class CGameArea;
  friend class CBooRenderer;
  friend class CMetroidModelInstance;
  friend class CSkinnedModel;
  friend struct GeometryUniformLayout;

public:
  enum class ESurfaceSelection { UnsortedOnly, SortedOnly, All };

private:
  CBooModel* m_next = nullptr;
  CBooModel* m_prev = nullptr;
  size_t m_uniUpdateCount = 0;
  TToken<CModel> m_modelTok;
  CModel* m_model;
  std::vector<CBooSurface>* x0_surfaces;
  const MaterialSet* x4_matSet;
  const GeometryUniformLayout* m_geomLayout;
  int m_matSetIdx = -1;
  const std::unordered_map<int, CModelShaders::ShaderPipelines>* m_pipelines;
  std::unordered_map<CAssetId, TCachedToken<CTexture>> x1c_textures;
  zeus::CAABox x20_aabb;
  CBooSurface* x38_firstUnsortedSurface = nullptr;
  CBooSurface* x3c_firstSortedSurface = nullptr;
  bool x40_24_texturesLoaded : 1;
  bool x40_25_modelVisible : 1;
  u8 x41_mask;
  u32 x44_areaInstanceIdx = UINT32_MAX;

  struct UVAnimationBuffer {
    static void ProcessAnimation(u8*& bufOut, const MaterialSet::Material::PASS& anim);
    static void PadOutBuffer(u8*& bufStart, u8*& bufOut);
    static void Update(u8*& bufOut, const MaterialSet* matSet, const CModelFlags& flags, const CBooModel* parent);
  };

  CModelShaders::LightingUniform m_lightingData;

  /* urde addition: boo! */
  size_t m_uniformDataSize = 0;
  struct ModelInstance {
    boo::ObjToken<boo::IGraphicsBufferD> m_geomUniformBuffer;
    boo::ObjToken<boo::IGraphicsBufferD> m_uniformBuffer;
    std::vector<std::vector<boo::ObjToken<boo::IShaderDataBinding>>> m_shaderDataBindings;
    boo::ObjToken<boo::IGraphicsBufferD> m_dynamicVbo;

    boo::ObjToken<boo::IGraphicsBuffer> GetBooVBO(const CBooModel& model, boo::IGraphicsDataFactory::Context& ctx);
  };
  std::vector<ModelInstance> m_instances;
  ModelInstance m_ballShadowInstance;

  boo::ObjToken<boo::IGraphicsBufferS> m_staticVbo;
  boo::ObjToken<boo::IGraphicsBufferS> m_staticIbo;

  boo::ObjToken<boo::ITexture> m_lastDrawnShadowMap;
  boo::ObjToken<boo::ITexture> m_lastDrawnOneTexture;
  boo::ObjToken<boo::ITextureCubeR> m_lastDrawnReflectionCube;

  ModelInstance* PushNewModelInstance(int sharedLayoutBuf = -1);
  void DrawAlphaSurfaces(const CModelFlags& flags) const;
  void DrawNormalSurfaces(const CModelFlags& flags) const;
  void DrawSurfaces(const CModelFlags& flags) const;
  void DrawSurface(const CBooSurface& surf, const CModelFlags& flags) const;
  void WarmupDrawSurfaces() const;
  void WarmupDrawSurface(const CBooSurface& surf) const;

  static zeus::CVector3f g_PlayerPosition;
  static float g_ModSeconds;
  static float g_TransformedTime;
  static float g_TransformedTime2;
  static CBooModel* g_LastModelCached;

  static bool g_DummyTextures;
  static bool g_RenderModelBlack;

public:
  ~CBooModel();
  CBooModel(TToken<CModel>& token, CModel* parent, std::vector<CBooSurface>* surfaces, SShader& shader,
            const boo::ObjToken<boo::IGraphicsBufferS>& vbo, const boo::ObjToken<boo::IGraphicsBufferS>& ibo,
            const zeus::CAABox& aabb, u8 renderMask, int numInsts);

  static void MakeTexturesFromMats(const MaterialSet& matSet,
                                   std::unordered_map<CAssetId, TCachedToken<CTexture>>& toksOut,
                                   IObjectStore& store);
  void MakeTexturesFromMats(std::unordered_map<CAssetId, TCachedToken<CTexture>>& toksOut, IObjectStore& store);

  bool IsOpaque() const { return x3c_firstSortedSurface == nullptr; }
  void ActivateLights(const std::vector<CLight>& lights);
  void SetAmbientColor(const zeus::CColor& color) { m_lightingData.ambient = color; }
  void DisableAllLights();
  void RemapMaterialData(SShader& shader);
  void RemapMaterialData(SShader& shader, const std::unordered_map<int, CModelShaders::ShaderPipelines>& pipelines);
  bool TryLockTextures() const;
  void UnlockTextures() const;
  void SyncLoadTextures() const;
  void Touch(int shaderIdx) const;
  void VerifyCurrentShader(int shaderIdx);
  boo::ObjToken<boo::IGraphicsBufferD> UpdateUniformData(const CModelFlags& flags, const CSkinRules* cskr,
                                                         const CPoseAsTransforms* pose, int sharedLayoutBuf = -1) const;
  void DrawAlpha(const CModelFlags& flags, const CSkinRules* cskr, const CPoseAsTransforms* pose) const;
  void DrawNormal(const CModelFlags& flags, const CSkinRules* cskr, const CPoseAsTransforms* pose) const;
  void Draw(const CModelFlags& flags, const CSkinRules* cskr, const CPoseAsTransforms* pose) const;
  void DrawFlat(ESurfaceSelection sel, EExtendedShader extendedIdx) const;

  void LockParent() { m_modelTok.Lock(); }
  void UnlockParent() { m_modelTok.Unlock(); }

  const MaterialSet::Material& GetMaterialByIndex(int idx) const { return x4_matSet->materials.at(idx); }

  void ClearUniformCounter() { m_uniUpdateCount = 0; }
  static void ClearModelUniformCounters();

  static bool g_DrawingOccluders;
  static void SetDrawingOccluders(bool occ) { g_DrawingOccluders = occ; }

  static void SetNewPlayerPositionAndTime(const zeus::CVector3f& pos);

  static zeus::CVector3f g_ReflectViewPos;
  static void KillCachedViewDepState();
  static void EnsureViewDepStateCached(const CBooModel& model, const CBooSurface* surf, zeus::CMatrix4f* mtxsOut,
                                       float& alphaOut);

  static boo::ObjToken<boo::ITexture> g_shadowMap;
  static zeus::CTransform g_shadowTexXf;
  static void EnableShadowMaps(const boo::ObjToken<boo::ITexture>& map, const zeus::CTransform& texXf);
  static void DisableShadowMaps();

  static boo::ObjToken<boo::ITexture> g_disintegrateTexture;
  static void SetDisintegrateTexture(const boo::ObjToken<boo::ITexture>& map) { g_disintegrateTexture = map; }

  static boo::ObjToken<boo::ITextureCubeR> g_reflectionCube;
  static void SetReflectionCube(const boo::ObjToken<boo::ITextureCubeR>& map) { g_reflectionCube = map; }

  static void SetDummyTextures(bool b) { g_DummyTextures = b; }
  static void SetRenderModelBlack(bool b) { g_RenderModelBlack = b; }

  static void Shutdown();

  const zeus::CAABox& GetAABB() const { return x20_aabb; }
};

class CModel {
  friend class CBooModel;
  friend struct GeometryUniformLayout;
  // std::unique_ptr<u8[]> x0_data;
  // u32 x4_dataLen;
  TToken<CModel> m_selfToken; /* DO NOT LOCK! */
  zeus::CAABox m_aabb;
  u32 m_flags;
  std::vector<CBooSurface> x8_surfaces;
  std::vector<SShader> x18_matSets;
  std::unique_ptr<CBooModel> x28_modelInst;
  // CModel* x30_next = nullptr;
  // CModel* x34_prev = nullptr;
  int x38_lastFrame;

  /* urde addition: boo! */
  boo::ObjToken<boo::IGraphicsBufferS> m_staticVbo;
  hecl::HMDLMeta m_hmdlMeta;
  std::unique_ptr<uint8_t[]> m_dynamicVertexData;
  boo::ObjToken<boo::IGraphicsBufferS> m_ibo;

public:
  using MaterialSet = DataSpec::DNAMP1::HMDLMaterialSet;

  CModel(std::unique_ptr<u8[]>&& in, u32 dataLen, IObjectStore* store, CObjectReference* selfRef);
  void DrawSortedParts(const CModelFlags& flags) const;
  void DrawUnsortedParts(const CModelFlags& flags) const;
  void Draw(const CModelFlags& flags) const;
  bool IsLoaded(int shaderIdx) const;
  void Touch(int shaderIdx) { x28_modelInst->Touch(shaderIdx); }

  const zeus::CAABox& GetAABB() const { return m_aabb; }
  CBooModel& GetInstance() { return *x28_modelInst; }
  const CBooModel& GetInstance() const { return *x28_modelInst; }
  std::unique_ptr<CBooModel> MakeNewInstance(int shaderIdx, int subInsts, bool lockParent = true);
  void UpdateLastFrame() const { const_cast<CModel&>(*this).x38_lastFrame = CGraphics::GetFrameCounter(); }

  size_t GetPoolVertexOffset(size_t idx) const;
  zeus::CVector3f GetPoolVertex(size_t idx) const;
  size_t GetPoolNormalOffset(size_t idx) const;
  zeus::CVector3f GetPoolNormal(size_t idx) const;
  void ApplyVerticesCPU(const boo::ObjToken<boo::IGraphicsBufferD>& vertBuf,
                        const std::vector<std::pair<zeus::CVector3f, zeus::CVector3f>>& vn) const;
  void RestoreVerticesCPU(const boo::ObjToken<boo::IGraphicsBufferD>& vertBuf) const;

  void _WarmupShaders();
  static void WarmupShaders(const SObjectTag& cmdlTag);
};

CFactoryFnReturn FModelFactory(const urde::SObjectTag& tag, std::unique_ptr<u8[]>&& in, u32 len,
                               const urde::CVParamTransfer& vparms, CObjectReference* selfRef);

} // namespace urde


text:
import versioneer
from setuptools import setup
import pysdn

setup(
    name='pysdn',
    version=versioneer.get_version(),
    cmdclass=versioneer.get_cmdclass(),
    description='A Python library for programming your network via the Brocade SDN Controller (BSC)',
    long_description=open('README.rst').read(),
    author='Brocade Communications',
    author_email='tnadeau@brocade.com',
    url='https://github.com/brocade/pysdn',
    packages=['pysdn',
              'pysdn.common',
              'pysdn.controller',
              'pysdn.netconfdev',
              'pysdn.netconfdev.vrouter',
              'pysdn.netconfdev.ovs',
              'pysdn.netconfdev.vdx',
              'pysdn.openflowdev'
              ],
    install_requires=['requests>=1.0.0',
                      'PyYAML',
                      'xmltodict'],
    zip_safe=False,
    include_package_data=True,
    platforms='any',
    license='Brocade Communications, Inc.',
    keywords='sdn nfv bvc brocade sdn controller network vrouter',
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Intended Audience :: System Administrators',
        'Topic :: System :: Networking',
        'License :: OSI Approved :: BSD License',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
    ]
)


text:
'use strict';

var assert = require('chai').assert;
var util = require('../src/util');
var acc = require('../src/accessor');

describe('time accessors', function() {

    // utc
    var tu = {t: Date.UTC(2005, 2, 3, 13, 17, 29)};
    var du = {d: new Date(tu.t)};

    // locale
    var dl = {d: new Date(2005, 2, 3, 13, 17, 29)};
    var tl = {t: +dl.d};

    it('should support year extraction', function() {
      assert.equal(2005, acc.$year('t')(tl));
      assert.equal(2005, acc.$year('d')(dl));
      assert.equal(2005, acc.$year()(dl.d));
      assert.equal('year_t', util.name(acc.$year('t')));
      assert.equal('year', util.name(acc.$year()));
    });

    it('should support month extraction', function() {
      assert.equal(2, acc.$month('t')(tl));
      assert.equal(2, acc.$month('d')(dl));
      assert.equal(2, acc.$month()(dl.d));
      assert.equal('month_t', util.name(acc.$month('t')));
      assert.equal('month', util.name(acc.$month()));
    });

    it('should support date extraction', function() {
      assert.equal(3, acc.$date('t')(tl));
      assert.equal(3, acc.$date('d')(dl));
      assert.equal(3, acc.$date()(dl.d));
      assert.equal('date_t', util.name(acc.$date('t')));
      assert.equal('date', util.name(acc.$date()));
    });

    it('should support day extraction', function() {
      var day = dl.d.getUTCDay();
      assert.equal(day, acc.$day('t')(tl));
      assert.equal(day, acc.$day('d')(dl));
      assert.equal(day, acc.$day()(dl.d));
      assert.equal('day_t', util.name(acc.$day('t')));
      assert.equal('day', util.name(acc.$day()));
    });

    it('should support hour extraction', function() {
      assert.equal(13, acc.$hour('t')(tl));
      assert.equal(13, acc.$hour('d')(dl));
      assert.equal(13, acc.$hour()(dl.d));
      assert.equal('hour_t', util.name(acc.$hour('t')));
      assert.equal('hour', util.name(acc.$hour()));
    });

    it('should support minute extraction', function() {
      assert.equal(17, acc.$minute('t')(tl));
      assert.equal(17, acc.$minute('d')(dl));
      assert.equal(17, acc.$minute()(dl.d));
      assert.equal('minute_t', util.name(acc.$minute('t')));
      assert.equal('minute', util.name(acc.$minute()));
    });

    it('should support second extraction', function() {
      assert.equal(29, acc.$second('t')(tl));
      assert.equal(29, acc.$second('d')(dl));
      assert.equal(29, acc.$second()(dl.d));
      assert.equal('second_t', util.name(acc.$second('t')));
      assert.equal('second', util.name(acc.$second()));
    });

    it('should support utc year extraction', function() {
      assert.equal(2005, acc.$utcYear('t')(tu));
      assert.equal(2005, acc.$utcYear('d')(du));
      assert.equal(2005, acc.$utcYear()(du.d));
      assert.equal('utcYear_t', util.name(acc.$utcYear('t')));
      assert.equal('utcYear', util.name(acc.$utcYear()));
    });

    it('should support utc month extraction', function() {
      assert.equal(2, acc.$utcMonth('t')(tu));
      assert.equal(2, acc.$utcMonth('d')(du));
      assert.equal(2, acc.$utcMonth()(du.d));
      assert.equal('utcMonth_t', util.name(acc.$utcMonth('t')));
      assert.equal('utcMonth', util.name(acc.$utcMonth()));
    });

    it('should support utc date extraction', function() {
      assert.equal(3, acc.$utcDate('t')(tu));
      assert.equal(3, acc.$utcDate('d')(du));
      assert.equal(3, acc.$utcDate()(du.d));
      assert.equal('utcDate_t', util.name(acc.$utcDate('t')));
      assert.equal('utcDate', util.name(acc.$utcDate()));
    });

    it('should support utc day extraction', function() {
      var day = du.d.getUTCDay();
      assert.equal(day, acc.$utcDay('t')(tu));
      assert.equal(day, acc.$utcDay('d')(du));
      assert.equal(day, acc.$utcDay()(du.d));
      assert.equal('utcDay_t', util.name(acc.$utcDay('t')));
      assert.equal('utcDay', util.name(acc.$utcDay()));
    });

    it('should support utc hour extraction', function() {
      assert.equal(13, acc.$utcHour('t')(tu));
      assert.equal(13, acc.$utcHour('d')(du));
      assert.equal(13, acc.$utcHour()(du.d));
      assert.equal('utcHour_t', util.name(acc.$utcHour('t')));
      assert.equal('utcHour', util.name(acc.$utcHour()));
    });

    it('should support utc minute extraction', function() {
      assert.equal(17, acc.$utcMinute('t')(tu));
      assert.equal(17, acc.$utcMinute('d')(du));
      assert.equal(17, acc.$utcMinute()(du.d));
      assert.equal('utcMinute_t', util.name(acc.$utcMinute('t')));
      assert.equal('utcMinute', util.name(acc.$utcMinute()));
    });

    it('should support utc second extraction', function() {
      assert.equal(29, acc.$utcSecond('t')(tu));
      assert.equal(29, acc.$utcSecond('d')(du));
      assert.equal(29, acc.$utcSecond()(du.d));
      assert.equal('utcSecond_t', util.name(acc.$utcSecond('t')));
      assert.equal('utcSecond', util.name(acc.$utcSecond()));
    });
});


text:
// Copyright 2009-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0

#pragma once

#include "stream.h"
#include <string>
#include <vector>

namespace embree
{
  /*! token class */
  class Token
  {
  public:

    enum Type { TY_EOF, TY_CHAR, TY_INT, TY_FLOAT, TY_IDENTIFIER, TY_STRING, TY_SYMBOL };

    Token (        const ParseLocation& loc = ParseLocation()) : ty(TY_EOF  ),       loc(loc) {}
    Token (char c, const ParseLocation& loc = ParseLocation()) : ty(TY_CHAR ), c(c), loc(loc) {}
    Token (int i,  const ParseLocation& loc = ParseLocation()) : ty(TY_INT  ), i(i), loc(loc) {}
    Token (float f,const ParseLocation& loc = ParseLocation()) : ty(TY_FLOAT), f(f), loc(loc) {}
    Token (std::string str, Type ty, const ParseLocation& loc = ParseLocation()) : ty(ty),   str(str), loc(loc) {}

    static Token Eof()                { return Token(); }
    static Token Sym(std::string str) { return Token(str,TY_SYMBOL); }
    static Token Str(std::string str) { return Token(str,TY_STRING); }
    static Token Id (std::string str) { return Token(str,TY_IDENTIFIER); }

    char Char() const {
      if (ty == TY_CHAR) return c;
      THROW_RUNTIME_ERROR(loc.str()+": character expected");
    }

    int Int() const {
      if (ty == TY_INT) return i;
      THROW_RUNTIME_ERROR(loc.str()+": integer expected");
    }

    float Float(bool cast = true)  const {
      if (ty == TY_FLOAT) return f;
      if (ty == TY_INT && cast) return (float)i;
      THROW_RUNTIME_ERROR(loc.str()+": float expected");
    }

    std::string Identifier() const {
      if (ty == TY_IDENTIFIER) return str;
      THROW_RUNTIME_ERROR(loc.str()+": identifier expected");
    }

    std::string String() const {
      if (ty == TY_STRING) return str;
      THROW_RUNTIME_ERROR(loc.str()+": string expected");
    }

    std::string Symbol() const {
      if (ty == TY_SYMBOL) return str;
      THROW_RUNTIME_ERROR(loc.str()+": symbol expected");
    }

    const ParseLocation& Location() const { return loc; }

    friend bool operator==(const Token& a, const Token& b)
    {
      if (a.ty != b.ty) return false;
      if (a.ty == TY_CHAR) return a.c == b.c;
      if (a.ty == TY_INT) return a.i == b.i;
      if (a.ty == TY_FLOAT) return a.f == b.f;
      if (a.ty == TY_IDENTIFIER) return a.str == b.str;
      if (a.ty == TY_STRING) return a.str == b.str;
      if (a.ty == TY_SYMBOL) return a.str == b.str;
      return true;
    }

    friend bool operator!=(const Token& a, const Token& b) {
      return !(a == b);
    }

    friend bool operator <( const Token& a, const Token& b ) {
      if (a.ty != b.ty) return (int)a.ty < (int)b.ty;
      if (a.ty == TY_CHAR) return a.c < b.c;
      if (a.ty == TY_INT) return a.i < b.i;
      if (a.ty == TY_FLOAT) return a.f < b.f;
      if (a.ty == TY_IDENTIFIER) return a.str < b.str;
      if (a.ty == TY_STRING) return a.str < b.str;
      if (a.ty == TY_SYMBOL) return a.str < b.str;
      return false;
    }

    friend std::ostream& operator<<(std::ostream& cout, const Token& t)
    {
      if (t.ty == TY_EOF) return cout << "eof";
      if (t.ty == TY_CHAR) return cout << "Char(" << t.c << ")";
      if (t.ty == TY_INT) return cout << "Int(" << t.i << ")";
      if (t.ty == TY_FLOAT) return cout << "Float(" << t.f << ")";
      if (t.ty == TY_IDENTIFIER) return cout << "Id(" << t.str << ")";
      if (t.ty == TY_STRING) return cout << "String(" << t.str << ")";
      if (t.ty == TY_SYMBOL) return cout << "Symbol(" << t.str << ")";
      return cout << "unknown";
    }

  private:
    Type ty;            //< the type of the token
    union {
      char c;           //< data for char tokens
      int i;            //< data for int tokens
      float f;          //< data for float tokens
    };
    std::string str;    //< data for string and identifier tokens
    ParseLocation loc;  //< the location the token is from
  };

  /*! build full tokenizer that takes list of valid characters and keywords */
  class TokenStream : public Stream<Token>
  {
  public:

    /*! shorthands for common sets of characters */
    static const std::string alpha;
    static const std::string ALPHA;
    static const std::string numbers;
    static const std::string separators;
    static const std::string stringChars;

  public:
    TokenStream(const Ref<Stream<int> >& cin,
                const std::string& alpha, //< valid characters for identifiers
                const std::string& seps,  //< characters that act as separators
                const std::vector<std::string>& symbols = std::vector<std::string>()); //< symbols
  public:
    ParseLocation location() { return cin->loc(); }
    Token next();
    bool trySymbol(const std::string& symbol);

  private:
    void skipSeparators();
    bool decDigits(std::string& str);
    bool decDigits1(std::string& str);
    bool trySymbols(Token& token, const ParseLocation& loc);
    bool tryFloat(Token& token, const ParseLocation& loc);
    bool tryInt(Token& token, const ParseLocation& loc);
    bool tryString(Token& token, const ParseLocation& loc);
    bool tryIdentifier(Token& token, const ParseLocation& loc);

    Ref<Stream<int> > cin;
    bool isSepMap[256];
    bool isAlphaMap[256];
    bool isStringCharMap[256];
    std::vector<std::string> symbols;

    /*! checks if a character is a separator */
    __forceinline bool isSeparator(unsigned int c) const { return c<256 && isSepMap[c]; }

    /*! checks if a character is a number */
    __forceinline bool isDigit(unsigned int c) const {  return c >= '0' && c <= '9'; }

    /*! checks if a character is valid inside a string */
    __forceinline bool isStringChar(unsigned int c) const { return c<256 && isStringCharMap[c]; }

    /*! checks if a character is legal for an identifier */
    __forceinline bool isAlpha(unsigned int c) const {  return c<256 && isAlphaMap[c];  }
    __forceinline bool isAlphaNum(unsigned int c) const { return isAlpha(c) || isDigit(c); }
  };
}


text:
package com.punyal.symbiotic.core.net.lwm2m;

import static com.punyal.symbiotic.constants.ConstantsNet.*;
import com.punyal.symbiotic.core.Core;
import com.punyal.symbiotic.core.net.Thing;
import java.net.Inet6Address;
import org.eclipse.californium.core.CoapClient;
import org.eclipse.californium.core.CoapResponse;

/**
 *
 * @author Pablo Puñal Pereira <pablo.punal@ltu.se>
 */
public class LWM2Mthread extends Thread{
    private final Core core;
    private final Thing thing;
    private boolean running;
    private final CoapClient coapClient;

    public LWM2Mthread(Core core, Thing thing) {
        this.core = core;
        this.thing = thing;
        this.setDaemon(true);
        coapClient = new CoapClient();
        running = true;
    }

    public void startThread() {
        this.start();
    }

    public void stopThread() {
        running = false;
    }

    private enum Steps {
        MANUFACTURER,
        MODEL,
        SERIAL,
        FIRMWARE
    }

    @Override
    public void run() {
        try {
            String uri = null, uriIP;
            CoapResponse response;
            Steps step = Steps.MANUFACTURER;

            // Check if it's an IPv4 or IPv6
            if (thing.getInetAddress() instanceof Inet6Address)
                uriIP = "coap://["+thing.getAddress()+"]:"+thing.getPort();
            else
                uriIP = "coap://"+thing.getAddress()+":"+thing.getPort();

            while (running) {
                switch(step) {
                    case MANUFACTURER:
                        uri = uriIP + LWM2M_RESOURCE_MANUFACTURER;
                        break;
                    case MODEL:
                        uri = uriIP + LWM2M_RESOURCE_MODEL_NUMBER;
                        break;
                    case SERIAL:
                        uri = uriIP + LWM2M_RESOURCE_SERIAL_NUMBER;
                        break;
                    case FIRMWARE:
                        uri = uriIP + LWM2M_RESOURCE_FIRMWARE_VERSION;
                        break;
                    default:
                        running = false;
                        break;
                }
                if (uri == null) running = false;
                else {
                    coapClient.setURI(uri);
                    response = coapClient.get();

                    if (response != null) {
                        String res = response.getResponseText();
                        String value;
                        value = (res.substring(res.indexOf("sv\":\"")+5, res.lastIndexOf("\"}")));
                        switch(step) {
                        case MANUFACTURER:
                            thing.setManufacturer(value);
                            step = Steps.MODEL;
                            break;
                        case MODEL:
                            thing.setModelNumber(value);
                            step = Steps.SERIAL;
                            break;
                        case SERIAL:
                            thing.setSerialNumber(value);
                            step = Steps.FIRMWARE;
                            break;
                        case FIRMWARE:
                            thing.setFirmwareVersion(value);
                            running = false;
                            //System.out.println("DONE");
                            break;
                        default:
                            running = false;
                            break;
                        }
                    }
                }

                try {
                    Thread.sleep(100); // Sleep 100ms
                } catch (InterruptedException ex) {
                    Thread.currentThread().interrupt(); // This should kill it propertly
                }
            }

        } finally {
            System.out.println("Killing LWM2Mthread "+ thing.getManufacturer()+ " "+ thing.getModelNumber()+ " "+ thing.getSerialNumber()+ " "+ thing.getFirmwareVersion()+ " ");

        }
    }
}


text:
var assert = require('assert');
var zipper = require('../build/Release/zipper');

/* assert ABI compatibility */
assert.ok(zipper.versions.node === process.versions.node, 'The running node version "' + process.versions.node + '" does not match the node version that zipper was compiled against: "' + zipper.versions.node + '"');

// push all C++ symbols into js module
for (var k in zipper) { exports[k] = zipper[k]; }


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

#if NET_2_0 || NETSTANDARD2_0
// .NET Compact Framework 1.0 has no support for application .config files
#if !NETCF

using System.Configuration;
using System.Xml;

namespace log4net.Config
{
    ///
    /// Class to register for the log4net section of the configuration file
    ///
    /// <remarks>
    /// The log4net section of the configuration file needs to have a section
    /// handler registered. This is the section handler used. It simply returns
    /// the XML element that is the root of the section.
    /// </remarks>
    /// <example>
    /// Example of registering the log4net section handler :
    ///
    /// <configuration>
    ///         <configSections>
    ///

    ///         </configSections>
    ///         <log4net>
    ///             log4net configuration XML goes here
    ///         </log4net>
    /// </configuration>
    ///
    /// </example>
    /// <author>Nicko Cadell</author>
    /// <author>Gert Driesen</author>
    public class Log4NetConfigurationSectionHandler : IConfigurationSectionHandler
    {
        ///
        /// Initializes a new instance of the <see cref="Log4NetConfigurationSectionHandler"/> class.
        ///
        /// <remarks>
        /// <para>
        /// Default constructor.
        /// </para>
        /// </remarks>
        public Log4NetConfigurationSectionHandler()
        {
        }

        ///
        /// Parses the configuration section.
        ///
        /// <param name="parent">The configuration settings in a corresponding parent configuration section.</param>
        /// <param name="configContext">The configuration context when called from the ASP.NET configuration system. Otherwise, this parameter is reserved and is a null reference.</param>
        /// <param name="section">The <see cref="XmlNode" /> for the log4net section.</param>
        /// <returns>The <see cref="XmlNode" /> for the log4net section.</returns>
        /// <remarks>
        /// <para>
        /// Returns the <see cref="XmlNode"/> containing the configuration data,
        /// </para>
        /// </remarks>
        public object Create(object parent, object configContext, XmlNode section)
        {
            return section;
        }
    }
}

#endif // !NETCF
#endif // NET_2_0 || NETSTANDARD2_0


text:
'use strict';

var resultQueue = new ResultQueue();
var pushSubscription = null;

var pushSubscriptionOptions = {
  userVisibleOnly: true
};

// Sends data back to the test. This must be in response to an earlier
// request, but it's ok to respond asynchronously. The request blocks until
// the response is sent.
function sendResultToTest(result) {
  console.log('sendResultToTest: ' + result);
  if (window.domAutomationController) {
    domAutomationController.send('' + result);
  }
}

function sendErrorToTest(error) {
  sendResultToTest(error.name + ' - ' + error.message);
}

// Queue storing asynchronous results received from the Service Worker. Results
// are sent to the test when requested.
function ResultQueue() {
  // Invariant: this.queue.length == 0 || this.pendingGets == 0
  this.queue = [];
  this.pendingGets = 0;
}

// Adds a data item to the queue. Will be sent to the test if there are
// pendingGets.
ResultQueue.prototype.push = function(data) {
  if (this.pendingGets > 0) {
    this.pendingGets--;
    sendResultToTest(data);
  } else {
    this.queue.unshift(data);
  }
};

// Called by native. Sends the next data item to the test if it is available.
// Otherwise increments pendingGets so it will be delivered when received.
ResultQueue.prototype.pop = function() {
  if (this.queue.length) {
    sendResultToTest(this.queue.pop());
  } else {
    this.pendingGets++;
  }
};

// Called by native. Immediately sends the next data item to the test if it is
// available, otherwise sends null.
ResultQueue.prototype.popImmediately = function() {
  sendResultToTest(this.queue.length ? this.queue.pop() : null);
};

// Notification permission has been coalesced with Push permission. After
// this is granted, Push API subscription can succeed.
function requestNotificationPermission() {
  Notification.requestPermission(function(permission) {
    sendResultToTest('permission status - ' + permission);
  });
}

function registerServiceWorker() {
  // The base dir used to resolve service_worker.js and the scope depends on
  // whether this script is included from an html file in ./, subscope1/, or
  // subscope2/.
  navigator.serviceWorker.register('service_worker.js', {scope: './'}).then(
      function(swRegistration) {
        sendResultToTest('ok - service worker registered');
      }, sendErrorToTest);
}

function unregisterServiceWorker() {
  navigator.serviceWorker.getRegistration().then(function(swRegistration) {
    swRegistration.unregister().then(function(result) {
      sendResultToTest('service worker unregistration status: ' + result);
    })
  }).catch(sendErrorToTest);
}

function removeManifest() {
  var element = document.querySelector('link[rel="manifest"]');
  if (element) {
    element.parentNode.removeChild(element);
    sendResultToTest('manifest removed');
  } else {
    sendResultToTest('unable to find manifest element');
  }
}

function subscribePush() {
  navigator.serviceWorker.ready.then(function(swRegistration) {
    return swRegistration.pushManager.subscribe(pushSubscriptionOptions)
        .then(function(subscription) {
          pushSubscription = subscription;
          sendResultToTest(subscription.endpoint);
        });
  }).catch(sendErrorToTest);
}

function getCurve25519dh() {
  navigator.serviceWorker.ready.then(function(swRegistration) {
    return swRegistration.pushManager.getSubscription()
        .then(function(subscription) {
          sendResultToTest(btoa(String.fromCharCode.apply(null,
              new Uint8Array(subscription.getKey('curve25519dh')))));
        });
  }).catch(sendErrorToTest);
}

function permissionState() {
  navigator.serviceWorker.ready.then(function(swRegistration) {
    return swRegistration.pushManager.permissionState(pushSubscriptionOptions)
        .then(function(permission) {
          sendResultToTest('permission status - ' + permission);
        });
  }).catch(sendErrorToTest);
}

function isControlled() {
  if (navigator.serviceWorker.controller) {
    sendResultToTest('true - is controlled');
  } else {
    sendResultToTest('false - is not controlled');
  }
}

function unsubscribePush() {
  if (!pushSubscription) {
    sendResultToTest('unsubscribe error: no subscription');
    return;
  }

  pushSubscription.unsubscribe().then(function(result) {
    sendResultToTest('unsubscribe result: ' + result);
  }, function(error) {
    sendResultToTest('unsubscribe error: ' + error.name + ': ' + error.message);
  });
}

function hasSubscription() {
  navigator.serviceWorker.ready.then(function(swRegistration) {
    return swRegistration.pushManager.getSubscription();
  }).then(function(subscription) {
    sendResultToTest(subscription ? 'true - subscribed'
                                  : 'false - not subscribed');
  }).catch(sendErrorToTest);
}

navigator.serviceWorker.addEventListener('message', function(event) {
  var message = JSON.parse(event.data);
  if (message.type == 'push')
    resultQueue.push(message.data);
}, false);


text:
package net.eusashead.bjugquerydsl.hateoas;

import java.math.BigDecimal;
import java.util.Date;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class SimplePropertyConverterImplTest {

	@Test
	public void testDefaultConversions() {

		// Default constructor
		SimplePropertyConverterImpl converter = new SimplePropertyConverterImpl();

		// Test date to string
		Object dateConverted = converter.convert(new Date(123456789l), String.class);
		Assert.assertEquals("Fri Jan 02 11:17:36 GMT 1970", dateConverted.toString());

		// Test decimal to string
		Object decimalConverted = converter.convert(BigDecimal.valueOf(23.45d), String.class);
		Assert.assertEquals("23.45", decimalConverted.toString());
	}
}


text:
RSpec::Matchers.define :match_original_file do
  match do |path|
    @path = path
    @original_contents = TestPaths.fake_app_fixture_path.join(path).read
    @actual_contents = TestPaths.app_path.join(path).read

    @original_contents == @actual_contents
  end

  failure_message do
    <<~MESSAGE
      #{@path} does not match original file. The diff is:
      #{differ.diff_as_string(@actual_contents, @original_contents)}
    MESSAGE
  end

  def differ
    RSpec::Support::Differ.new(
      object_preparer: lambda do |object|
        RSpec::Matchers::Composable.surface_descriptions_in(object)
      end,
      color: RSpec::Matchers.configuration.color?
    )
  end
end

RSpec::Matchers.define :have_syntax_error do
  # rubocop:disable Lint/RescueException
  match do |path|
    @path = path
    load TestPaths.app_path.join(path)
    false
  rescue SyntaxError
    true
  rescue Exception
    false
  end
  # rubocop:enable Lint/RescueException

  failure_message do
    "The file #{@path} has NO syntax errors"
  end
end

RSpec::Matchers.define_negated_matcher :have_no_syntax_error, :have_syntax_error