text:
package org.apache.guacamole.auth.postgresql;

import com.google.inject.Binder;
import com.google.inject.Module;
import com.google.inject.name.Names;
import java.util.Properties;
import org.apache.guacamole.GuacamoleException;
import org.mybatis.guice.datasource.helper.JdbcHelper;

/**
 * Guice module which configures PostgreSQL-specific injections.
 *
 * @author James Muehlner
 * @author Michael Jumper
 */
public class PostgreSQLAuthenticationProviderModule implements Module {

    /**
     * MyBatis-specific configuration properties.
     */
    private final Properties myBatisProperties = new Properties();

    /**
     * PostgreSQL-specific driver configuration properties.
     */
    private final Properties driverProperties = new Properties();

    /**
     * Creates a new PostgreSQL authentication provider module that configures
     * driver and MyBatis properties using the given environment.
     *
     * @param environment
     *     The environment to use when configuring MyBatis and the underlying
     *     JDBC driver.
     *
     * @throws GuacamoleException
     *     If a required property is missing, or an error occurs while parsing
     *     a property.
     */
    public PostgreSQLAuthenticationProviderModule(PostgreSQLEnvironment environment)
            throws GuacamoleException {

        // Set the PostgreSQL-specific properties for MyBatis.
        myBatisProperties.setProperty("mybatis.environment.id", "guacamole");
        myBatisProperties.setProperty("JDBC.host", environment.getPostgreSQLHostname());
        myBatisProperties.setProperty("JDBC.port", String.valueOf(environment.getPostgreSQLPort()));
        myBatisProperties.setProperty("JDBC.schema", environment.getPostgreSQLDatabase());
        myBatisProperties.setProperty("JDBC.username", environment.getPostgreSQLUsername());
        myBatisProperties.setProperty("JDBC.password", environment.getPostgreSQLPassword());
        myBatisProperties.setProperty("JDBC.autoCommit", "false");
        myBatisProperties.setProperty("mybatis.pooled.pingEnabled", "true");
        myBatisProperties.setProperty("mybatis.pooled.pingQuery", "SELECT 1");

        // Use UTF-8 in database
        driverProperties.setProperty("characterEncoding","UTF-8");

    }

    @Override
    public void configure(Binder binder) {

        // Bind PostgreSQL-specific properties
        JdbcHelper.PostgreSQL.configure(binder);

        // Bind MyBatis properties
        Names.bindProperties(binder, myBatisProperties);

        // Bing JDBC driver properties
        binder.bind(Properties.class)
            .annotatedWith(Names.named("JDBC.driverProperties"))
            .toInstance(driverProperties);

    }

}


text:
Track your subreddit activity

View and order your comments and posts by subreddit.

               Popular Subreddits

               View More Popular Subreddits

               New Subreddits

               View More Newly Created Subreddits

      Sorry. Reddit currently seems to be down. Please try again later.

      <back-top></back-top>

redpajama_set_name: RedPajamaGithub


text:
<BroadcastMonitor>
  <updated>2015-08-07T09:12:49</updated>
  <stationName>Radio 6</stationName>
  <Current>
    <startTime>2015-08-07T09:09:14</startTime>
    <itemId>1000080580:1243100</itemId>
    <titleId>216137994</titleId>
    <itemCode>10458</itemCode>
    <itemReference></itemReference>
    <titleName>The Animals</titleName>
    <artistName>Emily King</artistName>
    <albumName></albumName>
    <CategoryCode>736</CategoryCode>
    <CategoryName>SOUL</CategoryName>
    <itemDuration>224</itemDuration>
    <MultiMedia1></MultiMedia1>
    <MultiMedia2></MultiMedia2>
    <MultiMedia3></MultiMedia3>
    <MultiMedia4></MultiMedia4>
  </Current>
  <Next>
    <startTime>2015-08-07T09:12:59</startTime>
    <itemId>1000080580:1244576</itemId>
    <titleId>216077447</titleId>
    <itemCode></itemCode>
    <itemReference></itemReference>
    <titleName>*** BED Mambo no 5</titleName>
    <artistName></artistName>
    <albumName></albumName>
    <CategoryCode>653</CategoryCode>
    <CategoryName>Bedjes</CategoryName>
    <itemDuration>129</itemDuration>
    <MultiMedia1></MultiMedia1>
    <MultiMedia2></MultiMedia2>
    <MultiMedia3></MultiMedia3>
    <MultiMedia4></MultiMedia4>
  </Next>
</BroadcastMonitor>


text:
<%= ob.polyT('settings.addresses.sectionName') %>

<form class="padKids padStack contentBox pad rowMd clrP border clrBr js-addAddressForm">

      <%= ob.polyT('settings.addresses.name') %>

      <% if (ob.errors.name) print(ob.formErrorTmpl({ errors: ob.errors.name })) %>
      <input type="text" class="clrBr clrSh2" name="name" id="settingsAddressName" value="<%= ob.name %>" placeholder="<%= ob.polyT('settings.addressesTab.placeholderName') %>" />

      <%= ob.polyT('settings.addresses.company') %>

      <% if (ob.errors.company) print(ob.formErrorTmpl({ errors: ob.errors.company })) %>
      <input type="text" class="clrBr clrSh2" name="company" id="settingsAddressCompany" value="<%= ob.company %>" placeholder="<%= ob.polyT('settings.optional') %>" />

      <%= ob.polyT('settings.addresses.street') %>

      <% if (ob.errors.addressLineOne) print(ob.formErrorTmpl({ errors: ob.errors.addressLineOne })) %>
      <input type="text" class="clrBr clrSh2" name="addressLineOne" id="settingsAddressLineOne" value="<%= ob.addressLineOne %>"  placeholder="<%= ob.polyT('settings.addressesTab.placeholderAddress') %>" />

      <%= ob.polyT('settings.addresses.apt') %>

      <% if (ob.errors.addressLineTwo) print(ob.formErrorTmpl({ errors: ob.errors.addressLineTwo })) %>
      <input type="text" class="clrBr clrSh2" name="addressLineTwo" id="settingsAddressLineTwo" value="<%= ob.addressLineTwo %>" placeholder="<%= ob.polyT('settings.optional') %>" />

      <%= ob.polyT('settings.addresses.city') %>

      <% if (ob.errors.city) print(ob.formErrorTmpl({ errors: ob.errors.city })) %>
      <input type="text" class="clrBr clrSh2" name="city" id="settingsAddressCity" value="<%= ob.city %>" placeholder="<%= ob.polyT('settings.addressesTab.placeholderCity') %>" />

      <%= ob.polyT('settings.addresses.state') %>

      <% if (ob.errors.state) print(ob.formErrorTmpl({ errors: ob.errors.state })) %>
      <input type="text" class="clrBr clrSh2" name="state" id="settingsAddressState" value="<%= ob.state %>" placeholder="<%= ob.polyT('settings.addressesTab.placeholderState') %>" />

      <%= ob.polyT('settings.addresses.postalCode') %>

      <% if (ob.errors.postalCode) print(ob.formErrorTmpl({ errors: ob.errors.postalCode })) %>
      <input type="text" class="clrBr clrSh2" name="postalCode" id="settingsAddressPostalCode" value="<%= ob.postalCode %>" placeholder="<%= ob.polyT('settings.addressesTab.placeholderPostalCode') %>" />

      <%= ob.polyT('settings.addresses.country') %>

      <% if (ob.errors.country) print(ob.formErrorTmpl({ errors: ob.errors.country })) %>
      <select id="settingsAddressCountry" name="country">
        <% ob.countryList.forEach((country) => { %>
        <option value="<%= country.dataName %>" <% if (country.dataName == ob.country) print('selected') %>><%= country.name %></option>
        <% }); %>
      </select>

      <%= ob.polyT('settings.addresses.notes') %>

      <% if (ob.errors.addressNotes) print(ob.formErrorTmpl({ errors: ob.errors.addressNotes })) %>
      <textarea rows="6" name="addressNotes" class="clrBr clrSh2" id="settingsAddressNotes" placeholder="<%= ob.polyT('settings.addressesTab.placeholderNotes') %>"><%= ob.addressNotes %></textarea>

</form>


text:
package org.apache.taverna.scufl2.translator.t2flow.defaultactivities;

import java.math.BigInteger;
import java.net.URI;

import org.apache.taverna.scufl2.api.configurations.Configuration;
import org.apache.taverna.scufl2.api.io.ReaderException;
import org.apache.taverna.scufl2.translator.t2flow.ParserState;
import org.apache.taverna.scufl2.translator.t2flow.T2FlowParser;

import org.apache.taverna.scufl2.xml.t2flow.jaxb.ApiConsumerConfig;
import org.apache.taverna.scufl2.xml.t2flow.jaxb.ConfigBean;

import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

public class ApiConsomerActivityParser extends AbstractActivityParser {
	private static URI activityRavenURI = T2FlowParser.ravenURI
			.resolve("net.sf.taverna.t2.activities/apiconsumer-activity/");
	private static String activityClassName = "net.sf.taverna.t2.activities.apiconsumer.ApiConsumerActivity";
	public static URI ACTIVITY_URI = URI
			.create("http://ns.taverna.org.uk/2010/activity/apiconsumer");

	@Override
	public boolean canHandlePlugin(URI activityURI) {
		String activityUriStr = activityURI.toASCIIString();
		return activityUriStr.startsWith(activityRavenURI.toASCIIString())
				&& activityUriStr.endsWith(activityClassName);
	}

	@Override
	public URI mapT2flowRavenIdToScufl2URI(URI t2flowActivity) {
		return ACTIVITY_URI;
	}

	@Override
	public Configuration parseConfiguration(T2FlowParser t2FlowParser,
			ConfigBean configBean, ParserState parserState)
			throws ReaderException {
		ApiConsumerConfig config = unmarshallConfig(t2FlowParser, configBean,
				"xstream", ApiConsumerConfig.class);

		Configuration configuration = new Configuration();
		configuration.setParent(parserState.getCurrentProfile());

		ObjectNode json = (ObjectNode) configuration.getJson();
		configuration.setType(ACTIVITY_URI.resolve("#Config"));

		json.put("apiConsumerDescription", config.getApiConsumerDescription());
		json.put("apiConsumerName", config.getApiConsumerName());
		json.put("description", config.getDescription());
		json.put("className", config.getClassName());
		json.put("methodName", config.getMethodName());

		ArrayNode parameterNames = json.arrayNode();
		json.put("parameterNames", parameterNames);
		for (String parameterName : config.getParameterNames().getString())
			parameterNames.add(parameterName);

		ArrayNode parameterDimensions = json.arrayNode();
		json.put("parameterDimensions", parameterDimensions);
		for (BigInteger parameterDimension : config.getParameterDimensions()
				.getInt())
			parameterDimensions.add(parameterDimension.intValue());

		ArrayNode parameterTypes = json.arrayNode();
		json.put("parameterTypes", parameterTypes);
		for (String parameterType : config.getParameterTypes().getString())
			parameterTypes.add(parameterType);

		json.put("returnType", config.getReturnType());
		json.put("returnDimension", config.getReturnDimension().intValue());
		json.put("isMethodConstructor", config.isIsMethodConstructor());
		json.put("isMethodStatic", config.isIsMethodStatic());

		return configuration;
	}
}


text:
"""
Contains KWS DAO implementations.
"""

from django.conf import settings
from restclients.mock_http import MockHTTP
from restclients.dao_implementation.live import get_con_pool, get_live_url
from restclients.dao_implementation.mock import get_mockdata_url

KWS_MAX_POOL_SIZE = 10

class File(object):
    """
    The File DAO implementation returns generally static content.  Use this
    DAO with this configuration:

    RESTCLIENTS_KWS_DAO_CLASS = 'restclients.dao_implementation.kws.File'
    """
    def getURL(self, url, headers):
        return get_mockdata_url('kws', 'file', url, headers)

class Live(object):
    """
    This DAO provides real data.  It requires further configuration, e.g.

    RESTCLIENTS_KWS_CERT_FILE='/path/to/an/authorized/cert.cert',
    RESTCLIENTS_KWS_KEY_FILE='/path/to/the/certs_key.key',
    RESTCLIENTS_KWS_HOST='https://ucswseval1.cac.washington.edu:443',
    """
    pool = None

    def getURL(self, url, headers):
        if Live.pool is None:
            Live.pool = get_con_pool(settings.RESTCLIENTS_KWS_HOST,
                                     settings.RESTCLIENTS_KWS_KEY_FILE,
                                     settings.RESTCLIENTS_KWS_CERT_FILE,
                                     max_pool_size=KWS_MAX_POOL_SIZE)
        return get_live_url(Live.pool, 'GET',
                            settings.RESTCLIENTS_KWS_HOST,
                            url, headers=headers,
                            service_name='kws')


text:
package infrastructure

import models.AuthorizationInfo
import sun.misc.{BASE64Decoder, BASE64Encoder}

import scala.util.Try
import scala.util.matching.Regex

trait Decryptor {
  private val regEx = new Regex("^(.*):(.*)$", "username", "token")
  protected val decoder: BASE64Decoder
  protected val encoder: BASE64Encoder

  def decodeToken(tokenEncoded: String): Try[AuthorizationInfo] = {
    val decoded = decoder.decodeBuffer(tokenEncoded)
    val decodedAsString = new String(decoded)

    Try(
      regEx findFirstMatchIn decodedAsString match {
        case Some(m) => AuthorizationInfo(m.group("username"), m.group("token"))
        case None => throw InvalidTokenException
      }
    )
  }

  def encode(username: String, token: String) = encoder.encode(s"${username}:${token}".getBytes)
}

object Decryptor extends Decryptor {
  override protected val decoder: BASE64Decoder = new sun.misc.BASE64Decoder()
  override protected val encoder: BASE64Encoder = new sun.misc.BASE64Encoder()
}

//object RSA {
//  def decodePublicKey(encodedKey: String): Option[PublicKey] = {
//    this.decodePublicKey(new Base64().decode(encodedKey))
//  }
//
//  def decodePublicKey(encodedKey: Array[Byte]): Option[PublicKey] = {
//    scala.util.control.Exception.allCatch.opt {
//      val spec = new X509EncodedKeySpec(encodedKey)
//      val factory = KeyFactory.getInstance("RSA")
//      factory.generatePublic(spec)
//    }
//  }
//
//  def encrypt(key: PublicKey, data: Array[Byte]): Array[Byte] = {
//    val cipher = Cipher.getInstance("RSA")
//    cipher.init(Cipher.ENCRYPT_MODE, key)
//    cipher.doFinal(data)
//  }
//
//  def encryptB64(key: PublicKey, data: Array[Byte]): String = {
//    (new Base64()).encodeAsString(this.encrypt(key, data))
//  }
//
//  def encryptB64(key: PublicKey, data: String): String = {
//    this.encryptB64(key, data.getBytes)
//  }
//}


text:
.PHONY: all fetch unpack patch prepare build install clean distclean

PREFIX?=/usr
DESTDIR?=
VERSION?=5.6.7
FETCH?=curl -L --retry 3

all: build

fetch: dhcpcd-$(VERSION).tar.bz2
unpack: dhcpcd-$(VERSION)/
patch: unpack
prepare: dhcpcd-$(VERSION)/

configure: prepare
	cd dhcpcd-$(VERSION)/ && ./configure --prefix=$(PREFIX)
	@touch $@

build: configure
	$(MAKE) -C dhcpcd-$(VERSION)/

install: build
	$(MAKE) -C dhcpcd-$(VERSION)/ install DESTDIR=$(DESTDIR)

clean:
	$(RM) configure
	$(RM) -r dhcpcd-$(VERSION)/

distclean: clean
	$(RM) dhcpcd-$(VERSION).tar.bz2

dhcpcd-$(VERSION).tar.bz2:
	$(FETCH) http://roy.marples.name/downloads/dhcpcd/dhcpcd-$(VERSION).tar.bz2 > $@

dhcpcd-$(VERSION)/: dhcpcd-$(VERSION).tar.bz2
	tar xjf $<

.PHONY: Version
Version:
	@echo $(VERSION) > $@


text:
<?php

namespace AppBundle\Controller;

use AppBundle\Entity\Domaine;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;use Symfony\Component\HttpFoundation\Request;

/**
 * Domaine controller.
 *
 * @Route("admin/domaine")
 */
class DomaineController extends Controller
{
    /**
     * Lists all domaine entities.
     *
     * @Route("/", name="admin_domaine_index")
     * @Method("GET")
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $domaines = $em->getRepository('AppBundle:Domaine')->findAll();

        return $this->render('domaine/index.html.twig', array(
            'domaines' => $domaines,
        ));
    }

    /**
     * Creates a new domaine entity.
     *
     * @Route("/new", name="admin_domaine_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request)
    {
        $domaine = new Domaine();
        $form = $this->createForm('AppBundle\Form\DomaineType', $domaine);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();

            // Recuperation du code
            $dernierId = $em->getRepository('AppBundle:Domaine')->getDernierId();

            $domaine->setCode($dernierId);

            $em->persist($domaine);
            $em->flush($domaine);

            return $this->redirectToRoute('admin_domaine_index');
        }

        return $this->render('domaine/new.html.twig', array(
            'domaine' => $domaine,
            'form' => $form->createView(),
        ));
    }

    /**
     * Finds and displays a domaine entity.
     *
     * @Route("/{id}", name="admin_domaine_show")
     * @Method("GET")
     */
    public function showAction(Domaine $domaine)
    {
        $deleteForm = $this->createDeleteForm($domaine);

        return $this->render('domaine/show.html.twig', array(
            'domaine' => $domaine,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing domaine entity.
     *
     * @Route("/{id}/edit", name="admin_domaine_edit")
     * @Method({"GET", "POST"})
     */
    public function editAction(Request $request, Domaine $domaine)
    {
        $deleteForm = $this->createDeleteForm($domaine);
        $editForm = $this->createForm('AppBundle\Form\DomaineType', $domaine);
        $editForm->handleRequest($request);

        if ($editForm->isSubmitted() && $editForm->isValid()) {
            $this->getDoctrine()->getManager()->flush();

            return $this->redirectToRoute('admin_domaine_index');
        }

        return $this->render('domaine/edit.html.twig', array(
            'domaine' => $domaine,
            'edit_form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Deletes a domaine entity.
     *
     * @Route("/{id}", name="admin_domaine_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, Domaine $domaine)
    {
        $form = $this->createDeleteForm($domaine);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->remove($domaine);
            $em->flush($domaine);
        }

        return $this->redirectToRoute('admin_domaine_index');
    }

    /**
     * Creates a form to delete a domaine entity.
     *
     * @param Domaine $domaine The domaine entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm(Domaine $domaine)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('admin_domaine_delete', array('id' => $domaine->getId())))
            ->setMethod('DELETE')
            ->getForm()
        ;
    }
}


text:
// ----- this file has been automatically generated - do not edit
import { DataType, Variant, VariantOptions } from "node-opcua-variant"
import { LocalizedText, QualifiedName } from "node-opcua-data-model"
import { EUInformation } from "node-opcua-data-access"
import { UInt64, UInt16, UAString } from "node-opcua-basic-types"
import { DTRange } from "node-opcua-nodeset-ua/source/dt_range"
import { DTArgument } from "node-opcua-nodeset-ua/source/dt_argument"
import { UAOrderedList, UAOrderedList_Base } from "node-opcua-nodeset-ua/source/ua_ordered_list"
import { DTFileFormat } from "./dt_file_format"
/**
 * |                |                                                  |
 * |----------------|--------------------------------------------------|
 * |namespace       |http://opcfoundation.org/UA/Glass/Flat/           |
 * |nodeClass       |ObjectType                                        |
 * |typedDefinition |13:ProductionPlanType ns=13;i=1023                |
 * |isAbstract      |false                                             |
 */
export type UAProductionPlan_Base = UAOrderedList_Base;
export interface UAProductionPlan extends Omit<UAOrderedList, "$OrderedObject$">, UAProductionPlan_Base {
}


text:
<?php

class Red_Group {
	private $items = 0;
	private $name;
	private $tracking;
	private $module_id;
	private $status;
	private $position;

	public function __construct( $values = ''  ) {
		if ( is_object( $values ) ) {
			foreach ( $values as $key => $value ) {
			 	$this->$key = $value;
			}
		}
	}

	public function get_name() {
		return $this->name;
	}

	public function get_id() {
		return $this->id;
	}

	public function is_enabled() {
		return $this->status === 'enabled' ? true : false;
	}

	static function get( $id ) {
		global $wpdb;

		$row = $wpdb->get_row( $wpdb->prepare( "SELECT {$wpdb->prefix}redirection_groups.*,COUNT( {$wpdb->prefix}redirection_items.id ) AS items,SUM( {$wpdb->prefix}redirection_items.last_count ) AS redirects FROM {$wpdb->prefix}redirection_groups LEFT JOIN {$wpdb->prefix}redirection_items ON {$wpdb->prefix}redirection_items.group_id={$wpdb->prefix}redirection_groups.id WHERE {$wpdb->prefix}redirection_groups.id=%d GROUP BY {$wpdb->prefix}redirection_groups.id", $id ) );
		if ( $row )
			return new Red_Group( $row );
		return false;
	}

	static function get_for_select() {
		global $wpdb;

		$data = array();
		$rows = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}redirection_groups" );

		if ( $rows ) {
			foreach ( $rows as $row ) {
				$module = Red_Module::get( $row->module_id );
				if ( $module ) {
					$data[ $module->get_name() ][ $row->id ] = $row->name;
				}
			}
		}

		return $data;
	}

	static function create( $name, $module_id ) {
		global $wpdb;

		$name = trim( $name );

		if ( $name !== '' && $module_id > 0 ) {
			$position = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT( * ) FROM {$wpdb->prefix}redirection_groups WHERE module_id=%d", $module_id ) );

			$data = array(
				'name'      => trim( $name ),
				'module_id' => intval( $module_id ),
				'position'  => intval( $position ),
			);

			$wpdb->insert( $wpdb->prefix.'redirection_groups', $data );

			return Red_Group::get( $wpdb->insert_id );
		}

		return false;
	}

	public function update( $data ) {
		global $wpdb;

		$old_id = $this->module_id;
		$this->name = trim( wp_kses( stripslashes( $data['name'] ), array() ) );

		if ( Red_Module::is_valid_id( intval( $data['module_id'] ) ) )
			$this->module_id = intval( $data['module_id'] );

		$wpdb->update( $wpdb->prefix.'redirection_groups', array( 'name' => $this->name, 'module_id' => $this->module_id ), array( 'id' => intval( $this->id ) ) );

		if ( $old_id !== $this->module_id ) {
			Red_Module::flush_by_module( $old_id );
			Red_Module::flush_by_module( $this->module_id );
		}
	}

	public function delete() {
		global $wpdb;

		// Delete all items in this group
		$wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->prefix}redirection_items WHERE group_id=%d", $this->id ) );

		Red_Module::flush( $this->id );

		// Delete the group
		$wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->prefix}redirection_groups WHERE id=%d", $this->id ) );

		if ( $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}redirection_groups" ) === 0 )
			$wpdb->insert( $wpdb->prefix.'redirection_groups', array( 'name' => __( 'Redirections' ), 'module_id' => 1, 'position' => 0 ) );
	}

	public function get_total_redirects() {
		global $wpdb;

		return $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->prefix}redirection_items WHERE group_id=%d", $this->id ) );
	}

	public function enable() {
		global $wpdb;

		$wpdb->update( $wpdb->prefix.'redirection_groups', array( 'status' => 'enabled' ), array( 'id' => $this->id ) );
		$wpdb->update( $wpdb->prefix.'redirection_items', array( 'status' => 'enabled' ), array( 'group_id' => $this->id ) );

		Red_Module::flush( $this->id );
	}

	public function disable() {
		global $wpdb;

		$wpdb->update( $wpdb->prefix.'redirection_groups', array( 'status' => 'disabled' ), array( 'id' => $this->id ) );
		$wpdb->update( $wpdb->prefix.'redirection_items', array( 'status' => 'disabled' ), array( 'group_id' => $this->id ) );

		Red_Module::flush( $this->id );
	}

	public function get_module_id() {
		return $this->module_id;
	}
}


text:
package net.alexanderdev.lightdrive.util.math.geom.path;

import java.awt.geom.Point2D;

import net.alexanderdev.lightdrive.util.math.geom.VectorX;
import net.alexanderdev.lightdrive.util.time.Time;

/**
 * @author Christian Bryce Alexander
 * @since May 31, 2016, 12:12:13 AM
 */
public class Path {
	private EaseAlgorithm ex, ey;

	private Point2D start, end;

	private long duration, timer;

	public Path(EaseAlgorithm ex, EaseAlgorithm ey, Point2D start, Point2D end, long duration) {
		this.ex = ex;
		this.ey = ey;

		this.start = start;
		this.end = end;

		this.duration = duration;

		timer = Time.msTime();
	}

	public void reset() {
		timer = Time.msTime();
	}

	public EaseAlgorithm getEaseX() {
		return ex;
	}

	public void setEaseX(EaseAlgorithm ex) {
		this.ex = ex;
	}

	public EaseAlgorithm getEaseY() {
		return ey;
	}

	public void setEaseY(EaseAlgorithm ey) {
		this.ey = ey;
	}

	public Point2D getStart() {
		return start;
	}

	public void setStart(Point2D start) {
		this.start = start;
	}

	public Point2D getEnd() {
		return end;
	}

	public void setEnd(Point2D end) {
		this.end = end;
	}

	public long getDuration() {
		return duration;
	}

	public void setDuration(long duration) {
		this.duration = duration;
	}

	public long getMSElapsed() {
		return Math.min(Time.msTime() - timer, duration);
	}

	public VectorX getPoint() {
		VectorX vec = new VectorX();

		long elapsed = getMSElapsed();

		vec.x = ex.getOperation().ease(elapsed, duration, start.getX(), end.getX() - start.getX());
		vec.y = ey.getOperation().ease(elapsed, duration, start.getY(), end.getY() - start.getY());

		return vec;
	}
}


text:
package com.hypefree.ingenuity.problem2;

import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;

public final class IntRangeMapTest {
	private IntRangeMap<String> map;

	@Test
	public void testGivenExample() {
		map.add(1, 5, "A");
		map.add(6, 10, "B");
		map.add(11, 20, "C");
		map.add(21, 45, "D");
		map.add(50, 70, "E");
		map.add(79, 100, "F");

		assertEquals("A", map.get(4));
		assertEquals("A", map.get(2));
		assertEquals("D", map.get(31));
		assertEquals("F", map.get(100));
		assertNull(map.get(77));
	}

	@Test(expected=IllegalArgumentException.class)
	public void testOverlappingRangesNotAllowed() {
		map.add(1, 5, "A");
		map.add(1, 5, "B");
	}

	@Before
	public void setUp() {
		map = new IntRangeMap<>();
	}
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>PythonOlogClientLibrary: pyOlog.OlogDataTypes.Attachment Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

PythonOlogClientLibrary

Main Page

Namespaces

Classes

Files

Class List

Class Index

Class Members

Public Member Functions

pyOlog.OlogDataTypes.Attachment Class Reference

List of all members.

Public Member Functions

def 	__init__

def 	getFile

Detailed Description

A Attachment, a file associated with the log entry
TODO this is not thread safe

Definition at line 126 of file OlogDataTypes.py.

Constructor & Destructor Documentation

          def pyOlog.OlogDataTypes.Attachment.__init__
          (

          self,

          file

          )

Create Attachment
>> Attachment(file=open('/home/usr/databrowser.plt')
>> Attachment(file=open('test.jpg','rb')

Definition at line 132 of file OlogDataTypes.py.

The documentation for this class was generated from the following file:

/scratch/jenkins/workspace/Olog-Publish/modules/pyOlog/pyOlog/OlogDataTypes.py

pyOlog

OlogDataTypes

Attachment

Generated by

     1.8.1.1


text:
package be.fgov.caamihziv.services.quickmon.domain.aggregation.mostrecent;

import be.fgov.caamihziv.services.quickmon.domain.aggregation.AbstractHealthAggregator;
import be.fgov.caamihziv.services.quickmon.domain.aggregation.AggregatorBuilder;
import be.fgov.caamihziv.services.quickmon.domain.healthchecks.HealthStatus;

/**
 * Created by gs on 24.04.17.
 */
public class MostRecentAggregator extends AbstractHealthAggregator {

    public MostRecentAggregator(MostRecentAggregatorBuilder builder) {
        super(builder.getWindow());
    }

    @Override
    protected HealthStatus doComputeHealth(HealthStatus status) {
        return status;
    }

    @Override
    public AggregatorBuilder toBuilder() {
        return new MostRecentAggregatorBuilder()
                .window(getWindow());
    }

}


text:
<?php
/*
 * Monsum API Wrapper
 * Licensed under the MIT License (MIT)
 */

class MonsumProduct
{
    protected $api_obj = null;
    protected $art_data = null;

    public function __construct($api_obj) {
        $this->api_obj = $api_obj;
    }

    public function loadProductFromData($arr) {
        $this->art_data = $arr;
    }

    public function loadProductByID($artid) {
        $this->art_data = null;
        $query = array("SERVICE" => "article.get",
                       "FILTER" => array("ARTICLE_NUMBER" => $artid),
                       "LIMIT" => 1);

        if($this->api_obj->api_call($query, true))
            $this->art_data = $this->api_obj->get_data()->ARTICLES[0];
    }

    public function dump() {
        if(isset($this->art_data))
            print_r($this->art_data);
    }

    public function getID() {
        return (isset($this->art_data) ? $this->art_data->ARTICLE_ID : "");
    }

    public function getNumber() {
        return (isset($this->art_data) ? $this->art_data->ARTICLE_NUMBER : "");
    }

    public function getTitle() {
        return (isset($this->art_data) ? $this->art_data->TITLE : "");
    }

    public function getDescription() {
        return (isset($this->art_data) ? $this->art_data->DESCRIPTION : "");
    }

    public function getTags() {
        return (isset($this->art_data) ? $this->art_data->TAGS : "");
    }

    public function isGross() {
        if(isset($this->art_data->IS_ADDON) && $this->art_data->IS_GROSS == 1)
            return true;
        return false;
    }

    public function getUnitPrice() {
        return (isset($this->art_data) ? $this->art_data->UNIT_PRICE : "");
    }

    public function getSetupFee() {
        return (isset($this->art_data) ? $this->art_data->SETUP_FEE : "");
    }

    public function allowMultiple() {
        if(isset($this->art_data->ALLOW_MULTIPLE) && $this->art_data->ALLOW_MULTIPLE == 1)
            return true;
        return false;
    }

    public function getCurrencyCode() {
        return (isset($this->art_data) ? $this->art_data->CURRENCY_CODE : "");
    }

    public function isDigital() {
        if(isset($this->art_data->IS_DIGITAL) && $this->art_data->IS_DIGITAL == 1)
            return true;
        return false;
    }

    public function getVATPercent() {
        return (isset($this->art_data) ? $this->art_data->VAT_PERCENT : "");
    }

    public function getSubscriptionInterval() {
        return (isset($this->art_data) ? $this->art_data->SUBSCRIPTION_INTERVAL : "");
    }

    public function getSubscriptionNumberEvents() {
        return (isset($this->art_data) ? $this->art_data->SUBSCRIPTION_NUMBER_EVENTS : "");
    }

    public function getSubscriptionTrial() {
        return (isset($this->art_data) ? $this->art_data->SUBSCRIPTION_TRIAL : "");
    }

    public function getSubscriptionDuration() {
        return (isset($this->art_data) ? $this->art_data->SUBSCRIPTION_DURATION : "");
    }

    public function getSubscriptionDurationFollow() {
        return (isset($this->art_data) ? $this->art_data->SUBSCRIPTION_DURATION_FOLLOW : "");
    }

    public function getSubscriptionCancellation() {
        return (isset($this->art_data) ? $this->art_data->SUBSCRIPTION_CANCELLATION : "");
    }

    public function isAddon() {
        if(isset($this->art_data->IS_ADDON) && $this->art_data->IS_ADDON == 1)
            return true;
        return false;
    }

    public function getAddons() {
        // return a list of Addon Objects
    }

}

?>


text:
function Export-Function {
 <#
.Synopsis
    Exports a function from a module into a user given path

.Description
    As synopsis

.PARAMETER Function
    This Parameter takes a String input and is used in Both Parameter Sets

.PARAMETER ResolvedFunction
    This should be passed the Function that you want to work with as an object making use of the following
    $ResolvedFunction = Get-Command "Command"

.PARAMETER OutPath
    This is the location that you want to output all the module files to. It is recommended not to use the same location as where the module is installed.
    Also always check the files output what you expect them to.

.PARAMETER PrivateFunction
    This is a switch that is used to correctly export Private Functions and is used internally in Export-AllModuleFunction

.EXAMPLE
    Export-Function -Function Get-TwitterTweet -OutPath C:\TextFile\

    This will export the function into the C:\TextFile\Get\Get-TwitterTweet.ps1 file and also create a basic test file C:\TextFile\Get\Get-TwitterTweet.Tests.ps1

.EXAMPLE
    Get-Command -Module SPCSPS | Where-Object {$_.CommandType -eq 'Function'}  | ForEach-Object { Export-Function -Function $_.Name -OutPath C:\TextFile\SPCSPS\ }

    This will get all the Functions in the SPCSPS module (if it is loaded into memory or in a $env:PSModulePath as required by ModuleAutoLoading) and will export all the Functions into the C:\TextFile\SPCSPS\ folder under the respective Function Verbs. It will also create a basic Tests.ps1 file just like the prior example
#>
[cmdletbinding(DefaultParameterSetName='Basic')]

Param(
    [Parameter(Mandatory=$true,ParameterSetName='Basic',ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)]
    [Parameter(Mandatory=$true,ParameterSetName='Passthru',ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)]
    [ValidateNotNullOrEmpty()]
    [ValidateNotNull()]
    [Alias('Command')]
    [Alias('Name')]
    [String]
    $Function,

    [Parameter(Mandatory=$true,ParametersetName='Passthru')]
    $ResolvedFunction,

    [Parameter(Mandatory=$true,ParameterSetName='Basic')]
    [Parameter(Mandatory=$true,ParameterSetName='Passthru')]
    [Alias('Path')]
    [String]
    $OutPath,

    [Parameter(Mandatory=$false,ParametersetName='Passthru')]
    [Alias('Private')]
    [Switch]
    $PrivateFunction

    )

$sb = New-Object -TypeName System.Text.StringBuilder

 If (!($ResolvedFunction)) { $ResolvedFunction = Get-Command $function}
 $code = $ResolvedFunction | Select-Object -ExpandProperty Definition

        If (!($PrivateFunction)) {
            $PublicOutPath = "$OutPath\Public\"
            $ps1 = "$PublicOutPath$($ResolvedFunction.Verb)\$($ResolvedFunction.Name).ps1"
        }
        ElseIf ($PrivateFunction) {
            $ps1 = "$OutPath\Private\$function.ps1"
        }

        $sb.AppendLine("function $function {") | Out-Null

        foreach ($line in $code -split '\r?\n') {
            $sb.AppendLine('{0}' -f $line) | Out-Null
        }

        $sb.AppendLine('}') | Out-Null

        New-Item $ps1 -ItemType File -Force | Out-Null
        Write-Verbose -Message "Created File $ps1"

        Set-Content -Path $ps1 -Value $($sb.ToString()) -Encoding UTF8
        Write-Verbose -Message "Added the content of function $Function into the file"

        If(!($PrivateFunction)) {
        New-FunctionPesterTest -Function $Function -ResolvedFunction $ResolvedFunction -OutPath $PublicOutPath -Verbose:$VerbosePreference
        Write-Verbose -Message "Created a Pester Test file for $Function Under the Basic ParamaterSet"
        }
        ElseIf ($PrivateFunction) {
        New-FunctionPesterTest -Function $Function -ResolvedFunction $ResolvedFunction -PrivateFunction -OutPath $OutPath -Verbose:$VerbosePreference
        Write-Verbose -Message "Created a Pester Test file for $Function Under the Passthru ParamaterSet"
        }

}


text:
using Microsoft.Extensions.Options;

namespace Lib.AspNetCore.ServerSentEvents
{
    /// <summary>
    /// The <see cref="ServerSentEventsServiceOptions{TServerSentEventsService}"/> options related extensions.
    /// </summary>
    public static class OptionsExtensions
    {
        /// <summary>
        /// Converts an instace of <see cref="ServerSentEventsServiceOptions{TServerSentEventsService}"/> to <see cref="ServerSentEventsServiceOptions{ServerSentEventsService}"/>.
        /// </summary>
        /// <typeparam name="TServerSentEventsService">The type of <see cref="ServerSentEventsService"/> for the options instance.</typeparam>
        /// <param name="options">The options instance.</param>
        /// <returns>The option instance</returns>
        public static IOptions<ServerSentEventsServiceOptions<ServerSentEventsService>> ToBaseServerSentEventsServiceOptions<TServerSentEventsService>(this IOptions<ServerSentEventsServiceOptions<TServerSentEventsService>> options) where TServerSentEventsService : ServerSentEventsService
        {
            if (options is null)
            {
                return null;
            }

            if (options.Value is null)
            {
                return Options.Create<ServerSentEventsServiceOptions<ServerSentEventsService>>(null);
            }

            return Options.Create(new ServerSentEventsServiceOptions<ServerSentEventsService>
            {
                KeepaliveInterval = options.Value.KeepaliveInterval,
                KeepaliveMode = options.Value.KeepaliveMode,
                ReconnectInterval = options.Value.ReconnectInterval,
                OnClientConnected = options.Value.OnClientConnected,
                OnClientDisconnected = options.Value.OnClientDisconnected
            });
        }
    }
}


text:
<?php
/**
 * Logger class - Custom errors
 *
 * @author David Carr - dave@daveismyname.com
 * @version 2.2
 * @date June 27, 2014
 * @date updated Sept 19, 2015
 */

namespace Nova;

use Nova\Helpers\PhpMailer as Mailer;
use Nova\Config;

/**
 * Record and email/display errors or a custom error message.
 */
class Logger
{
    /**
    * Determins if error should be emailed to SITE_EMAIL defined in app/Core/Config.php.
    *
    * @var boolean
    */
    private static $emailError = false;

    /**
    * Clear the errorlog.
    *
    * @var boolean
    */
    private static $clear = false;

    /**
    * show the error.
    *
    * @var boolean
    */
    private static $display = false;

    /**
    * Path to error file.
    *
    * @var string
    */
    public static $errorFile = '/storage/logs/error.log';

    /**
    * store errors for output.
    *
    * @var string
    */
    public static $error;

    public static function initialize()
    {
        $options = Config::get('logger');

        if($options === null) {
            return;
        }

        self::$display = $options['display_errors'];
    }

    /**
    * In the event of an error show this message.
    */
    public static function customErrorMsg()
    {
        if (self::$display) {
            echo '
'.self::$error.'
';
        } else {
            echo "
An error occured. The error has been reported.
";
            exit;
        }

    }

    /**
    * Saved the exception and calls customer error function.
    *
    * @param  \Exception $e
    */
    public static function exceptionHandler($e)
    {
        self::newMessage($e);
    }

    /**
     * Saves error message from exception.
     *
     * @param  number $number  error number
     * @param  string  $message the error
     * @param  string  $file    file originated from
     * @param  number $line    line number
     *
     * @return int
     */
    public static function errorHandler($number, $message, $file, $line)
    {
        $msg = "$message in $file on line $line";

        if (($number !== E_NOTICE) && ($number < 2048)) {
            self::errorMessage($msg);
            self::$error = $msg;
            self::customErrorMsg();
        }

        return 0;
    }

    /**
     * New exception.
     *
     * @param  \Exception $exception
     * @internal param bool $printError show error or not
     * @internal param bool $clear clear the errorlog
     * @internal param string $errorFile file to save to
     */
    public static function newMessage($exception)
    {
        $message = $exception->getMessage();
        $code = $exception->getCode();
        $file = $exception->getFile();
        $line = $exception->getLine();
        $trace = $exception->getTraceAsString();
        $trace = str_replace(DB_PASS, '********', $trace);
        $date = date('M d, Y G:iA');
        $rootpath = dirname(__DIR__);

        $logMessage = "Exception information:\n
           Date: {$date}\n
           Message: {$message}\n
           Code: {$code}\n
           File: {$file}\n
           Line: {$line}\n
           Stack trace:\n
           {$trace}\n
           ---------\n\n";

        if (is_file($rootpath.self::$errorFile) === false) {
            file_put_contents($rootpath.self::$errorFile, '');
        }

        if (self::$clear) {
            $f = fopen($rootpath.self::$errorFile, "r+");
            if ($f !== false) {
                ftruncate($f, 0);
                fclose($f);
            }
        }

        // Append
        file_put_contents($rootpath.self::$errorFile, $logMessage, FILE_APPEND);

        self::$error = $logMessage;
        self::customErrorMsg();

        //send email
        self::sendEmail($logMessage);
    }

    /**
     * Custom error.
     *
     * @param  string $error the error
     * @internal param bool $printError display error
     * @internal param string $errorFile file to save to
     */
    public static function errorMessage($error)
    {
        $date = date('Y-m-d G:iA');
        $logMessage = "$date - $error\n\n";
        $rootpath = dirname(__DIR__);

        if (is_file($rootpath.self::$errorFile) === false) {
            file_put_contents($rootpath.self::$errorFile, '');
        }

        if (self::$clear) {
            $f = fopen($rootpath.self::$errorFile, "r+");
            if ($f !== false) {
                ftruncate($f, 0);
                fclose($f);
            }

            $content = null;
        } else {
            // Append
            file_put_contents($rootpath.self::$errorFile, $logMessage, FILE_APPEND);
        }

        /** send email */
        self::sendEmail($logMessage);
    }

    /**
     * Send Email upon error.
     *
     * @param  string $message holds the error to send
     */
    public static function sendEmail($message)
    {
        if (self::$emailError == true) {
            $mail = new Mailer();

            $mail->setFrom(SITE_EMAIL);
            $mail->addAddress(SITE_EMAIL);
            $mail->subject('New error on '.SITE_TITLE);
            $mail->body($message);

            $mail->send();
        }
    }
}


text:
package io.fabric8.openclustermanagement.api.model.governancepolicypropagator.policy;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.fabric8.openclustermanagement.api.model.governancepolicypropagator.policy.v1beta1.PolicyAutomation;
import io.fabric8.openclustermanagement.api.model.governancepolicypropagator.policy.v1beta1.PolicyAutomationBuilder;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.util.Collections;
import java.util.Scanner;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;

class PolicyAutomationTest {
  private final ObjectMapper mapper = new ObjectMapper();

  @Test
  void deserializationAndSerializationShouldWorkAsExpected() throws IOException {
    // Given
    String originalJson = new Scanner(getClass().getResourceAsStream("/valid-policyautomation.json"))
      .useDelimiter("\\A")
      .next();

    // When
    final PolicyAutomation policyAutomation = mapper.readValue(originalJson, PolicyAutomation.class);
    final String serializedJson = mapper.writeValueAsString(policyAutomation);
    final PolicyAutomation paFromSerializedJson = mapper.readValue(serializedJson, PolicyAutomation.class);

    // Then
    assertNotNull(policyAutomation);
    assertNotNull(serializedJson);
    assertNotNull(paFromSerializedJson);
    assertEquals(policyAutomation.getMetadata().getName(), paFromSerializedJson.getMetadata().getName());
    assertEquals("case5-test-policy", policyAutomation.getSpec().getPolicyRef());
    assertEquals("noncompliant", policyAutomation.getSpec().getEventHook());
    assertEquals("disabled", policyAutomation.getSpec().getMode());
    assertEquals("Demo Job Template", policyAutomation.getSpec().getAutomationDef().getName());
    assertEquals("toweraccess", policyAutomation.getSpec().getAutomationDef().getSecret());
    assertEquals(3, policyAutomation.getSpec().getAutomationDef().getExtraVars().size());
  }

  @Test
  void builderShouldCreateObject() {
    // Given
    PolicyAutomationBuilder policyAutomationBuilder = new PolicyAutomationBuilder()
      .withNewMetadata()
      .withName("create-service-now-ticket")
      .endMetadata()
      .withNewSpec()
      .withEventHook("noncompliant")
      .withPolicyRef("case5-test-policy")
      .withMode("disabled")
      .withNewAutomationDef()
      .withName("Demo Job Template")
      .withSecret("toweraccess")
      .addToExtraVars("sn_severity", 1)
      .addToExtraVars("sn_priority", 1)
      .addToExtraVars("target_clusters", Collections.singletonList("cluster1"))
      .endAutomationDef()
      .endSpec();

    // When
    PolicyAutomation policyAutomation = policyAutomationBuilder.build();

    // Then
    assertNotNull(policyAutomation);
    assertEquals("create-service-now-ticket", policyAutomation.getMetadata().getName());
    assertEquals("case5-test-policy", policyAutomation.getSpec().getPolicyRef());
    assertEquals("noncompliant", policyAutomation.getSpec().getEventHook());
    assertEquals("disabled", policyAutomation.getSpec().getMode());
    assertEquals("Demo Job Template", policyAutomation.getSpec().getAutomationDef().getName());
    assertEquals("toweraccess", policyAutomation.getSpec().getAutomationDef().getSecret());
    assertEquals(3, policyAutomation.getSpec().getAutomationDef().getExtraVars().size());
  }
}


text:
from .mock import *
from ..response import Response
from time import time

class RefreshMock(Mock):
    def __init__(self, failure=False, expires_in=3600):
        Mock.__init__(self)

        self._path = '/restapi/oauth/token'
        self._failure = failure
        self._expires_in = expires_in

    def get_response(self, request):
        if not self._failure:
            return Response(200, create_body({
                'access_token': 'ACCESS_TOKEN_FROM_REFRESH',
                'token_type': 'bearer',
                'expires_in': self._expires_in,
                'refresh_token': 'REFRESH_TOKEN_FROM_REFRESH',
                'refresh_token_expires_in': 60480,
                'scope': 'SMS RCM Foo Boo',
                'expireTime': time() + self._expires_in,
                'owner_id': 'foo'
            }))

        else:
            return Response(400, create_body({'message': 'Wrong token (mock)'}))

    def test(self, request):
        body = request.get_body()
        return Mock.test(self, request) and body and 'grant_type' in body and body['grant_type'] == 'refresh_token'


text:
package com.suscipio_solutions.consecro_mud.Abilities.Spells;
import java.util.Set;
import java.util.Vector;

import com.suscipio_solutions.consecro_mud.Abilities.interfaces.Ability;
import com.suscipio_solutions.consecro_mud.Common.interfaces.CMMsg;
import com.suscipio_solutions.consecro_mud.Common.interfaces.PhyStats;
import com.suscipio_solutions.consecro_mud.MOBS.interfaces.MOB;
import com.suscipio_solutions.consecro_mud.core.CMClass;
import com.suscipio_solutions.consecro_mud.core.CMLib;
import com.suscipio_solutions.consecro_mud.core.interfaces.Environmental;
import com.suscipio_solutions.consecro_mud.core.interfaces.Physical;
import com.suscipio_solutions.consecro_mud.core.interfaces.Tickable;

@SuppressWarnings("rawtypes")
public class Spell_FlamingEnsnarement extends Spell
{
	@Override public String ID() { return "Spell_FlamingEnsnarement"; }
	private final static String localizedName = CMLib.lang().L("Flaming Ensnarement");
	@Override public String name() { return localizedName; }
	private final static String localizedStaticDisplay = CMLib.lang().L("(Ensnared in Fire)");
	@Override public String displayText() { return localizedStaticDisplay; }
	@Override public int maxRange(){return adjustedMaxInvokerRange(5);}
	@Override public int minRange(){return 1;}
	@Override public int abstractQuality(){return Ability.QUALITY_MALICIOUS;}
	@Override protected int canAffectCode(){return CAN_MOBS;}
	@Override public int classificationCode(){ return Ability.ACODE_SPELL|Ability.DOMAIN_CONJURATION;}
	@Override public long flags(){return Ability.FLAG_BINDING|Ability.FLAG_FIREBASED|Ability.FLAG_HEATING;}

	public int amountRemaining=0;
	@Override
	public boolean okMessage(final Environmental myHost, final CMMsg msg)
	{
		if(!(affected instanceof MOB))
			return true;

		final MOB mob=(MOB)affected;

		// when this spell is on a MOBs Affected list,
		// it should consistantly prevent the mob
		// from trying to do ANYTHING except sleep
		if(msg.amISource(mob))
		{
			switch(msg.sourceMinor())
			{
			case CMMsg.TYP_ENTER:
			case CMMsg.TYP_ADVANCE:
			case CMMsg.TYP_LEAVE:
			case CMMsg.TYP_FLEE:
				if(mob.location().show(mob,null,CMMsg.MSG_OK_ACTION,L("<S-NAME> struggle(s) against the flaming ensnarement.")))
				{
					amountRemaining-=mob.phyStats().level();
					if(amountRemaining<0)
						unInvoke();
				}
				return false;
			}
		}
		return super.okMessage(myHost,msg);
	}

	@Override
	public void affectPhyStats(Physical affected, PhyStats affectableStats)
	{
		super.affectPhyStats(affected,affectableStats);
		affectableStats.setDisposition((int)(affectableStats.disposition()&(PhyStats.ALLMASK-PhyStats.IS_FLYING)));
	}
	@Override
	public void unInvoke()
	{
		// undo the affects of this spell
		if(!(affected instanceof MOB))
			return;
		final MOB mob=(MOB)affected;

		super.unInvoke();
		if(canBeUninvoked())
			mob.location().show(mob,null,CMMsg.MSG_NOISYMOVEMENT,L("<S-NAME> manage(s) to break <S-HIS-HER> way free of the burning ensnarement."));
	}

	@Override
	public boolean tick(Tickable ticking, int tickID)
	{
		if((tickID==Tickable.TICKID_MOB)
		&&(affected!=null)
		&&(affected instanceof MOB))
		{
			final MOB M=(MOB)affected;
			if((!M.amDead())&&(M.location()!=null))
			{
				CMLib.combat().postDamage(invoker,M,this,CMLib.dice().roll(2,4+super.getXLEVELLevel(invoker())+(2*super.getX1Level(invoker())),0),CMMsg.TYP_FIRE,-1,"<T-NAME> get(s) singed from <T-HIS-HER> flaming ensnarement!");
				if((!M.isInCombat())&&(M!=invoker)&&(M.location()!=null)&&(M.location().isInhabitant(invoker))&&(CMLib.flags().canBeSeenBy(invoker,M)))
					CMLib.combat().postAttack(M,invoker,M.fetchWieldedItem());
			}
		}
		return super.tick(ticking,tickID);
	}

	@Override
	public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel)
	{
		final Set<MOB> h=properTargets(mob,givenTarget,auto);
		if(h==null)
		{
			mob.tell(L("There doesn't appear to be anyone here worth ensnaring."));
			return false;
		}

		// the invoke method for spells receives as
		// parameters the invoker, and the REMAINING
		// command line parameters, divided into words,
		// and added as String objects to a vector.
		if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
			return false;

		boolean success=proficiencyCheck(mob,0,auto);

		if(success)
		{
			if(mob.location().show(mob,null,this,verbalCastCode(mob,null,auto),auto?"":L("^S<S-NAME> speak(s) and wave(s) <S-HIS-HER> fingers at the ground.^?")))
				for (final Object element : h)
				{
					final MOB target=(MOB)element;

					// it worked, so build a copy of this ability,
					// and add it to the affects list of the
					// affected MOB.  Then tell everyone else
					// what happened.
					final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),null);
					if((mob.location().okMessage(mob,msg))&&(target.fetchEffect(this.ID())==null))
					{
						mob.location().send(mob,msg);
						if(msg.value()<=0)
						{
							amountRemaining=60;
							if(target.location()==mob.location())
							{
								success=maliciousAffect(mob,target,asLevel,0,-1)!=null;
								target.location().show(target,null,CMMsg.MSG_OK_ACTION,L("<S-NAME> become(s) ensnared in the flaming tendrils erupting from the ground, and is unable to move <S-HIS-HER> feet!"));
							}
						}
					}
				}
		}
		else
			return maliciousFizzle(mob,null,L("<S-NAME> speak(s) and wave(s) <S-HIS-HER> fingers, but the spell fizzles."));

		// return whether it worked
		return success;
	}
}


text:
package com.facebook.buck.rules.coercer;

import com.facebook.buck.core.cell.resolver.CellPathResolver;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.google.common.base.Preconditions;
import java.nio.file.Path;
import java.util.Optional;

public class OptionalTypeCoercer<T> implements TypeCoercer<Optional<T>> {

  private final TypeCoercer<T> coercer;

  public OptionalTypeCoercer(TypeCoercer<T> coercer) {
    Preconditions.checkArgument(
        !coercer.getOutputClass().isAssignableFrom(Optional.class),
        "Nested optional fields are ambiguous.");
    this.coercer = coercer;
  }

  @Override
  @SuppressWarnings("unchecked")
  public Class<Optional<T>> getOutputClass() {
    return (Class<Optional<T>>) (Class<?>) Optional.class;
  }

  @Override
  public boolean hasElementClass(Class<?>... types) {
    return coercer.hasElementClass(types);
  }

  @Override
  public void traverse(CellPathResolver cellRoots, Optional<T> object, Traversal traversal) {
    if (object.isPresent()) {
      coercer.traverse(cellRoots, object.get(), traversal);
    }
  }

  @Override
  public Optional<T> coerce(
      CellPathResolver cellRoots,
      ProjectFilesystem filesystem,
      Path pathRelativeToProjectRoot,
      Object object)
      throws CoerceFailedException {
    if (object == null) {
      return Optional.empty();
    }
    return Optional.of(coercer.coerce(cellRoots, filesystem, pathRelativeToProjectRoot, object));
  }
}


text:
/* $Id: preloadimages.js 7323 2007-06-01 21:05:51Z alex $ */

/**
 * Zapatec PreloadImages class.
 *
 * @constructor
 * @param {object} objArgs Object properies
 */
Zapatec.ImagePreloader = function(objArgs) {
	// Zapatec.PreloadImages object
	this.job = null;
	// Image object
	this.image = null;
	// Initialize
	if (arguments.length > 0) this.init(objArgs);
};

/**
 * Initializes object.
 *
 *

 * Takes in following object:
 * {
 *   job: [object] Zapatec.PreloadImages object,
 *   url: [string] image URL,
 *   timeout: [number, optional] number of milliseconds to wait for onload
 *    event before forcing it
 * }
 *

 *
 * @private
 * @param {object} objArgs Object properies
 */
Zapatec.ImagePreloader.prototype.init = function(objArgs) {
	// Check arguments
	if (!objArgs || !objArgs.job) {
		return;
	}
	// Attach to PreloadImages
	this.job = objArgs.job;
	// Create new Image
	this.image = new Image();
	this.job.images.push(this.image);
	var objPreloader = this;
	this.image.onload = function() {
		objPreloader.job.loadedUrls.push(objArgs.url);
		// IE needs timeout to set image dimensions correctly
		setTimeout(function() {
			objPreloader.onLoad();
		}, 0);
	};
	this.image.onerror = function() {
		objPreloader.job.invalidUrls.push(objArgs.url);
		objPreloader.onLoad();
	};
	this.image.onabort = function() {
		objPreloader.job.abortedUrls.push(objArgs.url);
		objPreloader.onLoad();
	};
	this.image.src = objArgs.url;
	if (typeof objArgs.timeout == 'number') {
		setTimeout(function() {
			if (objPreloader.job) {
				// Onload didn't fire
				if (objPreloader.image.complete) {
					objPreloader.job.loadedUrls.push(objArgs.url);
				} else {
					objPreloader.job.abortedUrls.push(objArgs.url);
				}
				objPreloader.onLoad();
			}
		}, objArgs.timeout);
	}
};

/**
 * Image onload event handler.
 * @private
 */
Zapatec.ImagePreloader.prototype.onLoad = function() {
	// May be called more than once
	if (!this.job) {
		return;
	}
	// Remove handlers to prevent further calls
	this.image.onload = null;
	this.image.onerror = null;
	this.image.onabort = null;
	// Detach from PreloadImages
	var objJob = this.job;
	this.job = null;
	// Reduce counter
	objJob.leftToLoad--;
	// If this was last image
	if (objJob.leftToLoad == 0 && typeof objJob.onLoad == 'function') {
		// We don't need onload handler any more after last image was loaded
		var funcOnLoad = objJob.onLoad;
		objJob.onLoad = null;
		// onLoad callback
		funcOnLoad(objJob);
	}
};

/**
 * @constructor
 * @param {object} objArgs Object properies
 */
Zapatec.PreloadImages = function(objArgs) {
	// Array of Image objects
	this.images = [];
	// Counter to know when all images are loaded
	this.leftToLoad = 0;
	// Array of successfully loaded URLs
	this.loadedUrls = [];
	// Array of invalid URLs
	this.invalidUrls = [];
	// Array of aborted URLs
	this.abortedUrls = [];
	// Onload event handler
	this.onLoad = null;
	// Initialize
	if (arguments.length > 0) this.init(objArgs);
};

/**
 * Initializes object.
 *
 *

 * Takes in following object:
 * {
 *   urls: [object] array of absolute or relative image URLs to preload,
 *   onLoad: [function, optional] onload event handler,
 *   timeout: [number, optional] number of milliseconds to wait for onload
 *    event before forcing it
 * }
 *
 * onLoad callback function will be called in any case, even if errors occured
 * during loading or loading process was aborted. onLoad callback function
 * receives Zapatec.Transport.PreloadImages object. Its various properies can
 * be used:
 * {
 *   images: [object] array of Image objects,
 *   loadedUrls: [object] array of successfully loaded URLs,
 *   invalidUrls: [object] array of URLs that were not loaded due to errors,
 *   abortedUrls: [object] array of URLs that were not loaded due to abort,
 *   leftToLoad: [number] how many images left to load if event was forced
 * }
 *
 * If onLoad event doesn't fire during long period of time, it can be forced
 * using "timeout" argument.
 *

 *
 * @private
 * @param {object} objArgs Object properies
 */
Zapatec.PreloadImages.prototype.init = function(objArgs) {
	// Check arguments
	if (!objArgs) {
		return;
	}
	if (!objArgs.urls || !objArgs.urls.length) {
		if (typeof objArgs.onLoad == 'function') {
			// onLoad callback
			objArgs.onLoad(this);
		}
		return;
	}
	// Run job
	this.images = [];
	this.leftToLoad = objArgs.urls.length;
	this.loadedUrls = [];
	this.invalidUrls = [];
	this.abortedUrls = [];
	this.onLoad = objArgs.onLoad;
	// Go through URLs array
	for (var iUrl = 0; iUrl < objArgs.urls.length; iUrl++) {
		// Preload URL
		new Zapatec.ImagePreloader({
			job: this,
			url: objArgs.urls[iUrl],
			timeout: objArgs.timeout
		});
	}
};


text:
`sentry tsdb`
-------------

Tools for interacting with the time series database.

Options
```````

- ``--help``: print this help page.

Subcommands
```````````

.. toctree::
 :maxdepth: 1

 query <query/index>


text:
layout: model
title: German Legal Judgement Classifier (Medium)
author: John Snow Labs
name: legclf_judgement_medium
date: 2022-11-10
tags: [de, legal, licensed, classification, judgement, german]
task: Text Classification
language: de
edition: Legal NLP 1.0.0
spark_version: 3.0
supported: true
annotator: MedicalBertForSequenceClassification
article_header:
  type: cover
use_language_switcher: "Python-Scala-Java"
---

## Description

This is a `md` version of German Legal Judgement Text Classifier written in German legal writing style "Urteilsstil" (judgement style), which will retrieve if a text is either conclusion, definition, other or subsumption .

## Predicted Entities

`conclusion`, `definition`, `subsumption`, `other`

{:.btn-box}
<button class="button button-orange" disabled>Live Demo</button>
<button class="button button-orange" disabled>Open in Colab</button>
[Download](https://s3.amazonaws.com/auxdata.johnsnowlabs.com/legal/models/legclf_judgement_medium_de_1.0.0_3.0_1668064600984.zip){:.button.button-orange.button-orange-trans.arr.button-icon}

## How to use

<div class="tabs-box" markdown="1">
{% include programmingLanguageSelectScalaPythonNLU.html %}
```python

document_assembler = nlp.DocumentAssembler() \
                .setInputCol("text") \
                .setOutputCol("document")

tokenizer = nlp.Tokenizer() \
                .setInputCols(["document"]) \
                .setOutputCol("token")

classifierdl = legal.BertForSequenceClassification.pretrained("legclf_judgement_medium","de", "legal/models")\
    .setInputCols(["document", "token"])\
    .setOutputCol("label")

bert_clf_pipeline = Pipeline(stages=[document_assembler,
                                     tokenizer,
                                     classifierdl])

text = ["Insoweit ergibt sich tatsächlich im Ergebnis ein Verzicht der Arbeitnehmer in Höhe der RoSi-Zulage ."]
empty_df = spark.createDataFrame([[""]]).toDF("text")
model = bert_clf_pipeline.fit(empty_df)
res = model.transform(spark.createDataFrame([text]).toDF("text"))

```

</div>

## Results

```bash
+----------------------------------------------------------------------------------------------------+-------------+
|text                                                                                |result       |
+----------------------------------------------------------------------------------------------------+-------------+
|Insoweit ergibt sich tatsächlich im Ergebnis ein Verzicht der Arbeitnehmer in Höhe der RoSi-Zulage .|[subsumption]|
+----------------------------------------------------------------------------------------------------+-------------+

```

{:.model-param}
## Model Information

{:.table-model}
|---|---|
|Model Name:|legclf_judgement_medium|
|Compatibility:|Legal NLP 1.0.0+|
|License:|Licensed|
|Edition:|Official|
|Input Labels:|[document, token]|
|Output Labels:|[class]|
|Language:|de|
|Size:|409.8 MB|
|Case sensitive:|true|
|Max sentence length:|128|

## References

An in-house augmented version of [this dataset](https://zenodo.org/record/3936490#.Y2ybxctBxD-)

## Benchmarking

```bash

              precision    recall  f1-score   support

  conclusion       0.74      0.79      0.76       189
  definition       0.91      0.88      0.90       160
       other       0.85      0.82      0.83       163
 subsumption       0.71      0.70      0.70       159

    accuracy                           0.80       671
   macro avg       0.80      0.80      0.80       671
weighted avg       0.80      0.80      0.80       671

```