text:
import './datasource-entity.scss';

import 'md-color-picker';
import tinycolor from 'tinycolor2';
import $ from 'jquery';
import thingsboardTypes from '../common/types.constant';
import thingsboardDatakeyConfigDialog from './datakey-config-dialog.controller';
import thingsboardTruncate from './truncate.filter';

/* eslint-disable import/no-unresolved, import/default */

import datasourceEntityTemplate from './datasource-entity.tpl.html';
import datakeyConfigDialogTemplate from './datakey-config-dialog.tpl.html';

/* eslint-enable import/no-unresolved, import/default */

/* eslint-disable angular/angularelement */

export default angular.module('thingsboard.directives.datasourceEntity', [thingsboardTruncate, thingsboardTypes, thingsboardDatakeyConfigDialog])
    .directive('tbDatasourceEntity', DatasourceEntity)
    .name;

/*@ngInject*/
function DatasourceEntity($compile, $templateCache, $q, $mdDialog, $window, $document, $mdColorPicker, $mdConstant, types) {

    var linker = function (scope, element, attrs, ngModelCtrl) {
        var template = $templateCache.get(datasourceEntityTemplate);
        element.html(template);

        scope.ngModelCtrl = ngModelCtrl;
        scope.types = types;

        scope.alarmFields = [];
        for (var alarmField in types.alarmFields) {
            scope.alarmFields.push(alarmField);
        }

        scope.selectedTimeseriesDataKey = null;
        scope.timeseriesDataKeySearchText = null;

        scope.selectedAttributeDataKey = null;
        scope.attributeDataKeySearchText = null;

        scope.selectedAlarmDataKey = null;
        scope.alarmDataKeySearchText = null;

        scope.updateValidity = function () {
            if (ngModelCtrl.$viewValue) {
                var value = ngModelCtrl.$viewValue;
                var dataValid = angular.isDefined(value) && value != null;
                ngModelCtrl.$setValidity('entityData', dataValid);
                if (dataValid) {
                    ngModelCtrl.$setValidity('entityAlias',
                        angular.isDefined(value.entityAliasId) &&
                        value.entityAliasId != null);
                    if (scope.optDataKeys) {
                        ngModelCtrl.$setValidity('entityKeys', true);
                    } else {
                        ngModelCtrl.$setValidity('entityKeys',
                            angular.isDefined(value.dataKeys) &&
                            value.dataKeys != null &&
                            value.dataKeys.length > 0);
                    }
                }
            }
        };

        scope.$watch('entityAlias', function () {
            if (ngModelCtrl.$viewValue) {
                if (scope.entityAlias) {
                    ngModelCtrl.$viewValue.entityAliasId = scope.entityAlias.id;
                } else {
                    ngModelCtrl.$viewValue.entityAliasId = null;
                }
                scope.updateValidity();
                scope.selectedEntityAliasChange();
            }
        });

        scope.$watch('timeseriesDataKeys', function () {
            updateDataKeys();
        }, true);

        scope.$watch('attributeDataKeys', function () {
            updateDataKeys();
        }, true);

        scope.$watch('alarmDataKeys', function () {
            updateDataKeys();
        }, true);

        function updateDataKeys() {
            if (ngModelCtrl.$viewValue) {
                var dataKeys = [];
                dataKeys = dataKeys.concat(scope.timeseriesDataKeys);
                dataKeys = dataKeys.concat(scope.attributeDataKeys);
                dataKeys = dataKeys.concat(scope.alarmDataKeys);
                ngModelCtrl.$viewValue.dataKeys = dataKeys;
                scope.updateValidity();
            }
        }

        ngModelCtrl.$render = function () {
            if (ngModelCtrl.$viewValue) {
                var entityAliasId = ngModelCtrl.$viewValue.entityAliasId;
                var entityAliases = scope.aliasController.getEntityAliases();
                if (entityAliases[entityAliasId]) {
                    scope.entityAlias = entityAliases[entityAliasId];
                } else {
                    scope.entityAlias = null;
                }
                var timeseriesDataKeys = [];
                var attributeDataKeys = [];
                var alarmDataKeys = [];
                for (var d in ngModelCtrl.$viewValue.dataKeys) {
                    var dataKey = ngModelCtrl.$viewValue.dataKeys[d];
                    if (dataKey.type === types.dataKeyType.timeseries) {
                        timeseriesDataKeys.push(dataKey);
                    } else if (dataKey.type === types.dataKeyType.attribute) {
                        attributeDataKeys.push(dataKey);
                    } else if (dataKey.type === types.dataKeyType.alarm) {
                        alarmDataKeys.push(dataKey);
                    }
                }
                scope.timeseriesDataKeys = timeseriesDataKeys;
                scope.attributeDataKeys = attributeDataKeys;
                scope.alarmDataKeys = alarmDataKeys;
            }
        };

        scope.textIsNotEmpty = function(text) {
            return (text && text != null && text.length > 0) ? true : false;
        }

        scope.selectedEntityAliasChange = function () {
            if (!scope.timeseriesDataKeySearchText || scope.timeseriesDataKeySearchText === '') {
                scope.timeseriesDataKeySearchText = scope.timeseriesDataKeySearchText === '' ? null : '';
            }
            if (!scope.attributeDataKeySearchText || scope.attributeDataKeySearchText === '') {
                scope.attributeDataKeySearchText = scope.attributeDataKeySearchText === '' ? null : '';
            }
            if (!scope.alarmDataKeySearchText || scope.alarmDataKeySearchText === '') {
                scope.alarmDataKeySearchText = scope.alarmDataKeySearchText === '' ? null : '';
            }
        };

        scope.transformTimeseriesDataKeyChip = function (chip) {
            if (scope.maxDataKeys > 0 && ngModelCtrl.$viewValue.dataKeys.length >= scope.maxDataKeys ) {
                return null;
            } else {
                return scope.generateDataKey({chip: chip, type: types.dataKeyType.timeseries});
            }
        };

        scope.transformAttributeDataKeyChip = function (chip) {
            if (scope.maxDataKeys > 0 && ngModelCtrl.$viewValue.dataKeys.length >= scope.maxDataKeys ) {
                return null;
            } else {
                return scope.generateDataKey({chip: chip, type: types.dataKeyType.attribute});
            }
        };

        scope.transformAlarmDataKeyChip = function (chip) {
            return scope.generateDataKey({chip: chip, type: types.dataKeyType.alarm});
        };

        scope.showColorPicker = function (event, dataKey) {
            $mdColorPicker.show({
                value: dataKey.color,
                defaultValue: '#fff',
                random: tinycolor.random(),
                clickOutsideToClose: false,
                hasBackdrop: false,
                skipHide: true,
                preserveScope: false,

                mdColorAlphaChannel: true,
                mdColorSpectrum: true,
                mdColorSliders: true,
                mdColorGenericPalette: false,
                mdColorMaterialPalette: true,
                mdColorHistory: false,
                mdColorDefaultTab: 2,

                $event: event

            }).then(function (color) {
                dataKey.color = color;
                ngModelCtrl.$setDirty();
            });
        }

        scope.editDataKey = function (event, dataKey, index) {

            $mdDialog.show({
                controller: 'DatakeyConfigDialogController',
                controllerAs: 'vm',
                templateUrl: datakeyConfigDialogTemplate,
                locals: {
                    dataKey: angular.copy(dataKey),
                    dataKeySettingsSchema: scope.datakeySettingsSchema,
                    entityAlias: scope.entityAlias,
                    aliasController: scope.aliasController
                },
                parent: angular.element($document[0].body),
                fullscreen: true,
                targetEvent: event,
                skipHide: true,
                onComplete: function () {
                    var w = angular.element($window);
                    w.triggerHandler('resize');
                }
            }).then(function (dataKey) {
                if (dataKey.type === types.dataKeyType.timeseries) {
                    scope.timeseriesDataKeys[index] = dataKey;
                } else if (dataKey.type === types.dataKeyType.attribute) {
                    scope.attributeDataKeys[index] = dataKey;
                } else if (dataKey.type === types.dataKeyType.alarm) {
                    scope.alarmDataKeys[index] = dataKey;
                }
                ngModelCtrl.$setDirty();
            }, function () {
            });
        };

        scope.dataKeysSearch = function (searchText, type) {
            if (scope.widgetType == types.widgetType.alarm.value) {
                var dataKeys = searchText ? scope.alarmFields.filter(
                    scope.createFilterForDataKey(searchText)) : scope.alarmFields;
                return dataKeys;
            } else {
                if (scope.entityAlias) {
                    var deferred = $q.defer();
                    scope.fetchEntityKeys({entityAliasId: scope.entityAlias.id, query: searchText, type: type})
                        .then(function (dataKeys) {
                            deferred.resolve(dataKeys);
                        }, function (e) {
                            deferred.reject(e);
                        });
                    return deferred.promise;
                } else {
                    return $q.when([]);
                }
            }
        };

        scope.createFilterForDataKey = function (query) {
            var lowercaseQuery = angular.lowercase(query);
            return function filterFn(dataKey) {
                return (angular.lowercase(dataKey).indexOf(lowercaseQuery) === 0);
            };
        };

        scope.createKey = function (event, chipsId) {
            var chipsChild = $(chipsId, element)[0].firstElementChild;
            var el = angular.element(chipsChild);
            var chipBuffer = el.scope().$mdChipsCtrl.getChipBuffer();
            event.preventDefault();
            event.stopPropagation();
            el.scope().$mdChipsCtrl.appendChip(chipBuffer.trim());
            el.scope().$mdChipsCtrl.resetChipBuffer();
        }

        $compile(element.contents())(scope);
    }

    return {
        restrict: "E",
        require: "^ngModel",
        scope: {
            widgetType: '=',
            maxDataKeys: '=',
            optDataKeys: '=',
            aliasController: '=',
            datakeySettingsSchema: '=',
            generateDataKey: '&',
            fetchEntityKeys: '&',
            onCreateEntityAlias: '&'
        },
        link: linker
    };
}

/* eslint-enable angular/angularelement */


text:
package hcn

import (
	"os"
	"testing"

	"github.com/Microsoft/hcsshim"
)

const (
	NatTestNetworkName     string = "GoTestNat"
	NatTestEndpointName    string = "GoTestNatEndpoint"
	OverlayTestNetworkName string = "GoTestOverlay"
	BridgeTestNetworkName  string = "GoTestL2Bridge"
)

func TestMain(m *testing.M) {
	os.Exit(m.Run())
}

func CreateTestNetwork() (*hcsshim.HNSNetwork, error) {
	network := &hcsshim.HNSNetwork{
		Type: "NAT",
		Name: NatTestNetworkName,
		Subnets: []hcsshim.Subnet{
			{
				AddressPrefix:  "192.168.100.0/24",
				GatewayAddress: "192.168.100.1",
			},
		},
	}

	return network.Create()
}

func TestEndpoint(t *testing.T) {

	network, err := CreateTestNetwork()
	if err != nil {
		t.Fatal(err)
	}

	Endpoint := &hcsshim.HNSEndpoint{
		Name: NatTestEndpointName,
	}

	Endpoint, err = network.CreateEndpoint(Endpoint)
	if err != nil {
		t.Fatal(err)
	}

	err = Endpoint.HostAttach(1)
	if err != nil {
		t.Fatal(err)
	}

	err = Endpoint.HostDetach()
	if err != nil {
		t.Fatal(err)
	}

	_, err = Endpoint.Delete()
	if err != nil {
		t.Fatal(err)
	}

	_, err = network.Delete()
	if err != nil {
		t.Fatal(err)
	}
}

func TestEndpointGetAll(t *testing.T) {
	_, err := hcsshim.HNSListEndpointRequest()
	if err != nil {
		t.Fatal(err)
	}
}

func TestEndpointStatsAll(t *testing.T) {
	network, err := CreateTestNetwork()
	if err != nil {
		t.Fatal(err)
	}

	Endpoint := &hcsshim.HNSEndpoint{
		Name: NatTestEndpointName,
	}

	Endpoint, err = network.CreateEndpoint(Endpoint)
	if err != nil {
		t.Fatal(err)
	}

	epList, err := hcsshim.HNSListEndpointRequest()
	if err != nil {
		t.Fatal(err)
	}

	for _, e := range epList {
		_, err := hcsshim.GetHNSEndpointStats(e.Id)
		if err != nil {
			t.Fatal(err)
		}
	}

	_, err = network.Delete()
	if err != nil {
		t.Fatal(err)
	}
}

func TestNetworkGetAll(t *testing.T) {
	_, err := hcsshim.HNSListNetworkRequest("GET", "", "")
	if err != nil {
		t.Fatal(err)
	}
}

func TestNetwork(t *testing.T) {
	network, err := CreateTestNetwork()
	if err != nil {
		t.Fatal(err)
	}
	_, err = network.Delete()
	if err != nil {
		t.Fatal(err)
	}
}

redpajama_set_name: RedPajamaGithub


text:
package Tags::Utils::Preserve;

use strict;
use warnings;

use Class::Utils qw(set_params);
use List::MoreUtils qw(any);
use Readonly;

# Constants.
Readonly::Scalar my $LAST_INDEX => -1;

our $VERSION = 0.12;

# Constructor.
sub new {
	my ($class, @params) = @_;
	my $self = bless {}, $class;

	# Preserved tags.
	$self->{'preserved'} = [];

	# Process params.
	set_params($self, @params);

	# Initialization.
	$self->reset;

	# Object.
	return $self;
}

# Process for begin of tag.
sub begin {
	my ($self, $tag) = @_;

	$self->save_previous;
	if (scalar @{$self->{'preserved'}}
		&& any { $tag eq $_ } @{$self->{'preserved'}}) {

		push @{$self->{'preserved_stack'}}, $tag;
		$self->{'preserved_flag'} = 1;
	}

	# Return preserved flags.
	return wantarray
		? ($self->{'preserved_flag'}, $self->{'prev_preserved_flag'})
		: $self->{'preserved_flag'};
}

# Process for end of tag.
sub end {
	my ($self, $tag) = @_;

	$self->save_previous;
	my $stack = $self->{'preserved_stack'};
	if (scalar @{$stack} && $tag eq $stack->[$LAST_INDEX]) {
		pop @{$stack};
		if (! scalar @{$stack}) {
			$self->{'preserved_flag'} = 0;
		}
	}

	# Return preserved flags.
	return wantarray
		? ($self->{'preserved_flag'}, $self->{'prev_preserved_flag'})
		: $self->{'preserved_flag'};
}

# Get preserved flag.
sub get {
	my $self = shift;

	# Return preserved flags.
	return wantarray
		? ($self->{'preserved_flag'}, $self->{'prev_preserved_flag'})
		: $self->{'preserved_flag'};
}

# Resets.
sub reset {
	my $self = shift;

	# Preserved flag.
	$self->{'preserved_flag'} = 0;

	# Previsous preserved flag.
	$self->{'prev_preserved_flag'} = 0;

	# Preserved tag.
	$self->{'preserved_stack'} = [];

	return;
}

# Save previous stay.
sub save_previous {
	my $self = shift;

	$self->{'prev_preserved_flag'} = $self->{'preserved_flag'};

	return;
}

1;

__END__

=pod

=encoding utf8

=head1 NAME

 Tags::Utils::Preserve - Class to check if content in element is preserved?

=head1 SYNOPSIS

 use Tags::Utils::Preserve;

 my $obj = Tags::Utils::Preserve->new(%params);
 my $preserved_flag = $obj->begin;
 my ($preserver_flag, $prev_preserved_flag) = $obj->begin;
 my $preserved_flag = $obj->end;
 my ($preserved_flag, $prev_preserved_flag) = $obj->end;
 $obj->get;
 $obj->reset;
 $obj->save_previous;

=head1 METHODS

=over 8

=item C<new(%params)>

 Constructor.

=over 8

=item * C<preserved>

 Preserved tags.

=back

=item C<begin()>

 Process for begin of tag.
 Returns preserved flag in scalar context.
 Returns preserved flag and previous preserved flag in array context.

=item C<end()>

 Process for end of tag.
 Returns preserved flag in scalar context.
 Returns preserved flag and previous preserved flag in array context.

=item C<get()>

 Get preserved flag.
 Returns preserved flag in scalar context.
 Returns preserved flag and previous preserved flag in array context.

=item C<reset()>

 Resets.
 Returns undef.

=item C<save_previous()>

 Save previous stay.
 Returns undef.

=back

=head1 ERRORS

 new():
         From Class::Utils::set_params():
                 Unknown parameter '%s'.

=head1 EXAMPLE

 use strict;
 use warnings;

 use Tags::Utils::Preserve;

 # Begin element helper.
 sub begin_helper {
         my ($pr, $tag) = @_;
         print "TAG: $tag ";
         my ($pre, $pre_pre) = $pr->begin($tag);
         print "PRESERVED: $pre PREVIOUS PRESERVED: $pre_pre\n";
 }

 # End element helper.
 sub end_helper {
         my ($pr, $tag) = @_;
         print "ENDTAG: $tag ";
         my ($pre, $pre_pre) = $pr->end($tag);
         print "PRESERVED: $pre PREVIOUS PRESERVED: $pre_pre\n";

 }

 # Object.
 my $pr = Tags::Utils::Preserve->new(
         'preserved' => ['tag']
 );

 # Process.
 begin_helper($pr, 'foo');
 begin_helper($pr, 'tag');
 begin_helper($pr, 'foo');
 end_helper($pr, 'foo');
 end_helper($pr, 'tag');
 end_helper($pr, 'foo');

 # Output:
 # TAG: foo PRESERVED: 0 PREVIOUS PRESERVED: 0
 # TAG: tag PRESERVED: 1 PREVIOUS PRESERVED: 0
 # TAG: foo PRESERVED: 1 PREVIOUS PRESERVED: 1
 # ENDTAG: foo PRESERVED: 1 PREVIOUS PRESERVED: 1
 # ENDTAG: tag PRESERVED: 0 PREVIOUS PRESERVED: 1
 # ENDTAG: foo PRESERVED: 0 PREVIOUS PRESERVED: 0

=head1 DEPENDENCIES

L<Class::Utils>,
L<List::MoreUtils>,
L<Readonly>.

=head1 SEE ALSO

=over

=item L<Task::Tags>

Install the Tags modules.

=back

=head1 REPOSITORY

L<https://github.com/michal-josef-spacek/Tags>

=head1 AUTHOR

Michal Josef Špaček L<mailto:skim@cpan.org>

L<http://skim.cz/>

=head1 LICENSE AND COPYRIGHT

© 2005-2021 Michal Josef Špaček

BSD 2-Clause License

=head1 VERSION

0.12

=cut


text:
package uk.co.real_logic.aeron.samples;

import uk.co.real_logic.aeron.Subscription;
import uk.co.real_logic.aeron.common.BackoffIdleStrategy;
import uk.co.real_logic.aeron.common.IdleStrategy;
import uk.co.real_logic.aeron.common.RateReporter;
import uk.co.real_logic.aeron.common.concurrent.logbuffer.DataHandler;
import uk.co.real_logic.aeron.common.protocol.HeaderFlyweight;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;

import static uk.co.real_logic.aeron.common.CommonContext.ADMIN_DIR_PROP_NAME;
import static uk.co.real_logic.aeron.common.CommonContext.COUNTERS_DIR_PROP_NAME;
import static uk.co.real_logic.aeron.common.CommonContext.DATA_DIR_PROP_NAME;

/**
 * Utility functions for samples
 */
public class SamplesUtil
{
    /**
     * Use shared memory on Linux to avoid contention on the page cache.
     */
    public static void useSharedMemoryOnLinux()
    {
        if ("Linux".equalsIgnoreCase(System.getProperty("os.name")))
        {
            if (null == System.getProperty(ADMIN_DIR_PROP_NAME))
            {
                System.setProperty(ADMIN_DIR_PROP_NAME, "/dev/shm/aeron/conductor");
            }

            if (null == System.getProperty(COUNTERS_DIR_PROP_NAME))
            {
                System.setProperty(COUNTERS_DIR_PROP_NAME, "/dev/shm/aeron/counters");
            }

            if (null == System.getProperty(DATA_DIR_PROP_NAME))
            {
                System.setProperty(DATA_DIR_PROP_NAME, "/dev/shm/aeron/data");
            }
        }
    }

    /**
     * Return a reusable, parameterised event loop that calls a default idler when no messages are received
     *
     * @param limit        passed to {@link Subscription#poll(int)}
     * @param running      indication for loop
     * @return loop function
     */
    public static Consumer<Subscription> subscriberLoop(final int limit, final AtomicBoolean running)
    {
        final IdleStrategy idleStrategy = new BackoffIdleStrategy(
            100, 10, TimeUnit.MICROSECONDS.toNanos(1), TimeUnit.MICROSECONDS.toNanos(100));

        return subscriberLoop(limit, running, idleStrategy);
    }

    /**
     * Return a reusable, parameterized event loop that calls and idler when no messages are received
     *
     * @param limit        passed to {@link Subscription#poll(int)}
     * @param running      indication for loop
     * @param idleStrategy to use for loop
     * @return loop function
     */
    public static Consumer<Subscription> subscriberLoop(
        final int limit, final AtomicBoolean running, final IdleStrategy idleStrategy)
    {
        return
            (subscription) ->
            {
                try
                {
                    while (running.get())
                    {
                        final int fragmentsRead = subscription.poll(limit);
                        idleStrategy.idle(fragmentsRead);
                    }
                }
                catch (final Exception ex)
                {
                    ex.printStackTrace();
                }
            };
    }

    /**
     * Return a reusable, parameterized {@link DataHandler} that prints to stdout
     *
     * @param streamId to show when printing
     * @return subscription data handler function that prints the message contents
     */
    public static DataHandler printStringMessage(final int streamId)
    {
        return (buffer, offset, length, header) ->
        {
            final byte[] data = new byte[length];
            buffer.getBytes(offset, data);

            System.out.println(
                String.format(
                    "message to stream %d from session %x (%d@%d) <<%s>>",
                    streamId, header.sessionId(), length, offset, new String(data)));
        };
    }

    /**
     * Return a reusable, parameteried {@link DataHandler} that calls into a
     * {@link RateReporter}.
     *
     * @param reporter for the rate
     * @return {@link DataHandler} that records the rate information
     */
    public static DataHandler rateReporterHandler(final RateReporter reporter)
    {
        return (buffer, offset, length, header) -> reporter.onMessage(1, length);
    }

    /**
     * Generic error handler that just prints message to stdout.
     *
     * @param channel   for the error
     * @param streamId  for the error
     * @param sessionId for the error, if source
     * @param message   indicating what the error was
     * @param cause     of the error
     */
    public static void printError(
        final String channel,
        final int streamId,
        final int sessionId,
        final String message,
        final HeaderFlyweight cause)
    {
        System.out.println(message);
    }

    /**
     * Print the rates to stdout
     *
     * @param messagesPerSec being reported
     * @param bytesPerSec    being reported
     * @param totalMessages  being reported
     * @param totalBytes     being reported
     */
    public static void printRate(
        final double messagesPerSec,
        final double bytesPerSec,
        final long totalMessages,
        final long totalBytes)
    {
        System.out.println(
            String.format(
                "%.02g msgs/sec, %.02g bytes/sec, totals %d messages %d MB",
                messagesPerSec, bytesPerSec, totalMessages, totalBytes / (1024 * 1024)));
    }

    /**
     * Print the information for a new connection to stdout.
     *
     * @param channel           for the connection
     * @param streamId          for the stream
     * @param sessionId         for the connection publication
     * @param sourceInformation that is transport specific
     */
    public static void printNewConnection(
        final String channel, final int streamId, final int sessionId, final String sourceInformation)
    {
        System.out.println(
            String.format(
                "new connection on %s streamId %d sessionId %x from %s",
                channel, streamId, sessionId, sourceInformation));
    }

    /**
     * Print the information for an inactive connection to stdout.
     *
     * @param channel   for the connection
     * @param streamId  for the stream
     * @param sessionId for the connection publication
     */
    public static void printInactiveConnection(final String channel, final int streamId, final int sessionId)
    {
        System.out.println(
            String.format(
                "inactive connection on %s streamId %d sessionId %x",
                channel, streamId, sessionId));
    }
}


text:
<!-- This file uses Github Flavored Markdown (GFM) format. -->

# Greybus Simulator (gbsim)

A tool which simulates an AP Bridge, SVC, and an arbitrary set
of Ara modules plugged into Greybus.

Provided under BSD license. See *LICENSE* for details.

## Quick Start

This code depends on header files present in the "greybus" source
directory.  The location of this directory is defined in the *GBDIR*
environment variable.

To just build gbsim, do this:
```
export GBDIR=".../path/to/greybus"
./autogen.sh
./configure
make
```

## Install

The easiest path to get started is to run the kernel greybus support and
gbsim on the same machine. This is accomplished using the *dummy_hcd*
USB host+gadget driver in conjuction with the gadget configfs/functionfs
features.

Set the environment variable *GBDIR* to point at the kernel greybus
(https://github.com/gregkh/greybus) directory as the simulator shares
headers with the kernel code.

`export GBDIR=".../path/to/greybus"`

Build the kernel greybus subsystem, including the host driver and
related protocol drivers.
```
cd "${GBDIR}"
make -C /usr/src/linux-headers-foo M=$PWD
make -C /usr/src/linux-headers-foo M=$PWD modules_install
```

Build it:

gbsim has the following dependencies:

* libusbg (https://github.com/libusbg/libusbg)
* libconfig (http://hyperrealm.com/libconfig/libconfig.html)
* libsoc (https://github.com/jackmitch/libsoc)

It also assumes the *GBDIR* environment variable has been set.
```
cd /path/to/gbsim
./autogen.sh
./configure
make
make install
```

If you would like to cross-compile the simulator, you can optionally
specify the prefix used for compilation tools at configure time.
For example:
```
./configure --host=arm-linux-gnueabi
```

If your build environment only supplies the legacy (pre-V2) USB
descriptor format, you can indicate that when configuring as well:
```
./configure --enable-legacy-descriptors
```
(If you get errors about FUNCTIONFS_DESCRIPTORS_MAGIC_V2 not
being defined, you'll need this.)

## Run

Load up the greybus framework and ES1 USB driver:

```
modprobe greybus
modprobe gb-es1
modprobe gb-phy
```

Now start the simulator:

```
modprobe configfs
mount -t configfs none /sys/kernel/config
modprobe libcomposite
modprobe dummy_hcd
gbsim -h /path/to -v
```

Where */path/to* is the base directory containing the
directory *hotplug-modules*

gbsim supports the following option flags:

* -b: enable the BeagleBone Black hardware backend
* -h: hotplug base directory
* -i: i2c adapter (if BBB hardware backend is enabled)
* -v: enable verbose output

### Using the simulator

After running output should appear as follows:

```
[I] GBSIM: gbsim gadget created
[D] GBSIM: event BIND,0
[D] GBSIM: event ENABLE,2
[D] GBSIM: Start SVC/CPort endpoints
[D] GBSIM: SVC->AP handshake sent
[D] GBSIM: event SETUP,4
[D] GBSIM: AP->AP Bridge setup message:
[D] GBSIM:   bRequestType = 41
[D] GBSIM:   bRequest     = 01
[D] GBSIM:   wValue       = 0000
[D] GBSIM:   wIndex       = 0000
[D] GBSIM:   wLength      = 000b
[D] GBSIM: AP->SVC message:
  00 00 03 00 00 01 01 00 00 00 00
[I] GBSIM: AP handshake complete
```

This indicates that the simulated AP Bridge device was enumerated by the host,
a handshake message was sent to the AP, and another handshake message received
from the AP indicating that the handshake process has completed.

At this point, it's possible to hot plug/unplug modules by simply copying or
removing a conformant manifest blob file in the /path/to/hotplug-module
directory. Manifest blob files can be created using the Manifesto tool
found at https://github.com/projectara/manifesto. Using the Simple I2C Module as
an example, a module can be inserted as follows:

`cp /foo/bar/simple-i2c-module.mnfb /path/to/hotplug-module/simple-i2c-module.mnfb`

After module insertion, gbsim will report:

```
[I] GBSIM: simple-i2c-module.mnfb module inserted
[D] GBSIM: SVC->AP hotplug event (plug) sent
```


text:
using System.Threading.Tasks;
using Orleans.Concurrency;

namespace Orleans.MultiCluster
{
    /// <summary>
    /// Grain interface for grains that participate in multi-cluster log-consistency protocols.
    /// </summary>
    public interface ILogConsistencyProtocolParticipant  : IGrain
    {
        /// <summary>
        /// Called immediately before the user-level OnActivateAsync, on same scheduler.
        /// </summary>
        /// <returns></returns>
        Task PreActivateProtocolParticipant();

        /// <summary>
        /// Called immediately after the user-level OnActivateAsync, on same scheduler.
        /// </summary>
        /// <returns></returns>
        Task PostActivateProtocolParticipant();

        /// <summary>
        /// Called immediately after the user-level OnDeactivateAsync, on same scheduler.
        /// </summary>
        /// <returns></returns>
        Task DeactivateProtocolParticipant();
    }

    /// <summary>
    /// interface to mark classes that represent protocol messages.
    /// All such classes must be serializable.
    /// </summary>
    public interface ILogConsistencyProtocolMessage
    {
    }
}


text:
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
import serial

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)

def animate(i):
	pullData = ''
	with open('meusdados.txt', 'r+') as arq:
		with serial.Serial('/dev/ttyACM0',9600,timeout=1) as ser:
			arq.write(ser.readline())
		pullData = arq.read()
	dataArray = pullData.split('\n')
	xar = []
	yar = []
	for eachLine in dataArray:
		if len(eachLine)>1:
			x,y = eachLine.split(',')
			xar.append(int(x))
			yar.append(int(y))
	ax1.plot(xar,yar)
ani = animation.FuncAnimation(fig, animate, interval = 100)
plt.show()


text:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated 15-nov-2016 9:41:01 by Hibernate Tools 5.2.0.Beta1 -->
<hibernate-mapping>
    <class name="clasesHibernate.Usuarioadmin" table="usuarioadmin" catalog="proyectobd" optimistic-lock="version">
        <id name="email" type="string">
            <column name="email" length="25" />
            <generator class="assigned" />
        </id>
        <property name="nombre" type="string">
            <column name="nombre" length="25" not-null="true" />
        </property>
        <property name="apellidos" type="string">
            <column name="apellidos" length="25" not-null="true" />
        </property>
        <property name="password" type="string">
            <column name="password" length="10" not-null="true" />
        </property>
        <property name="direccion" type="string">
            <column name="direccion" length="25" not-null="true" />
        </property>
        <property name="telefono" type="int">
            <column name="telefono" not-null="true" />
        </property>
        <property name="club" type="string">
            <column name="club" length="25" not-null="true" />
        </property>
    </class>
</hibernate-mapping>


text:
function [ outputs ] = AspectRatio( ~, ~, ~, inputs )
%ASPECTRATIO AspectRatio module summary...
%
%   SUMMARY:
%       Determines the aspect ratio of the flake in the img.
%
%   INPUTS:
%       filledFlake - The filled cross-section of the cropped flake.
%
%   OUTPUTS:
%       1: Estimated aspect ratio
%

% Declare outputs
numOutputs = 1;
outputs = cell(1,numOutputs);

% Read inputs
filledFlake = inputs{1};

% Compute aspect ratio
stats = regionprops(filledFlake, 'MinorAxisLength', 'MajorAxisLength');
if length(stats) > 1
    % Erroneous edges detected, pick the best (i.e. biggest) edge...
    allSizes = [stats.MajorAxisLength];
    whichBound = find( allSizes == max(allSizes), 1, 'first' );
    stats = stats(whichBound);
end
asprat = stats.MinorAxisLength / stats.MajorAxisLength;

% Write outputs
outputs{1} = asprat;
% Clear all variables except outputs
clearvars -except outputs

end % Function end


text:
#include <aws/ec2/model/NetworkInterfaceType.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace EC2
  {
    namespace Model
    {
      namespace NetworkInterfaceTypeMapper
      {

        static const int interface_HASH = HashingUtils::HashString("interface");
        static const int natGateway_HASH = HashingUtils::HashString("natGateway");
        static const int efa_HASH = HashingUtils::HashString("efa");

        NetworkInterfaceType GetNetworkInterfaceTypeForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == interface_HASH)
          {
            return NetworkInterfaceType::interface;
          }
          else if (hashCode == natGateway_HASH)
          {
            return NetworkInterfaceType::natGateway;
          }
          else if (hashCode == efa_HASH)
          {
            return NetworkInterfaceType::efa;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<NetworkInterfaceType>(hashCode);
          }

          return NetworkInterfaceType::NOT_SET;
        }

        Aws::String GetNameForNetworkInterfaceType(NetworkInterfaceType enumValue)
        {
          switch(enumValue)
          {
          case NetworkInterfaceType::interface:
            return "interface";
          case NetworkInterfaceType::natGateway:
            return "natGateway";
          case NetworkInterfaceType::efa:
            return "efa";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return {};
          }
        }

      } // namespace NetworkInterfaceTypeMapper
    } // namespace Model
  } // namespace EC2
} // namespace Aws


text:
package bitswap

import (
	"context"
	"time"

	tn "github.com/ipfs/go-ipfs/exchange/bitswap/testnet"
	datastore2 "github.com/ipfs/go-ipfs/thirdparty/datastore2"

	ds "gx/ipfs/QmPpegoMqhAEqjncrzArm7KVWAkCm78rqL2DPuNjhPrshg/go-datastore"
	ds_sync "gx/ipfs/QmPpegoMqhAEqjncrzArm7KVWAkCm78rqL2DPuNjhPrshg/go-datastore/sync"
	delay "gx/ipfs/QmRJVNatYJwTAHgdSM1Xef9QVQ1Ch3XHdmcrykjP5Y4soL/go-ipfs-delay"
	blockstore "gx/ipfs/QmTVDM4LCSUMFNQzbDLL9zQwp8usE6QHymFdh3h8vL9v6b/go-ipfs-blockstore"
	testutil "gx/ipfs/QmVvkK7s5imCiq3JVbL3pGfnhcCnf3LrFJPF4GE2sAoGZf/go-testutil"
	p2ptestutil "gx/ipfs/QmYVR3C8DWPHdHxvLtNFYfjsXgaRAdh6hPMNH3KiwCgu4o/go-libp2p-netutil"
	peer "gx/ipfs/QmZoWKhxUmZ2seW4BzX6fJkNR8hh9PsGModr7q171yq2SS/go-libp2p-peer"
)

// WARNING: this uses RandTestBogusIdentity DO NOT USE for NON TESTS!
func NewTestSessionGenerator(
	net tn.Network) SessionGenerator {
	ctx, cancel := context.WithCancel(context.Background())
	return SessionGenerator{
		net:    net,
		seq:    0,
		ctx:    ctx, // TODO take ctx as param to Next, Instances
		cancel: cancel,
	}
}

// TODO move this SessionGenerator to the core package and export it as the core generator
type SessionGenerator struct {
	seq    int
	net    tn.Network
	ctx    context.Context
	cancel context.CancelFunc
}

func (g *SessionGenerator) Close() error {
	g.cancel()
	return nil // for Closer interface
}

func (g *SessionGenerator) Next() Instance {
	g.seq++
	p, err := p2ptestutil.RandTestBogusIdentity()
	if err != nil {
		panic("FIXME") // TODO change signature
	}
	return MkSession(g.ctx, g.net, p)
}

func (g *SessionGenerator) Instances(n int) []Instance {
	var instances []Instance
	for j := 0; j < n; j++ {
		inst := g.Next()
		instances = append(instances, inst)
	}
	for i, inst := range instances {
		for j := i + 1; j < len(instances); j++ {
			oinst := instances[j]
			inst.Exchange.network.ConnectTo(context.Background(), oinst.Peer)
		}
	}
	return instances
}

type Instance struct {
	Peer       peer.ID
	Exchange   *Bitswap
	blockstore blockstore.Blockstore

	blockstoreDelay delay.D
}

func (i *Instance) Blockstore() blockstore.Blockstore {
	return i.blockstore
}

func (i *Instance) SetBlockstoreLatency(t time.Duration) time.Duration {
	return i.blockstoreDelay.Set(t)
}

// session creates a test bitswap session.
//
// NB: It's easy make mistakes by providing the same peer ID to two different
// sessions. To safeguard, use the SessionGenerator to generate sessions. It's
// just a much better idea.
func MkSession(ctx context.Context, net tn.Network, p testutil.Identity) Instance {
	bsdelay := delay.Fixed(0)

	adapter := net.Adapter(p)
	dstore := ds_sync.MutexWrap(datastore2.WithDelay(ds.NewMapDatastore(), bsdelay))

	bstore, err := blockstore.CachedBlockstore(ctx,
		blockstore.NewBlockstore(ds_sync.MutexWrap(dstore)),
		blockstore.DefaultCacheOpts())
	if err != nil {
		panic(err.Error()) // FIXME perhaps change signature and return error.
	}

	const alwaysSendToPeer = true

	bs := New(ctx, p.ID(), adapter, bstore, alwaysSendToPeer).(*Bitswap)

	return Instance{
		Peer:            p.ID(),
		Exchange:        bs,
		blockstore:      bstore,
		blockstoreDelay: bsdelay,
	}
}


text:
#include <stdio.h>
#include <sys/queue.h>
#include <stdlib.h>
#include <time.h>

/*
 * Test set multiplier.
 */
#define MULTIPLIER 100000

typedef struct slist_item_s {
  void *value;
  int id;
  SLIST_ENTRY(slist_item_s) entries;
} Slist_item;

SLIST_HEAD(slist_s, slist_item_s);
typedef struct slist_s Slist;

static long get_cpu_time(void)
{
  struct timespec time;
  if (clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time) < 0)
  {
    fprintf(stderr, "Failed to get CPU time!\n");
    exit(1);
  }
  return time.tv_nsec;
}

int main(int argc, char **argv)
{
  long start_time = 0;
  long sum_time = 0;
  Slist slist;
  Slist_item *item;
  SLIST_INIT(&slist);

  printf("malloc | Allocate singly-linked list sequentially: ");
  {
    sum_time = 0;
    for (int i = 0; i < MULTIPLIER; i++)
    {
      start_time = get_cpu_time();
      item = malloc(sizeof(Slist_item));
      SLIST_INSERT_HEAD(&slist, item, entries);
      sum_time += get_cpu_time() - start_time;
    }
  }
  printf("%ld\n", sum_time);

  printf("malloc | Free singly-linked list allocated sequentially: ");
  {
    sum_time = 0;
    while (!SLIST_EMPTY(&slist))
    {
      start_time = get_cpu_time();
      item = SLIST_FIRST(&slist);
      free(item);
      SLIST_REMOVE_HEAD(&slist, entries);
      sum_time += get_cpu_time() - start_time;
    }
  }
  printf("%ld\n", sum_time);

  printf("malloc | Allocate singly-linked list non-sequentially: ");
  {
    Slist slist2;
    Slist_item *to_delete = NULL;
    SLIST_INIT(&slist2);
    int base_shard_size = sizeof(char);
    int max_shard_multiplier = 20;
    sum_time = 0;
    for (int i = 0; i < MULTIPLIER; i++)
    {
      item = malloc(sizeof(Slist_item));
      item->value = malloc(base_shard_size * (i % max_shard_multiplier) + 1);
      item->id = i;
      SLIST_INSERT_HEAD(&slist2, item, entries);
    }
    // Iteratively remove every third element. We can't remove element we're
    // inspecting, so free is invoked only on past elements.
    SLIST_FOREACH(item, &slist2, entries)
    {
      if (to_delete != NULL)
      {
        SLIST_REMOVE(&slist2, to_delete, slist_item_s, entries);
        free(to_delete->value);
        free(to_delete);
        to_delete = NULL;
      }
      if (item->id % 3 == 0)
      {
        to_delete = item;
      }
    }
    if (to_delete != NULL)
    {
      SLIST_REMOVE(&slist2, to_delete, slist_item_s, entries);
      free(to_delete->value);
      free(to_delete);
    }

    for (int i = 0; i < MULTIPLIER; i++)
    {
      start_time = get_cpu_time();
      item = malloc(sizeof(Slist_item));
      SLIST_INSERT_HEAD(&slist, item, entries);
      sum_time += get_cpu_time() - start_time;
    }

    // Get rid of temporary sequentially allocated list with holes
    while (!SLIST_EMPTY(&slist2))
    {
      item = SLIST_FIRST(&slist2);
      free(item->value);
      free(item);
      SLIST_REMOVE_HEAD(&slist2, entries);
    }
  }
  printf("%ld\n", sum_time);

  printf("malloc | Free singly-linked list allocated non-sequentially: ");
  {
    sum_time = 0;
    while (!SLIST_EMPTY(&slist))
    {
      start_time = get_cpu_time();
      item = SLIST_FIRST(&slist);
      free(item);
      SLIST_REMOVE_HEAD(&slist, entries);
      sum_time += get_cpu_time() - start_time;
    }
  }
  printf("%ld\n", sum_time);

  return 0;
}


text:
using System;
using System.Web;
using System.Web.Configuration;
using System.Web.SessionState;
using JayBird.Classes;
using JayBirdClassLibrary.Database;
using JayBirdClassLibrary.Tables;
using JayBirdClassLibrary.Wrappers;
using Newtonsoft.Json;

namespace JayBird.Services
{
    /// <summary>
    /// Summary description for LookupTableService
    /// </summary>
    public class LookupTableService : IHttpHandler, IReadOnlySessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            LookupTableWrapper wrapper;
            string wrapperJson;
            string action = context.Request.Params[AppConstants.SERVICE_ACTION];
            DatabaseConnection dbCon = new DatabaseConnection(WebConfigurationManager.AppSettings[AppConstants.SQL_CONNECTION_STRING]);

            try
            {
                switch (action)
                {
                    case AppConstants.SERVICE_ACTION_LOAD:

                        wrapper = new LookupTableWrapper();
                        wrapper.Load(dbCon);

                        wrapperJson = JsonConvert.SerializeObject(wrapper);

                        context.Response.ContentType = AppConstants.CONTENT_TYPE_APP_JSON;
                        context.Response.Write(wrapperJson);

                        break;

                    case AppConstants.SERVICE_ACTION_SAVE:

                        User sessionUser = WebHelper.GetSessionUser(HttpContext.Current);

                        wrapperJson = new System.IO.StreamReader(context.Request.InputStream).ReadToEnd();

                        wrapper = JsonConvert.DeserializeObject<LookupTableWrapper>(wrapperJson);

                        wrapper.Save(dbCon, sessionUser.UserID);

                        context.Response.ContentType = AppConstants.CONTENT_TYPE_TEXT_PLAIN;
                        context.Response.Write("Lookup table data saved successfully.");

                        break;
                }
            }
            catch (Exception ex)
            {
                context.Response.StatusCode = 500;
                context.Response.ContentType = AppConstants.CONTENT_TYPE_TEXT_PLAIN;
                context.Response.Write("[LookupTableService.ashx] " + ex.Message);

                //TODO: Log the error to the database here
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}


text:
package com.ThirtyNineEighty.Base.Renderable.Shaders;

import android.opengl.GLES20;

public class ShaderParticles
  extends Shader
{
  public int attributeDirectionVectorHandle;
  public int attributeStartTimeHandle;

  public int uniformLifeTimeHandle;
  public int uniformMatrixHandle;
  public int uniformTextureHandle;
  public int uniformPointSize;
  public int uniformStartColor;
  public int uniformEndColor;

  @Override
  public void compile()
  {
    compile("Shaders/Particles.vert", "Shaders/Particles.frag");
  }

  @Override
  protected void getLocations()
  {
    attributeDirectionVectorHandle = GLES20.glGetAttribLocation(programHandle, "a_directionVector");
    attributeStartTimeHandle       = GLES20.glGetAttribLocation(programHandle, "a_startTime");

    uniformLifeTimeHandle          = GLES20.glGetUniformLocation(programHandle, "u_lifeTime");
    uniformMatrixHandle            = GLES20.glGetUniformLocation(programHandle, "u_matrix");
    uniformTextureHandle           = GLES20.glGetUniformLocation(programHandle, "u_texture");
    uniformPointSize               = GLES20.glGetUniformLocation(programHandle, "u_pointSize");
    uniformStartColor              = GLES20.glGetUniformLocation(programHandle, "u_startColor");
    uniformEndColor                = GLES20.glGetUniformLocation(programHandle, "u_endColor");
  }
}


text:
require "mongoid/spec_helper"
mongoid_field = (defined?(Mongoid::Field)) ? Mongoid::Field : Mongoid::Fields

describe mongoid_field do
  extend FieldHelper
  configure!

  describe "Point conversions" do
    it "should work with point object has #lat and #lng methods" do
      address.location = point.to_lng_lat
      address.location.should == [-44, 72]
    end

    it 'should work with point object that has location attribute' do
      address.location = location.to_lng_lat
      address.location.should == [-44, 72]
    end

    it 'should work with point object that has position attribute add should add #lat and #lng methods' do
      address.location = position.to_lng_lat
      address.location.should == [-44, 72]
    end

    it 'should work with point object that has position attribute and should add #latitude and #longitude methods' do
      address.pos = position.to_lng_lat
      address.pos.should == [-44, 72]
    end

    it 'should work with point object that has #latitude and #longitude methods' do
      address.location = other_point.to_lng_lat
      address.location.should == [-44, 72]
    end
  end
end


text:
Tuning the Liberty Profile in the Cloud
========================================

## Tuning the JVM
Tuning the JVM is the most important tuning step whether you configure a development or production environment. To tune the JVM for the Liberty profile:
1. Create a jvm.options file in your server directory.
2. In the jvm.options file, specify each of the JVM arguments that you want to use, one option per line. For example:
```
-Xms50m
-Xmx256m
```

## Tip
* For a development environment, you can tune the heap size for a faster server startup. To do this, set the minimum heap size to a small value, and the maximum heap size to whatever value is needed for your application.
* For a production environment, you can tune the heap size for the best performance by avoiding heap expansion and contraction. To do this, set the minimum heap size and maximum heap size to the same value.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>PoolableConnection</title>
<meta name="date" content="2015-03-06">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.jetel.component.fileoperation.pool

Interface PoolableConnection

All Superinterfaces:

java.lang.AutoCloseable, java.io.Closeable

All Known Implementing Classes:

AbstractPoolableConnection, PooledFTPConnection, PooledSFTPConnection

public interface PoolableConnection
extends java.io.Closeable

Method Summary

Methods

Modifier and Type
Method and Description

Authority
getAuthority()

boolean
isBorrowed()

Returns true if the object is borrowed.

boolean
isOpen()

void
reset()

Resets the state of the object,
 as if it were newly created.

boolean
returnToPool()

Returns the object to the pool.

boolean
setBorrowed(boolean borrowed)

Sets the borrowed state of a connection and returns the previous state.

Methods inherited from interface java.io.Closeable

close

Method Detail

isOpen

boolean isOpen()

getAuthority

Authority getAuthority()

reset

void reset()

Resets the state of the object,
 as if it were newly created.

setBorrowed

boolean setBorrowed(boolean borrowed)

Sets the borrowed state of a connection and returns the previous state.
 This method should only be called by the ConnectionPool.

 It is not a part of the public interface.

isBorrowed

boolean isBorrowed()

Returns true if the object is borrowed.

Returns:

returnToPool

boolean returnToPool()

Returns the object to the pool.

 Returns false if an exception occurs,
 otherwise returns true.

 Whenever the object is borrowed or returned, #setBorrowed()
 is called automatically.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

				<address>Copyright © 2002-2015 Javlin a.s.</address>


text:
FROM ubuntu:14.04
MAINTAINER Steffen Roegner "steffen.roegner@gmail.com"
USER root

ENV REFRESHED_AT 2015-08-14

ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update
RUN locale-gen en_US en_US.UTF-8
ENV LANG en_US.UTF-8
RUN echo "export PS1='\e[1;31m\]\u@\h:\w\\$\[\e[0m\] '" >> /root/.bashrc

RUN apt-get install -y curl default-jre libwebkitgtk-1.0-0 lame xterm

RUN curl --fail --silent -L http://www.xmind.net/xmind/downloads/xmind-7-update1-linux_amd64.deb -o /tmp/xmind.deb && \
    dpkg -i /tmp/xmind.deb

ENV DISPLAY :0
CMD ["/usr/bin/XMind"]


text:
class Dataset < ApplicationRecord
  has_many :dataset_items, dependent: :destroy
  accepts_nested_attributes_for :dataset_items, allow_destroy: true

  validates :environment,     presence: true,
                              length: { maximum: 160 }
  validates :reference,       presence: true,
                              length: { maximum: 500 }
  validates :url,             presence: true,
                              length: { maximum: 200 }
  validates :project_website, presence: true,
                              length: { maximum: 200 }
end


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

namespace ASCIIMazeCS
{
    public class MusicThread
    {
        Thread mthread;

        public MusicThread()
        {
            updateMusic();
        }

        public void updateMusic()
        {
            switch (GameLib.curState)
            {
                case GameLib.GameState.Battle:
                    if (mthread != null)
                    {
                        stopMusic();
                    }
                    mthread = new Thread(new ThreadStart(playBattleTheme));
                    startMusic();
                    break;
                case GameLib.GameState.Game_Adv:
                case GameLib.GameState.Game_Sth:
                case GameLib.GameState.Game_Sur:
                    if (mthread != null)
                    {
                        stopMusic();
                    }
                    mthread = new Thread(new ThreadStart(playMainTheme));
                    startMusic();
                    break;
                case GameLib.GameState.GameOver:
                    if (mthread != null)
                    {
                        stopMusic();
                    }
                    mthread = new Thread(new ThreadStart(playGameOverTheme));
                    startMusic();
                    break;
                case GameLib.GameState.Menu:
                case GameLib.GameState.ClassChooser:
                case GameLib.GameState.Options:
                    if (mthread != null)
                    {
                        stopMusic();
                    }
                    mthread = new Thread(new ThreadStart(playMenuTheme));
                    startMusic();
                    break;
            }
        }

        private void playBattleTheme()
        {
            while (true)
            {
                Console.Beep((int)GameLib.Tone.Fsharp, (int)GameLib.Duration.EIGHTH);
                Console.Beep((int)GameLib.Tone.Fsharp, (int)GameLib.Duration.EIGHTH);
                Console.Beep((int)GameLib.Tone.A, (int)GameLib.Duration.EIGHTH);
                Console.Beep((int)GameLib.Tone.B, (int)GameLib.Duration.EIGHTH);
                Console.Beep((int)GameLib.Tone.A, (int)GameLib.Duration.EIGHTH);
                Console.Beep((int)GameLib.Tone.D, (int)GameLib.Duration.EIGHTH);
                Console.Beep((int)GameLib.Tone.Fsharp, (int)GameLib.Duration.EIGHTH);
                Console.Beep((int)GameLib.Tone.D, (int)GameLib.Duration.EIGHTH);
            }
        }

        private void playMenuTheme()
        {
            while (true)
            {
                Console.Beep((int)GameLib.Tone.Dsharp, (int)GameLib.Duration.QUARTER);
                Console.Beep((int)GameLib.Tone.E, (int)GameLib.Duration.QUARTER);
                Console.Beep((int)GameLib.Tone.A, (int)GameLib.Duration.QUARTER);
                Console.Beep((int)GameLib.Tone.G, (int)GameLib.Duration.QUARTER);
            }
        }

        private void playGameOverTheme()
        {
            while (true)
            {

            }
        }

        private void playMainTheme()
        {
            while (true)
            {
                Console.Beep((int)GameLib.Tone.C, (int)GameLib.Duration.HALF);
                Console.Beep((int)GameLib.Tone.Asharp, (int)GameLib.Duration.QUARTER);
                Console.Beep((int)GameLib.Tone.F, (int)GameLib.Duration.HALF);
                Console.Beep((int)GameLib.Tone.G, (int)GameLib.Duration.QUARTER);

                Console.Beep((int)GameLib.Tone.G, (int)GameLib.Duration.HALF);
                Console.Beep((int)GameLib.Tone.E, (int)GameLib.Duration.QUARTER);
                Console.Beep((int)GameLib.Tone.C, (int)GameLib.Duration.HALF);
                Console.Beep((int)GameLib.Tone.D, (int)GameLib.Duration.HALF);
            }
        }

        public void startMusic()
        {
            mthread.Start();
            while (!mthread.IsAlive) ;
        }

        public void stopMusic()
        {
            mthread.Abort();
            mthread.Join();
        }
    }
}


text:
import React from 'react'
import {
  getPackage,
} from './utils'

import {Progress} from './styled'

import {DefinitionRenderer} from './components'

export function BaseInserter ({
  //onItemSelect,
  conversation,
  conversation_part,
  pkg,
  app,
  onInitialize,
  location
}) {
  const [p, setPackage] = React.useState(null)
  const params = {
    appKey: app.key,
    id: pkg.name + '',
    hooKind: 'configure',
    ctx: {
      location,
      conversation_part: conversation_part?.key
    }
  }

  React.useEffect(() => {
    if (p && (p.kind === 'initialize')) {
      onInitialize({
        hooKind: p.kind,
        definitions: p.definitions,
        values: p.values,
        wait_for_input: p.wait_for_input,
        id: pkg.id,
        name: pkg.name
      })
    }
  }, [p])

  React.useEffect(() => getPackage(params, location, (data) => {
    setPackage(data.app.appPackage.callHook)
  }), [])

  function updatePackage (formData, cb) {
    const newParams = { ...params, ctx: {
      ...formData,
        conversation_key: conversation?.key,
        conversation_part: conversation_part?.key
      }
    }
    getPackage(newParams, location, (data) => {
      setPackage(data.app.appPackage.callHook)
      cb && cb()
    })
  }

  return (
    <div>
      {
        !p && <Progress/>
      }
      {p && <DefinitionRenderer
        location={location}
        schema={p.definitions}
        getPackage={getPackage}
        appPackage={p}
        updatePackage={updatePackage}
      />}
    </div>
  )
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package page_objects.customer.header;

/**
 *
 * @author m.czabaj
 */
public class CustomerHeaderFields{

    static String cartLocator = "div#cart .content";
    static String cartQuantityLocator = cartLocator + " .quantity";
    static String aLogotypeLocator = "a.logotype";

}


text:
layout: post
title: "IntelliJ Rust Changelog #63"
date: 2017-12-26 14:23:47 +0300
---

This is the latest release in this year.

We are very happy that more and more people use intellij-rust and
we are very pleased the number of contributors is constantly growing!
Hope that next year will be even better than this one!

Happy new year! 🎄 🎅 🔔 ✨ 🌟 🎆

## New Features

* Initial support of auto import 🎉 Now it is implemented as intention
so you can try it via Alt+Enter at unresolved reference

* Quick fix to add cast for the numeric types mismatch (by [@oleg-semenov])

* Goto type declaration action (Ctrl+Shift+B)

* New icon for type alias item (by [@Nilera])

## Fixes

* Don't show error on getting mut reference of function/method (by [@kumbayo])

* Correctly sanitize names in introduce variable action

* Correctly resolve struct literals and fields with type aliases (by [@kumbayo])

## Internal Improvements

* Fix some compiler warnings after migration to IDEA 2017.3

* Update gradle and kotlin

* Fix rustfmt-nightly compilation for CI builds

[@Nilera]: https://github.com/Nilera
[@kumbayo]: https://github.com/kumbayo
[@oleg-semenov]: https://github.com/oleg-semenov


text:
package org.keycloak.testsuite.federation.ldap.base;

import org.junit.Assert;
import org.junit.ClassRule;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.junit.runners.MethodSorters;
import org.keycloak.common.util.Time;
import org.keycloak.federation.ldap.LDAPFederationProvider;
import org.keycloak.federation.ldap.LDAPFederationProviderFactory;
import org.keycloak.federation.ldap.idm.model.LDAPObject;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;
import org.keycloak.models.LDAPConstants;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserFederationMapperModel;
import org.keycloak.models.UserFederationProvider;
import org.keycloak.models.UserFederationProviderModel;
import org.keycloak.models.UserFederationSyncResult;
import org.keycloak.models.UserModel;
import org.keycloak.models.UserProvider;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.services.managers.RealmManager;
import org.keycloak.services.managers.UsersSyncManager;
import org.keycloak.testsuite.federation.ldap.FederationTestUtils;
import org.keycloak.testsuite.rule.KeycloakRule;
import org.keycloak.testsuite.rule.LDAPRule;

import java.util.Map;

/**
 * @author Marek Posolda
 */
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class LDAPSyncTest {

    private static LDAPRule ldapRule = new LDAPRule();

    private static UserFederationProviderModel ldapModel = null;

    private static KeycloakRule keycloakRule = new KeycloakRule(new KeycloakRule.KeycloakSetup() {

        @Override
        public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
            // Other tests may left Time offset uncleared, which could cause issues
            Time.setOffset(0);

            Map<String,String> ldapConfig = ldapRule.getConfig();
            ldapConfig.put(LDAPConstants.SYNC_REGISTRATIONS, "false");
            ldapConfig.put(LDAPConstants.EDIT_MODE, UserFederationProvider.EditMode.WRITABLE.toString());
            ldapModel = appRealm.addUserFederationProvider(LDAPFederationProviderFactory.PROVIDER_NAME, ldapConfig, 0, "test-ldap",
                    -1, -1, 0);

            FederationTestUtils.addZipCodeLDAPMapper(appRealm, ldapModel);

            // Delete all LDAP users and add 5 new users for testing
            LDAPFederationProvider ldapFedProvider = FederationTestUtils.getLdapProvider(session, ldapModel);
            FederationTestUtils.removeAllLDAPUsers(ldapFedProvider, appRealm);

            for (int i=1 ; i<=5 ; i++) {
                LDAPObject ldapUser = FederationTestUtils.addLDAPUser(ldapFedProvider, appRealm, "user" + i, "User" + i + "FN", "User" + i + "LN", "user" + i + "@email.org", null, "12" + i);
                FederationTestUtils.updateLDAPPassword(ldapFedProvider, ldapUser, "Password1");
            }
        }
    });

    @ClassRule
    public static TestRule chain = RuleChain
            .outerRule(ldapRule)
            .around(keycloakRule);

//    @Test
//    public void test01runit() throws Exception {
//        Thread.sleep(10000000);
//    }

    @Test
    public void test01LDAPSync() {
        UsersSyncManager usersSyncManager = new UsersSyncManager();

        // wait a bit
        sleep(ldapRule.getSleepTime());

        KeycloakSession session = keycloakRule.startSession();
        try {
            KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
            UserFederationSyncResult syncResult = usersSyncManager.syncAllUsers(sessionFactory, "test", ldapModel);
            FederationTestUtils.assertSyncEquals(syncResult, 5, 0, 0, 0);
        } finally {
            keycloakRule.stopSession(session, false);
        }

        session = keycloakRule.startSession();
        try {
            RealmModel testRealm = session.realms().getRealm("test");
            UserProvider userProvider = session.userStorage();
            // Assert users imported
            FederationTestUtils.assertUserImported(userProvider, testRealm, "user1", "User1FN", "User1LN", "user1@email.org", "121");
            FederationTestUtils.assertUserImported(userProvider, testRealm, "user2", "User2FN", "User2LN", "user2@email.org", "122");
            FederationTestUtils.assertUserImported(userProvider, testRealm, "user3", "User3FN", "User3LN", "user3@email.org", "123");
            FederationTestUtils.assertUserImported(userProvider, testRealm, "user4", "User4FN", "User4LN", "user4@email.org", "124");
            FederationTestUtils.assertUserImported(userProvider, testRealm, "user5", "User5FN", "User5LN", "user5@email.org", "125");

            // Assert lastSync time updated
            Assert.assertTrue(ldapModel.getLastSync() > 0);
            for (UserFederationProviderModel persistentFedModel : testRealm.getUserFederationProviders()) {
                if (LDAPFederationProviderFactory.PROVIDER_NAME.equals(persistentFedModel.getProviderName())) {
                    Assert.assertTrue(persistentFedModel.getLastSync() > 0);
                } else {
                    // Dummy provider has still 0
                    Assert.assertEquals(0, persistentFedModel.getLastSync());
                }
            }

            // wait a bit
            sleep(ldapRule.getSleepTime());

            // Add user to LDAP and update 'user5' in LDAP
            LDAPFederationProvider ldapFedProvider = FederationTestUtils.getLdapProvider(session, ldapModel);
            FederationTestUtils.addLDAPUser(ldapFedProvider, testRealm, "user6", "User6FN", "User6LN", "user6@email.org", null, "126");
            LDAPObject ldapUser5 = ldapFedProvider.loadLDAPUserByUsername(testRealm, "user5");
            // NOTE: Changing LDAP attributes directly here
            ldapUser5.setSingleAttribute(LDAPConstants.EMAIL, "user5Updated@email.org");
            ldapUser5.setSingleAttribute(LDAPConstants.POSTAL_CODE, "521");
            ldapFedProvider.getLdapIdentityStore().update(ldapUser5);

            // Assert still old users in local provider
            FederationTestUtils.assertUserImported(userProvider, testRealm, "user5", "User5FN", "User5LN", "user5@email.org", "125");
            Assert.assertNull(userProvider.getUserByUsername("user6", testRealm));

            // Trigger partial sync
            KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
            UserFederationSyncResult syncResult = usersSyncManager.syncChangedUsers(sessionFactory, "test", ldapModel);
            FederationTestUtils.assertSyncEquals(syncResult, 1, 1, 0, 0);
        } finally {
            keycloakRule.stopSession(session, false);
        }

        session = keycloakRule.startSession();
        try {
            RealmModel testRealm = session.realms().getRealm("test");
            UserProvider userProvider = session.userStorage();
            // Assert users updated in local provider
            FederationTestUtils.assertUserImported(userProvider, testRealm, "user5", "User5FN", "User5LN", "user5updated@email.org", "521");
            FederationTestUtils.assertUserImported(userProvider, testRealm, "user6", "User6FN", "User6LN", "user6@email.org", "126");
        } finally {
            keycloakRule.stopSession(session, false);
        }
    }

    @Test
    public void test02duplicateUsernameAndEmailSync() {
        LDAPObject duplicatedLdapUser;

        KeycloakSession session = keycloakRule.startSession();
        try {
            RealmModel testRealm = session.realms().getRealm("test");

            FederationTestUtils.addLocalUser(session, testRealm, "user7", "user7@email.org", "password");
            LDAPFederationProvider ldapFedProvider = FederationTestUtils.getLdapProvider(session, ldapModel);

            // Add user to LDAP with duplicated username "user7"
            duplicatedLdapUser = FederationTestUtils.addLDAPUser(ldapFedProvider, testRealm, "user7", "User7FN", "User7LN", "user7-something@email.org", null, "126");

        } finally {
            keycloakRule.stopSession(session, true);
        }

        session = keycloakRule.startSession();
        try {
            RealmModel testRealm = session.realms().getRealm("test");

            // Assert syncing from LDAP fails due to duplicated username
            UserFederationSyncResult result = new UsersSyncManager().syncAllUsers(session.getKeycloakSessionFactory(), "test", ldapModel);
            Assert.assertEquals(1, result.getFailed());

            // Remove "user7" from LDAP
            LDAPFederationProvider ldapFedProvider = FederationTestUtils.getLdapProvider(session, ldapModel);
            ldapFedProvider.getLdapIdentityStore().remove(duplicatedLdapUser);

            // Add user to LDAP with duplicated email "user7@email.org"
            duplicatedLdapUser = FederationTestUtils.addLDAPUser(ldapFedProvider, testRealm, "user7-something", "User7FNN", "User7LNL", "user7@email.org", null, "126");
        } finally {
            keycloakRule.stopSession(session, true);
        }

        session = keycloakRule.startSession();
        try {
            RealmModel testRealm = session.realms().getRealm("test");

            // Assert syncing from LDAP fails due to duplicated email
            UserFederationSyncResult result = new UsersSyncManager().syncAllUsers(session.getKeycloakSessionFactory(), "test", ldapModel);
            Assert.assertEquals(1, result.getFailed());
            Assert.assertNull(session.userStorage().getUserByUsername("user7-something", testRealm));

            // Update LDAP user to avoid duplicated email
            duplicatedLdapUser.setSingleAttribute(LDAPConstants.EMAIL, "user7-changed@email.org");
            LDAPFederationProvider ldapFedProvider = FederationTestUtils.getLdapProvider(session, ldapModel);
            ldapFedProvider.getLdapIdentityStore().update(duplicatedLdapUser);

            // Assert user successfully synced now
            result = new UsersSyncManager().syncAllUsers(session.getKeycloakSessionFactory(), "test", ldapModel);
            Assert.assertEquals(0, result.getFailed());
        } finally {
            keycloakRule.stopSession(session, true);
        }

        // Assert user imported in another transaction
        session = keycloakRule.startSession();
        try {
            RealmModel testRealm = session.realms().getRealm("test");
            FederationTestUtils.assertUserImported(session.userStorage(), testRealm, "user7-something", "User7FNN", "User7LNL", "user7-changed@email.org", "126");
        } finally {
            keycloakRule.stopSession(session, false);
        }
    }

    // KEYCLOAK-1571
    @Test
    public void test03SameUUIDAndUsernameSync() {
        KeycloakSession session = keycloakRule.startSession();
        String origUuidAttrName;

        try {
            RealmModel testRealm = session.realms().getRealm("test");

            // Remove all users from model
            for (UserModel user : session.userStorage().getUsers(testRealm, true)) {
                session.userStorage().removeUser(testRealm, user);
            }

            UserFederationProviderModel providerModel = KeycloakModelUtils.findUserFederationProviderByDisplayName(ldapModel.getDisplayName(), testRealm);

            // Change name of UUID attribute to same like usernameAttribute
            LDAPFederationProvider ldapFedProvider = FederationTestUtils.getLdapProvider(session, ldapModel);
            String uidAttrName = ldapFedProvider.getLdapIdentityStore().getConfig().getUsernameLdapAttribute();
            origUuidAttrName = providerModel.getConfig().get(LDAPConstants.UUID_LDAP_ATTRIBUTE);
            providerModel.getConfig().put(LDAPConstants.UUID_LDAP_ATTRIBUTE, uidAttrName);

            // Need to change this due to ApacheDS pagination bug (For other LDAP servers, pagination works fine) TODO: Remove once ApacheDS upgraded and pagination is fixed
            providerModel.getConfig().put(LDAPConstants.BATCH_SIZE_FOR_SYNC, "10");
            testRealm.updateUserFederationProvider(providerModel);

        } finally {
            keycloakRule.stopSession(session, true);
        }

        session = keycloakRule.startSession();
        try {
            RealmModel testRealm = session.realms().getRealm("test");
            UserFederationProviderModel providerModel = KeycloakModelUtils.findUserFederationProviderByDisplayName(ldapModel.getDisplayName(), testRealm);

            KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
            UserFederationSyncResult syncResult = new UsersSyncManager().syncAllUsers(sessionFactory, "test", providerModel);
            Assert.assertEquals(0, syncResult.getFailed());

        } finally {
            keycloakRule.stopSession(session, false);
        }

        session = keycloakRule.startSession();
        try {
            RealmModel testRealm = session.realms().getRealm("test");

            // Assert users imported with correct LDAP_ID
            FederationTestUtils.assertUserImported(session.users(), testRealm, "user1", "User1FN", "User1LN", "user1@email.org", "121");
            FederationTestUtils.assertUserImported(session.users(), testRealm, "user2", "User2FN", "User2LN", "user2@email.org", "122");
            UserModel user1 = session.users().getUserByUsername("user1", testRealm);
            Assert.assertEquals("user1", user1.getFirstAttribute(LDAPConstants.LDAP_ID));

            // Revert config changes
            UserFederationProviderModel providerModel = KeycloakModelUtils.findUserFederationProviderByDisplayName(ldapModel.getDisplayName(), testRealm);
            providerModel.getConfig().put(LDAPConstants.UUID_LDAP_ATTRIBUTE, origUuidAttrName);
            testRealm.updateUserFederationProvider(providerModel);
        } finally {
            keycloakRule.stopSession(session, true);
        }
    }

    // KEYCLOAK-1728
    @Test
    public void test04MissingLDAPUsernameSync() {
        KeycloakSession session = keycloakRule.startSession();
        String origUsernameAttrName;

        try {
            RealmModel testRealm = session.realms().getRealm("test");

            // Remove all users from model
            for (UserModel user : session.userStorage().getUsers(testRealm, true)) {
                session.userStorage().removeUser(testRealm, user);
            }

            UserFederationProviderModel providerModel = KeycloakModelUtils.findUserFederationProviderByDisplayName(ldapModel.getDisplayName(), testRealm);

            // Add street mapper and add some user including street
            UserFederationMapperModel streetMapper = FederationTestUtils.addUserAttributeMapper(testRealm, ldapModel, "streetMapper", "street", LDAPConstants.STREET);
            LDAPFederationProvider ldapFedProvider = FederationTestUtils.getLdapProvider(session, ldapModel);
            LDAPObject streetUser = FederationTestUtils.addLDAPUser(ldapFedProvider, testRealm, "user8", "User8FN", "User8LN", "user8@email.org", "user8street", "126");

            // Change name of username attribute name to street
            origUsernameAttrName = providerModel.getConfig().get(LDAPConstants.USERNAME_LDAP_ATTRIBUTE);
            providerModel.getConfig().put(LDAPConstants.USERNAME_LDAP_ATTRIBUTE, "street");

            // Need to change this due to ApacheDS pagination bug (For other LDAP servers, pagination works fine) TODO: Remove once ApacheDS upgraded and pagination is fixed
            providerModel.getConfig().put(LDAPConstants.BATCH_SIZE_FOR_SYNC, "10");
            testRealm.updateUserFederationProvider(providerModel);

        } finally {
            keycloakRule.stopSession(session, true);
        }

        // Just user8 synced. All others failed to sync
        session = keycloakRule.startSession();
        try {
            RealmModel testRealm = session.realms().getRealm("test");
            UserFederationProviderModel providerModel = KeycloakModelUtils.findUserFederationProviderByDisplayName(ldapModel.getDisplayName(), testRealm);

            KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
            UserFederationSyncResult syncResult = new UsersSyncManager().syncAllUsers(sessionFactory, "test", providerModel);
            Assert.assertEquals(1, syncResult.getAdded());
            Assert.assertTrue(syncResult.getFailed() > 0);
        } finally {
            keycloakRule.stopSession(session, false);
        }

        session = keycloakRule.startSession();
        try {
            RealmModel testRealm = session.realms().getRealm("test");

            // Revert config changes
            UserFederationProviderModel providerModel = KeycloakModelUtils.findUserFederationProviderByDisplayName(ldapModel.getDisplayName(), testRealm);
            providerModel.getConfig().put(LDAPConstants.USERNAME_LDAP_ATTRIBUTE, origUsernameAttrName);
            testRealm.updateUserFederationProvider(providerModel);
            UserFederationMapperModel streetMapper = testRealm.getUserFederationMapperByName(providerModel.getId(), "streetMapper");
            testRealm.removeUserFederationMapper(streetMapper);
        } finally {
            keycloakRule.stopSession(session, true);
        }
    }

    private void sleep(int time) {
        try {
            Thread.sleep(time);
        } catch (InterruptedException ie) {
            throw new RuntimeException(ie);
        }
    }
}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model backend\modules\location\models\DistrictSearchModel */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
    ]); ?>

    <?= $form->field($model, 'id') ?>

    <?= $form->field($model, 'cityId') ?>

    <?= $form->field($model, 'name') ?>

        <?= Html::submitButton(Yii::t('app/location', 'Search'), ['class' => 'btn btn-primary']) ?>
        <?= Html::resetButton(Yii::t('app/location', 'Reset'), ['class' => 'btn btn-default']) ?>

    <?php ActiveForm::end(); ?>


text:
@echo off
if exist %SAHI_HOME% goto checkuserdata
set SAHI_HOME=..

:checkuserdata
if exist %SAHI_USERDATA_DIR% goto setuserdatadir
set SAHI_USERDATA_DIR_TMP=%SAHI_HOME%\userdata
goto startsahi

:setuserdatadir
set SAHI_USERDATA_DIR_TMP=%SAHI_USERDATA_DIR%

:startsahi
set SAHI_CLASS_PATH=%SAHI_HOME%\lib\sahi.jar;%SAHI_HOME%\extlib\rhino\js.jar;%SAHI_HOME%\extlib\apc\commons-codec-1.3.jar

echo --------
echo SAHI_HOME: %SAHI_HOME%
echo SAHI_USERDATA_DIR: %SAHI_USERDATA_DIR_TMP%
echo SAHI_EXT_CLASS_PATH: %SAHI_EXT_CLASS_PATH%
echo --------

java -classpath %SAHI_EXT_CLASS_PATH%;%SAHI_CLASS_PATH% net.sf.sahi.Proxy "%SAHI_HOME%" "%SAHI_USERDATA_DIR_TMP%"


text:
ifeq (, $(shell which xmroot))
$(error "No Xcelium installation in $(PATH)")
endif

XCELIUM_HOME = $(shell xmroot)

CC ?= gcc
CFLAGS := -c -std=c99 -fPIC -fno-stack-protector -g

LD ?= ld
LDFLAGS := -shared -E

#Only 32 bits is currently supported
CFLAGS  += -m32
LDFLAGS += -melf_i386

RM ?= rm
INCS := -I$(XCELIUM_HOME)/tools/include

XRUN ?= $(XCELIUM_HOME)/tools/bin/xrun

TOPLEVEL      := top_module
VPI_MODULES   :=
PARAMETERS    ?= vlogparam_bool=1 vlogparam_int=42 vlogparam_str=hello
PLUSARGS      ?= plusarg_bool=1 plusarg_int=42 plusarg_str=hello
XMSIM_OPTIONS ?= a few xmsim_options
XRUN_OPTIONS  ?= plenty of xrun_options
EXTRA_OPTIONS ?= $(XRUN_OPTIONS) $(if $(XMSIM_OPTIONS),-xmsimargs '$(XMSIM_OPTIONS)',) $(addprefix -defparam ,$(PARAMETERS)) $(addprefix +,$(PLUSARGS))

XRUN_CALL = $(XRUN) -q -f edalize_main.f $(addprefix -pli ,$(VPI_MODULES)) $(EXTRA_OPTIONS) -top $(TOPLEVEL)

all: $(VPI_MODULES)

run: $(VPI_MODULES)
	$(XRUN_CALL)

run-gui: $(VPI_MODULES)
	$(XRUN_CALL) -gui -access rwc

clean:


text:
"""Setup command."""
from ..api import setup

def run(args):
    if args.reset:
        # Prompt the user to be extra sure.
        res = input('THIS WILL DELETE ALL DATA! Type "yes" if you are sure: ')
        if res != 'yes':
            return
    im = setup.IndexMapper(args.url,
                           data_path=args.data_path,
                           delete_indexes=args.reset)
    im.run()


text:
<?php

/**
 * Unserialize the js files from the old txt config files
 *
 * @author   Arthur Jaouen <arthur@factorfx.com>
 * @license  http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU Public License, version 2
 * @link     http://www.ocsinventory-ng.org/
 *
 */
class TxtJsSerializer {
	public function serialize($js) {
		throw new Exception('Cannot serialize OCS 2.2 js config to old (pre 2.2) txt files');
	}

	public function unserialize($config) {
		if (!is_array($config)) {
			return false;
		}

		$js = array();
		foreach ($config['JAVASCRIPT'] as $file => $path) {
			$js []= $path.$file;
		}

		return $js;
	}
}

?>


text:
<?php

class Inchoo_GoogleConnect_AccountController extends Mage_Core_Controller_Front_Action
{

    public function preDispatch()
    {
        parent::preDispatch();

        if (!$this->getRequest()->isDispatched()) {
            return;
        }

        if (!Mage::getSingleton('customer/session')->authenticate($this)) {
            $this->setFlag('', 'no-dispatch', true);
        }
    }

    public function indexAction()
    {
        $userInfo = Mage::getSingleton('inchoo_googleconnect/userinfo')
                ->getUserInfo();

        Mage::register('inchoo_googleconnect_userinfo', $userInfo);

        $this->loadLayout();
        $this->renderLayout();
    }

}


text:
![Logo](images/logo.png)

# Documentation

:heavy_exclamation_mark: work in progress :heavy_exclamation_mark:

This repository includes several documents that explain both high-level and low-level concepts about Caliburn.Light.

- Introduction
  - [Overview](overview.md)
  - [History](history.md)
  - [Build the Code](build.md)
- Getting Started
  - [NuGet](nuget.md)
  - [Basic Configuration](configuration.md)
- What's next
  - [Screens, Conductors and Composition](composition.md)
  - [Validation](validation.md)
  - [WPF specifics](wpf.md)
  - [Windows Runtime specifics](windows-runtime.md)
- Advanced Topics
  - [Service Locator](service-locator.md)
  - [Simple IoC Container](simple-container.md)
  - [The Event Aggregator](event-aggregator.md)
  - [The Window Manager](window-manager.md)
  - [Design Time Support](design-time.md)
  - [ICoTask and Coroutines](coroutines.md)
  - [Async (Task Support)](async.md)
  - [View/ViewModel Resolution](viewmodel-resolver.md)
    - [Convention Based](conventions.md)
    - [Naming Conventions](naming-conventions.md)
    - [Handling Custom Conventions](custom-conventions.md)
    - [Using the NameTransformer](name-transformer.md)
  - [Office and WinForms Applications](winforms.md)
- Extending the Framework
  - The ViewModel Binder


text:
<?php

namespace ItemModule\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use ItemModule\Model\Item;
use ItemModule\Form\ItemForm;
use Zend\View\Model\JsonModel;

class ItemController extends AbstractActionController {

    protected $itemTable;
    protected $photoItemTable;
    protected $shopTable;
    protected $items2shopTable;
    protected $categoryTable;
    protected $subcategoryTable;

    public function indexAction() {

        $request = $this->getRequest();
        $where = array();
        if ($request->isPost()) {
            $search = $request->getPost()->get('data');
            foreach ($search as $key => $query) {

                if ($key == 'status' || $key == 'action') {
                    if ($query >= '0')
                        $where['item.' . $key] = (int) $query;
                } else
                    $where['item.' . $key . ' LIKE ?'] = '%' . $query . '%';
            }
        }

// grab the paginator from the ItemTable
        $paginator = $this->getItemTable()->fetchAll(true, $where);

// set the current page to what has been passed in query string, or to 1 if none set
        $paginator->setCurrentPageNumber((int) $this->params()->fromQuery('page', 1));
        // set the number of items per page to 10
        $paginator->setItemCountPerPage(10);
        $category = $this->getCategoryTable()->fetchAll();
        return new ViewModel(array(
            'paginator' => $paginator,
            'categorys' => $category,
            'search' => $search
        ));
    }

    public function getIndexLocation() {
// выборка конфигурации из конфигурационных данных модуля
        $config = $this->getServiceLocator()->get('config');
        if ($config instanceof Traversable) {
            $config = ArrayUtils::iteratorToArray($config);
        }
        if (!empty($config['module_config']['search_index'])) {
            return $config['module_config']['search_index'];
        } else {
            return FALSE;
        }
    }

    public function addAction() {
        set_time_limit(0);
        $form = new ItemForm();
        $form->get('submit')->setValue('Добавить');
        $options = $this->GetListCategory();
        $form->get('category_id')->setAttribute('options', $options);

        $options2shop = $this->GetListShop();
        $form->get('shop_id')->setValueOptions($options2shop);

        $options_sub = $this->GetListSubcategory($item->subcategory_id, $item->category_id);
        if ($options_sub)
            $form->get('subcategory_id')->setAttribute('options', $options_sub);

        $adapter = new \Zend\File\Transfer\Adapter\Http();

        $request = $this->getRequest();

        if ($request->isPost()) {
            $item = new Item();
            $form->setInputFilter($item->getInputFilter());
            $form->setData($request->getPost());
            if ($form->isValid()) {

                $item->exchangeArray($form->getData());
                $uploadFiles = $this->params()->fromFiles('id_photo');
                if ($uploadFiles) {
                    $uploadPath = $this->getFileUploadLocation();
// Сохранение выгруженного файла
                    $adapter = new \Zend\File\Transfer\Adapter\Http();
                    $adapter->addValidator('Size', false, array('max' => '15242880'));

                    if (!$adapter->isValid()) {
                        $dataError = $adapter->getMessages();
                        $error = array();
                        foreach ($dataError as $key => $row) {
                            $error[] = $row;
                        }
                        $form->setMessages(array('fileupload' => $error));
                    } else {

                        $adapter->setDestination($uploadPath);
                        $item->id = $this->getItemTable()->saveItem($item);
                        foreach ($uploadFiles as $file) {
                            if ($adapter->receive($file['name'])) {
                                $ext = split("[/\\.]", $file['name']);
                                $new_name = md5(microtime()) . '.' . $ext[count($ext) - 1];
                                $this->resizePhoto($file['name'], $new_name);

                                $data = array(
                                    'id_item' => $item->id,
                                    'patch' => $new_name,
                                    'status' => $item->status,
                                );
                                $item->id_photo = $this->getPhotoItemTable()->savePhoto($data);
                            }
                        }
                    }
                }
                $item->id = $this->getItemTable()->saveItem($item);
                $shop = $form->get('shop_id')->getValue();
                $this->getItems2ShopTable()->saveItem2Shop($item->id, $shop);

// Redirect to list of item
                return $this->redirect()->toRoute('item');
            }
        }
        return array('form' => $form);
    }

    public function editAction() {
        $id = (int) $this->params()->fromRoute('id', 0);

        if (!$id) {
            return $this->redirect()->toRoute('item', array(
                        'action' => 'add'
            ));
        }

// Get the Item with the specified id. An exception is thrown
// if it cannot be found, in which case go to the index page.
        try {
            $item = $this->getItemTable()->getItem($id);
        } catch (\Exception $ex) {
            return $this->redirect()->toRoute('item', array(
                        'action' => 'index'
            ));
        }

        $form = new ItemForm();
        $form->bind($item);
        $form->get('submit')->setAttribute('value', 'Редактировать');

        $options = $this->GetListCategory($item->category_id);
        $form->get('category_id')->setAttribute('options', $options);

        $options_sub = $this->GetListSubcategory($item->subcategory_id, $item->category_id);
        if ($options_sub)
            $form->get('subcategory_id')->setAttribute('options', $options_sub);

        $options2shop = $this->GetListShop($item);
        $form->get('shop_id')->setValueOptions($options2shop);

        $request = $this->getRequest();
        if ($request->isPost()) {
            $form->setInputFilter($item->getInputFilter());
            $form->setData($request->getPost());

            if ($form->isValid()) {
                $uploadFiles = $this->params()->fromFiles('id_photo');
                $uploadPath = $this->getFileUploadLocation();

                if ($uploadFiles) {
// Сохранение выгруженного файла
                    $adapter = new \Zend\File\Transfer\Adapter\Http();
                    $adapter->addValidator('Size', false, array('max' => '15242880'));
                    if (!$adapter->isValid()) {
                        $dataError = $adapter->getMessages();
                        $error = array();
                        foreach ($dataError as $key => $row) {
                            $error[] = $row;
                        }
                        $form->setMessages(array('fileupload' => $error));
                    } else {
                        $adapter->setDestination($uploadPath);
                        foreach ($uploadFiles as $file) {
                            if ($adapter->receive($file['name'])) {
                                $ext = split("[/\\.]", $file['name']);
                                $new_name = md5(microtime()) . '.' . $ext[count($ext) - 1];
                                $this->resizePhoto($file['name'], $new_name);
                                $data = array(
                                    'id_item' => $id,
                                    'patch' => $new_name,
                                    'status' => $item->status,
                                );
                                $item->id_photo = $this->getPhotoItemTable()->savePhoto($data);
                            }
                        }
                    }
                }
                $this->getItemTable()->saveItem($item);
                $shop = $form->get('shop_id')->getValue();
                $this->getItems2ShopTable()->saveItem2Shop($item->id, $shop);

// Redirect to list of $items
                return $this->redirect()->toRoute('item');
            }
        }
        if ($item->patch) {
            $patch = explode(',', $item->patch);
        }

        return array(
            'id' => $id,
            'form' => $form,
            'photos' => $patch,
        );
    }

    public function GetListSubcategory($subcategory_id, $cat_id) {
        $subcategories = $this->getSubcategoryTable()->getSubcategories($cat_id);
        for ($i = 0; $i < sizeof($subcategories); $i++) {
            if ($subcategories[$i]['id'] == $subcategory_id) {
                $selected = true;
            } else {
                $selected = false;
            }
            $options[] = (
                    array(
                        'value' => $subcategories[$i]['id'],
                        'label' => $subcategories[$i]['name'],
                        'selected' => $selected,
            ));
        }
        return $options;
    }

    public function GetListCategory($category_id) {
        $categories = $this->getCategoryTable()->getCategoryList();
        for ($i = 0; $i < sizeof($categories); $i++) {
            if ($categories[$i]['id'] == $category_id) {
                $selected = true;
            } else {
                $selected = false;
            }
            $options[] = (
                    array(
                        'value' => $categories[$i]['id'],
                        'label' => $categories[$i]['name'],
                        'selected' => $selected,
            ));
        }
        return $options;
    }

    public function GetListShop($item) {
        $shops = $this->getShopTable()->getShopList();
        $id_shop = explode(',', $item->id_shop);
        for ($i = 0; $i < sizeof($shops); $i++) {
            if (in_array($shops[$i]['id'], (array) $id_shop)) {
                $selected = true;
            } else {
                $selected = false;
            }
            $options[] = (
                    array(
                        'value' => $shops[$i]['id'],
                        'label' => $shops[$i]['address'],
                        'selected' => $selected,
            ));
        }
        return $options;
    }

    public function deletephotoAction() {
        $request = $this->getRequest();
        $patch = $request->getPost('qString');
        $data = array(
            'patch' => $patch,
        );
        $this->getPhotoItemTable()->deletePhotoWhere($data);
        $uploadPath = $this->getFileUploadLocation();
        try {
            unlink($uploadPath . '/' . $patch);
            unlink($uploadPath . '/small_' . $patch);
            unlink($uploadPath . '/big_' . $patch);
        } catch (Exception $ex) {

        }
#do something with the data
        $text = $text . "successfully processed";
        $result = new JsonModel(array(
            'text' => $text
        ));
        return $result;
    }

    public function deleteAction() {
        $id = (int) $this->params()->fromRoute('id', 0);
        if (!$id) {
            return $this->redirect()->toRoute('item');
        }

        $request = $this->getRequest();
        if ($request->isPost()) {
            $del = $request->getPost('del', 'No');

            if ($del == 'Да') {
                $id = (int) $request->getPost('id');
                $this->getItemTable()->deleteItem($id);
            }

// Redirect to list of item
            return $this->redirect()->toRoute('item');
        }
        return array(
            'id' => $id,
            'item' => $this->getItemTable()->getItem($id)
        );
    }

    public function getItemTable() {
        if (!$this->itemTable) {
            $sm = $this->getServiceLocator();
            $this->itemTable = $sm->get('ItemModule\Model\ItemTable');
        }
        return $this->itemTable;
    }

    public function getShopTable() {
        if (!$this->shopTable) {
            $sm = $this->getServiceLocator();
            $this->shopTable = $sm->get('ShopModule\Model\ShopTable');
        }
        return $this->shopTable;
    }

    public function getItems2ShopTable() {
        if (!$this->items2shopTable) {
            $sm = $this->getServiceLocator();
            $this->items2shopTable = $sm->get('ItemModule\Model\Items2ShopTable');
        }
        return $this->items2shopTable;
    }

    public function getCategoryTable() {
        if (!$this->categoryTable) {
            $sm = $this->getServiceLocator();
            $this->categoryTable = $sm->get('Category\Model\CategoryTable');
        }
        return $this->categoryTable;
    }

    public function getSubcategoryTable() {
        if (!$this->subcategoryTable) {
            $sm = $this->getServiceLocator();
            $this->subcategoryTable = $sm->get('Category\Model\SubcategoryTable');
        }
        return $this->subcategoryTable;
    }

    public function getPhotoItemTable() {
        if (!$this->photoItemTable) {
            $sm = $this->getServiceLocator();
            $this->photoItemTable = $sm->get('ItemModule\Model\PhotoItemTable');
        }
        return $this->photoItemTable;
    }

    public function getFileUploadLocation() {
// Получение конфигурации из конфигурационных данных модуля
        $config = $this->getServiceLocator()->get('config');
        return $config['module_config']['upload_location'];
    }

    public function resizePhoto($name, $new_name) {
        $uploadPath = $this->getFileUploadLocation();
        $filename = $uploadPath . '/' . $name;
        $small_filename = $uploadPath . '/small_' . $new_name;
        $big_filename = $uploadPath . '/big_' . $new_name;
        $thumbnailer = $this->getServiceLocator()->get('WebinoImageThumb');
        $thumb_small = $thumbnailer->create($filename, $options = array());
        $thumb_big = $thumbnailer->create($filename, $options = array());
        $thumb_big->adaptiveResize(600, 600);
        $thumb_big->save($big_filename);

        $thumb_small->adaptiveResize(200, 200);
        $thumb_small->save($small_filename);

        unlink($uploadPath . '/' . $name);

        /* $cmd = "/usr/bin/convert -resize 200 -gravity center  -crop 140x140+0+0 +repage    {$filename} {$small_filename}";
          exec($cmd . " 2>&1", $out, $retVal);

          $cmd = "/usr/bin/convert -resize 700 -gravity center  -crop 700x280+0+0 +repage    {$filename} {$big_filename}";
          exec($cmd . " 2>&1", $out, $retVal);

          $cmd = "/usr/bin/convert -resize 500 {$filename} {$filename}";
          exec($cmd . " 2>&1", $out, $retVal); */
    }

    function additionsearchAction() {

        $request = $this->getRequest();
        $key = $request->getQuery('key');
        $query = $request->getQuery('term');
        $where = array();
        $where['item.' . $key . ' LIKE ?'] = '%' . $query . '%';
        $info = $this->getItemTable()->fetchAll(false, $where);
        foreach ($info as $val) {
            $results[] = array('label' => $val->$key);
        }
        echo json_encode($results);
        exit();
        /* $result = new JsonModel(array(
          'results' => $results
          ));
          return $result;)
         *
         */
    }

}