text:
/*
 * This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file
 * at the root of this project for more details.
 */
package io.github.nucleuspowered.nucleus.modules.rules.config;

import io.github.nucleuspowered.nucleus.core.services.interfaces.annotation.configuratehelper.LocalisedComment;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Setting;

@ConfigSerializable
public class RulesConfig {

    @Setting(value = "rules-title")
    @LocalisedComment("config.rules.title")
    private String rulesTitle = "&6Server Rules";

    public String getRulesTitle() {
        return this.rulesTitle;
    }
}


text:
package com.github.czyzby.lml.parser.impl.attribute.scroll;

import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane;
import com.github.czyzby.lml.parser.LmlParser;
import com.github.czyzby.lml.parser.tag.LmlAttribute;
import com.github.czyzby.lml.parser.tag.LmlTag;

/** See {@link ScrollPane#setForceScroll(boolean, boolean)}. Sets only Y value. Mapped to "forceScrollY", "forceY".
 *
 * @author MJ */
public class ScrollForceYLmlAttribute implements LmlAttribute<ScrollPane> {
    @Override
    public Class<ScrollPane> getHandledType() {
        return ScrollPane.class;
    }

    @Override
    public void process(final LmlParser parser, final LmlTag tag, final ScrollPane actor,
            final String rawAttributeData) {
        actor.setForceScroll(actor.isForceScrollX(), parser.parseBoolean(rawAttributeData, actor));
    }
}

redpajama_set_name: RedPajamaGithub


text:
module.exports = {
	/**
	 * grunt-wp-i18n
	 *
	 * Internationalize WordPress themes and plugins.
	 *
	 * @link https://www.npmjs.com/package/grunt-wp-i18n
	 */
	prod: {
		options: {
			domainPath: '/i18n/languages/',
			potFilename: '<%= package.name %>.pot',
			type: 'wp-plugin'
		}
	}
};


text:
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.options;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * Provides functionality to import a scheme from another non-IntelliJ format.
 *
 * @author Rustam Vishnyakov
 */
public interface SchemeImporter <T extends Scheme> {

  /**
   * @return An extension of a source file which can be imported, for example, "xml".
   */
  String @NotNull [] getSourceExtensions();

  /**
   * Import a scheme from the given virtual file
   * @param project project
   * @param selectedFile  The input file to import from.
   * @param currentScheme source scheme to be updated or to base import on
   * @param schemeFactory The factory to create a scheme with a given name. Importer implementation should use this method
   *                      to create a scheme to which it will save imported values.
   * @return created/updated scheme, or null if action was cancelled
   * @see SchemeFactory
   */
  @Nullable
  T importScheme(@NotNull Project project,
                 @NotNull VirtualFile selectedFile,
                 @NotNull T currentScheme,
                 @NotNull SchemeFactory<T> schemeFactory) throws SchemeImportException;

  /**
   * Called after the scheme has been imported.
   *
   * @param scheme The imported scheme.
   * @return An information message to be displayed after import.
   */
  @Nullable
  default String getAdditionalImportInfo(@NotNull T scheme) {
    return null;
  }

  /**
   * @return File to import scheme. If {@code null}, file chooser is shown.
   */
  @Nullable
  default VirtualFile getImportFile() {
    return null;
  }
}


text:
package org.kie.workbench.common.dmn.client.editors.types.common.errors;

import com.google.gwtmockito.GwtMockitoTestRunner;
import org.jboss.errai.ui.client.local.spi.TranslationService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.workbench.common.dmn.client.editors.types.common.DataType;
import org.mockito.Mock;

import static org.junit.Assert.assertEquals;
import static org.kie.workbench.common.dmn.client.resources.i18n.DMNEditorConstants.NameIsBlankErrorMessage_RegularMessage;
import static org.kie.workbench.common.dmn.client.resources.i18n.DMNEditorConstants.NameIsBlankErrorMessage_StrongMessage;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

@RunWith(GwtMockitoTestRunner.class)
public class NameIsBlankErrorMessageTest {

    @Mock
    private TranslationService translationService;

    @Test
    public void testGetStrongMessage() {

        final DataType dataType = mock(DataType.class);
        final String expectedErrorMessage = "*Expected strong message.*";
        final NameIsBlankErrorMessage errorMessage = new NameIsBlankErrorMessage(translationService);

        when(translationService.format(NameIsBlankErrorMessage_StrongMessage)).thenReturn(expectedErrorMessage);

        final String actualErrorMessage = errorMessage.getStrongMessage(dataType);

        assertEquals(expectedErrorMessage, actualErrorMessage);
    }

    @Test
    public void testGetRegularMessage() {

        final String expectedErrorMessage = "Expected regular message.";
        final NameIsBlankErrorMessage errorMessage = new NameIsBlankErrorMessage(translationService);

        when(translationService.format(NameIsBlankErrorMessage_RegularMessage)).thenReturn(expectedErrorMessage);

        final String actualErrorMessage = errorMessage.getRegularMessage();

        assertEquals(expectedErrorMessage, actualErrorMessage);
    }
}


text:
package org.gradle.api.internal.artifacts.ivyservice.ivyresolve;

import org.gradle.api.artifacts.ComponentMetadata;
import org.gradle.api.artifacts.ivy.IvyModuleDescriptor;
import org.gradle.api.internal.artifacts.ivyservice.DefaultIvyModuleDescriptor;
import org.gradle.api.internal.artifacts.repositories.resolver.ComponentMetadataAdapter;
import org.gradle.internal.component.external.model.ivy.IvyModuleResolveMetadata;
import org.gradle.internal.component.external.model.ModuleComponentResolveMetadata;
import org.gradle.internal.resolve.result.BuildableModuleComponentMetaDataResolveResult;

class CachedMetadataProvider implements MetadataProvider {
    private final BuildableModuleComponentMetaDataResolveResult cachedResult;
    private final ComponentMetadata cachedComponentMetadata;
    private final boolean usable;

    CachedMetadataProvider(BuildableModuleComponentMetaDataResolveResult result) {
        cachedResult = result;
        usable = cachedResult.getState() == BuildableModuleComponentMetaDataResolveResult.State.Resolved;
        if (usable) {
            cachedComponentMetadata = new ComponentMetadataAdapter(cachedResult.getMetaData());
        } else {
            cachedComponentMetadata = null;
        }
    }

    @Override
    public ComponentMetadata getComponentMetadata() {
        return cachedComponentMetadata;
    }

    @Override
    public IvyModuleDescriptor getIvyModuleDescriptor() {
        ModuleComponentResolveMetadata metaData = cachedResult.getMetaData();
        if (metaData instanceof IvyModuleResolveMetadata) {
            IvyModuleResolveMetadata ivyMetadata = (IvyModuleResolveMetadata) metaData;
            return new DefaultIvyModuleDescriptor(ivyMetadata.getExtraAttributes(), ivyMetadata.getBranch(), ivyMetadata.getStatus());
        }
        return null;
    }

    @Override
    public boolean isUsable() {
        return usable;
    }
}


text:
title: Backups and disaster recovery
description: Learn how to backup your Docker Universal Control Plane cluster, and to recover your cluster from an existing backup.
keywords:
- docker, ucp, backup, restore, recovery
---

When you decide to start using Docker Universal Control Plane on a production
setting, you should
[configure it for high availability](index.md).

The next step is creating a backup policy and disaster recovery plan.

## Backup policy

Docker UCP nodes persist data using [named volumes](../architecture.md).

As part of your backup policy you should regularly create backups of the
controller nodes. Since the nodes used for running user containers don't
persist data, you can decide not to create any backups for them.

To perform a backup of a UCP controller node, use the `docker/ucp backup`
command. This creates a tar archive with the contents of the volumes used by
UCP on that node, and streams it to stdout.

To create a consistent backup, the backup command temporarily stops the UCP
containers running on the node where the backup is being performed. User
containers and services are not affected by this.

To have minimal impact on your business, you should:

* Schedule the backup to take place outside business hours.
* Configure UCP for high availability. This allows load-balancing user requests
across multiple UCP controller nodes.

## Backup command

The example below shows how to create a backup of a UCP controller node:

```bash
# Create a backup, encrypt it, and store it on /tmp/backup.tar
$ docker run --rm -i --name ucp \
  -v /var/run/docker.sock:/var/run/docker.sock \
  docker/ucp backup --interactive \
  --passphrase "secret" > /tmp/backup.tar

# Decrypt the backup and list its contents
$ gpg --decrypt /tmp/backup.tar | tar --list

Enter passphrase: secret

/ucp-client-root-ca/
./ucp-client-root-ca/cert.pem
./ucp-client-root-ca/config.json
./ucp-client-root-ca/key.pem
./ucp-cluster-root-ca/
# output snipped
```

## Restore command

The example below shows how to restore a UCP controller node from an existing
backup:

```bash
$ docker run --rm -i --name ucp \
  -v /var/run/docker.sock:/var/run/docker.sock  \
  docker/ucp restore < backup.tar
```

The restore command may also be invoked in interactive mode:

```bash
$ docker run --rm -i --name ucp \
  -v /var/run/docker.sock:/var/run/docker.sock \
  -v /path/to/backup.tar:/config/backup.tar \
  docker/ucp restore -i
```

## Restore your cluster

The restore command can be used to create a new UCP cluster from a backup file.
After the restore operation is complete, the following data will be copied from
the backup file:
* Users, Teams and Permissions.
* Cluster Configuration, such as the default Controller Port or the KV store
timeout.
* DDC Subscription License.
* Options on Scheduling, Content Trust, Authentication Methods and Reporting.

The restore operation may be performed against any Docker Engine, regardless of
swarm membership, as long as the target Engine is not already managed by a UCP
installation. If the Docker Engine is already part of a swarm, that swarm and
all deployed containers and services will be managed by UCP after the restore
operation completes.

As an example, if you have a cluster with three controller nodes, A, B, and C,
and your most recent backup was of node A:

1. Uninstall UCP from the swarm using the `uninstall-ucp` operation.
2. Restore one of the swarm managers, such as node B, using the most recent
   backup from node A.
3. Wait for all nodes of the swarm to become healthy UCP nodes.

You should now have your UCP cluster up and running.

Additionally, in the event where half or more controller nodes are lost and
cannot be recovered to a healthy state, the system can only be restored through
the following disaster recovery procedure. It is important to note that this
proceedure is not guaranteed to succeed with no loss of either swarm services or
UCP configuration data:

1. On one of the remaining manager nodes, perform `docker swarm init
   --force-new-cluster`. This will instantiate a new single-manager swarm by
   recovering as much state as possible from the existing manager. This is a
   disruptive operation and any existing tasks will be either terminated or
   suspended.
2. Obtain a backup of one of the remaining manager nodes if one is not already
   available.
3. Perform a restore operation on the recovered swarm manager node.
4. For all other nodes of the cluster, perform a `docker swarm leave --force`
   and then a `docker swarm join` operation with the cluster's new join-token.
5. Wait for all nodes of the swarm to become healthy UCP nodes.

## Where to go next

* [Set up high availability](index.md)
* [UCP architecture](../architecture.md)


text:
package org.apache.commons.ognl.internal;

import org.apache.commons.ognl.internal.entry.PermissionCacheEntry;
import org.apache.commons.ognl.internal.entry.PermissionCacheEntryFactory;
import org.apache.commons.ognl.test.objects.Bean2;
import org.junit.Test;

import java.security.Permission;

import static junit.framework.Assert.assertNotNull;

/**
 * User: Maurizio Cucchiara
 * Date: 10/15/11
 * Time: 8:00 AM
 */
public class PermissionCacheTest
{
    ConcurrentHashMapCache<PermissionCacheEntry, Permission> cache =
        new ConcurrentHashMapCache<PermissionCacheEntry, Permission>( new PermissionCacheEntryFactory());

    @Test
    public void testGet( )
        throws Exception
    {

        getPermission( new PermissionCacheEntry( Bean2.class.getMethod( "getBean3" ) ) );
        getPermission( new PermissionCacheEntry( Bean2.class.getMethod( "getId" ) ) );
    }

    private void getPermission( PermissionCacheEntry entry )
        throws CacheException
    {
        Permission permission = cache.get( entry );
        assertNotNull( permission );
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bot. univ. 2:327. 1771 (A. N. Duchesne, Hist. nat. frais. 145. 1766, as "races principales")

#### Original name
null

### Remarks
null


text:
<?php

namespace front\assets;

use yii\web\AssetBundle;

class SiteAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
        'css/site.css',
    ];
    public $js = [
        // ...
    ];
    public $depends = [
        'yii\web\YiiAsset',
        'yii\web\JqueryAsset',
        'yii\bootstrap\BootstrapAsset',
        'yii\bootstrap\BootstrapPluginAsset'
    ];
}


text:
package gomniauth

import (
	"github.com/outrightmental/go-omniauth/test"
	"github.com/outrightmental/go-objx"
	"github.com/stretchr/testify/assert"
	"testing"
)

func TestProviderPublicData(t *testing.T) {

	provider := new(test.TestProvider)

	provider.On("Name").Return("TestName")
	provider.On("DisplayName").Return("TestDisplayName")

	publicData, _ := ProviderPublicData(provider, objx.MSI("loginpathFormat", "~auth/%s/login"))
	publicDataMap := publicData.(map[string]interface{})

	assert.Equal(t, publicDataMap["name"], "TestName")
	assert.Equal(t, publicDataMap["display"], "TestDisplayName")
	assert.Equal(t, publicDataMap["loginpath"], "~auth/TestName/login")

}


text:
import paddle
import numpy as np

from .utils import np2torch, np2paddle, paddle2np, torch2np, check_print_diff

def check_data(data1: dict, data2: dict):
    for k in data1:
        if k not in data2:
            assert k in data2, 'k in data1 but not found in data2'.format(
                k, data2)

    for k in data2:
        if k not in data1:
            assert k in data1, 'k in data2 but not found in data1'.format(
                k, data2.keys())

def compute_diff(data1: dict, data2: dict):
    out_dict = {}
    for k in data1:
        assert k in data2
        sub_data1, sub_data2 = data1[k], data2[k]
        assert type(sub_data1) == type(sub_data2)
        if isinstance(sub_data1, dict):
            out = compute_diff(sub_data1, sub_data2)
            out_dict[k] = out
        elif isinstance(sub_data1, np.ndarray):
            if sub_data1.shape != sub_data2.shape and sub_data1.transpose(
            ).shape == sub_data2.shape:
                print('transpose sub_data1')
                sub_data1 = sub_data1.transpose()
            diff = np.abs(sub_data1 - sub_data2)
            out_dict[k] = {
                'mean': diff.mean(),
                'max': diff.max(),
                'min': diff.min()
            }
        else:
            raise NotImplementedError
    return out_dict

def compare_forward(torch_model,
                    paddle_model: paddle.nn.Layer,
                    input_dict: dict,
                    diff_threshold: float=1e-6,
                    diff_method: str='mean'):
    torch_input = np2torch(input_dict)
    paddle_input = np2paddle(input_dict)

    torch_model.eval()
    paddle_model.eval()
    torch_out = torch_model(**torch_input)
    paddle_out = paddle_model(**paddle_input)

    diff_dict = compute_diff(torch2np(torch_out), paddle2np(paddle_out))
    passed = check_print_diff(
        diff_dict,
        diff_method=diff_method,
        diff_threshold=diff_threshold,
        print_func=print)
    if passed:
        print('diff check passed')
    else:
        print('diff check failed')

def compare_loss_and_backward(torch_model,
                              paddle_model: paddle.nn.Layer,
                              torch_loss,
                              paddle_loss: paddle.nn.Layer,
                              input_dict: dict,
                              lr: float=1e-3,
                              steps: int=10,
                              diff_threshold: float=1e-6,
                              diff_method: str='mean'):
    import torch

    torch_input = np2torch(input_dict)
    paddle_input = np2paddle(input_dict)

    torch_model.eval()
    paddle_model.eval()

    torch_optim = torch.optim.SGD(params=torch_model.parameters(), lr=lr)
    paddle_optim = paddle.optimizer.SGD(parameters=paddle_model.parameters(),
                                        learning_rate=lr)

    for i in range(steps):
        # paddle
        paddle_outputs = paddle_model(**paddle_input)
        paddle_loss_value = paddle_loss(paddle_input, paddle_outputs)
        paddle_loss_value['loss'].backward()
        paddle_optim.step()

        paddle_grad_dict = {'loss': paddle_loss_value['loss'].numpy()}
        for name, parms in paddle_model.named_parameters():
            if not parms.stop_gradient and parms.grad is not None:
                paddle_grad_dict[name] = parms.grad.numpy()
        paddle_optim.clear_grad()

        # torch
        torch_outputs = torch_model(**torch_input)
        torch_loss_value = torch_loss(torch_input, torch_outputs)
        torch_loss_value['loss'].backward()
        torch_optim.step()

        torch_grad_dict = {'loss': torch_loss_value['loss'].detach().numpy()}
        for name, parms in torch_model.named_parameters():
            if parms.requires_grad and parms.grad is not None:
                torch_grad_dict[name] = parms.grad.numpy()
        torch_optim.zero_grad()

        # compare
        diff_dict = compute_diff(paddle_grad_dict, torch_grad_dict)
        passed = check_print_diff(
            diff_dict,
            diff_method=diff_method,
            diff_threshold=diff_threshold,
            print_func=print)
        if passed:
            print('diff check passed in iter {}'.format(i))
        else:
            print('diff check failed in iter {}'.format(i))
            return
    print('diff check passed')


text:
<?php

namespace SocialUno\Model;

use Doctrine\ORM\Mapping as ORM;

/** @ORM\Entity
 *   @ORM\Table(name="amizades")
 */
class Amizades
{

    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     */
    protected $id;

    /**
     * @ORM\ManyToOne(targetEntity="Usuario")
     * @ORM\JoinColumn(name="id_usuario", referencedColumnName="id")
     *
     * @var \SocialUno\Model\Usuario
     */
    protected $usuario;

    /**
     * @ORM\ManyToOne(targetEntity="Usuario")
     * @ORM\JoinColumn(name="id_amigo", referencedColumnName="id")
     *
     * @var \SocialUno\Model\Usuario
     */
    protected $amizade;

    /**
     * @ORM\ManyToOne(targetEntity="StatusAmizade")
     * @ORM\JoinColumn(name="id_status_amizade", referencedColumnName="id")
     *
     * @var \SocialUno\Model\StatusAmizade
     */
    protected $status_amizade;

    function getId()
    {
        return $this->id;
    }

    function getUsuario()
    {
        return $this->usuario;
    }

    function getAmizade()
    {
        return $this->amizade;
    }

    function getStatusAmizade()
    {
        return $this->status_amizade;
    }

    function setUsuario($usuario)
    {
        $this->usuario = $usuario;
    }

    function setAmizade($amizade)
    {
        $this->amizade = $amizade;
    }

    function setStatusAmizade($status_amizade)
    {
        $this->status_amizade = $status_amizade;
    }
}


text:
package v1alpha1

import (
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
)

var (
	SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes)
	AddToScheme   = SchemeBuilder.AddToScheme
)

// GroupName is the group name used in this package.
const GroupName = "metacontroller.k8s.io"

// SchemeGroupVersion is the group version used to register these objects.
var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1alpha1"}

// Resource takes an unqualified resource and returns a Group-qualified GroupResource.
func Resource(resource string) schema.GroupResource {
	return SchemeGroupVersion.WithResource(resource).GroupResource()
}

// addKnownTypes adds the set of types defined in this package to the supplied scheme.
func addKnownTypes(scheme *runtime.Scheme) error {
	scheme.AddKnownTypes(SchemeGroupVersion,
		&CompositeController{},
		&CompositeControllerList{},
		&DecoratorController{},
		&DecoratorControllerList{},
		&ControllerRevision{},
		&ControllerRevisionList{},
	)
	metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
	return nil
}


text:
#include <visp3/visual_features/vpFeatureBuilder.h>
#include <visp3/vs/vpServo.h>
#include <visp3/robot/vpSimulatorCamera.h>
#include <visp3/gui/vpDisplayX.h>
#include <visp3/gui/vpDisplayOpenCV.h>
#include <visp3/gui/vpDisplayGDI.h>
#include <visp3/gui/vpProjectionDisplay.h>
#include <visp3/vs/vpServoDisplay.h>
#include <visp3/robot/vpWireFrameSimulator.h>
#include <ros/ros.h>
#include <geometry_msgs/PoseStamped.h>
#include <geometry_msgs/Pose.h>
#include <geometry_msgs/Point.h>
#include <image_transport/image_transport.h>
#include "std_msgs/String.h"
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/opencv.hpp>

#include <iostream>
#include <cstdlib>
#include <fstream>

//#include <conio.h>
#include <math.h>
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <stdlib.h>
 #include <arpa/inet.h>
#define BUFLEN 512  //Max length of buffer
#define PORT 8888   //The port on which to listen for incoming data

#define DofNum 2
using namespace std;

void die(char *s)
{
    perror(s);
    exit(1);
}

 std::vector<float> convert2Float(std::vector<double> v)
 {
   std::vector<float> t;
   for(int i=0;i<v.size();i++)
     t.push_back((float)v[i]);
   return t;
}

void printOutStdVector(std::vector<double> v)
{
  cout<<"print out v:"<<endl;
  for(int i=0;i<v.size();i++)
  {
    cout<<v.at(i)<<"  ";
  }
  cout<<endl;
}

//"[0.53196,1.39524,1.09715,0.955755,-4.0458,-1.292023,-0.000904]"
//"[0.1037,1.167,1.3004,1.27976,-4.7181,-1.54276,-0.0039043]"

int main(int argc, char **argv )
{
 int udpSocket, nBytes;
  char buffer[1024];
  struct sockaddr_in serverAddr, clientAddr;
  struct sockaddr_storage serverStorage;
  socklen_t addr_size, client_addr_size;
  int i;

  /*Create UDP socket*/
  udpSocket = socket(PF_INET, SOCK_DGRAM, 0);

  /*Configure settings in address struct*/
  serverAddr.sin_family = AF_INET;
  serverAddr.sin_port = htons(2500);
  serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
  memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);

  /*Bind socket with address struct*/
  bind(udpSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr));

  /*Initialize size variable to be used later on*/
  addr_size = sizeof serverStorage;

  	//initialize the ROS system and become a node.
	ros::init(argc, argv, "chris_calibrator");
	ros::NodeHandle nh;
	//ros::Subscriber subP = nh.subscribe("/chris_tracker/currentPoint", 1000, currentPointCallback);
	//ros::Subscriber subPd = nh.subscribe("/chris_tracker/desiredPoint", 1000, desiredPointCallback);
        ros::Publisher pubTask = nh.advertise<std_msgs::String>("/chris_tracker/taskFinished", 1);

	//ros::ServiceClient Joint_move_client = nh.serviceClient<wam_srvs::JointMove>("/zeus/wam/joint_move");

       cout << "Press any key to continue..." << endl;
       getchar();
     // Joint_move_client.call(mv_srv);///////////////////////////////////////////////////

    // cout << "Press any key to continue the servoing loop..." << endl;
    ///  getchar();
      ros::Rate loop_rate(3);//////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    while(ros::ok())
    {
      ros::spinOnce();

       try {
	 cout << "UDP server start listening, 127.0.0.1, 2500..." << endl;
	/* Try to receive any incoming UDP datagram. Address and port of
      requesting client will be stored on serverStorage variable */
    nBytes = recvfrom(udpSocket,buffer,1024,0,(struct sockaddr *)&serverStorage, &addr_size);

    /*Convert message received to uppercase*/
    for(i=0;i<nBytes-1;i++)
      buffer[i] = toupper(buffer[i]);

    /*Send uppercase message back to client, using serverStorage as the address*/
    sendto(udpSocket,buffer,nBytes,0,(struct sockaddr *)&serverStorage,addr_size);

      // cout << "Dig into:-->>" << endl;
       //getchar();
      //Joint_move_client.call(mv_srv3);
    	//ros::spinOnce();

        //loop_rate.sleep();
        //waitKey(0);
       }
      catch(vpException &e) {
          std::cout << "Catch an exception: " << e << std::endl;
       }
    }
}


text:
"""  Frost Number by Nelson and Outcalt 1983.
DOI: 10.2307/1551363. http://www.jstor.org/stable/1551363

*The MIT License (MIT)*
Copyright (c) 2016 permamodel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*

"""
from __future__ import print_function

import numpy as np
from permamodel.components import perma_base
from permamodel.components import frost_number

class BmiFrostnumberMethod(perma_base.PermafrostComponent):
    """ Implement BMI interface to the Nelson-Outcalt Frost number code """
    def __init__(self):
        """ This overwrites __init__() method of PermafrostComponent """
        self._name = "Permamodel Frostnumber Component"
        self._model = None
        self.model = None
        self._values = {}
        self._var_units = {}
        self._grids = {}
        self._grid_type = {}

        self._att_map = {
            'model_name': 'PermaModel_frostnumber_method',
            'version':            '0.1',
            'author_name':        'J. Scott Stewart and Elchin Jafarov',
            'grid_type':          'none',
            'time_step_type':     'fixed',
            'step_method':        'explicit',
            #-------------------------------------------------------------
            'comp_name':          'frostnumber',
            'model_family':       'PermaModel',
            'cfg_extension':      '_frostnumber_model.cfg',
            'cmt_var_prefix':     '/input/',
            'gui_yaml_file':      '/input/frostnumber_model.yaml',
            'time_units':         'years'}

        self._input_var_names = (
            'atmosphere_bottom_air__time_min_of_temperature',
            'atmosphere_bottom_air__time_max_of_temperature',
        )

        self._output_var_names = (
            'frostnumber__air',            # Air Frost number
            'frostnumber__surface',        # Surface Frost number
            'frostnumber__stefan')        # Stefan Frost number

        self._var_name_map = {
            'atmosphere_bottom_air__time_min_of_temperature': 'T_air_min',
            'atmosphere_bottom_air__time_max_of_temperature': 'T_air_max',
            'frostnumber__air': 'air_frost_number',
            'frostnumber__surface': 'surface_frost_number',
            'frostnumber__stefan': 'stefan_frost_number',
        }

        self._var_units_map = {
            'atmosphere_bottom_air__time_min_of_temperature': 'deg_C',
            'atmosphere_bottom_air__time_max_of_temperature': 'deg_C',
            'frostnumber__air': '1',
            'frostnumber__surface': '1',
            'frostnumber__stefan': '1',
        }

    def initialize(self, cfg_file=None):
        """ this overwrites initialize() in PermafrostComponent """
        self._model = frost_number.FrostnumberMethod()
        # This allows testing to not use protected access to _model
        self.model = self._model

        self._model.initialize_from_config_file(cfg_file=cfg_file)
        self._model.initialize_frostnumber_component()

        # Verify that all input and output variable names are in the
        # variable name and the units map
        for varname in self._input_var_names:
            assert varname in self._var_name_map
            assert varname in self._var_units_map
        for varname in self._output_var_names:
            assert varname in self._var_name_map
            assert varname in self._var_units_map

        # Set the Frost Number grids, based on input and output variables
        # Set the names and types of the grids
        gridnumber = 0
        for varname in self._input_var_names:
            self._grids[gridnumber] = varname
            self._grid_type[gridnumber] = 'scalar'
            gridnumber += 1
        for varname in self._output_var_names:
            self._grids[gridnumber] = varname
            self._grid_type[gridnumber] = 'scalar'
            gridnumber += 1

        # Set the internal (frost number) variables that correspond
        # to the input and output variable names
        # Note: since we used Topoflow's _var_name_map for this, it is that
        self._values = {
            # These are the links to the model's variables and
            # should be consistent with _var_name_map
            'atmosphere_bottom_air__time_min_of_temperature': self._model.T_air_min,
            'atmosphere_bottom_air__time_max_of_temperature': self._model.T_air_max,
            'frostnumber__air':         self._model.air_frost_number,
            'frostnumber__surface':     self._model.surface_frost_number,
            'frostnumber__stefan':      self._model.stefan_frost_number,
        }

    def get_attribute(self, att_name):
        try:
            return self._att_map[att_name.lower()]
        except KeyError:
            raise KeyError("No attribute %s" % str(att_name))

    def get_input_var_names(self):
        #--------------------------------------------------------
        # Note: These are currently variables needed from other
        #       components vs. those read from files or GUI.
        #--------------------------------------------------------
        return self._input_var_names

    def get_output_var_names(self):

        return self._output_var_names

    def get_var_name(self, long_var_name):

        return self._var_name_map[long_var_name]

    def get_var_units(self, long_var_name):
        return self._var_units_map[long_var_name]

    def get_var_location(self, long_var_name):
        return "node"

    def update(self):
        """ This overwrites update() in Permafrost component
            and has different number of arguments """
        # Calculate the new frost number values
        self._model.update()
        self._values['frostnumber__air'] = self._model.air_frost_number

    def update_frac(self, time_fraction):
        """ This is for BMI compliance """
        # Only increment the time by a partial time step
        # Currently, only non-fractions are allowed, but this could be
        #  0, 1, 2, ...
        self._model.update(frac=time_fraction)
        self._values['frostnumber__air'] = self._model.air_frost_number

    def get_year_from_timestep(self, this_timestep):
        """ given the timestep, return the year """
        return int(self.get_time_step() * this_timestep + self._model.start_year)

    def update_until(self, stop_time):
        """ BMI-required, run until a specified time """
        stop_year = self.get_year_from_timestep(stop_time)

        # Ensure that stop_year is at least the current year
        if stop_year < self._model.year:
            print("Warning: update_until year is less than current year")
            print("  no update run")
            return

        if stop_year > self._model.end_year:
            print("Warning: update_until year was greater than end_year")
            print("  setting stop_year to end_year")
            stop_year = self._model.end_year

        # Implement the loop to update until stop_year
        # Note: running for the first timestep is a special case,
        #       for which the timestep should not be updated
        if stop_year == self.get_year_from_timestep(self.get_start_time()):
            # print("This year is end_year, so update_frac(0)")
            self.update_frac(0)
        else:
            year = self._model.year
            while year < stop_year:
                self.update()
                year = self._model.year

    def finalize(self):
        """ BMI-required, wrap up all things including writing output """
        # Write output last output
        self._model.write_output_to_file()

    def get_start_time(self):
        """ BMI-required although all WMT models start at time=0 """
        return 0.0

    def get_current_time(self):
        """ Number of timesteps (years) since start of model run """
        return float(self._model.year - self._model.start_year)

    def get_end_time(self):
        """ Number of timestesp (years) so that last year is included """
        return float(self._model.end_year - self._model.start_year)

    def get_grid_type(self, grid_number):
        """ BMI: inquire about the type of this grid """
        return self._grid_type[grid_number]

    def get_time_step(self):
        """ BMI: return the time step value (years) """
        return float(self._model.dt)

    def get_value_ref(self, var_name):
        """Reference to values.

        Parameters
        ----------
        var_name : str
            Name of variable as CSDMS Standard Name.

        Returns
        -------
        array_like
            Value array.
        """
        return self._values[var_name]

    def set_value(self, var_name, new_var_values):
        """ BMI: allow external set-access to model variable """
        array = getattr(self._model, self._var_name_map[var_name])
        if len(array) == 1:
            array[0] = new_var_values
        else:
            array[int(self._model.year - self._model.start_year) + 1] = new_var_values

        # setattr(self._model, self._var_name_map[var_name], new_var_values)
        # self._values[var_name] = new_var_values

    def set_value_at_indices(self, var_name, new_var_values, indices):
        """ BMI: allow external set-access to model array variable """
        self.get_value_ref(var_name).flat[indices] = new_var_values

    def get_var_itemsize(self, var_name):
        """ BMI: determine how many bytes a variable uses """
        return np.asarray(self.get_value_ref(var_name)).flatten()[0].nbytes

    def get_value_at_indices(self, var_name, indices):
        """ BMI: allow external get-access to model array variable """
        return self.get_value_ref(var_name).take(indices)

    def get_var_nbytes(self, var_name):
        """ BMI: number of bytes of a variable """
        return np.asarray(self.get_value_ref(var_name)).nbytes

    def get_value(self, var_name, out=None):
        """Copy of values.

        Parameters
        ----------
        var_name : str
            Name of variable as CSDMS Standard Name.

        Returns
        -------
        array_like
            Copy of values.
        """
        # Original version: from bmi_heat.py
        #return self.get_value_ref(var_name).copy()

        # Version to convert to numpy array for bmi-tester compliance
        # Note: converting to np arrays on the fly here
        # Note: float values don't have a copy() function
        #try:
        #    return np.array(self.get_value_ref(var_name).copy())
        #except AttributeError:
        #    return np.array(self.get_value_ref(var_name))
        if out is None:
            out = self.get_value_ref(var_name).copy()
        else:
            out[...] = self.get_value_ref(var_name)
        return out

    def get_var_type(self, var_name):
        """Data type of variable.

        Parameters
        ----------
        var_name : str
            Name of variable as CSDMS Standard Name.

        Returns
        -------
        str
            Data type.
        """
        return str(self.get_value_ref(var_name).dtype)

    def get_component_name(self):
        """ BMI: provide this component's name """
        return self._name

    # Copied from bmi_heat.py
    def get_var_grid(self, var_name):
        """Grid id for a variable.

        Parameters
        ----------
        var_name : str
            Name of variable as CSDMS Standard Name.

        Returns
        -------
        int
            Grid id.
        """
        for grid_id, var_name_list in self._grids.items():
            if var_name in var_name_list:
                return grid_id

    def get_grid_size(self, grid_id):
        """Size of grid.

        Parameters
        ----------
        grid_id : int
            Identifier of a grid.

        Returns
        -------
        int
            Size of grid.

        """
        return 1

    def get_grid_rank(self, grid_id):
        """Rank of grid.

        Parameters
        ----------
        grid_id : int
            Identifier of a grid.

        Returns
        -------
        int
            Rank of grid.
        """
        return 0


text:
package io.crnk.core.engine.information.resource;

import io.crnk.core.engine.information.bean.BeanAttributeInformation;
import io.crnk.core.resource.annotations.JsonIncludeStrategy;
import io.crnk.core.resource.annotations.LookupIncludeBehavior;
import io.crnk.core.resource.annotations.PatchStrategy;
import io.crnk.core.resource.annotations.RelationshipRepositoryBehavior;
import io.crnk.core.resource.annotations.SerializeType;

import java.util.Optional;

public class ResourceFieldInformationProviderBase implements ResourceFieldInformationProvider {

    protected ResourceInformationProviderContext context;

    @Override
    public void init(ResourceInformationProviderContext context) {
        this.context = context;
    }

    @Override
    public Optional<Boolean> isIgnored(BeanAttributeInformation attributeDesc) {
        return Optional.empty();
    }

    @Override
    public Optional<String> getJsonName(BeanAttributeInformation attributeDesc) {
        return Optional.empty();
    }

    @Override
    public Optional<Boolean> isPostable(BeanAttributeInformation attributeDesc) {
        return Optional.empty();
    }

    @Override
    public Optional<Boolean> isDeletable(BeanAttributeInformation attributeDesc) {
        return Optional.empty();
    }

    @Override
    public Optional<Boolean> isPatchable(BeanAttributeInformation attributeDesc) {
        return Optional.empty();
    }

    @Override
    public Optional<Boolean> isReadable(final BeanAttributeInformation attributeDesc) {
        return Optional.empty();
    }

    @Override
    public Optional<Boolean> isSortable(BeanAttributeInformation attributeDesc) {
        return Optional.empty();
    }

    @Override
    public Optional<Boolean> isFilterable(BeanAttributeInformation attributeDesc) {
        return Optional.empty();
    }

    @Override
    public Optional<ResourceFieldType> getFieldType(BeanAttributeInformation attributeDesc) {
        return Optional.empty();
    }

    @Override
    public Optional<String> getOppositeName(BeanAttributeInformation attributeDesc) {
        return Optional.empty();
    }

    @Override
    public Optional<Boolean> useFieldType(BeanAttributeInformation attributeDesc) {
        return Optional.empty();
    }

    @Override
    public Optional<LookupIncludeBehavior> getLookupIncludeBehavior(BeanAttributeInformation attributeDesc) {
        return Optional.empty();
    }

    @Override
    public Optional<SerializeType> getSerializeType(BeanAttributeInformation attributeDesc) {
        return Optional.empty();
    }

	@Override
	public Optional<JsonIncludeStrategy> getJsonIncludeStrategy(BeanAttributeInformation attributeDesc) {
		return Optional.empty();
	}

    @Override
    public Optional<RelationshipRepositoryBehavior> getRelationshipRepositoryBehavior(BeanAttributeInformation attributeDesc) {
        return Optional.empty();
    }

    @Override
    public Optional<PatchStrategy> getPatchStrategy(BeanAttributeInformation attributeDesc) {
        return Optional.empty();
    }

    @Override
    public Optional<String> getMappedBy(BeanAttributeInformation attributeDesc) {
        return Optional.empty();
    }

    @Override
    public Optional<VersionRange> getVersionRange(BeanAttributeInformation attributeDesc) {
        return Optional.empty();
    }

    @Override
    public boolean isEmbeddedType(BeanAttributeInformation attributeDesc) {
        return false;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<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.xhao</groupId>
    <artifactId>spring-security-demo</artifactId>
    <version>0.0.1</version>

    <properties>
        <java.version>1.8</java.version>
        <mybatis-starter.version>1.1.1</mybatis-starter.version>
        <oracle.driver.version>11.1.0.7.0</oracle.driver.version>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.3.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>${mybatis-starter.version}</version>
        </dependency>
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>${oracle.driver.version}</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.18</version>
        </dependency>

        <!--分页插件-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.0.0</version>
        </dependency>
    </dependencies>

</project>


text:
INSTALL_PATH ?= /usr/local
INSTALL = /usr/bin/install -v -C
REV := $(shell git rev-parse --short HEAD)
GOARCH ?= amd64

all: build

build:
	go build -o gowiki

cross-compile:
	GOOSi=darwin GOARCH=$(GOARCH) go build -o gowiki-osx
	GOOS=linux GOARCH=$(GOARCH) go build -o gowiki-linux
	GOOS=windows GOARCH=$(GOARCH) go build -o gowiki-windows

clean:
	rm -vf gowiki gowiki-* gowiki-*.tar.gz

install: gowiki
	@mkdir -p $(INSTALL_PATH)/bin
	@mkdir -p $(INSTALL_PATH)/share/gowiki/public/{css,js}
	@mkdir -p $(INSTALL_PATH)/share/gowiki/templates

	$(INSTALL) gowiki $(INSTALL_PATH)/bin/
	$(INSTALL) -m 0644 public/css/*.css $(INSTALL_PATH)/share/gowiki/public/css/
	$(INSTALL) -m 0644 public/js/*.js $(INSTALL_PATH)/share/gowiki/public/js/
	$(INSTALL) -m 0644 templates/*.html $(INSTALL_PATH)/share/gowiki/templates/

uninstall:
	rm -rvf $(INSTALL_PATH)/share/gowiki
	rm -vf $(INSTALL_PATH)/bin/gowiki

release: build
	@tar cvzf gowiki-$(REV).tar.gz gowiki public templates


text:
require_relative '../../../minitest_helper'
require_relative '../../../test_utilities'
require_relative '../../../../web_server/web_server'

class TestTweetElementGet < Minitest::Test

  describe 'tweet-element-get' do

    include TestUtilities

    before do
      clear_tables
    end

    it 'fails to get an element when there is no source' do
      get('/api/twitter/source/999/element/999')
      json_body(404)[:message].must_equal 'No source found for id [999]'
    end

    it 'fails to get an element when there is no element' do
      source = create_twitter_source('my_source')
      get("/api/twitter/source/#{source.id}/element/999")
      json_body(404)[:message].must_equal 'No tweet element found for id [999]'
    end

    it 'can get an element by its id' do
      source = create_twitter_source('my_source')
      timestamp = DateTime.now
      tweet_element = create_tweet_element(
        source,
        ['http://google.fr'],
        'AZERTY',
        timestamp,
        '{"key": "value"}'
      )

      resource = create_resource(
        'http://www.google.com',
        ExternalMemory::Resource::STATUS_CONTENT_HTML,
        'text/html',
        200,
        DateTime.now
      )

      create_element_url(tweet_element.element, 'http://google.com', resource)

      get("/api/twitter/source/#{source.id}/element/#{tweet_element.element.id}")
      tweet_element2 = json_body(200)
      tweet_element2.keys.length.must_equal 8
      tweet_element2.must_be_hash_values(
        {
          :id => tweet_element.element.id,
          :source => tweet_element.element.source_id,
          :created_at => tweet_element.element.created_at.rfc3339,
          :timestamp => tweet_element.element.timestamp.rfc3339,
          :content => parse_json(tweet_element.content),
          :tweet_id => tweet_element.tweet_id,
        })
      tweet_element2[:urls].length.must_equal 2
      tweet_element2[:urls].must_include('http://google.fr')
      tweet_element2[:urls].must_include('http://google.com')
      tweet_element2[:element_resources].length.must_equal 2

      element_resource1 = tweet_element2[:element_resources].find { |er| er[:url] == 'http://google.com' }
      element_resource1.keys.length.must_equal 2
      element_resource1[:resource][:id].must_equal resource.id

      element_resource2 = tweet_element2[:element_resources].find { |er| er[:url] == 'http://google.fr' }
      element_resource2.keys.length.must_equal 2
      element_resource2[:resource].must_be_nil
    end

    it 'fails to get elements when there is no source' do
      get('/api/twitter/source/999/element')
      json_body(404)[:message].must_equal 'No source found for id [999]'
    end

    it 'fails to get elements from its source when pagination params are wrong' do
      get('/api/twitter/source/42/element?page=0')
      json_body(400)[:message].must_equal 'Value [page] should be >= than [1] but is [0]'
      get('/api/twitter/source/42/element?per_page=0')
      json_body(400)[:message].must_equal 'Value [per_page] should be >= than [1] but is [0]'
      get('/api/twitter/source/42/element?per_page=101')
      json_body(400)[:message].must_equal 'Value [per_page] should be <= than [100] but is [101]'
    end

    it 'can get elements from its source' do
      source1 = create_twitter_source('my_source1')
      get("/api/twitter/source/#{source1.id}/element")
      json_body(200).must_equal({:tweetElements => []})
      header_total_count.must_equal 0

      tweet_element1 = create_tweet_element(source1, [], 'AZERTY1', (DateTime.now - 1), '{"key": "value"}')
      tweet_element2 = create_tweet_element(source1, [], 'AZERTY2', DateTime.now, '{"key": "value"}')
      source2 = create_twitter_source('my_source2')

      create_tweet_element(source2, [], 'REOEHR', DateTime.now, '{"key": "value"}')

      get("/api/twitter/source/#{source1.id}/element")
      header_total_count.must_equal 2
      tweet_elements = json_body(200)
      tweet_elements.keys.length.must_equal 1
      elements = tweet_elements[:tweetElements]
      elements.length.must_equal 2
      element0 = elements[0]
      element0.keys.length.must_equal 7
      element0.must_be_hash_values(
        {
          :id => tweet_element2.element.id,
          :tweet_id => tweet_element2.tweet_id,
          :timestamp => tweet_element2.element.timestamp.rfc3339,
          :content => parse_json(tweet_element2.content),
          :urls => [],
          :source => source1.id,
          :created_at => tweet_element2.element.created_at.rfc3339

        })
      element1 = elements[1]
      element1.keys.length.must_equal 7
      element1.must_be_hash_values(
        {
          :id => tweet_element1.element.id,
          :tweet_id => tweet_element1.tweet_id,
          :timestamp => tweet_element1.element.timestamp.rfc3339,
          :content => parse_json(tweet_element1.content),
          :urls => [],
          :source => source1.id,
          :created_at => tweet_element1.element.created_at.rfc3339

        })
      get("/api/twitter/source/#{source1.id}/element?per_page=1")
      header_total_count.must_equal 2
      tweet_elements = json_body(200)
      tweet_elements.keys.length.must_equal 1
      elements = tweet_elements[:tweetElements]
      elements.length.must_equal 1
      elements[0][:id].must_equal tweet_element2.element.id

      get("/api/twitter/source/#{source1.id}/element?per_page=1&page=1")
      header_total_count.must_equal 2
      tweet_elements = json_body(200)
      tweet_elements.keys.length.must_equal 1
      elements = tweet_elements[:tweetElements]
      elements.length.must_equal 1
      elements[0][:id].must_equal tweet_element2.element.id

      get("/api/twitter/source/#{source1.id}/element?per_page=1&page=2")
      header_total_count.must_equal 2
      tweet_elements = json_body(200)
      tweet_elements.keys.length.must_equal 1
      elements = tweet_elements[:tweetElements]
      elements.length.must_equal 1
      elements[0][:id].must_equal tweet_element1.element.id

      get("/api/twitter/source/#{source1.id}/element?per_page=1&page=3")
      header_total_count.must_equal 2
      tweet_elements = json_body(200)
      tweet_elements.keys.length.must_equal 1
      elements = tweet_elements[:tweetElements]
      elements.length.must_equal 0
    end

    it 'can get an element from its tweet id' do
      source1 = create_twitter_source('my_source1')
      get('/api/twitter/source/999/element/tweet_id/AZERTY')
      json_body(404)[:message].must_equal 'No source found for id [999]'

      tweet_element = create_tweet_element(
        source1,
        [],
        'AZERTY',
        DateTime.now,
        '{"key1": "value1"}'
      )

      create_tweet_element(
        source1,
        [],
        'AZERTYU',
        DateTime.now,
        '{"key1": "value1"}'
      )

      source2 = create_twitter_source('my_source2')
      create_tweet_element(
        source2,
        [],
        'AZERTY',
        DateTime.now,
        '{"key2": "value2"}'
      )

      get("/api/twitter/source/#{source1.id}/element/tweet_id/AZERTY")
      element = json_body(200)
      element.length.must_equal 8
      element.must_be_hash_values(
        {
          :id => tweet_element.element.id,
          :source => tweet_element.element.source_id,
          :created_at => tweet_element.element.created_at.rfc3339,
          :timestamp => tweet_element.element.timestamp.rfc3339,
          :content => parse_json(tweet_element.content),
          :tweet_id => tweet_element.tweet_id,
          :urls => [],
          :element_resources => [],
        })
    end

  end

end


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet href="latest_ob.xsl" type="text/xsl"?>
<current_observation version="1.0"
	 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
	 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	 xsi:noNamespaceSchemaLocation="http://www.weather.gov/view/current_observation.xsd">
	<credit>NOAA's National Weather Service</credit>
	<credit_URL>http://weather.gov/</credit_URL>
	<image>
		<url>http://weather.gov/images/xml_logo.gif</url>
		<title>NOAA's National Weather Service</title>
		<link>http://weather.gov</link>
	</image>
	<suggested_pickup>15 minutes after the hour</suggested_pickup>
	<suggested_pickup_period>60</suggested_pickup_period>
	<location>Unknown Station</location>
	<station_id>CWSP</station_id>
	<observation_time>Last Updated on Dec 21 2015, 2:00 pm ST </observation_time>
        <observation_time_rfc822>Mon, 21 Dec 2015 14:00:00 +0000</observation_time_rfc822>
	<temperature_string>42.0 F (5.3 C)</temperature_string>
	<temp_f>42.0</temp_f>
	<temp_c>5.3</temp_c>
	<relative_humidity>85</relative_humidity>
	<wind_string>East at 6.9 MPH (6 KT)</wind_string>
	<wind_dir>East</wind_dir>
	<wind_degrees>90</wind_degrees>
	<wind_mph>6.9</wind_mph>
	<wind_kt>6</wind_kt>
	<pressure_string>996.6 mb</pressure_string>
	<pressure_mb>996.6</pressure_mb>
	<dewpoint_string>37.4 F (3.0 C)</dewpoint_string>
	<dewpoint_f>37.4</dewpoint_f>
	<dewpoint_c>3.0</dewpoint_c>
	<windchill_string>38 F (3 C)</windchill_string>
      	<windchill_f>38</windchill_f>
      	<windchill_c>3</windchill_c>
	<two_day_history_url>http://www.weather.gov/data/obhistory/CWSP.html</two_day_history_url>
	<ob_url>http://www.weather.gov/data/METAR/CWSP.1.txt</ob_url>
	<disclaimer_url>http://weather.gov/disclaimer.html</disclaimer_url>
	<copyright_url>http://weather.gov/disclaimer.html</copyright_url>
	<privacy_policy_url>http://weather.gov/notice.html</privacy_policy_url>
</current_observation>


text:
<?php

/**
 * Todo Controller
 *
 * @license    http://opensource.org/licenses/MIT The MIT License (MIT)
 * @author     Omar El Gabry <omar.elgabry.93@gmail.com>
 */

class TodoController extends Controller{

    // override this method to perform any logic before calling action method as explained above
    public function beforeAction(){

        parent::beforeAction();

        // define the actions in this Controller
        $action = $this->request->param('action');

        // restrict the request to action methods
        // $this->Security->requireAjax(['create', 'delete']);
        $this->Security->requirePost(['create', 'delete']);

        // define the expected form fields for every action if exist
        switch($action){
            case "create":
                // you can exclude form fields if you don't care if they were sent with form fields or not
                $this->Security->config("form", [ 'fields' => ['content']]);
                break;
            case "delete":
				// If you want to disable validation for form tampering
				// $this->Security->config("validateForm", false);
                $this->Security->config("form", [ 'fields' => ['todo_id']]);
                break;
        }
    }

    public function index(){

        // display todo list
        $this->view->renderWithLayouts(Config::get('VIEWS_PATH') . "layout/todo/", Config::get('VIEWS_PATH') . 'todo/index.php');
    }

    public function create(){

        $content  = $this->request->data("content");
        $todo     = $this->todo->create(Session::getUserId(), $content);

        if(!$todo){

            // in case of normal post request
            Session::set('errors', $this->todo->errors());
            return $this->redirector->root("Todo");

            // in case of ajax
            // $this->view->renderErrors($this->todo->errors());

        }else{

            // in case of normal post request
            Session::set('success', "Todo has been created");
            return $this->redirector->root("Todo");

            // in case of ajax
            // $this->view->renderJson(array("success" => "Todo has been created"));
        }
    }

    public function delete(){

        $todoId = Encryption::decryptIdWithDash($this->request->data("todo_id"));
        $this->todo->delete($todoId);

        // in case of normal post request
        Session::set('success', "Todo has been deleted");
        return $this->redirector->root("Todo");

        // in case of ajax
        // $this->view->renderJson(array("success" => "Todo has been deleted"));
    }

    public function isAuthorized(){

        $action = $this->request->param('action');
        $role = Session::getUserRole();
        $resource = "todo";

        // only for admins
        Permission::allow('admin', $resource, ['*']);

        // only for normal users
        Permission::allow('user', $resource, ['delete'], 'owner');

        $todoId = $this->request->data("todo_id");

        if(!empty($todoId)){
            $todoId = Encryption::decryptIdWithDash($todoId);
        }

        $config = [
            "user_id" => Session::getUserId(),
            "table" => "todo",
            "id" => $todoId];

        return Permission::check($role, $resource, $action, $config);
    }
}


text:
class UserObserver < ActiveRecord::Observer

  def after_create(user)
    @user = user
    UserMailer.deliver_signup(@user)
  end

  def after_update(user)
    @user = user
    email_changes.each { |email| UserMailer.deliver_change_account(@user,email,'email') } if email_changes
    UserMailer.deliver_pending_delete(@user) if user_deleted?
  end

  protected

  def email_changes
    @user.custom_changed_cache[:email]
  end

  def user_deleted?
    @user.deleted? && @user.custom_changed_cache[:deleted] && @user.custom_changed_cache[:delete_after]
  end

end


text:
""" 使用言語変更メニュー
    暫定的にFMsgChangerの仕組みをテスト運用するためのページ
"""

import pygame.mixer
import os.path
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen

from common.fmsg import FMsg

import logging
logger = logging.getLogger(__name__)

file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'lang_change.kv'))
with open(file_path, 'r', encoding='utf8') as f:
    Builder.load_string(f.read())

class LangChangeScreen(Screen):

    def __init__(self, **kwargs):
        super(LangChangeScreen, self).__init__(**kwargs)
        FMsg.init_screen(self)

    def set_view(self):
        FMsg.init_screen(self)
        pygame.mixer.music.load(FMsg.get_voice("msg_00000"))  # 言語変更メッセージ
        pygame.mixer.music.play()

    def tr_system_top_scr(self):
        if self.manager is not None:
            self.manager.current = "system_top"
            logger.info("システムツールトップ画面へ移動")

    @staticmethod
    def change_lang(lang_id):
        FMsg.set_lang(lang_id)
        logger.info("言語変更:%d", lang_id)


text:
package org.apache.jackrabbit.vault.packaging.registry.impl;

import java.io.IOException;
import java.util.Properties;

import javax.jcr.RepositoryException;

import org.apache.jackrabbit.vault.packaging.JcrPackage;
import org.apache.jackrabbit.vault.packaging.impl.PackagePropertiesImpl;

public class JcrPackageProperties extends PackagePropertiesImpl {

    private JcrPackage pkg;

    public JcrPackageProperties(JcrPackage pkg) {
        this.pkg = pkg;
    }

    @Override
    protected Properties getPropertiesMap() {
        try {
            return pkg.getPackage().getMetaInf().getProperties();
        } catch (RepositoryException|IOException e) {
            throw new IllegalStateException(e);
        }
    }

}


text:
<?php

// Note: Do not move this code after the inclusion of wp-config. It adds
// slashes to POST data even if magic quotes is off.

// see if a registration response is available
if(isset($_POST['encrypted-message'])) {
  $response = $_POST['encrypted-message'];

  // make sure to remove magic quotes if in use
  if(get_magic_quotes_gpc()) {
    $response = stripcslashes($response);
  }
}

require_once('../../../wp-config.php');
require_once('payswarm-admin.inc');

if(!current_user_can('manage_options')) {
  wp_die(__('Access denied.'));
}

if(isset($response)) {
  payswarm_complete_registration($response);
} else {
  payswarm_init_registration();
}

/* end of file, omit ?> */


text:
/* eslint-env jest */

import path from 'path'
import webdriver from 'next-webdriver'
import {
  nextBuild,
  nextStart,
  findPort,
  killApp,
  renderViaHTTP,
  waitFor,
} from 'next-test-utils'

const appDir = path.join(__dirname, '..')
let app
let port

describe('Handles an Error in _error', () => {
  beforeAll(async () => {
    await nextBuild(appDir)
    port = await findPort()
    app = await nextStart(appDir, port)
  })
  afterAll(() => killApp(app))

  it('Handles error during SSR', async () => {
    const html = await renderViaHTTP(port, '/some-404-page')
    expect(html).toMatch(/internal server error/i)
  })

  it('Handles error during client transition', async () => {
    const browser = await webdriver(port, '/')
    await browser.waitForElementByCss('a').click()
    await waitFor(1000)
    const html = await browser.eval('document.body.innerHTML')
    expect(html).toMatch(/internal server error/i)
  })
})


text:
FASTJET_BEGIN_NAMESPACE

using namespace std;

/// allow for warnings
LimitedWarning ClusterSequenceAreaBase::_warnings;
LimitedWarning ClusterSequenceAreaBase::_warnings_zero_area;
LimitedWarning ClusterSequenceAreaBase::_warnings_empty_area;

//----------------------------------------------------------------------
/// return the total area, within the selector's range, that is free
/// of jets.
///
/// Calculate this as (range area) - \sum_{i in range} A_i
///
/// for ClusterSequences with explicit ghosts, assume that there will
/// never be any empty area, i.e. it is always filled in by pure
/// ghosts jets. This holds for seq.rec. algorithms
double ClusterSequenceAreaBase::empty_area(const Selector & selector) const {

  if (has_explicit_ghosts()) {return 0.0;}
  else { return empty_area_from_jets(inclusive_jets(0.0), selector);}

}

//----------------------------------------------------------------------
/// return the total area, within range, that is free of jets.
///
/// Calculate this as (range area) - \sum_{i in range} A_i
///
double ClusterSequenceAreaBase::empty_area_from_jets(
                      const std::vector<PseudoJet> & all_jets,
                      const Selector & selector) const {
  _check_selector_good_for_median(selector);

  double empty = selector.area();
  for (unsigned i = 0; i < all_jets.size(); i++) {
    if (selector.pass(all_jets[i])) empty -= area(all_jets[i]);
  }
  return empty;
}

double ClusterSequenceAreaBase::median_pt_per_unit_area(const Selector & selector) const {
  return median_pt_per_unit_something(selector,false);
}

double ClusterSequenceAreaBase::median_pt_per_unit_area_4vector(const Selector & selector) const {
  return median_pt_per_unit_something(selector,true);
}

//----------------------------------------------------------------------
/// the median of (pt/area) for jets contained within range, counting
/// the empty area as if it were made up of a collection of empty
/// jets each of area (0.55 * pi R^2).
double ClusterSequenceAreaBase::median_pt_per_unit_something(
                const Selector & selector, bool use_area_4vector) const {

  double median, sigma, mean_area;
  get_median_rho_and_sigma(selector, use_area_4vector, median, sigma, mean_area);
  return median;

}

//----------------------------------------------------------------------
/// fits a form pt_per_unit_area(y) = a + b*y^2 for jets in range.
/// exclude_above allows one to exclude large values of pt/area from fit.
/// use_area_4vector = true uses the 4vector areas.
void ClusterSequenceAreaBase::parabolic_pt_per_unit_area(
       double & a, double & b, const Selector & selector,
       double exclude_above, bool use_area_4vector) const {
  // sanity check on the selector: we require a finite area and that
  // it applies jet by jet (see BackgroundEstimator for more advanced
  // usage)
  _check_selector_good_for_median(selector);

  int n=0;
  int n_excluded = 0;
  double mean_f=0, mean_x2=0, mean_x4=0, mean_fx2=0;

  vector<PseudoJet> incl_jets = inclusive_jets();

  for (unsigned i = 0; i < incl_jets.size(); i++) {
    if (selector.pass(incl_jets[i])) {
      double this_area;
      if ( use_area_4vector ) {
          this_area = area_4vector(incl_jets[i]).perp();
      } else {
          this_area = area(incl_jets[i]);
      }
      double f = incl_jets[i].perp()/this_area;
      if (exclude_above <= 0.0 || f < exclude_above) {
	double x = incl_jets[i].rap(); double x2 = x*x;
	mean_f   += f;
	mean_x2  += x2;
	mean_x4  += x2*x2;
	mean_fx2 += f*x2;
	n++;
      } else {
	n_excluded++;
      }
    }
  }

  if (n <= 1) {
    // meaningful results require at least two jets inside the
    // area -- mind you if there are empty jets we should be in
    // any case doing something special...
    a = 0.0;
    b = 0.0;
  } else {
    mean_f   /= n;
    mean_x2  /= n;
    mean_x4  /= n;
    mean_fx2 /= n;

    b = (mean_f*mean_x2 - mean_fx2)/(mean_x2*mean_x2 - mean_x4);
    a = mean_f - b*mean_x2;
  }
  //cerr << "n_excluded = "<< n_excluded << endl;
}

void ClusterSequenceAreaBase::get_median_rho_and_sigma(
            const Selector & selector, bool use_area_4vector,
            double & median, double & sigma, double & mean_area) const {

  vector<PseudoJet> incl_jets = inclusive_jets();
  get_median_rho_and_sigma(incl_jets, selector, use_area_4vector,
			   median, sigma, mean_area, true);
}

void ClusterSequenceAreaBase::get_median_rho_and_sigma(
            const vector<PseudoJet> & all_jets,
            const Selector & selector, bool use_area_4vector,
            double & median, double & sigma, double & mean_area,
	    bool all_are_incl) const {

  _check_jet_alg_good_for_median();

  // sanity check on the selector: we require a finite area and that
  // it applies jet by jet (see BackgroundEstimator for more advanced
  // usage)
  _check_selector_good_for_median(selector);

  vector<double> pt_over_areas;
  double total_area  = 0.0;
  double total_njets = 0;

  for (unsigned i = 0; i < all_jets.size(); i++) {
    if (selector.pass(all_jets[i])) {
      double this_area;
      if (use_area_4vector) {
          this_area = area_4vector(all_jets[i]).perp();
      } else {
          this_area = area(all_jets[i]);
      }

      if (this_area>0) {
	pt_over_areas.push_back(all_jets[i].perp()/this_area);
      } else {
	_warnings_zero_area.warn("ClusterSequenceAreaBase::get_median_rho_and_sigma(...): discarded jet with zero area. Zero-area jets may be due to (i) too large a ghost area (ii) a jet being outside the ghost range (iii) the computation not being done using an appropriate algorithm (kt;C/A).");
      }

      total_area  += this_area;
      total_njets += 1.0;
    }
  }

  // there is nothing inside our region, so answer will always be zero
  if (pt_over_areas.size() == 0) {
    median = 0.0;
    sigma  = 0.0;
    mean_area = 0.0;
    return;
  }

  // get median (pt/area) [this is the "old" median definition. It considers
  // only the "real" jets in calculating the median, i.e. excluding the
  // only-ghost ones; it will be supplemented with more info below]
  sort(pt_over_areas.begin(), pt_over_areas.end());

  // now get the median & error, accounting for empty jets
  // define the fractions of distribution at median, median-1sigma
  double posn[2] = {0.5, (1.0-0.6827)/2.0};
  double res[2];

  double n_empty, empty_a;
  if (has_explicit_ghosts()) {
    // NB: the following lines of code are potentially incorrect in cases
    //     where there are unclustered particles (empty_area would do a better job,
    //     at least for active areas). This is not an issue with kt or C/A, or other
    //     algorithms that cluster all particles (and the median estimation should in
    //     any case only be done with kt or C/A!)
    empty_a = 0.0;
    n_empty = 0;
  } else if (all_are_incl) {
    // the default case
    empty_a = empty_area(selector);
    n_empty = n_empty_jets(selector);
  } else {
    // this one is intended to be used when e.g. one runs C/A, then looks at its
    // exclusive jets in order to get an effective smaller R value, and passes those
    // to this routine.
    empty_a = empty_area_from_jets(all_jets, selector);
    mean_area = total_area / total_njets; // temporary value
    n_empty   = empty_a / mean_area;
  }
  //cout << "*** tot_area = " << total_area << ", empty_a = " << empty_a << endl;
  //cout << "*** n_empty = " << n_empty << ", ntotal =  " << total_njets << endl;
  total_njets += n_empty;
  total_area  += empty_a;

  // we need an int (rather than an unsigned int) with the size of the
  // pt_over_areas array, because we'll often be doing subtraction of
  // -1, negating it, etc. All of these operations go crazy with unsigned ints.
  int pt_over_areas_size = pt_over_areas.size();
  if (n_empty < -pt_over_areas_size/4.0)
    _warnings_empty_area.warn("ClusterSequenceAreaBase::get_median_rho_and_sigma(...): the estimated empty area is suspiciously large and negative and may lead to an over-estimation of rho. This may be due to (i) a rare statistical fluctuation or (ii) too small a range used to estimate the background properties.");

  for (int i = 0; i < 2; i++) {
    double nj_median_pos =
      (pt_over_areas_size-1.0 + n_empty)*posn[i] - n_empty;
    double nj_median_ratio;
    if (nj_median_pos >= 0 && pt_over_areas_size > 1) {
      int int_nj_median = int(nj_median_pos);

     // avoid potential overflow issues
      if (int_nj_median+1 > pt_over_areas_size-1){
	int_nj_median = pt_over_areas_size-2;
	nj_median_pos = pt_over_areas_size-1;
      }

      nj_median_ratio =
        pt_over_areas[int_nj_median] * (int_nj_median+1-nj_median_pos)
        + pt_over_areas[int_nj_median+1] * (nj_median_pos - int_nj_median);
    } else {
      nj_median_ratio = 0.0;
    }
    res[i] = nj_median_ratio;
  }
  median = res[0];
  double error  = res[0] - res[1];
  mean_area = total_area / total_njets;
  sigma  = error * sqrt(mean_area);
}

/// return a vector of all subtracted jets, using area_4vector, given rho.
/// Only inclusive_jets above ptmin are subtracted and returned.
/// the ordering is the same as that of sorted_by_pt(cs.inclusive_jets()),
/// i.e. not necessarily ordered in pt once subtracted
vector<PseudoJet> ClusterSequenceAreaBase::subtracted_jets(const double rho,
                                                           const double ptmin)
                                                           const {
  vector<PseudoJet> sub_jets;
  vector<PseudoJet> jets = sorted_by_pt(inclusive_jets(ptmin));
  for (unsigned i=0; i<jets.size(); i++) {
     PseudoJet sub_jet = subtracted_jet(jets[i],rho);
     sub_jets.push_back(sub_jet);
  }
  return sub_jets;
}

/// return a vector of subtracted jets, using area_4vector.
/// Only inclusive_jets above ptmin are subtracted and returned.
/// the ordering is the same as that of sorted_by_pt(cs.inclusive_jets()),
/// i.e. not necessarily ordered in pt once subtracted
vector<PseudoJet> ClusterSequenceAreaBase::subtracted_jets(
                                                 const Selector & selector,
						 const double ptmin)
						 const {
  double rho = median_pt_per_unit_area_4vector(selector);
  return subtracted_jets(rho,ptmin);
}

/// return a subtracted jet, using area_4vector, given rho
PseudoJet ClusterSequenceAreaBase::subtracted_jet(const PseudoJet & jet,
                                                  const double rho) const {
  PseudoJet area4vect = area_4vector(jet);
  PseudoJet sub_jet;
  // sanity check
  if (rho*area4vect.perp() < jet.perp() ) {
    sub_jet = jet - rho*area4vect;
  } else { sub_jet = PseudoJet(0.0,0.0,0.0,0.0); }

  // make sure the subtracted jet has the same index (cluster, user, csw)
  // (i.e. "looks like") the original jet
  sub_jet.set_cluster_hist_index(jet.cluster_hist_index());
  sub_jet.set_user_index(jet.user_index());
  // do not use CS::_set_structure_shared_ptr here, which should
  // only be called to maintain the tally during construction
  sub_jet.set_structure_shared_ptr(jet.structure_shared_ptr());
  return sub_jet;
}

/// return a subtracted jet, using area_4vector;  note that this is
/// potentially inefficient if repeatedly used for many different
/// jets, because rho will be recalculated each time around.
PseudoJet ClusterSequenceAreaBase::subtracted_jet(const PseudoJet & jet,
                                       const Selector & selector) const {
  double rho = median_pt_per_unit_area_4vector(selector);
  PseudoJet sub_jet = subtracted_jet(jet, rho);
  return sub_jet;
}

/// return the subtracted pt, given rho
double ClusterSequenceAreaBase::subtracted_pt(const PseudoJet & jet,
                                              const double rho,
                                              bool use_area_4vector) const {
  if ( use_area_4vector ) {
     PseudoJet sub_jet = subtracted_jet(jet,rho);
     return sub_jet.perp();
  } else {
     return jet.perp() - rho*area(jet);
  }
}

/// return the subtracted pt; note that this is
/// potentially inefficient if repeatedly used for many different
/// jets, because rho will be recalculated each time around.
double ClusterSequenceAreaBase::subtracted_pt(const PseudoJet & jet,
                                              const Selector & selector,
                                              bool use_area_4vector) const {
  if ( use_area_4vector ) {
     PseudoJet sub_jet = subtracted_jet(jet,selector);
     return sub_jet.perp();
  } else {
     double rho = median_pt_per_unit_area(selector);
     return subtracted_pt(jet,rho,false);
  }
}

// check the selector is suited for the computations i.e. applies jet
// by jet and has a finite area
void ClusterSequenceAreaBase::_check_selector_good_for_median(const Selector &selector) const{
  // make sure the selector has a finite area
  if ((! has_explicit_ghosts()) &&  (! selector.has_finite_area())){
    throw Error("ClusterSequenceAreaBase: empty area can only be computed from selectors with a finite area");
  }

  // make sure the selector applies jet by jet
  if (! selector.applies_jet_by_jet()){
    throw Error("ClusterSequenceAreaBase: empty area can only be computed from selectors that apply jet by jet");
  }
}

/// check the jet algorithm is suitable (and if not issue a warning)
void ClusterSequenceAreaBase::_check_jet_alg_good_for_median() const {
  if (jet_def().jet_algorithm() != kt_algorithm
      && jet_def().jet_algorithm() != cambridge_algorithm
      && jet_def().jet_algorithm() !=  cambridge_for_passive_algorithm) {
    _warnings.warn("ClusterSequenceAreaBase: jet_def being used may not be suitable for estimating diffuse backgrounds (good options are kt, cam)");
  }
}

FASTJET_END_NAMESPACE


text:
//
//  StarIoExt.h
//  StarIO_Extension
//
//  Created by Yuji on 2015/**/**.
//  Copyright (c) 2015年 Star Micronics. All rights reserved.
//

#import <Foundation/Foundation.h>

#import "ISCBBuilder.h"
#import "ISDCBBuilder.h"
#import "ISSCBBuilder.h"

#import "ISCPConnectParser.h"

#import "ISSCPWeightParser.h"

typedef NS_ENUM(NSInteger, StarIoExtEmulation) {     // Don't insert!
    StarIoExtEmulationNone = 0,
    StarIoExtEmulationStarPRNT,
    StarIoExtEmulationStarLine,
    StarIoExtEmulationStarGraphic,
    StarIoExtEmulationEscPos,
    StarIoExtEmulationEscPosMobile,
    StarIoExtEmulationStarDotImpact,
    StarIoExtEmulationStarPRNTL
};

typedef NS_ENUM(NSInteger, StarIoExtCharacterCode) {     // Don't insert!
    StarIoExtCharacterCodeNone = 0,
    StarIoExtCharacterCodeStandard,
    StarIoExtCharacterCodeJapanese,
    StarIoExtCharacterCodeSimplifiedChinese,
    StarIoExtCharacterCodeTraditionalChinese
};

typedef NS_ENUM(NSInteger, StarIoExtBcrModel) {     // Don't insert!
    StarIoExtBcrModelNone = 0,
    StarIoExtBcrModelPOP1
};

typedef NS_ENUM(NSInteger, StarIoExtDisplayModel) {     // Don't insert!
    StarIoExtDisplayModelNone = 0,
    StarIoExtDisplayModelSCD222
};

typedef NS_ENUM(NSInteger, StarIoExtScaleModel) {     // Don't insert!
    StarIoExtScaleModelNone = 0,
    StarIoExtScaleModelAPS10,
    StarIoExtScaleModelAPS12,
    StarIoExtScaleModelAPS20
};

@interface StarIoExt : NSObject

#pragma mark - Generic

+ (NSString *)description;

#pragma mark - Builder

+ (ISCBBuilder *)createCommandBuilder:(StarIoExtEmulation)emulation;

+ (ISDCBBuilder *)createDisplayCommandBuilder:(StarIoExtDisplayModel)model;

+ (ISSCBBuilder *)createScaleCommandBuilder:(StarIoExtScaleModel)model;

#pragma mark - Parser

+ (ISCPConnectParser *)createBcrConnectParser:(StarIoExtBcrModel)model;

+ (ISCPConnectParser *)createDisplayConnectParser:(StarIoExtDisplayModel)model;

+ (ISCPConnectParser *)createScaleConnectParser:(StarIoExtScaleModel)model;

+ (ISSCPWeightParser *)createScaleWeightParser:(StarIoExtScaleModel)model;

@end


text:
package hk.ust.gmission;

import android.app.Application;
import android.app.Instrumentation;
import android.content.Context;
import android.support.multidex.MultiDex;

/**
 * gMission application
 */
public class BootstrapApplication extends Application {

    private static BootstrapApplication instance;

    /**
     * Create main application
     */
    public BootstrapApplication() {
    }

    /**
     * Create main application
     *
     * @param context
     */
    public BootstrapApplication(final Context context) {
        this();
        attachBaseContext(context);
    }

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

        instance = this;

        // Perform injection
        Injector.init(getRootModule(), this);

    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    private Object getRootModule() {
        return new RootModule();
    }

    /**
     * Create main application
     *
     * @param instrumentation
     */
    public BootstrapApplication(final Instrumentation instrumentation) {
        this();
        attachBaseContext(instrumentation.getTargetContext());
    }

    public static BootstrapApplication getInstance() {
        return instance;
    }
}


text:
'use strict';

var webpack = require('webpack');
var path = require('path');
var autoprefixer = require('autoprefixer');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var AssetsPlugin = require('assets-webpack-plugin');
var ExtractFilePlugin = require('extract-file-loader/Plugin');
var DashboardPlugin = require('webpack-dashboard/plugin');

process.traceDeprecation = true;
process.noDeprecation = true;

module.exports = function makeWebpackConfig(options) {
    /**
     * Whether we are generating minified assets for production
     */
    var BUILD = options.environment === 'prod';

    /**
     * Whether we are running in dev-server mode (versus simple compile)
     */
    var DEV_SERVER = process.env.WEBPACK_MODE === 'watch';

    /**
     * Whether we are running inside webpack-dashboard
     */
    var DASHBOARD = process.env.WEBPACK_DASHBOARD === 'enabled';

    var publicPath;
    if (options.parameters.dev_server_public_path && DEV_SERVER) {
        publicPath = options.parameters.dev_server_public_path;

    } else if (options.parameters.public_path) {
        publicPath = options.parameters.public_path;
    } else {
        publicPath = DEV_SERVER ? 'http://localhost:8080/compiled/' : '/compiled/';
    }

    /**
     * Config
     * Reference: https://webpack.js.org/concepts/
     * This is the object where all configuration gets set
     */
    var config = {
        entry: options.entry,
        /*node: {
            console: 'empty',
            fs: 'empty',
            net: 'empty',
            tls: 'empty'
        },*/
        resolve: {
            alias: options.alias,
            extensions: ['.js', '.jsx'],
            modules: ['node_modules']
        },

        output: {
            // Absolute output directory
            path: options.parameters.path ? options.parameters.path : __dirname + '/../../web/compiled/',

            // Output path from the view of the page
            publicPath: publicPath,

            // Filename for entry points
            // Only adds hash in build mode
            filename: BUILD ? '[name].[chunkhash].js' : '[name].bundle.js',

            // Filename for non-entry points
            // Only adds hash in build mode
            chunkFilename: BUILD ? '[name].[chunkhash].js' : '[name].bundle.js'
        },
        node: {
            fs: 'empty',
            net: 'empty',
            tls: 'empty'
        },

        /**
         * Options for webpack-dev-server.
         * Enables overlay inside the page if any error occurs when compiling.
         * Enables CORS headers to allow hot reload from other domain / port.
         * Reference: https://webpack.js.org/configuration/dev-server/
         */
        devServer: Object.assign({
            overlay: {
                warnings: false,
                errors: true
            },
            headers: { "Access-Control-Allow-Origin": "*" }
        }, options.parameters.dev_server || {})
    };

    /**
     * Loaders
     * Reference: https://webpack.js.org/concepts/loaders/
     * List: https://webpack.js.org/loaders/
     * This handles most of the magic responsible for converting modules
     */
    config.module = {
        rules: [
            /**
             * Compiles ES6 and ES7 into ES5 code
             * Reference: https://github.com/babel/babel-loader
             */
            {
                test: /\.jsx?$/i,
                loader: 'babel-loader',
                exclude: /node_modules/,
                options: {
                    presets: [['env', {
                        "modules": false
                    }]]
                }
            },

            /**
             * Minify PNG, JPEG, GIF and SVG images with imagemin
             * Reference: https://github.com/tcoopman/image-webpack-loader
             *
             * See `config.imageWebpackLoader` for configuration options
             *
             * Query string is needed for URLs inside css files, like bootstrap
             */
            {
                test: /\.(gif|png|jpe?g|svg)(\?.*)?$/i,
                enforce: 'pre',
                loader: 'image-webpack-loader',
                options: options.parameters.image_loader_options || {
                    optipng: {
                        optimizationLevel: 7,
                        progressive: true
                    }
                }
            },
            /**
             * Copy files to output directory
             * Rename the file using the asset hash
             * Pass along the updated reference to your code
             *
             * Reference: https://github.com/webpack/file-loader
             *
             * Query string is needed for URLs inside css files, like bootstrap
             * Overwrites name parameter to put original name in the destination filename, too
             */
            {
                test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)(\?.*)?$/i,
                loader: 'file-loader',
                options: {
                    name: '[name].[hash].[ext]'
                }
            },

            /**
             * Loads HTML files as strings inside JavaScript - can be used for templates
             *
             * Reference: https://github.com/webpack/raw-loader
             */
            {
                test: /\.html$/i,
                loader: 'raw-loader'
            },

            /**
             * Allow loading CSS through JS
             * Reference: https://github.com/webpack/css-loader
             *
             * postcss: Postprocess your CSS with PostCSS plugins (add vendor prefixes to CSS)
             * Reference: https://github.com/postcss/postcss-loader
             * Reference: https://github.com/postcss/autoprefixer
             *
             * ExtractTextPlugin: Extract CSS files into separate ones to load directly
             * Reference: https://github.com/webpack/extract-text-webpack-plugin
             *
             * If ExtractTextPlugin is disabled, use style loader
             * Reference: https://github.com/webpack/style-loader
             */
            {
                test: /\.(css|less|scss)$/i,
                loader: ExtractTextPlugin.extract({
                    'fallback': 'style-loader',
                    use: [
                        'css-loader?sourceMap',
                        {
                            loader: 'postcss-loader',
                            options: {
                                plugins: function () {
                                    return [
                                        autoprefixer({
                                            browsers: ['last 2 version']
                                        })
                                    ];
                                }
                            }
                        }
                    ]
                })
            },

            /**
             * Compile LESS to CSS, then use same rules
             * Reference: https://github.com/webpack-contrib/less-loader
             */
            {
                test: /\.less$/i,
                loader: 'less-loader?sourceMap',
                enforce: 'pre'
            },

            /**
             * Compile SASS to CSS, then use same rules
             * Reference: https://github.com/webpack-contrib/sass-loader
             */
            {
                test: /\.scss$/i,
                loader: 'sass-loader?sourceMap',
                enforce: 'pre'
            }
        ]
    };

    /**
     * Plugins
     * Reference: https://webpack.js.org/configuration/plugins/
     * List: https://webpack.js.org/plugins/
     */
    config.plugins = [
        /**
         * Used for CSS files to extract from JavaScript
         * Reference: https://github.com/webpack/extract-text-webpack-plugin
         */
        new ExtractTextPlugin(
            {
                filename: BUILD ? '[name].[hash].css' : '[name].bundle.css',
                disable: options.parameters.extract_css === false
            }
        ),

        /**
         * Webpack plugin that emits a json file with assets paths - used by the bundle
         * Reference: https://github.com/kossnocorp/assets-webpack-plugin
         */
        new AssetsPlugin({
            filename: path.basename(options.manifest_path),
            path: path.dirname(options.manifest_path)
        }),

        /**
         * Adds assets loaded with extract-file-loader as chunk files to be available in generated manifest
         * Used by the bundle to use binary files (like images) as entry-points
         * Reference: https://github.com/mariusbalcytis/extract-file-loader
         */
        new ExtractFilePlugin()
    ];

    /**
     * Adds CLI dashboard when compiling assets instead of the standard output
     * Reference: https://github.com/FormidableLabs/webpack-dashboard
     */
    if (DASHBOARD) {
        config.plugins.push(new DashboardPlugin());
    }

    /**
     * Build specific plugins - used only in production environment
     */
    if (BUILD) {
        config.plugins.push(
            /**
             * Only emit files when there are no errors
             * Reference: https://github.com/webpack/docs/wiki/list-of-plugins#noerrorsplugin
             */
            new webpack.NoEmitOnErrorsPlugin(),

            /**
             * Minify all javascript, switch loaders to minimizing mode
             * Reference: https://webpack.js.org/plugins/uglifyjs-webpack-plugin/
             */
            new webpack.optimize.UglifyJsPlugin()
        );
    }

    /**
     * Devtool - type of sourcemap to use per build type
     * Reference: https://webpack.js.org/configuration/devtool/
     */
    if (BUILD) {
        config.devtool = 'source-map';
    } else {
        config.devtool = 'eval';
    }

    return config;
};


text:
using System;
using Magellan.Routing;

namespace Magellan.Framework
{
    /// <summary>
    /// Provides information about the current request and the controller that is serving it.
    /// </summary>
    public class ControllerContext : IDisposable
    {
        private readonly IController controller;
        private readonly ResolvedNavigationRequest request;
        private readonly ViewEngineCollection viewEngines;
        private readonly ModelBinderDictionary modelBinders;
        private readonly Action releaseCallback;

        /// <summary>
        /// Initializes a new instance of the <see cref="ControllerContext"/> class.
        /// </summary>
        /// <param name="controller">The controller.</param>
        /// <param name="request">The request.</param>
        /// <param name="viewEngines">The view engines.</param>
        public ControllerContext(IController controller, ResolvedNavigationRequest request, ViewEngineCollection viewEngines)
            : this(controller, request, viewEngines, null, null)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ControllerContext"/> class.
        /// </summary>
        /// <param name="controller">The controller.</param>
        /// <param name="request">The request.</param>
        /// <param name="viewEngines">The view engines.</param>
        /// <param name="modelBinders"></param>
        /// <param name="releaseCallback">A callback that is invoked when the current request needs to be
        /// cleaned up.</param>
        public ControllerContext(IController controller, ResolvedNavigationRequest request, ViewEngineCollection viewEngines, ModelBinderDictionary modelBinders, Action releaseCallback)
        {
            this.controller = controller;
            this.request = request;
            this.viewEngines = viewEngines;
            this.modelBinders = modelBinders;
            this.releaseCallback = releaseCallback;
        }

        /// <summary>
        /// Gets the model binders.
        /// </summary>
        /// <value>The model binders.</value>
        public ModelBinderDictionary ModelBinders
        {
            get { return modelBinders; }
        }

        /// <summary>
        /// Gets the active controller.
        /// </summary>
        /// <value>The controller.</value>
        public IController Controller
        {
            get { return controller; }
        }

        /// <summary>
        /// Gets the name of the controller.
        /// </summary>
        /// <value>The name of the controller.</value>
        public string ControllerName
        {
            get { return Request.RouteValues.GetOrDefault<string>("controller"); }
        }

        /// <summary>
        /// Gets the name of the action.
        /// </summary>
        /// <value>The name of the action.</value>
        public string ActionName
        {
            get { return Request.RouteValues.GetOrDefault<string>("action"); }
        }

        /// <summary>
        /// Gets the current request.
        /// </summary>
        /// <value>The request.</value>
        public ResolvedNavigationRequest Request
        {
            get { return request; }
        }

        /// <summary>
        /// Gets the view engines.
        /// </summary>
        /// <value>The view engines.</value>
        public ViewEngineCollection ViewEngines
        {
            get { return viewEngines; }
        }

        /// <summary>
        /// Cleans up and releases the current controller context.
        /// </summary>
        public virtual void Dispose()
        {
            if (releaseCallback != null) releaseCallback();
        }
    }
}


text:
import DashboardPage from '../pages/DashboardPage.vue';
import LoginPage from '../pages/LoginPage.vue';
import { createRouter, createWebHistory } from 'vue-router';

export const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/', component: LoginPage },
    { path: '/dashboard', component: DashboardPage },
  ],
})


text:
package edu.monash.infotech.marvl.cola.vpsc;

import edu.monash.infotech.marvl.cola.TriConsumer;

import java.util.List;

public class Variable {

    public double offset = 0;
    public Block            block;
    public List<Constraint> cIn;
    public List<Constraint> cOut;
    public double           desiredPosition;
    public double           weight;
    public double           scale;

    public Variable(final double desiredPosition) {
        this(desiredPosition, 1.0);
    }

    public Variable(final double desiredPosition, final double weight) {
        this(desiredPosition, weight, 1.0);
    }

    public Variable(final double desiredPosition, final double weight, final double scale) {
        this.desiredPosition = desiredPosition;
        this.weight = weight;
        this.scale = scale;
    }

    public double dfdv() {
        return 2.0 * this.weight * (this.position() - this.desiredPosition);
    }

    public double position() {
        return (this.block.ps.scale * this.block.posn + this.offset) / this.scale;
    }

    // visit neighbours by active constraints within the same block
    public void visitNeighbours(final Variable prev, final TriConsumer<Constraint, Variable, ValueHolder> f, final ValueHolder value) {
        this.cOut.forEach(c -> {
            if (c.active && prev != c.right) {
                f.accept(c, c.right, value);
            }
        });
        this.cIn.forEach(c -> {
            if (c.active && prev != c.left) {
                f.accept(c, c.left, value);
            }
        });
    }
}


text:
/**
 * Coordinates :: This class is used for drawing board coordinates
 */

/**
 * Module definition and dependencies
 */
angular.module('ngGo.Board.Object.Coordinates.Service', [
  'ngGo',
])

/**
 * Factory definition
 */
.factory('Coordinates', function() {

  //Kanji
  const kanji = [
    '一', '二', '三', '四', '五', '六', '七',
    '八', '九', '十', '十一', '十二', '十三', '十四',
    '十五', '十六', '十七', '十八', '十九', '二十',
    '二十一', '二十二', '二十三', '二十四', '二十五',
    '二十六', '二十七', '二十八', '二十九', '三十',
    '三十一', '三十二', '三十三', '三十四', '三十五',
    '三十六', '三十七', '三十八', '三十九', '四十',
  ];

  //Character codes
  const aChar = 'A'.charCodeAt(0);
  const aCharLc = 'a'.charCodeAt(0);

  /**
   * Coordinate generators
   */
  const coordinates = {

    //Kanji coordinates
    kanji(i) {
      return kanji[i] || '';
    },

    //Numbers from 1
    numbers(i) {
      return i + 1;
    },

    //Capital letters from A
    letters(i) {

      //Initialize
      let ch = '';

      //Beyond Z? Prepend with A
      if (i >= 25) {
        ch = 'A';
        i -= 25;
      }

      //The letter I is ommitted
      if (i >= 8) {
        i++;
      }

      //Return
      return ch + String.fromCharCode(aChar + i);
    },

    //JGF coordinates (e.g. 0, 1, ...)
    jgf(i) {
      return i;
    },

    //SGF coordinates (e.g. a, b, ...)
    sgf(i) {
      let ch;
      if (i < 26) {
        ch = aCharLc + i;
      }
      else {
        ch = aChar + i;
      }
      return String.fromCharCode(ch);
    },
  };

  /**
   * Coordinates object
   */
  const Coordinates = {

    /**
     * Draw
     */
    draw() {

      //Can only draw when we have context and dimensions
      if (!this.context || !this.board.hasDrawSize()) {
        return;
      }

      //Get cell size
      const cellSize = this.board.getCellSize();

      //Get boundary coordinates
      const xl = Math.ceil((this.board.drawMarginHor - cellSize / 2) / 2);
      const xr = this.board.drawWidth - xl;
      const yt = Math.ceil((this.board.drawMarginVer - cellSize / 2) / 2);
      const yb = this.board.drawHeight - yt;

      //Get theme properties
      const theme = this.board.theme;
      const fillStyle = theme.get('coordinates.color');
      const vertical = {
        font: theme.get('coordinates.vertical.font'),
        size: theme.get('coordinates.vertical.size'),
        style: theme.get('coordinates.vertical.style'),
        inverse: theme.get('coordinates.vertical.inverse'),
      };
      const horizontal = {
        font: theme.get('coordinates.horizontal.font'),
        size: theme.get('coordinates.horizontal.size'),
        style: theme.get('coordinates.horizontal.style'),
        inverse: theme.get('coordinates.horizontal.inverse'),
      };

      //Configure context
      this.context.fillStyle = fillStyle;
      this.context.textBaseline = 'middle';
      this.context.textAlign = 'center';

      //Helper vars
      let i, j, x, y, ch;

      //Draw vertical coordinates
      for (i = 0; i < this.board.height; i++) {

        //Inverse?
        j = i;
        if (vertical.inverse) {
          j = this.board.height - i - 1;
        }

        //Get character
        if (typeof vertical.style === 'function') {
          ch = vertical.style.call(this, j);
        }
        else if (coordinates[vertical.style]) {
          ch = coordinates[vertical.style].call(this, j);
        }
        else {
          ch = j;
        }

        //Draw
        y = this.board.getAbsY(i);
        this.context.font = vertical.size(ch, cellSize) + ' ' + vertical.font;
        this.context.fillText(ch, xl, y);
        this.context.fillText(ch, xr, y);
      }

      //Draw horizontal coordinates
      for (i = 0; i < this.board.width; i++) {

        //Inverse?
        j = i;
        if (horizontal.inverse) {
          j = this.board.width - i - 1;
        }

        //Get character
        if (typeof horizontal.style === 'function') {
          ch = horizontal.style.call(this, j);
        }
        else if (coordinates[horizontal.style]) {
          ch = coordinates[horizontal.style].call(this, j);
        }
        else {
          ch = j;
        }

        //Draw
        x = this.board.getAbsX(i);
        this.context.font = horizontal.size(ch, cellSize) + ' ' + horizontal.font;
        this.context.fillText(ch, x, yt);
        this.context.fillText(ch, x, yb);
      }
    },
  };

  //Return
  return Coordinates;
});


text:
Does Waffle work on Linux?
==========================

Waffle relies on the [Windows SSPI](https://msdn.microsoft.com/en-us/library/windows/desktop/aa380493.aspx),
which doesn't exist on *nix.

For products that work cross-platform, see the [Waffle README](../../README.md) under *Related and Similar Products*.