text:
/*
 * obj_rec_ransac_result.cpp
 *
 *  Created on: Jan 23, 2013
 *      Author: papazov
 *
 *  Visualizes the result of the ObjRecRANSAC class.
 */

#include <pcl/segmentation/sac_segmentation.h>
#include <pcl/recognition/ransac_based/obj_rec_ransac.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/io/pcd_io.h>
#include <pcl/point_cloud.h>
#include <vtkPolyDataReader.h>
#include <vtkDoubleArray.h>
#include <vtkDataArray.h>
#include <vtkPointData.h>
#include <vtkHedgeHog.h>
#include <cstdio>
#include <vector>
#include <list>

using namespace std;
using namespace pcl;
using namespace io;
using namespace console;
using namespace recognition;
using namespace visualization;

class CallbackParameters;

void keyboardCB (const pcl::visualization::KeyboardEvent &event, void* params_void);
void update (CallbackParameters* params);
bool vtk2PointCloud (const char* file_name, PointCloud<PointXYZ>& pcl_points, PointCloud<Normal>& pcl_normals, vtkPolyData* vtk_data);
void run (float pair_width, float voxel_size, float max_coplanarity_angle);
bool loadScene (const char* file_name, PointCloud<PointXYZ>& non_plane_points, PointCloud<Normal>& non_plane_normals,
                PointCloud<PointXYZ>& plane_points);

//#define _SHOW_SCENE_POINTS_
#define _SHOW_OCTREE_POINTS_
//#define _SHOW_OCTREE_NORMALS_
//#define _SHOW_OCTREE_

class CallbackParameters
{
  public:
    CallbackParameters (ObjRecRANSAC& objrec, PCLVisualizer& viz, PointCloud<PointXYZ>& scene_points, PointCloud<Normal>& scene_normals)
    : objrec_ (objrec),
      viz_ (viz),
      scene_points_ (scene_points),
      scene_normals_ (scene_normals)
    {}

    ObjRecRANSAC& objrec_;
    PCLVisualizer& viz_;
    PointCloud<PointXYZ>& scene_points_;
    PointCloud<Normal>& scene_normals_;
    list<vtkActor*> actors_;
};

//===========================================================================================================================================

int
main (int argc, char** argv)
{
  printf ("\nUsage: ./pcl_obj_rec_ransac_scene_opps <pair_width> <voxel_size> <max_coplanarity_angle>\n\n");

  const int num_params = 3;
  float parameters[num_params] = {40.0f/*pair width*/, 5.0f/*voxel size*/, 15.0f/*max co-planarity angle*/};
  string parameter_names[num_params] = {"pair_width", "voxel_size", "max_coplanarity_angle"};

  // Read the user input if any
  for ( int i = 0 ; i < argc-1 && i < num_params ; ++i )
  {
    parameters[i] = static_cast<float> (atof (argv[i+1]));
    if ( parameters[i] <= 0.0f )
    {
      fprintf(stderr, "ERROR: the %i-th parameter has to be positive and not %f\n", i+1, parameters[i]);
      return (-1);
    }
  }

  printf ("The following parameter values will be used:\n");
  for ( int i = 0 ; i < num_params ; ++i )
    cout << "  " << parameter_names[i] << " = " << parameters[i] << endl;
  cout << endl;

  run (parameters[0], parameters[1], parameters[2]);
}

//===========================================================================================================================================

void
run (float pair_width, float voxel_size, float max_coplanarity_angle)
{
  // The object recognizer
  ObjRecRANSAC objrec (pair_width, voxel_size);
  objrec.setMaxCoplanarityAngleDegrees (max_coplanarity_angle);

  // The models to be loaded
  list<string> model_names;
  model_names.push_back (string ("tum_amicelli_box"));
  model_names.push_back (string ("tum_rusk_box"));
  model_names.push_back (string ("tum_soda_bottle"));

  list<PointCloud<PointXYZ>::Ptr> model_points_list;
  list<PointCloud<Normal>::Ptr> model_normals_list;
  list<vtkSmartPointer<vtkPolyData> > vtk_models_list;

  // Load the models and add them to the recognizer
  for ( list<string>::iterator it = model_names.begin () ; it != model_names.end () ; ++it )
  {
    PointCloud<PointXYZ>::Ptr model_points (new PointCloud<PointXYZ> ());
    model_points_list.push_back (model_points);

    PointCloud<Normal>::Ptr model_normals (new PointCloud<Normal> ());
    model_normals_list.push_back (model_normals);

    vtkSmartPointer<vtkPolyData> vtk_model = vtkSmartPointer<vtkPolyData>::New ();
    vtk_models_list.push_back (vtk_model);

    // Compose the file
    string file_name = string("../../test/") + *it + string (".vtk");

    // Get the points and normals from the input model
    if ( !vtk2PointCloud (file_name.c_str (), *model_points, *model_normals, vtk_model) )
      continue;

    // Add the model
    objrec.addModel (*model_points, *model_normals, *it, vtk_model);
  }

  // The scene in which the models are supposed to be recognized
  PointCloud<PointXYZ>::Ptr non_plane_points (new PointCloud<PointXYZ> ()), plane_points (new PointCloud<PointXYZ> ());
  PointCloud<Normal>::Ptr non_plane_normals (new PointCloud<Normal> ());

  // Detect the largest plane in the dataset
  if ( !loadScene ("../../test/tum_table_scene.vtk", *non_plane_points, *non_plane_normals, *plane_points) )
    return;

  // The parameters for the callback function and the visualizer
  PCLVisualizer viz;
  CallbackParameters params(objrec, viz, *non_plane_points, *non_plane_normals);
  viz.registerKeyboardCallback (keyboardCB, static_cast<void*> (&params));

  // Run the recognition and update the viewer. Have a look at this method, to see how to start the recognition and use the result!
  update (&params);

  // From this line on: visualization stuff only!
#ifdef _SHOW_OCTREE_
  show_octree(objrec.getSceneOctree (), viz);
#endif

#ifdef _SHOW_SCENE_POINTS_
  viz.addPointCloud (scene_points, "scene points");
  viz.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 2, "scene points");
#endif

#ifdef _SHOW_OCTREE_POINTS_
  PointCloud<PointXYZ>::Ptr octree_points (new PointCloud<PointXYZ> ());
  objrec.getSceneOctree ().getFullLeavesPoints (*octree_points);
  viz.addPointCloud (octree_points, "octree points");
//  viz.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "octree points");
  viz.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_COLOR, 1.0, 0.0, 0.0, "octree points");

  viz.addPointCloud (plane_points, "plane points");
  viz.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_COLOR, 0.9, 0.9, 0.9, "plane points");
#endif

#if defined _SHOW_OCTREE_NORMALS_ && defined _SHOW_OCTREE_POINTS_
  PointCloud<Normal>::Ptr normals_octree (new PointCloud<Normal> ());
  objrec.getSceneOctree ().getNormalsOfFullLeaves (*normals_octree);
  viz.addPointCloudNormals<PointXYZ,Normal> (points_octree, normals_octree, 1, 6.0f, "normals out");
#endif

  // Enter the main loop
  while (!viz.wasStopped ())
  {
    //main loop of the visualizer
    viz.spinOnce (100);
    boost::this_thread::sleep (boost::posix_time::microseconds (100000));
  }
}

//===============================================================================================================================

void
keyboardCB (const pcl::visualization::KeyboardEvent &event, void* params_void)
{
  if (event.getKeyCode () == 13 /*enter*/ && event.keyUp ())
    update (static_cast<CallbackParameters*> (params_void));
}

//===============================================================================================================================

void
update (CallbackParameters* params)
{
  // Clear the visualizer from old object instances
  vtkRenderer *renderer = params->viz_.getRenderWindow ()->GetRenderers ()->GetFirstRenderer ();
  for ( list<vtkActor*>::iterator it = params->actors_.begin () ; it != params->actors_.end () ; ++it )
    renderer->RemoveActor (*it);
  params->actors_.clear ();

  // This will be the output of the recognition
  list<ObjRecRANSAC::Output> rec_output;

  // For convenience
  ObjRecRANSAC& objrec = params->objrec_;

  // Run the recognition method
  objrec.recognize (params->scene_points_, params->scene_normals_, rec_output);
  int i = 0;

  // Show the hypotheses
  for ( list<ObjRecRANSAC::Output>::iterator it = rec_output.begin () ; it != rec_output.end () ; ++it, ++i )
  {
    cout << it->object_name_ << " has a confidence value of " << it->match_confidence_ << endl;

    // Make a copy of the VTK model
    vtkSmartPointer<vtkPolyData> vtk_model = vtkSmartPointer<vtkPolyData>::New ();
    vtk_model->DeepCopy (static_cast<vtkPolyData*> (it->user_data_));

    // Setup the matrix
    vtkSmartPointer<vtkMatrix4x4> vtk_mat = vtkSmartPointer<vtkMatrix4x4>::New ();
    vtk_mat->Identity ();
    const float *t = it->rigid_transform_;
    // Setup the rotation
    vtk_mat->SetElement (0, 0, t[0]); vtk_mat->SetElement (0, 1, t[1]); vtk_mat->SetElement (0, 2, t[2]);
    vtk_mat->SetElement (1, 0, t[3]); vtk_mat->SetElement (1, 1, t[4]); vtk_mat->SetElement (1, 2, t[5]);
    vtk_mat->SetElement (2, 0, t[6]); vtk_mat->SetElement (2, 1, t[7]); vtk_mat->SetElement (2, 2, t[8]);
    // Setup the translation
    vtk_mat->SetElement (0, 3, t[9]); vtk_mat->SetElement (1, 3, t[10]); vtk_mat->SetElement (2, 3, t[11]);

    // Setup the transform based on the matrix
    vtkSmartPointer<vtkTransform> vtk_transform = vtkSmartPointer<vtkTransform>::New ();
    vtk_transform->SetMatrix (vtk_mat);

    // Setup the transformator
    vtkSmartPointer<vtkTransformPolyDataFilter> vtk_transformator = vtkSmartPointer<vtkTransformPolyDataFilter>::New ();
    vtk_transformator->SetTransform (vtk_transform);
    vtk_transformator->SetInput (vtk_model);
    vtk_transformator->Update ();

    // Visualize
    vtkSmartPointer<vtkActor> vtk_actor = vtkSmartPointer<vtkActor>::New();
    vtkSmartPointer<vtkPolyDataMapper> vtk_mapper = vtkSmartPointer<vtkPolyDataMapper>::New ();
    vtk_mapper->SetInput(vtk_transformator->GetOutput ());
    vtk_actor->SetMapper(vtk_mapper);
    // Set the appearance & add to the renderer
    vtk_actor->GetProperty ()->SetColor (0.6, 0.7, 0.9);
    renderer->AddActor(vtk_actor);
    params->actors_.push_back (vtk_actor);

#ifdef _SHOW_TRANSFORM_SPACE_
    if ( transform_space.getPositionCellBounds ((*acc_hypo)->pos_id_, cb) )
    {
      sprintf (pos_cell_name, "cell [%i, %i, %i]\n", (*acc_hypo)->pos_id_[0], (*acc_hypo)->pos_id_[1], (*acc_hypo)->pos_id_[2]);
      params->viz_.addCube (cb[0], cb[1], cb[2], cb[3], cb[4], cb[5], 1.0, 1.0, 1.0, pos_cell_name);
    }
    else
      printf ("WARNING: no cell at position [%i, %i, %i]\n", (*acc_hypo)->pos_id_[0], (*acc_hypo)->pos_id_[1], (*acc_hypo)->pos_id_[2]);
#endif
  }
}

//===============================================================================================================================

bool
loadScene (const char* file_name, PointCloud<PointXYZ>& non_plane_points, PointCloud<Normal>& non_plane_normals,
    PointCloud<PointXYZ>& plane_points)
{
  PointCloud<PointXYZ>::Ptr all_points (new PointCloud<PointXYZ> ());
  PointCloud<Normal>::Ptr all_normals (new PointCloud<Normal> ());

  // Get the points and normals from the input scene
  if ( !vtk2PointCloud (file_name, *all_points, *all_normals, NULL) )
    return false;

  // Detect the largest plane and remove it from the sets
  pcl::ModelCoefficients::Ptr coefficients (new pcl::ModelCoefficients ());
  pcl::PointIndices::Ptr inliers (new pcl::PointIndices ());
  // Create the segmentation object
  pcl::SACSegmentation<pcl::PointXYZ> seg;
  // Optional
  seg.setOptimizeCoefficients (true);
  // Mandatory
  seg.setModelType (pcl::SACMODEL_PLANE);
  seg.setMethodType (pcl::SAC_RANSAC);
  seg.setDistanceThreshold (10.0);

  seg.setInputCloud (all_points);
  seg.segment (*inliers, *coefficients);

  if (inliers->indices.size () == 0)
  {
    PCL_ERROR ("Could not estimate a planar model for the given dataset.");
    return false;
  }

  // Copy the non-planar points
  non_plane_points.resize (all_points->size () - inliers->indices.size ());
  non_plane_normals.resize (all_points->size () - inliers->indices.size ());
  plane_points.resize (inliers->indices.size ());

  // Make sure that the ids are sorted
  sort (inliers->indices.begin (), inliers->indices.end ());
  size_t i, j, id;

  for ( i = 0, j = 0, id = 0 ; i < inliers->indices.size () ; )
  {
    if ( id == inliers->indices[i] )
    {
      plane_points.points[i] = all_points->points[id];
      ++id;
      ++i;
    }
    else
    {
      non_plane_points.points[j] = all_points->points[id];
      non_plane_normals.points[j] = all_normals->points[id];
      ++id;
      ++j;
    }
  }

  // Just copy the rest of the non-plane points
  for ( ; id < all_points->size () ; ++id, ++j )
  {
    non_plane_points.points[j] = all_points->points[id];
    non_plane_normals.points[j] = all_normals->points[id];
  }

  return true;
}

//===============================================================================================================================

bool
vtk2PointCloud (const char* file_name, PointCloud<PointXYZ>& pcl_points, PointCloud<Normal>& pcl_normals, vtkPolyData* vtk_data)
{
  size_t len = strlen (file_name);
  if ( file_name[len-3] != 'v' || file_name[len-2] != 't' || file_name[len-1] != 'k' )
  {
    fprintf (stderr, "ERROR: we need a .vtk object!\n");
    return false;
  }

  // Load the model
  vtkSmartPointer<vtkPolyDataReader> reader = vtkSmartPointer<vtkPolyDataReader>::New ();
  reader->SetFileName (file_name);
  reader->Update ();

  // Get the points
  vtkPolyData *vtk_poly = reader->GetOutput ();
  vtkPoints *vtk_points = vtk_poly->GetPoints ();
  vtkIdType num_points = vtk_points->GetNumberOfPoints ();
  double p[3];

  // Shall we copy the vtk object
  if ( vtk_data )
    vtk_data->DeepCopy (vtk_poly);

  pcl_points.resize (num_points);

  // Copy the points
  for ( vtkIdType i = 0 ; i < num_points ; ++i )
  {
    vtk_points->GetPoint (i, p);
    pcl_points[i].x = static_cast<float> (p[0]);
    pcl_points[i].y = static_cast<float> (p[1]);
    pcl_points[i].z = static_cast<float> (p[2]);
  }

  // Check if we have normals
  vtkDataArray *vtk_normals = vtk_poly->GetPointData ()->GetNormals ();
  if ( !vtk_normals )
    return false;

  pcl_normals.resize (num_points);
  // Copy the normals
  for ( vtkIdType i = 0 ; i < num_points ; ++i )
  {
    vtk_normals->GetTuple (i, p);
    pcl_normals[i].normal_x = static_cast<float> (p[0]);
    pcl_normals[i].normal_y = static_cast<float> (p[1]);
    pcl_normals[i].normal_z = static_cast<float> (p[2]);
  }

  return true;
}

//===============================================================================================================================


text:
package com.bt.pi.app.management;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.util.Arrays;
import java.util.concurrent.atomic.AtomicBoolean;

import org.junit.Before;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

import com.bt.pi.app.common.entities.InstanceTypeConfiguration;
import com.bt.pi.app.common.entities.InstanceTypes;
import com.bt.pi.app.common.id.PiIdBuilder;
import com.bt.pi.core.continuation.UpdateResolver;
import com.bt.pi.core.dht.BlockingDhtWriter;
import com.bt.pi.core.dht.DhtClientFactory;
import com.bt.pi.core.entity.PiEntity;
import com.bt.pi.core.id.KoalaIdFactory;
import com.bt.pi.core.id.PId;
import com.bt.pi.core.parser.KoalaJsonParser;
import com.bt.pi.core.parser.KoalaPiEntityFactory;

public class InstanceSeederTest {

    private AtomicBoolean writeSucceeded;
    @SuppressWarnings("unchecked")
    private Answer entityWrittenAnswer;
    private KoalaIdFactory koalaIdFactory;
    private PiIdBuilder piIdBuilder;
    private DhtClientFactory dhtClientFactory;
    private BlockingDhtWriter dhtWriterInstanceType;
    private PiEntity writtenEntity;
    private InstanceSeeder instanceSeeder;
    private PId instanceTypeId;

    @Before
    public void before() throws Exception {
        KoalaPiEntityFactory koalaPiEntityFactory = new KoalaPiEntityFactory();// {
        // @Override
        // protected String readFile(String aPiEntitiesJsonFile) throws IOException {
        // return
        // "{\"persistablePiEntityMappings\":[{\"type\" : \"InstanceTypes\", \"typeCode\" : 13, \"scheme\" : \"instancetypes\"}]}";
        // }
        // };
        koalaPiEntityFactory.setKoalaJsonParser(new KoalaJsonParser());
        koalaPiEntityFactory.setPiEntityTypes(Arrays.asList(new PiEntity[] { new InstanceTypes() }));
        // / koalaPiEntityFactory.setPersistedEntityMappings();

        koalaIdFactory = new KoalaIdFactory(99, 99);
        koalaIdFactory.setKoalaPiEntityFactory(koalaPiEntityFactory);
        piIdBuilder = new PiIdBuilder();
        piIdBuilder.setKoalaIdFactory(koalaIdFactory);

        instanceTypeId = piIdBuilder.getPId(new InstanceTypes());

        writtenEntity = null;
        writeSucceeded = new AtomicBoolean(true);

        dhtWriterInstanceType = mock(BlockingDhtWriter.class);

        entityWrittenAnswer = new Answer<Boolean>() {
            @Override
            public Boolean answer(InvocationOnMock invocation) throws Throwable {
                if (writeSucceeded.get()) {
                    writtenEntity = (PiEntity) invocation.getArguments()[1];
                }
                return writeSucceeded.get();
            }
        };

        dhtClientFactory = mock(DhtClientFactory.class);
        when(dhtClientFactory.createBlockingWriter()).thenReturn(dhtWriterInstanceType);

        instanceSeeder = new InstanceSeeder();
        instanceSeeder.setPiIdBuilder(piIdBuilder);
        instanceSeeder.setDhtClientFactory(dhtClientFactory);
    }

    @Test
    public void shouldConfigureInstanceTypes() throws Exception {
        // setup
        doAnswer(entityWrittenAnswer).when(dhtWriterInstanceType).writeIfAbsent(isA(PId.class), isA(InstanceTypes.class));
        InstanceTypeConfiguration type1 = new InstanceTypeConfiguration("m1.small", 1, 512, 10);
        InstanceTypeConfiguration type2 = new InstanceTypeConfiguration("m2.small", 2, 512, 5);
        InstanceTypeConfiguration type3 = new InstanceTypeConfiguration("m3.small", 3, 512, 1);

        String names = "m1.small;m2.small;m3.small";
        String cores = "1;2;3";
        String memory = "512;512;512";
        String disk = "10;5;1";

        // act
        boolean result = instanceSeeder.configureInstanceTypes(names, cores, memory, disk);

        // assert
        assertTrue(result);
        assertThatPiEntityIsCorrect(type1, type2, type3);
    }

    private void assertThatPiEntityIsCorrect(InstanceTypeConfiguration type1, InstanceTypeConfiguration type2, InstanceTypeConfiguration type3) {
        assertTrue(writtenEntity instanceof InstanceTypes);
        assertEquals(type1, ((InstanceTypes) writtenEntity).getInstanceTypeConfiguration(type1.getInstanceType()));
        assertEquals(type2, ((InstanceTypes) writtenEntity).getInstanceTypeConfiguration(type2.getInstanceType()));
        assertEquals(type3, ((InstanceTypes) writtenEntity).getInstanceTypeConfiguration(type3.getInstanceType()));
    }

    @Test
    public void shouldNotConfigureInstanceTypesIfAlreadyExists() throws Exception {
        // setup
        writeSucceeded.set(false);

        String names = "m1.small;m2.small;m3.small";
        String cores = "1;2;3";
        String memory = "512;512;512";
        String disk = "10;5;1";

        // act
        boolean result = instanceSeeder.configureInstanceTypes(names, cores, memory, disk);

        // assert
        assertFalse(result);
        assertEquals(null, writtenEntity);
    }

    @SuppressWarnings("unchecked")
    @Test
    public void shouldNotConfigureInstanceTypesIfArgumentNumbersMismatch() throws Exception {
        // setup
        writeSucceeded.set(false);

        String names = "m1.small;m2.small;m3.small";
        String cores = "1;2;3";
        String memory = "512;512;512";
        String disk = "10;5;1;4";

        // act
        boolean result = instanceSeeder.configureInstanceTypes(names, cores, memory, disk);

        // assert
        assertFalse(result);
        verify(dhtWriterInstanceType, never()).update(eq(instanceTypeId), isA(InstanceTypes.class), isA(UpdateResolver.class));
        assertEquals(null, writtenEntity);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package hcs

import (
	"time"

	"github.com/Microsoft/hcsshim/internal/logfields"
	"github.com/Microsoft/hcsshim/internal/timeout"
	"github.com/sirupsen/logrus"
)

// syscallWatcher is used as a very simple goroutine around calls into
// the platform. In some cases, we have seen HCS APIs not returning due to
// various bugs, and the goroutine making the syscall ends up not returning,
// prior to its async callback. By spinning up a syscallWatcher, it allows
// us to at least log a warning if a syscall doesn't complete in a reasonable
// amount of time.
//
// Usage is:
//
// completed := false
// go syscallWatcher(context, &completed)
// <syscall>
// completed = true
//
func syscallWatcher(context logrus.Fields, syscallCompleted *bool) {
	time.Sleep(timeout.SyscallWatcher)
	if *syscallCompleted {
		return
	}
	logrus.WithFields(context).
		WithField(logfields.Timeout, timeout.SyscallWatcher).
		Warning("Syscall did not complete within operation timeout. This may indicate a platform issue. If it appears to be making no forward progress, obtain the stacks and see if there is a syscall stuck in the platform API for a significant length of time.")
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width">
    <title>Тема classic</title>
    <link rel="stylesheet" href="bundle.css">

    Шапка

Заголовок первого уровня

Тело восстанавливает эксимер почти так же, как в резонаторе газового лазера. Гомогенная среда, в первом приближении, выталкивает нестационарный резонатор, как и предсказывает общая теория поля. Возмущение плотности, в рамках ограничений классической механики, выталкивает ускоряющийся пульсар только в отсутствие тепло- и массообмена с окружающей средой. В ряде недавних экспериментов плазма перманентно стабилизирует коллапсирующий лептон. Идеальная тепловая машина, по данным астрономических наблюдений, переворачивает ультрафиолетовый сверхпроводник.

Заголовок второго уровня

Тело восстанавливает эксимер почти так же, как в резонаторе газового лазера. Гомогенная среда, в первом приближении, выталкивает нестационарный резонатор, как и предсказывает общая теория поля. Возмущение плотности, в рамках ограничений классической механики, выталкивает ускоряющийся пульсар только в отсутствие тепло- и массообмена с окружающей средой. В ряде недавних экспериментов плазма перманентно стабилизирует коллапсирующий лептон. Идеальная тепловая машина, по данным астрономических наблюдений, переворачивает ультрафиолетовый сверхпроводник.

Заголовок третьего уровня

Тело восстанавливает эксимер почти так же, как в резонаторе газового лазера. Гомогенная среда, в первом приближении, выталкивает нестационарный резонатор, как и предсказывает общая теория поля. Возмущение плотности, в рамках ограничений классической механики, выталкивает ускоряющийся пульсар только в отсутствие тепло- и массообмена с окружающей средой. В ряде недавних экспериментов плазма перманентно стабилизирует коллапсирующий лептон. Идеальная тепловая машина, по данным астрономических наблюдений, переворачивает ультрафиолетовый сверхпроводник.

    Подвал


text:
describe Simms::Packet do

  SAMPLE_TIMESTAMP = '2012-06-27 16:16:08'
  SAMPLE_PACKET = 'FB10040002000015ABA0B0220100FF00FF00FFFFFFFFFFFF0100790E937900022A00FFFF0B351A820000C8000100040002000015ABA0B022010053696D6D734F666669636550616E656C0000'

  before(:all) do
    @beacon = Simms::Packet.parse(SAMPLE_TIMESTAMP, SAMPLE_PACKET)
  end

  it 'should parse valid packets' do
    Simms::Packet.parse(SAMPLE_TIMESTAMP, SAMPLE_PACKET).should_not be_nil
  end

  it 'should return the correct beacon type' do
    @beacon.should be_a(Simms::GlobalConfigBeacon)
  end

  it 'should correctly set the beacon\'s device UUID' do
    @beacon.uuid.should == '00-15-AB-A0-B0-22'
  end

  it 'should correctly set the beacon\'s timestamp' do
    @beacon.timestamp.should == Time.utc(2012,6,27,16,16,8)
  end

  it 'should return raise on invalid packet data' do
    lambda{Simms::Packet.parse(SAMPLE_TIMESTAMP, '1234')}.should raise_error
  end

end


text:
import { M, L } from "../../point/points"
import segments from "../../pathstring/segments"

export default function fromPolyline(node) {
  if (node.nodeName.toLowerCase() !== "polyline") {
    throw new Error("The element you provided in the `fromPolyline` function is not a valid SVG polyline node.")
  }

  const points = node.getAttribute("points")
  const coords = segments(points)[0]

  return coords.reduce(
    (acc, coord, index) => {
      // x coordinate
      if (index % 2 === 0) {
        const x = coord
        const y = coords[index + 1]

        return [
          ...acc,
          index === 0 ? M(x, y) : L(x, y),
        ]
      }

      return acc
    },
    [],
  )
}


text:
package net.venaglia.nondairy.soylang.parser;

import net.venaglia.nondairy.SoyTestUtil;
import org.jetbrains.annotations.NonNls;
import org.junit.Test;

import java.util.concurrent.TimeUnit;

/**
 * Created by IntelliJ IDEA.
 * User: ed
 * Date: Aug 18, 2010
 * Time: 10:39:10 PM
 */
@SuppressWarnings({ "HardCodedStringLiteral" })
public class SoyStructureParserTest extends BaseParserTest {

    @Override
    protected void parseImpl(TokenSource tokenSource) {
        new SoyStructureParser(tokenSource).parse();
    }

    @Test
    public void testMinimal() throws Exception {
        testNoErrorsImpl("minimal.soy");
    }

    @Test
    public void testAliases() throws Exception {
        testNoErrorsImpl("aliases.soy");
    }

    @Test
    public void testExample() throws Exception {
        testNoErrorsImpl("example.soy");
    }

    @Test
    public void testLet() throws Exception {
        testNoErrorsImpl("let.soy");
    }

    @Test
    public void testFeatures() throws Exception {
        testNoErrorsImpl("features.soy");
    }

    @Test
    public void testInnerParameters() throws Exception {
        testNoErrorsImpl("innerParams.soy");
    }

    @Test
    public void testInnerParametersNullable() throws Exception {
        testNoErrorsImpl("innerParamsNullable.soy");
    }

    @Test
    public void testInnerParametersComplex() throws Exception {
        testNoErrorsImpl("innerParamsComplex.soy");
    }

    @Test
    public void testInnerParametersComplex2() throws Exception {
        testNoErrorsImpl("innerParamsComplex2.soy");
    }

    @Test
    public void testEdgeCases() throws Exception {
        testNoErrorsImpl("edge-cases.soy");
    }

    @Test
    public void attributesKind() throws Exception {
        testNoErrorsImpl("attributes-kind.soy");
    }

    @Test
    public void testDelegatesDefault() throws Exception {
        testNoErrorsImpl("delegates-default.soy");
    }

    @Test
    public void testDelegatesOverride() throws Exception {
        testNoErrorsImpl("delegates-override.soy");
    }

    @Test
    public void testDelegatesCall() throws Exception {
        testNoErrorsImpl("delegates-call.soy");
    }

    @Test
    public void testCss() throws Exception {
        testNoErrorsImpl("css.soy");
    }

    @Test
    public void testDelegatesCallSimple() throws Exception {
        testNoErrorsImpl("delegates-simple.soy");
    }

    @Test
    public void testErrorCases() throws Exception {
        testParseSequence(SoyTestUtil.getTestSourceBuffer("error-cases.soy"), "YYINITIAL", "error-cases.soy");
    }

    @Test
    public void testBadParam() throws Exception {
        testParseSequence("{namespace foo.bar}\n{template .bam}\n{param :foo}value{/param}\n{/template}", "YYINITIAL", "inline-source");
    }

    @Test
    public void testInMultipleThreads() throws Exception {
        @NonNls
        String[] sources = {"example.soy","features.soy","edge-cases.soy", "example.soy","features.soy","edge-cases.soy"};
        SoyTestRunner[] threads = new SoyTestRunner[sources.length];
        for (int i = 0; i < threads.length; i++) {
            @NonNls String threadNameFormat = "soy test %d: %s";
            String name = String.format(threadNameFormat, i, sources[i]);
            threads[i] = new SoyTestRunner(TimeUnit.SECONDS, 6, sources[i], name);
        }
        for (Thread thread : threads) {
            thread.start();
        }
        for (Thread thread : threads) {
            thread.join();
        }
        for (SoyTestRunner thread : threads) {
            thread.representFail();
        }
    }

    private void testNoErrorsImpl(@NonNls String resourceName) throws Exception {
        testParseSequence(SoyTestUtil.getTestSourceBuffer(resourceName), "YYINITIAL", MockParseMetaToken.ASSERT_NO_ERRORS, resourceName);
    }

    private class SoyTestRunner extends Thread {

        private final long millis;
        private final String source;

        private Exception fail = null;

        public SoyTestRunner(TimeUnit unit,
                             int duration,
                             String source,
                             String name) {
            super(name);
            this.source = source;
            millis = unit.toMillis(duration);
        }

        @Override
        public void run() {
            long end = System.currentTimeMillis() + millis;
            try {
                do {
                    testNoErrorsImpl(source);
                } while (System.currentTimeMillis() < end);
            } catch (Exception e) {
                fail = e;
            }
        }

        public void representFail() throws Exception {
            if (fail != null) {
                throw fail;
            }
        }
    }
}


text:
/*
 * We use FT232RL chip in synchronous bit bang mode, as described
 * in FTDI Application Note AN232R-01:
 * "Bit Bang Modes for the FT232R and FT245R".
 *
 * On Linux, access to FTDI USB devices is restricted to root by default.
 * You can use 'sudo' to run the program, or open the user access
 * by creaating a rule for udev service:
 *      gedit /etc/udev/rules.d/10-ftdi.rules
 *
 * Add the following line:
 *      # FTDI USB-Serial
 *      SUBSYSTEM=="usb", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6001", GROUP="users", MODE="0666"
 *
 * On Mac OS X, in case you have FTDI Virtual Com Port (VCP) driver installed,
 * this needs to be disabled before bitbang mode will work;
 * the two cannot coexist. In a Terminal window, type:
 *
 *      sudo kextunload /System/Library/Extensions/IOUSBFamily.kext/Contents/PlugIns/AppleUSBFTDI.kext
 *
 * To restore the driver and resume using Arduino or other FTDI serial devices:
 *
 *      sudo kextload /System/Library/Extensions/IOUSBFamily.kext/Contents/PlugIns/AppleUSBFTDI.kext
 */
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <usb.h>
#include "bitbang.h"

#define VID_FTDI    0x0403
#define PID_FT232R  0x6001

/*
 * USB endpoints.
 */
#define IN_EP			0x02
#define OUT_EP			0x81

/* Requests */
#define SIO_RESET		0   /* Reset the port */
#define SIO_MODEM_CTRL		1   /* Set the modem control register */
#define SIO_SET_FLOW_CTRL	2   /* Set flow control register */
#define SIO_SET_BAUD_RATE	3   /* Set baud rate */
#define SIO_SET_DATA		4   /* Set the data characteristics of the port */
#define SIO_POLL_MODEM_STATUS	5
#define SIO_SET_EVENT_CHAR	6
#define SIO_SET_ERROR_CHAR	7
#define SIO_SET_LATENCY_TIMER	9
#define SIO_GET_LATENCY_TIMER	10
#define SIO_SET_BITMODE		11
#define SIO_READ_PINS		12
#define SIO_READ_EEPROM		0x90
#define SIO_WRITE_EEPROM	0x91
#define SIO_ERASE_EEPROM	0x92

static usb_dev_handle *adapter;

/*
 * On INT signal (^C pressed), close the connection and
 * terminate the process.
 */
static void sigint(int sig)
{
    bitbang_close();
    exit(-1);
}

/*
 * Connect to FT232RL adapter by name.
 * Configure needed pins as outputs by mask.
 */
int bitbang_open(char *device_desc, int output_mask)
{
    struct usb_bus *bus;
    struct usb_device *dev;
    char string [256];

    usb_init();
    usb_find_busses();
    usb_find_devices();
    for (bus = usb_get_busses(); bus; bus = bus->next) {
        for (dev = bus->devices; dev; dev = dev->next) {
            if (dev->descriptor.idVendor == VID_FTDI &&
                dev->descriptor.idProduct == PID_FT232R)
            {
                adapter = usb_open (dev);
                if (! adapter)
                    continue;

                /* Get product description string. */
                if (usb_get_string_simple (adapter, dev->descriptor.iProduct,
                    string, sizeof(string)) <= 0) {
                    if (errno == EPERM) {
                        printf("No access to FTDI USB-Serial device from user mode.\n");
                        printf("Please, run this application via 'sudo', or enable\n");
                        printf("user access to FTDI USB-Serial devices in /etc/udev/rules.d\n\n");
                    } else
                        printf("Cannot get iProduct string\n");
                    usb_close (adapter);
                    continue;
                }

                /* Select device by description. */
                if (strncmp (string, device_desc, sizeof(string)) != 0) {
                    printf("Device name '%s' don't match\n", string);
                    usb_close (adapter);
                    continue;
                }
                goto found;
            }
        }
    }
    printf("FTDI FT232R adapter not found.\n");
    return -1;

found:;

#if ! defined (__CYGWIN32__) && ! defined (MINGW32) && ! defined (__APPLE__)
    if (usb_get_driver_np (adapter, 0, string, sizeof(string)) == 0) {
        if (usb_detach_kernel_driver_np (adapter, 0) < 0) {
            printf("Failed to detach the '%s' kernel driver.\n", string);
            usb_close(adapter);
            return -1;
        }
    }
#endif
    usb_claim_interface (adapter, 0);

    /* Reset the device. */
    if (usb_control_msg (adapter,
        USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_OUT,
        SIO_RESET, 0, 0, 0, 0, 1000) != 0) {
            /* Unable to reset device. */
            printf("FT232R: Unable to reset device.\n");
            return -1;
    }

    /* Sync bit bang mode. */
    if (usb_control_msg (adapter,
        USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_OUT,
        SIO_SET_BITMODE, output_mask | 0x400,
        0, 0, 0, 1000) != 0) {
            printf("FT232R: Cannot set sync bitbang mode.\n");
            return -1;
    }

    /* Ровно 500 нсек между выдачами. */
    unsigned divisor = 1;
    unsigned latency_timer = 1;

    /* Frequency divisor is 14-bit non-zero value. */
    if (usb_control_msg (adapter,
        USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_OUT,
        SIO_SET_BAUD_RATE, divisor,
        0, 0, 0, 1000) != 0) {
            printf("FT232R: Cannot set baud rate.\n");
            return -1;
    }
    if (usb_control_msg (adapter,
        USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_OUT,
        SIO_SET_LATENCY_TIMER, latency_timer, 0, 0, 0, 1000) != 0) {
            printf("FT232R: Unable to set latency timer.\n");
            return -1;
    }

    atexit(bitbang_close);
    signal(SIGINT, sigint);
    return 0;
}

/*
 * Properly close the connection to FT232R adapter.
 */
void bitbang_close()
{
    if (adapter) {
        usb_release_interface(adapter, 0);
        usb_close(adapter);
        adapter = 0;
    }
}

/*
 * Perform sync bitbang output/input transaction.
 * Array output[] contains data to send.
 * Counter nbytes gives a length.
 * On return, received data are put back to array reply[64].
 */
int bitbang_io(unsigned char *output, int nbytes, unsigned char *reply)
{
    int bytes_to_write, bytes_written, n, txdone, rxdone;
    int empty_rxfifo, bytes_to_read, bytes_read;
    unsigned char buf[64];

    /* FIFO TX buffer of FT232R chip has size of 128 bytes.
     * FIFO RX buffer has 256 bytes. First two receive bytes
     * contain modem and line status. */
    if (nbytes <= 0)
        return -1;

    /* RX buffer is empty, except two status bytes. */
    empty_rxfifo = sizeof(buf) - 2;

    /* Indexes in data buffer. */
    txdone = 0;
    rxdone = 0;
    while (rxdone < nbytes) {
        /* Try to send as much as possible,
         * but avoid overflow of receive buffer. */
        bytes_to_write = 64;
        if (bytes_to_write > nbytes - txdone)
            bytes_to_write = nbytes - txdone;
        if (bytes_to_write > empty_rxfifo)
            bytes_to_write = empty_rxfifo;

        /* Write data. */
        bytes_written = 0;
        while (bytes_written < bytes_to_write) {
            /*printf("--usb bulk write %d bytes\n",
                bytes_to_write - bytes_written);*/
            n = usb_bulk_write (adapter, IN_EP,
                (char*) output + txdone + bytes_written,
                bytes_to_write - bytes_written, 1000);
            if (n < 0) {
                printf("FT232R: write failed (%u bytes)\n",
                    bytes_to_write - bytes_written);
                exit(-1);
            }
            /*if (n != bytes_to_write)
                printf("--usb bulk written %d bytes of %d\n",
                    n, bytes_to_write - bytes_written);*/
            bytes_written += n;
        }
        txdone += bytes_written;
        empty_rxfifo -= bytes_written;

        if (empty_rxfifo == 0 || txdone == nbytes) {
            /* Get reply. */
            bytes_to_read = sizeof(buf) - empty_rxfifo - 2;
            bytes_read = 0;
            while (bytes_read < bytes_to_read) {
                n = usb_bulk_read (adapter, OUT_EP,
                    (char*) buf,
                    bytes_to_read - bytes_read + 2, 2000);
                if (n < 0) {
                    printf("FT232R: read failed\n");
                    exit(-1);
                }
                /*if (n != bytes_to_read + 2)
                    printf("--usb error: bulk read %d bytes of %d\n",
                        n, bytes_to_read - bytes_read + 2);
                else
                    printf("--usb bulk read %d bytes\n", n)*/;

                if (n > 2) {
                    /* Copy data. */
                    if (reply)
                        memcpy (reply + rxdone, buf + 2, n - 2);
                    bytes_read += n;
                    rxdone += n - 2;
                }
            }
            empty_rxfifo = sizeof(buf) - 2;
        }
    }
    return 0;
}


text:
package com.rabbitframework.web.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtils {

    public static String getCookie(HttpServletRequest request, String cookieName) {

        Cookie[] cookies = request.getCookies();
        if (cookies == null)
            return null;
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(cookieName)) {
                return cookie.getValue();
            }
        }
        return null;
    }

    /**
     * 添加cookies,默认当前有效,httpOnly为false
     *
     * @param response
     * @param name     名称key
     * @param value    值
     * @param path     路径
     */
    public static void addCookies(HttpServletResponse response, String name,
                                  String value, String path) {
        addCookies(response, name, value, path, false);
    }

    /**
     * 添加cookies,默认当前有效
     *
     * @param response
     * @param name     名称key
     * @param value    值
     * @param path     路径
     * @param httpOnly 是否只读
     */
    public static void addCookies(HttpServletResponse response, String name, String value,
                                  String path, boolean httpOnly) {
        addCookies(response, name, value, -1, path, httpOnly);
    }

    public static void addCookies(HttpServletResponse response, String name, String value,
                                  String path, int expiry) {
        addCookies(response, name, value, expiry, path, false);
    }

    public static void addCookies(HttpServletResponse response, String name,
                                  String value, int expiry, String path, boolean httpOnly) {
        Cookie cookie = new Cookie(name, value);
        cookie.setHttpOnly(httpOnly);
        cookie.setMaxAge(expiry);
        cookie.setPath(path);
        response.addCookie(cookie);
    }

    public static void clearCookie(HttpServletResponse response, String key, String path) {
        Cookie cookie = new Cookie(key, null);
        cookie.setMaxAge(0);
        cookie.setPath(path);
        response.addCookie(cookie);
    }
}


text:
<?php

declare(strict_types=1);

/*
 * This file is part of the RollerworksSearch package.
 *
 * (c) Sebastiaan Stok <s.stok@rollerscapes.net>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Rollerworks\Component\Search\Doctrine\Dbal;

use Doctrine\DBAL\Query\QueryBuilder;
use Psr\SimpleCache\CacheInterface as Cache;
use Rollerworks\Component\Search\Doctrine\Dbal\Query\QueryGenerator;
use Rollerworks\Component\Search\SearchCondition;

/**
 * Handles caching of a Doctrine DBAL ConditionGenerator.
 *
 * Instead of using the ConditionGenerator directly you use the
 * CachedConditionGenerator as all related calls are delegated.
 *
 * The cache-key is a hashed (sha256) combination of the SearchCondition
 * (root ValuesGroup and FieldSet name) and configured field mappings.
 *
 * Caution: Any noticeable changes to your (FieldSet's) configuration
 * should purge all cached entries.
 */
final class CachedConditionGenerator extends AbstractCachedConditionGenerator implements ConditionGenerator
{
    private QueryBuilder $qb;
    private FieldConfigurationSet $fieldsConfig;

    /**
     * @param mixed|null $ttl
     */
    public function __construct(QueryBuilder $queryBuilder, SearchCondition $searchCondition, Cache $cacheDriver, $ttl = null)
    {
        parent::__construct($cacheDriver, $searchCondition, $ttl);

        $this->qb = $queryBuilder;
        $this->fieldsConfig = new FieldConfigurationSet($searchCondition->getFieldSet());
    }

    public function setField(string $fieldName, string $column, string $alias = null, string $type = 'string')
    {
        $this->fieldsConfig->setField($fieldName, $column, $alias, $type);

        return $this;
    }

    public function apply(): void
    {
        if ($this->isApplied) {
            trigger_error('SearchCondition was already applied. Ignoring operation.', \E_USER_WARNING);

            return;
        }

        $this->isApplied = true;

        $fields = $this->fieldsConfig->fields;
        $cacheKey = $this->getCacheKey($fields);
        $cached = $this->getFromCache($cacheKey);

        // Note that ordering is not part of the cache as this only applies at the root level
        // And is handled by QueryBuilder itself, making it possible to reuse the same condition
        // with a different ordering.

        if ($cached !== null) {
            [$whereClause, $parameters] = $cached;
        } else {
            $connection = $this->qb->getConnection();
            $generator = new QueryGenerator($connection, SqlConditionGenerator::getQueryPlatform($connection), $fields);

            $whereClause = $generator->getWhereClause($this->searchCondition);
            $parameters = $generator->getParameters();

            $this->storeInCache($whereClause, $cacheKey, $parameters);
        }

        QueryGenerator::applySortingTo($this->searchCondition->getPrimaryCondition()?->getOrder(), $this->qb, $fields);
        QueryGenerator::applySortingTo($this->searchCondition->getOrder(), $this->qb, $fields);

        if ($whereClause !== '') {
            $this->qb->andWhere($whereClause);

            foreach ($parameters as $name => [$value, $type]) {
                $this->qb->setParameter($name, $value, $type);
            }
        }
    }

    public function getQueryBuilder(): QueryBuilder
    {
        return $this->qb;
    }
}


text:
<!DOCTYPE html>

        <title>Class test</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link rel="stylesheet" href="lib/qunit.css" type="text/css" media="screen" />

Class test


text:
package com.hello.natives.vibrate;

import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import android.os.Vibrator;
import android.content.Context;

public class VibrateModule extends ReactContextBaseJavaModule {

	private ReactApplicationContext mReactApplicationContext;
	private Vibrator mVibrator;

	public VibrateModule(ReactApplicationContext reactContext) {
		super(reactContext);
		mVibrator = (Vibrator) reactContext.getSystemService(Context.VIBRATOR_SERVICE);
	}

	@ReactMethod
	public void vibrate(int millionseconds) {
		mVibrator.vibrate(millionseconds);
	}

	@Override
	public String getName() {
		return "VibrateAndroid";
	}
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using Cosmos.TestRunner;
using Sys = Cosmos.System;

namespace Cosmos.Compiler.Tests.Interfaces.Kernel
{
    public class ClassA : IInterfaceA
    {
        public virtual void PrintText()
        {
            this.PrintTextA();
        }

        public virtual void PrintTextA()
        {
            Console.WriteLine("PrintTextA : ClassA : InterfaceA");
        }
    }

    public class ClassB : ClassA, IInterfaceB
    {
        public override void PrintText()
        {
            base.PrintText();

            this.PrintTextB();
        }

        public virtual void PrintTextB()
        {
            Console.WriteLine("PrintTextB : ClassB : InterfaceB");
        }
    }

    public class ClassC : ClassB, IInterfaceB
    {
        public override void PrintText()
        {
            base.PrintText();

            base.PrintTextA();
            this.PrintTextA();

            base.PrintTextB();
            this.PrintTextB();
        }

        public override void PrintTextA()
        {
            Console.WriteLine("PrintTextA : ClassC : InterfaceA");
        }

        public override void PrintTextB()
        {
            Console.WriteLine("PrintTextB : ClassC : InterfaceB");
        }
    }

    public class ClassT<T> : ClassC, IInterfaceT<T>
    {
        public void PrintText(T aType)
        {
            this.PrintTextT(aType);
        }

        public void PrintTextT(T aType)
        {
            Console.WriteLine("PrintText<{0}> : ClassT : InterfaceT", typeof(T).ToString());
        }
    }

    public class Kernel : Sys.Kernel
    {
        protected override void BeforeRun()
        {
            Console.WriteLine("Cosmos booted successfully.");
        }

        protected override void Run()
        {
            var xA = new ClassA();
            var xB = new ClassB();
            var xC = new ClassC();
            var xT = new ClassT<string>();

            Console.WriteLine("-- A --");
            xA.PrintText();

            Console.WriteLine("-- B --");
            xB.PrintText();

            Console.WriteLine("-- C --");
            xC.PrintText();

            Console.WriteLine("-- T --");
            xT.PrintText("Test");

            TestController.Completed();
        }
    }
}


text:
It is possible to run Bitcoin Core as an
[I2P (Invisible Internet Project)](https://en.wikipedia.org/wiki/I2P)
service and connect to such services.

This [glossary](https://geti2p.net/en/about/glossary) may be useful to get
started with I2P terminology.

## Run Bitcoin Core with an I2P router (proxy)

A running I2P router (proxy) with [SAM](https://geti2p.net/en/docs/api/samv3)
enabled is required. Options include:

- [i2prouter (I2P Router)](https://geti2p.net), the official implementation in
  Java
- [i2pd (I2P Daemon)](https://github.com/PurpleI2P/i2pd)
  ([documentation](https://i2pd.readthedocs.io/en/latest)), a lighter
  alternative in C++ (successfully tested with version 2.23 and up; version 2.36
  or later recommended)
- [i2p-zero](https://github.com/i2p-zero/i2p-zero)
- [other alternatives](https://en.wikipedia.org/wiki/I2P#Routers)

Note the IP address and port the SAM proxy is listening to; usually, it is
`127.0.0.1:7656`.

Once an I2P router with SAM enabled is up and running, use the following Bitcoin
Core configuration options:

```
-i2psam=<ip:port>
     I2P SAM proxy to reach I2P peers and accept I2P connections (default:
     none)

-i2pacceptincoming
     If set and -i2psam is also set then incoming I2P connections are
     accepted via the SAM proxy. If this is not set but -i2psam is set
     then only outgoing connections will be made to the I2P network.
     Ignored if -i2psam is not set. Listening for incoming I2P
     connections is done through the SAM proxy, not by binding to a
     local address and port (default: 1)
```

In a typical situation, this suffices:

```
bitcoind -i2psam=127.0.0.1:7656
```

The first time Bitcoin Core connects to the I2P router, its I2P address (and
corresponding private key) will be automatically generated and saved in a file
named `i2p_private_key` in the Bitcoin Core data directory.

## Additional configuration options related to I2P

```
-debug=i2p
```

Set the `debug=i2p` config logging option to see additional information in the
debug log about your I2P configuration and connections. Run `bitcoin-cli help
logging` for more information.

```
-onlynet=i2p
```

Make outgoing connections only to I2P addresses. Incoming connections are not
affected by this option. It can be specified multiple times to allow multiple
network types, e.g. onlynet=ipv4, onlynet=ipv6, onlynet=onion, onlynet=i2p.

Warning: if you use -onlynet with values other than onion, and the -onion or
-proxy option is set, then outgoing onion connections will still be made; use
-noonion or -onion=0 to disable outbound onion connections in this case.

I2P support was added to Bitcoin Core in version 22.0 and there may be fewer I2P
peers than Tor or IP ones. Therefore, using I2P alone without other networks may
make a node more susceptible to [Sybil
attacks](https://en.bitcoin.it/wiki/Weaknesses#Sybil_attack). You can use
`bitcoin-cli -addrinfo` to see the number of I2P addresses known to your node.

Another consideration with `onlynet=i2p` is that the initial blocks download
phase when syncing up a new node can be very slow. This phase can be sped up by
using other networks, for instance `onlynet=onion`, at the same time.

In general, a node can be run with both onion and I2P hidden services (or
any/all of IPv4/IPv6/onion/I2P), which can provide a potential fallback if one
of the networks has issues.

## I2P-related information in Bitcoin Core

There are several ways to see your I2P address in Bitcoin Core:
- in the debug log (grep for `AddLocal`, the I2P address ends in `.b32.i2p`)
- in the output of the `getnetworkinfo` RPC in the "localaddresses" section
- in the output of `bitcoin-cli -netinfo` peer connections dashboard

To see which I2P peers your node is connected to, use `bitcoin-cli -netinfo 4`
or the `getpeerinfo` RPC (e.g. `bitcoin-cli getpeerinfo`).

To see which I2P addresses your node knows, use the `getnodeaddresses 0 i2p`
RPC.

## Compatibility

Bitcoin Core uses the [SAM v3.1](https://geti2p.net/en/docs/api/samv3) protocol
to connect to the I2P network. Any I2P router that supports it can be used.

## Ports in I2P and Bitcoin Core

Bitcoin Core uses the [SAM v3.1](https://geti2p.net/en/docs/api/samv3)
protocol. One particularity of SAM v3.1 is that it does not support ports,
unlike newer versions of SAM (v3.2 and up) that do support them and default the
port numbers to 0. From the point of view of peers that use newer versions of
SAM or other protocols that support ports, a SAM v3.1 peer is connecting to them
on port 0, from source port 0.

To allow future upgrades to newer versions of SAM, Bitcoin Core sets its
listening port to 0 when listening for incoming I2P connections and advertises
its own I2P address with port 0. Furthermore, it will not attempt to connect to
I2P addresses with a non-zero port number because with SAM v3.1 the destination
port (`TO_PORT`) is always set to 0 and is not in the control of Bitcoin Core.


text:
'use strict';

var arrify = require('arrify');
var assert = require('assert');
var extend = require('extend');
var googleProtoFiles = require('google-proto-files');
var mockery = require('mockery-next');

var util = require('../../lib/common/util.js');

var extended = false;
var fakeStreamRouter = {
  extend: function(Class, methods) {
    if (Class.name !== 'Logging') {
      return;
    }

    extended = true;
    methods = arrify(methods);
    assert.deepEqual(methods, [
      'getEntries',
      'getSinks'
    ]);
  }
};

var fakeUtil = extend({}, util, {
  makeAuthenticatedRequestFactory: util.noop
});

function FakeBucket() {
  this.calledWith_ = arguments;
}

function FakeDataset() {
  this.calledWith_ = arguments;
}

function FakeTopic() {
  this.calledWith_ = arguments;
}

function FakeEntry() {
  this.calledWith_ = arguments;
}

FakeEntry.fromApiResponse_ = function() {
  return arguments;
};

function FakeLog() {
  this.calledWith_ = arguments;
}

function FakeSink() {
  this.calledWith_ = arguments;
}

function FakeGrpcService() {
  this.calledWith_ = arguments;
}

describe('Logging', function() {
  var Logging;
  var logging;

  var PROJECT_ID = 'project-id';

  before(function() {
    mockery.registerMock('../../lib/common/grpc-service.js', FakeGrpcService);
    mockery.registerMock('../../lib/common/stream-router.js', fakeStreamRouter);
    mockery.registerMock('../../lib/common/util.js', fakeUtil);
    mockery.registerMock('../../lib/bigquery/dataset.js', FakeDataset);
    mockery.registerMock('../../lib/pubsub/topic.js', FakeTopic);
    mockery.registerMock('../../lib/storage/bucket.js', FakeBucket);
    mockery.registerMock('../../lib/logging/log.js', FakeLog);
    mockery.registerMock('../../lib/logging/entry.js', FakeEntry);
    mockery.registerMock('../../lib/logging/sink.js', FakeSink);

    mockery.enable({
      useCleanCache: true,
      warnOnUnregistered: false
    });

    Logging = require('../../lib/logging/index.js');
  });

  after(function() {
    mockery.deregisterAll();
    mockery.disable();
  });

  beforeEach(function() {
    logging = new Logging({
      projectId: PROJECT_ID
    });
    logging.projectId = PROJECT_ID;

    logging.request = util.noop;
  });

  after(function() {
    mockery.deregisterAll();
    mockery.disable();
  });

  describe('instantiation', function() {
    it('should extend the correct methods', function() {
      assert(extended); // See `fakeStreamRouter.extend`
    });

    it('should normalize the arguments', function() {
      var options = {
        projectId: PROJECT_ID,
        credentials: 'credentials',
        email: 'email',
        keyFilename: 'keyFile'
      };

      var normalizeArguments = fakeUtil.normalizeArguments;
      var normalizeArgumentsCalled = false;
      var fakeContext = {};

      fakeUtil.normalizeArguments = function(context, options_) {
        normalizeArgumentsCalled = true;
        assert.strictEqual(context, fakeContext);
        assert.strictEqual(options, options_);
        return options_;
      };

      Logging.call(fakeContext, options);
      assert(normalizeArgumentsCalled);

      fakeUtil.normalizeArguments = normalizeArguments;
    });

    it('should inherit from GrpcService', function() {
      assert(logging instanceof FakeGrpcService);

      var calledWith = logging.calledWith_[0];

      assert.strictEqual(calledWith.baseUrl, 'logging.googleapis.com');
      assert.strictEqual(calledWith.service, 'logging');
      assert.strictEqual(calledWith.apiVersion, 'v2');
      assert.deepEqual(calledWith.protoServices, {
        ConfigServiceV2:
          googleProtoFiles('logging', 'v2', 'logging_config.proto'),
        LoggingServiceV2: googleProtoFiles.logging.v2
      });
      assert.deepEqual(calledWith.scopes, [
        'https://www.googleapis.com/auth/cloud-platform'
      ]);
    });
  });

  describe('createSink', function() {
    var SINK_NAME = 'name';

    it('should throw if a name is not provided', function() {
      assert.throws(function() {
        logging.createSink();
      }, 'A sink name must be provided.');
    });

    it('should throw if a config object is not provided', function() {
      assert.throws(function() {
        logging.createSink(SINK_NAME);
      }, 'A sink configuration object must be provided.');
    });

    it('should set acls for a Bucket destination', function(done) {
      var bucket = new FakeBucket();

      var CONFIG = {
        destination: bucket
      };

      logging.setAclForBucket_ = function(name, config, callback) {
        assert.strictEqual(name, SINK_NAME);
        assert.strictEqual(config, CONFIG);
        callback(); // done()
      };

      logging.createSink(SINK_NAME, CONFIG, done);
    });

    it('should set acls for a Dataset destination', function(done) {
      var dataset = new FakeDataset();

      var CONFIG = {
        destination: dataset
      };

      logging.setAclForDataset_ = function(name, config, callback) {
        assert.strictEqual(name, SINK_NAME);
        assert.strictEqual(config, CONFIG);
        callback(); // done()
      };

      logging.createSink(SINK_NAME, CONFIG, done);
    });

    it('should set acls for a Topic destination', function(done) {
      var topic = new FakeTopic();

      var CONFIG = {
        destination: topic
      };

      logging.setAclForTopic_ = function(name, config, callback) {
        assert.strictEqual(name, SINK_NAME);
        assert.strictEqual(config, CONFIG);
        callback(); // done()
      };

      logging.createSink(SINK_NAME, CONFIG, done);
    });

    describe('API request', function() {
      it('should make the correct API request', function(done) {
        var config = {
          a: 'b',
          c: 'd'
        };

        var expectedConfig = extend({}, config, {
          name: SINK_NAME
        });

        logging.request = function(protoOpts, reqOpts) {
          assert.strictEqual(protoOpts.service, 'ConfigServiceV2');
          assert.strictEqual(protoOpts.method, 'createSink');

          var expectedProjectName = 'projects/' + logging.projectId;
          assert.strictEqual(reqOpts.projectName, expectedProjectName);
          assert.deepEqual(reqOpts.sink, expectedConfig);

          done();
        };

        logging.createSink(SINK_NAME, config, assert.ifError);
      });

      describe('error', function() {
        var error = new Error('Error.');
        var apiResponse = {};

        beforeEach(function() {
          logging.request = function(protoOpts, reqOpts, callback) {
            callback(error, apiResponse);
          };
        });

        it('should exec callback with error & API response', function(done) {
          logging.createSink(SINK_NAME, {}, function(err, sink, apiResponse_) {
            assert.strictEqual(err, error);
            assert.strictEqual(sink, null);
            assert.strictEqual(apiResponse_, apiResponse);

            done();
          });
        });
      });

      describe('success', function() {
        var apiResponse = {
          name: SINK_NAME
        };

        beforeEach(function() {
          logging.request = function(protoOpts, reqOpts, callback) {
            callback(null, apiResponse);
          };
        });

        it('should exec callback with Sink & API response', function(done) {
          var sink = {};

          logging.sink = function(name_) {
            assert.strictEqual(name_, SINK_NAME);
            return sink;
          };

          logging.createSink(SINK_NAME, {}, function(err, sink_, apiResponse_) {
            assert.ifError(err);

            assert.strictEqual(sink_, sink);
            assert.strictEqual(sink_.metadata, apiResponse);
            assert.strictEqual(apiResponse_, apiResponse);

            done();
          });
        });
      });
    });
  });

  describe('entry', function() {
    var RESOURCE = {};
    var DATA = {};

    it('should return an Entry object', function() {
      var entry = logging.entry(RESOURCE, DATA);
      assert(entry instanceof FakeEntry);
      assert.strictEqual(entry.calledWith_[0], RESOURCE);
      assert.strictEqual(entry.calledWith_[1], DATA);
    });
  });

  describe('getEntries', function() {
    it('should accept only a callback', function(done) {
      logging.request = function(protoOpts, reqOpts) {
        assert.deepEqual(reqOpts, {
          orderBy: 'timestamp desc',
          projectIds: [logging.projectId]
        });
        done();
      };

      logging.getEntries(assert.ifError);
    });

    it('should make the correct API request', function(done) {
      var options = {};

      logging.request = function(protoOpts, reqOpts) {
        assert.strictEqual(protoOpts.service, 'LoggingServiceV2');
        assert.strictEqual(protoOpts.method, 'listLogEntries');

        assert.deepEqual(reqOpts, extend(options, {
          orderBy: 'timestamp desc',
          projectIds: [logging.projectId]
        }));

        done();
      };

      logging.getEntries(options, assert.ifError);
    });

    it('should allow overriding orderBy', function(done) {
      var options = {
        orderBy: 'timestamp asc'
      };

      logging.request = function(protoOpts, reqOpts) {
        assert.deepEqual(reqOpts.orderBy, options.orderBy);
        done();
      };

      logging.getEntries(options, assert.ifError);
    });

    describe('error', function() {
      var error = new Error('Error.');
      var apiResponse = {};

      beforeEach(function() {
        logging.request = function(protoOpts, reqOpts, callback) {
          callback(error, apiResponse);
        };
      });

      it('should execute callback with error & API response', function(done) {
        logging.getEntries({}, function(err, entries, nextQuery, apiResponse_) {
          assert.strictEqual(err, error);
          assert.strictEqual(entries, null);
          assert.strictEqual(nextQuery, null);
          assert.strictEqual(apiResponse_, apiResponse);

          done();
        });
      });
    });

    describe('success', function() {
      var apiResponse = {
        entries: [
          {
            logName: 'syslog'
          }
        ]
      };

      beforeEach(function() {
        logging.request = function(protoOpts, reqOpts, callback) {
          callback(null, apiResponse);
        };
      });

      it('should build a nextQuery if necessary', function(done) {
        var nextPageToken = 'next-page-token';
        var apiResponseWithNextPageToken = extend({}, apiResponse, {
          nextPageToken: nextPageToken
        });
        var expectedNextQuery = {
          orderBy: 'timestamp desc',
          projectIds: [logging.projectId],
          pageToken: nextPageToken
        };

        logging.request = function(protoOpts, reqOpts, callback) {
          callback(null, apiResponseWithNextPageToken);
        };

        logging.getEntries({}, function(err, entries, nextQuery) {
          assert.ifError(err);

          assert.deepEqual(nextQuery, expectedNextQuery);

          done();
        });
      });

      it('should execute callback with entries & API resp', function(done) {
        logging.getEntries({}, function(err, entries, nextQuery, apiResponse_) {
          assert.ifError(err);

          var argsPassedToFromApiResponse_ = entries[0];
          assert.strictEqual(
            argsPassedToFromApiResponse_[0],
            apiResponse.entries[0]
          );

          assert.strictEqual(apiResponse_, apiResponse);

          done();
        });
      });
    });
  });

  describe('getSinks', function() {
    it('should accept only a callback', function(done) {
      logging.request = function() {
        done();
      };

      logging.getSinks(assert.ifError);
    });

    it('should make the correct API request', function(done) {
      logging.request = function(protoOpts, reqOpts) {
        assert.strictEqual(protoOpts.service, 'ConfigServiceV2');
        assert.strictEqual(protoOpts.method, 'listSinks');

        var expectedProjectName = 'projects/' + logging.projectId;
        assert.strictEqual(reqOpts.projectName, expectedProjectName);

        done();
      };

      logging.getSinks({}, assert.ifError);
    });

    describe('error', function() {
      var error = new Error('Error.');
      var apiResponse = {};

      beforeEach(function() {
        logging.request = function(protoOpts, reqOpts, callback) {
          callback(error, apiResponse);
        };
      });

      it('should execute callback with error & API response', function(done) {
        logging.getSinks({}, function(err, sinks, nextQuery, apiResponse_) {
          assert.strictEqual(err, error);
          assert.strictEqual(sinks, null);
          assert.strictEqual(nextQuery, null);
          assert.strictEqual(apiResponse_, apiResponse);

          done();
        });
      });
    });

    describe('success', function() {
      var apiResponse = {
        sinks: [
          {
            name: 'sink-name'
          }
        ]
      };

      beforeEach(function() {
        logging.request = function(protoOpts, reqOpts, callback) {
          callback(null, apiResponse);
        };
      });

      it('should build a nextQuery if necessary', function(done) {
        var nextPageToken = 'next-page-token';
        var apiResponseWithNextPageToken = extend({}, apiResponse, {
          nextPageToken: nextPageToken
        });
        var expectedNextQuery = {
          pageToken: nextPageToken
        };

        logging.request = function(protoOpts, reqOpts, callback) {
          callback(null, apiResponseWithNextPageToken);
        };

        logging.getSinks({}, function(err, sinks, nextQuery) {
          assert.ifError(err);

          assert.deepEqual(nextQuery, expectedNextQuery);

          done();
        });
      });

      it('should execute callback with Logs & API resp', function(done) {
        var log = {};

        logging.sink = function(name) {
          assert.strictEqual(name, apiResponse.sinks[0].name);
          return log;
        };

        logging.getSinks({}, function(err, sinks, nextQuery, apiResponse_) {
          assert.ifError(err);

          assert.strictEqual(sinks[0], log);
          assert.strictEqual(sinks[0].metadata, apiResponse.sinks[0]);

          assert.strictEqual(apiResponse_, apiResponse);

          done();
        });
      });
    });
  });

  describe('log', function() {
    var NAME = 'log-name';

    it('should return a Log object', function() {
      var log = logging.log(NAME);
      assert(log instanceof FakeLog);
      assert.strictEqual(log.calledWith_[0], logging);
      assert.strictEqual(log.calledWith_[1], NAME);
    });
  });

  describe('sink', function() {
    var NAME = 'sink-name';

    it('should return a Log object', function() {
      var sink = logging.sink(NAME);
      assert(sink instanceof FakeSink);
      assert.strictEqual(sink.calledWith_[0], logging);
      assert.strictEqual(sink.calledWith_[1], NAME);
    });
  });

  describe('setAclForBucket_', function() {
    var SINK_NAME = 'name';
    var CONFIG;

    var bucket;

    beforeEach(function() {
      bucket = new FakeBucket();
      bucket.name = 'bucket-name';
      bucket.acl = {
        owners: {
          addGroup: util.noop
        }
      };

      CONFIG = {
        destination: bucket
      };
    });

    it('should add cloud-logs as an owner', function(done) {
      bucket.acl.owners.addGroup = function(entity) {
        assert.strictEqual(entity, 'cloud-logs@google.com');
        done();
      };

      logging.setAclForBucket_(SINK_NAME, CONFIG, assert.ifError);
    });

    describe('error', function() {
      var error = new Error('Error.');
      var apiResponse = {};

      beforeEach(function() {
        bucket.acl.owners.addGroup = function(entity, callback) {
          callback(error, apiResponse);
        };
      });

      it('should return error and API response to callback', function(done) {
        logging.setAclForBucket_(SINK_NAME, CONFIG, function(err, sink, resp) {
          assert.strictEqual(err, error);
          assert.strictEqual(sink, null);
          assert.strictEqual(resp, apiResponse);

          done();
        });
      });
    });

    describe('success', function() {
      var apiResponse = {};

      beforeEach(function() {
        bucket.acl.owners.addGroup = function(entity, callback) {
          callback(null, apiResponse);
        };
      });

      it('should call createSink with string destination', function(done) {
        bucket.acl.owners.addGroup = function(entity, callback) {
          logging.createSink = function(name, config, callback) {
            assert.strictEqual(name, SINK_NAME);

            assert.strictEqual(config, CONFIG);

            var expectedDestination = 'storage.googleapis.com/' + bucket.name;
            assert.strictEqual(config.destination, expectedDestination);

            callback(); // done()
          };

          callback(null, apiResponse);
        };

        logging.setAclForBucket_(SINK_NAME, CONFIG, done);
      });
    });
  });

  describe('setAclForDataset_', function() {
    var SINK_NAME = 'name';
    var CONFIG;
    var dataset;

    beforeEach(function() {
      dataset = new FakeDataset();
      dataset.id = 'dataset-id';
      dataset.parent = {
        projectId: PROJECT_ID
      };

      CONFIG = {
        destination: dataset
      };
    });

    describe('metadata refresh', function() {
      describe('error', function() {
        var error = new Error('Error.');
        var apiResponse = {};

        beforeEach(function() {
          dataset.getMetadata = function(callback) {
            callback(error, null, apiResponse);
          };
        });

        it('should execute the callback with error & API resp', function(done) {
          logging.setAclForDataset_(SINK_NAME, CONFIG, function(err, _, resp) {
            assert.strictEqual(err, error);
            assert.strictEqual(_, null);
            assert.strictEqual(resp, apiResponse);
            done();
          });
        });
      });

      describe('success', function() {
        var apiResponse = {
          access: [{}, {}]
        };

        var originalAccess = [].slice.call(apiResponse.access);

        beforeEach(function() {
          dataset.getMetadata = function(callback) {
            callback(null, apiResponse, apiResponse);
          };
        });

        it('should set the correct metadata', function(done) {
          var access = {
            role: 'WRITER',
            groupByEmail: 'cloud-logs@google.com'
          };

          var expectedAccess = [].slice.call(originalAccess).concat(access);

          dataset.setMetadata = function(metadata) {
            assert.deepEqual(apiResponse.access, originalAccess);
            assert.deepEqual(metadata.access, expectedAccess);
            done();
          };

          logging.setAclForDataset_(SINK_NAME, CONFIG, assert.ifError);
        });

        describe('updating metadata error', function() {
          var error = new Error('Error.');
          var apiResponse = {};

          beforeEach(function() {
            dataset.setMetadata = function(metadata, callback) {
              callback(error, apiResponse);
            };
          });

          it('should exec callback with error & API response', function(done) {
            logging.setAclForDataset_(SINK_NAME, CONFIG, function(err, _, res) {
              assert.strictEqual(err, error);
              assert.strictEqual(_, null);
              assert.strictEqual(res, apiResponse);
              done();
            });
          });
        });

        describe('updating metadata success', function() {
          var apiResponse = {};

          beforeEach(function() {
            dataset.setMetadata = function(metadata, callback) {
              callback(null, apiResponse);
            };
          });

          it('should call createSink with string destination', function(done) {
            logging.createSink = function(name, config, callback) {
              var expectedDestination = [
                'bigquery.googleapis.com',
                'projects',
                dataset.parent.projectId,
                'datasets',
                dataset.id
              ].join('/');

              assert.strictEqual(name, SINK_NAME);
              assert.strictEqual(config, CONFIG);
              assert.strictEqual(config.destination, expectedDestination);
              callback(); // done()
            };

            logging.setAclForDataset_(SINK_NAME, CONFIG, done);
          });
        });
      });
    });
  });

  describe('setAclForTopic_', function() {
    var SINK_NAME = 'name';
    var CONFIG;
    var topic;

    beforeEach(function() {
      topic = new FakeTopic();
      topic.name = 'topic-name';
      topic.iam = {
        getPolicy: util.noop,
        setPolicy: util.noop
      };

      CONFIG = {
        destination: topic
      };
    });

    describe('get policy', function() {
      describe('error', function() {
        var error = new Error('Error.');
        var apiResponse = {};

        beforeEach(function() {
          topic.iam.getPolicy = function(callback) {
            callback(error, null, apiResponse);
          };
        });

        it('should execute the callback with error & API resp', function(done) {
          logging.setAclForTopic_(SINK_NAME, CONFIG, function(err, _, resp) {
            assert.strictEqual(err, error);
            assert.strictEqual(_, null);
            assert.strictEqual(resp, apiResponse);
            done();
          });
        });
      });

      describe('success', function() {
        var apiResponse = {
          bindings: [{}, {}]
        };

        var originalBindings = [].slice.call(apiResponse.bindings);

        beforeEach(function() {
          topic.iam.getPolicy = function(callback) {
            callback(null, apiResponse, apiResponse);
          };
        });

        it('should set the correct policy bindings', function(done) {
          var binding = {
            role: 'roles/pubsub.publisher',
            members: [
              'serviceAccount:cloud-logs@system.gserviceaccount.com'
            ]
          };

          var expectedBindings = [].slice.call(originalBindings);
          expectedBindings.push(binding);

          topic.iam.setPolicy = function(policy) {
            assert.strictEqual(policy, apiResponse);
            assert.deepEqual(policy.bindings, expectedBindings);
            done();
          };

          logging.setAclForTopic_(SINK_NAME, CONFIG, assert.ifError);
        });

        describe('updating policy error', function() {
          var error = new Error('Error.');
          var apiResponse = {};

          beforeEach(function() {
            topic.iam.setPolicy = function(policy, callback) {
              callback(error, null, apiResponse);
            };
          });

          it('should exec callback with error & API response', function(done) {
            logging.setAclForTopic_(SINK_NAME, CONFIG, function(err, _, res) {
              assert.strictEqual(err, error);
              assert.strictEqual(_, null);
              assert.strictEqual(res, apiResponse);
              done();
            });
          });
        });

        describe('updating policy success', function() {
          var apiResponse = {};

          beforeEach(function() {
            topic.iam.setPolicy = function(policy, callback) {
              callback(null, apiResponse);
            };
          });

          it('should call createSink with string destination', function(done) {
            logging.createSink = function(name, config, callback) {
              var expectedDestination = 'pubsub.googleapis.com/' + topic.name;
              assert.strictEqual(name, SINK_NAME);
              assert.strictEqual(config, CONFIG);
              assert.strictEqual(config.destination, expectedDestination);
              callback(); // done()
            };

            logging.setAclForTopic_(SINK_NAME, CONFIG, done);
          });
        });
      });
    });
  });
});


text:
module Omnibus
  class Compressor::Null < Compressor::Base
    id :null

    def package_name
      ""
    end

    def run!
      # noop
    end
  end
end


text:
/*
 * \brief
 * \author Sylvain Jaume, Francois Huguet
 */

# ifndef SO_VTK_HYPERSTREAMLINE_H_
# define SO_VTK_HYPERSTREAMLINE_H_

# include <Inventor/engines/SoSubEngine.h>

# include "xip/inventor/vtk/SoSFVtkAlgorithmOutput.h"
# include "xip/inventor/vtk/SoSFVtkObject.h"

# include "vtkHyperStreamline.h"

# include "Inventor/fields/SoSFInt32.h"
# include "Inventor/fields/SoSFFloat.h"
# include "xip/inventor/core/SbVariant.h"
# include "xip/inventor/core/SoMFVariant.h"

class SoVtkHyperStreamline : public SoEngine
{
	SO_ENGINE_HEADER( SoVtkHyperStreamline );

public:

	/// Constructor
	SoVtkHyperStreamline();

	/// Class Initialization
	static void initClass();

	// Inputs
	/// IntegrationEigenvector
	SoSFInt32 IntegrationEigenvector;
	/// Radius
	SoSFFloat Radius;
	/// StartPosition
	SoMFVariant StartPosition;
	/// IntegrationStepLength
	SoSFFloat IntegrationStepLength;
	/// MaximumPropagationDistance
	SoSFFloat MaximumPropagationDistance;
	/// LogScaling
	SoSFInt32 LogScaling;
	/// IntegrationDirection
	SoSFInt32 IntegrationDirection;
	/// NumberOfSides
	SoSFInt32 NumberOfSides;
	/// StepLength
	SoSFFloat StepLength;
	/// TerminalEigenvalue
	SoSFFloat TerminalEigenvalue;
	/// Input connection
	SoSFVtkAlgorithmOutput InputConnection;
	/// StartLocation
	SoMFVariant StartLocation;

	// Outputs
	/// SoSFVtkObject of type vtkPolyData
	SoEngineOutput Output;
	/// SoSFVtkAlgorithmOutput
	SoEngineOutput OutputPort;

protected:

	/// Destructor
	~SoVtkHyperStreamline();

	/// Evaluate Function
	virtual void evaluate();

	/// inputChanged Function
	virtual void inputChanged(SoField *);

	/// reset Function
	virtual void reset();

	/// vtkPolyData
	SoVtkObject *mOutput;

	/// vtkAlgorithm
	SoVtkAlgorithmOutput *mOutputPort;

private:

	vtkHyperStreamline* mObject;
	/// addCalled checks if the Add*() method has been called
	bool addCalled;
};

#endif // SO_VTK_HYPERSTREAMLINE_H_


text:
- Clone this repo to some neutral location (like /opt).
- Change ownership to your user (like `chown -R nick:nick /opt/wdir`).
- Go to wdir: `cd /opt/wdir`
- Run: `sudo ./install`.

## Usages

- Run `wdir add .` to add current dir to watch list


text:
<?xml version="1.0" encoding="UTF-8"?>
<sbml xmlns="http://www.sbml.org/sbml/level2/version4" level="2" version="4">
  <model id="parameterNamespace_speciesAndLocal">
    <listOfCompartments>
      <compartment id="compartment" size="1"/>
    </listOfCompartments>
    <listOfSpecies>
      <species id="S1" compartment="compartment" initialAmount="3e-015"/>
      <species id="S2" compartment="compartment" initialAmount="0"/>
      <species id="S3" compartment="compartment" initialAmount="0"/>
    </listOfSpecies>
    <listOfParameters>
      <parameter id="k" value="1" units="dimensionless"/>
    </listOfParameters>
    <listOfReactions>
      <reaction id="R2" reversible="false">
        <listOfReactants>
          <speciesReference species="S2"/>
        </listOfReactants>
        <listOfProducts>
          <speciesReference species="S3"/>
        </listOfProducts>
        <listOfModifiers>
          <modifierSpeciesReference species="S1"/>
        </listOfModifiers>
        <kineticLaw>
          <math xmlns="http://www.w3.org/1998/Math/MathML">
            <apply>
              <times/>
              <ci> compartment </ci>
              <ci> S2 </ci>
            </apply>
          </math>
          <listOfParameters>
            <parameter id="compartment" value="0.1" units="dimensionless"/>
          </listOfParameters>
        </kineticLaw>
      </reaction>
    </listOfReactions>
  </model>
</sbml>


text:
title: GPaste 3.0 released
author: Marc-Antoine Perennou
tags: GPaste, release, clipboard, gnome
---

Finally version 3.0 is there. It's lacking a few things that I wanted in, but I miss a lot of time these days, so I
postponed these for 3.1.

It's available [there](http://www.imagination-land.org/files/gpaste/gpaste-3.0.tar.xz), get it while it's hot!

## What's new?

- Various build fixes
- Support of gnome-control-center for setting keybindings
- Compatibility with newer gnome-shell

And don't forget to run `gpaste dr` aka `gpaste daemon-reexec` after upgrading GPaste to activate new functionalities ;)


text:
<?php

namespace app\modules\admin\models;

use Yii;

/**
 * This is the model class for table "trailer".
 */
class Trailer extends \app\modules\admin\models\base\Trailer
{
    /**
     * Возвращает подробное имя прицепа
     *
     * @return string
     */
    public function getFullName()
    {
        return $this->make_model . ' (' . $this->reg_number . ')';
    }
}


text:
/*
  DO NOT EDIT THIS FILE - the content was created using a source code generator
*/

#ifndef KDATECOMBOBOXSLOTS_H
#define KDATECOMBOBOXSLOTS_H

#include <QtCore/QObject>
#include <QtCore/QCoreApplication>
#include <QtCore/QList>
#include <QtCore/QString>

#include <KWidgetsAddons/KDateComboBox>

#include "qt5xhb_common.h"
#include "qt5xhb_macros.h"
#include "qt5xhb_utils.h"
#include "qt5xhb_signals.h"

class KDateComboBoxSlots: public QObject
{
  Q_OBJECT
  public:
  KDateComboBoxSlots(QObject *parent = 0);
  ~KDateComboBoxSlots();
  public slots:
  void dateEntered( const QDate & date );
  void dateChanged( const QDate & date );
  void dateEdited( const QDate & date );
};

#endif /* KDATECOMBOBOXSLOTS_H */


text:
const config = require('../../config/config')
const log = require('../../utilities/ColoredLog')
const Sequelize = require('sequelize')

var sequelize = new Sequelize(
	config.dbOptions.dbName,
	config.dbOptions.dbUser,
	config.dbOptions.dbPassword,
	{
		host: config.dbOptions.dbHost,
		port: config.dbOptions.dbPort,
		dialect: config.dbOptions.dbDialect,
		logging: config.dbOptions.loggingOption,
		charset: config.dbOptions.charsetOption,
		collate: config.dbOptions.collateOption
	}
);

module.exports.SystemUser = require('./AppModels/SystemUser')(sequelize, Sequelize)
module.exports.Contact = require('./AppModels/Contact')(sequelize, Sequelize)
module.exports.BlogPost = require('./AppModels/BlogPost')(sequelize, Sequelize)
module.exports.BlogCategories = require('./AppModels/BlogCategories')(sequelize, Sequelize)

module.exports.createTable = function () {
	var chk = false;

	try {
		sequelize.authenticate();
		chk = true;
		log.success('Connection established!')

		if (chk) {
			sequelize.sync({
				force: config.dbOptions.dbForceOption
			}).then(function () {
				log.success('Tables Created!')

			}).catch(function (err) {
				log.error('Error Occurd! in the DbContext Sync')
			});
		}

	} catch (e) {

		log.error('Error Occurd in the DbContext! CreateTable')

	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="slidingmenuoffset">100dp</dimen>
</resources>


text:
package org.apache.hadoop.hbase;

import org.apache.hadoop.hbase.testclassification.SmallTests;
import org.junit.Rule;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TestRule;

@Category({SmallTests.class})
public class TestTimeout {
  @Rule public final TestRule timeout = CategoryBasedTimeout.builder()
      .withTimeout(this.getClass())
      .withLookingForStuckThread(true)
      .build();

    @Test
    public void run1() throws InterruptedException {
        Thread.sleep(100);
    }

    /**
     * Enable to check if timeout works.
     * Can't enable as it waits 30seconds and expected doesn't do Exception catching
     */
    @Ignore @Test
    public void infiniteLoop() {
        while (true) {}
   }
}


text:
/**
 *
 * @author dpc22
 *
 */

package forces;

import java.util.List;

import jboxGlue.Mass;

public class CenterMass extends Force {

	private double myExponent = 0;
	private double myCenterX = 0;
	private double myCenterY = 0;
	private String TAG = "centermass";

	public CenterMass(double magnitude, double exponent) {
		super(magnitude);
		myExponent = exponent;
		TAG = "m";
	}

	/*
	 * This method should return the type of force that will be taken in for
	 * ApplyForce
	 */
	public double[] calculateForceVector(Mass m) {
		double[] directions = calculateDirection(m);
		// distance formula - this also gives magnitude to create unit vector
		double distance = Math.sqrt(Math.pow((directions[0]), 2) + Math.pow((directions[1]), 2));
		double magnitude = myMagnitude * Math.pow((1 / distance), myExponent);
		double[] unitVector = { directions[0] * magnitude, directions[1] * magnitude };
		double[] forceVector = { unitVector[0], unitVector[1] };
		return forceVector;
	}

	// This method calculates the direction that the force should be directed in
	public double[] calculateDirection(Mass m) {
		double[] directions = new double[2];
		directions[0] = myCenterX - m.x;
		directions[1] = myCenterY - m.y;
		return directions;
	}

	// This method takes all of the masses in the environment and creates the
	// center of mass location
	public void setCenter(List<Mass> massList) {
		double myX = 0;
		double myY = 0;
		for (Mass mass : massList) {
			myX += mass.x;
			myY += mass.y;
		}
		myCenterX = myX / massList.size();
		myCenterY = myY / massList.size();
	}

	public void setExponent(double exponent) {
		myExponent = exponent;
	}

	public void applyForce(List<Mass> list) {
		setCenter(list);
		for (Mass m : list) {
			double[] forceVector = calculateForceVector(m);
			m.setForce(forceVector[0], forceVector[1]);
		}
	}

	public String getTag() {
		return TAG;
	}

}


text:
<fieldset style="width: 300px; margin-top:1em; margin-bottom: 1em; border: 1px solid lightgrey;">
  The value is {{ value | json }}
</fieldset>

<jqxSlider [(ngModel)]="value" [width]="200" [height]="25" [value]="5"></jqxSlider>


text:
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ** This file is automatically generated by gapic-generator-typescript. **
// ** https://github.com/googleapis/gapic-generator-typescript **
// ** All changes to this file may be overwritten. **

'use strict';

function main() {
  // [START datastream_v1alpha1_generated_Datastream_FetchErrors_async]
  /**
   * This snippet has been automatically generated and should be regarded as a code template only.
   * It will require modifications to work.
   * It may require correct/in-range values for request initialization.
   * TODO(developer): Uncomment these variables before running the sample.
   */
  /**
   *  Name of the Stream resource for which to fetch any errors.
   */
  // const stream = 'abc123'

  // Imports the Datastream library
  const {DatastreamClient} = require('@google-cloud/datastream').v1alpha1;

  // Instantiates a client
  const datastreamClient = new DatastreamClient();

  async function callFetchErrors() {
    // Construct request
    const request = {
    };

    // Run request
    const [operation] = await datastreamClient.fetchErrors(request);
    const [response] = await operation.promise();
    console.log(response);
  }

  callFetchErrors();
  // [END datastream_v1alpha1_generated_Datastream_FetchErrors_async]
}

process.on('unhandledRejection', err => {
  console.error(err.message);
  process.exitCode = 1;
});
main(...process.argv.slice(2));


text:
<?php namespace Veemo\Themes\Adapters;

/**
 * Project: Veemo
 * User: ddedic
 * Email: dedic.d@gmail.com
 * Date: 16/03/15
 * Time: 23:42
 */

use Illuminate\Filesystem\Filesystem;
use Illuminate\Config\Repository;
use Illuminate\Support\Collection;

use Veemo\Core\Modules\Exceptions\FileMissingException;

/**
 * Class FileManagerAdapter
 * @package Veemo\Themes\Adapters
 */
class DummyManagerAdapter implements ThemeManagerAdapterInterface
{

    /**
     * @param $slug
     * @return bool
     */
    public function exist($slug)
    {
        // TODO: Implement exist() method.
    }

    /**
     * @return mixed
     */
    public function getAll()
    {
        $themes = [
            'Default' => [
                'slug' => 'default',
                'type' => 'frontend',
                'enabled' => true
            ],

            'test' => [
                'slug' => 'default',
                'type' => 'frontend',
                'enabled' => true
            ],

            'AdminLTE' => [
                'slug' => 'default',
                'type' => 'backend',
                'enabled' => true
            ]
        ];

        return new Collection($themes);
    }

    /**
     * @param bool $enabled
     * @return mixed
     */
    public function getFrontend($enabled = true)
    {

        $themes = [
            'Default' => [
                'slug' => 'default',
                'type' => 'frontend',
                'enabled' => true
            ],

            'test' => [
                'slug' => 'test',
                'type' => 'frontend',
                'enabled' => true
            ]
        ];

        return new Collection($themes);

    }

    /**
     * @param bool $enabled
     * @return mixed
     */
    public function getBackend($enabled = true)
    {
        $themes = [

            'default' => [
                'slug' => 'default',
                'type' => 'backend',
                'enabled' => true
            ]
        ];

        return new Collection($themes);

    }

    /**
     * @param $slug
     * @return mixed
     */
    public function find($slug)
    {
        // TODO: Implement find() method.
    }

    /**
     * @return bool
     */
    public function isEnabled($slug)
    {
        // TODO: Implement isEnabled() method.
    }

    /**
     * @return bool
     */
    public function isDisabled($slug)
    {
        // TODO: Implement isDisabled() method.
    }

    /**
     * @param $slug
     * @return mixed
     */
    public function enable($slug)
    {
        // TODO: Implement enable() method.
    }

    /**
     * @param $slug
     * @return mixed
     */
    public function disable($slug)
    {
        // TODO: Implement disable() method.
    }

    /**
     * @param $slug
     * @return mixed
     */
    public function setActive($slug)
    {
        // TODO: Implement setActive() method.
    }
}


text:
<!DOCTYPE html>

		<title>时髦网站__符海飞个人网站</title>

		<link rel="shortcut icon" type="image/x-icon" href="../../../images/favicon/favicon.ico">
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

		<link rel="stylesheet" type="text/css" href="http://apps.bdimg.com/libs/bootstrap/3.2.0/css/bootstrap.min.css">
		<link rel="stylesheet" href="css/style.css">

ACCOUNT

LOGIN

									<form id="loginForm">
										<fieldset id="body">
											<fieldset>
												Email Address
												<input type="text" name="email" id="email">
											</fieldset>
											<fieldset>
												Password
												<input type="password" name="password" id="password">
											</fieldset>
											<input type="submit" id="login" value="Sign in">

												<input type="checkbox" id="checkbox"> Remember me
										</fieldset>
										Forgot your password?
									</form>

Home

About

Gallery

News

Codes

Contact

						<form>
							<input class="sb-search-input" placeholder="search term..." type="search" name="search" id="search">
							<input class="sb-search-submit" type="submit" value="">

						</form>

About Us

Piece of classical by injected humourrandomised

Nam libero tempore cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus omnis optio cumque nihil impedit quo minus id quod maxime placeat facere possimus.Sed ut perspiciatis unde omnis iste natus
							error

Donec quam andomised words.

Etiam volutpa andomised words

Varius fusce domised words.

Lorem Ipsum is has a moreless

Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet embarrassing hidden in the middle of text.

Our Team

Vaura Tegsner

Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary

Jark Kohnson

Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary

Goes Mehak

Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary

Jark Kohnson

Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary

 © 2015 Stylish. All rights reserved | Design by 符海飞


text:
package com.yahoo.ycsb.generator;

import com.yahoo.ycsb.Utils;

/**
 * Generates longs randomly uniform from an interval.
 */
public class UniformLongGenerator extends NumberGenerator {
  private final long lb, ub, interval;

  /**
   * Creates a generator that will return longs uniformly randomly from the
   * interval [lb,ub] inclusive (that is, lb and ub are possible values)
   * (lb and ub are possible values).
   *
   * @param lb the lower bound (inclusive) of generated values
   * @param ub the upper bound (inclusive) of generated values
   */
  public UniformLongGenerator(long lb, long ub) {
    this.lb = lb;
    this.ub = ub;
    interval = this.ub - this.lb + 1;
  }

  @Override
  public Long nextValue() {
    long ret = Math.abs(Utils.random().nextLong()) % interval  + lb;
    setLastValue(ret);

    return ret;
  }

  @Override
  public double mean() {
    return ((lb + (long) ub)) / 2.0;
  }
}


text:
import Vue from 'vue'
import router from './router'
import App from 'views/app'

// promise polyfill
require('es6-promise').polyfill()

window.app = new Vue({ el: '#app', router, ...App })


text:
using System;
using Newtonsoft.Json;
using System.Linq.Expressions;
using Nest.Resolvers.Converters;

namespace Nest
{
	[JsonConverter(typeof(ReadAsTypeConverter<TimestampFieldMapping>))]
	public interface ITimestampFieldMapping : ISpecialField
	{
		[JsonProperty("enabled")]
		bool Enabled { get; set; }

		[JsonProperty("path")]
		PropertyPathMarker Path { get; set; }

		[JsonProperty("format")]
		string Format { get; set; }
	}

	public class TimestampFieldMapping : ITimestampFieldMapping
	{
		public bool Enabled { get; set; }

		public PropertyPathMarker Path { get; set; }

		public string Format { get; set; }
	}

	public class TimestampFieldMappingDescriptor<T> : ITimestampFieldMapping
	{
		private ITimestampFieldMapping Self { get { return this; } }

		bool ITimestampFieldMapping.Enabled { get; set;}

		PropertyPathMarker ITimestampFieldMapping.Path { get; set;}

		string ITimestampFieldMapping.Format { get; set; }

		public TimestampFieldMappingDescriptor<T> Enabled(bool enabled = true)
		{
			Self.Enabled = enabled;
			return this;
		}
		public TimestampFieldMappingDescriptor<T> Path(string path)
		{
			Self.Path = path;
			return this;
		}
		public TimestampFieldMappingDescriptor<T> Path(Expression<Func<T, object>> objectPath)
		{
			objectPath.ThrowIfNull("objectPath");
			Self.Path = objectPath;
			return this;
		}
		public TimestampFieldMappingDescriptor<T> Format(string format)
		{
			Self.Format = format;
			return this;
		}

	}
}