text:
<?php

declare(strict_types=1);

/*
 * This file is part of SolidInvoice project.
 *
 * (c) Pierre du Plessis <open-source@solidworx.co>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace SolidInvoice\DataGridBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

class GridConfiguration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder('datagrid');
        $node = $treeBuilder->getRootNode();

        $node
            ->useAttributeAsKey('name', true)
            ->arrayPrototype()
                ->children()
                    ->scalarNode('icon')
                        ->defaultValue('')
                    ->end()
                    ->scalarNode('title')
                        ->defaultValue('')
                    ->end()
                    ->arrayNode('properties')
                        ->addDefaultsIfNotSet()
                        ->children()
                            ->booleanNode('sortable')
                                ->defaultTrue()
                            ->end()
                            ->booleanNode('paginate')
                                ->defaultTrue()
                            ->end()
                            ->scalarNode('route')
                                ->defaultNull()
                            ->end()
                        ->end()
                    ->end()
                    ->arrayNode('source')
                        ->isRequired()
                        ->children()
                            ->scalarNode('repository')
                                ->cannotBeEmpty()
                                ->isRequired()
                            ->end()
                            ->scalarNode('method')
                                ->cannotBeEmpty()
                                ->isRequired()
                            ->end()
                        ->end()
                    ->end()
                    ->arrayNode('columns')
                        ->isRequired()
                        ->requiresAtLeastOneElement()
                        ->arrayPrototype()
                            ->children()
                                ->scalarNode('name')
                                    ->isRequired()
                                    ->cannotBeEmpty()
                                ->end()
                                ->scalarNode('label')
                                    ->isRequired()
                                    ->cannotBeEmpty()
                                ->end()
                                ->booleanNode('editable')
                                    ->defaultFalse()
                                ->end()
                                ->scalarNode('cell')
                                    ->isRequired()
                                    ->cannotBeEmpty()
                                ->end()
                                ->scalarNode('formatter')
                                    ->defaultNull()
                                ->end()
                            ->end()
                        ->end()
                    ->end()
                    ->arrayNode('search')
                        ->addDefaultsIfNotSet()
                        ->children()
                            ->arrayNode('fields')
                                ->isRequired()
                                ->requiresAtLEastOneElement()
                                ->scalarPrototype()
                                ->end()
                            ->end()
                        ->end()
                    ->end()
                    ->arrayNode('actions')
                        ->arrayPrototype()
                            ->children()
                                ->scalarNode('label')
                                    ->isRequired()
                                    ->cannotBeEmpty()
                                ->end()
                                ->scalarNode('icon')
                                    ->defaultNull()
                                ->end()
                                ->scalarNode('confirm')
                                    ->defaultNull()
                                ->end()
                                ->scalarNode('className')
                                    ->defaultValue('default')
                                ->end()
                                ->scalarNode('action')
                                    ->isRequired()
                                    ->cannotBeEmpty()
                                ->end()
                            ->end()
                        ->end()
                    ->end()
                    ->arrayNode('line_actions')
                        ->arrayPrototype()
                            ->validate()
                                ->ifTrue(function ($data) {
                                    return empty($data['icon']) && empty($data['label']);
                                })
                                ->thenInvalid('At least one of "icon" or "label" needs to be set')
                            ->end()
                            ->children()
                                ->scalarNode('label')
                                    ->defaultNull()
                                ->end()
                                ->scalarNode('icon')
                                    ->defaultNull()
                                ->end()
                                ->scalarNode('route')
                                    ->isRequired()
                                    ->cannotBeEmpty()
                                ->end()
                                ->arrayNode('route_params')
                                    ->useAttributeAsKey('name')
                                    ->scalarPrototype()
                                    ->end()
                                ->end()
                                ->arrayNode('conditions')
                                    ->scalarPrototype()
                                    ->end()
                                ->end()
                            ->end()
                        ->end()
                    ->end()
                    ->arrayNode('filters')
                        ->arrayPrototype()
                            ->children()
                                ->scalarNode('type')
                                    ->isRequired()
                                    ->cannotBeEmpty()
                                ->end()
                                ->booleanNode('multiple')
                                    ->defaultFalse()
                                ->end()
                                ->arrayNode('source')
                                    ->children()
                                        ->scalarNode('repository')
                                            ->cannotBeEmpty()
                                            ->isRequired()
                                        ->end()
                                        ->scalarNode('method')
                                            ->cannotBeEmpty()
                                            ->isRequired()
                                        ->end()
                                    ->end()
                                ->end()
                            ->end()
                        ->end()
                    ->end()
                ->end()
            ->end();

        return $treeBuilder;
    }
}


text:
package be.ge0ffrey.coursera.knapsack.persistence;

import java.io.File;

import org.optaplanner.core.impl.solution.ProblemIO;
import org.optaplanner.core.impl.solution.Solution;

public class KnapsackProblemIO implements ProblemIO {

    public static final String FILE_EXTENSION = "txt";

    private KnapsackImporter importer = new KnapsackImporter();
    private KnapsackExporter exporter = new KnapsackExporter();

    public String getFileExtension() {
        return FILE_EXTENSION;
    }

    public Solution read(File inputSolutionFile) {
        return importer.readSolution(inputSolutionFile);
    }

    public void write(Solution solution, File outputSolutionFile) {
        exporter.writeSolution(solution, outputSolutionFile);
    }

}

redpajama_set_name: RedPajamaGithub


text:
export interface Dimensions {
	/**
	 * Add an event handler. Supported events:change
	 * It is supported in react-native only
	 */

	addEventListener: (type: string, handler: () => void) => void;

	/**
	 * Remove an event handler.
	 * It is supported in react-native only
	 */

	removeEventListener: (type: string, handler: () => void) => void;

	/**
	 * This should only be called from native code by sending the didUpdateDimensions event
	 * It is supported in react-native only
	 */

	set: (dims: object) => void;

	/**
	 * Initial dimensions are set before runApplication is called
	 *  so they should be available before any other require's are run, but may be updated later.
	 * It is supported in react-native only
	 */

	get: (dim: 'window' | 'screen') => object;
}


text:
<?php defined('SYSPATH') or die('No direct script access.');

class Model_Slider extends ORM
{
    protected $_table_name = "slider";
    protected $_primary_key = 'id';
}


text:
/* global ionic, define */
define([
  'app',
  'services/listings',
  'services/user'
], function (app) {

  app.controller('ListingCtrl', [
    '$scope',
    '$stateParams',
    '$window',
    '$ionicPopup',
    'listingService',
    'userService',
    '$state',
    function ($scope, $stateParams, $window, $ionicPopup, listingService, userService, $state) {

      // Go to the add listing view
      $scope.addListing = function () {
        $state.go('new_listing');
      };

      // Edit the listing
      $scope.editListing = function (listingObjectId) {
        console.log("going to edit listing: " + listingObjectId);
        $state.go("new_listing", {id: listingObjectId});
      };

      // Gets the current user whose object id is specified, sets it as $scope.profile
      // Then calls getListings
      $scope.getProfileAndListings = function (objectId) {
        var query = new Parse.Query(Parse.User);
        query.equalTo("objectId", objectId);

        query.first().then(function (profile) {
          $scope.profile = profile;
          $scope.getListings(profile);
        }, function (error) {
          console.error("Error finding user " + error);
        });

      };

      // Gets the user specifieds listings and sets them as $scope.listings
      // For all the listings it checks to see if an image is specified, if not it will set a default url.
      $scope.getListings = function (owner) {
        var listingsQuery = Parse.Object.extend("Listings");
        var query = new Parse.Query(listingsQuery);
        query.equalTo("parent", owner);
        query.find({
          success: function (results) {
            console.log("loaded");
            for (var i = 0; i < results.length; i++) {
              var listing = results[i];

              // Check if they have an image, if not set the default image
              if (listing.attributes.imageURL == null) {
                listing.imageURL = "http://www.novelupdates.com/img/noimagefound.jpg";
              } else {
                listing.imageURL = listing.attributes.imageURL;
              }

            }

            $scope.listings = results;
            $scope.loading = false;
          },
          error: function (error) {
            alert("Error: " + error.code + " " + error.message);
          }
        });
      };

      // Start loading and load listing owner and there listings
      $scope.loading = true;
      $scope.getProfileAndListings($stateParams.id);

      // Not being currently used
      // Used to refresh the page and update content
      $scope.reload = function () {
        $state.go("listing", {id: $scope.profile.id});
      };

      // Called by a button click on the UI
      // Launched a map application on the users device with the current users position.
      $scope.map = function () {
        if (ionic.Platform.isIOS()) {
          $window.open('maps://?q=' + $scope.profile.attributes.lat + ',' + $scope.profile.attributes.long, '_system');
        } else {
          $window.open('geo://0,0?q=' + $scope.profile.attributes.lat + ',' + $scope.profile.attributes.long + '(' + $scope.profile.attributes.firstName + '/' + $scope.profile.attributes.city + ')&z=15', '_system');
        }
      };

      // TODO backend logic
      // It opens a prompt to enter a message to report a user
      $scope.report = function () {
        $ionicPopup.prompt({
          scope: $scope,
          title: 'Report an issue',
          subTitle: 'What\'s wrong or missing?',
          inputType: 'text',
          inputPlaceholder: ''
        }).then(function (res) {
          if (res) {
            // TODO
          }

        });

      };

    }
  ]);
});


text:
#include "rotateItem.h"

using namespace graphicsUtils;

RotateItem::RotateItem(QGraphicsItem *parent)
	: AbstractItem(parent)
{
}

QRectF RotateItem::rect() const
{
	return boundingRect();
}

Rotater &RotateItem::rotater()
{
	return mRotater;
}

void RotateItem::init()
{
	mRotater.setMasterItem(this);
	mRotater.setVisible(false);
}

QVariant RotateItem::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value)
{
	if (change == QGraphicsItem::ItemSelectedChange) {
		mRotater.setVisible(theOnlySelectedRotateItem(value.toBool()));
		mRotater.setSelected(mRotater.isVisible());
	}

	return AbstractItem::itemChange(change, value);
}

bool RotateItem::theOnlySelectedRotateItem(bool thisSelected) const
{
	if (!thisSelected) {
		return false;
	}

	for (QGraphicsItem * const selectedItem : scene()->selectedItems()) {
		if (dynamic_cast<RotateItem *>(selectedItem) && selectedItem != this) {
			return false;
		}
	}

	return true;
}


text:
namespace caf {

/// Defines a configuration option for the application.
class CAF_CORE_EXPORT config_option {
public:
  // -- member types -----------------------------------------------------------

  /// Custom vtable-like struct for delegating to type-specific functions and
  /// storing type-specific information shared by several config options.
  struct meta_state {
    /// Tries to perform this sequence of steps:
    /// - Convert the config value to the type of the config option.
    /// - Assign the converted value back to the config value to synchronize
    ///   conversions back to the caller.
    /// - Store the converted value in the pointer unless it is `nullptr`.
    error (*sync)(void*, config_value&);

    /// Tries to extract a value from the given location. Exists for backward
    /// compatibility only and will get removed with CAF 0.17.
    config_value (*get)(const void*);

    /// Human-readable name of the option's type.
    std::string_view type_name;
  };

  // -- constructors, destructors, and assignment operators --------------------

  ///  Constructs a config option.
  config_option(std::string_view category, std::string_view name,
                std::string_view description, const meta_state* meta,
                void* value = nullptr);

  config_option(const config_option&);

  config_option(config_option&&) = default;

  config_option& operator=(const config_option&);

  config_option& operator=(config_option&&) = default;

  // -- swap function ----------------------------------------------------------

  friend void swap(config_option& first, config_option& second) noexcept;

  // -- properties -------------------------------------------------------------

  /// Returns the category of the option.
  std::string_view category() const noexcept;

  /// Returns the name of the option.
  std::string_view long_name() const noexcept;

  /// Returns (optional) one-letter short names of the option.
  std::string_view short_names() const noexcept;

  /// Returns a human-readable description of the option.
  std::string_view description() const noexcept;

  /// Returns the full name for this config option as "<category>.<long name>".
  std::string_view full_name() const noexcept;

  /// Synchronizes the value of this config option with `x` and vice versa.
  ///
  /// Tries to perform this sequence of steps:
  /// - Convert the config value to the type of the config option.
  /// - Assign the converted value back to the config value to synchronize
  ///   conversions back to the caller.
  /// - Store the converted value unless this option is stateless.
  error sync(config_value& x) const;

  /// Returns a human-readable representation of this option's expected type.
  std::string_view type_name() const noexcept;

  /// Returns whether this config option stores a boolean flag.
  bool is_flag() const noexcept;

  /// Returns whether the category is optional for CLI options.
  bool has_flat_cli_name() const noexcept;

private:
  std::string_view buf_slice(size_t from, size_t to) const noexcept;

  std::unique_ptr<char[]> buf_;
  uint16_t category_separator_;
  uint16_t long_name_separator_;
  uint16_t short_names_separator_;
  uint16_t buf_size_;
  const meta_state* meta_;
  mutable void* value_;
};

/// Finds `config_option` string with a matching long name in (`first`, `last`],
/// where each entry is a pointer to a string. Returns a `ForwardIterator` to
/// the match and a `string_view` of the option value if the entry is
/// found and a `ForwardIterator` to `last` with an empty `string_view`
/// otherwise.
template <class ForwardIterator, class Sentinel>
std::pair<ForwardIterator, std::string_view>
find_by_long_name(const config_option& x, ForwardIterator first,
                  Sentinel last) {
  auto long_name = x.long_name();
  for (; first != last; ++first) {
    std::string_view str{*first};
    // Make sure this is a long option starting with "--".
    if (!starts_with(str, "--"))
      continue;
    str.remove_prefix(2);
    // Skip optional "caf#" prefix.
    if (starts_with(str, "caf#"))
      str.remove_prefix(4);
    // Make sure we are dealing with the right key.
    if (!starts_with(str, long_name))
      continue;
    // Make sure the key is followed by an assignment.
    str.remove_prefix(long_name.size());
    if (!starts_with(str, "="))
      continue;
    // Remove leading '=' and return the value.
    str.remove_prefix(1);
    return {first, str};
  }
  return {first, std::string_view{}};
}

} // namespace caf


text:
'use strict';

import NativeEventEmitter from '../EventEmitter/NativeEventEmitter';
import NativePushNotificationManagerIOS from './NativePushNotificationManagerIOS';
import invariant from 'invariant';

const PushNotificationEmitter = new NativeEventEmitter(
  NativePushNotificationManagerIOS,
);

const _notifHandlers = new Map();

const DEVICE_NOTIF_EVENT = 'remoteNotificationReceived';
const NOTIF_REGISTER_EVENT = 'remoteNotificationsRegistered';
const NOTIF_REGISTRATION_ERROR_EVENT = 'remoteNotificationRegistrationError';
const DEVICE_LOCAL_NOTIF_EVENT = 'localNotificationReceived';

export type ContentAvailable = 1 | null | void;

export type FetchResult = {
  NewData: string,
  NoData: string,
  ResultFailed: string,
  ...
};

/**
 * An event emitted by PushNotificationIOS.
 */
export type PushNotificationEventName = $Keys<{
  /**
   * Fired when a remote notification is received. The handler will be invoked
   * with an instance of `PushNotificationIOS`.
   */
  notification: string,
  /**
   * Fired when a local notification is received. The handler will be invoked
   * with an instance of `PushNotificationIOS`.
   */
  localNotification: string,
  /**
   * Fired when the user registers for remote notifications. The handler will be
   * invoked with a hex string representing the deviceToken.
   */
  register: string,
  /**
   * Fired when the user fails to register for remote notifications. Typically
   * occurs when APNS is having issues, or the device is a simulator. The
   * handler will be invoked with {message: string, code: number, details: any}.
   */
  registrationError: string,
  ...
}>;

/**
 *
 * Handle push notifications for your app, including permission handling and
 * icon badge number.
 *
 * See https://reactnative.dev/docs/pushnotificationios.html
 */
class PushNotificationIOS {
  _data: Object;
  _alert: string | Object;
  _sound: string;
  _category: string;
  _contentAvailable: ContentAvailable;
  _badgeCount: number;
  _notificationId: string;
  _isRemote: boolean;
  _remoteNotificationCompleteCallbackCalled: boolean;
  _threadID: string;

  static FetchResult: FetchResult = {
    NewData: 'UIBackgroundFetchResultNewData',
    NoData: 'UIBackgroundFetchResultNoData',
    ResultFailed: 'UIBackgroundFetchResultFailed',
  };

  /**
   * Schedules the localNotification for immediate presentation.
   *
   * See https://reactnative.dev/docs/pushnotificationios.html#presentlocalnotification
   */
  static presentLocalNotification(details: Object) {
    invariant(
      NativePushNotificationManagerIOS,
      'PushNotificationManager is not available.',
    );
    NativePushNotificationManagerIOS.presentLocalNotification(details);
  }

  /**
   * Schedules the localNotification for future presentation.
   *
   * See https://reactnative.dev/docs/pushnotificationios.html#schedulelocalnotification
   */
  static scheduleLocalNotification(details: Object) {
    invariant(
      NativePushNotificationManagerIOS,
      'PushNotificationManager is not available.',
    );
    NativePushNotificationManagerIOS.scheduleLocalNotification(details);
  }

  /**
   * Cancels all scheduled localNotifications.
   *
   * See https://reactnative.dev/docs/pushnotificationios.html#cancelalllocalnotifications
   */
  static cancelAllLocalNotifications() {
    invariant(
      NativePushNotificationManagerIOS,
      'PushNotificationManager is not available.',
    );
    NativePushNotificationManagerIOS.cancelAllLocalNotifications();
  }

  /**
   * Remove all delivered notifications from Notification Center.
   *
   * See https://reactnative.dev/docs/pushnotificationios.html#removealldeliverednotifications
   */
  static removeAllDeliveredNotifications(): void {
    invariant(
      NativePushNotificationManagerIOS,
      'PushNotificationManager is not available.',
    );
    NativePushNotificationManagerIOS.removeAllDeliveredNotifications();
  }

  /**
   * Provides you with a list of the app's notifications that are still displayed in Notification Center.
   *
   * See https://reactnative.dev/docs/pushnotificationios.html#getdeliverednotifications
   */
  static getDeliveredNotifications(
    callback: (notifications: Array<Object>) => void,
  ): void {
    invariant(
      NativePushNotificationManagerIOS,
      'PushNotificationManager is not available.',
    );
    NativePushNotificationManagerIOS.getDeliveredNotifications(callback);
  }

  /**
   * Removes the specified notifications from Notification Center
   *
   * See https://reactnative.dev/docs/pushnotificationios.html#removedeliverednotifications
   */
  static removeDeliveredNotifications(identifiers: Array<string>): void {
    invariant(
      NativePushNotificationManagerIOS,
      'PushNotificationManager is not available.',
    );
    NativePushNotificationManagerIOS.removeDeliveredNotifications(identifiers);
  }

  /**
   * Sets the badge number for the app icon on the home screen.
   *
   * See https://reactnative.dev/docs/pushnotificationios.html#setapplicationiconbadgenumber
   */
  static setApplicationIconBadgeNumber(number: number) {
    invariant(
      NativePushNotificationManagerIOS,
      'PushNotificationManager is not available.',
    );
    NativePushNotificationManagerIOS.setApplicationIconBadgeNumber(number);
  }

  /**
   * Gets the current badge number for the app icon on the home screen.
   *
   * See https://reactnative.dev/docs/pushnotificationios.html#getapplicationiconbadgenumber
   */
  static getApplicationIconBadgeNumber(callback: Function) {
    invariant(
      NativePushNotificationManagerIOS,
      'PushNotificationManager is not available.',
    );
    NativePushNotificationManagerIOS.getApplicationIconBadgeNumber(callback);
  }

  /**
   * Cancel local notifications.
   *
   * See https://reactnative.dev/docs/pushnotificationios.html#cancellocalnotification
   */
  static cancelLocalNotifications(userInfo: Object) {
    invariant(
      NativePushNotificationManagerIOS,
      'PushNotificationManager is not available.',
    );
    NativePushNotificationManagerIOS.cancelLocalNotifications(userInfo);
  }

  /**
   * Gets the local notifications that are currently scheduled.
   *
   * See https://reactnative.dev/docs/pushnotificationios.html#getscheduledlocalnotifications
   */
  static getScheduledLocalNotifications(callback: Function) {
    invariant(
      NativePushNotificationManagerIOS,
      'PushNotificationManager is not available.',
    );
    NativePushNotificationManagerIOS.getScheduledLocalNotifications(callback);
  }

  /**
   * Attaches a listener to remote or local notification events while the app
   * is running in the foreground or the background.
   *
   * See https://reactnative.dev/docs/pushnotificationios.html#addeventlistener
   */
  static addEventListener(type: PushNotificationEventName, handler: Function) {
    invariant(
      type === 'notification' ||
        type === 'register' ||
        type === 'registrationError' ||
        type === 'localNotification',
      'PushNotificationIOS only supports `notification`, `register`, `registrationError`, and `localNotification` events',
    );
    let listener;
    if (type === 'notification') {
      listener = PushNotificationEmitter.addListener(
        DEVICE_NOTIF_EVENT,
        notifData => {
          handler(new PushNotificationIOS(notifData));
        },
      );
    } else if (type === 'localNotification') {
      listener = PushNotificationEmitter.addListener(
        DEVICE_LOCAL_NOTIF_EVENT,
        notifData => {
          handler(new PushNotificationIOS(notifData));
        },
      );
    } else if (type === 'register') {
      listener = PushNotificationEmitter.addListener(
        NOTIF_REGISTER_EVENT,
        registrationInfo => {
          handler(registrationInfo.deviceToken);
        },
      );
    } else if (type === 'registrationError') {
      listener = PushNotificationEmitter.addListener(
        NOTIF_REGISTRATION_ERROR_EVENT,
        errorInfo => {
          handler(errorInfo);
        },
      );
    }
    _notifHandlers.set(type, listener);
  }

  /**
   * Removes the event listener. Do this in `componentWillUnmount` to prevent
   * memory leaks.
   *
   * See https://reactnative.dev/docs/pushnotificationios.html#removeeventlistener
   */
  static removeEventListener(
    type: PushNotificationEventName,
    handler: Function,
  ) {
    invariant(
      type === 'notification' ||
        type === 'register' ||
        type === 'registrationError' ||
        type === 'localNotification',
      'PushNotificationIOS only supports `notification`, `register`, `registrationError`, and `localNotification` events',
    );
    const listener = _notifHandlers.get(type);
    if (!listener) {
      return;
    }
    listener.remove();
    _notifHandlers.delete(type);
  }

  /**
   * Requests notification permissions from iOS, prompting the user's
   * dialog box. By default, it will request all notification permissions, but
   * a subset of these can be requested by passing a map of requested
   * permissions.
   *
   * See https://reactnative.dev/docs/pushnotificationios.html#requestpermissions
   */
  static requestPermissions(permissions?: {
    alert?: boolean,
    badge?: boolean,
    sound?: boolean,
    ...
  }): Promise<{
    alert: boolean,
    badge: boolean,
    sound: boolean,
    ...
  }> {
    let requestedPermissions = {
      alert: true,
      badge: true,
      sound: true,
    };
    if (permissions) {
      requestedPermissions = {
        alert: !!permissions.alert,
        badge: !!permissions.badge,
        sound: !!permissions.sound,
      };
    }
    invariant(
      NativePushNotificationManagerIOS,
      'PushNotificationManager is not available.',
    );
    return NativePushNotificationManagerIOS.requestPermissions(
      requestedPermissions,
    );
  }

  /**
   * Unregister for all remote notifications received via Apple Push Notification service.
   *
   * See https://reactnative.dev/docs/pushnotificationios.html#abandonpermissions
   */
  static abandonPermissions() {
    invariant(
      NativePushNotificationManagerIOS,
      'PushNotificationManager is not available.',
    );
    NativePushNotificationManagerIOS.abandonPermissions();
  }

  /**
   * See what push permissions are currently enabled. `callback` will be
   * invoked with a `permissions` object.
   *
   * See https://reactnative.dev/docs/pushnotificationios.html#checkpermissions
   */
  static checkPermissions(callback: Function) {
    invariant(typeof callback === 'function', 'Must provide a valid callback');
    invariant(
      NativePushNotificationManagerIOS,
      'PushNotificationManager is not available.',
    );
    NativePushNotificationManagerIOS.checkPermissions(callback);
  }

  /**
   * This method returns a promise that resolves to either the notification
   * object if the app was launched by a push notification, or `null` otherwise.
   *
   * See https://reactnative.dev/docs/pushnotificationios.html#getinitialnotification
   */
  static getInitialNotification(): Promise<?PushNotificationIOS> {
    invariant(
      NativePushNotificationManagerIOS,
      'PushNotificationManager is not available.',
    );
    return NativePushNotificationManagerIOS.getInitialNotification().then(
      notification => {
        return notification && new PushNotificationIOS(notification);
      },
    );
  }

  /**
   * You will never need to instantiate `PushNotificationIOS` yourself.
   * Listening to the `notification` event and invoking
   * `getInitialNotification` is sufficient
   *
   */
  constructor(nativeNotif: Object) {
    this._data = {};
    this._remoteNotificationCompleteCallbackCalled = false;
    this._isRemote = nativeNotif.remote;
    if (this._isRemote) {
      this._notificationId = nativeNotif.notificationId;
    }

    if (nativeNotif.remote) {
      // Extract data from Apple's `aps` dict as defined:
      // https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html
      Object.keys(nativeNotif).forEach(notifKey => {
        const notifVal = nativeNotif[notifKey];
        if (notifKey === 'aps') {
          this._alert = notifVal.alert;
          this._sound = notifVal.sound;
          this._badgeCount = notifVal.badge;
          this._category = notifVal.category;
          this._contentAvailable = notifVal['content-available'];
          this._threadID = notifVal['thread-id'];
        } else {
          this._data[notifKey] = notifVal;
        }
      });
    } else {
      // Local notifications aren't being sent down with `aps` dict.
      this._badgeCount = nativeNotif.applicationIconBadgeNumber;
      this._sound = nativeNotif.soundName;
      this._alert = nativeNotif.alertBody;
      this._data = nativeNotif.userInfo;
      this._category = nativeNotif.category;
    }
  }

  /**
   * This method is available for remote notifications that have been received via:
   * `application:didReceiveRemoteNotification:fetchCompletionHandler:`
   *
   * See https://reactnative.dev/docs/pushnotificationios.html#finish
   */
  finish(fetchResult: string) {
    if (
      !this._isRemote ||
      !this._notificationId ||
      this._remoteNotificationCompleteCallbackCalled
    ) {
      return;
    }
    this._remoteNotificationCompleteCallbackCalled = true;

    invariant(
      NativePushNotificationManagerIOS,
      'PushNotificationManager is not available.',
    );
    NativePushNotificationManagerIOS.onFinishRemoteNotification(
      this._notificationId,
      fetchResult,
    );
  }

  /**
   * An alias for `getAlert` to get the notification's main message string
   */
  getMessage(): ?string | ?Object {
    // alias because "alert" is an ambiguous name
    return this._alert;
  }

  /**
   * Gets the sound string from the `aps` object
   *
   * See https://reactnative.dev/docs/pushnotificationios.html#getsound
   */
  getSound(): ?string {
    return this._sound;
  }

  /**
   * Gets the category string from the `aps` object
   *
   * See https://reactnative.dev/docs/pushnotificationios.html#getcategory
   */
  getCategory(): ?string {
    return this._category;
  }

  /**
   * Gets the notification's main message from the `aps` object
   *
   * See https://reactnative.dev/docs/pushnotificationios.html#getalert
   */
  getAlert(): ?string | ?Object {
    return this._alert;
  }

  /**
   * Gets the content-available number from the `aps` object
   *
   * See https://reactnative.dev/docs/pushnotificationios.html#getcontentavailable
   */
  getContentAvailable(): ContentAvailable {
    return this._contentAvailable;
  }

  /**
   * Gets the badge count number from the `aps` object
   *
   * See https://reactnative.dev/docs/pushnotificationios.html#getbadgecount
   */
  getBadgeCount(): ?number {
    return this._badgeCount;
  }

  /**
   * Gets the data object on the notif
   *
   * See https://reactnative.dev/docs/pushnotificationios.html#getdata
   */
  getData(): ?Object {
    return this._data;
  }

  /**
   * Gets the thread ID on the notif
   *
   * See https://reactnative.dev/docs/pushnotificationios.html#getthreadid
   */
  getThreadID(): ?string {
    return this._threadID;
  }
}

module.exports = PushNotificationIOS;


text:
import samples_repository
import numpy as np
import matplotlib.pyplot as plt

ALPHABET_LOW = ["g","p","q","s_bassa"]
ALPHABET_HIGH = ["d_alta","s_alta","b","f","h","l"]
ALPHABET_MID = ["a","c","d_mediana","e","i","m","n","o","r","s_mediana","t","u"]
ALPHABET_ALL = ["a","c","d_mediana","e","i","m","n","o","r","s_mediana","t","u",\
                "d_alta","s_alta","b","f","h","l","g","p","q","s_bassa"]

pos_neg_ratio=1.0
train_test_ratio=6.0/7.0
neg_labeled_height_ratio = 1.0/2.0

def split_by_ratio(array, ratio):
    first_half_size, second_half_size = calc_ratio(len(array), ratio)
    first_half, second_half = split(array, first_half_size)
    assert len(first_half) == first_half_size
    assert len(second_half) == second_half_size
    assert (len(first_half) + len(second_half)) == len(array)
    return (first_half, second_half)

def calc_ratio(val, ratio):
    first_half_size = int(val*ratio)
    second_half_size = val - first_half_size
    assert (first_half_size + second_half_size) == val
    return (first_half_size, second_half_size)

def split(array, index):
    first_half = array[:index]
    second_half = array[index:]
    return (first_half, second_half)

def generate_positive_and_negative_labeled(char, pos_neg_ratio=pos_neg_ratio, train_test_ratio=train_test_ratio, verbose=1):
    # Calcolo i samples e le labels positivi per il training e il test
    positive_samples = samples_repository.get_all_positive_samples_by_char(char)
    positive_samples_train, positive_samples_test = split_by_ratio(positive_samples, train_test_ratio)
    positive_samples_train_labels = np.ones(positive_samples_train.shape[0], dtype='uint8')
    positive_samples_test_labels = np.ones(positive_samples_test.shape[0], dtype='uint8')

    if verbose == 1:
        print ("Trovati", positive_samples.shape[0], "esempi positivi per il carattere", char.upper(), ".")
        print ("Campioni di training:", positive_samples_train.shape[0], "\tCampioni di test:", positive_samples_test.shape[0])

    # Calolo i samples negativi e le labels per il training e per il test
    neg_samples_n = int(positive_samples.shape[0]*pos_neg_ratio)
    negative_samples = samples_repository.get_n_negative_labeled_samples_by_char(char, neg_samples_n)
    negative_samples_train, negative_samples_test = split_by_ratio(negative_samples, train_test_ratio)
    negative_samples_train_labels = np.zeros(negative_samples_train.shape[0], dtype='uint8')
    negative_samples_test_labels = np.zeros(negative_samples_test.shape[0], dtype='uint8')

    if verbose == 1:
        print ("Richiesti", neg_samples_n, "esempi negativi: trovati", negative_samples.shape[0], "generici.")

    assert neg_samples_n == negative_samples.shape[0]

    train_imgs = np.append(positive_samples_train, negative_samples_train, axis=0)
    train_labels = np.append(positive_samples_train_labels, negative_samples_train_labels, axis=0)

    if verbose == 1:
        print ("Numero totale di campioni di training:", train_imgs.shape[0])

    test_imgs = np.append(positive_samples_test, negative_samples_test, axis=0)
    test_labels = np.append(positive_samples_test_labels, negative_samples_test_labels, axis=0)

    if verbose == 1:
        print ("Numero totale di campioni di test:", test_imgs.shape[0])

    return (train_imgs, train_labels, test_imgs, test_labels)

def generate_half_labeled_half_height(char, char_type,
                                      pos_neg_ratio=pos_neg_ratio, train_test_ratio=train_test_ratio,
                                      neg_labeled_height_ratio=neg_labeled_height_ratio):

    # Calcolo i samples e le labels positivi per il training e il test
    positive_samples = samples_repository.get_all_positive_samples_by_char(char)
    positive_samples_train, positive_samples_test = split_by_ratio(positive_samples, train_test_ratio)
    positive_samples_train_labels = np.ones(positive_samples_train.shape[0], dtype='uint8')
    positive_samples_test_labels = np.ones(positive_samples_test.shape[0], dtype='uint8')

    print ("Trovati", positive_samples.shape[0], "esempi positivi per il carattere", char.upper(), ".")
    print ("Campioni di training:", positive_samples_train.shape[0], "\tCampioni di test:", positive_samples_test.shape[0])

    # Calolo i samples negativi e le labels per il training e per il test
    neg_samples_n = int(positive_samples.shape[0]*pos_neg_ratio)
    # divisi in generici e per altezza
    neg_labeled_samples_n, neg_height_samples_n = calc_ratio(neg_samples_n, neg_labeled_height_ratio)
    neg_labeled_samples = samples_repository.get_n_negative_labeled_samples_by_char(char, neg_labeled_samples_n)
    neg_height_samples = samples_repository.get_n_negative_samples_by_height_and_char(char, char_type, neg_height_samples_n)

    print ("Richiesti", neg_samples_n, "esempi negativi: trovati", neg_labeled_samples.shape[0], "generici e", neg_height_samples.shape[0], "per altezza.")

    assert neg_labeled_samples_n == neg_labeled_samples.shape[0]
    assert neg_height_samples_n == neg_height_samples.shape[0]

    neg_labeled_samples_train, neg_labeled_samples_test = split_by_ratio(neg_labeled_samples, train_test_ratio)
    neg_height_samples_train , neg_height_samples_test = split_by_ratio(neg_height_samples, train_test_ratio)

    print ("Samples negativi generici in training:", neg_labeled_samples_train.shape[0], "\tin test:", neg_labeled_samples_test.shape[0])
    print ("Samples negativi per altezza in training:", neg_height_samples_train.shape[0], "\tin test:", neg_height_samples_test.shape[0])

    neg_samples_train = np.append(neg_labeled_samples_train, neg_height_samples_train, axis=0)
    neg_samples_test = np.append(neg_labeled_samples_test, neg_height_samples_test, axis=0)
    neg_samples_train_labels = np.zeros(neg_samples_train.shape[0], dtype='uint8')
    neg_samples_test_labels = np.zeros(neg_samples_test.shape[0], dtype='uint8')

    print ("Campioni di training:", neg_samples_train.shape[0], "\tCampioni di test:", neg_samples_test.shape[0])

    train_imgs = np.append(positive_samples_train, neg_samples_train, axis=0)
    train_labels = np.append(positive_samples_train_labels, neg_samples_train_labels, axis=0)

    print ("Numero totale di campioni di training:", train_imgs.shape[0])

    test_imgs = np.append(positive_samples_test, neg_samples_test, axis=0)
    test_labels = np.append(positive_samples_test_labels, neg_samples_test_labels, axis=0)

    print ("Numero totale di campioni di test:", test_imgs.shape[0])

    return (train_imgs, train_labels, test_imgs, test_labels)

def generate_all_for_char_with_class(char, classification,
                                     train_test_ratio=train_test_ratio, verbose=1):

    # Calcolo i samples e le labels positivi per il training e il test
    positive_samples = samples_repository.get_all_positive_samples_by_char(char)
    positive_samples_train, positive_samples_test = split_by_ratio(positive_samples, train_test_ratio)
    positive_samples_train_labels = np.empty(positive_samples_train.shape[0], dtype='uint8')
    positive_samples_train_labels.fill(classification)
    positive_samples_test_labels = np.empty(positive_samples_test.shape[0], dtype='uint8')
    positive_samples_test_labels.fill(classification)

    if(verbose == 1):
        print ("Trovati", positive_samples.shape[0], "esempi positivi per il carattere", char.upper(), ".")
        print ("Campioni di training:", positive_samples_train.shape[0], "\tCampioni di test:", positive_samples_test.shape[0])

    train_imgs = positive_samples_train
    train_labels = positive_samples_train_labels # not actually labels, it's the class

    if(verbose == 1):
        print ("Numero totale di campioni di training:", train_imgs.shape[0])

    test_imgs = positive_samples_test
    test_labels = positive_samples_test_labels

    if(verbose == 1):
        print ("Numero totale di campioni di test:", test_imgs.shape[0])

    return (train_imgs, train_labels, test_imgs, test_labels)

def generate_all_chars_with_class(chars = ALPHABET_ALL,
                                  train_test_ratio=train_test_ratio, plot=False, verbose=1):

    sizes = np.zeros(len(chars))

    classifications = range(len(chars)) # this way chars[classification] = "a" if classification == 0

    (train_imgs, train_class, test_imgs, test_class) = generate_all_for_char_with_class(chars[0],\
                                                                                classifications[0], \
                                                                                verbose=verbose)
    sizes[0] = train_imgs.shape[0] + test_imgs.shape[0];

    for i in classifications:
        if (i>0):
            (train_imgs_prov, train_class_prov, test_imgs_prov, test_class_prov) = \
                                                            generate_all_for_char_with_class(chars[i],\
                                                            classifications[i], verbose=verbose)

            sizes[i] = train_imgs_prov.shape[0] + train_imgs_prov.shape[0]

            train_imgs = np.append(train_imgs, train_imgs_prov, axis=0)
            train_class = np.append(train_class, train_class_prov, axis=0)
            test_imgs = np.append(test_imgs, test_imgs_prov, axis=0)
            test_class = np.append(test_class, test_class_prov, axis=0)

    chars = np.asarray(chars)

    if plot:
        plt.plot(sizes, 'ro')
        plt.xticks(classifications, chars, rotation='vertical')
        plt.margins(0.1)
        plt.subplots_adjust(bottom=0.15)
        plt.show()

    return (train_imgs, train_class, test_imgs, test_class, chars)

def generate_all_chars_with_same_class(chars = ALPHABET_ALL, classification=0,
                                       train_test_ratio=train_test_ratio, plot=False, verbose=1):

    sizes = np.zeros(len(chars))

    classifications = range(len(chars)) # this way chars[classification] = "a" if classification == 0

    (train_imgs, train_class, test_imgs, test_class) = generate_all_for_char_with_class(chars[0],\
                                                                                classification, \
                                                                                verbose=verbose)
    sizes[0] = train_imgs.shape[0] + test_imgs.shape[0];

    for i in classifications:
        if (i>0):
            (train_imgs_prov, train_class_prov, test_imgs_prov, test_class_prov) = \
                                                            generate_all_for_char_with_class(chars[i],\
                                                            classification, verbose=verbose)

            sizes[i] = train_imgs_prov.shape[0] + train_imgs_prov.shape[0]

            train_imgs = np.append(train_imgs, train_imgs_prov, axis=0)
            train_class = np.append(train_class, train_class_prov, axis=0)
            test_imgs = np.append(test_imgs, test_imgs_prov, axis=0)
            test_class = np.append(test_class, test_class_prov, axis=0)

    chars = np.asarray(chars)

    if plot:
        plt.plot(sizes, 'ro')
        plt.xticks(classifications, chars, rotation='vertical')
        plt.margins(0.1)
        plt.subplots_adjust(bottom=0.15)
        plt.show()

    return (train_imgs, train_class, test_imgs, test_class, chars)

# Returns a dataset of bad cutted letters, useful for build a classificator that discriminate good cutted letters
# from bad cutted letters
def generate_bad_letters_of_chosen_chars(chars=ALPHABET_ALL, n_sample_for_class_width=100, split_ratio=0.7, verbose=0, plot=True):

    images = []

    yAxis = []

    for letter in chars:
        datas = samples_repository.get_n_negative_samples_by_width_and_char(letter, n_sample_for_class_width, verbose = verbose)
        yAxis.append(len(datas))
        images.extend(datas)

    images_len = len(images)
    split_value = int(images_len*split_ratio)

    indexes = [i for i in range(images_len)]
    np.random.shuffle(indexes)

    images = np.array(images)

    if plot:
        plt.plot(yAxis, 'ro')
        plt.xticks(np.arange(len(chars)),chars, rotation='vertical')
        plt.margins(0.1)
        plt.subplots_adjust(bottom=0.15)
        plt.show()

    return (images[indexes[:split_value]], images[indexes[split_value:]])

def generate_dataset_for_segmentator(verbose=0, plot=True, label_pos_class=1, label_neg_class=0):
    (X_train_Pos, y_train_Pos, X_test_Pos, y_test_Pos, _) = generate_all_chars_with_same_class(verbose=verbose, plot=plot, classification=label_pos_class)
    (X_train_Neg, X_test_Neg) = generate_bad_letters_of_chosen_chars(n_sample_for_class_width = 5000, plot=plot, verbose=verbose)

    X_train = []
    X_train.extend(X_train_Pos)
    X_train.extend(X_train_Neg)

    X_test = []
    X_test.extend(X_test_Pos)
    X_test.extend(X_test_Neg)

    y_train_Neg = [label_neg_class] * len(X_train_Neg)
    y_test_Neg = [label_neg_class] * len(X_test_Neg)

    y_train = []
    y_train.extend(y_train_Pos)
    y_train.extend(y_train_Neg)

    y_test = []
    y_test.extend(y_test_Pos)
    y_test.extend(y_test_Neg)

    X_train = np.array(X_train)
    X_test = np.array(X_test)
    y_train = np.array(y_train)
    y_test = np.array(y_test)

    return (X_train, y_train, X_test, y_test)


text:
using System.Collections.Generic;
using DICOMcloud;

namespace DICOMcloud.DataAccess
{
    public interface IObjectStorageDataAccess
    {
        void StoreInstance        ( IObjectId objectId, IEnumerable<IDicomDataParameter> parameters, InstanceMetadata data ) ;
        void StoreInstanceMetadata( IObjectId objectId, InstanceMetadata data ) ;

        bool DeleteInstance ( IObjectId instance );
        bool DeleteStudy    ( IStudyId  study    );
        bool DeleteSeries   ( ISeriesId series   );

        IEnumerable<InstanceMetadata> GetStudyMetadata    ( IStudyId study );
        IEnumerable<InstanceMetadata> GetSeriesMetadata   ( ISeriesId series );
        InstanceMetadata              GetInstanceMetadata ( IObjectId instance ) ;

    }
}


text:
using Moq;
using Moq.Protected;
using NUnit.Framework;
using Stylet;
using System;
using System.Threading.Tasks;

namespace StyletUnitTests
{
    [TestFixture]
    public class ConductorNavigatingTests
    {
        public interface IMyScreen : IScreen, IDisposable
        { }

        private class MyConductor : Conductor<IScreen>.StackNavigation
        {
            public bool CanCloseValue = true;
            public override async Task<bool> CanCloseAsync()
            {
                return this.CanCloseValue && await base.CanCloseAsync();
            }
        }

        private MyConductor conductor;

        [SetUp]
        public void SetUp()
        {
            this.conductor = new MyConductor();
        }

        [Test]
        public void ActiveItemIsNullBeforeAnyItemsActivated()
        {
            Assert.IsNull(this.conductor.ActiveItem);
            Assert.That(this.conductor.GetChildren(), Is.EquivalentTo(new IScreen[] { null }));
        }

        [Test]
        public void InitialActivateSetsItemAsActiveItem()
        {
            var screen = new Mock<IScreen>();
            this.conductor.ActivateItem(screen.Object);
            Assert.AreEqual(screen.Object, this.conductor.ActiveItem);
        }

        [Test]
        public void InitialActivateDoesNotActivateItemIfConductorIsNotActive()
        {
            var screen = new Mock<IScreen>();
            this.conductor.ActivateItem(screen.Object);
            screen.Verify(x => x.Activate(), Times.Never);
        }

        [Test]
        public void InitialActivateActivatesItemIfConductorIsActive()
        {
            ((IScreenState)this.conductor).Activate();
            var screen = new Mock<IScreen>();
            this.conductor.ActivateItem(screen.Object);
            screen.Verify(x => x.Activate());
        }

        [Test]
        public void InitialActivateDeactivatesItemIfConductorIsDeactivated()
        {
            var screen = new Mock<IScreen>();
            this.conductor.ActivateItem(screen.Object);
            screen.Verify(x => x.Deactivate());
        }

        [Test]
        public void ActivatesActiveItemWhenActivated()
        {
            var screen = new Mock<IScreen>();
            this.conductor.ActivateItem(screen.Object);
            screen.Verify(x => x.Activate(), Times.Never);

            ((IScreenState)this.conductor).Activate();
            screen.Verify(x => x.Activate());
        }

        [Test]
        public void DeactivatesActiveItemWhenDeactivated()
        {
            ((IScreenState)this.conductor).Activate();
            var screen = new Mock<IScreen>();
            this.conductor.ActivateItem(screen.Object);
            ((IScreenState)this.conductor).Deactivate();
            screen.Verify(x => x.Deactivate());
        }

        [Test]
        public void ActivateDeactivatesPreviousItemIfConductorIsActiveAndPreviousItemCanClose()
        {
            var screen1 = new Mock<IScreen>();
            var screen2 = new Mock<IScreen>();
            ((IScreenState)this.conductor).Activate();
            this.conductor.ActivateItem(screen1.Object);
            screen1.Setup(x => x.CanCloseAsync()).Returns(Task.FromResult(true));
            this.conductor.ActivateItem(screen2.Object);
            screen1.Verify(x => x.Deactivate());
        }

        [Test]
        public void ActivatingCurrentScreenReactivatesScreen()
        {
            var screen = new Mock<IMyScreen>();
            ((IScreenState)this.conductor).Activate();
            this.conductor.ActivateItem(screen.Object);
            this.conductor.ActivateItem(screen.Object);
            screen.Verify(x => x.Activate(), Times.Exactly(2));
            screen.Verify(x => x.Close(), Times.Never);
            screen.Verify(x => x.Dispose(), Times.Never);
        }

        [Test]
        public void CloseItemDoesNothingIfToldToDeactiveInactiveItem()
        {
            var screen1 = new Mock<IMyScreen>();
            var screen2 = new Mock<IMyScreen>();
            ((IScreenState)this.conductor).Activate();
            this.conductor.ActivateItem(screen1.Object);
            this.conductor.CloseItem(screen2.Object);

            screen1.Verify(x => x.Close(), Times.Never);
            screen1.Verify(x => x.Dispose(), Times.Never);
            screen2.Verify(x => x.Activate(), Times.Never);
        }

        [Test]
        public void DeactiveDoesNotChangeActiveItem()
        {
            var screen = new Mock<IScreen>();
            ((IScreenState)this.conductor).Activate();
            this.conductor.ActivateItem(screen.Object);
            this.conductor.DeactivateItem(screen.Object);

            screen.Verify(x => x.Deactivate());
            Assert.AreEqual(this.conductor.ActiveItem, screen.Object);
        }

        [Test]
        public void ActivateSetsConductorAsItemsParent()
        {
            var screen = new Mock<IScreen>();
            this.conductor.ActivateItem(screen.Object);
            screen.VerifySet(x => x.Parent = this.conductor);
        }

        [Test]
        public void SettingActiveItemActivatesItem()
        {
            var screen = new Mock<IScreen>();
            ((IScreenState)this.conductor).Activate();
            this.conductor.ActiveItem =screen.Object;
            screen.Verify(x => x.Activate());
            Assert.AreEqual(this.conductor.ActiveItem, screen.Object);
        }

        [Test]
        public void CloseClosesAndRemovesItemsParent()
        {
            var screen = new Mock<IScreen>();
            screen.Setup(x => x.CanCloseAsync()).Returns(Task.FromResult(true));
            screen.Setup(x => x.Parent).Returns(this.conductor);
            this.conductor.ActivateItem(screen.Object);
            this.conductor.CloseItem(screen.Object);
            screen.Verify(x => x.Close());
            screen.VerifySet(x => x.Parent = null);
        }

        [Test]
        public void CloseDisposesItemIfDisposeChildrenIsTrue()
        {
            var screen = new Mock<IMyScreen>();
            screen.Setup(x => x.CanCloseAsync()).Returns(Task.FromResult(true));
            this.conductor.ActivateItem(screen.Object);
            this.conductor.CloseItem(screen.Object);
            screen.Verify(x => x.Dispose());
        }

        [Test]
        public void CloseDoesNotDisposeItemIfDisposeChildrenIsFalse()
        {
            var screen = new Mock<IMyScreen>();
            screen.Setup(x => x.CanCloseAsync()).Returns(Task.FromResult(true));
            this.conductor.DisposeChildren = false;
            this.conductor.ActivateItem(screen.Object);
            this.conductor.CloseItem(screen.Object);
            screen.Verify(x => x.Dispose(), Times.Never);
        }

        [Test]
        public void CanCloseReturnsTrueIfNoActiveItem()
        {
            Assert.IsTrue(this.conductor.CanCloseAsync().Result);
        }

        [Test]
        public void CanCloseReturnsAllItemsCanClose()
        {
            var screen1 = new Mock<IScreen>();
            var screen2 = new Mock<IScreen>();
            this.conductor.ActivateItem(screen1.Object);
            this.conductor.ActivateItem(screen2.Object);
            screen1.Setup(x => x.CanCloseAsync()).Returns(Task.FromResult(true));
            screen2.Setup(x => x.CanCloseAsync()).Returns(Task.FromResult(false));
            Assert.IsFalse(this.conductor.CanCloseAsync().Result);
        }

        [Test]
        public void ConductorCanCloseAsyncCallsCanCloseOnSelfBeforeChildren()
        {
            var screen = new Mock<IScreen>();

            this.conductor.ActivateItem(screen.Object);
            this.conductor.CanCloseValue = false;

            Assert.IsFalse(this.conductor.CanCloseAsync().Result);

            screen.Verify(x => x.CanCloseAsync(), Times.Never());
        }

        [Test]
        public void DeactivatingActiveItemGoesBack()
        {
            ((IScreenState)this.conductor).Activate();
            var screen1 = new Mock<IScreen>();
            var screen2 = new Mock<IScreen>();

            this.conductor.ActivateItem(screen1.Object);
            screen1.Verify(x => x.Activate());

            this.conductor.ActivateItem(screen2.Object);
            screen2.Verify(x => x.Activate());

            this.conductor.DeactivateItem(screen2.Object);
            screen2.Verify(x => x.Deactivate(), Times.Once);
            screen1.Verify(x => x.Activate(), Times.Once);
        }

        [Test]
        public void ClearClosesAllItemsExceptCurrent()
        {
            ((IScreenState)this.conductor).Activate();
            var screen1 = new Mock<IScreen>();
            var screen2 = new Mock<IScreen>();
            this.conductor.ActivateItem(screen1.Object);
            this.conductor.ActivateItem(screen2.Object);
            this.conductor.Clear();

            Assert.AreEqual(screen2.Object, this.conductor.ActiveItem);

            screen2.Setup(x => x.CanCloseAsync()).Returns(Task.FromResult(true));
            this.conductor.GoBack();
            Assert.IsNull(this.conductor.ActiveItem);
        }

        [Test]
        public void CloseClosesAllItems()
        {
            var screen1 = new Mock<IMyScreen>();
            screen1.SetupGet(x => x.Parent).Returns(this.conductor);
            var screen2 = new Mock<IMyScreen>();
            screen2.SetupGet(x => x.Parent).Returns(this.conductor);
            this.conductor.ActivateItem(screen1.Object);
            this.conductor.ActivateItem(screen2.Object);

            ((IScreenState)this.conductor).Close();
            screen1.Verify(x => x.Close());
            screen1.VerifySet(x => x.Parent = null);
            screen2.Verify(x => x.Close());
            screen2.VerifySet(x => x.Parent = null);
        }

        [Test]
        public void ClosesItemIfItemRequestsClose()
        {
            var screen = new Mock<IMyScreen>();
            this.conductor.ActivateItem(screen.Object);
            screen.Setup(x => x.CanCloseAsync()).Returns(Task.FromResult(true));
            ((IChildDelegate)this.conductor).CloseItem(screen.Object);

            screen.Verify(x => x.Close());
            Assert.Null(this.conductor.ActiveItem);
        }

        [Test]
        public void NestedActivateItemsResultsInLastActivatedItemActive()
        {
            var screen1 = new Mock<Screen>() { CallBase = true };
            var screen2 = new Screen();
            screen1.Protected().Setup("OnActivate").Callback(() => conductor.ActivateItem(screen2));
            ((IScreenState)this.conductor).Activate();

            this.conductor.ActivateItem(screen1.Object);

            Assert.AreEqual(screen2, this.conductor.ActiveItem);
        }
    }
}


text:
"""Implements the standard thread module, using greenthreads."""
from six.moves import _thread as __thread
import six
from eventlet.support import greenlets as greenlet
from eventlet import greenthread
from eventlet.semaphore import Semaphore as LockType
import sys

__patched__ = ['get_ident', 'start_new_thread', 'start_new', 'allocate_lock',
               'allocate', 'exit', 'interrupt_main', 'stack_size', '_local',
               'LockType', '_count']

error = __thread.error
__threadcount = 0

if six.PY3:
    def _set_sentinel():
        # TODO this is a dummy code, reimplementing this may be needed:
        # https://hg.python.org/cpython/file/b5e9bc4352e1/Modules/_threadmodule.c#l1203
        return allocate_lock()

    TIMEOUT_MAX = __thread.TIMEOUT_MAX

def _count():
    return __threadcount

def get_ident(gr=None):
    if gr is None:
        return id(greenlet.getcurrent())
    else:
        return id(gr)

def __thread_body(func, args, kwargs):
    global __threadcount
    __threadcount += 1
    try:
        func(*args, **kwargs)
    finally:
        __threadcount -= 1

def start_new_thread(function, args=(), kwargs=None):
    if (sys.version_info >= (3, 4)
            and getattr(function, '__module__', '') == 'threading'
            and hasattr(function, '__self__')):
        # Since Python 3.4, threading.Thread uses an internal lock
        # automatically released when the python thread state is deleted.
        # With monkey patching, eventlet uses green threads without python
        # thread state, so the lock is not automatically released.
        #
        # Wrap _bootstrap_inner() to release explicitly the thread state lock
        # when the thread completes.
        thread = function.__self__
        bootstrap_inner = thread._bootstrap_inner

        def wrap_bootstrap_inner():
            try:
                bootstrap_inner()
            finally:
                # The lock can be cleared (ex: by a fork())
                if thread._tstate_lock is not None:
                    thread._tstate_lock.release()

        thread._bootstrap_inner = wrap_bootstrap_inner

    kwargs = kwargs or {}
    g = greenthread.spawn_n(__thread_body, function, args, kwargs)
    return get_ident(g)

start_new = start_new_thread

def allocate_lock(*a):
    return LockType(1)

allocate = allocate_lock

def exit():
    raise greenlet.GreenletExit

exit_thread = __thread.exit_thread

def interrupt_main():
    curr = greenlet.getcurrent()
    if curr.parent and not curr.parent.dead:
        curr.parent.throw(KeyboardInterrupt())
    else:
        raise KeyboardInterrupt()

if hasattr(__thread, 'stack_size'):
    __original_stack_size__ = __thread.stack_size

    def stack_size(size=None):
        if size is None:
            return __original_stack_size__()
        if size > __original_stack_size__():
            return __original_stack_size__(size)
        else:
            pass
            # not going to decrease stack_size, because otherwise other greenlets in
            # this thread will suffer

from eventlet.corolocal import local as _local


text:
package nl.jpoint.vertx.deploy.agent.util;

public enum ApplicationDeployState {
    OK,
    ERROR;

    public static ApplicationDeployState map(String state) {
        if (state == null || state.isEmpty()) {
            return OK;
        }
        try {
            return ApplicationDeployState.valueOf(state.toUpperCase());
        } catch (IllegalArgumentException e) {
            return OK;
        }
    }
}


text:
class Mu
module Curl
class Error < StandardError
    def initialize json={}
        super json['reason'] || "Hmmm, something went wrong. Try again in a little bit?"
    end

    class Authorize < Error
        attr_reader :scheme, :host, :port, :uuid

        def initialize json
            @scheme = json['scheme']
            @host   = json['host']
            @port   = json['port']
            @uuid   = json['uuid']
            super
        end
    end

    class Region < Error
        attr_reader :region

        def initialize json
            @region = json['region']
            super
        end
    end

    class DNS < Region
    end

    class Connect < Region
        def initialize json
            json['reason'] = "Can't connect to this server"
            super
        end
    end

    class Timeout < Region
        def initialize json
            json['reason'] = "Response timed out. Try increasing --timeout"
            super
        end
    end

    class Status < Region
        def initialize json
            json['reason'] = "Assertion on status failed"
            super
        end
    end
end
end # Curl
end # Mu


text:
from JumpScale import j

class LoaderBase(object):
    """
    is loader for all objects e.g. for all actors or spaces
    """

    def __init__(self, type, objectClass):
        """
        """
        self.id2object = {}
        self.__dict__["%ss" % type] = self.id2object
        self.type = type
        self._objectClass = objectClass

    def getLoaderFromId(self, id):
        id = id.lower()
        if id in self.id2object:
            return self.id2object[id]
        else:
            raise RuntimeError("Could not find loader with id %s" % id)

    def removeLoader(self, id):
        id = id.lower()
        if id in self.id2object:
            self.id2object.pop(id)
            loader = self.__dict__["%ss" % self.type]
            if id in loader:
                loader.pop(id)

    # def _getSystemLoaderForUsersGroups(self):
    #     lba = LoaderBaseObject("")
    #     userspath = j.sal.fs.joinPaths(j.portal.server.active.cfgdir, 'users.cfg')
    #     if not j.sal.fs.exists(userspath):
    #         ini = j.config.getInifile(userspath)
    #         ini.addSection('admin')
    #         ini.addParam('admin', 'passwd', 'admin')
    #         ini.addParam('admin', 'groups', 'admin')
    #         ini.addParam('admin', 'reset', '1')
    #         ini.addSection('guest')
    #         ini.addParam('guest', 'passwd', '')
    #         ini.addParam('guest', 'groups', 'guest')
    #         ini.addParam('guest', 'reset', '1')

    #     lba.processUsers(j.portal.server.active.cfgdir)

    def scan(self, path, reset=False):
        """
        path can be 1 path or list of paths
        """
        paths = path
        if isinstance(path, str):
            paths = [path]

        for path in paths:
            items = [j.sal.fs.pathNormalize(item.replace(".%s" % self.type, "") + "/") for
                     item in j.sal.fs.listDirsInDir(path, True, False, True)
                     if j.sal.fs.getDirName(item + "/", True) == ".%s" % self.type]

            # find objects like spaces,actors,...
            for path in items:
                object = self._objectClass()
                result = object.loadFromDisk(path, reset)
                if result != False:
                    print(("load %s %s" % (self.type, path)))
                    self.id2object[object.model.id.lower()] = object

class Model():
    pass

class LoaderBaseObject():
    """
    is loader for 1 object
    """

    def __init__(self, type):
        self.model = Model()
        if type == "actor":
            self.model.application = ""
            self.model.actor = ""
        self.model.id = ""
        self.model.path = ""
        self.model.acl = {}  # dict with key the group or username; and the value is a string
        self.type = type
        self.model.hidden = False

    def _createDefaults(self, path):
        if self.type == "space":
            macros = j.sal.fs.joinPaths(j.portalloader.getTemplatesPath(), "space/.macros")
            dest = j.sal.fs.joinPaths(path, ".macros")
            j.sal.fs.copyDirTree(macros, dest, keepsymlinks=False, deletefirst=False, overwriteFiles=False)
            if (j.sal.fs.exists("%s/home.md" % path) or j.sal.fs.exists("%s/Home.md" % path)):
                space = "spaceMD"
            elif (j.sal.fs.exists("%s/home.wiki" % path) or j.sal.fs.exists("%s/Home.wiki" % path)):
                space = "spaceWIKI"
            spaces = j.sal.fs.joinPaths(j.portalloader.getTemplatesPath(), "space/.%s" % space)
            dest = j.sal.fs.joinPaths(path, ".space")
            j.sal.fs.copyDirTree(spaces, dest, keepsymlinks=False, deletefirst=False, overwriteFiles=False)
        else:
            src = j.sal.fs.joinPaths(j.portalloader.getTemplatesPath(), "%s" % self.type)
            dest = j.sal.fs.joinPaths(path)
            j.sal.fs.copyDirTree(src, dest, keepsymlinks=False, deletefirst=False, overwriteFiles=False)

    def _loadFromDisk(self, path, reset=False):
        # path=path.replace("\\","/")
        # print "loadfromdisk:%s" % path

        # remove old cfg and write new one with only id
        cfgpath = j.sal.fs.joinPaths(path, ".%s" % self.type, "main.cfg")

        if not j.sal.fs.exists(cfgpath):
            self.createDefaults(path)

        if j.sal.fs.exists(cfgpath):
            ini = j.tools.inifile.open(cfgpath)
        else:
            ini = j.tools.inifile.new(cfgpath)
        ini.addSection("main")
        name = j.sal.fs.getDirName(path, True)
        ini.setParam("main", "id", name)
        ini.write()

        self.model.id = name
        if ini.checkParam('main', 'name'):
            self.model.name = ini.getValue('main', 'name')
        else:
            self.model.name = name

        if ini.checkParam('main', 'hidden'):
            self.model.hidden = ini.getBooleanValue('main', 'hidden')
        self.model.path = path
        self.processAcl()

    def processAcl(self, cfgdir=""):
        # populate acl
        if cfgdir == "":
            cfgfile = j.sal.fs.joinPaths(self.model.path, ".%s" % self.type, "acl.cfg")
        else:
            cfgfile = j.sal.fs.joinPaths(cfgdir, "acl.cfg")

        lines = j.sal.fs.fileGetContents(cfgfile).split("\n")
        for line in lines:
            line = line.strip()
            if line.strip() == "" or line[0] == "#":
                continue
            for separator in ["=", ":"]:
                if line.find(separator) != -1:
                    name, rights = line.split(separator)
                    name = name.lower().strip()
                    rights = str(rights.lower().strip())
                    self.model.acl[name] = rights
                    # print "ACE:%s %s"%(name,rights)

    def deleteOnDisk(self):
        if j.sal.fs.isLink(self.model.path):
            actualpath = j.sal.fs.readlink(self.model.path)
            j.sal.fs.removeDirTree(actualpath)
        j.sal.fs.removeDirTree(self.model.path)

    def reset(self):
        self.loadFromDisk(self.model.path, reset=True)


text:
using Fpm.ProfileData.Entities.LookUps;
using Fpm.ProfileData.Entities.Profile;
using NHibernate;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Fpm.ProfileData
{
    public class ProfilesWriter : ProfilesReader, IProfilesWriter
    {
        public ProfilesWriter(ISessionFactory sessionFactory)
            : base(sessionFactory)
        { }

        public void ReorderIndicatorSequence(int groupId, int areaTypeId)
        {
            var groupings = GetGroupingsByGroupIdAndAreaTypeId(groupId, areaTypeId);
            new GroupingListProcessor().RecalculateSequences(groupings);
            UpdateGroupingList(groupings);
        }

        public void UpdateTargetConfig(TargetConfig target)
        {
            var fromDatabase = GetTargetById(target.Id);
            CopyTargetConfig(target, fromDatabase);
            UpdateObject(fromDatabase);
        }

        public TargetConfig NewTargetConfig(TargetConfig target)
        {
            var newTarget = new TargetConfig();
            CopyTargetConfig(target, newTarget);
            var id = SaveNewObject(newTarget);
            return GetTargetById(id);
        }

        public void UpdateGroupingMetadata(GroupingMetadata groupingMetadata)
        {
            GroupingMetadata fromDatabase = GetGroupingMetadata(groupingMetadata.GroupId);

            // Copy properties to object retrieved from the database
            fromDatabase.GroupName = groupingMetadata.GroupName;
            fromDatabase.Sequence = groupingMetadata.Sequence;

            UpdateObject(fromDatabase);
        }

        public void UpdateGroupingList(IList<Grouping> groupings)
        {
            ITransaction transaction = null;
            try
            {
                transaction = CurrentSession.BeginTransaction();
                foreach (var grouping in groupings)
                {
                    CurrentSession.Update(grouping);
                }
                transaction.Commit();
            }
            catch (Exception)
            {
                if (transaction != null && transaction.WasRolledBack == false)
                {
                    transaction.Rollback();
                }
                throw;
            }
        }

        public GroupingMetadata NewGroupingMetadata(string name, int sequence, int profileId)
        {
            var groupingMetadata = new GroupingMetadata
            {
                GroupName = name,
                Sequence = sequence,
                Description = name,
                ProfileId = profileId
            };

            var id = SaveNewObject(groupingMetadata);

            return GetGroupingMetadata(id);
        }

        public void DeleteOverriddenIndicatorMetadataTextValue(IndicatorMetadataTextValue indicatorMetadataTextValue)
        {
            var profileId = indicatorMetadataTextValue.ProfileId;

            // Profile will only be defined if overridden metadata is defined
            if (profileId.HasValue)
            {
                var fromDatabase = GetMetadataTextValueForAnIndicatorById(
                    indicatorMetadataTextValue.IndicatorId, profileId.Value);
                DeleteObject(fromDatabase);
            }
        }

        public int NewIndicatorMetadataTextValue(IndicatorMetadataTextValue indicatorMetadataTextValue)
        {
            var id = SaveNewObject(indicatorMetadataTextValue);
            return id;
        }

        public void DeleteTargetConfig(TargetConfig target)
        {
            DeleteObject(GetTargetById(target.Id));
        }

        public void NewTargetConfigAudit(TargetConfigAudit targetAudit)
        {
            SaveNewObject(targetAudit);
        }

        public ContentItem NewContentItem(int profileId, string contentKey, string description, bool isPlainTextContent, string content)
        {
            var contentItem = new ContentItem
            {
                ProfileId = profileId,
                Content = content,
                ContentKey = contentKey,
                Description = description,
                IsPlainText = isPlainTextContent
            };

            var id = SaveNewObject(contentItem);
            return GetContentItem(id);
        }

        public ContentAudit NewContentAudit(ContentAudit contentAudit)
        {
            var id = SaveNewObject(contentAudit);
            return GetContentAuditFromId(id);
        }

        public void UpdateContentItem(ContentItem contentItem)
        {
            var fromDatabase = GetContentItem(contentItem.Id);

            // Copy properties to object retrieved from the database
            fromDatabase.Content = contentItem.Content;
            fromDatabase.ContentKey = contentItem.ContentKey;
            fromDatabase.Description = contentItem.Description;
            fromDatabase.IsPlainText = contentItem.IsPlainText;

            UpdateObject(fromDatabase);
        }

        public void DeleteContentItem(string contentKey, int profileId)
        {
            var contentItem = GetContentItem(contentKey, profileId);
            DeleteObject(contentItem);
        }

        public int NewDocument(Document doc)
        {
            var id = SaveNewObject(doc);
            return id;
        }

        public void UpdateDocument(Document doc)
        {
            UpdateObject(doc);
        }

        public void DeleteDocument(Document doc)
        {
            DeleteObject(doc);
        }

        public void DeleteGroupingMetadata(int groupId)
        {
            DeleteObject(GetGroupingMetadata(groupId));
        }

        public void ReorderDomainSequence(IList<int> groupIds)
        {
            var groupingMetadataList = GetGroupingMetadataList(groupIds.ToList());

            var sequenceNumber = 1;
            foreach (var groupingMetadata in groupingMetadataList)
            {
                groupingMetadata.Sequence = sequenceNumber++;
            }

            UpdateObjectList(groupingMetadataList.Cast<object>().ToList());
        }

        public void DeleteIndicatorMetatdataById(IndicatorMetadata indicatorMetadata)
        {
            if (indicatorMetadata == null)
            {
                return;
            }

            ITransaction transaction = null;
            try
            {
                transaction = CurrentSession.BeginTransaction();

                // Delete indicator metadata
                CurrentSession.Delete(indicatorMetadata);

                // Delete core data
                var queryString = "delete from CoreDataSet d where d.IndicatorId = :indicatorId";
                IQuery q = CurrentSession.CreateQuery(queryString);
                q.SetParameter("indicatorId", indicatorMetadata.IndicatorId);
                q.ExecuteUpdate();

                // Delete text values
                var sqlQuery = CurrentSession.CreateSQLQuery(
                    "delete from IndicatorMetadataTextValues where indicatorid = " +
                    indicatorMetadata.IndicatorId);
                sqlQuery.ExecuteUpdate();

                transaction.Commit();
            }
            catch (Exception)
            {
                if (transaction != null && transaction.WasRolledBack == false)
                {
                    transaction.Rollback();
                }
                throw;
            }
        }

        public void UpdateCategoryType(CategoryType categoryType)
        {
            var fromDatabase = GetCategoryType(categoryType.Id);

            // Copy properties to object retrieved from the database
            fromDatabase.Name = categoryType.Name;
            fromDatabase.ShortName = categoryType.ShortName;
            fromDatabase.Description = categoryType.Description;
            fromDatabase.Notes = categoryType.Notes;

            UpdateObject(fromDatabase);
        }

        private void DeleteObject(object objectToDelete)
        {
            if (objectToDelete != null)
            {
                ITransaction transaction = null;
                try
                {
                    transaction = CurrentSession.BeginTransaction();
                    CurrentSession.Delete(objectToDelete);
                    transaction.Commit();
                }
                catch (Exception)
                {
                    if (transaction != null && transaction.WasRolledBack == false)
                    {
                        transaction.Rollback();
                    }
                    throw;
                }
            }
        }

        private int SaveNewObject(object objectToSave)
        {
            int id;
            ITransaction transaction = null;
            try
            {
                transaction = CurrentSession.BeginTransaction();
                id = (int)CurrentSession.Save(objectToSave);
                transaction.Commit();
            }
            catch (Exception)
            {
                if (transaction != null && transaction.WasRolledBack == false)
                {
                    transaction.Rollback();
                }
                throw;
            }
            return id;
        }

        private void UpdateObject(object objectToUpdate)
        {
            ITransaction transaction = null;
            try
            {
                transaction = CurrentSession.BeginTransaction();
                CurrentSession.Update(objectToUpdate);
                transaction.Commit();
            }
            catch (Exception)
            {
                if (transaction != null && transaction.WasRolledBack == false)
                {
                    transaction.Rollback();
                }
                throw;
            }
        }

        private void UpdateObjectList(List<object> objectsToUpdate)
        {
            ITransaction transaction = null;
            try
            {
                transaction = CurrentSession.BeginTransaction();
                foreach (var objectToUpdate in objectsToUpdate)
                {
                    CurrentSession.Update(objectToUpdate);
                }

                transaction.Commit();
            }
            catch (Exception)
            {
                if (transaction != null && transaction.WasRolledBack == false)
                {
                    transaction.Rollback();
                }
                throw;
            }
        }

        private static void CopyTargetConfig(TargetConfig @from, TargetConfig to)
        {
            to.Description = @from.Description;
            to.LowerLimit = @from.LowerLimit;
            to.UpperLimit = @from.UpperLimit;
            to.PolarityId = @from.PolarityId;
            to.LegendHtml = @from.LegendHtml;
            to.UseCIsForLimitComparison = @from.UseCIsForLimitComparison;
        }
    }
}


text:
package org.entirej.applicationframework.tmt.application.interfaces;

/**
 * The form chosen event is fired when the used chooses a form to open
 * <p>
 * The form chosen event should be used to inform EJ that a form should be
 * opened. Once EJ has opened the form, a form opened event is fired
 */
public interface EJTMTFormChosenListener
{
    /**
     * Called by the form selector whenever a new form is chosen.
     *
     * @param pEvent
     *            The event containing the chosen form name
     */
    public void formChosen(EJTMTFormChosenEvent event);
}


text:
import json
import os
import pickle
import shutil
import tempfile
from unittest import TestCase
from unittest.mock import patch

import numpy as np
from datasets import Dataset

from transformers import is_faiss_available
from transformers.models.bart.configuration_bart import BartConfig
from transformers.models.bart.tokenization_bart import BartTokenizer
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES
from transformers.models.dpr.configuration_dpr import DPRConfig
from transformers.models.dpr.tokenization_dpr import DPRQuestionEncoderTokenizer
from transformers.models.rag.configuration_rag import RagConfig
from transformers.models.rag.retrieval_rag import CustomHFIndex, RagRetriever
from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES
from transformers.testing_utils import (
    require_datasets,
    require_faiss,
    require_sentencepiece,
    require_tokenizers,
    require_torch,
)

if is_faiss_available():
    import faiss

@require_faiss
@require_datasets
class RagRetrieverTest(TestCase):
    def setUp(self):
        self.tmpdirname = tempfile.mkdtemp()
        self.retrieval_vector_size = 8

        # DPR tok
        vocab_tokens = [
            "[UNK]",
            "[CLS]",
            "[SEP]",
            "[PAD]",
            "[MASK]",
            "want",
            "##want",
            "##ed",
            "wa",
            "un",
            "runn",
            "##ing",
            ",",
            "low",
            "lowest",
        ]
        dpr_tokenizer_path = os.path.join(self.tmpdirname, "dpr_tokenizer")
        os.makedirs(dpr_tokenizer_path, exist_ok=True)
        self.vocab_file = os.path.join(dpr_tokenizer_path, DPR_VOCAB_FILES_NAMES["vocab_file"])
        with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer:
            vocab_writer.write("".join([x + "\n" for x in vocab_tokens]))

        # BART tok
        vocab = [
            "l",
            "o",
            "w",
            "e",
            "r",
            "s",
            "t",
            "i",
            "d",
            "n",
            "\u0120",
            "\u0120l",
            "\u0120n",
            "\u0120lo",
            "\u0120low",
            "er",
            "\u0120lowest",
            "\u0120newer",
            "\u0120wider",
            "<unk>",
        ]
        vocab_tokens = dict(zip(vocab, range(len(vocab))))
        merges = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""]
        self.special_tokens_map = {"unk_token": "<unk>"}

        bart_tokenizer_path = os.path.join(self.tmpdirname, "bart_tokenizer")
        os.makedirs(bart_tokenizer_path, exist_ok=True)
        self.vocab_file = os.path.join(bart_tokenizer_path, BART_VOCAB_FILES_NAMES["vocab_file"])
        self.merges_file = os.path.join(bart_tokenizer_path, BART_VOCAB_FILES_NAMES["merges_file"])
        with open(self.vocab_file, "w", encoding="utf-8") as fp:
            fp.write(json.dumps(vocab_tokens) + "\n")
        with open(self.merges_file, "w", encoding="utf-8") as fp:
            fp.write("\n".join(merges))

    def get_dpr_tokenizer(self) -> DPRQuestionEncoderTokenizer:
        return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname, "dpr_tokenizer"))

    def get_bart_tokenizer(self) -> BartTokenizer:
        return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname, "bart_tokenizer"))

    def tearDown(self):
        shutil.rmtree(self.tmpdirname)

    def get_dummy_dataset(self):
        dataset = Dataset.from_dict(
            {
                "id": ["0", "1"],
                "text": ["foo", "bar"],
                "title": ["Foo", "Bar"],
                "embeddings": [np.ones(self.retrieval_vector_size), 2 * np.ones(self.retrieval_vector_size)],
            }
        )
        dataset.add_faiss_index("embeddings", string_factory="Flat", metric_type=faiss.METRIC_INNER_PRODUCT)
        return dataset

    def get_dummy_canonical_hf_index_retriever(self):
        dataset = self.get_dummy_dataset()
        config = RagConfig(
            retrieval_vector_size=self.retrieval_vector_size,
            question_encoder=DPRConfig().to_dict(),
            generator=BartConfig().to_dict(),
        )
        with patch("transformers.models.rag.retrieval_rag.load_dataset") as mock_load_dataset:
            mock_load_dataset.return_value = dataset
            retriever = RagRetriever(
                config,
                question_encoder_tokenizer=self.get_dpr_tokenizer(),
                generator_tokenizer=self.get_bart_tokenizer(),
            )
        return retriever

    def get_dummy_custom_hf_index_retriever(self, from_disk: bool):
        dataset = self.get_dummy_dataset()
        config = RagConfig(
            retrieval_vector_size=self.retrieval_vector_size,
            question_encoder=DPRConfig().to_dict(),
            generator=BartConfig().to_dict(),
            index_name="custom",
        )
        if from_disk:
            config.passages_path = os.path.join(self.tmpdirname, "dataset")
            config.index_path = os.path.join(self.tmpdirname, "index.faiss")
            dataset.get_index("embeddings").save(os.path.join(self.tmpdirname, "index.faiss"))
            dataset.drop_index("embeddings")
            dataset.save_to_disk(os.path.join(self.tmpdirname, "dataset"))
            del dataset
            retriever = RagRetriever(
                config,
                question_encoder_tokenizer=self.get_dpr_tokenizer(),
                generator_tokenizer=self.get_bart_tokenizer(),
            )
        else:
            retriever = RagRetriever(
                config,
                question_encoder_tokenizer=self.get_dpr_tokenizer(),
                generator_tokenizer=self.get_bart_tokenizer(),
                index=CustomHFIndex(config.retrieval_vector_size, dataset),
            )
        return retriever

    def get_dummy_legacy_index_retriever(self):
        dataset = Dataset.from_dict(
            {
                "id": ["0", "1"],
                "text": ["foo", "bar"],
                "title": ["Foo", "Bar"],
                "embeddings": [np.ones(self.retrieval_vector_size + 1), 2 * np.ones(self.retrieval_vector_size + 1)],
            }
        )
        dataset.add_faiss_index("embeddings", string_factory="Flat", metric_type=faiss.METRIC_INNER_PRODUCT)

        index_file_name = os.path.join(self.tmpdirname, "hf_bert_base.hnswSQ8_correct_phi_128.c_index")
        dataset.save_faiss_index("embeddings", index_file_name + ".index.dpr")
        pickle.dump(dataset["id"], open(index_file_name + ".index_meta.dpr", "wb"))

        passages_file_name = os.path.join(self.tmpdirname, "psgs_w100.tsv.pkl")
        passages = {sample["id"]: [sample["text"], sample["title"]] for sample in dataset}
        pickle.dump(passages, open(passages_file_name, "wb"))

        config = RagConfig(
            retrieval_vector_size=self.retrieval_vector_size,
            question_encoder=DPRConfig().to_dict(),
            generator=BartConfig().to_dict(),
            index_name="legacy",
            index_path=self.tmpdirname,
        )
        retriever = RagRetriever(
            config, question_encoder_tokenizer=self.get_dpr_tokenizer(), generator_tokenizer=self.get_bart_tokenizer()
        )
        return retriever

    def test_canonical_hf_index_retriever_retrieve(self):
        n_docs = 1
        retriever = self.get_dummy_canonical_hf_index_retriever()
        hidden_states = np.array(
            [np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)], dtype=np.float32
        )
        retrieved_doc_embeds, doc_ids, doc_dicts = retriever.retrieve(hidden_states, n_docs=n_docs)
        self.assertEqual(retrieved_doc_embeds.shape, (2, n_docs, self.retrieval_vector_size))
        self.assertEqual(len(doc_dicts), 2)
        self.assertEqual(sorted(doc_dicts[0]), ["embeddings", "id", "text", "title"])
        self.assertEqual(len(doc_dicts[0]["id"]), n_docs)
        self.assertEqual(doc_dicts[0]["id"][0], "1")  # max inner product is reached with second doc
        self.assertEqual(doc_dicts[1]["id"][0], "0")  # max inner product is reached with first doc
        self.assertListEqual(doc_ids.tolist(), [[1], [0]])

    def test_canonical_hf_index_retriever_save_and_from_pretrained(self):
        retriever = self.get_dummy_canonical_hf_index_retriever()
        with tempfile.TemporaryDirectory() as tmp_dirname:
            with patch("transformers.models.rag.retrieval_rag.load_dataset") as mock_load_dataset:
                mock_load_dataset.return_value = self.get_dummy_dataset()
                retriever.save_pretrained(tmp_dirname)
                retriever = RagRetriever.from_pretrained(tmp_dirname)
                self.assertIsInstance(retriever, RagRetriever)
                hidden_states = np.array(
                    [np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)], dtype=np.float32
                )
                out = retriever.retrieve(hidden_states, n_docs=1)
                self.assertTrue(out is not None)

    def test_custom_hf_index_retriever_retrieve(self):
        n_docs = 1
        retriever = self.get_dummy_custom_hf_index_retriever(from_disk=False)
        hidden_states = np.array(
            [np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)], dtype=np.float32
        )
        retrieved_doc_embeds, doc_ids, doc_dicts = retriever.retrieve(hidden_states, n_docs=n_docs)
        self.assertEqual(retrieved_doc_embeds.shape, (2, n_docs, self.retrieval_vector_size))
        self.assertEqual(len(doc_dicts), 2)
        self.assertEqual(sorted(doc_dicts[0]), ["embeddings", "id", "text", "title"])
        self.assertEqual(len(doc_dicts[0]["id"]), n_docs)
        self.assertEqual(doc_dicts[0]["id"][0], "1")  # max inner product is reached with second doc
        self.assertEqual(doc_dicts[1]["id"][0], "0")  # max inner product is reached with first doc
        self.assertListEqual(doc_ids.tolist(), [[1], [0]])

    def test_custom_hf_index_retriever_save_and_from_pretrained(self):
        retriever = self.get_dummy_custom_hf_index_retriever(from_disk=False)
        with tempfile.TemporaryDirectory() as tmp_dirname:
            retriever.save_pretrained(tmp_dirname)
            retriever = RagRetriever.from_pretrained(tmp_dirname)
            self.assertIsInstance(retriever, RagRetriever)
            hidden_states = np.array(
                [np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)], dtype=np.float32
            )
            out = retriever.retrieve(hidden_states, n_docs=1)
            self.assertTrue(out is not None)

    def test_custom_hf_index_retriever_retrieve_from_disk(self):
        n_docs = 1
        retriever = self.get_dummy_custom_hf_index_retriever(from_disk=True)
        hidden_states = np.array(
            [np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)], dtype=np.float32
        )
        retrieved_doc_embeds, doc_ids, doc_dicts = retriever.retrieve(hidden_states, n_docs=n_docs)
        self.assertEqual(retrieved_doc_embeds.shape, (2, n_docs, self.retrieval_vector_size))
        self.assertEqual(len(doc_dicts), 2)
        self.assertEqual(sorted(doc_dicts[0]), ["embeddings", "id", "text", "title"])
        self.assertEqual(len(doc_dicts[0]["id"]), n_docs)
        self.assertEqual(doc_dicts[0]["id"][0], "1")  # max inner product is reached with second doc
        self.assertEqual(doc_dicts[1]["id"][0], "0")  # max inner product is reached with first doc
        self.assertListEqual(doc_ids.tolist(), [[1], [0]])

    def test_custom_hf_index_retriever_save_and_from_pretrained_from_disk(self):
        retriever = self.get_dummy_custom_hf_index_retriever(from_disk=True)
        with tempfile.TemporaryDirectory() as tmp_dirname:
            retriever.save_pretrained(tmp_dirname)
            retriever = RagRetriever.from_pretrained(tmp_dirname)
            self.assertIsInstance(retriever, RagRetriever)
            hidden_states = np.array(
                [np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)], dtype=np.float32
            )
            out = retriever.retrieve(hidden_states, n_docs=1)
            self.assertTrue(out is not None)

    def test_legacy_index_retriever_retrieve(self):
        n_docs = 1
        retriever = self.get_dummy_legacy_index_retriever()
        hidden_states = np.array(
            [np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)], dtype=np.float32
        )
        retrieved_doc_embeds, doc_ids, doc_dicts = retriever.retrieve(hidden_states, n_docs=n_docs)
        self.assertEqual(retrieved_doc_embeds.shape, (2, n_docs, self.retrieval_vector_size))
        self.assertEqual(len(doc_dicts), 2)
        self.assertEqual(sorted(doc_dicts[0]), ["text", "title"])
        self.assertEqual(len(doc_dicts[0]["text"]), n_docs)
        self.assertEqual(doc_dicts[0]["text"][0], "bar")  # max inner product is reached with second doc
        self.assertEqual(doc_dicts[1]["text"][0], "foo")  # max inner product is reached with first doc
        self.assertListEqual(doc_ids.tolist(), [[1], [0]])

    def test_legacy_hf_index_retriever_save_and_from_pretrained(self):
        retriever = self.get_dummy_legacy_index_retriever()
        with tempfile.TemporaryDirectory() as tmp_dirname:
            retriever.save_pretrained(tmp_dirname)
            retriever = RagRetriever.from_pretrained(tmp_dirname)
            self.assertIsInstance(retriever, RagRetriever)
            hidden_states = np.array(
                [np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)], dtype=np.float32
            )
            out = retriever.retrieve(hidden_states, n_docs=1)
            self.assertTrue(out is not None)

    @require_torch
    @require_tokenizers
    @require_sentencepiece
    def test_hf_index_retriever_call(self):
        import torch

        n_docs = 1
        retriever = self.get_dummy_canonical_hf_index_retriever()
        question_input_ids = [[5, 7], [10, 11]]
        hidden_states = np.array(
            [np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)], dtype=np.float32
        )
        out = retriever(question_input_ids, hidden_states, prefix=retriever.config.generator.prefix, n_docs=n_docs)
        context_input_ids, context_attention_mask, retrieved_doc_embeds = (
            out["context_input_ids"],
            out["context_attention_mask"],
            out["retrieved_doc_embeds"],
        )
        self.assertEqual(retrieved_doc_embeds.shape, (2, n_docs, self.retrieval_vector_size))
        self.assertIsInstance(context_input_ids, list)
        self.assertIsInstance(context_attention_mask, list)
        self.assertIsInstance(retrieved_doc_embeds, np.ndarray)

        out = retriever(
            question_input_ids,
            hidden_states,
            prefix=retriever.config.generator.prefix,
            n_docs=n_docs,
            return_tensors="pt",
        )
        context_input_ids, context_attention_mask, retrieved_doc_embeds, doc_ids = (  # noqa: F841
            out["context_input_ids"],
            out["context_attention_mask"],
            out["retrieved_doc_embeds"],
            out["doc_ids"],
        )
        self.assertEqual(retrieved_doc_embeds.shape, (2, n_docs, self.retrieval_vector_size))
        self.assertIsInstance(context_input_ids, torch.Tensor)
        self.assertIsInstance(context_attention_mask, torch.Tensor)
        self.assertIsInstance(retrieved_doc_embeds, torch.Tensor)


text:
launchCurlOrProtractor() {
    retryCount=1
    maxRetry=10
    httpUrl="http://localhost:8080"
    if [[ ("$JHIPSTER" == 'app-microservice-eureka') || ("$JHIPSTER" == 'app-microservice-consul') ]]; then
        httpUrl="http://localhost:8081/management/health"
    fi

    rep=$(curl -v "$httpUrl")
    status=$?
    while [ "$status" -ne 0 ] && [ "$retryCount" -le "$maxRetry" ]; do
        echo "[$(date)] Application not reachable yet. Sleep and retry - retryCount =" $retryCount "/" $maxRetry
        retryCount=$((retryCount+1))
        sleep 10
        rep=$(curl -v "$httpUrl")
        status=$?
    done

    if [ "$status" -ne 0 ]; then
        echo "[$(date)] Not connected after" $retryCount " retries."
        exit 1
    fi

    if [ "$PROTRACTOR" != 1 ]; then
        exit 0
    fi

    retryCount=0
    maxRetry=2
    until [ "$retryCount" -ge "$maxRetry" ]
    do
        result=0
        if [[ -f "gulpfile.js" ]]; then
            gulp itest --no-notification
        elif [[ -f "tsconfig.json" ]]; then
            yarn run e2e
        fi
        result=$?
        [ $result -eq 0 ] && break
        retryCount=$((retryCount+1))
        echo "e2e tests failed... retryCount =" $retryCount "/" $maxRetry
        sleep 15
    done
    exit $result
}

#-------------------------------------------------------------------------------
# Package UAA
#-------------------------------------------------------------------------------
if [ "$JHIPSTER" == "app-ng2-gateway-uaa" ]; then
    cd "$HOME"/uaa
    ./mvnw verify -DskipTests -P"$PROFILE"
fi

#-------------------------------------------------------------------------------
# Package the application
#-------------------------------------------------------------------------------
cd "$APP_FOLDER"

if [ -f "mvnw" ]; then
    ./mvnw verify -DskipTests -P"$PROFILE"
    mv target/*.war app.war
elif [ -f "gradlew" ]; then
    ./gradlew bootRepackage -P"$PROFILE" -x test
    mv build/libs/*.war app.war
else
    echo "No mvnw or gradlew"
    exit 0
fi
if [ $? -ne 0 ]; then
    echo "Error when packaging"
    exit 1
fi

#-------------------------------------------------------------------------------
# Run the application
#-------------------------------------------------------------------------------
if [ "$RUN_APP" == 1 ]; then
    if [ "$JHIPSTER" == "app-ng2-gateway-uaa" ]; then
        cd "$UAA_APP_FOLDER"
        java -jar target/*.war \
            --spring.profiles.active="$PROFILE" \
            --logging.level.io.github.jhipster.sample=ERROR \
            --logging.level.io.github.jhipster.travis=ERROR &
        sleep 80
    fi

    cd "$APP_FOLDER"
    java -jar app.war \
        --spring.profiles.active="$PROFILE" \
        --logging.level.io.github.jhipster.sample=ERROR \
        --logging.level.io.github.jhipster.travis=ERROR &
    sleep 40

    launchCurlOrProtractor
fi