text:
page_title: "config.winrm - Vagrantfile"
sidebar_current: "vagrantfile-winrm"
---

# WinRM Settings

**Config namespace: `config.winrm`**

The settings within `config.winrm` relate to configuring how Vagrant
will access your Windows guest over WinRM. As with most Vagrant settings, the
defaults are typically fine, but you can fine tune whatever you'd like.

These settings are only used if you've set your communicator type to `:winrm`.

## Available Settings

`config.winrm.username` - This sets the username that Vagrant will use
to login to the WinRM web service by default. Providers are free to override
this if they detect a more appropriate user. By default this is "vagrant,"
since that is what most public boxes are made as.

`config.winrm.password` - This sets a password that Vagrant will use to
authenticate the WinRM user. By default this is "vagrant," since that is
what most public boxes are made as.

`config.winrm.host` - The hostname or IP to connect to the WinRM service.
By default this is empty, because the provider usually figures this out for
you.

`config.winrm.port` - The WinRM port to connect to, by default 5985.

`config.winrm.guest_port` - The port on the guest that WinRM is running on.
This is used by some providers to detect forwarded ports for WinRM. For
example, if this is set to 5985 (the default), and Vagrant detects a forwarded
port to port 5985 on the guest from port 4567 on the host, Vagrant will attempt
to use port 4567 to talk to the guest if there is no other option.


text:
package org.bdgenomics.adam.models

import com.esotericsoftware.kryo.{ Kryo, Serializer }
import com.esotericsoftware.kryo.io.{ Input, Output }
import org.apache.spark.Logging
import Ordering.Option
import org.bdgenomics.adam.instrumentation.Timers.CreateReferencePositionPair

object ReferencePositionPair extends Logging {
  def apply(singleReadBucket: SingleReadBucket): ReferencePositionPair = CreateReferencePositionPair.time {
    singleReadBucket.primaryMapped.toSeq.lift(0) match {
      case None =>
        // No mapped reads
        new ReferencePositionPair(None, None)
      case Some(read1) =>
        val read1pos = ReferencePositionWithOrientation.fivePrime(read1)
        if (read1.getReadPaired && read1.getMateMapped) {
          singleReadBucket.primaryMapped.toSeq.lift(1) match {
            case None =>
              // Orphaned read. Missing its mate.
              log.warn("%s denoted mate as mapped but mate does not exist".format(read1.getReadName))
              new ReferencePositionPair(read1pos, None)
            case Some(read2) =>
              // Both reads are mapped
              val read2pos = ReferencePositionWithOrientation.fivePrime(read2)
              if (read1pos < read2pos) {
                new ReferencePositionPair(read1pos, read2pos)
              } else {
                new ReferencePositionPair(read2pos, read1pos)
              }
          }
        } else {
          singleReadBucket.primaryMapped.toSeq.lift(1) match {
            case None =>
              // Mate is not mapped...
              new ReferencePositionPair(read1pos, None)
            case Some(read2) =>
              val read2pos = ReferencePositionWithOrientation.fivePrime(read2)
              log.warn("%s claimed to not have mate but mate found".format(read1.getReadName))
              if (read1pos < read2pos) {
                new ReferencePositionPair(read1pos, read2pos)
              } else {
                new ReferencePositionPair(read2pos, read1pos)
              }
          }
        }
    }
  }
}

case class ReferencePositionPair(read1refPos: Option[ReferencePositionWithOrientation],
                                 read2refPos: Option[ReferencePositionWithOrientation])

class ReferencePositionPairSerializer extends Serializer[ReferencePositionPair] {
  val rps = new ReferencePositionWithOrientationSerializer()

  def writeOptionalReferencePos(kryo: Kryo, output: Output, optRefPos: Option[ReferencePositionWithOrientation]) = {
    optRefPos match {
      case None =>
        output.writeBoolean(false)
      case Some(refPos) =>
        output.writeBoolean(true)
        rps.write(kryo, output, refPos)
    }
  }

  def readOptionalReferencePos(kryo: Kryo, input: Input): Option[ReferencePositionWithOrientation] = {
    val exists = input.readBoolean()
    if (exists) {
      Some(rps.read(kryo, input, classOf[ReferencePositionWithOrientation]))
    } else {
      None
    }
  }

  def write(kryo: Kryo, output: Output, obj: ReferencePositionPair) = {
    writeOptionalReferencePos(kryo, output, obj.read1refPos)
    writeOptionalReferencePos(kryo, output, obj.read2refPos)
  }

  def read(kryo: Kryo, input: Input, klazz: Class[ReferencePositionPair]): ReferencePositionPair = {
    val read1ref = readOptionalReferencePos(kryo, input)
    val read2ref = readOptionalReferencePos(kryo, input)
    new ReferencePositionPair(read1ref, read2ref)
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (C) 2016 Simon Vig Therkildsen
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~    http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginBottom="6dip"
    android:layout_marginTop="6dip"
    android:background="@color/contentBackground"
    android:gravity="center_vertical"
    android:orientation="vertical">

  <LinearLayout
      android:id="@+id/header"
      android:layout_width="match_parent"
      android:layout_height="56dp"
      android:background="@color/toolbarColor"
      android:gravity="center_vertical"
      android:orientation="horizontal">

    <LinearLayout
        android:id="@+id/widget_header"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:orientation="vertical">

      <TextView
          android:id="@+id/widget_title"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:layout_gravity="center_vertical"
          android:text="@string/appwidget_header_upcoming"
          android:textAppearance="?attr/textAppearanceSubtitle2"
          android:textColor="@color/appwidget_toolbar_title"
          android:textSize="18sp"/>
    </LinearLayout>
  </LinearLayout>

  <ListView
      android:id="@android:id/list"
      android:layout_width="match_parent"
      android:layout_height="0dp"
      android:layout_weight="1"
      android:cacheColorHint="#00000000"/>
</LinearLayout>


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2017.07.24 at 05:36:05 PM EEST
//

package lt.registrucentras.esaskaita.integration.entity.beans.fvais;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import com.google.common.base.Objects;
import lt.registrucentras.esaskaita.integration.entity.beans.common.AbstractMessageWithRefType;

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

 * <complexType>
 *   <complexContent>
 *     <extension base="{urn:finmin:esaskaita:integration:common}AbstractMessageWithRefType">
 *       <sequence>
 *         <element name="Invoices" minOccurs="0">
 *           <complexType>
 *             <complexContent>
 *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                 <sequence>
 *                   <element name="Invoice" type="{urn:finmin:esaskaita:integration:fvais}InvoiceWithIdAndState" maxOccurs="unbounded"/>
 *                 </sequence>
 *               </restriction>
 *             </complexContent>
 *           </complexType>
 *         </element>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "invoices"
})
@XmlRootElement(name = "GetInvoiceStateListResponse")
public class GetInvoiceStateListResponse
    extends AbstractMessageWithRefType
    implements Serializable
{

    private final static long serialVersionUID = 1L;
    @XmlElement(name = "Invoices")
    protected GetInvoiceStateListResponse.Invoices invoices;

    /**
     * Default no-arg constructor
     *
     */
    public GetInvoiceStateListResponse() {
        super();
    }

    /**
     * Fully-initialising value constructor
     *
     */
    public GetInvoiceStateListResponse(final String guid, final Calendar time, final String systemCode, final String refGUID, final GetInvoiceStateListResponse.Invoices invoices) {
        super(guid, time, systemCode, refGUID);
        this.invoices = invoices;
    }

    /**
     * Gets the value of the invoices property.
     *
     * @return
     *     possible object is
     *     {@link GetInvoiceStateListResponse.Invoices }
     *
     */
    public GetInvoiceStateListResponse.Invoices getInvoices() {
        return invoices;
    }

    /**
     * Sets the value of the invoices property.
     *
     * @param value
     *     allowed object is
     *     {@link GetInvoiceStateListResponse.Invoices }
     *
     */
    public void setInvoices(GetInvoiceStateListResponse.Invoices value) {
        this.invoices = value;
    }

    public GetInvoiceStateListResponse withInvoices(GetInvoiceStateListResponse.Invoices value) {
        setInvoices(value);
        return this;
    }

    @Override
    public GetInvoiceStateListResponse withRefGUID(String value) {
        setRefGUID(value);
        return this;
    }

    @Override
    public GetInvoiceStateListResponse withGUID(String value) {
        setGUID(value);
        return this;
    }

    @Override
    public GetInvoiceStateListResponse withTime(Calendar value) {
        setTime(value);
        return this;
    }

    @Override
    public GetInvoiceStateListResponse withSystemCode(String value) {
        setSystemCode(value);
        return this;
    }

    @Override
    public String toString() {
        return Objects.toStringHelper(this).add("guid", guid).add("time", time).add("systemCode", systemCode).add("refGUID", refGUID).add("invoices", invoices).toString();
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(guid, time, systemCode, refGUID, invoices);
    }

    @Override
    public boolean equals(Object other) {
        if (this == other) {
            return true;
        }
        if (other == null) {
            return false;
        }
        if (getClass()!= other.getClass()) {
            return false;
        }
        final GetInvoiceStateListResponse o = ((GetInvoiceStateListResponse) other);
        return ((((Objects.equal(guid, o.guid)&&Objects.equal(time, o.time))&&Objects.equal(systemCode, o.systemCode))&&Objects.equal(refGUID, o.refGUID))&&Objects.equal(invoices, o.invoices));
    }

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

     * <complexType>
     *   <complexContent>
     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     *       <sequence>
     *         <element name="Invoice" type="{urn:finmin:esaskaita:integration:fvais}InvoiceWithIdAndState" maxOccurs="unbounded"/>
     *       </sequence>
     *     </restriction>
     *   </complexContent>
     * </complexType>
     *

     *
     *
     */
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {
        "invoice"
    })
    public static class Invoices implements Serializable
    {

        private final static long serialVersionUID = 1L;
        @XmlElement(name = "Invoice", required = true)
        protected List<InvoiceWithIdAndState> invoice;

        /**
         * Default no-arg constructor
         *
         */
        public Invoices() {
            super();
        }

        /**
         * Fully-initialising value constructor
         *
         */
        public Invoices(final List<InvoiceWithIdAndState> invoice) {
            this.invoice = invoice;
        }

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

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

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

         *    getInvoice().add(newItem);
         *

         *
         *
         *

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

        public GetInvoiceStateListResponse.Invoices withInvoice(InvoiceWithIdAndState... values) {
            if (values!= null) {
                for (InvoiceWithIdAndState value: values) {
                    getInvoice().add(value);
                }
            }
            return this;
        }

        public GetInvoiceStateListResponse.Invoices withInvoice(Collection<InvoiceWithIdAndState> values) {
            if (values!= null) {
                getInvoice().addAll(values);
            }
            return this;
        }

        @Override
        public String toString() {
            return Objects.toStringHelper(this).add("invoice", invoice).toString();
        }

        @Override
        public int hashCode() {
            return Objects.hashCode(invoice);
        }

        @Override
        public boolean equals(Object other) {
            if (this == other) {
                return true;
            }
            if (other == null) {
                return false;
            }
            if (getClass()!= other.getClass()) {
                return false;
            }
            final GetInvoiceStateListResponse.Invoices o = ((GetInvoiceStateListResponse.Invoices) other);
            return Objects.equal(invoice, o.invoice);
        }

    }

}


text:
<?php
if( session::verify() === true ) {
	// user is authorized, regenerate session
	session::regenerate();

	// you should verify the token on each request through post or get.
	// if posting as part of a form
	$token = '';
	$error = '';
	if(isset($_POST['csrf'])) { $token = trim(filter_input(INPUT_POST, 'csrf', FILTER_SANITIZE_SPECIAL_CHARS, array('flags' => FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH))); }
	elseif( isset($_REQUEST['csrf']) ) { $token = trim(filter_input(INPUT_GET, 'csrf', FILTER_SANITIZE_SPECIAL_CHARS, array('flags' => FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH))); }
	if($token != $_SESSION['csrf']) {
		session::destroy();
		$error = 'CSRF Attack Detected';
	}

	if(empty($error)) {
		// regenerate csrf token
		$newtoken = session::csrf(true);

		// get information about logged in user
		$userinfo = users::info($_SESSION['user']);

		if(empty($userinfo['otp'])) {
			// display add authenticator form

			// OTP Stuff
			otp::$algorithm = OTP_ALGORITHM;
			otp::$digits	= OTP_LENGTH;
			otp::$company	= OTP_COMPANY;
			$otp = isset($_SESSION['otp']) ? $_SESSION['otp'] : otp::GenerateSecret( $_SESSION['user'] );
			$_SESSION['otp'] = $otp;
			otp::SetSecret($_SESSION['user'], $otp);

			// regenerate and save session data
			session::regenerate();

			// check if form was submitted, and if so, grab values
			$scratch_codes = '';
			if(!empty($_POST)) {
				$password = trim(filter_input(INPUT_POST, 'password', FILTER_SANITIZE_SPECIAL_CHARS, array('flags' => FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH)));
				$otpcode = trim(filter_input(INPUT_POST, 'code', FILTER_SANITIZE_SPECIAL_CHARS, array('flags' => FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH)));

				// get scratch codes
				$scratch_codes = users::addotp( $_SESSION['user'], $password, $otp, $otpcode );
			}

			if(empty($scratch_codes)) {
				$qrcode = otp::GenerateQRCode();

				if(!empty($_POST)) { $error = 'Invalid Credentials'; }

				// display authenticator form
				$smarty
					->assign('QRCODE',				$qrcode['image'])
					->assign('TITLE',				'Authenticator | Add')
					->assign('FORM',				'add');
			} else {
				// show scratch codes
				$smarty
					->assign('CODES',				$scratch_codes)
					->assign('TITLE',				'Authenticator | Scratch Codes')
					->assign('FORM',				'scratch');
			}

		} else {
			// display remove authenticator form
			$success = false;
			if(!empty($_POST)) {
				$password = trim(filter_input(INPUT_POST, 'password', FILTER_SANITIZE_SPECIAL_CHARS, array('flags' => FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH)));
				$otpcode  = trim(filter_input(INPUT_POST, 'code', FILTER_SANITIZE_SPECIAL_CHARS, array('flags' => FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH)));

				if(!empty($password) && !empty($otpcode)) {
					otp::$algorithm = OTP_ALGORITHM;
					otp::$digits	= OTP_LENGTH;
					otp::$company	= OTP_COMPANY;
					otp::SetSecret($_SESSION['user'], $userinfo['otp']);
					$code = otp::GetCode();

					if($code->code == $otpcode) {
						// remove authenticator
						if(users::remove_otp($userinfo['username'], $password)) {
							$success = true;
						}
					} else {
						// will automatically remove authenticator if code is scratch code
						if(users::validate($userinfo['username'], $password, $otpcode) === false) {
							$error = 'Invalid Credentials';
						} else {
							$success = true;
						}
					}
				}
			}

			if($success === true) {
				$smarty
					->assign('TITLE',				'Authenticator | Removed')
					->assign('FORM',				'removed');
			} else {
				$smarty
					->assign('TITLE',				'Authenticator | Remove')
					->assign('FORM',				'remove');
			}

		}

		$smarty
			->assign('THEME',				APP_THEME)
			->assign('SMARTY_TEMPLATES',	SMARTY_DIR_TEMPLATES)
			->assign('CSRF',				$newtoken,	true)
			->assign('ERROR',				$error)
			->assign('USER',				$userinfo)
			->assign('ADMIN',				($userinfo['acl'] > ACL_ADMIN_MAX || $userinfo['acl'] < ACL_ADMIN_MIN) ? false : true )
			->assign('NOTIFICATIONS',		users::notifications($_SESSION['user']))

			->display(APP_THEME . '/authenticator.tpl');
		exit(0);

	} else {
		echo $error;
	}

} else {
	// this page requires the user to login
	redirect('login');
}


text:
#ifndef WELS_ACCESS_UNIT_WRITER_H__
#define WELS_ACCESS_UNIT_WRITER_H__

#include "parameter_sets.h"
#include "param_svc.h"
#include "utils.h"
namespace WelsEnc {
/*!
 *************************************************************************************
 * \brief	to write Sequence Parameter Set (SPS)
 *
 * \param 	pSps     	SWelsSPS to be wrote
 * \param	bs_aux		bitstream writer auxiliary
 *
 * \return	0 - successed
 *		    1 - failed
 *
 * \note	Call it in case EWelsNalUnitType is SPS.
 *************************************************************************************
 */

int32_t WelsWriteSpsNal (SWelsSPS* pSps, SBitStringAux* pBitStringAux, int32_t* pSpsIdDelta);

/*!
 *************************************************************************************
 * \brief	to write SubSet Sequence Parameter Set
 *
 * \param 	sub_sps		subset pSps parsed
 * \param	bs_aux		bitstream writer auxiliary
 *
 * \return	0 - successed
 *		    1 - failed
 *
 * \note	Call it in case EWelsNalUnitType is SubSet SPS.
 *************************************************************************************
 */
int32_t WelsWriteSubsetSpsSyntax (SSubsetSps* pSubsetSps, SBitStringAux* pBitStringAux , int32_t* pSpsIdDelta);

/*!
 *************************************************************************************
 * \brief	to write Picture Parameter Set (PPS)
 *
 * \param 	pPps     	pPps
 * \param	bs_aux		bitstream writer auxiliary
 *
 * \return	0 - successed
 *		    1 - failed
 *
 * \note	Call it in case EWelsNalUnitType is PPS.
 *************************************************************************************
 */
int32_t WelsWritePpsSyntax (SWelsPPS* pPps, SBitStringAux* pBitStringAux, SParaSetOffset* sPSOVector);

/*!
 * \brief	initialize pSps based on configurable parameters in svc
 * \param	pSps				SWelsSPS*
 * \param   pLayerParam     SSpatialLayerConfig  dependency layer parameter
 * \param	pLayerParamInternal		SSpatialLayerInternal*, internal dependency layer parameter
 * \param	iSpsId			SPS Id
 * \return	0 - successful
 *			1 - failed
 */
int32_t WelsInitSps (SWelsSPS* pSps, SSpatialLayerConfig* pLayerParam, SSpatialLayerInternal* pLayerParamInternal,
                     const uint32_t kuiIntraPeriod, const int32_t kiNumRefFrame,
                     const uint32_t kiSpsId, const bool kbEnableFrameCropping, bool bEnableRc,
                     const int32_t kiDlayerCount,bool bSVCBaselayer);

/*!
 * \brief	initialize subset pSps based on configurable parameters in svc
 * \param	pSubsetSps		SSubsetSps*
 * \param   pLayerParam     SSpatialLayerConfig  dependency layer parameter
 * \param	pLayerParamInternal		SSpatialLayerInternal*, internal dependency layer parameter
 * \param	kiSpsId			SPS Id
 * \return	0 - successful
 *			1 - failed
 */
int32_t WelsInitSubsetSps (SSubsetSps* pSubsetSps, SSpatialLayerConfig* pLayerParam,
                           SSpatialLayerInternal* pLayerParamInternal,
                           const uint32_t kuiIntraPeriod, const int32_t kiNumRefFrame,
                           const uint32_t kiSpsId, const bool kbEnableFrameCropping, bool bEnableRc,
                           const int32_t kiDlayerCount);

/*!
 * \brief	initialize pPps based on configurable parameters and pSps(subset pSps) in svc
 * \param	pPps							SWelsPPS*
 * \param	pSps							SWelsSPS*
 * \param	pSubsetSps					SSubsetSps*
 * \param   kbDeblockingFilterPresentFlag			bool
 * \param	kiPpsId						PPS Id
 * \param	kbUsingSubsetSps					bool
 * \return	0 - successful
 *			1 - failed
 */
int32_t WelsInitPps (SWelsPPS* pPps,
                     SWelsSPS* pSps,
                     SSubsetSps* pSubsetSps,
                     const uint32_t kuiPpsId,
                     const bool kbDeblockingFilterPresentFlag,
                     const bool kbUsingSubsetSps,
                     const bool kbEntropyCodingModeFlag);

int32_t WelsCheckRefFrameLimitationNumRefFirst (SLogContext* pLogCtx, SWelsSvcCodingParam* pParam);
int32_t WelsCheckRefFrameLimitationLevelIdcFirst (SLogContext* pLogCtx, SWelsSvcCodingParam* pParam);

int32_t WelsAdjustLevel (SSpatialLayerConfig* pSpatialLayer);

/*!
 * \brief	check if the current parameter can found a presenting sps
 * \param	pParam		      the current encoding paramter in SWelsSvcCodingParam
 * \param	kbUseSubsetSps	bool
 * \param	iDlayerIndex		int, the index of current D layer
 * \param	iDlayerCount	  int, the number of total D layer
 * \param pSpsArray			  array of all the stored SPSs
 * \param	pSubsetArray		array of all the stored Subset-SPSs
 * \return	0 - successful
 *			   -1 - cannot find existing SPS for current encoder parameter
 */
int32_t FindExistingSps (SWelsSvcCodingParam* pParam, const bool kbUseSubsetSps, const int32_t iDlayerIndex,
                         const int32_t iDlayerCount,  const int32_t iSpsNumInUse,
                         SWelsSPS* pSpsArray,
                         SSubsetSps* pSubsetArray,
                         bool bSVCBaselayer);
}
#endif//WELS_ACCESS_UNIT_PARSER_H__


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

   <meta http-equiv="content-type" content="text/html; charset=utf-8" />
   <title>git ready » {{ page.title }}</title>
   <meta name="author" content="Nick Quaranto, Alexey Bobyakov" />
   <link href="http://feeds2.feedburner.com/git-ready" rel="alternate" title="RSS" type="application/rss+xml" />
   <link rel="stylesheet" href="/css/reset.css" type="text/css" media="screen, projection" />
   <link rel="stylesheet" href="/css/screen.css" type="text/css" media="screen, projection" />
   <link rel="stylesheet" href="/css/960.css" type="text/css" media="screen, projection" />

git ready

Изучайте Git коммит за коммитом

Автор — Ник Куаранто, перевод — Алексей Бобьяков

      {{ content }}

начинающим

      {% for post in site.categories.beginner %}
        {{ post.title }}
      {% endfor %}

продолжающим

      {% for post in site.categories.intermediate %}
        {{ post.title }}
      {% endfor %}

опытным

      {% for post in site.categories.advanced %}
        {{ post.title }}
      {% endfor %}

Ссылки

      Git Community Book
      GitHub Guides
      GitWiki
      GitCasts
      Git for everyone
      Git-SVN Crash Course
      $ cheat git
      Why Git is Better Than X
      Git for Computer Scientists
      Git Magic
      Gitology
      gitguru
      Pro Git Book
      Git Guys

        О сайте
        Исходный текст
        Отправить совет
        RSS
        Twitter

        Сайт доступен на:
        немецком |
        испанском |
        french |
        английском |
        hebrew |
        итальянском |
        japanese |
        korean |
        dutch |
        португальском |
        шведском |
        вашем языке?


text:
package org.janvs.junit.helpers;

import org.janvs.annotations.JanusOptions;
import org.janvs.annotations.UnderTest;
import org.janvs.specs.TestCase;
import org.janvs.specs.TestSuite;
import org.janvs.specs.TestClassData;
import org.junit.Ignore;
import org.junit.Test;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public final class TestContainerReader {
    private final Class<?> testContainer;

    public TestContainerReader(final Class<?> testContainer) {
        this.testContainer = testContainer;
    }

    public TestClassData getTestClassData() throws IllegalAccessException, InstantiationException {
        final Field interfaceUnderTest = getInterfaceUnderTest();
        final String basePackage = getBasePackageUnderTest();
        final TestSuite testSuite = new TestSuite(getTestCases());

        return new TestClassData(testContainer.newInstance(), testSuite, interfaceUnderTest, basePackage);

    }

    private List<TestCase> getTestCases() {
        final ArrayList<TestCase> testCases = new ArrayList<TestCase>();
        for (final Method method : testContainer.getDeclaredMethods()) {
            if (isATestMethod(method)) {
                testCases.add(new TestCase(method));
            }
        }
        return testCases;
    }

    private Field getInterfaceUnderTest() {
        final Field[] fields = testContainer.getDeclaredFields();
        Field fieldUnderTest = null;
        int numberOfFieldsUnderTest = 0;
        for (final Field field : fields) {
            if (isUnderTest(field)) {
                numberOfFieldsUnderTest++;
                fieldUnderTest = field;
            }
        }
        if (numberOfFieldsUnderTest == 1) {
            return fieldUnderTest;
        }
        if (numberOfFieldsUnderTest > 1) {
            throw new RuntimeException("Multiple fields designated as @" + UnderTest.class.getName());
        }
        throw new RuntimeException("No field designated as @" + UnderTest.class.getName());
    }

    private String getBasePackageUnderTest() {
        for (final Annotation annotation : testContainer.getAnnotations()) {
            if (annotation.annotationType().equals(JanusOptions.class)) {
                final JanusOptions options = (JanusOptions) annotation;
                return options.basePackage();
            }
        }
        throw new RuntimeException("Base package not defined in @" + JanusOptions.class.getName() + " annotation");
    }

    private boolean isUnderTest(final Field field) {
        return field.getAnnotation(UnderTest.class) != null;
    }

    private boolean isATestMethod(final Method method) {
        return method.getAnnotation(Test.class) != null && method.getAnnotation(Ignore.class) == null;
    }
}


text:
/*

This class represent the turret of the 2012 robot.

It is a thread so that auto-tracking runs in the background in terms of the rest
of the robot operation.

*/

package edu.wpi.first.wpilibj.templates;

import edu.wpi.first.wpilibj.DriverStationLCD;
import edu.wpi.first.wpilibj.camera.AxisCamera;
import edu.wpi.first.wpilibj.camera.AxisCameraException;
import edu.wpi.first.wpilibj.can.CANTimeoutException;
import edu.wpi.first.wpilibj.image.ColorImage;
import edu.wpi.first.wpilibj.image.BinaryImage;
import edu.wpi.first.wpilibj.image.NIVisionException;
import edu.wpi.first.wpilibj.image.ParticleAnalysisReport;

//------------------------------------------------------------------------------
public class Turret extends Thread {
//------------------------------------------------------------------------------

    public class FoundRectangle {
        public double target;
        public double distance;
        public boolean confidence;
        public int pixelWidth;

        public FoundRectangle(double target, double dist, boolean confidence, int pixelWidth) {
            this.target = target;
            this.distance = dist;
            this.confidence = confidence;
            this.pixelWidth = pixelWidth;
        }
    }

    /**
     * sweep back and forth between positive and negative angles
     */
    class Sweeper {
        int state = 0;
        double val[];

        /**
         * create a sweeper class
         *
         * @param val an array of alternating (pod/neg) angles. if first pos, last should be neg/
         */
        public Sweeper(double[] val) {
            this.val = val;
        }

        /**
         * make sweep start over
         */
        public void reset() {
            state = 0;
        }

        /**
         * do one iteration of the sweep returning a relative movement value
         *
         * @param turretAngle specify the current turret position
         * @param inc the value of the increment passed back
         * @return the increment as either positive or negative for direction
         */
        public double sweep(double turretAngle, double inc) {
            for (int i=0; i<3; i++) {
                if (state >= val.length)
                    state = 0;

                double sval = val[state];

                if (sval < 0) {
                    if (turretAngle < sval)
                        state++;
                    else
                        return Math.min(sval, -inc);
                } else {
                    if (turretAngle > sval)
                        state++;
                    else
                        return Math.min(sval, inc);
                }
            }
            return 0;
        }
    }

    final int TARGET_LOCK_RANGE_PIXELS = 5;   // offset around centered for tracking

    final int STATE_TRACK           = 1;
    final int STATE_SPECIAL_SEARCH  = 2;
    final int STATE_BACK            = 3;
    final int STATE_GENERAL_SEARCH  = 4;
    final int STATE_GENERAL_SEARCH1 = 5;

    int state = STATE_GENERAL_SEARCH;

    final int camera_Angle = 22; //HARTFORD CHANGE "22 for original angle"

    final int RGB_FILTER_R_MIN =   0; //0 HARTFORD CHANGE
    final int RGB_FILTER_R_MAX = 150; //150
    final int RGB_FILTER_G_MIN = 200; //200
    final int RGB_FILTER_G_MAX = 255; //255
    final int RGB_FILTER_B_MIN = 100; //100
    final int RGB_FILTER_B_MAX = 255; //255

    final double qualityMin = 20.0;
    final double qualityMax = 40.0;

    final double SMALLEST_TARGETING_INCREMENT_DEGREES  = 0.13;
    double lsInc = 8.6;  // degrees
    double lastDistance = 15.0;

    // used to control whether tracking thread is enabled
    boolean image = true;
    boolean shouldTrack = false;
    boolean holdHome = false;
    boolean testState = false;
    boolean manualTrack = false;
    boolean isTargetLocked = false;

    FoundRectangle result;
    AxisCamera cam;
    DriverStationLCD screen;
    TurretRotationControl turretRCntl = new TurretRotationControl();

    // define a sweep pattern relative to 0
    double s[] = {3, -5, 10, -15, 20, -25, 5, -10, 25, -30, 30, -3};
    Sweeper sweeper = new Sweeper(s);

    //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    public void run() {
    //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        ColorImage img;
        BinaryImage binImg;
        double screenCenter;
        ParticleAnalysisReport[] particle;

        cam = AxisCamera.getInstance();
        screen = DriverStationLCD.getInstance();

        // assume the robot is correctly aligned at power up

        try {
            System.out.println("\n $$$$$$$$$$$$$$$$$ THREAD IS HERE $$$$$$$$$$$$$$$$$$\n");

            while (true) {

                if (!cam.freshImage()) {
                    yield();
                    continue;
                }

               // sleep1(3000);

                isTargetLocked = false;

                //
                // image acquistion and basic analysis
                //
                img = cam.getImage();
                if (image)
                {
                img.write("/ColorImage.jpg");
                image  = false;
                }
                binImg = img.thresholdRGB(RGB_FILTER_R_MIN, RGB_FILTER_R_MAX, RGB_FILTER_G_MIN, RGB_FILTER_G_MAX, RGB_FILTER_B_MIN, RGB_FILTER_B_MAX);

                img.free();

                particle = binImg.getOrderedParticleAnalysisReports(10);
                screenCenter = binImg.getWidth()/2.0;
                binImg.free();

                result = isFound(particle);
                if (result != null) {
                    double error = result.target - screenCenter;

                    //System.out.println("\nTargeting Error (pixels)" + error);

                    double d = result.distance/12;
                    int ft = (int)Math.floor(d);
                    //System.out.println("Distance: " + ft + " ft " + (d-ft)*12 + " in");
                    screen.println(DriverStationLCD.Line.kMain6, 1, "Distance: " + ft + " ft " + (d - ft) * 12 + " in");

                    // see if we are close enough
                    if (Math.abs(error) <= TARGET_LOCK_RANGE_PIXELS) {
                        isTargetLocked = result.confidence;
                        //System.out.println("\n############################## TRACKING LOCK ###############################\n");
                        screen.println(DriverStationLCD.Line.kUser5, 1, "------@@@@@@@@@@@@@@@@@@@@@@@@TARGET LOCK@@@@@@@@@@@@@@@@@@@@@---------");
                    // else apply correction
                    }else{
                        screen.println(DriverStationLCD.Line.kUser5, 1, "                                                                                ");
                    }
                    screen.updateLCD();
                    if (doAim()){
                        double ca = getTargetingCorrectionAngle(error, result.distance, result.pixelWidth);
                       // System.out.println("Tracking (correction angle applied): " + ca);
                        turretRCntl.setAngleRelative(ca, 1000);
                    }
                } else{
                    if(doAim())
                    {
                        turretRCntl.goHome();
                    }
                }

                //
                // do we see the rectangles
                //

            }

        } catch (AxisCameraException ex) {
            ex.printStackTrace();
        } catch (NIVisionException ex) {
            ex.printStackTrace();
        } catch (CANTimeoutException ex) {
            ex.printStackTrace();
        }

        try {
            turretRCntl.goHome();
        } catch (CANTimeoutException ex) {
            ex.printStackTrace();
        }

        image = true;
    }

    /**
     * Calculates the relative movement angle needed to correct the targeting
     * error.
     *
     * @param  targetingErrorPixels specifies the number of pixels and direction of the error
     * @param  targetDistanceInches  specifies the distance from the target in inches
     * @return the relative angle in degrees that should be moved.
     */
    protected double getTargetingCorrectionAngle(double targetingErrorPixels, double targetDistanceInches, int pixelWidth) {
        double corr;
        double pixelPerDeg = Math.tan(Math.toRadians(1)) * targetDistanceInches * pixelWidth/24.0;
       // System.out.println("PixelWidth" + pixelWidth);
       // System.out.println("pixel per degrees  " + pixelPerDeg);

        corr = Math.abs(targetingErrorPixels / pixelPerDeg);

        corr = Math.max(corr, SMALLEST_TARGETING_INCREMENT_DEGREES);
        return targetingErrorPixels > 0.0 ? corr: -corr;
    }
    protected double getSearchCorrectionAngle(double targetDistanceInches) {
        double corr;
        if (targetDistanceInches < 10*12) {
            corr = 5;
        } else if (targetDistanceInches < 20*12) {
            corr = 10;
        } else {
            corr = 7;
        }

        return corr;
    }

    /**
     * returns the distance to the target in inches
     *
     * @param width  width of one of the found rectangles
     */
    protected double distanceInches(int width) {
        return 24 * 320 / (width * Math.tan(Math.toRadians(camera_Angle))); //HARTFORD CHANGE
    }

    /**
     * determines if the two center height rectangles are visible to the camera
     *
     * @param particle  array from the NIvision system
     # @return null if false else the data needed for tracking
     */
    protected FoundRectangle isFound(ParticleAnalysisReport[] particle) {
        int cnt = 0, rcnt = 0;
        double dist = 0.0;
        int left = 100000;
        int right = -100000;
        int top = 1000000;
        double topcenter = 10000000.0;
        double lavg = 0;
        int leftTop = 0, rightTop = 0, rightWidth = 0, pixelWidth = 0;
        //System.out.println();

        //
        // must search all found particles for rectangles (particles with desired a 'quality')
        //
        for (int i=0; i < particle.length; i++) {
            ParticleAnalysisReport p = particle[i];
            double ratio = p.boundingRectWidth * 1.0 / p.boundingRectHeight;
            //System.out.println("ratio  "+ratio);
            //System.out.println(+ i + " , " + p.boundingRectLeft + " , " + p.boundingRectTop+ " , " + p.particleQuality + " , " + p.boundingRectWidth + " , " + p.boundingRectHeight);

            // based on ratio
            if (1.15 < ratio && ratio < 1.45 && p.boundingRectWidth > 45) {

                if (p.boundingRectTop < top){
                    lastDistance = dist = distanceInches(p.boundingRectWidth);
                    top = p.boundingRectTop;
                    topcenter = p.boundingRectLeft + p.boundingRectWidth/2.0;
                }

                //System.out.println("ratio: " + ratio + "Left Top Coor. "+ p.boundingRectLeft+ " , "+ p.boundingRectTop);
                rcnt++;
            }

            // based on quality
            if (qualityMin < p.particleQuality && p.particleQuality < qualityMax) {
                if (cnt == 0){
                    lastDistance = dist = distanceInches(p.boundingRectWidth);
                    pixelWidth = p.boundingRectWidth;
                }
                cnt++;

                if (p.boundingRectLeft < left) {
                    left = p.boundingRectLeft;
                    leftTop = p.boundingRectTop;
                }

                if (p.boundingRectLeft > right){
                    right = p.boundingRectLeft;
                    rightTop = p.boundingRectTop;
                    rightWidth = p.boundingRectWidth;
                }
            } else {
                lavg += p.boundingRectTop;
            }
        }

        //System.out.println("Average Left:" + (lavg/(particle.length - cnt)));

        // see if we have the middle row
        if (cnt >= 2 && Math.abs(leftTop - rightTop) < 11) {
           // System.out.println("\n ####Two Rectangle Search#### \n");
            return new FoundRectangle(left + (right + rightWidth -left)/2.0, dist, true, pixelWidth);
        }
        else if (rcnt >= 1){
          //  System.out.println("\n ****Top Rectangle Search**** \n");
            return new FoundRectangle(topcenter, dist, rcnt > 1, pixelWidth);
        }
        else
            return null;
    }

    /**
     * check to see of the robot has it's back to our targets
     *
     * @return boolean of the check
     */

    public synchronized boolean doAim() {
        return manualTrack;
    }

    public synchronized void setAim(boolean manualTrack) {
        this.manualTrack = manualTrack;
    }

    public synchronized void setTestState(boolean testState) {
        this.testState = testState;
    }

    public synchronized boolean getTestState() {
        return testState;
    }

    protected void sleep1(long ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException ex) {

        }
    }

    public void setX(double xVal){
        try {
            turretRCntl.setAngleRelative(xVal * 4.0, 10);
        } catch (CANTimeoutException ex) {
            ex.printStackTrace();
        }
    }

    /* try new light ,
     * fps for diff resolution: 640-480 is approx.4.5 FPS: 480-360 is approx. 10 FPS :320-240 is approx. 15 FPS: 240-180 is approx. 17 FPS: 160-120 is approx. 24 however it is inaccurate due to an occilating camera ,
     * gyro,
     * RGB far distance is  R: 0/150 G: 170/255 B: 0/255;
     * distance */
}


text:
use strict;
use warnings;
use Pod::Usage;
use Data::Dumper;
use Getopt::Long;
use File::Spec;
use Bio::TreeIO;

### args/flags
pod2usage("$0: No files given.") if ((@ARGV == 0) && (-t STDIN));

my ($verbose, $species_in, $gene_in, $tformat);
my ($sregex, $gregex);
my $nclade = 4;
my $brlen;
GetOptions(
	   "species=s" => \$species_in,			# tree file
	   "gene=s" => \$gene_in,
	   "format=s" => \$tformat,				# tree format
	   "sregex=s" => \$sregex, 				# altering species tree names
	   "gregex=s" => \$gregex, 				# altering gene tree names
	   "clade=i" => \$nclade, 				# number of clades
	   "brlen=f" => \$brlen, 				# brlen jump for collapsing clades
	   "verbose" => \$verbose,
	   "help|?" => \&pod2usage # Help
	   );

### I/O error & defaults
die " Provide a species tree file (newick or nexus).\n" if ! $species_in;
#die " Provide a gene tree file (newick or nexus).\n" if ! $gene_in;
$tformat = check_tree_format($tformat);
$sregex = qr/$sregex/ if $sregex;
$gregex = qr/$gregex/ if $gregex;

### MAIN
# loading species tree #
my $streeo = tree_io($species_in, $tformat);

# collapsing tips #
## adding brlen if not present ##
#add_brlen($streeo);

## getting max branch length
#my $max_brlen = max_brlen($streeo);
my $max_brlen = max_height($streeo);
$brlen = $max_brlen / 50 unless $brlen;

## collapsing ##
$streeo = collapse_tips_brlen($species_in, $nclade, $brlen, $max_brlen);

#print Dumper $streeo; exit;

# writing modified tree #
tree_write($streeo);

### Subroutines
sub tree_write{
	### writting out a nexus tree file ###
	my ($treeo) = @_;

	my $out = new Bio::TreeIO(-fh => \*STDOUT, -format => "newick");
	$out->write_tree($treeo);
	}

sub add_brlen{
	my ($treeo) = @_;

	foreach my $node ($treeo->get_nodes){
		$node->branch_length($brlen) unless $node->branch_length();
		}
	}

sub collapse_tips_brlen{
# collapsing #
	my ($species_in, $nclade, $brlen, $max_brlen) = @_;

	my $nclade_brlen;
	for (my $i=0; $i<=$max_brlen; $i+=$brlen){
		my $treeo_tmp = tree_io($species_in, $tformat);		# loading tree each time

		for my $node ($treeo_tmp->get_nodes){
			next if $node->is_Leaf;					# no collapsign of leaves directly

			# collapsing node #
			my @rm_list;
			if($node->height < $i){
				my $rm_num = 0;
				# removing leaf nodes 1st #
				for my $child ( $node->each_Descendent ){
					next unless $child->is_Leaf;

					push(@rm_list, $child->id);

						#print $child->id, "\n";
					$treeo_tmp->remove_Node($child);
					$rm_num++;
					}

				# removing internal nodes #
				if ($rm_num){
					for my $child ( $node->each_Descendent ){
						push(@rm_list, $child->id) if $child->id;
						$treeo_tmp->remove_Node($child);
						}
					}

				# new name for node #
				next unless @rm_list;		# only if something was removed

				# appending leaf names to node #
				if($node->id){
					$node->id( join("__", $node->id, @rm_list)); }
				else{
					$node->id( join("__", @rm_list));
					}
				}
			}

		# if N-nodes == $nclade, return nodes #
		my $nnodes = scalar $treeo_tmp->get_leaf_nodes;
		print STDERR "...Branch length cutoff: $i; Number of clades: $nnodes\n";
		return $treeo_tmp if $nnodes <= $nclade;
		}

	die " ERROR: the desired number of clades ($nclade) could not be found!\n";
	}

sub max_height{
	my ($treeo) = @_;

	# getting max branch length between nodes #
	my $max_brlen = 0;
	for my $node ($treeo->get_nodes){
		next if $node->is_Leaf;
		$max_brlen = $node->height if $node->height > $max_brlen;
		}
	print STDERR "...max branch length between leaves: $max_brlen\n";

	return $max_brlen;
	}

sub max_brlen{
	my ($treeo) = @_;

	# getting max branch length between nodes #
	my $max_brlen = 0;
	for my $node1 ($treeo->get_leaf_nodes){
		for my $node2 ($treeo->get_leaf_nodes){
			next if $node1->id eq $node2->id;
			my $dist = $treeo->distance(-nodes => [$node1, $node2]);
			$max_brlen = $dist if $dist > $max_brlen;
			}
		}
	print STDERR "...max branch length between leaves: $max_brlen\n";

	return $max_brlen;
	}

sub tree_io{
	# loading tree object #
	my ($tree_in, $format) = @_;
	my $input = Bio::TreeIO->new(-file => $tree_in,
								-format => $format);
	my $treeio = $input->next_tree;
	return $treeio;
	}

sub check_tree_format{
	my $format = shift;
	$format = "newick" if ! $format;
	$format =~ s/^new$/newick/i;
	$format =~ s/^nex$/nexus/i;
	die " Designated tree format ($format) not recognized.\n" if $format !~ /newick|nexus/;
	return $format;
	}

__END__

=pod

=head1 NAME

tree_collapse_tips.pl -- collapsing tips by a branch length cutoff

=head1 SYNOPSIS

tree_collapse_tips.pl [flags]

=head2 require flags

=over

=item -t

Tree file (newick or nexus).

=back

=head2 optional flags

=over

=item -format

Tree file format (newick or nexus). [newick]

=item -length

Branch length cutoff. [< 0]

=item -count

Count file in Mothur format

=item -meta

Metadata file in ITOL format

=item -color

Color file in ITOL format

=item -regex

Regular expression for excluding taxa from being collapsed.

=item -branch

Write out all branch lengths (internal nodes to most distant decendent).

=item -v	Verbose output

=item -h	This help message

=back

=head2 For more information:

perldoc tree_collapse_tips.pl

=head1 DESCRIPTION

Collapse branches in a tree that have a branch length of < (-length)
from the ancestral node.

Collapsed nodes are labeled as: "collapsed-nodeID"_"number_taxa_collapsed"

If any metadata files are provided (count, ITOL-metadata, color),
the taxon labels are updated and the abundances are summed. A random
taxon in a collapsed clade will be used for the color info if a
color file is provided.

Output file names are based on input file names ("*br-col*")

=head2 WARNING

'-count' flag not fully tested!

=head1 EXAMPLES

=head2 Getting branch length distribution

tree_collapse_tips.pl -t tree.nwk -branch

=head2 Collapse tree with a metadata file

tree_collapse_tips.pl -t tree.nwk -meta meta.txt

=head2 Collapse tree with a count file

tree_collapse_tips.pl -t tree.nwk -count count.txt

=head1 AUTHOR

Nick Youngblut <nyoungb2@illinois.edu>

=head1 AVAILABILITY

sharchaea.life.uiuc.edu:/home/git/tree_edit/

=head1 COPYRIGHT

Copyright 2010, 2011
This software is licensed under the terms of the GPLv3

=cut


text:
package org.ritvik;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.annotation.WebServlet;

import org.apache.log4j.Logger;

/**
 * Servlet implementation class TestServlet
 */
@WebServlet("/TestServlet")
public class TestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private Logger logger = Logger.getLogger("org.ritvik.processLog");

    /**
     * Default constructor.
     */
    public TestServlet() {

    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.debug("Entered TestServlet");
		TestDao dao = new TestDao();

		response.getWriter().append("Served at: ").append(request.getContextPath());
		try {
			response.getWriter().append("\nName is: ").append(dao.getData());
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}


text:
from __future__ import print_function
from hyperopt import Trials, STATUS_OK, tpe
from hyperas import optim
from hyperas.distributions import choice, uniform

def keras_model():
    from keras.datasets import mnist
    from keras.models import Sequential
    from keras.layers.core import Dense, Dropout, Activation
    from keras.optimizers import RMSprop
    from keras.utils import np_utils

    (X_train, y_train), (X_test, y_test) = mnist.load_data()
    X_train = X_train.reshape(60000, 784)
    X_test = X_test.reshape(10000, 784)
    X_train = X_train.astype('float32')
    X_test = X_test.astype('float32')
    X_train /= 255
    X_test /= 255
    nb_classes = 10

    Y_train = np_utils.to_categorical(y_train, nb_classes)
    Y_test = np_utils.to_categorical(y_test, nb_classes)

    model = Sequential()
    model.add(Dense(512, input_shape=(784,)))
    model.add(Activation('relu'))
    model.add(Dropout({{uniform(0, 1)}}))
    model.add(Dense({{choice([256, 512, 1024])}}))
    model.add(Activation('relu'))
    model.add(Dropout({{uniform(0, 1)}}))
    model.add(Dense(10))
    model.add(Activation('softmax'))

    rms = RMSprop()
    model.compile(loss='categorical_crossentropy', optimizer=rms)

    model.fit(X_train, Y_train,
              batch_size={{choice([64, 128])}},
              nb_epoch=1,
              show_accuracy=True,
              verbose=2,
              validation_data=(X_test, Y_test))
    score = model.evaluate(X_test, Y_test,
                           show_accuracy=True, verbose=0)
    print('Test accuracy:', score[1])
    return {'loss': -score[1], 'status': STATUS_OK}

if __name__ == '__main__':
    best_run = optim.minimize(keras_model,
                              algo=tpe.suggest,
                              max_evals=10,
                              trials=Trials())
    print(best_run)


text:
#include <aws/ivs/model/ServiceQuotaExceededException.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace IVS
{
namespace Model
{

ServiceQuotaExceededException::ServiceQuotaExceededException() :
    m_exceptionMessageHasBeenSet(false)
{
}

ServiceQuotaExceededException::ServiceQuotaExceededException(JsonView jsonValue) :
    m_exceptionMessageHasBeenSet(false)
{
  *this = jsonValue;
}

ServiceQuotaExceededException& ServiceQuotaExceededException::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("exceptionMessage"))
  {
    m_exceptionMessage = jsonValue.GetString("exceptionMessage");

    m_exceptionMessageHasBeenSet = true;
  }

  return *this;
}

JsonValue ServiceQuotaExceededException::Jsonize() const
{
  JsonValue payload;

  if(m_exceptionMessageHasBeenSet)
  {
   payload.WithString("exceptionMessage", m_exceptionMessage);

  }

  return payload;
}

} // namespace Model
} // namespace IVS
} // namespace Aws


text:
package net.sf.kraken.protocols.oscar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.kano.joscar.DefensiveTools;
import net.kano.joscar.snac.SnacRequest;

/**
 * Handles pending SNAC commands.
 *
 * @author Daniel Henninger
 * Heavily inspired by joscardemo from the joscar project.
 */
public class PendingSnacMgr {

    protected Map<Integer,List<SnacRequest>> snacs = new HashMap<Integer,List<SnacRequest>>();

    public boolean isPending(int familyCode) {
        return snacs.containsKey(familyCode);
    }

    public void add(SnacRequest request) {
        Integer family = request.getCommand().getFamily();

        List<SnacRequest> pending = snacs.get(family);

        pending.add(request);
    }

    public List<SnacRequest> getPending(int familyCode) {
        List<SnacRequest> pending = snacs.get(familyCode);
        return DefensiveTools.getUnmodifiableCopy(pending);
    }

    public void setPending(int familyCode, boolean pending) {
        if (pending) {
            snacs.put(familyCode, new ArrayList<SnacRequest>());
        }
        else {
            snacs.remove(familyCode);
        }
    }
}


text:
This is the sample application for
[*The Odin Project*](http://www.theodinproject.com/).

## Getting started

To get started with the app, clone the repo and then install the needed gems:

```
$ bundle install --without production
```

Next, migrate the database:

```
$ rails db:migrate
```

Finally, run the test suite to verify that everything is working correctly:

```
$ rails test
```

If the test suite passes, you'll be ready to run the app in a local server:

```
$ rails server
```

For more information, see the
[*The Odin Project*](http://www.theodinproject.com/).


text:
@interface NGModel : NSObject

- (NSString *)className;
+ (NSString *)className;
+ (NSString *)pluralizedName;
- (NSString *)descriptionString;

@end

#import "NGModel+Serialization.h"
#import "NGModel+Validations.h"
#import "NGModel+Instantation.h"


text:
package org.csi.yucca.fabriccontroller.beans;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import org.apache.commons.io.FileUtils;
import org.csi.yucca.fabriccontroller.objects.CustomLogger;
import org.csi.yucca.fabriccontroller.objects.UtilClass;
import org.csi.yucca.fabriccontroller.objects.json.JsonPojo;
import org.csi.yucca.fabriccontroller.objects.json.detailTenant.JsonDettaglioTenantPojo;
import org.csi.yucca.fabriccontroller.objects.json.jenkinsStatus.JenkinsStatusBuild;
import org.csi.yucca.fabriccontroller.objects.json.negativeUpdateStatusResult.NegativeResult;
import org.csi.yucca.fabriccontroller.objects.json.positiveUpdateStatusResult.PositiveResult;
import org.csi.yucca.fabriccontroller.objects.json.stream.JsonStreamPojo;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * Created with IntelliJ IDEA.
 * User: Stefano Porro - Consoft SpA
 * Date: 30/09/2014
 * Time: 14:38
 */
public class InstallTenantBeanExecutor extends AbstractExecutorBean
{
    //Logger logger = Logger.getLogger("fabriccontroller");
    CustomLogger logger = CustomLogger.getInstance();

    JsonDettaglioTenantPojo pojo;

    //old
    //install|tenant|nometenant|user|pwd|target
    //                   0        1   2    3
    //old
    //install|tenant|nometenant|user|pwd
    //                   0        1   2
    //new
    //install|tenant|nometenant
    //

    public String elaboraRichiesta() throws Exception{
        String tagSvn = UtilClass.getLastTag(getProperties().getTenantSvnUrl(), getProperties().getTenantSvnUser(), getProperties().getTenantSvnPwd());
        pojo = (JsonDettaglioTenantPojo) createFmppFile();

    	//logger.info("[InstallTenantBeanExecutor::elaboraRichiesta] userName " + pojo.getUsername() );
        String jenkinsUrl = getProperties().getJenkinsPrefix() + getProperties().getTenantMavenJobName() + "/buildWithParameters";
        String jenkinsParams = "tagName=" + tagSvn + "&tenantName=" + getParams().get(0) + "&mvnRepo=" + getProperties().getMavenLocalRepo()
                + "&tenantUser=" + pojo.getTenantcode() + "&tenantPassword=" + pojo.getPassword()+ "&targetEnv=" + getProperties().getEnvPropertiesFile(); //getParams().get(3);
        JenkinsCaller jenkinsCaller = new JenkinsCaller(jenkinsUrl, getProperties().getJenkinsAuth(), jenkinsParams).invoke();
        JenkinsStatusBuild status = jenkinsCaller.getStatus();
        String buildNumber = jenkinsCaller.getBuildNumber();
        if (status.getResult().equals("SUCCESS"))
        {
            String pathBuild = getProperties().getTenantJenkinsBuildPath();
            pathBuild = pathBuild.replace("@buildNumber@", buildNumber).replace("@tenantName@", getParams().get(0));
            String pathDest = getProperties().getLocalArtifactsArchive() + "/TenantInstall/" + buildNumber;
            FileUtils.forceMkdir(new File(pathDest));
            FileUtils.copyDirectory(new File(pathBuild), new File(pathDest));
            logger.info("InstallTenantBeanExecutor terminated",key);
            return pathDest;
        } else
            throw new Exception("Il build numero " + buildNumber + " non e' andato a buon fine");

    }

    public JsonPojo createFmppFile()
            throws IOException, InvocationTargetException, NoSuchMethodException, IllegalAccessException

    {
    	JsonDettaglioTenantPojo pojo = createPojoJsonObject();
    	logger.info("POJO - " + pojo.toString(), key);

        //UtilClass.createFileFmpp(pojo, getProperties());
        if (new File("./config_tenant_template.fmpp").exists())
            UtilClass.createFileFmppFromTemplate(pojo, getProperties(),
                    //new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("config_template.fmpp")));
                    //new FileInputStream(this.getClass().getClassLoader().getResource("config_template.fmpp").getPath()));
                    new FileInputStream("./config_tenant_template.fmpp"), 1, getParams());
        else
            UtilClass.createFileFmppFromTemplate(pojo, getProperties(),
                    //new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("config_template.fmpp")));
                    new FileInputStream(
                            this.getClass().getClassLoader().getResource("config_tenant_template.fmpp").getPath()), 1,
                    getParams());
        //new FileInputStream("./config_template.fmpp"));
        return pojo;
    }

    private JsonDettaglioTenantPojo createPojoJsonObject() throws IOException
    {

        //0 = codice tenant
        //1 = codice virtual entity
        //2 = codice stream
        String dettaglioTenant = UtilClass.getJsonFromUrl(getProperties().getServiceDettaglioTenant() + getParams().get(0));
        setJsonCallDetail(dettaglioTenant);

        logger.info(dettaglioTenant, key);

        /*Type componentType = new TypeToken<List<Element>>()
        {
        }.getType();*/
        //JSONObject jsonObject = new JSONObject(json);
        //JSONArray jsonArray = jsonObject.getJSONArray("streamInternalChildren");
        Gson gson = new Gson();
                //new GsonBuilder().registerTypeAdapter(componentType, new ArrayOrSingleStreamElementAdapter<Element>())
                //        .create();
        return gson.fromJson(dettaglioTenant, JsonDettaglioTenantPojo.class);
    }

    public String generateKey()
    {
        this.key = getOperation()+ "_tenant_" + getParams().get(0);
        return this.key;
    }

    @Override
    public void updateStatus(boolean result, String message) throws Exception {
        if(getOperation().equals("migrate"))
        {
        	return;
        }
        else {
        	String resultStr = result ? "ok" : "ko";
	    	String jsonRequest = "{\"status\": \"" + resultStr+"\"}";
	    	logger.info("ResultUpdate:" +jsonRequest, "");
	        String urlToUpdate = getProperties().getUrlTenantUpdate();
	        urlToUpdate = urlToUpdate.replace("@tenantcode@", pojo.getTenantcode());
	        logger.info("UrlUpdate:" +urlToUpdate, "");
	       UtilClass.putJsonFromUrlWithJsonParameter(urlToUpdate, jsonRequest);

        }
    }
}


text:
Loopback Stats Mixin - CHANGELOG
=============

The **loopback-stats-mixin** module change .

- **Version 1.2.2**.-
    - Fixed issues on custom dates.
- **Version 1.2.1**.-
    - Removed then to avoid duplicated callbacks.
- **Version 1.2.0**.-
    - Migrated to @mean-expert scope for fireloop usage.
- **Version 1.1.9**.-
    - Fixed headers already set issue in wrapper
- **Version 1.1.8**.-
    - Fixed headers already set issue in stats
- **Version 1.1.7**.-
    - Parse universal time as integer
    - Implemented groupBy functionallity
    - Implemented new unit test
- **Version 1.1.6**.-
    - Replaced by 1.1.7
- **Version 1.1.5**.-
    - Implemented universal time in response
- **Version 1.1.4**.-
    - Fixed issue on yearly range
- **Version 1.1.3**.-
    - Replaced by 1.1.4
- **Version 1.1.2**.-
    - Updated loopback explorer documentation
- **Version 1.1.1**.-
    - Hotfix missing babel-runtime in package.json
- **Version 1.1.0**.-
    - Implemented Babel.
    - Fully implemented ES6.
    - Refactor project structure.
    - Removed unnecessary PK Builder.
    - Updated documentation.
    - Implemented & passed ESLINT tests.
    - Implemented unit tests.
    - Corrected ranges from hourly to yearly according right definition
    - Removed node_modules from repo and added .gitignore
    - Added development tools, gulp, mocha, etc. (see package.json)
- **Version 1.0.4**.-
    - Refactor PrimaryKey Builder <https://github.com/victorhqc>.
    - Implemented Custom Range
- **Version 1.0.3**.-
    - Refactor builders into different files.
    - Improved properties description for swagger by more specific details.
    - Added Stats Wrapper example in README.md
- **Version 1.0.2**.-
    - Added validation to verify micro-services to be wrapped actually exists.
    - Added custom primary key support.
- **Version 1.0.1**.-
    - Added Stats Mixin Wrapper
- **Version 1.0.0**.-
    - Created Stats Mixin
    - Initial Publish

For issues or contributions: https://github.com/jonathan-casarrubias/loopback-stats-mixin.

LICENSE
=============
[MTI](LICENSE)


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta http-equiv="Pragma" content="no-cache">
        <title>Andean Naturals - Process</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width">

        <link rel="stylesheet" href="../css/normalize.css">
        <link rel="stylesheet" href="../css/main.css">
        <link rel="stylesheet" href="../css/anslide.css">
        <link href='http://fonts.googleapis.com/css?family=Fjalla+One' rel='stylesheet' type='text/css'>
		<link href='http://fonts.googleapis.com/css?family=IM+Fell+English' rel='stylesheet' type='text/css'>

        	<map name="sidepapermap">
				<area coords="156,176,90" href="../" title="Andean Naturals" shape="circle" />

        	</map>

    			 When Antonio Salazar was six years old, he figured out how to repair his family's TV. Today, his business card says Technical Specialist. Calmly intense behind lab mask and goggles,
    			 he continues to excel at making things work better… especially at developing new products and smarter processes to refine the refining of quinoa.

Antonio joined Andean Naturals in 2005. He embodies the devotion that ensures that all quinoa passing through our processing facility in El Alto resumes its journey with its nourishing goodness vibrantly alive. All he and his team removes is fragments of seedpod, stalk, grit, quartz and other tiny nuisances.

					<map name="iconslinksmap">
						<area coords="0,0,23,23" href="https://www.facebook.com/AndeanNaturals?ref=hl" target="_blank" shape="rect" />
						<area coords="30,0,53,23" href="https://pinterest.com" target="_blank" shape="rect" />
						<area coords="60,0,83,23" href="https://twitter.com/AndeanNaturals" target="_blank" shape="rect" />
						<area coords="90,0,113,23" href="http://www.bcorporation.net/" target="_blank" shape="rect" />
						<area coords="120,0,143,23" href="http://www.fairtradeusa.org/" target="_blank" shape="rect" />
					</map>

CONTACT

NEWS

FAQ

BLOG

PASSION

MISSION

PROCESS

PRODUCTS

SUPER FOOD


text:
// Copyright 2008 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.opengse.handlers;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import javax.servlet.ServletResponse;
import javax.servlet.ServletRequest;
import javax.servlet.FilterChain;

/**
 * An implementation of RequestHandler that only returns 404's
 *
 * @author Mike Jennings
 */
public final class NotFoundHandler implements FilterChain {
  public void doFilter(ServletRequest request,
      ServletResponse resp) throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) resp;
    response.setStatus(HttpServletResponse.SC_NOT_FOUND);
  }
}


text:
set -e
set -x

# apt-get update
apt-get install salt-master salt-minion debconf-utils -y --force-yes
service salt-master restart
cp -rf etc/salt /etc
service salt-minion restart

salt-call state.highstate


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="Encoding">
    <file url="file://$PROJECT_DIR$" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/comics-blog-business" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/comics-blog-data" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/comics-blog-web" charset="UTF-8" />
    <file url="PROJECT" charset="UTF-8" />
  </component>
</project>


text:
Installation for Mac OS X
=========================
The cryptography.io requirement is a statically linked build for Yosemite and above.
You only need one step:

.. code:: console

    $ pip install oneid-connect

If you're using an older version of OS X or want to link to a specific version
of openSSL you will need a C compiler, development headers and possibly
even the openSSL Library. This is all provided by Apple's Xcode development tools.

.. code:: console

    $ xcode-select --install

This will install a compiler and the development libraries required.


text:
import os
import unittest

from attributes.unit_test.discoverer import get_test_discoverer
from tests import get_lsloc, REPOS_PATH

class CppTestDiscovererTestCase(unittest.TestCase):
    def setUp(self):
        self.discoverer = get_test_discoverer('C++')

    @unittest.skipIf(not os.path.exists(REPOS_PATH), 'setup.sh not run.')
    def test_discover(self):
        # Test: Project using Boost
        path = os.path.join(REPOS_PATH, 'externals-clasp')
        proportion = self.discoverer.discover(path)
        self.assertLess(0, proportion)

        # Test: Project with no unit tests (when these tests were written)
        path = os.path.join(REPOS_PATH, 'electron')
        proportion = self.discoverer.discover(path)
        self.assertEqual(0, proportion)

        # Test: Project in Ruby to simulate a project with no C source code
        path = os.path.join(REPOS_PATH, 'squib')
        proportion = self.discoverer.discover(path)
        self.assertEqual(0, proportion)

    @unittest.skipIf(not os.path.exists(REPOS_PATH), 'setup.sh not run.')
    def test_assert(self):
        # Test: Project using assert.h
        path = os.path.join(REPOS_PATH, 'IEDiagnosticsAdapter')
        proportion = self.discoverer.__assert__(
            path, get_lsloc(path, self.discoverer.languages)
        )
        self.assertLess(0, proportion)

        # Test: Project not using assert.h
        path = os.path.join(REPOS_PATH, 'electron')
        proportion = self.discoverer.__assert__(
            path, get_lsloc(path, self.discoverer.languages)
        )
        self.assertEqual(0, proportion)

    @unittest.skipIf(not os.path.exists(REPOS_PATH), 'setup.sh not run.')
    def test_boost(self):
        # Test: Project using Boost
        path = os.path.join(REPOS_PATH, 'externals-clasp')
        proportion = self.discoverer.__boost__(
            path, get_lsloc(path, self.discoverer.languages)
        )
        self.assertLess(0, proportion)

        # Test: Project not using Boost
        path = os.path.join(REPOS_PATH, 'openage')
        proportion = self.discoverer.__boost__(
            path, get_lsloc(path, self.discoverer.languages)
        )
        self.assertEqual(0, proportion)

    @unittest.skipIf(not os.path.exists(REPOS_PATH), 'setup.sh not run.')
    def test_catch(self):
        # Test: Project using Catch
        path = os.path.join(REPOS_PATH, 'variant')
        proportion = self.discoverer.__catch__(
            path, get_lsloc(path, self.discoverer.languages)
        )
        self.assertLess(0, proportion)

        # Test: Project not using Catch
        path = os.path.join(REPOS_PATH, 'electron')
        proportion = self.discoverer.__catch__(
            path, get_lsloc(path, self.discoverer.languages)
        )
        self.assertEqual(0, proportion)

    @unittest.skipIf(not os.path.exists(REPOS_PATH), 'setup.sh not run.')
    def test_gtest(self):
        # Test: Project using GTest
        path = os.path.join(REPOS_PATH, 'angle')
        proportion = self.discoverer.__gtest__(
            path, get_lsloc(path, self.discoverer.languages)
        )
        self.assertLess(0, proportion)

        # Test: Project not using Gtest
        path = os.path.join(REPOS_PATH, 'electron')
        proportion = self.discoverer.__gtest__(
            path, get_lsloc(path, self.discoverer.languages)
        )
        self.assertEqual(0, proportion)

    @unittest.skipIf(not os.path.exists(REPOS_PATH), 'setup.sh not run.')
    def test_stout_gtest(self):
        # Test: Project using Stout Gtest
        path = os.path.join(REPOS_PATH, 'mesos')
        proportion = self.discoverer.__stout_gtest__(
            path, get_lsloc(path, self.discoverer.languages)
        )
        self.assertLess(0, proportion)

        # Test: Project not using Stout Gtest
        path = os.path.join(REPOS_PATH, 'electron')
        proportion = self.discoverer.__boost__(
            path, get_lsloc(path, self.discoverer.languages)
        )
        self.assertEqual(0, proportion)


text:
import Resource from './resource';
import defaultResolver from './default-resolver';

// GraphQL
import shopQuery from './graphql/shopQuery.graphql';
import shopPolicyQuery from './graphql/shopPolicyQuery.graphql';

/**
 * The JS Buy SDK shop resource
 * @class
 */
class ShopResource extends Resource {

  /**
   * Fetches shop information (`currencyCode`, `description`, `moneyFormat`, `name`, and `primaryDomain`).
   * See the {@link https://help.shopify.com/api/storefront-api/reference/object/shop|Storefront API reference} for more information.
   *
   * @example
   * client.shop.fetchInfo().then((shop) => {
   *   // Do something with the shop
   * });
   *
   * @return {Promise|GraphModel} A promise resolving with a `GraphModel` of the shop.
   */
  fetchInfo() {
    return this.graphQLClient
      .send(shopQuery)
      .then(defaultResolver('shop'));
  }

  /**
   * Fetches shop policies (privacy policy, terms of service and refund policy).
   *
   * @example
   * client.shop.fetchPolicies().then((shop) => {
   *   // Do something with the shop
   * });
   *
   * @return {Promise|GraphModel} A promise resolving with a `GraphModel` of the shop.
   */
  fetchPolicies() {
    return this.graphQLClient
      .send(shopPolicyQuery)
      .then(defaultResolver('shop'));
  }
}

export default ShopResource;


text:
<?php

/** @file   dba_dump.php
 * @brief   Program DBA dump utility
 * @ingroup Examples
 * @author  Marcus Boerger
 * @date    2003 - 2005
 *
 * Usage: php dba_dump.php \<file\> \<handler\> [\<regex\>]
 *
 * Show all groups in the ini file specified by \<file\>.
 * The regular expression \<regex\> is used to filter the by setting name.
 *
 * Note: configure with --enable-dba
 */

if ($argc < 3) {
	echo <<<EOF
Usage: php ${_SERVER['PHP_SELF']} <file> <handler> [<regex>]

Show all groups in the ini file specified by <file>.
The regular expression <regex> is used to filter the by setting name.

EOF;
	exit(1);
}

if (!class_exists("DbaReader", false)) require_once("dbareader.inc");
if (!class_exists("KeyFilter", false)) require_once("keyfilter.inc");

$db = new DbaReader($argv[1], $argv[2]);

if ($argc>3) {
	$db = new KeyFilter($db, $argv[3]);
}

foreach($db as $key => $val) {
	echo "'$key' => '$val'\n";
}

?>


text:
/**
 *   Web service interface which relies on reslet to process the http queries.
 */
package org.daisy.pipeline.webservice.impl;


text:
package multiverse.mars.behaviors;

import multiverse.msgsys.*;
import multiverse.server.objects.*;
import multiverse.server.engine.*;
import multiverse.server.util.*;
import multiverse.server.plugins.*;
import multiverse.server.messages.*;
import multiverse.mars.plugins.*;
import multiverse.mars.objects.*;

public class CombatBehavior extends Behavior implements MessageCallback {
    public CombatBehavior() {
	super();
    }

    public CombatBehavior(SpawnData data) {
	super(data);
	String value = (String)data.getProperty("combat.aggressive");
	if (value != null) {
	    setAggressive(Boolean.valueOf(value));
	}
	value = (String)data.getProperty("combat.reactionRadius");
	if (value != null) {
	    setReactionRadius(Integer.valueOf(value));
	}
	value = (String)data.getProperty("combat.movementSpeed");
	if (value != null) {
	    setMovementSpeed(Integer.valueOf(value));
	}
    }

    public void initialize() {
        SubjectFilter filter = new SubjectFilter(obj.getOid());
        filter.addType(CombatClient.MSG_TYPE_DAMAGE);
        filter.addType(PropertyMessage.MSG_TYPE_PROPERTY);
        if (aggressive) {
            filter.addType(ObjectTracker.MSG_TYPE_NOTIFY_REACTION_RADIUS);
        }
        eventSub = Engine.getAgent().createSubscription(filter, this);
    }
    public void activate() {
	activated = true;
	if (aggressive) {
	    Log.debug("CombatBehavior.activate: adding reaction radius");
	    MobManagerPlugin.getTracker(obj.getInstanceOid()).addReactionRadius(obj.getOid(), reactionRadius);
	}
    }
    public void deactivate() {
	lock.lock();
	try {
	    activated = false;
	    if (eventSub != null) {
	        Engine.getAgent().removeSubscription(eventSub);
		eventSub = null;
	    }
	}
	finally {
	    lock.unlock();
	}
    }

    public Boolean getAggressive() {
	return aggressive;
    }
    public void setAggressive(Boolean val) {
	aggressive = val;
    }
    protected Boolean aggressive = Boolean.FALSE;

    public void setMovementSpeed(int speed) {
        this.speed = new Integer(speed);
    }
    public int getMovementSpeed() {
        return speed.intValue();
    }
    protected Integer speed = new Integer(6000);

    public void setReactionRadius(int radius) {
	reactionRadius = radius;
    }
    public int getReactionRadius() {
	return reactionRadius.intValue();
    }
    protected Integer reactionRadius = new Integer(10000);

    public void handleMessage(Message msg, int flags) {
	lock.lock();
	try {
	    if (activated == false) {
		return;
	    }
	    if (msg instanceof CombatClient.DamageMessage) {
		CombatClient.DamageMessage dmgMsg = (CombatClient.DamageMessage)msg;
		attackTarget(dmgMsg.getAttackerOid());
	    }
	    if (msg.getMsgType() == ObjectTracker.MSG_TYPE_NOTIFY_REACTION_RADIUS) {
		if (!aggressive) {
		    return;
		}
		ObjectTracker.NotifyReactionRadiusMessage nMsg = (ObjectTracker.NotifyReactionRadiusMessage)msg;
                if (Log.loggingDebug)
                    Log.debug("CombatBehavior.onMessage: got reaction message=" + nMsg);
		if (nMsg.getInRadius() && (currentTarget == null)) {
                    Long targetOid = nMsg.getTarget();
		    Long subjectOid = nMsg.getSubject();
		    ObjectStub subject = (ObjectStub)EntityManager.getEntityByNamespace(subjectOid, Namespace.MOB);
                    if (Log.loggingDebug)
                        Log.debug("CombatBehavior.onMessage: targetOid=" + targetOid + " subjectOid=" + subjectOid + " subject=" + subject + " type=" + subject.getType());
		    if (subject.getType() != ObjectTypes.player) {
			return;
		    }
		    attackTarget(subjectOid);
		}
	    }
	    if (msg instanceof PropertyMessage) {
		PropertyMessage propMsg = (PropertyMessage) msg;
		Boolean dead = (Boolean)propMsg.getProperty(CombatInfo.COMBAT_PROP_DEADSTATE);
		if (dead != null && dead) {
                    if (Log.loggingDebug)
                        Log.debug("CombatBehavior.onMessage: obj=" + obj + " got death=" + propMsg.getSubject() + " currentTarget=" + currentTarget);
		    if (propMsg.getSubject() == obj.getOid()) {
			Log.debug("CombatBehavior.onMessage: mob died, deactivating all behaviors");
			for(Behavior behav : obj.getBehaviors()) {
			    behav.deactivate();
			    obj.removeBehavior(behav);
			}
		    }
		    else if (propMsg.getSubject() == currentTarget) {
			attackTarget(null);
		    }
		}
	    }
	    //return true;
	}
	finally {
	    lock.unlock();
	}
    }

    protected void attackTarget(Long targetOid) {
        if (Log.loggingDebug)
            Log.debug("CombatBehavior.attackTarget: obj=" + obj + " targetOid=" + targetOid);

	if (targetSub != null) {
	    Engine.getAgent().removeSubscription(targetSub);
	}

	currentTarget = targetOid;

	if (currentTarget != null) {
	    SubjectFilter filter = new SubjectFilter(targetOid);
	    filter.addType(PropertyMessage.MSG_TYPE_PROPERTY);
	    targetSub = Engine.getAgent().createSubscription(filter, this);

	    Engine.getAgent().sendBroadcast(new BaseBehavior.FollowCommandMessage(obj, new EntityHandle(currentTarget), speed));
	    CombatClient.autoAttack(obj.getOid(), currentTarget, true);
	}
	else {
	    CombatClient.autoAttack(obj.getOid(), null, false);
	    Engine.getAgent().sendBroadcast(new BaseBehavior.ArrivedEventMessage(obj));
	}
    }

    Long eventSub = null;
    Long targetSub = null;
    protected Long currentTarget = null;
    protected boolean activated = false;
    private static final long serialVersionUID = 1L;
}


text:
package healthcheck

import (
	"crypto/tls"
	"crypto/x509"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"time"

	"github.com/Sirupsen/logrus"
	"github.com/amalgam8/amalgam8/sidecar/config"
)

const (
	defaultHTTPInterval = 30 * time.Second
	defaultHTTPTimeout  = 5 * time.Second
	defaultHTTPMethod   = http.MethodGet
	defaultHTTPCode     = 200
)

// HTTP performs periodic HTTP health checks.
type HTTP struct {
	client *http.Client

	url    string
	method string
	code   int
}

// NewHTTP creates a new HTTP health check.
func NewHTTP(conf config.HealthCheck) (Check, error) {
	if err := validateHTTPConfig(&conf); err != nil {
		return nil, err
	}
	var client *http.Client
	if conf.Type == config.HTTPSHealthCheck &&
		conf.CACertFile != "" {

		logrus.Debug("HTTPS HealthCheck, CA cert file = " + conf.CACertFile)
		// Load trusted CA certs
		caCerts, err := ioutil.ReadFile(conf.CACertFile)
		if err != nil {
			logrus.WithError(err).Debug("Error reading CA trust .pem file: " + conf.CACertFile)
			return nil, err
		}
		certPool := x509.NewCertPool()
		certPool.AppendCertsFromPEM(caCerts)
		tlsConfig := &tls.Config{RootCAs: certPool}
		tlsConfig.BuildNameToCertificate()
		transport := &http.Transport{TLSClientConfig: tlsConfig}
		client = &http.Client{Transport: transport,
			Timeout: conf.Timeout}
	} else {
		logrus.Debug("HTTP HealthCheck: " + conf.Type + " " + conf.CACertFile)
		client = &http.Client{Timeout: conf.Timeout}
	}
	return &HTTP{
		url:    conf.Value,
		client: client,
		method: conf.Method,
		code:   conf.Code,
	}, nil
}

// validateHTTPConfig validates, sanitizes, and sets defaults for an HTTP health check configuration.
func validateHTTPConfig(conf *config.HealthCheck) error {

	// Validate healthcheck type
	switch conf.Type {
	case "", config.HTTPHealthCheck, config.HTTPSHealthCheck:
	default:
		return fmt.Errorf("invalid type for an HTTP healthcheck: '%s'", conf.Type)
	}

	// Validate URL
	if conf.Value == "" {
		return fmt.Errorf("empty URL for HTTP healthcheck")
	}
	u, err := url.Parse(conf.Value)
	if err != nil {
		return fmt.Errorf("error parsing URL '%s' for HTTP healthcheck: %v", conf.Value, err)
	}
	if u.Scheme == "" || u.Host == "" {
		return fmt.Errorf("invalid URL '%s' for HTTP healthcheck", conf.Value)
	}

	// Validate interval
	if conf.Interval == 0 {
		conf.Interval = defaultHTTPInterval
	}

	// Validate timeout
	if conf.Timeout == 0 {
		conf.Timeout = defaultHTTPTimeout
	}

	// Validate method
	switch conf.Method {
	case http.MethodGet, http.MethodHead, http.MethodPost,
		http.MethodPut, http.MethodPatch, http.MethodDelete,
		http.MethodConnect, http.MethodOptions, http.MethodTrace:
	case "":
		conf.Method = defaultHTTPMethod
	default:
		return fmt.Errorf("invalid method for an HTTP healthcheck: '%s'", conf.Method)
	}

	// Validate code
	if conf.Code == 0 {
		conf.Code = defaultHTTPCode
	} else if conf.Code < 100 || conf.Code > 599 {
		return fmt.Errorf("invalid code for an HTTP healthcheck: '%d'", conf.Code)
	}

	return nil
}

// Execute a HTTP operation on the URL and check the response code.
func (h *HTTP) Execute() error {
	req, err := http.NewRequest(h.method, h.url, nil)
	if err != nil {
		return err
	}

	resp, err := h.client.Do(req)
	if err != nil {
		return err
	}

	if resp.StatusCode != h.code {
		return fmt.Errorf("HTTP/HTTPS health check expected %v, got %v", h.code, resp.StatusCode)
	}

	return nil
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
org.apache.poi.hmef (POI API Documentation)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

org.apache.poi.hmef

Classes

Attachment

CompressedRTF

HMEFMessage


text:
using Midori.Runtime;
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace NaiadSimulator
{

  public class TestRegionWindowJoin : TestInterface
  {

    public void Execute(string[] args)
    {
      int windowSize = 4;
      Region actorRegion =
        RegionAllocator.AllocateRegion(NaiadSimulator.ACTOR_REGION_SIZE);
      RegionWindowJoinVertex<Document, Author, int, JoinOutput> windowJoinVertex;
      using (RegionContext regContext = RegionContext.Create(actorRegion))
      {
        windowJoinVertex =
          new RegionWindowJoinVertex<Document, Author, int, JoinOutput>(
            windowSize,
            document => document.authorId,
            author => author.id,
            (document, author) => new JoinOutput(document.title,
                                                 author.name,
                                                 author.age));
        // Note: Depending on how we use batching we may or may not have to
        // clone the fields.
        // (document, author) => new JoinOutput(String.Copy(document.title),
        //                                      String.Copy(author.name),
        //                                      author.age));
      }
      PlayData(windowJoinVertex, args[0], args[1], actorRegion);
      RegionAllocator.FreeRegion(actorRegion);
    }

    public void PlayData(RegionWindowJoinVertex<Document, Author, int, JoinOutput> vertex,
                         string docFileName, string authorFileName,
                         Region actorRegion) {
      if (File.Exists(docFileName) && File.Exists(authorFileName))
      {
        using (StreamReader docFile = File.OpenText(docFileName))
        {
          using (StreamReader authorFile = File.OpenText(authorFileName))
          {
            bool docEmpty = false;
            bool authorEmpty = false;
            Region inputRegion =
              RegionAllocator.AllocateRegion(NaiadSimulator.TMP_REGION_SIZE);
            using (RegionContext regContext = RegionContext.Create(inputRegion))
            {
              while (!docEmpty || !authorEmpty)
              {
                var line = docFile.ReadLine();
                if (line != null)
                {
                  ReadDocBatch(docFile, line, vertex, actorRegion);
                }
                else
                {
                  docEmpty = true;
                }

                line = authorFile.ReadLine();
                if (line != null)
                {
                  ReadAuthorBatch(authorFile, line, vertex, actorRegion);
                }
                else
                {
                  authorEmpty = true;
                }
              }
            }
            RegionAllocator.FreeRegion(inputRegion);
          }
        }
      }
    }

    public void ReadAuthorBatch(StreamReader file,
                                String line,
                                RegionWindowJoinVertex<Document, Author, int, JoinOutput> vertex,
                                Region actorRegion)
    {
      var elements = line.Split(' ');
      if (elements[0] == "BEGIN")
      {
        int time = Convert.ToInt32(elements[1]);
        int batch_size = Convert.ToInt32(elements[2]);
        Message<int, Author> msg =
          new Message<int, Author>(time, batch_size);
        for (int i = 0; i < batch_size; i++)
        {
          elements = file.ReadLine().Split(' ');
          msg.put(new Author(Convert.ToInt32(elements[1]),
                             elements[2],
                             Convert.ToInt32(elements[3])));
        }
        vertex.onReceive(msg, actorRegion);
      }
      else if (elements[0] == "END")
      {
        // NOTE: This is commented because we don't want to call onNotify
        // twice for the same time epoch.
        // vertex.onNotify(Convert.ToInt32(elements[1]));
      }
    }

    public void ReadDocBatch(StreamReader file,
                             String line,
                             RegionWindowJoinVertex<Document, Author, int, JoinOutput> vertex,
                             Region actorRegion)
    {
      var elements = line.Split(' ');
      if (elements[0] == "BEGIN")
      {
        int time = Convert.ToInt32(elements[1]);
        int batch_size = Convert.ToInt32(elements[2]);
        Message<int, Document> msg =
          new Message<int, Document>(time, batch_size);
        for (int i = 0; i < batch_size; i++)
        {
          elements = file.ReadLine().Split(' ');
          msg.put(new Document(Convert.ToInt32(elements[1]),
                               Convert.ToInt32(elements[2]),
                               Convert.ToInt32(elements[3]),
                               elements[4]));
        }
        vertex.onReceive(msg, actorRegion);
      }
      else if (elements[0] == "END")
      {
        vertex.onNotify(Convert.ToInt32(elements[1]));
      }
    }
  }

}


text:
from django import forms
from django.templatetags.static import static
from django.utils.encoding import force_str
from django.utils.html import conditional_escape, format_html
from django.utils.safestring import mark_safe
from django.utils.translation import gettext

from olympia.constants.categories import CATEGORIES_BY_ID

class IconTypeSelect(forms.RadioSelect):
    base_html = (
        '
'
        ''
        ''
        ''
        '{original_widget}'
        '
'
    )

    def render(self, name, value, attrs=None, renderer=None):
        output = []

        for option in self.subwidgets(name, value, attrs):
            option_value = option['value']

            option['widget'] = self.create_option(
                name=name,
                value=option['value'],
                label=option['label'],
                selected=option_value == value,
                index=option['index'],
                attrs=option['attrs'],
            )

            if option_value.split('/')[0] == 'icon' or option_value == '':
                icon_name = option['label']

                original_widget = self._render(self.option_template_name, option)
                if not original_widget.startswith('<label for='):
                    # django2.2+ already wraps widget in a label
                    original_widget = format_html(
                        '{widget}',
                        label_id=option['widget']['attrs']['id'],
                        widget=original_widget,
                    )
                output.append(
                    format_html(
                        self.base_html,
                        active='active' if option_value == value else '',
                        icon_url=static(f'img/addon-icons/{icon_name}-32.png'),
                        icon_name=icon_name,
                        original_widget=original_widget,
                    )
                )
            else:
                output.append(
                    format_html(
                        '
{widget}
',
                        widget=self._render(self.option_template_name, option),
                    )
                )

        return mark_safe('\n'.join(output))

class CategoriesSelectMultiple(forms.CheckboxSelectMultiple):
    """Widget that formats the Categories checkboxes."""

    def __init__(self, **kwargs):
        super(self.__class__, self).__init__(**kwargs)

    def render(self, name, value, attrs=None, renderer=None):
        value = value or []
        has_id = attrs and 'id' in attrs
        final_attrs = self.build_attrs(attrs, {'name': name})

        choices = []
        other = None

        for c in self.choices:
            if CATEGORIES_BY_ID[c[0]].misc:
                msg = gettext("My add-on doesn't fit into any of the categories")
                other = (c[0], msg)
            else:
                choices.append(c)

        choices = list(enumerate(choices))
        choices_size = len(choices)

        groups = [choices]
        if other:
            groups.append([(choices_size, other)])

        str_values = set([force_str(v) for v in value])

        output = []
        for (k, group) in enumerate(groups):
            cls = 'addon-misc-category' if k == 1 else 'addon-categories'
            output.append('
' % cls)

            for i, (option_value, option_label) in group:
                if has_id:
                    final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i))
                    label_for = ' for="%s"' % final_attrs['id']
                else:
                    label_for = ''

                cb = forms.CheckboxInput(
                    final_attrs, check_test=lambda value: value in str_values
                )
                option_value = force_str(option_value)
                rendered_cb = cb.render(name, option_value)
                option_label = conditional_escape(force_str(option_label))
                output.append(
                    '
%s %s
'
                    % (label_for, rendered_cb, option_label)
                )

            output.append('
')

        return mark_safe('\n'.join(output))


text:
<?php

    namespace app\rbac;

    use app\models\User;
    use yii\helpers\ArrayHelper;
    use yii\rbac\Item;
    use yii\rbac\Rule;
    use Yii;

    class AccessToPaymentRule extends Rule
    {

        public $name = 'isCapableToAccessPayment';

        /**
         * Executes the rule.
         *
         * @param string|integer $user the user ID. This should be either an integer or a string representing
         * the unique identifier of a user. See [[\yii\web\User::id]].
         * @param Item $item the role or permission that this rule is associated with
         * @param array $params parameters passed to [[ManagerInterface::checkAccess()]].
         * @return boolean a value indicating whether the rule permits the auth item it is associated with.
         */
        public function execute($user, $item, $params)
        {
            $role = array_keys(Yii::$app->authManager->getRolesByUser($user))[0]; //get role of user to which this rule is applied
            if ($role == User::ROLE_ENDY) {
                return true;
            } elseif ($role == User::ROLE_MAN) {
                return true;
            } elseif ($role == User::ROLE_END_USER) {
                return true;
            } elseif ($role == User::ROLE_DISTR) {
                return true;
            } elseif ($role == User::ROLE_SALES) {
                return true;
            } else {
                return false;
            }
        }
    }


text:
package org.apereo.cas.shell.commands.db;

import org.apereo.cas.shell.commands.BaseCasShellCommandTests;

import lombok.val;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;

import java.io.File;

import static org.junit.jupiter.api.Assertions.*;

/**
 * This is {@link GenerateDdlCommandTests}.
 *
 * @author Misagh Moayyed
 * @since 6.2.0
 */
@EnableAutoConfiguration
public class GenerateDdlCommandTests extends BaseCasShellCommandTests {
    @Test
    public void verifyOperation() throws Exception {
        val file = File.createTempFile("ddl", "sql");
        val result = shell.evaluate(
            () -> "generate-ddl --file " + file + " --dialect HSQL");
        assertNotNull(result);
    }
}


text:
namespace gnet {

class Actor;
class Reactor;
class Buffer;

class Connector : public Handle
{
public:
    Connector(GNet* gnet, Actor* actor, int fd);
    virtual ~Connector();

    // return 0, success
    // return < 0, fail
    int Send(const char* buffer, int len);

    // return bytes should be read
    virtual int OnRead(const char* buffer, int len);

    virtual void OnDisconnect();

private:
    void proc_in();
    void proc_out();

private:
    Buffer* rbuf_;
    Buffer* wbuf_;
    Actor* actor_;
};

}

#endif


text:
package com.toconnor.pool.page;

import com.toconnor.pool.PoolUI;
import com.toconnor.pool.data.UserManager;
import com.toconnor.pool.model.User;
import com.toconnor.pool.util.Formatter;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.CssLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;

/**
 * ConfirmPage
 */
@PageInfo(id="confirm", title="Confirm New Account")
public class ConfirmPage extends AbstractPage
{
	@Override
	protected void render()
	{
		final User user = UserManager.getCurrentUser();
		if(user.isActive())
		{
			//this page is only for first time inactive users
			return;
		}

		CssLayout content = new CssLayout();
		content.addStyleName("content");

		VerticalLayout panel = new VerticalLayout();
		panel.addStyleName("layout-panel");
		panel.addStyleName("padded");
		panel.setMargin(true);
		content.addComponent(panel);

		Label about = new Label("This is the first time that you are attempting to use this account.  " +
				"If this is your first time accessing the site this season then please just verify the account information below.  " +
				"If this is not your first time then it means that you are using a different account than your first visit.  " +
				"This might be because you chose the wrong login provider or are using a shared computer and someone else is logged in.");
		about.addStyleName("h2");
		about.addStyleName("v-table-cell-content-losing");
		panel.addComponent(about);

		panel.addComponent(new Label(""));

		Label name = new Label("Name: " + user.fetchFullName());
		name.addStyleName("h1");
		panel.addComponent(name);

		panel.addComponent(new Label(""));

		Label email = new Label("Email: " + user.getEmail());
		email.addStyleName("h1");
		panel.addComponent(email);

		panel.addComponent(new Label(""));

		Label source = new Label("Provider: " + Formatter.formatProvider(user.getProvider()));
		source.addStyleName("h1");
		panel.addComponent(source);

		panel.addComponent(new Label(""));

		HorizontalLayout buttons = new HorizontalLayout();
		buttons.setMargin(true);
		buttons.setWidth(650, Unit.PIXELS);
		buttons.setHeight(100, Unit.PIXELS);
		panel.addComponent(buttons);

		Button yes = new Button("Yes, this is the account I want to use.");
		yes.addClickListener(new Button.ClickListener()
		{
			@Override
			public void buttonClick(Button.ClickEvent clickEvent)
			{
				user.setActive(true);
				UserManager.saveUser(user);
				UserManager.updateCurrentUser(user);
				UI.getCurrent().getNavigator().navigateTo(PoolPage.HOME.getNav());
			}
		});
		buttons.addComponent(yes);
		buttons.setComponentAlignment(yes, Alignment.MIDDLE_CENTER);

		Button oops = new Button("Oops, I logged in with the wrong account.");
		oops.addClickListener(new Button.ClickListener()
		{
			@Override
			public void buttonClick(Button.ClickEvent clickEvent)
			{
				UserManager.deleteUser(user);
				((PoolUI)UI.getCurrent()).buildLoginView(true);
			}
		});
		buttons.addComponent(oops);
		buttons.setComponentAlignment(oops, Alignment.MIDDLE_CENTER);

		addComponent(content);
		setExpandRatio(content, 1);
	}

	protected boolean allowRender()
	{
		//this ensures that only inactive users are confirmed
		User user = UserManager.getCurrentUser();
		return user != null && !user.isActive();
	}
}