text:
#ifndef PLATFORM_H
#define PLATFORM_H
/* -*-C++-*-
 *****************************************************************************
 *
 * File:         Platform.h
 * Description:  Platform, operating system, and compiler-dependent settings
 *
 * Created:      9/8/95
 * Modified:	 08/08/2006
 * Language:     C (works with both C and C++ compilers)
 *
 *
 *****************************************************************************
 */
#define __STDC_LIMIT_MACROS
#define __STDC_FORMAT_MACROS

/*
// On Linux, either NA_BIG_ENDIAN or NA_LITTLE_ENDIAN may have already
// been set because some other target may have been defined.  The following
// should set it correctly on Linux.
*/
#include <endian.h>
#if __BYTE_ORDER == __LITTLE_ENDIAN
#undef NA_BIG_ENDIAN
#define NA_LITTLE_ENDIAN
#else
#undef NA_LITTLE_ENDIAN
#define NA_BIG_ENDIAN
#endif

/* -----------------------------------------------------------------------  */
/* Set the flavor of Guardian IPC that is used                              */
/* -----------------------------------------------------------------------  */
#define NA_GUARDIAN_IPC

/* ----------------------------------------------------------------------- */
/* MSVC perform template instantiation at compile time,                    */
/* so make sure they see the template implementation files                 */
/* ----------------------------------------------------------------------- */
#define NA_COMPILE_INSTANTIATE

#define NA_MAX_PATH  PATH_MAX

/* For declare thread private variables (have to be POD types) */
#define THREAD_P __thread

namespace std {}
using namespace std;

/* For process thread id, it is long on Linux currently */
typedef long ThreadId;

/*
 ---------------------------------------------------------------------
 Used where variable size matters
 ---------------------------------------------------------------------
*/
typedef char            Int8;
typedef unsigned char   UInt8;
typedef unsigned char   UChar;
typedef short           Int16;
typedef unsigned short  UInt16;

typedef int             Int32;
typedef unsigned int    UInt32;

typedef float           Float32;
typedef double          Float64;

typedef long Int64;
typedef unsigned long UInt64;

/* Linux with the gcc compiler */
typedef int TInt32;
typedef long long int TInt64;

/*
 format strings
*/
#define PFLL  "%ld"
#define PFLLX "%lx"
#define PF64  "%ld"
#define PF64X "%lx"
#define PFSZ  "%lu"
#define PFSZX "%lx"

/*
 additional format strings.
 PFV64 and PFLV64 for variable width field and left pad 0s
 PFP64 added for variable precision.
*/
#define PFV64  "%*ld"
#define PFLV64  "%0*ld"
#define PFP64  "%.*ld"

/* Lng32 to replace "long" or "signed long" */
/* and some will remain Int32 and others would become Int64 when done */
typedef int             Lng32;

/* ULng32 to replace "unsigned long" or "unsigned long int" */
/* and some will remain UInt32 and others would become UInt64 when done */
typedef unsigned int    ULng32;

/* These types are used for variables that must store integers sometime */
/* and pointers other time. Could have given a better name */
typedef  long Long;
typedef  unsigned long ULong;

#endif /* PLATFORM_H  */


text:
Team

Line manager

  {% if profile.data.line_manager is defined %}

  {% else %}

-- N/A --

  {% endif %}

Team members

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace ShoppingCart;

use ShoppingCart\Service\ShoppingCartService;

use Zend\Session\Container as SessionContainer;

return array(
    /*'doctrine' => array(
        'driver' => array(
            'orm_default' => array(
                'drivers' => array(
                    'Category' => 'annotation_driver'
                )
            ),
            'annotation_driver' => array(
                'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver',
                'cache' => 'array',
                'paths' => array(
                    __DIR__ . '/../src/ShoppingCart/Model'
                )
            )
        )
    ),*/

    'controllers' => array(
        'invokables' => array(
            'ShoppingCart\Controller\ShoppingCart' => 'ShoppingCart\Controller\ShoppingCartController'
        ),
        'factories' => [
            'ShoppingCart\Controller\ShoppingCart' => 'ShoppingCart\Controller\ShoppingCartControllerFactory'
        ]
    ),

    'service_manager' => [
        'factories' => [
            'ShoppingCartService' => function ($sm) {
                $catalogService = $sm->get('CatalogService');

                $sessionContainer = new SessionContainer('cart');

                $service = new ShoppingCartService($sessionContainer, $catalogService);

                return $service;
            }
        ]
    ],

    'router' => array(
        'routes' => array(
            'cart' => array(
                'type'    => 'segment',
                'options' => array(
                    'route'    => '/cart[/:action][/:id]',
                    'constraints' => array(
                        'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                        'id'     => '[0-9]+',
                    ),
                    'defaults' => array(
                        'controller' => 'ShoppingCart\Controller\ShoppingCart',
                        'action'     => 'view',
                    ),
                ),
            ),
        ),
    ),

    'view_manager' => array(
        'template_path_stack' => array(
            'cart' => __DIR__ . '/../view',
        ),
    ),
);


text:
<?php
namespace TypiCMS\Modules\Menus\Providers;

use Lang;
use View;
use Config;
use Illuminate\Support\ServiceProvider;
use Illuminate\Foundation\Application;

// Model
use TypiCMS\Modules\Menus\Models\Menu;

// Repo
use TypiCMS\Modules\Menus\Repositories\EloquentMenu;

// Cache
use TypiCMS\Modules\Menus\Repositories\CacheDecorator;
use TypiCMS\Services\Cache\LaravelCache;

// Form
use TypiCMS\Modules\Menus\Services\Form\MenuForm;
use TypiCMS\Modules\Menus\Services\Form\MenuFormLaravelValidator;

class ModuleProvider extends ServiceProvider
{

    public function boot()
    {
        // Bring in the routes
        require __DIR__ . '/../routes.php';

        // Add dirs
        View::addLocation(__DIR__ . '/../Views');
        Lang::addNamespace('menus', __DIR__ . '/../lang');
        Config::addNamespace('menus', __DIR__ . '/../config');
    }

    public function register()
    {

        $app = $this->app;

        /**
         * Sidebar view composer
         */
        $app->view->composer('admin._sidebar', 'TypiCMS\Modules\Menus\Composers\SidebarViewComposer');

        $app->bind('TypiCMS\Modules\Menus\Repositories\MenuInterface', function (Application $app) {
            $repository = new EloquentMenu(new Menu);
            if (! Config::get('app.cache')) {
                return $repository;
            }
            $laravelCache = new LaravelCache($app['cache'], ['menus', 'menulinks', 'pages'], 10);

            return new CacheDecorator($repository, $laravelCache);
        });

        $app->bind('TypiCMS\Modules\Menus\Services\Form\MenuForm', function (Application $app) {
            return new MenuForm(
                new MenuFormLaravelValidator($app['validator']),
                $app->make('TypiCMS\Modules\Menus\Repositories\MenuInterface')
            );
        });

        /*
        |--------------------------------------------------------------------------
        | Get all menus.
        |--------------------------------------------------------------------------|
        */
        $this->app['TypiCMS.menus'] = $this->app->share(function (Application $app) {
            return $app->make('TypiCMS\Modules\Menus\Repositories\MenuInterface')->getAllMenus();
        });

        $app->before(function ($request, $response) {
            require __DIR__ . '/../breadcrumbs.php';
        });

    }
}


text:
package uaa

import (
	"fmt"
	"net"
	"net/url"

	bosherr "github.com/cloudfoundry/bosh-utils/errors"
	boshhttp "github.com/cloudfoundry/bosh-utils/httpclient"
	boshlog "github.com/cloudfoundry/bosh-utils/logger"
)

type Factory struct {
	logTag string
	logger boshlog.Logger
}

func NewFactory(logger boshlog.Logger) Factory {
	return Factory{
		logTag: "uaa.Factory",
		logger: logger,
	}
}

func (f Factory) New(config Config) (UAA, error) {
	err := config.Validate()
	if err != nil {
		return UAAImpl{}, bosherr.WrapErrorf(
			err, "Validating UAA connection config")
	}

	client, err := f.httpClient(config)
	if err != nil {
		return UAAImpl{}, err
	}

	return UAAImpl{client: client}, nil
}

func (f Factory) httpClient(config Config) (Client, error) {
	certPool, err := config.CACertPool()
	if err != nil {
		return Client{}, err
	}

	if certPool == nil {
		f.logger.Debug(f.logTag, "Using default root CAs")
	} else {
		f.logger.Debug(f.logTag, "Using custom root CAs")
	}

	rawClient := boshhttp.CreateDefaultClient(certPool)

	httpClient := boshhttp.NewHTTPClient(rawClient, f.logger)

	endpoint := url.URL{
		Scheme: "https",
		Host:   net.JoinHostPort(config.Host, fmt.Sprintf("%d", config.Port)),
		Path:   config.Path,
	}

	return NewClient(endpoint.String(), config.Client, config.ClientSecret, httpClient, f.logger), nil
}


text:
try:
    from unittest import mock  # noqa: F401
except ImportError:
    from mock import mock  # noqa: F401

def echo_args(*args):
    return args


text:
import { IRole } from '../../models/IRole';

export interface IServerHeaderProps {
    serverName: string;
    numberOfUsers?: string;
    roles: Array<IRole>;
}


text:
package org.keycloak.testsuite.rule;

import org.keycloak.adapters.spi.AuthenticationError;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Marek Posolda
 */
public class ErrorServlet extends HttpServlet {
    public static AuthenticationError authError;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        authError = (AuthenticationError)req.getAttribute(AuthenticationError.class.getName());

        Integer statusCode = (Integer) req.getAttribute("javax.servlet.error.status_code");

        resp.setContentType("text/html");
        PrintWriter pw = resp.getWriter();
        pw.printf("<title>%s</title>", "Error Page");
        pw.print("
There was an error
");
        if (statusCode != null)
            pw.print("
HTTP status code: " + statusCode);
        if (authError != null)
            pw.print("
Error info: " + authError.toString());
        pw.print("");
        pw.flush();

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}


text:
var multer = require('multer'),
  storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, 'uploads/images/');
    },
    filename: function (req, file, cb) {
      cb(null, file.fieldname + '-' + Date.now());
    }
  }),

  filter = (req, file, cb) => {
    if (['image/gif', 'image/jpeg'].indexOf(file.mimetype) !== -1) {
      return cb(null, true);
    }
    cb(req.res.status(415).json({
      success: false,
      message: 'Invalid file type. Only \'jpeg\' and \'gif\' Images are allowed'
    }));
  },

  limits = {
    fileSize: 10000000
  },

  upload = multer({
    storage: storage,
    fileFilter: filter,
    limits: limits
  });

module.exports = upload;


text:
package uk.ac.ebi.subs.api.controllers;

import org.springframework.data.rest.webmvc.BasePathAwareController;
import org.springframework.data.rest.webmvc.support.RepositoryEntityLinks;
import org.springframework.hateoas.Resource;
import org.springframework.hateoas.ResourceAssembler;
import org.springframework.hateoas.Resources;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import uk.ac.ebi.subs.api.services.ValidationResultService;
import uk.ac.ebi.subs.data.status.StatusDescription;
import uk.ac.ebi.subs.repository.model.Submission;
import uk.ac.ebi.subs.repository.repos.SubmissionRepository;

import java.util.*;
import java.util.stream.Collectors;

import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;

/**
 * Created by karoly on 13/07/2017.
 */
@RestController
@BasePathAwareController
@RequestMapping("/submissions/{submissionId}")
public class SubmissionStatusController {

    private Map<String, StatusDescription> submissionStatusDescriptionMap;
    private SubmissionRepository submissionRepository;
    private ValidationResultService validationResultService;
    private ResourceAssembler<StatusDescription, Resource<StatusDescription>> submissionStatusResourceAssembler;
    private RepositoryEntityLinks repositoryEntityLinks;

    public SubmissionStatusController(Map<String, StatusDescription> submissionStatusDescriptionMap, SubmissionRepository submissionRepository, ValidationResultService validationResultService, ResourceAssembler<StatusDescription, Resource<StatusDescription>> submissionStatusResourceAssembler, RepositoryEntityLinks repositoryEntityLinks) {
        this.submissionStatusDescriptionMap = submissionStatusDescriptionMap;
        this.submissionRepository = submissionRepository;
        this.validationResultService = validationResultService;
        this.submissionStatusResourceAssembler = submissionStatusResourceAssembler;
        this.repositoryEntityLinks = repositoryEntityLinks;
    }

    @RequestMapping("/availableSubmissionStatuses")
    public Resources<Resource<StatusDescription>> availableSubmissionStatuses(@PathVariable String submissionId) {
        Submission currentSubmission = submissionRepository.findOne(submissionId);

        Collection<String> statusNames;

        if (validationResultService.isValidationFinishedAndPassed(currentSubmission.getSubmissionStatus().getId())) {
            StatusDescription statusDescription = submissionStatusDescriptionMap.get(currentSubmission.getSubmissionStatus().getStatus());

            statusNames = statusDescription.getUserTransitions();
        } else {
            statusNames = Collections.emptySet();
        }

        List<Resource<StatusDescription>> statusResources = statusNames
                .stream()
                .map(statusName -> submissionStatusDescriptionMap.get(statusName))
                .filter(Objects::nonNull)
                .map(statusDescription -> submissionStatusResourceAssembler.toResource(statusDescription))
                .collect(Collectors.toList());

        Resources<Resource<StatusDescription>> resources = new Resources<>(statusResources);

        resources.add(
            linkTo(
                methodOn(this.getClass())
                    .availableSubmissionStatuses(submissionId)
            ).withSelfRel()
        );

        resources.add(
            repositoryEntityLinks.linkToSingleResource(Submission.class,submissionId)
        );

        return resources;
    }
}


text:
package com.thoughtworks.go.domain;

import com.thoughtworks.go.config.EnvironmentVariableConfig;
import com.thoughtworks.go.config.EnvironmentVariablesConfig;
import com.thoughtworks.go.security.GoCipher;
import com.thoughtworks.go.util.command.EnvironmentVariableContext;
import org.junit.Test;

import java.util.Arrays;

import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.*;

public class EnvironmentVariablesTest {

    @Test
    public void add_shouldAddEnvironmentVariable() {
        final EnvironmentVariables environmentVariables = new EnvironmentVariables();
        assertThat(environmentVariables, hasSize(0));

        environmentVariables.add("foo", "bar");

        assertThat(environmentVariables, hasSize(1));
        assertThat(environmentVariables, contains(new EnvironmentVariable("foo", "bar")));
    }

    @Test
    public void toEnvironmentVariables_shouldConvertEnvironmentVariablesConfigToEnvironmentVariable() {
        final EnvironmentVariablesConfig environmentVariableConfigs = new EnvironmentVariablesConfig(Arrays.asList(
                new EnvironmentVariableConfig("foo", "bar"),
                new EnvironmentVariableConfig(new GoCipher(), "baz", "car", true)
        ));

        final EnvironmentVariables environmentVariables = EnvironmentVariables.toEnvironmentVariables(environmentVariableConfigs);

        assertThat(environmentVariables, containsInAnyOrder(
                new EnvironmentVariable("foo", "bar", false),
                new EnvironmentVariable("baz", "car", true)
        ));
    }

    @Test
    public void addTo_shouldAddEnvironmentVariablesToEnvironmentVariableContext() {
        final EnvironmentVariableContext environmentVariableContext = mock(EnvironmentVariableContext.class);
        final EnvironmentVariables environmentVariables = new EnvironmentVariables(
                new EnvironmentVariable("foo", "bar"),
                new EnvironmentVariable("baz", "car", true)
        );

        environmentVariables.addTo(environmentVariableContext);

        verify(environmentVariableContext, times(1)).setProperty("foo", "bar", false);
        verify(environmentVariableContext, times(1)).setProperty("baz", "car", true);
    }

    @Test
    public void addToIfExists_shouldAddEnvironmentVariableToEnvironmentVariableContext() {
        final EnvironmentVariableContext environmentVariableContext = mock(EnvironmentVariableContext.class);
        final EnvironmentVariables environmentVariables = new EnvironmentVariables(
                new EnvironmentVariable("foo", "bar"),
                new EnvironmentVariable("baz", "car", true)
        );

        when(environmentVariableContext.hasProperty("foo")).thenReturn(false);
        when(environmentVariableContext.hasProperty("baz")).thenReturn(true);

        environmentVariables.addToIfExists(environmentVariableContext);

        verify(environmentVariableContext, times(0)).setProperty("foo", "bar", false);
        verify(environmentVariableContext, times(1)).setProperty("baz", "car", true);
    }

    @Test
    public void shouldGetOnlyInsecureValues() {
        EnvironmentVariables variables = new EnvironmentVariables(
                new EnvironmentVariable("key1", "value1", true),
                new EnvironmentVariable("key2", "value2")
        );

        assertThat(variables.getInsecureEnvironmentVariableOrDefault("key1", "def1"), is("def1"));
        assertThat(variables.getInsecureEnvironmentVariableOrDefault("key2", null), is("value2"));
        assertThat(variables.getInsecureEnvironmentVariableOrDefault("key3", null), is(nullValue()));
    }

    @Test
    public void shouldOverrideWithProvidedOverrideValues() {
        EnvironmentVariables variables = new EnvironmentVariables(
                new EnvironmentVariable("key1", "value1"),
                new EnvironmentVariable("key2", "value2")
        );

        EnvironmentVariables variablesForOverride = new EnvironmentVariables(
                new EnvironmentVariable("key2", "value2-new")
        );

        variables.overrideWith(variablesForOverride);

        assertThat(variables.getInsecureEnvironmentVariableOrDefault("key1", null), is("value1"));
        assertThat(variables.getInsecureEnvironmentVariableOrDefault("key2", null), is("value2-new"));
        assertThat(variables.getInsecureEnvironmentVariableOrDefault("key3", null), is(nullValue()));
    }
}


text:
#include "SlopeAnalysisMap.h"

#include <QDebug>
#include <QtCore/qmath.h>

SlopeAnalysisMap::SlopeAnalysisMap(ElevationDataMap *elevationDataMap, QSettings *settings, QObject *parent) :
    AnalysisMap(elevationDataMap,settings,parent)
{
    // Init
    _name = "Slope Analysis";
    _elevationDataMap = elevationDataMap;
}

double SlopeAnalysisMap::calculateScoreForPixel(int x, int y) {
    // Get slope in degrees
    return mapSlopeToScore(calculateSlopeForPoint(x,y));
};

double SlopeAnalysisMap::calculateSlopeForPoint(int x, int y) {
    // Calculate the height differences dHx & dHy for this point
    // TODO: handle coordinate change??
    double height_y2 = _elevationDataMap->getElevationAtPoint(x,y+1);
    double height_y1 = _elevationDataMap->getElevationAtPoint(x,y-1);
    double height_x2 = _elevationDataMap->getElevationAtPoint(x+1,y);
    double height_x1 = _elevationDataMap->getElevationAtPoint(x-1,y);

    double dHy = height_y2 - height_y1;
    double dHx = height_x2 - height_x1;

    // Slopes (note resX is dependent on y value)
    double gradientY = dHy/(2*_elevationDataMap->getYResolutionAtPixel());
    double gradientX = dHx/(2*_elevationDataMap->getXResolutionAtPixel(y));

    // Find the angle of the scalar of the gradient (radians 0 to 1/2PI)
    double gradient = qAtan( qSqrt(gradientX*gradientX + gradientY*gradientY));
    // Convert angle to degrees
    double slope = gradient*180.0/M_PI;

    return slope;

}

double SlopeAnalysisMap::mapSlopeToScore(double slope) {
    // Linear analysis
    return qPow((-1.0/90.0*slope+1.0),6.0);
    //return (-100/90*slope+100)/100;
    //return qPow((-1/90*slope+1),16);
}


text:
package org.apache.mesos.chronos.scheduler.config

import java.lang.Thread.UncaughtExceptionHandler
import java.util.concurrent.ScheduledThreadPoolExecutor
import java.util.logging.{Level, Logger}

import akka.actor.{ActorRef, ActorSystem, Props}
import akka.util.Timeout
import org.apache.mesos.chronos.notification.{MailClient, RavenClient, SlackClient}
import org.apache.mesos.chronos.scheduler.graph.JobGraph
import org.apache.mesos.chronos.scheduler.jobs.{JobMetrics, JobScheduler, JobStats, TaskManager}
import org.apache.mesos.chronos.scheduler.mesos.{MesosDriverFactory, MesosJobFramework, MesosTaskBuilder}
import org.apache.mesos.chronos.scheduler.state.PersistenceStore
import com.google.common.util.concurrent.{ListeningScheduledExecutorService, MoreExecutors, ThreadFactoryBuilder}
import com.google.inject.{AbstractModule, Inject, Provides, Singleton}
import mesosphere.mesos.util.FrameworkIdUtil
import mesosphere.util.BackToTheFuture
import org.apache.curator.framework.CuratorFramework
import org.apache.curator.framework.recipes.leader.LeaderLatch
import org.apache.mesos.Protos.FrameworkInfo
import org.apache.mesos.Scheduler
import org.joda.time.Seconds

import scala.concurrent.duration._
import scala.language.postfixOps

/**
 * Guice glue code of application logic components.
 * @author Florian Leibert (flo@leibert.de)
 */
class MainModule(val config: SchedulerConfiguration) extends AbstractModule {
  private[this] val log = Logger.getLogger(getClass.getName)

  override def configure() {
    log.info("Wiring up the application")

    bind(classOf[SchedulerConfiguration]).toInstance(config)
    bind(classOf[Scheduler]).to(classOf[MesosJobFramework]).asEagerSingleton()
    bind(classOf[TaskManager]).asEagerSingleton()
    bind(classOf[MesosTaskBuilder]).asEagerSingleton()

    //TODO(FL): Only bind this if config.dependentJobs is turned on.
    bind(classOf[JobGraph]).asEagerSingleton()
  }

  @Inject
  @Singleton
  @Provides
  def provideFrameworkInfo(frameworkIdUtil: FrameworkIdUtil): FrameworkInfo = {
    import mesosphere.util.BackToTheFuture.Implicits.defaultTimeout

import scala.concurrent.ExecutionContext.Implicits.global

    val frameworkInfo = FrameworkInfo.newBuilder()
      .setName(config.mesosFrameworkName())
      .setCheckpoint(config.mesosCheckpoint())
      .setRole(config.mesosRole())
      .setFailoverTimeout(config.failoverTimeoutSeconds())
      .setUser(config.user())
    frameworkIdUtil.setIdIfExists(frameworkInfo)
    frameworkInfo.build()
  }

  @Singleton
  @Provides
  def provideMesosSchedulerDriverFactory(mesosScheduler: Scheduler, frameworkInfo: FrameworkInfo): MesosDriverFactory =
    new MesosDriverFactory(mesosScheduler, frameworkInfo, config)

  @Singleton
  @Provides
  def provideTaskScheduler(
                            taskManager: TaskManager,
                            dependencyScheduler: JobGraph,
                            persistenceStore: PersistenceStore,
                            mesosSchedulerDriver: MesosDriverFactory,
                            curator: CuratorFramework,
                            leaderLatch: LeaderLatch,
                            notificationClients: List[ActorRef],
                            metrics: JobMetrics,
                            stats: JobStats): JobScheduler = {
    new JobScheduler(
      scheduleHorizon = Seconds.seconds(config.scheduleHorizonSeconds()).toPeriod,
      taskManager = taskManager,
      jobGraph = dependencyScheduler,
      persistenceStore = persistenceStore,
      mesosDriver = mesosSchedulerDriver,
      curator = curator,
      leaderLatch = leaderLatch,
      leaderPath = config.zooKeeperCandidatePath,
      notificationClients = notificationClients,
      failureRetryDelay = config.failureRetryDelayMs(),
      disableAfterFailures = config.disableAfterFailures(),
      jobMetrics = metrics,
      jobStats = stats,
      clusterName = config.clusterName.get)
  }

  @Singleton
  @Provides
  def provideNotificationClients(): List[ActorRef] = {
    implicit val system = ActorSystem("chronos-actors")
    implicit val timeout = Timeout(36500 days)

    def create(clazz: Class[_], args: scala.Any*): ActorRef = {
      log.warning("Starting [%s] notification client.".format(clazz))
      system.actorOf(Props(clazz, args: _*))
    }

    List(
      for {
        server <- config.mailServer.get if !server.isEmpty && server.contains(":")
        from <- config.mailFrom.get if !from.isEmpty
      } yield {
        create(classOf[MailClient], server, from, config.mailUser.get, config.mailPassword.get, config.mailSslOn())
      },
      for {
        ravenDsn <- config.ravenDsn.get if !ravenDsn.isEmpty
      } yield {
        create(classOf[RavenClient], ravenDsn)
      },
      for {
        webhookUrl <- config.slackWebhookUrl.get if !config.slackWebhookUrl.isEmpty
        token <- config.slackToken.get if !config.slackToken.isEmpty
        channel <- config.slackChannel.get if !config.slackChannel.isEmpty
      } yield {
        create(classOf[SlackClient], webhookUrl, token, channel)
      }
    ).flatten
  }

  @Singleton
  @Provides
  def provideListeningExecutorService(): ListeningScheduledExecutorService = {
    val uncaughtExceptionHandler = new UncaughtExceptionHandler {
      def uncaughtException(thread: Thread, t: Throwable) {
        log.log(Level.SEVERE, "Error occurred in ListeningExecutorService, catching in thread", t)
      }
    }
    MoreExecutors.listeningDecorator(new ScheduledThreadPoolExecutor(5,
      new ThreadFactoryBuilder().setNameFormat("task_executor_thread-%d")
        .setUncaughtExceptionHandler(uncaughtExceptionHandler).build()))
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">GridNote</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="first_question">今天过得怎么样?</string>
    <string name="second_question">今天的作息正常吗?</string>
    <string name="third_question">今天我吃了什么?</string>
    <string name="forth_question">今天发生了什么新鲜事?</string>
    <string name="fifth_question">我今天完成了什么?</string>
    <string name="sixth_question">今天读了什么书?</string>
    <string name="weather">天气</string>
	<string-array name="weather">
	    <item name="sunny">晴朗</item>
        <item name="cloudy">多云</item>
        <item name="overcast">阴天</item>
        <item name="rain">降雨</item>
        <item name="snow">降雪</item>
        <item name="hail">冰雹</item>
        <item name="smoky">烟雾</item>
        <item name="sandstorm">沙尘暴</item>
	</string-array>
</resources>


text:
// @flow

import T from 'terrific';
import $ from 'jquery';

/**
 * Basic Module description.
 */
T.Module.<%= Name %> = T.createModule({
	_selectors: {},
	_eventNames: {},
	_stateClasses: {},

	start(resolve: () => void) {
		// this.$ctx will contain a jQuery reference to the root element in the DOM.
		resolve();
	},

	sync() {
		// Called when start() method of all registered modules was called.
	},
});


text:
<?php
namespace MyApp\ApBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Entity
 */
class Note
{
    /**
     * @ORM\GeneratedValue
     * @ORM\Id
     * @ORM\Column(type="integer")
     */
    public $id;

     /**
     * @ORM\Column(type="string",length=255)
     */
    public $type;

     /**
     * @ORM\Column(type="string",length=255)
     */
    public $note;

     /**
     * @ORM\ManyToOne(targetEntity="Client", inversedBy="note", cascade={"persist"})
     * @ORM\JoinColumn(name="client_id", referencedColumnName="id")
     */
    public $client;

     /**
     * @ORM\Column(type="datetime")
     */
    protected $created;

    /**
     * @ORM\Column(type="datetime")
     */
    protected $updated;

    public function __construct()
    {
        $this->setCreated(new \DateTime());
        $this->setUpdated(new \DateTime());
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set type
     *
     * @param string $type
     */
    public function setType($type)
    {
        $this->type = $type;
    }

    /**
     * Get type
     *
     * @return string
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * Set note
     *
     * @param string $note
     */
    public function setNote($note)
    {
        $this->note = $note;
    }

    /**
     * Get note
     *
     * @return string
     */
    public function getNote()
    {
        return $this->note;
    }

    /**
     * Set client
     *
     * @param MyApp\ApBundle\Entity\Client $client
     */
    public function setClient(\MyApp\ApBundle\Entity\Client $client)
    {
        $this->client = $client;
    }

    /**
     * Get client
     *
     * @return MyApp\ApBundle\Entity\Client
     */
    public function getClient()
    {
        return $this->client;
    }

    /**
     * Set created
     *
     * @param datetime $created
     */
    public function setCreated($created)
    {
        $this->created = $created;
    }

    /**
     * Get created
     *
     * @return datetime
     */
    public function getCreated()
    {
        return $this->created;
    }

    /**
     * Set updated
     *
     * @param datetime $updated
     */
    public function setUpdated($updated)
    {
        $this->updated = $updated;
    }

    /**
     * Get updated
     *
     * @return datetime
     */
    public function getUpdated()
    {
        return $this->updated;
    }
}


text:
package release

// ByVersion implements sort.Interface for the []Releaser based Version field.
type ByVersion []Releaser

func (a ByVersion) Len() int {
	return len(a)
}

func (a ByVersion) Swap(i, j int) {
	a[i], a[j] = a[j], a[i]
}

func (a ByVersion) Less(i, j int) bool {
	return a[i].Version().LessThan(a[j].Version())
}


text:
import os
import unittest

import numpy as np
import tensorlayer as tl
from tests.utils import CustomTestCase

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'

class Test_Leaky_ReLUs(CustomTestCase):

    @classmethod
    def setUpClass(cls):
        cls.alpha = 0.2

        cls.vmin = 0
        cls.vmax = 10

    @classmethod
    def tearDownClass(cls):
        pass

    def test_lrelu(self):
        for i in range(-5, 15):

            if i > 0:
                good_output = i
            else:
                good_output = self.alpha * i

            computed_output = tl.act.leaky_relu(float(i), alpha=self.alpha)

            self.assertAlmostEqual(computed_output.numpy(), good_output, places=5)

        net = tl.layers.Input([10, 2])
        net = tl.layers.Dense(n_units=100, act=lambda x: tl.act.lrelu(x, 0.2), name='dense')(net)
        print(net)

    def test_lrelu6(self):
        for i in range(-5, 15):

            if i < 0:
                good_output = self.alpha * i
            else:
                good_output = min(6, i)

            computed_output = tl.act.leaky_relu6(float(i), alpha=self.alpha)

            self.assertAlmostEqual(computed_output.numpy(), good_output, places=5)

        net = tl.layers.Input([10, 2])
        net = tl.layers.Dense(n_units=100, act=lambda x: tl.act.leaky_relu6(x, 0.2), name='dense')(net)
        print(net)

    def test_ltrelu6(self):
        for i in range(-5, 15):

            if i < 0:
                good_output = self.alpha * i
            elif i < 6:
                good_output = i
            else:
                good_output = 6 + (self.alpha * (i - 6))

            computed_output = tl.act.leaky_twice_relu6(float(i), alpha_low=self.alpha, alpha_high=self.alpha)

            self.assertAlmostEqual(computed_output.numpy(), good_output, places=5)

        net = tl.layers.Input([10, 200])
        net = tl.layers.Dense(n_units=100, act=lambda x: tl.act.leaky_twice_relu6(x, 0.2, 0.2), name='dense')(net)
        print(net)

    def test_ramp(self):

        for i in range(-5, 15):

            if i < self.vmin:
                good_output = self.vmin
            elif i > self.vmax:
                good_output = self.vmax
            else:
                good_output = i

            computed_output = tl.act.ramp(float(i), v_min=self.vmin, v_max=self.vmax)

            self.assertAlmostEqual(computed_output.numpy(), good_output, places=5)

    def test_sign(self):

        for i in range(-5, 15):

            if i < 0:
                good_output = -1
            elif i == 0:
                good_output = 0
            else:
                good_output = 1

            computed_output = tl.act.sign(float(i))

            self.assertAlmostEqual(computed_output.numpy(), good_output, places=5)

    def test_swish(self):
        import numpy as np

        for i in range(-5, 15):

            good_output = i / (1 + np.math.exp(-i))

            computed_output = tl.act.swish(float(i))

            self.assertAlmostEqual(computed_output.numpy(), good_output, places=5)

    def test_mish(self):
        for i in range(-5, 15):
            good_output = i * np.tanh(np.math.log(1 + np.math.exp(i)))

            computed_output = tl.act.mish(float(i))

            self.assertAlmostEqual(computed_output.numpy(), good_output, places=5)

if __name__ == '__main__':

    unittest.main()


text:
#import "WXScrollerProtocol.h"
#import "WXComponent.h"

@interface WXScrollerComponent : WXComponent <WXScrollerProtocol, UIScrollViewDelegate>

@property (nonatomic, copy) void (^onScroll)(UIScrollView *scrollView);

@property (nonatomic, copy) void (^scrollEventListener)(WXScrollerComponent* sender, NSString* event, NSDictionary* params);

@property (nonatomic, assign) NSUInteger loadmoreretry;

@property (nonatomic, assign) CGSize contentSize;

- (void)handleAppear;

- (CGPoint)absolutePositionForComponent:(WXComponent *)component;

@end


text:
export class battleshipGame {
  public status: boolean;
  public player: string;
}


text:
<?php

App::uses('AppController', 'Controller');

class ConfigAppController extends AppController {

/**
 * Components
 *
 * @var array
 * @access public
 */
	public $components = array('Security');

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="Source to the Rust file `/home/jacob/.cargo/registry/src/github.com-1ecc6299db9ec823/nalgebra-0.11.2/src/geometry/unit_complex_construction.rs`.">
    <meta name="keywords" content="rust, rustlang, rust-lang">

    <title>unit_complex_construction.rs.html -- source</title>

    <link rel="stylesheet" type="text/css" href="../../../normalize.css">
    <link rel="stylesheet" type="text/css" href="../../../rustdoc.css">
    <link rel="stylesheet" type="text/css" href="../../../main.css">

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options…"
                       type="search">

        </form>

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107

#[cfg(feature = "arbitrary")]
use quickcheck::{Arbitrary, Gen};

use num::One;
use num_complex::Complex;
use rand::{Rand, Rng};

use alga::general::Real;
use core::ColumnVector;
use core::dimension::{U1, U2};
use core::storage::Storage;
use geometry::{UnitComplex, RotationBase};

impl<N: Real> UnitComplex<N> {
    /// The unit complex number multiplicative identity.
    #[inline]
    pub fn identity() -> Self {
        Self::new_unchecked(Complex::new(N::one(), N::zero()))
    }

    /// Builds the unit complex number corresponding to the rotation with the angle.
    #[inline]
    pub fn new(angle: N) -> Self {
        let (s, c) = angle.sin_cos();
        UnitComplex::new_unchecked(Complex::new(c, s))
    }

    /// Builds the unit complex number corresponding to the rotation with the angle.
    ///
    /// Same as `Self::new(angle)`.
    #[inline]
    pub fn from_angle(angle: N) -> Self {
        Self::new(angle)
    }

    /// Builds a unit complex rotation from an angle in radian wrapped in a 1-dimensional vector.
    ///
    /// Equivalent to `Self::new(axisangle[0])`.
    #[inline]
    pub fn from_scaled_axis<SB: Storage<N, U1, U1>>(axisangle: ColumnVector<N, U1, SB>) -> Self {
        Self::from_angle(axisangle[0])
    }

    /// Creates a new unit complex number from a complex number.
    ///
    /// The input complex number will be normalized.
    #[inline]
    pub fn from_complex(q: Complex<N>) -> Self {
        Self::new_unchecked(q / (q.im * q.im + q.re * q.re).sqrt())
    }

    /// Builds the unit complex number from the corresponding 2D rotation matrix.
    #[inline]
    pub fn from_rotation_matrix<S: Storage<N, U2, U2>>(rotmat: &RotationBase<N, U2, S>) -> Self {
        Self::new_unchecked(Complex::new(rotmat[(0, 0)], rotmat[(1, 0)]))
    }

    /// The unit complex needed to make `a` and `b` be collinear and point toward the same
    /// direction.
    #[inline]
    pub fn rotation_between<SB, SC>(a: &ColumnVector<N, U2, SB>, b: &ColumnVector<N, U2, SC>) -> Self
        where SB: Storage<N, U2, U1>,
              SC: Storage<N, U2, U1> {
        Self::scaled_rotation_between(a, b, N::one())
    }

    /// The smallest rotation needed to make `a` and `b` collinear and point toward the same
    /// direction, raised to the power `s`.
    #[inline]
    pub fn scaled_rotation_between<SB, SC>(a: &ColumnVector<N, U2, SB>, b: &ColumnVector<N, U2, SC>, s: N) -> Self
        where SB: Storage<N, U2, U1>,
              SC: Storage<N, U2, U1> {
        if let (Some(na), Some(nb)) = (a.try_normalize(N::zero()), b.try_normalize(N::zero())) {
            let sang = na.perp(&nb);
            let cang = na.dot(&nb);

            Self::from_angle(sang.atan2(cang) * s)
        }
        else {
            Self::identity()
        }
    }
}

impl<N: Real> One for UnitComplex<N> {
    #[inline]
    fn one() -> Self {
        Self::identity()
    }
}

impl<N: Real + Rand> Rand for UnitComplex<N> {
    #[inline]
    fn rand<R: Rng>(rng: &mut R) -> Self {
        UnitComplex::from_angle(N::rand(rng))
    }
}

#[cfg(feature="arbitrary")]
impl<N: Real + Arbitrary> Arbitrary for UnitComplex<N> {
    #[inline]
    fn arbitrary<G: Gen>(g: &mut G) -> Self {
        UnitComplex::from_angle(N::arbitrary(g))

    }
}

Help

Keyboard Shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

+

Collapse/expand all sections

Search Tricks

                    Prefix searches with a type followed by a colon (e.g.
                    fn:) to restrict the search to a given type.

                    Accepted types are: fn, mod,
                    struct, enum,
                    trait, type, macro,
                    and const.

                    Search functions by type signature (e.g.
                    vec -> usize or * -> vec)


text:
extern crate libc;

pub use ffi::{
    Class,
    Method,
    Ivar,
    Category,
    objc_property_t,
    SEL,
    id,
    Id
};

mod macros;

#[doc(hidden)]
pub mod ffi;
pub mod objc;
pub mod object;
pub mod class;
pub mod method;
pub mod ivar;
pub mod protocol;
pub mod sel;
pub mod user_macros;


text:
<?php

namespace Phpatterns\Structural\Facade;

class Account
{
    /** @var float */
    private $balance;

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

    /**
     * @return float
     */
    public function getBalance()
    {
        return $this->balance;
    }

    /**
     * @param float $balance
     */
    public function setBalance($balance)
    {
        $this->balance = $balance;
    }
}


text:
<?php
/*
* Mysql database class - only one connection alowed
*/

class Database {
	private $_connection;
	private static $_instance; //The single instance
	private $_host = DB_API_HOST;
	private $_username = DB_API_USERNAME;
	private $_password = DB_API_PASSWORD;
	private $_database = DB_API_DATABASE;
	/*
	Get an instance of the Database
	@return Instance
	*/
	public static function getInstance() {
		if(!self::$_instance) { // If no instance then make one
			self::$_instance = new self();
		}
		return self::$_instance;
	}
	// Constructor
	private function __construct() {
		$dsn = "mysql:dbname={$this->_database};host={$this->_host}";

		try {
		    $this->_connection = new PDO($dsn, $this->_username, $this->_password);
		} catch (PDOException $e) {
		    echo 'Connection failed: ' . $e->getMessage();
		}

	}
	// Magic method clone is empty to prevent duplication of connection
	private function __clone() { }
	// Get mysqli connection
	public function getConnection() {
		return $this->_connection;
	}
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.mguidi.soa</groupId>
	<artifactId>commons-service</artifactId>
	<version>1.0.0</version>
	<packaging>jar</packaging>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.2</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
		</plugins>
	</build>

	<dependencies>
		<dependency>
			<groupId>com.google.code.gson</groupId>
			<artifactId>gson</artifactId>
			<version>2.3</version>
		</dependency>

	</dependencies>

</project>


text:
using namespace boost::python;
using namespace IECorePython;
using namespace Gaffer;
using namespace GafferBindings;

namespace
{

Spreadsheet::RowPlugPtr defaultRow( Spreadsheet::RowsPlug &rowsPlug )
{
	return rowsPlug.defaultRow();
}

size_t addColumn( Spreadsheet::RowsPlug &rowsPlug, ValuePlug &value, IECore::InternedString name )
{
	ScopedGILRelease gilRelease;
	return rowsPlug.addColumn( &value, name );
}

void removeColumn( Spreadsheet::RowsPlug &rowsPlug, size_t columnIndex )
{
	ScopedGILRelease gilRelease;
	return rowsPlug.removeColumn( columnIndex );
}

Spreadsheet::RowPlugPtr addRow( Spreadsheet::RowsPlug &rowsPlug )
{
	ScopedGILRelease gilRelease;
	return rowsPlug.addRow();
}

void addRows( Spreadsheet::RowsPlug &rowsPlug, size_t numRows )
{
	ScopedGILRelease gilRelease;
	rowsPlug.addRows( numRows );
}

void removeRow( Spreadsheet::RowsPlug &rowsPlug, Spreadsheet::RowPlug &row )
{
	ScopedGILRelease gilRelease;
	rowsPlug.removeRow( &row );
}

ValuePlugPtr activeInPlug( Spreadsheet &s, const ValuePlug &outPlug )
{
	ScopedGILRelease gilRelease;
	return s.activeInPlug( &outPlug );
}

class RowsPlugSerialiser : public ValuePlugSerialiser
{

	public :

		std::string postConstructor( const Gaffer::GraphComponent *graphComponent, const std::string &identifier, const Serialisation &serialisation ) const override
		{
			std::string result = ValuePlugSerialiser::postConstructor( graphComponent, identifier, serialisation );

			const auto *plug = static_cast<const Spreadsheet::RowsPlug *>( graphComponent );
			for( const auto &cell : Spreadsheet::CellPlug::Range( *plug->getChild<Spreadsheet::RowPlug>( 0 )->cellsPlug() ) )
			{
				PlugPtr p = cell->valuePlug()->createCounterpart( cell->getName(), Plug::In );
				const Serialiser *plugSerialiser = Serialisation::acquireSerialiser( p.get() );
				result += identifier + ".addColumn( " + plugSerialiser->constructor( p.get(), serialisation ) + " )\n";
			}

			const size_t numRows = plug->children().size();
			if( numRows > 1 )
			{
				result += identifier + ".addRows( " + std::to_string( numRows - 1 ) + " )\n";
			}
			return result;
		}

		bool childNeedsConstruction( const Gaffer::GraphComponent *child, const Serialisation &serialisation ) const override
		{
			// We can serialise much more compactly via the `addRows()` call made by `postConstructor()`.
			return false;
		}

};

} // namespace

void GafferModule::bindSpreadsheet()
{

	scope s = DependencyNodeClass<Spreadsheet>()
		.def( "activeInPlug", &activeInPlug )
	;

	PlugClass<Spreadsheet::RowsPlug>()
		.def( init<std::string, Plug::Direction, unsigned>(
				(
					arg( "name" )=GraphComponent::defaultName<Spreadsheet::RowsPlug>(),
					arg( "direction" )=Plug::In,
					arg( "flags" )=Plug::Default
				)
			)
		)
		.def( "defaultRow", &defaultRow )
		.def( "addColumn", &addColumn, ( arg( "value" ), arg( "name" ) = "" ) )
		.def( "removeColumn", &removeColumn )
		.def( "addRow", &addRow )
		.def( "addRows", &addRows )
		.def( "removeRow", &removeRow )
		.attr( "__qualname__" ) = "Spreadsheet.RowsPlug"
	;

	PlugClass<Spreadsheet::RowPlug>()
		.attr( "__qualname__" ) = "Spreadsheet.RowPlug"
	;

	PlugClass<Spreadsheet::CellPlug>()
		.attr( "__qualname__" ) = "Spreadsheet.CellPlug"
	;

	Serialisation::registerSerialiser( Gaffer::Spreadsheet::RowsPlug::staticTypeId(), new RowsPlugSerialiser );

}


text:
package org.cloudfoundry.reactor.routing.v1.tcproutes;

import org.cloudfoundry.reactor.AbstractRestTest;
import org.cloudfoundry.reactor.InteractionContext;
import org.cloudfoundry.reactor.TestRequest;
import org.cloudfoundry.reactor.TestResponse;
import org.junit.Test;
import reactor.core.publisher.Flux;
import reactor.netty.ByteBufFlux;
import reactor.netty.Connection;
import reactor.netty.http.client.HttpClientResponse;
import reactor.test.StepVerifier;

import java.time.Duration;

import static io.netty.handler.codec.http.HttpMethod.GET;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;

public final class EventStreamCodecTest extends AbstractRestTest {

    @Test
    public void allData() {
        mockRequest(InteractionContext.builder()
            .request(TestRequest.builder()
                .method(GET)
                .path("/")
                .build())
            .response(TestResponse.builder()
                .status(OK)
                .payload("org/cloudfoundry/reactor/routing/v1/tcproutes/all-data.txt")
                .build())
            .build());

        CONNECTION_CONTEXT.getHttpClient()
            .get()
            .uri(this.root.block())
            .responseConnection(EventStreamCodecTest::toEventsFlux)
            .as(StepVerifier::create)
            .expectNext(ServerSentEvent.builder()
                .data("This is the first message.")
                .build())
            .expectNext(ServerSentEvent.builder()
                .data("This is the second message, it")
                .data("has two lines.")
                .build())
            .expectNext(ServerSentEvent.builder()
                .data("This is the third message.")
                .build())
            .expectComplete()
            .verify(Duration.ofSeconds(5));
    }

    @Test
    public void colonSpacing() {
        mockRequest(InteractionContext.builder()
            .request(TestRequest.builder()
                .method(GET)
                .path("/")
                .build())
            .response(TestResponse.builder()
                .status(OK)
                .payload("org/cloudfoundry/reactor/routing/v1/tcproutes/colon-spacing.txt")
                .build())
            .build());

        CONNECTION_CONTEXT.getHttpClient()
            .get()
            .uri(this.root.block())
            .responseConnection(EventStreamCodecTest::toEventsFlux)
            .as(StepVerifier::create)
            .expectNext(ServerSentEvent.builder()
                .data("test")
                .build())
            .expectNext(ServerSentEvent.builder()
                .data("test")
                .build())
            .expectComplete()
            .verify(Duration.ofSeconds(5));
    }

    @Test
    public void randomColons() {
        mockRequest(InteractionContext.builder()
            .request(TestRequest.builder()
                .method(GET)
                .path("/")
                .build())
            .response(TestResponse.builder()
                .status(OK)
                .payload("org/cloudfoundry/reactor/routing/v1/tcproutes/random-colons.txt")
                .build())
            .build());

        CONNECTION_CONTEXT.getHttpClient()
            .get()
            .uri(this.root.block())
            .responseConnection(EventStreamCodecTest::toEventsFlux)
            .as(StepVerifier::create)
            .expectNext(ServerSentEvent.builder()
                .data("")
                .build())
            .expectNext(ServerSentEvent.builder()
                .data("")
                .data("")
                .build())
            .expectComplete()
            .verify(Duration.ofSeconds(5));
    }

    @Test
    public void threeLines() {
        mockRequest(InteractionContext.builder()
            .request(TestRequest.builder()
                .method(GET)
                .path("/")
                .build())
            .response(TestResponse.builder()
                .status(OK)
                .payload("org/cloudfoundry/reactor/routing/v1/tcproutes/three-lines.txt")
                .build())
            .build());

        CONNECTION_CONTEXT.getHttpClient()
            .get()
            .uri(this.root.block())
            .responseConnection(EventStreamCodecTest::toEventsFlux)
            .as(StepVerifier::create)
            .expectNext(ServerSentEvent.builder()
                .data("YHOO")
                .data("+2")
                .data("10")
                .build())
            .expectComplete()
            .verify(Duration.ofSeconds(5));
    }

    @Test
    public void withComment() {
        mockRequest(InteractionContext.builder()
            .request(TestRequest.builder()
                .method(GET)
                .path("/")
                .build())
            .response(TestResponse.builder()
                .status(OK)
                .payload("org/cloudfoundry/reactor/routing/v1/tcproutes/with-comment.txt")
                .build())
            .build());

        CONNECTION_CONTEXT.getHttpClient()
            .get()
            .uri(this.root.block())
            .responseConnection(EventStreamCodecTest::toEventsFlux)
            .as(StepVerifier::create)
            .expectNext(ServerSentEvent.builder()
                .id("1")
                .data("first event")
                .build())
            .expectNext(ServerSentEvent.builder()
                .id("")
                .data("second event")
                .build())
            .expectNext(ServerSentEvent.builder()
                .data(" third event")
                .build())
            .expectComplete()
            .verify(Duration.ofSeconds(5));
    }

    @Test
    public void withEventTypes() {
        mockRequest(InteractionContext.builder()
            .request(TestRequest.builder()
                .method(GET)
                .path("/")
                .build())
            .response(TestResponse.builder()
                .status(OK)
                .payload("org/cloudfoundry/reactor/routing/v1/tcproutes/with-event-types.txt")
                .build())
            .build());

        CONNECTION_CONTEXT.getHttpClient()
            .get()
            .uri(this.root.block())
            .responseConnection(EventStreamCodecTest::toEventsFlux)
            .as(StepVerifier::create)
            .expectNext(ServerSentEvent.builder()
                .eventType("add")
                .data("73857293")
                .build())
            .expectNext(ServerSentEvent.builder()
                .eventType("remove")
                .data("2153")
                .build())
            .expectNext(ServerSentEvent.builder()
                .eventType("add")
                .data("113411")
                .build())
            .expectComplete()
            .verify(Duration.ofSeconds(5));
    }

    private static Flux<ServerSentEvent> toEventsFlux(HttpClientResponse response, Connection connection) {
        connection.addHandler(EventStreamCodec.createDecoder(response));
        ByteBufFlux body = connection.inbound().receive();

        return EventStreamCodec.decode(body);
    }

}


text: google-site-verification: google3dc3d2cfa03aa2a6.html


text:
import synapse.tests.utils as s_t_utils

class InitTest(s_t_utils.SynTest):
    pass

    '''
    def test_init_modules(self):
        os.environ['SYN_MODULES'] = 'fakenotrealmod , badnothere,math'
        msg = 'SYN_MODULES failed: badnothere (NoSuchDyn: name=\'badnothere\')'
        with self.getLoggerStream('synapse', msg) as stream:
            imp.reload(synapse)
            self.true(stream.wait(10))

        stream.seek(0)
        self.isin(msg, stream.read())
        self.isin(('math', 2.0, None), synapse.lib.modules.call('sqrt', 4))
    '''


text:
wx.env.USER_DATA_PATH

// https://github.com/wechat-miniprogram/api-typings/issues/13
const ctx = wx.createCanvasContext('myCanvas')
ctx.drawImage('', 1, 1)
ctx.drawImage('', 0, 0, 150, 100)
ctx.drawImage('', 0, 0, 0, 0, 0, 0, 0, 0)

// https://github.com/wechat-miniprogram/api-typings/issues/15
wx.getSetting({
  success(res) {
    // $ExpectType boolean | undefined
    res.authSetting['scope.userInfo']
  },
})

// https://github.com/wechat-miniprogram/api-typings/issues/25
// https://github.com/wechat-miniprogram/api-typings/issues/32
// https://github.com/wechat-miniprogram/api-typings/issues/42
wx.cloud.callFunction({
  name: 'add',
  data: {
    x: 1,
    y: 2,
  },
  success: res => {
    // $ExpectType string
    res.errMsg
  },
  fail: err => {
    // $ExpectType string
    err.errMsg
  },
})

wx.cloud.deleteFile({
  fileList: ['a7xzcb'],
  success: res => {
    // $ExpectType DeleteFileResultItem[]
    res.fileList
  },
})

// https://github.com/wechat-miniprogram/api-typings/issues/33
wx.addCard({
  cardList: [
    {
      cardId: '',
      cardExt: '{"code": "", "openid": "", "timestamp": "", "signature":""}',
    },
    {
      cardId: '',
      cardExt: '{"code": "", "openid": "", "timestamp": "", "signature":""}',
    },
  ],
  success(res) {
    // $ExpectType AddCardResponseInfo[]
    res.cardList
  },
})

// https://github.com/wechat-miniprogram/api-typings/issues/35
wx.chooseMessageFile({
  count: 10,
  type: 'image',
  success(res) {
    // $ExpectType ChooseFile[]
    res.tempFiles
  },
})

// https://github.com/wechat-miniprogram/api-typings/issues/43
wx.canvasGetImageData({
  canvasId: 'myCanvas',
  x: 0,
  y: 0,
  width: 100,
  height: 100,
  success(res) {
    // $ExpectType number
    res.width
    // $ExpectType number
    res.height
    // $ExpectType Uint8ClampedArray
    res.data
    // $ExpectType number
    res.data.length
  },
})

// https://github.com/wechat-miniprogram/api-typings/issues/45
wx.onGyroscopeChange(res => {
  // $ExpectType number
  res.x
  // $ExpectType number
  res.y
  // $ExpectType number
  res.z
})

// https://github.com/wechat-miniprogram/api-typings/issues/47
wx.reportAnalytics('purchase', {
  price: 120,
  color: 'red',
})

// https://github.com/wechat-miniprogram/api-typings/issues/48
wx.navigateBack()
wx.navigateBack({})
wx.navigateBack({ delta: 1 })
wx.setTabBarStyle()
wx.setTabBarStyle({})
wx.setTabBarStyle({ color: '#111111' })
wx.setBackgroundColor({ backgroundColor: '#111111' })
wx.setNavigationBarColor({
  frontColor: '#ffffff',
  backgroundColor: '#123456',
})

// https://github.com/wechat-miniprogram/api-typings/issues/59
wx.login({
  success(res) {
    // $ExpectType string
    res.errMsg
  },
})

// https://github.com/wechat-miniprogram/api-typings/issues/60
wx.loadFontFace({
  source: '',
  family: 'font',
  success(res) {
    // $ExpectType string
    res.status
  },
  fail(res) {
    // $ExpectType string
    res.status
  },
  complete(res) {
    // $ExpectType string
    res.status
  },
})

// https://github.com/wechat-miniprogram/api-typings/issues/65
wx.request({
  url: '',
  success(res) {
    const data: WechatMiniprogram.IAnyObject = { res }
    // $ExpectType any
    data.customData
  },
})
interface IResponse {
  customData: string
}
wx.request({
  url: '',
  success(res) {
    const data = res.data as IResponse
    // $ExpectType string
    data.customData
  },
})

// https://github.com/wechat-miniprogram/api-typings/issues/73
{
  const task = wx.connectSocket({ url: '' })
  task.onClose(res => {
    // $ExpectType number
    res.code
    // $ExpectType string
    res.reason
  })
}

// https://github.com/wechat-miniprogram/api-typings/issues/75
{
  wx.onBluetoothDeviceFound(res => {
    res.devices.forEach(device => {
      // $ExpectType string
      device.name
      // $ExpectType string
      device.deviceId
    })
  })
}

// https://github.com/wechat-miniprogram/api-typings/issues/82
{
  interface IDialogMethod
    extends Partial<WechatMiniprogram.Component.MethodOption> {
    f?: () => string
    g: () => void
  }
  type Dialog = WechatMiniprogram.Component.Instance<{}, {}, IDialogMethod>
  Page({
    f() {
      const comp = this.selectComponent('#comp') as Dialog
      // $ExpectType (() => string) | undefined
      comp.f
      if (comp.f)
        // $ExpectType string
        comp.f()
      comp.g()
    },
  })
}

// https://github.com/wechat-miniprogram/api-typings/issues/85
{
  Behavior({
    observers: {
      value(v) {
        // $ExpectType any
        v
      },
    },
  })
}

// https://github.com/wechat-miniprogram/api-typings/issues/87
import WX = WechatMiniprogram
{
  type ILoginResult = WX.LoginSuccessCallbackResult
  const t: ILoginResult = { code: '', errMsg: '' }
  // $ExpectType LoginSuccessCallbackResult
  t
}

// https://github.com/wechat-miniprogram/api-typings/issues/88
{
  wx.createSelectorQuery()
    .select('#canvas')
    .fields({ node: true })
    .exec(res => {
      wx.canvasToTempFilePath({ canvas: res[0].node })
      wx.canvasToTempFilePath({ canvas: res[0].node, quality: 0.5 })
    })
  wx.canvasToTempFilePath({ canvasId: '' })
}

// https://github.com/wechat-miniprogram/api-typings/issues/89
{
  const udp = wx.createUDPSocket()
  const port = udp.bind()
  // $ExpectType number
  port
}

// https://github.com/wechat-miniprogram/api-typings/issues/91
{
  wx.getExtConfig({
    success(res) {
    },
  })
}

// https://github.com/wechat-miniprogram/api-typings/issues/95
{
  Page({
    ctx: {} as unknown as WechatMiniprogram.CameraContext,
    onLoad() {
      this.ctx = wx.createCameraContext()
    },
    takePhoto() {
      this.ctx.takePhoto({
        quality: 'high',
        success: res => {
          // $ExpectType string
          res.tempImagePath
          this.setData({
            src: res.tempImagePath,
          })
        },
      })
    },
    startRecord() {
      this.ctx.startRecord({
        success: res => {
          // $ExpectType string
          res.errMsg
          console.log('startRecord')
        },
      })
    },
    stopRecord() {
      this.ctx.stopRecord({
        success: res => {
          // $ExpectType string
          res.tempThumbPath
          // $ExpectType string
          res.tempVideoPath
          this.setData({
            src: res.tempThumbPath,
            videoSrc: res.tempVideoPath,
          })
        },
      })
    },
  })
}

// https://github.com/wechat-miniprogram/api-typings/issues/133
{
  type IData = {
    name: string
  }
  type IProperty = {
    id: typeof Number
  }
  type IMethod = {
    setJob(job: string): void
  }
  type ICustomInstanceProperty = {
    job: string
  }
  Component<IData, IProperty, IMethod, ICustomInstanceProperty>({
    properties: {
      id: Number,
    },

    data: {
      name: '',
    },

    methods: {
      setJob(job) {
        this.job = job
        // $ExpectType string
        this.job
      },
    },
  })
}

// https://github.com/wechat-miniprogram/api-typings/issues/134
{
  const ctx = wx.createMapContext('map')
  ctx.getRegion({
    success(res) {
      // $ExpectType number
      res.southwest.longitude
      // $ExpectType number
      res.southwest.latitude
      // $ExpectType number
      res.northeast.longitude
      // $ExpectType number
      res.northeast.latitude
    },
  })
}

// https://github.com/wechat-miniprogram/api-typings/issues/136
{
  Page({
    onAddToFavorites(res) {
      if (res.webviewUrl) {
        // webview 页面返回 webviewUrl
        // $ExpectType string
        res.webviewUrl
      }
      return {
        title: '自定义标题',
        imageUrl: 'http://demo.png',
        query: 'name=xxx&age=xxx',
      }
    },
  })
}

// https://github.com/wechat-miniprogram/api-typings/issues/154
{
  wx.requestPayment({
    timeStamp: '',
    nonceStr: '',
    package: '',
    signType: 'MD5',
    paySign: '',
  })
  wx.requestPayment({
    timeStamp: '',
    nonceStr: '',
    package: '',
    signType: 'RSA',
    paySign: '',
  })
}

// https://github.com/wechat-miniprogram/api-typings/issues/157
{
  wx.saveFile({
    tempFilePath: '',
    success(res) {
      // $ExpectType string
      res.savedFilePath
    },
  })
}

// https://github.com/wechat-miniprogram/api-typings/issues/159
{
  Page({
    onShareTimeline() {
      return {
        title: '',
        query: '',
        imageUrl: '',
      }
    },
  })
}

// https://github.com/wechat-miniprogram/api-typings/issues/161
{
  Component({
    properties: {
      bar: {
        type: Object,
        value: { skuNum: 0 },
        observer() {},
      },
    },
    data: {
      foo: 123,
    },
    methods: {
      getDataOrPoperty() {
        return this.data.foo
      },
      test() {
        // $ExpectType number
        this.getDataOrPoperty()
      },
    },
  })
}

// https://github.com/wechat-miniprogram/api-typings/issues/164
{
  requirePlugin('myPlugin')
  requireMiniProgram()
}

// https://github.com/wechat-miniprogram/api-typings/issues/175
{
  wx.requestSubscribeMessage({
    tmplIds: ['1', '2'],
    success: res => {
      // $ExpectType string
      res.errMsg
      // $ExpectType string
      res.whatever
      // $ExpectType string
      res.randomTemplateId
    },
  })
}


text:
package io.pravega.auth;

import java.security.Principal;

/**
 * Custom authorization/authentication handlers implement this interface.
 * The implementations are loaded from the classpath using `ServiceLoader` (https://docs.oracle.com/javase/7/docs/api/java/util/ServiceLoader.html)
 * Pravega controller also implements this interface through {@code io.pravega.controller.server.rpc.auth.PasswordAuthHandler}.
 *
 * Each custom auth handler is registered with a unique name identifying a supported authentication scheme.
 *
 * The client supplies authentication credentials formatted as per HTTP 1.1 (RFC 7235):
 * <pre>
 *     Authentication: <scheme> <token>
 * </pre>
 * This is done by implementing `PravegaCredentials` interface and passing it to client calls.
 *
 * The credentials are passed via the {@code Authorization} header.  For gRPC, the header is passed via call metadata.
 * For REST, the credentials are passed as the value of the HTTP {@code Authorization} header.
 * For gRPC, the credentials are passed as the value of the {@code Authorization} header in call metadata.
 *
 */
public interface AuthHandler {

    enum Permissions {
        NONE,
        READ,
        READ_UPDATE
    }

    /**
     * Returns name of the handler. Only the first implementation with a unique name will be loaded.
     * @return The unique name assigned to the handler.
     */
    String getHandlerName();

    /**
     * Authenticates a given request. Pravega controller passes the HTTP headers associated with the call.
     * The custom implementation returns whether the user represented by these headers is authenticated.
     *
     * @param token the credentials token passed via the {@code Authorization} header.
     * @return Returns the Principal represented by the token.
     *
     * @throws AuthException Exception of type AuthException thrown if there is any error.
     */
    Principal authenticate(String token) throws AuthException;

    /**
     * Authorizes the access to a given resource. Pravega controller passes the HTTP headers associated with the call.
     * The implementations of this interface should return the maximum level of authorization possible for the user represented
     * by the headers.
     *
     * @param resource the resource that needs to be accessed.
     * @param principal the Principal which needs to be authorized. This is generally a Principal returned by an earlier
     *                  call to `authenticate` method.
     * @return The level of authorization.
     */
    Permissions authorize(String resource, Principal principal);

    /**
     * Sets the configuration. If the auth handler needs to access the server configuration, it can be accessed though this var.
     *
     * @param serverConfig The server configuration.
     */
    default void initialize(ServerConfig serverConfig) {
        // Do nothing if the handler does not need any configuration being injected.
    }
}


text:
define({
    paths:{
        // Libraries
        // ---------
        "vendor": "bower_components",
        "underscore": "bower_components/underscore/underscore",
        "mustache": "bower_components/mustache/mustache",
        "jquery": "bower_components/jquery/dist/jquery.min",
        "backbone": "bower_components/backbone/backbone", //fully amd

        "marionette": "bower_components/marionette/lib/backbone.marionette.min", //already includes wreqr and babysitter
        "backbone.wreqr": "bower_components/backbone.wreqr/lib/backbone.wreqr.min", //kept for the backbone only example
        "backbone.babysitter": "bower_components/backbone.babysitter/lib/backbone.babysitter.min",

        "bootstrap": "bower_components/bootstrap/dist/js/bootstrap.min", //non-amd

        // Require Modules to be used as pragmas
        // ---------
        "text": "bower_components/requirejs-text/text",

        // Backbone Folder Structure
        // -------------------
        "models": "js/models",
        "collections": "collections",
        "routers": "routers",
        "views": "views",
        "templates": "templates"
    },
    shim:{
        //Globally exposed variables:
        //$ jQuery Backbone _
        //unexposed globally variables:
        //mustache(need exposing inorder to be used) bootstrap(built ontop of $)
        "backbone":{
            "deps":[
                "underscore",
                "mustache"
            ]
        },
        "backbone.wreqr":{
            "deps": ["backbone"]
        },
        "backbone.babysitter":{
            "deps": ["backbone"]
        },
        "marionette":{
            "deps":[
                "backbone",
                "backbone.wreqr",
                "backbone.babysitter"
            ]
        },
        "bootstrap":{
            "deps":["jquery"]
        }

    }
});


text:
/**
**  @file tcWaterDetectionDBObject.h
*/
/*
**  Copyright (c) 2014, GCBLUE PROJECT
**  All rights reserved.
**
**  Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
**
**  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
**
**  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
**     documentation and/or other materials provided with the distribution.
**
**  3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from
**     this software without specific prior written permission.
**
**  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
**  NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
**  COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
**  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
**  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
**  IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#ifndef _WATERDETECTIONDBOBJECT_H_
#define _WATERDETECTIONDBOBJECT_H_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#include <string>

namespace database
{
	class tcSqlReader;
    class tcSignatureModel;
    class tcAcousticModel;

    /**
    * Describes detectability of object through water with sonar
    */
    class tcWaterDetectionDBObject
    {
    public:
        float TS;                           ///< Target strength for active sonar detection
        std::string TS_Model;               ///< aspect variation model for acoustic backscatter
        std::string acousticModel;          ///< acoustic model for SL vs speed
        std::string SL_Model;               ///< aspect variation model for radiated noise

		static void AddSqlColumns(std::string& columnString);
		void ReadSql(tcSqlReader& entry);
		void WriteSql(std::string& valueString);

        float GetSourceLevel(float speed_mps, float depth_m, float az_deg) const;
        float GetTargetStrength(float az_deg) const;

        float GetCavitationSpeedKts(float depth_m) const;
        float GetMinNonCavitatingDepth(float speed_kts) const;
        float GetCavitatingSourceLevel() const;
        float GetSnorkelingSourceLevel() const;

        float GetNoiseLevelForSpeed(float speed_mps) const;
        float GetNoiseLevelForSpeedKts(float speed_kts) const;

        tcWaterDetectionDBObject();
        tcWaterDetectionDBObject(const tcWaterDetectionDBObject& obj); ///< copy constructor
        virtual ~tcWaterDetectionDBObject();

    private:
        tcSignatureModel* TS_pattern;
        tcSignatureModel* SL_pattern;
        tcAcousticModel* acousticNoise;

        void BindSignatureModels();

    };

}

#endif


text:
var EncryptionHandler = (function () {
    function EncryptionHandler(keydata, initVektor) {
        var self = this;
        if (initVektor == undefined || initVektor.length == 0) {
            //Einen initierungsvektor erstellen, wenn keiner übergeben wurde.
            this.iv = crypto.getRandomValues(new Uint8Array(16));
        }
        else {
            this.iv = initVektor;
        }
        //Aus dem Raum-Namen einen 256bit Hash erstellen.
        this.sha256(keydata).then(function (digest) {
            //Aus dem Hash und den Vektor einen Cryptokey für AEC-CBC erstellen und Speichern.
            crypto.subtle.importKey("raw", digest, "AES-CBC", true, ["encrypt", "decrypt"]).then(function (keyObj) {
                self.key = keyObj;
            });
        });
    }
    EncryptionHandler.prototype.sha256 = function (str) {
        // String in einen Arraybuffer umwandeln
        var buffer = new TextEncoder("utf-8").encode(str);
        return crypto.subtle.digest("SHA-256", buffer).then(function (hash) {
            return hash;
        });
    };
    EncryptionHandler.prototype.encryptString = function (data) {
        //Einen String mit dem AES-Key Verschlüsseln.
        //Gibt einen Promise zurück - Welcher einen JSONifed String zurück gibt
        var self = this;
        var buffer = new TextEncoder('utf-8').encode(data);
        return new Promise(function (resolve, reject) {
            self.encryptBuffer(buffer).then(function (ergebnis) {
                var bufferArray = new Uint8Array(ergebnis);
                resolve(JSON.stringify(bufferArray));
            }).catch(function (reason) {
                reject(reason);
            });
        });
    };
    EncryptionHandler.prototype.encryptBuffer = function (data) {
        //Einen Buffer mit dem AES-Key Verschlüsseln.
        //Gibt einen Promise zurück mit einem Buffer als Argument
        var self = this;
        if (this.key == null) {
            throw new Error("Cryptokey ist nicht initialisiert.");
        }
        return new Promise(function (resolve, reject) {
            crypto.subtle.encrypt({ name: "AES-CBC", iv: self.iv }, self.key, data).then(function (encryptedBuffer) {
                resolve(encryptedBuffer);
            }, function (params) {
                reject(params);
            });
        });
    };
    EncryptionHandler.prototype.decryptJSON = function (data) {
        //Einen JSON-String mit dem AES-Key Entschlüsseln.
        //Gibt einen Promise zurück - Welcher den UR - String zurück gibt
        var self = this;
        return new Promise(function (resolve, reject) {
            //Aus der JSON wieder einen Buffer erzeugen - Da der Server keine Binäre Übertragung unterstüzt.
            var obj = JSON.parse(data);
            var arr = [];
            for (var i in obj) {
                arr[i] = obj[i];
            }
            var buffer = new Uint8Array(arr).buffer;
            //Buffer entschlüsseln
            self.decryptBuffer(buffer).then(function (decryptedBuffer) {
                //Aus Buffer wieder einen String machen
                resolve(new TextDecoder('utf-8').decode(decryptedBuffer));
            }).catch(function (reason) {
                reject(reason);
            });
        });
    };
    EncryptionHandler.prototype.decryptBuffer = function (data) {
        //Einen Buffer entschlüsseln.
        //Rückgabewert ist ein Promise mit Buffer als Argument.
        var self = this;
        return new Promise(function (resolve, reject) {
            crypto.subtle.decrypt({ name: "AES-CBC", iv: self.iv }, self.key, data).then(function (decryptedBuffer) {
                resolve(decryptedBuffer);
            }).catch(function (reason) {
                reject(reason);
            });
        });
    };
    EncryptionHandler.prototype.getInitVektor = function () {
        //Den IV Lesbar machen
        return this.iv;
    };
    return EncryptionHandler;
})();


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:elevation="@dimen/app_bar_elevation"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:navigationIcon="@drawable/ic_arrow_back_white_24dp"
        app:title="@string/notification"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/icon_no_data"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:drawableTop="@drawable/ic_no_data"
            android:drawablePadding="16dp"
            android:text="@string/no_message"
            android:textColor="#ffbababa"
            android:textSize="16sp"
            android:gravity="center" />

        <android.support.v4.widget.SwipeRefreshLayout
            android:id="@+id/refresh_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/recycler_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />

        </android.support.v4.widget.SwipeRefreshLayout>

    </FrameLayout>

</LinearLayout>


text:
(function () {
  "use strict";

  var http = require('http'),
    scannerDb = require('scanner-sqlite3'),
    filepush = require('filepush');

  function sortBySizeAndTime(a, b) {
    // Files that have changed recently
    // are most likely to change again
    if (a.mtime > b.mtime) { return 1; }
    if (a.mtime < b.mtime) { return -1; }
    // smallest files are easiest to upload
    if (a.size > b.size) { return 1; }
    if (a.size < b.size) { return -1; }
    return 0;
  }

  function processScan(scanResults) {
    var allStats,
      stop;

    function pushBatch(response) {
      console.log("pushBatch");
      var chunks = [];
      response.on('data', function (chunk) {
        // TODO process each chunk right away
        // TODO stream parse JSON
        chunks.push(chunk.toString());
      });
      response.on('end', function () {
        var data = JSON.parse(chunks.join(''));

        if (data.length !== Object.keys(allStats).length) {
          console.log(new Error("sent and receive numbers mismatch"));
        }
        data.forEach(function (item) {
          var orig = allStats[item.qmd5];

          allStats[item.qmd5] = undefined;
          delete allStats[item.qmd5];

          if (!orig) {
            console.log(new Error("got back results for a file that wasn't sent"));
            return;
          }
          orig.md5 = item.md5;
          orig.saved = true;
        });
        if (Object.keys(allStats).length) {
          console.log(new Error("files didn't sync"));
        }

        processBatch();
      });
      cb(response)
    }

    function processBatch() {
      var i,
        packet = 0,
        set,
        file;

      for (i = 0; i < scanResults.length; i += 1) {
        file = scanResults[i];
        packet += file.size;
        if (packet >= max_packet_size) {
          stop = i + 1;
          break;
        }
      }

      set = scanResults.splice(0, stop);
      allStats = indexOn(set.slice(), 'qmd5');
      if (!set.length) {
        return;
      }
      console.log('set: ');
      console.log(set);
      filepush(options, set, pushBatch);
    }

    // TODO compare against last scan
    scanResults.sort(sortBySizeAndTime);
    processBatch();
  }

  module.exports = {
    push: processScan
  };
}());


text:
import { RecordingFilled20 } from "../../";

export = RecordingFilled20;


text:
Objective for this tutorial is to print 1 and 2 on the output screen as below.

![Screen-Output-1][img_011]

### Write Task Code

1. Execute RoboPlus Task Program.

    As seen in the picture below, go to `Start > All Programs > ROBOTIS > RoboPlus > Software > RoboPlus Task` to execute RoboPlus Task.

    ![Screen-Output-2][img_012]

   - RoboPlus Task Initial Screen

    ![Screen-Output-3][img_013]

2. Select a Controller.

    Double click an empty line or press `Enter`, In the `Select Control` window, select the controller to use, then press the `OK` button.

    ![Screen-Output-4][img_014]

3. Generating `Start Program`.

    Select `Start Program` from the `Select Instruction Type` window, `Start Program` will be automatically generated in RoboPlus Task.

    ![Screen-Output-5][img_015]

4. Input `Endless Loop` command

    To print the numbers on the screen endlessly, use the `Endless Loop` command(Create a command line).
    Double click or press `Enter` on an empty line between `{` and `}` of Start Program to invoke the `Select Instruction Type` window. Select `Loop > Endless Loop(while(1))` from the list.

    ![Screen-Output-6][img_016]

5. Input `Load` command

    Use `Load` command to input a `Print` command, which is needed to print numbers on the screen.
    Insert `Execute > Load (Assignment value)` into an empty line between `{` and `}` of `Endless Loop`.

    ![Screen-Output-7][img_017]

6. Load `1` into `Print`

    Choose the left parameter ( ? ) among the `Load` parameters(Explanation on the parameter).
    The left parameter receives input from the right parameter.
    Double click the left parameter ( ? ), or press `Enter` key after clicking it once to invoke the `Select Parameter Window`.
    Select `Controller > Print` then press `OK`.

    ![Screen-Output-8][img_018]

    Select `Constant Numbers > Number > 1` for the right parameter ( ? ) in the same way.

    ![Screen-Output-9][img_019]

    When both parameters of the `Load` command have been set, it should look like below.

    ![Screen-Output-10][img_020]

7. Load `2` into `Print with Line`

    Select `}` under `Print` command (at the end of the endless loop section), and add new lines by pressing the `Space` key. Repeat Steps 5 and 6 to input the `Load` command and to input  `Controller > Print with Line` and `2`. The final task code is shown below.

    ![Screen-Output-11][img_021]

8. Save Task Code

    Press Ctrl + S or the Save icon.

    ![Screen-Output-12][img_022]

### Download Task Code

Download the task code created above.([How to Download Task Code])

### Execute Task Code

1. Open the Program Output Monitor

    To see the output of the program, **you must open the Program Output Monitor BEFORE executing the program**.
    There are three ways to open the Program Output Monitor.

    - Click on the View Print of Program in the Download Program window

      ![Screen-Output-13][img_023]

    - Click on the `View Print of Program` button in TOOLS.
    - Press `F5` or click on View Print of Program (V)  menu under Program (P).

2. Executing the Program

    When you turn on the controller, the LED will blink, showing it is in standby mode.
    Press the MODE button to move it to PLAY, then press START to execute the downloaded task code.
    You should see "1" and "2" being printed on the Program Output Monitor.

    ![Screen-Output-1][img_011]

[How to Download Task Code]: /docs/en/software/rplus1/task/getting_started/#program-download
[img_011]: /assets/images/edu/bioloid/bioloid_entry_tutorial_printscr_01.png
[img_012]: /assets/images/edu/bioloid/bioloid_entry_tutorial_printscr_02.png
[img_013]: /assets/images/edu/bioloid/bioloid_entry_tutorial_printscr_03.png
[img_014]: /assets/images/edu/bioloid/bioloid_entry_tutorial_printscr_04.png
[img_015]: /assets/images/edu/bioloid/bioloid_entry_tutorial_printscr_05.png
[img_016]: /assets/images/edu/bioloid/bioloid_entry_tutorial_printscr_06.png
[img_017]: /assets/images/edu/bioloid/bioloid_entry_tutorial_printscr_07.png
[img_018]: /assets/images/edu/bioloid/bioloid_entry_tutorial_printscr_08.png
[img_019]: /assets/images/edu/bioloid/bioloid_entry_tutorial_printscr_09.png
[img_020]: /assets/images/edu/bioloid/bioloid_entry_tutorial_printscr_10.png
[img_021]: /assets/images/edu/bioloid/bioloid_entry_tutorial_printscr_11.png
[img_022]: /assets/images/edu/bioloid/bioloid_entry_tutorial_printscr_12.png
[img_023]: /assets/images/edu/bioloid/bioloid_entry_tutorial_printscr_13.png


text:
import os
import sys
import random
import subprocess as sub
import getopt
import time

def identity(x):
    return x

def cygpath(x):
    command = ["cygpath", "-wp", x]
    p = sub.Popen(command,stdout=sub.PIPE)
    output, errors = p.communicate()
    lines = output.split("\n")
    return lines[0]

if sys.platform == "cygwin":
    normclasspath = cygpath
else:
    normclasspath = identity

CUSTOM_CONF_FILE = ""
CONFIG_OPTS = []
STATUS = 0
JKUBERNETES_DIR = "/".join(os.path.realpath( __file__ ).split("/")[:-2])
JKUBERNETES_CONF_DIR = os.getenv("JKUBERNETES_CONF_DIR", JKUBERNETES_DIR + "/conf" )
CONFIG_OPTS = []
EXCLUDE_JARS = []
INCLUDE_JARS = []

API_SERVER_ADDRESS = ""
JKUBERNETES_CREATE_YAML_PATH = ""

def check_java():
    check_java_cmd = 'which java'
    ret = os.system(check_java_cmd)
    if ret != 0:
        print("Failed to find java, please add java to PATH")
        sys.exit(-1)

def print_commands():
    """Print all client commands and link to documentation"""
    print ("kubectl command [-s http://apiserverip:port]")
    print ("Commands:\n\t",  "\n\t".join(sorted(COMMANDS.keys())))
    print ("\nHelp:", "\n\thelp", "\n\thelp <command>")
    print ("\nDocumentation for the jkubernetes client can be found at https://github.com/gwisoft/jkubernetes/wiki/jkubernetes-Chinese-Documentation\n")

def get_jars_full(adir):
    ret = []
    temp = adir.strip()
    print (temp == "")

    if temp == "":
         return ret
    files = os.listdir(adir)
    for f in files:
        if f.endswith(".jar") == False:
            continue
        filter = False
        for exclude_jar in EXCLUDE_JARS:
            if f.find(exclude_jar) >= 0:
                filter = True
                break

        if filter == True:
            print ("Don't add " + f + " to classpath")
        else:
            ret.append(adir + "/" + f)
    return ret

def unknown_command(*args):
    print ("Unknown command: [kubectl %s]" % ' '.join(sys.argv[1:]))
    print_usage()

def print_usage(command=None):
    """Print one help message or list of available commands"""
    if command != None:
        if command in COMMANDS:
            print (COMMANDS[command].__doc__ or
                  "No documentation provided for <%s>" % command)
        else:
           print ("<%s> is not a valid command" % command)
    else:
        print_commands()

def parse_config_opts_and_args(args):
	curr = args[:]
	curr.reverse()
	config_list = []
	args_list = []

	while len(curr) > 0:
		token = curr.pop()
		if token == "-s":
			global API_SERVER_ADDRESS
			API_SERVER_ADDRESS = curr.pop()
		elif token == "-c":
			config_list.append(curr.pop())
		elif token == "--config":
			global CUSTOM_CONF_FILE
			CUSTOM_CONF_FILE = curr.pop()
		else:
			args_list.append(token)
	print ("config_list=")
	print (config_list)
	print ("args_list=")
	print (args_list)
	return config_list, args_list

def parse_config_opts(config_list):
    global CONFIG_OPTS
    if len(config_list) > 0:
        for config in config_list:
            CONFIG_OPTS.append(config)

def filter_array(array):
    ret = []
    for item in array:
        temp = item.strip()
        if temp != "":
            ret.append(temp)
    return ret

def get_config_opts():
    global CONFIG_OPTS
    print ("-Dkubernetes.options=" + (','.join(CONFIG_OPTS)).replace(' ', "%%%%"))
    return "-Dkubernetes.options=" + (','.join(CONFIG_OPTS)).replace(' ', "%%%%")

#扩展的jar包入参
def get_exclude_jars():
    global EXCLUDE_JARS
    return " -Dexclude.jars=" + (','.join(EXCLUDE_JARS))

def create(args):
	"""
	kubectl create -f ***.yaml
	"""
	pass

	args = parse_client_createopts(args)

	childopts = get_client_customopts() + get_exclude_jars() + get_client_createopts()
	print ("childopts=")
	print (childopts)
	exec_jkubernetes_class(
        "org.gwisoft.jkubernetes.kubectl.KubectlCreate",
        jvmtype="-client -Xms256m -Xmx256m",
        sysdirs=[JKUBERNETES_CONF_DIR, JKUBERNETES_DIR + "/bin",CUSTOM_CONF_FILE],
        args=args,
        childopts=childopts,
        isBackgroundRun="false")

def kube(args):
	"""
	kubectl kube
	"""
	pass

	childopts = get_client_customopts() + get_exclude_jars()
	print ("childopts=")
	print (childopts)
	exec_jkubernetes_class(
        "org.gwisoft.jkubernetes.daemon.kube.KubeServer",
        jvmtype="-server -Xms256m -Xmx256m",
        sysdirs=[JKUBERNETES_CONF_DIR, JKUBERNETES_DIR + "/bin",CUSTOM_CONF_FILE],
        args=args,
        childopts=childopts,
        isBackgroundRun="true")

def kubelet(args):
    """
    kubectl kubelet
    """
    pass

    childopts = get_client_customopts() + get_exclude_jars()
    print ("childopts=")
    print (childopts)
    exec_jkubernetes_class(
        "org.gwisoft.jkubernetes.daemon.kubelet.Kubelet",
        jvmtype="-server -Xms256m -Xmx256m",
        sysdirs=[JKUBERNETES_CONF_DIR, JKUBERNETES_DIR + "/bin",CUSTOM_CONF_FILE],
        args=args,
        childopts=childopts,
        isBackgroundRun="true")

def delete(args):
    """
    kubectl delete -f ***.yaml
    """
    pass

    args = parse_client_createopts(args)

    childopts = get_client_customopts() + get_exclude_jars() + get_client_createopts()
    print ("childopts=")
    print (childopts)
    exec_jkubernetes_class(
        "org.gwisoft.jkubernetes.kubectl.KubectlDelete",
        jvmtype="-server -Xms256m -Xmx256m",
        sysdirs=[JKUBERNETES_CONF_DIR, JKUBERNETES_DIR + "/bin",CUSTOM_CONF_FILE],
        args=args,
        childopts=childopts,
        isBackgroundRun="false")

def rollingUpdate(args):
    """
    kubectl rolling-update [old topology name] -f ***.yaml
    """
    pass

    args = parse_client_createopts(args)

    childopts = get_client_customopts() + get_exclude_jars() + get_client_createopts()
    print ("childopts=")
    print (childopts)
    exec_jkubernetes_class(
        "org.gwisoft.jkubernetes.kubectl.KubectlRollingUpdate",
        jvmtype="-server -Xms256m -Xmx256m",
        sysdirs=[JKUBERNETES_CONF_DIR, JKUBERNETES_DIR + "/bin",CUSTOM_CONF_FILE],
        args=args,
        childopts=childopts,
        isBackgroundRun="false")

def replace(args):
    """
    kubectl replace -f ***.yaml
    """
    pass

    args = parse_client_createopts(args)

    childopts = get_client_customopts() + get_exclude_jars() + get_client_createopts()
    print ("childopts=")
    print (childopts)
    exec_jkubernetes_class(
        "org.gwisoft.jkubernetes.kubectl.KubectlReplace",
        jvmtype="-server -Xms256m -Xmx256m",
        sysdirs=[JKUBERNETES_CONF_DIR, JKUBERNETES_DIR + "/bin",CUSTOM_CONF_FILE],
        args=args,
        childopts=childopts,
        isBackgroundRun="false")

def get(args):
    """
    kubectl get po [topology name]
    """
    pass

    childopts = get_client_customopts() + get_exclude_jars()
    print ("childopts=")
    print (childopts)
    exec_jkubernetes_class(
        "org.gwisoft.jkubernetes.kubectl.KubectlGet",
        jvmtype="-server -Xms256m -Xmx256m",
        sysdirs=[JKUBERNETES_CONF_DIR, JKUBERNETES_DIR + "/bin",CUSTOM_CONF_FILE],
        args=args,
        childopts=childopts,
        isBackgroundRun="false")

def get_client_createopts():
	ret = (" -Dkubernetes.create.yaml=" + JKUBERNETES_CREATE_YAML_PATH + " -Dkubernetes.apiserver.address=" + API_SERVER_ADDRESS)
	return ret

def parse_client_createopts(args):
	print ("parse_client_createopts=")
	print (args)
	curr = args
	curr.reverse()
	args_list = []
	while len(curr) > 0:
		token = curr.pop()
		print (token == "-f")
		if token == "-f":
			global JKUBERNETES_CREATE_YAML_PATH
			JKUBERNETES_CREATE_YAML_PATH = curr.pop()
		else:
			args_list.append(token)
	print (args_list)
	return 	args_list

def exec_jkubernetes_class(klass, jvmtype="-server", sysdirs=[], args=[], childopts="",isBackgroundRun=""):

    args_str = " ".join(args)

    command = "java " + " -Dkubernetes.home=" + JKUBERNETES_DIR + " " + get_config_opts() + " " + childopts + " -cp " + get_classpath(sysdirs) + " " + klass + " " + args_str

    print ("Running: " + command)
    global STATUS
    STATUS = os.execvp("java", filter_array(command.split(" ")))

#系统自定义的配置入参
def get_client_customopts():
    ret = ("")
    """
    ret = (" -Dkubernetes.root.logger=INFO,stdout -Dlogback.configurationFile=" + JKUBERNETES_DIR +
           "/conf/client_logback.xml -Dlog4j.configuration=File:" + JKUBERNETES_DIR +
           "/conf/client_log4j.properties")
    """
    return ret

def get_classpath(extrajars):
    ret = []
    ret.extend(extrajars)
    ret.extend(get_jars_full(JKUBERNETES_DIR))
    ret.extend(get_jars_full(JKUBERNETES_DIR + "/lib"))
    ret.extend(INCLUDE_JARS)
    return normclasspath(":".join(ret))

def main():
	if len(sys.argv) <= 1:
		print_usage()
		sys.exit(-1)

	global CONFIG_OPTS
	config_list, args = parse_config_opts_and_args(sys.argv[1:])
	parse_config_opts(config_list)
	COMMAND = args[0]
	ARGS = args[1:]
	if COMMANDS.get(COMMAND) == None:
		unknown_command(COMMAND)
		sys.exit(-1)
	if len(ARGS) != 0 and ARGS[0] == "help":
		print_usage(COMMAND)
		sys.exit(0)
	try:
		(COMMANDS.get(COMMAND,"help"))(ARGS)
	except Exception as msg:
		print(msg)
		print_usage(COMMAND)
		sys.exit(-1)
	sys.exit(STATUS)

COMMANDS = {"create": create,"kube":kube,"kubelet":kubelet,"delete":delete,"rolling-update":rollingUpdate,"replace":replace,"get":get}

if __name__ == "__main__":
    #check_java()
    main()


text:
def phovea(registry):
  """
  register extension points
  :param registry:
  """
  # generator-phovea:begin
  registry.append('user_stores', 'phovea_security_store_ldap', 'phovea_security_store_ldap.ldap', {})

  registry.append('command', 'ldap', 'phovea_security_store_ldap.main', {})
  # generator-phovea:end
  pass

def phovea_config():
  """
  :return: file pointer to config file
  """
  from os import path
  here = path.abspath(path.dirname(__file__))
  config_file = path.join(here, 'config.json')
  return config_file if path.exists(config_file) else None


text:
<?php
namespace bunq\Model\Generated\Object;

use bunq\Model\Core\BunqModel;

/**
 * @generated
 */
class BunqMeMerchantAvailable extends BunqModel
{
    /**
     * A merchant type supported by bunq.me.
     *
     * @var string
     */
    protected $merchantType;

    /**
     * Whether or not the merchant is available for the user.
     *
     * @var bool
     */
    protected $available;

    /**
     * A merchant type supported by bunq.me.
     *
     * @return string
     */
    public function getMerchantType()
    {
        return $this->merchantType;
    }

    /**
     * @deprecated User should not be able to set values via setters, use
     * constructor.
     *
     * @param string $merchantType
     */
    public function setMerchantType($merchantType)
    {
        $this->merchantType = $merchantType;
    }

    /**
     * Whether or not the merchant is available for the user.
     *
     * @return bool
     */
    public function getAvailable()
    {
        return $this->available;
    }

    /**
     * @deprecated User should not be able to set values via setters, use
     * constructor.
     *
     * @param bool $available
     */
    public function setAvailable($available)
    {
        $this->available = $available;
    }

    /**
     * @return bool
     */
    public function isAllFieldNull()
    {
        if (!is_null($this->merchantType)) {
            return false;
        }

        if (!is_null($this->available)) {
            return false;
        }

        return true;
    }
}