text:
import { Stream } from 'stream'

/**
 * @description lineNum start from 0
 * */
export function readStreamByLine(
  stream: NodeJS.ReadableStream,
  _onLine?: (line: string, lineNum: number) => void,
  _onError?: (e: Error) => void,
  _onComplete?: () => void,
) {
  const _lineStream = new Stream()
  let _lineNum = -1
  let acc = ''

  const onLine = (line: string) => {
    _lineNum++
    const data = { line, lineNum: _lineNum }
    _lineStream.emit('data', data)
    if (_onLine) {
      _onLine(line, _lineNum)
    }
  }
  const onError = (e: any) => {
    _lineStream.emit('error', e)
    if (_onError) {
      _onError(e)
    }
  }
  const onComplete = () => {
    if (acc !== '') {
      console.warn('stream ends without newline')
      onLine(acc)
    }
    _lineStream.emit('end')
    if (_onComplete) {
      _onComplete()
    }
  }

  stream.on('data', s => {
    acc += s
    const ss = acc.split('\n')
    if (ss.length === 1) {
      return
    }
    const n = ss.length - 1
    for (let i = 0; i < n; i++) {
      onLine(ss[i])
    }
    acc = ss[n]
  })
  stream.on('error', onError)
  stream.on('end', onComplete)

  return _lineStream
}

export function readStreamAllLine(
  stream: NodeJS.ReadableStream,
): Promise<string[]> {
  return new Promise<string[]>((resolve, reject) => {
    const lines: string[] = []
    readStreamByLine(
      stream,
      line => lines.push(line),
      e => reject(e),
      () => resolve(lines),
    )
  })
}

export function readStreamAsString(
  stream: NodeJS.ReadableStream,
  lineFeed = '\n',
): Promise<string> {
  return readStreamAllLine(stream).then(lines => lines.join(lineFeed))
}

redpajama_set_name: RedPajamaGithub


text:
package io.crate.sql.tree;

import java.util.List;
import java.util.Optional;

public final class CreateTable<T> extends Statement {

    private final Table<T> name;
    private final List<TableElement<T>> tableElements;
    private final Optional<PartitionedBy<T>> partitionedBy;
    private final Optional<ClusteredBy<T>> clusteredBy;
    private final boolean ifNotExists;
    private final GenericProperties<T> properties;

    public CreateTable(Table<T> name,
                       List<TableElement<T>> tableElements,
                       Optional<PartitionedBy<T>> partitionedBy,
                       Optional<ClusteredBy<T>> clusteredBy,
                       GenericProperties<T> genericProperties,
                       boolean ifNotExists) {
        this.name = name;
        this.tableElements = tableElements;
        this.partitionedBy = partitionedBy;
        this.clusteredBy = clusteredBy;
        this.ifNotExists = ifNotExists;
        this.properties = genericProperties;
    }

    public boolean ifNotExists() {
        return ifNotExists;
    }

    public Table<T> name() {
        return name;
    }

    public List<TableElement<T>> tableElements() {
        return tableElements;
    }

    public Optional<ClusteredBy<T>> clusteredBy() {
        return clusteredBy;
    }

    public Optional<PartitionedBy<T>> partitionedBy() {
        return partitionedBy;
    }

    public GenericProperties<T> properties() {
        return properties;
    }

    @Override
    public <R, C> R accept(AstVisitor<R, C> visitor, C context) {
        return visitor.visitCreateTable(this, context);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        CreateTable that = (CreateTable) o;

        if (ifNotExists != that.ifNotExists) return false;
        if (!name.equals(that.name)) return false;
        if (!tableElements.equals(that.tableElements)) return false;
        if (!partitionedBy.equals(that.partitionedBy)) return false;
        if (!clusteredBy.equals(that.clusteredBy)) return false;
        return properties.equals(that.properties);
    }

    @Override
    public int hashCode() {
        int result = name.hashCode();
        result = 31 * result + tableElements.hashCode();
        result = 31 * result + partitionedBy.hashCode();
        result = 31 * result + clusteredBy.hashCode();
        result = 31 * result + (ifNotExists ? 1 : 0);
        result = 31 * result + properties.hashCode();
        return result;
    }

    @Override
    public String toString() {
        return "CreateTable{" +
               "name=" + name +
               ", tableElements=" + tableElements +
               ", partitionedBy=" + partitionedBy +
               ", clusteredBy=" + clusteredBy +
               ", ifNotExists=" + ifNotExists +
               ", properties=" + properties +
               '}';
    }
}


text:
//
// Copyright 2014-2021 Cristian Maglie. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//

/*
Package serial is a cross-platform serial library for the go language.

The canonical import for this library is go.bug.st/serial so the import line
is the following:

	import "go.bug.st/serial"

It is possible to get the list of available serial ports with the
GetPortsList function:

	ports, err := serial.GetPortsList()
	if err != nil {
		log.Fatal(err)
	}
	if len(ports) == 0 {
		log.Fatal("No serial ports found!")
	}
	for _, port := range ports {
		fmt.Printf("Found port: %v\n", port)
	}

The serial port can be opened with the Open function:

	mode := &serial.Mode{
		BaudRate: 115200,
	}
	port, err := serial.Open("/dev/ttyUSB0", mode)
	if err != nil {
		log.Fatal(err)
	}

The Open function needs a "mode" parameter that specifies the configuration
options for the serial port. If not specified the default options are 9600_N81,
in the example above only the speed is changed so the port is opened using 115200_N81.
The following snippets shows how to declare a configuration for 57600_E71:

	mode := &serial.Mode{
		BaudRate: 57600,
		Parity: serial.EvenParity,
		DataBits: 7,
		StopBits: serial.OneStopBit,
	}

The configuration can be changed at any time with the SetMode function:

	err := port.SetMode(mode)
	if err != nil {
		log.Fatal(err)
	}

The port object implements the io.ReadWriteCloser interface, so we can use
the usual Read, Write and Close functions to send and receive data from the
serial port:

	n, err := port.Write([]byte("10,20,30\n\r"))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Sent %v bytes\n", n)

	buff := make([]byte, 100)
	for {
		n, err := port.Read(buff)
		if err != nil {
			log.Fatal(err)
			break
		}
		if n == 0 {
			fmt.Println("\nEOF")
			break
		}
		fmt.Printf("%v", string(buff[:n]))
	}

If a port is a virtual USB-CDC serial port (for example an USB-to-RS232
cable or a microcontroller development board) is possible to retrieve
the USB metadata, like VID/PID or USB Serial Number, with the
GetDetailedPortsList function in the enumerator package:

	import "go.bug.st/serial/enumerator"

	ports, err := enumerator.GetDetailedPortsList()
	if err != nil {
		log.Fatal(err)
	}
	if len(ports) == 0 {
		fmt.Println("No serial ports found!")
		return
	}
	for _, port := range ports {
		fmt.Printf("Found port: %s\n", port.Name)
		if port.IsUSB {
			fmt.Printf("   USB ID     %s:%s\n", port.VID, port.PID)
			fmt.Printf("   USB serial %s\n", port.SerialNumber)
		}
	}

for details on USB port enumeration see the documentation of the specific package.

This library tries to avoid the use of the "C" package (and consequently the need
of cgo) to simplify cross compiling.
Unfortunately the USB enumeration package for darwin (MacOSX) requires cgo
to access the IOKit framework. This means that if you need USB enumeration
on darwin you're forced to use cgo.
*/
package serial


text:
'use strict';

require('mocha');
var fs = require('fs');
var del = require('delete');
var path = require('path');
var assert = require('assert');
var mkdirp = require('mkdirp');
var background = require('../');

var fixtures = path.join.bind(path, __dirname, 'fixtures');
var actual = path.join.bind(path, __dirname, 'actual');

describe('background-process', function() {
  beforeEach(mkdirp.bind(mkdirp, actual()));
  afterEach(del.bind(del, actual()));

  it('should return the child process id', function() {
    this.timeout(10000);
    var stdout = fs.openSync(actual('stdout.txt'), 'a');
    var stderr = fs.openSync(actual('stderr.txt'), 'a');

    // start the worker and pass options
    var childPid = background.start(fixtures('worker.js'), {
        stdio: [stdout, stderr]
    });

    assert(childPid, 'expected to return the child process ID');
    assert.equal(typeof childPid, 'number');
  });

  it('should export an object', function() {
    assert(background);
    assert.equal(typeof background, 'object');
  });

  it('should run a worker script', function(cb) {
    this.timeout(10000);
    var stdout = fs.openSync(actual('stdout.txt'), 'a');
    var stderr = fs.openSync(actual('stderr.txt'), 'a');

    // start the worker and pass options
    background.start(fixtures('worker.js'), {
      stdio: [stdout, stderr],
      timeout: 1000
    });

    setTimeout(function() {
      var contents = fs.readFileSync(actual('stdout.txt'), 'utf8');
      assert.equal(contents, 'doing something for the specified amount of time\n');
    }, 500);

    setTimeout(function() {
      var contents = fs.readFileSync(actual('stdout.txt'), 'utf8');
      assert.equal(contents, 'doing something for the specified amount of time\nfinished doing something\n');
      cb();
    }, 2000);
  });
});


text:
package unsw.curation.api.domain.abstraction;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

import unsw.curation.api.domain.Classification;

public interface IClassificationTextLogisticRegression {

	void LoadDataset(File arffFileName) throws IOException;
	List<Classification> EvaluateLogisticRegression() throws Exception;
	void LearnLogisticRegression() throws Exception;
	void SaveModel(String modelName) throws FileNotFoundException, IOException;
}


text:
package io.katharsis.jackson;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.katharsis.jackson.serializer.IncludedRelationshipExtractor;
import io.katharsis.queryParams.RequestParams;
import io.katharsis.queryParams.RequestParamsBuilder;
import io.katharsis.request.path.FieldPath;
import io.katharsis.request.path.ResourcePath;
import io.katharsis.resource.field.ResourceField;
import io.katharsis.resource.RestrictedQueryParamsMembers;
import io.katharsis.resource.mock.models.Project;
import io.katharsis.resource.mock.models.Task;
import io.katharsis.response.Container;
import io.katharsis.response.ResourceResponse;
import org.junit.Before;
import org.junit.Test;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;

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

public class IncludedRelationshipExtractorTest {

    private IncludedRelationshipExtractor sut;
    private ResourceField resourceField;

    @Before
    public void setUp() throws Exception {
        sut = new IncludedRelationshipExtractor();
        Field someField = Task.class.getDeclaredField("project");
        List<Annotation> declaredAnnotations = Arrays.asList(someField.getDeclaredAnnotations());
        resourceField = new ResourceField(someField.getName(), someField.getType(), someField.getGenericType(),
            declaredAnnotations);
    }

    @Test
    public void onEmptyInclusionShouldReturnEmptySet() throws Exception {
        // GIVEN
        ResourceResponse response = new ResourceResponse(null, null, new RequestParams(null), null);

        // WHEN
        Set result = sut.extractIncludedResources(new Project(), Collections.<ResourceField>emptySet(), response);

        // THEN
        assertThat(result).isEmpty();
    }

    @Test
    public void onDefaultNullInclusionShouldReturnEmptySet() throws Exception {
        // GIVEN
        ResourceResponse response = new ResourceResponse(null, null, new RequestParams(null), null);

        // WHEN
        Set result = sut.extractIncludedResources(new Task(), Collections.singleton(resourceField), response);

        // THEN
        assertThat(result).isEmpty();
    }

    @Test
    public void onDefaultInclusionShouldReturnOneElement() throws Exception {
        // GIVEN
        ResourceResponse response = new ResourceResponse(null, null, new RequestParams(null), null);
        Task resource = new Task();
        Project project = new Project();
        resource.setProject(project);

        // WHEN
        Set<?> result = sut.extractIncludedResources(resource, Collections.singleton(resourceField), response);

        // THEN
        assertThat(result).containsExactly(new Container(project, new RequestParams(null)));
    }

    @Test
    public void onInclusionShouldReturnOneElement() throws Exception {
        // GIVEN
        RequestParams requestParams = getRequestParamsWithInclusion("[\"project\"]");

        ResourceResponse response = new ResourceResponse(null, new ResourcePath("tasks"), requestParams, null);
        Task resource = new Task();
        Project project = new Project();
        resource.setProject(project);

        // WHEN
        Set<?> result = sut.extractIncludedResources(resource, Collections.emptySet(), response);

        // THEN
        assertThat(result).containsExactly(new Container(project, new RequestParams(null)));
    }

    @Test
    public void onNullInclusionShouldReturnEmptySet() throws Exception {
        // GIVEN
        RequestParams requestParams = getRequestParamsWithInclusion("[]");
        ResourceResponse response = new ResourceResponse(null, new ResourcePath("tasks"), requestParams, null);

        // WHEN
        Set<?> result = sut.extractIncludedResources(null, Collections.emptySet(), response);

        // THEN
        assertThat(result).isEmpty();
    }

    @Test
    public void onFieldInclusionShouldReturnOneElement() throws Exception {
        // GIVEN
        RequestParams requestParams = getRequestParamsWithInclusion("[\"task.project\"]");

        ResourceResponse response = new ResourceResponse(null, new FieldPath("project"), requestParams, null);
        Task resource = new Task();
        Project project = new Project();
        resource.setProject(project);

        // WHEN
        Set<?> result = sut.extractIncludedResources(resource, Collections.emptySet(), response);

        // THEN
        assertThat(result).containsExactly(new Container(project, new RequestParams(null)));
    }

    @Test
    public void onMultipleFieldsInclusionShouldReturnOneElement() throws Exception {
        // GIVEN
        RequestParams requestParams = getRequestParamsWithInclusion("[\"classBs.classCs\"]");

        ResourceResponse response = new ResourceResponse(null, new ResourcePath("classAs"), requestParams, null);
        ClassC classC = new ClassC();
        ClassA classA = new ClassA(new ClassB(classC));

        // WHEN
        Set<?> result = sut.extractIncludedResources(classA, Collections.emptySet(), response);

        // THEN
        assertThat(result).containsExactly(new Container(classC, new RequestParams(null)));
    }

    @Test
    public void onNullFieldInclusionShouldReturnEmptySet() throws Exception {
        // GIVEN
        RequestParams requestParams = getRequestParamsWithInclusion("[\"task.project\"]");
        ResourceResponse response = new ResourceResponse(null, new FieldPath("tasks"), requestParams, null);
        Task resource = new Task();

        // WHEN
        Set<?> result = sut.extractIncludedResources(resource, Collections.emptySet(), response);

        // THEN
        assertThat(result).isEmpty();
    }

    private RequestParams getRequestParamsWithInclusion(String project1) {
        RequestParamsBuilder requestParamsBuilder = new RequestParamsBuilder(new ObjectMapper());
        return requestParamsBuilder.buildRequestParams(Collections.singletonMap(RestrictedQueryParamsMembers.include.name(), project1));
    }

    public static class ClassA {
        private final List<ClassB> classBs;

        public ClassA(ClassB classBs) {
            this.classBs = Collections.singletonList(classBs);
        }

        public List<ClassB> getClassBs() {
            return classBs;
        }
    }

    public static class ClassB {
        private final List<ClassC> classCs;

        public ClassB(ClassC classCs) {
            this.classCs = Collections.singletonList(classCs);
        }

        public List<ClassC> getClassCs() {
            return classCs;
        }
    }

    private static class ClassC {
    }
}


text:
@implementation iAmHearGraph

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        for(int i = 0; i < 30; ++i){
            vals[i] = 0;
        }
        threshold = 0.01;
    }
    return self;
}

-(void) setVals:(double*) val
{
    for(int i = 0; i < 10; ++i){
        vals[9-i] = val[i];
    }

}

-(void) setThreshold:(double) val
{
    threshold = val;
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    CGContextRef context    = UIGraphicsGetCurrentContext();

    CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);

    // Draw them with a 2.0 stroke width so they are a bit more visible.
    CGContextSetLineWidth(context, 2.0);

    CGContextMoveToPoint(context, 250,190); //start at this point

    for(int i = 0; i < 10; ++i){
        CGContextAddLineToPoint(context, 250.0 - i/10.0*250.0 - 15.0, 190 - vals[i]/(threshold*2)*190);
        CGContextMoveToPoint(context, 250.0 - i/10.0*250.0 - 15.0, 190 - vals[i]/(threshold*2)*190);
    }
    CGContextAddLineToPoint(context, 0, 190);

    CGContextStrokePath(context);

    context    = UIGraphicsGetCurrentContext();

    CGContextSetStrokeColorWithColor(context, [UIColor greenColor].CGColor);

    float dash[2]={6 ,5}; // pattern 6 times "solid", 5 times "empty"

    CGContextSetLineDash(context,0,dash,2);

    CGContextMoveToPoint(context, 250,190-0.002/0.008*190); //start at this point

    CGContextAddLineToPoint(context, 0,190-0.002/0.008*190);

    float normal[1]={1};
    CGContextSetLineDash(context,0,normal,0);

    CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);

    // and now draw the Path!
    CGContextStrokePath(context);

}

@end


text:
using System;

namespace Carbonfrost.Commons.Shared {

	[Flags]
	public enum ServiceStates {
	    None= 0,
	    Starting = 1,
	    Started = 2,
	    StartedWithErrors = Started | WithErrors,
	    Disposing = 4,
	    Disposed = 8,
	    DisposedWithErrors = Disposed | WithErrors,
	    WithErrors = 0x100,
	    WithDeferral = 0x200,
	    WithFrozenState = 0x400,
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Verrucaria cretophila Oxner

### Remarks
null


text:
<?php

declare(strict_types=1);

namespace Railt\SDL;

use GraphQL\Contracts\TypeSystem\SchemaInterface;
use Phplrt\Contracts\Source\ReadableInterface;

/**
 * Interface CompilerInterface
 */
interface CompilerInterface
{
    /**
     * Loads GraphQL source into the compiler.
     *
     * @param ReadableInterface|string|resource|mixed $source
     * @param array $variables
     * @return CompilerInterface|$this
     */
    public function preload($source, array $variables = []): self;

    /**
     * Compiles the sources and all previously loaded types
     * into the final document.
     *
     * @param ReadableInterface|string|resource|mixed $source
     * @param array $variables
     * @return SchemaInterface
     */
    public function compile($source, array $variables = []): SchemaInterface;
}


text:
package uk.ac.ebi.spot.goci.curation.model;

/**
 * Created by emma on 19/01/15.
 *
 * @author emma
 *         <p>
 *         Service class to deal with processing string containing country of origin value, these appear as separate
 *         tags in HTML view
 */
public class CountryOfOrigin {

    private String[] originCountryValues;

    public CountryOfOrigin() {

    }

    public CountryOfOrigin(String[] originCountryValues) {
        this.originCountryValues = originCountryValues;
    }

    public String[] getOriginCountryValues() {
        return originCountryValues;
    }

    public void setOriginCountryValues(String[] originCountryValues) {
        this.originCountryValues = originCountryValues;
    }
}


text:
package ua.goit.dao;

import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ua.goit.model.User;

import java.util.List;

@Component("userDao")
public class UserDaoImpl extends AbstractDao<User> implements UserDao {

  @Autowired
  public UserDaoImpl(SessionFactory sessionFactory) {
    super(sessionFactory, User.class);
  }

  @Override
  public User create(User user) {
    sessionFactory.getCurrentSession()
        .persist(user);

    return user;
  }

  @Override
  public User delete(User user) {
    throw new UnsupportedOperationException();
  }

  @Override
  public User update(User user) {
    throw new UnsupportedOperationException();
  }

  @Override
  public User findById(Integer id) {
    throw new UnsupportedOperationException();
  }

  @Override
  public User findByToken(String token) {
    List<User> users = sessionFactory.getCurrentSession()
        .createCriteria(User.class)
        .add(Restrictions.eq("token", token))
        .list();

    return users.isEmpty() ? null : users.get(0);
  }
}


text:
package org.wso2.siddhi.plugins.idea.psi;

import com.intellij.lang.ASTNode;
import org.antlr.jetbrains.adaptor.psi.ANTLRPsiNode;
import org.jetbrains.annotations.NotNull;

public class IdNode extends ANTLRPsiNode {
    public IdNode(@NotNull ASTNode node) {
        super(node);
    }
}


text:
package org.spanna.event.inventory;

public enum InventoryType {

    /**
     * A chest inventory, with 0, 9, 18, 27, 36, 45, or 54 slots of type
     * CONTAINER.
     */
    CHEST(27,"Chest"),
    /**
     * A dispenser inventory, with 9 slots of type CONTAINER.
     */
    DISPENSER(9,"Dispenser"),
    /**
     * A dropper inventory, with 9 slots of type CONTAINER.
     */
    DROPPER(9, "Dropper"),
    /**
     * A furnace inventory, with a RESULT slot, a CRAFTING slot, and a FUEL
     * slot.
     */
    FURNACE(3,"Furnace"),
    /**
     * A workbench inventory, with 9 CRAFTING slots and a RESULT slot.
     */
    WORKBENCH(10,"Crafting"),
    /**
     * A player's crafting inventory, with 4 CRAFTING slots and a RESULT slot.
     * Also implies that the 4 ARMOR slots are accessible.
     */
    CRAFTING(5,"Crafting"),
    /**
     * An enchantment table inventory, with one CRAFTING slot and three
     * enchanting buttons.
     */
    ENCHANTING(1,"Enchanting"),
    /**
     * A brewing stand inventory, with one FUEL slot and three CRAFTING slots.
     */
    BREWING(4,"Brewing"),
    /**
     * A player's inventory, with 9 QUICKBAR slots, 27 CONTAINER slots, and 4
     * ARMOR slots. The ARMOUR slots may not be visible to the player, though.
     */
    PLAYER(36,"Player"),
    /**
     * The creative mode inventory, with only 9 QUICKBAR slots and nothing
     * else. (The actual creative interface with the items is client-side and
     * cannot be altered by the server.)
     */
    CREATIVE(9,"Creative"),
    /**
     * The merchant inventory, with 2 TRADE-IN slots, and 1 RESULT slot.
     */
    MERCHANT(3,"Villager"),
    /**
     * The ender chest inventory, with 27 slots.
     */
    ENDER_CHEST(27,"Ender Chest"),
    /**
     * An anvil inventory, with 2 CRAFTING slots and 1 RESULT slot
     */
    ANVIL(3, "Repairing"),
    /**
     * A beacon inventory, with 1 CRAFTING slot
     */
    BEACON(1, "container.beacon"),
    /**
     * A hopper inventory, with 5 slots of type CONTAINER.
     */
    HOPPER(5, "Item Hopper"),
    ;

    private final int size;
    private final String title;

    private InventoryType(int defaultSize, String defaultTitle) {
        size = defaultSize;
        title = defaultTitle;
    }

    public int getDefaultSize() {
        return size;
    }

    public String getDefaultTitle() {
        return title;
    }

    public enum SlotType {
        /**
         * A result slot in a furnace or crafting inventory.
         */
        RESULT,
        /**
         * A slot in the crafting matrix, or the input slot in a furnace
         * inventory, the potion slot in the brewing stand, or the enchanting
         * slot.
         */
        CRAFTING,
        /**
         * An armour slot in the player's inventory.
         */
        ARMOR,
        /**
         * A regular slot in the container or the player's inventory; anything
         * not covered by the other enum values.
         */
        CONTAINER,
        /**
         * A slot in the bottom row or quickbar.
         */
        QUICKBAR,
        /**
         * A pseudo-slot representing the area outside the inventory window.
         */
        OUTSIDE,
        /**
         * The fuel slot in a furnace inventory, or the ingredient slot in a
         * brewing stand inventory.
         */
        FUEL;
    }
}


text:
package sri.web.examples.routerexample

import sri.universal.components._
import sri.web.all._
import sri.web.examples.routerexample.WebRouterExample._
import sri.web.examples.styles.Colors
import sri.web.router
import sri.web.router.{WebDynamicPage, WebRouterComponent, WebStaticPage}
import sri.web.styles.WebStyleSheet

import scala.scalajs.js
import scala.scalajs.js.Dynamic.{literal => json}
import scala.scalajs.js.annotation.ScalaJSDefined
import scala.scalajs.js.{UndefOr => U}

object TopNav {

  @ScalaJSDefined
  class Component extends WebRouterComponent[Unit, Unit] {
    def render() = {
      View(style = styles.navMenu)(
        getStaticItem("Home", HomePage),
        getStaticItem("Static Query", StaticQueryPage, query = new StaticQuery(sorting = "ASC", option = js.undefined)),
        getStaticItem("Static State", StaticStatePage, state = json(counter = 10)),
        getDynamicItem("Dynamic", DynamicPage, "123"),
        getDynamicItem("Dynamic Query", DynamicQueryPage, "125", query = json(includeDuplicates = true)),
        getDynamicItem("Dynamic State", DynamicStatePage, "129", state = json(hasChild = true)),
        getStaticItem("Items", ItemsRouteModule.All)
      )
    }

    def getStaticItem(text: String, page: WebStaticPage, query: js.UndefOr[js.Object] = js.undefined, state: js.UndefOr[js.Object] = js.undefined) = {
      TouchableHighlight(style = styles.menuItem(page == currentRoute.page),
        onPress = () => navigateTo(page, query = query, state = state))(
          Text()(text)
        )
    }

    def getDynamicItem(text: String, page: WebDynamicPage[_], placeholder: String, query: js.UndefOr[js.Object] = js.undefined, state: js.UndefOr[js.Object] = js.undefined) = {
      TouchableHighlight(style = styles.menuItem(page == currentRoute.page),
        onPress = () => navigateToDynamic(page, placeholder = placeholder, query = query, state = state))(
          Text()(text)
        )
    }
  }

  @ScalaJSDefined
  class StaticQuery(val sorting: String, val option: js.UndefOr[String] = js.undefined) extends js.Object

  object styles extends WebStyleSheet {

    val navMenu = style(
      flexDirection.row,
      alignItems.center,
      backgroundColor := Colors.blue,
      margin := 0,
      paddingLeft := 40)

    def menuItem(selected: Boolean) = {
      val bg = if (selected) Colors.darkBlue else Colors.transparent
      val fw = if (selected) "500" else "normal"
      style(
        padding := 20,
        fontSize := "1.5em",
        cursor.pointer,
        color := "rgb(244, 233, 233)",
        backgroundColor := bg,
        fontWeight := fw,
        marginLeft := "10px",
        marginRight := "10px"
      )
    }

  }

  val ctor = getTypedConstructor(js.constructorOf[Component], classOf[Component])

  ctor.contextTypes = router.routerContextTypes

  def apply(ref: js.UndefOr[String] = "", key: js.Any = {}) = createElementNoProps(ctor)

}


text:
package com.invariantproperties.sandbox.springentitylistener.listener;

import java.util.Properties;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.apache.log4j.Logger;
import org.hibernate.ejb.HibernatePersistence;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;

/**
 * @author Bear Giles <bgiles@coyotesong.com>
 */
@Configuration
@ComponentScan(basePackages = { "com.invariantproperties.sandbox.springentitylistener.persistence",
        "com.invariantproperties.sandbox.springentitylistener.listener",
        "com.invariantproperties.sandbox.springentitylistener.service" })
@EnableJpaRepositories(basePackages = { "com.invariantproperties.sandbox.springentitylistener.repository" })
@ImportResource("classpath:applicationContext.xml")
@PropertySource("classpath:application.properties")
public class ApplicationContext implements DisposableBean {
    private static final Logger log = Logger.getLogger(ApplicationContext.class);

    private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
    private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
    private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
    private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";

    private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
    private static final String PROPERTY_NAME_HIBERNATE_FORMAT_SQL = "hibernate.format_sql";
    private static final String PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY = "hibernate.ejb.naming_strategy";
    private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
    private static final String PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO = "hibernate.hbm2ddl.auto";
    private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";
    // private static final String PROPERTY_NAME_PERSISTENCE_UNIT_NAME =
    // "persistence.unit.name";

    @Resource
    private Environment environment;

    private EmbeddedDatabase db;

    @Bean
    public DataSource dataSource() {
        EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
        db = builder.setType(EmbeddedDatabaseType.H2).build();
        return db;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws ClassNotFoundException {
        LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean();

        System.out.println("url: " + environment.getProperty(PROPERTY_NAME_DATABASE_URL));

        bean.setDataSource(dataSource());
        bean.setPackagesToScan(environment.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
        bean.setPersistenceProviderClass(HibernatePersistence.class);
        // bean.setPersistenceUnitName(environment
        // .getRequiredProperty(PROPERTY_NAME_PERSISTENCE_UNIT_NAME));

        HibernateJpaVendorAdapter va = new HibernateJpaVendorAdapter();
        bean.setJpaVendorAdapter(va);

        Properties jpaProperties = new Properties();
        jpaProperties.put(PROPERTY_NAME_HIBERNATE_DIALECT,
                environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
        jpaProperties.put(PROPERTY_NAME_HIBERNATE_FORMAT_SQL,
                environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_FORMAT_SQL));
        jpaProperties.put(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY,
                environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY));
        jpaProperties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL,
                environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
        jpaProperties.put(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO,
                environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO));

        bean.setJpaProperties(jpaProperties);

        return bean;
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        JpaTransactionManager tm = new JpaTransactionManager();

        try {
            tm.setEntityManagerFactory(this.entityManagerFactory().getObject());
        } catch (ClassNotFoundException e) {
            log.info("class not found: " + e.getMessage());
        }

        return tm;
    }

    @Override
    public void destroy() {
        if (db != null) {
            db.shutdown();
            db = null;
        }
    }
}


text:
FROM ubuntu:14.04
MAINTAINER Mike Bartoli "michael.bartoli@pomona.edu"

RUN apt-get update && apt-get install -y build-essential \
	python \
	python-dev \
	python-setuptools \
	python-numpy \
	git

WORKDIR /home
RUN git clone https://github.com/saffsd/langid.py

WORKDIR /home/langid.py
RUN python setup.py build
RUN python setup.py install

WORKDIR /home/langid.py/langid
#RUN python langid.py -s


text:
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    qDebug("6! is %d", MathFunctions::factorial(6));
    return a.exec();
}


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(parent) {
  // [START dialogflow_v2_generated_Participants_SuggestFaqAnswers_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.
   */
  /**
   *  Required. The name of the participant to fetch suggestion for.
   *  Format: `projects/<Project ID>/locations/<Location
   *  ID>/conversations/<Conversation ID>/participants/<Participant ID>`.
   */
  // const parent = 'abc123'
  /**
   *  Optional. The name of the latest conversation message to compile suggestion
   *  for. If empty, it will be the latest message of the conversation.
   *  Format: `projects/<Project ID>/locations/<Location
   *  ID>/conversations/<Conversation ID>/messages/<Message ID>`.
   */
  // const latestMessage = 'abc123'
  /**
   *  Optional. Max number of messages prior to and including
   *  latest_message  to use as context when compiling the
   *  suggestion. By default 20 and at most 50.
   */
  // const contextSize = 1234
  /**
   *  Parameters for a human assist query.
   */
  // const assistQueryParams = {}

  // Imports the Dialogflow library
  const {ParticipantsClient} = require('@google-cloud/dialogflow').v2;

  // Instantiates a client
  const dialogflowClient = new ParticipantsClient();

  async function callSuggestFaqAnswers() {
    // Construct request
    const request = {
      parent,
    };

    // Run request
    const response = await dialogflowClient.suggestFaqAnswers(request);
    console.log(response);
  }

  callSuggestFaqAnswers();
  // [END dialogflow_v2_generated_Participants_SuggestFaqAnswers_async]
}

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


text:
![Go](https://github.com/openconfig/goyang/workflows/Go/badge.svg?branch=master)
[![Coverage Status](https://coveralls.io/repos/github/openconfig/goyang/badge.svg?branch=master)](https://coveralls.io/github/openconfig/goyang?branch=master)

Current support for `goyang` is for the [latest 3 Go releases](https://golang.org/project/#release).

# goyang
YANG parser and compiler for Go programs.

The yang package (pkg/yang) is used to convert a YANG schema into either an
in memory abstract syntax trees (ast) or more fully resolved, in memory, "Entry"
trees.  An Entry tree consists only of Entry structures and has had
augmentation, imports, and includes all applied.

goyang is a sample program that uses the yang (pkg/yang) package.

goyang uses the yang package to create an in-memory tree representation of
schemas defined in YANG and then dumps out the contents in several forms.
The forms include:

*  tree - a simple tree representation
*  types - list understood types extracted from the schema

The yang package, and the goyang program, are not complete and are a work in
progress.

For more complex output types, such as Go structs, and protobuf messages
please use the [openconfig/ygot](https://github.com/openconfig/ygot) package,
which uses this package as its backend.

### Getting started

To build goyang, ensure you have go language tools installed
(available at [golang.org](https://golang.org/dl)) and that the `GOPATH`
environment variable is set to your Go workspace.

1. `go get github.com/openconfig/goyang`
    * This will download goyang code and dependencies into the src
subdirectory in your workspace.

2. `cd <workspace>/src/github.com/openconfig/goyang`

3. `go build`

   * This will build the goyang binary and place it in the bin
subdirectory in your workspace.

### Contributing to goyang

goyang is still a work-in-progress and we welcome contributions.  Please see
the `CONTRIBUTING` file for information about how to contribute to the codebase.

### Disclaimer

This is not an official Google product.


text:
import {Component,Input, OnInit } from '@angular/core';
import {TranslateService} from '@ngx-translate/core';

/**Object*/
import { QuestionGroup } from '../../model/questiongroup.ts';
import { Question } from '../../model/question.ts';
/**Service*/
import { QuestionGroupService } from '../../services/questiongroup.service.ts';
import { QuestionService } from '../../services/question.service.ts';
/**Service Dialog*/
import { QuestionFormDialogsService } from '../../services/questionform-dialog.service.ts';

@Component({
   selector: 'project-form',
  //selector: 'list-guestion-ingroup',
  //styleUrls: ['/_pluggable/pypollmanage/javascript/pages/sample2/project/table-pagination-example.css'],
  templateUrl: '/_pluggable/pypollmanage/javascript/pages/sample2/controller/listquestion/listquestion.component.html',
})
export class ListQuestionComponent implements OnInit{
    selectLang : string;
    questionGroup:QuestionGroup;
    selectQuestion:Question;
    constructor( private translate: TranslateService,
                private questionGroupService: QuestionGroupService,
                private questionFormDialogsService: QuestionFormDialogsService,
                private questionService: QuestionService

          ){

      this.selectLang = 'th';
      translate.addLangs(["en", "th"]);
      translate.setDefaultLang('th');

        //let browserLang = translate.getBrowserLang();
        //translate.use(browserLang.match(/en|fr/) ? browserLang : 'fr');
        //translate.use("en");
    };

    ngOnInit() {
        console.log("ngOnInit: listquestion.component");
        this.questionGroup = new QuestionGroup();
        this.questionGroup.id_question_group = 211;
        this.questionGroup.id_question_project = 109;
        this.questionGroupService.changeQuestionGroup(this.questionGroup);
        this.questionService.currentQuestion.subscribe(question => this.showQuestion(question));

    };

    showLanguage() {
        if (this.selectLang === 'th'){
            this.selectLang = 'en';
            }
        else{
            this.selectLang = 'th';
            }
        this.translate.use(this.selectLang);
    }

    addQuestion():void{
        console.log("add Question");
        console.log( this.questionGroup.id_question_group );
        console.log( this.questionGroup.id_question_project );
        this.selectQuestion = new Question();
        this.selectQuestion.id_question_project = this.questionGroup.id_question_project;
        this.selectQuestion.id_question_group = this.questionGroup.id_question_group;
        this.questionFormDialogsService.showContainer(this.selectQuestion
                ).subscribe(result => {
                       // this.findnotfound();
                    console.log(result);
                  });

    }

    private messageError(error:any):void{
        console.log(error)
        if(error.status === 500){

        }
    }
    private showQuestion(question:Question):void{
        console.log(question);
        if (question.id_question){
            this.questionFormDialogsService.showContainer(question
                    ).subscribe(result => {
                           // this.findnotfound();
                        console.log(result);
                      });
        }
    }
}


text:
classdef PassingExceptionTest < TestCase
   methods
      function self = PassingExceptionTest(methodName)
         self = self@TestCase(methodName);
      end

      function testThrowsException(self)
         f = @() error('a:b:c', 'error message');
         assertExceptionThrown(f, 'a:b:c');
      end
   end
end


text:
{% load i18n %}

{{ inline_admin_formset.opts.verbose_name_plural|capfirst }}

        {% block inline-item-tools %}
            {% if inline_admin_formset.opts.allow_add %}

{% endif %}
        {% endblock %}

    {{ inline_admin_formset.formset.management_form }}
    {{ inline_admin_formset.formset.non_form_errors }}
    {{ inline_admin_formset.opts.model.opts.order_with_respect_to }}

            {% for field in inline_admin_formset.fields %}
                {% if not field.widget.is_hidden %}

{{ field.label|capfirst }}

                {% endif %}
            {% endfor %}

        {% for inline_admin_form in inline_admin_formset %}

            {% if inline_admin_form.form.non_field_errors %}

{{ inline_admin_form.form.non_field_errors }}

            {% endif %}

{{ inline_admin_formset.opts.verbose_name|title }} #{{ forloop.counter }}  {% if inline_admin_form.original %} {{ inline_admin_form.original }}{% endif %}

            {% spaceless %}
            {% for fieldset in inline_admin_form %}
                {% for line in fieldset %}
                    {% for field in line %}
                        {% if field.field.is_hidden %} {{ field.field }} {% endif %}
                    {% endfor %}
                {% endfor %}
            {% endfor %}
            {% endspaceless %}

            {% for fieldset in inline_admin_form %}
                {% for line in fieldset %}
                    {% for field in line %}
                        {% if not field.field.is_hidden %}

                                {% if field.is_readonly %}
                                {{ field.contents }}
                                {% else %}
                                {{ field.field }}
                                {% endif %}
                                {{ field.field.errors.as_ul }}

                        {% endif %}
                    {% endfor %}
                {% endfor %}
            {% endfor %}

                    {% if inline_admin_formset.formset.can_delete and inline_admin_form.original %}
{{ inline_admin_form.deletion_field.field }}
{% endif %}
                    {% if inline_admin_form.show_url %}

{% endif %}
                    {% comment %}{% if inline_admin_formset.opts.sortable %}

{% endif %}{% endcomment %}

            {{ inline_admin_form.fk_field.field }}
            {% if inline_admin_form.needs_explicit_pk_field %}{{ inline_admin_form.pk_field.field }}{% endif %}

        {% endfor %}


text:
from django import forms
from django_summernote.widgets import SummernoteWidget
from django_summernote.widgets import SummernoteInplaceWidget
from .models import Question
from .models import Answer

class QuestionForm(forms.ModelForm):
    class Meta:
        model = Question
        fields = (
            'title',
            'content',
        )
        widgets = {
            'content': SummernoteInplaceWidget(),
            # 'content': SummernoteWidget(),
        }

class AnswerForm(forms.ModelForm):
    class Meta:
        model = Answer
        fields = (
            'content',
        )
        widgets = {
            'content': SummernoteInplaceWidget(),
            # 'content': SummernoteWidget(),
        }

# class ContentForm(forms.Form):
    # content = forms.CharField(widget=SummernoteInplaceWidget())
    # content = forms.CharField(widget=SummernoteWidget())


text:
Conjunto de roles simples para configuração inicial de minha workstation

## Compatibilidade

As roles foram testadas na versão desktop do Xubuntu **16.04.2 LTS (x64)**

Contudo algumas tasks são pessoais de acordo com meu dia-a-dia.

## Uso

Primeiro baixe as roles pelo galaxy:

`ansible-galaxy install -r requirements.yml --roles-path roles`

Em seguida execute o playbook

`ansible-playbook playbook.yml -i inventory.ini --ask-become-pass`

> A opção `--ask-become-pass` para definir a senha usada para torna-se root
>
> Lembre-se de conferir se o hosts está correto de acordo com suas necessidades

## Roles Externas

 * [geerlingguy.docker](https://github.com/geerlingguy/ansible-role-docker)


text:
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | PHP version 4                                                        |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2006 The PHP Group                                |
// +----------------------------------------------------------------------+
// | This source file is subject to version 3.0 of the PHP license,       |
// | that is bundled with this package in the file LICENSE, and is        |
// | available through the world-wide-web at the following url:           |
// | http://www.php.net/license/3_0.txt.                                  |
// | If you did not receive a copy of the PHP license and are unable to   |
// | obtain it through the world-wide-web, please send a note to          |
// | license@php.net so we can mail you a copy immediately.               |
// +----------------------------------------------------------------------+
// | Authors: Frederic Poeydomenge <fpoeydomenge@free.fr>                 |
// +----------------------------------------------------------------------+

/**
 * Wrapper for the var_dump function.
 *
 * " The var_dump function displays structured information about expressions
 * that includes its type and value. Arrays are explored recursively
 * with values indented to show structure. "
 *
 * The Var_Dump class captures the output of the var_dump function,
 * by using output control functions, and then uses external renderer
 * classes for displaying the result in various graphical ways :
 * simple text, HTML/XHTML text, HTML/XHTML table, XML, ...
 *
 * @category  PHP
 * @package   Var_Dump
 * @author    Frederic Poeydomenge <fpoeydomenge@free.fr>
 * @copyright 1997-2006 The PHP Group
 * @license   http://www.php.net/license/3_0.txt PHP License 3.0
 * @version   CVS: $Id: Var_Dump.php 237750 2007-06-15 08:06:25Z fredericpoeydome $
 * @link      http://pear.php.net/package/Var_Dump
 */

/**
 * Include Renderer class
 */

require_once 'Var_Dump/Renderer.php';

/**
 * Constants
 */

define ('VAR_DUMP_START_GROUP',          1);
define ('VAR_DUMP_FINISH_GROUP',         2);
define ('VAR_DUMP_START_ELEMENT_NUM',    3);
define ('VAR_DUMP_START_ELEMENT_STR',    4);
define ('VAR_DUMP_FINISH_ELEMENT',       5);
define ('VAR_DUMP_FINISH_STRING',        6);

define ('VAR_DUMP_PREG_MATCH',           0);
define ('VAR_DUMP_PREG_SPACES',          1);
define ('VAR_DUMP_PREG_KEY_QUOTE',       2);
define ('VAR_DUMP_PREG_KEY',             3);
define ('VAR_DUMP_PREG_STRING_TYPE',     4);
define ('VAR_DUMP_PREG_STRING_LENGTH',   5);
define ('VAR_DUMP_PREG_STRING_VALUE',    6);
define ('VAR_DUMP_PREG_VALUE',           7);
define ('VAR_DUMP_PREG_VALUE_REFERENCE', 8);
define ('VAR_DUMP_PREG_VALUE_TYPE',      9);
define ('VAR_DUMP_PREG_VALUE_COMPL',    10);
define ('VAR_DUMP_PREG_VALUE_RESOURCE', 11);
define ('VAR_DUMP_PREG_ARRAY_END',      12);
define ('VAR_DUMP_PREG_ARRAY_START',    13);
define ('VAR_DUMP_PREG_ARRAY_TYPE',     14);
define ('VAR_DUMP_PREG_ARRAY_COUNT',    15);
define ('VAR_DUMP_PREG_STRING_COMPL',   16);

/**
 * Main class.
 *
 * @category  PHP
 * @package   Var_Dump
 * @author    Frederic Poeydomenge <fpoeydomenge@free.fr>
 * @copyright 1997-2006 The PHP Group
 * @license   http://www.php.net/license/3_0.txt PHP License 3.0
 * @version   CVS: $Id: Var_Dump.php 237750 2007-06-15 08:06:25Z fredericpoeydome $
 * @link      http://pear.php.net/package/Var_Dump
 */

class Var_Dump
{

    /**
     * Default configuration options.
     *
     * @var array
     * @access public
     */
    var $defaultOptions = array(
        'display_mode' => 'XHTML_Text', // Display mode.
        'ignore_list'  => NULL          // List of ignored class names.
    );

    /**
     * Run-time configuration options.
     *
     * @var array
     * @access public
     */
    var $options = array();

    /**
     * Rendering object.
     *
     * @var object
     * @access public
     */
    var $renderer = NULL;

    /**
     * Rendering configuration options.
     *
     * See Var_Dump/Renderer/*.php for the complete list of options
     *
     * @var array
     * @access public
     */
    var $rendererOptions = array();

    /**
     * Class constructor.
     *
     * The factory approach must be used in relationship with the
     * toString() method.
     * See Var_Dump/Renderer/*.php for the complete list of options
     *
     * @see Var_Dump::toString()
     * @param mixed $options String (display mode) or array (Global parameters).
     * @param array $rendererOptions Parameters for the rendering.
     * @access public
     */
    function Var_Dump($options = array(), $rendererOptions = array())
    {

        if (! is_null($options)) {
            if (is_string($options)) {
                $options = array(
                    'display_mode' => $options
                );
            }
            $this->options = array_merge (
                $this->defaultOptions,
                $options
            );
        }

        if (! is_null($rendererOptions) and is_array($rendererOptions)) {
            $this->rendererOptions = $rendererOptions;
            $this->renderer = & Var_Dump_Renderer::factory(
                $this->options['display_mode'],
                $this->rendererOptions
            );
        }

    }

    /**
     * Attempt to return a concrete Var_Dump instance.
     *
     * The factory approach must be used in relationship with the
     * toString() method.
     * See Var_Dump/Renderer/*.php for the complete list of options
     *
     * @see Var_Dump::toString()
     * @param mixed $options String (display mode) or array (Global parameters).
     * @param array $rendererOptions Parameters for the rendering.
     * @access public
     */
    function & factory($options = array(), $rendererOptions = array())
    {
        $obj = new Var_Dump($options, $rendererOptions);
        return $obj;
    }

    /**
     * Uses a renderer object to return the string representation of a variable.
     *
     * @param mixed $expression The variable to parse.
     * @return string The string representation of the variable.
     * @access public
     */
    function toString($expression)
    {

        if (is_null($this->renderer)) {
            return '';
        }

        $family = array(); // element family
        $depth  = array(); // element depth
        $type   = array(); // element type
        $value  = array(); // element value

        // When xdebug is loaded, disable the custom fancy var_dump() function,
        // that is not compatible with the regexp parsing below, by forcing
        // the "html_errors" configuration option to "off"

        if (extension_loaded('xdebug')) {
            ini_set('html_errors', '0');
        }

        // Captures the output of the var_dump function,
        // by using output control functions.

        ob_start();
        var_dump($expression);
        $variable = ob_get_contents();
        ob_end_clean();

        // When xdebug is loaded, restore the value of the
        // "html_errors" configuration option

        if (extension_loaded('xdebug')) {
            ini_restore('html_errors');
        }

        // Regexp that parses the output of the var_dump function.
        // The numbers between square brackets [] are the reference
        // of the captured subpattern, and correspond to the entries
        // in the resulting $matches array.

        preg_match_all(
            '!^
              (\s*)                                 # 2 spaces for each depth level
              (?:                                   #
                (?:\[("?)(.*?)\\2\]=>)              # Key [2-3]
                  |                                 #   or
                (?:(&?string\((\d+)\))\s+"(.*))     # String [4-6]
                  |                                 #   or
                (                                   # Value [7-11]
                  (&?)                              #   - reference [8]
                  (bool|int|float|resource|         #   - type [9]
                  NULL|\*RECURSION\*|UNKNOWN:0)     #
                  (?:\((.*?)\))?                    #   - complement [10]
                  (?:\sof\stype\s\((.*?)\))?        #   - resource [11]
                )                                   #
                  |                                 #   or
                (})                                 # End of array/object [12]
                  |                                 #   or
                (?:(&?(array|object)\((.+)\).*)\ {) # Start of array/object [13-15]
                  |                                 #   or
                (.*)                                # String (additional lines) [16]
              )                                     #
            $!Smx',
            $variable,
            $matches,
            PREG_SET_ORDER
        );

        // Used to keep the maxLen of the keys for each nested variable.

        $stackLen = array();
        $keyLen = array();
        $maxLen = 0;

        // Used when matching a string, to count the remaining
        // number of chars before the end of the string.

        $countdown = 0;

        // Loop through the matches of the previously defined regexp.

        reset($matches);
        while (list($key, $match) = each($matches)) {

            $count = count($match) - 1;

            // Find which alternative has been matched in the regexp,
            // by looking at the number of elements in the $match array.

            switch ($count) {

                // Key
                //=====
                // - Compute the maxLen of the keys at the actual depth

                case VAR_DUMP_PREG_KEY:
                    $len = strlen($match[VAR_DUMP_PREG_KEY]);
                    if ($len > $maxLen) {
                        $maxLen = $len;
                    }
                    if (empty($match[VAR_DUMP_PREG_KEY_QUOTE])) {
                        $family[] = VAR_DUMP_START_ELEMENT_NUM;
                    } else {
                        $family[] = VAR_DUMP_START_ELEMENT_STR;
                    }
                    $depth[] = strlen($match[VAR_DUMP_PREG_SPACES]) >> 1;
                    $type[]  = NULL;
                    $value[] = $match[VAR_DUMP_PREG_KEY];
                    break;

                // String
                //========
                // - Set the countdown (remaining number of chars before eol) =
                //   len of the string - matched len + 1 (final ")

                case VAR_DUMP_PREG_STRING_TYPE:
                case VAR_DUMP_PREG_STRING_LENGTH:
                case VAR_DUMP_PREG_STRING_VALUE:
                    $countdown =
                        $match[VAR_DUMP_PREG_STRING_LENGTH]
                        - strlen($match[VAR_DUMP_PREG_STRING_VALUE])
                        + 1;
                    $family[] = VAR_DUMP_FINISH_STRING;
                    $depth[] = strlen($match[VAR_DUMP_PREG_SPACES]) >> 1;
                    $type[] = $match[VAR_DUMP_PREG_STRING_TYPE];
                    if ($countdown == 0) {
                        $value[] = substr($match[VAR_DUMP_PREG_STRING_VALUE], 0, -1);
                    } else {
                        $value[] = $match[VAR_DUMP_PREG_STRING_VALUE];
                    }
                    break;

                // String (additional lines)
                //===========================
                // - Compute new countdown value
                // - Pop value off the end of the array, and concatenate new value
                // - Last additional line : remove trailing "
                // - Push new value onto the end of array

                case VAR_DUMP_PREG_STRING_COMPL:
                    if ($countdown > 0) {
                        $countdown -= strlen($match[VAR_DUMP_PREG_MATCH]) + 1;
                        $new_value =
                            array_pop($value) . "\n" .
                            $match[VAR_DUMP_PREG_STRING_COMPL];
                        if ($countdown == 0) {
                            $new_value = substr($new_value, 0, -1);
                        }
                        array_push($value, $new_value);
                    }
                    break;

                // Value
                //=======

                case VAR_DUMP_PREG_VALUE:
                case VAR_DUMP_PREG_VALUE_REFERENCE:
                case VAR_DUMP_PREG_VALUE_TYPE:
                case VAR_DUMP_PREG_VALUE_COMPL:
                case VAR_DUMP_PREG_VALUE_RESOURCE:
                    $family[] = VAR_DUMP_FINISH_ELEMENT;
                    $depth[] = strlen($match[VAR_DUMP_PREG_SPACES]) >> 1;
                    switch ($match[VAR_DUMP_PREG_VALUE_TYPE]) {
                        case 'bool':
                        case 'int':
                        case 'float':
                            $type[] =
                                $match[VAR_DUMP_PREG_VALUE_REFERENCE] .
                                $match[VAR_DUMP_PREG_VALUE_TYPE];
                            $value[] = $match[VAR_DUMP_PREG_VALUE_COMPL];
                            break;
                        case 'resource':
                            $type[] =
                                $match[VAR_DUMP_PREG_VALUE_REFERENCE] .
                                $match[VAR_DUMP_PREG_VALUE_TYPE] .
                                '(' . $match[VAR_DUMP_PREG_VALUE_RESOURCE] . ')';
                            $value[] = $match[VAR_DUMP_PREG_VALUE_COMPL];
                            break;
                        default:
                            $type[] =
                                $match[VAR_DUMP_PREG_VALUE_REFERENCE] .
                                $match[VAR_DUMP_PREG_VALUE_TYPE];
                            $value[] = NULL;
                            break;
                    }
                    break;

                // String (additional line containing a single "}")
                //==================================================
                // - see "case VAR_DUMP_PREG_STRING_COMPL" just above
                //
                // OR End of array/object
                //========================
                // - Pop the maxLen of the keys off the end of the stack
                // - If the last element on the stack is an array(0) or object(0),
                //   replace it by a standard element

                case VAR_DUMP_PREG_ARRAY_END:

                    if ($countdown > 0) {
                        // String
                        $countdown -= strlen($match[VAR_DUMP_PREG_MATCH]) + 1;
                        $new_value = array_pop($value) . "\n" . '}';
                        if ($countdown == 0) {
                            $new_value = substr($new_value, 0, -1);
                        }
                        array_push($value, $new_value);
                    } else {
                        // End of array/object
                        $oldLen = array_pop($stackLen);
                        $keyLen[$oldLen[0]] = $maxLen;
                        $maxLen = $oldLen[1];
                        if (
                            ($family[count($family) - 1] == VAR_DUMP_START_GROUP)
                                and
                            ($type[count($type) - 1] === 0)
                        ) {
                            $family[count($family) - 1] = VAR_DUMP_FINISH_ELEMENT;
                            $type[count($type) - 1] = $value[count($value) - 1];
                            $value[count($value) - 1] = NULL;
                        } else {
                            $family[] = VAR_DUMP_FINISH_GROUP;
                            $depth[] = strlen($match[VAR_DUMP_PREG_SPACES]) >> 1;
                            $type[] = NULL;
                            $value[] = $match[VAR_DUMP_PREG_ARRAY_END];
                        }
                    }
                    break;

                // Start of array/object
                //=======================
                // - If object is in the "ignore_list", jump at the end of it
                // - Else process it normally :
                //   - Push the maxLen of the keys onto the end of the stack
                //   - Initialize new maxLen to 0

                case VAR_DUMP_PREG_ARRAY_START:
                case VAR_DUMP_PREG_ARRAY_TYPE:
                case VAR_DUMP_PREG_ARRAY_COUNT:

                    $parse = TRUE;

                    // If object is in the "ignore_list", jump at the end of it.

                    if ($match[VAR_DUMP_PREG_ARRAY_TYPE] == 'object') {
                        $infos = $match[VAR_DUMP_PREG_ARRAY_COUNT];
                        $class_name = substr($infos, 0, strpos($infos, ')'));
                        if (
                            ! is_null($this->options['ignore_list'])
                                and
                            in_array($class_name, $this->options['ignore_list'])
                        ) {
                            $family[] = VAR_DUMP_FINISH_STRING;
                            $depth[] = strlen($match[VAR_DUMP_PREG_SPACES]) >> 1;
                            $type[] = 'object(' . $class_name . ')';
                            $value[] = 'Not parsed.';
                            while ($parse) {
                                list($dummy, $each) = each($matches);
                                if (
                                    $match[VAR_DUMP_PREG_SPACES] == $each[VAR_DUMP_PREG_SPACES]
                                        and
                                    (count($each) - 1) == VAR_DUMP_PREG_ARRAY_END
                                ) {
                                    $parse = FALSE;
                                }
                            };
                        }
                    }

                    // If not, process it normally.

                    if ($parse) {

                        array_push($stackLen, array(count($family), $maxLen));
                        $maxLen = 0;
                        $family[] = VAR_DUMP_START_GROUP;
                        $depth[] = strlen($match[VAR_DUMP_PREG_SPACES]) >> 1;
                        $type[] = (int) $match[VAR_DUMP_PREG_ARRAY_COUNT];
                        $value[] = $match[VAR_DUMP_PREG_ARRAY_START];

                    }

                    break;

            }

        }

        $this->renderer->initialize($family, $depth, $type, $value, $keyLen);

        return $this->renderer->toString();

    }

    /**
     * Attempt to return a concrete singleton Var_Dump instance.
     *
     * The singleton approach must be used in relationship with the
     * displayInit() and display() methods.
     * See Var_Dump/Renderer/*.php for the complete list of options
     *
     * @see Var_Dump::display(), Var_Dump::displayInit()
     * @return object Var_Dump instance
     * @access public
     */
    function & singleton()
    {
        static $instance;
        if (! isset($instance)) {
            $instance = new Var_Dump(array(), array(), array());
        }
        return $instance;
    }

    /**
     * Initialise the singleton object used by the display() method.
     *
     * @see Var_Dump::singleton(), Var_Dump::display()
     * @param mixed $options String (display mode) or array (Global parameters).
     * @param array $rendererOptions Parameters for the rendering.
     * @access public
     */
    function displayInit($options = array(), $rendererOptions = array())
    {
        $displayInit = & Var_Dump::singleton();
        $displayInit->Var_Dump($options, $rendererOptions);
    }

    /**
     * Outputs or returns a string representation of a variable.
     *
     * @see Var_Dump::singleton(), Var_Dump::displayInit()
     * @param mixed $expression The variable to parse.
     * @param bool $return Whether the variable should be echoed or returned.
     * @param mixed $options String (display mode) or array (Global parameters).
     * @param array $rendererOptions Parameters for the rendering.
     * @return string If returned, the string representation of the variable.
     * @access public
     */
    function display($expression, $return = FALSE, $options = NULL, $rendererOptions = NULL)
    {
        $display = & Var_Dump::singleton();
        if (! is_null($options) or ! is_null($rendererOptions)) {
            if (is_null($rendererOptions)) {
                $rendererOptions = array();
            }
            $display->Var_Dump($options, $rendererOptions);
        }
        if ($return === TRUE) {
            return $display->toString($expression);
        } else {
            echo $display->toString($expression);
        }
    }

}

?>


text:
Date: 2018/02/19
Authors: Echo Can Luo
Keywords: 3D Avatar Performance, Installation

---
---

# Nicely nicely all the time! – Nr. 1

![](Echo_3.jpg)

In Deutschland leben viele Menschen mit unterschiedlicher Herkunft. Die meisten davon haben schon Erfahrungen mit Diskriminierung und Rassismus erlebt. Um in dieses Thema weiter einzusteigen habe ich Interviews mit einigen Betroffenen geführt und eine Reihe von Gesichtern 3D eingescannt um diese als interaktive Avatare dem Publikum zur Verfügung zu stellen. Während die Besucherin oder der Besucher eine der Geschichten aus den Interviews am Mikrofon vorließt, wird das Gesicht durch das eines der animierten Avatare ersetzt. In anderer, virtueller Haut werden Erfahrungen neu erlebt.

![](Echo_2.jpg)

![](Echo_1.jpg)


text:
<?php

/* bootstrap/well.html.twig */
class __TwigTemplate_ad6d86933973a8dd3f3fc1301e11ece32c77f21d721e091858d880b7f5a4494d extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 1
        echo "
getAttribute((isset($context["attributes"]) ? $context["attributes"] : null), "class", array(), "array");
        echo "\" ";
        $this->loadTemplate("partials/_attributes.html.twig", "bootstrap/well.html.twig", 1)->display(array_merge($context, array("ignore" => array(0 => "class"))));
        echo ">
    ";
        // line 2
        echo (isset($context["content"]) ? $context["content"] : null);
        echo "

";
    }

    public function getTemplateName()
    {
        return "bootstrap/well.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  31 => 2,  19 => 1,);
    }

    public function getSource()
    {
        return "

    {{ content }}

";
    }
}


text:
#include "arm_compute/core/CPP/kernels/CPPBoxWithNonMaximaSuppressionLimitKernel.h"

#include "arm_compute/core/Helpers.h"
#include "src/core/helpers/WindowHelpers.h"

#include <algorithm>
#include <cmath>

namespace arm_compute
{
namespace
{
template <typename T>
std::vector<int> SoftNMS(const ITensor *proposals, std::vector<std::vector<T>> &scores_in, std::vector<int> inds, const BoxNMSLimitInfo &info, int class_id)
{
    std::vector<int> keep;
    const int        proposals_width = proposals->info()->dimension(1);

    std::vector<T> x1(proposals_width);
    std::vector<T> y1(proposals_width);
    std::vector<T> x2(proposals_width);
    std::vector<T> y2(proposals_width);
    std::vector<T> areas(proposals_width);

    for(int i = 0; i < proposals_width; ++i)
    {
        x1[i]    = *reinterpret_cast<T *>(proposals->ptr_to_element(Coordinates(class_id * 4, i)));
        y1[i]    = *reinterpret_cast<T *>(proposals->ptr_to_element(Coordinates(class_id * 4 + 1, i)));
        x2[i]    = *reinterpret_cast<T *>(proposals->ptr_to_element(Coordinates(class_id * 4 + 2, i)));
        y2[i]    = *reinterpret_cast<T *>(proposals->ptr_to_element(Coordinates(class_id * 4 + 3, i)));
        areas[i] = (x2[i] - x1[i] + 1.0) * (y2[i] - y1[i] + 1.0);
    }

    // Note: Soft NMS scores have already been initialized with input scores

    while(!inds.empty())
    {
        // Find proposal with max score among remaining proposals
        int max_pos = 0;
        for(unsigned int i = 1; i < inds.size(); ++i)
        {
            if(scores_in[class_id][inds.at(i)] > scores_in[class_id][inds.at(max_pos)])
            {
                max_pos = i;
            }
        }
        int element = inds.at(max_pos);
        keep.push_back(element);
        std::swap(inds.at(0), inds.at(max_pos));

        // Remove first element and compute IoU of the remaining boxes with identified max box
        inds.erase(inds.begin());

        std::vector<int> sorted_indices_temp;
        for(auto idx : inds)
        {
            const auto xx1 = std::max(x1[idx], x1[element]);
            const auto yy1 = std::max(y1[idx], y1[element]);
            const auto xx2 = std::min(x2[idx], x2[element]);
            const auto yy2 = std::min(y2[idx], y2[element]);

            const auto w     = std::max((xx2 - xx1 + 1.f), 0.f);
            const auto h     = std::max((yy2 - yy1 + 1.f), 0.f);
            const auto inter = w * h;
            const auto ovr   = inter / (areas[element] + areas[idx] - inter);

            // Update scores based on computed IoU, overlap threshold and NMS method
            T weight;
            switch(info.soft_nms_method())
            {
                case NMSType::LINEAR:
                    weight = (ovr > info.nms()) ? (1.f - ovr) : 1.f;
                    break;
                case NMSType::GAUSSIAN: // Gaussian
                    weight = std::exp(-1.f * ovr * ovr / info.soft_nms_sigma());
                    break;
                case NMSType::ORIGINAL: // Original NMS
                    weight = (ovr > info.nms()) ? 0.f : 1.f;
                    break;
                default:
                    ARM_COMPUTE_ERROR("Not supported");
            }

            // Discard boxes with new scores below min threshold and update pending indices
            scores_in[class_id][idx] *= weight;
            if(scores_in[class_id][idx] >= info.soft_nms_min_score_thres())
            {
                sorted_indices_temp.push_back(idx);
            }
        }
        inds = sorted_indices_temp;
    }

    return keep;
}

template <typename T>
std::vector<int> NonMaximaSuppression(const ITensor *proposals, std::vector<int> sorted_indices, const BoxNMSLimitInfo &info, int class_id)
{
    std::vector<int> keep;

    const int proposals_width = proposals->info()->dimension(1);

    std::vector<T> x1(proposals_width);
    std::vector<T> y1(proposals_width);
    std::vector<T> x2(proposals_width);
    std::vector<T> y2(proposals_width);
    std::vector<T> areas(proposals_width);

    for(int i = 0; i < proposals_width; ++i)
    {
        x1[i]    = *reinterpret_cast<T *>(proposals->ptr_to_element(Coordinates(class_id * 4, i)));
        y1[i]    = *reinterpret_cast<T *>(proposals->ptr_to_element(Coordinates(class_id * 4 + 1, i)));
        x2[i]    = *reinterpret_cast<T *>(proposals->ptr_to_element(Coordinates(class_id * 4 + 2, i)));
        y2[i]    = *reinterpret_cast<T *>(proposals->ptr_to_element(Coordinates(class_id * 4 + 3, i)));
        areas[i] = (x2[i] - x1[i] + 1.0) * (y2[i] - y1[i] + 1.0);
    }

    while(!sorted_indices.empty())
    {
        int i = sorted_indices.at(0);
        keep.push_back(i);

        std::vector<int> sorted_indices_temp = sorted_indices;
        std::vector<int> new_indices;
        sorted_indices_temp.erase(sorted_indices_temp.begin());

        for(unsigned int j = 0; j < sorted_indices_temp.size(); ++j)
        {
            const float xx1 = std::max(x1[sorted_indices_temp.at(j)], x1[i]);
            const float yy1 = std::max(y1[sorted_indices_temp.at(j)], y1[i]);
            const float xx2 = std::min(x2[sorted_indices_temp.at(j)], x2[i]);
            const float yy2 = std::min(y2[sorted_indices_temp.at(j)], y2[i]);

            const float w     = std::max((xx2 - xx1 + 1.f), 0.f);
            const float h     = std::max((yy2 - yy1 + 1.f), 0.f);
            const float inter = w * h;
            const float ovr   = inter / (areas[i] + areas[sorted_indices_temp.at(j)] - inter);
            const float ctr_x = xx1 + (w / 2);
            const float ctr_y = yy1 + (h / 2);

            // If suppress_size is specified, filter the boxes based on their size and position
            const bool keep_size = !info.suppress_size() || (w >= info.min_size() && h >= info.min_size() && ctr_x < info.im_width() && ctr_y < info.im_height());
            if(ovr <= info.nms() && keep_size)
            {
                new_indices.push_back(j);
            }
        }

        const unsigned int new_indices_size = new_indices.size();
        std::vector<int>   new_sorted_indices(new_indices_size);
        for(unsigned int i = 0; i < new_indices_size; ++i)
        {
            new_sorted_indices[i] = sorted_indices[new_indices[i] + 1];
        }
        sorted_indices = new_sorted_indices;
    }

    return keep;
}
} // namespace

CPPBoxWithNonMaximaSuppressionLimitKernel::CPPBoxWithNonMaximaSuppressionLimitKernel()
    : _scores_in(nullptr), _boxes_in(nullptr), _batch_splits_in(nullptr), _scores_out(nullptr), _boxes_out(nullptr), _classes(nullptr), _batch_splits_out(nullptr), _keeps(nullptr), _keeps_size(nullptr),
      _info()
{
}

bool CPPBoxWithNonMaximaSuppressionLimitKernel::is_parallelisable() const
{
    return false;
}

template <typename T>
void CPPBoxWithNonMaximaSuppressionLimitKernel::run_nmslimit()
{
    const int                     batch_size   = _batch_splits_in == nullptr ? 1 : _batch_splits_in->info()->dimension(0);
    const int                     num_classes  = _scores_in->info()->dimension(0);
    const int                     scores_count = _scores_in->info()->dimension(1);
    std::vector<int>              total_keep_per_batch(batch_size);
    std::vector<std::vector<int>> keeps(num_classes);
    int                           total_keep_count = 0;

    std::vector<std::vector<T>> in_scores(num_classes, std::vector<T>(scores_count));
    for(int i = 0; i < scores_count; ++i)
    {
        for(int j = 0; j < num_classes; ++j)
        {
            in_scores[j][i] = *reinterpret_cast<const T *>(_scores_in->ptr_to_element(Coordinates(j, i)));
        }
    }

    int offset        = 0;
    int cur_start_idx = 0;
    for(int b = 0; b < batch_size; ++b)
    {
        const int num_boxes = _batch_splits_in == nullptr ? 1 : static_cast<int>(*reinterpret_cast<T *>(_batch_splits_in->ptr_to_element(Coordinates(b))));
        // Skip first class if there is more than 1 except if the number of classes is 1.
        const int j_start = (num_classes == 1 ? 0 : 1);
        for(int j = j_start; j < num_classes; ++j)
        {
            std::vector<T>   cur_scores(scores_count);
            std::vector<int> inds;
            for(int i = 0; i < scores_count; ++i)
            {
                const T score = in_scores[j][i];
                cur_scores[i] = score;

                if(score > _info.score_thresh())
                {
                    inds.push_back(i);
                }
            }
            if(_info.soft_nms_enabled())
            {
                keeps[j] = SoftNMS(_boxes_in, in_scores, inds, _info, j);
            }
            else
            {
                std::sort(inds.data(), inds.data() + inds.size(),
                          [&cur_scores](int lhs, int rhs)
                {
                    return cur_scores[lhs] > cur_scores[rhs];
                });

                keeps[j] = NonMaximaSuppression<T>(_boxes_in, inds, _info, j);
            }
            total_keep_count += keeps[j].size();
        }

        if(_info.detections_per_im() > 0 && total_keep_count > _info.detections_per_im())
        {
            // merge all scores (represented by indices) together and sort
            auto get_all_scores_sorted = [&in_scores, &keeps, total_keep_count]()
            {
                std::vector<T> ret(total_keep_count);

                int ret_idx = 0;
                for(unsigned int i = 1; i < keeps.size(); ++i)
                {
                    auto &cur_keep = keeps[i];
                    for(auto &ckv : cur_keep)
                    {
                        ret[ret_idx++] = in_scores[i][ckv];
                    }
                }

                std::sort(ret.data(), ret.data() + ret.size());

                return ret;
            };

            auto    all_scores_sorted = get_all_scores_sorted();
            const T image_thresh      = all_scores_sorted[all_scores_sorted.size() - _info.detections_per_im()];
            for(int j = 1; j < num_classes; ++j)
            {
                auto            &cur_keep = keeps[j];
                std::vector<int> new_keeps_j;
                for(auto &k : cur_keep)
                {
                    if(in_scores[j][k] >= image_thresh)
                    {
                        new_keeps_j.push_back(k);
                    }
                }
                keeps[j] = new_keeps_j;
            }
            total_keep_count = _info.detections_per_im();
        }

        total_keep_per_batch[b] = total_keep_count;

        // Write results
        int cur_out_idx = 0;
        for(int j = j_start; j < num_classes; ++j)
        {
            auto     &cur_keep        = keeps[j];
            auto      cur_out_scores  = reinterpret_cast<T *>(_scores_out->ptr_to_element(Coordinates(cur_start_idx + cur_out_idx)));
            auto      cur_out_classes = reinterpret_cast<T *>(_classes->ptr_to_element(Coordinates(cur_start_idx + cur_out_idx)));
            const int box_column      = (cur_start_idx + cur_out_idx) * 4;

            for(unsigned int k = 0; k < cur_keep.size(); ++k)
            {
                cur_out_scores[k]     = in_scores[j][cur_keep[k]];
                cur_out_classes[k]    = static_cast<T>(j);
                auto cur_out_box_row0 = reinterpret_cast<T *>(_boxes_out->ptr_to_element(Coordinates(box_column + 0, k)));
                auto cur_out_box_row1 = reinterpret_cast<T *>(_boxes_out->ptr_to_element(Coordinates(box_column + 1, k)));
                auto cur_out_box_row2 = reinterpret_cast<T *>(_boxes_out->ptr_to_element(Coordinates(box_column + 2, k)));
                auto cur_out_box_row3 = reinterpret_cast<T *>(_boxes_out->ptr_to_element(Coordinates(box_column + 3, k)));
                *cur_out_box_row0     = *reinterpret_cast<const T *>(_boxes_in->ptr_to_element(Coordinates(j * 4 + 0, cur_keep[k])));
                *cur_out_box_row1     = *reinterpret_cast<const T *>(_boxes_in->ptr_to_element(Coordinates(j * 4 + 1, cur_keep[k])));
                *cur_out_box_row2     = *reinterpret_cast<const T *>(_boxes_in->ptr_to_element(Coordinates(j * 4 + 2, cur_keep[k])));
                *cur_out_box_row3     = *reinterpret_cast<const T *>(_boxes_in->ptr_to_element(Coordinates(j * 4 + 3, cur_keep[k])));
            }

            cur_out_idx += cur_keep.size();
        }

        if(_keeps != nullptr)
        {
            cur_out_idx = 0;
            for(int j = 0; j < num_classes; ++j)
            {
                for(unsigned int i = 0; i < keeps[j].size(); ++i)
                {
                    *reinterpret_cast<T *>(_keeps->ptr_to_element(Coordinates(cur_start_idx + cur_out_idx + i))) = static_cast<T>(keeps[j].at(i));
                }
                *reinterpret_cast<uint32_t *>(_keeps_size->ptr_to_element(Coordinates(j + b * num_classes))) = keeps[j].size();
                cur_out_idx += keeps[j].size();
            }
        }

        offset += num_boxes;
        cur_start_idx += total_keep_count;
    }

    if(_batch_splits_out != nullptr)
    {
        for(int b = 0; b < batch_size; ++b)
        {
            *reinterpret_cast<float *>(_batch_splits_out->ptr_to_element(Coordinates(b))) = total_keep_per_batch[b];
        }
    }
}

void CPPBoxWithNonMaximaSuppressionLimitKernel::configure(const ITensor *scores_in, const ITensor *boxes_in, const ITensor *batch_splits_in, ITensor *scores_out, ITensor *boxes_out, ITensor *classes,
                                                          ITensor *batch_splits_out, ITensor *keeps, ITensor *keeps_size, const BoxNMSLimitInfo info)
{
    ARM_COMPUTE_ERROR_ON_NULLPTR(scores_in, boxes_in, scores_out, boxes_out, classes);
    ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(scores_in, 1, DataType::F16, DataType::F32);
    ARM_COMPUTE_ERROR_ON_MISMATCHING_DATA_TYPES(scores_in, boxes_in, scores_out);
    const unsigned int num_classes = scores_in->info()->dimension(0);

    ARM_COMPUTE_UNUSED(num_classes);
    ARM_COMPUTE_ERROR_ON_MSG((4 * num_classes) != boxes_in->info()->dimension(0), "First dimension of input boxes must be of size 4*num_classes");
    ARM_COMPUTE_ERROR_ON_MSG(scores_in->info()->dimension(1) != boxes_in->info()->dimension(1), "Input scores and input boxes must have the same number of rows");

    ARM_COMPUTE_ERROR_ON(scores_out->info()->dimension(0) != boxes_out->info()->dimension(1));
    ARM_COMPUTE_ERROR_ON(boxes_out->info()->dimension(0) != 4);
    ARM_COMPUTE_ERROR_ON(scores_out->info()->dimension(0) != classes->info()->dimension(0));
    if(keeps != nullptr)
    {
        ARM_COMPUTE_ERROR_ON_MSG(keeps_size == nullptr, "keeps_size cannot be nullptr if keeps has to be provided as output");
        ARM_COMPUTE_ERROR_ON_MISMATCHING_DATA_TYPES(scores_in, keeps);
        ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(keeps_size, 1, DataType::U32);
        ARM_COMPUTE_ERROR_ON(scores_out->info()->dimension(0) != keeps->info()->dimension(0));
        ARM_COMPUTE_ERROR_ON(num_classes != keeps_size->info()->dimension(0));
    }
    if(batch_splits_in != nullptr)
    {
        ARM_COMPUTE_ERROR_ON_MISMATCHING_DATA_TYPES(scores_in, batch_splits_in);
    }
    if(batch_splits_out != nullptr)
    {
        ARM_COMPUTE_ERROR_ON_MISMATCHING_DATA_TYPES(scores_in, batch_splits_out);
    }

    _scores_in        = scores_in;
    _boxes_in         = boxes_in;
    _batch_splits_in  = batch_splits_in;
    _scores_out       = scores_out;
    _boxes_out        = boxes_out;
    _classes          = classes;
    _batch_splits_out = batch_splits_out;
    _keeps            = keeps;
    _keeps_size       = keeps_size;
    _info             = info;

    // Configure kernel window
    Window win = calculate_max_window(*scores_in->info(), Steps(scores_in->info()->dimension(0)));

    IKernel::configure(win);
}

void CPPBoxWithNonMaximaSuppressionLimitKernel::run(const Window &window, const ThreadInfo &info)
{
    ARM_COMPUTE_UNUSED(info);
    ARM_COMPUTE_UNUSED(window);
    ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(this);
    ARM_COMPUTE_ERROR_ON_MISMATCHING_WINDOWS(IKernel::window(), window);

    switch(_scores_in->info()->data_type())
    {
        case DataType::F32:
            run_nmslimit<float>();
            break;
        case DataType::F16:
            run_nmslimit<half>();
            break;
        default:
            ARM_COMPUTE_ERROR("Not supported");
    }
}
} // namespace arm_compute


text:
#ifndef __IO_MASK_RENDER_WIDGET_INC__
#define __IO_MASK_RENDER_WIDGET_INC__

#include <QWidget>

namespace ui
{
  /*! \class maskRenderWidget
    \brief A brief description
    \author gmatthew
  */
  class maskRenderWidget : public QWidget
  {
    Q_OBJECT

    struct Impl;
    Impl* pimpl_;

    virtual void keyPressEvent(QKeyEvent *);
    virtual void mousePressEvent(QMouseEvent *);
    virtual void mouseMoveEvent(QMouseEvent *);
    virtual void mouseReleaseEvent(QMouseEvent *);
    virtual void paintEvent(QPaintEvent *);

  public:
    /*! \brief Constructor
    */
    explicit maskRenderWidget(QWidget *parent = 0);
    /*! \brief Constructor
    */
    explicit maskRenderWidget(const QImage &, QWidget *parent = 0);
    /*! \brief Destructor
    */
    virtual ~maskRenderWidget() throw();

#ifndef DOXYGEN_SHOULD_SKIP_THIS
    virtual QSize sizeHint() const;
    virtual QSize minimumSizeHint() const;
#endif

    /*! \brief Set the drawable pen.
      \param The pen object.
    */
    void setPen(const QPen &pen);
    /*! \brief Returns the drawable pen.
      \return pen The pen object.
    */
    QPen pen() const;
    /*! \brief Set the background Image.
      \param image The image to be set as the background.
    */
    void setImage(const QImage &);
    /*! \brief Load the alpha mask.
      \param filename The path to the image to be used as the mask.
    */
    void load(const QString &filename);
    /*! \brief Save the alpha mask.
      \param filename The path to the image to be used as the mask.
			\param w The width of the image to save to.
			\param h The height of the image to save to.
    */
    void save(const QString &filename, int w, int h);
    /*! \brief Get the alpha mask.
			\param w The width of the image to return.
			\param h The height of the image to return.
    */
    QImage getMask(int w, int h) const;
    /*! \brief Set the alpha mask.
      \param image The image to be set as the mask.
    */
    void setAlphaMask(const QImage &image);
    /*! \brief Returns the alpha mask.
      \return An qimage object.
    */
    QImage alphaMask() const;

  public slots:
    /*! \brief Undoes the last action and adds the current action to the redo stack and updates the display.  If no more actions could be undone, does nothing.

    The number of times this can be done is limited only by the resources available.
    */
    void undo();
    /*! \brief Redoes the last action and adds the current action to the undo stack and updates the display.  If no more actions could be redone, does nothing.

    The number of times this can be done is limited only by the resources available.
    */
    void redo();
    /*! \brief Clears the display.

    This action is also added to the undo actions.
    */
    void clear();

  signals:
    void pointSelected(const QPoint &);
  };
};

#endif


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.beyondcorp.v1.model;

/**
 * ConnectionConfig represents a Connection Configuration object.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the BeyondCorp API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class CloudSecurityZerotrustApplinkAppConnectorProtoConnectionConfig extends com.google.api.client.json.GenericJson {

  /**
   * application_endpoint is the endpoint of the application the form of host:port. For example,
   * "localhost:80".
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String applicationEndpoint;

  /**
   * application_name represents the given name of the application the connection is connecting
   * with.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String applicationName;

  /**
   * gateway lists all instances running a gateway in GCP. They all connect to a connector on the
   * host.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<CloudSecurityZerotrustApplinkAppConnectorProtoGateway> gateway;

  /**
   * name is the unique ID for each connection. TODO(b/190732451) returns connection name from user-
   * specified name in config. Now, name = ${application_name}:${application_endpoint}
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String name;

  /**
   * project represents the consumer project the connection belongs to.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String project;

  /**
   * tunnels_per_gateway reflects the number of tunnels between a connector and a gateway.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Long tunnelsPerGateway;

  /**
   * user_port specifies the reserved port on gateways for user connections.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Integer userPort;

  /**
   * application_endpoint is the endpoint of the application the form of host:port. For example,
   * "localhost:80".
   * @return value or {@code null} for none
   */
  public java.lang.String getApplicationEndpoint() {
    return applicationEndpoint;
  }

  /**
   * application_endpoint is the endpoint of the application the form of host:port. For example,
   * "localhost:80".
   * @param applicationEndpoint applicationEndpoint or {@code null} for none
   */
  public CloudSecurityZerotrustApplinkAppConnectorProtoConnectionConfig setApplicationEndpoint(java.lang.String applicationEndpoint) {
    this.applicationEndpoint = applicationEndpoint;
    return this;
  }

  /**
   * application_name represents the given name of the application the connection is connecting
   * with.
   * @return value or {@code null} for none
   */
  public java.lang.String getApplicationName() {
    return applicationName;
  }

  /**
   * application_name represents the given name of the application the connection is connecting
   * with.
   * @param applicationName applicationName or {@code null} for none
   */
  public CloudSecurityZerotrustApplinkAppConnectorProtoConnectionConfig setApplicationName(java.lang.String applicationName) {
    this.applicationName = applicationName;
    return this;
  }

  /**
   * gateway lists all instances running a gateway in GCP. They all connect to a connector on the
   * host.
   * @return value or {@code null} for none
   */
  public java.util.List<CloudSecurityZerotrustApplinkAppConnectorProtoGateway> getGateway() {
    return gateway;
  }

  /**
   * gateway lists all instances running a gateway in GCP. They all connect to a connector on the
   * host.
   * @param gateway gateway or {@code null} for none
   */
  public CloudSecurityZerotrustApplinkAppConnectorProtoConnectionConfig setGateway(java.util.List<CloudSecurityZerotrustApplinkAppConnectorProtoGateway> gateway) {
    this.gateway = gateway;
    return this;
  }

  /**
   * name is the unique ID for each connection. TODO(b/190732451) returns connection name from user-
   * specified name in config. Now, name = ${application_name}:${application_endpoint}
   * @return value or {@code null} for none
   */
  public java.lang.String getName() {
    return name;
  }

  /**
   * name is the unique ID for each connection. TODO(b/190732451) returns connection name from user-
   * specified name in config. Now, name = ${application_name}:${application_endpoint}
   * @param name name or {@code null} for none
   */
  public CloudSecurityZerotrustApplinkAppConnectorProtoConnectionConfig setName(java.lang.String name) {
    this.name = name;
    return this;
  }

  /**
   * project represents the consumer project the connection belongs to.
   * @return value or {@code null} for none
   */
  public java.lang.String getProject() {
    return project;
  }

  /**
   * project represents the consumer project the connection belongs to.
   * @param project project or {@code null} for none
   */
  public CloudSecurityZerotrustApplinkAppConnectorProtoConnectionConfig setProject(java.lang.String project) {
    this.project = project;
    return this;
  }

  /**
   * tunnels_per_gateway reflects the number of tunnels between a connector and a gateway.
   * @return value or {@code null} for none
   */
  public java.lang.Long getTunnelsPerGateway() {
    return tunnelsPerGateway;
  }

  /**
   * tunnels_per_gateway reflects the number of tunnels between a connector and a gateway.
   * @param tunnelsPerGateway tunnelsPerGateway or {@code null} for none
   */
  public CloudSecurityZerotrustApplinkAppConnectorProtoConnectionConfig setTunnelsPerGateway(java.lang.Long tunnelsPerGateway) {
    this.tunnelsPerGateway = tunnelsPerGateway;
    return this;
  }

  /**
   * user_port specifies the reserved port on gateways for user connections.
   * @return value or {@code null} for none
   */
  public java.lang.Integer getUserPort() {
    return userPort;
  }

  /**
   * user_port specifies the reserved port on gateways for user connections.
   * @param userPort userPort or {@code null} for none
   */
  public CloudSecurityZerotrustApplinkAppConnectorProtoConnectionConfig setUserPort(java.lang.Integer userPort) {
    this.userPort = userPort;
    return this;
  }

  @Override
  public CloudSecurityZerotrustApplinkAppConnectorProtoConnectionConfig set(String fieldName, Object value) {
    return (CloudSecurityZerotrustApplinkAppConnectorProtoConnectionConfig) super.set(fieldName, value);
  }

  @Override
  public CloudSecurityZerotrustApplinkAppConnectorProtoConnectionConfig clone() {
    return (CloudSecurityZerotrustApplinkAppConnectorProtoConnectionConfig) super.clone();
  }

}


text:
/**
Written by:  Smyth Chang

Description:  The Macros header is used to define macros for use across multiple files
*/

#pragma once

#define SAFE_RELEASE(x) if(x){x->Release(); x = nullptr;}
#define SAFE_RELEASE2(x) if(x){x->release(); x = nullptr;}


text:
START_ATF_NAMESPACE
    namespace ATL
    {
        struct CSocketAddrVtbl
        {
            void *(WINAPIV *__vecDelDtor)(CSocketAddr *_this, unsigned int);
        };
    }; // end namespace ATL
END_ATF_NAMESPACE


text:
using namespace ::apache::thrift;
using namespace ::apache::thrift::protocol;
using namespace ::apache::thrift::transport;
using namespace ::apache::thrift::server;

using boost::shared_ptr;

using namespace  ::monitorsScaner;

class MonitorsScanerHandler : virtual public MonitorsScanerIf
{
 public:
  MonitorsScanerHandler()
  {}

  void getInfo(Data& _return, const InfoRequest& infoRequest)
  {
	CInforamtionProvider::getInstance()->getInfo( _return, infoRequest );
  }

};

void
init( boost::thread_group & _threadGroup )
{
	common::SelectDimsParams( CNetworkParams::TESTNET );

	common::CPeriodicActionExecutor * periodicActionExecutor
			= common::CPeriodicActionExecutor::getInstance();

	_threadGroup.create_thread(boost::bind(&common::CPeriodicActionExecutor::processingLoop, periodicActionExecutor ));

	_threadGroup.create_thread(boost::bind(&common::CActionHandler::loop, common::CActionHandler::getInstance()));

	_threadGroup.create_thread( boost::bind( &common::CTimeMedium::workLoop, common::CTimeMedium::getInstance() ) );

	common::CActionHandler::getInstance()->addConnectionProvider( client::CSettingsConnectionProvider::getInstance() );

	common::CActionHandler::getInstance()->addConnectionProvider( client::CTrackerLocalRanking::getInstance() );

	common::CActionHandler::getInstance()->addConnectionProvider( client::CErrorMediumProvider::getInstance() );

	client::CConnectAction * connectAction =  new client::CConnectAction( false );

	connectAction->m_connected.connect( boost::bind( &CInforamtionProvider::reloadData, CInforamtionProvider::getInstance() ) );

	common::CPeriodicActionExecutor::getInstance()->addAction( connectAction, 120000 );
}

int main(int argc, char **argv)
{
	int port = 9090;
	ParseParameters(argc, argv);

  shared_ptr<MonitorsScanerHandler> handler(new MonitorsScanerHandler());
  shared_ptr<TProcessor> processor(new MonitorsScanerProcessor(handler));
  shared_ptr<TServerTransport> serverTransport(new TServerSocket(port));
  shared_ptr<TTransportFactory> transportFactory(new TBufferedTransportFactory());
  shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());

  boost::thread_group threadGroup;

  init( threadGroup );

  TSimpleServer server(processor, serverTransport, transportFactory, protocolFactory);
  server.serve();

	threadGroup.join_all();

  return 0;
}