text:
<?php

class Indicateur4 extends Indicateur{

    protected $titre;
    protected $type;
    protected $data;
    protected $idCours;
    protected $em;

    function mesIndicateurs($idCours)
    {
        $data = array();

        //Affiche les graphes étudiants
        $data[1]['titre'] = 'Connexions';
        $data[1]['max'] = 50;
        $data[1]['type'] = 'line';
        $data[1]['indicateur1']['titre'] = 'Moyenne des connexions des étudiants au cours, par semaine.';
        $data[1]['indicateur1']['desc'] = '(Moyenne) <br/>Moyenne des connexions des étudiants au cours, par semaine.';
        $data[1]['indicateur1']['fonction']['Connexions au cours (/10)'] = 'getConnexionPerStudent';
        $data[1]['indicateur1']['fonction']['Nombre de rendus'] = 'getNbRenduPerStudent';

        //On définit une alerte
        $data['alerte'][1]['message'] = "Attention, certains étudiants n'ont pas rendu leurs devoirs";
        $data['alerte'][1]['couleur'] = array('green' => false, 'orange' => true, 'red' => true);
        $data['alerte'][1]['fonction'] = "getAlerteRendus";
        $data['alerte'][2]['message'] = "Attention, connexions en baisse !";
        $data['alerte'][2]['couleur'] = array('green' => false, 'orange' => true, 'red' => true);
        $data['alerte'][2]['fonction'] = "getAlerteConnexions";

        $this->idCours = $idCours;
        return $data;
    }

    /** FONCTIONS PERSONNALISEES */

    /**
     * @return array
     * Retourne le nombre de rendu par étudiant
     */
    public function getNbRenduPerStudent()
    {
        $allStudent = Indicateur::getAllStudent($this->idCours);
        $action = 'submitted';
        $statement = "SELECT COUNT(*) as nb, mdl_logstore_standard_log.userid, CONCAT(lastname,' ',firstname) as prenom
                  FROM mdl_user
                  LEFT JOIN mdl_role_assignments ON mdl_user.id = mdl_role_assignments.userid
                  LEFT JOIN mdl_context ON mdl_role_assignments.contextid = mdl_context.id
                  LEFT JOIN mdl_course ON mdl_context.instanceid = mdl_course.id
                  LEFT JOIN mdl_logstore_standard_log ON mdl_logstore_standard_log.userid = mdl_user.id
                  AND mdl_logstore_standard_log.courseid = mdl_course.id
                  WHERE mdl_course.id = ".$this->idCours."
                  AND roleid in (5)
                  AND mdl_logstore_standard_log.component NOT IN ('core', 'mod_forum')
                  AND action = '".$action."'
                  GROUP BY mdl_logstore_standard_log.userid
                  ORDER BY prenom ASC";

        $results = Indicateur::executeMultipleRequete($statement);

        $tabEtudiants = array();
        foreach($results as $etudiant)
            $tabEtudiants[$etudiant['prenom']] = intval($etudiant['nb']);

        foreach($allStudent as $student)
        {
            if(array_key_exists($student, $tabEtudiants))
                $dataAutre[$student] = $tabEtudiants[$student];
            else
                $dataAutre[$student] = 0;
        }

        return $dataAutre;
    }

    /**
     * @param $idCours
     *
     * Retourne le nombre de connexions par étudiant, divisé par 10
     */
    public function getConnexionPerStudent()
    {
        $allStudent = Indicateur::getAllStudent($this->idCours);
        $statement = "SELECT ROUND(AVG(cnt.c),0) as moy, userid, prenom FROM (
                            SELECT count(mdl_logstore_standard_log.id) AS c, mdl_user.id as userid, CONCAT(lastname,' ',firstname) as prenom
                            FROM mdl_user
                            LEFT JOIN mdl_role_assignments ON mdl_user.id = mdl_role_assignments.userid
                            LEFT JOIN mdl_context ON mdl_role_assignments.contextid = mdl_context.id
                            LEFT JOIN mdl_course ON mdl_context.instanceid = mdl_course.id
                            LEFT JOIN mdl_logstore_standard_log ON mdl_logstore_standard_log.userid = mdl_user.id
                            AND mdl_logstore_standard_log.courseid = mdl_course.id
                            WHERE mdl_course.id = ".$this->idCours."
                            AND roleid in (5)
                            GROUP BY weekofyear( mdl_logstore_standard_log.timecreated ) , userid
                            )cnt GROUP BY userid ORDER BY prenom ASC";
        $results = Indicateur::executeMultipleRequete($statement);

        $tabEtudiants = array();
        foreach($results as $etudiant)
            $tabEtudiants[$etudiant['prenom']] = round($etudiant['moy'] / 10);

        foreach($allStudent as $student)
        {
            if(array_key_exists($student, $tabEtudiants))
                $dataAutre[$student] = $tabEtudiants[$student];
            else
                $dataAutre[$student] = 0;
        }

        return $dataAutre;
    }

    /**
     * Devoirs et tests non rendus
     *
     * Référence = nombre maximum de rendus par au moins 2 étudiants
     * Renvoie OBLIGATOIREMENT un tableau avec étudiant
     * Vert : nbre de rendus de l'étudiant = référence
     * Orange : nbre de rendus de l'étudiant = référence -1
     * Rouge : nbre de rendus de l'étudiant < référence * 0.7
     */
    public function getAlerteRendus()
    {
        $allStudent = Indicateur::getAllStudent($this->idCours);
        $statement = "SELECT COUNT(tmp.c) as max FROM(
                        SELECT count(cnt.nb) AS c, contextid FROM (
                          SELECT count(*) AS nb, contextid, userid FROM mdl_logstore_standard_log
                          WHERE courseid = ".$this->idCours."
                          AND component NOT IN ('core', 'mod_forum')
                          AND action= 'submitted'
                          GROUP BY contextid, userid)cnt
                        group by contextid having count(cnt.nb) > 1)tmp
                    ";
        $results = Indicateur::executeRequete($statement);
        $reference = $results['max'];

        $query = "SELECT COUNT(*) as nb, mdl_logstore_standard_log.userid, CONCAT(lastname,' ',firstname) as prenom
                  FROM mdl_user
                  LEFT JOIN mdl_role_assignments ON mdl_user.id = mdl_role_assignments.userid
                  LEFT JOIN mdl_context ON mdl_role_assignments.contextid = mdl_context.id
                  LEFT JOIN mdl_course ON mdl_context.instanceid = mdl_course.id
                  LEFT JOIN mdl_logstore_standard_log ON mdl_logstore_standard_log.userid = mdl_user.id
                  AND mdl_logstore_standard_log.courseid = mdl_course.id
                  WHERE mdl_course.id = ".$this->idCours."
                  AND roleid in (5)
                  AND mdl_logstore_standard_log.component NOT IN ('core', 'mod_forum')
                  AND action= 'submitted'
                  GROUP BY mdl_logstore_standard_log.userid
                  ORDER BY prenom ASC";

        $resultsEdt = Indicateur::executeMultipleRequete($query);

        $data = array();
        foreach($resultsEdt as $etudiant)
        {
            if($etudiant['nb'] < ($reference - 1))
                $val = 'red';
            else if($etudiant['nb'] == $reference - 1)
                $val = 'orange';
            else if(intval($etudiant['nb']) >= $reference)
                $val = "green";

            if(in_array($etudiant['prenom'], $allStudent))
                $data[$etudiant['prenom']] = $val;
            else
                $data[$etudiant['prenom']] = "red";
        }

        return $data;
    }

    /**
     * Connexions au cours
     *
     * Référence = nombre de moyen de connexions sur les étudiants s'étant connectés les 20 derniers jours
     * Renvoie OBLIGATOIREMENT un tableau avec étudiant
     * Vert : nbre de rendus de l'étudiant = référence
     * Orange : nbre de rendus de l'étudiant = référence -1
     * Rouge : nbre de rendus de l'étudiant < référence * 0.7
     */
    public function getAlerteConnexions()
    {
        $allStudent = Indicateur::getAllStudent($this->idCours);
        $statement = "SELECT ROUND(AVG(cnt.c), 0) as moy FROM (
                          SELECT DISTINCT mdl_user.id as userid, count(*) as c
                             FROM mdl_user
                             LEFT JOIN mdl_role_assignments ON mdl_user.id = mdl_role_assignments.userid
                             LEFT JOIN mdl_context ON mdl_role_assignments.contextid = mdl_context.id
                             LEFT JOIN mdl_course ON mdl_context.instanceid = mdl_course.id
                             LEFT JOIN mdl_logstore_standard_log ON mdl_logstore_standard_log.userid = mdl_user.id
                             AND mdl_logstore_standard_log.courseid = mdl_course.id
                             WHERE mdl_course.id = ".$this->idCours."
                             AND mdl_logstore_standard_log.courseid = ".$this->idCours."
                             AND roleid in (5)
                             AND mdl_user.id IN
                                (SELECT DISTINCT mdl_user.id as userid
                                    FROM mdl_user
                                    LEFT JOIN mdl_role_assignments ON mdl_user.id = mdl_role_assignments.userid
                                    LEFT JOIN mdl_context ON mdl_role_assignments.contextid = mdl_context.id
                                    LEFT JOIN mdl_course ON mdl_context.instanceid = mdl_course.id
                                    LEFT JOIN mdl_logstore_standard_log ON mdl_logstore_standard_log.userid = mdl_user.id
                                    AND mdl_logstore_standard_log.courseid = mdl_course.id
                                    WHERE mdl_course.id = ".$this->idCours."
                                    AND mdl_logstore_standard_log.courseid = ".$this->idCours."
                                    AND roleid in (5)
                                    AND DATEDIFF( CURDATE(), FROM_UNIXTIME(mdl_logstore_standard_log.timecreated)) < 21
                                )
                             GROUP BY userid)cnt
                         ";

        $results = Indicateur::executeRequete($statement);
        $reference = $results['moy'];

        $query = "SELECT count(mdl_logstore_standard_log.id) AS nb, mdl_user.id as userid, CONCAT(lastname,' ',firstname) as prenom
                            FROM mdl_user
                            LEFT JOIN mdl_role_assignments ON mdl_user.id = mdl_role_assignments.userid
                            LEFT JOIN mdl_context ON mdl_role_assignments.contextid = mdl_context.id
                            LEFT JOIN mdl_course ON mdl_context.instanceid = mdl_course.id
                            LEFT JOIN mdl_logstore_standard_log ON mdl_logstore_standard_log.userid = mdl_user.id
                            AND mdl_logstore_standard_log.courseid = mdl_course.id
                            WHERE mdl_course.id = ".$this->idCours."
                            AND mdl_logstore_standard_log.courseid = ".$this->idCours."
                            AND roleid in (5)
                            GROUP BY userid
                            ORDER BY prenom ASC";

        $resultsEdt = Indicateur::executeMultipleRequete($query);

        $data = array();
        foreach($resultsEdt as $etudiant)
        {
            foreach($resultsEdt as $etudiant)
            {
                if($etudiant['nb'] > $reference * 0.7)
                    $val = 'green';
                else if($etudiant['nb'] > $reference * 0.5)
                    $val = 'orange';
                else if($etudiant['nb'] < $reference * 0.5 )
                    $val = "red";

                if(in_array($etudiant['prenom'], $allStudent))
                    $data[$etudiant['prenom']] = $val;
                else
                    $data[$etudiant['prenom']] = "red";
            }
        }

        return $data;
    }

    /** NE PAS TOUCHER */
    public function getIdCours()
    {
        return $this->idCours;
    }

    public function setIdCours($id)
    {
        $this->idCours = $id;
    }
}
?>


text:
var Canvas = require('canvas'),
  defaultConfig = {
    maxWidth : 8000,
    maxHeight : 8000,
    backgroundStyle : '#CCC',
    textStyle : '#FFF',
    fontFamily : 'Impact',
    fontSizeParam : 5
  };

module.exports = function (width, height) {
  var config = {};

  for(k in defaultConfig) {
    config[k] = defaultConfig[k];
  }
  canvas = new Canvas(width, height);
  ctx = canvas.getContext('2d');
  fontSize = Math.round(Math.min(width/config.fontSizeParam,height));

  ctx.save();
  ctx.fillStyle = config.backgroundStyle;
  ctx.fillRect(0, 0, width, height);
  ctx.restore();

  ctx.save();
  ctx.font = fontSize + 'px ' + config.fontFamily;
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.fillStyle = config.textStyle;
  ctx.fillText(width + '×' + height, width / 2, height / 2 - fontSize * 0.1);
  ctx.restore();
  return canvas.toBuffer();
}

redpajama_set_name: RedPajamaGithub


text:
class AddValueColumnsToStaffActionLogs < ActiveRecord::Migration
  def change
    add_column :staff_action_logs, :subject, :text
    add_column :staff_action_logs, :previous_value, :text
    add_column :staff_action_logs, :new_value, :text
  end
end


text:
MemoryManager::MemoryManager() {
	selected_local = 0;
}

MemoryManager::~MemoryManager() {
	for (int i = 0; i < local_mems.size(); i++)
		delete local_mems[i];

	local_mems.clear();
}

void MemoryManager::init(FILE* file) {
	global.init(file);

	Memory* local_base = new Memory();
	local_base->init(file, false);
	local_mems.push_back(local_base);

	temp.init(file);
}

void MemoryManager::dump() {
	global.dump();
	//local.dump();
	temp.dump();
}

void MemoryManager::expand_mem() {
	Memory* new_local = new Memory();
	new_local->copy(local_mems[0]);

	local_mems.push_back(new_local);

	//printf("Selected local [%d]\n", selected_local);
}

void MemoryManager::free_mem() {
	Memory* del_local = local_mems[selected_local];
	local_mems.pop_back();
	delete del_local;
	selected_local--;
}

data_type MemoryManager::read(int address) {
	if (address >= 0 && address < block_size)
		return global.read(address);
	else if (address >= block_size && address < block_size*2)
		return local_mems[selected_local]->read(address - block_size);
	else if (address >= block_size*2 && address < block_size*3)
		return temp.read(address - block_size*2);
	else if (address != -1)
		printf("Access of invalid address\n");
}

data_type MemoryManager::read_sp(int address) {
	if (address >= block_size && address < block_size*2)
		return local_mems[selected_local+1]->read(address - block_size);
	else
		printf("Access of invalid address\n");
}

void MemoryManager::jump_sub() {
	selected_local++;
}

void MemoryManager::write(int address, bool value) {
	if (address >= 0 && address < block_size)
		global.write(address, value);
	else if (address >= block_size && address < block_size*2)
		local_mems[selected_local]->write(address - block_size, value);
	else if (address >= block_size*2 && address < block_size*3)
		temp.write(address - block_size*2, value);
	else if (address != -1)
		printf("Access of invalid address\n");
}

void MemoryManager::write(int address, char value) {
	if (address >= 0 && address < block_size)
		global.write(address, value);
	else if (address >= block_size && address < block_size*2)
		local_mems[selected_local]->write(address - block_size, value);
	else if (address >= block_size*2 && address < block_size*3)
		temp.write(address - block_size*2, value);
	else if (address != -1)
		printf("Access of invalid address\n");
}

void MemoryManager::write(int address, short value) {
	if (address >= 0 && address < block_size)
		global.write(address, value);
	else if (address >= block_size && address < block_size*2)
		local_mems[selected_local]->write(address - block_size, value);
	else if (address >= block_size*2 && address < block_size*3)
		temp.write(address - block_size*2, value);
	else if (address != -1)
		printf("Access of invalid address\n");
}

void MemoryManager::write(int address, int value) {
	if (address >= 0 && address < block_size)
		global.write(address, value);
	else if (address >= block_size && address < block_size*2)
		local_mems[selected_local]->write(address - block_size, value);
	else if (address >= block_size*2 && address < block_size*3)
		temp.write(address - block_size*2, value);
	else if (address != -1)
		printf("Access of invalid address\n");
}

void MemoryManager::write(int address, long value) {
	if (address >= 0 && address < block_size)
		global.write(address, value);
	else if (address >= block_size && address < block_size*2)
		local_mems[selected_local]->write(address - block_size, value);
	else if (address >= block_size*2 && address < block_size*3)
		temp.write(address - block_size*2, value);
	else if (address != -1)
		printf("Access of invalid address\n");
}

void MemoryManager::write(int address, float value) {
	if (address >= 0 && address < block_size)
		global.write(address, value);
	else if (address >= block_size && address < block_size*2)
		local_mems[selected_local]->write(address - block_size, value);
	else if (address >= block_size*2 && address < block_size*3)
		temp.write(address - block_size*2, value);
	else if (address != -1)
		printf("Access of invalid address\n");
}

void MemoryManager::write(int address, double value) {
	if (address >= 0 && address < block_size)
		global.write(address, value);
	else if (address >= block_size && address < block_size*2)
		local_mems[selected_local]->write(address - block_size, value);
	else if (address >= block_size*2 && address < block_size*3)
		temp.write(address - block_size*2, value);
	else if (address != -1)
		printf("Access of invalid address\n");
}

void MemoryManager::write(int address, char* value) {
	if (address >= 0 && address < block_size)
		global.write(address, value);
	else if (address >= block_size && address < block_size*2)
		local_mems[selected_local]->write(address - block_size, value);
	else if (address >= block_size*2 && address < block_size*3)
		temp.write(address - block_size*2, value);
	else if (address != -1)
		printf("Access of invalid address\n");
}


text:
package org.apache.accumulo.server.cli;

import org.apache.accumulo.core.client.Instance;
import org.apache.accumulo.core.client.ZooKeeperInstance;
import org.apache.accumulo.core.util.DeprecationUtil;
import org.apache.accumulo.server.client.HdfsZooInstance;

public class ClientOnRequiredTable extends org.apache.accumulo.core.cli.ClientOnRequiredTable {
  {
    setPrincipal("root");
  }

  @Override
  synchronized public Instance getInstance() {
    if (cachedInstance != null)
      return cachedInstance;

    if (mock)
      return cachedInstance = DeprecationUtil.makeMockInstance(instance);
    if (instance == null) {
      return cachedInstance = HdfsZooInstance.getInstance();
    }
    return cachedInstance = new ZooKeeperInstance(getClientConfiguration());
  }
}


text:
Observium
=========

Dockerized version of Observium with support for external database, both
communitiy and professional editions (via arbritrary svn source), packages
to allow native LDAP auth, and easy plugin support by exposing htmldir as a
volume.

Using this image
----------------

Examples assume the following directory layout:

    $ tree $PWD
    /opt/observium/volumes
    ├── config
    │   └── config.php
    ├── html
    ├── logs
    └── rrd

Linking volumes and using Observium CE:

    $ docker run -d \
        --name observium \
        -p 8000:8000 \
        -v /opt/observium/volumes/config:/config \
        -v /opt/observium/volumes/html:/opt/observium/html \
        -v /opt/observium/volumes/logs:/opt/observium/logs \
        -v /opt/observium/volumes/rrd:/opt/observium/rrd \
        yelp/observium

Using Observium PE (or another SVN source):

    $ docker run -d \
        --name observium \
        -p 8000:8000 \
        -v /opt/observium/volumes/config:/config \
        -v /opt/observium/volumes/html:/opt/observium/html \
        -v /opt/observium/volumes/logs:/opt/observium/logs \
        -v /opt/observium/volumes/rrd:/opt/observium/rrd \
        -e USE_SVN=true \
        -e SVN_USER=user@example.com \
        -e SVN_PASS=dfed555743854a475345ae01a7668acc \
        -e SVN_REPO=http://svn.observium.org/svn/observium/trunk \
        yelp/observium

Volumes
-------

The following volumes are set in the container:

1. `/config`

   `config.php` should go here

2. `/opt/observium/html`

   This allows you to add HTML plugins if you wish (such as weathermap!)

3. `/opt/observium/logs`

   HTML error and access logs will be placed here as well as
   `observium.log` and `update-errors.log`

4. `/opt/observium/rrd`

   Preferably mount this volume where you have a good amount of space.
   Recommended that you back these up.

5. `/var/run/mysqld/mysqld.sock`

   If you're running MySQL on the local docker host, make use of this volume
   and set the SQL host to `localhost` is `config.php`

If you need to sub-in random, single files just add an extra `-v` argument to
your run (or however you're starting the container. Puppet anyone?) to the
path. We do this for `/etc/php5/apache2/php.ini`

Ports
-----

Only TCP/8000 is exposed.

Environment variables
---------------------

All of the environment variables that are used were shown above.

    USE_SVN=true
    SVN_USER=username
    SVN_PASS=password
    SVN_REPO=http://url/to/repo@revision

If you don't have a subscription but run your own managed copy, feel free to
sub-in your own repo.


text:
<?php

namespace TDM\BlogBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class TDMBlogBundle extends Bundle
{
}


text:
package ca.uhn.fhir.validation;

import ca.uhn.fhir.context.ConfigurationException;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.rest.api.EncodingEnum;
import ca.uhn.fhir.util.ClasspathUtil;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.w3c.dom.ls.LSInput;
import org.w3c.dom.ls.LSResourceResolver;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXParseException;

import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringReader;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class SchemaBaseValidator implements IValidatorModule {
	public static final String RESOURCES_JAR_NOTE = "Note that as of HAPI FHIR 1.2, DSTU2 validation files are kept in a separate JAR (hapi-fhir-validation-resources-XXX.jar) which must be added to your classpath. See the HAPI FHIR download page for more information.";

	private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SchemaBaseValidator.class);
	private static final Set<String> SCHEMA_NAMES;
	private static boolean ourJaxp15Supported;

	static {
		HashSet<String> sn = new HashSet<>();
		sn.add("xml.xsd");
		sn.add("xhtml1-strict.xsd");
		sn.add("fhir-single.xsd");
		sn.add("fhir-xhtml.xsd");
		sn.add("tombstone.xsd");
		sn.add("opensearch.xsd");
		sn.add("opensearchscore.xsd");
		sn.add("xmldsig-core-schema.xsd");
		SCHEMA_NAMES = Collections.unmodifiableSet(sn);
	}

	private final Map<String, Schema> myKeyToSchema = new HashMap<>();
	private FhirContext myCtx;

	public SchemaBaseValidator(FhirContext theContext) {
		myCtx = theContext;
	}

	private void doValidate(IValidationContext<?> theContext) {
		Schema schema = loadSchema();

		try {
			Validator validator = schema.newValidator();
			MyErrorHandler handler = new MyErrorHandler(theContext);
			validator.setErrorHandler(handler);
			String encodedResource;
			if (theContext.getResourceAsStringEncoding() == EncodingEnum.XML) {
				encodedResource = theContext.getResourceAsString();
			} else {
				encodedResource = theContext.getFhirContext().newXmlParser().encodeResourceToString((IBaseResource) theContext.getResource());
			}

			try {
				/*
				 * See https://github.com/hapifhir/hapi-fhir/issues/339
				 * https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing
				 */
				validator.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
				validator.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
			} catch (SAXNotRecognizedException ex) {
				ourLog.debug("Jaxp 1.5 Support not found.", ex);
			}

			validator.validate(new StreamSource(new StringReader(encodedResource)));
		} catch (SAXParseException e) {
			SingleValidationMessage message = new SingleValidationMessage();
			message.setLocationLine(e.getLineNumber());
			message.setLocationCol(e.getColumnNumber());
			message.setMessage(e.getLocalizedMessage());
			message.setSeverity(ResultSeverityEnum.FATAL);
			theContext.addValidationMessage(message);
		} catch (SAXException | IOException e) {
			// Catch all
			throw new ConfigurationException("Could not load/parse schema file", e);
		}
	}

	private Schema loadSchema() {
		String key = "fhir-single.xsd";

		synchronized (myKeyToSchema) {
			Schema schema = myKeyToSchema.get(key);
			if (schema != null) {
				return schema;
			}

			Source baseSource = loadXml("fhir-single.xsd");

			SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
			schemaFactory.setResourceResolver(new MyResourceResolver());

			try {
				try {
					/*
					 * See https://github.com/hapifhir/hapi-fhir/issues/339
					 * https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing
					 */
					schemaFactory.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
					ourJaxp15Supported = true;
				} catch (SAXNotRecognizedException e) {
					ourJaxp15Supported = false;
					ourLog.warn("Jaxp 1.5 Support not found.", e);
				}
				schema = schemaFactory.newSchema(new Source[]{baseSource});
			} catch (SAXException e) {
				throw new ConfigurationException("Could not load/parse schema file: " + "fhir-single.xsd", e);
			}
			myKeyToSchema.put(key, schema);
			return schema;
		}
	}

	Source loadXml(String theSchemaName) {
		String pathToBase = myCtx.getVersion().getPathToSchemaDefinitions() + '/' + theSchemaName;
		ourLog.debug("Going to load resource: {}", pathToBase);

		String contents = ClasspathUtil.loadResource(pathToBase, ClasspathUtil.withBom());
		return new StreamSource(new StringReader(contents), null);
	}

	@Override
	public void validateResource(IValidationContext<IBaseResource> theContext) {
		doValidate(theContext);
	}

	private final class MyResourceResolver implements LSResourceResolver {
		private MyResourceResolver() {
		}

		@Override
		public LSInput resolveResource(String theType, String theNamespaceURI, String thePublicId, String theSystemId, String theBaseURI) {
			if (theSystemId != null && SCHEMA_NAMES.contains(theSystemId)) {
				LSInputImpl input = new LSInputImpl();
				input.setPublicId(thePublicId);
				input.setSystemId(theSystemId);
				input.setBaseURI(theBaseURI);
				String pathToBase = myCtx.getVersion().getPathToSchemaDefinitions() + '/' + theSystemId;

				ourLog.debug("Loading referenced schema file: " + pathToBase);

				byte[] bytes = ClasspathUtil.loadResourceAsByteArray(pathToBase);
				input.setByteStream(new ByteArrayInputStream(bytes));
				return input;

			}

			throw new ConfigurationException("Unknown schema: " + theSystemId);
		}
	}

	private static class MyErrorHandler implements org.xml.sax.ErrorHandler {

		private IValidationContext<?> myContext;

		MyErrorHandler(IValidationContext<?> theContext) {
			myContext = theContext;
		}

		private void addIssue(SAXParseException theException, ResultSeverityEnum theSeverity) {
			SingleValidationMessage message = new SingleValidationMessage();
			message.setLocationLine(theException.getLineNumber());
			message.setLocationCol(theException.getColumnNumber());
			message.setMessage(theException.getLocalizedMessage());
			message.setSeverity(theSeverity);
			myContext.addValidationMessage(message);
		}

		@Override
		public void error(SAXParseException theException) {
			addIssue(theException, ResultSeverityEnum.ERROR);
		}

		@Override
		public void fatalError(SAXParseException theException) {
			addIssue(theException, ResultSeverityEnum.FATAL);
		}

		@Override
		public void warning(SAXParseException theException) {
			addIssue(theException, ResultSeverityEnum.WARNING);
		}

	}

	public static boolean isJaxp15Supported() {
		return ourJaxp15Supported;
	}

}


text:
package org.testcontainers.junit.wait;

import org.jetbrains.annotations.NotNull;
import org.junit.Before;
import org.rnorth.ducttape.RetryCountExceededException;
import org.rnorth.visibleassertions.VisibleAssertions;
import org.testcontainers.containers.ContainerLaunchException;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.wait.WaitStrategy;

import java.time.Duration;
import java.util.concurrent.atomic.AtomicBoolean;

import static org.junit.Assert.*;

/**
 * Common test methods for {@link WaitStrategy} implementations.
 *
 * @author Pete Cornish {@literal <outofcoffee@gmail.com>}
 */
public abstract class AbstractWaitStrategyTest<W extends WaitStrategy> {
    private static final long WAIT_TIMEOUT_MILLIS = 3000;
    private static final String IMAGE_NAME = "alpine:latest";

    /**
     * Indicates that the WaitStrategy has completed waiting successfully.
     */
    private AtomicBoolean ready;

    /**
     * Subclasses should return an instance of {@link W} that sets {@code ready} to {@code true},
     * if the wait was successful.
     *
     * @param ready the AtomicBoolean on which to indicate success
     * @return WaitStrategy implementation
     */
    @NotNull
    protected abstract W buildWaitStrategy(final AtomicBoolean ready);

    @Before
    public void setUp() throws Exception {
        ready = new AtomicBoolean(false);
    }

    /**
     * Starts a GenericContainer with the {@link #IMAGE_NAME} image, passing the given {@code shellCommand} as
     * a parameter to {@literal sh -c} (the container CMD).
     *
     * @param shellCommand the shell command to execute
     * @return the (unstarted) container
     */
    private GenericContainer startContainerWithCommand(String shellCommand) {
        final WaitStrategy waitStrategy = buildWaitStrategy(ready)
                .withStartupTimeout(Duration.ofMillis(WAIT_TIMEOUT_MILLIS));

        // apply WaitStrategy to container
        return new GenericContainer(IMAGE_NAME)
                .withExposedPorts(8080)
                .withCommand("sh", "-c", shellCommand)
                .waitingFor(waitStrategy);
    }

    /**
     * Expects that the WaitStrategy returns successfully after connection to a container with a listening port.
     *
     * @param shellCommand the shell command to execute
     */
    protected void waitUntilReadyAndSucceed(String shellCommand) {
        final GenericContainer container = startContainerWithCommand(shellCommand);

        // start() blocks until successful or timeout
        container.start();

        assertTrue(String.format("Expected container to be ready after timeout of %sms",
                WAIT_TIMEOUT_MILLIS), ready.get());
    }

    /**
     * Expects that the WaitStrategy throws a {@link RetryCountExceededException} after unsuccessful connection
     * to a container with a listening port.
     *
     * @param shellCommand the shell command to execute
     */
    protected void waitUntilReadyAndTimeout(String shellCommand) {
        final GenericContainer container = startContainerWithCommand(shellCommand);

        // start() blocks until successful or timeout
        VisibleAssertions.assertThrows("an exception is thrown when timeout occurs (" + WAIT_TIMEOUT_MILLIS + "ms)",
                ContainerLaunchException.class,
                container::start);

    }
}


text:
using System;
using System.Linq;
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Excess.Compiler.Core;

namespace Excess.Compiler.Roslyn
{
    using CSharp = Microsoft.CodeAnalysis.CSharp.SyntaxFactory;

    public class RoslynLexicalAnalysis : BaseLexicalAnalysis<SyntaxToken, SyntaxNode, SemanticModel>
    {
        public override IIndentationGrammarAnalysis<SyntaxToken, SyntaxNode, GNode> indented<GNode, GRoot>(
            string keyword,
            ExtensionKind kind,
            Action<GRoot, LexicalExtension<SyntaxToken>> init)
        {
            var result = new RoslynIndentationGrammarAnalysis<GNode, GRoot>(null);
            var grammar = new IndentedGrammar<SyntaxToken, SyntaxNode, GNode>(
                (extension, scope) =>
                {
                    var indentRoot = IndentationParser.Parse(extension.Body, 4); //td: !!!
                    var root = new GRoot();
                    init?.Invoke(root, extension);

                    foreach (var child in indentRoot.Children)
                    {
                        result.transform(root, child, scope);
                    }

                    return root;
                });

            result.Grammar = grammar<IndentedGrammar<SyntaxToken, SyntaxNode, GNode>, GNode>(keyword, kind, grammar);
            return result;
        }

        protected override SyntaxNode normalize(SyntaxNode root, Scope scope)
        {
            IEnumerable<SyntaxNode> rootStatements = null;
            IEnumerable<SyntaxNode> rootMembers = null;
            IEnumerable<SyntaxNode> rootTypes = null;

            var node = root;
            var normalized = false;
            if (_normalizeStatements != null)
                node = normalizeCode(root, out rootStatements, out normalized);

            if (!normalized && (_normalizeMembers != null || _normalizeTypes != null))
                node = normalizePass(root, out rootMembers, out rootTypes, out normalized);

            if (normalized)
            {
                if (_normalizeStatements != null &&  rootStatements != null && rootStatements.Any())
                    node = _normalizeStatements(node, rootStatements, scope);

                if (_normalizeMembers != null)
                {
                    if (node != root)
                    {
                        node = normalizePass(node, out rootMembers, out rootTypes, out normalized);
                        root = node;
                    }

                    if (rootMembers != null && rootMembers.Any())
                        node = _normalizeMembers(node, rootMembers, scope);
                }

                if (_normalizeTypes != null)
                {
                    if (node != root)
                        node = normalizePass(node, out rootMembers, out rootTypes, out normalized);

                    if (rootTypes != null && rootTypes.Any())
                        node = _normalizeTypes(node, rootTypes, scope);
                }
            }

            if (_normalizeThen != null)
                node = _normalizeThen(node, scope);

            return node;
        }

        private SyntaxNode normalizeCode(SyntaxNode root, out IEnumerable<SyntaxNode> rootStatements, out bool normalized)
        {
            normalized = true;
            rootStatements = null;

            //td: line numbers!
            var newTree = CSharp.ParseSyntaxTree("void m() {" + root.ToFullString() + "}", options: new CSharpParseOptions(kind: SourceCodeKind.Script));
            try
            {
                var block = newTree
                    .GetRoot()
                    .ChildNodes()
                    .OfType<MethodDeclarationSyntax>()
                    .Single()
                    .Body;

                if (block.ChildNodes().All(child => child is StatementSyntax))
                {
                    rootStatements = new List<StatementSyntax>(block.ChildNodes().OfType<StatementSyntax>());
                    return block;
                }
            }
            catch
            {
            }

            normalized = false;
            return root;
        }

        private SyntaxNode normalizePass(SyntaxNode root, out IEnumerable<SyntaxNode> rootMembers, out IEnumerable<SyntaxNode> rootTypes, out bool normalized)
        {
            rootMembers = null;
            rootTypes = null;
            normalized = false;

            var tree = root.SyntaxTree;
            var codeErrors = root.GetDiagnostics().Where(error => error.Id == "CS1022").
                                  OrderBy(error => error.Location.SourceSpan.Start).GetEnumerator();

            Diagnostic currError = null;
            int currErrorPos = 0;

            if (codeErrors != null && codeErrors.MoveNext())
                currError = codeErrors.Current;

            BlockSyntax statementBlock;

            List<StatementSyntax> statements = new List<StatementSyntax>();
            List<MemberDeclarationSyntax> members = new List<MemberDeclarationSyntax>();
            List<MemberDeclarationSyntax> types = new List<MemberDeclarationSyntax>();
            List<TextSpan> toRemove = new List<TextSpan>();
            foreach (var child in root.ChildNodes())
            {
                if (child is IncompleteMemberSyntax)
                    continue;

                if (child is FieldDeclarationSyntax)
                {
                    //case: code variable?
                    FieldDeclarationSyntax field = (FieldDeclarationSyntax)child;
                    if (!field.Modifiers.Any())
                    {
                        //td: !!! variable initialization
                        continue;
                    }
                }

                if (child is MethodDeclarationSyntax)
                {
                    //case: bad method?
                    MethodDeclarationSyntax method = (MethodDeclarationSyntax)child;
                    if (method.Body == null)
                        continue;
                }

                if (child is MemberDeclarationSyntax)
                {
                    bool foundError = false;
                    if (currError != null)
                    {
                        if (child.SpanStart > currError.Location.SourceSpan.Start)
                        {
                            var errorSpan = new TextSpan(currErrorPos, child.SpanStart - currErrorPos);
                            SourceText errorSource = tree.GetText().GetSubText(errorSpan);

                            statementBlock = (BlockSyntax)SyntaxFactory.ParseStatement("{" + errorSource + "}");
                            statements.AddRange(statementBlock.Statements);

                            toRemove.Add(errorSpan);

                            foundError = true;
                            currError = null;
                            while (codeErrors.MoveNext())
                            {
                                var nextError = codeErrors.Current;
                                if (nextError.Location.SourceSpan.Start > child.Span.End)
                                {
                                    currError = nextError;
                                    break;
                                }
                            }
                        }
                    }

                    currErrorPos = child.Span.End;
                    var toAdd = child as MemberDeclarationSyntax;

                    if (foundError)
                    {
                        toAdd = toAdd.ReplaceTrivia(child.GetLeadingTrivia(), (oldTrivia, newTrivia) =>
                        {
                            return CSharp.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, string.Empty);
                        });
                    }

                    if (toAdd is TypeDeclarationSyntax || toAdd is EnumDeclarationSyntax)
                        types.Add(toAdd);
                    else if (!(toAdd is NamespaceDeclarationSyntax))
                        members.Add(toAdd);
                }
                else
                {
                    //any other top level construct indicates completeness
                    return root;
                }
            }

            if (currError != null)
            {
                var errorSpan = new TextSpan(currErrorPos, tree.GetRoot().FullSpan.End - currErrorPos);
                SourceText errorSource = tree.GetText().GetSubText(errorSpan);
                statementBlock = (BlockSyntax)SyntaxFactory.ParseStatement("{" + errorSource + "}");
                statements.AddRange(statementBlock.Statements);

                toRemove.Add(errorSpan);
            }

            normalized = statements.Any() || members.Any() || !types.Any();

            if (!normalized)
                return root; //nothing to se here

            rootMembers = members;
            rootTypes = types;

            if (!toRemove.Any())
                return root; //nothing to remove

            return root.RemoveNodes(
                root
                    .ChildNodes()
                    .Where(node => contained(node, toRemove)),
                SyntaxRemoveOptions.KeepEndOfLine);
        }

        private bool contained(SyntaxNode node, List<TextSpan> text)
        {
            foreach(var inner in text)
            {
                if (inner.Contains(node.FullSpan))
                    return true;
            }

            return false;
        }
    }
}


text:
.class Landroid/widget/StackView$StackFrame;
.super Landroid/widget/FrameLayout;
.source "StackView.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/widget/StackView;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "StackFrame"
.end annotation

# instance fields
.field sliderAnimator:Ljava/lang/ref/WeakReference;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/lang/ref/WeakReference",
            "<",
            "Landroid/animation/ObjectAnimator;",
            ">;"
        }
    .end annotation
.end field

.field transformAnimator:Ljava/lang/ref/WeakReference;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/lang/ref/WeakReference",
            "<",
            "Landroid/animation/ObjectAnimator;",
            ">;"
        }
    .end annotation
.end field

# direct methods
.method public constructor <init>(Landroid/content/Context;)V
    .locals 0
    .parameter "context"

    .prologue
    .line 475
    invoke-direct {p0, p1}, Landroid/widget/FrameLayout;-><init>(Landroid/content/Context;)V

    .line 476
    return-void
.end method

# virtual methods
.method cancelSliderAnimator()Z
    .locals 2

    .prologue
    .line 498
    iget-object v1, p0, Landroid/widget/StackView$StackFrame;->sliderAnimator:Ljava/lang/ref/WeakReference;

    if-eqz v1, :cond_0

    .line 499
    iget-object v1, p0, Landroid/widget/StackView$StackFrame;->sliderAnimator:Ljava/lang/ref/WeakReference;

    invoke-virtual {v1}, Ljava/lang/ref/WeakReference;->get()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/animation/ObjectAnimator;

    .line 500
    .local v0, oa:Landroid/animation/ObjectAnimator;
    if-eqz v0, :cond_0

    .line 501
    invoke-virtual {v0}, Landroid/animation/ObjectAnimator;->cancel()V

    .line 502
    const/4 v1, 0x1

    .line 505
    .end local v0           #oa:Landroid/animation/ObjectAnimator;
    :goto_0
    return v1

    :cond_0
    const/4 v1, 0x0

    goto :goto_0
.end method

.method cancelTransformAnimator()Z
    .locals 2

    .prologue
    .line 487
    iget-object v1, p0, Landroid/widget/StackView$StackFrame;->transformAnimator:Ljava/lang/ref/WeakReference;

    if-eqz v1, :cond_0

    .line 488
    iget-object v1, p0, Landroid/widget/StackView$StackFrame;->transformAnimator:Ljava/lang/ref/WeakReference;

    invoke-virtual {v1}, Ljava/lang/ref/WeakReference;->get()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/animation/ObjectAnimator;

    .line 489
    .local v0, oa:Landroid/animation/ObjectAnimator;
    if-eqz v0, :cond_0

    .line 490
    invoke-virtual {v0}, Landroid/animation/ObjectAnimator;->cancel()V

    .line 491
    const/4 v1, 0x1

    .line 494
    .end local v0           #oa:Landroid/animation/ObjectAnimator;
    :goto_0
    return v1

    :cond_0
    const/4 v1, 0x0

    goto :goto_0
.end method

.method setSliderAnimator(Landroid/animation/ObjectAnimator;)V
    .locals 1
    .parameter "oa"

    .prologue
    .line 483
    new-instance v0, Ljava/lang/ref/WeakReference;

    invoke-direct {v0, p1}, Ljava/lang/ref/WeakReference;-><init>(Ljava/lang/Object;)V

    iput-object v0, p0, Landroid/widget/StackView$StackFrame;->sliderAnimator:Ljava/lang/ref/WeakReference;

    .line 484
    return-void
.end method

.method setTransformAnimator(Landroid/animation/ObjectAnimator;)V
    .locals 1
    .parameter "oa"

    .prologue
    .line 479
    new-instance v0, Ljava/lang/ref/WeakReference;

    invoke-direct {v0, p1}, Ljava/lang/ref/WeakReference;-><init>(Ljava/lang/Object;)V

    iput-object v0, p0, Landroid/widget/StackView$StackFrame;->transformAnimator:Ljava/lang/ref/WeakReference;

    .line 480
    return-void
.end method


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using Microsoft.MixedReality.Toolkit.Core.Definitions.Devices;
using Microsoft.MixedReality.Toolkit.Core.Definitions.InputSystem;
using Microsoft.MixedReality.Toolkit.Core.Definitions.Utilities;
using Microsoft.MixedReality.Toolkit.Core.Interfaces.InputSystem;
using UnityEngine;

namespace Microsoft.MixedReality.Toolkit.Core.DataProviders.Controllers.OpenVR
{
    /// <summary>
    /// Open VR Implementation of the Windows Mixed Reality Motion Controllers.
    /// </summary>
    public class WindowsMixedRealityOpenVRMotionController : GenericOpenVRController
    {
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="trackingState"></param>
        /// <param name="controllerHandedness"></param>
        /// <param name="inputSource"></param>
        /// <param name="interactions"></param>
        public WindowsMixedRealityOpenVRMotionController(TrackingState trackingState, Handedness controllerHandedness, IMixedRealityInputSource inputSource = null, MixedRealityInteractionMapping[] interactions = null)
            : base(trackingState, controllerHandedness, inputSource, interactions)
        {
            PointerOffsetAngle = -30f;
        }

        /// <inheritdoc />
        public override MixedRealityInteractionMapping[] DefaultLeftHandedInteractions => new[]
        {
            new MixedRealityInteractionMapping(0, "Spatial Pointer", AxisType.SixDof, DeviceInputType.SpatialPointer, MixedRealityInputAction.None),
            new MixedRealityInteractionMapping(1, "Spatial Grip", AxisType.SixDof, DeviceInputType.SpatialGrip, MixedRealityInputAction.None),
            new MixedRealityInteractionMapping(2, "Grip Press", AxisType.SingleAxis, DeviceInputType.TriggerPress, ControllerMappingLibrary.AXIS_11),
            new MixedRealityInteractionMapping(3, "Trigger Position", AxisType.SingleAxis, DeviceInputType.Trigger, ControllerMappingLibrary.AXIS_9),
            new MixedRealityInteractionMapping(4, "Trigger Press (Select)", AxisType.Digital, DeviceInputType.TriggerPress,  KeyCode.JoystickButton14),
            new MixedRealityInteractionMapping(5, "Trigger Touch", AxisType.SingleAxis, DeviceInputType.TriggerTouch, ControllerMappingLibrary.AXIS_9),
            new MixedRealityInteractionMapping(6, "Touchpad Position", AxisType.DualAxis, DeviceInputType.Touchpad, ControllerMappingLibrary.AXIS_17, ControllerMappingLibrary.AXIS_18),
            new MixedRealityInteractionMapping(7, "Touchpad Touch", AxisType.Digital, DeviceInputType.TouchpadTouch, KeyCode.JoystickButton16),
            new MixedRealityInteractionMapping(8, "Touchpad Press", AxisType.Digital, DeviceInputType.TouchpadPress, KeyCode.JoystickButton8),
            new MixedRealityInteractionMapping(9, "Menu Press", AxisType.Digital, DeviceInputType.ButtonPress,  KeyCode.JoystickButton0),
            new MixedRealityInteractionMapping(10, "Thumbstick Position", AxisType.DualAxis, DeviceInputType.ThumbStick, ControllerMappingLibrary.AXIS_1, ControllerMappingLibrary.AXIS_2, false, true),
            new MixedRealityInteractionMapping(11, "Thumbstick Click", AxisType.Digital, DeviceInputType.ButtonPress,  KeyCode.JoystickButton8),
        };

        /// <inheritdoc />
        public override MixedRealityInteractionMapping[] DefaultRightHandedInteractions => new[]
        {
            new MixedRealityInteractionMapping(0, "Spatial Pointer", AxisType.SixDof, DeviceInputType.SpatialPointer, MixedRealityInputAction.None),
            new MixedRealityInteractionMapping(1, "Spatial Grip", AxisType.SixDof, DeviceInputType.SpatialGrip, MixedRealityInputAction.None),
            new MixedRealityInteractionMapping(2, "Grip Press", AxisType.SingleAxis, DeviceInputType.ButtonPress, ControllerMappingLibrary.AXIS_12),
            new MixedRealityInteractionMapping(3, "Trigger Position", AxisType.SingleAxis, DeviceInputType.Trigger, ControllerMappingLibrary.AXIS_10),
            new MixedRealityInteractionMapping(4, "Trigger Press (Select)", AxisType.Digital, DeviceInputType.TriggerPress,  KeyCode.JoystickButton15),
            new MixedRealityInteractionMapping(5, "Trigger Touch", AxisType.SingleAxis, DeviceInputType.TriggerTouch, ControllerMappingLibrary.AXIS_10),
            new MixedRealityInteractionMapping(6, "Touchpad Position", AxisType.DualAxis, DeviceInputType.Touchpad, ControllerMappingLibrary.AXIS_19, ControllerMappingLibrary.AXIS_20),
            new MixedRealityInteractionMapping(7, "Touchpad Touch", AxisType.Digital, DeviceInputType.TouchpadTouch, KeyCode.JoystickButton17),
            new MixedRealityInteractionMapping(8, "Touchpad Press", AxisType.Digital, DeviceInputType.TouchpadPress, KeyCode.JoystickButton9),
            new MixedRealityInteractionMapping(9, "Menu Press", AxisType.Digital, DeviceInputType.ButtonPress, KeyCode.JoystickButton2),
            new MixedRealityInteractionMapping(10, "Thumbstick Position", AxisType.DualAxis, DeviceInputType.ThumbStick, ControllerMappingLibrary.AXIS_4, ControllerMappingLibrary.AXIS_5, false, true),
            new MixedRealityInteractionMapping(11, "Thumbstick Click", AxisType.Digital, DeviceInputType.ButtonPress,  KeyCode.JoystickButton9),
        };

        /// <inheritdoc />
        public override void SetupDefaultInteractions(Handedness controllerHandedness)
        {
            AssignControllerMappings(controllerHandedness == Handedness.Left ? DefaultLeftHandedInteractions : DefaultRightHandedInteractions);
        }
    }
}


text:
package number

import (
	"net/http"
	"reflect"
	"testing"

	"github.com/messagebird/go-rest-api/v9/internal/mbtest"
	"github.com/stretchr/testify/assert"
)

func TestMain(m *testing.M) {
	mbtest.EnableServer(m)
}

func TestSearch(t *testing.T) {
	mbtest.WillReturnTestdata(t, "numberSearch.json", http.StatusOK)
	client := mbtest.Client(t)

	numLis, err := Search(client, "NL", &SearchRequest{
		Limit:         10,
		Features:      []string{"sms", "voice"},
		Type:          "mobile",
		SearchPattern: SearchPatternEnd,
	})
	assert.NoError(t, err)
	assert.Equal(t, "NL", numLis.Items[0].Country)

	mbtest.AssertEndpointCalled(t, http.MethodGet, "/v1/available-phone-numbers/NL")

	query := mbtest.Request.URL.RawQuery
	assert.Equal(t, "exclude_numbers_require_verification=false&features=sms&features=voice&limit=10&prices=false&search_pattern=end&type=mobile", query)
}

func TestList(t *testing.T) {
	mbtest.WillReturnTestdata(t, "numberList.json", http.StatusOK)
	client := mbtest.Client(t)

	numLis, err := List(client, &ListRequest{Limit: 10})
	assert.NoError(t, err)
	assert.Equal(t, "NL", numLis.Items[0].Country)

	mbtest.AssertEndpointCalled(t, http.MethodGet, "/v1/phone-numbers")

	query := mbtest.Request.URL.RawQuery
	assert.Equal(t, "limit=10", query)
}

func TestRead(t *testing.T) {
	mbtest.WillReturnTestdata(t, "numberRead.json", http.StatusOK)
	client := mbtest.Client(t)

	num, err := Read(client, "31612345670")
	assert.NoError(t, err)
	assert.Equal(t, "31612345670", num.Number)

	mbtest.AssertEndpointCalled(t, http.MethodGet, "/v1/phone-numbers/31612345670")
}

func TestDelete(t *testing.T) {
	mbtest.WillReturn([]byte(""), http.StatusNoContent)
	client := mbtest.Client(t)

	err := Delete(client, "31612345670")
	assert.NoError(t, err)

	mbtest.AssertEndpointCalled(t, http.MethodDelete, "/v1/phone-numbers/31612345670")
}

func TestUpdate(t *testing.T) {

	mbtest.WillReturnTestdata(t, "numberUpdatedObject.json", http.StatusOK)
	client := mbtest.Client(t)

	number, err := Update(client, "31612345670", &UpdateRequest{
		Tags: []string{"tag1", "tag2", "tag3"},
	})
	assert.NoError(t, err)

	mbtest.AssertEndpointCalled(t, http.MethodPatch, "/v1/phone-numbers/31612345670")
	mbtest.AssertTestdata(t, "numberUpdateRequestObject.json", mbtest.Request.Body)

	if !reflect.DeepEqual(number.Tags, []string{"tag1", "tag2", "tag3"}) {
		t.Errorf("Unexpected number tags: %s, expected: ['tag1', 'tag2', 'tag3']", number.Tags)
	}
}

func TestPurchase(t *testing.T) {
	mbtest.WillReturnTestdata(t, "numberCreateObject.json", http.StatusCreated)
	client := mbtest.Client(t)

	number, err := Purchase(client, &PurchaseRequest{
		Number:                "31971234567",
		Country:               "NL",
		BillingIntervalMonths: 1,
	})
	assert.NoError(t, err)

	mbtest.AssertEndpointCalled(t, http.MethodPost, "/v1/phone-numbers")
	mbtest.AssertTestdata(t, "numberCreateRequestObject.json", mbtest.Request.Body)
	assert.Equal(t, "31971234567", number.Number)
	assert.Equal(t, "NL", number.Country)
}


text:
(* ::Package:: *)

(*
   Based on Andrej Karpathy. Not completely faithful implementation. (He uses extra convolution layer and ReLU)
   See: http://cs.stanford.edu/people/karpathy/convnetjs/demo/cifar10.html

   Epoch: 56
   Training Loss: .752
   Validation Loss: 1.18

   Validation: 60.6%
*)

<<"C:/users/julian/documents/github/Machine-Vision/NeuralNetworks/NeuralNetwork.m"

<<"C:/users/julian/documents/github/Machine-Vision/NeuralNetworks/CIFAR10/CIFAR10Data.m"

SeedRandom[1234];
CIFARNet2={
   ConvolveFilterBankToFilterBank[Table[
      ConvolveFilterBankTo2D[0,{
         (Table[Random[],{5},{5}]-.5),
         (Table[Random[],{5},{5}]-.5),
         (Table[Random[],{5},{5}]-.5)}/(25*3.)],
      {f,1,32}]],Tanh,
   MaxPoolingFilterBankToFilterBank,
   ConvolveFilterBankToFilterBank[Table[
      ConvolveFilterBankTo2D[0,
         (Table[Random[],{32},{5},{5}]-.5)/(32*5*5)],
      {f,1,32}]],Tanh,
   FilterBankToFilterBankInit[32,32],
   Tanh,
   Adaptor3DTo1D[32,10,10],
   FullyConnected1DTo1D[Table[.0,{10}],Table[Random[]-.5,{10},{32*10*10}]],
   Softmax
};

CIFAR10NetTrainingInputs=ColTrainingImages[[1;;4000]]*1.;
CIFAR10NetTrainingOutputs=Map[ReplacePart[ConstantArray[0,10],(#+1)->1]&,TrainingLabels];

CIFAR10NetValidationInputs=ColValidationImages[[All]]*1.;
CIFAR10NetValidationOutputs=Map[ReplacePart[ConstantArray[0,10],(#+1)->1]&,ValidationLabels];

wl=CIFARNet2;
TrainingHistory={};
ValidationHistory={};

FilterBankToFilterBankInit[noFromLayers_,noToLayers_]:=
   FilterBankToFilterBank[Table[0.,{noToLayers}],Table[Random[]-.5,{noToLayers},{noFromLayers}]/Sqrt[noFromLayers]]

TrainNet2MB:=MiniBatchGradientDescent[
      wl,ColTrainingImages,CIFAR10NetTrainingOutputs,
      NNGrad,ClassificationLoss,
        {MaxEpoch->500000,
         ValidationInputs->ColValidationImages[[1;;500]],
         ValidationTargets->CIFAR10NetValidationOutputs[[1;;500]],
         UpdateFunction->WebMonitor["CIFAR10\\Net2MB"],
         InitialLearningRate->\[Lambda]}];

CIFAR10Output[probs_]:=BarChart[probs[[Reverse[Ordering[probs,-3]]]],ChartLabels->WordLabels[[Reverse[Ordering[probs,-3]]]]];

CIFAR10Outputs[probs_,pics_]:=MapThread[{Image[#2,Interleaving->False],CIFAR10Output[#1]}&,{probs,pics}];


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="@dimen/nav_header_height"
    android:background="@drawable/side_nav_bar"
    android:gravity="bottom"
    android:orientation="vertical"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        android:src="@drawable/image_bg"
        android:scaleType="centerCrop"/>

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/menu_center_grad"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="karthik@gmail.com"
        android:textSize="@dimen/_14sdp"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="10dp"
        android:id="@+id/tvHeaderCustomerName"
        android:layout_marginLeft="10dp"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/tvHeaderCustomerName"
        android:text="karthikeyan"
        android:textColor="@color/colorWhite"
        android:textSize="@dimen/_20sdp"
        android:layout_marginLeft="10dp"
        />

</RelativeLayout>


text:
title: "Troubleshooting"
description: "Need to troubleshoot Sensu Go? Here's how to look into errors, including service logging and the log levels you need to know about. Logs produced by Sensu services – i.e., sensu-backend and sensu-agent – are often the best source of truth when troubleshooting issues, so we recommend you start there."
weight: 2000
version: "5.5"
product: "Sensu Go"
platformContent: false
menu:
  sensu-go-5.5:
    parent: guides
---

- [Service logging](#service-logging)
	- [Log levels](#log-levels)
	- [Log file locations](#log-file-locations)
- [Sensu backend startup errors](#sensu-backend-startup-errors)
- [Permission issues](#permission-issues)
- [Handlers and filters](#troubleshooting-handlers-and-filters)

## Service logging

Logs produced by Sensu services -- i.e. sensu-backend and sensu-agent -- are
often the best place to start when troubleshooting a variety of issues.

### Log levels

Each log message is associated with a log level, indicative of the relative severity of the event being
logged:

| Log level          | Description |
|--------------------|-----------------------------------------------------------------------|
| panic              | Severe errors causing the service to shut down in an unexpected state |
| fatal              | Fatal errors causing the service to shut down (status 0)              |
| error              | Non-fatal service error messages                                      |
| warn               | Warning messages indicating potential issues                          |
| info               | Informational messages representing service actions                   |
| debug              | Detailed service operation messages to help troubleshoot issues       |

These log levels can be configured by specifying the desired log level as the
value of `log-level` in the service configuration file (e.g. `agent.yml` or
`backend.yml` configuration files), or as an argument to the `--log-level`
command line flag:

{{< highlight shell >}}
sensu-agent start --log-level debug
{{< /highlight >}}

Changes to log level via configuration file or command line arguments require
restarting the service. For guidance on restarting a service, please
consult the Operating section of the [agent][agent-ref] or
[backend][backend-ref] reference, respectively.

### Log file locations

Sensu services print [structured log messages][structured] to standard output.
In order to capture these log messages to disk or another logging facility, Sensu services
make use of capabilities provided by the underlying operating system's service
management. For example, logs are sent to the journald when systemd is the service manager,
whereas log messages are redirected to `/var/log/sensu` when running under sysv
init schemes. If you are running systemd as your service manager and would rather have logs written to `/var/log/sensu/`, see the guide to [forwarding logs from journald to syslog][journald-syslog].

In the table below, the common targets for logging and example commands for
following those logs are described. The name of the desired service, e.g.
`backend` or `agent` may be substituted for `${service}` variable.

| Platform     | Version           | Target | Command to follow log |
|--------------|-------------------|--------------|-----------------------------------------------|
| RHEL/Centos  | >= 7       | journald     | {{< highlight shell >}}journalctl --follow --unit sensu-${service}{{< /highlight >}}   |
| RHEL/Centos  | <= 6       | log file     | {{< highlight shell >}}tail --follow /var/log/sensu/sensu-${service}{{< /highlight >}} |
| Ubuntu       | >= 15.04   | journald     | {{< highlight shell >}}journalctl --follow --unit sensu-${service}{{< /highlight >}}   |
| Ubuntu       | <= 14.10   | log file     | {{< highlight shell >}}tail --follow /var/log/sensu/sensu-${service}{{< /highlight >}} |
| Debian       | >= 8       | journald     | {{< highlight shell >}}journalctl --follow --unit sensu-${service}{{< /highlight >}}   |
| Debian       | <= 7       | log file     | {{< highlight shell >}}tail --follow /var/log/sensu/sensu-${service}{{< /highlight >}} |
| Windows      | Any        | log file     | {{< highlight powershell >}}Get-Content -  Path "C:\scripts\test.txt" -Wait{{< /highlight >}}

_NOTE: Platform versions described above are for reference only and do not
supercede the documented [supported platforms][platforms]._

## Sensu backend startup errors

The following errors are expected when starting up a Sensu backend with the default configuration.

{{< highlight shell >}}
{"component":"etcd","level":"warning","msg":"simple token is not cryptographically signed","pkg":"auth","time":"2019-11-04T10:26:31-05:00"}
{"component":"etcd","level":"warning","msg":"set the initial cluster version to 3.3","pkg":"etcdserver/membership","time":"2019-11-04T10:26:31-05:00"}
{"component":"etcd","level":"warning","msg":"serving insecure client requests on 127.0.0.1:2379, this is strongly discouraged!","pkg":"embed","time":"2019-11-04T10:26:33-05:00"}
{{< /highlight >}}

The `serving insecure client requests` error is an expected warning from etcd.
TLS configuration is recommended but not required. For more information, see [etcd security documentation][1].

## Permission issues

Files and folders within `/var/cache/sensu/` and `/var/lib/sensu/` need to be owned by the sensu user and group. You will see a logged error similar to the following if there is a permission issue with either the sensu-backend or the sensu-agent:

{{< highlight shell >}}
{"component":"agent","error":"open /var/cache/sensu/sensu-agent/assets.db: permission denied","level":"fatal","msg":"error executing sensu-agent","time":"2019-02-21T22:01:04Z"}
{"component":"backend","level":"fatal","msg":"error starting etcd: mkdir /var/lib/sensu: permission denied","time":"2019-03-05T20:24:01Z"}
{{< /highlight >}}

You can use a recursive `chown` to resolve permission issues with the sensu-backend:

{{< highlight shell >}}
sudo chown -R sensu:sensu /var/cache/sensu/sensu-backend
{{< /highlight >}}

or the sensu-agent:

{{< highlight shell >}}
sudo chown -R sensu:sensu /var/cache/sensu/sensu-agent
{{< /highlight >}}

## Troubleshooting handlers and filters

Whether implementing new workflows or modifying existing ones, its sometimes necessary to troubleshoot various stages of the event pipeline. In many cases generating events using the [agent API][agent-api] will save you time and effort over modifying existing check configurations.

Here's an example using curl with the API of a local sensu-agent process to generate test-event check results:

{{< highlight shell >}}
curl -X POST \
-H 'Content-Type: application/json' \
-d '{
  "check": {
    "metadata": {
      "name": "test-event",
      "namespace": "default"
    },
    "status": 2,
    "output": "this is a test event targeting the email_ops handler",
    "handlers": [ "email_ops" ]
  }
}' \
http://127.0.0.1:3031/events
{{< /highlight >}}

Additionally, it's frequently helpful to see the full event object being passed to your workflows. We recommend using a debug handler like this one to write an event to disk as JSON data:

{{< language-toggle >}}

{{< highlight yml >}}
type: Handler
api_version: core/v2
metadata:
  name: debug
  namespace: default
spec:
  type: pipe
  command: cat > /var/log/sensu/debug-event.json
  timeout: 2
{{< /highlight >}}

{{< highlight json >}}
{
  "type": "Handler",
  "api_version": "core/v2",
  "metadata": {
    "name": "debug"
  },
  "spec": {
    "type": "pipe",
    "command": "cat > /var/log/sensu/debug-event.json",
    "timeout": 2
  }
}
{{< /highlight >}}

{{< /language-toggle >}}

With this handler definition installed in your Sensu backend, you can add the `debug` to the list of handlers in your test event:

{{< highlight shell >}}
curl -X POST \
-H 'Content-Type: application/json' \
-d '{
  "check": {
    "metadata": {
      "name": "test-event"
    },
    "status": 2,
    "output": "this is a test event targeting the email_ops handler",
    "handlers": [ "email_ops", "debug" ]
  }
}' \
http://127.0.0.1:3031/events
{{< /highlight >}}

The event data should be written to `/var/log/sensu/debug-event.json` for inspection. The contents of this file will be overwritten by every event sent to the `debug` handler.

_NOTE: When multiple Sensu backends are configured in a cluster, event processing is distributed across all members. You may need to check the filesystem of each Sensu backend to locate the debug output for your test event._

[agent-api]: ../../reference/agent#events-post
[structured]: https://dzone.com/articles/what-is-structured-logging
[journalctl]: https://www.digitalocean.com/community/tutorials/how-to-use-journalctl-to-view-and-manipulate-systemd-logs
[platforms]: ../../installation/platforms
[agent-ref]: ../../reference/agent/#restarting-the-service
[backend-ref]: ../../reference/backend/#restarting-the-service
[journald-syslog]: ../systemd-logs
[1]: https://etcd.io/docs/v3.4.0/op-guide/security/


text:
class WarRoom::ListParser::Transform < Parslet::Transform
  rule(total: simple(:n)) { Integer n }

  rule(name: simple(:name)) do
    WarRoom::ListParser::List::Item.new(name)
  end

  rule(name:        simple(:name),
       points:      simple(:points),
       attachments: sequence(:attachments)) do
    WarRoom::ListParser::List::Item.new(name, warbj_points: Integer(points), attachments: attachments)
  end

  rule(name: simple(:name),
       cost: simple(:cost)) do
    WarRoom::ListParser::List::Item.new(name, cost: Integer(cost))
  end

  rule(name:        simple(:name),
       cost:        simple(:cost),
       attachments: sequence(:attachments)) do
    WarRoom::ListParser::List::Item.new(name, cost: Integer(cost), attachments: attachments)
  end

  rule(name:        simple(:name),
       descriptor:  simple(:descriptor),
       cost:        simple(:cost)) do
    WarRoom::ListParser::List::Item.new(name, cost: Integer(cost), descriptor: descriptor)
  end

  rule(name:        simple(:name),
       descriptor:  simple(:descriptor),
       cost:        simple(:cost),
       attachments: sequence(:attachments)) do
    WarRoom::ListParser::List::Item.new(name, cost: Integer(cost), descriptor: descriptor, attachments: attachments)
  end

  rule(name:           simple(:name),
       tier:           simple(:tier),
       allowed_models: simple(:allowed_models),
       tiers:          sequence(:tiers)) do
    WarRoom::ListParser::List::Theme.new(name, tier: Integer(tier), allowed_models: allowed_models, tiers: tiers)
  end

  rule(tier:         simple(:tier),
       requirements: simple(:requirements),
       benefits:     simple(:benefits)) do
    WarRoom::ListParser::List::Theme::Tier.new(requirements, benefits)
  end

  rule(items: sequence(:items)) { items }

  rule(faction:          simple(:faction),
       contract_or_pact: simple(:contract_or_pact),
       title:            simple(:title),
       totals:           {points:         simple(:points),
                          max_points:     simple(:max_points),
                          point_level:    simple(:point_level),
                          warbj_points:   simple(:warbj_points),
                          warnouns:       simple(:total_warnouns),
                          warbjs:         simple(:total_warbjs),
                          battle_engines: simple(:total_battle_engines),
                          solos:          simple(:total_solos),
                          units:          simple(:total_units)},
       sections:         subtree(:sections),
       theme:            simple(:theme)) do
    warnoun        = total_warnouns > 0 ? sections.shift[0] : nil
    battle_engines = total_battle_engines > 0 ? sections.shift : []
    units          = total_units > 0 ? sections.pop : []
    # can't rely on total_solos, because sometimes a warlock attachment acts as a solo, sometimes it doesn't
    solos          = sections.length > 0 ? sections.shift : []
    WarRoom::ListParser::List.new(title:            title,
                                  faction:          faction,
                                  contract_or_pact: contract_or_pact,
                                  point_level:      Integer(point_level),
                                  points:           Integer(points),
                                  max_points:       Integer(max_points),
                                  warbj_points:     Integer(warbj_points),
                                  warnoun:          warnoun,
                                  battle_engines:   battle_engines,
                                  solos:            solos,
                                  units:            units,
                                  theme:            theme)
  end
end