text:
package org.lastaflute.taglib.html;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;

import org.dbflute.optional.OptionalThingFunction;
import org.lastaflute.taglib.base.BaseNonBodyTag;
import org.lastaflute.taglib.base.TaglibAttributeKey;
import org.lastaflute.web.LastaWebKey;
import org.lastaflute.web.ruts.config.ActionMapping;
import org.lastaflute.web.ruts.config.ModuleConfig;
import org.lastaflute.web.servlet.session.SessionManager;
import org.lastaflute.web.token.DoubleSubmitTokenMap;
import org.lastaflute.web.util.LaActionRuntimeUtil;

/**
 * Split as basic form tag and mapping form tag, so see also MappingHtmlFormTag.
 * @author modified by jflute (originated in Struts)
 */
public abstract class HtmlFormTag extends BaseNonBodyTag {

    // ===================================================================================
    //                                                                          Definition
    //                                                                          ==========
    private static final long serialVersionUID = 1L;
    protected static final String lineEnd = "\n";

    // ===================================================================================
    //                                                                           Attribute
    //                                                                           =========
    protected String action;
    protected ModuleConfig moduleConfig;
    protected String enctype;
    protected String focus = null;
    protected String focusIndex = null;
    protected ActionMapping mapping = null;
    protected String method = null;
    protected String onreset = null;
    protected String onsubmit = null;
    protected boolean scriptLanguage = true;
    protected String style = null;
    protected String styleClass = null;
    protected String styleId = null;
    protected String target = null;
    protected String beanName; // is form key, initialized at lookup()
    protected String acceptCharset = null;
    private boolean disabled = false;
    protected boolean readonly = false;

    // ===================================================================================
    //                                                                           Start Tag
    //                                                                           =========
    @Override
    public int doStartTag() throws JspException {
        lookup();

        final StringBuilder sb = new StringBuilder();
        sb.append(renderFormStartElement());
        sb.append(renderToken());
        write(sb.toString());

        pageContext.setAttribute(TaglibAttributeKey.FORM_KEY, this, PageContext.REQUEST_SCOPE);

        initFormBean();
        return EVAL_BODY_INCLUDE;
    }

    protected abstract void lookup() throws JspException;

    protected abstract void initFormBean() throws JspException;

    protected String renderFormStartElement() {
        final StringBuilder sb = new StringBuilder("<form");
        renderName(sb);
        renderAttribute(sb, "method", getMethod() == null ? "post" : getMethod());
        renderAction(sb);
        renderAttribute(sb, "accept-charset", getAcceptCharset());
        renderAttribute(sb, "class", getStyleClass());
        renderAttribute(sb, "enctype", getEnctype());
        renderAttribute(sb, "onreset", getOnreset());
        renderAttribute(sb, "onsubmit", getOnsubmit());
        renderAttribute(sb, "style", getStyle());
        renderAttribute(sb, "target", getTarget());
        renderOtherAttributes(sb);
        sb.append(">"); // HTML5 style
        return sb.toString();
    }

    protected void renderName(StringBuilder sb) {
        renderAttribute(sb, "name", beanName);
        renderAttribute(sb, "id", getStyleId());
    }

    protected abstract void renderAction(StringBuilder sb);

    protected void renderOtherAttributes(StringBuilder s) {
    }

    protected String renderToken() {
        final String tokenKey = LastaWebKey.TRANSACTION_TOKEN_KEY;
        final SessionManager manager = getRequestManager().getSessionManager();
        return manager.getAttribute(tokenKey, DoubleSubmitTokenMap.class).map(new OptionalThingFunction<DoubleSubmitTokenMap, String>() {
            @Override
            public String apply(DoubleSubmitTokenMap tokenMap) {
                final Class<?> actionType = LaActionRuntimeUtil.getActionRuntime().getActionType();
                return tokenMap.get(actionType).map(new OptionalThingFunction<String, String>() {
                    @Override
                    public String apply(String token) {
                        final StringBuilder sb = new StringBuilder();
                        sb.append("
<input type=\"hidden\" name=\"").append(tokenKey);
                        sb.append("\" value=\"").append(token).append("\">").append("
");
                        return sb.toString();
                    }
                }).orElse("");
            }
        }).orElse("");
    }

    protected void renderAttribute(StringBuilder sb, String attribute, String value) {
        if (value != null) {
            sb.append(" ").append(attribute).append("=\"").append(value).append("\"");
        }
    }

    // ===================================================================================
    //                                                                             End Tag
    //                                                                             =======
    @Override
    public int doEndTag() throws JspException {
        pageContext.removeAttribute(TaglibAttributeKey.BEAN_KEY, PageContext.REQUEST_SCOPE);
        pageContext.removeAttribute(TaglibAttributeKey.FORM_KEY, PageContext.REQUEST_SCOPE);

        final StringBuilder sb = new StringBuilder("</form>");
        if (focus != null) {
            sb.append(renderFocusJavascript());
        }
        write(sb.toString());
        return EVAL_PAGE;
    }

    protected String renderFocusJavascript() {
        final StringBuilder results = new StringBuilder();
        results.append(lineEnd);
        results.append("");
        results.append(lineEnd);
        return results.toString();
    }

    // ===================================================================================
    //                                                                       Enhance Logic
    //                                                                       =============
    @Override
    protected String buildErrorIdentity() {
        return "action=" + action + " method=" + method;
    }

    // ===================================================================================
    //                                                                             Release
    //                                                                             =======
    @Override
    public void release() {
        super.release();
        action = null;
        moduleConfig = null;
        enctype = null;
        disabled = false;
        focus = null;
        focusIndex = null;
        mapping = null;
        method = null;
        onreset = null;
        onsubmit = null;
        readonly = false;
        style = null;
        styleClass = null;
        styleId = null;
        target = null;
        acceptCharset = null;
    }

    // ===================================================================================
    //                                                                            Accessor
    //                                                                            ========
    public String getBeanName() {
        return beanName;
    }

    public String getAction() {
        return action;
    }

    public void setAction(String action) {
        this.action = action;
    }

    public String getEnctype() {
        return enctype;
    }

    public void setEnctype(String enctype) {
        this.enctype = enctype;
    }

    public String getFocus() {
        return focus;
    }

    public void setFocus(String focus) {
        this.focus = focus;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getOnreset() {
        return onreset;
    }

    public void setOnreset(String onReset) {
        this.onreset = onReset;
    }

    public String getOnsubmit() {
        return onsubmit;
    }

    public void setOnsubmit(String onSubmit) {
        this.onsubmit = onSubmit;
    }

    public String getStyle() {
        return style;
    }

    public void setStyle(String style) {
        this.style = style;
    }

    public String getStyleClass() {
        return styleClass;
    }

    public void setStyleClass(String styleClass) {
        this.styleClass = styleClass;
    }

    public String getStyleId() {
        return styleId;
    }

    public void setStyleId(String styleId) {
        this.styleId = styleId;
    }

    public String getTarget() {
        return target;
    }

    public void setTarget(String target) {
        this.target = target;
    }

    public String getAcceptCharset() {
        return acceptCharset;
    }

    public void setAcceptCharset(String acceptCharset) {
        this.acceptCharset = acceptCharset;
    }

    public void setDisabled(boolean disabled) {
        this.disabled = disabled;
    }

    public boolean isDisabled() {
        return disabled;
    }

    public void setReadonly(boolean readonly) {
        this.readonly = readonly;
    }

    public boolean isReadonly() {
        return readonly;
    }

    public String getFocusIndex() {
        return focusIndex;
    }

    public void setFocusIndex(String focusIndex) {
        this.focusIndex = focusIndex;
    }

    public boolean getScriptLanguage() {
        return scriptLanguage;
    }

    public void setScriptLanguage(boolean scriptLanguage) {
        this.scriptLanguage = scriptLanguage;
    }
}


text:
package com.demigodsrpg.chitchat;

import com.google.gson.GsonBuilder;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

public class PrivateMessage implements Serializable {
    // -- SERIAL VERSION UID -- //

    public static final long serialVersionUID = 1L;

    // -- TRANSIENT DATA -- //

    private final transient Chitchat INST;

    // -- META DATA -- //

    private String target;
    private String sender;
    private String message;

    // -- CONSTRUCTORS -- //

    @SuppressWarnings("unchecked")
    public PrivateMessage(Chitchat inst, String json) {
        INST = inst;
        Map<String, Object> map = new GsonBuilder().create().fromJson(json, Map.class);
        target = map.get("target").toString();
        sender = map.get("sender").toString();
        message = map.get("message").toString();
    }

    public PrivateMessage(Chitchat inst, String target, String sender, String message) {
        INST = inst;
        this.target = target;
        this.sender = sender;
        this.message = message;
    }

    // -- GETTERS -- //

    public String getTarget() {
        return target;
    }

    public String getSender() {
        return sender;
    }

    public String getMessage() {
        return message;
    }

    public String getFormattedMessage(boolean out) {
        return ChatColor.DARK_GRAY + "PM" + (out ? " to" : " from") + " <" + ChatColor.DARK_AQUA +
                (out ? target : sender) + ChatColor.DARK_GRAY + ">: " + ChatColor.GRAY + message;
    }

    public String getLogMessage() {
        return "PM <" + sender + " to " + target + ">: " + message;
    }

    public String toJson() {
        Map<String, Object> map = new HashMap<>();
        map.put("target", target);
        map.put("sender", sender);
        map.put("message", message);
        return new GsonBuilder().create().toJson(map, Map.class);
    }

    // -- SEND -- //

    public void send() {
        // Get the sender
        OfflinePlayer sender = Bukkit.getOfflinePlayer(this.sender);

        // Check if the player is on this server
        if (Bukkit.getPlayer(target) != null) {
            Bukkit.getPlayer(target).sendMessage(getFormattedMessage(false));
            Chitchat.getInst().getLogger().info(getLogMessage());
        } else if (Chitchat.getInst().USE_REDIS) {
            // Nope, send through redis
            RChitchat.REDIS_MSG.publishAsync(toJson());
        } else if (sender.isOnline()) {
            // Something went wrong
            sender.getPlayer().sendMessage(ChatColor.RED + "There was an error sending a private message.");
            return;
        }

        // Send the 'sent' message
        if (sender.isOnline()) {
            sender.getPlayer().sendMessage(getFormattedMessage(true));
        }

        // Add to the reply map
        INST.getReplyMap().put(this.sender, this.target);
        INST.getReplyMap().put(this.target, this.sender);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace common\models;

use common\components\Emailer;
use Sil\EmailService\Client\EmailServiceClient;
use yii\base\Model;
use yii\helpers\ArrayHelper;
use yii\web\ServerErrorHttpException;

class Verification extends Model
{
    const TYPE_EMAIL = 'email';
    const TYPE_PHONE = 'phone';

    /**
     * Send email for verification
     * @param string $toAddress
     * @param string $subject
     * @param string $view Full view path with alias, ex: @common/mail/reset/self
     * @param string $code
     * @param string $expireTime
     * @param User $forUser
     * @param null|string $ccAddress
     * @param null|integer $eventLogUserId
     * @param null|string $eventLogTopic
     * @param null|string $eventLogDetails
     * @param array $additionalEmailParameters
     * @throws ServerErrorHttpException
     */
    public static function sendEmail(
        $toAddress,
        $subject,
        $view,
        $code,
        $expireTime,
        $forUser,
        $ccAddress = null,
        $eventLogUserId = null,
        $eventLogTopic = null,
        $eventLogDetails = null,
        $additionalEmailParameters = []
    ) {

        $parameters = ArrayHelper::merge(
            [
                'idpDisplayName' => \Yii::$app->params['idpDisplayName'],
                'name' => $forUser->first_name,
                'code' => $code,
                'expireTime' => $expireTime,
                'toAddress' => $toAddress,
                'helpCenterUrl' => \Yii::$app->params['helpCenterUrl'],
                'supportName' => \Yii::$app->params['support']['name'],
                'supportEmail' => \Yii::$app->params['support']['email'],
                'emailSignature' => \Yii::$app->params['emailSignature'],
            ],
            $additionalEmailParameters
        );

        $body = \Yii::$app->view->render(
            $view,
            $parameters
        );

        /* @var $emailer Emailer */
        $emailer = \Yii::$app->emailer;
        $emailer->email($toAddress, $subject, $body, strip_tags($body), $ccAddress);

        if ($eventLogTopic !== null && $eventLogDetails !== null && $eventLogUserId !== null) {
            EventLog::log($eventLogTopic, $eventLogDetails, $eventLogUserId);
        }
    }

    /**
     * Check if user submitted code matches the code emailed to them
     * @param string $code
     * @param string $userProvided
     * @return bool
     */
    public static function isEmailCodeValid($code, $userProvided)
    {
        return strval($code) === strval($userProvided);
    }

}


text:
## Getting Started

###Installation

If you're using Xcode 6, Swifter can be installed by simply dragging the Swifter Xcode project into your own project and adding either the SwifteriOS or SwifterMac framework as an embedded framework.

###Usage

Instantiation with ACAccount:

`let swifter = Swifter(account: twitterAccount)`

Instantiation with OAuth:

`let swifter = Swifter(consumerKey: "", consumerSecret: "")`

OAuth Authorization:

	swifter.authorizeWithCallbackURL(callbackURL, success: {
		accessToken, response in

		// ...

		},
		failure: {

		// ...

		})

Get Home Timeline:

	swifter.getStatusesHomeTimelineWithCount(20, sinceID: nil, maxID: nil, trimUser: true, contributorDetails: false, includeEntities: true, success: {
		statuses, response in

		// ...

		}, failure: {

		// ...

		})

Streaming API:

	swifter.getStatusesSampleDelimited(nil, stallWarnings: nil, progress: {
		statuses, response in

		// ...

		}, failure: {

		// ...

		})

Status Update:

	swifter.postStatusUpdate("Hello, world", inReplyToStatusID: nil, lat: nil, long: nil, placeID: nil, displayCoordinates: nil, trimUser: nil, success: {
		json, response in

		// ...

		}, failure: {

		// ...

		})

#License

Swifter is licensed under the MIT License. See the LICENSE file for more information.


text:
using System;

class CurrentDateAndTime
{
    static void Main()
    {
        DateTime now = DateTime.Now;
        Console.WriteLine(now);
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<TITLE
>Variant Comparison Files</TITLE
><META
NAME="GENERATOR"
CONTENT="Modular DocBook HTML Stylesheet Version 1.79"><LINK
REV="MADE"
HREF="mailto:pgsql-docs@postgresql.org"><LINK
REL="HOME"
TITLE="PostgreSQL 9.6.2 Documentation"
HREF="index.html"><LINK
REL="UP"
TITLE="Regression Tests"
HREF="regress.html"><LINK
REL="PREVIOUS"
TITLE="Test Evaluation"
HREF="regress-evaluation.html"><LINK
REL="NEXT"
TITLE="TAP Tests"
HREF="regress-tap.html"><LINK
REL="STYLESHEET"
TYPE="text/css"
HREF="stylesheet.css"><META
HTTP-EQUIV="Content-Type"
CONTENT="text/html; charset=ISO-8859-1"><META
NAME="creation"
CONTENT="2017-02-06T21:56:32">

PostgreSQL 9.6.2 Documentation

Prev	Up	Chapter 31. Regression Tests	Next

31.3. Variant Comparison Files

    Since some of the tests inherently produce environment-dependent
    results, we have provided ways to specify alternate "expected"
    result files.  Each regression test can have several comparison files
    showing possible results on different platforms.  There are two
    independent mechanisms for determining which comparison file is used
    for each test.

    The first mechanism allows comparison files to be selected for
    specific platforms.  There is a mapping file,
    <TT
CLASS="FILENAME"
>src/test/regress/resultmap</TT
>, that defines
    which comparison file to use for each platform.
    To eliminate bogus test "failures" for a particular platform,
    you first choose or make a variant result file, and then add a line to the
    <TT
CLASS="FILENAME"
>resultmap</TT
> file.

    Each line in the mapping file is of the form

testname:output:platformpattern=comparisonfilename

    The test name is just the name of the particular regression test
    module. The output value indicates which output file to check. For the
    standard regression tests, this is always <TT
CLASS="LITERAL"
>out</TT
>. The
    value corresponds to the file extension of the output file.
    The platform pattern is a pattern in the style of the Unix
    tool <TT
CLASS="COMMAND"
>expr</TT
> (that is, a regular expression with an implicit
    <TT
CLASS="LITERAL"
>^</TT
> anchor at the start).  It is matched against the
    platform name as printed by <TT
CLASS="COMMAND"
>config.guess</TT
>.
    The comparison file name is the base name of the substitute result
    comparison file.

    For example: some systems interpret very small floating-point values
    as zero, rather than reporting an underflow error.  This causes a
    few differences in the <TT
CLASS="FILENAME"
>float8</TT
> regression test.
    Therefore, we provide a variant comparison file,
    <TT
CLASS="FILENAME"
>float8-small-is-zero.out</TT
>, which includes
    the results to be expected on these systems.  To silence the bogus
    "failure" message on OpenBSD
    platforms, <TT
CLASS="FILENAME"
>resultmap</TT
> includes:

float8:out:i.86-.*-openbsd=float8-small-is-zero.out

    which will trigger on any machine where the output of
    <TT
CLASS="COMMAND"
>config.guess</TT
> matches <TT
CLASS="LITERAL"
>i.86-.*-openbsd</TT
>.
    Other lines
    in <TT
CLASS="FILENAME"
>resultmap</TT
> select the variant comparison file for other
    platforms where it's appropriate.

    The second selection mechanism for variant comparison files is
    much more automatic: it simply uses the "best match" among
    several supplied comparison files.  The regression test driver
    script considers both the standard comparison file for a test,
    <TT
CLASS="LITERAL"
><TT
CLASS="REPLACEABLE"
>testname</TT
>.out</TT
>, and variant files named
    <TT
CLASS="LITERAL"
><TT
CLASS="REPLACEABLE"
>testname</TT
>_<TT
CLASS="REPLACEABLE"
>digit</TT
>.out</TT
>
    (where the <TT
CLASS="REPLACEABLE"
>digit</TT
> is any single digit
    <TT
CLASS="LITERAL"
>0</TT
>-<TT
CLASS="LITERAL"
>9</TT
>).  If any such file is an exact match,
    the test is considered to pass; otherwise, the one that generates
    the shortest diff is used to create the failure report.  (If
    <TT
CLASS="FILENAME"
>resultmap</TT
> includes an entry for the particular
    test, then the base <TT
CLASS="REPLACEABLE"
>testname</TT
> is the substitute
    name given in <TT
CLASS="FILENAME"
>resultmap</TT
>.)

    For example, for the <TT
CLASS="LITERAL"
>char</TT
> test, the comparison file
    <TT
CLASS="FILENAME"
>char.out</TT
> contains results that are expected
    in the <TT
CLASS="LITERAL"
>C</TT
> and <TT
CLASS="LITERAL"
>POSIX</TT
> locales, while
    the file <TT
CLASS="FILENAME"
>char_1.out</TT
> contains results sorted as
    they appear in many other locales.

    The best-match mechanism was devised to cope with locale-dependent
    results, but it can be used in any situation where the test results
    cannot be predicted easily from the platform name alone.  A limitation of
    this mechanism is that the test driver cannot tell which variant is
    actually "correct" for the current environment; it will just pick
    the variant that seems to work best.  Therefore it is safest to use this
    mechanism only for variant results that you are willing to consider
    equally valid in all contexts.

Prev	Home	Next

Test Evaluation	Up	TAP Tests


text:
MPSig::SigScannerFileOpenException::SigScannerFileOpenException(const std::string& fileName) :
    std::runtime_error(std::string("Failed to open file ") + fileName)
{}


text:
package com.zeus.eclipsePlugin.zxtmview;

/**
 * Used to store a rule in local memory.
 */
public class RuleCopy
{
   private String name;
   private String rule;

   /**
    * Create a copy of the rule.
    * @param name The name of the rule.
    * @param rule The contents of the rule. This must be the RAW contents of the
    * rule, e.g. rule.getRawCode() and NOT rule.getCode().
    */
   public RuleCopy( String name, String rule )
   {
      super();
      this.name = name;
      this.rule = rule;
   }

   /**
    * Get the name of the rule stored in this class.
    * @return The name of the rule.
    */
   public String getName()
   {
      return name;
   }

   /**
    * Get the code of the stored rule
    * @return The rules code.
    */
   public String getContents()
   {
      return rule;
   }

}


text:
<?php

namespace skeeks\cms\shop\models;

use skeeks\cms\shop\models\queries\ShopCasheboxShiftQuery;
use yii\base\Exception;
use yii\db\Expression;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "shop_cashebox_shift".
 *
 * @property int           $id
 * @property int           $shop_cashebox_id
 * @property int|null      $created_by
 * @property int|null      $created_at
 * @property int|null      $closed_at
 * @property int|null      $closed_by
 * @property int           $shift_number
 *
 * @property ShopCashebox  $shopCashebox
 * @property ShopPayment[] $shopPayments
 * @property ShopOrder[]   $shopOrders
 * @property float         $totalCash
 */
class ShopCasheboxShift extends \skeeks\cms\base\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%shop_cashebox_shift}}';
    }

    public function init()
    {
        $this->on(self::EVENT_BEFORE_UPDATE, [$this, "_beforeUpdate"]);
        $this->on(self::EVENT_BEFORE_INSERT, [$this, "_beforeInsert"]);

        return parent::init();
    }

    public function _beforeUpdate($e)
    {
        if ($this->isAttributeChanged("closed_at")) {
            $this->closed_by = \Yii::$app->user->id;
        }
    }

    public function _beforeInsert($e)
    {
        //Если смена уже открыта этим пользователем
        if (static::find()->cachebox($this->shopCashebox->id)->notClosed()->exists()) {
            throw new Exception("Смена на кассе уже открыта! Возможно в ней работает другой кассир!");
        }
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return ArrayHelper::merge(parent::rules(), [
            [['shop_cashebox_id'], 'required'],

            [['shop_cashebox_id', 'shift_number', 'created_by', 'created_at', 'closed_at', 'closed_by'], 'integer'],
            [['shop_cashebox_id'], 'exist', 'skipOnError' => true, 'targetClass' => ShopCashebox::className(), 'targetAttribute' => ['shop_cashebox_id' => 'id']],
            [
                ['created_by'],
                'default',
                'value' => function () {
                    return \Yii::$app->user->id;
                },
            ],

            [
                ['shift_number'],
                'default',
                'value' => function () {
                    $shopCasheboxShift = ShopCasheboxShift::find()->cachebox($this->shop_cashebox_id)->orderBy(['id' => SORT_DESC])->one();
                    if ($shopCasheboxShift) {
                        return $shopCasheboxShift->shift_number + 1;
                    } else {
                        return 1;
                    }
                },
            ],
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return ArrayHelper::merge(parent::attributeLabels(), [
            'id'               => 'ID',
            'shift_number'     => 'Смена',
            'shop_cashebox_id' => 'Касса',
            'created_by'       => 'Кассир',
            'created_at'       => 'Открыта',
            'closed_at'        => 'Закрыта',
            'closed_by'        => 'Закрыл смену',
        ]);
    }

    public function asText()
    {
        return "Смена #".$this->shift_number;
    }

    /**
     * Gets query for [[ShopCachebox]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getShopCashebox()
    {
        return $this->hasOne(ShopCashebox::class, ['id' => 'shop_cashebox_id']);
    }

    /**
     * @return \skeeks\cms\query\CmsActiveQuery|ShopStoreQuery
     */
    public static function find()
    {
        return new ShopCasheboxShiftQuery(get_called_class());
    }

    /**
     * Gets query for [[ShopCasheboxShifts]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getShopPayments()
    {
        return $this->hasMany(ShopPayment::className(), ['shop_cashebox_shift_id' => 'id']);
    }

    /**
     * Gets query for [[ShopCasheboxShifts]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getShopOrders()
    {
        return $this->hasMany(ShopOrder::className(), ['shop_cashebox_shift_id' => 'id']);
    }

    /**
     * Всего пришло наличных
     * @return float
     */
    public function getTotalCash()
    {
        $debit = $this->getShopPayments()->select(['sum' => new Expression("SUM(amount)")])->andWhere(['shop_store_payment_type' => ShopPayment::STORE_PAYMENT_TYPE_CASH])->andWhere(['is_debit' => 1])->asArray()->one();
        return (float)(ArrayHelper::getValue($debit, "sum"));
    }

    /**
     * Всего пришло по банку
     * @return float
     */
    public function getTotalCard()
    {
        $debit = $this->getShopPayments()->select(['sum' => new Expression("SUM(amount)")])->andWhere(['shop_store_payment_type' => ShopPayment::STORE_PAYMENT_TYPE_CARD])->andWhere(['is_debit' => 1])->asArray()->one();
        return (float)(ArrayHelper::getValue($debit, "sum"));
    }

    /**
     * Всего вернули по банку
     * @return float
     */
    public function getTotalReturnCard()
    {
        $debit = $this->getShopPayments()->select(['sum' => new Expression("SUM(amount)")])->andWhere(['shop_store_payment_type' => ShopPayment::STORE_PAYMENT_TYPE_CARD])->andWhere(['is_debit' => 0])->asArray()->one();
        return (float)(ArrayHelper::getValue($debit, "sum"));
    }

    /**
     * Всего вернули наличных
     * @return float
     */
    public function getTotalReturnCash()
    {
        $debit = $this->getShopPayments()->select(['sum' => new Expression("SUM(amount)")])->andWhere(['shop_store_payment_type' => ShopPayment::STORE_PAYMENT_TYPE_CASH])->andWhere(['is_debit' => 0])->asArray()->one();
        return (float)(ArrayHelper::getValue($debit, "sum"));
    }

    /**
     * @return float
     */
    public function getTotalBank()
    {
        $debit = $this->getShopPayments()->select(['sum' => new Expression("SUM(amount)")])->andWhere(['shop_store_payment_type' => ShopPayment::STORE_PAYMENT_TYPE_CASH])->andWhere(['is_debit' => 1])->asArray()->one();
        $creadit = $this->getShopPayments()->select(['sum' => new Expression("SUM(amount)")])->andWhere(['is_debit' => 0])->andWhere(['shop_store_payment_type' => ShopPayment::STORE_PAYMENT_TYPE_CASH])->asArray()->one();

        return (float)(ArrayHelper::getValue($debit, "sum") - ArrayHelper::getValue($creadit, "sum"));
    }

}


text:
using System;
using System.Data;
using System.Data.Common;
using System.Data.Entity.Infrastructure.Interception;
using System.Linq;

namespace Example.Infraestructure.Data
{
    /// <summary>
    ///
    /// </summary>
    public class UtcDbCommandInterceptor : DbCommandInterceptor
    {
        /// <inheritdoc />
        public override void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
        {
            ProcessParams(command.Parameters);

            base.NonQueryExecuting(command, interceptionContext);
        }

        /// <inheritdoc />
        public override void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
        {
            ProcessParams(command.Parameters);

            base.ReaderExecuted(command, interceptionContext);

            if (interceptionContext.Result != null && !(interceptionContext.Result is UtcDbDataReader))
            {
                interceptionContext.Result = new UtcDbDataReader(interceptionContext.Result);
            }
        }

        /// <inheritdoc />
        public override void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
        {
            ProcessParams(command.Parameters);

            base.ReaderExecuting(command, interceptionContext);
        }

        /// <inheritdoc />
        public override void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
        {
            ProcessParams(command.Parameters);

            base.ScalarExecuting(command, interceptionContext);
        }

        private void ProcessParams(DbParameterCollection parameters)
        {
            DbType[] dateTypes = new DbType[] {
                    DbType.DateTime,
                    DbType.DateTime2,
                    DbType.Date
                };

            foreach (DbParameter param in parameters)
            {
                if (param.Value != null && dateTypes.Any(x => x == param.DbType))
                {
                    DateTime date = (DateTime)param.Value;
                    param.Value = date.ToUniversalTime();
                }
            }
        }
    }
}


text:
<?php

namespace Parkcms\Admin\Dashboard;

use View;
use Sentry;

class Controller extends \Controller
{
    public function index()
    {
        return View::make('admin.dashboard')->with('user', Sentry::getUser());
    }
}


text:
<?php
	session_start();
	session_destroy();
	header("location:login-admin.php");
?>


text:
__author__ = 'amw'

from quicktest.Reporting import plot3d, plot2d, create_dataset, create_plot_matrix

# Initialise database config
db_config = {"hostname": "localhost", "port": "27017", "db_name": "simulations", "collection_name": "02-09-13"}

# Create plot
tag = "direct_null_020913"
x_param = "parameters.numPubSubs"
y_param = "parameters.numToSend_4"
z_param = "results.<Channel 4>: Latency - All nodes - Avgmean"
filter_list = [{"parameters.packetSize": "16B"},
               {"parameters.packetSize": "32B"},
               {"parameters.packetSize": "64B"},
               {"parameters.packetSize": "128B"},
               {"parameters.packetSize": "1024B"}
               ]
plot3d(db_config, tag, x_param, y_param, z_param, filter_list, 2, 3, "Direct Null: Average Latency to all nodes")

tag = "direct_null_020913"
x_param = "parameters.numPubSubs" # name of the x-parameter
y_param = "results.<Channel 4>: Latency - All nodes - Avgmean"

filter_list = [{"parameters.packetSize": "16B", "parameters.numToSend_4": "1"},
               {"parameters.packetSize": "16B", "parameters.numToSend_4": "3"},
               {"parameters.packetSize": "16B", "parameters.numToSend_4": "5"},
               {"parameters.packetSize": "16B", "parameters.numToSend_4": "7"},
               {"parameters.packetSize": "16B", "parameters.numToSend_4": "10"},
               {"parameters.packetSize": "16B", "parameters.numToSend_4": "15"},
               {"parameters.packetSize": "16B", "parameters.numToSend_4": "20"},
               {"parameters.packetSize": "16B", "parameters.numToSend_4": "30"}
               ]

# generate the 2d plots. the arguments "numCols" and "numRows" describe the layout of the resulting matrix of plots
plot2d(db_config, tag, x_param, y_param, filter_list, 3, 3, "Direct Null: Average Latency to all nodes")

y_param = "results.<Channel 4>: Latency - All nodes - Minmean"
plot2d(db_config, tag, x_param, y_param, filter_list, 3, 3, "Direct Null: Minimum Latency to all nodes")

y_param = "results.<Channel 4>: Latency - All nodes - Maxmean"
plot2d(db_config, tag, x_param, y_param, filter_list, 3, 3, "Direct Null; Maximum Latency to all nodes")


text:
#ifdef HAVE_CONFIG_H
#  include "config.h"
#endif

#include <string.h>
#include <locale.h>

#include "tools.h"

static void
have_type_handler (GstElement * typefind, guint probability,
    const GstCaps * caps, GstCaps ** p_caps)
{
  if (p_caps) {
    *p_caps = gst_caps_copy (caps);
  }
}

static void
typefind_file (const gchar * filename)
{
  GstStateChangeReturn sret;
  GstElement *pipeline;
  GstElement *source;
  GstElement *typefind;
  GstElement *fakesink;
  GstState state;
  GstCaps *caps = NULL;
  GDir *dir;

  if ((dir = g_dir_open (filename, 0, NULL))) {
    const gchar *entry;

    while ((entry = g_dir_read_name (dir))) {
      gchar *path;

      path = g_strconcat (filename, G_DIR_SEPARATOR_S, entry, NULL);
      typefind_file (path);
      g_free (path);
    }

    g_dir_close (dir);
    return;
  }

  pipeline = gst_pipeline_new ("pipeline");

  source = gst_element_factory_make ("filesrc", "source");
  g_assert (GST_IS_ELEMENT (source));
  typefind = gst_element_factory_make ("typefind", "typefind");
  g_assert (GST_IS_ELEMENT (typefind));
  fakesink = gst_element_factory_make ("fakesink", "fakesink");
  g_assert (GST_IS_ELEMENT (typefind));

  gst_bin_add_many (GST_BIN (pipeline), source, typefind, fakesink, NULL);
  gst_element_link_many (source, typefind, fakesink, NULL);

  g_signal_connect (G_OBJECT (typefind), "have-type",
      G_CALLBACK (have_type_handler), &caps);

  g_object_set (source, "location", filename, NULL);

  GST_DEBUG ("Starting typefinding for %s", filename);

  /* typefind will only commit to PAUSED if it actually finds a type;
   * otherwise the state change fails */
  gst_element_set_state (GST_ELEMENT (pipeline), GST_STATE_PAUSED);

  /* wait until state change either completes or fails */
  sret = gst_element_get_state (GST_ELEMENT (pipeline), &state, NULL, -1);

  switch (sret) {
    case GST_STATE_CHANGE_FAILURE:{
      GstMessage *msg;
      GstBus *bus;
      GError *err = NULL;

      bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline));
      msg = gst_bus_poll (bus, GST_MESSAGE_ERROR, 0);
      gst_object_unref (bus);

      if (msg) {
        gst_message_parse_error (msg, &err, NULL);
        g_printerr ("%s - FAILED: %s\n", filename, err->message);
        g_clear_error (&err);
        gst_message_unref (msg);
      } else {
        g_printerr ("%s - FAILED: unknown error\n", filename);
      }
      break;
    }
    case GST_STATE_CHANGE_SUCCESS:{
      if (caps) {
        gchar *caps_str;

        caps_str = gst_caps_to_string (caps);
        g_print ("%s - %s\n", filename, caps_str);
        g_free (caps_str);
        gst_caps_unref (caps);
      } else {
        g_print ("%s - %s\n", filename, "No type found");
      }
      break;
    }
    default:
      g_assert_not_reached ();
  }

  gst_element_set_state (pipeline, GST_STATE_NULL);
  gst_object_unref (pipeline);
}

int
main (int argc, char *argv[])
{
  gchar **filenames = NULL;
  guint num, i;
  GError *err = NULL;
  GOptionContext *ctx;
  GOptionEntry options[] = {
    GST_TOOLS_GOPTION_VERSION,
    {G_OPTION_REMAINING, 0, 0, G_OPTION_ARG_FILENAME_ARRAY, &filenames, NULL},
    {NULL}
  };

  setlocale (LC_ALL, "");

#ifdef ENABLE_NLS
  bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
  bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
  textdomain (GETTEXT_PACKAGE);
#endif

  g_set_prgname ("gst-typefind-" GST_API_VERSION);

  ctx = g_option_context_new ("FILES");
  g_option_context_add_main_entries (ctx, options, GETTEXT_PACKAGE);
  g_option_context_add_group (ctx, gst_init_get_option_group ());
  if (!g_option_context_parse (ctx, &argc, &argv, &err)) {
    g_print ("Error initializing: %s\n", GST_STR_NULL (err->message));
    g_clear_error (&err);
    g_option_context_free (ctx);
    exit (1);
  }
  g_option_context_free (ctx);

  gst_tools_print_version ();

  if (filenames == NULL || *filenames == NULL) {
    g_print ("Please give one or more filenames to %s\n\n", g_get_prgname ());
    return 1;
  }

  num = g_strv_length (filenames);

  for (i = 0; i < num; ++i) {
    typefind_file (filenames[i]);
  }

  g_strfreev (filenames);

  return 0;
}


text:
<template name="posts_list">

    {{> UI.dynamic template=postsListIncoming data=incoming}}

      {{#each postsCursor}}
        {{> UI.dynamic template=before_post_item}}
        {{> UI.dynamic template=post_item}}
        {{> UI.dynamic template=after_post_item}}
      {{/each}}

    {{> UI.dynamic template=postsLoadMore}}

</template>


text:
from JumpScale import j

# TODO: P2 S4 :eduard TextLineEditor tool does not work any more, is a
# pitty because ideal to parse config files on a filesystem (id:83)

class TextLineEditor:
    """
    represents a piece of text but broken appart in blocks/tokens
    this one works on a line basis
    """

    def __init__(self, text, path):
        self.lines = []
        self._higestblocknr = {}  # key is name of block, the value is the last used blocknr
        self.path = path
        for line in text.split("\n"):
            self.lines.append(LTLine(line))

    def getNrLines(self):
        return len(self.lines)

    def existsBlock(self, blockname):
        return blockname in self._higestblocknr

    def getBlockNames(self):
        return list(self._higestblocknr.keys())

    def matchBlocks(self, blockname, blockStartPatterns=[
                    '.*'], blockStartPatternsNegative=[], blockStopPatterns=[], blockStopPatternsNegative=[], blockfilter=""):
        """
        walk over blocks which are marked as matched and split blocks in more blocks depending criteria
        can be usefull to do this multiple times (sort of iterative) e.g. find class and then in class remove comments
        @param blockfilter will always match beginning of blockname e.g. can use userauth.sites  then change userauth.sites  will match all sites
        look for blocks starting with line which matches one of patterns in blockStartPatterns and not matching one of patterns in blockStartPatternsNegative
        block will stop when line found which matches one of patterns in blockStopPatterns and not in blockStopPatternsNegative or when next match for start is found
        example pattern: '^class ' looks for class at beginning of line with space behind

        """

        # check types of input
        if type(blockStartPatterns).__name__ != 'list' or type(blockStartPatternsNegative).__name__ != 'list' or type(blockStopPatterns).__name__ != 'list' \
                or type(blockStopPatternsNegative).__name__ != 'list':
            raise j.exceptions.RuntimeError(
                "Blockstartpatterns,blockStartPatternsNegative,blockStopPatterns,blockStopPatternsNegative has to be of type list")

        state = "scan"
        lines = self.lines
        line = ""
        for t in range(len(lines)):
            lineObject = lines[t]
            line = lineObject.line
            # print "\nPROCESS: %s,%s state:%s line:%s" % (t,len(lines)-1,state,line)
            emptyLine = line.strip() == ""

            if t == len(lines) - 1:
                # end of file
                if state == "foundblock":  # still in found block so add the last line
                    self._processLine(lineObject, blockname)  # add last line
                return

            if state == "foundblock" and j.tools.code.regex.matchMultiple(
                    blockStopPatterns, line) and not j.tools.code.regex.matchMultiple(blockStopPatternsNegative, line):
                # found end of block
                state = "scan"  # can continue to scan for next line
                self._processLine(lineObject, blockname)
                continue

            if state == "foundblock":  # still in found block so add the last line
                self._processLine(lineObject, blockname)  # add last line

            if j.tools.code.regex.matchMultiple(blockStartPatterns, line) and not j.tools.code.regex.matchMultiple(
                    blockStartPatternsNegative, line):
                # found beginning of block
                state = "foundblock"
                self._processLine(lineObject, blockname, next=True)

    def _processLine(self, lineObject, blockname, next=False):
        if lineObject.block == blockname:
            j.errorconditionhandler.raiseBug(
                message="Cannot find block with name %s in block which has already same name" % blo, category="lineeditor")
        lineObject.block = blockname
        if next:
            lineObject.blocknr = self.getNextBlockNr(blockname)
        else:
            lineObject.blocknr = self.getHighestBlockNr(blockname)

    def getNextBlockNr(self, name):
        if name not in self._higestblocknr:
            self._higestblocknr[name] = 1
        else:
            self._higestblocknr[name] += 1
        return self._higestblocknr[name]

    def getHighestBlockNr(self, name):
        if name not in self._higestblocknr:
            raise j.exceptions.RuntimeError("Cound not find block with name %s" % name)
        else:
            return self._higestblocknr[name]

    def appendBlock(self, text, blockname=""):
        """
        @param match means block was found and matching
        """
        blocknr = self.getNextBlockNr(blockname)
        for line in text.split("\n"):
            self.lines.append(LTLine(line, blockname, blocknr))

    def insertBlock(self, linenr, text, blockname="", blocknr=None):
        """
        block will be inserted at linenr, means line with linenr will be moved backwards
        """
        if blocknr is None:
            blocknr = self.getNextBlockNr(blockname)
        for line in text.split("\n").revert():
            self.lines.insert(linenr, LTLine(line, blockname, blocknr))

    def deleteBlock(self, blockname, blocknr=None):
        """
        mark block as not matching based on startline
        """
        if blocknr is None:
            if not self.existsBlock(blockname):
                return
        else:
            self.getBlock(blockname, blocknr)  # just to check if block exists
        if blocknr is None:
            self.lines = [line for line in self.lines if (line.block != blockname)]
        else:
            self.lines = [line for line in self.lines if (line.block != blockname and line.blocknr == blocknr)]

    def getBlock(self, blockname, blocknr):
        """
        get block based on startline
        """
        block = [line for line in self.lines if (line.block == blockname and line.blocknr == blocknr)]
        if len(block) == 0:
            raise j.exceptions.RuntimeError(
                "Cannot find block from text with blockname %s and blocknr %s" % (blockname, blocknr))
        return str.join(block)

    def replaceBlock(self, blockname, text, blocknr=1):
        """
        set block based on startline with new content
        """
        if text[-1] != "\n":
            text += "\n"
        state = "scan"
        lastBlockNameNr = ""
        linenr = 0
        nrlines = len(self.lines)
        x = 0
        lastx = 0
        while True:
            if x > nrlines - 1:
                break
            line = self.lines[x]
            # print "%s %s"%(x,line)
            if line.block == blockname and line.blocknr == blocknr:
                state = "found"
                lastBlockNameNr = "%s_%s" % (line.block, line.blocknr)
                self.lines.pop(x)
                x = x - 1
                nrlines = len(self.lines)
                lastx = x

            if state == "found" and lastBlockNameNr != lastBlockNameNr:
                # end of block
                break

            x = x + 1

        self.lines.append(None)

        x = lastx + 1
        text = text.rstrip()
        for line in text.split("\n"):
            self.lines.insert(x, LTLine(line, blockname, blocknr))
            x += 1

        self.lines = self.lines[:-1]

    def save(self):
        txt = "\n".join([item.line for item in self.lines])

        j.sal.fs.writeFile(filename=self.path, contents=txt)

    def getFirstLineNrForBlock(self, blockname, blocknr):
        for linenr in range(len(self.lines)):
            line = self.lines[linenr]
            if line.name == blockname and line.blocknr == blocknr:
                return linenr
        raise j.exceptions.RuntimeError("Could not find block with name %s and blocknr %s" % (blockname, blocknr))

    def addBlock(self, blockname, text):
        first = True
        for line in text.split("\n"):
            if first:
                self.lines.append(LTLine(line, blockname, self.getNextBlockNr(blockname)))
                first = False
            else:
                self.lines.append(LTLine(line, blockname, self.getHighestBlockNr(blockname)))

    def __repr__(self):
        return self.__str__()

    def __str__(self):
        if len(self.lines) > 0:
            return "".join([str(block) for block in self.lines])
        else:
            return ""

class LTLine:

    def __init__(self, line, blockname="", blocknr=0):
        """
        @param no blockname means ignore
        """
        self.block = blockname
        self.line = line
        self.blocknr = blocknr

    def __repr__(self):
        return self.__str__()

    def __str__(self):
        if self.block != "":
            text = "+ %s %s: %s\n" % (self.block, self.blocknr, self.line)
            return text
        else:
            text = "- %s\n" % (self.line)
            return text


text:
 <!--

 	Manuel Treutlein

 	Auf diese Seite wird nach der Datenverwaltung weitergeleitet. Neue Daten werden verwaltet.
 	Mit Ajax könnte man das ändern von Daten auf der Seite dataAdministration.php sichtbar machen.

  -->
<?php
	include_once 'User.php';
	include_once 'Security.php';
	session_start();
	$user = $_SESSION['user'];
	$sec = new Security();

	$new_email 						= $sec->safeEscape($_POST["new_email"]);
	$new_grade 						= $_POST["new_grade"];
//	$new_school 					= $_POST[""];

	$new_search 					= $_POST["new_search"];
	$new_searchSubject_weekday 		= $_POST["sucheFaecher_new_weekday"];
	$new_searchSubject_hoursPerWeek = $_POST["sucheFaecher_new_hoursPerWeek"];

	$new_offer 						= $_POST["new_offer"];
	$new_giveSubject_weekday 		= $_POST["gebeFaecher_new_weekday"];
	$new_giveSubject_hoursPerWeek 	= $_POST["gebeFaecher_new_hoursPerWeek"];

	$new_activity 					= $_POST["new_activity"];

	// E-Mail updaten
	if($new_email)
	{
		$old_email = $user->valueThroughID("`e`.`EMail`", "`haupttabelle` AS `h` LEFT JOIN `e-mails` AS `e` ON `h`.`E-Mail_id` = `e`.`id`"); // alte E-Mail, für den $where-Teil
		$successful = $user->updateOneEntry("`e-mails`", "EMail = '$new_email'", "EMail = '$old_email'");
	}

	// Neue Jahrgangsstufe
	if($new_grade)
	{
		$successful = $user->updateThroughID("`haupttabelle`", "Jahrgangsstufe = $new_grade");
	}

	// Der Benutzer sucht Nachhilfe
	$array_search = array(); // in dem Array werden die ID`s der Fächer eingetragen, die der Benutzer sucht
	// neues Fach, dass der Schüler sucht
	if(!(in_array(null, $new_search)) && $new_search) // null muss geprüft werden, da dies bei einem Nichtauswählen im Array enthalten wäre, und der Array somit "true"
	{
		for($i = 0; $i < count($new_search); $i++) // alle ausgewählten Optionen des mehrfachen Auswahlmenüs durchgehen
		{
			if(isset($new_search[$i])) // wenn dieses Fach ausgewählt wurde:
			{
				array_push($array_search, $user->search("id", "faecher", "Fach LIKE '$new_search[$i]'")); // Id des Faches in den Array aufnehmen
			}
		}
		$search = $user->arrayToString($array_search); // in String konvertieren
		$successful = $user->updateThroughID("`haupttabelle`", "sucheFaecher_id = '$search'"); // in der Datenbank abspeichern
	}

	$array_searchSubject_weekday = array();
	// neuer Wochentag
	if(!(in_array(null, $new_searchSubject_weekday)) && $new_searchSubject_weekday)
	{
		for($i = 0; $i < count($new_searchSubject_weekday); $i++) // alle ausgewählten Optionen des mehrfachen Auswahlmenüs durchgehen
		{
			if(isset($new_searchSubject_weekday[$i])) // wenn dieses Fach ausgewählt wurde:
			{
				array_push($array_searchSubject_weekday, $user->search("id", "wochentage", "Wochentag LIKE '$new_searchSubject_weekday[$i]'")); // Id des Wochentags in den Array aufnehmen
			}
		}
		$weekdays = $user->arrayToString($array_searchSubject_weekday); // in String konvertieren
		$successful = $user->updateThroughID("`haupttabelle`", "sucheFaecher_Wochentage_id = '$weekdays'"); // in der Datenbank abspeichern
	}

	if($new_searchSubject_hoursPerWeek)
	{
		$successful = $user->updateThroughID("`haupttabelle`", "sucheFaecher_Stundenzahl = $new_searchSubject_hoursPerWeek");
	}

	// Der Benutzer bietet Nachhilfe an
	$array_offer = array();
	// neues Fach, dass der Schüler geben will
	if(!(in_array(null, $new_offer)) && $new_offer)
	{
		for($i = 0; $i < count($new_offer); $i++) // alle ausgewählten Optionen des mehrfachen Auswahlmenüs durchgehen
		{
			if(isset($new_offer[$i])) // wenn dieses Fach ausgewählt wurde:
			{
				array_push($array_offer, $user->search("id", "faecher", "Fach LIKE '$new_offer[$i]'")); // Id des Faches in den Array aufnehmen
			}
		}
		$offer = $user->arrayToString($array_offer); // in String konvertieren
		$successful = $user->updateThroughID("`haupttabelle`", "gebeFaecher_id = '$offer'"); // in der Datenbank abspeichern
	}

	$array_weekday = array();
	// neuer Wochentag
	if(!(in_array(null, $new_giveSubject_weekday)) && $new_giveSubject_weekday)
	{
		for($i = 0; $i < count($new_giveSubject_weekday); $i++) // alle ausgewählten Optionen des mehrfachen Auswahlmenüs durchgehen
		{
			if(isset($new_giveSubject_weekday[$i])) // wenn dieses Fach ausgewählt wurde:
			{
				array_push($array_weekday, $user->search("id", "wochentage", "Wochentag LIKE '$new_giveSubject_weekday[$i]'")); // Id des Wochentags in den Array aufnehmen
			}
		}
		$weekdays = $user->arrayToString($array_weekday); // in String konvertieren
		$successful = $user->updateThroughID("`haupttabelle`", "gebeFaecher_Wochentage_id = '$weekdays'"); // in der Datenbank abspeichern
	}

	// neue Stundenanzahl
	if($new_giveSubject_hoursPerWeek)
	{
		$successful = $user->updateThroughID("`haupttabelle`", "gebeFaecher_Stundenzahl = $new_giveSubject_hoursPerWeek");
	}

	// Aktivität/Status verändern, wird in Datenbank als Aktivität gespeichert, da 'status' reserviertes Wort
	if($new_activity)
	{
		$aktivitaetId = $user->search("id", "`aktivitaet`", "Aktivitaet = '$new_activity'");
		$successful = $user->updateThroughID("`haupttabelle`", "aktivitaet_id = $aktivitaetId");
	}

	// Wieder zurück zur Datenverwaltung, wenn alle Änderungen abgearbeitet wurden
	header('location: dataAdministration.php');

?>


text:
<?php

namespace Google\Cloud\Samples\VideoIntelligence;

// [START video_speech_transcription_gcs]
use Google\Cloud\VideoIntelligence\V1\VideoIntelligenceServiceClient;
use Google\Cloud\VideoIntelligence\V1\Feature;
use Google\Cloud\VideoIntelligence\V1\VideoContext;
use Google\Cloud\VideoIntelligence\V1\SpeechTranscriptionConfig;

/**
 * @param string $uri The cloud storage object to analyze (gs://your-bucket-name/your-object-name)
 * @param int $pollingIntervalSeconds
 */
function analyze_transcription(string $uri, int $pollingIntervalSeconds = 0)
{
    # set configs
    $speechTranscriptionConfig = (new SpeechTranscriptionConfig())
        ->setLanguageCode('en-US')
        ->setEnableAutomaticPunctuation(true);
    $videoContext = (new VideoContext())
        ->setSpeechTranscriptionConfig($speechTranscriptionConfig);

    # instantiate a client
    $client = new VideoIntelligenceServiceClient();

    # execute a request.
    $features = [Feature::SPEECH_TRANSCRIPTION];
    $operation = $client->annotateVideo([
        'inputUri' => $uri,
        'videoContext' => $videoContext,
        'features' => $features,
    ]);

    print('Processing video for speech transcription...' . PHP_EOL);
    # Wait for the request to complete.
    $operation->pollUntilComplete([
        'pollingIntervalSeconds' => $pollingIntervalSeconds
    ]);

    # Print the result.
    if ($operation->operationSucceeded()) {
        $result = $operation->getResult();
        # there is only one annotation_result since only
        # one video is processed.
        $annotationResults = $result->getAnnotationResults()[0];
        $speechTranscriptions = $annotationResults ->getSpeechTranscriptions();

        foreach ($speechTranscriptions as $transcription) {
            # the number of alternatives for each transcription is limited by
            # $max_alternatives in SpeechTranscriptionConfig
            # each alternative is a different possible transcription
            # and has its own confidence score.
            foreach ($transcription->getAlternatives() as $alternative) {
                print('Alternative level information' . PHP_EOL);

                printf('Transcript: %s' . PHP_EOL, $alternative->getTranscript());
                printf('Confidence: %s' . PHP_EOL, $alternative->getConfidence());

                print('Word level information:');
                foreach ($alternative->getWords() as $wordInfo) {
                    printf(
                        '%s s - %s s: %s' . PHP_EOL,
                        $wordInfo->getStartTime()->getSeconds(),
                        $wordInfo->getEndTime()->getSeconds(),
                        $wordInfo->getWord()
                    );
                }
            }
        }
    }
    $client->close();
}
// [END video_speech_transcription_gcs]

// The following 2 lines are only needed to run the samples
require_once __DIR__ . '/../../testing/sample_helpers.php';
\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);


text:
namespace MassTransit.Transports.Fabric
{
    public interface IMessageFabricObserver<in TContext>
        where TContext : class
    {
        void ExchangeDeclared(TContext context, string name, ExchangeType exchangeType);

        void ExchangeBindingCreated(TContext context, string source, string destination, string routingKey = default);

        void QueueDeclared(TContext context, string name);

        void QueueBindingCreated(TContext context, string source, string destination);

        TopologyHandle ConsumerConnected(TContext context, TopologyHandle handle, string queueName);
    }
}


text:
<?php
class Kwf_Controller_Action_User_ActionsLogController extends Kwf_Controller_Action_Auto_Grid
{
    protected $_defaultOrder = array('field' => 'date', 'direction' => 'DESC');
    protected $_model = 'Kwf_User_ActionsLogModel';
    protected $_buttons = array();
    protected $_paging = 200;

    public function preDispatch()
    {
        $this->_filters['date'] = array(
            'type' => 'DateRange',
            'label' => trlKwf('Date'),
        );

        $data = array();
        $db = Kwf_Registry::get('db');
        $select = new Zend_Db_Select($db);
        $select = $this->_createSelectToShowOnlyPermittedEntriesZendExpression($select);
        $currentUser = Kwf_Registry::get('userModel')->getAuthedUser();
        $allowedDomains = $this->_getAllowedDomains($currentUser);
        if (!empty($allowedDomains)) {
            $select->from(
                array('kwf_user_actionslog'),
                array(new Zend_Db_Expr('distinct(user_name)'))
            );
            foreach ($db->fetchAll($select) as $r) {
                $data[] = array($r['user_name'], $r['user_name']);
            }
        }
        $this->_filters['user_name'] = array(
            'type' => 'ComboBox',
            'width' => 100,
            'label' => trlKwf('User'),
            'data' => $data,
        );

        $data = array();
        $db = Kwf_Registry::get('db');
        $select = new Zend_Db_Select($db);
        $select = $this->_createSelectToShowOnlyPermittedEntriesZendExpression($select);
        if (!empty($allowedDomains)) {
            $select->from(
                array('kwf_user_actionslog'),
                array(new Zend_Db_Expr('distinct(domain)'))
            );
            foreach ($db->fetchAll($select) as $r) {
                $data[] = array($r['domain'], $r['domain']);
            }
        }
        $this->_filters['domain'] = array(
            'type' => 'ComboBox',
            'width' => 100,
            'label' => trlKwf('Domain'),
            'data' => $data,
        );

        $this->_filters['text'] = array(
            'type'=>'TextField',
            'label' => 'Suche',
            'width' => 200
        );
        parent::preDispatch();
    }

    protected function _initColumns()
    {
        parent::_initColumns();

        $this->_columns->add(new Kwf_Grid_Column('date', trlKwf('Time'), 110))
            ->setRenderer('localizedDatetime');
        $this->_columns->add(new Kwf_Grid_Column('user_name', trlKwf('User'), 150));
        $this->_columns->add(new Kwf_Grid_Column('domain', trlKwf('Domain'), 120));
        $this->_columns->add(new Kwf_Grid_Column('url', trlKwf('URL'), 300));
        $this->_columns->add(new Kwf_Grid_Column('details', trlKwf('Details'), 150));
    }

    protected function _getSelect()
    {
        $ret = parent::_getSelect();
        $currentUser = Kwf_Registry::get('userModel')->getAuthedUser();
        if ($this->_getAllowedDomains($currentUser)) {
            $ret = $this->_createSelectToShowOnlyPermittedEntriesKwfExpression($ret);
        } else {
            // Return no result (id is Auto_Increment and can't be -1)
            $ret = $ret->where(new Kwf_Model_Select_Expr_Equal('id', '-1'));
        }
        return $ret;
    }

    private function _createSelectToShowOnlyPermittedEntriesZendExpression($select) {
        $currentUser = Kwf_Registry::get('userModel')->getAuthedUser();
        if ($currentUser->role == 'admin') return $select;

        foreach ($this->_getAllowedDomains($currentUser) as $domainName) {
            $select->orWhere('domain = ?', $domainName);
        }

        return $select;
    }

    private function _createSelectToShowOnlyPermittedEntriesKwfExpression($select) {
        $currentUser = Kwf_Registry::get('userModel')->getAuthedUser();
        if ($currentUser->role == 'admin') return $select;
        $orExpr = new Kwf_Model_Select_Expr_Or(array());

        foreach ($this->_getAllowedDomains($currentUser) as $domainName) {
            $orExpr->addExpression(new Kwf_Model_Select_Expr_Equal('domain', $domainName));
        }

        return $select->where($orExpr);
    }

    private function _getAllowedDomains($currentUser) {
        $domainNames = array();
        foreach ($currentUser->getDomains() as $domain => $value ) {
            $domainComponent = Kwf_Component_Data_Root::getInstance()->getComponentByDbId('root-'.$domain);
            $domainNames[] = $domainComponent ? $domainComponent->getRow()->name : null;
        }
        return $domainNames;
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.redkalex.source.pgsql;

import org.redkale.net.client.ClientConnection;
import org.redkale.util.ByteArray;
import static org.redkalex.source.pgsql.PgClientRequest.*;

/**
 *
 * @author zhangjx
 */
public class PgReqClose extends PgClientRequest {

    public static final PgReqClose INSTANCE = new PgReqClose();

    public PgReqClose() {
    }

    @Override
    public int getType() {
        return REQ_TYPE_UPDATE;
    }

    @Override
    public String toString() {
        return "PgReqClose{}";
    }

    @Override
    public void accept(ClientConnection conn, ByteArray array) {
        array.putByte('X');
        array.putInt(4);
    }

}


text:
// $Id: Message_Queue.cpp 79134 2007-07-31 18:23:50Z johnnyw $

#include "ace/Message_Queue.h"
#include "ace/Log_Msg.h"

#if !defined (__ACE_INLINE__)
#include "ace/Message_Queue.inl"
#endif /* __ACE_INLINE__ */

ACE_RCSID (ace,
           Message_Queue,
           "$Id: Message_Queue.cpp 79134 2007-07-31 18:23:50Z johnnyw $")

ACE_BEGIN_VERSIONED_NAMESPACE_DECL

ACE_Message_Queue_Base::~ACE_Message_Queue_Base (void)
{
}

int
ACE_Message_Queue_Base::state (void)
{
  ACE_TRACE ("ACE_Message_Queue_Base::state");

  return this->state_;
}

#if defined (ACE_HAS_WIN32_OVERLAPPED_IO)

ACE_Message_Queue_NT::ACE_Message_Queue_NT (DWORD max_threads)
  : max_cthrs_ (max_threads),
    cur_thrs_ (0),
    cur_bytes_ (0),
    cur_length_ (0),
    cur_count_ (0),
    completion_port_ (ACE_INVALID_HANDLE)
{
  ACE_TRACE ("ACE_Message_Queue_NT::ACE_Message_Queue_NT");
  this->open (max_threads);
}

int
ACE_Message_Queue_NT::open (DWORD max_threads)
{
  ACE_TRACE ("ACE_Message_Queue_NT::open");
  this->max_cthrs_ = max_threads;
  this->completion_port_ = ::CreateIoCompletionPort (ACE_INVALID_HANDLE,
                                                     0,
                                                     ACE_Message_Queue_Base::ACTIVATED,
                                                     max_threads);
  return (this->completion_port_ == 0 ? -1 : 0);
}

int
ACE_Message_Queue_NT::close (void)
{
  ACE_TRACE ("ACE_Message_Queue_NT::close");
  ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, ace_mon, this->lock_, -1);
  this->deactivate ();
  return (::CloseHandle (this->completion_port_) ? 0 : -1 );
}

ACE_Message_Queue_NT::~ACE_Message_Queue_NT (void)
{
  ACE_TRACE ("ACE_Message_Queue_NT::~ACE_Message_Queue_NT");
  this->close ();
}

int
ACE_Message_Queue_NT::enqueue (ACE_Message_Block *new_item,
                               ACE_Time_Value *)
{
  ACE_TRACE ("ACE_Message_Queue_NT::enqueue");
  ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, ace_mon, this->lock_, -1);
  if (this->state_ != ACE_Message_Queue_Base::DEACTIVATED)
    {
      size_t const msize = new_item->total_size ();
      size_t const mlength = new_item->total_length ();
      // Note - we send ACTIVATED in the 3rd arg to tell the completion
      // routine it's _NOT_ being woken up because of deactivate().
      ULONG_PTR state_to_post;
      state_to_post = ACE_Message_Queue_Base::ACTIVATED;
      if (::PostQueuedCompletionStatus (this->completion_port_,
                                        static_cast<DWORD> (msize),
                                        state_to_post,
                                        reinterpret_cast<LPOVERLAPPED> (new_item)))
        {
          // Update the states once I succeed.
          this->cur_bytes_ += msize;
          this->cur_length_ += mlength;
          return ACE_Utils::truncate_cast<int> (++this->cur_count_);
        }
    }
  else
    errno = ESHUTDOWN;

  // Fail to enqueue the message.
  return -1;
}

int
ACE_Message_Queue_NT::dequeue (ACE_Message_Block *&first_item,
                               ACE_Time_Value *timeout)
{
  ACE_TRACE ("ACE_Message_Queue_NT::dequeue_head");

  {
    ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, ace_mon, this->lock_, -1);

    // Make sure the MQ is not deactivated before proceeding.
    if (this->state_ == ACE_Message_Queue_Base::DEACTIVATED)
      {
        errno = ESHUTDOWN;      // Operation on deactivated MQ not allowed.
        return -1;
      }
    else
      ++this->cur_thrs_;        // Increase the waiting thread count.
  }

  ULONG_PTR queue_state;
  DWORD msize;
  // Get a message from the completion port.
  int retv = ::GetQueuedCompletionStatus (this->completion_port_,
                                          &msize,
                                          &queue_state,
                                          reinterpret_cast<LPOVERLAPPED *> (&first_item),
                                          (timeout == 0 ? INFINITE : timeout->msec ()));
  {
    ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, ace_mon, this->lock_, -1);
    --this->cur_thrs_;          // Decrease waiting thread count.
    if (retv)
      {
        if (queue_state == ACE_Message_Queue_Base::ACTIVATED)
          {                     // Really get a valid MB from the queue.
            --this->cur_count_;
            this->cur_bytes_ -= msize;
            this->cur_length_ -= first_item->total_length ();
            return ACE_Utils::truncate_cast<int> (this->cur_count_);
          }
        else                    // Woken up by deactivate () or pulse ().
            errno = ESHUTDOWN;
      }
  }
  return -1;
}

int
ACE_Message_Queue_NT::deactivate (void)
{
  ACE_TRACE ("ACE_Message_Queue_NT::deactivate");
  ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, ace_mon, this->lock_, -1);

  int const previous_state = this->state_;
  if (previous_state != ACE_Message_Queue_Base::DEACTIVATED)
    {
      this->state_ = ACE_Message_Queue_Base::DEACTIVATED;

      // Get the number of shutdown messages necessary to wake up all
      // waiting threads.
      DWORD cntr =
        this->cur_thrs_ - static_cast<DWORD> (this->cur_count_);
      while (cntr-- > 0)
        ::PostQueuedCompletionStatus (this->completion_port_,
                                      0,
                                      this->state_,
                                      0);
    }
  return previous_state;
}

int
ACE_Message_Queue_NT::activate (void)
{
  ACE_TRACE ("ACE_Message_Queue_NT::activate");
  ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, ace_mon, this->lock_, -1);
  int const previous_status = this->state_;
  this->state_ = ACE_Message_Queue_Base::ACTIVATED;
  return previous_status;
}

int
ACE_Message_Queue_NT::pulse (void)
{
  ACE_TRACE ("ACE_Message_Queue_NT::pulse");
  ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, ace_mon, this->lock_, -1);

  int const previous_state = this->state_;
  if (previous_state != ACE_Message_Queue_Base::DEACTIVATED)
    {
      this->state_ = ACE_Message_Queue_Base::PULSED;

      // Get the number of shutdown messages necessary to wake up all
      // waiting threads.

      DWORD cntr =
        this->cur_thrs_ - static_cast<DWORD> (this->cur_count_);
      while (cntr-- > 0)
        ::PostQueuedCompletionStatus (this->completion_port_,
                                      0,
                                      this->state_,
                                      0);
    }
  return previous_state;
}

void
ACE_Message_Queue_NT::dump (void) const
{
#if defined (ACE_HAS_DUMP)
  ACE_TRACE ("ACE_Message_Queue_NT::dump");

  ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this));
  switch (this->state_)
    {
    case ACE_Message_Queue_Base::ACTIVATED:
      ACE_DEBUG ((LM_DEBUG,
                  ACE_TEXT ("state = ACTIVATED\n")));
      break;
    case ACE_Message_Queue_Base::DEACTIVATED:
      ACE_DEBUG ((LM_DEBUG,
                  ACE_TEXT ("state = DEACTIVATED\n")));
      break;
    case ACE_Message_Queue_Base::PULSED:
      ACE_DEBUG ((LM_DEBUG,
                  ACE_TEXT ("state = PULSED\n")));
      break;
    }

  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("max_cthrs_ = %d\n")
              ACE_TEXT ("cur_thrs_ = %d\n")
              ACE_TEXT ("cur_bytes = %d\n")
              ACE_TEXT ("cur_length = %d\n")
              ACE_TEXT ("cur_count = %d\n")
              ACE_TEXT ("completion_port_ = %x\n"),
              this->max_cthrs_,
              this->cur_thrs_,
              this->cur_bytes_,
              this->cur_length_,
              this->cur_count_,
              this->completion_port_));
  ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP));
#endif /* ACE_HAS_DUMP */
}

#endif /* ACE_HAS_WIN32_OVERLAPPED_IO */

ACE_END_VERSIONED_NAMESPACE_DECL


text:
package ssh

import (
	"strings"

	"github.com/hashicorp/vault/helper/salt"
	"github.com/hashicorp/vault/logical"
	"github.com/hashicorp/vault/logical/framework"
)

type backend struct {
	*framework.Backend
	salt *salt.Salt
}

func Factory(conf *logical.BackendConfig) (logical.Backend, error) {
	b, err := Backend(conf)
	if err != nil {
		return nil, err
	}
	return b.Setup(conf)
}

func Backend(conf *logical.BackendConfig) (*backend, error) {
	salt, err := salt.NewSalt(conf.StorageView, &salt.Config{
		HashFunc: salt.SHA256Hash,
	})
	if err != nil {
		return nil, err
	}

	var b backend
	b.salt = salt
	b.Backend = &framework.Backend{
		Help: strings.TrimSpace(backendHelp),

		PathsSpecial: &logical.Paths{
			Unauthenticated: []string{
				"verify",
			},
		},

		Paths: []*framework.Path{
			pathConfigZeroAddress(&b),
			pathKeys(&b),
			pathListRoles(&b),
			pathRoles(&b),
			pathCredsCreate(&b),
			pathLookup(&b),
			pathVerify(&b),
		},

		Secrets: []*framework.Secret{
			secretDynamicKey(&b),
			secretOTP(&b),
		},
	}
	return &b, nil
}

const backendHelp = `
The SSH backend generates credentials allowing clients to establish SSH
connections to remote hosts.

There are two variants of the backend, which generate different types of
credentials: dynamic keys and One-Time Passwords (OTPs). The desired behavior
is role-specific and chosen at role creation time with the 'key_type'
parameter.

Please see the backend documentation for a thorough description of both
types. The Vault team strongly recommends the OTP type.

After mounting this backend, before generating credentials, configure the
backend's lease behavior using the 'config/lease' endpoint and create roles
using the 'roles/' endpoint.
`


text:
<?php

/**
 * @see Zend_Gdata
 */
// require_once 'Zend/Gdata.php';

/**
 * @see Zend_Gdata_Docs_DocumentListFeed
 */
// require_once 'Zend/Gdata/Docs/DocumentListFeed.php';

/**
 * @see Zend_Gdata_Docs_DocumentListEntry
 */
// require_once 'Zend/Gdata/Docs/DocumentListEntry.php';

/**
 * @see Zend_Gdata_App_Extension_Category
 */
// require_once 'Zend/Gdata/App/Extension/Category.php';

/**
 * @see Zend_Gdata_App_Extension_Title
 */
// require_once 'Zend/Gdata/App/Extension/Title.php';

/**
 * Service class for interacting with the Google Document List data API
 * @link http://code.google.com/apis/documents/
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Docs
 * @copyright  Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Docs extends Zend_Gdata
{
    const DOCUMENTS_LIST_FEED_URI = 'https://docs.google.com/feeds/documents/private/full';
    const DOCUMENTS_FOLDER_FEED_URI = 'https://docs.google.com/feeds/folders/private/full';
    const DOCUMENTS_CATEGORY_SCHEMA = 'http://schemas.google.com/g/2005#kind';
    const DOCUMENTS_CATEGORY_TERM = 'http://schemas.google.com/docs/2007#folder';
    const AUTH_SERVICE_NAME = 'writely';

    /**
     * @var string
     */
    protected $_defaultPostUri = self::DOCUMENTS_LIST_FEED_URI;

    /**
     * @var array
     */
    protected static $SUPPORTED_FILETYPES = array(
        'TXT'  => 'text/plain',
        'CSV'  => 'text/csv',
        'TSV'  => 'text/tab-separated-values',
        'TAB'  => 'text/tab-separated-values',
        'HTML' => 'text/html',
        'HTM'  => 'text/html',
        'DOC'  => 'application/msword',
        'DOCX' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'ODS'  => 'application/vnd.oasis.opendocument.spreadsheet',
        'ODT'  => 'application/vnd.oasis.opendocument.text',
        'RTF'  => 'application/rtf',
        'SXW'  => 'application/vnd.sun.xml.writer',
        'XLS'  => 'application/vnd.ms-excel',
        'XLSX' => 'application/vnd.ms-excel',
        'PPT'  => 'application/vnd.ms-powerpoint',
        'PPS'  => 'application/vnd.ms-powerpoint'
    );

    /**
     * Create Gdata_Docs object
     *
     * @param Zend_Http_Client $client (optional) The HTTP client to use when
     *          when communicating with the Google servers.
     * @param string $applicationId The identity of the app in the form of Company-AppName-Version
     */
    public function __construct($client = null, $applicationId = 'MyCompany-MyApp-1.0')
    {
        $this->registerPackage('Zend_Gdata_Docs');
        parent::__construct($client, $applicationId);
        $this->_httpClient->setParameterPost('service', self::AUTH_SERVICE_NAME);
    }

    /**
     * Looks up the mime type based on the file name extension. For example,
     * calling this method with 'csv' would return
     * 'text/comma-separated-values'. The Mime type is sent as a header in
     * the upload HTTP POST request.
     *
     * @param string $fileExtension
     * @return string The mime type to be sent to the server to tell it how the
     *          multipart mime data should be interpreted.
     */
    public static function lookupMimeType($fileExtension)
    {
        return self::$SUPPORTED_FILETYPES[strtoupper($fileExtension)];
    }

    /**
     * Retreive feed object containing entries for the user's documents.
     *
     * @param mixed $location The location for the feed, as a URL or Query
     * @return Zend_Gdata_Docs_DocumentListFeed
     */
    public function getDocumentListFeed($location = null)
    {
        if ($location === null) {
            $uri = self::DOCUMENTS_LIST_FEED_URI;
        } else if ($location instanceof Zend_Gdata_Query) {
            $uri = $location->getQueryUrl();
        } else {
            $uri = $location;
        }
        return parent::getFeed($uri, 'Zend_Gdata_Docs_DocumentListFeed');
    }

    /**
     * Retreive entry object representing a single document.
     *
     * @param mixed $location The location for the entry, as a URL or Query
     * @return Zend_Gdata_Docs_DocumentListEntry
     * @throws Zend_Gdata_App_InvalidArgumentException
     */
    public function getDocumentListEntry($location = null)
    {
        if ($location === null) {
            // require_once 'Zend/Gdata/App/InvalidArgumentException.php';
            throw new Zend_Gdata_App_InvalidArgumentException(
                    'Location must not be null'
            );
        } else if ($location instanceof Zend_Gdata_Query) {
            $uri = $location->getQueryUrl();
        } else {
            $uri = $location;
        }
        return parent::getEntry($uri, 'Zend_Gdata_Docs_DocumentListEntry');
    }

    /**
     * Retreive entry object representing a single document.
     *
     * This method builds the URL where this item is stored using the type
     * and the id of the document.
     * @param string $docId The URL key for the document. Examples:
     *     dcmg89gw_62hfjj8m, pKq0CzjiF3YmGd0AIlHKqeg
     * @param string $docType The type of the document as used in the Google
     *     Document List URLs. Examples: document, spreadsheet, presentation
     * @return Zend_Gdata_Docs_DocumentListEntry
     */
    public function getDoc($docId, $docType)
    {
        $location = 'https://docs.google.com/feeds/documents/private/full/' .
            $docType . '%3A' . $docId;

        return $this->getDocumentListEntry($location);
    }

    /**
     * Retreive entry object for the desired word processing document.
     *
     * @param string $id The URL id for the document. Example: dcmg89gw_62hfjj8m
     * @return Zend_Gdata_Docs_DocumentListEntry
     */
    public function getDocument($id)
    {
        return $this->getDoc($id, 'document');
    }

    /**
     * Retreive entry object for the desired spreadsheet.
     *
     * @param string $id The URL id for the document. Example: pKq0CzjiF3YmGd0AIlHKqeg
     * @return Zend_Gdata_Docs_DocumentListEntry
     */
    public function getSpreadsheet($id)
    {
        return $this->getDoc($id, 'spreadsheet');
    }

    /**
     * Retreive entry object for the desired presentation.
     *
     * @param string $id The URL id for the document. Example: dcmg89gw_21gtrjcn
     * @return Zend_Gdata_Docs_DocumentListEntry
     */
    public function getPresentation($id)
    {
        return $this->getDoc($id, 'presentation');
    }

    /**
     * Upload a local file to create a new Google Document entry.
     *
     * @param string $fileLocation The full or relative path of the file to
     *         be uploaded.
     * @param string $title The name that this document should have on the
     *         server. If set, the title is used as the slug header in the
     *         POST request. If no title is provided, the location of the
     *         file will be used as the slug header in the request. If no
     *         mimeType is provided, this method attempts to determine the
     *         mime type based on the slugHeader by looking for .doc,
     *         .csv, .txt, etc. at the end of the file name.
     *         Example value: 'test.doc'.
     * @param string $mimeType Describes the type of data which is being sent
     *         to the server. This must be one of the accepted mime types
     *         which are enumerated in SUPPORTED_FILETYPES.
     * @param string $uri (optional) The URL to which the upload should be
     *         made.
     *         Example: 'https://docs.google.com/feeds/documents/private/full'.
     * @return Zend_Gdata_Docs_DocumentListEntry The entry for the newly
     *         created Google Document.
     */
    public function uploadFile($fileLocation, $title = null, $mimeType = null,
        $uri = null
    )
    {
        // Set the URI to which the file will be uploaded.
        if ($uri === null) {
            $uri = $this->_defaultPostUri;
        }

        // Create the media source which describes the file.
        $fs = $this->newMediaFileSource($fileLocation);
        if ($title !== null) {
            $slugHeader = $title;
        } else {
            $slugHeader = $fileLocation;
        }

        // Set the slug header to tell the Google Documents server what the
        // title of the document should be and what the file extension was
        // for the original file.
        $fs->setSlug($slugHeader);

        // Set the mime type of the data.
        if ($mimeType === null) {
          $filenameParts = explode('.', $fileLocation);
          $fileExtension = end($filenameParts);
          $mimeType = self::lookupMimeType($fileExtension);
        }

        // Set the mime type for the upload request.
        $fs->setContentType($mimeType);

        // Send the data to the server.
        return $this->insertDocument($fs, $uri);
    }

    /**
     * Creates a new folder in Google Docs
     *
     * @param string $folderName The folder name to create
     * @param string|null $folderResourceId The parent folder to create it in
     *        ("folder%3Amy_parent_folder")
     * @return Zend_Gdata_Entry The folder entry created.
     * @todo ZF-8732: This should return a *subclass* of Zend_Gdata_Entry, but
     *       the appropriate type doesn't exist yet.
     */
    public function createFolder($folderName, $folderResourceId = null)
    {
        $category = new Zend_Gdata_App_Extension_Category(
            self::DOCUMENTS_CATEGORY_TERM,
            self::DOCUMENTS_CATEGORY_SCHEMA
        );
        $title    = new Zend_Gdata_App_Extension_Title($folderName);
        $entry    = new Zend_Gdata_Entry();

        $entry->setCategory(array($category));
        $entry->setTitle($title);

        $uri = self::DOCUMENTS_LIST_FEED_URI;
        if ($folderResourceId != null) {
            $uri = self::DOCUMENTS_FOLDER_FEED_URI . '/' . $folderResourceId;
        }

        return $this->insertEntry($entry, $uri);
    }

    /**
     * Inserts an entry to a given URI and returns the response as an Entry.
     *
     * @param mixed  $data The Zend_Gdata_Docs_DocumentListEntry or media
     *         source to post. If it is a DocumentListEntry, the mediaSource
     *         should already have been set. If $data is a mediaSource, it
     *         should have the correct slug header and mime type.
     * @param string $uri POST URI
     * @param string $className (optional) The class of entry to be returned.
     *         The default is a 'Zend_Gdata_Docs_DocumentListEntry'.
     * @return Zend_Gdata_Docs_DocumentListEntry The entry returned by the
     *     service after insertion.
     */
    public function insertDocument($data, $uri,
        $className = 'Zend_Gdata_Docs_DocumentListEntry')
    {
        return $this->insertEntry($data, $uri, $className);
    }
}


text:
package ru.job4j.tracker;

public class ValidateInput extends ConsoleInput {
    private final Input input;

    public ValidateInput(Input input) {
        this.input = input;
    }

    @Override
    public String ask(String question) {
        return this.input.ask(question);
    }

    @Override
    public int ask(String question, int[] range) {
        boolean invalid = true;
        int value = -1;
        do {
            try {
                 value = this.input.ask(question, range);
                 invalid = false;
            } catch (MenuOutOfRange moe) {
                System.out.println("Please select key from menu.");
            } catch (NumberFormatException nfe) {
                System.out.println("Please enter valid data again.");
            }
        } while (invalid);
        return (value);
    }
}


text:
package org.elasticsearch.rest.action.admin.cluster.allocation;

import java.io.IOException;

import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.action.admin.cluster.allocation.ClusterAllocationExplainRequest;
import org.elasticsearch.action.admin.cluster.allocation.ClusterAllocationExplainResponse;
import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.BytesRestResponse;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.action.support.RestActions;
import org.elasticsearch.rest.action.support.RestBuilderListener;

/**
 * Class handling cluster allocation explanation at the REST level
 */
public class RestClusterAllocationExplainAction extends BaseRestHandler {

    @Inject
    public RestClusterAllocationExplainAction(Settings settings, RestController controller) {
        super(settings);
        controller.registerHandler(RestRequest.Method.GET, "/_cluster/allocation/explain", this);
        controller.registerHandler(RestRequest.Method.POST, "/_cluster/allocation/explain", this);
    }

    @Override
    public void handleRequest(final RestRequest request, final RestChannel channel, final NodeClient client) {
        ClusterAllocationExplainRequest req;
        if (RestActions.hasBodyContent(request) == false) {
            // Empty request signals "explain the first unassigned shard you find"
            req = new ClusterAllocationExplainRequest();
        } else {
            BytesReference content = RestActions.getRestContent(request);
            try (XContentParser parser = XContentFactory.xContent(content).createParser(content)) {
                req = ClusterAllocationExplainRequest.parse(parser);
            } catch (IOException e) {
                logger.debug("failed to parse allocation explain request", e);
                channel.sendResponse(
                    new BytesRestResponse(ExceptionsHelper.status(e), BytesRestResponse.TEXT_CONTENT_TYPE, BytesArray.EMPTY));
                return;
            }
        }

        try {
            req.includeYesDecisions(request.paramAsBoolean("include_yes_decisions", false));
            client.admin().cluster().allocationExplain(req, new RestBuilderListener<ClusterAllocationExplainResponse>(channel) {
                @Override
                public RestResponse buildResponse(ClusterAllocationExplainResponse response, XContentBuilder builder) throws Exception {
                    response.getExplanation().toXContent(builder, ToXContent.EMPTY_PARAMS);
                    return new BytesRestResponse(RestStatus.OK, builder);
                }
            });
        } catch (Exception e) {
            logger.error("failed to explain allocation", e);
            channel.sendResponse(new BytesRestResponse(ExceptionsHelper.status(e), BytesRestResponse.TEXT_CONTENT_TYPE, BytesArray.EMPTY));
        }
    }
}


text:
'use strict';
var _ = require('underscore');
var Read = require('./read');

var AwsAdapter = function(config) {

    for (let property of ['access_key', 'secret_key', 'region']) {
        if (!_.has(config, property)) {
            throw new Error(`AWS Adapter configuration missing required value ${property}`);
        }
    }

    Read.init(config);

    return {
        name: 'aws',
        read: Read.read
    };
};

module.exports = AwsAdapter;


text:
"""Unit tests for perf_uploader module."""

import json
import os
import sys
import tempfile
import urllib2
import urlparse

sys.path.insert(0, os.path.abspath('%s/../..' % os.path.dirname(__file__)))
from chromite.lib import cros_test_lib
from chromite.lib import perf_uploader
from chromite.lib import osutils

class PerfUploadTestCase(cros_test_lib.MockTestCase):
  """Base utility class to setup mock objects and temp file for tests."""

  def setUp(self):
    presentation_info = perf_uploader.PresentationInfo(
        master_name='ChromeOSPerf',
        test_name='TestName',
    )
    self.PatchObject(perf_uploader, '_GetPresentationInfo',
                     return_value=presentation_info)
    self.file_name = tempfile.NamedTemporaryFile().name

  def tearDown(self):
    osutils.SafeUnlink(self.file_name)

class OutputPerfValueTest(PerfUploadTestCase):
  """Test function OutputPerfValue."""

  def testInvalidDescription(self):
    self.assertRaises(ValueError, perf_uploader.OutputPerfValue,
                      'ignored', 'a' * 257, 0, 'ignored')
    self.assertRaises(ValueError, perf_uploader.OutputPerfValue,
                      'ignored', 'a\x00c', 0, 'ignored')

  def testInvalidUnits(self):
    self.assertRaises(ValueError, perf_uploader.OutputPerfValue,
                      'ignored', 'ignored', 0, 'a' * 257)
    self.assertRaises(ValueError, perf_uploader.OutputPerfValue,
                      'ignored', 'ignored', 0, 'a\x00c')

  def testValidJson(self):
    perf_uploader.OutputPerfValue(self.file_name, 'desc', 42, 'units')
    data = osutils.ReadFile(self.file_name)
    entry = json.loads(data)
    self.assertTrue(isinstance(entry, dict))

class LoadPerfValuesTest(PerfUploadTestCase):
  """Test function LoadPerfValues."""

  def testEmptyFile(self):
    osutils.WriteFile(self.file_name, '')
    entries = perf_uploader.LoadPerfValues(self.file_name)
    self.assertEqual(0, len(entries))

  def testLoadOneValue(self):
    perf_uploader.OutputPerfValue(self.file_name, 'desc', 41, 'units')
    entries = perf_uploader.LoadPerfValues(self.file_name)
    self.assertEqual(1, len(entries))
    self.assertEqual(41, entries[0].value)
    self.assertEqual('desc', entries[0].description)
    self.assertEqual(True, entries[0].higher_is_better)

  def testLoadTwoValues(self):
    perf_uploader.OutputPerfValue(self.file_name, 'desc', 41, 'units')
    perf_uploader.OutputPerfValue(self.file_name, 'desc2', 42, 'units2')
    entries = perf_uploader.LoadPerfValues(self.file_name)
    self.assertEqual(2, len(entries))
    self.assertEqual(41, entries[0].value)
    self.assertEqual(42, entries[1].value)
    self.assertEqual('desc2', entries[1].description)
    self.assertEqual(None, entries[1].graph)

class SendToDashboardTest(PerfUploadTestCase):
  """Ensure perf values are sent to chromeperf via HTTP."""

  def setUp(self):
    self.urlopen = self.PatchObject(urllib2, 'urlopen')

  def testOneEntry(self):
    perf_uploader.OutputPerfValue(self.file_name, 'desc1', 42, 'unit')
    perf_values = perf_uploader.LoadPerfValues(self.file_name)
    perf_uploader.UploadPerfValues(perf_values, 'platform', 'cros', 'chrome',
                                   'TestName')
    request = self.urlopen.call_args[0][0]
    # pylint: disable=W0212
    self.assertEqual(perf_uploader._DASHBOARD_UPLOAD_URL,
                     request.get_full_url())
    # pylint: enable=W0212
    data = request.get_data()
    data = urlparse.parse_qs(data)['data']
    entries = [json.loads(x) for x in data]
    entry = entries[0][0]
    self.assertEqual('cros', entry['supplemental_columns']['r_cros_version'])
    self.assertEqual(42, entry['value'])
    self.assertEqual('cbuildbot.TestName/desc1', entry['test'])
    self.assertEqual('unit', entry['units'])

class UploadPerfValuesTest(PerfUploadTestCase):
  """Test UploadPerfValues function."""

  def setUp(self):
    self.send_func = self.PatchObject(perf_uploader, '_SendToDashboard')

  def testOneEntry(self):
    """Upload one perf value."""
    perf_uploader.OutputPerfValue(self.file_name, 'desc1', 42, 'unit')
    perf_values = perf_uploader.LoadPerfValues(self.file_name)
    perf_uploader.UploadPerfValues(perf_values, 'platform', 'cros', 'chrome',
                                   'TestName')
    positional_args, _ = self.send_func.call_args
    first_param = positional_args[0]
    data = json.loads(first_param['data'])
    self.assertEqual(1, len(data))
    entry = data[0]
    self.assertEqual('unit', entry['units'])
    self.assertEqual('cros',
                     entry['supplemental_columns']['r_cros_version'])
    self.assertEqual('chrome',
                     entry['supplemental_columns']['r_chrome_version'])
    self.assertEqual('cros-platform', entry['bot'])
    self.assertEqual(42, entry['value'])
    self.assertEqual(0, entry['error'])

  def testTwoEntriesOfSameTest(self):
    """Upload one test, two perf values."""
    perf_uploader.OutputPerfValue(self.file_name, 'desc1', 40, 'unit')
    perf_uploader.OutputPerfValue(self.file_name, 'desc1', 42, 'unit')
    perf_values = perf_uploader.LoadPerfValues(self.file_name)
    perf_uploader.UploadPerfValues(perf_values, 'platform', 'cros', 'chrome',
                                   'TestName')
    positional_args, _ = self.send_func.call_args
    first_param = positional_args[0]
    data = json.loads(first_param['data'])
    self.assertEqual(1, len(data))
    entry = data[0]
    self.assertEqual('unit', entry['units'])
    # Average of 40 and 42
    self.assertEqual(41, entry['value'])
    # Standard deviation sqrt(2)
    self.assertEqual(1.4142, entry['error'])

  def testTwoTests(self):
    """Upload two tests, one perf value each."""
    perf_uploader.OutputPerfValue(self.file_name, 'desc1', 40, 'unit')
    perf_uploader.OutputPerfValue(self.file_name, 'desc2', 42, 'unit')
    perf_values = perf_uploader.LoadPerfValues(self.file_name)
    perf_uploader.UploadPerfValues(perf_values, 'platform', 'cros', 'chrome',
                                   'TestName')
    positional_args, _ = self.send_func.call_args
    first_param = positional_args[0]
    data = json.loads(first_param['data'])
    self.assertEqual(2, len(data))
    data = sorted(data, key=lambda x: x['test'])
    entry = data[0]
    self.assertEqual(40, entry['value'])
    self.assertEqual(0, entry['error'])
    entry = data[1]
    self.assertEqual(42, entry['value'])
    self.assertEqual(0, entry['error'])

  def testTwoTestsThreeEntries(self):
    """Upload two tests, one perf value each."""
    perf_uploader.OutputPerfValue(self.file_name, 'desc1', 40, 'unit')
    perf_uploader.OutputPerfValue(self.file_name, 'desc1', 42, 'unit')
    perf_uploader.OutputPerfValue(self.file_name, 'desc2', 42, 'unit')
    perf_values = perf_uploader.LoadPerfValues(self.file_name)
    perf_uploader.UploadPerfValues(perf_values, 'platform', 'cros', 'chrome',
                                   'TestName')
    positional_args, _ = self.send_func.call_args
    first_param = positional_args[0]
    data = json.loads(first_param['data'])
    self.assertEqual(2, len(data))
    data = sorted(data, key=lambda x: x['test'])
    entry = data[0]
    self.assertEqual(41, entry['value'])
    self.assertEqual(1.4142, entry['error'])
    entry = data[1]
    self.assertEqual(42, entry['value'])
    self.assertEqual(0, entry['error'])

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


text:
% PRTBRV - PRT Bayesian Random Variable Class
%   Abstract Methods:
%       nDimensions

classdef prtBrv < prtAction
    methods (Abstract)
        self = estimateParameters(self, priorSelf, x)
        y = predictivePdf(self, x)
        y = predictiveLogPdf(self, x)

        d = getNumDimensions(self)

        self = initialize(self, x)
    end

    methods
        % Optional methods that would be nice to have
        % You don't have to implement these but you are welcome to some
        % types of processing for example VB with
        % calculateNegativeFreeEnergy = true, might require some of these
        function kld = conjugateKld(self, prior) %#ok<INUSD,STOUT>
            missingMethodError(self,'conjugateKld')
        end
        function x = posteriorMeanDraw(self, n, varargin) %#ok<INUSD,STOUT>
            missingMethodError(self,'posteriorMeanDraw')
        end
        function s = posteriorMeanStruct(self) %#ok<STOUT>
            missingMethodError(self,'posteriorMeanStruct')
        end
        function plotCollection(selfVec,colors) %#ok<INUSD>
           missingMethodError(selfVec(1),'plotCollection')
        end
        function val = plotLimits(self) %#ok<STOUT>
           missingMethodError(self,'plotLimits')
        end
        %function plot(self)
        %    plotCollection(self);
        %end
    end

    % All prtBrv's get the property nDimensions
    % For a particular subclass getNumDimensions must be implemented
    properties (Dependent)
        nDimensions
    end
    methods
        function val = get.nDimensions(self)
            val = zeros(size(self));
            for iRv = 1:numel(self)
                val(iRv) = self(iRv).getNumDimensions();
            end
        end
    end

    % Because we are a prtAction we also must implement something like this

    %%% properties (SetAccess=private)
    %%%     name = 'Maximum a Posteriori'   % Maximum a Posteriori
    %%%     nameAbbreviation = 'MAP'        % MAP
    %%%     isNativeMary = true;            % True
    %%% end

    % For prtAction, we also must implement trainAction() and runAction()
    methods (Access = protected, Hidden = true)
        function self = trainAction(self, ds)
            self = estimateParameters(self, ds);
        end

        function ds = runAction(self, ds)
            ds = ds.setObservations(self.predictiveLogPdf(ds.getObservations));
        end
    end

    methods (Access = 'protected', Hidden = true)
        function missingMethodError(self,methodName) %#ok<MANU>
            error('The method %s is not defined for this prtBrv object',methodName);
        end

        function self = constructorInputParse(self,varargin)

            nIn = length(varargin);

            % Quick Exit for the zero input constructor
            if nIn == 0
                return
            elseif mod(nIn,2)
                error('prt:prtBrv:constructorInputParse','Inputs must be supplied by as string/value pairs');
            end

            self = prtUtilAssignStringValuePairs(self, varargin{:});

        end
    end
end