text:
package org.jkiss.dbeaver.ext.postgresql.edit;

import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.ext.postgresql.PostgreConstants;
import org.jkiss.dbeaver.ext.postgresql.PostgreUtils;
import org.jkiss.dbeaver.ext.postgresql.model.*;
import org.jkiss.dbeaver.ext.postgresql.model.data.type.PostgreTypeHandler;
import org.jkiss.dbeaver.ext.postgresql.model.data.type.PostgreTypeHandlerProvider;
import org.jkiss.dbeaver.model.*;
import org.jkiss.dbeaver.model.edit.DBECommandContext;
import org.jkiss.dbeaver.model.edit.DBECommandWithOptions;
import org.jkiss.dbeaver.model.edit.DBEObjectRenamer;
import org.jkiss.dbeaver.model.edit.DBEPersistAction;
import org.jkiss.dbeaver.model.exec.DBCExecutionContext;
import org.jkiss.dbeaver.model.impl.edit.DBECommandAbstract;
import org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistAction;
import org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistActionAtomic;
import org.jkiss.dbeaver.model.impl.sql.edit.struct.SQLTableColumnManager;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.sql.SQLUtils;
import org.jkiss.dbeaver.model.struct.DBSObject;
import org.jkiss.dbeaver.model.struct.cache.DBSObjectCache;
import org.jkiss.utils.ArrayUtils;
import org.jkiss.utils.CommonUtils;

import java.util.List;
import java.util.Map;

/**
 * Postgre table column manager
 */
public class PostgreTableColumnManager extends SQLTableColumnManager<PostgreTableColumn, PostgreTableBase>
        implements DBEObjectRenamer<PostgreTableColumn>, DBPScriptObjectExt2 {

    String OPTION_NON_STRUCT_CREATE_ACTION = "non.struct.create.action";

    protected final ColumnModifier<PostgreTableColumn> PostgreDataTypeModifier = (monitor, column, sql, command) -> {
        sql.append(' ');

        final PostgreDataType dataType = column.getDataType();
        if (dataType != null) {
            sql.append(dataType.getFullyQualifiedName(DBPEvaluationContext.DDL));

            final PostgreTypeHandler handler = PostgreTypeHandlerProvider.getTypeHandler(dataType);
            if (handler != null) {
                sql.append(handler.getTypeModifiersString(dataType, column.getTypeMod()));
            }
        } else {
            sql.append(column.getTypeName());
        }

        if (column.getTable() instanceof PostgreTableForeign) {
            String[] foreignTableColumnOptions = column.getForeignTableColumnOptions();
            if (foreignTableColumnOptions != null && foreignTableColumnOptions.length != 0) {
                sql.append(" OPTIONS").append(PostgreUtils.getOptionsString(foreignTableColumnOptions));
            }
        }
    };

    protected final ColumnModifier<PostgreTableColumn> PostgreDefaultModifier = (monitor, column, sql, command) -> {
        String defaultValue = column.getDefaultValue();
        if (!CommonUtils.isEmpty(defaultValue) && defaultValue.startsWith("nextval")) {
            // Remove serial type default value from DDL
            if (PostgreConstants.SERIAL_TYPES.containsKey(column.getDataType().getName())) {
                return;
            }
        }
        DefaultModifier.appendModifier(monitor, column, sql, command);
    };

    protected final ColumnModifier<PostgreTableColumn> PostgreIdentityModifier = (monitor, column, sql, command) -> {
        PostgreAttributeIdentity identity = column.getIdentity();
        if (identity != null) {
            sql.append(" ").append(identity.getDefinitionClause());
        }
    };

    protected final ColumnModifier<PostgreTableColumn> PostgreCollateModifier = (monitor, column, sql, command) -> {
        try {
            PostgreCollation collation = column.getCollation(monitor);
            if (collation != null && !PostgreConstants.COLLATION_DEFAULT.equals(collation.getName())) {
                sql.append(" COLLATE \"").append(collation.getName()).append("\"");
            }
        } catch (DBException e) {
            log.debug(e);
        }
    };

    protected final ColumnModifier<PostgreTableColumn> PostgreCommentModifier = (monitor, column, sql, command) -> {
        String comment = column.getDescription();
        boolean createNonStructAction = command instanceof DBECommandWithOptions && ((DBECommandWithOptions) command).getOptions().containsKey(OPTION_NON_STRUCT_CREATE_ACTION); // Column already has comment in this action
        if (!createNonStructAction && !CommonUtils.isEmpty(comment)) {
            sql.append(" -- ").append(CommonUtils.getSingleLineString(comment));
        }
    };

    protected final ColumnModifier<PostgreTableColumn> PostgreGeneratedModifier = (monitor, column, sql, command) -> {
        String generatedValue = column.getGeneratedValue();
        if (!CommonUtils.isEmpty(generatedValue)) {
            sql.append(" GENERATED ALWAYS AS (").append(generatedValue).append(") STORED");
        }
    };

    @Override
    public boolean canEditObject(PostgreTableColumn object) {
        return true;
    }

    @Nullable
    @Override
    public DBSObjectCache<? extends DBSObject, PostgreTableColumn> getObjectsCache(PostgreTableColumn object)
    {
        return object.getParentObject().getContainer().getSchema().getTableCache().getChildrenCache(object.getParentObject());
    }

    protected ColumnModifier[] getSupportedModifiers(PostgreTableColumn column, Map<String, Object> options)
    {
        ColumnModifier[] modifiers = {PostgreDataTypeModifier, NullNotNullModifier, PostgreDefaultModifier, PostgreIdentityModifier, PostgreCollateModifier, PostgreGeneratedModifier};
        if (CommonUtils.getOption(options, DBPScriptObject.OPTION_INCLUDE_COMMENTS)) {
            modifiers = ArrayUtils.add(ColumnModifier.class, modifiers, PostgreCommentModifier);
        }
        return modifiers;
    }

    @Override
    public StringBuilder getNestedDeclaration(DBRProgressMonitor monitor, PostgreTableBase owner, DBECommandAbstract<PostgreTableColumn> command, Map<String, Object> options)
    {
        StringBuilder decl = super.getNestedDeclaration(monitor, owner, command, options);
        final PostgreAttribute column = command.getObject();
        return decl;
    }

    @Override
    protected PostgreTableColumn createDatabaseObject(final DBRProgressMonitor monitor, final DBECommandContext context, final Object container, Object copyFrom, Map<String, Object> options) throws DBException {
        PostgreTableBase table = (PostgreTableBase) container;

        final PostgreTableColumn column;
        if (copyFrom instanceof PostgreTableColumn) {
            column = new PostgreTableColumn(monitor, table, (PostgreTableColumn)copyFrom);
        } else {
            column = new PostgreTableColumn(table);
            column.setName(getNewColumnName(monitor, context, table));
            final PostgreDataType dataType = table.getDatabase().getDataType(monitor, PostgreOid.VARCHAR);
            column.setDataType(dataType); //$NON-NLS-1$
            column.setOrdinalPosition(-1);
        }
        return column;
    }

    @Override
    protected void addObjectCreateActions(DBRProgressMonitor monitor, DBCExecutionContext executionContext, List<DBEPersistAction> actions, ObjectCreateCommand command, Map<String, Object> options) {
        options.put(OPTION_NON_STRUCT_CREATE_ACTION, true);
        super.addObjectCreateActions(monitor, executionContext, actions, command, options);
        if (!CommonUtils.isEmpty(command.getObject().getDescription())) {
            addColumnCommentAction(actions, command.getObject());
        }
    }

    @Override
    protected void addObjectModifyActions(DBRProgressMonitor monitor, DBCExecutionContext executionContext, List<DBEPersistAction> actionList, ObjectChangeCommand command, Map<String, Object> options)
    {
        final PostgreAttribute column = command.getObject();
        boolean isAtomic = column.getDataSource().getServerType().isAlterTableAtomic();
        // PostgreSQL can't perform all changes by one query
//        ALTER [ COLUMN ] column [ SET DATA ] TYPE data_type [ COLLATE collation ] [ USING expression ]
//        ALTER [ COLUMN ] column SET DEFAULT expression
//        ALTER [ COLUMN ] column DROP DEFAULT
//        ALTER [ COLUMN ] column { SET | DROP } NOT NULL
//        ALTER [ COLUMN ] column SET STATISTICS integer
//        ALTER [ COLUMN ] column SET ( attribute_option = value [, ... ] )
//        ALTER [ COLUMN ] column RESET ( attribute_option [, ... ] )
//        ALTER [ COLUMN ] column SET STORAGE { PLAIN | EXTERNAL | EXTENDED | MAIN }
        String prefix = "ALTER TABLE " + DBUtils.getObjectFullName(column.getTable(), DBPEvaluationContext.DDL) + " ALTER COLUMN " + DBUtils.getQuotedIdentifier(column) + " ";
        String typeClause = column.getFullTypeName();
        if (column.getDataSource().getServerType().supportsAlterTableColumnWithUSING() && column.getDataType() != null) {
            typeClause += " USING " + DBUtils.getQuotedIdentifier(column) + "::" + column.getDataType().getName();
        }
        if (command.hasProperty("fullTypeName") || command.hasProperty("maxLength") || command.hasProperty("precision") || command.hasProperty("scale")) {
            actionList.add(new SQLDatabasePersistActionAtomic("Set column type", prefix + "TYPE " + typeClause, isAtomic));
        }
        if (command.hasProperty(DBConstants.PROP_ID_REQUIRED)) {
            actionList.add(new SQLDatabasePersistActionAtomic("Set column nullability", prefix + (column.isRequired() ? "SET" : "DROP") + " NOT NULL", isAtomic));
        }

        if (command.hasProperty(DBConstants.PROP_ID_DEFAULT_VALUE)) {
            if (CommonUtils.isEmpty(column.getDefaultValue())) {
                actionList.add(new SQLDatabasePersistActionAtomic("Drop column default", prefix + "DROP DEFAULT", isAtomic));
            } else {
                actionList.add(new SQLDatabasePersistActionAtomic("Set column default", prefix + "SET DEFAULT " + column.getDefaultValue(), isAtomic));
            }
        }
        if (command.getProperty(DBConstants.PROP_ID_DESCRIPTION) != null) {
            addColumnCommentAction(actionList, column);
        }
    }

    public static void addColumnCommentAction(List<DBEPersistAction> actionList, PostgreAttribute column) {
        actionList.add(new SQLDatabasePersistAction("Set column comment", "COMMENT ON COLUMN " +
            DBUtils.getObjectFullName(column.getTable(), DBPEvaluationContext.DDL) + "." + DBUtils.getQuotedIdentifier(column) +
            " IS " + SQLUtils.quoteString(column, CommonUtils.notEmpty(column.getDescription()))));
    }

    @Override
    public void renameObject(@NotNull DBECommandContext commandContext, @NotNull PostgreTableColumn object, @NotNull Map<String, Object> options, @NotNull String newName) throws DBException {
        processObjectRename(commandContext, object, options, newName);
        final PostgreTableBase table = object.getTable();
        if (table.isPersisted() && table instanceof PostgreViewBase) {
            table.setObjectDefinitionText(null);
            commandContext.addCommand(new EmptyCommand(table), new RefreshObjectReflector(), true);
        }
    }

    @Override
    protected void addObjectRenameActions(DBRProgressMonitor monitor, DBCExecutionContext executionContext, List<DBEPersistAction> actions, ObjectRenameCommand command, Map<String, Object> options)
    {
        final PostgreAttribute column = command.getObject();

        actions.add(
            new SQLDatabasePersistAction(
                "Rename column",
                "ALTER TABLE " + DBUtils.getObjectFullName(column.getTable(), DBPEvaluationContext.DDL) + " RENAME COLUMN " +
                    DBUtils.getQuotedIdentifier(column.getDataSource(), command.getOldName()) + " TO " +
                    DBUtils.getQuotedIdentifier(column.getDataSource(), command.getNewName())));
    }

    @Override
    public boolean supportsObjectDefinitionOption(String option) {
        return DBPScriptObject.OPTION_INCLUDE_COMMENTS.equals(option);
    }
}


text:
#ifndef QUANT_PDE_MODULES_LAMBDAS_PAYOFFS_HPP
#define QUANT_PDE_MODULES_LAMBDAS_PAYOFFS_HPP

namespace QuantPDE {

namespace Modules {

/**
 * @param K strike price.
 * @return Lambda function payoff for a digital call option, \f$1_{S \geq K}\f$.
 */
inline Function1 digitalCallPayoff(Real K) {
	return [K] (Real S) { return S < K ? 0. : 1.; };
}

/**
 * @param K strike price.
 * @return Lambda function payoff for a digital put option, \f$1_{S \leq K}\f$.
 */
inline Function1 digitalPutPayoff(Real K) {
	return [K] (Real S) { return S > K ? 0. : 1.; };
}

/**
 * @param K Strike price.
 * @return Lambda function payoff for a vanilla call option,
 *         \f$\left(S\right)\equiv max\left(S - K, 0\right)\f$.
 */
inline Function1 callPayoff(Real K) {
	return [K] (Real S) { return S < K ? 0. : S - K; };
}

/**
 * @param K Strike price.
 * @return Lambda function payoff for a vanilla put option,
 *         \f$\left(S\right)\equiv max\left(S - K, 0\right)\f$.
 */
inline Function1 putPayoff(Real K) {
	return [K] (Real S) { return S < K ? K - S : 0.; };
}

/**
 * @param K Strike price.
 * @return Lambda function payoff for a straddle; the sum of the payoffs of a
 *         call and a put.
 */
inline Function1 straddlePayoff(Real K) {
	return [K] (Real S) { return S < K ? K - S : S - K; };
}

} // Modules

} // QuantPDE

#endif

redpajama_set_name: RedPajamaGithub


text:
// if a control group has an error, mark its parents has having an error
$(function() {
  $('.control-group.error').parents('.control-group').addClass('error');
});


text:
using System.Collections.Generic;
using System.Security;
using System.Threading.Tasks;

namespace HyperQube.Library
{
    public interface IConfigurationProvider
    {
        string GetAPIKey();
        void SetAPIKey(string value);

        string GetValue(string key);
        IDictionary<string, string> GetValues(params string[] keys);
        void SetValue(string key, string value);
        void SetValues(IDictionary<string, string> kvps);
        SecureString GetSecureValue(string key);
        void SetSecureValue(string key, string value);
        void Remove(string key);
        void Remove(params string[] keys);
        void Save();

        Task<string> GetValueAsync(string key);
        Task<IDictionary<string, string>> GetValuesAsync(params string[] keys);
        Task SetValueAsync(string key, string value);
        Task SetValuesAsync(IDictionary<string, string> kvps);
        Task<SecureString> GetSecureValueAsync(string key);
        Task SetSecureValueAsync(string key, string value);
        Task SaveAsync();

        Task<string> GetAPIKeyAsync();
        Task SetAPIKeyAsync(string value);
        Task RemoveAsync(string key);
        Task RemoveAsync(params string[] keys);
    }
}


text:
require 'spec_helper'
describe 'ntp_config' do
  describe 'old style' do
    fake_operatingsystem
    describe Puppet::Type.type(:ntp_config) do
      it_behaves_like 'name is the namevar'
      it_behaves_like 'string', attribute: :source_interface
      it_behaves_like 'boolean', attribute: :authenticate
      it_behaves_like 'array of strings or integers property', attribute: :trusted_key
    end
  end
  describe 'resource-api' do
    describe 'the ntp_config type' do
      it 'loads' do
        expect(Puppet::Type.type(:ntp_config)).not_to be_nil
      end
    end
  end
end


text:
import React from 'react';
import PropTypes from 'prop-types';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
import { List, ListItem } from 'material-ui/List';
import Divider from 'material-ui/Divider';
import IconMenu from 'material-ui/IconMenu';
import IconButton from 'material-ui/IconButton';
import Avatar from 'material-ui/Avatar';
import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert';
import MenuItem from 'material-ui/MenuItem';
import { grey400 } from 'material-ui/styles/colors';
import AutoComplete from 'material-ui/AutoComplete';
import Person from 'material-ui/svg-icons/social/person';

class CommentersEditorDialog extends React.Component {

	constructor(props) {
		super(props);

		this.state = {
			searchText: ''
		};
	}

	deleteCommenter(index) {
		const currentCommenters = this.state.currentCommenters;
		currentCommenters.splice(index, 1);

		this.props.setCommenters(currentCommenters);
	}

	changeSearchTextValue(value) {
		this.setState({
			searchText: value
		});
	}

	selectCommenter(commenter) {
		if (commenter.name) {

			this.setState({
				searchText: ''
			});
		}
	}

	render() {
		const { allCommenters, commentersIds } = this.state;
		const commentersList = [];

		allCommenters.forEach((commenter) => {
			if (commentersIds.indexOf(commenter._id) === -1) {
				commentersList.push(commenter);
			}
		});

		const actions = [
			<FlatButton
				label="Close"
				primary
				onClick={this.props.handleClose}
			/>,
		];

		const iconButtonElement = (
			<IconButton
				iconClassName="material-icons"
				touch
			>
				<MoreVertIcon color={grey400} />
			</IconButton>
		);

		return (
			<Dialog
				title="Commenters"
				actions={actions}
				modal={false}
				open={this.props.open}
				onRequestClose={this.props.handleClose}
				autoScrollBodyContent
			>

						<List>
							{commenters.map((commenter, index) =>
								<div key={`${commenter.slug}-div`}>
									<ListItem
										primaryText={commenter.name}
										key={`${commenter.slug}`}
										rightIconButton={
											<IconMenu iconButtonElement={iconButtonElement}>
												<MenuItem
													onClick={() => this.deleteCommenter(index)}
												>Remove from comment</MenuItem>
											</IconMenu>
										}
										leftAvatar={commenter.avatar ? <Avatar src={commenter.avatar.src} /> : <Person />}
									/>
									<Divider key={`${commenter.slug}-divider`} />

							)}
						</List>

							Add new

						<AutoComplete
							hintText="Enter commenter"
							dataSource={commentersList}
							dataSourceConfig={{text: 'name', value: 'slug'}}
							onNewRequest={this.selectCommenter}
							onUpdateInput={this.changeSearchTextValue}
							filter={(searchText, key) => searchText !== '' && key.toLowerCase().indexOf(searchText.toLowerCase()) !== -1}
							fullWidth
							openOnFocus
							searchText={this.state.searchText}
						/>

			</Dialog>
		);
	}
}

CommentersEditorDialog.propTypes = {
	setCommenters: PropTypes.func,
	handleClose: PropTypes.func,
	open: PropTypes.bool,
	commenters: PropTypes.array,
};

export default CommentersEditorDialog;


text:
"""PyVDP theme.

Forked from sphinx_rtd_theme.

https://github.com/rtfd/sphinx_rtd_theme
"""
import os

def get_html_theme_path():
    """Return list of HTML theme paths."""
    cur_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
    return cur_dir


text:
package scodec
package codecs

import scalaz.\/
import scodec.bits._
import scodec.codecs._

class ListCodecTest extends CodecSuite {

  "the listOfN codec" should {

    "limit decoding to the specified number of records" in {
      val codec = listOfN(provide(10), uint8)
      val buffer = BitVector.low(8 * 100)
      codec.decode(buffer) shouldBe \/.right((BitVector.low(8 * 90), List.fill(10)(0)))
    }

    "support encoding size before vector contents" in {
      val codec = listOfN(int32, uint8)
      codec.encode((1 to 10).toList) shouldBe \/.right(hex"0000000a0102030405060708090a".bits)
    }

    "support not encoding size before vector contents" in {
      val codec = listOfN(provide(10), uint8)
      codec.encode((1 to 10).toList) shouldBe \/.right(hex"102030405060708090a".bits)
    }
  }
}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.09.11 at 01:59:10 PM CDT
//

package com.github.stinkbird.helpspot.private_api.response_for.request.get_changed;

import java.io.Serializable;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element ref="{}xRequest" maxOccurs="unbounded"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "xRequest"
})
@XmlRootElement(name = "requests")
public class Requests implements Serializable {

	private static final long serialVersionUID = 6058659118635021115L;

	@XmlElement(required = false)
    protected List<BigInteger> xRequest;

    /**
     * Gets the value of the xRequest property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the xRequest property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getXRequest().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link BigInteger }
     *
     *
     */
    public List<BigInteger> getXRequest() {
        if (xRequest == null) {
            xRequest = new ArrayList<BigInteger>();
        }
        return this.xRequest;
    }

}


text:
<?xml version="1.0" encoding="utf-8" ?>
<INTERACTIONS>
<INTERACTION>
<SOURCE>
<CLINICAL_SOURCE>ANSM</CLINICAL_SOURCE>
<SOURCE_FILE>267-HYDROQUINIDINE.html
</SOURCE_FILE>
</SOURCE>
<DRUG1>
<DRUG name="HYDROQUINIDINE" rxcui="27220">
</DRUG>
</DRUG1>
<DRUG2>
<CLASS name="URINARY ALKALIZERS" code="B05-001" /></DRUG2>
<DESCRIPTION>Increase of the plasma concentrations of the hydroquinidine and risk of overdose (decrease of the renal excretion of the hydroquinidine due to alkalinizing of the urine )</DESCRIPTION>
<SEVERITY>Precaution for use</SEVERITY>
<COMMENT>Clinical monitoring, EKG, and, possibly testing of the concentrations of the hydroquinidine; if needed, adjustment of the dosage during the alkalinizing treatment and after it is stopped. </COMMENT>
</INTERACTION>
<INTERACTION>
<SOURCE>
<CLINICAL_SOURCE>ANSM</CLINICAL_SOURCE>
<SOURCE_FILE>267-HYDROQUINIDINE.html
</SOURCE_FILE>
</SOURCE>
<DRUG1>
<DRUG name="HYDROQUINIDINE" rxcui="27220">
</DRUG>
</DRUG1>
<DRUG2>
<DRUG name="DIGOXIN " rxcui="3407">
<ATC code="C01AA05" />
</DRUG>
</DRUG2>
<DESCRIPTION>Increase of the digoxinemia due to decrease of the renal clearance of the digoxin. In addition, disorders of autoregulation (excessive bradycardia and disorders of atrioventricular conduction).</DESCRIPTION>
<SEVERITY>Precaution for use</SEVERITY>
<COMMENT>Clinical monitoring and EKG. In the case of unexpected results, test the digoxinemia and adjust the dosage.</COMMENT>
</INTERACTION>
<INTERACTION>
<SOURCE>
<CLINICAL_SOURCE>ANSM</CLINICAL_SOURCE>
<SOURCE_FILE>267-HYDROQUINIDINE.html
</SOURCE_FILE>
</SOURCE>
<DRUG1>
<DRUG name="HYDROQUINIDINE" rxcui="27220">
</DRUG>
</DRUG1>
<DRUG2>
<DRUG name="ITRACONAZOLE" rxcui="28031">
<ATC code="J02AC02" />
</DRUG>
</DRUG2>
<DESCRIPTION>Risk of tinnitis and/or loss of hearing acuity: cinchonism linked to a decrease of the hepatic metabolism of the antiarrythmic by the itraconazole</DESCRIPTION>
<SEVERITY>Precaution for use</SEVERITY>
<COMMENT>Monitoring of the plasma concentrations of the antiarrythmic and possible decrease of its dosage if necessary.</COMMENT>
</INTERACTION>
</INTERACTIONS>


text:
package com.funcache.exception;

/**
 * TODO: Class description here.
 *
 * @author tjeubaoit
 */
public class LimitExceededException extends RuntimeException {
}


text:
namespace Epic::Math::XForm
{
	namespace detail
	{
		template<class T, class Inner>
		struct ScaleImpl;
	}

	template<class Inner = Linear>
	struct Scale;
}

//////////////////////////////////////////////////////////////////////////////

template<class T, class Inner>
struct Epic::Math::XForm::detail::ScaleImpl
{
	T Scale = (T)1;

	Inner ScaleInner;

	// NOTE: Equivalent to Modulate<Constant, Inner>
	constexpr T operator() (T t) const noexcept
	{
		const T tprime = ScaleInner(t);

		return Scale * tprime;
	}
};

template<class T>
struct Epic::Math::XForm::detail::ScaleImpl<T, Epic::Math::XForm::detail::LinearImpl<T>>
{
	T Scale = (T)1;

	// NOTE: Equivalent to Modulate<Constant, Linear>
	constexpr T operator() (T t) const noexcept
	{
		return Scale * t;
	}
};

//////////////////////////////////////////////////////////////////////////////

template<class Inner>
struct Epic::Math::XForm::Scale
	: public detail::XFormImpl1<Inner, detail::ScaleImpl> { };

template<template<class...> class Inner, class... InnerArgs>
struct Epic::Math::XForm::Scale<Inner<InnerArgs...>>
	: public detail::XFormImpl1<Inner<InnerArgs...>, detail::ScaleImpl> { };

//////////////////////////////////////////////////////////////////////////////

namespace Epic::Math::XForm
{
	using Scale1 = Scale<>;
}


text:
<?php
/**
 * User: Bahadir Malkoc
 * Date: 08/02/2017
 * Time: 18:15
 * Purpose: Provide interactive test without a vicidial instance
 */

if (!empty($_REQUEST['test_form'])) {

    $phone_login   = "";
    $phone_pass    = "";
    $server_ip     = "";
    $websocket_url = "";
    $system_key    = "";
    $callerid      = "";
    $codecs        = "";
    $protocol      = "SIP";

    if (!empty($_REQUEST['phone_login'])) {
        $phone_login = trim($_REQUEST['phone_login']);
    }

    if (!empty($_REQUEST['phone_pass'])) {
        $phone_pass = trim($_REQUEST['phone_pass']);
    }

    if (!empty($_REQUEST['server_ip'])) {
        $server_ip = trim($_REQUEST['server_ip']);
    }

    if (!empty($_REQUEST['websocket_url'])) {
        $websocket_url = trim($_REQUEST['websocket_url']);
    }

    if (!empty($_REQUEST['system_key'])) {
        $system_key = trim($_REQUEST['system_key']);
    }

    if (!empty($_REQUEST['callerid'])) {
        $callerid = trim($_REQUEST['callerid']);
    }

    if (!empty($_REQUEST['codecs'])) {
        $codecs = trim($_REQUEST['codecs']);
    }

    if (!empty($_REQUEST['protocol'])) {
        $protocol = trim($_REQUEST['protocol']);
    }

    $optionstr = "INITIAL_LOAD--DIALPAD_Y--AUTOANSWER_Y--WEBSOCKETURL$websocket_url";

    $query = http_build_query(array(
        'phone_login' => $phone_login ? base64_encode($phone_login) : '',
        'phone_pass'  => $phone_pass ? base64_encode($phone_pass) : '',
        'options'     => base64_encode($optionstr),
        'serverip'    => $server_ip ? base64_encode($server_ip) : '',
        'system_key'  => $system_key ? base64_encode($system_key) : '',
        'callerid'    => $callerid ? base64_encode($callerid) : '',
        'codecs'      => $codecs ? base64_encode($codecs) : '',
        'protocol'    => $protocol ? base64_encode($protocol) : ''
    ));

    $uri = 'index.php?' . $query;

    header('Location: ' . $uri);

    exit;
}

?>

Test Phone Variables:

After you send the form, phone page will be displayed in the right frame.

    <form method="get" action="test.php" target="phone_iframe" id="phone_form">
        <input type="hidden" name="test_form" value="1">

                Phone Login:

            <input type="text" placeholder="Enter phone login" id="phone_login" name="phone_login">

                Phone Pass:

            <input type="text" placeholder="Enter phone password" id="phone_pass" name="phone_pass">

                WebSocket URL:

            <input type="text" placeholder="Enter server ip (optional)" id="websocket_url" name="websocket_url">

            <button type="submit">
                Test Now
            </button>

    </form>

Console:

            Legend:

            Log
            Error
            Info
            Debug

    <button type="button" onclick="clearDebug()">
        Clear Console
    </button>

Test Phone Iframe:

    <button type="button" onclick="document.getElementById('phone_iframe').src='about:blank'">
        Close Phone
    </button>


text:
enum SERVER_STATE
{
    DISCONNECTED,
    CONNECTED,
    WAITING
};

class PLENControlServerAPI
{
    private _state: SERVER_STATE = SERVER_STATE.DISCONNECTED;
    private _socket: WebSocket = null;
    private _ip_addr: string = 'localhost:17264';

    constructor(
        private _$jquery: JQueryStatic
    )
    {
        this.connect();

        this._$jquery(window).on('beforeunload', () => { this.disconnect(); });
    }

    connect(success_callback = null): void
    {
        if (this._state === SERVER_STATE.DISCONNECTED)
        {
            this._state = SERVER_STATE.WAITING;

            this._$jquery.get('//' + this._ip_addr + '/v2/connect')
                .done((response: any) =>
                {
                    if (response.data.result === true)
                    {
                        this._state = SERVER_STATE.CONNECTED;
                        this._createWebSocket();

                        if (success_callback !== null)
                        {
                            success_callback();
                        }
                    }
                    else
                    {
                        this._state = SERVER_STATE.DISCONNECTED;

                        alert('USB connection has been disconnected!');
                    }
                })
                .fail(() =>
                {
                    this._state = SERVER_STATE.DISCONNECTED;

                    alert("The control-server hasn't run.");
                });
        }
    }

    disconnect(success_callback = null): void
    {
        if (this._state === SERVER_STATE.CONNECTED)
        {
            this._state = SERVER_STATE.WAITING;

            this._$jquery.get('//' + this._ip_addr + '/v2/disconnect')
                .done((response: any) =>
                {
                    if (response.data.result === true)
                    {
                        if (success_callback !== null)
                        {
                            success_callback();
                        }
                    }

                    this._state = SERVER_STATE.DISCONNECTED;
                })
                .fail(() =>
                {
                    this._state = SERVER_STATE.CONNECTED;
                });
        }
    }

    play(slot: number, success_callback = null): void
    {
        if (this._state === SERVER_STATE.CONNECTED)
        {
            this._state = SERVER_STATE.WAITING;

            this._$jquery.get('//' + this._ip_addr + '/v2/motions/' + slot.toString() + '/play')
                .done((response: any) =>
                {
                    this._state = SERVER_STATE.CONNECTED;

                    if (response.data.result === true)
                    {
                        if (success_callback !== null)
                        {
                            success_callback();
                        }
                    }
                    else
                    {
                        this._state = SERVER_STATE.DISCONNECTED;

                        alert('USB connection was disconnected!');
                    }
                })
                .fail(() =>
                {
                    this._state = SERVER_STATE.DISCONNECTED;
                });
        }
    }

    stop(success_callback = null): void
    {
        if (this._state === SERVER_STATE.CONNECTED)
        {
            this._state = SERVER_STATE.WAITING;

            this._$jquery.get('//' + this._ip_addr + '/v2/motions/stop')
                .done((response: any) =>
                {
                    this._state = SERVER_STATE.CONNECTED;

                    if (response.data.result === true)
                    {
                        if (!(success_callback == null))
                        {
                            success_callback();
                        }
                    }
                    else
                    {
                        this._state = SERVER_STATE.DISCONNECTED;

                        alert('USB connection was disconnected!');
                    }
                })
                .fail(() =>
                {
                    this._state = SERVER_STATE.DISCONNECTED;
                });
        }
    }

    push(slot: number, loop_count: number = 0): void
    {
         this._socket.send('push/' + slot.toString() + '/' + loop_count.toString());
    }

    pop(): void
    {
         this._socket.send('pop');
    }

    applyNative(device: string, value: number): void
    {
        if (this._state === SERVER_STATE.CONNECTED)
        {
            this._socket.send('apply/' + device + '/' + value.toString());
            this._state = SERVER_STATE.WAITING;
        }
    }

    applyDiff(device: string, value: number): void
    {
        if (this._state === SERVER_STATE.CONNECTED)
        {
            this._socket.send('applyDiff/' + device + '/' + value.toString());
            this._state = SERVER_STATE.WAITING;
        }
    }

    getStatus(): SERVER_STATE
    {
        return this._state;
    }

    checkVersionOfPLEN(): void
    {
        if (this._state === SERVER_STATE.CONNECTED)
        {
            var deferred: JQueryDeferred<any> = this._$jquery.Deferred();
            var promise: JQueryPromise<any>   = deferred.promise();

            var urls: Array<string> = [
                '//' + this._ip_addr + '/v2/version',
                '//' + this._ip_addr + '/v2/metadata'
            ];

            var responses: Array<any> = [];

            urls.forEach((url: string) =>
            {
                promise = promise.always(() =>
                {
                    return this._$jquery.get(url)
                        .done((response: any) =>
                        {
                            responses.push(response);
                        });
                });
            });

            promise = promise
                .then(() =>
                {
                    try {
                        var firmware_version: number = parseInt(responses[0].data['version'].replace(/\./g, ''));
                        var required_verison: number = parseInt(responses[1].data['required-firmware'].replace(/[\.\~]/g, ''));

                        if (firmware_version < required_verison) throw 'version error';
                    }
                    catch (e)
                    {
                        this._state = SERVER_STATE.DISCONNECTED;

                        alert('Firmware version of your PLEN is old. Please update version ' + responses[1].data['required-firmware'] + '.');
                    }
                })
                .fail(() =>
                {
                    this._state = SERVER_STATE.DISCONNECTED;
                });

            deferred.resolve();
        }
    }

    private _createWebSocket(): void
    {
        if (this._socket !== null)
        {
            this._socket.close();
            this._socket = null;
        }

        this._socket = new WebSocket('ws://' + this._ip_addr + '/v2/cmdstream');

        this._socket.onopen = () =>
        {
            if (this._socket.readyState === WebSocket.OPEN)
            {
                this._state = SERVER_STATE.CONNECTED;
            }
        };

        this._socket.onmessage = (e: MessageEvent) =>
        {
            if (e.data == 'False')
            {
                if (this._state === SERVER_STATE.WAITING)
                {
                    this._state = SERVER_STATE.DISCONNECTED;

                    alert('USB connection has been disconnected!');
                }
            }
            else
            {
                this._state = SERVER_STATE.CONNECTED;
            }
        };

        this._socket.onerror = () =>
        {
            this._state = SERVER_STATE.DISCONNECTED;

            alert("The control-server hasn't run.");
        };
    }
}


text:
require "csv"

module Gws::Addon::Import::Facility
  module Item
    extend ActiveSupport::Concern
    extend SS::Addon
    include SS::Scope::ActivationDate

    included do
      attr_accessor :in_file, :imported
      permit_params :in_file
    end

    module ClassMethods
      def to_csv
        CSV.generate do |data|
          data << csv_headers.map { |k| header_value_to_text(k) }
          criteria.each do |item|
            line = []
            line << item.id
            line << item.name
            add_category(line, item)
            line << item.order
            line << item.min_minutes_limit
            line << item.max_minutes_limit
            line << item.max_days_limit
            line << datetime_to_text(item.reservation_start_date)
            line << datetime_to_text(item.reservation_end_date)
            line << datetime_to_text(item.activation_date)
            line << datetime_to_text(item.expiration_date)
            line << approval_check_state_datas_value_to_text(item.approval_check_state)
            line << type_datas_value_to_text(item.text_type)
            line << item.text
            attrs = %i(
              id
              class_name
              name
              order
              required
              tooltips
              prefix_label
              postfix_label
              input_type
              min_decimal
              max_decimal
              initial_decimal
              scale
              minus_type
              max_length
              place_holder
              additional_attr
              select_options
              upload_file_count
            )

            columns_max.times do |i|
              attrs.each do |attr|
                line << output_line(attr, item.columns[i])
              end
            end
            line << item.reservable_group_names.join("\n")
            line << item.reservable_member_names.join("\n")
            line << readable_setting_range_datas_value_to_text(item.readable_setting_range)
            line << item.readable_group_names.join("\n")
            line << item.readable_member_names.join("\n")
            line << item.group_names.join("\n")
            line << item.user_names.join("\n")
            line << item.permission_level
            data << line
          end
        end
      end

      def csv_headers
        headers = %w(
          id name category_id order min_minutes_limit max_minutes_limit
          max_days_limit reservation_start_date reservation_end_date
          activation_date expiration_date approval_check_state type html
        )
        headers += columns_headers
        headers += %w(
          reservable_group_names reservable_member_names readable_setting_range
          readable_group_names readable_member_names group_names user_names permission_level
        )
        headers
      end

      def columns_max
        criteria.map(&:columns).map(&:size).max.to_i
      end

      def columns_headers
        headers = %i(
          id
          type
          name
          order
          required
          tooltips
          prefix_label
          postfix_label
          input_type
          min_decimal
          max_decimal
          initial_decimal
          scale
          minus_type
          max_length
          place_holder
          additional_attr
          select_options
          upload_file_count
        )

        columns_max.times.flat_map do |i|
          headers.map do |header|
            ["columns.#{header}", n: i + 1]
          end
        end
      end

      def output_line(attr, record)
        return if record.blank?
        return if !record.respond_to?(attr)
        case attr
        when :input_type
          I18n.t("gws/facility/item.csv.columns.input_type_datas.#{record.send(attr)}")
        when :required
          I18n.t("gws/facility/item.csv.columns.required_datas.#{record.send(attr)}")
        when :minus_type
          I18n.t("gws/facility/item.csv.columns.minus_type_datas.#{record.send(attr)}")
        when :class_name
          record.class.model_name.human
        when :select_options
          record.send(attr).join("\n")
        else
          record.send(attr)
        end
      end

      def add_category(line, item)
        return line << item.category.name if item.category.present?
        line << nil
      end

      def datetime_to_text(time)
        return if time.blank?
        I18n.l(time)
      end

      def header_value_to_text(header, options = {})
        I18n.t("gws/facility/item.csv.#{header}", options)
      end

      def type_datas_value_to_text(type_datas)
        return if type_datas.blank?
        I18n.t("gws/facility/item.csv.type_datas.#{type_datas}")
      end

      def approval_check_state_datas_value_to_text(approval_check_state)
        return if approval_check_state.blank?
        I18n.t("gws/facility/item.csv.approval_check_state_datas.#{approval_check_state}")
      end

      def readable_setting_range_datas_value_to_text(readable_setting_range)
        return if readable_setting_range.blank?
        I18n.t("gws/facility/item.csv.readable_setting_range_datas.#{readable_setting_range}")
      end
    end

    def import
      @imported = 0
      validate_import
      return false unless errors.empty?

      table = CSV.read(in_file.path, headers: true, encoding: 'SJIS:UTF-8')
      table.each_with_index do |row, i|
        update_row(row, i + 2)
      end
      errors.blank?
    end

    def validate_import
      return errors.add :in_file, :blank if in_file.blank?
      return errors.add :cur_site, :blank if cur_site.blank?

      fname = in_file.original_filename
      unless /^\.csv$/i.match?(::File.extname(fname))
        errors.add :in_file, :invalid_file_type
        return
      end

      begin
        CSV.read(in_file.path, headers: true, encoding: 'SJIS:UTF-8')
        in_file.rewind
      rescue => e
        errors.add :in_file, :invalid_file_type
      end
    end

    def update_row(row, index)
      id = row[header_t("id")].to_s.strip
      name = row[header_t("name")].to_s.strip
      category_name = row[t("category_id")].to_s.strip
      order = row[header_t("order")].to_s.strip
      min_minutes_limit = row[header_t("min_minutes_limit")].to_s.strip
      max_minutes_limit = row[header_t("max_minutes_limit")].to_s.strip
      max_days_limit = row[header_t("max_days_limit")].to_s.strip
      reservation_start_date = row[header_t("reservation_start_date")].to_s.strip
      reservation_end_date = row[header_t("reservation_end_date")].to_s.strip
      activation_date = row[header_t("activation_date")].to_s.strip
      expiration_date = row[header_t("expiration_date")].to_s.strip
      approval_check_state = row[header_t("approval_check_state")].to_s.strip

      reservable_group_names = row[header_t("reservable_group_names")].to_s.strip.split("\n")
      reservable_member_names = row[header_t("reservable_member_names")].to_s.strip.split("\n")
      readable_setting_range = row[header_t("readable_setting_range")].to_s.strip
      readable_group_names = row[header_t("readable_group_names")].to_s.strip.split("\n")
      readable_member_names = row[header_t("readable_member_names")].to_s.strip.split("\n")
      group_names = row[header_t("group_names")].to_s.strip.split("\n")
      user_names = row[header_t("user_names")].to_s.strip.split("\n")
      permission_level = row[header_t("permission_level")].to_s.strip
      text_type = row[header_value_to_text("type")].to_s.strip
      text = row[header_value_to_text("html")].to_s.strip

      if id.present?
        item = self.class.unscoped.site(cur_site).where(id: id).first
        if item.blank?
          self.errors.add :base, :not_found, line_no: index, id: id
          return
        end

        if name.blank?
          item.disable
          @imported += 1
          return
        end
      else
        item = self.class.new
      end
      item.site = @cur_site
      item.user = @cur_user
      item.name = name
      item.category = Gws::Facility::Category.site(@cur_site).where(name: category_name).first
      item.order = order
      item.min_minutes_limit = min_minutes_limit
      item.max_minutes_limit = max_minutes_limit
      item.max_days_limit = max_days_limit
      item.reservation_start_date = reservation_start_date
      item.reservation_end_date = reservation_end_date
      item.activation_date = activation_date
      item.expiration_date = expiration_date

      item.reservable_group_ids = group_names_to_ids(reservable_group_names)
      item.reservable_member_ids = user_names_to_ids(reservable_member_names)

      item.readable_setting_range = readable_setting_range_datas_text_to_value(readable_setting_range)

      item.text_type = type_datas_text_to_value(text_type)
      item.text = text

      item.readable_group_ids = group_names_to_ids(readable_group_names)
      item.readable_member_ids = user_names_to_ids(readable_member_names)
      item.group_ids = group_names_to_ids(group_names)
      item.user_ids = user_names_to_ids(user_names)
      item.permission_level = permission_level

      item.approval_check_state = approval_check_state_datas_text_to_value(approval_check_state)
      if item.save
        @imported += 1
        @cur_form = item
        set_errors(item, index) unless update_columns(row, index, item)
      else
        set_errors(item, index)
      end
    end

    def set_errors(item, index)
      error = ""
      item.errors.each do |n, e|
        if item.class.t(n) == "Base"
          error += "#{e} "
        else
          error += "#{item.class.t(n)}#{e} "
        end
      end
      self.errors.add :base, "#{index}: #{error}"
    end

    def header_t(header, options = {})
      I18n.t("gws/facility/item.csv.#{header}", options)
    end

    def user_names_to_ids(names)
      user_names = names.map do |name|
        name.gsub(/ \(.+\)\z/, "")
      end
      Gws::User.any_in(name: user_names).pluck(:id)
    end

    def group_names_to_ids(names)
      Gws::Group.any_in(name: names).pluck(:id)
    end

    def update_columns(row, index, item)
      columns_setting = I18n.t("modules.addons.gws/facility/column_setting")

      column_with_index = row.select { |header_key, _v| header_key =~ /\A#{columns_setting}/ }.to_h
      column_with_index = column_with_index.group_by do |k, v|
        k =~ /\A#{columns_setting}([0-9]+)/
        $1
      end

      datas = column_with_index.each_with_object({}) do |(key, value), hash|
        hash[key] = value.each_with_object({}) do |(k, v), h|
          text_key, _text_value = I18n.t("gws/facility/item.csv.columns").find do |key, value|
            k.match(value.gsub("%{n}", "[0-9]+"))
          end
          h[text_key] = v
        end
      end
      errors = []
      datas.each do |key, value|
        next if value.values.none?
        add_data_by_type(key, value, errors)
      end
      return true if errors.blank?
      columns_set_errors(item, errors)
      false
    end

    def add_data_by_type(key, value, errors)
      if value[:id].present?
        column = Gws::Column::Base.unscoped.site(cur_site).where(id: value[:id]).first
        if column.blank?
          column = Gws::Column::Base.new
          column.errors.add :id, :not_found, id: value[:id]
          create_column_errors(errors, key, column)
          return
        end

        if value[:name].blank?
          column.destroy
          @imported += 1
          return
        end
      else
        column = column_model(value[:type]).new
      end

      case column
      when Gws::Column::TextField
        column.input_type = input_type_datas_text_to_value(value[:input_type].to_s.strip)
        column.max_length = value[:max_length].to_s.strip
        column.additional_attr = value[:additional_attr].to_s.strip
        column.place_holder = value[:place_holder].to_s.strip
      when Gws::Column::DateField
        column.input_type = input_type_datas_text_to_value(value[:input_type].to_s.strip)
        column.place_holder = value[:place_holder].to_s.strip
      when Gws::Column::UrlField
        column.max_length = value[:max_length].to_s.strip
        column.additional_attr = value[:additional_attr].to_s.strip
        column.place_holder = value[:place_holder].to_s.strip
      when Gws::Column::NumberField
        column.min_decimal = value[:min_decimal].to_s.strip
        column.max_decimal = value[:max_decimal].to_s.strip
        column.initial_decimal = value[:initial_decimal].to_s.strip
        column.scale = value[:scale].to_s.strip
        column.minus_type = minus_type_datas_text_to_value(value[:minus_type].to_s.strip)
        column.max_length = value[:max_length].to_s.strip
        column.additional_attr = value[:additional_attr].to_s.strip
        column.place_holder = value[:place_holder].to_s.strip
      when Gws::Column::TextArea
        column.max_length = value[:max_length].to_s.strip
        column.additional_attr = value[:additional_attr].to_s.strip
        column.place_holder = value[:place_holder].to_s.strip
      when Gws::Column::Select
        column.select_options = value[:select_options].to_s.strip.split("\n")
        column.place_holder = value[:place_holder].to_s.strip
      when Gws::Column::RadioButton
        column.select_options = value[:select_options].to_s.strip.split("\n")
      when Gws::Column::CheckBox
        column.select_options = value[:select_options].to_s.strip.split("\n")
      when Gws::Column::FileUpload
        column.upload_file_count = value[:upload_file_count].to_s.strip
        column.place_holder = value[:place_holder].to_s.strip
      end

      column.site = @cur_site
      column.form = @cur_form
      column.name = value[:name].to_s.strip
      column.order = value[:order].to_s.strip
      column.required = value[:require].to_s.strip
      column.tooltips = value[:tooltips].to_s.strip
      column.prefix_label = value[:prefix_label].to_s.strip
      column.postfix_label = value[:postfix_label].to_s.strip

      column.required = required_datas_text_to_value(value[:required].to_s.strip)
      if column.save
        @imported += 1
      else
        create_column_errors(errors, key, column)
      end
    end

    def column_model(type)
      return if type.blank?
      type_text_to_value(type).sub('/', '/column/').classify.constantize
    end

    def type_text_to_value(text)
      return if text.blank?
      k, _v = I18n.t("gws.columns").find do |key, value|
        text.match(value)
      end
      k.to_s
    end

    def input_type_datas_text_to_value(text)
      k, _v = I18n.t("gws/facility/item.csv.columns.input_type_datas").find do |key, value|
        text.match(value)
      end
      k.to_s
    end

    def required_datas_text_to_value(text)
      k, _v = I18n.t("gws/facility/item.csv.columns.required_datas").find do |key, value|
        text.match(value)
      end
      k.to_s
    end

    def minus_type_datas_text_to_value(text)
      k, _v = I18n.t("gws/facility/item.csv.columns.minus_type_datas").find do |key, value|
        text.match(value)
      end
      k.to_s
    end

    def header_value_to_text(header)
      I18n.t("gws/facility/item.csv.#{header}")
    end

    def column_header_value_to_text(header, options = {})
      I18n.t("gws/facility/item.csv.columns.#{header}", options)
    end

    def approval_check_state_datas_text_to_value(approval_check_state_datas)
      k, _v = I18n.t("gws/facility/item.csv.approval_check_state_datas").find do |key, value|
        approval_check_state_datas.match(value)
      end
      k.to_s
    end

    def readable_setting_range_datas_text_to_value(readable_setting_range_datas)
      k, _v = I18n.t("gws/facility/item.csv.readable_setting_range_datas").find do |key, value|
        readable_setting_range_datas.match(value)
      end
      k.to_s
    end

    def type_datas_text_to_value(text)
      k, _v = I18n.t("gws/facility/item.csv.type_datas").find do |key, value|
        text.match(value)
      end
      k.to_s
    end

    def disable
      super
      columns.each(&:destroy)
    end

    def create_column_errors(errors, key, column)
      column.errors.messages.map do |n, e|
        errors << "#{column_header_value_to_text(n, n: key)}#{e[0]}"
      end
    end

    def columns_set_errors(item, errors)
      item.errors.add :base, errors.join(" ").to_s
    end
  end
end


text:
[#]: collector: (lujun9972)
[#]: translator: ( )
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (Game Review: Steel Rats is an Enjoyable Bike-Combat Game)
[#]: via: (https://itsfoss.com/steel-rats)
[#]: author: (Ankush Das https://itsfoss.com/author/ankush/)

Game Review: Steel Rats is an Enjoyable Bike-Combat Game
======

Steel Rats is a quite impressive 2.5D motorbike combat game with exciting stunts involved. It was already available for Windows on [Steam][1] – however, recently it has been made available for Linux and Mac as well.

In case you didn't know, you can easily [install Steam on Ubuntu][2] or other distributions and [enable Steam Play feature to run some Windows games on Linux][3].

So, in this article, we shall take a look at what the game is all about and if it is a good purchase for you.

This game is neither free nor open source. We have covered it here because the game developers made an effort to port it to Linux.

### Story Overview

![steel rats][4]

You belong to a biker gang – " **Steel Rats** " – who stepped up to protect their city from alien robots invasion. The alien robots aren't just any tiny toys that you can easily defeat but with deadly weapons and abilities.

The games features the setting as an alternative version of 1940's USA – with the retro theme in place. You have to use your bike as the ultimate weapon to go against waves of alien robot and boss fights as well.

You will encounter 4 different characters with unique abilities to switch from after progressing through a couple of rounds.

You will start playing as " **Toshi** " and unlock other characters as you progress. **Toshi** is a genius and will be using a drone as his gadget to fight the alien robots. **James** – is the leader with the hammer attack as his special ability. **Lisa** would be the one utilizing fire to burn the junk robots. And, **Randall** will have his harpoon ready to destroy aerial robots with ease.

### Gameplay

![][5]

Honestly, I am not a fan of 2.5 D (or 2D games). But, games like [Unravel][6] will be the exception – which is still not available for Linux, such a shame – EA.

In this case, I did end up enjoying " **Steel Rats** " as one of the few 2D games I play.

There is really no rocket science for this game – you just have to get good with the controls. No matter whether you use a controller or a keyboard, it is definitely challenging to get comfortable with the controls.

You do not need to plan ahead in order to save your health or nitro boost because you will always have it when needed while also having checkpoints to resume your progress.

You just need to keep the right pace and the perfect jump while hitting every enemy to get the best score in the leader boards. Once you do that, the game ends up being an easy and fun experience.

If you're curious about the gameplay, we recommend watching this video:

<https://www.youtube.com/embed/e2RhSKjLKf0?enablejsapi=1&autoplay=0&cc_load_policy=0&iv_load_policy=1&loop=0&modestbranding=1&rel=0&showinfo=0&fs=1&playsinline=0&autohide=2&theme=dark&color=red&controls=2&?

### Performance & Visuals

![][7]

The graphics or visuals do matter in a game. Even though the minimum system requirements is not something to worry about, you should be good with a processor similar to or better than **Intel Core 2 Duo** coupled with **4 Gigs of RAM** at least and a dedicated GPU ( **GeForce GT 630 / Radeon HD 7570)**.

I tried it on my system with **i5-7400** coupled with **8 Gigs of RAM** and a **GTX 1050** graphics card on board. With the highest settings, the game worked smooth and looked visually good as well. Of course, we will avoid talking about the frames I got – because anything above **25-30 FPS** for this kind of game is perfectly fine.

However, I did encounter multiple crashes – so had to restart the game. Maybe the [Nvidia driver][8] was at fault? Maybe the fact that I'm using Elementary OS?

I'm not so sure why I had issues – but just a heads up for you. Once the game launches successfully without a crash, it works well without any hiccups.

### Final Verdict

While this may not be the most challenging game you've come across but it surely is a fun experience. Along with a good gameplay and visuals – the background theme music of the game is also very good.

The music actually sets up the mood of a gamer while playing this – so thought of pointing this out as well.

Depending on your region – you will find this game listed on Steam for either **19.99 USD** or **529 INR**.

Is it worth it? **Yes** , if you want a exciting and fun motorbike-action game in a 2.5D experience. **No** , if you want an extremely challenging 2D game in your library.

What do you think about the game? Let us know in the comments below.

--------------------------------------------------------------------------------

via: https://itsfoss.com/steel-rats

作者:[Ankush Das][a]
选题:[lujun9972][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)

本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出

[a]: https://itsfoss.com/author/ankush/
[b]: https://github.com/lujun9972
[1]: https://store.steampowered.com/app/619700/Steel_Rats/
[2]: https://itsfoss.com/install-steam-ubuntu-linux/
[3]: https://itsfoss.com/steam-play/
[4]: https://i0.wp.com/itsfoss.com/wp-content/uploads/2019/03/steel-rats-screenshot-1.jpg?fit=800%2C450&ssl=1
[5]: https://i0.wp.com/itsfoss.com/wp-content/uploads/2019/03/steel-rats-screenshot-2.jpg?fit=800%2C450&ssl=1
[6]: https://en.wikipedia.org/wiki/Unravel_(video_game)
[7]: https://i2.wp.com/itsfoss.com/wp-content/uploads/2019/03/steel-rats-screenshot-3.jpg?fit=800%2C450&ssl=1
[8]: https://itsfoss.com/install-additional-drivers-ubuntu/


text:
<?php

namespace AppBundle\Repository;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\ResultSetMapping;

/**
 * GangMembershipRepository
 */
class GangMembershipRepository extends EntityRepository
{
    public function getGangMembershipsForGang($gang)
    {
        $queryBuilder = $this->createQueryBuilder('gang_memberships');
        $queryBuilder
            ->join('gang_memberships.member', 'members')
            ->where('gang_memberships.gang = :gang')
            ->andWhere('gang_memberships.deletedAt IS NULL')
            ->andWhere('members.deletedAt IS NULL')
            ->setParameter('gang', $gang);

        return $queryBuilder->getQuery()->getResult();
    }

    public function isInGang($memberId, $gangId)
    {
        $queryBuilder = $this->createQueryBuilder('gang_memberships');
        $queryBuilder
            ->select('COUNT(gang_memberships)')
            ->where('gang_memberships.gang = :gangId')
            ->andWhere('gang_memberships.member = :memberId')
            ->andWhere('gang_memberships.deletedAt IS NULL')
            ->setParameter('gangId', $gangId)
            ->setParameter('memberId', $memberId)
        ;

        $result = $queryBuilder->getQuery()->getSingleScalarResult();

        return (Boolean)$result;
    }

    public function bothInSameGang($memberId, $targetMemberId)
    {
        $rsm = new ResultSetMapping();
        $query = $this->getEntityManager()->createNativeQuery('
            SELECT gm1.id
            FROM gang_memberships gm1
            WHERE
                gm1.member_id = ?
                AND gm1.deleted_at IS NULL
                AND gm1.gang_id IN (
                    SELECT gm2.gang_id
                    FROM gang_memberships gm2
                    WHERE gm2.member_id = ?
                    AND gm2.deleted_at IS NULL
                )
        ', $rsm);

        $query->setParameter(1, $memberId);
        $query->setParameter(2, $targetMemberId);

        $result = $query->getScalarResult();
        return count($result) > 0;
    }
}


text:
package net.kuujo.copycat.io.serializer.lang;

import net.kuujo.copycat.io.BufferInput;
import net.kuujo.copycat.io.BufferOutput;
import net.kuujo.copycat.io.serializer.Serializer;
import net.kuujo.copycat.io.serializer.TypeSerializer;

/**
 * Long serializer.
 *
 * @author Jordan Halterman
 */
public class LongSerializer implements TypeSerializer<Long> {

  @Override
  public void write(Long object, BufferOutput buffer, Serializer serializer) {
    buffer.writeLong(object);
  }

  @Override
  public Long read(Class<Long> type, BufferInput buffer, Serializer serializer) {
    return buffer.readLong();
  }

}


text:
#
#
# /* See http://www.boost.org for most recent version. */
#
# ifndef BOOST_PREPROCESSOR_REPETITION_DEDUCE_R_HPP
# define BOOST_PREPROCESSOR_REPETITION_DEDUCE_R_HPP
#
# include <boost/preprocessor/detail/auto_rec.hpp>
# include <boost/preprocessor/repetition/for.hpp>
#
# /* BOOST_PP_DEDUCE_R */
#
# define BOOST_PP_DEDUCE_R() BOOST_PP_AUTO_REC(BOOST_PP_FOR_P, 256)
#
# endif


text:
package com.google.clearsilver.jsilver.syntax;

import com.google.clearsilver.jsilver.autoescape.EscapeMode;
import com.google.clearsilver.jsilver.exceptions.JSilverBadSyntaxException;
import com.google.clearsilver.jsilver.exceptions.JSilverIOException;
import com.google.clearsilver.jsilver.syntax.lexer.Lexer;
import com.google.clearsilver.jsilver.syntax.lexer.LexerException;
import com.google.clearsilver.jsilver.syntax.node.Start;
import com.google.clearsilver.jsilver.syntax.node.Switch;
import com.google.clearsilver.jsilver.syntax.parser.Parser;
import com.google.clearsilver.jsilver.syntax.parser.ParserException;

import java.io.IOException;
import java.io.PushbackReader;
import java.io.Reader;
import java.util.Arrays;

/**
 * Parses a JSilver text template into an abstract syntax tree (AST).
 *

 * Acts as a facade around SableCC generated code. The simplest way to process the resulting tree is
 * to use a visitor by extending
 * {@link com.google.clearsilver.jsilver.syntax.analysis.DepthFirstAdapter} and passing it to
 * {@link Start#apply(com.google.clearsilver.jsilver.syntax.node.Switch)}.
 *

 *
Example:

 *
 *

 * SyntaxTreeBuilder builder = new SyntaxTreeBuilder();
 * Start tree = builder.parse(myTemplate, "some-template.cs");
 * // Dump out the tree
 * tree.apply(new SyntaxTreeDumper(System.out));
 *

 *
 */
public class SyntaxTreeBuilder {

  public SyntaxTreeBuilder() {}

  /**
   * Size of buffer in PushbackReader... needs to be large enough to parse CS opening tag and push
   * back if it is not valid. e.g. "<?csX" : not a tag, so pushback.
   */
  private static final int PUSHBACK_SIZE = "<?cs ".length();

  /**
   * Syntax tree optimizers, declared in the order they must be applied:
   *

   *
Type resultion makes the abstract tree concrete and must come first.
   *
Sequence optimization simplifies the tree and should come before most other optimizations.
   *
Inline rewriting to remove data nodes from 'inline' sections. This should come before any
   * optimization of variables.
   *
Var optimization simplifies complex var expressions and must come after both type
   * resolution and sequence optimization.
   *

   */
  protected final Switch typeResolver = new TypeResolver();
  protected final Switch sequenceOptimizer = new SequenceOptimizer();
  protected final Switch inlineRewriter = new InlineRewriter();
  protected final Switch varOptimizer = new VarOptimizer(Arrays.asList("html", "js", "url"));

  /**
   * Perform any additional processing on the tree. EscapeMode and templateName are required by
   * AutoEscaper.
   *
   * @param root The AST to post process.
   * @param escapeMode The escaping mode to apply to the given AST. If this is not
   *        EscapeMode.ESCAPE_NONE, AutoEscaper will be called on the AST.
   * @param templateName The name of template being processed. Passed to AutoEscaper, which uses it
   *        when displaying error messages.
   */
  protected void process(Start root, EscapeMode escapeMode, String templateName) {
    root.apply(typeResolver);
    root.apply(sequenceOptimizer);
    root.apply(inlineRewriter);
    // Temporarily disabled ('cos it doesn't quite work)
    // root.apply(varOptimizer);

    if (!escapeMode.equals(EscapeMode.ESCAPE_NONE)) {
      // AutoEscaper contains per-AST context like HTML parser object.
      // Therefore, instantiating a new AutoEscaper each time.
      root.apply(new AutoEscaper(escapeMode, templateName));
    }
  }

  /**
   * @param templateName Used for meaningful error messages.
   * @param escapeMode Run {@link AutoEscaper} on the abstract syntax tree created from template.
   */
  public TemplateSyntaxTree parse(Reader input, String templateName, EscapeMode escapeMode)
      throws JSilverIOException, JSilverBadSyntaxException {
    try {
      PushbackReader pushbackReader = new PushbackReader(input, PUSHBACK_SIZE);
      Lexer lexer = new Lexer(pushbackReader);
      Parser parser = new Parser(lexer);
      Start root = parser.parse();
      process(root, escapeMode, templateName);
      return new TemplateSyntaxTree(root);
    } catch (IOException exception) {
      throw new JSilverIOException(exception);
    } catch (ParserException exception) {
      throw new JSilverBadSyntaxException(exception.getMessage(), exception.getToken().getText(),
          templateName, exception.getToken().getLine(), exception.getToken().getPos(), exception);
    } catch (LexerException exception) {
      throw new JSilverBadSyntaxException(exception.getMessage(), null, templateName,
          JSilverBadSyntaxException.UNKNOWN_POSITION, JSilverBadSyntaxException.UNKNOWN_POSITION,
          exception);
    }
  }
}


text:
/**
 * Configuration options for tests
 */
//if (!process.env.TEST_FOO) throw new Error('Test foo must be configured in ENV.');

jasmine.DEFAULT_TIMEOUT_INTERVAL = 60000;

module.exports = {
    spinner: by.css('.spinner'),
    //user: process.env.TEST_FOO,
    timeout: 60000
};


text:
package org.llaith.toolkit.common.etc;

/**
 *
 */
public class OkFlag {

    private boolean ok = true;

    public boolean eval(final boolean in) {
        if (!in) this.ok = false;
        return in;
    }

    public boolean isOk() {
        return this.ok;
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
-->

<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
             http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
             version="2.1">

	<persistence-unit name="workflowEngineRegistry" transaction-type="RESOURCE_LOCAL">
		<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

		<class>krawczls.workflowEngineRegistry.WorkflowEngine
		</class>

		<properties>
			<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
			<property name="hibernate.connection.driver_class" value="org.postgresql.Driver"/>
			<property name="hibernate.connection.username" value="postgres"/>
        	<property name="hibernate.connection.password" value="ness26"/>
        	<property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/engines"/>
      		<property name="hibernate.hbm2ddl.auto" value="update"/>
      		<property name="hibernate.show_sql" value="false"/>
    	</properties>
	</persistence-unit>

</persistence>


text:
var later = require('../../index'),
    should = require('should');

describe('Later.array.prevInvalid', function() {

  it('should exist', function() {
    should.exist(later.array.prevInvalid);
  });

  it('should return the previous invalid value', function() {
    var arr = [1,2,5],
        extent = [1,5],
        cur = 5,
        expected = 4,
        actual = later.array.prevInvalid(cur, arr, extent);

    actual.should.eql(expected);
  });

  it('should return the previous invalid value when less than arr', function() {
    var arr = [2,3,5],
        extent = [1,10],
        cur = 3,
        expected = 1,
        actual = later.array.prevInvalid(cur, arr, extent);

    actual.should.eql(expected);
  });

  it('should return the previous invalid value when zero value is largest', function() {
    var arr = [1,2,5,0],
        extent = [1,31],
        cur = 31,
        expected = 30,
        actual = later.array.prevInvalid(cur, arr, extent);

    actual.should.eql(expected);
  });

  it('should return the previous invalid value when zero value is smallest', function() {
    var arr = [0,1,2,5,10],
        extent = [0,10],
        cur = 2,
        expected = 9,
        actual = later.array.prevInvalid(cur, arr, extent);

    actual.should.eql(expected);
  });

  it('should return the current value if it is invalid', function() {
    var arr = [0,1,2,5,10],
        extent = [0,10],
        cur = 4,
        expected = 4,
        actual = later.array.prevInvalid(cur, arr, extent);

    actual.should.eql(expected);
  });

  it('should return undefined if there is no invalid value', function() {
    var arr = [0,1,2,3,4,5],
        extent = [0,5],
        cur = 4;

    should.not.exist(later.array.prevInvalid(cur, arr, extent));
  });
});


text:
---
id: 587d824e367417b2b2512c57
title: Test if an Object is an Instance of a Constructor
challengeType: 2
forumTopicId: 301605
---

## Description

As a reminder, this project is being built upon the following starter project on Glitch, or cloned from GitHub.
#instanceOf asserts that an object is an instance of a constructor.

## Instructions

Use assert.instanceOf() or assert.notInstanceOf() to make the tests pass.

## Tests

```yml
tests:
  - text: All tests should pass.
    testString: getUserInput => $.get(getUserInput('url') + '/_api/get-tests?type=unit&n=17').then(data => { assert.equal(data.state,'passed'); }, xhr => { throw new Error(xhr.responseText); })
  - text: You should choose the right assertion - instanceOf vs. notInstanceOf.
    testString: getUserInput => $.get(getUserInput('url') + '/_api/get-tests?type=unit&n=17').then(data => { assert.equal(data.assertions[0].method, 'notInstanceOf', 'myCar is not an instance of Plane'); }, xhr => { throw new Error(xhr.responseText); })
  - text: You should choose the right assertion - instanceOf vs. notInstanceOf.
    testString: getUserInput => $.get(getUserInput('url') + '/_api/get-tests?type=unit&n=17').then(data => { assert.equal(data.assertions[1].method, 'instanceOf', 'airlinePlane is an instance of Plane'); }, xhr => { throw new Error(xhr.responseText); })
  - text: You should choose the right assertion - instanceOf vs. notInstanceOf.
    testString: getUserInput => $.get(getUserInput('url') + '/_api/get-tests?type=unit&n=17').then(data => { assert.equal(data.assertions[2].method, 'instanceOf', 'everything is an Object in JavaScript...'); }, xhr => { throw new Error(xhr.responseText); })
  - text: You should choose the right assertion - instanceOf vs. notInstanceOf.
    testString: getUserInput => $.get(getUserInput('url') + '/_api/get-tests?type=unit&n=17').then(data => { assert.equal(data.assertions[3].method, 'notInstanceOf', 'myCar.wheels is not an instance of String'); }, xhr => { throw new Error(xhr.responseText); })

```

## Challenge Seed

## Solution

```js
/**
  Backend challenges don't need solutions,
  because they would need to be tested against a full working project.
  Please check our contributing guidelines to learn more.
*/
```


text:
package org.apache.abdera.model;

import org.apache.abdera.i18n.iri.IRI;
import org.apache.abdera.i18n.iri.IRISyntaxException;

/**
 * <p>
 * The IRI interface provides a common base for a set of feed and entry elements whose content value must be a valid
 * IRI/URI reference. These include the elements atom:icon, atom:logo, and atom:id.
 * </p>
 */
public interface IRIElement extends Element {

    /**
     * Returns the value of the element as a java.net.URI
     *
     * @return The IRI value of this element
     */
    IRI getValue();

    /**
     * Sets the value of the element
     *
     * @param iri The iri value
     * @throws IRISyntaxException if the value is malformed
     */
    IRIElement setValue(String iri);

    /**
     * Set the value of this element using the normalization as specified in RFC4287
     *
     * @param iri A non-normalized IRI
     * @throws IRISyntaxException if the iri is malformed
     */
    IRIElement setNormalizedValue(String iri);

    /**
     * Returns the value of the element resolved against the current in-scope Base URI
     *
     * @return The resolved IRI value
     */
    IRI getResolvedValue();

}


text:
<?php
// +----------------------------------------------------------------------+
// | PHP version 5                                                        |
// +----------------------------------------------------------------------+
// | Copyright (c) 2002-2006 James Heinrich, Allan Hansen                 |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2 of the GPL license,         |
// | that is bundled with this package in the file license.txt and is     |
// | available through the world-wide-web at the following url:           |
// | http://www.gnu.org/copyleft/gpl.html                                 |
// +----------------------------------------------------------------------+
// | getID3() - http://getid3.sourceforge.net or http://www.getid3.org    |
// +----------------------------------------------------------------------+
// | Authors: James Heinrich <infoØgetid3*org>                            |
// |          Allan Hansen <ahØartemis*dk>                                |
// +----------------------------------------------------------------------+
// | write.apetag.php                                                     |
// | writing module for ape tags                                          |
// | dependencies: module.tag.apetag.php                                  |
// | dependencies: module.tag.id3v1.php                                   |
// | dependencies: module.tag.lyrics3.php                                 |
// +----------------------------------------------------------------------+
//
// $Id: write.apetag.php,v 1.9 2006/11/20 16:13:31 ah Exp $

class getid3_write_apetag extends getid3_handler_write
{

    public $comments;

    public function read() {

        $engine = new getid3;
        $engine->filename = $this->filename;
        $engine->fp = fopen($this->filename, 'rb');
        $engine->include_module('tag.apetag');

        $tag = new getid3_apetag($engine);
        $tag->Analyze();

        if (!isset($engine->info['ape']['comments'])) {
            return;
        }

        $this->comments = $engine->info['ape']['comments'];

        // convert single element arrays to string
        foreach ($this->comments as $key => $value) {
            if (sizeof($value) == 1) {
                $this->comments[$key] = $value[0];
            }
        }

        return true;
    }

    public function write() {

        // remove existing apetag
        $this->remove();

        $engine = new getid3;
        $engine->filename = $this->filename;
        $engine->fp = fopen($this->filename, 'rb');
        $engine->include_module('tag.id3v1');
        $engine->include_module('tag.lyrics3');

        $tag = new getid3_id3v1($engine);
        $tag->Analyze();

        $tag = new getid3_lyrics3($engine);
        $tag->Analyze();

        $apetag = $this->generate_tag();

        if (!$fp = @fopen($this->filename, 'a+b')) {
            throw new getid3_exception('Could not open a+b: ' . $this->filename);
        }

        // init: audio ends at eof
        $post_audio_offset = filesize($this->filename);

        // lyrics3 tag present
        if (@$engine->info['lyrics3']['tag_offset_start']) {

            // audio ends before lyrics3 tag
            $post_audio_offset = @$engine->info['lyrics3']['tag_offset_start'];
        }

        // id3v1 tag present
        elseif (@$engine->info['id3v1']['tag_offset_start']) {

            // audio ends before id3v1 tag
            $post_audio_offset = $engine->info['id3v1']['tag_offset_start'];
        }

        // seek to end of audio data
        fseek($fp, $post_audio_offset, SEEK_SET);

        // save data after audio data
        $post_audio_data = '';
        if (filesize($this->filename) > $post_audio_offset) {
            $post_audio_data = fread($fp, filesize($this->filename) - $post_audio_offset);
        }

        // truncate file before start of new apetag
        fseek($fp, $post_audio_offset, SEEK_SET);
        ftruncate($fp, ftell($fp));

        // write new apetag
        fwrite($fp, $apetag, strlen($apetag));

        // rewrite data after audio
        if (!empty($post_audio_data)) {
            fwrite($fp, $post_audio_data, strlen($post_audio_data));
        }

        fclose($fp);
        clearstatcache();

        return true;
    }

    public function remove() {

        $engine = new getid3;
        $engine->filename = $this->filename;
        $engine->fp = fopen($this->filename, 'rb');
        $engine->include_module('tag.apetag');

        $tag = new getid3_apetag($engine);
        $tag->Analyze();

        if (isset($engine->info['ape']['tag_offset_start']) && isset($engine->info['ape']['tag_offset_end'])) {

            if (!$fp = @fopen($this->filename, 'a+b')) {
                throw new getid3_exception('Could not open a+b: ' . $this->filename);
            }

            // get data after apetag
            if (filesize($this->filename) > $engine->info['ape']['tag_offset_end']) {
                fseek($fp, $engine->info['ape']['tag_offset_end'], SEEK_SET);
                $data_after_ape = fread($fp, filesize($this->filename) - $engine->info['ape']['tag_offset_end']);
            }

            // truncate file before start of apetag
            ftruncate($fp, $engine->info['ape']['tag_offset_start']);

            // rewrite data after apetag
            if (isset($data_after_ape)) {
                fseek($fp, $engine->info['ape']['tag_offset_start'], SEEK_SET);
                fwrite($fp, $data_after_ape, strlen($data_after_ape));
            }

            fclose($fp);
            clearstatcache();
        }

        // success when removing non-existant tag
        return true;
    }

    protected function generate_tag() {

        // NOTE: All data passed to this function must be UTF-8 format

        $items = array();
        if (!is_array($this->comments)) {
            throw new getid3_exception('Cannot write empty tag, use remove() instead.');
        }

        foreach ($this->comments as $key => $values) {

            // http://www.personal.uni-jena.de/~pfk/mpp/sv8/apekey.html
            // A case-insensitive vobiscomment field name that may consist of ASCII 0x20 through 0x7E.
            // ASCII 0x41 through 0x5A  inclusive (A-Z) is to be considered equivalent to ASCII 0x61 through 0x7A inclusive (a-z).
            if (preg_match("/[^\x20-\x7E]/", $key)) {
                throw new getid3_exception('Field name "' . $key . '" contains invalid character(s).');
            }

            $key = strtolower($key);

            // convert single value comment to array
            if (!is_array($values)) {
                $values = array ($values);
            }

            $value_array = array ();
            foreach ($values as $value) {
                $value_array[] = str_replace("\x00", '', $value);
            }
            $value_string = implode("\x00", $value_array);

            // length of the assigned value in bytes
            $tag_item  = getid3_lib::LittleEndian2String(strlen($value_string), 4);

            $tag_item .= "\x00\x00\x00\x00" . $key . "\x00" . $value_string;

            $items[] = $tag_item;
        }

        return $this->generate_header_footer($items, true) . implode('', $items) . $this->generate_header_footer($items, false);
    }

    protected function generate_header_footer(&$items, $is_header=false) {

        $comments_length = 0;
        foreach ($items as $item_data) {
            $comments_length += strlen($item_data);
        }

        $header  = 'APETAGEX';
        $header .= getid3_lib::LittleEndian2String(2000, 4);
        $header .= getid3_lib::LittleEndian2String(32 + $comments_length, 4);
        $header .= getid3_lib::LittleEndian2String(count($items), 4);
        $header .= $this->generate_flags(true, true, $is_header, 0, false);
        $header .= str_repeat("\x00", 8);

        return $header;
    }

    protected function generate_flags($header=true, $footer=true, $is_header=false, $encoding_id=0, $read_only=false) {

        $flags = array_fill(0, 4, 0);

        // Tag contains a header
        if ($header) {
            $flags[0] |= 0x80;
        }

        // Tag contains no footer
        if (!$footer) {
            $flags[0] |= 0x40;
        }

        // This is the header, not the footer
        if ($is_header) {
            $flags[0] |= 0x20;
        }

        // 0: Item contains text information coded in UTF-8
        // 1: Item contains binary information °)
        // 2: Item is a locator of external stored information °°)
        // 3: reserved
        $flags[3] |= ($encoding_id << 1);

        // Tag or Item is Read Only
        if ($read_only) {
            $flags[3] |= 0x01;
        }

        return chr($flags[3]).chr($flags[2]).chr($flags[1]).chr($flags[0]);
    }

}

?>