text:
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Chapter 9. Triggers</title>
<link href="../docbook.css" rel="stylesheet" type="text/css">
<meta content="DocBook XSL-NS Stylesheets V1.74.0" name="generator">
<meta name="keywords" content="Hsqldb, HyperSQL, SQL">
<meta name="keywords" content="Hsqldb, HyperSQL, Database, JDBC, Java">
<link rel="home" href="index.html" title="HyperSQL User Guide">
<link rel="up" href="index.html" title="HyperSQL User Guide">
<link rel="prev" href="sqlroutines-chapt.html" title="Chapter 8. SQL-Invoked Routines">
<link rel="next" href="builtinfunctions-chapt.html" title="Chapter 10. Built In Functions">

 	Chapter 9. Triggers

Chapter 8. SQL-Invoked Routines 		 Chapter 10. Built In Functions

Chapter 9. Triggers

Fred Toussi

The HSQL Development Group

$Revision: 3042 $

Copyright 2010 Fred Toussi. Permission is granted to distribute
      this document without any alteration under the terms of the HSQLDB
      license. Additional permission is granted to the HSQL Development Group
      to distribute this document with or without alterations under the terms
      of the HSQLDB license.

$Date: 2009-07-14 17:55:19 +0100 (Tue, 14 Jul 2009) $

Table of Contents

Overview

Trigger Properties

Trigger Event

Granularity

Trigger Action Time

References to Rows

Trigger Condition

Trigger Action in SQL

Trigger Action in Java

Trigger Creation

Overview

Trigger functionality first appeared in SQL:1999. Triggers embody
    the live database concept, where changes in SQL data
    can be monitored and acted upon. This means each time a DELETE, UPDATE or
    INSERT is performed, additional actions are taken by the declared
    triggers. SQL Standard triggers are imperative
    while the relational aspects of SQL are
    declarative. Triggers allow performing an arbitrary
    transformation of data that is being updated or inserted, or to prevent
    insert, updated or deletes, or to perform additional operations.

Some bad examples of SQL triggers in effect enforce an “integrity
    constraint” which would better be expressed as a CHECK constraint. A
    trigger that causes an exception if the value inserted in a column is
    negative is such an example. A check constraint that declares
    CHECK VALUE >= 0 (declarative) is a better way of
    expressing an integrity constraint than a trigger that throws an exception
    if the same condition is false.

Usage constraints cannot always be expressed by SQL’s integrity
    constraint statements. Triggers can enforce these constraints. For
    example, it is may be possible to write a check constraint that prevents
    data from being added, or modified on weekends. But it is not possible to
    use a check constraint to prevent deletes. A trigger can be used to
    enforce the time when each operation is allowed.

A trigger can modify the values that are inserted into the
    database, instead of rejecting them. For example, a badly formatted string
    can be cleaned up by a trigger before INSERT.

Triggers can also perform additional data changes, for example
    inserting an additional row into a different table for data
    audits.

A trigger is declared to activate when an UPDATE, INSERT or
    DELETE action is performed on a table. These actions may be direct or
    indirect. Indirect actions may arise from CASCADE actions of FOREIGN KEY
    constraints, or from data change statements performed on a VIEW that is
    based on the table that in.

It is possible to declare multiple triggers on a single table.
    The triggers activate one by one according to the order in which they were
    defined.

A row level trigger allows access to the deleted or inserted
    rows. For UPDATE actions there is both an old and new version of each row.
    A trigger can be specified to activate before or after the action has been
    performed. Triggers that are performed after the action cannot modify the
    rows that have been modified. These triggers can perform other actions,
    such as inserting rows into other tables. Triggers that are performed
    before the action can modify the inserted or updated rows but not the
    deleted rows.

A TRIGGER that is declared on a VIEW, is an INSTEAD OF trigger.
    This term means when an INSERT, UPDATE or DELETE statement is executed,
    the trigger action is all that is performed, and no further data change
    takes place on the VIEW. The trigger action can include all the statements
    that are necessary to change the data in the tables that underlie the
    VIEW. With the use of INSTEAD OF triggers a read-only view can effectively
    become updatable or insertable-into.

Trigger Properties

A trigger is declared on a specific table or view. Various trigger
    properties determine when the trigger is executed and how.

Trigger Event

The trigger event specifies the type of SQL statement that causes
      the trigger to execute. Each trigger is specified to execute when an
      INSERT, DELETE or UPDATE takes place.

The event can be filtered by two separate means. For all triggers,
      the WHEN clause can specify a condition against the rows that are the
      subject of the trigger, together with the data in the database. For
      example, a trigger can activate when the size of a table becomes larger
      than a certain amount. Or it can activate when the values in the rows
      being modified satisfy certain conditions.

An UPDATE trigger can be declared to execute only when certain
      columns are the subject of an update statement. For example, a trigger
      declared as AFTER UPDATE OF (datecolumn) will activate only when the
      UPDATE statement that is executed includes the column, datecolumn, as
      one of the columns specified in its SET statements.

Granularity

A statement level trigger is performed once for the executed SQL
      statement and is declared as FOR EACH STATEMENT.

A row level trigger is performed once for each row that is
      modified during the execution of an SQL statement and is declared as FOR
      EACH ROW. Note that an SQL statement can INSERT, UPDATE or DELETE zero
      or more rows.

If a statement does not apply to any row, then the trigger is not
      executed.

If FOR EACH ROW or FOR EACH STATEMENT is not specified, then the
      default is FOR EACH STATEMENT.

The granularity dictates whether the REFERENCING clause can
      specify OLD ROW, NEW ROW, or OLD TABLE, NEW TABLE.

A trigger declared as FOR EACH STATEMENT can only be an AFTER
      trigger.

Trigger Action Time

A trigger is executed BEFORE, AFTER or INSTEAD OF the trigger
      event.

INSTEAD OF triggers are allowed only when the trigger is declared
      on a VIEW. With this type of trigger, the event (SQL statement) itself
      is not executed, only the trigger.

BEFORE or AFTER triggers are executed just before or just after
      the execution of the event. For example, just before a row is inserted
      into a table, the BEFORE trigger is activated, and just after the row is
      inserted, the AFTER trigger is executed.

BEFORE triggers can modify the row that is being inserted or
      updated. AFTER triggers cannot modify rows. They are usually used to
      perform additional operations, such as inserting rows into other
      tables.

A trigger declared as FOR EACH STATEMENT can only be an AFTER
      trigger.

References to Rows

If the old rows or new rows are referenced in the SQL statements
      in the trigger action, they must have names. The REFERENCING clause is
      used to give names to the old and new rows. The clause, REFERENCING OLD
      | NEW TABLE is used for statement level triggers. The clause,
      REFERENCING OLD | NEW ROW is used for row level triggers. If the old
      rows or new rows are referenced in the SQL statements in the trigger
      action, they must have names. In the SQL statements, the columns of the
      old or new rows are qualified with the specified names.

Trigger Condition

The WHEN clause can specify a condition for the columns of the row
      that is being changed. Using this clause you can simply avoid
      unnecessary trigger activation for rows that do not need it.

For UPDATE trigger, you can specify a list of columns of the
      table. If a list of columns is specified, then if the UPDATE statement
      does not change the columns with SET clauses, then the trigger is not
      activated at all.

Trigger Action in SQL

The trigger action specifies what the trigger does when it is
      activated. This is usually written as one or more SQL statements.

When a row level trigger is activated, there is an OLD ROW, or a
      NEW ROW, or both. An INSERT statement supplies a NEW ROW row to be
      inserted into a table. A DELETE statement supplied an OLD ROW be
      deleted. An UPDATE statement supplies both OLD ROW and NEW ROW that
      represent the updated rows before and after the update. The REFERENCING
      clause gives names to these rows, so that the rows can be referenced in
      the trigger action.

In the example below, a name is given to the NEW ROW and it is
      used both in the WHEN clause and in the trigger action SQL to insert a
      row into a triglog table after each row insert into the testtrig
      table.

create trigger trig after insert on testtrig
   referencing new row as newrow
   for each row when (newrow.id > 1)
   insert into triglog values (newrow.id, newrow.data, 'inserted')

In the example blow, the trigger code modifies the updated data if
      a condition is true. This type of trigger is useful when the application
      does not perform the necessary checks and modifications to data.

create trigger t before update on customer
   referencing new as newrow for each row
   begin atomic
   if length(newrow.firstname ) > 10 then
   set newrow.firstname = lower(newrow.firstname);
   end if;
   end

Trigger Action in Java

A trigger action can be written as a Java class that implements
      the org.hsqldb.Trigger interface. This interface has a single method
      which is called when the trigger is activated, either before or after
      the event. When the method is called by the engine, it supplies the name
      of the trigger (as name argument), the name of the table (as table
      argument), the OLD ROW (as row1 argument) and the NEW ROW (as row2
      argument). The row1 argument is null for row level INSERT triggers. The
      row2 argument is null for row level DELETE triggers. For table level
      triggers, both arguments are null (that is, there is no access to the
      data). The triggerType argument is one of the constants in the
      org.hsqldb.Trigger interface which indicate the type of trigger, for
      example, INSERT_BEFORE_ROW or UPDATE_AFTER_ROW.

The Java class for the trigger can be reused for several triggers
      on different tables. The method code can distinguish between the
      different tables and triggers using the supplied arguments and take
      appropriate action.

    fire (int triggerType, String name, String table, Object row1[], Object row2[])

The Java method for a synchronous trigger (see below) can modify
      the values in row2 in a BEFORE trigger. Such modifications are reflected
      in the row that is being inserted or updated. Any other modifications
      are ignored by the engine.

A Java trigger that uses an instance of
      org.hsqldb.Trigger has two forms, synchronous, or
      asynchronous (immediate or queued). By default, or when QUEUE 0 is
      specified, the action is performed immediately by calling the Java
      method. This is similar to SQL trigger actions. When QUEUE n is
      specified with n larger than 0, the engine uses a separate thread to
      execute the Java method, using a queue with the size n. For certain
      applications, such as real-time systems this allows asynchronous
      notifications to be sent by the trigger event, without introducing
      delays in the engine. With asynchronous triggers, an extra parameter,
      NOWAIT can be used in trigger definition. This overcomes the queue full
      condition. In this mode, old calls that are still in the queue are
      discarded one by one and replaced with new calls.

Java triggers can modify the row data. They should not be used to
      modify the database, e.g. insert new rows, etc.

For sample trigger classes and test code see,
      org.hsqldb.sample.TriggerSample, org.hsqldb.test.TestTriggers,
      org.hsqldb.test.TriggerClass and the associated text script
      TestTriggers.txt in /testrun/hsqldb/ directory. In the example below,
      the trigger is activated only if the update statement includes SET
      clauses that modify any of the specified columns (c1, c2, c3).
      Furthermore, the trigger is not activated if the c2 column in the
      updated row is null.

create trigger trigbur before update of c1, c2, c3 on testtrig
   referencing new row as newrow
   for each row when (newrow.c2 is not null)
   call "org.hsqldb.test.TriggerClass"

Java functions can be called from an SQL trigger. So it is
      possible to define the Java function to perform any external
      communication that are necessary for the trigger, and use SQL code for
      checks and alterations to data.

create trigger t before update on customer
   referencing new as newrow for each row
   begin atomic
   if length(newrow.firstname ) > 10 then
   call my_java_function(newrow.firstname, newrow.lastname);
   end if;
   end

Trigger Creation

CREATE TRIGGER

trigger definition

<trigger definition> ::= CREATE TRIGGER
    <trigger name> <trigger action time> <trigger event> ON
    <table name> [BEFORE <other trigger name>] [ REFERENCING
    <transition table or variable list> ] <triggered
    action>

<trigger action time> ::= BEFORE | AFTER | INSTEAD
    OF

<trigger event> ::= INSERT | DELETE | UPDATE [ OF
    <trigger column list> ]

<trigger column list> ::= <column name
    list>

<triggered action> ::= [ FOR EACH { ROW |
    STATEMENT } ] [ <triggered when clause> ] <triggered SQL
    statement>

<triggered when clause> ::= WHEN <left
    paren> <search condition> <right paren>

<triggered SQL statement> ::= <SQL procedure
    statement> | BEGIN ATOMIC { <SQL procedure statement>
    <semicolon> }... END | [QUEUE <integer literal>] [NOWAIT] CALL
    <HSQLDB trigger class FQN>

<transition table or variable list> ::=
    <transition table or variable>...

<transition table or variable> ::= OLD [ ROW ] [
    AS ] <old transition variable name> | NEW [ ROW ] [ AS ] <new
    transition variable name> | OLD TABLE [ AS ] <old transition table
    name> | NEW TABLE [ AS ] <new transition table
    name>

<old transition table name> ::= <transition
    table name>

<new transition table name> ::= <transition
    table name>

<transition table name> ::=
    <identifier>

<old transition variable name> ::= <correlation
    name>

<new transition variable name> ::= <correlation
    name>

Trigger definition is a relatively complex statement. The
    combination of <trigger action time> and
    <trigger event> determines the type of the
    trigger. Examples include BEFORE DELETE, AFTER UPDATE, INSTEAD OF INSERT.
    If the optional [ OF <trigger column list> ] is
    specified for an UPDATE trigger, then the trigger is activated only if one
    of the columns that is in the <trigger column
    list> is specified in the UPDATE statement that activates the
    trigger.

If a trigger is FOR EACH ROW, which is the
    default option, then the trigger is activated for each row of the table
    that is affected by the execution of an SQL statement. Otherwise, it is
    activated once only per statement execution. In the first case, there is a
    before and after state for each row. For UPDATE triggers, both before and
    after states exist, representing the row before the update, and after the
    update. For DELETE, triggers, there is only a before state. For INSERT
    triggers, there is only an after state. If a trigger is FOR EACH
    STATEMENT, then a transient table is created containing all the
    rows for the before state and another transient table is created for the
    after state.

The [ REFERENCING <transition table or variable>
    ] is used to give a name to the before and after data row or
    table. This name can be referenced in the <SQL procedure
    statement> to access the data.

The optional <triggered when clause> is
    a search condition, similar to the search condition of a DELETE or UPDATE
    statement. If the search condition is not TRUE for a row, then the trigger
    is not activated for that row.

The <SQL procedure statement> is limited
    to INSERT, DELETE, UPDATE and MERGE statements.

The <HSQLDB trigger class FQN> is a
    delimited identifer that contains the fully qualified name of a Java class
    that implements the org.hsqldb.Trigger
    interface.

Early releases of HyperSQL version 2.0 do not allow the use of
    OLD TABLE or NEW TABLE in statement level triggers.

TRIGGERED SQL
    STATEMENT

triggered SQL statement

The <triggered SQL statement> has three
    forms.

The first form is a single SQL procedure statement. This
    statement can reference the OLD ROW and NEW ROW variables. For example, it
    can reference these variables and insert a row into a separate
    table.

The second form is enclosed in a BEGIN ... END block and can
    include one or more SQL procedure statements. In BEFORE triggers, you can
    include SET statements to modify the inserted or updated rows. In AFTER
    triggers, you can include INSERT, DELETE and UPDATE statements to change
    the data in other database tables. SELECT and CALL statements are allowed
    in BEFORE and AFTER triggers. CALL statements in BEFORE triggers should
    not modify data.

The third form specifies a call to a Java method.

An example of a trigger with a block is given below. The block
    can include elements discussed the SQL-Invoked Routines chapter, including
    local variables, loops and conditionals. You can also raise an exception
    in such blocks in order to terminate the execution of the SQL statement
    that caused the trigger to execute.

create trigger trig after insert on testtrig
   referencing new row as newrow
   for each row when (newrow.id > 1)
   begin atomic
   insert into triglog values (newrow.id, newrow.data, 'inserted');
   /* more statements can be included */
   end

TRIGGER EXECUTION
    ORDER

trigger execution order

<trigger execution order> ::= BEFORE <other
    trigger name>

HyperSQL extends the SQL Standard to allow the order of execution
    of a trigger to be specified by using [BEFORE <other trigger name>]
    in the definition. The newly defined trigger will be executed before the
    specified other trigger. If this clause is not used, the new trigger is
    executed after all the previously defined triggers of the same scope
    (BEFORE, AFTER, EACH ROW, EACH STATEMENT).

DROP TRIGGER

drop trigger statement

<drop trigger statement> ::= DROP TRIGGER
    <trigger name>

Destroy a trigger.

$Revision: 3601 $

Chapter 8. SQL-Invoked Routines 		 Chapter 10. Built In Functions


text:
layout: post
title: "..."
date: 2007-03-07 18:54:52.000000000 +00:00
type: post
published: true
status: publish
categories: []
tags: []
meta:
  spaces_3b4c7ab08b2559d7e6deed6ee4bb7aaa_permalink: http://cid-bdfcf232da5f8179.users.api.live.net/Users(-4756660806184107655)/Blogs('BDFCF232DA5F8179!102')/Entries('BDFCF232DA5F8179!797')?authkey=hSbGhYtz7bY%24
author:
  login: fmcarvalho
  email: mcarvalho@cc.isel.ipl.pt
  display_name: fmcarvalho
  first_name: ''
  last_name: ''
---

É este o meu estado de espírito. Sinto que à minha volta não passa tudo de uma …. Uma mistura de … com "o que é que eu ando aqui a fazer?". Vejo na televisão e no cinema uma série de factos da vida retratados de forma mais ou menos sensacionalista, ou mais ou menos realista. Mas por pior ou melhor que sejam os retratos, não quero acreditar em nenhum. Quero acreditar que não reproduzem a verdade. Mas retratam.

Presentemente vi na televisão e no cinema duas formas diferentes de retratar o mesmo. Uma na novela. A forma sensacionalista. Outra no filme "The Departed". A mais natural. Não quero acreditar em nenhuma. Mas é verdade.

Basta olhar à minha volta e vejo-o em todo o lado. Conformo-me, junto-me, revolto-me ou "escapo-me"? Não sei, mas sei que não quero viver assim. Só quero viver com alegrias, com motivação, com emoção e sem preocupação. O mar continua a ser um escape excelente. Mas não é tudo. Ainda me falta algo. Algo que ainda não encontrei, nem sei onde procurar. Mas algo irá mudar!

redpajama_set_name: RedPajamaGithub


text:
FROM cleawing/debian
MAINTAINER Cleawing Dockerfile <dockerfile@cleawing.com>

RUN apt-get -qy update && apt-get -qy upgrade \
  && apt-get -qy install build-essential autoconf libncurses5 libncurses5-dev libssl-dev htop mc net-tools \
  && apt-get clean && rm -rf /var/lib/apt/lists/*


text:
SYNONYM

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

#### Published in
Bothalia 4: 425 (1942)

#### Original name
Phyllachora bottomleyae Doidge, 1942

### Remarks
null


text:
package org.dbpedia.spotlight.db.disk

import net.kotek.jdbm.DBMaker

/**
 * Base class for JDBM disk-based stores.
 *
 * @author Joachim Daiber
 */

class JDBMStore[A, B](databaseFile: String) {

  val db = DBMaker.openFile(databaseFile).enableSoftCache().make()
  var data = Option(db.getHashMap[A, B]("data")) match {
    case None => db.createHashMap[A, B]("data")
    case Some(map) => map
  }

  def add(a: A, b: B) {
    data.put(a, b)
  }

  def commit() {
    db.commit()
  }

  def get(key: A): B = data.get(key)

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace ProvisioningTests.Mocks
{
    public class MockContentType
    {
        [XmlAttribute]
        public string ID { get; set; }
        [XmlAttribute]
        public string Name { get; set; }
        [XmlAttribute]
        public bool IsDefault { get; set; }
    }
}


text:
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
using ICSharpCode.WpfDesign.Adorners;
using ICSharpCode.WpfDesign.Extensions;

using ICSharpCode.WpfDesign.Designer.Services;
using ICSharpCode.WpfDesign.Designer.Controls;

namespace ICSharpCode.WpfDesign.Designer.Extensions
{

	/// <summary>
	/// The drag handle displayed for Framework Elements
	/// </summary>
	[ExtensionServer(typeof(PrimarySelectionButOnlyWhenMultipleSelectedExtensionServer))]
	[ExtensionFor(typeof(FrameworkElement))]
	public class TopLeftContainerDragHandleMultipleItems : AdornerProvider
	{
		/// <summary/>
		public TopLeftContainerDragHandleMultipleItems()
		{ }

		protected override void OnInitialized()
		{
			base.OnInitialized();

			ContainerDragHandle rect = new ContainerDragHandle();

			rect.PreviewMouseDown += delegate(object sender, MouseButtonEventArgs e) {
				//Services.Selection.SetSelectedComponents(new DesignItem[] { this.ExtendedItem }, SelectionTypes.Auto);
				new DragMoveMouseGesture(this.ExtendedItem, false).Start(this.ExtendedItem.Services.DesignPanel,e);
				e.Handled=true;
			};

			var items = this.ExtendedItem.Services.Selection.SelectedItems;

			double minX = 0;
			double minY = 0;
			double maxX = 0;
			double maxY = 0;

			foreach (DesignItem di in items) {
				Point relativeLocation = di.View.TranslatePoint(new Point(0, 0), this.ExtendedItem.View);

				minX = minX < relativeLocation.X ? minX : relativeLocation.X;
				minY = minY < relativeLocation.Y ? minY : relativeLocation.Y;
				maxX = maxX > relativeLocation.X + ((FrameworkElement)di.View).ActualWidth ? maxX : relativeLocation.X + ((FrameworkElement)di.View).ActualWidth;
				maxY = maxY > relativeLocation.Y + ((FrameworkElement)di.View).ActualHeight ? maxY : relativeLocation.Y + ((FrameworkElement)di.View).ActualHeight;
			}

			Rectangle rect2 = new Rectangle() {
				Width = (maxX - minX) + 4,
				Height = (maxY - minY) + 4,
				Stroke = Brushes.Black,
				StrokeThickness = 2,
				StrokeDashArray = new DoubleCollection(){ 2, 2 },
			};

			RelativePlacement p = new RelativePlacement(HorizontalAlignment.Left, VerticalAlignment.Top);
			p.XOffset = minX - 3;
			p.YOffset = minY - 3;

			RelativePlacement p2 = new RelativePlacement(HorizontalAlignment.Left, VerticalAlignment.Top);
			p2.XOffset = (minX + rect2.Width) - 2;
			p2.YOffset = (minY + rect2.Height) - 2;

			AddAdorner(p, AdornerOrder.Background, rect);
			AddAdorner(p2, AdornerOrder.Background, rect2);
		}
	}
}


text:
#ifndef ROBOGEN_CARDAN_MODEL_H_
#define ROBOGEN_CARDAN_MODEL_H_

#include "../Model.h"

namespace robogen {

/**
 * A Cardan is modelled with 4 boxes and a universal joint
 */
class CardanModel: public Model {

public:

	static const float MASS_SLOT;
	static const float MASS_FRAME;
	static const float SLOT_WIDTH;
	static const float SLOT_THICKNESS;
	static const float CONNNECTION_PART_LENGTH;
	static const float CONNECTION_PART_HEIGHT;
	static const float CONNECTION_PART_OFFSET;

	static const unsigned int SLOT_A = 0;
	static const unsigned int SLOT_B = 1;

	static const unsigned int B_SLOT_A_ID = 0;
	static const unsigned int B_SLOT_B_ID = 1;
	static const unsigned int B_CONNECTION_A_ID = 2;
	static const unsigned int B_CONNECTION_B_ID = 3;

	CardanModel(dWorldID odeWorld, dSpaceID odeSpace, std::string id);

	virtual ~CardanModel();

	virtual bool initModel();

	virtual dBodyID getRoot();

	virtual dBodyID getSlot(unsigned int i);

	virtual osg::Vec3 getSlotPosition(unsigned int i);

	virtual osg::Vec3 getSlotOrientation(unsigned int i);

	virtual osg::Vec3 getSlotAxis(unsigned int i);

	dJointID getJoint();

private:

	dBodyID cardanRoot_;
	dBodyID cardanTail_;

	dJointID universalJoint_;

};

}

#endif /* ROBOGEN_CARDAN_MODEL_H_ */


text:
package com.hazelcast.internal.crdt;

import java.util.List;
import java.util.Random;

public class Operation<T, S> {

    protected final Random rnd;
    protected final int crdtIndex;

    public Operation(Random rnd) {
        this.rnd = rnd;
        this.crdtIndex = rnd.nextInt(10000);
    }

    protected T getCRDT(List<T> crdts) {
        return crdts.get(crdtIndex % crdts.size());
    }

    protected void perform(List<T> crdts, S state) {
        perform(getCRDT(crdts), state);
    }

    protected void perform(T crdt, S state) {
        // intended for override
    }
}


text:
Merb.logger.info("Loaded PRODUCTION Environment...")
Merb::Config.use { |c|
  c[:exception_details] = false
  c[:reload_classes] = false
  c[:log_level] = :error
  c[:log_file] = Merb.log_path + "/production.log"
}

Merb::Mailer.config = {:sendmail_path => '/usr/sbin/sendmail'}
Merb::Mailer.delivery_method = :sendmail


text:
package edu.harvard.we99.services.experiments;

import edu.harvard.we99.domain.Compound;
import edu.harvard.we99.domain.Experiment;
import edu.harvard.we99.domain.ExperimentStatus;
import edu.harvard.we99.domain.Plate;
import edu.harvard.we99.domain.PlateType;
import edu.harvard.we99.domain.lists.PlateResults;
import edu.harvard.we99.domain.results.PlateResult;
import edu.harvard.we99.services.BaseRESTServiceImpl;
import edu.harvard.we99.services.experiments.internal.DoseResponseResourceInternal;
import edu.harvard.we99.services.experiments.internal.ExperimentResourceInternal;
import edu.harvard.we99.services.experiments.internal.MemberResourceInternal;
import edu.harvard.we99.services.experiments.internal.PlatesResourceInternal;
import edu.harvard.we99.services.io.PlateCSVReader;
import edu.harvard.we99.services.io.PlateWithOptionalResults;
import edu.harvard.we99.services.storage.CompoundStorage;
import edu.harvard.we99.services.storage.ExperimentStorage;
import edu.harvard.we99.services.storage.ResultStorage;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Generated;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

import static edu.harvard.we99.services.experiments.PlateResultResourceImpl.compute;

/**
 * @author mford
 */
public abstract class ExperimentResourceImpl extends BaseRESTServiceImpl<Experiment>
        implements ExperimentResourceInternal {

    private static final Logger log = LoggerFactory.getLogger(ExperimentResourceImpl.class);

    private Long id;
    private final ResultStorage resultStorage;
    private final CompoundStorage compoundStorage;
    private Experiment experiment;

    public ExperimentResourceImpl(ExperimentStorage storage,
                                  ResultStorage resultStorage,
                                  CompoundStorage compoundStorage) {
        super(storage);
        this.resultStorage = resultStorage;
        this.compoundStorage = compoundStorage;
    }

    @Override
    public Experiment get() {
        if (experiment == null) {
            experiment = super.get(id);
        }
        return experiment;
    }

    @Override
    public Experiment update(Experiment experiment) {
        return super.update(id, experiment);
    }

    @Override
    public Experiment publish() {
        try {
            Experiment experiment = get();
            if (experiment.getStatus() != ExperimentStatus.UNPUBLISHED) {
                throw new WebApplicationException(Response.status(409).build());
            }
            ExperimentStorage es = (ExperimentStorage) this.storage;
            return es.publish(experiment);
        } catch(Exception e) {
            log.error("error publising experiment {}", id);
            throw new WebApplicationException(Response.serverError().build());
        }
    }

    @Override
    public Response delete() {
        deleteImpl(id);
        return Response.ok().build();
    }

    @Override
    public MemberResource getMembers() {
        MemberResourceInternal mr = createMemberResource();
        mr.setId(id);
        return mr;
    }

    @Override
    public PlatesResource getPlates() {
        Experiment experiment = get();
        PlatesResourceInternal pr = createPlatesResource();
        pr.setExperiment(experiment);
        return pr;
    }

    @Override
    public DoseResponseResource getDoseResponses() {
        Experiment experiment = get();
        DoseResponseResourceInternal dr = createDoseResponseResource();
        dr.setExperiment(experiment);
        return dr;
    }

    @Override
    public PlateResults listResults(Integer page, Integer pageSize, String typeAhead) {
        try {
            return resultStorage.listAllByExperiment(id, page, pageSize, typeAhead);
        } catch(Exception e) {
            log.error("error listing results. Page {}, pageSize {}, query {}",
                    page, pageSize, typeAhead, e);
            throw new WebApplicationException(Response.serverError().build());
        }
    }

    @Override
    public Response fullMonty(String namePrefix, PlateType plateType, InputStream csv) {
        // read the csv into a List<PlateResult>
        // assign the Plate / Experiment to the PlateResult
        // persist all to the storage

        assert plateType != null;

        String source;
        try {
            source = IOUtils.toString(csv);

            PlateCSVReader reader = new PlateCSVReader();
            List<PlateWithOptionalResults> list = reader.read(new StringReader(source));

            log.debug("Full monty will load {} plates with results", list.size());

            Set<Compound> compoundSet = new LinkedHashSet<>();
            for(PlateWithOptionalResults pwoList : list) {
                pwoList.getPlate()
                        .getWells()
                        .values()
                        .stream()
                        .forEach(
                                w -> w.getContents()
                                        .stream()
                                        .filter(d -> d.getCompound() != null)
                                        .forEach(d -> compoundSet.add(d.getCompound())));
            }

            Map<Compound, Long> compoundLongMap = compoundStorage.resolveIds(compoundSet);

            for(PlateWithOptionalResults pwoList : list) {
                pwoList.getPlate()
                        .getWells()
                        .values()
                        .stream()
                        .forEach(
                                w -> w.getContents()
                                        .stream()
                                        .filter(d -> d.getCompound() != null)
                                        .forEach(d -> d.getCompound().setId(compoundLongMap.get(d.getCompound()))));
            }

            if (namePrefix == null) {
                namePrefix = "plate ";
            }

            for(PlateWithOptionalResults pwithResult : list) {
                PlateResult results = pwithResult.getResults();
                Plate plate = pwithResult.getPlate();
                plate.setName(namePrefix + UUID.randomUUID().toString());
                plate.setPlateType(plateType);
                plate.setExperimentId(experiment.getId());
                pwithResult.getResults().setPlate(plate);
                results.setMetrics(compute(results, plate));
            }

            List<PlateResult> resultList = list
                    .stream()
                    .map(PlateWithOptionalResults::getResults)
                    .collect(Collectors.toList());
            resultStorage.fullMonty(resultList);
            return Response.ok().build();
        } catch (IOException e) {
            log.error("error parsing results csv", e);
            throw new WebApplicationException(Response.serverError().build());
        } catch (WebApplicationException e) {
            throw e;
        } catch (Exception e) {
            log.error("error inserting results csv", e);
            throw new WebApplicationException(Response.serverError().build());
        }
    }

    protected abstract PlatesResourceInternal createPlatesResource();

    protected abstract DoseResponseResourceInternal createDoseResponseResource();

    protected abstract MemberResourceInternal createMemberResource();

    @Generated(value = "generated by IDE")
    public Long getId() {
        return id;
    }

    @Generated(value = "generated by IDE")
    public void setId(Long id) {
        this.id = id;
    }

    @Generated("generated by IDE")
    public Experiment getExperiment() {
        return experiment;
    }
}


text:
class MagazineModel :
    public ItemModel
{
public:
    /// The type of projectiles which can be contained.
    RangedWeaponType projectileType;
    /// The maximum amount.
    unsigned int maxAmount;

    MagazineModel();

    virtual ~MagazineModel();

    ModelType getType() const override;

    std::string getTypeName() const override;

    bool setModel(const std::string & source) override;

    void getSheet(Table & sheet) const override;
};


text:
using namespace std;

class MovableClass
{
public:
	MovableClass()
	{
		cout << "Default constructor" << endl;
	}

	MovableClass(const MovableClass& src)
	{
		cout << "Copy constructor" << endl;
	}

	MovableClass(MovableClass&& src)
	{
		cout << "Move constructor" << endl;
	}

	MovableClass& operator=(const MovableClass& rhs)
	{
		cout << "Copy assignment operator" << endl;
		return *this;
	}

	MovableClass& operator=(MovableClass&& rhs)
	{
		cout << "Move assignment operator" << endl;
		return *this;
	}
};

int main()
{
	vector<MovableClass> vec;
	MovableClass mc;

	vec.push_back(mc);
	vec.push_back(mc);

	cout << "-----" << endl;
	vector<MovableClass> vecOne(vec.begin(), vec.end());
	cout << "-----" << endl;

	vector<MovableClass> vecTwo(make_move_iterator(vec.begin()),
															make_move_iterator(vec.end()));
	cout << "-----" << endl;

	return 0;
}


text:
package org.semispace.ws;

import org.semispace.Holder;
import org.semispace.SemiSpace;
import org.semispace.ws.WsSpaceImpl;

import junit.framework.TestCase;

public class SpaceImplTest extends TestCase {
    private WsSpaceImpl space;
    private SemiSpace semispace;

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        space = new WsSpaceImpl();
        semispace = (SemiSpace) SemiSpace.retrieveSpace();
        space.setSpace(semispace);
    }

    public void testSimpleXml() {
        String entry = "<contents>ab</contents>";
        String queryOk = "<contents>a</contents>";
        String queryNoMatch = "<contents>X</contents>";
        space.write(entry, 1000 );
        assertNull("No match - should not give any results.", space.readIfExists(queryNoMatch));
        assertEquals("Match - should find something which is equal to entry.", entry, space.readIfExists(queryOk));
        assertNotNull("Should be able to be able to remove entry", space.takeIfExists(entry));
        assertNull("Should not be able to take the element twice", space.takeIfExists(entry));
    }

    public void testTwoDifferentXmls() {
        String entry = "<contents>ab</contents>";
        String different = "<different>ab</different>";
        String query = "<contents>b</contents>";
        space.write(entry, 100000 );
        space.write(different, 100000 );

        assertEquals("Match - should find something which is equal to entry with query: "+query, entry, space.takeIfExists(query));
        assertEquals("Should NOT find something with match twice with query "+query,null,space.takeIfExists(query));

        assertNotNull("Should be able to be able to remove the other entry", space.takeIfExists(different));
    }

    public void testRetrievePropertiesFromXml() {
        String entry = "<contents>ab</contents>";
        String different = "<different>ab</different>";

        Holder propsa = space.retrievePropertiesFromXml( entry );
        Holder propsb = space.retrievePropertiesFromXml( different );
        assertEquals("contents", propsa.getClassName());
        assertEquals("different", propsb.getClassName());
        assertFalse("This test will run red when having changed space to contain different classes in different maps.",
                propsa.getSearchMap().entrySet().containsAll(propsb.getSearchMap().entrySet()));
    }

    public void testEqualityOfInterfaces() {
        JunitWsHolder holder = new JunitWsHolder();
        holder.a = "a";
        holder.b = "b";
        String entry = "<org.semispace.ws.JunitWsHolder>ab</org.semispace.ws.JunitWsHolder>";
        space.write(entry, 100000 );
        assertNotNull(semispace.readIfExists(holder));
        assertNotNull(semispace.takeIfExists(holder));
        semispace.write( holder, 10000 );
        assertNotNull(space.takeIfExists(entry));
    }
}


text:
#include "protocolfactory.h"
#include "protocolplugin.h"

QTX_BEGIN_NAMESPACE

void ProtocolFactory::registerPlugin(ProtocolPlugin *plugin)
{
    mPlugins.prepend(plugin);
}

QNetworkReply * ProtocolFactory::createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest & req, QIODevice * outgoingData /* = 0 */)
{
    foreach (ProtocolPlugin *plugin, mPlugins) {
        QNetworkReply *reply = plugin->createRequest(op, req, outgoingData);
        if (reply) { return reply; }
    }
    return 0;
}

QList<ProtocolPlugin *> ProtocolFactory::mPlugins;

QTX_END_NAMESPACE


text:
import {MithrilComponent} from "jsx/mithril-component";
import _ from "lodash";
import m from "mithril";
import {ElasticAgentProfile, ElasticAgentProfiles} from "models/elastic_profiles/types";
import {PluginInfo} from "models/shared/plugin_infos_new/plugin_info";
import {CollapsiblePanel} from "views/components/collapsible_panel";
import {FlashMessage, MessageType} from "views/components/flash_message";
import * as Icons from "views/components/icons";
import {IconGroup} from "views/components/icons";
import {KeyValuePair, KeyValueTitle} from "views/components/key_value_pair";
import {CloneOperation, DeleteOperation, EditOperation} from "views/pages/page_operations";

interface ElasticAgentProfileAddOperation {
  onAdd: (elasticAgentProfile: ElasticAgentProfile, e: MouseEvent) => void;
}

export type ElasticAgentOperations =
  EditOperation<ElasticAgentProfile>
  & DeleteOperation<string>
  & CloneOperation<ElasticAgentProfile>
  & ElasticAgentProfileAddOperation;

export interface Attrs {
  elasticProfiles: ElasticAgentProfiles;
  isUserAnAdmin: boolean;
  onShowUsages: (profileId: string, event: MouseEvent) => void;
  elasticAgentOperations: ElasticAgentOperations;
}

interface PluginInfoAttrs {
  pluginInfo?: PluginInfo;
}

export class ElasticProfilesWidget extends MithrilComponent<Attrs & PluginInfoAttrs, {}> {

  view(vnode: m.Vnode<Attrs & PluginInfoAttrs, {}>) {
    if (vnode.attrs.pluginInfo !== undefined && ElasticProfilesWidget.noElasticProfileConfigured(vnode)) {
      return <FlashMessage type={MessageType.info}
                           message="Click on 'Add' button to create new elastic agent profile."/>;
    }

    return (

          {
            _.entries(vnode.attrs.elasticProfiles.groupByPlugin()).map(([pluginId, profiles]) => {
              return profiles.map((profile: ElasticAgentProfile) =>
                                    <ElasticProfileWidget key={profile.id()} elasticProfile={profile}
                                                          pluginInfo={vnode.attrs.pluginInfo}
                                                          onEdit={vnode.attrs.elasticAgentOperations.onEdit.bind(vnode.attrs,
                                                                                profile)}
                                                          onClone={vnode.attrs.elasticAgentOperations.onClone.bind(vnode.attrs,
                                                                                profile)}
                                                          onDelete={vnode.attrs.elasticAgentOperations.onDelete.bind(
                                                            vnode.attrs,
                                                            profile.id()!)}
                                                          onShowUsage={vnode.attrs.onShowUsages.bind(vnode.attrs,
                                                                                profile.id()!)}
                                    />
              );
            })
          }

    );
  }

  private static noElasticProfileConfigured(vnode: m.Vnode<Attrs & PluginInfoAttrs, {}>) {
    return vnode.attrs.elasticProfiles == null || vnode.attrs.elasticProfiles.empty();
  }
}

export interface ProfileAttrs {
  pluginInfo?: PluginInfo;
  elasticProfile: ElasticAgentProfile;
  onEdit: (e: MouseEvent) => void;
  onClone: (e: MouseEvent) => void;
  onDelete: (e: MouseEvent) => void;
  onShowUsage: (e: MouseEvent) => void;
}

export class ElasticProfileWidget extends MithrilComponent<ProfileAttrs> {

  static profileHeader(profileId: string) {
    const title =
{profileId}
;
    return <KeyValueTitle image={null} title={title}/>;
  }

  view(vnode: m.Vnode<ProfileAttrs, {}>) {
    const elasticProfile = vnode.attrs.elasticProfile;
    const actions        = [
      <IconGroup>
        <Icons.Edit data-test-id="edit-elastic-profile" onclick={vnode.attrs.onEdit}
                    disabled={!vnode.attrs.pluginInfo}/>
        <Icons.Clone data-test-id="clone-elastic-profile" onclick={vnode.attrs.onClone}
                     disabled={!vnode.attrs.pluginInfo}/>
        <Icons.Delete data-test-id="delete-elastic-profile" onclick={vnode.attrs.onDelete}/>
        <Icons.Usage data-test-id="show-usage-elastic-profile" onclick={vnode.attrs.onShowUsage}/>
      </IconGroup>
    ];
    return (
      <CollapsiblePanel header={ElasticProfileWidget.profileHeader(elasticProfile.id()!)} actions={actions}
                        dataTestId={"elastic-profile-header"}>
        <KeyValuePair data={new Map(elasticProfile.properties() != null ? elasticProfile.properties()!.asMap() : [])}/>
      </CollapsiblePanel>
    );
  }
}


text:
package com.marublo.feelcycle.service;

import javax.annotation.Generated;
import org.seasar.extension.unit.S2TestCase;

/**
 * {@link UserFeelcycleService}のテストクラスです。
 *
 */
@Generated(value = {"S2JDBC-Gen 2.4.46", "org.seasar.extension.jdbc.gen.internal.model.ServiceTestModelFactoryImpl"}, date = "2015/09/21 17:01:14")
public class UserFeelcycleServiceTest extends S2TestCase {

    private UserFeelcycleService userFeelcycleService;

    /**
     * 事前処理をします。
     *
     * @throws Exception
     */
    @Override
    protected void setUp() throws Exception {
        super.setUp();
        include("app.dicon");
    }

    /**
     * {@link #userFeelcycleService}が利用可能であることをテストします。
     *
     * @throws Exception
     */
    public void testAvailable() throws Exception {
        assertNotNull(userFeelcycleService);
    }
}


text:
package com.linecorp.armeria.client.circuitbreaker;

import java.time.Duration;
import java.util.List;

import com.google.common.base.MoreObjects;

import com.linecorp.armeria.common.annotation.Nullable;

/**
 * Stores configurations of circuit breaker.
 */
final class CircuitBreakerConfig {

    @Nullable
    private final String name;

    private final double failureRateThreshold;

    private final long minimumRequestThreshold;

    private final Duration circuitOpenWindow;

    private final Duration trialRequestInterval;

    private final Duration counterSlidingWindow;

    private final Duration counterUpdateInterval;

    private final List<CircuitBreakerListener> listeners;

    CircuitBreakerConfig(@Nullable String name,
                         double failureRateThreshold, long minimumRequestThreshold,
                         Duration circuitOpenWindow, Duration trialRequestInterval,
                         Duration counterSlidingWindow, Duration counterUpdateInterval,
                         List<CircuitBreakerListener> listeners) {
        this.name = name;
        this.failureRateThreshold = failureRateThreshold;
        this.minimumRequestThreshold = minimumRequestThreshold;
        this.circuitOpenWindow = circuitOpenWindow;
        this.trialRequestInterval = trialRequestInterval;
        this.counterSlidingWindow = counterSlidingWindow;
        this.counterUpdateInterval = counterUpdateInterval;
        this.listeners = listeners;
    }

    @Nullable
    String name() {
        return name;
    }

    double failureRateThreshold() {
        return failureRateThreshold;
    }

    long minimumRequestThreshold() {
        return minimumRequestThreshold;
    }

    Duration circuitOpenWindow() {
        return circuitOpenWindow;
    }

    Duration trialRequestInterval() {
        return trialRequestInterval;
    }

    Duration counterSlidingWindow() {
        return counterSlidingWindow;
    }

    Duration counterUpdateInterval() {
        return counterUpdateInterval;
    }

    List<CircuitBreakerListener> listeners() {
        return listeners;
    }

    @Override
    public String toString() {
        return MoreObjects
                .toStringHelper(this)
                .add("name", name)
                .add("failureRateThreshold", failureRateThreshold)
                .add("minimumRequestThreshold", minimumRequestThreshold)
                .add("circuitOpenWindow", circuitOpenWindow)
                .add("trialRequestInterval", trialRequestInterval)
                .add("counterSlidingWindow", counterSlidingWindow)
                .add("counterUpdateInterval", counterUpdateInterval)
                .toString();
    }
}


text:
/* Author: Peter Mitrano */

#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/eigen.h>
#include <moveit/collision_detection/world.h>
#include <moveit/collision_detection/collision_matrix.h>
#include <moveit/collision_detection/collision_common.h>
#include <moveit/python/pybind_rosmsg_typecasters.h>

namespace py = pybind11;

using namespace collision_detection;

void def_collision_detection_bindings(py::module& m)
{
  m.doc() = "contains collision detection, the world, and allowed collision matrices";
  py::enum_<BodyType>(m, "BodyType")
      .value("ROBOT_ATTACHED", BodyType::ROBOT_ATTACHED)
      .value("ROBOT_LINK", BodyType::ROBOT_LINK)
      .value("WORLD_OBJECT", BodyType::WORLD_OBJECT)
      .export_values();
  py::class_<Contact>(m, "Contact")
      .def(py::init<>())
      .def_readwrite("body_name_1", &Contact::body_name_1)
      .def_readwrite("body_name_2", &Contact::body_name_2)
      .def_readwrite("body_type_1", &Contact::body_type_1)
      .def_readwrite("body_type_2", &Contact::body_type_2)
      .def_readwrite("depth", &Contact::depth)
      .def_property_readonly("nearest_points",
                             [](const Contact& contact) {
                               std::vector<Eigen::Vector3d> v{ contact.nearest_points[0], contact.nearest_points[1] };
                               return v;
                             })
      .def_readwrite("normal", &Contact::normal)
      .def_readwrite("percent_interpolation", &Contact::percent_interpolation)
      .def_readwrite("pos", &Contact::pos)
      //
      ;
  py::class_<CollisionRequest>(m, "CollisionRequest")
      .def(py::init<>())
      .def_readwrite("contacts", &CollisionRequest::contacts)
      .def_readwrite("cost", &CollisionRequest::cost)
      .def_readwrite("distance", &CollisionRequest::distance)
      .def_readwrite("group_name", &CollisionRequest::group_name)
      .def_readwrite("is_done", &CollisionRequest::is_done)
      .def_readwrite("max_contacts", &CollisionRequest::max_contacts)
      .def_readwrite("max_contacts_per_pair", &CollisionRequest::max_contacts_per_pair)
      .def_readwrite("max_cost_sources", &CollisionRequest::max_cost_sources)
      .def_readwrite("verbose", &CollisionRequest::verbose)
      //
      ;
  py::class_<CollisionResult>(m, "CollisionResult")
      .def(py::init<>())
      .def_readwrite("collision", &CollisionResult::collision)
      .def_readwrite("contact_count", &CollisionResult::contact_count)
      .def_readwrite("contacts", &CollisionResult::contacts)
      .def_readwrite("cost_sources", &CollisionResult::cost_sources)
      .def_readwrite("distance", &CollisionResult::distance)
      .def("clear", &CollisionResult::clear)
      //
      ;
  py::class_<AllowedCollisionMatrix>(m, "AllowedCollisionMatrix")
      .def(py::init<>())
      .def("setEntry",
           py::overload_cast<const std::string&, const std::string&, bool>(&AllowedCollisionMatrix::setEntry))
      //
      ;
  py::class_<World, WorldPtr>(m, "World").def(py::init<>());
}


text:
<?php
namespace gossi\trixionary\client\formatter;

interface ReferenceInterface {

	const BOOK = 'book';
	const ARTICLE = 'article';
	const INBOOK = 'inbook';
	const INCOLLECTION = 'incollection';
	const URL = 'url';
	const UNPUBLISHED = 'unpublished';
	const BACHELORTHESIS = 'bachelorthesis';
	const MASTERTHESIS = 'masterthesis';
	const DIPLOMATHESIS = 'diplomathesis';
	const PHDTHESIS = 'phdthesis';
	const HABILITATIONTHESIS = 'habilitationthesis';
	const MULTIMEDIA = 'multimedia';

	/**
	 * @return int
	 */
	public function getId();

	/**
	 * Returns the type, one of the ReferenceInterface constants
	 * @return string
	 */
	public function getType();

	/**
	 * @return string
	 */
	public function getTitle();

	/**
	 * @return string
	 */
	public function getBooktitle();

	/**
	 * @return int
	 */
	public function getYear();

	/**
	 * @return string
	 */
	public function getAuthor();

	/**
	 * @return string
	 */
	public function getPublisher();

	/**
	 * @return string
	 */
	public function getAddress();

	/**
	 * @return string
	 */
	public function getEditor();

	/**
	 * @return string
	 */
	public function getJournal();

	/**
	 * @return string
	 */
	public function getNumber();

	/**
	 * @return string
	 */
	public function getSchool();

	/**
	 * @return string
	 */
	public function getVolume();

	/**
	 * @return string
	 */
	public function getEdition();

	/**
	 * @return string
	 */
	public function getPages();

	/**
	 * @return string
	 */
	public function getHowpublished();

	/**
	 * @return string
	 */
	public function getNote();

	/**
	 * @return string
	 */
	public function getUrl();

	/**
	 * Returns lastchecked
	 * @param string $format
	 * @return string|\DateTime string when $format is passed, anyway a DateTime object
	 */
	public function getLastchecked($format = null);

}


text:
package com.github.database.rider.junit5.integration;

import com.github.database.rider.core.api.connection.ConnectionHolder;
import io.micronaut.context.ApplicationContext;
import io.micronaut.inject.qualifiers.Qualifiers;
import io.micronaut.test.extensions.junit5.MicronautJunit5Extension;
import org.junit.jupiter.api.extension.ExtensionContext;

import javax.sql.DataSource;
import java.util.Optional;

import static com.github.database.rider.core.util.ClassUtils.isOnClasspath;
import static com.github.database.rider.junit5.jdbc.ConnectionManager.getConfiguredDataSourceBeanName;
import static com.github.database.rider.junit5.jdbc.ConnectionManager.getConnectionHolder;

public class Micronaut {

    public static boolean isEnabled(ExtensionContext extensionContext) {
        return isExtensionEnabled(extensionContext) && getApplicationContext(extensionContext).isPresent();
    }

    public static ConnectionHolder getConnectionFromMicronautContext(ExtensionContext extensionContext, String executorId) {
        String configuredDataSourceBeanName = getConfiguredDataSourceBeanName(extensionContext);
        DataSource dataSource = getDataSourceFromMicronautContext(extensionContext, configuredDataSourceBeanName);
        return getConnectionHolder(executorId, dataSource);
    }

    private static boolean isExtensionEnabled(ExtensionContext extensionContext) {
        try {
            return isOnClasspath("io.micronaut.test.extensions.junit5.MicronautJunit5Extension");
        } catch (Exception e) {
            return false;
        }
    }

    private static Optional<ApplicationContext> getApplicationContext(ExtensionContext extensionContext) {
        ExtensionContext.Store micronautStore = extensionContext.getRoot().getStore(ExtensionContext.Namespace.create(MicronautJunit5Extension.class));
        if (micronautStore != null) {
            try {
                io.micronaut.context.ApplicationContext appContext = (io.micronaut.context.ApplicationContext) micronautStore.get(io.micronaut.context.ApplicationContext.class);
                if (appContext != null) {
                    return Optional.of(appContext);
                }
            } catch (ClassCastException ex) {
            }
        }
        return Optional.empty();
    }

    private static DataSource getDataSourceFromMicronautContext(ExtensionContext extensionContext, String beanName) {
        Optional<io.micronaut.context.ApplicationContext> context = getApplicationContext(extensionContext);
        if (context.isPresent()) {
            return beanName.isEmpty() ? context.get().getBean(DataSource.class) : context.get().getBean(DataSource.class, Qualifiers.byName(beanName));
        }
        throw new RuntimeException("Micronaut context is not available for test: " + extensionContext.getTestClass().get().getName());
    }

}


text:
<?php
namespace Payum\Core\Request;

use Payum\Core\Exception\LogicException;
use Payum\Core\Model\CreditCardInterface;

class ObtainCreditCard
{
    /**
     * @var CreditCardInterface
     */
    protected $creditCard;

    /**
     * @param CreditCardInterface $creditCard
     */
    public function set(CreditCardInterface $creditCard)
    {
        $this->creditCard = $creditCard;
    }

    /**
     * @return CreditCardInterface
     */
    public function obtain()
    {
        if (false == $this->creditCard) {
            throw new LogicException('Credit card could not be obtained. It has to be set before obtain.');
        }

        return $this->creditCard;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using CuttingEdge.Conditions;
using ZimmerBot.Core.TemplateParser;
using ZimmerBot.Core.Utilities;

namespace ZimmerBot.Core.Knowledge
{
  public class TemplateExpander : ITemplateExpander
  {
    static Random Randomizer = new Random();

    protected ResponseGenerationContext ResponseContext { get; set; }

    public TemplateExpander(ResponseGenerationContext context)
    {
      Condition.Requires(context, nameof(context)).IsNotNull();

      ResponseContext = context;
    }

    public string ExpandPlaceholders(string s)
    {
      string output = TextMerge.MergeTemplate(s, ResponseContext.Variables);
      return output;
    }

    public string ExpandConcept(string conceptId)
    {
      if (ResponseContext.KnowledgeBase.Concepts.TryGetValue(conceptId, out Concept concept))
      {
        List<string> words = concept.ExpandPatterns().ToList();
        return words[Randomizer.Next(words.Count)];
      }
      else
        return "UNDEFINED CONCEPT: " + conceptId;
    }

    public string Invoke(string s)
    {
      Request request = new Request(ResponseContext.Request, s);
      List<string> output = new List<string>();

      BotUtility
        .InvokeStatements(ResponseContext.InputContext.RequestContext, request, fromTemplate: true, output: output);

      return output.Aggregate((a, b) => a + "\n" + b);
    }
  }
}


text:
pytest-3.0.5
============

pytest 3.0.5 has just been released to PyPI.

This is a bug-fix release, being a drop-in replacement. To upgrade::

  pip install --upgrade pytest

The changelog is available at http://doc.pytest.org/en/latest/changelog.html.

Thanks to all who contributed to this release, among them:

* Ana Vojnovic
* Bruno Oliveira
* Daniel Hahler
* Duncan Betts
* Igor Starikov
* Ismail
* Luke Murphy
* Ned Batchelder
* Ronny Pfannschmidt
* Sebastian Ramacher
* nmundar

Happy testing,
The pytest Development Team


text:
import logging
import os
import sys

logging.basicConfig(level=logging.ERROR)

self_dir = os.path.abspath(os.path.dirname(__file__))
top_dir = os.path.abspath(
    os.path.join(self_dir, os.pardir, os.pardir, os.pardir))

sys.path.insert(0, top_dir)
sys.path.insert(0, self_dir)

import taskflow.engines

import my_flows  # noqa
import my_utils  # noqa

backend = my_utils.get_backend()
engine = taskflow.engines.load_from_factory(my_flows.flow_factory,
                                            backend=backend)
print('Running flow %s %s' % (engine.storage.flow_name,
                              engine.storage.flow_uuid))
engine.run()


text:
package com.rackspace.papi.components.logging;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.common.collect.Lists;
import com.rackspace.papi.commons.util.logging.apache.format.stock.RequestLineHandler;
import com.rackspace.papi.commons.util.logging.apache.format.stock.ResponseMessageHandler;
import com.rackspace.papi.commons.util.servlet.http.MutableHttpServletResponse;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.slf4j.MDC;

import java.util.*;

public class HttpSlf4jLoggerWrapper {
    private static final Logger logger = LoggerFactory.getLogger("repose-http-logger");

    private static final String START_TIME_ATTRIBUTE = "com.rackspace.repose.logging.start.time";
    private static final double DEFAULT_MULTIPLIER = 1000;
    private double multiplier = DEFAULT_MULTIPLIER;
    private static RequestLineHandler requestLineHandler = new RequestLineHandler();
    private static ResponseMessageHandler responseMessageHandler = new ResponseMessageHandler();

    public HttpSlf4jLoggerWrapper() {
    }

    public synchronized void handle(HttpServletRequest request, HttpServletResponse response) {
        final HashMap<String,Object> httpMDC = new HashMap<String,Object>();
        final HashMap<String,Object> requestHeaders = new HashMap<String,Object>();
        final HashMap<String,Object> responseHeaders = new HashMap<String,Object>();
        httpMDC.put("requestHeaders", requestHeaders);
        httpMDC.put("responseHeaders", responseHeaders);

        final Enumeration<String> requestHeaderNames = request.getHeaderNames();
        while (requestHeaderNames.hasMoreElements()) {
            final String nextHeaderName = requestHeaderNames.nextElement();
            final Enumeration<String> headerValues = request.getHeaders(nextHeaderName);

            String value = null;
            List<String> values = null;
            while (headerValues.hasMoreElements()) {
                if (values != null) {
                    values.add(headerValues.nextElement());
                } else if (value != null) {
                    values = Lists.newArrayList(value, headerValues.nextElement());
                } else {
                    value = headerValues.nextElement();
                }
            }
            if (value != null) {
                requestHeaders.put(nextHeaderName, values == null ? value : values);
            }
        }

        for (String headerName : response.getHeaderNames()) {
            final Collection<String> headerValues = response.getHeaders(headerName);
            if (headerValues.isEmpty()) {
                continue;
            } else if (headerValues.size() > 1) {
                responseHeaders.put(headerName, headerValues.toArray());
            } else {
                responseHeaders.put(headerName, headerValues.iterator().next());
            }
        }

        Object startTime = request.getAttribute(START_TIME_ATTRIBUTE);
        if (startTime != null) {
            httpMDC.put("requestReceived", startTime);
            httpMDC.put("processingTime", (System.currentTimeMillis() - (Long) startTime) * multiplier);
        }

        int responseStatus = response.getStatus();
        httpMDC.put("status", responseStatus);
        httpMDC.put("method", request.getMethod());
        httpMDC.put("protocol", request.getProtocol());
        httpMDC.put("requestURI", request.getRequestURI());
        httpMDC.put("requestURL", request.getRequestURL().toString());
        httpMDC.put("scheme", request.getScheme());
        httpMDC.put("serverName", request.getServerName());
        httpMDC.put("serverPort", request.getServerPort());
        httpMDC.put("localName", request.getLocalName());
        httpMDC.put("localPort", request.getLocalPort());
        httpMDC.put("remoteHost", request.getRemoteHost());
        httpMDC.put("remotePort", request.getRemotePort());

        httpMDC.put("requestContentLength", request.getContentLength());

        long responseContentLength = MutableHttpServletResponse.wrap(request, response).getResponseSize();
        httpMDC.put("responseContentLength", responseContentLength);

        String contextPath = request.getContextPath();
        if (contextPath != null && !contextPath.isEmpty()) {
            httpMDC.put("contextPath", contextPath);
        }
        String servletPath = request.getServletPath();
        if (servletPath != null && !servletPath.isEmpty()) {
            httpMDC.put("servletPath", servletPath);
        }
        Map<String, String[]> parameterMap = request.getParameterMap();
        if (parameterMap != null && !parameterMap.isEmpty()) {
            httpMDC.put("parameterMap", parameterMap);
        }
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length != 0) {
            httpMDC.put("cookies", cookies);
        }
        String pathInfo = request.getPathInfo();
        if (pathInfo != null && !pathInfo.isEmpty()) {
            httpMDC.put("pathInfo", pathInfo);
        }
        String pathTranslated = request.getPathTranslated();
        if (pathTranslated != null && !pathTranslated.isEmpty()) {
            httpMDC.put("pathTranslated", pathTranslated);
        }
        String queryString = request.getQueryString();
        if (queryString != null && !queryString.isEmpty()) {
            httpMDC.put("queryString", queryString);
        }

        MDC.setContextMap(httpMDC);
        try {
            String message = requestLineHandler.handle(request, response);
            if (responseStatus >= 400) {
                MDC.put("errorMessage", responseMessageHandler.handle(request, response));
                if (responseStatus >= 500) {
                    logger.error(message);
                } else {
                    logger.warn(message);
                }
            } else {
                logger.info(message);
            }
        } finally {
            MDC.clear();
        }
    }
}


text:
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="/extension_control_browser_proxy.html">

<dom-module id="extension-controlled-indicator">
  <template>

    <template is="dom-if" if="[[extensionCanBeDisabled]]">
      <paper-button class="secondary-button" on-tap="onDisableTap_">
        $i18n{disable}
      </paper-button>
    </template>
  </template>
</dom-module>


text:
using System;
using System.IO;
using System.Linq;
using Android.Content;
using Android.Telephony;
using Calculators.Droid;
using Xamarin.Forms;

[assembly: Dependency(typeof(Dialer_Droid))]
namespace Calculators.Droid
{
	public class Dialer_Droid : IDialer
	{
		public bool Dial(string number)
		{
			var context = Forms.Context;
			if (context == null)
				return false;

			var intent = new Intent(Intent.ActionCall);
			intent.SetData(Android.Net.Uri.Parse("tel:" + number));

			if (IsIntentAvailable(context, intent))
			{
				context.StartActivity(intent);
				return true;
			}

			return false;
		}

		public static bool IsIntentAvailable(Context context, Intent intent)
		{

			var packageManager = context.PackageManager;

			var list = packageManager.QueryIntentServices(intent, 0)
				.Union(packageManager.QueryIntentActivities(intent, 0));
			if (list.Any())
				return true;

			TelephonyManager mgr = TelephonyManager.FromContext(context);
			return mgr.PhoneType != PhoneType.None;
		}
	}
}


text:
namespace arangodb {
namespace application_features {

class ClusterFeaturePhase : public ApplicationFeaturePhase {
 public:
  explicit ClusterFeaturePhase(ApplicationServer& server);
};

}  // namespace application_features
}  // namespace arangodb


text:
package example.repo;

import example.model.Customer411;

import java.util.List;

import org.springframework.data.repository.CrudRepository;

public interface Customer411Repository extends CrudRepository<Customer411, Long> {

	List<Customer411> findByLastName(String lastName);
}


text:
import numpy
import pickle
readcmnt = open('../used/test/cmnt_inside.txt','r')
readtran = open('../used/test/cmnt_outside.txt','r');

def preprocess(line):
    lline = list(line.decode("utf-8"));
    lline = [x for x in lline if x != u' ']
    del lline[-1]
    return lline
def static(dictionary,lline):
    for i in xrange(len(lline) - 1):
        if lline[i] in dictionary:
            if lline[i + 1] in dictionary[lline[i]]:
                dictionary[lline[i]][lline[i + 1]] += 1
            else:
                dictionary[lline[i]][lline[i + 1]] = 1;
        else:
            dictionary[lline[i]] = {}
            dictionary[lline[i]][lline[i + 1]] = 1;
    return dictionary,len(lline)

def fileStatic(fileHandle,count):
    statDict = {}
    number = 0;
    i = 0;
    while i < count:
        line = fileHandle.readline();
        if not line:
            print "touch the end of file"
            break
        statDict,temp = static(statDict,preprocess(line))
        number += temp
        i += 1
    print "total number is : ",number
    return statDict

def extractDict(dict1,dict2):
    common = [];
    dict_x = []
    dict_y = []
    for x in dict1:
        for y in dict1[x]:
            if x in dict2 and y in dict2[x]:
                if x not in dict_x:
                    dict_x.append(x)
                if y not in dict_y:
                    dict_y.append(y)
                common.append([x,y])
    matrix1 = numpy.zeros((len(dict_x),len(dict_y)));
    matrix2 = numpy.zeros((len(dict_x),len(dict_y)));
    for i,x in enumerate(dict_x):
        for j,y in enumerate(dict_y):
            if x in dict1 and y in dict1[x]:
                matrix1[i,j] = dict1[x][y];
            if x in dict1 and y in dict2[x]:
                matrix2[i,j] = dict2[x][y];
    return matrix1,matrix2

def similarityMatrix(matrix1,matrix2):
    similar = numpy.zeros(matrix1.shape[0])
    for i in xrange(matrix1.shape[0]):
        temp = numpy.zeros(1);
        temp1 = numpy.zeros(1);
        temp2 = numpy.zeros(1);
        for j in xrange(matrix1.shape[1]):
            temp += matrix1[i,j] * matrix2[i,j];
            temp1 += matrix1[i,j] ** 2;
            temp2 += matrix2[i,j] ** 2;
        similar[i] = temp / (numpy.sqrt(temp1) * numpy.sqrt(temp2));
    return similar

def main(count):
    cmnt_dict = fileStatic(readcmnt,count);
    tran_dict = fileStatic(readtran,count);
    matrix1,matrix2 = extractDict(cmnt_dict,tran_dict);
#    writeMatrix = open('matrix.pkl','w');
#    pickle.dump(matrix1,writeMatrix);
#    pickle.dump(matrix2,writeMatrix);
#    writeMatrix.close();
#    readMatrix = open('matrix.pkl','r');
#    matrix1 = pickle.load(readMatrix)
#    matrix2 = pickle.load(readMatrix);
    similar = similarityMatrix(matrix1,matrix2);
    print sum(matrix1)
    print sum(matrix2)
    print float(sum(similar >= 0.8)) / float(len(similar))
    print float(sum(similar >= 0.5)) / float(len(similar))

if __name__ == '__main__':
    main(1000000);


text:
package com.wordnik.jaxrs;

import io.swagger.annotations.ApiParam;

import javax.validation.constraints.Min;
import javax.ws.rs.*;
import java.util.List;

/**
 * @author chekong on 15/5/9.
 */
public class MyBean extends MyParentBean {

    @ApiParam(value = "ID of pet that needs to be updated", required = true)
    @PathParam("petId")
    private String petId;

    @ApiParam(value = "Updated name of the pet", required = false, defaultValue = "defaultValue")
    @FormParam("name")
    private String name;

    @ApiParam(value = "Updated status of the pet", required = false, allowableValues = "value1, value2")
    @FormParam("status")
    private String status;

    @HeaderParam("myHeader")
    private String myHeader;

    @HeaderParam("intValue")
    private int intValue;

    @QueryParam(value = "listValue")
    private List<String> listValue;

    @ApiParam(value = "testIntegerAllowableValues", defaultValue = "25", allowableValues = "25, 50, 100")
    @QueryParam("testIntegerAllowableValues")
    @DefaultValue("25")
    public Integer testIntegerAllowableValues;

    public String getMyheader() {
        return myHeader;
    }

    public void setmyHeader(String myHeader) {
        this.myHeader = myHeader;
    }

    public String getPetId() {
        return petId;
    }

    public void setPetId(String petId) {
        this.petId = petId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public int getIntValue() {
        return intValue;
    }

    public void setIntValue(int intValue) {
        this.intValue = intValue;
    }

    public List<String> getListValue() {
        return listValue;
    }

    public void setListValue(List<String> listValue) {
        this.listValue = listValue;
    }

}


text:
package org.jboss.weld.atinject.tck;

import org.jboss.weld.bootstrap.spi.BeanDiscoveryMode;
import org.jboss.weld.bootstrap.spi.BeansXml;
import org.jboss.weld.bootstrap.spi.Metadata;
import org.jboss.weld.bootstrap.spi.Scanning;

import java.net.URL;
import java.util.Collections;
import java.util.List;

public class AllDiscoveryBeansXml implements BeansXml {
    public static final AllDiscoveryBeansXml INSTANCE = new AllDiscoveryBeansXml();

    @Override
    public List<Metadata<String>> getEnabledAlternativeStereotypes() {
        return Collections.emptyList();
    }

    @Override
    public List<Metadata<String>> getEnabledAlternativeClasses() {
        return Collections.emptyList();
    }

    @Override
    public List<Metadata<String>> getEnabledDecorators() {
        return Collections.emptyList();
    }

    @Override
    public List<Metadata<String>> getEnabledInterceptors() {
        return Collections.emptyList();
    }

    @Override
    public Scanning getScanning() {
        return Scanning.EMPTY_SCANNING;
    }

    @Override
    public URL getUrl() {
        return null;
    }

    @Override
    public BeanDiscoveryMode getBeanDiscoveryMode() {
        return BeanDiscoveryMode.ALL;
    }

    @Override
    public String getVersion() {
        return null;
    }

    @Override
    public boolean isTrimmed() {
        return false;
    }
}


text:
<?php

class Google_Service_Dfareporting_DfareportingFile extends Google_Model
{
  protected $dateRangeType = 'Google_Service_Dfareporting_DateRange';
  protected $dateRangeDataType = '';
  public $etag;
  public $fileName;
  public $format;
  public $id;
  public $kind;
  public $lastModifiedTime;
  public $reportId;
  public $status;
  protected $urlsType = 'Google_Service_Dfareporting_DfareportingFileUrls';
  protected $urlsDataType = '';

  /**
   * @param Google_Service_Dfareporting_DateRange
   */
  public function setDateRange(Google_Service_Dfareporting_DateRange $dateRange)
  {
    $this->dateRange = $dateRange;
  }
  /**
   * @return Google_Service_Dfareporting_DateRange
   */
  public function getDateRange()
  {
    return $this->dateRange;
  }
  public function setEtag($etag)
  {
    $this->etag = $etag;
  }
  public function getEtag()
  {
    return $this->etag;
  }
  public function setFileName($fileName)
  {
    $this->fileName = $fileName;
  }
  public function getFileName()
  {
    return $this->fileName;
  }
  public function setFormat($format)
  {
    $this->format = $format;
  }
  public function getFormat()
  {
    return $this->format;
  }
  public function setId($id)
  {
    $this->id = $id;
  }
  public function getId()
  {
    return $this->id;
  }
  public function setKind($kind)
  {
    $this->kind = $kind;
  }
  public function getKind()
  {
    return $this->kind;
  }
  public function setLastModifiedTime($lastModifiedTime)
  {
    $this->lastModifiedTime = $lastModifiedTime;
  }
  public function getLastModifiedTime()
  {
    return $this->lastModifiedTime;
  }
  public function setReportId($reportId)
  {
    $this->reportId = $reportId;
  }
  public function getReportId()
  {
    return $this->reportId;
  }
  public function setStatus($status)
  {
    $this->status = $status;
  }
  public function getStatus()
  {
    return $this->status;
  }
  /**
   * @param Google_Service_Dfareporting_DfareportingFileUrls
   */
  public function setUrls(Google_Service_Dfareporting_DfareportingFileUrls $urls)
  {
    $this->urls = $urls;
  }
  /**
   * @return Google_Service_Dfareporting_DfareportingFileUrls
   */
  public function getUrls()
  {
    return $this->urls;
  }
}


text:
var miniGUI = { REVISION: '0.1' };

miniGUI.Slide = function(obj){
    this.container = obj.container;
    this.zone = null;
    this.bg = null;
    this.col = null;
    this.pin = null;
    this.txt = null;
    this.name = obj.name || "slider";
    this.color = obj.color || [55,123,167];
    this.id =  obj.id || 0;
    this.x = obj.x || 0;
    this.y = obj.y || 0;
    this.isMove = false;
    this.value = obj.value || 0;
    this.onChange = obj.onChange;

    this.init();
}

miniGUI.Slide.prototype = {
    constructor: miniGUI.Slide,
    init:function(){
        var _this = this;
        this.zone = document.createElement('div');
        this.zone.style.cssText = "position:absolute; left:"+this.x+"px; top:"+this.y+"px; width:120px; height:30px; cursor:pointer;";
        this.zone.id="name";
        this.container.appendChild(this.zone);

        this.bg = document.createElement('div');
        this.bg.style.cssText = "position:absolute; left:10px; top:18px; width:100px; height:4px; pointer-events:none; background-color:rgba(0,0,0,0.1);";
        this.zone.appendChild(this.bg);

        this.col = document.createElement('div');
        this.col.style.cssText = "position:absolute; left:10px; top:18px; width:"+this.value*100+"px; height:4px; pointer-events:none; ";
        this.col.style.backgroundColor = 'rgba('+this.color[0]+','+this.color[1]+','+this.color[2]+',0.5)';
        this.zone.appendChild(this.col);

        this.pin = document.createElement('div');
        this.pin.style.cssText = "position:absolute; left:"+((this.value*100)+10)+"px; top:15px; width:2px; margin-left:-1px; height:10px; pointer-events:none; background-color:#eeeeee;";
        this.zone.appendChild(this.pin);

        this.txt = document.createElement('div');
        this.txt.style.cssText = "position:absolute; left:10px; top:0px; width:120px; height:10px; pointer-events:none; font-size:11px;";
        this.zone.appendChild(this.txt);
        this.txt.textContent = this.name+ ":"+ this.value;

        this.zone.addEventListener('mouseover', function ( e ) { e.preventDefault(); _this.over(e); }, false);
        this.zone.addEventListener('mouseout' , function ( e ) { e.preventDefault(); _this.out(e);  }, false);
        this.zone.addEventListener('mousemove', function ( e ) { e.preventDefault(); _this.move(e); }, false);
        this.zone.addEventListener('mousedown', function ( e ) { e.preventDefault(); _this.isMove = true; _this.move(e); }, false);
        this.zone.addEventListener('mouseup'  , function ( e ) { e.preventDefault(); _this.isMove = false;}, false);
    },
    set:function(v){
        this.value = Math.round(v*100)/100;//v.toFixed(2);
        if(this.value<0)this.value=0;
        if(this.value>1)this.value=1;
        this.col.style.width = this.value*100+"px";
        this.pin.style.left = 10+this.value*100+"px";
        this.txt.textContent = this.name + ":"+ this.value;
    },
    over:function(e, t){
        this.bg.style.backgroundColor = 'rgba(0,0,0,0.5)';
        this.col.style.backgroundColor = 'rgba('+this.color[0]+','+this.color[1]+','+this.color[2]+',1)';
    },
    out:function(e, t){
        this.isMove = false;
        this.bg.style.backgroundColor = 'rgba(0,0,0,0.1)';
        this.col.style.backgroundColor = 'rgba('+this.color[0]+','+this.color[1]+','+this.color[2]+',0.5)';
    },
    move:function(e){
        if(this.isMove){
            this.set((e.clientX-10)/100)
            this.onChange(this.value);
        }
    }
}

miniGUI.OnOff = function(obj){
    this.container = obj.container;
    this.zonen = null;
    this.bg = null;
    this.col = null;
    this.pin = null;
    this.txt = null;
    this.name = obj.name || "onOff";
    this.x = obj.x || 0;
    this.y = obj.y || 0;
    this.value = obj.value || false;
    this.onChange = obj.onChange;

    this.init();
}

miniGUI.OnOff.prototype = {
    constructor: miniGUI.OnOff,
    init:function(){
        var _this = this;
        var tx = "off";
        var p = 0;
        if(this.value){tx = "on"; p = 30;}
        this.zonen = document.createElement('div');
        this.zonen.style.cssText = "position:absolute; left:"+this.x+"px; top:"+this.y+"px; width:120px; height:30px; cursor:pointer;";
        this.container.appendChild(this.zonen);

        this.bg = document.createElement('div');
        this.bg.style.cssText = "position:absolute; left:80px; top:18px; width:30px; height:4px; pointer-events:none; background-color:rgba(0,0,0,0.1);";
        this.zonen.appendChild(this.bg);

        this.col = document.createElement('div');
        this.col.style.cssText = "position:absolute; left:80px; top:18px; width:"+p+"px; height:4px; pointer-events:none; background-color:rgba(55,123,167,0.5);";
        this.zonen.appendChild(this.col);

        this.pin = document.createElement('div');
        this.pin.style.cssText = "position:absolute; left:"+(80+p)+"px; top:15px; width:2px; margin-left:-1px; height:10px; pointer-events:none; background-color:#eeeeee;";
        this.zonen.appendChild(this.pin);

        this.txt = document.createElement('div');
        this.txt.style.cssText = "position:absolute; left:10px; top:0px; width:120px; height:10px; pointer-events:none; font-size:11px;";
        this.zonen.appendChild(this.txt);

        this.txt.textContent = this.name+ " "+ tx;

        this.zonen.addEventListener('mouseover', function ( e ) { e.preventDefault(); _this.over(e); }, false);
        this.zonen.addEventListener('mouseout' , function ( e ) { e.preventDefault(); _this.out(e);  }, false);
        this.zonen.addEventListener('mousedown', function ( e ) { e.preventDefault(); _this.click(e); }, false);
    },
    over:function(e){
        this.bg.style.backgroundColor = 'rgba(0,0,0,0.5)';
        this.col.style.backgroundColor = 'rgba(55,123,167,1)';
    },
    out:function(e){
        this.bg.style.backgroundColor = 'rgba(0,0,0,0.1)';
        this.col.style.backgroundColor = 'rgba(55,123,167,0.5)';
    },
    click:function(e){
        var tx = "on";
        var p = 30;
        if(this.value){this.value = false; tx = "off"; p=0;}
        else{ this.value = true;}

        this.onChange(this.value);
        this.txt.textContent = this.name + " "+ tx;
        this.col.style.width = p+"px";
        this.pin.style.left = 80+p+"px";
    }
}


text:
#ifndef LIBRADIODNS_H_
# define LIBRADIODNS_H_                 1

typedef struct radiodns_struct radiodns_t;
typedef struct radiodns_app_struct radiodns_app_t;
typedef struct radiodns_srv_struct radiodns_srv_t;
typedef struct radiodns_kv_struct radiodns_kv_t;

struct radiodns_kv_struct
{
	const char *key;
	const char *value;
};

struct radiodns_app_struct
{
	radiodns_app_t *next;
	char *name;
	radiodns_kv_t *params;
	int nparams;
	int nsrv;
	radiodns_srv_t *srv;
	char *_pbuf;
	int _plen;
};

struct radiodns_srv_struct
{
	int priority;
	int weight;
	int port;
	char *target;
};

# ifdef __cplusplus
extern "C" {
# endif

	/* Create a new RadioDNS context using a specified domain name */
	radiodns_t *radiodns_create(const char *domain);

	/* Create a new RadioDNS context for a VHF/FM service
	 * - country must be either a 2-letter country code or a 3-character
	 *   RDS ECC.
	 * - suffix may be specified to override the default 'radiodns.org',
	 *   otherwise NULL
	 */
	radiodns_t *radiodns_create_fm(unsigned int freq, unsigned int pi, const char *country, const char *suffix);

	/* Create a new RadioDNS context for a DAB service delivered via X-PAD */
	radiodns_t *radiodns_create_dab_xpad(unsigned int appty, unsigned int uatype, unsigned int scids, unsigned long sid, unsigned int eid, unsigned int ecc, const char *suffix);

	/* Create a new RadioDNS context for a DAB service delivered via a SC */
	radiodns_t *radiodns_create_dab_sc(unsigned int pa, unsigned int scids, unsigned long sid, unsigned int eid, unsigned int ecc, const char *suffix);

	/* Create a new RadioDNS context for a DAB service delivered by neither
	 * X-PAD nor an independent Service Component
	 */
	radiodns_t *radiodns_create_dab(unsigned int scids, unsigned long sid, unsigned int eid, unsigned int ecc, const char *suffix);

	/* Create a new RadioDNS context for a DRM service */
	radiodns_t *radiodns_create_drm(unsigned long sid, const char *suffix);

	/* Create a new RadioDNS context for an AMSS service */
	radiodns_t *radiodns_create_amss(unsigned long sid, const char *suffix);

	/* Create a new RadioDNS context for an iBiquity HD Radio service */
	radiodns_t *radiodns_create_hdradio(unsigned long tx, unsigned int cc, const char *suffix);

	/* Create a new RadioDNS context for a DVB service */
	radiodns_t *radiodns_create_dvb(unsigned int onid, unsigned int tsid, unsigned long sid, unsigned long nid, const char *suffix);

	/* Destroy a RadioDNS context */
	void radiodns_destroy(radiodns_t *context);

	/* Determine the source domain name for a context, as set by one of the
	 * radiodns_create_xxx() functions
	 */
	const char *radiodns_domain(radiodns_t *context);

	/* Determine the target FQDN (beneath which SRV records are published)
	 * for a context.
	 */
	const char *radiodns_target(radiodns_t *context);

	/* Attempt to resolve the target FQDN for a context */
	const char *radiodns_resolve_target(radiodns_t *context);

	/* Locate all instances of the specified application for a context */
	radiodns_app_t *radiodns_resolve_app(radiodns_t *context, const char *name, const char *protocol);

	/* Destroy an application (list of instances) returned by
	 * radiodns_resolve_app()
	 */
	void radiodns_destroy_app(radiodns_app_t *app);

# ifdef __cplusplus
}
# endif

#endif /*!LIBRADIODNS_H_*/


text:
published: true
layout: default
---

No, Rapes In Sweden Are Not Up by 70%

I've only been to Sweden a couple, maybe six times, but something was striking me as just wrong with the Breitbart story on Swedish rapes rising 70 percent in a year.

ERMAHGERD! That's like, totally GHERSTLY! What could be behind this? Some digging shows it: The Swedish National Council for Crime Prevention (Brottsförebyggande rådet, or Brå) put out its English-language estimate of crimes in Sweden.

In the English-language summary, based on reported crimes, Brå estimated that the populace "exposed" to sexual assault rose from 1% to 1.7% in 2016.

Wow. from 1% to 1.7% actually is a 70% increase. And Breitbart's Liam Deacon (best recent headline: "Transgender Killer Moved from Female Prison after Sex with Inmates") wrote about it on January 11. He's not wrong, is he? I mean, if Brå said it, it must be right, right?

Still, that's a weird way to do crime statistics, huh? "From 1% to 1.7% of the population," "exposed" to a crime type?

A little, you know, reading, brings a lot of enlightenment. In the original Swedish (no, I don't, but I have me some Google, and I like statistics, so stay with me, I source everything I say), we see that Brå was, like, a lot more specific:

In 2016, "Antalet anmälda våldtäkter ökade med 13 procent till 6 560 brott," Brå proclaims, "medan anmälda brott om sexuellt tvång och utnyttjande minskade med 1 procent till 1 240," they said.

Which means, "The number of reported rapes increased by 13%, to 6,560, while the number of reports of sexual coersion and exploitation declined by 1%, to 1,240."

The increase was year-over-year. That was partly because reported rapes in 2015 had declined by 12% over 2014 numbers, from 6,700 to 5,920.<input type="checkbox" id="sn-demo" class="margin-toggle"/>"Antalet anmälda våldtäkter minskade med 12 procent till 5 920 brott. Minskningen förklaras delvis av att statistiken för 2014 innehöll ett stort ärende med många våldtäktsbrott."

OK, so that's totes more specific and a lot more palatable than 70%.

But wait! Again!

It turns out that, in 2014, reported rapes had increased by 11%: "...anmälda våldtäkterna ökade med 11 procent till 6 700 brott. Anmälda brott om grov kvinnofridskränkning minskade till 2 000 anmälda brott (–7 %), medan grov fridskränkning ökade till 1 770 anmälda brott (+2 %)."

Or, "...reported rapes increased by 11 percent, to 6,700. Reported "gross violations of women" decreased to 2,000 offenses, while "gross violation of integrity" increased 2%, to 1,770 reported offenses."

Thus, comparing 2016 figures of 6,560 reported rapes to 2014 figures of 6,700 reported rapes, we see a decrease of 2.08% AFTER Sweden began taking in such large numbers of refugees.

Say! Let's look at that as a graphical representation, hmm?

Oh, snap.

It also seems as if Brå, like the FBI, may have done some changing prior to 2014 as to exactly how it calculates and reports on sexual assault numbers, which would result in some fluctuations - note the differences in language ("gross violations of women" in 2014, versus "sexual coersion" in 2016, etc.)

But the one thing that seems clear is that in Sweden, you can bet your sweet Smörgåsbord that rapes are not up by 70% year-over-year.


text:
from disco.bot import CommandLevels
from disco.util.sanitize import S
from disco.types.message import MessageEmbed

from rowboat.plugins import RowboatPlugin as Plugin, CommandFail, CommandSuccess
from rowboat.types import Field
from rowboat.types.plugin import PluginConfig
from rowboat.models.tags import Tag
from rowboat.models.user import User

class TagsConfig(PluginConfig):
    max_tag_length = Field(int)
    min_level_remove_others = Field(int, default=int(CommandLevels.MOD))

@Plugin.with_config(TagsConfig)
class TagsPlugin(Plugin):
    @Plugin.command('create', '<name:str> <content:str...>', group='tags', aliases=['add'], level=CommandLevels.TRUSTED)
    def on_tags_create(self, event, name, content):
        name = S(name)
        content = S(content)

        if len(content) > event.config.max_tag_length:
            raise CommandFail('tag content is too long (max {} characters)'.format(event.config.max_tag_length))

        _, created = Tag.get_or_create(
            guild_id=event.guild.id,
            author_id=event.author.id,
            name=name,
            content=content
        )

        if not created:
            raise CommandFail('a tag by that name already exists')

        raise CommandSuccess('ok, your tag named `{}` has been created'.format(name))

    @Plugin.command('tags', '<name:str>', aliases=['tag'], level=CommandLevels.TRUSTED)
    @Plugin.command('show', '<name:str>', group='tags', level=CommandLevels.TRUSTED)
    def on_tags(self, event, name):
        try:
            tag = Tag.select(Tag, User).join(
                User, on=(User.user_id == Tag.author_id)
            ).where(
                (Tag.guild_id == event.guild.id) &
                (Tag.name == S(name))
            ).get()
        except Tag.DoesNotExist:
            raise CommandFail('no tag by that name exists')

        # Track the usage of the tag
        Tag.update(times_used=Tag.times_used + 1).where(
            (Tag.guild_id == tag.guild_id) &
            (Tag.name == tag.name)
        ).execute()

        event.msg.reply(':information_source: {}'.format(
            tag.content
        ))

    @Plugin.command('remove', '<name:str>', group='tags', aliases=['del', 'rm'], level=CommandLevels.TRUSTED)
    def on_tags_remove(self, event, name):
        try:
            tag = Tag.select(Tag, User).join(
                User, on=(User.user_id == Tag.author_id)
            ).where(
                (Tag.guild_id == event.guild.id) &
                (Tag.name == S(name))
            ).get()
        except Tag.DoesNotExist:
            raise CommandFail('no tag by that name exists')

        if tag.author_id != event.author.id:
            if event.user_level <= event.config.min_level_remove_others:
                raise CommandFail('you do not have the required permissions to remove other users tags')

        tag.delete_instance()
        raise CommandSuccess(u'ok, deleted tag `{}`'.format(tag.name))

    @Plugin.command('info', '<name:str>', group='tags', level=CommandLevels.TRUSTED)
    def on_tags_info(self, event, name):
        try:
            tag = Tag.select(Tag, User).join(
                User, on=(User.user_id == Tag.author_id).alias('author')
            ).where(
                (Tag.guild_id == event.guild.id) &
                (Tag.name == S(name))
            ).get()
        except Tag.DoesNotExist:
            raise CommandFail('no tag by that name exists')

        embed = MessageEmbed()
        embed.title = tag.name
        embed.description = tag.content
        embed.add_field(name='Author', value=unicode(tag.author), inline=True)
        embed.add_field(name='Times Used', value=str(tag.times_used), inline=True)
        embed.timestamp = tag.created_at.isoformat()
        event.msg.reply(embed=embed)


text:
(function UnauthInterceptorFactory(module) {

  function UnauthorizedInterceptor(
    $rootScope,
    $q,
    jwtHelper,
    httpBufferSvc
  ) {

    return {
      responseError: function responseError(rejection) {
         if (!rejection.config.ignoreAuthModule) {
            switch (rejection.status) {
               case 401:
                  var deferred = $q.defer();
                  httpBufferSvc.append(rejection.config, deferred);
                  $rootScope.$broadcast('event:auth-refreshRequired', rejection, deferred);
                  return deferred.promise;
               case 403:
                  $rootScope.$broadcast('event:auth-forbidden', rejection);
                  break;
               // no default
            }
         }
         // otherwise, default behaviour
         return $q.reject(rejection);
      }
    };
  }

  module.factory('unauthorizedInterceptor', [
    "$rootScope",
    "$q",
    "jwtHelper",
    "httpBufferSvc",
    UnauthorizedInterceptor
  ]);

})(angular.module("angular.token.interceptors"));


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Pharcidia lichenum Arnold

### Remarks
null


text:
var gulp = require('gulp');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var del = require('del');
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var path = require('path');

gulp.task('clean', function () {
  del(['./build/*']);
});

gulp.task('copy', function () {
  gulp.src('./client/**/*.html')
    .pipe(gulp.dest('build'));
  gulp.src('./client/img/*')
    .pipe(gulp.dest('build/img'));
  gulp.src('./bower_components/slick-carousel/slick/fonts/*')
      .pipe(gulp.dest('./build/fonts'));
  return gulp.src('./bower_components/slick-carousel/slick/ajax-loader.gif')
      .pipe(gulp.dest('./build'));
});

gulp.task('sass', function () {
  return  gulp.src(['./client/scss/**/*.scss'])
              .pipe(sass({
                includePaths : ['bower_components', 'node_modules'],
                errLogToConsole: true
              }))
              .pipe(autoprefixer({
                browsers: ['last 2 versions'],
                cascade: false
              }))
              .pipe(gulp.dest('./build/css'));
});

gulp.task('server', ['copy', 'sass'], function (callback) {
  var myConfig = require('./webpack.config');
  var webpackCompiler = webpack(myConfig, function(err, stats) {
  });

  new WebpackDevServer(webpackCompiler, {
    contentBase: './build',
    hot: true,
    debug: true
  }).listen(8000, 'localhost', function (err, result) {

  });
});

gulp.task('watch', function () {
  gulp.watch(['./client/**/*{scss,sass}'], ['sass']);
  gulp.watch(['./client/**/*.html'], ['copy']);
});

gulp.task('default', ['watch', 'server'], function () {

});