text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
info: >
    when String.prototype.indexOf(searchString, position) is called first Call ToString, giving it the this value as its argument.
    Then Call ToString(searchString) and Call ToNumber(position)
es5id: 15.5.4.7_A4_T2
description: >
    Override toString and valueOf functions, second toString throw
    exception
includes: [$FAIL.js]
---*/

var __obj = {toString:function(){return "\u0041B";}}
var __obj2 = {valueOf:function(){return {};},toString:function(){throw "intointeger";}}
var __str = new String("ABB\u0041BABAB");

//////////////////////////////////////////////////////////////////////////////
//CHECK#1
with(__str){
    try {
      var x = indexOf(__obj, __obj2);
      $FAIL('#1: "var x = indexOf(__obj, __obj2)" lead to throwing exception');
    } catch (e) {
      if (e!=="intointeger") {
        $ERROR('#1.1: Exception === "intointeger". Actual: '+e);
      }
    }
}
//
//////////////////////////////////////////////////////////////////////////////


text:
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __MAIN_H
#define __MAIN_H

/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx_hal.h"
#include "stm32f4_discovery.h"

/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/
/* User can use this section to tailor DAC Channel used and associated
   resources */
/* Definition for DAC clock resources */
#define DACx_CHANNEL1_GPIO_CLK_ENABLE()  __HAL_RCC_GPIOA_CLK_ENABLE()
#define DMAx_CLK_ENABLE()               __HAL_RCC_DMA1_CLK_ENABLE()

#define DACx_FORCE_RESET()              __HAL_RCC_DAC_FORCE_RESET()
#define DACx_RELEASE_RESET()            __HAL_RCC_DAC_RELEASE_RESET()

/* Definition for DACx Channel1 Pin */
#define DACx_CHANNEL1_PIN                GPIO_PIN_4
#define DACx_CHANNEL1_GPIO_PORT          GPIOA

/* Definition for DACx's Channel1 */
#define DACx_CHANNEL1                    DAC_CHANNEL_1

/* Definition for DACx's DMA Channel1 */
#define DACx_DMA_CHANNEL1                DMA_CHANNEL_7
#define DACx_DMA_STREAM1                 DMA1_Stream5

/* Definition for DACx's NVIC */
#define DACx_DMA_IRQn1                   DMA1_Stream5_IRQn
#define DACx_DMA_IRQHandler1             DMA1_Stream5_IRQHandler

/* Exported macro ------------------------------------------------------------*/
/* Exported functions ------------------------------------------------------- */

#endif /* __MAIN_H */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

redpajama_set_name: RedPajamaGithub


text:
namespace openscreen {
namespace discovery {

// The InstanceKey ctor used below cares about the Instance ID of the
// MdnsRecord, while this class doesn't, so it's possible that the InstanceKey
// ctor will fail for this reason. That's not a problem though - A failure when
// creating an InstanceKey would mean that the record we received was invalid,
// so there is no reason to continue processing.
ServiceKey::ServiceKey(const MdnsRecord& record) {
  ErrorOr<ServiceKey> key = TryCreate(record);
  OSP_DCHECK(key.is_value());
  *this = std::move(key.value());
}

ServiceKey::ServiceKey(const DomainName& domain) {
  ErrorOr<ServiceKey> key = TryCreate(domain);
  OSP_DCHECK(key.is_value());
  *this = std::move(key.value());
}

ServiceKey::ServiceKey(absl::string_view service, absl::string_view domain)
    : service_id_(service.data(), service.size()),
      domain_id_(domain.data(), domain.size()) {
  OSP_DCHECK(IsServiceValid(service_id_));
  OSP_DCHECK(IsDomainValid(domain_id_));
}

ServiceKey::ServiceKey(const ServiceKey& other) = default;
ServiceKey::ServiceKey(ServiceKey&& other) = default;

ServiceKey& ServiceKey::operator=(const ServiceKey& rhs) = default;
ServiceKey& ServiceKey::operator=(ServiceKey&& rhs) = default;

// static
ErrorOr<ServiceKey> ServiceKey::TryCreate(const MdnsRecord& record) {
  return TryCreate(GetDomainName(record));
}

// static
ErrorOr<ServiceKey> ServiceKey::TryCreate(const DomainName& names) {
  // Size must be at least 4, because the minimum valid label is of the form
  // <instance>.<service type>.<protocol>.<domain>
  if (names.labels().size() < 4) {
    return Error::Code::kParameterInvalid;
  }

  // Skip the InstanceId.
  auto it = ++names.labels().begin();

  std::string service_name = *it++;
  const std::string protocol = *it++;
  const std::string service_id = service_name.append(".").append(protocol);
  if (!IsServiceValid(service_id)) {
    return Error::Code::kParameterInvalid;
  }

  const std::string domain_id = absl::StrJoin(it, names.labels().end(), ".");
  if (!IsDomainValid(domain_id)) {
    return Error::Code::kParameterInvalid;
  }

  return ServiceKey(service_id, domain_id);
}

}  // namespace discovery
}  // namespace openscreen


text:
Search Paths
------------

.. automodule:: ament_index_python.search_paths


text:
set -e
# Push Service and Service Broker
cf push -f hello-service/manifest.yml -b java_buildpack
cf push -f hello-service-broker/manifest.yml -b java_buildpack
# Register Service Broker with Cloud Foundry
cf create-service-broker Hello user password http://hello-service-broker.local.micropcf.io
cf m
cf service-brokers
cf enable-service-access hello-service
cf m
# Create Service and Push hello-service-client
cf cs hello-service english hello-service
cf push -f hello-service-client/manifest.yml -b java_buildpack
open http://hello-service-client.local.micropcf.io/hello


text:
var v: string;
for (v of new StringIterator) { } // Should fail

class StringIterator {
    next() {
        return "";
    }
    [Symbol.iterator]() {
        return this;
    }
}

//// [for-of15.js]
var v;
for (v of new StringIterator) { } // Should fail
class StringIterator {
    next() {
        return "";
    }
    [Symbol.iterator]() {
        return this;
    }
}


text:
#ifndef OPENTISSUE_KINEMATICS_SKELETON_IO_SKELETON_XML_WRITE_H
#define OPENTISSUE_KINEMATICS_SKELETON_IO_SKELETON_XML_WRITE_H
//
// OpenTissue Template Library
// - A generic toolbox for physics-based modeling and simulation.
// Copyright (C) 2008 Department of Computer Science, University of Copenhagen.
//
// OTTL is licensed under zlib: http://opensource.org/licenses/zlib-license.php
//
#include <OpenTissue/configuration.h>

#include <TinyXML/tinyxml.h>

#include <stdexcept>

namespace OpenTissue
{
  namespace skeleton
  {
    namespace detail
    {

      /**
      * Write Skeleton.
      *
      * @param doc          The XML document that should be written.
      * @param skeleton     This argument holds the skeleton that should be written to the XML file.
      *
      * @return           If skeleton was written succesfully then the return value is true otherwise it is false.
      */
      template<typename skeleton_type>
      bool xml_write(TiXmlDocument & doc, skeleton_type const & skeleton)
      {
        typedef typename skeleton_type::math_types::coordsys_type    coordsys_type;
        typedef typename skeleton_type::bone_type                    bone_type;
        typedef typename bone_type::bone_traits                      bone_traits;
        typedef typename skeleton_type::const_bone_iterator          const_bone_iterator;

        TiXmlElement * skeleton_elem = new TiXmlElement( "skeleton" );
        doc.LinkEndChild(skeleton_elem);

        const_bone_iterator bone = skeleton.begin();
        const_bone_iterator end  = skeleton.end();
        for(;bone!=end;++bone)
        {
          TiXmlElement * bone_elem = new TiXmlElement( "bone" );

          if(bone->parent())
          {
            bone_elem->SetAttribute( "parent", bone->parent()->get_name() );
          }
          bone_elem->SetAttribute( "name", bone->get_name() );
          {
            coordsys_type bind_pose = bone_traits::convert( bone->bind_pose() );
            std::stringstream stream;
            stream.precision(15);
            stream << bind_pose;
            bone_elem->SetAttribute( "bindpose", stream.str() );
          }
          {
            coordsys_type bone_space = bone_traits::convert( bone->bone_space() );
            std::stringstream stream;
            stream.precision(15);
            stream << bone_space;
            bone_elem->SetAttribute( "bonespace", stream.str() );
          }
          skeleton_elem->LinkEndChild( bone_elem );
        }

        return true;
      }

    }// namespace detail

    /**
    * Write Skeleton.
    *
    * @param filename     The filename of the XML document that should be written.
    * @param skeleton     This argument holds the skeleton that should be written to the XML file.
    *
    * @return           If skeleton was written succesfully then the return value is true otherwise it is false.
    */
    template<typename skeleton_type>
    bool xml_write(std::string const & filename,skeleton_type const & skeleton)
    {
      // build document
      TiXmlDocument doc;

      TiXmlDeclaration * decl = new TiXmlDeclaration( "1.0", "", "" );
      doc.LinkEndChild(decl);

      if(!OpenTissue::skeleton::detail::xml_write( doc, skeleton ) )
        return false;

      // write the document
#ifdef TIXML_USE_STL
      doc.SaveFile(filename);
#else
      doc.SaveFile(filename.c_str());
#endif

      return true;
    }

  } // namespace skeleton
} // namespace OpenTissue

//OPENTISSUE_KINEMATICS_SKELETON_IO_SKELETON_XML_WRITE_H
#endif


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>sleep on Joost Plattel</title>
    <link>http://jplattel.nl/tags/sleep/</link>
    <description>Recent content in sleep on Joost Plattel</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <copyright>&copy; 2019</copyright>
    <lastBuildDate>Thu, 06 Oct 2011 10:54:09 +0200</lastBuildDate>

	<atom:link href="http://jplattel.nl/tags/sleep/index.xml" rel="self" type="application/rss+xml" />

    <item>
      <title>Moon phases and sleep patterns</title>
      <link>http://jplattel.nl/post/2011-10-06-moon-phases-and-sleep-patterns/</link>
      <pubDate>Thu, 06 Oct 2011 10:54:09 +0200</pubDate>

      <guid>http://jplattel.nl/post/2011-10-06-moon-phases-and-sleep-patterns/</guid>
      <description>Even before I got a Zeo, I was wondering if the phases of the moon are of influence of my sleep quality. With the Zeo that offers an API, I finally had a chance to investigate. As it turns out after four months of experimenting: the phase of the moon doesn't have any influence on my sleep quality or the time it takes to fall asleep.
I've been building my own interface for the Zeo, because the flash based website doesn't suit my needs, here's a small screenshot:</description>
    </item>

    <item>
      <title>First nights with the Zeo sleep monitor</title>
      <link>http://jplattel.nl/post/2011-06-22-zeo-sleep-monitor/</link>
      <pubDate>Wed, 22 Jun 2011 21:53:57 +0200</pubDate>

      <guid>http://jplattel.nl/post/2011-06-22-zeo-sleep-monitor/</guid>
      <description>During the QS Conference the awesome guys from Zeo gifted me one of their sleep monitors. And 1 week ago it arrived by mail. I promised to create as much value in return if I liked the Zeo. And I do, I absolutely do. Here is why:
As an average person sleep 8 hours a day you spend 1/3 of your life lying in bed... That's a lot of time spend.</description>
    </item>

    <item>
      <title>My method for improving dream recall</title>
      <link>http://jplattel.nl/post/2011-04-19-my-method-for-improving-dream-recall/</link>
      <pubDate>Tue, 19 Apr 2011 20:26:21 +0200</pubDate>

      <guid>http://jplattel.nl/post/2011-04-19-my-method-for-improving-dream-recall/</guid>
      <description>
On average, a human spends one third (8 hours) of it's time sleeping. That's a lot and one of the reasons I decided to dip my interest into dreaming and dream recall.

With trial and error, I've made a modified version of the WILD ((http://www.world-of-lucid-dreaming.com/wake-induced-lucid-dreams.html)) method that works for me with a success-rate of about 80% for dream recall, no lucid state yet. So here is how it works:  </description>
    </item>

  </channel>
</rss>


text:
/*
 * @lc app=leetcode id=365 lang=java
 *
 * [365] Water and Jug Problem
 *
 * https://leetcode.com/problems/water-and-jug-problem/description/
 *
 * algorithms
 * Medium (30.87%)
 * Total Accepted:    43.8K
 * Total Submissions: 142K
 * Testcase Example:  '3\n5\n4'
 *
 * You are given two jugs with capacities x and y litres. There is an infinite
 * amount of water supply available. You need to determine whether it is
 * possible to measure exactly z litres using these two jugs.
 *
 * If z liters of water is measurable, you must have z liters of water
 * contained within one or both buckets by the end.
 *
 * Operations allowed:
 *
 *
 * Fill any of the jugs completely with water.
 * Empty any of the jugs.
 * Pour water from one jug into another till the other jug is completely full
 * or the first jug itself is empty.
 *
 *
 * Example 1: (From the famous "Die Hard" example)
 *
 *
 * Input: x = 3, y = 5, z = 4
 * Output: True
 *
 *
 * Example 2:
 *
 *
 * Input: x = 2, y = 6, z = 5
 * Output: False
 *
 *
 * Constraints:
 *
 *
 * 0 <= x <= 10^6
 * 0 <= y <= 10^6
 * 0 <= z <= 10^6
 *
 *
 */
class Solution {
    public boolean canMeasureWater(int x, int y, int z) {
        if (z == 0)
            return true;
        int t = x+y;
        if (z > t)
            return false;
        x = Math.max(x, y);
        y = t-x;
        if (y == 0)
            return z == x;
        Set<Integer> set = new HashSet<>();
        int mod = 0;
        while (!set.contains(mod)) {
            set.add(mod);
            if (mod == z%y)
                return true;
            mod = y-(x-mod)%y;
        }
        return false;
    }
}


text:
<?php

namespace EnvPHP;

class Env
{

    private function __construct()
    {
    }

    public static function prefix($keyword)
    {
        $selected = array_filter($_SERVER, function($key) use($keyword) {
            return Env::startsWith($key, $keyword);
        }, ARRAY_FILTER_USE_KEY);
        return Env::reduce_string($selected, '/\A'.$keyword.'(.*)/');
    }

    public static function suffix($keyword)
    {
        $selected = array_filter($_SERVER, function($key) use($keyword) {
            return Env::endsWith($key, $keyword);
        }, ARRAY_FILTER_USE_KEY);
        return Env::reduce_string($selected, '/(.*)'.$keyword.'\z/');
    }

    private static function reduce_string($arr, $keyword)
    {
        $result = array();
        foreach ($arr as $key => $value) {
            preg_match($keyword, $key, $matches);
            $newKey = strtolower($matches[1]);
            $result[$newKey] = $value;
        }
        return $result;
    }

    private static function startsWith($input, $keyword)
    {
        if (is_string($input)) {
            return substr_compare($input, $keyword, 0, strlen($keyword)) === 0;
        }
    }

    private static function endsWith($input, $keyword)
    {
        if (is_string($input)) {
            return substr_compare($input, $keyword, - strlen($keyword)) === 0;
        }
    }
}


text:
package nl.talsmasoftware.umldoclet.javadoc;

import nl.talsmasoftware.umldoclet.uml.TypeName;

import javax.lang.model.element.Element;
import javax.lang.model.element.QualifiedNameable;
import javax.lang.model.type.ArrayType;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.NoType;
import javax.lang.model.type.PrimitiveType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.TypeVariable;
import javax.lang.model.type.TypeVisitor;
import javax.lang.model.type.WildcardType;
import javax.lang.model.util.SimpleTypeVisitor9;
import java.util.Collections;
import java.util.EnumSet;
import java.util.IdentityHashMap;
import java.util.Set;

/**
 * The UML type name implemented as {@link TypeVisitor}.
 *
 * @author Sjoerd Talsma
 */
final class TypeNameVisitor extends SimpleTypeVisitor9<TypeName, Void> {
    private static final EnumSet<TypeKind> NO_KNOWN_TYPES = EnumSet.of(
            TypeKind.VOID, TypeKind.NONE, TypeKind.NULL, TypeKind.ERROR, TypeKind.OTHER);

    static final TypeNameVisitor INSTANCE = new TypeNameVisitor();

    private TypeNameVisitor() {
    }

    private static ThreadLocal<Set<TypeMirror>> VISITED = ThreadLocal.withInitial(
            () -> Collections.newSetFromMap(new IdentityHashMap<>()));

    /**
     * Internal variant of {@link #visit(TypeMirror, Object)} for calls from inside this visitor itself.
     * <p>
     * Main purpose of this method is to limit the endless recursion that would result for types such as
     * {@code <T extends Comparable<T>>}
     *
     * @param type      The type to visit.
     * @param parameter The parameter (ignored by our visitor).
     * @return The type name
     */
    private TypeName _visit(TypeMirror type, Void parameter) {
        if (VISITED.get().add(type)) try {
            return super.visit(type, parameter);
        } finally {
            VISITED.get().remove(type);
            if (VISITED.get().isEmpty()) VISITED.remove();
        }
        return defaultAction(type, parameter);
    }

    @Override
    public TypeName visitPrimitive(PrimitiveType primitiveType, Void parameter) {
        // "byte", "char", "short", "int", "long", "float", "double", "boolean"
        final String primitive = primitiveType.getKind().name().toLowerCase();
        return new TypeName(primitive, primitive);
    }

    @Override
    public TypeName visitNoType(NoType noType, Void parameter) {
        // "void", "package", "module", "none"
        final String none = noType.getKind().name().toLowerCase();
        return new TypeName(none, none);
    }

    @Override
    public TypeName visitDeclared(DeclaredType declaredType, Void parameter) {
        final Element el = declaredType.asElement();
        final String simpleName = el.getSimpleName().toString();
        final String qualifiedName = el instanceof QualifiedNameable
                ? ((QualifiedNameable) el).getQualifiedName().toString() : simpleName;
        final TypeName[] generics = declaredType.getTypeArguments().stream()
                .map(generic -> _visit(generic, parameter))
                .toArray(TypeName[]::new);
        return new TypeName(simpleName, qualifiedName, generics);
    }

    @Override
    public TypeName visitArray(ArrayType arrayType, Void parameter) {
        return TypeName.Array.of(_visit(arrayType.getComponentType(), parameter));
    }

    @Override
    public TypeName visitTypeVariable(TypeVariable typeVariable, Void parameter) {
        TypeMirror upperBound = typeVariable.getUpperBound();
        if (upperBound != null && !NO_KNOWN_TYPES.contains(upperBound.getKind())) {
            // Fix for #64: Avoid redundant <T extends Object> (which is obviously true for all T's)
            TypeName upperBoundName = _visit(upperBound, parameter);
            if (!Object.class.getName().equals(upperBoundName.qualified)) {
                return TypeName.Variable.extendsBound(typeVariable.toString(), upperBoundName);
            }
        }
        TypeMirror lowerBound = typeVariable.getLowerBound();
        if (lowerBound != null && !NO_KNOWN_TYPES.contains(lowerBound.getKind())) {
            return TypeName.Variable.superBound(typeVariable.toString(), _visit(lowerBound, parameter));

        }

        return defaultAction(typeVariable, parameter);
    }

    @Override
    public TypeName visitWildcard(WildcardType wildcardType, Void parameter) {
        TypeMirror extendsBound = wildcardType.getExtendsBound();
        if (extendsBound != null) return TypeName.Variable.extendsBound("?", _visit(extendsBound, parameter));
        TypeMirror superBound = wildcardType.getSuperBound();
        if (superBound != null) return TypeName.Variable.superBound("?", _visit(superBound, parameter));

        return defaultAction(wildcardType, parameter);
    }

    @Override
    protected TypeName defaultAction(TypeMirror tp, Void parameter) {
        String qualified = tp.toString();
        int lt = qualified.lastIndexOf('<');
        int dot = (lt < 0 ? qualified : qualified.substring(0, lt)).lastIndexOf('.');
        return new TypeName(qualified.substring(dot + 1), qualified);
    }

}


text:
{% extends "base.html" %}
{% load compress %}

{% block ngapp %}jobrunner{% endblock %}

{% block extrahead %}
    <script type="text/javascript">
        var ws_server = '{{ ws_server }}';
    </script>
{% endblock %}

{% block extrajs %}
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>

    {% compress js %}
        <script type="text/javascript" src="{{ STATIC_URL }}js/bootstrap/bootstrap-modal.js"></script>
        <script type="text/javascript" src="{{ STATIC_URL }}js/bootstrap/bootstrap-transition.js"></script>
        <script type="text/javascript" src="{{ STATIC_URL }}js/bootstrap/bootstrap-tab.js"></script>

        <script type="text/javascript" src="{{ STATIC_URL }}js/moment.min.js"></script>

        <script type="text/javascript" src="{{ STATIC_URL }}job_runner/js/app.js"></script>
        <script type="text/javascript" src="{{ STATIC_URL }}job_runner/js/controllers.js"></script>
        <script type="text/javascript" src="{{ STATIC_URL }}job_runner/js/models.js"></script>
        <script type="text/javascript" src="{{ STATIC_URL }}job_runner/js/services.js"></script>
        <script type="text/javascript" src="{{ STATIC_URL }}job_runner/js/filters.js"></script>
        <script type="text/javascript" src="{{ STATIC_URL }}job_runner/js/directives.js"></script>
    {% endcompress %}

    <script type="text/javascript">google.load("visualization", "1", {packages:["corechart"]});</script>
{% endblock %}

{% block extracss %}
    <link rel="stylesheet/less" href="{{ STATIC_URL }}job_runner/less/job_runner.less" />
{% endblock %}

{% block bodyid %}job_runner{% endblock %}

{% block content %}
    <div ng-view></div>
{% endblock %}


text:
package com.javarush.task.task15.task1507;

/*
ООП - Перегрузка
Перегрузите метод printMatrix 8 различными способами. В итоге должно получиться 10 различных методов printMatrix.
*/

public class Solution {
    public static void main(String[] args) {
        printMatrix(2, 3, "8");
    }

    public static void printMatrix(int m, int n, String value) { //1
        System.out.println("Заполняем объектами String");
        printMatrix(m, n, (Object) value);
    }

    public static void printMatrix(int m, int n, Object value) { //2
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(value);
            }
            System.out.println();
        }
    }
    public static void printMatrix(){                            //3
        System.out.println("Что-то по умолчанию");
    }

    public static void printMatrix(int[][] matrix) {             //4
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.print(matrix[i][j]);
            }
        }
    }

    public static void printMatrix(String title){               //5
            System.out.println(title);
    }

    public static int printMatrix(int n, int m){               //6
        return n*m;
    }

    public static int printMatrix(int n, int m, int k){        //7
        return n*m*k;
    }

    public static double printMatrix(double n, double m){      //8
        return n*m;
    }

    public static String printMatrix(Object o){               //9
        return "Matrix SAY: Hello my FirstName is:"+o.getClass().getSimpleName();
    }

    public static Object printMatrix(Object o, boolean life){  //10
        boolean is = true;
        if (life || is || life)
            return o;
        return null;
    }

}


text:
package im.actor.server.sequence

import akka.actor.ActorSystem
import com.google.protobuf.wrappers.{ Int32Value, StringValue }
import com.relayrides.pushy.apns.PushNotificationResponse
import com.relayrides.pushy.apns.util.{ SimpleApnsPushNotification, TokenUtil }
import im.actor.server.model.push.ApplePushCredentials
import io.netty.util.concurrent.{ Future ⇒ NFuture }
import scodec.bits.BitVector

import scala.collection.concurrent.TrieMap

trait APNSSend {

  private val listeners = TrieMap.empty[String, PushFutureListener]

  protected def sendNotification(payload: String, creds: ApplePushCredentials, userId: Int)(implicit client: ApplePushExtension#Client, system: ActorSystem): NFuture[PushNotificationResponse[SimpleApnsPushNotification]] = {
    // when topic is null, it will be taken from APNs certificate
    // http://relayrides.github.io/pushy/apidocs/0.6/com/relayrides/pushy/apns/ApnsPushNotification.html#getTopic--
    val token = BitVector(creds.token.toByteArray).toHex
    val topic: String = (creds.apnsKey, creds.bundleId) match {
      case (_, Some(bundleId)) ⇒ bundleId.value
      case (Some(key), _)      ⇒ ApplePushExtension(system).apnsBundleId.get(key.value).orNull
      case _ ⇒
        system.log.warning("Wrong creds format on sending notification. Creds: {}", creds)
        null
    }
    system.log.debug(s"Sending APNS, token: {}, key: {}, isVoip: {}, topic: {}, payload: $payload", token, creds.apnsKey, creds.isVoip, topic)
    val notification = new SimpleApnsPushNotification(TokenUtil.sanitizeTokenString(token), topic, payload)
    val listener = listeners.getOrElseUpdate(token, new PushFutureListener(userId, creds, extractCredsId(creds))(system))
    client.sendNotification(notification).addListener(listener)
  }

  protected def extractCredsId(creds: ApplePushCredentials): String = (creds.apnsKey, creds.bundleId) match {
    case (Some(Int32Value(key)), _)       ⇒ key.toString
    case (_, Some(StringValue(bundleId))) ⇒ bundleId
    case _                                ⇒ throw new RuntimeException("Wrong credentials format")
  }

}


text:
/*
 * GWTPHP is a port to PHP of the GWT RPC package.
 * This framework is based on GWT.
 * Design, strategies and part of the methods documentation are developed by Google Inc.
 * PHP port, extensions and modifications by Rafal M.Malinowski. All rights reserved.
 * Additional modifications, GWT generators and linkers by Yifei Teng. All rights reserved.
 * For more information, please see {@link https://github.com/tengyifei/gwtphp}
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.tyf.gwtphp.linker;

import java.io.PrintWriter;
import java.io.StringWriter;

import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.user.rebind.SourceWriter;

public class CustomIndentSourceWriter implements SourceWriter {
	private final String indentString;
	private final StringWriter buffer = new StringWriter();
	private int indentLevel = 0;
	private String indentPrefix = "";
	private boolean needsIndent;
	private final PrintWriter out = new PrintWriter(buffer);

	public CustomIndentSourceWriter(){
		this.indentString = "  ";
	}

	public CustomIndentSourceWriter(String indentString){
		this.indentString = indentString;
	}

	public void beginJavaDocComment() {
		println("/**");
		indentPrefix = " * ";
	}

	/**
	 * This is a no-op.
	 */
	public void commit(TreeLogger logger) {
		out.flush();
	}

	public void endJavaDocComment() {
		indentPrefix = "";
		println("*/");
	}

	public void indent() {
		indentLevel++;
	}

	public void indentln(String s) {
		indent();
		println(s);
		outdent();
	}

	public void indentln(String s, Object... args) {
		indentln(String.format(s, args));
	}

	public void outdent() {
		indentLevel = Math.max(indentLevel - 1, 0);
	}

	public void print(String s) {
		maybeIndent();
		out.print(s);
	}

	public void print(String s, Object... args) {
		print(String.format(s, args));
	}

	public void println() {
		maybeIndent();
		// Unix-style line endings for consistent behavior across platforms.
		out.print('\n');
		needsIndent = true;
	}

	public void println(String s) {
		print(s);
		println();
	}

	public void println(String s, Object... args) {
		println(String.format(s, args));
	}

	@Override
	public String toString() {
		out.flush();
		return buffer.getBuffer().toString();
	}

	private void maybeIndent() {
		if (needsIndent) {
			needsIndent = false;
			for (int i = 0; i < indentLevel; i++) {
				out.print(indentString);
				out.print(indentPrefix);
			}
		}
	}
}


text:
<?php

pake_desc('upgrade to a new symfony release');
pake_task('upgrade');

pake_desc('downgrade to a previous symfony release');
pake_task('downgrade', 'project_exists');

function run_downgrade($task, $args)
{
  throw new Exception('I have no downgrade script for this release.');
}

function run_upgrade($task, $args)
{
  if (!isset($args[0]))
  {
    throw new Exception('You must provide the upgrade script to use (1.0 to upgrade to symfony 1.0 for example).');
  }

  $version = $args[0];

   if ($version == '1.0')
   {
     run_upgrade_1_0($task, $args);
   }
   else
   {
     throw new Exception('I have no upgrade script for this release.');
   }
}

function run_upgrade_1_0($task, $args)
{
  // check we have a project
  if (!file_exists('symfony') && !file_exists('SYMFONY'))
  {
    throw new Exception('You must be in a symfony project directory');
  }

  // upgrade propel.ini
  _upgrade_1_0_propel_ini();

  // upgrade i18n support
  _upgrade_1_0_i18n();

  // upgrade model classes
  _upgrade_1_0_propel_model();

  // migrate activate to enabled
  _upgrade_1_0_activate();

  // find all applications for this project
  $apps = pakeFinder::type('directory')->ignore_version_control()->name(sfConfig::get('sf_app_module_dir_name'))->mindepth(1)->maxdepth(1)->relative()->in(sfConfig::get('sf_apps_dir_name'));

  // install symfony CLI
  if (file_exists(sfConfig::get('sf_root_dir').'/SYMFONY'))
  {
    pake_remove(sfConfig::get('sf_root_dir').'/SYMFONY', '');
  }
  pake_copy(sfConfig::get('sf_symfony_data_dir').'/skeleton/project/symfony', sfConfig::get('sf_root_dir').'/symfony');
  pake_chmod('symfony', sfConfig::get('sf_root_dir'), 0777);

  // update schemas
  _upgrade_1_0_schemas();

  // add bootstrap files for tests
  _add_1_0_test_bootstraps();

  // upgrade main config.php
  _upgrade_1_0_main_config_php();

  // upgrade all applications
  foreach ($apps as $app_module_dir)
  {
    $app = str_replace(DIRECTORY_SEPARATOR.sfConfig::get('sf_app_module_dir_name'), '', $app_module_dir);
    pake_echo_action('upgrade 1.0', pakeColor::colorize(sprintf('upgrading application "%s"', $app), array('fg' => 'cyan')));

    $app_dir = sfConfig::get('sf_apps_dir_name').'/'.$app;

    // upgrade config.php
    _upgrade_1_0_config_php($app_dir);

    // upgrade filters.yml
    _upgrade_1_0_filters_yml($app_dir);

    // upgrade all modules
    $dir = $app_dir.'/'.sfConfig::get('sf_app_module_dir_name');
    if ($dir)
    {
      // template dirs
      $template_dirs   = pakeFinder::type('directory')->ignore_version_control()->name('templates')->mindepth(1)->maxdepth(1)->in($dir);
      $template_dirs[] = $app_dir.'/'.sfConfig::get('sf_app_template_dir_name');

      _upgrade_1_0_deprecated_for_templates($template_dirs);

      _upgrade_1_0_date_form_helpers($template_dirs);

      _upgrade_1_0_deprecated_for_generator($app_dir);

      _upgrade_1_0_cache_yml($app_dir);

      // actions dirs
      $action_dirs = pakeFinder::type('directory')->ignore_version_control()->name('actions')->mindepth(1)->maxdepth(1)->in($dir);

      _upgrade_1_0_deprecated_for_actions($action_dirs);

      // view.yml
      _upgrade_1_0_view_yml($app_dir);

      _upgrade_1_0_php_files($app_dir);
    }
  }

  pake_echo_action('upgrade 1.0', 'done');

  pake_mkdirs(sfConfig::get('sf_root_dir').'/plugins');
  if (is_dir(sfConfig::get('sf_lib_dir').'/plugins'))
  {
    pake_echo_comment('WARNING: you must re-install all your plugins');
  }

  pake_echo_comment('Now, you must:');
  pake_echo_comment(' - rebuild your model classes: symfony propel-build-model');
  pake_echo_comment(' - clear the cache: symfony cc');
}

function _upgrade_1_0_i18n()
{
  $dirs = array(sfConfig::get('sf_lib_dir_name'), sfConfig::get('sf_apps_dir_name'));
  $finder = pakeFinder::type('file')->ignore_version_control()->name('*.php');

  $seen = false;
  foreach ($finder->in($dirs) as $php_file)
  {
    $content = file_get_contents($php_file);

    $count = 0;
    $content = str_replace('sfConfig::get(\'sf_i18n_instance\')', 'sfContext::getInstance()->getI18N()', $content, $count);

    if ($count && !$seen)
    {
      $seen = true;
      pake_echo_comment('sfConfig::get(\'sf_i18n_instance\') is deprecated');
      pake_echo_comment(' use sfContext::getInstance()->getI18N()');
    }

    if ($count)
    {
      file_put_contents($php_file, $content);
    }
  }
}

function _upgrade_1_0_php_files($app_dir)
{
  pake_echo_action('upgrade 1.0', 'upgrading sf/ path configuration');

  $php_files = pakeFinder::type('file')->ignore_version_control()->name('*.php')->in($app_dir);
  foreach ($php_files as $php_file)
  {
    $content = file_get_contents($php_file);

    $deprecated = array(
      "'/sf/js/prototype"     => "sfConfig::get('sf_prototype_web_dir').'/js",
      "'/sf/css/prototype"    => "sfConfig::get('sf_prototype_web_dir').'/css",
      "'/sf/js/sf_admin"      => "sfConfig::get('sf_admin_web_dir').'/js",
      "'/sf/css/sf_admin"     => "sfConfig::get('sf_admin_web_dir').'/css",
      "'/sf/images/sf_admin"  => "sfConfig::get('sf_admin_web_dir').'/images",
    );
    $seen = array();
    $updated = false;
    foreach ($deprecated as $old => $new)
    {
      $count = 0;
      $content = str_replace($old, $new, $content, $count);
      if ($count)
      {
        $updated = true;
      }
      if ($count && !isset($seen[$old]))
      {
        $seen[$old] = true;
        pake_echo_comment(sprintf('%s is deprecated', $old));
        pake_echo_comment(sprintf(' use %s', $new));
      }
    }

    if ($updated)
    {
      file_put_contents($php_file, $content);
    }
  }
}

function _upgrade_1_0_activate()
{
  pake_echo_action('upgrade 1.0', 'migrate activate to enabled');

  $config_files = array(
    'settings.yml' => array(
      'activated_modules:' => 'enabled_modules:  ',
    ),
    'cache.yml' => array(
      'activate:' => 'enabled: ',
    ),
    'logging.yml' => array(
      'active:' => 'enabled:',
    ),
    '*.php' => array(
      'sf_logging_'.'active' => 'sf_logging_enabled',
    ),
    'apps/*/modules/*/validate/*.yml' => array(
      'activate:' => 'enabled: ',
    ),
  );
  $seen = array();
  foreach ($config_files as $config_file => $changed)
  {
    list($dir, $config_file) = array(dirname($config_file), basename($config_file));
    $files = pakeFinder::type('file')->ignore_version_control()->name($config_file)->in(sfConfig::get('sf_root_dir').DIRECTORY_SEPARATOR.$dir);
    foreach ($files as $file)
    {
      $content = file_get_contents($file);

      $updated = false;
      foreach ($changed as $old => $new)
      {
        $content = str_replace($old, $new, $content, $count);
        if ($count)
        {
          $updated = true;
        }
        if ($count && !isset($seen[$config_file.$old]))
        {
          $seen[$config_file.$old] = true;

          pake_echo_comment(sprintf('%s is deprecated in %s', $old, $config_file));
          pake_echo_comment(sprintf(' use %s', $new));
        }
      }

      if ($updated)
      {
        file_put_contents($file, $content);
      }
    }
  }
}

function _upgrade_1_0_view_yml($app_dir)
{
  pake_echo_action('upgrade 1.0', 'upgrading view configuration');

  $yml_files = pakeFinder::type('file')->ignore_version_control()->name('*.yml')->in($app_dir);
  foreach ($yml_files as $yml_file)
  {
    $content = file_get_contents($yml_file);

    $deprecated = array(
      '/sf/js/prototype'     => '%SF_PROTOTYPE_WEB_DIR%/js',
      '/sf/css/prototype'    => '%SF_PROTOTYPE_WEB_DIR%/css',
      '/sf/js/sf_admin'      => '%SF_ADMIN_WEB_DIR%/js',
      '/sf/css/sf_admin'     => '%SF_ADMIN_WEB_DIR%/css',
      '/sf/images/sf_admin'  => '%SF_ADMIN_WEB_DIR%/images',
    );
    $seen = array();
    $updated = false;
    foreach ($deprecated as $old => $new)
    {
      $count = 0;
      $content = str_replace($old, $new, $content, $count);
      if ($count)
      {
        $updated = true;
      }
      if ($count && !isset($seen[$old]))
      {
        $seen[$old] = true;
        pake_echo_comment(sprintf('%s is deprecated', $old));
        pake_echo_comment(sprintf(' use %s', $new));
      }
    }

    if ($updated)
    {
      file_put_contents($yml_file, $content);
    }
  }
}

function _upgrade_1_0_cache_yml($app_dir)
{
  pake_echo_action('upgrade 1.0', 'upgrading cache configuration');

  $yml_files = pakeFinder::type('files')->ignore_version_control()->name('cache.yml')->in($app_dir);

  $seen = false;
  foreach ($yml_files as $yml_file)
  {
    $content = file_get_contents($yml_file);

    $count = 0;
    $updated = false;
    $content = preg_replace_callback('/type\:(\s*)(.+)$/m', '_upgrade_1_0_cache_yml_callback', $content, -1, $count);
    if ($count)
    {
      $updated = true;
    }
    if ($count && !$seen)
    {
      $seen = true;
      pake_echo_comment('"type" has been removed in cache.yml');
      pake_echo_comment('  read the doc about "with_layout"');
    }

    if ($updated)
    {
      file_put_contents($yml_file, $content);
    }
  }
}

function _upgrade_1_0_cache_yml_callback($match)
{
  return 'with_layout:'.str_repeat(' ', max(1, strlen($match[1]) - 6)).(0 === strpos($match[2], 'page') ? 'true' : 'false');
}

function _upgrade_1_0_deprecated_for_generator($app_dir)
{
  pake_echo_action('upgrade 1.0', 'upgrading deprecated helpers in generator.yml');

  $yml_files = pakeFinder::type('files')->ignore_version_control()->name('generator.yml')->in($app_dir);

  $seen = array();
  $deprecated_str = array(
    'admin_input_upload_tag' => 'admin_input_file_tag',
  );
  foreach ($yml_files as $yml_file)
  {
    $updated = false;
    foreach ($deprecated_str as $old => $new)
    {
      $content = file_get_contents($yml_file);

      $count = 0;
      $content = str_replace($old, $new, $content, $count);
      if ($count)
      {
        $updated = true;
      }
      if ($count && !isset($seen[$old]))
      {
        $seen[$old] = true;
        pake_echo_comment(sprintf('%s() has been removed', $old));
        pake_echo_comment(sprintf(' use %s()', $new));
      }
    }

    if ($updated)
    {
      file_put_contents($yml_file, $content);
    }
  }
}

function _upgrade_1_0_deprecated_for_actions($action_dirs)
{
  pake_echo_action('upgrade 1.0', 'upgrading deprecated methods in actions');

  $php_files = pakeFinder::type('file')->ignore_version_control()->name('*.php')->in($action_dirs);
  foreach ($php_files as $php_file)
  {
    $content = file_get_contents($php_file);

    $deprecated = array(
      '$this->addHttpMeta'   => '$this->getContext()->getResponse()->addHttpMeta',
      '$this->addMeta'       => '$this->getContext()->getResponse()->addMeta',
      '$this->setTitle'      => '$this->getContext()->getResponse()->setTitle',
      '$this->addStylesheet' => '$this->getContext()->getResponse()->addStylesheet',
      '$this->addJavascript' => '$this->getContext()->getResponse()->addJavascript',
    );
    $seen = array();
    $updated = false;
    foreach ($deprecated as $old => $new)
    {
      $count = 0;
      $content = str_replace($old, $new, $content, $count);
      if ($count)
      {
        $updated = true;
      }
      if ($count && !isset($seen[$old]))
      {
        $seen[$old] = true;
        pake_echo_comment(sprintf('%s has been removed', $old));
        pake_echo_comment(sprintf(' use %s', $new));
      }
    }

    if ($updated)
    {
      file_put_contents($php_file, $content);
    }
  }
}

function _upgrade_1_0_date_form_helpers($template_dirs)
{
  pake_echo_action('upgrade 1.0', 'upgrading date form helpers');

  $helpers = array(
    'select_day_tag', 'select_month_tag', 'select_year_tag', 'select_date_tag', 'select_second_tag', 'select_minute_tag',
    'select_hour_tag', 'select_ampm_tag', 'select_time_tag', 'select_datetime_tag', 'select_number_tag', 'select_timezone_tag',
  );
  $regex = '/('.implode('|', $helpers).')/';

  $php_files = pakeFinder::type('file')->ignore_version_control()->name('*.php')->in($template_dirs);
  $seen = false;
  foreach ($php_files as $php_file)
  {
    $updated = false;

    $content = file_get_contents($php_file);

    if (preg_match($regex, $content) && false === strpos($content, 'DateForm'))
    {
      $updated = true;
      if (!$seen)
      {
        $seen = true;

        pake_echo_comment('date form helpers has been moved to the DateForm helper group');
      }
    }

    if ($updated)
    {
      file_put_contents($php_file, $content);
    }
  }
}

function _upgrade_1_0_deprecated_for_templates($template_dirs)
{
  pake_echo_action('upgrade 1.0', 'upgrading deprecated helpers');

  $php_files = pakeFinder::type('file')->ignore_version_control()->name('*.php')->in($template_dirs);
  $seen = array();
  $deprecated_str = array(
    'use_helpers'                   => 'use_helper',
    'object_admin_input_upload_tag' => 'object_admin_input_file_tag',
    'input_upload_tag'              => 'input_file_tag',
    '$sf_last_module'               => '$sf_context->getModuleName()',
    '$sf_last_action'               => '$sf_context->getActionName()',
    '$sf_first_module'              => '$sf_context->getActionStack()->getFirstEntry()->getModuleName()',
    '$sf_first_action'              => '$sf_context->getActionStack()->getFirstEntry()->getActionName()',
  );
  foreach ($php_files as $php_file)
  {
    $content = file_get_contents($php_file);

    $updated = false;
    $count = 0;

    foreach ($deprecated_str as $old => $new)
    {
      $content = str_replace($old, $new, $content, $count);
      if ($count)
      {
        $updated = true;
      }
      if ($count && !isset($seen[$old]))
      {
        $seen[$old] = true;
        pake_echo_comment(sprintf('%s has been removed', $old));
        pake_echo_comment(sprintf(' use %s', $new));
      }
    }

    if ($updated)
    {
      file_put_contents($php_file, $content);
    }
  }
}

function _upgrade_1_0_config_php($app_dir)
{
  pake_echo_action('upgrade 1.0', 'upgrading config.php');

  pake_copy(sfConfig::get('sf_symfony_data_dir').'/skeleton/app/app/config/config.php', $app_dir.DIRECTORY_SEPARATOR.sfConfig::get('sf_config_dir_name').DIRECTORY_SEPARATOR.'config.php');
}

function _upgrade_1_0_filters_yml($app_dir)
{
  pake_echo_action('upgrade 1.0', 'upgrading filters.yml');

  $configFile = $app_dir.DIRECTORY_SEPARATOR.sfConfig::get('sf_config_dir_name').DIRECTORY_SEPARATOR.'filters.yml';
  $content = file_get_contents($configFile);

  // default symfony filters
  $default = file_get_contents(sfConfig::get('sf_symfony_data_dir').'/skeleton/app/app/config/filters.yml');

  $placeholder = '# generally, you will want to insert your own filters here';

  // upgrade module filters.yml
  $seen = false;
  $yml_files = pakeFinder::type('file')->ignore_version_control()->name('filters.yml')->in($app_dir.DIRECTORY_SEPARATOR.'modules');
  foreach ($yml_files as $yml_file)
  {
    $module_content = file_get_contents($yml_file);

    if (false === strpos($module_content, 'rendering:'))
    {
      $lb = (strpos($module_content, "\r\n") !== false) ? "\r\n" : "\n";

      $module_content = str_replace($placeholder, $placeholder.$lb.$content.$lb.$module_content, $default);

      file_put_contents($yml_file, $module_content);

      if (!$seen)
      {
        pake_echo_comment('filters.yml now contains core symfony filters');
      }

      $seen = true;
    }
  }

  // upgrade app filters.yml
  if (false === strpos($content, 'rendering:'))
  {
    $lb = (strpos($content, "\r\n") !== false) ? "\r\n" : "\n";
    $content = str_replace($placeholder, $placeholder.$lb.$content, $default);

    file_put_contents($configFile, $content);

    if (!$seen)
    {
      pake_echo_comment('filters.yml now contains core symfony filters');
    }
  }

  // upgrade project filters.yml
  $configFile = sfConfig::get('sf_config_dir').DIRECTORY_SEPARATOR.'filters.yml';
  if (is_readable($configFile))
  {
    $content = file_get_contents($configFile);
    if (false === strpos($content, 'rendering:'))
    {
      $lb = (strpos($content, "\r\n") !== false) ? "\r\n" : "\n";
      $content = str_replace($placeholder, $placeholder.$lb.$content, $default);

      file_put_contents($configFile, $content);

      if (!$seen)
      {
        pake_echo_comment('filters.yml now contains core symfony filters');
      }
    }
  }
}

function _upgrade_1_0_main_config_php()
{
  pake_echo_action('upgrade 1.0', 'upgrading main config.php');

  $content = file_get_contents(sfConfig::get('sf_root_dir').'/config/config.php');

  if (false === strpos($content, 'sf_symfony_lib_dir'))
  {
    pake_echo_comment('symfony lib and data dir are now configured in main config.php');

    $lib_dir = sfConfig::get('sf_symfony_lib_dir');
    $data_dir = sfConfig::get('sf_symfony_data_dir');
    if (is_link('lib/symfony') && is_link('data/symfony'))
    {
      $config = <<<EOF

\$sf_symfony_lib_dir  = dirname(__FILE__).'/../lib/symfony';
\$sf_symfony_data_dir = dirname(__FILE__).'/../data/symfony';

EOF;
    }
    else
    {
      $config = <<<EOF

\$sf_symfony_lib_dir  = '$lib_dir';
\$sf_symfony_data_dir = '$data_dir';

EOF;
    }

    $content = preg_replace('/^<\?php/s', '<?php'.$config, $content);

    file_put_contents(sfConfig::get('sf_root_dir').'/config/config.php', $content);
  }
}

function _upgrade_1_0_propel_model()
{
  pake_echo_action('upgrade 1.0', 'upgrading require in models');

  $seen = false;
  $php_files = pakeFinder::type('file')->ignore_version_control()->name('*.php')->in(sfConfig::get('sf_lib_dir').'/model');
  foreach ($php_files as $php_file)
  {
    $content = file_get_contents($php_file);

    $count1 = 0;
    $count2 = 0;
    $updated = false;
    $content = str_replace('require_once \'model', 'require_once \'lib/model', $content, $count1);
    $content = str_replace('include_once \'model', 'include_once \'lib/model', $content, $count2);
    if ($count1 || $count2)
    {
      $updated = true;
    }
    if (($count1 || $count2) && !$seen)
    {
      $seen = true;
      pake_echo_comment('model require must be lib/model/...');
      pake_echo_comment('  instead of model/...');
    }

    if ($updated)
    {
      file_put_contents($php_file, $content);
    }
  }
}

function _upgrade_1_0_schemas()
{
  pake_echo_action('upgrade 1.0', 'upgrading schemas');

  $seen = false;
  $xml_files = pakeFinder::type('file')->ignore_version_control()->name('*schema.xml')->in(sfConfig::get('sf_config_dir'));
  foreach ($xml_files as $xml_file)
  {
    $content = file_get_contents($xml_file);

    if (preg_match('/<database[^>]*package[^>]*>/', $content))
    {
      continue;
    }

    $count = 0;
    $updated = false;
    $content = str_replace('<database', '<database package="lib.model"', $content, $count);
    if ($count)
    {
      $updated = true;
    }
    if ($count && !$seen)
    {
      $seen = true;
      pake_echo_comment('schema.xml must now have a database package');
      pake_echo_comment('  default is package="lib.model"');
    }

    if ($updated)
    {
      file_put_contents($xml_file, $content);
    }
  }
}

function _upgrade_1_0_propel_ini()
{
  pake_echo_action('upgrade 1.0', 'upgrading propel.ini configuration file');

  $propel_file = sfConfig::get('sf_config_dir').DIRECTORY_SEPARATOR.'propel.ini';

  if (is_readable($propel_file))
  {
    $updated = false;
    $propel_ini = file_get_contents($propel_file);

    $count = 0;

    // new target package (needed for new plugin system)
    $propel_ini = preg_replace('#propel\.targetPackage(\s*)=(\s*)model#', 'propel.targetPackage$1=$2lib.model', $propel_ini, -1, $count);
    if ($count)
    {
      $updated = true;
    }
    $propel_ini = preg_replace('#propel.php.dir(\s*)=(\s*)\${propel.output.dir}/lib#', 'propel.php.dir$1=$2\${propel.output.dir}', $propel_ini, -1, $count);
    if ($count)
    {
      $updated = true;
    }

    if (false === strpos($propel_ini, 'propel.packageObjectModel'))
    {
      $updated = true;
      $propel_ini = rtrim($propel_ini);
      $propel_ini .= "\npropel.packageObjectModel = true\n";
    }

    // new propel builder class to be able to remove require_* and strip comments
    $propel_ini = str_replace('propel.engine.builder.om.php5.PHP5ExtensionObjectBuilder', 'addon.propel.builder.SfExtensionObjectBuilder', $propel_ini, $count);
    if ($count)
    {
      $updated = true;
    }
    $propel_ini = str_replace('propel.engine.builder.om.php5.PHP5ExtensionPeerBuilder', 'addon.propel.builder.SfExtensionPeerBuilder', $propel_ini, $count);
    if ($count)
    {
      $updated = true;
    }
    $propel_ini = str_replace('propel.engine.builder.om.php5.PHP5MultiExtendObjectBuilder', 'addon.propel.builder.SfMultiExtendObjectBuilder', $propel_ini, $count);
    if ($count)
    {
      $updated = true;
    }
    $propel_ini = str_replace('propel.engine.builder.om.php5.PHP5MapBuilderBuilder', 'addon.propel.builder.SfMapBuilderBuilder', $propel_ini, $count);
    if ($count)
    {
      $updated = true;
    }

    // replace old symfony.addon.propel path to addon.propel
    $propel_ini = str_replace('symfony.addon.propel.builder.', 'addon.propel.builder.', $propel_ini, $count);
    if ($count)
    {
      $updated = true;
    }

    if (false === strpos($propel_ini, 'addIncludes'))
    {
      $updated = true;
      $propel_ini .= <<<EOF

propel.builder.addIncludes  = false
propel.builder.addComments  = false
propel.builder.addBehaviors = false

EOF;

      pake_echo_comment('there are 3 new propel.ini options:');
      pake_echo_comment(' - propel.builder.addIncludes');
      pake_echo_comment(' - propel.builder.addComments');
      pake_echo_comment(' - propel.builder.addBehaviors');
    }

    if ($updated)
    {
      file_put_contents($propel_file, $propel_ini);
    }
  }
}

function _add_1_0_test_bootstraps()
{
  pake_echo_action('upgrade 1.0', 'add test bootstrap files');

  pake_mkdirs(sfConfig::get('sf_root_dir').'/test/bootstrap');

  pake_copy(sfConfig::get('sf_symfony_data_dir').'/skeleton/project/test/bootstrap/functional.php', sfConfig::get('sf_root_dir').'/test/bootstrap/functional.php');
  pake_copy(sfConfig::get('sf_symfony_data_dir').'/skeleton/project/test/bootstrap/unit.php', sfConfig::get('sf_root_dir').'/test/bootstrap/unit.php');
}


text:
numpy.ma.MaskedArray.ptp
========================

.. currentmodule:: numpy.ma

.. automethod:: MaskedArray.ptp


text:
import click
import getpass
import json
import os
import requests
import yaml

from six.moves import input

class Config(object):

    def __init__(self, path):
        '''Create a new instance.

        Args:
            path: string containing file path
        '''
        self.path = path
        self.read()

    def get(self, key):
        '''Get a configuration value.

        Args:
            key: key as a string to get value for

        Returns:
            Configuration value for requested key.
        '''
        if not self.yaml:
            return None
        return self.yaml.get(key)

    def read(self):
        '''Read the contents of the configuration file.'''
        fd = os.open(self.path, os.O_RDONLY | os.O_CREAT, 0o600)
        with os.fdopen(fd, 'r') as file:
            y = yaml.load(file.read())
            self.yaml = y if y else {}

    def set(self, key, value):
        '''Set a configuration value.

        Args:
            key: key as a string to set the value for
            value: value to assign to key
        '''
        if not self.yaml:
            self.yaml = {}
        self.yaml[key] = value

    def write(self):
        '''Write the configuration to the file.'''
        fd = os.open(self.path, os.O_WRONLY | os.O_CREAT, 0o600)
        with os.fdopen(fd, 'w') as file:
            file.write(yaml.safe_dump(self.yaml, default_flow_style=False))

class Wizard(object):

    show_message = True

    def __init__(self):
        '''Helps create a configuration file when it does not exist.'''
        self.steps = [Api(), Token()]

    def __call__(self, ctx, param, values):
        '''Usable as the callback in a click.Parameter.

        Args:
            ctx: click.Context
            param: click.Param
            values: parameter value

        Returns:
            groceries.config.Config
        '''
        config = Config(values)
        for step in self.steps:
            if not config.get(step.key):
                if self.show_message:
                    self.show_message = False
                    click.echo('Part of the configuration is incomplete. '
                               'Please answer the following questions:')
                config = step(ctx, config)
        return config

class Step(object):

    key = None
    error = 'Invalid value provided'
    max_tries = 3

    def __call__(self, ctx, config, count=1):
        '''Execute a single step in the wizard.

        Args:
            ctx: click.Context
            config: groceries.config.Config
            count: number of tries

        Returns:
            groceries.config.Config
        '''
        try:
            config.set(self.key, self.value(config))
        except KeyboardInterrupt:
            ctx.abort()
        except:
            if count < self.max_tries:
                click.echo(self.error)
                count += 1
                return self(ctx, config, count)
            ctx.abort()
        config.write()
        return config

class Api(Step):

    key = 'api'
    error = 'Invalid URL provided'

    def value(self, config):
        '''Get the URL for the API.

        Args:
            config: groceries.config.Config

        Returns:
            String containing the URL.
        '''
        url = input('What is the URL of the API? ')
        r = requests.get('{0}{1}'.format(url, '/status'))
        if not r.status_code == 200:
            raise Exception()
        return url

class Token(Step):

    key = 'token'
    error = 'Invalid username and/or password provided.'

    def value(self, config):
        '''Get the token to use for authentication.

        Args:
            config: groceries.config.Config

        Returns:
            String containing the token.
        '''
        username = input('What is your username? ')
        password = getpass.getpass('And your password? ')
        r = requests.post('{0}{1}'.format(config.get('api'), '/login'),
                          data=json.dumps({'username': username,
                                           'password': password}),
                          headers={'Content-Type': 'application/json'})
        return r.json().get('token')


text:
define(function(require, exports, module) {
    var TauDocument = require("./tau-document");

    TauDocument.initialize();
    TauDocument.initializeMenus();
});


text:
<?php

namespace DefaultBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class DefaultBundle extends Bundle
{
}


text:
package com.springsource.greenhouse.profile;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import org.springframework.social.greenhouse.api.GreenhouseProfile;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;

import com.googlecode.androidannotations.annotations.App;
import com.googlecode.androidannotations.annotations.Background;
import com.googlecode.androidannotations.annotations.EActivity;
import com.googlecode.androidannotations.annotations.UiThread;
import com.googlecode.androidannotations.annotations.ViewById;
import com.springsource.greenhouse.AbstractGreenhouseActivity;
import com.springsource.greenhouse.MainApplication;
import com.springsource.greenhouse.R;

/**
 * @author Roy Clarkson
 */
@EActivity(R.layout.profile)
public class ProfileActivity extends AbstractGreenhouseActivity {

	protected static final String TAG = ProfileActivity.class.getSimpleName();

	private GreenhouseProfile profile;

	@App
	MainApplication application;

	@ViewById(R.id.profile_textview_member_name)
	TextView textViewMemberName;

	@ViewById(R.id.profile_imageview_picture)
	ImageView imageViewPicture;

	//***************************************
    // Activity methods
    //***************************************

	@Override
	public void onStart() {
		super.onStart();

		if (profile == null) {
			downloadProfile();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.profile_menu, menu);
	    return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
		    case R.id.profile_menu_refresh:
		        downloadProfile();
		        return true;
		    case R.id.profile_menu_sign_out:
		        signOut();
		        return true;
		    default:
		        return super.onOptionsItemSelected(item);
	    }
	}

	//***************************************
    // Private methods
    //***************************************
	private void refreshProfile(GreenhouseProfile profile) {
		if (profile == null) {
			return;
		}

		this.profile = profile;

		textViewMemberName.setText(profile.getDisplayName());
		downloadProfileImage(profile.getPictureUrl());
	}

	@Background
	void downloadProfileImage(String urlString) {
        Bitmap bitmap = null;
        try {
            URL url = new URL(urlString);
            URLConnection conn = url.openConnection();
            conn.connect();
            InputStream is = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            bitmap = BitmapFactory.decodeStream(bis);
            bis.close();
            is.close();
        } catch (IOException e) {
            Log.e(TAG, "Error retrieving profile image", e);
        } catch(Exception e) {
            Log.e(TAG, e.getLocalizedMessage(), e);
        }
        profileImageDownloaded(bitmap);
	}

	@UiThread
	void profileImageDownloaded(Bitmap result) {
        imageViewPicture.setImageBitmap(result);
	}

    private void downloadProfile() {
        showProgressDialog();
		downloadProfileInbackground();
	}

    @Background
    void downloadProfileInbackground() {
        try {
            GreenhouseProfile downloadedProfile = application.getPrimaryConnection().getApi().userOperations().getUserProfile();
            downloadProfileDone(downloadedProfile, null);
        } catch(Exception e) {
            Log.e(TAG, e.getLocalizedMessage(), e);
            downloadProfileDone(null, e);
        }
    }

    @UiThread
    void downloadProfileDone(GreenhouseProfile result, Exception exception)  {
        dismissProgressDialog();
        processException(exception);
        refreshProfile(result);
    }

}


text:
$(document).on('ajaxComplete ready', function () {

    // Initialize relationship pickers
    $('input[data-provides="anomaly.field_type.relationship"]:not([data-initialized])').each(function () {

        $(this).attr('data-initialized', '');

        var input = $(this);
        var field = input.data('field_name');
        var wrapper = input.closest('.form-group');
        var modal = $('#' + field + '-modal');

        modal.on('click', '[data-entry]', function (e) {

            e.preventDefault();

            wrapper.find('.selected').load(REQUEST_ROOT_PATH + '/streams/relationship-field_type/selected/' + $(this).data('key') + '?uploaded=' + $(this).data('entry'), function () {
                modal.modal('hide');
            });

            $('[name="' + field + '"]').val($(this).data('entry'));

            $(wrapper).find('[data-dismiss="relationship"]').removeClass('hidden');
        });

        $(wrapper).on('click', '[data-dismiss="relationship"]', function (e) {

            e.preventDefault();

            $('[name="' + field + '"]').val('');

            wrapper.find('.selected').html('');

            $(this).addClass('hidden');
        });
    });
});
;


text:
*   No changes.

## Rails 5.0.7.1 (November 27, 2018) ##

*   No changes.

## Rails 5.0.7 (March 29, 2018) ##

*   No changes.

## Rails 5.0.6 (September 07, 2017) ##

*   No changes.

## Rails 5.0.6.rc1 (August 24, 2017) ##

*   No changes.

## Rails 5.0.5 (July 31, 2017) ##

*   No changes.

## Rails 5.0.5.rc2 (July 25, 2017) ##

*   No changes.

## Rails 5.0.5.rc1 (July 19, 2017) ##

*   No changes.

## Rails 5.0.4 (June 19, 2017) ##

*   Fix regression in numericality validator when comparing Decimal and Float input
    values with more scale than the schema.

    *Bradley Priest*

## Rails 5.0.3 (May 12, 2017) ##

*   The original string assigned to a model attribute is no longer incorrectly
    frozen.

    Fixes #24185, #28718.

    *Matthew Draper*

*   Avoid converting integer as a string into float.

    *namusyaka*

## Rails 5.0.2 (March 01, 2017) ##

*   No changes.

## Rails 5.0.1 (December 21, 2016) ##

*   No changes.

## Rails 5.0.1.rc2 (December 10, 2016) ##

*   No changes.

## Rails 5.0.1.rc1 (December 01, 2016) ##

*   Fix `Type::Date#serialize` to cast a value to a date object properly.
    This casting fixes queries for finding records by date column.

    Fixes #25354.

    *Ryuta Kamizono*

## Rails 5.0.0 (June 30, 2016) ##

*   `Dirty`'s `*_changed?` methods now return an actual singleton, never `nil`, as in 4.2.
    Fixes #24220.

    *Sen-Zhang*

*   Ensure that instances of `ActiveModel::Errors` can be marshalled.
    Fixes #25165.

    *Sean Griffin*

*   Allow passing record being validated to the message proc to generate
    customized error messages for that object using I18n helper.

    *Prathamesh Sonpatki*

*   Validate multiple contexts on `valid?` and `invalid?` at once.

    Example:

        class Person
          include ActiveModel::Validations

          attr_reader :name, :title
          validates_presence_of :name, on: :create
          validates_presence_of :title, on: :update
        end

        person = Person.new
        person.valid?([:create, :update])    # => false
        person.errors.messages               # => {:name=>["can't be blank"], :title=>["can't be blank"]}

    *Dmitry Polushkin*

*   Add case_sensitive option for confirmation validator in models.

    *Akshat Sharma*

*   Ensure `method_missing` is called for methods passed to
    `ActiveModel::Serialization#serializable_hash` that don't exist.

    *Jay Elaraj*

*   Remove `ActiveModel::Serializers::Xml` from core.

    *Zachary Scott*

*   Add `ActiveModel::Dirty#[attr_name]_previously_changed?` and
    `ActiveModel::Dirty#[attr_name]_previous_change` to improve access
    to recorded changes after the model has been saved.

    It makes the dirty-attributes query methods consistent before and after
    saving.

    *Fernando Tapia Rico*

*   Deprecate the `:tokenizer` option for `validates_length_of`, in favor of
    plain Ruby.

    *Sean Griffin*

*   Deprecate `ActiveModel::Errors#add_on_empty` and `ActiveModel::Errors#add_on_blank`
    with no replacement.

    *Wojciech Wnętrzak*

*   Deprecate `ActiveModel::Errors#get`, `ActiveModel::Errors#set` and
    `ActiveModel::Errors#[]=` methods that have inconsistent behavior.

    *Wojciech Wnętrzak*

*   Allow symbol as values for `tokenize` of `LengthValidator`.

    *Kensuke Naito*

*   Assigning an unknown attribute key to an `ActiveModel` instance during initialization
    will now raise `ActiveModel::AttributeAssignment::UnknownAttributeError` instead of
    `NoMethodError`.

    Example:

        User.new(foo: 'some value')
        # => ActiveModel::AttributeAssignment::UnknownAttributeError: unknown attribute 'foo' for User.

    *Eugene Gilburg*

*   Extracted `ActiveRecord::AttributeAssignment` to `ActiveModel::AttributeAssignment`
    allowing to use it for any object as an includable module.

    Example:

        class Cat
          include ActiveModel::AttributeAssignment
          attr_accessor :name, :status
        end

        cat = Cat.new
        cat.assign_attributes(name: "Gorby", status: "yawning")
        cat.name   # => 'Gorby'
        cat.status # => 'yawning'
        cat.assign_attributes(status: "sleeping")
        cat.name   # => 'Gorby'
        cat.status # => 'sleeping'

    *Bogdan Gusiev*

*   Add `ActiveModel::Errors#details`

    To be able to return type of used validator, one can now call `details`
    on errors instance.

    Example:

        class User < ActiveRecord::Base
          validates :name, presence: true
        end

        user = User.new; user.valid?; user.errors.details
        => {name: [{error: :blank}]}

    *Wojciech Wnętrzak*

*   Change `validates_acceptance_of` to accept `true` by default besides `'1'`.

    The default for `validates_acceptance_of` is now `'1'` and `true`.
    In the past, only `"1"` was the default and you were required to pass
    `accept: true` separately.

    *mokhan*

*   Remove deprecated `ActiveModel::Dirty#reset_#{attribute}` and
    `ActiveModel::Dirty#reset_changes`.

    *Rafael Mendonça França*

*   Change the way in which callback chains can be halted.

    The preferred method to halt a callback chain from now on is to explicitly
    `throw(:abort)`.
    In the past, returning `false` in an Active Model `before_` callback had
    the side effect of halting the callback chain.
    This is not recommended anymore and, depending on the value of the
    `ActiveSupport.halt_callback_chains_on_return_false` option, will
    either not work at all or display a deprecation warning.

    *claudiob*

Please check [4-2-stable](https://github.com/rails/rails/blob/4-2-stable/activemodel/CHANGELOG.md) for previous changes.


text:
package org.springframework.boot.actuate.metrics.cache;

import java.util.Collections;

import com.github.benmanes.caffeine.cache.Caffeine;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.junit.Test;

import org.springframework.cache.caffeine.CaffeineCache;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Tests for {@link CacheMetricsRegistrar}.
 *
 * @author Stephane Nicoll
 */
public class CacheMetricsRegistrarTests {

	private final MeterRegistry meterRegistry = new SimpleMeterRegistry();

	@Test
	public void bindToSupportedCache() {
		CacheMetricsRegistrar registrar = new CacheMetricsRegistrar(this.meterRegistry,
				"root", Collections.singleton(new CaffeineCacheMeterBinderProvider()));
		assertThat(registrar.bindCacheToRegistry(
				new CaffeineCache("test", Caffeine.newBuilder().build()))).isTrue();
		assertThat(this.meterRegistry.find("root.requests").tags("name", "test").meter())
				.isPresent();
	}

	@Test
	public void bindToUnsupportedCache() {
		CacheMetricsRegistrar registrar = new CacheMetricsRegistrar(this.meterRegistry,
				"root", Collections.emptyList());
		assertThat(registrar.bindCacheToRegistry(
				new CaffeineCache("test", Caffeine.newBuilder().build()))).isFalse();
		assertThat(this.meterRegistry.find("root.requests").tags("name", "test").meter())
				.isNotPresent();
	}

}


text:
import { Component, ViewChild } from '@angular/core';
import NfRegistryService from 'services/nf-registry.service';
import NfRegistryApi from 'services/nf-registry.api';
import { MatDialogRef } from '@angular/material/dialog';
import { FdsSnackBarService } from '@nifi-fds/core';

/**
 * NfRegistryCreateBucket constructor.
 *
 * @param nfRegistryApi         The api service.
 * @param fdsSnackBarService    The FDS snack bar service module.
 * @param nfRegistryService     The nf-registry.service module.
 * @param matDialogRef          The angular material dialog ref.
 * @constructor
 */
function NfRegistryCreateBucket(nfRegistryApi, fdsSnackBarService, nfRegistryService, matDialogRef) {
    // Services
    this.snackBarService = fdsSnackBarService;
    this.nfRegistryService = nfRegistryService;
    this.nfRegistryApi = nfRegistryApi;
    this.dialogRef = matDialogRef;
    // local state
    this.keepDialogOpen = false;
    this.protocol = location.protocol;
}

NfRegistryCreateBucket.prototype = {
    constructor: NfRegistryCreateBucket,

    /**
     * Create a new bucket.
     *
     * @param newBucketName                 The newBucketName element.
     * @param newBucketDescription          The newBucketDescription element.
     * @param newBucketPublicReadCheckbox   The newBucketPublicReadCheckbox element.
     */
    createBucket: function (newBucketName, newBucketDescription, newBucketPublicReadCheckbox) {
        var self = this;
        this.nfRegistryApi.createBucket(newBucketName.value, newBucketDescription.value, newBucketPublicReadCheckbox.checked).subscribe(function (bucket) {
            if (!bucket.error) {
                self.nfRegistryService.buckets.push(bucket);
                self.nfRegistryService.filterBuckets();
                self.nfRegistryService.allBucketsSelected = false;
                if (self.keepDialogOpen !== true) {
                    self.dialogRef.close();
                }
                self.snackBarService.openCoaster({
                    title: 'Success',
                    message: 'Bucket has been added.',
                    verticalPosition: 'bottom',
                    horizontalPosition: 'right',
                    icon: 'fa fa-check-circle-o',
                    color: '#1EB475',
                    duration: 3000
                });
            } else {
                self.dialogRef.close();
            }
        });
    },

    /**
     * Cancel creation of a new bucket and close dialog.
     */
    cancel: function () {
        this.dialogRef.close();
    }
};

NfRegistryCreateBucket.annotations = [
    new Component({
        templateUrl: './nf-registry-create-bucket.html',
        queries: {
            newBucketName: new ViewChild('newBucketName'),
            newBucketDescription: new ViewChild('newBucketDescription')
        }
    })
];

NfRegistryCreateBucket.parameters = [
    NfRegistryApi,
    FdsSnackBarService,
    NfRegistryService,
    MatDialogRef
];

export default NfRegistryCreateBucket;


text:
package org.olat.portfolio.ui.artefacts.view.details;

import javax.servlet.http.HttpServletRequest;

import org.olat.core.CoreSpringFactory;
import org.olat.core.dispatcher.mapper.Mapper;
import org.olat.core.gui.UserRequest;
import org.olat.core.gui.components.Component;
import org.olat.core.gui.components.link.Link;
import org.olat.core.gui.components.link.LinkFactory;
import org.olat.core.gui.components.velocity.VelocityContainer;
import org.olat.core.gui.control.Controller;
import org.olat.core.gui.control.Event;
import org.olat.core.gui.control.WindowControl;
import org.olat.core.gui.control.controller.BasicController;
import org.olat.core.gui.control.generic.closablewrapper.CloseableCalloutWindowController;
import org.olat.core.gui.media.MediaResource;
import org.olat.core.util.Formatter;
import org.olat.core.util.filter.Filter;
import org.olat.core.util.filter.FilterFactory;
import org.olat.core.util.vfs.VFSContainer;
import org.olat.core.util.vfs.VFSItem;
import org.olat.core.util.vfs.VFSLeaf;
import org.olat.core.util.vfs.VFSMediaResource;
import org.olat.portfolio.manager.EPFrontendManager;
import org.olat.portfolio.model.artefacts.AbstractArtefact;
import org.olat.portfolio.ui.artefacts.collect.EPCreateTextArtefactStepForm00;

/**
 * Description:

 * Show the specific part of the EPTextArtefact
 *

 * Initial Date: 11 oct. 2010

 *
 * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com
 */
public class TextArtefactDetailsController extends BasicController {

	private final VelocityContainer vC;
	private final boolean readOnlyMode;
	private Link editBtn;
	private CloseableCalloutWindowController calloutCtrl;
	private EPCreateTextArtefactStepForm00 textEditCtrl;
	private final AbstractArtefact artefact;
	private final EPFrontendManager ePFMgr;

	public TextArtefactDetailsController(final UserRequest ureq, final WindowControl wControl, final AbstractArtefact artefact, final boolean readOnlyMode) {
		super(ureq, wControl);
		this.readOnlyMode = readOnlyMode;
		this.artefact = artefact;
		ePFMgr = (EPFrontendManager) CoreSpringFactory.getBean("epFrontendManager");
		vC = createVelocityContainer("textDetails");
		init();

		putInitialPanel(vC);
	}

	private void init() {
		final String artFulltextContent = ePFMgr.getArtefactFullTextContent(artefact);
		if (!readOnlyMode) {
			// prepare an edit link
			String fulltext = FilterFactory.getHtmlTagAndDescapingFilter().filter(artFulltextContent);
			fulltext = Formatter.truncate(fulltext, 50);
			editBtn = LinkFactory.createCustomLink("text.edit.link", "edit", fulltext, Link.NONTRANSLATED, vC, this);
			editBtn.setCustomEnabledLinkCSS("b_inline_editable b_ep_nolink");
		} else {
			// register a mapper to deliver uploaded media files
			final VFSContainer artefactFolder = ePFMgr.getArtefactContainer(artefact);
			final String mapperBase = registerMapper(new Mapper() {
				@SuppressWarnings("unused")
				@Override
				public MediaResource handle(final String relPath, final HttpServletRequest request) {
					final VFSItem currentItem = artefactFolder.resolve(relPath);
					final VFSMediaResource vmr = new VFSMediaResource((VFSLeaf) currentItem);
					return vmr;
				}
			});
			final Filter urlFilter = FilterFactory.getBaseURLToMediaRelativeURLFilter(mapperBase);
			final String wrappedText = urlFilter.filter(artFulltextContent);
			vC.contextPut("text", wrappedText);
		}
	}

	@Override
	@SuppressWarnings("unused")
	protected void event(final UserRequest ureq, final Component source, final Event event) {
		if (source == editBtn) {
			popupEditorCallout(ureq);
		}
	}

	@SuppressWarnings("unused")
	@Override
	protected void event(final UserRequest ureq, final Controller source, final Event event) {
		if (source == calloutCtrl && event.equals(CloseableCalloutWindowController.CLOSE_WINDOW_EVENT)) {
			removeAsListenerAndDispose(calloutCtrl);
			calloutCtrl = null;
		} else if (source == textEditCtrl && event == Event.DONE_EVENT) {
			// close callout, refresh artefact-details
			calloutCtrl.deactivate();
			removeAsListenerAndDispose(calloutCtrl);
			init();
		}
	}

	private void popupEditorCallout(final UserRequest ureq) {
		removeAsListenerAndDispose(textEditCtrl);
		textEditCtrl = new EPCreateTextArtefactStepForm00(ureq, getWindowControl(), artefact);
		listenTo(textEditCtrl);
		instantiateCalloutController(ureq, textEditCtrl.getInitialComponent(), editBtn);
	}

	private void instantiateCalloutController(final UserRequest ureq, final Component content, final Link button) {
		removeAsListenerAndDispose(calloutCtrl);
		final String title = translate("textartefact.edit.title");
		calloutCtrl = new CloseableCalloutWindowController(ureq, getWindowControl(), content, button, title, true, null);
		listenTo(calloutCtrl);
		calloutCtrl.activate();
	}

	@Override
	protected void doDispose() {
		// nothing
	}
}


text:
package main

import (
	"encoding/json"
	"flag"
	"fmt"
)

var (
	testMarshal   bool
	testUnmarshal bool
)

type Packet struct {
	Cmd  string      `json:"cmd"`
	Data interface{} `json:"data"`
}

type Control struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
}

type Message struct {
	Msg string `json:"msg"`
}

func testSerialization() {
	cp := &Packet{
		Cmd: "ctrl",
		Data: &Control{
			Code: 0xDEADBEEF,
			Msg:  "heartbeat",
		},
	}

	raw, err := json.Marshal(cp)
	if err != nil {
		panic(err)
	}

	fmt.Println(string(raw))

	mp := &Packet{
		Cmd: "msg",
		Data: &Message{
			Msg: "Echo",
		},
	}

	raw, err = json.Marshal(mp)
	if err != nil {
		panic(err)
	}

	fmt.Println(string(raw))
}

func testDeserialization() {
	var err error

	p := &Packet{}
	cpJson := `{"cmd":"ctrl","data":{"code":3735928559,"msg":"heartbeat"}}`
	err = json.Unmarshal([]byte(cpJson), p)
	if err != nil {
		panic(err)
	}
	printPacket(p)

	mpJson := `{"cmd":"msg","data":{"msg":"Echo"}}`
	err = json.Unmarshal([]byte(mpJson), p)
	if err != nil {
		panic(err)
	}
	printPacket(p)
}

func printPacket(packet *Packet) {
	data := packet.Data.(map[string]interface{})

	switch packet.Cmd {
	case "ctrl":
		code := int(data["code"].(float64)) // ???
		msg := data["msg"].(string)
		fmt.Printf("Control packet\ncode=%d\nmsg=%s\n", code, msg)
		break
	case "msg":
		msg := data["msg"].(string)
		fmt.Printf("Message packet\nmsg=%s\n", msg)
		break
	default:
		panic("unreachable")
	}
}

func main() {
	flag.BoolVar(&testMarshal, "marshal", false, "")
	flag.BoolVar(&testUnmarshal, "unmarshal", false, "")
	flag.Parse()

	if testMarshal {
		testSerialization()
	}

	if testUnmarshal {
		testDeserialization()
	}
}


text:
<!DOCTYPE html>

    <title>Application Title</title>
    <meta charset="utf-8">
    <meta http-equiv="Content-type" content="text/html;charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link href="/img/brand/favicon.ico" rel="shortcut icon" type="image/x-icon">

        <md-sidenav md-component-id="left" md-is-locked-open="$mdMedia('gt-sm')" class="md-whiteframe-z2 du-sidenav" tabindex="-1">

            <md-content ui-view="sidebar" role="navigation" class="flex" flex>
            </md-content>

        </md-sidenav>
        <md-content layout="column" id="ui-view-content-container" class="ui-view-content-container" flex>
            <md-toolbar id="site-content-toolbar" class="md-whiteframe-glow-z1 site-content-toolbar"><navigation></navigation></md-toolbar>
            <md-content layout="column" flex layout-padding id="content" ng-animate="view" ui-view="content"></md-content>
        </md-content>


text:
package io.redbarn;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.IOException;
import java.io.Reader;

import static io.redbarn.ResourceUtils.getResourceReader;

/**
 * Loads all scripts and prepares the ScriptEngine.
 *
 * @author Mike Atkisson
 * @since 0.1.0
 */
public class RedbarnScriptEngineManager extends ScriptEngineManager {

    public static final String SCRIPT_ENGINE_NAME = "nashorn";
    private static final Logger logger =
            LoggerFactory.getLogger(RedbarnScriptEngineManager.class);

    /**
     * Gets a JavaScript script engine preloaded with scripts needed for
     * template translation.
     *
     * @return A ScriptEngine instance.
     * @throws IOException Thrown if one of the preloaded script resources
     *                     could not be found.
     */
    public ScriptEngine getScriptEngine() throws IOException, ScriptException {
        ScriptEngine engine = getEngineByName(SCRIPT_ENGINE_NAME);
        try (Reader console = getResourceReader("scripts/io/redbarn/console.js")) {
            engine.eval(console);
        }
        return engine;
    }

}


text:
function AnimationHandle(animation, callback, mirrored){
	if(animation instanceof AnimationHandle){
		animation = animation.animation;
	}
	this.animation = animation;
	this.callback = callback === undefined ? null : callback;

	this.currentFrame = 0;
	this.time = 0;

	if(mirrored === undefined) mirrored = false;
	this.renderMirrored = mirrored;

	this.speed = 1;
	this.start = 0;
	this.end = 1;

	this.playTo = -1;

	this.loop = true;
	this.playing = false;
}

AnimationHandle.constructor = AnimationHandle;

AnimationHandle.prototype.clone = function() {
	var clone = new AnimationHandle(this.animation, this.callback, this.renderMirrored);
	clone.start = this.start;
	clone.end = this.end;
	clone.time = this.time;
	return clone;
};

AnimationHandle.prototype.update = function(dt) {
	if (!this.playing) {
		this.currentFrame = Math.floor(this.time * this.animation.framerate) % this.animation.nbrOfFrames;
		return;
	}

	var oldTime = this.time;
	this.time += this.speed * dt;
	var halfFrame = 0.5 / this.animation.framerate;

	var animationLength = this.animation.animationLength;

	if (this.loop) {
		if (this.speed > 0) {
			this.time = this.time >= animationLength * this.end ? this.start * animationLength : this.time;
		} else {
			this.time = this.time <= animationLength * this.start ? this.end * animationLength - halfFrame : this.time;
		}
	} else {
		var tempPlayTo;
		if (this.speed > 0) {
			tempPlayTo = this.playTo >= 0 ? this.playTo : this.end;
			if (this.time >= animationLength * tempPlayTo) {
				this.time = animationLength * tempPlayTo - halfFrame;
				this.playing = false;
			}
		} else {
			tempPlayTo = this.playTo >= 0 ? this.playTo : this.start;
			if (this.time <= animationLength * tempPlayTo) {
				this.time = animationLength * tempPlayTo + halfFrame;
				this.playing = false;
			}
		}
	}

	this.time = Math.max(0, this.time);

	this.currentFrame = Math.floor(this.time * this.animation.framerate) % this.animation.nbrOfFrames;

	if(this.callback !== null){
		var timeToCheck = this.playing ? this.time : (this.speed > 0 ? animationLength * this.end : this.animation.animationLength * this.start);
		var evts;
		if(oldTime < timeToCheck)
			evts = this.animation.getEvents(oldTime, timeToCheck);
		else
			evts = this.animation.getEventsSlow(oldTime, timeToCheck, animationLength * this.start, animationLength * this.end, dt);

		if(evts.length >= 2){
			this.time = this.animation.getTimeForNextEvent(oldTime, timeToCheck);
			evts = [evts[0]];
		}

		for (var e = 0; e < evts.length; e++) {
			this.callback(evts[e], this);
		}

		if (!this.playing) {
			this.callback("stopped", this);
		}
	}
};

AnimationHandle.prototype.draw = function(render, x, y, angle, alpha, tint) {
	var image = this.animation.frames[this.currentFrame];

	var baseX = this.renderMirrored ? x - (image.textureWidth - this.animation.pivotx) : x - this.animation.pivotx;
	render.drawImage(image, baseX, y - this.animation.pivoty, angle, false, alpha, tint, this.renderMirrored);
};

AnimationHandle.prototype.mirror = function() {
	this.renderMirrored = !this.renderMirrored;
};

AnimationHandle.prototype.play = function(loop) {
	this.playTo = -1;
	if(loop === undefined) loop = true;
	if (this.time >= this.end * this.animation.animationLength - 0.5 / this.animation.framerate)
		this.time = this.start * this.animation.animationLength;
	this.loop = loop;
	this.playing = true;
};

AnimationHandle.prototype.playToTime = function(t) {
	this.playTo = t;
	if (this.time >= this.playTo * this.animation.animationLength - 0.5 / this.animation.framerate)
		this.time = this.start * this.animation.animationLength;
	this.playing = true;
};

AnimationHandle.prototype.playToEvent = function(name) {
	for (var i = 0; i < this.animation.events.length; i++) {
		var e = this.animation.events[i];
		if(e.name == name){
			this.playToTime(e.time / this.animation.animationLength);
			break;
		}
	}
};

AnimationHandle.prototype.stop = function() {
	this.playing = false;
};

AnimationHandle.prototype.rewind = function() {
	this.time = this.start * this.animation.animationLength;
};

AnimationHandle.prototype.gotoTime = function(time) {
	this.time = time * this.animation.animationLength;
};

AnimationHandle.prototype.gotoEvent = function(evt) {
	for (var i = 0; i < this.animation.events.length; i++) {
		var e = this.animation.events[i];
		if(e.name == evt) {
			this.time = e.time;
			break;
		}
	}
};

AnimationHandle.prototype.gotoEnd = function() {
	var halfFrame = 0.5 / this.animation.framerate;
	this.time = (this.end - halfFrame) * this.animation.animationLength;
};

AnimationHandle.prototype.setRange = function(s, e) {
	this.start = s;
	this.end = e;

	var length = this.animation.animationLength;

	if(this.time < s * length) this.time = s * length;
	if(this.time > e * length) this.time = e * length;
};

AnimationHandle.prototype.setSpeed = function(speed) {
	this.speed = speed;
};

AnimationHandle.prototype.getLength = function() {
	return this.animation.animationLength * (this.end - this.start);
};

AnimationHandle.prototype.getCurrentPosition = function() {
	return this.time;
};

AnimationHandle.prototype.isStopped = function() {
	return !this.playing;
};

AnimationHandle.prototype.setCallback = function(callback) {
	this.callback = callback;
};

function Animation(anim, frames){
	copy(anim, this);

	/**
	 * The frames in the animation.
	 */
	this.frames = frames;
	/**
	 * How long the animation is in seconds.
	 */
	this.animationLength = frames.length / anim.framerate;
}

Animation.prototype.constructor = Animation;

/**
 * Return all events between the different points in time
 *
 * @returns [String]
 */
Animation.prototype.getEvents = function (from, to) {
	var events = [];
	for (var e = 0; e < this.events.length; e++) {
		var evt =  this.events[e];
		if (evt.time >= from && evt.time < to) {
			events.push(evt.name);
		}
	}

	return events;
};

Animation.prototype.getTimeForNextEvent = function(from, to){
	var first = -1;
	for (var e = 0; e < this.events.length; e++) {
		var evt =  this.events[e];
		if (evt.time > from && evt.time < to) {
			if(first != -1) return evt.time;
			first = evt.time;
		}
	}
	return first;
};

Animation.prototype.getEventsSlow = function (from, to, start, end, dt) {
	var events = [];
	var e, evt;
	for (e = 0; e < this.events.length; e++) {
		evt =  this.events[e];
		if (evt.time >= from && evt.time < end) {
			events.push(evt.name);
		}
	}

	for (e = 0; e < this.events.length; e++) {
		evt =  this.events[e];
		if (evt.time >= start && evt.time < to) {
			events.push(evt.name);
		}
	}

	return events;
};


text:
def double(z):
    """ this is where you put an optional docstring that explains what the function does. for example,
    this function multiplies its input by 2"""
    return z * 2

def apply_to_one(f):
    """ calls the function f with 1 as its argument"""
    return f(1)

my_double = double
x = apply_to_one(my_double)
y = apply_to_one(lambda z: z + 4)
another_double_lambda = lambda z: 2 * z

def another_double(z):
    return 2 * z

def my_print(message="my default message"):
    print message

my_print("hello")
my_print()

def subtract(a=0, b=0):
    """
    """
    return a - b

subtract(10, 5)
subtract(0, 5)
subtract(b=5)


text:
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class AddRoleIdUsersTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::table('users', function(Blueprint $table) {
			$table->integer('role_id')->after('user_id');
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::table('users', function(Blueprint $table) {
			$table->dropColumn('role_id');
		});
	}

}


text:
package com.clescot.webappender.formatter;

public interface BodyFormatter extends Formatter {
}


text:
title: FluentImportDeclaration - fluentast-core
---

[fluentast-core](../../index.html) / [at.hschroedl.fluentast.ast](../index.html) / [FluentImportDeclaration](.)

# FluentImportDeclaration

`class FluentImportDeclaration : `[`FluentASTNode`](../-fluent-a-s-t-node/index.html) [(source)](https://github.com/hschroedl/FluentAST/tree/master/core/src/main/kotlin//at.hschroedl.fluentast/ast/ASTNode.kt#L74)

### Functions

| [build](build.html) | `fun build(ast: `[`AST`](https://help.eclipse.org/neon/topic/org.eclipse.jdt.doc.isv/reference/api/org/eclipse/jdt/core/dom/AST.html)`): `[`ASTNode`](https://help.eclipse.org/neon/topic/org.eclipse.jdt.doc.isv/reference/api/org/eclipse/jdt/core/dom/ASTNode.html) |