text:
Support

        Email Us

redpajama_set_name: RedPajamaGithub


text:
package org.apache.usergrid.rest.exceptions;

public class UnsupportedRestOperationException extends RuntimeException{

    public UnsupportedRestOperationException(String message ) {
        super(message);
    }

}


text:
layout: page
title: Links
excerpt: "Links zu Information zur RT 125"
image:
  feature: rt_125_close-up_2.jpg
---

## Informationen zur RT 125 finden Sie unter:

* [Wikipedia-Artikel "RT 125"](http://de.wikipedia.org/wiki/RT_125)
* [Englischer Wikipedia-Artikel "Harley-Davidson Hummer"](http://en.wikipedia.org/wiki/Harley-Davidson_Hummer)
* [1948 Harley-Davidson S-125](http://auto.howstuffworks.com/1948-harley-davidson-s-1251.htm)
* [Englischer Wikipedia-Artikel "BSA Bantam"](http://en.wikipedia.org/wiki/BSA_Bantam)
* [Archivmartial auf sachsen.de](http://www.archiv.sachsen.de/6354.htm)


text:
var addToUnscopables = require('../internals/add-to-unscopables');

addToUnscopables('flatMap');


text:
namespace graphics
{
  struct VertexStream;
  /// Single attribute of vertex.
  struct VertexAttrib
  {
    ESemantic m_semantic;
    size_t m_offset;
    EDataType m_elemType;
    size_t m_elemCount;
    size_t m_stride;

    VertexAttrib(ESemantic semantic,
                 size_t offset,
                 EDataType elemType,
                 size_t elemCount,
                 size_t stride);

    void initStream(VertexStream * vs,
                    unsigned char * v,
                    unsigned stride) const;
  };

  /// Vertex structure declaration.
  class VertexDecl
  {
  private:
    vector<VertexAttrib> m_attrs;
    size_t m_elemSize;
  public:
    /// constructor.
    VertexDecl(VertexAttrib const * attrs, size_t cnt);
    /// get the number of attributes.
    size_t attrCount() const;
    /// get vertex attribute.
    VertexAttrib const * getAttr(size_t i) const;
    /// size of single element.
    size_t elemSize() const;
    /// initialize vertex stream
    void initStream(VertexStream * vs, unsigned char * v) const;
  };
}


text:
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

require_once(APPPATH."models/ModeloList/Listacategoriasproduto.php");
require_once(APPPATH."models/ModeloList/Listacidades.php");

class Cidade_categoria extends MY_Model {

    public $id_cidade_categoria;
    public $id_cidade;
    public $id_categoria;

    public function  __construct() {
        parent::__construct($this);
    }

    public function insert() {
        $this->set_post($this);
        $this->id_cidade_categoria = null;
        if ($this->db->insert('cidade_categoria', $this))
            $this->id_cidade_categoria = $this->db->insert_id();
        if (empty($this->id_cidade_categoria))
          return $this->db->error()['message'];
        return $this->id_cidade_categoria;
    }

    public function update() {
        $this->set_post($this);
        $this->db->update('cidade_categoria', $this, array('id_cidade_categoria' => $this->id_cidade_categoria));
        if ($this->db->error()['code'] > 0)
          $this->set_log_error_db();
        $this->set_response_db('Alteração concluída com sucesso');
    }

    public function delete() {
        $this->set_post($this);
        $this->db->delete('cidade_categoria', $this, array('id_cidade_categoria' => $this->id_cidade_categoria));
        if ($this->db->error()['code'] > 0)
          $this->set_log_error_db();
        $this->set_response_db('Removido com sucesso');
    }

    protected function get_config_prop(){
        $this->id_categoria = isset($this->id_categoria) ? $this->get_categoria() : "";
        $this->id_cidade  = isset($this->id_cidade)  ? $this->get_cidade()  : "";
    }

    private function get_cidade(){
        $Listacidades = new Listacidades();
        return $Listacidades->get($this->id_cidade);
    }

    private function get_categoria(){
        $Listacategoriasproduto = new Listacategoriasproduto();
        return $Listacategoriasproduto->get($this->id_cidade);
    }
}


text:
package swarm.server.handlers.normal;

import java.util.logging.Level;
import java.util.logging.Logger;

import swarm.server.account.E_Role;
import swarm.server.account.UserSession;

import swarm.server.blobxn.BlobTransaction_CreateUser;
import swarm.server.data.blob.BlobException;
import swarm.server.data.blob.BlobManagerFactory;
import swarm.server.data.blob.E_BlobCacheLevel;
import swarm.server.data.blob.E_BlobTransactionType;
import swarm.server.data.blob.I_BlobManager;
import swarm.server.entities.ServerUser;
import swarm.server.session.SessionManager;
import swarm.server.transaction.A_DefaultRequestHandler;
import swarm.server.transaction.I_RequestHandler;
import swarm.server.transaction.TransactionContext;
import swarm.shared.app.BaseAppContext;
import swarm.shared.entities.A_Grid;
import swarm.shared.json.A_JsonFactory;
import swarm.shared.json.E_JsonKey;
import swarm.shared.json.I_JsonObject;
import swarm.shared.json.JsonHelper;
import swarm.shared.transaction.E_ResponseError;
import swarm.shared.transaction.TransactionRequest;
import swarm.shared.transaction.TransactionResponse;

public class getUserData extends A_DefaultRequestHandler
{
	private static final Logger s_logger = Logger.getLogger(getUserData.class.getName());

	public final boolean m_autoCreateHomeCell;
	public final int m_gridExpansionDelta;

	public getUserData(boolean autoCreateHomeCell, int gridExpansionDelta)
	{
		m_autoCreateHomeCell = autoCreateHomeCell;
		m_gridExpansionDelta = gridExpansionDelta;
	}

	@Override
	public void handleRequest(TransactionContext context, TransactionRequest request, TransactionResponse response)
	{
		if( !m_serverContext.sessionMngr.isAuthorized(request, response, E_Role.USER) )
		{
			return;
		}

		UserSession userSession = m_serverContext.sessionMngr.getSession(request, response);

		ServerUser user = null;

		I_BlobManager blobManager = m_serverContext.blobMngrFactory.create(E_BlobCacheLevel.PERSISTENT);

		//--- DRK > First try to just get the user with a straight read...should be successful most of the time.
		try
		{
			user = blobManager.getBlob(userSession, ServerUser.class);
		}
		catch(BlobException e)
		{
			response.setError(E_ResponseError.SERVICE_EXCEPTION);

			s_logger.log(Level.SEVERE, "Could not retrieve user due to exception.", e);

			return;
		}

		//--- DRK > If the read turned up empty, it means that the user hasn't been created yet, so we have to do that.
		//---		Most of the time this should be because the user is going through the sign up process.
		//---		It is possible however that when the user first signed up, something went wrong with the transaction,
		//---		so subsequent requests that should normally be pure reads end up having to retry user creation implicitly.
		boolean createdUser = false;
		if( user == null )
		{
			try
			{
				BlobTransaction_CreateUser createUserTransaction = new BlobTransaction_CreateUser(userSession, m_autoCreateHomeCell, m_gridExpansionDelta);
				createUserTransaction.perform(m_serverContext.blobMngrFactory, E_BlobTransactionType.MULTI_BLOB_TYPE, 5);

				//--- DRK > Not a huge fan of this method of letting client know that grid size changed.
				//---		Better would be if I could let client know through batch system, but I can't figure
				//---		out how to make that efficient without completely spaghettifying server code.
				if( createUserTransaction.didGridGrow() )
				{
					A_Grid dummyGrid = new A_Grid(createUserTransaction.getGridWidth(), createUserTransaction.getGridHeight())
					{
						@Override
						public void writeJson(I_JsonObject json_out, A_JsonFactory factory)
						{
							//--- DRK > Only sending down width and height so we don't overwrite other properties.
							factory.getHelper().putInt(json_out, E_JsonKey.gridWidth, this.getWidth());
							factory.getHelper().putInt(json_out, E_JsonKey.gridHeight, this.getHeight());
						}
					};

					dummyGrid.writeJson(response.getJsonArgs(), m_serverContext.jsonFactory);
				}

				user = createUserTransaction.getUser();
				createdUser = true;
			}
			catch(BlobException e)
			{
				response.setError(E_ResponseError.SERVICE_EXCEPTION);

				s_logger.log(Level.SEVERE, "Could not create user because of exception.", e);

				return;
			}
		}

		//--- DRK > Just being really anal here...should never be null by this point.
		if( user == null )
		{
			response.setError(E_ResponseError.SERVICE_EXCEPTION);

			s_logger.severe("User object came up null when it should have been initialized.");

			return;
		}

		m_serverContext.jsonFactory.getHelper().putBoolean(response.getJsonArgs(), E_JsonKey.createdUser, createdUser);
		user.writeJson(response.getJsonArgs(), m_serverContext.jsonFactory);
	}
}


text:
#include "screen.h"

#include "logtype.h"

#define MINESERVER_C_API
#include "plugin_api.h"

#include <cstdlib>
#include <ctime>
#include <iostream>
#include <stack>

// Constants
#define PLUGIN_NAME "cursesui"
const char* pluginName = PLUGIN_NAME;
const char* logSource = "plugin.screen";
const float pluginVersion = 1.0f;

enum
{
  LOG_TITLE,
  LOG_COMMAND,
  LOG_GENERAL,
  LOG_PLAYERS
};

// Variables
mineserver_pointer_struct* mineserver;
CursesScreen *screen;

std::string currentTimestamp(bool seconds)
{
  time_t currentTime = time(NULL);
  struct tm *Tm  = localtime(&currentTime);
  std::string timeStamp (asctime(Tm));
  timeStamp = timeStamp.substr(11, seconds ? 8 : 5);

  return timeStamp;
}

void CursesScreen::initWindows()
{
  // Work out our dimensions
  int titleHeight = 5;
  int logBar = titleHeight - 1;
  int commandHeight = 1;
  int commandBar = LINES - commandHeight - 1;
  int helpBar = commandBar - 1;
  int chatBar = (commandBar - logBar)/2 + logBar + 1;
  int logHeight = chatBar - logBar - 1;
  int chatHeight = helpBar - chatBar - 1;
  int playerWidth = 20;
  int playerHeight = commandBar - logBar - 1;

  // Create our windows
  // CursesScreen::createWindow(int width, int height, int startx, int starty)
  titleWin = createWindow(COLS, titleHeight, 0, 0);
  logWin = createWindow(COLS - (playerWidth + 1),
                        logHeight,
                        0,
                        logBar + 1);
  chatWin = createWindow(COLS - (playerWidth + 1),
                         chatHeight,
                         0,
                         chatBar + 1);
  playerWin = createWindow(playerWidth,
                           playerHeight,
                           COLS - playerWidth,
                           logBar + 1);
  commandWin = createWindow(COLS,
                            commandHeight,
                            0,
                            commandBar + 1);

  // Make sure nothing waits for input
  wtimeout(titleWin, 0);
  wtimeout(logWin, 0);
  wtimeout(chatWin, 0);
  wtimeout(commandWin, 0);
  wtimeout(playerWin, 0);
  nodelay(titleWin, true);
  nodelay(logWin, true);
  nodelay(chatWin, true);
  nodelay(commandWin, true);
  nodelay(playerWin, true);

  // Setup color if we haz it
  if (has_colors())
  {
    start_color();
    use_default_colors();
    init_pair(TEXT_COLOR_RED, COLOR_RED, -1);
    init_pair(TEXT_COLOR_GREEN, COLOR_GREEN, -1);
    init_pair(TEXT_COLOR_YELLOW, COLOR_YELLOW, -1);
    init_pair(TEXT_COLOR_BLUE, COLOR_BLUE, -1);
    init_pair(TEXT_COLOR_MAGENTA, COLOR_MAGENTA, -1);
    init_pair(TEXT_COLOR_CYAN, COLOR_CYAN, -1);
    init_pair(TEXT_COLOR_WHITE, COLOR_WHITE, -1);
    init_pair(TEXT_COLOR_INVERSE, COLOR_BLACK, COLOR_WHITE);

    wattron(titleWin, COLOR_PAIR(TEXT_COLOR_CYAN));
    wattron(playerWin, COLOR_PAIR(TEXT_COLOR_WHITE));
  }

  // Write our border lines on the regular stdscr
  attron(COLOR_PAIR(TEXT_COLOR_WHITE));

  /* Draw dividers */
  /* These mvaddch calls are cast to void to avoid an unused return value
     warning in clang. If there's a better way to do it, feel free to change
     things. */
  // log bar
  for (int x = 0; x < COLS; x++)
    (void)mvaddch(logBar, x, '=');

  // chat bar
  for(int x = 0; x < COLS - (playerWidth + 1); x++)
    (void)mvaddch(chatBar, x, '=');

  // help bar
  const char* helpStr = "Help:/help History:<UP>|<DOWN> Delete:<BACKSACE> CLEAR:<HOME>";
  mvaddstr(helpBar, 0, helpStr);

  // command bar
  for (int x = 0; x < COLS; x++)
    (void)mvaddch(commandBar, x, '=');

  // playerlist column divider
  for (int y = logBar + 1; y < commandBar; y++)
    (void)mvaddch(y, COLS - (playerWidth + 1), '|');

  attroff(COLOR_PAIR(TEXT_COLOR_MAGENTA));

  // Write the window labels
  attron(COLOR_PAIR(TEXT_COLOR_WHITE));
  attron(WA_BOLD);
  mvprintw(logBar, 2, " Log ");
  mvprintw(logBar, COLS - 15, " Players ");
  mvprintw(chatBar, 2, " Chat ");
  attroff(COLOR_PAIR(TEXT_COLOR_WHITE));
  attroff(WA_BOLD);
  refresh();

  // Now shove our logo in at the top
  log(LogType::LOG_INFO, "Title", "  /\\/\\ (_)_ __   ___ ___  ___ _ ____   _____ _ __ ");
  log(LogType::LOG_INFO, "Title", " /    \\| | '_ \\ / _ | __|/ _ \\ '__\\ \\ / / _ \\ '__|");
  log(LogType::LOG_INFO, "Title", "/ /\\/\\ \\ | | | |  __|__ \\  __/ |   \\ V /  __/ |   ");
  log(LogType::LOG_INFO, "Title", "\\/    \\/_|_| |_|\\___|___/\\___|_|    \\_/ \\___|_|  ");

  wmove(titleWin, logBar - 1, 50);
  wattron(titleWin, COLOR_PAIR(TEXT_COLOR_WHITE));
  wprintw(titleWin, ("v"+this->version).c_str());
  wattroff(titleWin, COLOR_PAIR(TEXT_COLOR_WHITE));
  wrefresh(titleWin);

  keypad(commandWin, true);

}

void CursesScreen::init(std::string version)
{
  this->version = version;
  commandBuf = "";

  initscr(); // Start NCurses
  timeout(0); // Non blocking
  //noecho();
  echo();
  refresh();

  CursesScreen::initWindows();
  CursesScreen::redrawPlayerList();
}

void CursesScreen::redraw()
{
  timeout(0);
  refresh();
  CursesScreen::initWindows();
  CursesScreen::redrawPlayerList();

  wclear(commandWin);
  waddstr(commandWin, commandBuf.c_str());
  wrefresh(commandWin);
}

std::string CursesScreen::prevCommand()
{
  std::string str = "";
  if (prevCommands.size() > 0)
  {
    str = prevCommands.top();
    prevCommands.pop();
    nextCommands.push(str);
  }
  return str;
}

std::string CursesScreen::nextCommand()
{
  std::string str = "";
  if (nextCommands.size() > 0)
  {
    str = nextCommands.top();
    nextCommands.pop();
    prevCommands.push(str);
  }
  return str;
}

void CursesScreen::addCommand(std::string str)
{
  while (!prevCommands.empty())
  {
    nextCommands.push(prevCommands.top());
    prevCommands.pop();
  }
  nextCommands.push(str);
}

/* This is where the keyboard interactions are handled. */
bool CursesScreen::hasCommand()
{
  bool running = true;
  std::string str = "";
  int c;

  do{
    c = wgetch(commandWin);
    switch(c)
    {
      case ERR:
      case KEY_RIGHT:
      case KEY_END:
        running = false;
        break;
      case KEY_RESIZE:
        CursesScreen::redraw();
        wdeleteln(commandWin);
        wclear(commandWin);
        waddstr(commandWin, commandBuf.c_str());
        running = false;
        break;
      case KEY_UP:
      case KEY_PPAGE:
        str = nextCommand();
        wdeleteln(commandWin);
        wclear(commandWin);
        if (str == "")
        {
          waddstr(commandWin, commandBuf.c_str());
        }
        else
        {
          waddstr(commandWin, str.c_str());
          commandBuf = str;
        }
        break;
      case KEY_DOWN:
      case KEY_NPAGE:
        str = prevCommand();
        wdeleteln(commandWin);
        wclear(commandWin);
        waddstr(commandWin, str.c_str());
        commandBuf = str;
        break;
      case KEY_ENTER:
      case '\n':
      case '\r':
        wdeleteln(commandWin);
        wclear(commandWin);
        command = commandBuf;
        addCommand(commandBuf);
        commandBuf = "";
        return true;
        break;
      case KEY_HOME:
        wdeleteln(commandWin);
        wclear(commandWin);
        commandBuf = "";
        running = false;
        break;
      case KEY_BACKSPACE:
      case KEY_LEFT:
      case KEY_SDC:
      case KEY_DC:
      case '\b':
        if (commandBuf.length() > 0)
          commandBuf.erase(commandBuf.length()-1,1);
        wdeleteln(commandWin);
        wclear(commandWin);
        waddstr(commandWin, commandBuf.c_str());
        running = false;
        break;
      default:
        commandBuf += c;
    }
  } while(running);

  return false;
}

std::string CursesScreen::getCommand()
{
  std::string str = command;
  command = "";
  return str;
}

WINDOW* CursesScreen::createWindow(int width, int height, int startx, int starty)
{
  WINDOW *local_win;

  local_win = newwin(height, width, starty, startx);
  scrollok(local_win, 1);    // Fine to scroll
  wrefresh(local_win);

  return local_win;
}

void CursesScreen::destroyWindow(WINDOW *local_win)
{
  /* box(local_win, ' ', ' '); : This won't produce the desired
   * result of erasing the window. It will leave it's four corners
   * and so an ugly remnant of window.
   */
  wborder(local_win, ' ', ' ', ' ',' ',' ',' ',' ',' ');
  /* The parameters taken are
   * 1. win: the window on which to operate
   * 2. ls: character to be used for the left side of the window
   * 3. rs: character to be used for the right side of the window
   * 4. ts: character to be used for the top side of the window
   * 5. bs: character to be used for the bottom side of the window
   * 6. tl: character to be used for the top left corner of the window
   * 7. tr: character to be used for the top right corner of the window
   * 8. bl: character to be used for the bottom left corner of the window
   * 9. br: character to be used for the bottom right corner of the window
   */
  wrefresh(local_win);
  delwin(local_win);
}

void CursesScreen::end()
{
  // Kill our windows
  destroyWindow(titleWin);
  destroyWindow(logWin);
  destroyWindow(chatWin);
  destroyWindow(playerWin);

  // Stop NCurses
  endwin();
}

void CursesScreen::log(LogType::LogType type, const std::string& source, const std::string& message)
{
  WINDOW *window;

  if (source == "Chat")
  {
    window = chatWin;
  }
  else if (source == "Command")
  {
    window = commandWin;
  }
  else if (source == "Players")
  {
    window = playerWin;
  }
  else if (source == "Title")
  {
    window = titleWin;
  }
  else
  {
    window = logWin;
  }

  // Set the color
  if (type == LogType::LOG_ERROR)
  {
    wattron(window, COLOR_PAIR(TEXT_COLOR_RED));
  }

  // Get the cursor so we can indent a bit
  int x, y;
  getyx(window, y, x);

  if (type != LogType::LOG_ERROR && (window == chatWin || window == logWin))
  {
    waddstr(window, "\n");
    wattron(window, WA_BOLD);
    waddstr(window, ("[" + currentTimestamp(true) + "] ").c_str());
    wattroff(window, WA_BOLD);
    waddstr(window, (message).c_str());
  }
  else if (window == titleWin || window == playerWin)
  {
    waddstr(window, (message).c_str());
    waddstr(window, "\n");
  }
  else
  {
    waddstr(window, "\n");
    waddstr(window, (message).c_str());
  }

  // Turn off color again
  if (type == LogType::LOG_ERROR)
  {
    wattroff(window, COLOR_PAIR(TEXT_COLOR_RED));
  }

  wrefresh(window);
}

#include <algorithm>

void CursesScreen::redrawPlayerList()
{
  // Clear the playerlist
  wclear(playerWin);

  // Now fill it up!
  if(usernames.size() == 0)
  {
    log(LogType::LOG_INFO, "Players", "No active players");
  }
  else
  {
    for (std::vector<std::string>::const_iterator username = usernames.begin();
         username != usernames.end();
         ++username)
    {
      log(LogType::LOG_INFO, "Players", *username);
    }
  }
}

void CursesScreen::updatePlayerList(bool joining, const char *username)
{
  // Update the list
  if (joining)
  {
    usernames.push_back(username);
  }
  else
  {
    std::vector<std::string>::iterator element = std::find(usernames.begin(), usernames.end(), std::string(username));

    if (element != usernames.end())
    {
      usernames.erase(element);
    }
  }

  // Redraw the list
  CursesScreen::redrawPlayerList();
}

bool logPost(int type, const char* source, const char* message)
{
  screen->log((LogType::LogType)type, source, message);
  return false;
}

static const unsigned int SERVER_CONSOLE_UID = -1;

bool checkForCommand()
{
  if (screen->hasCommand())
  {
    // Now handle this command as normal
    mineserver->chat.handleMessage("[Server]", screen->getCommand().c_str());
  }
  return false;
}

bool on_player_login(const char *username)
{
  screen->updatePlayerList(true, username);
  return false;
}

bool on_player_quit(const char *username)
{
  screen->updatePlayerList(false, username);
  return false;
}

PLUGIN_API_EXPORT void CALLCONVERSION cursesui_init(mineserver_pointer_struct* mineserver_temp)
{
  mineserver = mineserver_temp;

  if (mineserver->plugin.getPluginVersion(pluginName) > 0)
  {
    mineserver->logger.log(LogType::LOG_INFO, logSource, "The " PLUGIN_NAME " plugin is already loaded");
    return;
  }

  mineserver->plugin.setPluginVersion(pluginName, pluginVersion);

  screen = new CursesScreen();
  screen->init("1.2"); // TODO This should query mineserver for the version
  mineserver->plugin.addCallback("LogPost", reinterpret_cast<voidF>(logPost));
  mineserver->plugin.addCallback("Timer200", reinterpret_cast<voidF>(checkForCommand));
  mineserver->plugin.addCallback("PlayerLoginPost", reinterpret_cast<voidF>(on_player_login));
  mineserver->plugin.addCallback("PlayerQuitPost", reinterpret_cast<voidF>(on_player_quit));

  mineserver->logger.log(LogType::LOG_INFO, logSource, "Loaded " PLUGIN_NAME);
}

PLUGIN_API_EXPORT void CALLCONVERSION cursesui_shutdown(void)
{
  screen->end();
  //mineserver = NULL;
}


text:
namespace Llvm.NET.Instructions
{
    class VaArg : UnaryInstruction
    {
        internal VaArg( LLVMValueRef valueRef, bool preValidated )
            : base( preValidated ? valueRef : ValidateConversion( valueRef, NativeMethods.IsABranchInst ) )
        {
        }
    }
}


text:
'use strict';

const md5        = require('md5');
const evalString = require('../eval-string');
const coffeeEval = require('../coffee-eval');

module.exports = (audio, context) => {
  if(!audio) {return;}

  context.setUnlessExists('responseBody.directives', []);

  let url;

  if(audio === 'stop'){
    context.responseBody.directives.push({
      "type": "AudioPlayer.Stop"
    });
    return;
  }
  if(audio === 'clear enqueued'){
    context.responseBody.directives.push({
      "type": "AudioPlayer.ClearQueue",
      "clearBehavior" : "CLEAR_ENQUEUED"
    });
    return;
  }
  if(audio === 'clear all' || audio === 'clear'){
    context.responseBody.directives.push({
      "type": "AudioPlayer.ClearQueue",
      "clearBehavior" : "CLEAR_ALL"
    });
    return;
  }
  if(typeof audio === 'string'){
    url = evalString(audio, context);
    context.responseBody.directives.push({
      "type": "AudioPlayer.Play",
      "playBehavior": "REPLACE_ALL",
      "audioItem": {
        "stream": {
          "token": md5(url),
          "url": url,
          "offsetInMilliseconds": 0
        }
      }
    });
  } else if (Array.isArray(audio)) {
    // if we happen to get an array
    // the best attempt is to try the
    // first item because why not
    if(!audio.length){return;}
    url = evalString(audio[0], context);
    context.responseBody.directives.push({
      "type": "AudioPlayer.Play",
      "playBehavior": "REPLACE_ALL",
      "audioItem": {
        "stream": {
          "token": md5(url),
          "url": url,
          "offsetInMilliseconds": 0
        }
      }
    });
  } else if (typeof audio === 'object') {
    if(!audio.url){ return; }
    url = evalString(audio.url, context);
    context.responseBody.directives.push({
      "type": "AudioPlayer.Play",
      "playBehavior": audio.behavior || "REPLACE_ALL",
      "audioItem": {
        "stream": {
          "token": audio.token ? JSON.stringify(audio.token) : md5(url),
          "url": url,
          "offsetInMilliseconds": audio.offset || 0
        }
      }
    });
  }
}


text:
<?php

namespace Drupal\field;

use Drupal\Core\Config\Config;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\DeletedFieldsRepositoryInterface;
use Drupal\Core\Field\FieldConfigStorageBase;
use Drupal\Core\Field\FieldTypePluginManagerInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Component\Uuid\UuidInterface;

/**
 * Storage handler for field config.
 */
class FieldConfigStorage extends FieldConfigStorageBase {

  /**
   * The entity manager.
   *
   * @var \Drupal\Core\Entity\EntityManagerInterface
   */
  protected $entityManager;

  /**
   * The field type plugin manager.
   *
   * @var \Drupal\Core\Field\FieldTypePluginManagerInterface
   */
  protected $fieldTypeManager;

  /**
   * The deleted fields repository.
   *
   * @var \Drupal\Core\Field\DeletedFieldsRepositoryInterface
   */
  protected $deletedFieldsRepository;

  /**
   * Constructs a FieldConfigStorage object.
   *
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   The entity type definition.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory service.
   * @param \Drupal\Component\Uuid\UuidInterface $uuid_service
   *   The UUID service.
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
   *   The language manager.
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
   *   The entity manager.
   * @param \Drupal\Core\Field\FieldTypePluginManagerInterface $field_type_manager
   *   The field type plugin manager.
   * @param \Drupal\Core\Field\DeletedFieldsRepositoryInterface $deleted_fields_repository
   *   The deleted fields repository.
   */
  public function __construct(EntityTypeInterface $entity_type, ConfigFactoryInterface $config_factory, UuidInterface $uuid_service, LanguageManagerInterface $language_manager, EntityManagerInterface $entity_manager, FieldTypePluginManagerInterface $field_type_manager, DeletedFieldsRepositoryInterface $deleted_fields_repository) {
    parent::__construct($entity_type, $config_factory, $uuid_service, $language_manager);
    $this->entityManager = $entity_manager;
    $this->fieldTypeManager = $field_type_manager;
    $this->deletedFieldsRepository = $deleted_fields_repository;
  }

  /**
   * {@inheritdoc}
   */
  public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
    return new static(
      $entity_type,
      $container->get('config.factory'),
      $container->get('uuid'),
      $container->get('language_manager'),
      $container->get('entity.manager'),
      $container->get('plugin.manager.field.field_type'),
      $container->get('entity_field.deleted_fields_repository')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function importDelete($name, Config $new_config, Config $old_config) {
    // If the field storage has been deleted in the same import, the field will
    // be deleted by then, and there is nothing left to do. Just return TRUE so
    // that the file does not get written to active store.
    if (!$old_config->get()) {
      return TRUE;
    }
    return parent::importDelete($name, $new_config, $old_config);
  }

  /**
   * {@inheritdoc}
   */
  public function loadByProperties(array $conditions = []) {
    // Include deleted fields if specified in the $conditions parameters.
    $include_deleted = isset($conditions['include_deleted']) ? $conditions['include_deleted'] : FALSE;
    unset($conditions['include_deleted']);

    $fields = [];

    // Get fields stored in configuration. If we are explicitly looking for
    // deleted fields only, this can be skipped, because they will be
    // retrieved from the deleted fields repository below.
    if (empty($conditions['deleted'])) {
      if (isset($conditions['entity_type']) && isset($conditions['bundle']) && isset($conditions['field_name'])) {
        // Optimize for the most frequent case where we do have a specific ID.
        $id = $conditions['entity_type'] . '.' . $conditions['bundle'] . '.' . $conditions['field_name'];
        $fields = $this->loadMultiple([$id]);
      }
      else {
        // No specific ID, we need to examine all existing fields.
        $fields = $this->loadMultiple();
      }
    }

    // Merge deleted fields from the deleted fields repository if needed.
    if ($include_deleted || !empty($conditions['deleted'])) {
      $deleted_field_definitions = $this->deletedFieldsRepository->getFieldDefinitions();
      foreach ($deleted_field_definitions as $id => $field_definition) {
        if ($field_definition instanceof FieldConfigInterface) {
          $fields[$id] = $field_definition;
        }
      }
    }

    // Collect matching fields.
    $matching_fields = [];
    foreach ($fields as $field) {
      // Some conditions are checked against the field storage.
      $field_storage = $field->getFieldStorageDefinition();

      // Only keep the field if it matches all conditions.
      foreach ($conditions as $key => $value) {
        // Extract the actual value against which the condition is checked.
        switch ($key) {
          case 'field_name':
            $checked_value = $field_storage->getName();
            break;

          case 'field_id':
          case 'field_storage_uuid':
            $checked_value = $field_storage->uuid();
            break;

          case 'uuid';
            $checked_value = $field->uuid();
            break;

          case 'deleted';
            $checked_value = $field->isDeleted();
            break;

          default:
            $checked_value = $field->get($key);
            break;
        }

        // Skip to the next field as soon as one condition does not match.
        if ($checked_value != $value) {
          continue 2;
        }
      }

      // When returning deleted fields, key the results by UUID since they
      // can include several fields with the same ID.
      $key = $include_deleted ? $field->uuid() : $field->id();
      $matching_fields[$key] = $field;
    }

    return $matching_fields;
  }

}


text:
var help = require('./app/help')
var hello = require('./app/hello')
var argv = require('yargs')
  // .default('name', 'World')
  .argv

var prompt = require('prompt')

if (argv.help) {
  help();
}

prompt.override = argv;
prompt.message = prompt.delimiter = '';
prompt.start();

prompt.get(['name'], function (err, result) {
  argv.name = result.name;

  hello.printHello(result.name)
});

// process.stdout.write("Hello World Again! \n");

// process.stderr.write('OMG ERRORRRRRR \n');

// console.log(process.argv)

// console.log(argv)


text:
layout: post
title:  "Run jupyter notebook using docker"
project: false
---

How to create an opinionated stack using docker for jupyter-notebook

- Create a `Dockerfile` for setting up the environment

```
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.

# Base image of pyspark-notebook hosted on docker hub
FROM jupyter/pyspark-notebook

MAINTAINER Jupyter Project <jupyter@googlegroups.com>

USER root

# RSpark config
ENV R_LIBS_USER $SPARK_HOME/R/lib

# R pre-requisites
RUN apt-get update && \
    apt-get install -y --no-install-recommends \
    fonts-dejavu \
    gfortran \
    gcc && apt-get clean && \
    rm -rf /var/lib/apt/lists/*

USER $NB_USER

# R packages
RUN conda config --system --add channels r && \
    conda install --quiet --yes \
    'r-base=3.3.2' \
    'r-irkernel=0.7*' \
    'r-ggplot2=2.2*' \
    'r-rcurl=1.95*' && conda clean -tipsy

# Apache Toree kernel
RUN pip --no-cache-dir install https://dist.apache.org/repos/dist/dev/incubator/toree/0.2.0/snapshots/dev1/toree-pip/toree-0.2.0.dev1.tar.gz
RUN jupyter toree install --sys-prefix

# Spylon-kernel
RUN conda install --quiet --yes 'spylon-kernel=0.2*' && \
    conda clean -tipsy
RUN python -m spylon_kernel install --sys-prefix
```

- Create a `docker-compose.yml` file to define services

```
version: '2'

services:
  jupyter:
    build:
        context: .
    command: jupyter-notebook
    ports:
      - 8888:8888
    volumes:
      - .:/home/jovyan
```

- Build image locally ( This will create a local image by pulling base image and other dependencies defined in `Dockerfile` )

`Note: This will take a while since the dependant image from docker hub has to be pulled(downloaded and extracted) and build locally`

```
docker-compose build jupyter
```

-

```
docker-compose run jupyter bash
```
This is the path given in docker-compose.yml

- Run jupyter service to opena  jupyter notebook running on docker

```
docker-compose up jupyter
```

### Credits: [Jupyter @Github](https://github.com/jupyter/docker-stacks/tree/master/all-spark-notebook)


text:
import java.io.*;
import java.util.*;
public class W27 {
	public static void main(String [] args){
		Student[] studentArray=new Student[20];
		Student student;
		String namn;
		int vilkenStudent=1;
		for (int i=0;i<20;i++) {
			student=new Student();
			namn="Namn"+vilkenStudent;
			student.setNamn(namn);
			student.setId((int)((Math.abs(Math.random()*1000-100))+100));
			//		student.setStatus((int)(Math.random()*4+1));
			student.setStatus(3);
			student.setFödelseår(1950+(int)(Math.random()*32));
			studentArray[i]=student;
			vilkenStudent++;
		}
		for (int j=0;j<20;j++)
			if (studentArray[j].getStatus()==3)
				System.out.println(studentArray[j].print());

	}
}


text:
package org.apereo.cas.configuration.model.core.authentication;

import org.apereo.cas.configuration.support.RequiresModule;

import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * This is {@link StubPrincipalAttributesProperties}.
 *
 * @author Misagh Moayyed
 * @since 5.2.0
 */
@RequiresModule(name = "cas-server-support-person-directory", automated = true)
@Getter
@Setter
public class StubPrincipalAttributesProperties implements Serializable {

    private static final long serialVersionUID = 7017508256487553063L;

    /**
     * Static attributes that need to be mapped to a hardcoded value belong here.
     * The structure follows a key-value pair where key is the attribute name
     * and value is the attribute value. The key is the attribute fetched
     * from the source and the value is the attribute name CAS should
     * use for virtual renames.
     */
    private Map<String, String> attributes = new HashMap();
}


text:
from .reports import ReportBase
from .reportdata import ReportData


text:
'''PyVows is a Behavior-Driven Development framework for Python.  (And and it
is **fast**!)

---

PyVows runs tests asynchronously.  This makes tests which target I/O
run much faster, by running them concurrently. A faster test suite gets
run more often, thus improving the feedback cycle.

PyVows is inspired by Vows, a BDD framework for Node.js.

----

You typically shouldn't need to import any specific modules from the `pyvows`
package.  Normal use is:

    from pyvows import Vows, expect

----

To learn more, check out:   http://pyvows.org

'''

# pyVows testing engine
# https://github.com/heynemann/pyvows
#
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 Bernardo Heynemann heynemann@gmail.com

# flake8: noqa

#-------------------------------------------------------------------------------------------------

try:
    from preggy import expect
except:
    pass

try:
    from pyvows.core import Vows, expect
except ImportError:
    pass


text:
.class final Landroid/app/ActivityThread$ProviderKey;
.super Ljava/lang/Object;
.source "ActivityThread.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/app/ActivityThread;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x1a
    name = "ProviderKey"
.end annotation

# instance fields
.field final authority:Ljava/lang/String;

.field final userId:I

# direct methods
.method public constructor <init>(Ljava/lang/String;I)V
    .locals 0
    .parameter "authority"
    .parameter "userId"

    .prologue
    .line 237
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 238
    iput-object p1, p0, Landroid/app/ActivityThread$ProviderKey;->authority:Ljava/lang/String;

    .line 239
    iput p2, p0, Landroid/app/ActivityThread$ProviderKey;->userId:I

    .line 240
    return-void
.end method

# virtual methods
.method public equals(Ljava/lang/Object;)Z
    .locals 4
    .parameter "o"

    .prologue
    const/4 v1, 0x0

    .line 244
    instance-of v2, p1, Landroid/app/ActivityThread$ProviderKey;

    if-eqz v2, :cond_0

    move-object v0, p1

    .line 245
    check-cast v0, Landroid/app/ActivityThread$ProviderKey;

    .line 246
    .local v0, other:Landroid/app/ActivityThread$ProviderKey;
    iget-object v2, p0, Landroid/app/ActivityThread$ProviderKey;->authority:Ljava/lang/String;

    iget-object v3, v0, Landroid/app/ActivityThread$ProviderKey;->authority:Ljava/lang/String;

    invoke-static {v2, v3}, Lcom/android/internal/util/Objects;->equal(Ljava/lang/Object;Ljava/lang/Object;)Z

    move-result v2

    if-eqz v2, :cond_0

    iget v2, p0, Landroid/app/ActivityThread$ProviderKey;->userId:I

    iget v3, v0, Landroid/app/ActivityThread$ProviderKey;->userId:I

    if-ne v2, v3, :cond_0

    const/4 v1, 0x1

    .line 248
    .end local v0           #other:Landroid/app/ActivityThread$ProviderKey;
    :cond_0
    return v1
.end method

.method public hashCode()I
    .locals 2

    .prologue
    .line 253
    iget-object v0, p0, Landroid/app/ActivityThread$ProviderKey;->authority:Ljava/lang/String;

    if-eqz v0, :cond_0

    iget-object v0, p0, Landroid/app/ActivityThread$ProviderKey;->authority:Ljava/lang/String;

    invoke-virtual {v0}, Ljava/lang/String;->hashCode()I

    move-result v0

    :goto_0
    iget v1, p0, Landroid/app/ActivityThread$ProviderKey;->userId:I

    xor-int/2addr v0, v1

    return v0

    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method


text:
Intercept some fool questions crash

if not working try check `-no_compact_unwind` linker flag
http://stackoverflow.com/questions/28660855/ios-64bit-try-catch-not-working


text:
package org.jkiss.dbeaver.model.struct.rdb;

import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;

import java.util.Collection;

/**
 * Procedures container
 */
public interface DBSProcedureContainer
{
    Collection<? extends DBSProcedure> getProcedures(DBRProgressMonitor monitor) throws DBException;

    DBSProcedure getProcedure(DBRProgressMonitor monitor, String uniqueName) throws DBException;
}


text:
mode="???"
x_delim="###"
y_delim=","
features_delim=","
feature_name_val_delim=":"

fs_scheme="???"
libsvm_data_path="???"
ytklearn_data_path="???"

nohup java -server -Xmx1000m -XX:-OmitStackTraceInFastThrow -classpath .:lib/*:config -Dlog4j.configuration=file:config/log4j.properties com.fenbi.ytklearn.utils.LibsvmConvertTool  \
    "${mode}" "${x_delim}" "${y_delim}" "${features_delim}" "${feature_name_val_delim}" "${fs_scheme}" "${libsvm_data_path}" "${ytklearn_data_path}"  >> log/info.log 2>&1 &


text:
namespace Egs
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Diagnostics;
    using System.ComponentModel;
    using System.Globalization;
    using Egs.EgsDeviceControlCore.Properties;

    /// <summary>
    /// Exception thrown by some process (e.g. Firmware Update) in the application, to close the host application
    /// </summary>
    [Serializable]
    public sealed class EgsHostApplicationIsClosingException : Exception
    {
        public EgsHostApplicationIsClosingException(string reasonMessage) : base(reasonMessage) { }
    }

    internal class EgsDevicesManager : IDisposable, INotifyPropertyChanged
    {
        class CameraInterfaceInformation
        {
            public uint Index { get; set; }
            public string Description { get; set; }
            public string DevicePath { get; set; }
            public string RootDeviceDevicePath { get; set; }
            public string RootDeviceSerialNumber { get; set; }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            var t = PropertyChanged;
            if (t != null) { t(this, new PropertyChangedEventArgs(propertyName)); }
        }

        internal AForge.Video.DirectShow.FilterInfoCollection AForgeVideoCaptureDeviceInformationCollection { get; private set; }

        public IList<EgsDevice> DeviceList { get; private set; }
        internal EgsDevicesWindowMessageReceivingForm MessageReceivingForm { get; private set; }

        System.Windows.Forms.Timer EachDeviceStatusMonitoringTimer { get; set; }
        public double TemperatureMonitoringTimerIntervalTotalSeconds
        {
            get { return (double)EachDeviceStatusMonitoringTimer.Interval / 1000.0; }
            set
            {
                if (value < 1.0 || 60.0 < value)
                {
                    throw new ArgumentOutOfRangeException("TemperatureMonitoringTimerInterval", "Interval must be from 1[sec] to 60[sec]");
                }
                EachDeviceStatusMonitoringTimer.Interval = (int)(value * 1000.0);
                OnPropertyChanged(nameof(TemperatureMonitoringTimerIntervalTotalSeconds));
            }
        }

        System.Windows.Forms.Timer OnDeviceConnectedDelayTimer { get; set; }
        System.Windows.Forms.Timer OnDeviceDisconnectedDelayTimer { get; set; }
        internal int DeviceConnectionDelayTimersInterval
        {
            get { return OnDeviceConnectedDelayTimer.Interval; }
            set
            {
                OnDeviceConnectedDelayTimer.Interval = value;
                OnDeviceDisconnectedDelayTimer.Interval = value;
            }
        }

        internal EgsDevicesManager()
        {
            DeviceList = new List<EgsDevice>();
            MessageReceivingForm = new EgsDevicesWindowMessageReceivingForm();

            EachDeviceStatusMonitoringTimer = new System.Windows.Forms.Timer() { Interval = ApplicationCommonSettings.IsDebugging ? 1000 : 5000 };
            EachDeviceStatusMonitoringTimer.Tick += delegate
            {
                foreach (var device in DeviceList) { device.UpdateTemperatureProperties(); }
            };
            EachDeviceStatusMonitoringTimer.Start();

            // MUSTDO: Need investigatino.  "Connecting a device after running a host application" can cause a problem that the host application cannot catch the mouse event from the device!
            // NOTE: Immediately after the source event raises, AForge.NET (DirectShow wrapper) cannot enumerate all devices!!  So I added delay reluctantly.
            OnDeviceConnectedDelayTimer = new System.Windows.Forms.Timer();
            OnDeviceConnectedDelayTimer.Interval = 2000;
            OnDeviceConnectedDelayTimer.Tick += delegate
            {
                OnDeviceConnectedDelayTimer.Stop();
                UpdateNotInitializedFirstEgsDeviceOnSomeDeviceConnected();
            };
            MessageReceivingForm.DeviceConnected += delegate { OnDeviceConnectedDelayTimer.Start(); };

            OnDeviceDisconnectedDelayTimer = new System.Windows.Forms.Timer();
            OnDeviceDisconnectedDelayTimer.Interval = 2000;
            OnDeviceDisconnectedDelayTimer.Tick += delegate
            {
                OnDeviceDisconnectedDelayTimer.Stop();
                InitializeDisconnectedEgsDeviceOnSomeDeviceDisconnected();
            };
            MessageReceivingForm.DeviceDisconnected += delegate { OnDeviceDisconnectedDelayTimer.Start(); };
        }

        IList<CameraInterfaceInformation> GetCameraInterfaceInformationList()
        {
            var ret = new List<CameraInterfaceInformation>();
            try
            {
                var vidKeyStr = "vid_" + Win32SetupDiForEgsDevice.VendorId.ToString("x", CultureInfo.InvariantCulture);
                var pidKeyStr = "pid_" + Win32SetupDiForEgsDevice.ProductId.ToString("x", CultureInfo.InvariantCulture);

                AForgeVideoCaptureDeviceInformationCollection = new AForge.Video.DirectShow.FilterInfoCollection(AForge.Video.DirectShow.FilterCategory.VideoInputDevice);
                int variousMakersCamerasCount = AForgeVideoCaptureDeviceInformationCollection.Count;
                for (int i = 0; i < variousMakersCamerasCount; i++)
                {
                    string description = AForgeVideoCaptureDeviceInformationCollection[i].Name;
                    string devicePath = AForgeVideoCaptureDeviceInformationCollection[i].MonikerString;
                    if (devicePath.Contains(vidKeyStr) && devicePath.Contains(pidKeyStr))
                    {
                        var matchedItem = new CameraInterfaceInformation()
                        {
                            Index = (uint)i,
                            Description = description,
                            DevicePath = devicePath
                        };
                        // TODO: MUSTDO: get serial number from device path
                        var devicePathSubStrings = devicePath.Split('#').SelectMany(e => e.Split('&'));
                        if (false)
                        {
                            foreach (var item in devicePathSubStrings) { Debug.WriteLine(item); };
                        }
                        matchedItem.RootDeviceDevicePath = devicePathSubStrings.Where(e => e.ToLowerInvariant().Contains("exva")).SingleOrDefault();
                        ret.Add(matchedItem);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                if (ApplicationCommonSettings.IsDebugging) { Debugger.Break(); }
                throw;
            }
            return ret;
        }

        internal void UpdateNotInitializedFirstEgsDeviceOnSomeDeviceConnected()
        {
            // TODO: MUSTDO: Test with connecting and re-connecting USB connector, because various problems can occur here.
            try
            {
                // At first it checks HID connection.
                MessageReceivingForm.SetupDi.Update();
                foreach (var device in DeviceList) { device.UpdateHidDeviceConnectionStatus(); }

                // And then it checks camera connection.
                var cameras = GetCameraInterfaceInformationList();
                Debug.WriteLine("cameras.Count: " + cameras.Count);
                foreach (var camera in cameras)
                {
                    var matchedDeviceExists = DeviceList.Any(e => e.CameraViewImageSourceBitmapCapture.VideoCaptureDeviceIndex == camera.Index);
                    if (matchedDeviceExists) { continue; }
                    var notInitializedFirstEgsDevice = DeviceList.FirstOrDefault(e => (e.CameraViewImageSourceBitmapCapture.VideoCaptureDeviceIndex.HasValue == false));
                    if (notInitializedFirstEgsDevice == null) { return; }

                    Trace.Assert(notInitializedFirstEgsDevice.Settings != null);

                    // TODO: MUSTDO: get root device's serial number;
                    notInitializedFirstEgsDevice.CameraViewImageSourceBitmapCapture.VideoCaptureDeviceIndex = camera.Index;
                    notInitializedFirstEgsDevice.CameraViewImageSourceBitmapCapture.VideoCaptureDeviceName = camera.Description;
                    notInitializedFirstEgsDevice.CameraViewImageSourceBitmapCapture.VideoCaptureDeviceDevicePath = camera.DevicePath;
                    notInitializedFirstEgsDevice.TrySetIsCameraDeviceConnectedToTrue();
                    Debug.WriteLine("notInitializedFirstEgsDevice.IsConnected: " + notInitializedFirstEgsDevice.IsConnected);
                }
            }
            catch (EgsHostApplicationIsClosingException)
            {
                // NOTE: The exception occurs from inside of Timer, so the application thread cannot catch it.  EgsDevicesManager.Dispose() is called and then the application exit in the event handler of EgsDevicesManager.Disposing.
                System.Windows.Forms.MessageBox.Show(Resources.CommonStrings_ApplicationWillExit, ApplicationCommonSettings.HostApplicationName, System.Windows.Forms.MessageBoxButtons.OK);
                // NOTE! EgsHostAppBaseComponents should save Settings before disposing this object!
                this.Dispose();
            }
            catch (Exception ex)
            {
                if (ApplicationCommonSettings.IsDebugging) { Debugger.Break(); }
                Debug.WriteLine(ex.Message);
            }
        }

        void InitializeDisconnectedEgsDeviceOnSomeDeviceDisconnected()
        {
            try
            {
                // At first it checks HID connection.
                MessageReceivingForm.SetupDi.Update();
                foreach (var device in DeviceList) { device.UpdateHidDeviceConnectionStatus(); }

                // And then it checks camera connection.
                var cameras = GetCameraInterfaceInformationList();
                Debug.WriteLine("cameras.Count: " + cameras.Count);
                foreach (var device in DeviceList)
                {
                    var matchedCameraExists = cameras.Any(e => e.Index == device.CameraViewImageSourceBitmapCapture.VideoCaptureDeviceIndex);
                    if (matchedCameraExists) { continue; }
                    device.SetIsCameraDeviceConnectedToFalse();
                }
            }
            catch (Exception ex)
            {
                if (ApplicationCommonSettings.IsDebugging) { Debugger.Break(); }
                Debug.WriteLine(ex.Message);
            }
        }

        internal EgsDevice CreateNewEgsDeviceAndAddToDeviceList()
        {
            var device = EgsDevice.GetEgsDeviceForEgsDevicesManager(DeviceList.Count);
            DeviceList.Add(device);

            // TODO: MUSTDO: This is ad-hoc implementation.  This way cannot recognize multiple device's connection and disconnection.  This is very bad way, it should be fixed.
            MessageReceivingForm.CurrentDevice = device;

            return device;
        }

        internal void RemoveDeviceFromDeviceList(EgsDevice device)
        {
            if (DeviceList.Contains(device) == false) { return; }
            device.Close();
            DeviceList.Remove(device);
            // TODO: MUSTDO: delete MessageReceivingForm.CurrentDevice itself
            MessageReceivingForm.CurrentDevice = null;
        }

        #region IDisposable
        public event EventHandler Disposing;
        public event EventHandler Disposed;
        protected virtual void OnDisposing(EventArgs e) { var t = Disposing; if (t != null) { t(this, e); } }
        protected virtual void OnDisposed(EventArgs e) { var t = Disposed; if (t != null) { t(this, e); } }
        protected bool hasOnDisposingCalled = false;
        private bool disposed = false;
        public void Dispose() { Dispose(true); GC.SuppressFinalize(this); }
        protected virtual void Dispose(bool disposing)
        {
            if (disposed) { return; }
            if (disposing)
            {
                if (hasOnDisposingCalled == false)
                {
                    hasOnDisposingCalled = true;
                    OnDisposing(EventArgs.Empty);
                    if (disposed) { return; }
                }

                // dispose managed objects, and dispose objects that implement IDisposable
                if (EachDeviceStatusMonitoringTimer != null) { EachDeviceStatusMonitoringTimer.Dispose(); EachDeviceStatusMonitoringTimer = null; }
                if (OnDeviceConnectedDelayTimer != null) { OnDeviceConnectedDelayTimer.Stop(); OnDeviceConnectedDelayTimer.Dispose(); OnDeviceConnectedDelayTimer = null; }
                if (OnDeviceDisconnectedDelayTimer != null) { OnDeviceDisconnectedDelayTimer.Stop(); OnDeviceDisconnectedDelayTimer.Dispose(); OnDeviceDisconnectedDelayTimer = null; }
                if (MessageReceivingForm != null) { MessageReceivingForm.CurrentDevice = null; }
                if (DeviceList != null)
                {
                    foreach (var device in DeviceList) { device.Close(); }
                    DeviceList.Clear();
                    DeviceList = null;
                }
                if (MessageReceivingForm != null) { MessageReceivingForm.Dispose(); MessageReceivingForm = null; }
            }
            // release any unmanaged objects and set the object references to null
            disposed = true;
            OnDisposed(EventArgs.Empty);
        }
        ~EgsDevicesManager() { Dispose(false); }
        #endregion
    }
}


text:
@interface KTPPledgeOverviewViewController () <KTPPieChartDelegate, KTPPieChartDataSource>// <XYPieChartDelegate, XYPieChartDataSource>

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *contentView;

@property (nonatomic, strong) KTPPieChart *pointsPieChart;

@end

@implementation KTPPledgeOverviewViewController

- (instancetype)init {
    self = [super init];
    if (self) {
        self.scrollView = [UIScrollView new];
        self.contentView = [UIView new];

        self.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"Overview" image:[UIImage imageNamed:@"ChartIcon"] tag:0];
        self.navigationItem.title = @"Overview";

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pledgeTasksDidUpdate) name:KTPNotificationPledgeTasksUpdated object:nil];
    }
    return self;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self pledgeTasksDidUpdate]; // assume tasks have updated and handle accordingly
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self loadSubviews];
    [self autoLayoutSubviews];
}

- (void)loadSubviews {
    // Container views
    self.scrollView.frame = self.view.bounds;
    self.scrollView.alwaysBounceVertical = YES;
    self.scrollView.delaysContentTouches = NO;
    [self.view addSubview:self.scrollView];

    self.contentView.frame = self.scrollView.bounds;
    [self.scrollView addSubview:self.contentView];

    // Content views
    [self loadPointsPieChart];
}

- (void)loadPointsPieChart {
    self.pointsPieChart = [KTPPieChart new];
    self.pointsPieChart.delegate = self;
    self.pointsPieChart.dataSource = self;
    self.pointsPieChart.textColor = [UIColor grayColor];
    self.pointsPieChart.title = @"Pledge Points";
    self.pointsPieChart.titlePosition = KTPPieChartTitlePositionCenter;
//    self.pointsPieChart.labelFont = [UIFont boldSystemFontOfSize:17];
    [self.contentView addSubview:self.pointsPieChart];
}

#pragma mark - KTPPieChartDataSource methods

- (NSUInteger)numberOfSlicesInPieChart:(KTPPieChart *)pieChart {
    return 2; // earned vs needed points
}

- (CGFloat)pieChart:(KTPPieChart *)pieChart valueForSliceAtIndex:(NSUInteger)index {
    if (index == 0) {
        return [KTPSPledgeTasks pledgeTasks].totalPointsEarned;
    } else {
        return [KTPSPledgeTasks pledgeTasks].totalPointsNeeded - [KTPSPledgeTasks pledgeTasks].totalPointsEarned;
    }
}

- (UIColor *)pieChart:(KTPPieChart *)pieChart colorForSliceAtIndex:(NSUInteger)index {
    if (index == 0) {
        return [UIColor colorWithRed:172/255.0 green:221/255.0 blue:168/255.0 alpha:1];
    } else {
        return [UIColor colorWithRed:238/255.0 green:181/255.0 blue:173/255.0 alpha:1];
    }
}

- (NSString *)pieChart:(KTPPieChart *)pieChart textForSliceAtIndex:(NSUInteger)index {
    CGFloat value = [self pieChart:pieChart valueForSliceAtIndex:index];
    return value ? [NSString stringWithFormat:@"%1.0f", value] : @"";
}

#pragma mark - KTPPieChartDelegate methods

- (void)pieChart:(KTPPieChart *)pieChart didSelectSliceAtIndex:(NSUInteger)index {

}

#pragma mark - Layout Subviews

- (void)autoLayoutSubviews {
    self.pointsPieChart.translatesAutoresizingMaskIntoConstraints = NO;

    NSDictionary *views = @{
                            @"pointsPieChart"  :   self.pointsPieChart
                            };

    [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[pointsPieChart]-10-|" options:0 metrics:nil views:views]];
    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.pointsPieChart attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.pointsPieChart attribute:NSLayoutAttributeHeight multiplier:1 constant:0]];
    [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-10-[pointsPieChart]" options:0 metrics:nil views:views]];
}

- (void)viewWillLayoutSubviews {
    self.pointsPieChart.maxPieRadius = 0.75;
    self.pointsPieChart.minPieRadius = 0.20;
    self.pointsPieChart.textRadius  = (self.pointsPieChart.maxPieRadius + self.pointsPieChart.minPieRadius) / 2;
}

#pragma mark - Notification Handling

- (void)pledgeTasksDidUpdate {
    [self.pointsPieChart reloadData];
}

@end


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

<!--
  ~ Copyright 2017 D.Hope. https://github.com/Hope0310
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~    http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<resources>

    <style name="Base.Theme" parent="Theme.AppCompat.DayNight.NoActionBar">
        <item name="android:windowTranslucentStatus">true</item>
    </style>

    <style name="Base.Theme.TranslucentNavigation">
        <item name="android:windowTranslucentNavigation">true</item>
    </style>

    <style name="Base.Theme.DrawStatusBar"/>

    <style name="Base.Theme.DrawStatusBar.TranslucentNavigation">
        <item name="android:windowTranslucentNavigation">true</item>
    </style>

</resources>


text:
<component name="libraryTable">
  <library name="kotlinx-metadata">
    <CLASSES>
      <root url="jar://$PROJECT_DIR$/third-party/java/kotlinx-metadata-jvm/kotlinx-metadata-jvm-0.1.0.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="jar://$PROJECT_DIR$/third-party/java/kotlinx-metadata-jvm/kotlinx-metadata-jvm-0.1.0-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
package org.h2.test.unit;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.channels.FileLock;
import java.nio.channels.NonWritableChannelException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Random;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.h2.dev.fs.FilePathZip2;
import org.h2.message.DbException;
import org.h2.mvstore.DataUtils;
import org.h2.mvstore.cache.FilePathCache;
import org.h2.store.fs.FilePath;
import org.h2.store.fs.FilePathEncrypt;
import org.h2.store.fs.FilePathRec;
import org.h2.store.fs.FileUtils;
import org.h2.test.TestBase;
import org.h2.test.utils.AssertThrows;
import org.h2.test.utils.FilePathDebug;
import org.h2.tools.Backup;
import org.h2.tools.DeleteDbFiles;
import org.h2.util.IOUtils;

/**
 * Tests various file system.
 */
public class TestFileSystem extends TestBase {

    /**
     * Run just this test.
     *
     * @param a ignored
     */
    public static void main(String... a) throws Exception {
        TestBase test = TestBase.createCaller().init();
        // test.config.traceTest = true;
        test.test();
    }

    @Override
    public void test() throws Exception {
        testFileSystem(getBaseDir() + "/fs");

        testAbsoluteRelative();
        testDirectories(getBaseDir());
        testMoveTo(getBaseDir());
        testUnsupportedFeatures(getBaseDir());
        FilePathZip2.register();
        FilePath.register(new FilePathCache());
        FilePathRec.register();
        testZipFileSystem("zip:");
        testZipFileSystem("cache:zip:");
        testZipFileSystem("zip2:");
        testZipFileSystem("cache:zip2:");
        testMemFsDir();
        testClasspath();
        FilePathDebug.register().setTrace(true);
        FilePathEncrypt.register();
        testSimpleExpandTruncateSize();
        testSplitDatabaseInZip();
        testDatabaseInMemFileSys();
        testDatabaseInJar();
        // set default part size to 1 << 10
        String f = "split:10:" + getBaseDir() + "/fs";
        FileUtils.toRealPath(f);
        testFileSystem(getBaseDir() + "/fs");
        testFileSystem("memFS:");
        testFileSystem("memLZF:");
        testFileSystem("nioMemFS:");
        testFileSystem("nioMemLZF:");
        testFileSystem("rec:memFS:");
        testUserHome();
        try {
            testFileSystem("nio:" + getBaseDir() + "/fs");
            testFileSystem("cache:nio:" + getBaseDir() + "/fs");
            testFileSystem("nioMapped:" + getBaseDir() + "/fs");
            testFileSystem("encrypt:0007:" + getBaseDir() + "/fs");
            testFileSystem("cache:encrypt:0007:" + getBaseDir() + "/fs");
            if (!config.splitFileSystem) {
                testFileSystem("split:" + getBaseDir() + "/fs");
                testFileSystem("split:nioMapped:" + getBaseDir() + "/fs");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } catch (Error e) {
            e.printStackTrace();
            throw e;
        } finally {
            FileUtils.delete(getBaseDir() + "/fs");
        }
    }

    private void testZipFileSystem(String prefix) throws IOException {
        Random r = new Random(1);
        for (int i = 0; i < 5; i++) {
            testZipFileSystem(prefix, r);
        }
    }

    private void testZipFileSystem(String prefix, Random r) throws IOException {
        byte[] data = new byte[r.nextInt(16 * 1024)];
        long x = r.nextLong();
        FilePath file = FilePath.get(getBaseDir() + "/fs/readonly" + x + ".zip");
        r.nextBytes(data);
        OutputStream out = file.newOutputStream(false);
        ZipOutputStream zipOut = new ZipOutputStream(out);
        ZipEntry entry = new ZipEntry("data");
        zipOut.putNextEntry(entry);
        zipOut.write(data);
        zipOut.closeEntry();
        zipOut.close();
        out.close();
        FilePath fp = FilePath.get(
                prefix + getBaseDir() + "/fs/readonly" + x + ".zip!data");
        FileChannel fc = fp.open("r");
        StringBuilder buff = new StringBuilder();
        try {
            int pos = 0;
            for (int i = 0; i < 100; i++) {
                trace("op " + i);
                switch (r.nextInt(5)) {
                case 0: {
                    int p = r.nextInt(data.length);
                    trace("seek " + p);
                    buff.append("seek " + p + "\n");
                    fc.position(p);
                    pos = p;
                    break;
                }
                case 1: {
                    int len = r.nextInt(1000);
                    int offset = r.nextInt(100);
                    int arrayLen = len + offset;
                    len = Math.min(len, data.length - pos);
                    byte[] b1 = new byte[arrayLen];
                    byte[] b2 = new byte[arrayLen];
                    trace("readFully " + len);
                    buff.append("readFully " + len + "\n");
                    System.arraycopy(data, pos, b1, offset, len);
                    ByteBuffer byteBuff = createSlicedBuffer(b2, offset, len);
                    FileUtils.readFully(fc, byteBuff);
                    assertEquals(b1, b2);
                    pos += len;
                    break;
                }
                case 2: {
                    int len = r.nextInt(1000);
                    int offset = r.nextInt(100);
                    int arrayLen = len + offset;
                    int p = r.nextInt(data.length);
                    len = Math.min(len, data.length - p);
                    byte[] b1 = new byte[arrayLen];
                    byte[] b2 = new byte[arrayLen];
                    trace("readFully " + p + " " + len);
                    buff.append("readFully " + p + " " + len + "\n");
                    System.arraycopy(data, p, b1, offset, len);
                    ByteBuffer byteBuff = createSlicedBuffer(b2, offset, len);
                    DataUtils.readFully(fc, p, byteBuff);
                    assertEquals(b1, b2);
                    break;
                }
                case 3: {
                    trace("getFilePointer");
                    buff.append("getFilePointer\n");
                    assertEquals(pos, fc.position());
                    break;
                }
                case 4: {
                    trace("length " + data.length);
                    buff.append("length " + data.length + "\n");
                    assertEquals(data.length, fc.size());
                    break;
                }
                default:
                }
            }
            fc.close();
            file.delete();
        } catch (Throwable e) {
            e.printStackTrace();
            fail("Exception: " + e + "\n"+ buff.toString());
        }
    }

    private void testAbsoluteRelative() {
        assertFalse(FileUtils.isAbsolute("test/abc"));
        assertTrue(FileUtils.isAbsolute("~/test/abc"));
    }

    private void testMemFsDir() throws IOException {
        FileUtils.newOutputStream("memFS:data/test/a.txt", false).close();
        assertEquals(FileUtils.newDirectoryStream("memFS:data/test").toString(),
                1, FileUtils.newDirectoryStream("memFS:data/test").size());
        FileUtils.deleteRecursive("memFS:", false);
    }

    private void testClasspath() throws IOException {
        String resource = "org/h2/test/testSimple.in.txt";
        InputStream in;
        in = getClass().getResourceAsStream("/" + resource);
        assertTrue(in != null);
        in.close();
        in = getClass().getClassLoader().getResourceAsStream(resource);
        assertTrue(in != null);
        in.close();
        in = FileUtils.newInputStream("classpath:" + resource);
        assertTrue(in != null);
        in.close();
        in = FileUtils.newInputStream("classpath:/" + resource);
        assertTrue(in != null);
        in.close();
    }

    private void testSimpleExpandTruncateSize() throws Exception {
        String f = "memFS:" + getBaseDir() + "/fs/test.data";
        FileUtils.createDirectories("memFS:" + getBaseDir() + "/fs");
        FileChannel c = FileUtils.open(f, "rw");
        c.position(4000);
        c.write(ByteBuffer.wrap(new byte[1]));
        FileLock lock = c.tryLock();
        c.truncate(0);
        if (lock != null) {
            lock.release();
        }
        c.close();
        FileUtils.deleteRecursive("memFS:", false);
    }

    private void testSplitDatabaseInZip() throws SQLException {
        String dir = getBaseDir() + "/fs";
        FileUtils.deleteRecursive(dir, false);
        Connection conn;
        Statement stat;
        conn = getConnection("jdbc:h2:split:18:"+dir+"/test");
        stat = conn.createStatement();
        stat.execute(
                "create table test(id int primary key, name varchar) " +
                "as select x, space(10000) from system_range(1, 100)");
        // stat.execute("shutdown defrag");
        conn.close();
        Backup.execute(dir + "/test.zip", dir, "", true);
        DeleteDbFiles.execute("split:" + dir, "test", true);
        conn = getConnection(
                "jdbc:h2:split:zip:"+dir+"/test.zip!/test");
        conn.createStatement().execute("select * from test where id=1");
        conn.close();
        FileUtils.deleteRecursive(dir, false);
    }

    private void testDatabaseInMemFileSys() throws SQLException {
        org.h2.Driver.load();
        deleteDb("fsMem");
        String url = "jdbc:h2:" + getBaseDir() + "/fsMem";
        Connection conn = getConnection(url, "sa", "sa");
        conn.createStatement().execute(
                "CREATE TABLE TEST AS SELECT * FROM DUAL");
        conn.createStatement().execute(
                "BACKUP TO '" + getBaseDir() + "/fsMem.zip'");
        conn.close();
        org.h2.tools.Restore.main("-file", getBaseDir() + "/fsMem.zip", "-dir",
                "memFS:");
        conn = getConnection("jdbc:h2:memFS:fsMem", "sa", "sa");
        ResultSet rs = conn.createStatement()
                .executeQuery("SELECT * FROM TEST");
        rs.close();
        conn.close();
        deleteDb("fsMem");
        FileUtils.delete(getBaseDir() + "/fsMem.zip");
    }

    private void testDatabaseInJar() throws Exception {
        if (getBaseDir().indexOf(':') > 0) {
            return;
        }
        if (config.networked) {
            return;
        }
        org.h2.Driver.load();
        String url = "jdbc:h2:" + getBaseDir() + "/fsJar";
        Connection conn = getConnection(url, "sa", "sa");
        Statement stat = conn.createStatement();
        stat.execute("create table test(id int primary key, " +
                "name varchar, b blob, c clob)");
        stat.execute("insert into test values(1, 'Hello', " +
                "SECURE_RAND(2000), space(2000))");
        ResultSet rs;
        rs = stat.executeQuery("select * from test");
        rs.next();
        byte[] b1 = rs.getBytes(3);
        String s1 = rs.getString(4);
        conn.close();
        conn = getConnection(url, "sa", "sa");
        stat = conn.createStatement();
        stat.execute("backup to '" + getBaseDir() + "/fsJar.zip'");
        conn.close();

        deleteDb("fsJar");
        for (String f : FileUtils.newDirectoryStream(
                "zip:" + getBaseDir() + "/fsJar.zip")) {
            assertFalse(FileUtils.isAbsolute(f));
            assertTrue(!FileUtils.isDirectory(f));
            assertTrue(FileUtils.size(f) > 0);
            assertTrue(f.endsWith(FileUtils.getName(f)));
            assertEquals(0, FileUtils.lastModified(f));
            FileUtils.setReadOnly(f);
            assertFalse(FileUtils.canWrite(f));
            InputStream in = FileUtils.newInputStream(f);
            int len = 0;
            while (in.read() >= 0) {
                len++;
            }
            assertEquals(len, FileUtils.size(f));
            testReadOnly(f);
        }
        String urlJar = "jdbc:h2:zip:" + getBaseDir() + "/fsJar.zip!/fsJar";
        conn = getConnection(urlJar, "sa", "sa");
        stat = conn.createStatement();
        rs = stat.executeQuery("select * from test");
        rs.next();
        assertEquals(1, rs.getInt(1));
        assertEquals("Hello", rs.getString(2));
        byte[] b2 = rs.getBytes(3);
        String s2 = rs.getString(4);
        assertEquals(2000, b2.length);
        assertEquals(2000, s2.length());
        assertEquals(b1, b2);
        assertEquals(s1, s2);
        assertFalse(rs.next());
        conn.close();
        FileUtils.delete(getBaseDir() + "/fsJar.zip");
    }

    private void testReadOnly(final String f) throws IOException {
        new AssertThrows(IOException.class) {
            @Override
            public void test() throws IOException {
                FileUtils.newOutputStream(f, false);
        }};
        new AssertThrows(DbException.class) {
            @Override
            public void test() {
                FileUtils.move(f, f);
        }};
        new AssertThrows(DbException.class) {
            @Override
            public void test() {
                FileUtils.move(f, f);
        }};
        new AssertThrows(IOException.class) {
            @Override
            public void test() throws IOException {
                FileUtils.createTempFile(f, ".tmp", false, false);
        }};
        final FileChannel channel = FileUtils.open(f, "r");
        new AssertThrows(IOException.class) {
            @Override
            public void test() throws IOException {
                channel.write(ByteBuffer.allocate(1));
        }};
        new AssertThrows(IOException.class) {
            @Override
            public void test() throws IOException {
                channel.truncate(0);
        }};
        assertTrue(null == channel.tryLock());
        channel.force(false);
        channel.close();
    }

    private void testUserHome() {
        String userDir = System.getProperty("user.home").replace('\\', '/');
        assertTrue(FileUtils.toRealPath("~/test").startsWith(userDir));
        assertTrue(FileUtils.toRealPath("file:~/test").startsWith(userDir));
    }

    private void testFileSystem(String fsBase) throws Exception {
        testRootExists(fsBase);
        testPositionedReadWrite(fsBase);
        testSetReadOnly(fsBase);
        testParentEventuallyReturnsNull(fsBase);
        testSimple(fsBase);
        testTempFile(fsBase);
        testRandomAccess(fsBase);
    }

    private void testRootExists(String fsBase) {
        String fileName = fsBase + "/testFile";
        FilePath p = FilePath.get(fileName);
        while (p.getParent() != null) {
            p = p.getParent();
        }
        assertTrue(p.exists());
    }

    private void testSetReadOnly(String fsBase) {
        String fileName = fsBase + "/testFile";
        if (FileUtils.exists(fileName)) {
            FileUtils.delete(fileName);
        }
        if (FileUtils.createFile(fileName)) {
            FileUtils.setReadOnly(fileName);
            assertFalse(FileUtils.canWrite(fileName));
            FileUtils.delete(fileName);
        }
    }

    private static void testDirectories(String fsBase) {
        final String fileName = fsBase + "/testFile";
        if (FileUtils.exists(fileName)) {
            FileUtils.delete(fileName);
        }
        if (FileUtils.createFile(fileName)) {
            new AssertThrows(DbException.class) {
                @Override
                public void test() {
                    FileUtils.createDirectory(fileName);
            }};
            new AssertThrows(DbException.class) {
                @Override
                public void test() {
                    FileUtils.createDirectories(fileName + "/test");
            }};
            FileUtils.delete(fileName);
        }
    }

    private static void testMoveTo(String fsBase) {
        final String fileName = fsBase + "/testFile";
        final String fileName2 = fsBase + "/testFile2";
        if (FileUtils.exists(fileName)) {
            FileUtils.delete(fileName);
        }
        if (FileUtils.createFile(fileName)) {
            FileUtils.move(fileName, fileName2);
            FileUtils.createFile(fileName);
            new AssertThrows(DbException.class) {
                @Override
                public void test() {
                    FileUtils.move(fileName2, fileName);
            }};
            FileUtils.delete(fileName);
            FileUtils.delete(fileName2);
            new AssertThrows(DbException.class) {
                @Override
                public void test() {
                    FileUtils.move(fileName, fileName2);
            }};
        }
    }

    private static void testUnsupportedFeatures(String fsBase) throws IOException {
        final String fileName = fsBase + "/testFile";
        if (FileUtils.exists(fileName)) {
            FileUtils.delete(fileName);
        }
        if (FileUtils.createFile(fileName)) {
            final FileChannel channel = FileUtils.open(fileName, "rw");
            new AssertThrows(UnsupportedOperationException.class) {
                @Override
                public void test() throws IOException {
                    channel.map(MapMode.PRIVATE, 0, channel.size());
            }};
            new AssertThrows(UnsupportedOperationException.class) {
                @Override
                public void test() throws IOException {
                    channel.read(new ByteBuffer[]{ByteBuffer.allocate(10)}, 0, 0);
            }};
            new AssertThrows(UnsupportedOperationException.class) {
                @Override
                public void test() throws IOException {
                    channel.write(new ByteBuffer[]{ByteBuffer.allocate(10)}, 0, 0);
            }};
            new AssertThrows(UnsupportedOperationException.class) {
                @Override
                public void test() throws IOException {
                    channel.transferFrom(channel, 0, 0);
            }};
            new AssertThrows(UnsupportedOperationException.class) {
                @Override
                public void test() throws IOException {
                    channel.transferTo(0, 0, channel);
            }};
            new AssertThrows(UnsupportedOperationException.class) {
                @Override
                public void test() throws IOException {
                    channel.lock();
            }};
            channel.close();
            FileUtils.delete(fileName);
        }
    }

    private void testParentEventuallyReturnsNull(String fsBase) {
        FilePath p = FilePath.get(fsBase + "/testFile");
        assertTrue(p.getScheme().length() > 0);
        for (int i = 0; i < 100; i++) {
            if (p == null) {
                return;
            }
            p = p.getParent();
        }
        fail("Parent is not null: " + p);
        String path = fsBase + "/testFile";
        for (int i = 0; i < 100; i++) {
            if (path == null) {
                return;
            }
            path = FileUtils.getParent(path);
        }
        fail("Parent is not null: " + path);
    }

    private void testSimple(final String fsBase) throws Exception {
        long time = System.currentTimeMillis();
        for (String s : FileUtils.newDirectoryStream(fsBase)) {
            FileUtils.delete(s);
        }
        FileUtils.createDirectories(fsBase + "/test");
        assertTrue(FileUtils.exists(fsBase));
        FileUtils.delete(fsBase + "/test");
        FileUtils.delete(fsBase + "/test2");
        assertTrue(FileUtils.createFile(fsBase + "/test"));
        List<FilePath> p = FilePath.get(fsBase).newDirectoryStream();
        assertEquals(1, p.size());
        String can = FilePath.get(fsBase + "/test").toRealPath().toString();
        assertEquals(can, p.get(0).toString());
        assertTrue(FileUtils.canWrite(fsBase + "/test"));
        FileChannel channel = FileUtils.open(fsBase + "/test", "rw");
        byte[] buffer = new byte[10000];
        Random random = new Random(1);
        random.nextBytes(buffer);
        channel.write(ByteBuffer.wrap(buffer));
        assertEquals(10000, channel.size());
        channel.position(20000);
        assertEquals(20000, channel.position());
        assertEquals(-1, channel.read(ByteBuffer.wrap(buffer, 0, 1)));
        String path = fsBase + "/test";
        assertEquals("test", FileUtils.getName(path));
        can = FilePath.get(fsBase).toRealPath().toString();
        String can2 = FileUtils.toRealPath(FileUtils.getParent(path));
        assertEquals(can, can2);
        FileLock lock = channel.tryLock();
        if (lock != null) {
            lock.release();
        }
        assertEquals(10000, channel.size());
        channel.close();
        assertEquals(10000, FileUtils.size(fsBase + "/test"));
        channel = FileUtils.open(fsBase + "/test", "r");
        final byte[] test = new byte[10000];
        FileUtils.readFully(channel, ByteBuffer.wrap(test, 0, 10000));
        assertEquals(buffer, test);
        final FileChannel fc = channel;
        new AssertThrows(IOException.class) {
            @Override
            public void test() throws Exception {
                fc.write(ByteBuffer.wrap(test, 0, 10));
            }
        };
        new AssertThrows(NonWritableChannelException.class) {
            @Override
            public void test() throws Exception {
                fc.truncate(10);
            }
        };
        channel.close();
        long lastMod = FileUtils.lastModified(fsBase + "/test");
        if (lastMod < time - 1999) {
            // at most 2 seconds difference
            assertEquals(time, lastMod);
        }
        assertEquals(10000, FileUtils.size(fsBase + "/test"));
        List<String> list = FileUtils.newDirectoryStream(fsBase);
        assertEquals(1, list.size());
        assertTrue(list.get(0).endsWith("test"));
        IOUtils.copyFiles(fsBase + "/test", fsBase + "/test3");
        FileUtils.move(fsBase + "/test3", fsBase + "/test2");
        FileUtils.move(fsBase + "/test2", fsBase + "/test2");
        assertTrue(!FileUtils.exists(fsBase + "/test3"));
        assertTrue(FileUtils.exists(fsBase + "/test2"));
        assertEquals(10000, FileUtils.size(fsBase + "/test2"));
        byte[] buffer2 = new byte[10000];
        InputStream in = FileUtils.newInputStream(fsBase + "/test2");
        int pos = 0;
        while (true) {
            int l = in.read(buffer2, pos, Math.min(10000 - pos, 1000));
            if (l <= 0) {
                break;
            }
            pos += l;
        }
        in.close();
        assertEquals(10000, pos);
        assertEquals(buffer, buffer2);

        assertTrue(FileUtils.tryDelete(fsBase + "/test2"));
        FileUtils.delete(fsBase + "/test");
        if (fsBase.indexOf("memFS:") < 0 && fsBase.indexOf("memLZF:") < 0
            && fsBase.indexOf("nioMemFS:") < 0 && fsBase.indexOf("nioMemLZF:") < 0) {
            FileUtils.createDirectories(fsBase + "/testDir");
            assertTrue(FileUtils.isDirectory(fsBase + "/testDir"));
            if (!fsBase.startsWith("jdbc:")) {
                FileUtils.deleteRecursive(fsBase + "/testDir", false);
                assertTrue(!FileUtils.exists(fsBase + "/testDir"));
            }
        }
    }

    private void testPositionedReadWrite(String fsBase) throws IOException {
        FileUtils.deleteRecursive(fsBase + "/testFile", false);
        FileUtils.delete(fsBase + "/testFile");
        FileUtils.createDirectories(fsBase);
        assertTrue(FileUtils.createFile(fsBase + "/testFile"));
        FileChannel fc = FilePath.get(fsBase + "/testFile").open("rw");
        ByteBuffer buff = ByteBuffer.allocate(4000);
        for (int i = 0; i < 4000; i++) {
            buff.put((byte) i);
        }
        buff.flip();
        fc.write(buff, 96);
        assertEquals(0, fc.position());
        assertEquals(4096, fc.size());
        buff = ByteBuffer.allocate(4000);
        assertEquals(4000, fc.read(buff, 96));
        assertEquals(0, fc.position());
        buff.flip();
        for (int i = 0; i < 4000; i++) {
            assertEquals((byte) i, buff.get());
        }
        buff = ByteBuffer.allocate(0);
        assertTrue(fc.read(buff, 8000) <= 0);
        assertEquals(0, fc.position());
        assertTrue(fc.read(buff, 4000) <= 0);
        assertEquals(0, fc.position());
        assertTrue(fc.read(buff, 2000) <= 0);
        assertEquals(0, fc.position());
        buff = ByteBuffer.allocate(1);
        assertEquals(-1, fc.read(buff, 8000));
        assertEquals(1, fc.read(buff, 4000));
        buff.flip();
        assertEquals(1, fc.read(buff, 2000));
        fc.close();
    }

    private void testRandomAccess(String fsBase) throws Exception {
        testRandomAccess(fsBase, 1);
    }

    private void testRandomAccess(String fsBase, int seed) throws Exception {
        StringBuilder buff = new StringBuilder();
        String s = FileUtils.createTempFile(fsBase + "/tmp", ".tmp", false, false);
        File file = new File(TestBase.BASE_TEST_DIR + "/tmp");
        file.getParentFile().mkdirs();
        file.delete();
        RandomAccessFile ra = new RandomAccessFile(file, "rw");
        FileUtils.delete(s);
        FileChannel f = FileUtils.open(s, "rw");
        assertEquals(s, f.toString());
        assertEquals(-1, f.read(ByteBuffer.wrap(new byte[1])));
        f.force(true);
        Random random = new Random(seed);
        int size = getSize(100, 500);
        try {
            for (int i = 0; i < size; i++) {
                trace("op " + i);
                int pos = random.nextInt(10000);
                switch (random.nextInt(7)) {
                case 0: {
                    pos = (int) Math.min(pos, ra.length());
                    trace("seek " + pos);
                    buff.append("seek " + pos + "\n");
                    f.position(pos);
                    ra.seek(pos);
                    break;
                }
                case 1: {
                    int arrayLen = random.nextInt(1000);
                    int offset = arrayLen / 10;
                    offset = offset == 0 ? 0 : random.nextInt(offset);
                    int len = arrayLen == 0 ? 0 : random.nextInt(arrayLen - offset);
                    byte[] buffer = new byte[arrayLen];
                    ByteBuffer byteBuff = createSlicedBuffer(buffer, offset, len);
                    random.nextBytes(buffer);
                    trace("write " + offset + " len " + len);
                    buff.append("write " + offset + " " + len + "\n");
                    f.write(byteBuff);
                    ra.write(buffer, offset, len);
                    break;
                }
                case 2: {
                    trace("truncate " + pos);
                    buff.append("truncate " + pos + "\n");
                    f.truncate(pos);
                    if (pos < ra.length()) {
                        // truncate is supposed to have no effect if the
                        // position is larger than the current size
                        ra.setLength(pos);
                    }
                    assertEquals(ra.getFilePointer(), f.position());
                    break;
                }
                case 3: {
                    int len = random.nextInt(1000);
                    int offset = random.nextInt(100);
                    int arrayLen = len + offset;
                    len = (int) Math.min(len, ra.length() - ra.getFilePointer());
                    byte[] b1 = new byte[arrayLen];
                    byte[] b2 = new byte[arrayLen];
                    trace("readFully " + len);
                    buff.append("readFully " + len + "\n");
                    ra.readFully(b1, offset, len);
                    ByteBuffer byteBuff = createSlicedBuffer(b2, offset, len);
                    FileUtils.readFully(f, byteBuff);
                    assertEquals(b1, b2);
                    break;
                }
                case 4: {
                    trace("getFilePointer");
                    buff.append("getFilePointer\n");
                    assertEquals(ra.getFilePointer(), f.position());
                    break;
                }
                case 5: {
                    trace("length " + ra.length());
                    buff.append("length " + ra.length() + "\n");
                    assertEquals(ra.length(), f.size());
                    break;
                }
                case 6: {
                    trace("reopen");
                    buff.append("reopen\n");
                    f.close();
                    ra.close();
                    ra = new RandomAccessFile(file, "rw");
                    f = FileUtils.open(s, "rw");
                    assertEquals(ra.length(), f.size());
                    break;
                }
                default:
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
            fail("Exception: " + e + "\n"+ buff.toString());
        } finally {
            f.close();
            ra.close();
            file.delete();
            FileUtils.delete(s);
        }
    }

    private static ByteBuffer createSlicedBuffer(byte[] buffer, int offset,
            int len) {
        ByteBuffer byteBuff = ByteBuffer.wrap(buffer);
        byteBuff.position(offset);
        // force the arrayOffset to be non-0
        byteBuff = byteBuff.slice();
        byteBuff.limit(len);
        return byteBuff;
    }

    private void testTempFile(String fsBase) throws Exception {
        int len = 10000;
        String s = FileUtils.createTempFile(fsBase + "/tmp", ".tmp", false, false);
        OutputStream out = FileUtils.newOutputStream(s, false);
        byte[] buffer = new byte[len];
        out.write(buffer);
        out.close();
        out = FileUtils.newOutputStream(s, true);
        out.write(1);
        out.close();
        InputStream in = FileUtils.newInputStream(s);
        for (int i = 0; i < len; i++) {
            assertEquals(0, in.read());
        }
        assertEquals(1, in.read());
        assertEquals(-1, in.read());
        in.close();
        out.close();
        FileUtils.delete(s);
    }

}


text: sqpBackbone.models.countryItem = Backbone.Model.extend({});


text:
<?php

declare(strict_types=1);

namespace App\Tests\Repository;

use App\Entity\AamcMethod;
use App\Entity\DTO\AamcMethodDTO;
use App\Repository\AamcMethodRepository;
use App\Tests\Fixture\LoadAamcMethodData;
use Doctrine\Common\DataFixtures\ReferenceRepository;
use Liip\TestFixturesBundle\Services\DatabaseToolCollection;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\HttpKernel\KernelInterface;

class AamcMethodRepositoryTest extends KernelTestCase
{
    protected ReferenceRepository $fixtures;
    protected AamcMethodRepository $repository;

    protected function setUp(): void
    {
        self::bootKernel();

        $databaseToot = self::$kernel->getContainer()->get(DatabaseToolCollection::class)->get();
        $executor = $databaseToot->loadFixtures([
            LoadAamcMethodData::class
        ]);
        $this->fixtures = $executor->getReferenceRepository();

        $this->repository = self::$kernel->getContainer()
            ->get('doctrine')
            ->getManager()
            ->getRepository(AamcMethod::class);
    }

    public function testFindById()
    {
        $entity = $this->repository->findOneBy(['id' => 'AM002']);
        $this->assertNotNull($entity);
        $this->assertInstanceOf(AamcMethod::class, $entity);
        $this->assertSame('AM002', $entity->getId());
    }

    public function testFindDtoById()
    {
        $dto = $this->repository->findDTOBy(['id' => 'AM002']);
        $this->assertNotNull($dto);
        $this->assertInstanceOf(AamcMethodDTO::class, $dto);
        $this->assertSame('AM002', $dto->id);
    }

    public function testFindDtosBy()
    {
        $dtos = $this->repository->findDTOsBy([]);
        $this->assertIsArray($dtos);
        $this->assertCount(2, $dtos);
        $this->assertInstanceOf(AamcMethodDTO::class, $dtos[0]);
        $this->assertSame('AM001', $dtos[0]->id);
        $this->assertInstanceOf(AamcMethodDTO::class, $dtos[1]);
        $this->assertSame('AM002', $dtos[1]->id);
    }

    public function testFindDtosByWithCacheEnabled()
    {
        $env = getenv('ILIOS_FEATURE_DTO_CACHING');
        putenv("ILIOS_FEATURE_DTO_CACHING=true");
        for ($i = 0; $i <= 1; $i++) {
            $dtos = $this->repository->findDTOsBy([]);
            $this->assertIsArray($dtos);
            $this->assertCount(2, $dtos);
            $this->assertInstanceOf(AamcMethodDTO::class, $dtos[0]);
            $this->assertSame('AM001', $dtos[0]->id);
            $this->assertInstanceOf(AamcMethodDTO::class, $dtos[1]);
            $this->assertSame('AM002', $dtos[1]->id);
        }
        putenv("ILIOS_FEATURE_DTO_CACHING=${env}");
    }

    protected function tearDown(): void
    {
        parent::tearDown();

        unset($this->repository);
    }
}


text:
"""Tests the JSON encoder and decoder."""

import enum

from tensorflow.python.framework import dtypes
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import tensor_spec
from tensorflow.python.keras.saving.saved_model import json_utils
from tensorflow.python.platform import test

class JsonUtilsTest(test.TestCase):

  def test_encode_decode_tensor_shape(self):
    metadata = {
        'key1': tensor_shape.TensorShape(None),
        'key2': [tensor_shape.TensorShape([None]),
                 tensor_shape.TensorShape([3, None, 5])]}
    string = json_utils.Encoder().encode(metadata)
    loaded = json_utils.decode(string)

    self.assertEqual(set(loaded.keys()), {'key1', 'key2'})
    self.assertAllEqual(loaded['key1'].rank, None)
    self.assertAllEqual(loaded['key2'][0].as_list(), [None])
    self.assertAllEqual(loaded['key2'][1].as_list(), [3, None, 5])

  def test_encode_decode_tuple(self):
    metadata = {
        'key1': (3, 5),
        'key2': [(1, (3, 4)), (1,)]}
    string = json_utils.Encoder().encode(metadata)
    loaded = json_utils.decode(string)

    self.assertEqual(set(loaded.keys()), {'key1', 'key2'})
    self.assertAllEqual(loaded['key1'], (3, 5))
    self.assertAllEqual(loaded['key2'], [(1, (3, 4)), (1,)])

  def test_encode_decode_type_spec(self):
    spec = tensor_spec.TensorSpec((1, 5), dtypes.float32)
    string = json_utils.Encoder().encode(spec)
    loaded = json_utils.decode(string)
    self.assertEqual(spec, loaded)

    invalid_type_spec = {'class_name': 'TypeSpec', 'type_spec': 'Invalid Type',
                         'serialized': None}
    string = json_utils.Encoder().encode(invalid_type_spec)
    with self.assertRaisesRegexp(ValueError, 'No TypeSpec has been registered'):
      loaded = json_utils.decode(string)

  def test_encode_decode_enum(self):
    class Enum(enum.Enum):
      CLASS_A = 'a'
      CLASS_B = 'b'
    config = {'key': Enum.CLASS_A, 'key2': Enum.CLASS_B}
    string = json_utils.Encoder().encode(config)
    loaded = json_utils.decode(string)
    self.assertAllEqual({'key': 'a', 'key2': 'b'}, loaded)

if __name__ == '__main__':
  test.main()


text:
<!DOCTYPE HTML>

				<button class="btn btn-primary" th:text="#{admin.drugs.add}"
					data-toggle="modal" data-target="#modalAgregarMedicamento">
				</button>

					<button type="button" class="close" data-dismiss="alert">
						× Close
					</button>

					<button type="button" class="close" data-dismiss="alert">
						× Close
					</button>

												<button type="button" class="btn btn-default onUpdate"
													th:attr="data-id=${drug.idDrug}"
													data-toggle="modal" data-target="#modalUpdateDrug">

												</button>

    	<form id="agregarMedicamentoForm" th:action="@{/admin/drugs/addDrug}" method="post" >

        			<button type="button" class="close" data-dismiss="modal">×Close</button>

    				<input type="text" class="form-control" id="nombre" name="nombre" th:placeholder="#{admin.drugs.nombre}" />

    				<input type="text" class="form-control" id="descripcion" name="descripcion" th:placeholder="#{admin.drugs.descripcion}" />

    				<select id="tipo" name="tipo" class="form-control">
    					<option value="">Seleccione</option>
    					<option value="1">Institucional</option>
    					<option value="0">No Institucional</option>
    				</select>

        		<button type="button" class="btn btn-default" data-dismiss="modal" th:text="#{general.btn.cancelar}"></button>
        		<button type="submit" class="btn btn-primary" th:text="#{general.btn.guardar}"></button>

      		</form>

    	<form id="updateMedicamentoForm" th:action="@{/admin/drugs/updateDrug}" method="post" >

        			<button type="button" class="close" data-dismiss="modal">×Close</button>

	      			<input type="text" id="idUpdate" name="idUpdate" style="display: none;"/>

	    				<input type="text" class="form-control" id="nombreUpdate" name="nombreUpdate" th:placeholder="#{admin.drugs.nombre}" readonly="readonly"/>

	    				<input type="text" class="form-control" id="descripcionUpdate" name="descripcionUpdate" th:placeholder="#{admin.drugs.descripcion}" />

							<input type="radio" id="insitucional" value="1" name="tipo"/> Insitucional

							<input type="radio" id="noInstitucional" value="0" name="tipo"/> No Insitucional

							<input type="radio" id="activo" value="1" name="radio"/> Activo

							<input type="radio" id="desactivo" value="0" name="radio"/> Inactivo

        		<button type="button" class="btn btn-default" data-dismiss="modal" th:text="#{general.btn.cancelar}"></button>
        		<button type="submit" class="btn btn-primary" th:text="#{general.btn.guardar}"></button>

      		</form>