text:
<?php

/**
 * Spiral Framework.
 *
 * @license   MIT
 * @author    Anton Titov (Wolfy-J)
 */

declare(strict_types=1);

namespace Spiral\Cookies;

use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ServerRequestInterface;
use Spiral\Core\Container\SingletonInterface;
use Spiral\Core\Exception\ScopeException;

/**
 * Cookies manages provides the ability to write and read cookies from the active request/response scope.
 */
final class CookieManager implements SingletonInterface
{
    /** @var ContainerInterface */
    private $container;

    /**
     * @param ContainerInterface $container
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    /**
     * @param string $name
     * @return bool
     *
     * @throws ScopeException
     */
    public function has(string $name): bool
    {
        return array_key_exists($name, $this->getRequest()->getCookieParams());
    }

    /**
     * @param string $name
     * @param null   $default
     * @return mixed
     *
     * @throws ScopeException
     */
    public function get(string $name, $default = null)
    {
        return $this->getRequest()->getCookieParams()[$name] ?? $default;
    }

    /**
     * Get all cookies.
     *
     * @return array
     */
    public function getAll(): array
    {
        return $this->getRequest()->getCookieParams();
    }

    /**
     * Schedule new cookie. Cookie will be send while dispatching request.
     *
     * Domain, path, and secure values can be left in null state, in this case cookie manager will
     * populate them automatically.
     *
     * @link http://php.net/manual/en/function.setcookie.php
     *
     * @param string      $name     The name of the cookie.
     * @param string|null $value    The value of the cookie. This value is stored on the clients
     *                              computer; do not store sensitive information.
     * @param int|null    $lifetime Cookie lifetime. This value specified in seconds and declares period
     *                              of time in which cookie will expire relatively to current time()
     *                              value.
     * @param string|null $path     The path on the server in which the cookie will be available on.
     *                              If set to '/', the cookie will be available within the entire
     *                              domain.
     *                              If set to '/foo/', the cookie will only be available within the
     *                              /foo/
     *                              directory and all sub-directories such as /foo/bar/ of domain. The
     *                              default value is the current directory that the cookie is being set
     *                              in.
     * @param string|null $domain   The domain that the cookie is available. To make the cookie
     *                              available
     *                              on all subdomains of example.com then you'd set it to
     *                              '.example.com'.
     *                              The . is not required but makes it compatible with more browsers.
     *                              Setting it to www.example.com will make the cookie only available in
     *                              the www subdomain. Refer to tail matching in the spec for details.
     * @param bool        $secure   Indicates that the cookie should only be transmitted over a secure
     *                              HTTPS connection from the client. When set to true, the cookie will
     *                              only be set if a secure connection exists. On the server-side, it's
     *                              on the programmer to send this kind of cookie only on secure
     *                              connection (e.g. with respect to $_SERVER["HTTPS"]).
     * @param bool        $httpOnly When true the cookie will be made accessible only through the HTTP
     *                              protocol. This means that the cookie won't be accessible by
     *                              scripting
     *                              languages, such as JavaScript. This setting can effectively help to
     *                              reduce identity theft through XSS attacks (although it is not
     *                              supported by all browsers).
     * @param string|null $sameSite The value of the samesite element should be either None, Lax or Strict. If any of
     *                              the allowed options are not given, their default values are the same as the default
     *                              values of the explicit parameters. If the samesite element is omitted, no SameSite
     *                              cookie attribute is set. When Same-Site attribute is set to "None" it is required
     *                              to have "Secure" attribute enable. Otherwise it will be converted to "Lax".
     * @return $this
     *
     */
    public function set(
        string $name,
        ?string $value = null,
        ?int $lifetime = null,
        ?string $path = null,
        ?string $domain = null,
        ?bool $secure = null,
        bool $httpOnly = true,
        ?string $sameSite = null
    ): self {
        $this->getCookieQueue()->set($name, $value, $lifetime, $path, $domain, $secure, $httpOnly, $sameSite);

        return $this;
    }

    /**
     * Schedule new cookie instance to be send while dispatching request.
     *
     * @param Cookie $cookie
     *
     * @return $this
     */
    public function schedule(Cookie $cookie): self
    {
        $this->getCookieQueue()->schedule($cookie);

        return $this;
    }

    /**
     * Schedule cookie removal.
     *
     * @param string $name
     *
     * @throws ScopeException
     */
    public function delete(string $name): void
    {
        $this->getCookieQueue()->delete($name);
    }

    /**
     * Cookies has to be send (specified via global scope).
     *
     * @return Cookie[]
     *
     * @throws ScopeException
     */
    public function getScheduled(): array
    {
        return $this->getCookieQueue()->getScheduled();
    }

    /**
     * @return ServerRequestInterface
     *
     * @throws ScopeException
     */
    private function getRequest(): ServerRequestInterface
    {
        try {
            return $this->container->get(ServerRequestInterface::class);
        } catch (NotFoundExceptionInterface $e) {
            throw new ScopeException('Unable to receive active request', $e->getCode(), $e);
        }
    }

    /**
     * @return CookieQueue
     *
     * @throws ScopeException
     */
    private function getCookieQueue(): CookieQueue
    {
        try {
            return $this->container->get(CookieQueue::class);
        } catch (NotFoundExceptionInterface $e) {
            throw new ScopeException('Unable to receive cookie queue, invalid request scope', $e->getCode(), $e);
        }
    }
}


text:
using System;

namespace Xamarin.Forms.iiCalendar.Droid
{
    public enum RangeState
    {
        None,
        First,
        Middle,
        Last
    }

    public class MonthCellDescriptor : Java.Lang.Object
    {
        public DateTime DateTime { get; set; }
        public int Value { get; set; }
        public bool IsCurrentMonth { get; set; }
        public bool IsSelected { get; set; }
        public bool IsToday { get; set; }
        public bool IsSelectable { get; set; }
        public bool IsHighlighted { get; set; }
        public RangeState RangeState { get; set; }

        public MonthCellDescriptor(DateTime date, bool isCurrentMonth, bool isSelectable, bool isSelected,
            bool isToday, bool isHighlighted, int value, RangeState rangeState)
        {
            DateTime = date;
            Value = value;
            IsCurrentMonth = isCurrentMonth;
            IsSelected = isSelected;
            IsHighlighted = isHighlighted;
            IsToday = isToday;
            IsSelectable = isSelectable;
            RangeState = rangeState;
        }

        public override string ToString()
        {
            return "MonthCellDescriptor{"
                   + "Date=" + DateTime
                   + ", Value=" + Value
                   + ", IsCurrentMonth=" + IsCurrentMonth
                   + ", IsSelected=" + IsSelected
                   + ", IsToday=" + IsToday
                   + ", IsSelectable=" + IsSelectable
                   + ", IsHighlighted=" + IsHighlighted
                   + ", RangeSTate=" + RangeState
                   + "}";
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
using Guardtime.KSI.Exceptions;
using Guardtime.KSI.Service;
using Guardtime.KSI.Test.Properties;
using NUnit.Framework;

namespace Guardtime.KSI.Test.Service
{
    /// <summary>
    /// Extender configuration tests with static response
    /// </summary>
    [TestFixture]
    public class ExtenderConfigRequestStaticTests : StaticServiceTestsBase
    {
        [Test]
        public void BeginetExtenderConfigWithoutExtendingServiceProtocol()
        {
            KsiService service = new KsiService(null, null, null, null, null, null);

            KsiServiceException ex = Assert.Throws<KsiServiceException>(delegate
            {
                service.BeginGetExtenderConfig(null, null);
            });

            Assert.That(ex.Message.StartsWith("Extending service protocol is missing from service"), "Unexpected exception message: " + ex.Message);
        }

        [Test]
        public void BeginGetExtenderConfigWithoutExtendingServiceCredentials()
        {
            TestKsiServiceProtocol protocol = new TestKsiServiceProtocol();
            KsiService service = new KsiService(null, null, protocol, null, null, null);

            KsiServiceException ex = Assert.Throws<KsiServiceException>(delegate
            {
                service.BeginGetExtenderConfig(null, null);
            });

            Assert.That(ex.Message.StartsWith("Extending service credentials are missing."), "Unexpected exception message: " + ex.Message);
        }

        [Test]
        public void EndGetExtenderConfigWithoutExtendingServiceProtocol()
        {
            KsiService service = new KsiService(null, null, null, null, null, null);

            KsiServiceException ex = Assert.Throws<KsiServiceException>(delegate
            {
                service.EndGetExtenderConfig(new TestAsyncResult());
            });

            Assert.That(ex.Message.StartsWith("Extending service protocol is missing from service"), "Unexpected exception message: " + ex.Message);
        }

        /// <summary>
        /// Test extender configuration request
        /// </summary>
        [Test]
        public void ExtenderConfigRequestStaticTest()
        {
            Ksi ksi = GetStaticKsi(Resources.KsiService_ExtenderConfigResponsePdu);

            ExtenderConfig config = ksi.GetExtenderConfig();

            Assert.AreEqual(273, config.MaxRequests, "Unexpected max requests value");
            Assert.AreEqual(1455478441, config.CalendarFirstTime, "Unexpected calendar first time value");
            Assert.AreEqual(1455478442, config.CalendarLastTime, "Unexpected calendar last time value");
        }

        /// <summary>
        /// Test extender configuration request. Warning about unexpected payload is logged.
        /// </summary>
        [Test]
        public void ExtenderConfigRequestWithMultiPayloadsResponseStaticTest()
        {
            // Response has multiple payloads (2 extending payloads and a configuration payload)
            Ksi ksi = GetStaticKsi(Resources.KsiService_ExtendResponsePdu_Multi_Payloads);

            ExtenderConfig config = ksi.GetExtenderConfig();

            Assert.AreEqual(273, config.MaxRequests, "Unexpected max requests value");
            Assert.AreEqual(1455478441, config.CalendarFirstTime, "Unexpected calendar first time value");
            Assert.AreEqual(1455478442, config.CalendarLastTime, "Unexpected calendar last time value");
        }

        /// <summary>
        /// Test extender configuration request fail.
        /// </summary>
        [Test]
        public void ExtenderConfigRequestInvalidStaticTest()
        {
            // pdu does not contain extender config payload
            Ksi ksi = GetStaticKsi(Resources.KsiService_ExtendResponsePdu_RequestId_1043101455);

            KsiServiceException ex = Assert.Throws<KsiServiceException>(delegate
            {
                ksi.GetExtenderConfig();
            });

            Assert.That(ex.Message.StartsWith("Invalid response PDU. Could not find a valid payload."), "Unexpected exception message: " + ex.Message);
        }
    }
}


text:
import java.io.*
import collection.*

object Test {

  def serializeDeserialize[T <: AnyRef](obj: T) = {
    val buffer = new ByteArrayOutputStream
    val out = new ObjectOutputStream(buffer)
    out.writeObject(obj)
    val in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray))
    in.readObject.asInstanceOf[T]
  }

  def main(args: Array[String]): Unit = {
    val values = mutable.Map(1 -> 1).values
    assert(serializeDeserialize(values).toList == values.toList)

    val keyset = mutable.Map(1 -> 1).keySet
    assert(serializeDeserialize(keyset) == keyset)

    val imkeyset = immutable.Map(1 -> 1).keySet
    assert(serializeDeserialize(imkeyset) == imkeyset)

    val defaultmap = immutable.Map(1 -> 1).withDefaultValue(1)
    assert(serializeDeserialize(defaultmap) == defaultmap)

    val minusmap = mutable.Map(1 -> 1).withDefault(x => -x)
    assert(serializeDeserialize(minusmap) == minusmap)
  }

}


text:
module.exports = (function() {
    'use strict';
    var shell = require('shelljs'),
        folderPath = '.envinator';

   return {
        create: createTemp
    };

   ///////////

    function createTemp(){
        shell.rm('-rf',folderPath);
        shell.mkdir(folderPath);
        return folderPath;
    }
})();


text:
<?php

namespace Cine\CinemaBundle\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;

class GenreAdmin extends Admin
{
	protected function configureFormFields(FormMapper $FormMapper){
        $FormMapper
            ->with('Général')
                ->add('nom', null, array(
                    'label' => 'Nom'
                ))
            ->end();
    }

	protected function configureDatagridFilters(DatagridMapper $datagridMapper) {
        $datagridMapper
            ->add('nom');
    }

    protected function configureListFields(ListMapper $listMapper) {
        $listMapper
            ->addIdentifier('nom');
    }
}


text:
This is the code for the paper

Ragav Venkatesan, Parag Shridhar Chandakkar, Baoxin Li "Simpler non-parametric methods provide as good or better results to multiple-instance learning." at the IEEE International Conference on Computer Vision (ICCV), Santiago, Chile, 2015.

The code also contains the DR dataset and one Synthetic datasets. To run the code, simply setup the parameters in `MILLooper.m` and run. The parameters are self-explanatory and are commented upon in a detailed manner in the code itself. The code only has the brute force optimization. Due to license issues I am not able to provide the EMDD version of the code, for which I used the original Y.Chen's executable. It is not difficult to implement from there on. The results are close but are not the same as reported because of the change in optimization methodology.

Thanks for using the code, hope you had fun.

Ragav Venkatesan
http://www.public.asu.edu/~rvenka10


text:
import React from 'react'
import styled from 'styled-components'

export default ({ text }) =>
  <Button>
    {text}
  </Button>

const Button = styled.a`
  border: ${props => props.theme.border};
  border-radius: ${props => props.theme.rounding};
  margin: .5rem;
  padding: .5rem;
  cursor: pointer;
  border-color: white;

  &:hover {
    background-color: white;
    color: black;
  }
`


text:
<!DOCTYPE HTML>
<?php
	require_once("php/controller/create-db.php");

?>

		<title>melonJS Template</title>
		<link rel="stylesheet" type="text/css" media="screen" href="index.css">
		<meta id="viewport" name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="mobile-web-app-capable" content="yes">
		<meta name="apple-mobile-web-app-status-bar-style" content="black">
        <link rel="apple-touch-icon" href="icons/touch-icon-iphone-60x60.png">
        <link rel="apple-touch-icon" sizes="76x76" href="icons/touch-icon-ipad-76x76.png">
        <link rel="apple-touch-icon" sizes="120x120" href="icons/touch-icon-iphone-retina-120x120.png">
        <link rel="apple-touch-icon" sizes="152x152" href="icons/touch-icon-ipad-retina-152x152.png">

		<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/themes/smoothness/jquery-ui.css" />

        <form id="input"method ="post">

                   Username

                  <input type='text' name='username' id='username' autocomplete='off'>

              	Password
                <input type='password' name='password' id='password'>

              <button type='button' id='register'>Register</button>
			  <button type='button' id='load'>Load</button>
			  <button type='button' id='mainmenu'>Main Menu</button>
		</form>


text:
#include "config.h"
#include "core/animation/DocumentAnimations.h"

#include "core/animation/ActiveAnimations.h"
#include "core/animation/AnimationClock.h"
#include "core/animation/DocumentTimeline.h"
#include "core/dom/Document.h"
#include "core/dom/Element.h"
#include "core/dom/Node.h"
#include "core/frame/Frame.h"
#include "core/frame/FrameView.h"
#include "core/rendering/RenderLayerCompositor.h"
#include "core/rendering/RenderView.h"

namespace WebCore {

namespace {

void updateAnimationTiming(Document& document, double monotonicAnimationStartTime)
{
    document.animationClock().updateTime(monotonicAnimationStartTime);
    bool didTriggerStyleRecalc = document.timeline()->serviceAnimations();
    didTriggerStyleRecalc |= document.transitionTimeline()->serviceAnimations();
    if (!didTriggerStyleRecalc)
        document.animationClock().unfreeze();
}

void dispatchAnimationEvents(Document& document)
{
    document.timeline()->dispatchEvents();
    document.transitionTimeline()->dispatchEvents();
}

void dispatchAnimationEventsAsync(Document& document)
{
    document.timeline()->dispatchEventsAsync();
    document.transitionTimeline()->dispatchEventsAsync();
}

} // namespace

void DocumentAnimations::serviceOnAnimationFrame(Document& document, double monotonicAnimationStartTime)
{
    if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled())
        return;

    updateAnimationTiming(document, monotonicAnimationStartTime);
    dispatchAnimationEvents(document);
}

void DocumentAnimations::serviceBeforeGetComputedStyle(Node& node, CSSPropertyID property)
{
    if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled())
        return;

    if (node.isElementNode()) {
        const Element& element = toElement(node);
        if (const ActiveAnimations* activeAnimations = element.activeAnimations()) {
            if (activeAnimations->hasActiveAnimationsOnCompositor(property))
                updateAnimationTiming(element.document(), monotonicallyIncreasingTime());
        }
    }

}

void DocumentAnimations::serviceAfterStyleRecalc(Document& document)
{
    if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled())
        return;

    if (document.cssPendingAnimations().startPendingAnimations() && document.view())
        document.view()->scheduleAnimation();

    document.animationClock().unfreeze();
    dispatchAnimationEventsAsync(document);
}

} // namespace WebCore


text:
package iavanish.collegepal.Calendar;

import java.util.ArrayList;
import java.util.Iterator;

/**
 * Created by iavanish on 02-May-15.
 */
public class Demo {

    public ArrayList <RepresentableDeadline> schedulePublicDeadlines(ArrayList <RepresentableDeadline> representableDeadlines, int date) {

        Iterator <RepresentableDeadline> iterator = representableDeadlines.iterator();

        ArrayList <RepresentableDeadline> returnVal = new ArrayList <RepresentableDeadline> ();

        while(iterator.hasNext()) {

            RepresentableDeadline tempD = iterator.next();

            int deadlineDate = Integer.parseInt(tempD.deadlineDate.substring(0, tempD.deadlineDate.indexOf('/')));
            int noOfDays = deadlineDate - date;
            if(noOfDays < 1) {
                continue;
            }
            if(!tempD.deadlineType.equalsIgnoreCase("public")) {
                continue;
            }
            if(noOfDays > 1) {
                noOfDays -= 1;
            }
            tempD.percentage = 100 / noOfDays;
            returnVal.add(tempD);

        }

        return returnVal;

    }

    public ArrayList <RepresentableDeadline> schedulePrivateDeadlines(ArrayList<RepresentableDeadline> representableDeadlines, int date) {

        Iterator <RepresentableDeadline> iterator = representableDeadlines.iterator();

        ArrayList <RepresentableDeadline> returnVal = new ArrayList <RepresentableDeadline> ();

        while(iterator.hasNext()) {

            RepresentableDeadline tempD = iterator.next();

            int deadlineDate = Integer.parseInt(tempD.deadlineDate.substring(0, tempD.deadlineDate.indexOf('/')));
            int noOfDays = deadlineDate - date;
            if(noOfDays < 1) {
                continue;
            }
            if(!tempD.deadlineType.equalsIgnoreCase("private")) {
                continue;
            }
            tempD.percentage = 100 / noOfDays;
            returnVal.add(tempD);

        }

        return returnVal;

    }

}


text:
import numpy as np
import roslib
import rospy
import tf
from geometry_msgs.msg import PoseStamped

roslib.load_manifest('qbo_arduqbo')
from sensor_msgs.msg import JointState

# The motor state message type from qbo_arduqbo has annoying capitalisation.
from qbo_arduqbo.msg import motor_state as MotorState

class Mapping(object):
    """
    A mapping between an encoder value and an output angle. It is parameterised
    in terms of a scale and offset such that:

        output_angle = scale * (encoder_value + offset)

    The default scale is 1.0 and the default offset is 0.0.
    """

    def __init__(self, scale=None, offset=None):
        # The float() call here is to massage the input to a floating point
        # value even if we're passed a string or an integer. Mucky but it gets
        # the job done.
        self.scale = float(scale or 1.0)
        self.offset = float(offset or 0.0)

    def encoder_to_angle(self, encoder_value):
        return self.scale * (encoder_value + self.offset)

    def angle_to_encoder(self, angle):
        return (angle / self.scale) - self.offset

class JointOdomController(object):
    """
    Publish a tf from base_frame_id to head_frame_id when pan and tilt angles update.

    """

    def __init__(self, head_pan=None, head_tilt=None, base_frame_id=None, head_frame_id=None, head_offset=None):
        # The default is to have an identity mapping
        self.head_pan = head_pan or Mapping()
        self.head_tilt = head_tilt or Mapping()
        self.head_offset = np.asarray(head_offset or [0, 0, 0.3])

        # The default frame ids are 'base_link' and 'head'
        self.base_frame_id = base_frame_id or 'base_link'
        self.head_frame_id = head_frame_id or 'head'

        # The last pan and tilt as an angle
        self.last_pan_angle = 0
        self.last_tilt_angle = 0
        self.when = 0   # the last time stamp

        # Publischer of the new head pose
        #self.pub = rospy.Publisher('/head/pose', PoseStamped, queue_size=10)
        self.pub = rospy.Publisher('/head_joints', JointState, queue_size=10)

    def on_head_pan_joint(self, motor_state):
        # ---------------------
        # Filter because of noise in motor state readings.
        # Angle should never be more/less than +/- 45 degrees.
        # -------------------------
        if abs(self.head_pan.encoder_to_angle(motor_state.position)) < 45:
            self.last_pan_angle = self.head_pan.encoder_to_angle(motor_state.position)
        self.when = motor_state.header.stamp
#        self._publish_state()

    def on_head_tilt_joint(self, motor_state):
        # ---------------------
        # Filter because of noise in motor state readings.
        # Angle should never be more/less than +/- 45 degrees.
        # -------------------------
        if abs(self.head_tilt.encoder_to_angle(motor_state.position)) < 45:
            self.last_tilt_angle = self.head_tilt.encoder_to_angle(motor_state.position)

        # rospy.loginfo("Last tilt = %s", self.last_tilt_angle)
        self.when = motor_state.header.stamp
#        self._publish_state()

    def _publish_state(self, time):
        """Publish the current head state as a tf message."""
        # Create a broadcaster
        #br = tf.TransformBroadcaster()

        # Working out the final pose of the head is subtle. It depends which
        # order we apply the transformations. We need to rotate in the tilt
        # axis (about y) first and then rotate in the pan axis (about z).

        # Calculate rotation matrices
        pan_rot = np.deg2rad(self.last_pan_angle)
        #pan_rot = tf.transformations.rotation_matrix(
        #        np.deg2rad(self.last_pan_angle), (0, 0, 1))

        # ---------------------
        # The tilt angle is not accurate.
        # Following compensation is needed in order to get a correct
        # tf transformation for the Asus Xtion.
        # --------------------------
        tilt_rot = np.deg2rad(self.last_tilt_angle)
        tilt_rot = tilt_rot + (tilt_rot+0.568)*(0.132/0.568)
#        rospy.loginfo("Last tilt = %s", tilt_rot)
        #tilt_rot = tf.transformations.rotation_matrix(
        #        tilt_rot, (0, 1, 0))

        # Combine rotation matrix
        #pose = pan_rot.dot(tilt_rot)
        #quat = tf.transformations.quaternion_from_matrix(pose)

        msg = JointState()
        msg.header.frame_id = "head_joints"
        msg.header.stamp = rospy.Time.now()
        msg.name.append("head_tilt_joint");
        msg.name.append("head_pan_joint");
        msg.position.append(tilt_rot)
        msg.position.append(pan_rot)

        """
        msg = PoseStamped()
        msg.header.frame_id = "head_joint"
        msg.header.stamp = rospy.Time.now()
        msg.pose.position.x = self.head_offset[0]
        msg.pose.position.y = self.head_offset[1]
        msg.pose.position.z = self.head_offset[2]
        msg.pose.orientation.x = quat[0]
        msg.pose.orientation.y = quat[1]
        msg.pose.orientation.z = quat[2]
        msg.pose.orientation.w = quat[3]
        """
        """
        # Calculate and send the tf
        br.sendTransform(
                self.head_offset,
                tf.transformations.quaternion_from_matrix(pose),
                rospy.Time.now(), self.head_frame_id, self.base_frame_id)

        """
        # Publish the new head position
        try:
            self.pub.publish(msg)
        except ROSException as e:
            rospy.logerror("Error publishing 'head_joints': {0}.".format(e))

def mapping_from_servo(param_base):
    """
    Initialise and return a Mapping object by reading ROS parameters from
    param_base. If param_base is /foo/bar then the following parameters are
    used:

        /foo/bar/invert
        /foo/bar/neutral
        /foo/bar/range
        /foo/bar/ticks

    If any of the parameters are unavailable, a warning message is logged an
    an identity mapping is returned.

    """
    rospy.loginfo('Extracting servo information from {0}'.format(param_base))

    try:
        invert = rospy.get_param(param_base + '/invert')
        rospy.loginfo('invert: {0}'.format(invert))
        neutral = rospy.get_param(param_base + '/neutral')
        rospy.loginfo('neutral: {0}'.format(neutral))
        range_ = rospy.get_param(param_base + '/range')
        rospy.loginfo('range: {0}'.format(range))
        ticks = rospy.get_param(param_base + '/ticks')
        rospy.loginfo('ticks: {0}'.format(ticks))
    except KeyError as e:
        rospy.logwarn("unable to get servo parameters from {0}:{1}".format(param_base, e))
        return Mapping()

    # Calculate scale and offset
    scale = float(range_) / float(ticks)
    offset = -float(neutral)
    if invert:
        scale *= -1.0

    rospy.loginfo('Computed mapping: scale={0}, offset={1}'.format(scale, offset))

    return Mapping(scale, offset)

def main():
    """
    Initialise the node, subscribe to topics and spin waiting for data.

    """
    # initialise our node
    rospy.init_node('qbo_joint_odom')

    # get the head offset
    head_offset = rospy.get_param('~head_offset', None)

    # get the frame ids
    head_frame_id = rospy.get_param('~head_frame_id', None)
    base_frame_id = rospy.get_param('~base_frame_id', None)

    # which namespace can we find parameters for the servos in?
    head_pan_joint_servo = str(rospy.get_param('~head_pan_joint/servo_ns',
        '/qbo_arduqbo/dynamixelservo/head_pan_joint'))
    head_tilt_joint_servo = str(rospy.get_param('~head_tilt_joint/servo_ns',
        '/qbo_arduqbo/dynamixelservo/head_tilt_joint'))

    head_pan_mapping = mapping_from_servo(head_pan_joint_servo)
    head_tilt_mapping = mapping_from_servo(head_tilt_joint_servo)

    # initialise the controller
    odom_controller = JointOdomController(
            head_pan = head_pan_mapping, head_tilt = head_tilt_mapping,
            head_frame_id = head_frame_id, base_frame_id = base_frame_id,
            head_offset = head_offset)

    # which topics should we subscribe to?
    head_pan_joint_topic = str(rospy.get_param('~head_pan_joint/topic',
        '/qbo_arduqbo/head_pan_joint/state'))
    head_tilt_joint_topic = str(rospy.get_param('~head_tilt_joint/topic',
        '/qbo_arduqbo/head_tilt_joint/state'))

    # subscribe to the topics, wiring callbacks into the controller
    rospy.loginfo('Subscribing to {0} for pan state'.format(head_pan_joint_topic))
    head_pan_sub = rospy.Subscriber(head_pan_joint_topic, MotorState,
            odom_controller.on_head_pan_joint)

    rospy.loginfo('Subscribing to {0} for tilt state'.format(head_tilt_joint_topic))
    head_tilt_sub = rospy.Subscriber(head_tilt_joint_topic, MotorState,
            odom_controller.on_head_tilt_joint)

    rospy.Timer(rospy.Duration(0.01), odom_controller._publish_state)

    # launch the ROS event loop
    rospy.spin()

if __name__ == '__main__':
    try:
        main()
    except rospy.ROSInterruptException:
        pass


text:
<?php

    namespace common\classes;

    class VKApi
    {
        const API_VERSION = 5.37;

        /**
         * @param string $groupUrl
         * @return mixed
         */
        public static function getGroupIdByUrl($groupUrl)
        {
            $groupName = basename($groupUrl);

            $group = json_decode(file_get_contents('https://api.vk.com/method/groups.getById?v=5.37&group_id=' . $groupName), true);

            return self::hasError($group) ? false : $group['response'][0]['id'];
        }

        /**
         * @param integer $id
         * @return mixed
         */
        public static function getWallPosts($id){
            $wall = json_decode(file_get_contents('https://api.vk.com/method/wall.get?v=5.37&count=100&filter=owner&owner_id=-' . $id), true);

            return self::hasError($wall) ? false : $wall['response']['items'];
        }

        private static function hasError($array){
            return isset($array['error']);
        }
    }


text:
package com.kenodoggy.navigationdrawer;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import org.json.JSONObject;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link DetailFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class DetailFragment extends Fragment {

    private static final String POSITION = "nav_item_position";
    private static final String TITLE = "item_title";
    private static final String IMAGE = "item_image";
    private static final String DESCRIPTION = "item_description";

    private int mPosition;
    private String mTitle;
    private String mImage;
    private String mDescription;

    /**
     * factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param position
     * @return A new instance of fragment DetailFragment.
     */
    public static DetailFragment newInstance(JSONObject puppy, int position) {
        DetailFragment fragment = new DetailFragment();
        Bundle args = new Bundle();
        args.putInt(POSITION, position);
        args.putString(TITLE, puppy.optString("title"));
        args.putString(IMAGE, puppy.optString("image"));
        args.putString(DESCRIPTION, puppy.optString("description"));
        fragment.setArguments(args);
        return fragment;
    }

    public DetailFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mPosition = getArguments().getInt(POSITION);
            mTitle = getArguments().getString(TITLE);
            mImage = getArguments().getString(IMAGE);
            mDescription = getArguments().getString(DESCRIPTION);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_detail, container, false);

        TextView title = (TextView) view.findViewById(R.id.fragment_detail_title);
        TextView description = (TextView) view.findViewById(R.id.fragment_detail_description);
        ImageView imageView = ((ImageView) view.findViewById(R.id.fragment_detail_image));

        title.setText(mTitle);
        description.setText(mDescription);
        int imageId = getResources().getIdentifier(mImage, "drawable", getActivity().getPackageName());
        imageView.setImageResource(imageId);

        getActivity().setTitle(mTitle);

        return view;
    }

}


text:
from google.appengine.api import users
from google.appengine.ext import ndb

from serie import Serie

import time
import webapp2

class NextEpisodeHandler(webapp2.RequestHandler):
    def get(self):
	id = self.request.GET['id']
        user = users.get_current_user()

	if (user != None
	and id != None):
		user_name = user.nickname()
		access_link = users.create_logout_url("/")

		try:
			serie = ndb.Key(urlsafe = id).get()
		except:
			self.redirect("/main")
			return

		serie.lastEpisode += 1
		serie.put()
		time.sleep(1)
		self.redirect("/main?id=" + serie.key.urlsafe())
	else:
		self.redirect("/")


text:
package org.apache.etch.interoptester;

import java.util.HashMap;
import java.util.Map;

import org.apache.etch.interoptester.Param;
import org.apache.etch.util.AssertionException;
import org.apache.etch.util.core.xml.XmlParser;
import org.apache.etch.util.core.xml.XmlParser.TagElement;
import org.junit.Test;

import static org.junit.Assert.*;

/** */
public class TestParam
{
	private final Map<String, String> args = new HashMap<String, String>();
	{
		args.put( "bar", "123" );
		args.put( "baz", "456" );
	}

	private TagElement parseXml( String s ) throws Exception
	{
		return new XmlParser().parseOne( s );
	}

	/** @throws Exception */
	@Test( expected = AssertionException.class )
	public void parse1() throws Exception
	{
		// tag is param
		Param.parse( parseXml( "<foo/>" ) );
	}

	/** @throws Exception */
	@Test( expected = IllegalArgumentException.class )
	public void parse2() throws Exception
	{
		// param tag has no name attribute
		Param.parse( parseXml( "<param/>" ) );
	}

	/** @throws Exception */
	@Test
	public void parse3() throws Exception
	{
		Param p = Param.parse( parseXml( "<param name=\"foo\"/>" ) );
		assertEquals( "foo", p.name() );
		assertNull( p.value( args ) );
	}

	/** @throws Exception */
	@Test
	public void parse4() throws Exception
	{
		Param p = Param.parse( parseXml( "<param name=\"foo\"></param>" ) );
		assertEquals( "foo", p.name() );
		assertNull( p.value( args ) );
	}

	/** @throws Exception */
	@Test
	public void parse5() throws Exception
	{
		Param p = Param.parse( parseXml( "<param name=\"foo\">789</param>" ) );
		assertEquals( "foo", p.name() );
		assertEquals( "789", p.value( args ) );
	}

	/** @throws Exception */
	@Test
	public void parse6() throws Exception
	{
		Param p = Param.parse( parseXml( "<param name=\"foo\" default=\"\"/>" ) );
		assertEquals( "foo", p.name() );
		assertEquals( "", p.value( args ) );
	}

	/** @throws Exception */
	@Test
	public void parse7() throws Exception
	{
		Param p = Param.parse( parseXml( "<param name=\"foo\" default=\"789\"/>" ) );
		assertEquals( "foo", p.name() );
		assertEquals( "789", p.value( args ) );
	}

	/** @throws Exception */
	@Test
	public void parse8() throws Exception
	{
		Param p = Param.parse( parseXml( "<param name=\"bar\"/>" ) );
		assertEquals( "bar", p.name() );
		assertEquals( "123", p.value( args ) );
	}

	/** @throws Exception */
	@Test
	public void parse9() throws Exception
	{
		Param p = Param.parse( parseXml( "<param name=\"baz\" default=\"234\"/>" ) );
		assertEquals( "baz", p.name() );
		assertEquals( "456", p.value( args ) );
	}

	/** @throws Exception */
	@Test
	public void toString1() throws Exception
	{
		Param p = Param.parse( parseXml( "<param name=\"baz\" default=\"234\"/>" ) );
		assertEquals( "Param( baz, 234 )", p.toString() );
	}
}


text:
<!DOCTYPE html>

<meta name="generator" content="Hexo 3.9.0">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    <meta name="theme-color" content="#3F51B5">

    <meta name="keywords" content>

    <title>文章: 设计之路 | codante</title>
    <link type="text/css" rel="stylesheet" source="/blog/css/style.min.css?_v=77623b489ee77b522ff8437b98d73b89" media="all">

codante

    Blender 3D 技巧收集

    <time class="article-date-time" title="2020.04.27 14:18:05"
      datetime="2020-04-27T06:18:05.662Z">2020.04.27 14:18:05</time>

    设计之路

    3Dblender工具

        Modifierscannotbeappliedtomulti-userdataPressU>ObjectsandData.Thenapplyyourmodifier.UsingjustObjectwillmaketheobjectanew,separatedatablockforthemesh(butwillignore...

cosh-1.0.0$

<input type="text" class="inputing">


text:
package org.apache.cassandra.io.sstable.format;

import static org.apache.cassandra.utils.ByteBufferUtil.bytes;

import java.io.File;
import java.nio.ByteBuffer;

import com.google.common.util.concurrent.Runnables;
import org.junit.BeforeClass;
import org.junit.Test;

import org.apache.cassandra.concurrent.ScheduledExecutors;
import org.apache.cassandra.config.CFMetaData;
import org.apache.cassandra.config.Config;
import org.apache.cassandra.db.Slices;
import org.apache.cassandra.db.filter.ColumnFilter;
import org.apache.cassandra.db.marshal.BytesType;
import org.apache.cassandra.db.rows.UnfilteredRowIterator;
import org.apache.cassandra.dht.ByteOrderedPartitioner;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.io.sstable.Descriptor;

/**
 * Tests backwards compatibility for SSTables
 */
public class ClientModeSSTableTest
{
    public static final String LEGACY_SSTABLE_PROP = "legacy-sstable-root";
    public static final String KSNAME = "Keyspace1";
    public static final String CFNAME = "Standard1";

    public static File LEGACY_SSTABLE_ROOT;

    static CFMetaData metadata;

    @BeforeClass
    public static void defineSchema() throws ConfigurationException
    {
        Config.setClientMode(true);

        metadata = CFMetaData.Builder.createDense(KSNAME, CFNAME, false, false)
                                                .addPartitionKey("key", BytesType.instance)
                                                .addClusteringColumn("column", BytesType.instance)
                                                .addRegularColumn("value", BytesType.instance)
                                                .withPartitioner(ByteOrderedPartitioner.instance)
                                                .build();

        String scp = System.getProperty(LEGACY_SSTABLE_PROP);
        assert scp != null;
        LEGACY_SSTABLE_ROOT = new File(scp).getAbsoluteFile();
        assert LEGACY_SSTABLE_ROOT.isDirectory();
    }

    /**
     * Get a descriptor for the legacy sstable at the given version.
     */
    protected Descriptor getDescriptor(String ver)
    {
        File directory = new File(LEGACY_SSTABLE_ROOT + File.separator + ver + File.separator + KSNAME);
        return new Descriptor(ver, directory, KSNAME, CFNAME, 0, SSTableFormat.Type.LEGACY);
    }

    @Test
    public void testVersions() throws Throwable
    {
        boolean notSkipped = false;

        for (File version : LEGACY_SSTABLE_ROOT.listFiles())
        {
            if (!new File(LEGACY_SSTABLE_ROOT + File.separator + version.getName() + File.separator + KSNAME).isDirectory())
                continue;
            if (Version.validate(version.getName()) && SSTableFormat.Type.LEGACY.info.getVersion(version.getName()).isCompatible())
            {
                notSkipped = true;
                testVersion(version.getName());
            }
        }

        assert notSkipped;
    }

    public void testVersion(String version) throws Throwable
    {
        SSTableReader reader = null;
        try
        {
            reader = SSTableReader.openNoValidation(getDescriptor(version), metadata);

            ByteBuffer key = bytes(Integer.toString(100));

            try (UnfilteredRowIterator iter = reader.iterator(metadata.decorateKey(key), Slices.ALL, ColumnFilter.selection(metadata.partitionColumns()), false, false))
            {
                assert iter.next().clustering().get(0).equals(key);
            }
        }
        catch (Throwable e)
        {
            System.err.println("Failed to read " + version);
            throw e;
        }
        finally
        {
            if (reader != null)
            {
                int globalTidyCount = SSTableReader.GlobalTidy.lookup.size();
                reader.selfRef().release();
                assert reader.selfRef().globalCount() == 0;

                // await clean-up to complete if started.
                ScheduledExecutors.nonPeriodicTasks.submit(Runnables.doNothing()).get();
                // Ensure clean-up completed.
                assert SSTableReader.GlobalTidy.lookup.size() < globalTidyCount;
            }
        }
    }
}


text:
<?php

/**
 * The "clusters" collection of methods.
 * Typical usage is:
 *  <code>
 *   $dataprocService = new Google_Service_Dataproc(...);
 *   $clusters = $dataprocService->clusters;
 *  </code>
 */
class Google_Service_Dataproc_Resource_ProjectsRegionsClusters extends Google_Service_Resource
{
  /**
   * Creates a cluster in a project. (clusters.create)
   *
   * @param string $projectId Required. The ID of the Google Cloud Platform
   * project that the cluster belongs to.
   * @param string $region Required. The Cloud Dataproc region in which to handle
   * the request.
   * @param Google_Service_Dataproc_Cluster $postBody
   * @param array $optParams Optional parameters.
   *
   * @opt_param string requestId Optional. A unique id used to identify the
   * request. If the server receives two CreateClusterRequest requests with the
   * same id, then the second request will be ignored and the first
   * google.longrunning.Operation created and stored in the backend is returned.It
   * is recommended to always set this value to a UUID
   * (https://en.wikipedia.org/wiki/Universally_unique_identifier).The id must
   * contain only letters (a-z, A-Z), numbers (0-9), underscores (_), and hyphens
   * (-). The maximum length is 40 characters.
   * @return Google_Service_Dataproc_Operation
   */
  public function create($projectId, $region, Google_Service_Dataproc_Cluster $postBody, $optParams = array())
  {
    $params = array('projectId' => $projectId, 'region' => $region, 'postBody' => $postBody);
    $params = array_merge($params, $optParams);
    return $this->call('create', array($params), "Google_Service_Dataproc_Operation");
  }
  /**
   * Deletes a cluster in a project. (clusters.delete)
   *
   * @param string $projectId Required. The ID of the Google Cloud Platform
   * project that the cluster belongs to.
   * @param string $region Required. The Cloud Dataproc region in which to handle
   * the request.
   * @param string $clusterName Required. The cluster name.
   * @param array $optParams Optional parameters.
   *
   * @opt_param string clusterUuid Optional. Specifying the cluster_uuid means the
   * RPC should fail (with error NOT_FOUND) if cluster with specified UUID does
   * not exist.
   * @opt_param string requestId Optional. A unique id used to identify the
   * request. If the server receives two DeleteClusterRequest requests with the
   * same id, then the second request will be ignored and the first
   * google.longrunning.Operation created and stored in the backend is returned.It
   * is recommended to always set this value to a UUID
   * (https://en.wikipedia.org/wiki/Universally_unique_identifier).The id must
   * contain only letters (a-z, A-Z), numbers (0-9), underscores (_), and hyphens
   * (-). The maximum length is 40 characters.
   * @return Google_Service_Dataproc_Operation
   */
  public function delete($projectId, $region, $clusterName, $optParams = array())
  {
    $params = array('projectId' => $projectId, 'region' => $region, 'clusterName' => $clusterName);
    $params = array_merge($params, $optParams);
    return $this->call('delete', array($params), "Google_Service_Dataproc_Operation");
  }
  /**
   * Gets cluster diagnostic information. After the operation completes, the
   * Operation.response field contains DiagnoseClusterOutputLocation.
   * (clusters.diagnose)
   *
   * @param string $projectId Required. The ID of the Google Cloud Platform
   * project that the cluster belongs to.
   * @param string $region Required. The Cloud Dataproc region in which to handle
   * the request.
   * @param string $clusterName Required. The cluster name.
   * @param Google_Service_Dataproc_DiagnoseClusterRequest $postBody
   * @param array $optParams Optional parameters.
   * @return Google_Service_Dataproc_Operation
   */
  public function diagnose($projectId, $region, $clusterName, Google_Service_Dataproc_DiagnoseClusterRequest $postBody, $optParams = array())
  {
    $params = array('projectId' => $projectId, 'region' => $region, 'clusterName' => $clusterName, 'postBody' => $postBody);
    $params = array_merge($params, $optParams);
    return $this->call('diagnose', array($params), "Google_Service_Dataproc_Operation");
  }
  /**
   * Gets the resource representation for a cluster in a project. (clusters.get)
   *
   * @param string $projectId Required. The ID of the Google Cloud Platform
   * project that the cluster belongs to.
   * @param string $region Required. The Cloud Dataproc region in which to handle
   * the request.
   * @param string $clusterName Required. The cluster name.
   * @param array $optParams Optional parameters.
   * @return Google_Service_Dataproc_Cluster
   */
  public function get($projectId, $region, $clusterName, $optParams = array())
  {
    $params = array('projectId' => $projectId, 'region' => $region, 'clusterName' => $clusterName);
    $params = array_merge($params, $optParams);
    return $this->call('get', array($params), "Google_Service_Dataproc_Cluster");
  }
  /**
   * Lists all regions/{region}/clusters in a project.
   * (clusters.listProjectsRegionsClusters)
   *
   * @param string $projectId Required. The ID of the Google Cloud Platform
   * project that the cluster belongs to.
   * @param string $region Required. The Cloud Dataproc region in which to handle
   * the request.
   * @param array $optParams Optional parameters.
   *
   * @opt_param string pageToken Optional. The standard List page token.
   * @opt_param int pageSize Optional. The standard List page size.
   * @opt_param string filter Optional. A filter constraining the clusters to
   * list. Filters are case-sensitive and have the following syntax:field = value
   * AND field = value ...where field is one of status.state, clusterName, or
   * labels.[KEY], and [KEY] is a label key. value can be * to match all values.
   * status.state can be one of the following: ACTIVE, INACTIVE, CREATING,
   * RUNNING, ERROR, DELETING, or UPDATING. ACTIVE contains the CREATING,
   * UPDATING, and RUNNING states. INACTIVE contains the DELETING and ERROR
   * states. clusterName is the name of the cluster provided at creation time.
   * Only the logical AND operator is supported; space-separated items are treated
   * as having an implicit AND operator.Example filter:status.state = ACTIVE AND
   * clusterName = mycluster AND labels.env = staging AND labels.starred = *
   * @return Google_Service_Dataproc_ListClustersResponse
   */
  public function listProjectsRegionsClusters($projectId, $region, $optParams = array())
  {
    $params = array('projectId' => $projectId, 'region' => $region);
    $params = array_merge($params, $optParams);
    return $this->call('list', array($params), "Google_Service_Dataproc_ListClustersResponse");
  }
  /**
   * Updates a cluster in a project. (clusters.patch)
   *
   * @param string $projectId Required. The ID of the Google Cloud Platform
   * project the cluster belongs to.
   * @param string $region Required. The Cloud Dataproc region in which to handle
   * the request.
   * @param string $clusterName Required. The cluster name.
   * @param Google_Service_Dataproc_Cluster $postBody
   * @param array $optParams Optional parameters.
   *
   * @opt_param string gracefulDecommissionTimeout Optional. Timeout for graceful
   * YARN decomissioning. Graceful decommissioning allows removing nodes from the
   * cluster without interrupting jobs in progress. Timeout specifies how long to
   * wait for jobs in progress to finish before forcefully removing nodes (and
   * potentially interrupting jobs). Default timeout is 0 (for forceful
   * decommission), and the maximum allowed timeout is 1 day.Only supported on
   * Dataproc image versions 1.2 and higher.
   * @opt_param string requestId Optional. A unique id used to identify the
   * request. If the server receives two UpdateClusterRequest requests with the
   * same id, then the second request will be ignored and the first
   * google.longrunning.Operation created and stored in the backend is returned.It
   * is recommended to always set this value to a UUID
   * (https://en.wikipedia.org/wiki/Universally_unique_identifier).The id must
   * contain only letters (a-z, A-Z), numbers (0-9), underscores (_), and hyphens
   * (-). The maximum length is 40 characters.
   * @opt_param string updateMask Required. Specifies the path, relative to
   * Cluster, of the field to update. For example, to change the number of workers
   * in a cluster to 5, the update_mask parameter would be specified as
   * config.worker_config.num_instances, and the PATCH request body would specify
   * the new value, as follows: {   "config":{     "workerConfig":{
   * "numInstances":"5"     }   } } Similarly, to change the number of preemptible
   * workers in a cluster to 5, the update_mask parameter would be
   * config.secondary_worker_config.num_instances, and the PATCH request body
   * would be set as follows: {   "config":{     "secondaryWorkerConfig":{
   * "numInstances":"5"     }   } } Note: Currently, only the following fields can
   * be updated:      Mask  Purpose      labels  Update labels
   * config.worker_config.num_instances  Resize primary worker group
   * config.secondary_worker_config.num_instances  Resize secondary worker group
   * @return Google_Service_Dataproc_Operation
   */
  public function patch($projectId, $region, $clusterName, Google_Service_Dataproc_Cluster $postBody, $optParams = array())
  {
    $params = array('projectId' => $projectId, 'region' => $region, 'clusterName' => $clusterName, 'postBody' => $postBody);
    $params = array_merge($params, $optParams);
    return $this->call('patch', array($params), "Google_Service_Dataproc_Operation");
  }
}


text:
const { mix } = require('laravel-mix');
const path = require('path');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.webpackConfig({
  output: {
    publicPath: "/",
    chunkFilename: 'js/[name].[chunkhash].js'
  },
  resolve: {
    alias: {
      'components': 'assets/js/components',
      'config': 'assets/js/config',
      'lang': 'assets/js/lang',
      'plugins': 'assets/js/plugins',
      'vendor': 'assets/js/vendor',
      'views': 'assets/js/views',
      'dashboard': 'assets/js/views/dashboard',
    },
    modules: [
      'node_modules',
      path.resolve(__dirname, "resources")
    ]
  },
})

mix.js('resources/assets/js/app.js', 'public/js')
   .sass('resources/assets/sass/app.scss', 'public/css')
   .js('resources/assets/js/home.js', 'public/js')
   .sass('resources/assets/sass/home.scss', 'public/css')
   .version();


text:
package ru.stqa.jft.addressbook.tests;

import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import ru.stqa.jft.addressbook.model.ContactData;
import ru.stqa.jft.addressbook.model.Contacts;
import ru.stqa.jft.addressbook.model.GroupData;
import ru.stqa.jft.addressbook.model.Groups;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

/**
 * Created by Anna on 2017-01-26.
 */
public class ContactDeletionFromGroup extends TestBase{

    int contactId;
    int groupId;
    String groupName;
    Contacts contacts;
    ContactData contact;

    @BeforeMethod
    public void ensurePreconditions() {
        if (app.db().contacts().size() == 0) {
            app.goTo().newContact();
            app.contact().create(new ContactData().withName("Jan").withSurname("Kowalski").withAddress("Zielona 7").withHomeNumber("675-76-16").withMobileNumber("123 43 23").withWorkNumber("(44)-67-678").withEmail1("kowalski@poczta.pl"));
        }
        if (app.db().groups().size() == 0) {
            GroupData group = new GroupData().withName("group").withHeader("header").withFooter("footer");
            app.group().create(group);
        }

        Groups groups = app.db().groups();
        for (GroupData group: groups) {
            if (group.getContacts().equals(null)) {
                contacts = app.db().contacts();
                contact = contacts.iterator().next();
                GroupData group1 = groups.iterator().next();
                app.contact().selectContactById(contact.getId());
                app.contact().selectGroup(group1.getName());
                app.contact().addToGroup();
            } else {
                break;
            }
        }
    }

    @Test
    public void testDeletionFromGroup() {
        Groups groups = app.db().groups();
        for (GroupData group: groups) {
            if (!group.getContacts().equals(null)) {
                Contacts contacts = group.getContacts();
                groupName = group.getName();
                groupId = group.getId();
                for (ContactData contact: contacts) {
                    contactId = contact.getId();
                break;
                }
                break;
            }
        }

        app.contact().chooseGroup(groupName);
        app.contact().selectContactById(contactId);
        app.contact().removeFromGroup();
        app.group().goToGroupPage(groupId);

        assertThat(app.db().contacts(), equalTo(contacts.remove(contact)));

    }
}


text:
package magictheshouter

import (
	"appengine"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"regexp"
	"strconv"
	"time"
)

func init() {
	http.HandleFunc("/ready", ready)
	http.HandleFunc("/cancel", cancel)

	http.HandleFunc("/regist", regist)
	http.HandleFunc("/magic", magic)

	http.HandleFunc("/testdata", testdata)
}

/*
魔法準備
*/
func ready(w http.ResponseWriter, r *http.Request) {
	changeReady(w, r, Ready)
}

/*
魔法取り消し
*/
func cancel(w http.ResponseWriter, r *http.Request) {
	changeReady(w, r, Nothing)
}

/*
魔法準備状態の変更
*/
func changeReady(w http.ResponseWriter, r *http.Request, magicNo int) {
	c := appengine.NewContext(r)
	r.ParseForm()
	w.Header().Add("Content-type", "text/html; charset=utf-8")

	magicData := MagicData{
		DateTime: time.Now().Unix(),
		MagicNo:  magicNo,
	}

	// 登録
	regerr := RegistMagic(c, magicData)
	if regerr != nil {
		c.Debugf("[changeReady] regist err: %v", regerr)
		http.Error(w, regerr.Error(), http.StatusInternalServerError)
		return
	}

	fmt.Fprintf(w, strconv.Itoa(http.StatusOK))
}

/*
Masic情報を登録する
*/
func regist(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	r.ParseForm()
	w.Header().Add("Content-type", "text/html; charset=utf-8")

	// リクエスト内容を取得
	data, readerr := ioutil.ReadAll(r.Body)
	if readerr != nil {
		c.Debugf("[regist] read body err: %v", readerr)
		http.Error(w, readerr.Error(), http.StatusInternalServerError)
		return
	}

	// リクエストJSON
	var voiceData VoiceData
	jsonerr := json.Unmarshal(data, &voiceData)
	if jsonerr != nil {
		c.Debugf("[regist] json err: %v", jsonerr)
		http.Error(w, jsonerr.Error(), http.StatusInternalServerError)
		return
	}

	magicData := MagicData{
		DateTime: time.Now().Unix(),
		MagicNo:  GetMagicNo(voiceData.Data),
	}

	// 登録
	regerr := RegistMagic(c, magicData)
	if regerr != nil {
		c.Debugf("[regist] regist err: %v", regerr)
		http.Error(w, regerr.Error(), http.StatusInternalServerError)
		return
	}

	fmt.Fprintf(w, strconv.Itoa(http.StatusOK))
}

/*
Magic情報を取得する
*/
func magic(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	magicData, err := GetMagicData(c)

	if err != nil {
		c.Debugf("[magic] GetMagicData err: %v", err)
		w.Header().Add("Content-type", "text/html; charset=utf-8")
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	resjson, jsonerr := json.Marshal(magicData)

	if jsonerr != nil {
		c.Debugf("[magic] json err: %v", jsonerr)
		w.Header().Add("Content-type", "text/html; charset=utf-8")
		http.Error(w, jsonerr.Error(), http.StatusInternalServerError)
		return
	}

	// 結果を返す
	w.Header().Add("Content-type", "application/json")
	fmt.Fprintf(w, string(resjson))
}

var magicStr = [...]string{
	StrFireBall,
	StrDragon,
	StrBegiragon,
	StrMegante,
	StrIceStorm,
	StrRaidein,
	StrThunderStorm,
	StrScrewWave,
	StrBigWave,
	StrGigadoriru,
	StrKurushio,
	StrTigerBazooka,
	StrParopunte,
	StrSJK,
	StrFinalDragoon,
	StrRocknRoll,
	StrRainField,
}

/*
Magic番号を取得する
*/
func GetMagicNo(data string) (magicNo int) {
	magicNo = Nothing
	for _, val := range magicStr {
		re, _ := regexp.Compile(val)
		mat := re.FindAllStringSubmatch(data, -1)
		if 0 < len(mat) {
			switch val {
			case StrFireBall:
				magicNo = FireBall
			case StrDragon:
				magicNo = Dragon
			case StrBegiragon:
				magicNo = Begiragon
			case StrMegante:
				magicNo = Megante
			case StrIceStorm:
				magicNo = IceStorm
			case StrRaidein:
				magicNo = Raidein
			case StrThunderStorm:
				magicNo = ThunderStorm
			case StrScrewWave:
				magicNo = ScrewWave
			case StrBigWave:
				magicNo = BigWave
			case StrGigadoriru:
				magicNo = Gigadoriru
			case StrKurushio:
				magicNo = Kurushio
			case StrTigerBazooka:
				magicNo = TigerBazooka
			case StrParopunte:
				magicNo = Paropunte
			case StrSJK:
				magicNo = SJK
			case StrFinalDragoon:
				magicNo = FinalDragoon
			case StrRocknRoll:
				magicNo = RocknRoll
			case StrRainField:
				magicNo = RainField
			}

			break
		}
	}

	return
}

func testdata(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	r.ParseForm()
	w.Header().Add("Content-type", "text/html; charset=utf-8")

	magicData1 := MagicData{
		DateTime: time.Now().Unix(),
		MagicNo:  GetMagicNo("ファイヤーボール"),
	}

	magicData2 := MagicData{
		DateTime: time.Now().Unix() + int64(10),
		MagicNo:  GetMagicNo("ドラゴン!!!"),
	}

	// 登録
	regerr := RegistMagic(c, magicData1)
	regerr = RegistMagic(c, magicData2)
	if regerr != nil {
		c.Debugf("[regist] regist err: %v", regerr)
		http.Error(w, regerr.Error(), http.StatusInternalServerError)
		return
	}

	fmt.Fprintf(w, strconv.Itoa(http.StatusOK))
}


text:
#ifndef __IP4_CONFIG2_IMPL_H__
#define __IP4_CONFIG2_IMPL_H__

#define IP4_CONFIG2_INSTANCE_SIGNATURE    SIGNATURE_32 ('I', 'P', 'C', '2')
#define IP4_FORM_CALLBACK_INFO_SIGNATURE  SIGNATURE_32 ('I', 'F', 'C', 'I')

#define IP4_CONFIG2_VARIABLE_ATTRIBUTE    (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS)

#define DATA_ATTRIB_SIZE_FIXED              0x1
#define DATA_ATTRIB_VOLATILE                0x2

#define DATA_ATTRIB_SET(Attrib, Bits)       (BOOLEAN)((Attrib) & (Bits))
#define SET_DATA_ATTRIB(Attrib, Bits)       ((Attrib) |= (Bits))
#define REMOVE_DATA_ATTRIB(Attrib, Bits)    ((Attrib) &= (~Bits))

typedef struct _IP4_CONFIG2_INSTANCE IP4_CONFIG2_INSTANCE;

#define IP4_CONFIG2_INSTANCE_FROM_PROTOCOL(Proto) \
  CR ((Proto), \
      IP4_CONFIG2_INSTANCE, \
      Ip4Config2, \
      IP4_CONFIG2_INSTANCE_SIGNATURE \
      )

#define IP4_SERVICE_FROM_IP4_CONFIG2_INSTANCE(Instance) \
  CR ((Instance), \
      IP4_SERVICE, \
      Ip4Config2Instance, \
      IP4_SERVICE_SIGNATURE \
      )

#define IP4_CONFIG2_INSTANCE_FROM_FORM_CALLBACK(Callback) \
  CR ((Callback), \
      IP4_CONFIG2_INSTANCE, \
      CallbackInfo, \
      IP4_CONFIG2_INSTANCE_SIGNATURE \
      )

#define IP4_FORM_CALLBACK_INFO_FROM_CONFIG_ACCESS(ConfigAccess) \
  CR ((ConfigAccess), \
      IP4_FORM_CALLBACK_INFO, \
      HiiConfigAccessProtocol, \
      IP4_FORM_CALLBACK_INFO_SIGNATURE \
      )

/**
  The prototype of work function for EfiIp4Config2SetData().

  @param[in]     Instance The pointer to the IP4 config2 instance data.
  @param[in]     DataSize In bytes, the size of the buffer pointed to by Data.
  @param[in]     Data     The data buffer to set.

  @retval EFI_BAD_BUFFER_SIZE  The DataSize does not match the size of the type,
                               8 bytes.
  @retval EFI_SUCCESS          The specified configuration data for the EFI IPv4
                               network stack was set successfully.

**/
typedef
EFI_STATUS
(*IP4_CONFIG2_SET_DATA) (
  IN IP4_CONFIG2_INSTANCE *Instance,
  IN UINTN                DataSize,
  IN VOID                 *Data
  );

/**
  The prototype of work function for EfiIp4Config2GetData().

  @param[in]      Instance The pointer to the IP4 config2 instance data.
  @param[in, out] DataSize On input, in bytes, the size of Data. On output, in
                           bytes, the size of buffer required to store the specified
                           configuration data.
  @param[in]      Data     The data buffer in which the configuration data is returned.
                           Ignored if DataSize is ZERO.

  @retval EFI_BUFFER_TOO_SMALL The size of Data is too small for the specified
                               configuration data, and the required size is
                               returned in DataSize.
  @retval EFI_SUCCESS          The specified configuration data was obtained successfully.

**/
typedef
EFI_STATUS
(*IP4_CONFIG2_GET_DATA) (
  IN IP4_CONFIG2_INSTANCE *Instance,
  IN OUT UINTN            *DataSize,
  IN VOID                 *Data      OPTIONAL
  );

typedef union {
  VOID                                      *Ptr;
  EFI_IP4_CONFIG2_INTERFACE_INFO            *IfInfo;
  EFI_IP4_CONFIG2_POLICY                    *Policy;
  EFI_IP4_CONFIG2_MANUAL_ADDRESS            *ManualAddress;
  EFI_IPv4_ADDRESS                          *Gateway;
  EFI_IPv4_ADDRESS                          *DnsServers;
} IP4_CONFIG2_DATA;

typedef struct {
  IP4_CONFIG2_SET_DATA SetData;
  IP4_CONFIG2_GET_DATA GetData;
  EFI_STATUS           Status;
  UINT8                Attribute;
  NET_MAP              EventMap;
  IP4_CONFIG2_DATA     Data;
  UINTN                DataSize;
} IP4_CONFIG2_DATA_ITEM;

typedef struct {
  UINT16                    Offset;
  UINT32                    DataSize;
  EFI_IP4_CONFIG2_DATA_TYPE DataType;
} IP4_CONFIG2_DATA_RECORD;

#pragma pack(1)

//
// heap data that contains the data for each data record.
//
//  EFI_IP4_CONFIG2_POLICY                    Policy;
//  UINT32                                    ManualaddressCount;
//  UINT32                                    GatewayCount;
//  UINT32                                    DnsServersCount;
//  EFI_IP4_CONFIG2_MANUAL_ADDRESS            ManualAddress[];
//  EFI_IPv4_ADDRESS                          Gateway[];
//  EFI_IPv4_ADDRESS                          DnsServers[];
//
typedef struct {
  UINT16                  Checksum;
  UINT16                  DataRecordCount;
  IP4_CONFIG2_DATA_RECORD DataRecord[1];
} IP4_CONFIG2_VARIABLE;

#pragma pack()

typedef struct {
  EFI_IP4_CONFIG2_POLICY                   Policy;               ///< manual or automatic
  EFI_IP4_CONFIG2_MANUAL_ADDRESS           *ManualAddress;       ///< IP addresses
  UINT32                                   ManualAddressCount;   ///< IP addresses count
  EFI_IPv4_ADDRESS                         *GatewayAddress;      ///< Gateway address
  UINT32                                   GatewayAddressCount;  ///< Gateway address count
  EFI_IPv4_ADDRESS                         *DnsAddress;          ///< DNS server address
  UINT32                                   DnsAddressCount;      ///< DNS server address count
} IP4_CONFIG2_NVDATA;

typedef struct _IP4_FORM_CALLBACK_INFO {
  UINT32                           Signature;
  EFI_HANDLE                       ChildHandle;
  EFI_HII_CONFIG_ACCESS_PROTOCOL   HiiConfigAccessProtocol;
  EFI_DEVICE_PATH_PROTOCOL         *HiiVendorDevicePath;
  EFI_HII_HANDLE                   RegisteredHandle;
} IP4_FORM_CALLBACK_INFO;

struct _IP4_CONFIG2_INSTANCE {
  UINT32                                    Signature;
  BOOLEAN                                   Configured;
  LIST_ENTRY                                Link;
  UINT16                                    IfIndex;

  EFI_IP4_CONFIG2_PROTOCOL                  Ip4Config2;

  EFI_IP4_CONFIG2_INTERFACE_INFO            InterfaceInfo;
  EFI_IP4_CONFIG2_POLICY                    Policy;
  IP4_CONFIG2_DATA_ITEM                     DataItem[Ip4Config2DataTypeMaximum];

  EFI_EVENT                                 Dhcp4SbNotifyEvent;
  VOID                                      *Registration;
  EFI_HANDLE                                Dhcp4Handle;
  EFI_DHCP4_PROTOCOL                        *Dhcp4;
  BOOLEAN                                   DhcpSuccess;
  BOOLEAN                                   OtherInfoOnly;
  EFI_EVENT                                 Dhcp4Event;
  UINT32                                    FailedIaAddressCount;
  EFI_IPv4_ADDRESS                          *DeclineAddress;
  UINT32                                    DeclineAddressCount;

  IP4_FORM_CALLBACK_INFO                    CallbackInfo;

  IP4_CONFIG2_NVDATA                        Ip4NvData;
};

//
// Configure the DHCP to request the routers and netmask
// from server. The DHCP4_TAG_NETMASK is included in Head.
//
#pragma pack(1)
typedef struct {
  EFI_DHCP4_PACKET_OPTION Head;
  UINT8                   Route;
  UINT8                   Dns;
} IP4_CONFIG2_DHCP4_OPTION;
#pragma pack()

/**
  Read the configuration data from variable storage according to the VarName and
  gEfiIp4Config2ProtocolGuid. It checks the integrity of variable data. If the
  data is corrupted, it clears the variable data to ZERO. Othewise, it outputs the
  configuration data to IP4_CONFIG2_INSTANCE.

  @param[in]      VarName       The pointer to the variable name
  @param[in, out] Instance      The pointer to the IP4 config2 instance data.

  @retval EFI_NOT_FOUND         The variable can not be found or already corrupted.
  @retval EFI_OUT_OF_RESOURCES  Fail to allocate resource to complete the operation.
  @retval EFI_SUCCESS           The configuration data was retrieved successfully.

**/
EFI_STATUS
Ip4Config2ReadConfigData (
  IN     CHAR16               *VarName,
  IN OUT IP4_CONFIG2_INSTANCE *Instance
  );

/**
  Start the DHCP configuration for this IP service instance.
  It will locates the EFI_IP4_CONFIG2_PROTOCOL, then start the
  DHCP configuration.

  @param[in]  Instance           The IP4 config2 instance to configure.

  @retval EFI_SUCCESS            The auto configuration is successfully started.
  @retval Others                 Failed to start auto configuration.

**/
EFI_STATUS
Ip4StartAutoConfig (
  IN IP4_CONFIG2_INSTANCE   *Instance
  );

/**
  Initialize an IP4_CONFIG2_INSTANCE.

  @param[out]    Instance       The buffer of IP4_CONFIG2_INSTANCE to be initialized.

  @retval EFI_OUT_OF_RESOURCES  Failed to allocate resources to complete the operation.
  @retval EFI_SUCCESS           The IP4_CONFIG2_INSTANCE initialized successfully.

**/
EFI_STATUS
Ip4Config2InitInstance (
  OUT IP4_CONFIG2_INSTANCE  *Instance
  );

/**
  Release an IP4_CONFIG2_INSTANCE.

  @param[in, out] Instance    The buffer of IP4_CONFIG2_INSTANCE to be freed.

**/
VOID
Ip4Config2CleanInstance (
  IN OUT IP4_CONFIG2_INSTANCE  *Instance
  );

/**
  Request Ip4AutoReconfigCallBackDpc as a DPC at TPL_CALLBACK.

  @param Event     The event that is signalled.
  @param Context   The IP4 service binding instance.

**/
VOID
EFIAPI
Ip4AutoReconfigCallBack (
  IN EFI_EVENT              Event,
  IN VOID                   *Context
  );

/**
  Destroy the Dhcp4 child in IP4_CONFIG2_INSTANCE and release the resources.

  @param[in, out] Instance    The buffer of IP4 config2 instance to be freed.

  @retval EFI_SUCCESS         The child was successfully destroyed.
  @retval Others              Failed to destroy the child.

**/
EFI_STATUS
Ip4Config2DestroyDhcp4 (
  IN OUT IP4_CONFIG2_INSTANCE  *Instance
  );

#endif


text:
package com.jaquadro.minecraft.storagedrawers.client.model.component;

import com.jaquadro.minecraft.chameleon.Chameleon;
import com.jaquadro.minecraft.chameleon.model.WrappedChamModel;
import com.jaquadro.minecraft.chameleon.render.ChamRender;
import com.jaquadro.minecraft.storagedrawers.StorageDrawers;
import com.jaquadro.minecraft.storagedrawers.block.BlockDrawers;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.util.ResourceLocation;

public class DrawerSealedModel extends WrappedChamModel
{
    public static final ResourceLocation iconTapeCover = new ResourceLocation(StorageDrawers.MOD_ID + ":blocks/tape");

    public DrawerSealedModel (IBakedModel model, IBlockState state, boolean mergeLayers) {
        super(model, state, mergeLayers);
    }

    @Override
    protected void renderMippedLayer (ChamRender renderer, IBlockState state, Object... args) {
        if (!(state.getBlock() instanceof BlockDrawers))
            return;

        BlockDrawers block = (BlockDrawers) state.getBlock();
        float depth = block.isHalfDepth(state) ? .5f : 1f;
        TextureAtlasSprite iconTape = Chameleon.instance.iconRegistry.getIcon(iconTapeCover);

        renderer.startBaking(DefaultVertexFormats.ITEM, 0);
        renderer.setRenderBounds(0, 0, .995f - depth, 1, 1, 1);
        renderer.bakeFace(ChamRender.FACE_ZNEG, state, iconTape, false);
        renderer.stopBaking();
    }
}


text:
namespace nvbio {
namespace bowtie2 {
namespace cuda {

std::map<std::string,std::string> load_options(const char* name)
{
    std::map<std::string,std::string> options;

    FILE* file = fopen( name, "r" );
    if (file == NULL)
    {
        log_warning( stderr, "failed opening \"%s\"\n", name );
        return options;
    }

    char key[1024];
    char value[1024];

    while (fscanf( file, "%s %s", key, value ) == 2)
        options[ key ] = std::string( value );

    fclose( file );

    return options;
}

// bogus implementation of a function to check if a string is a number
bool is_number(const char* str, uint32 len = uint32(-1))
{
    if (str[0] == '-')
        ++str;

    for (uint32 l = 0; *str != '\0' && l < len; ++l)
    {
        const char c = *str; ++str;
        if (c == '.')             continue;
        if (c >= '0' && c <= '9') continue;
        return false;
    }
    return true;
}

// bogus implementation of a function to check if an option is a function
SimpleFunc parse_function(const char* str, const SimpleFunc def)
{
    if (str[1] != ',')
        return def;

    if (!(str[0] == 'C' ||
          str[0] == 'L' ||
          str[0] == 'G' ||
          str[0] == 'S'))
          return def;

    SimpleFunc ret;
    ret.type = (str[0] == 'C') ? SimpleFunc::LinearFunc :
               (str[0] == 'L') ? SimpleFunc::LinearFunc :
               (str[0] == 'G') ? SimpleFunc::LogFunc    :
                                 SimpleFunc::SqrtFunc;

    std::string nums = std::string( str + 2 );
    const size_t c = nums.find(',');
    if (c == std::string::npos)
        return def;

    if (is_number( nums.c_str(), (uint32)c )      == false) return def;
    if (is_number( nums.c_str() + c + 1 ) == false) return def;

    const std::string num1 = nums.substr( 0, c );
    const std::string num2 = std::string( nums.c_str() + c + 1 );

    ret.k = (float)atof( num1.c_str() );
    ret.m = (float)atof( nums.c_str() + c + 1 );

    // take care of transforming constant functions in linear ones
    if (str[0] == 'C')
    {
        //ret.k += ret.m;
        ret.m = 0.0f;
    }
    return ret;
}

template <typename options_type>
SimpleFunc func_option(const options_type& options, const char* name, const SimpleFunc func)
{
    return (options.find( std::string(name) ) != options.end()) ?
        parse_function( options.find(std::string(name))->second.c_str(), func ) :
        func;
}

template <typename options_type>
SimpleFunc func_option(const options_type& options, const char* name1, const char* name2, const SimpleFunc func)
{
    return
        (options.find( std::string(name1) ) != options.end()) ?
            parse_function( options.find(std::string(name1))->second.c_str(), func ) :
        (options.find( std::string(name2) ) != options.end()) ?
            parse_function( options.find(std::string(name2))->second.c_str(), func ) :
            func;
}

void parse_options(Params& params, const std::map<std::string,std::string>& options, bool init)
{
    const bool   old_local        = params.alignment_type == LocalAlignment;
    const uint32 old_scoring_mode = params.scoring_mode;

    params.mode             = mapping_mode( string_option(options, "mode",    init ? "best" : mapping_mode( params.mode )).c_str() ); // mapping mode
    params.scoring_mode     = scoring_mode( string_option(options, "scoring", init ? "sw"   : scoring_mode( params.scoring_mode )).c_str() ); // scoring mode
    params.alignment_type   = uint_option(options, "local",                 init ? 0u      : params.alignment_type == LocalAlignment ) ? LocalAlignment : EndToEndAlignment;           // local alignment
    params.keep_stats       = bool_option(options, "stats",                 init ? 1u      : params.keep_stats);           // keep stats
    params.max_hits         = uint_option(options, "max-hits",              init ? 100u    : params.max_hits);             // too big = memory exhaustion
    params.max_dist         = uint_option(options, "max-dist",              init ? 15u     : params.max_dist);             // must be <= MAX_BAND_LEN/2
    params.max_effort_init  = uint_option(options, "max-effort-init",       init ? 15u     : params.max_effort_init);      // initial scoring effort limit
    params.max_effort       = uint_option(options, "max-effort",    "D",    init ? 15u     : params.max_effort);           // scoring effort limit
    params.min_ext          = uint_option(options, "min-ext",               init ? 30u     : params.min_ext);              // min # of extensions
    params.max_ext          = uint_option(options, "max-ext",               init ? 400u    : params.max_ext);              // max # of extensions
    params.max_reseed       = uint_option(options, "max-reseed",    "R",    init ? 2u      : params.max_reseed);           // max # of reseeding rounds
    params.rep_seeds        = uint_option(options, "rep-seeds",             init ? 300u    : params.rep_seeds);            // reseeding threshold
    params.allow_sub        = uint_option(options, "N",                     init ? 0u      : params.allow_sub);            // allow substitution in seed
    params.mapq_filter      = uint_option(options, "mapQ-filter",   "Q",    init ? 0u      : params.mapq_filter);          // filter anything below this
    params.report           = string_option(options, "report",              init ? ""      : params.report.c_str());       // generate a report file
    params.scoring_file     = string_option(options, "scoring-scheme",      init ? ""      : params.scoring_file.c_str());
    params.randomized       = bool_option(options, "rand",                  init ? 1u      : params.randomized);           // use randomized selection
    params.randomized       =!bool_option(options, "no-rand",                               !params.randomized);           // don't use randomized selection
    params.top_seed         = uint_option(options, "top",                   init ? 0u      : params.top_seed);             // explore top seed entirely
    params.min_read_len     = uint_option(options, "min-read-len",          init ? 12u     : params.min_read_len);         // minimum read length
    params.ungapped_mates   = bool_option(options, "ungapped-mates", "ug",  init ? 0u      : params.ungapped_mates);       // ungapped mate alignment
    params.fw               = !bool_option(options, "nofw",                 init ? false   : !params.fw);                  // fw alignment
    params.rc               = !bool_option(options, "norc",                 init ? false   : !params.rc);                  // rc alignment

    // force the all-mapping mode with the '--all|-a' option
    if (uint_option(options, "all", "a", params.mode == AllMapping))
        params.mode = AllMapping;

    // force Edit-Distance scoring with the '--ed' option
    if (uint_option(options, "ed", params.scoring_mode == EditDistanceMode))
        params.scoring_mode = EditDistanceMode;

    // force Smith-Waterman scoring with the '--sw' option
    if (uint_option(options, "sw", params.scoring_mode == SmithWatermanMode))
        params.scoring_mode = SmithWatermanMode;

    const bool local = params.alignment_type == LocalAlignment;

    // set the default seeding values, or reset them if the alignment type has been changed
    if (init || (local != old_local))
    {
        params.seed_len  = local ? 20 : 22u;
        params.seed_freq = SimpleFunc( SimpleFunc::SqrtFunc, 1.0f, (local ? 0.75f : 1.15f) );
    }

    params.seed_len         = uint_option(options,  "seed-len",      "L",                    params.seed_len);          // no greater than 32
    params.seed_freq        = func_option( options, "seed-freq",     "i",                    params.seed_freq );        // seed interval
    params.subseed_len      = uint_option(options,  "subseed-len",          init ? 0u      : params.subseed_len);       // no greater than 32

    params.pe_overlap    =  bool_option(options, "overlap",         init ? true    : params.pe_overlap);                // paired-end overlap
    params.pe_overlap    = !bool_option(options, "no-overlap",                      !params.pe_overlap);                // paired-end overlap
    params.pe_dovetail   =  bool_option(options, "dovetail",        init ? false   : params.pe_dovetail);               // paired-end dovetail
    params.pe_unpaired   = !bool_option(options, "no-mixed",        init ? false   :!params.pe_unpaired);               // paired-end no-mixed
    params.pe_discordant = !bool_option(options, "no-discordant",   init ? false   :!params.pe_discordant);             // paired-end no-discordant
    params.pe_discordant =  bool_option(options, "discordant",                       params.pe_discordant);             // paired-end discordant
    params.min_frag_len  = uint_option(options, "minins", "I",      init ? 0u      : params.min_frag_len);              // paired-end minimum fragment length
    params.max_frag_len  = uint_option(options, "maxins", "X",      init ? 500u    : params.max_frag_len);              // paired-end maximum fragment length

    // the maximum batch of reads processed in parallel
    params.max_batch_size  = uint_option(options, "batch-size",      init ? 1024u           : params.max_batch_size );  // maximum batch size
    params.avg_read_length = uint_option(options, "read-length",     init ? AVG_READ_LENGTH : params.avg_read_length ); // average read length

    // internal controls
    params.scoring_window   = uint_option(options, "scoring-window",        init ? 32u  : params.scoring_window);       // scoring window size
    params.debug.read_id    = (uint32)int_option(options, "debug-read",     init ? -1   : (int32)params.debug.read_id); // debug read id
    params.debug.select     = bool_option(options, "debug-select",          init ? false: params.debug.select);         // debug select kernel
    params.debug.locate     = bool_option(options, "debug-locate",          init ? false: params.debug.locate);         // debug locate kernel
    params.debug.score      = bool_option(options, "debug-score",           init ? true : params.debug.score);          // debug score kernel
    params.debug.score_bad  = bool_option(options, "debug-score-bad",       init ? false: params.debug.score_bad);      // debug score bad
    params.debug.score_info = bool_option(options, "debug-score-info",      init ? false: params.debug.score_info);     // debug score info
    params.debug.reduce     = bool_option(options, "debug-reduce",          init ? true : params.debug.reduce);         // debug reduce kernel
    params.debug.traceback  = bool_option(options, "debug-traceback",       init ? true : params.debug.traceback);      // debug traceback kernel
    params.debug.asserts    = bool_option(options, "debug-asserts",         init ? true : params.debug.asserts);        // debug asserts

    params.persist_batch     =  int_option(options, "persist-batch",        init ? -1   : params.persist_batch);         // persist pass
    params.persist_seeding   =  int_option(options, "persist-seeding",      init ? -1   : params.persist_seeding);       // persist pass
    params.persist_extension =  int_option(options, "persist-extension",    init ? -1   : params.persist_extension);     // persist pass
    params.persist_file      =  string_option(options, "persist-file",      init ? ""   : params.persist_file.c_str() ); // persist file

    params.no_multi_hits     =  int_option(options, "no-multi-hits",        init ? 0    : params.no_multi_hits );       // disable multi-hit selection

    params.max_effort_init = nvbio::max( params.max_effort_init, params.max_effort );
    params.max_ext         = nvbio::max( params.max_ext,         params.max_effort );

    UberScoringScheme& sc = params.scoring_scheme;

    // set the default ED values, or reset them if the scoring mode has been changed
    if (init || (params.scoring_mode != old_scoring_mode))
        sc.ed.m_score_min = SimpleFunc( SimpleFunc::LinearFunc, -(float)params.max_dist, 0.0f );

    // set the default SW values, or reset them if the alignment type has been changed
    if (init || (local != old_local))
    {
        sc.sw = local ?
            SmithWatermanScoringScheme<>::local() :
            SmithWatermanScoringScheme<>();
    }

    // load scoring scheme from file
    if (params.scoring_file != "")
        sc.sw = load_scoring_scheme( params.scoring_file.c_str(), AlignmentType( params.alignment_type ) );

    // score-min
    sc.ed.m_score_min = func_option( options, "score-min", sc.ed.m_score_min );
    sc.sw.m_score_min = func_option( options, "score-min", sc.sw.m_score_min );

    // match bonus
    sc.sw.m_match.m_val = int_option( options, "ma", sc.sw.m_match.m_val );

    // mismatch penalties
    const int2 mp = int2_option( options, "mp", make_int2( sc.sw.m_mmp.m_max_val, sc.sw.m_mmp.m_min_val ) );
    sc.sw.m_mmp.m_max_val = mp.x;
    sc.sw.m_mmp.m_min_val = mp.y;

    // np
    sc.sw.m_np.m_val = int_option( options, "np", sc.sw.m_np.m_val );

    // read gaps
    const int2 rdg         = int2_option( options, "rdg", make_int2( sc.sw.m_read_gap_const, sc.sw.m_read_gap_coeff ) );
    sc.sw.m_read_gap_const = rdg.x;
    sc.sw.m_read_gap_coeff = rdg.y;

    // reference gaps
    const int2 rfg        = int2_option( options, "rfg", make_int2( sc.sw.m_ref_gap_const, sc.sw.m_ref_gap_coeff ) );
    sc.sw.m_ref_gap_const = rfg.x;
    sc.sw.m_ref_gap_coeff = rfg.y;

    // presets
    if (params.alignment_type == EndToEndAlignment)
    {
        if (uint_option(options, "very-fast", 0u))
        {
            params.max_effort = 5u;
            params.max_reseed = 1u;
            params.seed_len   = 22u;
            params.seed_freq  = SimpleFunc( SimpleFunc::SqrtFunc, 0.0f, 2.5f );
        }
        if (uint_option(options, "fast", 0u))
        {
            params.max_effort = 10u;
            params.max_reseed = 2u;
            params.seed_len   = 22u;
            params.seed_freq  = SimpleFunc( SimpleFunc::SqrtFunc, 0.0f, 2.5f );
        }
        if (uint_option(options, "sensitive", 0u))
        {
            params.max_effort = 15u;
            params.max_reseed = 2u;
            params.seed_len   = 22u;
            params.seed_freq  = SimpleFunc( SimpleFunc::SqrtFunc, 1.0f, 1.15f );
        }
        if (uint_option(options, "very-sensitive", 0u))
        {
            params.max_effort = 20u;
            params.max_reseed = 3u;
            params.seed_len   = 20u;
            params.seed_freq  = SimpleFunc( SimpleFunc::SqrtFunc, 1.0f, 0.5f );
        }

        if (uint_option(options, "very-fast-local", 0u))
        {
            if (uint_option(options, "end-to-end", 0u ) == 0)
            {
                params.alignment_type = LocalAlignment;
                params.max_effort = 5u;
                params.max_reseed = 1u;
                params.seed_len   = 25u;
                params.seed_freq  = SimpleFunc( SimpleFunc::SqrtFunc, 1.0f, 2.0f );
            }
            else
                log_warning(stderr, "--very-fast-local is incompatible with --end-to-end\n");
        }
        if (uint_option(options, "fast-local", 0u))
        {
            if (uint_option(options, "end-to-end", 0u ) == 0)
            {
                params.alignment_type = LocalAlignment;
                params.max_effort = 10u;
                params.max_reseed = 2u;
                params.seed_len   = 22u;
                params.seed_freq  = SimpleFunc( SimpleFunc::SqrtFunc, 1.0f, 1.75f );
            }
            else
                log_warning(stderr, "--fast-local is incompatible with --end-to-end\n");
        }
        if (uint_option(options, "sensitive-local", 0u))
        {
            if (uint_option(options, "end-to-end", 0u ) == 0)
            {
                params.alignment_type = LocalAlignment;
                params.max_effort = 15u;
                params.max_reseed = 2u;
                params.seed_len   = 20u;
                params.seed_freq  = SimpleFunc( SimpleFunc::SqrtFunc, 1.0f, 0.75f );
            }
            else
                log_warning(stderr, "--sensitive-local is incompatible with --end-to-end\n");
        }
        if (uint_option(options, "very-sensitive-local", 0u))
        {
            if (uint_option(options, "end-to-end", 0u ) == 0)
            {
                params.alignment_type = LocalAlignment;
                params.max_effort = 20u;
                params.max_reseed = 3u;
                params.seed_len   = 20u;
                params.seed_freq  = SimpleFunc( SimpleFunc::SqrtFunc, 1.0f, 0.5f );
            }
            else
                log_warning(stderr, "--very-sensitive-local is incompatible with --end-to-end\n");
        }
    }
    else
    {
        if (uint_option(options, "very-fast", "very-fast-local", 0u))
        {
            params.max_effort = 5u;
            params.max_reseed = 1u;
            params.seed_len   = 25u;
            params.seed_freq  = SimpleFunc( SimpleFunc::SqrtFunc, 1.0f, 2.0f );
        }
        if (uint_option(options, "fast", "fast-local", 0u))
        {
            params.max_effort = 10u;
            params.max_reseed = 2u;
            params.seed_len   = 22u;
            params.seed_freq  = SimpleFunc( SimpleFunc::SqrtFunc, 1.0f, 1.75f );
        }
        if (uint_option(options, "sensitive", "sensitive-local", 0u))
        {
            params.max_effort = 15u;
            params.max_reseed = 2u;
            params.seed_len   = 20u;
            params.seed_freq  = SimpleFunc( SimpleFunc::SqrtFunc, 1.0f, 0.75f );
        }
        if (uint_option(options, "very-sensitive", "very-sensitive-local", 0u))
        {
            params.max_effort = 20u;
            params.max_reseed = 3u;
            params.seed_len   = 20u;
            params.seed_freq  = SimpleFunc( SimpleFunc::SqrtFunc, 1.0f, 0.5f );
        }
    }
}

} // namespace cuda
} // namespace bowtie2
} // namespace nvbio


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

<title>AutoSignal</title>
<meta name="date" content="2014-07-09">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Required |

Optional

Detail:

Element

at.irian.ankor.annotation

Annotation Type AutoSignal

@Target(value={TYPE,METHOD})
@Retention(value=RUNTIME)
public @interface AutoSignal

Optional Element Summary

Optional Elements

Modifier and Type
Optional Element and Description

java.lang.String[]
value

Element Detail

value

public abstract java.lang.String[] value

Default:

""

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Required |

Optional

Detail:

Element


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
es5id: 15.4.4.21-9-5
description: >
    Array.prototype.reduce - callbackfn not called for array with one
    element
---*/

  var callCnt = 0;
  function callbackfn(prevVal, curVal, idx, obj)
  {
    callCnt++;
    return 2;
  }

  var arr = [1];

assert.sameValue(arr.reduce(callbackfn), 1, 'arr.reduce(callbackfn)');
assert.sameValue(callCnt, 0, 'callCnt');