text:
'use strict';

var Q = require('q');
var Calculator = require('../Calculator');
var defaults = require('../lib/defaults');

describe('Calculator', function() {

    var calculator;

    function fakeDeferred() {
        return Q.defer().promise;
    }

    beforeEach(function() {
        calculator = new Calculator({
            publicKey: 'some key'
        });
    });

    it('should have DestinationError', function() {
        expect(Calculator.DestinationError).toBeDefined();
        expect(new Calculator.DestinationError() instanceof Error).toBeTruthy();
    });

    it('should have PackagesError', function() {
        expect(Calculator.PackagesError).toBeDefined();
        expect(new Calculator.PackagesError() instanceof Error).toBeTruthy();
    });

    it('should use default settings', function() {
        expect(calculator.settings.apiUrl).toBe(defaults.apiUrl);
        expect(calculator.settings.version).toBe(defaults.version);
    });

    it('settings may be redefined', function() {
        var calc2 = new Calculator({
            apiUrl: 'http://some.url/',
            version: 2
        });
        expect(calc2.settings.apiUrl).toBe('http://some.url/');
        expect(calc2.settings.version).toBe(2);
    });

    describe('`calc` method', function() {
        var packages = [
            {
                weight: 2.7,
                length: 20,
                width: 30,
                height: 10
            }
        ];

        function updatePackages(packages, prop, value) {
            var packs = [];
            packages.forEach(function(p) {
                var np = {};
                for (var pr in p) {
                    if (p.hasOwnProperty(pr)) {
                        np[pr] = (pr === prop) ? value : p[pr];
                    }
                }
                packs.push(np);
            });
            return packs;
        }

        var dest = 'some destination';

        it('should validate destination', function() {
            var badDestinations = [ null, 123, [], {}, 'ab', 'a', '' ];
            badDestinations.forEach(function(dest) {
                expect(function() {
                    calculator.calc(dest, packages);
                }).toThrowError(Calculator.DestinationError);
            });
        });

        it('should validate packages as array', function() {
            var badPackages = [ null, 123, {}, 'some' ];
            badPackages.forEach(function(pack) {
                expect(function() {
                    calculator.calc(dest, pack)
                }).toThrowError(Calculator.PackagesError);
            });
        });

        it('should not validate empty array packages', function() {
            expect(function() {
                calculator.calc(dest, [])
            }).toThrowError(Calculator.PackagesError);
        });

        it('should not validate package with bad values', function() {
            var subs = [
                ['weight', 0], ['weight', 'a'], ['weight', null], ['weight', {}], ['weight', []],
                ['length', 0], ['length', 'a'], ['length', null], ['length', {}], ['length', []],
                ['width', 0], ['width', 'a'], ['width', null], ['width', {}], ['width', []],
                ['height', 0], ['height', 'a'], ['height', null], ['height', {}], ['height', []]
            ];
            subs.forEach(function(sub) {
                expect(function() {
                    calculator.calc(dest, updatePackages(packages, sub[0], sub[1]));
                }).toThrowError(Calculator.PackagesError);
            });
        });

        it('should make deferred request to `price` endpoint and returns promise', function() {
            spyOn(calculator.requests, 'deferred').and.callThrough();
            var promise = calculator.calc(dest, packages);
            expect(calculator.requests.deferred).toHaveBeenCalledWith('price', {
                destination: dest,
                packages: packages,
                total_cost: 0
            });
            expect(Q.isPromise(promise)).toBeTruthy();
        });

        it('should accept `totalCost` as third argument as float', function() {
            spyOn(calculator.requests, 'deferred').and.callFake(fakeDeferred);
            var promise = calculator.calc(dest, packages, 234.5);
            expect(calculator.requests.deferred).toHaveBeenCalledWith('price', {
                destination: dest,
                packages: packages,
                total_cost: 234.5
            });
            expect(Q.isPromise(promise)).toBeTruthy();
        });
    });

    describe('`calcOrderId` method', function() {
        it('should make deferred request to `price` endpoint and returns promise', function() {
            spyOn(calculator.requests, 'deferred').and.callFake(fakeDeferred);
            var promise = calculator.calcOrderId('999-000-000-001');
            expect(calculator.requests.deferred).toHaveBeenCalledWith('price', {
                'order_id': '999-000-000-001'
            });
            expect(Q.isPromise(promise)).toBeTruthy();
        });
    });
});

redpajama_set_name: RedPajamaGithub


text:
package main

import (
	"context"
	"flag"
	"fmt"
	"net"
	"os"
	"time"

	drghs_v1 "github.com/GoogleCloudPlatform/devrel-services/drghs/v1"
	"github.com/GoogleCloudPlatform/devrel-services/samplr"
	"github.com/GoogleCloudPlatform/devrel-services/samplr/samplrd/samplrapi"

	"cloud.google.com/go/profiler"
	"github.com/sirupsen/logrus"
	"golang.org/x/sync/errgroup"
	"google.golang.org/grpc"
)

var (
	listen        = flag.String("listen", "0.0.0.0:3009", "gRPC listen address")
	owner         = flag.String("owner", "", "Google Cloud Storage bucket to use for settings storage")
	repo          = flag.String("repo", "", "File that contains the list of repositories")
	defaultBranch = flag.String("branch", "master", "Branch to track snippets from")
	verbose       = flag.Bool("verbose", false, "Verbose logs")
)

var log *logrus.Logger

func init() {
	log = logrus.New()
	log.Formatter = &logrus.JSONFormatter{
		FieldMap: logrus.FieldMap{
			logrus.FieldKeyTime:  "timestamp",
			logrus.FieldKeyLevel: "severity",
			logrus.FieldKeyMsg:   "message",
		},
		TimestampFormat: time.RFC3339Nano,
	}
	samplr.FormatLog(log.Formatter)

	log.Out = os.Stdout
}

func main() {

	flag.Parse()

	if *verbose == true {
		log.Level = logrus.DebugLevel
		samplr.VerboseLog()
	}

	if *owner == "" {
		err := fmt.Errorf("must provide --owner")
		log.Fatal(err)
	}

	if *repo == "" {
		err := fmt.Errorf("must provide --repos")
		log.Fatal(err)
	}

	// Profiler initialization, best done as early as possible.
	if err := profiler.Start(profiler.Config{
		Service:        fmt.Sprintf("samplrd-%v-%v", *owner, *repo),
		ServiceVersion: "0.0.1",
		MutexProfiling: true,
	}); err != nil {
		log.Error(fmt.Errorf("error initializing profiler: %v", err))
	}

	corpus := &samplr.Corpus{}

	loadGroup, _ := errgroup.WithContext(context.Background())

	repoPath := fmt.Sprintf("https://github.com/%v/%v", *owner, *repo)
	loadGroup.Go(func() error {
		log.Printf("Tracking repo: %s", repoPath)
		return corpus.TrackGit(repoPath, *defaultBranch)
	})

	if err := loadGroup.Wait(); err != nil {
		log.Fatal(err)
		return
	}

	err := corpus.Initialize(context.Background())
	if err != nil {
		log.Error(err)
		return
	}

	group, ctx := errgroup.WithContext(context.Background())

	group.Go(func() error {
		return corpus.Sync(ctx)
	})

	group.Go(func() error {
		lis, err := net.Listen("tcp", *listen)
		if err != nil {
			log.Fatalf("failed to listen %v", err)
		}

		grpcServer := grpc.NewServer()
		drghs_v1.RegisterSampleServiceServer(grpcServer, samplrapi.NewSampleServiceServer(corpus))

		go func() {
			select {
			case <-ctx.Done():
				grpcServer.GracefulStop()
			}
		}()

		log.Printf("gRPC server listening on: %s", *listen)
		return grpcServer.Serve(lis)
	})

	err = group.Wait()
	log.Fatal(err)
}


text:
Cantango is by default setup to autoload the following:

* Models (app/models)
* Permits (app/permits)

The autoloading is performed as part of the Cantango Rails engine initialization.

To configure autoloading:

```ruby
Cantango.configure.autoload do |load|
  load.models :off
  load.permits :on
end
```

## Models autoloading

Models are autoloaded in order to be sure that the Cantango class macros such as `#tango_user` are executed
and thus that User and Account modesl are registered with Cantango.

If you don't wont to autoload the models for performance or other
reasons, you can alternatively register the models directly (see [Models
registration]]).

## Permits autoloading

Permits autoloading is done so as to ensure they are made available to
CanTango::Ability. If you want full control over which Permits are
loaded when, you can disable this feature.


text:
package org.db2project.EventDetection.Classifier;
/**
 * This class models the node of  graph.
 * @author eleal
 *
 * @param <T>
 */
public class GraphNode<T> {
	private String name;
	private long id;
	T element;

	public GraphNode(T element) {
		this.element = element;
		this.name = element.toString();
	}

	public GraphNode(T element, String name) {
		this.element = element;
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public long getID(){
		return this.id;
	}

	public void setID(long id){
		this.id = id;
	}

	public String toString(){
		return name;
	}

	public T getElement(){
		return element;
	}

}


text:
\clearpage
\phantomsection
\addcontentsline{toc}{subsection}{XLARG}
\label{insn:xlarg}
\subsection*{XLARG: translation argument}

\subsubsection*{Format}

\textrm{XLARG \%rd, \%r1, \%r2}

\begin{center}
\begin{bytefield}[endianness=big,bitformatting=\scriptsize]{32}
\bitheader{0,7,8,15,16,23,24,31} \\
\bitbox{8}{0x4F}
\bitbox{8}{r1}
\bitbox{8}{r2}
\bitbox{8}{rd}
\end{bytefield}
\end{center}

\subsubsection*{Description}

The \instruction{xlarg} instruction translates a single argument from
a structure and returns the tranlsated value in \registerop{rd}.

\emph{NOTE:} This instruction is not used by the kernel as all
translations are handled in user space.

\subsubsection*{Failure modes}

This instruction has no run-time failure modes beyond its constraints.


text:
package io.mycat.manager.response;

import java.nio.ByteBuffer;

import io.mycat.MycatServer;
import io.mycat.backend.mysql.PacketUtil;
import io.mycat.config.Fields;
import io.mycat.manager.ManagerConnection;
import io.mycat.net.FrontendConnection;
import io.mycat.net.NIOProcessor;
import io.mycat.net.mysql.EOFPacket;
import io.mycat.net.mysql.FieldPacket;
import io.mycat.net.mysql.ResultSetHeaderPacket;
import io.mycat.net.mysql.RowDataPacket;
import io.mycat.server.ServerConnection;
import io.mycat.util.LongUtil;
import io.mycat.util.StringUtil;
import io.mycat.util.TimeUtil;

/**
 * @author mycat
 */
public final class ShowConnectionSQL {

    private static final int FIELD_COUNT = 7;
    private static final ResultSetHeaderPacket header = PacketUtil.getHeader(FIELD_COUNT);
    private static final FieldPacket[] fields = new FieldPacket[FIELD_COUNT];
    private static final EOFPacket eof = new EOFPacket();
    static {
        int i = 0;
        byte packetId = 0;
        header.packetId = ++packetId;

        fields[i] = PacketUtil.getField("ID", Fields.FIELD_TYPE_LONG);
        fields[i++].packetId = ++packetId;

        fields[i] = PacketUtil.getField("HOST", Fields.FIELD_TYPE_VAR_STRING);
        fields[i++].packetId = ++packetId;

        fields[i] = PacketUtil.getField("USER", Fields.FIELD_TYPE_VAR_STRING);
        fields[i++].packetId = ++packetId;

        fields[i] = PacketUtil.getField("SCHEMA", Fields.FIELD_TYPE_VAR_STRING);
        fields[i++].packetId = ++packetId;

        fields[i] = PacketUtil.getField("START_TIME", Fields.FIELD_TYPE_LONGLONG);
        fields[i++].packetId = ++packetId;

        fields[i] = PacketUtil.getField("EXECUTE_TIME", Fields.FIELD_TYPE_LONGLONG);
        fields[i++].packetId = ++packetId;

        fields[i] = PacketUtil.getField("SQL", Fields.FIELD_TYPE_VAR_STRING);
        fields[i++].packetId = ++packetId;

        eof.packetId = ++packetId;
    }

    public static void execute(ManagerConnection c) {
        ByteBuffer buffer = c.allocate();

        // write header
        buffer = header.write(buffer, c,true);

        // write fields
        for (FieldPacket field : fields) {
            buffer = field.write(buffer, c,true);
        }

        // write eof
        buffer = eof.write(buffer, c,true);

        // write rows
        byte packetId = eof.packetId;
        String charset = c.getCharset();
        for (NIOProcessor p : MycatServer.getInstance().getProcessors()) {
            for (FrontendConnection fc : p.getFrontends().values()) {
                if (!fc.isClosed()) {
                	if(fc.getExecuteSql()==null){
                		continue;
                	}
                	if(fc instanceof ServerConnection){
                		RowDataPacket row = getRow(fc, charset);
                        row.packetId = ++packetId;
                        buffer = row.write(buffer, c,true);
                	}
                }
            }
        }

        // write last eof
        EOFPacket lastEof = new EOFPacket();
        lastEof.packetId = ++packetId;
        buffer = lastEof.write(buffer, c,true);

        // write buffer
        c.write(buffer);
    }

    private static RowDataPacket getRow(FrontendConnection c, String charset) {
    	String executeSql = c.getExecuteSql();
        RowDataPacket row = new RowDataPacket(FIELD_COUNT);
        row.add(LongUtil.toBytes(c.getId()));
        row.add(StringUtil.encode(c.getHost(), charset));
        row.add(StringUtil.encode(c.getUser(), charset));
        row.add(StringUtil.encode(c.getSchema(), charset));
        row.add(LongUtil.toBytes(c.getLastReadTime()));
        long rt = c.getLastReadTime();
        long wt = c.getLastWriteTime();
        row.add(LongUtil.toBytes(executeSql==null?0:((wt > rt) ? (wt - rt) : (TimeUtil.currentTimeMillis() - rt))));
        row.add(StringUtil.encode(executeSql==null?"":executeSql, charset) );
        return row;
    }

}


text:
<!doctype html>

		<title>Druid Stat JSON API</title>
		<meta http-equiv="Content-Type" content="text/html; charset=utf8" />
		<link href='css/bootstrap.min.css' rel="stylesheet" />
		<link href="css/style.css" type="text/css" rel="stylesheet"/>

          					JSON API

									Name
									Description

								basic.json
								basic info.

								datasource.json
								DatsSourceStat List

								datasource-{id}.json
								DatasourceStat for id={id},id is DatsSourceStat.ID

						Example: druid/datasource-1.json

								activeConnectionStackTrace-{datasourceId}.json
								StrackTrace for activeConnection in datasource which datasource.id={datasourceId},id is DatsSourceStat.ID

						Required: set removeAbandoned=true

						Example: druid/activeConnectionStackTrace-1.json

								sql.json
								SqlStat for id={id} ,id is SqlStat.ID

						Example: druid/sql-1.json

								WallStat.json
								WallStat List

								wall-{id}.json
								WallStat for id={id},id is DatsSourceStat.ID

						Example: druid/wall-1.json

								basic.json

								weburi.json

								websession.json

								 reset-all.json
								 Reset all stat


text:
package scouter.server.term;

import java.io.IOException;

import scala.tools.jline.TerminalFactory;
import scala.tools.jline.console.ConsoleReader;
import scala.tools.jline.console.completer.StringsCompleter;
import scouter.server.ShutdownManager;
import scouter.server.term.handler.Help;
import scouter.server.term.handler.ProcessMain;
import scouter.util.IShutdown;
import scouter.util.ShellArg;
import scouter.util.SystemUtil;

public class TermMain {

	public static void process(ShellArg ar) throws IOException, Exception {

		AnsiPrint.enable = SystemUtil.IS_WINDOWS == false;

		if (ar.hasKey("-ansi"))
			AnsiPrint.enable = true;
		else if (ar.hasKey("-noansi"))
			AnsiPrint.enable = false;

		ShutdownManager.add(new IShutdown() {
			public void shutdown() {
				try {
					TerminalFactory.get().restore();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		ConsoleReader console = new ConsoleReader();
		console.setHistoryEnabled(true);
		// console.addCompleter(new FileNameCompleter());
		console.addCompleter(new StringsCompleter(Help.words()));

		console.setPrompt(AnsiPrint.green("scouter> "));
		while (true) {
			try {
				String cmd = console.readLine();
				ProcessMain.process(cmd.trim());
			} catch (Throwable t) {
				t.printStackTrace();
			}
		}
	}

	public static void exit() {
		System.exit(0);
	}

}


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Pacman.GameLogic.Ghosts;

namespace Pacman.GameLogic
{
	public static class StateInfo
	{
		public static bool IsInverse(Direction d1, Direction d2) {
			if( d1 == Direction.Up && d2 == Direction.Down ) return true;
			if( d1 == Direction.Down && d2 == Direction.Up ) return true;
			if( d1 == Direction.Left && d2 == Direction.Right ) return true;
			if( d1 == Direction.Right && d2 == Direction.Left ) return true;
			return false;
		}

		public static Direction GetInverse(Direction d) {
			switch( d ) {
				case Direction.Up: return Direction.Down;
				case Direction.Down: return Direction.Up;
				case Direction.Left: return Direction.Right;
				case Direction.Right: return Direction.Left;
			}
			return Direction.None;
		}

		public static PillPath NearestPill(Node currentNode, GameState gs) {
			Node bestNode = null;
			Node.PathInfo bestPath = null;
			foreach( Node node in gs.Map.PillNodes ) {
				//if( node.Walkable ) {
				//	if( node.Type == Node.NodeType.Pill || node.Type == Node.NodeType.PowerPill ) {
						if( bestPath == null ) {
							bestNode = node;
							bestPath = gs.Pacman.Node.ShortestPath[node.X, node.Y];
							continue;
						}
						Node.PathInfo curPath = currentNode.ShortestPath[node.X, node.Y];
						if( curPath != null && curPath.Distance < bestPath.Distance ) {
							bestNode = node;
							bestPath = curPath;
						}
				//	}
				//}
			}
			return new PillPath(bestNode, bestPath);
		}

        // Return the nearest edible ghost in the game.
        public static Ghost NearestEdibleGhost(GameState gs)
        {
            Ghost _nearestGhost = null;

            foreach (var ghost in gs.Ghosts)
            {
                if (_nearestGhost == null)
                {
                    if (ghost.Fleeing && ghost.Entered)
                    {
                        _nearestGhost = ghost;
                    }
                }
                else if (_nearestGhost.Node.ManhattanDistance(gs.Pacman.Node) > ghost.Node.ManhattanDistance(gs.Pacman.Node)
                    && ghost.Fleeing && ghost.Entered)
                {
                    _nearestGhost = ghost;
                }
            }

            return _nearestGhost;
        }

        // Return the nearest ghost to Pacman.
        public static Ghost NearestGhost(GameState gs)
        {
            Ghost _nearestGhost = null;

            foreach (var ghost in gs.Ghosts)
            {
                // If no ghost has been assigned the make it the first one
                if (_nearestGhost == null)
                {
                    if (ghost.Entered)
                    {
                        _nearestGhost = ghost;
                    }
                }
                else if (_nearestGhost.Node.ManhattanDistance(gs.Pacman.Node) >
                         ghost.Node.ManhattanDistance(gs.Pacman.Node))
                {
                    _nearestGhost = ghost;
                }
            }

            return _nearestGhost;
        }

        public static PillPath NearestPowerPill(Node currentNode, GameState gs)
        {
            Node bestNode = null;
            Node.PathInfo bestPath = null;

            foreach (Node node in gs.Map.PowerPillNodes)
            {
                //if (node.Walkable)
                //{
                    if (node.Type == Node.NodeType.PowerPill)
                    {
                        if (bestPath == null)
                        {
                            bestNode = node;
                            bestPath = gs.Pacman.Node.ShortestPath[node.X, node.Y];
                            continue;
                        }

                        Node.PathInfo curPath = currentNode.ShortestPath[node.X, node.Y];

                        if (curPath != null && curPath.Distance < bestPath.Distance)
                        {
                            bestNode = node;
                            bestPath = curPath;
                        }
                    }
                //}
            }
            return new PillPath(bestNode, bestPath);
        }

		public static PillPath FurthestPill(Node currentNode, GameState gs) {
			Node bestNode = null;
			Node.PathInfo bestPath = null;
			foreach( Node node in gs.Map.Nodes ) {
				if( node.Walkable ) {
					if( node.Type == Node.NodeType.Pill || node.Type == Node.NodeType.PowerPill ) {
						if( bestPath == null ) {
							bestNode = node;
							bestPath = gs.Pacman.Node.ShortestPath[node.X, node.Y];
							continue;
						}
						Node.PathInfo curPath = currentNode.ShortestPath[node.X, node.Y];
						if( curPath != null && curPath.Distance > bestPath.Distance ) {
							bestNode = node;
							bestPath = curPath;
						}
					}
				}
			}
			return new PillPath(bestNode, bestPath);
		}

        // Return the remaining amount of power pills in the map
        public static int RemainingPowerPills(GameState gs)
        {
            return (gs.Map.PillNodes.Where(n => n.Type == Node.NodeType.PowerPill).Count());
        }

		public class PillPath
		{
			public Node Target;
			public Node.PathInfo PathInfo;

			public PillPath(Node target, Node.PathInfo pathInfo) {
				this.Target = target;
				this.PathInfo = pathInfo;
			}
		}
	}
}


text:
FOUNDATION_EXPORT double LUAutocompleteViewVersionNumber;

//! Project version string for LUAutocompleteView.
FOUNDATION_EXPORT const unsigned char LUAutocompleteViewVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <LUAutocompleteView/PublicHeader.h>


text:
package org.camunda.bpm.engine.test.api.authorization.externaltask;

import static org.camunda.bpm.engine.test.api.authorization.util.AuthorizationScenario.scenario;
import static org.camunda.bpm.engine.test.api.authorization.util.AuthorizationSpec.grant;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.camunda.bpm.engine.authorization.Permissions;
import org.camunda.bpm.engine.authorization.Resources;
import org.camunda.bpm.engine.externaltask.ExternalTask;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.test.Deployment;
import org.camunda.bpm.engine.test.ProcessEngineRule;
import org.camunda.bpm.engine.test.api.authorization.util.AuthorizationScenario;
import org.camunda.bpm.engine.test.api.authorization.util.AuthorizationTestRule;
import org.camunda.bpm.engine.test.util.ProvidedProcessEngineRule;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)
public class SetExternalTasksRetriesAuthorizationTest {
  public ProcessEngineRule engineRule = new ProvidedProcessEngineRule();
  public AuthorizationTestRule authRule = new AuthorizationTestRule(engineRule);

  @Rule
  public RuleChain chain = RuleChain.outerRule(engineRule).around(authRule);

  @Parameter
  public AuthorizationScenario scenario;

  @Parameters(name = "Scenario {index}")
  public static Collection<AuthorizationScenario[]> scenarios() {
    return AuthorizationTestRule.asParameters(
      scenario()
      .withAuthorizations(
          grant(Resources.PROCESS_INSTANCE, "processInstanceId2", "userId", Permissions.UPDATE))
        .withoutAuthorizations()
        .failsDueToRequired(
          grant(Resources.PROCESS_INSTANCE, "processInstanceId1", "userId", Permissions.UPDATE),
          grant(Resources.PROCESS_DEFINITION, "oneExternalTaskProcess", "userId", Permissions.UPDATE_INSTANCE)),
      scenario()
        .withAuthorizations(
          grant(Resources.PROCESS_INSTANCE, "processInstanceId1", "userId", Permissions.UPDATE),
          grant(Resources.PROCESS_INSTANCE, "processInstanceId2", "userId", Permissions.UPDATE))
        .succeeds(),
      scenario()
        .withAuthorizations(
          grant(Resources.PROCESS_INSTANCE, "*", "userId", Permissions.UPDATE))
        .succeeds(),
      scenario()
        .withAuthorizations(
          grant(Resources.PROCESS_DEFINITION, "processDefinitionKey", "userId", Permissions.UPDATE_INSTANCE))
        .succeeds(),
      scenario()
        .withAuthorizations(
          grant(Resources.PROCESS_DEFINITION, "*", "userId", Permissions.UPDATE_INSTANCE))
        .succeeds()
      );
  }

  @Before
  public void setUp() {
    authRule.createUserAndGroup("userId", "groupId");
  }

  @After
  public void tearDown() {
    authRule.deleteUsersAndGroups();
  }

  @Test
  @Deployment(resources = "org/camunda/bpm/engine/test/api/externaltask/oneExternalTaskProcess.bpmn20.xml")
  public void testSetRetrieSync() {

    // given
    ProcessInstance processInstance1 = engineRule.getRuntimeService().startProcessInstanceByKey("oneExternalTaskProcess");
    ProcessInstance processInstance2 = engineRule.getRuntimeService().startProcessInstanceByKey("oneExternalTaskProcess");
    List<ExternalTask> tasks = engineRule.getExternalTaskService().createExternalTaskQuery().list();

    // when
    authRule
      .init(scenario)
      .withUser("userId")
      .bindResource("processInstanceId1", processInstance1.getId())
      .bindResource("processInstanceId2", processInstance2.getId())
      .bindResource("processDefinitionKey", "oneExternalTaskProcess")
      .start();

    ArrayList<String> externalTaskIds = new ArrayList<String>();
    externalTaskIds.add(tasks.get(0).getId());
    externalTaskIds.add(tasks.get(1).getId());

    engineRule.getExternalTaskService().setRetries(externalTaskIds, 5);

    // then
    if (authRule.assertScenario(scenario)) {
      tasks = engineRule.getExternalTaskService().createExternalTaskQuery().list();
      Assert.assertEquals(5, (int) tasks.get(0).getRetries());
      Assert.assertEquals(5, (int) tasks.get(1).getRetries());
    }

  }
}


text:
package org.ovirt.engine.core.bll.adbroker;

public enum IPAUserAttributes {
    ipaUniqueId,
    krbPrincipalname,
    givenname,
    department,
    title,
    mail,
    memberof,
    sn
}


text:
import { connect } from 'react-redux';
import { withHandlers } from 'recompose';
import { USERS_PROFESIONAL_SECTORS as sectors } from 'data/constants';
import actions from './modal-download-actions';
import reducers, { initialState } from './modal-download-reducers';

import Component from './modal-download-component';

import { countriesSelector, sectorsSelector } from './modal-download-selectors';

const mapStateToProps = ({ modalDownload, countries }) => ({
  isOpen: modalDownload.isOpen,
  downloadSize: modalDownload.downloadSize,
  countries: countriesSelector({ countries }),
  sectors: sectorsSelector({ sectors }),
  requiredError: modalDownload.requiredError,
  errorMessage: modalDownload.errorMessage,
  processing: modalDownload.processing
});

const includeActions = withHandlers({
  onRequestClose: props => () => {
    props.toggleModalDownload({ open: false });
  },

  onSubmit: ({ setRequiredFieldsError, saveSurveyData }) => internalState => {
    setRequiredFieldsError(internalState);
    saveSurveyData(internalState);
  }
});

export { actions, reducers, initialState };

export default connect(mapStateToProps, actions)(includeActions(Component));


text:
package ee.cone.c4ui

import ee.cone.c4actor._
import ee.cone.c4actor.dep.request.LeafInfoHolderTypes.ProductLeafInfoHolder
import ee.cone.c4actor.dep.request._
import ee.cone.c4actor.dep.{Dep, DepFactory, DepFactoryApp}
import ee.cone.c4actor.dep_impl.RequestDep
import ee.cone.c4actor.hashsearch.base.{HashSearchDepRequestFactory, HashSearchDepRequestFactoryApp, HashSearchDepRequestFactoryCreator}
import ee.cone.c4actor.hashsearch.condition.ConditionCheckWithCl
import ee.cone.c4actor.hashsearch.rangers.HashSearchRangerRegistryApp
import ee.cone.c4di.{Component, ComponentsApp, c4, provide}
import ee.cone.c4ui.dep.request.{FLRequestDef, FilterListRequestApp}

import scala.collection.immutable.Seq

case class DepFilterPK(filtersPK: String, matches: List[String])

trait DepFilterWrapperApp {
  def depFilterWrapper[Model <: Product](modelCl: Class[Model], listName: String, matches: List[DepFilterPK] = DepFilterPK("", ".*" :: Nil) :: Nil): DepFilterWrapper[Model]
}

trait DepFilterWrapperMix extends DepFilterWrapperApp with HashSearchRangerRegistryApp with DepFactoryApp {
  def modelConditionFactory: ModelConditionFactory[Unit]

  def modelFactory: ModelFactory

  def depFilterWrapper[Model <: Product](modelCl: Class[Model], listName: String, matches: List[DepFilterPK] = DepFilterPK("", ".*" :: Nil) :: Nil): DepFilterWrapper[Model] = {
    val modelCondFactoryTyped = modelConditionFactory.ofWithCl(modelCl)
    DepFilterWrapperImpl(Nil, listName, matches)(Seq({ _ => depFactory.resolvedRequestDep(modelCondFactoryTyped.any) }), modelCl, modelCondFactoryTyped, depFactory)
  }
}

trait DepFilterWrapperProvider {
  def filterWrappers: List[DepFilterWrapper[_ <: Product]]
}

trait DepFilterWrapperCollectorMixBase
  extends HashSearchDepRequestFactoryApp

@c4("DepFilterWrapperCollectorMix") final class DepFilterWrapperCollectorLeafs(
  providers: List[DepFilterWrapperProvider],
  creator: HashSearchDepRequestFactoryCreator
) {
  @provide def leafs: Seq[ProductLeafInfoHolder] = for {
    provider <- providers
    filterWrapper <- provider.filterWrappers
    leaf <- filterWrapper.getLeafs
  } yield leaf

  @provide def filterDepList: Seq[FLRequestDef] =
    providers.flatMap(_.filterWrappers).flatMap(_.filterRequests(creator))
}

case class DepFilterWrapperImpl[Model <: Product](
  leafs: List[LeafInfoHolder[Model, _ <: Product, _]],
  listName: String,
  matches: List[DepFilterPK]
)(
  depConditionSeq: Seq[String => Dep[Condition[Model]]],
  val modelCl: Class[Model],
  modelConditionFactory: ModelConditionFactory[Model],
  depFactory: DepFactory
) extends DepFilterWrapper[Model] {
  def add[By <: Product, Field](
    byDep: String => Dep[Option[Access[By]]],
    lens: ProdGetter[Model, Field],
    byOptions: List[AbstractMetaAttr] = Nil
  )(
    implicit checker: ConditionCheckWithCl[By, Field]
  ): DepFilterWrapper[Model] = {
    val (sByCl, sFieldCl) = (checker.byCl, checker.fieldCl)
    val newLeafs = LeafInfoHolder(lens, byOptions, checker, modelCl, sByCl, sFieldCl) :: leafs
    import modelConditionFactory._
    val newDep: String => Dep[Condition[Model]] = pk =>
      for {
        byResolved <- byDep(pk)
      } yield {
        leaf[By, Field](lens, byResolved.get.initialValue, byOptions)(checker)
      }
    DepFilterWrapperImpl(
      newLeafs,
      listName,
      matches
    )(newDep +: depConditionSeq,
      modelCl,
      modelConditionFactory,
      depFactory
    )
  }

  def getLeafs: List[LeafInfoHolder[_ <: Product, _ <: Product, _]] = leafs

  def getFilterDep: HashSearchDepRequestFactoryCreator => String => Dep[List[Model]] = factory => filterPK => {
    val typedFactory = factory.ofWithCl(modelCl)
    for {
      conditions <- depFactory.parallelSeq[Condition[Model]](depConditionSeq.map(_.apply(filterPK)))
      list <- {
        val rq = typedFactory.conditionToHashSearchRequest(conditions.reduce(modelConditionFactory.intersect))
        new RequestDep[List[Model]](rq)
      }
    } yield list
  }

  def filterRequests: HashSearchDepRequestFactoryCreator => List[FLRequestDef] = factory =>
    for {
      depFilterPK <- matches
      DepFilterPK(filtersPK, matches) = depFilterPK
      preAppliedLambda = getFilterDep(factory)
    } yield {
      FLRequestDef(listName, filtersPK, matches)(preAppliedLambda(filtersPK).asInstanceOf[Dep[List[_]]])
    }

  def addSwitch(
    isLeftDep: String => Dep[Boolean],
    partLeft: DepFilterWrapperPartApi[Model],
    partRight: DepFilterWrapperPartApi[Model]
  ): DepFilterWrapper[Model] = {
    val newDep: String => Dep[Condition[Model]] = pk => for {
      isLeft <- isLeftDep(pk)
      depCondition = if (isLeft) partLeft.depCondition else partRight.depCondition
      condition <- depCondition(pk)
    } yield {
      condition
    }

    DepFilterWrapperImpl[Model](
      partLeft.leafs ::: partRight.leafs ::: leafs,
      listName,
      matches
    )(
      newDep +: depConditionSeq,
      modelCl,
      modelConditionFactory,
      depFactory
    )
  }

  def getPart: DepFilterWrapperPrePartApi[Model] =
    DepFilterWrapperPrePartImpl((leafs.size, listName, matches.size))(modelCl, modelConditionFactory, depFactory)
}

case class DepFilterWrapperPrePartImpl[Model <: Product](
  status: (Int, String, Int)
)(
  val modelCl: Class[Model],
  val modelConditionFactory: ModelConditionFactory[Model],
  depFactory: DepFactory
) extends DepFilterWrapperPrePartApi[Model] {
  def createWith(
    leaf: LeafInfoHolder[Model, _ <: Product, _],
    newDep: String => Dep[Condition[Model]]
  ): DepFilterWrapperPartApi[Model] =
    DepFilterWrapperPartImpl(
      leaf :: Nil
    )(
      Seq(newDep),
      modelCl,
      modelConditionFactory,
      depFactory
    )
}

case class DepFilterWrapperPartImpl[Model <: Product](
  leafs: List[LeafInfoHolder[Model, _ <: Product, _]]
)(
  val depConditionSeq: Seq[String => Dep[Condition[Model]]],
  val modelCl: Class[Model],
  val modelConditionFactory: ModelConditionFactory[Model],
  depFactory: DepFactory
) extends DepFilterWrapperPartApi[Model] {

  def createWith(
    leaf: LeafInfoHolder[Model, _ <: Product, _],
    newDep: String => Dep[Condition[Model]]
  ): DepFilterWrapperPartApi[Model] =
    DepFilterWrapperPartImpl(
      leaf :: leafs
    )(newDep +: depConditionSeq,
      modelCl,
      modelConditionFactory,
      depFactory
    )

  def depCondition: String => Dep[Condition[Model]] = pk =>
    for {
      conditions <- depFactory.parallelSeq(depConditionSeq.map(_.apply(pk)))
    } yield {
      conditions.reduce(modelConditionFactory.intersect)
    }
}

trait DepFilterWrapper[Model <: Product] extends Product {
  def add[By <: Product, Field](
    byDep: String => Dep[Option[Access[By]]],
    lens: ProdGetter[Model, Field],
    byOptions: List[AbstractMetaAttr] = Nil
  )(
    implicit checker: ConditionCheckWithCl[By, Field]
  ): DepFilterWrapper[Model]

  /*
    If true, then first is selected, otherwise second
   */
  def addSwitch(
    isLeftDep: String => Dep[Boolean],
    partLeft: DepFilterWrapperPartApi[Model],
    partRight: DepFilterWrapperPartApi[Model]
  ): DepFilterWrapper[Model]

  def getPart: DepFilterWrapperPrePartApi[Model]

  def getLeafs: List[LeafInfoHolder[_ <: Product, _ <: Product, _]]

  def filterRequests: HashSearchDepRequestFactoryCreator => List[FLRequestDef]

  def modelCl: Class[Model]

  def listName: String
}

trait DepFilterWrapperPrePartApi[Model <: Product] extends DepFilterWrapperPartAdd[Model]

trait DepFilterWrapperPartApi[Model <: Product] extends DepFilterWrapperPartAdd[Model] {
  def leafs: List[LeafInfoHolder[Model, _ <: Product, _]]

  def depCondition: String => Dep[Condition[Model]]
}

trait DepFilterWrapperPartAdd[Model <: Product] {
  def modelCl: Class[Model]

  def modelConditionFactory: ModelConditionFactory[Model]

  def createWith(leaf: LeafInfoHolder[Model, _ <: Product, _], newDep: String => Dep[Condition[Model]]): DepFilterWrapperPartApi[Model]

  def add[By <: Product, Field](
    byDep: String => Dep[Option[Access[By]]],
    lens: ProdGetter[Model, Field],
    byOptions: List[AbstractMetaAttr] = Nil
  )(
    implicit checker: ConditionCheckWithCl[By, Field]
  ): DepFilterWrapperPartApi[Model] = {
    val (sByCl, sFieldCl) = (checker.byCl, checker.fieldCl)
    val newLeaf = LeafInfoHolder(lens, byOptions, checker, modelCl, sByCl, sFieldCl)
    val newDep: String => Dep[Condition[Model]] = pk =>
      for {
        byResolved <- byDep(pk)
      } yield {
        modelConditionFactory.leaf[By, Field](lens, byResolved.get.initialValue, byOptions)(checker)
      }
    createWith(newLeaf, newDep)
  }
}


text:
package org.apache.geode.cache.partition;

import java.util.Set;

/**
 * Information describing the data storage and distribution of a partitioned region. The
 * {@link PartitionRegionHelper} is used to gather PartitionRegionInfo. Each instance
 * describes a single partitioned region identified by {@link #getRegionPath()}.
 *

 * This is an immutable snapshot of the information.
 *
 * @since GemFire 6.0
 */
public interface PartitionRegionInfo {

  /**
   * Returns the {@link org.apache.geode.cache.Region#getFullPath() full path} of the partitioned
   * region that this object describes.
   *
   * @return the full path of the partitioned region that this info describes
   */
  String getRegionPath();

  /**
   * Returns an immutable set of PartitionMemberInfo representing every member that is
   * configured to provide storage space to the partitioned region.
   *
   * @return set of member info configured for storage space
   */
  Set<PartitionMemberInfo> getPartitionMemberInfo();

  /**
   * Returns the {@link org.apache.geode.cache.PartitionAttributes#getTotalNumBuckets() configured
   * number of buckets} for the partitioned region.
   *
   * @return the configured number of buckets
   */
  int getConfiguredBucketCount();

  /**
   * Returns the number of actual buckets that have been created to hold data for the partitioned
   * region. This is less than or equal to {#link #getConfiguredBucketCount()}.
   *
   * @return the current number of actual buckets that have been created
   */
  int getCreatedBucketCount();

  /**
   * Returns the number of created buckets that have fewer than the
   * {@link #getConfiguredRedundantCopies() configured redundant copies} for this partitioned
   * region.
   *
   * @return the number of created buckets that have fewer than the configured redundant copies
   * @see #getActualRedundantCopies()
   */
  int getLowRedundancyBucketCount();

  /**
   * Returns the number of {@link org.apache.geode.cache.PartitionAttributes#getRedundantCopies()
   * redundant copies} the partitioned region was configured for.
   *
   * @return the number of redundant copies the partitioned region was configured for
   */
  int getConfiguredRedundantCopies();

  /**
   * Returns the lowest number of redundant copies for any bucket holding data for the partitioned
   * region. If all data is currently at full redundancy then this will return the same value as
   * {@link #getConfiguredRedundantCopies}.
   *
   * @return the lowest number of redundant copies for any bucket of the partitioned region.
   */
  int getActualRedundantCopies();

  /**
   * Returns the {@link org.apache.geode.cache.Region#getFullPath() full path} of the partitioned
   * region that this region has been configured to be
   * {@link org.apache.geode.cache.PartitionAttributes#getColocatedWith() colocated with} or null if
   * it is not colocated.
   *
   * @return the full path of the partitioned region that the region is colocated with or null if
   *         there is none.
   */
  String getColocatedWith();
}


text:
"""
Django HAL
==========

A set of utilities for building HAL REST APIs in Django.

"""

import os
from setuptools import setup, find_packages

PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
VERSION_FILE_PATH = os.path.join(PROJECT_DIR, 'VERSION')
README_FILE_PATH = os.path.join(PROJECT_DIR, 'README.rst')

def read(path):
  if not os.path.isfile(path):
    raise EnvironmentError("File not found: %s" % path)
  with open(path) as f:
    return f.read().strip()

if __name__ == '__main__':
  setup(
    name='django-hal',
    version=read(VERSION_FILE_PATH),
    description=read(README_FILE_PATH),
    author='Nick Zarczynski',
    author_email='nick@unb.services',
    url='https://github.com/unbservices/django-hal',
    license='MIT',
    packages=find_packages(),
    include_package_data=True,
    install_requires=[],
    # For a full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=[
      'Development Status :: 2 - Pre-Alpha',
      'Environment :: Web Environment',
      'Framework :: Django',
      'Framework :: Django :: 1.8',
      'License :: OSI Approved :: MIT License',
      'Natural Language :: English',
      'Operating System :: OS Independent',
      'Programming Language :: Python',
      'Programming Language :: Python :: 2.7',
    ],
  )


text:
from django.db import models
from django.utils import timezone

# Category
class Category(models.Model):
    name        = models.TextField()
    name_search = models.CharField(max_length=512)
    alias       = models.CharField(max_length=100)
    description = models.TextField()
    parent      = models.ForeignKey('self', null=True, default=None)
    level       = models.IntegerField()
    order       = models.IntegerField()
    path        = models.CharField(max_length=512, null=True)
    state       = models.BooleanField(default=True)
    created     = models.DateTimeField()
    created_by  = models.CharField(max_length=100, null=True, default=None)
    modified    = models.DateTimeField()
    modified_by = models.CharField(max_length=100, null=True, default=None)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ['order']

# Doc Type
class DocType(models.Model):
    name        = models.TextField()
    name_search = models.CharField(max_length=512)
    alias       = models.CharField(max_length=100)
    state       = models.BooleanField(default=True)
    created     = models.DateTimeField()
    created_by  = models.CharField(max_length=100, null=True, default=None)
    modified    = models.DateTimeField()
    modified_by = models.CharField(max_length=100, null=True, default=None)

    def __str__(self):
        return self.alias

    class Meta:
        ordering = ['alias']

# Language
class Language(models.Model):
    name        = models.TextField()
    name_search = models.CharField(max_length=512)
    alias       = models.CharField(max_length=100)
    state       = models.BooleanField(default=True)
    created     = models.DateTimeField()
    created_by  = models.CharField(max_length=100, null=True, default=None)
    modified    = models.DateTimeField()
    modified_by = models.CharField(max_length=100, null=True, default=None)

    def __str__(self):
        return self.alias

    class Meta:
        ordering = ['alias']

# License
class License(models.Model):
    name        = models.TextField()
    name_search = models.CharField(max_length=512)
    alias       = models.CharField(max_length=100)
    description = models.TextField()                                           # Описание
    state       = models.BooleanField(default=True)
    created     = models.DateTimeField()
    created_by  = models.CharField(max_length=100, null=True, default=None)
    modified    = models.DateTimeField()
    modified_by = models.CharField(max_length=100, null=True, default=None)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ['alias']

# Article
class Article(models.Model):
    title        = models.TextField()                                           # Заголовок
    title_search = models.CharField(max_length=512)
    alias        = models.CharField(max_length=100, null=True)                  # Псевдоним (служебное поле)
    patch        = models.CharField(max_length=512, null=True)                  # Путь
    thumb_src    = models.CharField(max_length=512, null=True)                  # Ссылка на изображение-предпросмотр

    intro        = models.TextField()                                           # Вводный текст
    content      = models.TextField()                                           # Текст статьи
    description  = models.TextField()                                           # Описание

    category     = models.ForeignKey(Category, null=True, default=None)         # Категория
    language     = models.ForeignKey(Language, null=True, default=None)         # Язык
    license      = models.ForeignKey(License,  null=True, default=None)         # Лицензия
    copyright    = models.CharField(max_length=512, null=True)                  # Копирайт

    source       = models.CharField(max_length=512, null=True)                  # Источник
    source_url   = models.CharField(max_length=512, null=True)                  # Ссылка на источник

    state        = models.BooleanField(default=True)                            # Статус (опубликована ли статья)
    on_main      = models.BooleanField(default=False)                           # На главной ли статья

    created      = models.DateTimeField()
    created_by   = models.CharField(max_length=100, null=True, default=None)
    modified     = models.DateTimeField()
    modified_by  = models.CharField(max_length=100, null=True, default=None)
    published    = models.DateTimeField(null=True, default=None)
    published_by = models.CharField(max_length=100, null=True, default=None)
    pub_from     = models.DateTimeField(null=True, default=None)
    pub_to       = models.DateTimeField(null=True, default=None)

    def __str__(self):
        return self.title

    class Meta:
        ordering = ['-created']

# Document
class Document(models.Model):
    title        = models.TextField()                                           # Заголовок
    title_search = models.CharField(max_length=512)
    alias        = models.CharField(max_length=100, null=True)                  # Псевдоним (служебное поле)
    patch        = models.CharField(max_length=512, null=True)                  # Путь
    src          = models.CharField(max_length=512, null=True)                  # Ссылка на расположение
    thumb_src    = models.CharField(max_length=512, null=True)                  # Ссылка на изображение-предпросмотр
    doc_type     = models.ForeignKey(DocType, null=True, default=None)          # Тип документа

    description  = models.TextField()                                           # Описание

    category     = models.ForeignKey(Category, null=True, default=None)         # Категория
    language     = models.ForeignKey(Language, null=True, default=None)         # Язык
    license      = models.ForeignKey(License,  null=True, default=None)         # Лицензия
    copyright    = models.CharField(max_length=512, null=True)                  # Копирайт

    source       = models.CharField(max_length=512, null=True)                  # Источник
    source_url   = models.CharField(max_length=512, null=True)                  # Ссылка на источник

    state        = models.BooleanField(default=True)

    created      = models.DateTimeField()
    created_by   = models.CharField(max_length=100, null=True, default=None)
    published    = models.DateTimeField(null=True, default=None)
    published_by = models.CharField(max_length=100, null=True, default=None)
    pub_from     = models.DateTimeField(null=True, default=None)
    pub_to       = models.DateTimeField(null=True, default=None)

    hash_md5     = models.CharField(max_length=100, null=True, default=None)

    def __str__(self):
        return self.title

    class Meta:
        ordering = ['-created']

# Document Collection
class DocumentCollection(models.Model):
    title        = models.TextField()                                           # Заголовок
    title_search = models.CharField(max_length=512)
    alias        = models.CharField(max_length=100, null=True)
    state        = models.BooleanField(default=True)
    created      = models.DateTimeField()
    created_by   = models.CharField(max_length=100, null=True, default=None)
    modified     = models.DateTimeField()
    modified_by  = models.CharField(max_length=100, null=True, default=None)

    to_article   = models.ManyToManyField(
        Article,  db_table='anodos_collection_to_article')
    to_document  = models.ManyToManyField(
        Document, db_table='anodos_collection_to_document')

    def __str__(self):
        return self.title

    class Meta:
        ordering = ['-created']

# Log manager
class LogManager(models.Manager):

    def add(self, subject, channel, title, description):

        log = Log(
            subject     = subject[:100],
            channel     = channel[:100],
            title       = title[:100],
            description = description,
            created     = timezone.now())
        print(log)
        log.save()
        return log

# Log
class Log(models.Model):

    subject     = models.CharField(max_length=100)
    channel     = models.CharField(max_length=100)
    title       = models.CharField(max_length=100)
    description = models.TextField()
    created     = models.DateTimeField()

    objects     = LogManager()

    def __str__(self):
        return "{} | {} | {} | {}".format(self.subject, self.channel, self.title, self.description)

    class Meta:
        ordering = ['-created']


text:
<?php

namespace Sylius\Component\Sequence\Model;

class Sequence implements SequenceInterface
{
    /**
     * Identifier
     * @var integer
     */
    protected $id;

    /**
     * Sequence index
     * @var integer
     */
    protected $index = 0;

    /**
     * Sequence type
     * @var string
     */
    protected $type;

    public function __construct($type)
    {
        $this->type = $type;
    }

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

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

    /**
     * {@inheritdoc}
     */
    public function getIndex()
    {
        return $this->index;
    }

    /**
     * {@inheritdoc}
     */
    public function incrementIndex()
    {
        $this->index++;

        return $this;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Copyright 2015 Red Hat, Inc. and/or its affiliates
    and other contributors as indicated by the @author tags.

    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.

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

  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.hawkular.alerts</groupId>
    <artifactId>hawkular-alerts</artifactId>
    <version>1.0.0.Alpha1-SNAPSHOT</version>
  </parent>

  <artifactId>hawkular-alerts-bus</artifactId>
  <packaging>jar</packaging>
  <name>Hawkular Alerts Bus Listener</name>

  <dependencies>

    <dependency>
      <groupId>org.hawkular.alerts</groupId>
      <artifactId>hawkular-alerts-api</artifactId>
      <version>${project.version}</version>
    </dependency>

    <dependency>
      <groupId>org.hawkular.alerts</groupId>
      <artifactId>hawkular-notifiers-api</artifactId>
      <version>${project.version}</version>
    </dependency>

    <!-- The hawkular platform will provide these -->
    <dependency>
      <groupId>org.hawkular.bus</groupId>
      <artifactId>hawkular-bus-mdb</artifactId>
      <version>${project.version}</version>
      <scope>provided</scope>
    </dependency>

    <!-- The hawkular platform will provide these transitive deps from common -->
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>${version.com.google.guava}</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>${version.com.google.code.gson}</version>
      <scope>provided</scope>
    </dependency>

    <!-- these will be provided by our RA - the MDB itself will never need ActiveMQ specific classes -->
    <dependency>
      <groupId>org.apache.activemq</groupId>
      <artifactId>activemq-all</artifactId>
      <version>${version.org.apache.activemq}</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>org.apache.activemq</groupId>
      <artifactId>activemq-jaas</artifactId>
      <version>${version.org.apache.activemq}</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${version.org.slf4j}</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>javax</groupId>
      <artifactId>javaee-api</artifactId>
      <version>${version.javaee.spec}</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${version.junit}</version>
      <scope>test</scope>
    </dependency>

  </dependencies>

</project>


text:
namespace tensorflow {
namespace text {
namespace {

using ::testing::ElementsAre;

TEST(ByteSplitterTest, SplitAscii) {
  const absl::string_view input_string("hello");
  std::vector<unsigned char> output_bytes;
  std::vector<int> output_offsets;
  ByteSplitter s;
  s.Split(input_string, &output_bytes, &output_offsets);
  EXPECT_THAT(output_bytes, ElementsAre(104, 101, 108, 108, 111));
  EXPECT_THAT(output_offsets, ElementsAre(0, 1, 2, 3, 4, 5));
}

TEST(ByteSplitterTest, SplitUnicode) {
  const absl::string_view input_string("muñdʓ");
  std::vector<unsigned char> output_bytes;
  std::vector<int> output_offsets;
  ByteSplitter s;
  s.Split(input_string, &output_bytes, &output_offsets);
  EXPECT_THAT(output_bytes, ElementsAre(109, 117, 195, 177, 100, 202, 147));
  EXPECT_THAT(output_offsets, ElementsAre(0, 1, 2, 3, 4, 5, 6, 7));
}

TEST(ByteSplitterTest, SplitEmoji) {
  const absl::string_view input_string("😀🙃");
  std::vector<unsigned char> output_bytes;
  std::vector<int> output_offsets;
  ByteSplitter s;
  s.Split(input_string, &output_bytes, &output_offsets);
  EXPECT_THAT(output_bytes,
              ElementsAre(240, 159, 152, 128, 240, 159, 153, 131));
  EXPECT_THAT(output_offsets, ElementsAre(0, 1, 2, 3, 4, 5, 6, 7, 8));
}

TEST(ByteSplitterTest, SplitHanzi) {
  const absl::string_view input_string("你好");
  std::vector<unsigned char> output_bytes;
  std::vector<int> output_offsets;
  ByteSplitter s;
  s.Split(input_string, &output_bytes, &output_offsets);
  EXPECT_THAT(output_bytes, ElementsAre(228, 189, 160, 229, 165, 189));
  EXPECT_THAT(output_offsets, ElementsAre(0, 1, 2, 3, 4, 5, 6));
}

}  // namespace
}  // namespace text
}  // namespace tensorflow


text:
title: Pai Nosso ...
date: 2019-07-22
author: Gustavo Furtado de Oliveira Alves
category: Reflexões
slug: 17o-domingo-do-tempo-comum-ano-c
description: Reflexão sobre o 17º domingo do tempo comum - Ano C
image: /images/jesus-rezando.jpg

> "Pai nosso, que estais no céu, santificado seja o Vosso Nome..."

Assim começamos a oração que o próprio Cristo nos ensinou.

O único dígno de ser chamado Filho de Deus, nos dá a dignidade de também sermos acolhidos como filhos do Pai Santo.

Pelos méritos de Jesus, temos a oportunidade de experimentar o Amor de Deus. E, assim, podemos pedir.

> "venha a nós o Vosso Reino..."

Desta forma, como bebês sujos que precisam ser limpos,
choramos e demonstramos nossa insatisfação com os reinados deste mundo.

> "seja feita a Vossa vontade assim na terra como no céu."

Então nos dispomos a ser instrumentos de evangelização para o que o Reino de Deus aconteça em nossas relações.
E reconhecemos o Senhorio de Deus, pedindo que Ele exerça o Seu reinado.

![Jesus rezando](/images/jesus-rezando.jpg){:style="width: 100%; padding: 10px;"}

> "O pão nosso de cada dia nos dai hoje."

Confiando na providência Divina, entregamos toda a nossa vida a Deus, pedindo o necessário para a nossa subsistência.

E devemos ter a consciência de que muitos passam fome, principalmente por causa da ganância e egoísmo de outros.
Devemos, então, viver o Evangelho através da partilha para que o Reino de Deus aconteça no meio de nós.

> "E perdoai-nos as nossas ofensas, assim como nós perdoamos a quem nos tem ofendido."

Só conseguiremos viver o Reino dos Céus aqui na terra quando reconhecermos a nossa condição de pecadores,
e nos sustentarmos uns aos outros, como irmãos frágeis que somos, partilhando o perdão de Deus.

Condicionamos, assim, a medida do perdão de Deus para conosco ao tamanho do nosso perdão.

> "E não nos deixeis cair em tentação. Mas livrai-nos do mal."

Por fim, pedimos ao Pai que não nos deixe desviar do caminho do Cristo.
Pois a nossa oração não tem sentido se não estivermos em comunhão com Ele.

A liturdia deste domingo (28/07/2019) nos convida a ser perseverantes na oração,
pois a oração sincera consegue mover o coração de Deus Pai.

Por isso sigamos os ensinamentos do Mestre e peçamos a Ele que nos ensine a rezar.

Se você for tocar/cantar nessa missa do **17º domingo do tempo comum - Ano C**?
No link aqui em baixo temos algumas sugestões de músicas para te ajudar na preparação.

[**>>Sugestões de música para a missa do 17º domingo do tempo comum - Ano C**](https://musicasparamissa.com.br/sugestoes-para/17o-domingo-do-tempo-comum-ano-c/){:target=\_blank}

E se for cantar o salmo, também gravamos uma melodia que pode te ajudar, confira aqui:

[**>>Melodia para o SALMO 137 (138) - NAQUELE DIA EM QUE GRITEI, VÓS ME ESCUTASTES, Ó SENHOR!**](https://musicasparamissa.com.br/musica/salmo-137-naquele-dia-em-que-gritei-vos-me-escutastes-o-senhor/){:target=\_blank}

Que Deus nos abençoe!

Gustavo


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

import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.xmlb.XmlSerializer;
import com.intellij.util.xmlb.XmlSerializerUtil;
import org.jdom.Element;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Konstantin Bulenkov
 */
@State(name = "DateTimeFormatter", storages = @Storage("ui-datetime.xml"))
public class DateTimeFormatManager implements PersistentStateComponent<Element> {
  private boolean myPrettyFormattingAllowed = true;
  private HashMap<String, String> myPatterns = new HashMap<>();

  @Nullable
  @Override
  public Element getState() {
    return XmlSerializer.serialize(this);
  }

  @Override
  public void loadState(@Nonnull Element state) {
    DateTimeFormatManager loaded = XmlSerializer.deserialize(state, DateTimeFormatManager.class);
    XmlSerializerUtil.copyBean(loaded, this);
  }

  public void setPrettyFormattingAllowed(boolean prettyFormattingAllowed) {
    myPrettyFormattingAllowed = prettyFormattingAllowed;
  }

  @Nullable
  public DateFormat getDateFormat(@Nonnull String formatterID) {
    String pattern = myPatterns.get(formatterID);
    if (pattern == null) {
      for (DateTimeFormatterBean formatterBean : DateTimeFormatterBean.EP_NAME.getExtensionList()) {
        if (formatterBean.id.equals(formatterID)) {
          if (!StringUtil.isEmpty(formatterBean.format)) {
            pattern = formatterBean.format;
          }
        }
      }
    }

    if (pattern != null) {
      try {
        return new SimpleDateFormat(pattern);
      }
      catch (IllegalArgumentException e) {
        e.printStackTrace();
      }
    }
    return null;
  }

  public Set<String> getIds() {
    return DateTimeFormatterBean.EP_NAME.getExtensionList().stream().map(bean -> bean.id).collect(Collectors.toSet());
  }

  @Nullable
  public String getDateFormatPattern(String formatterID) {
    return myPatterns.get(formatterID);
  }

  public void setDateFormatPattern(String formatterID, @Nullable String pattern) {
    //assert myPatterns.containsKey(formatterID) : "Unknown formatterID: " + formatterID
    if (StringUtil.isEmpty(pattern)) {
      myPatterns.remove(formatterID);
    }
    else {
      myPatterns.put(formatterID, pattern);
    }
  }

  public boolean isPrettyFormattingAllowed() {
    return myPrettyFormattingAllowed;
  }

  public static DateTimeFormatManager getInstance() {
    return ServiceManager.getService(DateTimeFormatManager.class);
  }

  public HashMap<String, String> getPatterns() {
    return myPatterns;
  }

  public void setPatterns(HashMap<String, String> patterns) {
    myPatterns = patterns;
  }
}


text:
function add(a, b) {
  return a + b;
}

function square(x){
  return x * x;
}

const foo = add(?, 1);
const bar = square(?);

expect(bar(foo(2))).toEqual(9);
expect(foo(2)).toEqual(3);
expect(bar(4)).toEqual(16);
expect(foo.length).toEqual(1);
expect(foo.name).toEqual("add");
expect(bar.length).toEqual(1);
expect(bar.name).toEqual("square");


text:
package vnmr.util;

import java.awt.*;
import java.beans.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import javax.swing.text.*;
import vnmr.ui.*;

/**
 * Message output
 */
public class MessageTool extends JScrollPane implements ChangeListener, PropertyChangeListener
{ /** session share */
    private SessionShare m_sshare;
    private AppIF m_appIf;
    private int  m_nVInc;
    private Point m_point;
    protected JTable m_table = null;
    private JTextArea textArea = null;
    private JScrollBar vScrollBar = null;
    private boolean bEndReturn = false;
    private Runnable scrollUpdater;

    /**
     * constructor
     */

    public MessageTool(SessionShare sshare, AppIF ep) {
        this.m_sshare = sshare;
        this.m_appIf = ep;

        textArea = new JTextArea();
        setViewportView(textArea);
        textArea.setEditable(false);
        textArea.setLineWrap(true);
        // textArea.setWrapStyleWord(true);

       /********************************
        DefaultTableModel tableModel = new DefaultTableModel(0, 1);
        m_table = new JTable(tableModel);
        m_table.setShowGrid(false);
        m_table.setTableHeader(null);
        m_table.setDefaultEditor(m_table.getColumnClass(0), null);
        setViewportView(m_table);
        setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        m_nVInc = this.getVerticalScrollBar().getUnitIncrement(SwingConstants.VERTICAL);
        tableModel.addTableModelListener(new TableModelListener()
        {
            public void tableChanged(TableModelEvent e)
            {
                doAction(e);
            }
        });
       **************************/

        setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        vScrollBar = getVerticalScrollBar();
        getViewport().addChangeListener( this );
        DisplayOptions.addChangeListener(this);
        scrollUpdater = new Runnable() {
           public void run() {
                  updateScrollBar();
           }
        };
        setUiColor();
    } // MessageTool

    private void setUiColor() {
        /**********
        Color c = DisplayOptions.getVJColor("VJBackground");
        if (c != null) {
            textArea.setBackground(c);
            setBackground(c);
        }
        c = DisplayOptions.getVJColor("VJTextFG");
        if (c != null) {
            textArea.setForeground(c);
        }
        **********/
    }

    public void propertyChange(PropertyChangeEvent evt)
    {
        if (DisplayOptions.isUpdateUIEvent(evt))
            setUiColor();
    }

    public void insert(String str) {
    }

    private void updateScrollBar() {
        // Dimension dim = textArea.getPreferredScrollableViewportSize();
        // vScrollBar.setValue(dim.height);
        int vMax = vScrollBar.getMaximum();
        vScrollBar.setValue(vMax);
    }

    public void append(String str) {
        int rows;
        if (str == null)
            return;
        if (textArea != null) {
            if (bEndReturn) {
                textArea.append("\n");
                bEndReturn = false;
            }
            // the last line should not be an empty line.
            rows = str.length() - 1;
            if (rows > 0 && str.endsWith("\n")) {
                str = str.substring(0, rows);
                bEndReturn = true;
            }
            textArea.append(str);
            if (vScrollBar == null || !vScrollBar.isVisible())
                return;
	    rows = textArea.getLineCount();
            if (rows >= Util.getStatusMessagesNumber()) {
                int offset = 1;
                if (rows > 60) {
                    offset = 6;
                    if (rows > 120)
                        offset = 12;
                }
                try {
                    offset = textArea.getLineStartOffset(offset);
                }
                catch(Exception e) { offset = 0; }
                if (offset > 0) {
                    textArea.replaceRange("", 0, offset);
                }
            }
            if (rows > 1)
                SwingUtilities.invokeLater(scrollUpdater);
            return;
        }
        DefaultTableModel model = (DefaultTableModel)m_table.getModel();
        rows = model.getRowCount();
        if (rows >= Util.getStatusMessagesNumber())
            model.removeRow(0);
        String[] aStrLine = {str};
        model.addRow(aStrLine);
    }

    protected void doAction(TableModelEvent e)
    {
        if (e.getType() == TableModelEvent.INSERT)
        {
            int row = m_table.getModel().getRowCount() - 1;
            if (row < 0)
                return;

            //m_table.scrollRectToVisible(rectangle);

            getViewport().invalidate();
            getViewport().validate();
            getVerticalScrollBar().setValue(getVerticalScrollBar().getMaximum());
        }
    }

    public void showBottomLine() {
        getViewport().invalidate();
        getViewport().validate();
        getVerticalScrollBar().setValue(getVerticalScrollBar().getMaximum());

        /*Point pt = getViewport().getViewPosition();
        Rectangle  rect = getBounds();
        Rectangle  rect2 = m_taMessageTool.getBounds();
        if (rect2.height > rect.height) {
            pt.y = rect2.height - rect.height;
            getViewport().setViewPosition(pt);
        }*/
    }

    public void pushupMessages( int scrolled )
    {
	showBottomLine();
/*
	int x = point.x;
	int y = point.y + scrolled;
	point = new Point( x, y );
	this.getViewport().setViewPosition( point );
*/
    }

    public void stateChanged( ChangeEvent e )
    {
        if( e.getSource() == this.getViewport() )
        {
           m_point = this.getViewport().getViewPosition();
        }
    }

    public void moveUp() {
    }

    public void moveDown() {
    }

    public void clear() {
        if (textArea != null) {
            textArea.setText("");
            return;
        }
        DefaultTableModel model = (DefaultTableModel)m_table.getModel();
        while(model.getRowCount() > 0)
        {
            model.removeRow(0);
        }
    }

    public int getRowHeight() {
        FontMetrics metrics;
        if (textArea != null)
           metrics = textArea.getFontMetrics(textArea.getFont());
        else
           metrics = getFontMetrics(m_table.getFont());
        int rowHeight = metrics.getHeight();
        return rowHeight;
    }

    public int getColumnWidth() {
        FontMetrics metrics;
        if (textArea != null)
           metrics = textArea.getFontMetrics(textArea.getFont());
        else
           metrics = getFontMetrics(m_table.getFont());
        int cw = metrics.charWidth('m');
        return cw;
    }

} // class MessageTool


text:
"""Utility functions."""

import enum
import os
from typing import Any, Dict, Optional, Union

import flax
import jax
import jax.numpy as jnp
import numpy as np
from PIL import ExifTags
from PIL import Image

_Array = Union[np.ndarray, jnp.ndarray]

@flax.struct.dataclass
class Pixels:
  """All tensors must have the same num_dims and first n-1 dims must match."""
  pix_x_int: _Array
  pix_y_int: _Array
  lossmult: _Array
  near: _Array
  far: _Array
  cam_idx: _Array
  exposure_idx: Optional[_Array] = None
  exposure_values: Optional[_Array] = None

@flax.struct.dataclass
class Rays:
  """All tensors must have the same num_dims and first n-1 dims must match."""
  origins: _Array
  directions: _Array
  viewdirs: _Array
  radii: _Array
  imageplane: _Array
  lossmult: _Array
  near: _Array
  far: _Array
  cam_idx: _Array
  exposure_idx: Optional[_Array] = None
  exposure_values: Optional[_Array] = None

# Dummy Rays object that can be used to initialize NeRF model.
def dummy_rays(include_exposure_idx: bool = False,
               include_exposure_values: bool = False) -> Rays:
  data_fn = lambda n: jnp.zeros((1, n))
  exposure_kwargs = {}
  if include_exposure_idx:
    exposure_kwargs['exposure_idx'] = data_fn(1).astype(jnp.int32)
  if include_exposure_values:
    exposure_kwargs['exposure_values'] = data_fn(1)
  return Rays(
      origins=data_fn(3),
      directions=data_fn(3),
      viewdirs=data_fn(3),
      radii=data_fn(1),
      imageplane=data_fn(2),
      lossmult=data_fn(1),
      near=data_fn(1),
      far=data_fn(1),
      cam_idx=data_fn(1).astype(jnp.int32),
      **exposure_kwargs)

@flax.struct.dataclass
class Batch:
  """Data batch for NeRF training or testing."""
  rays: Union[Pixels, Rays]
  rgb: Optional[_Array] = None
  disps: Optional[_Array] = None
  normals: Optional[_Array] = None
  alphas: Optional[_Array] = None

class DataSplit(enum.Enum):
  """Dataset split."""
  TRAIN = 'train'
  TEST = 'test'

class BatchingMethod(enum.Enum):
  """Draw rays randomly from a single image or all images, in each batch."""
  ALL_IMAGES = 'all_images'
  SINGLE_IMAGE = 'single_image'

def open_file(pth, mode='r'):
  return open(pth, mode=mode)

def file_exists(pth):
  return os.path.exists(pth)

def listdir(pth):
  return os.listdir(pth)

def isdir(pth):
  return os.path.isdir(pth)

def makedirs(pth):
  if not file_exists(pth):
    os.makedirs(pth)

def shard(xs):
  """Split data into shards for multiple devices along the first dimension."""
  return jax.tree_util.tree_map(
      lambda x: x.reshape((jax.local_device_count(), -1) + x.shape[1:]), xs)

def unshard(x, padding=0):
  """Collect the sharded tensor to the shape before sharding."""
  y = x.reshape([x.shape[0] * x.shape[1]] + list(x.shape[2:]))
  if padding > 0:
    y = y[:-padding]
  return y

def load_img(pth: str) -> np.ndarray:
  """Load an image and cast to float32."""
  with open_file(pth, 'rb') as f:
    image = np.array(Image.open(f), dtype=np.float32)
  return image

def load_exif(pth: str) -> Dict[str, Any]:
  """Load EXIF data for an image."""
  with open_file(pth, 'rb') as f:
    image_pil = Image.open(f)
    exif_pil = image_pil._getexif()  # pylint: disable=protected-access
    if exif_pil is not None:
      exif = {
          ExifTags.TAGS[k]: v for k, v in exif_pil.items() if k in ExifTags.TAGS
      }
    else:
      exif = {}
  return exif

def save_img_u8(img, pth):
  """Save an image (probably RGB) in [0, 1] to disk as a uint8 PNG."""
  with open_file(pth, 'wb') as f:
    Image.fromarray(
        (np.clip(np.nan_to_num(img), 0., 1.) * 255.).astype(np.uint8)).save(
            f, 'PNG')

def save_img_f32(depthmap, pth):
  """Save an image (probably a depthmap) to disk as a float32 TIFF."""
  with open_file(pth, 'wb') as f:
    Image.fromarray(np.nan_to_num(depthmap).astype(np.float32)).save(f, 'TIFF')


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace corsairs.core.worldgen.biomes
{
    public class ShallowWater : Water
    {
        public override int MinHeight
        {
            get
            {
                return 75;
            }
        }

        public override char DebugSymbol
        {
            get { return '.'; }
        }

        public override bool SuitableForPOI
        {
            get
            {
                return true;
            }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace AppUpdater.Utils
{
    public static class Checksum
    {
        public static string Calculate(Stream stream)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            SHA256Managed sha = new SHA256Managed();
            byte[] checksum = sha.ComputeHash(stream);
            StringBuilder sb = new StringBuilder();
            foreach (byte b in checksum)
            {
                sb.Append(b.ToString("X2"));
            }

            return sb.ToString();
        }
    }
}


text:
var io = require('socket.io-client')
, expect = require("chai").expect;
var server = require('../server');
	//,io_server = require('socket.io').listen(3001);

var socketUrl = 'http://localhost:3000';

var options = {
            'reconnection delay' : 0
            , 'reopen delay' : 0
            , 'force new connection' : true
       	 	};
			var socket;
			var util = require('util');

describe('sockets', function(){
	beforeEach(function(){
		teacher = io.connect(socketUrl, options);
		student = io.connect(socketUrl, options);
	})
	afterEach(function(){
		student.disconnect();
		teacher.disconnect();
	})

	it('should connect as a teacher and a new lecture should be created', function(done){

		teacher.on('connect', function(){
			teacher.emit('usertype', 'teacher', 1);
		});
		teacher.on('update',function(array){
			expect(array['students']).to.equal(0)
			done();
		});
	});

	it('should connect as a student on an existing lecture', function(done){
		teacher.on('connect', function(){
			teacher.emit('usertype', 'teacher', 1);
		});
		student.on('connect', function(){
			student.emit('usertype', 'student', 1);
		});
		teacher.once('update', function(array){
			expect(array['students']).to.equal(0)
			teacher.once('update', function(array){
				expect(array['students']).to.equal(1);
				done();
			});
		});
	});

	it('Should update slower-array when student push the slower button', function(done){
			teacher.on('connect', function(){
				teacher.emit('usertype', 'teacher', 2);
			});
			student.on('connect', function(){
				student.emit('usertype', 'student', 2);
				student.emit('slower');
			});
			teacher.once('update', function(){
				teacher.once('update', function(){
					teacher.on('update', function(array){
						expect(array['slower']).to.equal(1);
						done();
					});
				});
			});
	});

	it('Should update slower-array when student push the faster button', function(done){
			teacher.on('connect', function(){
				teacher.emit('usertype', 'teacher', 2);
			});
			student.on('connect', function(){
				student.emit('usertype', 'student', 2);
				student.emit('faster');
			});
			teacher.once('update', function(){
				teacher.once('update', function(){
					teacher.on('update', function(array){
						expect(array['faster']).to.equal(1);
						done();
					});
				});
			});
	});

	it('should update when student log out', function(done){
		teacher.on('connect', function(){
			teacher.emit('usertype', 'teacher', 3);
		});
		student.on('connect', function(){
			student.emit('usertype', 'student', 3);
		});
		teacher.once('update', function(array){
			teacher.once('update', function(array){
				expect(array['students']).to.equal(1);
				student.disconnect();
				teacher.on('update', function(array){
					expect(array['students']).to.equal(0);
					done();
				});
			});
		});
	});

	it('should be possible for a teacher to end a lecture', function(done){
		teacher.on('connect', function(){
			teacher.emit('usertype', 'teacher', 4);
		})
		student.on('connect', function(){
			student.emit('usertype', 'student', 4);
		})
		teacher.emit('endlecture', 4);
		student.on('endlecture', function(){
			done();
		})

	})
	it('should be possible for a teacher to start a task', function(done){
		this.timeout(4000)
		teacher.on('connect', function(){
			teacher.emit('usertype', 'teacher', 1)
		})
		student.on('connect', function(){
			student.emit('usertype', 'student', 1)
		})
		teacher.emit('starttask', 1, 1)
		student.on('starttask', function(task){
			student.emit('studentanswer', true, 1)
		})
		teacher.on('sendtasksummay', function(taskid,correct,wrong, loggedon){
			expect(correct).to.equal(1)
			done();
		})
	})
});


text:
package org.apache.tuscany.sdo.util.metadata.impl;

import commonj.sdo.Type;

import java.util.Collection;
import java.util.List;

import org.apache.tuscany.sdo.impl.DataObjectBase;

import org.apache.tuscany.sdo.util.metadata.JavaMetaData;
import org.apache.tuscany.sdo.util.metadata.MetadataFactory;
import org.apache.tuscany.sdo.util.metadata.SDOMetaDataGroup;
import org.apache.tuscany.sdo.util.metadata.TypeMetaData;
import org.apache.tuscany.sdo.util.metadata.XSDMetaData;

/**
 *
 * An implementation of the model object 'SDO Meta Data Group'.
 *
 *

 * The following features are implemented:
 *

 *
{@link org.apache.tuscany.sdo.util.metadata.impl.SDOMetaDataGroupImpl#getJavaMetaData Java Meta Data}

 *
{@link org.apache.tuscany.sdo.util.metadata.impl.SDOMetaDataGroupImpl#getXsdMetaData Xsd Meta Data}

 *
{@link org.apache.tuscany.sdo.util.metadata.impl.SDOMetaDataGroupImpl#getTypeMetaData Type Meta Data}

 *

 *

 *
 * @generated
 */
public class SDOMetaDataGroupImpl extends DataObjectBase implements SDOMetaDataGroup
{
  /**
   * The feature id for the 'Java Meta Data' containment reference list.
   *
   *
   * @generated
   * @ordered
   */
  public final static int JAVA_META_DATA = 0;

  /**
   * The feature id for the 'Xsd Meta Data' containment reference list.
   *
   *
   * @generated
   * @ordered
   */
  public final static int XSD_META_DATA = 1;

  /**
   * The feature id for the 'Type Meta Data' containment reference list.
   *
   *
   * @generated
   * @ordered
   */
  public final static int TYPE_META_DATA = 2;

  /**
   * This represents the number of properties for this type.
   *
   *
   * @generated
   * @ordered
   */

  public final static int SDO_PROPERTY_COUNT = 3;

  /**
   * The cached value of the '{@link #getJavaMetaData() Java Meta Data}' containment reference list.
   *
   *
   * @see #getJavaMetaData()
   * @generated
   * @ordered
   */

  protected List javaMetaData = null;

  /**
   * The cached value of the '{@link #getXsdMetaData() Xsd Meta Data}' containment reference list.
   *
   *
   * @see #getXsdMetaData()
   * @generated
   * @ordered
   */

  protected List xsdMetaData = null;

  /**
   * The cached value of the '{@link #getTypeMetaData() Type Meta Data}' containment reference list.
   *
   *
   * @see #getTypeMetaData()
   * @generated
   * @ordered
   */

  protected List typeMetaData = null;

  /**
   *
   *
   * @generated
   */
  protected SDOMetaDataGroupImpl()
  {
    super();
  }

  /**
   *
   *
   * @generated
   */
  public Type getStaticType()
  {
    return ((MetadataFactoryImpl)MetadataFactory.INSTANCE).getSDOMetaDataGroup();
  }

  /**
   *
   *
   * @generated
   */
  public List getJavaMetaData()
  {
    if (javaMetaData == null)
    {
      javaMetaData = createPropertyList(ListKind.CONTAINMENT, JavaMetaData.class, JAVA_META_DATA);
    }
    return javaMetaData;
  }
  /**
   *
   *
   * @generated
   */
  public List getXsdMetaData()
  {
    if (xsdMetaData == null)
    {
      xsdMetaData = createPropertyList(ListKind.CONTAINMENT, XSDMetaData.class, XSD_META_DATA);
    }
    return xsdMetaData;
  }
  /**
   *
   *
   * @generated
   */
  public List getTypeMetaData()
  {
    if (typeMetaData == null)
    {
      typeMetaData = createPropertyList(ListKind.CONTAINMENT, TypeMetaData.class, TYPE_META_DATA);
    }
    return typeMetaData;
  }
  /**
   *
   *
   * @generated
   */
  public ChangeContext inverseRemove(Object otherEnd, int propertyIndex, ChangeContext changeContext)
  {
    switch (propertyIndex)
    {
      case JAVA_META_DATA:
        return removeFromList(getJavaMetaData(), otherEnd, changeContext);
      case XSD_META_DATA:
        return removeFromList(getXsdMetaData(), otherEnd, changeContext);
      case TYPE_META_DATA:
        return removeFromList(getTypeMetaData(), otherEnd, changeContext);
    }
    return super.inverseRemove(otherEnd, propertyIndex, changeContext);
  }

  /**
   *
   *
   * @generated
   */
  public Object get(int propertyIndex, boolean resolve)
  {
    switch (propertyIndex)
    {
      case JAVA_META_DATA:
        return getJavaMetaData();
      case XSD_META_DATA:
        return getXsdMetaData();
      case TYPE_META_DATA:
        return getTypeMetaData();
    }
    return super.get(propertyIndex, resolve);
  }

  /**
   *
   *
   * @generated
   */
  public void set(int propertyIndex, Object newValue)
  {
    switch (propertyIndex)
    {
      case JAVA_META_DATA:
        getJavaMetaData().clear();
        getJavaMetaData().addAll((Collection)newValue);
        return;
      case XSD_META_DATA:
        getXsdMetaData().clear();
        getXsdMetaData().addAll((Collection)newValue);
        return;
      case TYPE_META_DATA:
        getTypeMetaData().clear();
        getTypeMetaData().addAll((Collection)newValue);
        return;
    }
    super.set(propertyIndex, newValue);
  }

  /**
   *
   *
   * @generated
   */
  public void unset(int propertyIndex)
  {
    switch (propertyIndex)
    {
      case JAVA_META_DATA:
        getJavaMetaData().clear();
        return;
      case XSD_META_DATA:
        getXsdMetaData().clear();
        return;
      case TYPE_META_DATA:
        getTypeMetaData().clear();
        return;
    }
    super.unset(propertyIndex);
  }

  /**
   *
   *
   * @generated
   */
  public boolean isSet(int propertyIndex)
  {
    switch (propertyIndex)
    {
      case JAVA_META_DATA:
        return javaMetaData != null && !javaMetaData.isEmpty();
      case XSD_META_DATA:
        return xsdMetaData != null && !xsdMetaData.isEmpty();
      case TYPE_META_DATA:
        return typeMetaData != null && !typeMetaData.isEmpty();
    }
    return super.isSet(propertyIndex);
  }

} //SDOMetaDataGroupImpl


text:
/**************************************************************************//**
 * @file     cmsis_compiler.h
 * @brief    CMSIS compiler generic header file
 * @version  V5.0.2
 * @date     13. February 2017
 ******************************************************************************/
/*
 * Copyright (c) 2009-2017 ARM Limited. All rights reserved.
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * 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
 *
 * 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.
 */

#ifndef __CMSIS_COMPILER_H
#define __CMSIS_COMPILER_H

#include <stdint.h>

/*
 * ARM Compiler 4/5
 */
#if   defined ( __CC_ARM )
  #include "cmsis_armcc.h"

/*
 * ARM Compiler 6 (armclang)
 */
#elif defined (__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)
  #include "cmsis_armclang.h"

/*
 * GNU Compiler
 */
#elif defined ( __GNUC__ )
  #include "cmsis_gcc.h"

/*
 * IAR Compiler
 */
#elif defined ( __ICCARM__ )

  #ifndef   __ASM
    #define __ASM                                  __asm
  #endif
  #ifndef   __INLINE
    #define __INLINE                               inline
  #endif
  #ifndef   __STATIC_INLINE
    #define __STATIC_INLINE                        static inline
  #endif

  #include <cmsis_iar.h>

  /* CMSIS compiler control architecture macros */
  #if (__CORE__ == __ARM6M__) || (__CORE__ == __ARM6SM__)
    #ifndef __ARM_ARCH_6M__
      #define __ARM_ARCH_6M__                      1
    #endif
  #elif (__CORE__ == __ARM7M__)
    #ifndef __ARM_ARCH_7M__
      #define __ARM_ARCH_7M__                      1
    #endif
  #elif (__CORE__ == __ARM7EM__)
    #ifndef __ARM_ARCH_7EM__
      #define __ARM_ARCH_7EM__                     1
    #endif
  #elif (__CORE__ == __ARM8M_BASELINE__)
    #ifndef __ARM_ARCH_8M_BASE__
      #define __ARM_ARCH_8M_BASE__                 1
    #endif
  #elif (__CORE__ == __ARM8M_MAINLINE__)
    #ifndef __ARM_ARCH_8M_MAIN__
      #define __ARM_ARCH_8M_MAIN__                 1
    #endif
  #endif

  // IAR version 7.8.1 and earlier do not include __ALIGNED
  #ifndef __ALIGNED
  #define __ALIGNED(x) __attribute__((aligned(x)))
  #endif

  #ifndef   __NO_RETURN
    #define __NO_RETURN                            __noreturn
  #endif
  #ifndef   __USED
    #define __USED                                 __root
  #endif
  #ifndef   __WEAK
    #define __WEAK                                 __weak
  #endif
  #ifndef   __PACKED
    #define __PACKED                               __packed
  #endif
  #ifndef   __PACKED_STRUCT
    #define __PACKED_STRUCT                        __packed struct
  #endif
  #ifndef   __UNALIGNED_UINT32        /* deprecated */
    __packed struct T_UINT32 { uint32_t v; };
    #define __UNALIGNED_UINT32(x)                  (((struct T_UINT32 *)(x))->v)
  #endif
  #ifndef   __UNALIGNED_UINT16_WRITE
    __PACKED_STRUCT T_UINT16_WRITE { uint16_t v; };
    #define __UNALIGNED_UINT16_WRITE(addr, val)    (void)((((struct T_UINT16_WRITE *)(void *)(addr))->v) = (val))
  #endif
  #ifndef   __UNALIGNED_UINT16_READ
    __PACKED_STRUCT T_UINT16_READ { uint16_t v; };
    #define __UNALIGNED_UINT16_READ(addr)          (((const struct T_UINT16_READ *)(const void *)(addr))->v)
  #endif
  #ifndef   __UNALIGNED_UINT32_WRITE
    __PACKED_STRUCT T_UINT32_WRITE { uint32_t v; };
    #define __UNALIGNED_UINT32_WRITE(addr, val)    (void)((((struct T_UINT32_WRITE *)(void *)(addr))->v) = (val))
  #endif
  #ifndef   __UNALIGNED_UINT32_READ
    __PACKED_STRUCT T_UINT32_READ { uint32_t v; };
    #define __UNALIGNED_UINT32_READ(addr)          (((const struct T_UINT32_READ *)(const void *)(addr))->v)
  #endif
  #ifndef   __ALIGNED
    #warning No compiler specific solution for __ALIGNED. __ALIGNED is ignored.
    #define __ALIGNED(x)
  #endif

/*
 * TI ARM Compiler
 */
#elif defined ( __TI_ARM__ )
  #include <cmsis_ccs.h>

  #ifndef   __ASM
    #define __ASM                                  __asm
  #endif
  #ifndef   __INLINE
    #define __INLINE                               inline
  #endif
  #ifndef   __STATIC_INLINE
    #define __STATIC_INLINE                        static inline
  #endif
  #ifndef   __NO_RETURN
    #define __NO_RETURN                            __attribute__((noreturn))
  #endif
  #ifndef   __USED
    #define __USED                                 __attribute__((used))
  #endif
  #ifndef   __WEAK
    #define __WEAK                                 __attribute__((weak))
  #endif
  #ifndef   __PACKED
    #define __PACKED                               __attribute__((packed))
  #endif
  #ifndef   __PACKED_STRUCT
    #define __PACKED_STRUCT                        struct __attribute__((packed))
  #endif
  #ifndef   __UNALIGNED_UINT32        /* deprecated */
    struct __attribute__((packed)) T_UINT32 { uint32_t v; };
    #define __UNALIGNED_UINT32(x)                  (((struct T_UINT32 *)(x))->v)
  #endif
  #ifndef   __UNALIGNED_UINT16_WRITE
    __PACKED_STRUCT T_UINT16_WRITE { uint16_t v; };
    #define __UNALIGNED_UINT16_WRITE(addr, val)    (void)((((struct T_UINT16_WRITE *)(void*)(addr))->v) = (val))
  #endif
  #ifndef   __UNALIGNED_UINT16_READ
    __PACKED_STRUCT T_UINT16_READ { uint16_t v; };
    #define __UNALIGNED_UINT16_READ(addr)          (((const struct T_UINT16_READ *)(const void *)(addr))->v)
  #endif
  #ifndef   __UNALIGNED_UINT32_WRITE
    __PACKED_STRUCT T_UINT32_WRITE { uint32_t v; };
    #define __UNALIGNED_UINT32_WRITE(addr, val)    (void)((((struct T_UINT32_WRITE *)(void *)(addr))->v) = (val))
  #endif
  #ifndef   __UNALIGNED_UINT32_READ
    __PACKED_STRUCT T_UINT32_READ { uint32_t v; };
    #define __UNALIGNED_UINT32_READ(addr)          (((const struct T_UINT32_READ *)(const void *)(addr))->v)
  #endif
  #ifndef   __ALIGNED
    #define __ALIGNED(x)                           __attribute__((aligned(x)))
  #endif

/*
 * TASKING Compiler
 */
#elif defined ( __TASKING__ )
  /*
   * The CMSIS functions have been implemented as intrinsics in the compiler.
   * Please use "carm -?i" to get an up to date list of all intrinsics,
   * Including the CMSIS ones.
   */

  #ifndef   __ASM
    #define __ASM                                  __asm
  #endif
  #ifndef   __INLINE
    #define __INLINE                               inline
  #endif
  #ifndef   __STATIC_INLINE
    #define __STATIC_INLINE                        static inline
  #endif
  #ifndef   __NO_RETURN
    #define __NO_RETURN                            __attribute__((noreturn))
  #endif
  #ifndef   __USED
    #define __USED                                 __attribute__((used))
  #endif
  #ifndef   __WEAK
    #define __WEAK                                 __attribute__((weak))
  #endif
  #ifndef   __PACKED
    #define __PACKED                               __packed__
  #endif
  #ifndef   __PACKED_STRUCT
    #define __PACKED_STRUCT                        struct __packed__
  #endif
  #ifndef   __UNALIGNED_UINT32        /* deprecated */
    struct __packed__ T_UINT32 { uint32_t v; };
    #define __UNALIGNED_UINT32(x)                  (((struct T_UINT32 *)(x))->v)
  #endif
  #ifndef   __UNALIGNED_UINT16_WRITE
    __PACKED_STRUCT T_UINT16_WRITE { uint16_t v; };
    #define __UNALIGNED_UINT16_WRITE(addr, val)    (void)((((struct T_UINT16_WRITE *)(void *)(addr))->v) = (val))
  #endif
  #ifndef   __UNALIGNED_UINT16_READ
    __PACKED_STRUCT T_UINT16_READ { uint16_t v; };
    #define __UNALIGNED_UINT16_READ(addr)          (((const struct T_UINT16_READ *)(const void *)(addr))->v)
  #endif
  #ifndef   __UNALIGNED_UINT32_WRITE
    __PACKED_STRUCT T_UINT32_WRITE { uint32_t v; };
    #define __UNALIGNED_UINT32_WRITE(addr, val)    (void)((((struct T_UINT32_WRITE *)(void *)(addr))->v) = (val))
  #endif
  #ifndef   __UNALIGNED_UINT32_READ
    __PACKED_STRUCT T_UINT32_READ { uint32_t v; };
    #define __UNALIGNED_UINT32_READ(addr)          (((const struct T_UINT32_READ *)(const void *)(addr))->v)
  #endif
  #ifndef   __ALIGNED
    #define __ALIGNED(x)              __align(x)
  #endif

/*
 * COSMIC Compiler
 */
#elif defined ( __CSMC__ )
   #include <cmsis_csm.h>

 #ifndef   __ASM
    #define __ASM                                  _asm
  #endif
  #ifndef   __INLINE
    #define __INLINE                               inline
  #endif
  #ifndef   __STATIC_INLINE
    #define __STATIC_INLINE                        static inline
  #endif
  #ifndef   __NO_RETURN
    // NO RETURN is automatically detected hence no warning here
    #define __NO_RETURN
  #endif
  #ifndef   __USED
    #warning No compiler specific solution for __USED. __USED is ignored.
    #define __USED
  #endif
  #ifndef   __WEAK
    #define __WEAK                                 __weak
  #endif
  #ifndef   __PACKED
    #define __PACKED                               @packed
  #endif
  #ifndef   __PACKED_STRUCT
    #define __PACKED_STRUCT                        @packed struct
  #endif
  #ifndef   __UNALIGNED_UINT32        /* deprecated */
    @packed struct T_UINT32 { uint32_t v; };
    #define __UNALIGNED_UINT32(x)                  (((struct T_UINT32 *)(x))->v)
  #endif
  #ifndef   __UNALIGNED_UINT16_WRITE
    __PACKED_STRUCT T_UINT16_WRITE { uint16_t v; };
    #define __UNALIGNED_UINT16_WRITE(addr, val)    (void)((((struct T_UINT16_WRITE *)(void *)(addr))->v) = (val))
  #endif
  #ifndef   __UNALIGNED_UINT16_READ
    __PACKED_STRUCT T_UINT16_READ { uint16_t v; };
    #define __UNALIGNED_UINT16_READ(addr)          (((const struct T_UINT16_READ *)(const void *)(addr))->v)
  #endif
  #ifndef   __UNALIGNED_UINT32_WRITE
    __PACKED_STRUCT T_UINT32_WRITE { uint32_t v; };
    #define __UNALIGNED_UINT32_WRITE(addr, val)    (void)((((struct T_UINT32_WRITE *)(void *)(addr))->v) = (val))
  #endif
  #ifndef   __UNALIGNED_UINT32_READ
    __PACKED_STRUCT T_UINT32_READ { uint32_t v; };
    #define __UNALIGNED_UINT32_READ(addr)          (((const struct T_UINT32_READ *)(const void *)(addr))->v)
  #endif
  #ifndef   __ALIGNED
    #warning No compiler specific solution for __ALIGNED. __ALIGNED is ignored.
    #define __ALIGNED(x)
  #endif

#else
  #error Unknown compiler.
#endif

#endif /* __CMSIS_COMPILER_H */


text:
@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (assign, nonatomic, readonly) BOOL isBackground;

@end


text:
<?php

namespace Pogodi\Brain\Presenters;

use Nette\Application\UI\Form;
use Pogodi\CategoryManager;

class CategoryPresenter extends BasePresenter
{

    /**
     * @var CategoryManager @inject
     */
    public $categoryManager;

    public function renderDefault()
    {
        $this->template->categories = $this->categoryManager->getAll();
    }

    public function renderForm($id = NULL)
    {
        $newCategory = TRUE;
        if ($id) {
            /** @var Form $form */
            $form = $this['categoryForm'];
            $category = $this->categoryManager->getById($id);
            $form->setDefaults([
                'category_id' => $category['id'],
                'title' => $category['title'],
            ]);
            $newCategory = FALSE;
        }
        $this->template->newCategory = $newCategory;
    }

    public function createComponentCategoryForm()
    {
        $form = new Form();
        $form->addText("title", "Title: ")
            ->setRequired();
        $form->addSubmit('ok', 'Save');
        $form->addHidden('category_id');
        $form->onSuccess[] = $this->categoryFormSubmitted;
        return $form;
    }

    public function categoryFormSubmitted(Form $form)
    {
        $values = $form->getValues();
        if ($values->category_id) {
            $this->categoryManager->update($values->category_id, $values->title);
            $this->flashMessage('Category was successfully updated.', 'success');
        } else {
            $this->categoryManager->insert($values->title);
            $this->flashMessage('New category was successfully created.', 'success');
        }
        $this->redirect('default');
    }

    public function actionDelete($category_id)
    {
        $this->categoryManager->delete($category_id);
        $this->flashMessage('Category was successfully  deleted.', 'success');
        $this->redirect('default');
    }

}


text:
<!DOCTYPE html>

		<meta charset="UTF-8">
		<link rel="stylesheet" type="text/css" href="page.css">
		<meta name="viewport" content="width=device-width">
		<title>{% block title %}{% endblock %}</title>

	{% block body %}{% endblock %}

Questions or problems? Email {{ constant('EMAIL') }}