text:
/*************************************************************************/
/*  screen_button.cpp                                                    */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                    http://www.godotengine.org                         */
/*************************************************************************/
/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md)    */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/
#include "screen_button.h"
#include "input_map.h"
#include "os/input.h"
#include "os/os.h"

void TouchScreenButton::set_texture(const Ref<Texture> &p_texture) {

	texture = p_texture;
	update();
}

Ref<Texture> TouchScreenButton::get_texture() const {

	return texture;
}

void TouchScreenButton::set_texture_pressed(const Ref<Texture> &p_texture_pressed) {

	texture_pressed = p_texture_pressed;
	update();
}

Ref<Texture> TouchScreenButton::get_texture_pressed() const {

	return texture_pressed;
}

void TouchScreenButton::set_bitmask(const Ref<BitMap> &p_bitmask) {

	bitmask = p_bitmask;
}

Ref<BitMap> TouchScreenButton::get_bitmask() const {

	return bitmask;
}

void TouchScreenButton::set_shape(const Ref<Shape2D> &p_shape) {

	if (shape.is_valid())
		shape->disconnect("changed", this, "update");

	shape = p_shape;

	if (shape.is_valid())
		shape->connect("changed", this, "update");

	update();
}

Ref<Shape2D> TouchScreenButton::get_shape() const {

	return shape;
}

void TouchScreenButton::set_shape_centered(bool p_shape_centered) {

	shape_centered = p_shape_centered;
	update();
}

bool TouchScreenButton::is_shape_visible() const {

	return shape_visible;
}

void TouchScreenButton::set_shape_visible(bool p_shape_visible) {

	shape_visible = p_shape_visible;
	update();
}

bool TouchScreenButton::is_shape_centered() const {

	return shape_centered;
}

void TouchScreenButton::_notification(int p_what) {

	switch (p_what) {

		case NOTIFICATION_DRAW: {

			if (!is_inside_tree())
				return;
			if (!get_tree()->is_editor_hint() && !OS::get_singleton()->has_touchscreen_ui_hint() && visibility == VISIBILITY_TOUCHSCREEN_ONLY)
				return;

			if (finger_pressed != -1) {

				if (texture_pressed.is_valid())
					draw_texture(texture_pressed, Point2());
				else if (texture.is_valid())
					draw_texture(texture, Point2());

			} else {
				if (texture.is_valid())
					draw_texture(texture, Point2());
			}

			if (!shape_visible)
				return;
			if (!get_tree()->is_editor_hint() && !get_tree()->is_debugging_collisions_hint())
				return;
			if (shape.is_valid()) {
				Color draw_col = get_tree()->get_debug_collisions_color();
				Vector2 pos = shape_centered ? get_item_rect().size * 0.5f : Vector2();
				draw_set_transform_matrix(get_canvas_transform().translated(pos));
				shape->draw(get_canvas_item(), draw_col);
			}

		} break;
		case NOTIFICATION_ENTER_TREE: {

			if (!get_tree()->is_editor_hint() && !OS::get_singleton()->has_touchscreen_ui_hint() && visibility == VISIBILITY_TOUCHSCREEN_ONLY)
				return;
			update();

			if (!get_tree()->is_editor_hint())
				set_process_input(is_visible());

			if (action.operator String() != "" && InputMap::get_singleton()->has_action(action)) {
				action_id = InputMap::get_singleton()->get_action_id(action);
			} else {
				action_id = -1;
			}
		} break;
		case NOTIFICATION_EXIT_TREE: {
			if (is_pressed())
				_release(true);
		} break;
		case NOTIFICATION_VISIBILITY_CHANGED: {
			if (get_tree()->is_editor_hint())
				break;
			if (is_visible()) {
				set_process_input(true);
			} else {
				set_process_input(false);
				if (is_pressed())
					_release();
			}
		} break;
		case NOTIFICATION_PAUSED: {
			if (is_pressed())
				_release();
		} break;
	}
}

bool TouchScreenButton::is_pressed() const {

	return finger_pressed != -1;
}

void TouchScreenButton::set_action(const String &p_action) {

	action = p_action;
	if (action.operator String() != "" && InputMap::get_singleton()->has_action(action)) {
		action_id = InputMap::get_singleton()->get_action_id(action);
	} else {
		action_id = -1;
	}
}

String TouchScreenButton::get_action() const {

	return action;
}

void TouchScreenButton::_input(const InputEvent &p_event) {

	if (!get_tree())
		return;

	if (p_event.device != 0)
		return;

	ERR_FAIL_COND(!is_visible());

	if (passby_press) {

		if (p_event.type == InputEvent::SCREEN_TOUCH && !p_event.screen_touch.pressed && finger_pressed == p_event.screen_touch.index) {

			_release();
		}

		if ((p_event.type == InputEvent::SCREEN_TOUCH && p_event.screen_touch.pressed) || p_event.type == InputEvent::SCREEN_DRAG) {

			if (finger_pressed == -1 || p_event.screen_touch.index == finger_pressed) {

				if (_is_touch_inside(p_event.screen_touch)) {
					if (finger_pressed == -1) {
						_press(p_event.screen_touch.index);
					}
				} else {
					if (finger_pressed != -1) {
						_release();
					}
				}
			}
		}

	} else {

		if (p_event.type == InputEvent::SCREEN_TOUCH) {

			if (p_event.screen_touch.pressed) {

				const bool can_press = finger_pressed == -1;
				if (!can_press)
					return; //already fingering

				if (_is_touch_inside(p_event.screen_touch)) {
					_press(p_event.screen_touch.index);
				}
			} else {
				if (p_event.screen_touch.index == finger_pressed) {
					_release();
				}
			}
		}
	}
}

bool TouchScreenButton::_is_touch_inside(const InputEventScreenTouch &p_touch) {

	Point2 coord = get_global_transform_with_canvas().affine_inverse().xform(Point2(p_touch.x, p_touch.y));

	bool touched = false;
	bool check_rect = true;

	Rect2 item_rect = get_item_rect();

	if (shape.is_valid()) {

		check_rect = false;
		Matrix32 xform = shape_centered ? Matrix32().translated(item_rect.size * 0.5f) : Matrix32();
		touched = shape->collide(xform, unit_rect, Matrix32(0, coord + Vector2(0.5, 0.5)));
	}

	if (bitmask.is_valid()) {

		check_rect = false;
		if (!touched && Rect2(Point2(), bitmask->get_size()).has_point(coord)) {

			if (bitmask->get_bit(coord))
				touched = true;
		}
	}

	if (!touched && check_rect) {

		if (texture.is_valid())
			touched = item_rect.has_point(coord);
	}

	return touched;
}

void TouchScreenButton::_press(int p_finger_pressed) {

	finger_pressed = p_finger_pressed;

	if (action_id != -1) {

		Input::get_singleton()->action_press(action);
		InputEvent ie;
		ie.type = InputEvent::ACTION;
		ie.ID = 0;
		ie.action.action = action_id;
		ie.action.pressed = true;
		get_tree()->input_event(ie);
	}

	emit_signal("pressed");
	update();
}

void TouchScreenButton::_release(bool p_exiting_tree) {

	finger_pressed = -1;

	if (action_id != -1) {

		Input::get_singleton()->action_release(action);
		if (!p_exiting_tree) {
			InputEvent ie;
			ie.type = InputEvent::ACTION;
			ie.ID = 0;
			ie.action.action = action_id;
			ie.action.pressed = false;
			get_tree()->input_event(ie);
		}
	}

	if (!p_exiting_tree) {
		emit_signal("released");
		update();
	}
}

Rect2 TouchScreenButton::get_item_rect() const {

	if (texture.is_null())
		return Rect2(0, 0, 1, 1);
	//if (texture.is_null())
	//	return CanvasItem::get_item_rect();

	return Rect2(Size2(), texture->get_size());
}

void TouchScreenButton::set_visibility_mode(VisibilityMode p_mode) {
	visibility = p_mode;
	update();
}

TouchScreenButton::VisibilityMode TouchScreenButton::get_visibility_mode() const {

	return visibility;
}

void TouchScreenButton::set_passby_press(bool p_enable) {

	passby_press = p_enable;
}

bool TouchScreenButton::is_passby_press_enabled() const {

	return passby_press;
}

void TouchScreenButton::_bind_methods() {

	ObjectTypeDB::bind_method(_MD("set_texture", "texture"), &TouchScreenButton::set_texture);
	ObjectTypeDB::bind_method(_MD("get_texture"), &TouchScreenButton::get_texture);

	ObjectTypeDB::bind_method(_MD("set_texture_pressed", "texture_pressed"), &TouchScreenButton::set_texture_pressed);
	ObjectTypeDB::bind_method(_MD("get_texture_pressed"), &TouchScreenButton::get_texture_pressed);

	ObjectTypeDB::bind_method(_MD("set_bitmask", "bitmask"), &TouchScreenButton::set_bitmask);
	ObjectTypeDB::bind_method(_MD("get_bitmask"), &TouchScreenButton::get_bitmask);

	ObjectTypeDB::bind_method(_MD("set_shape", "shape"), &TouchScreenButton::set_shape);
	ObjectTypeDB::bind_method(_MD("get_shape"), &TouchScreenButton::get_shape);

	ObjectTypeDB::bind_method(_MD("set_shape_centered", "bool"), &TouchScreenButton::set_shape_centered);
	ObjectTypeDB::bind_method(_MD("is_shape_centered"), &TouchScreenButton::is_shape_centered);

	ObjectTypeDB::bind_method(_MD("set_shape_visible", "bool"), &TouchScreenButton::set_shape_visible);
	ObjectTypeDB::bind_method(_MD("is_shape_visible"), &TouchScreenButton::is_shape_visible);

	ObjectTypeDB::bind_method(_MD("set_action", "action"), &TouchScreenButton::set_action);
	ObjectTypeDB::bind_method(_MD("get_action"), &TouchScreenButton::get_action);

	ObjectTypeDB::bind_method(_MD("set_visibility_mode", "mode"), &TouchScreenButton::set_visibility_mode);
	ObjectTypeDB::bind_method(_MD("get_visibility_mode"), &TouchScreenButton::get_visibility_mode);

	ObjectTypeDB::bind_method(_MD("set_passby_press", "enabled"), &TouchScreenButton::set_passby_press);
	ObjectTypeDB::bind_method(_MD("is_passby_press_enabled"), &TouchScreenButton::is_passby_press_enabled);

	ObjectTypeDB::bind_method(_MD("is_pressed"), &TouchScreenButton::is_pressed);

	ObjectTypeDB::bind_method(_MD("_input"), &TouchScreenButton::_input);

	ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "normal", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), _SCS("set_texture"), _SCS("get_texture"));
	ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "pressed", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), _SCS("set_texture_pressed"), _SCS("get_texture_pressed"));
	ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "bitmask", PROPERTY_HINT_RESOURCE_TYPE, "BitMap"), _SCS("set_bitmask"), _SCS("get_bitmask"));
	ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "shape", PROPERTY_HINT_RESOURCE_TYPE, "Shape2D"), _SCS("set_shape"), _SCS("get_shape"));
	ADD_PROPERTY(PropertyInfo(Variant::BOOL, "shape_centered"), _SCS("set_shape_centered"), _SCS("is_shape_centered"));
	ADD_PROPERTY(PropertyInfo(Variant::BOOL, "shape_visible"), _SCS("set_shape_visible"), _SCS("is_shape_visible"));
	ADD_PROPERTY(PropertyInfo(Variant::BOOL, "passby_press"), _SCS("set_passby_press"), _SCS("is_passby_press_enabled"));
	ADD_PROPERTY(PropertyInfo(Variant::STRING, "action"), _SCS("set_action"), _SCS("get_action"));
	ADD_PROPERTY(PropertyInfo(Variant::INT, "visibility_mode", PROPERTY_HINT_ENUM, "Always,TouchScreen Only"), _SCS("set_visibility_mode"), _SCS("get_visibility_mode"));

	ADD_SIGNAL(MethodInfo("pressed"));
	ADD_SIGNAL(MethodInfo("released"));
}

TouchScreenButton::TouchScreenButton() {

	finger_pressed = -1;
	action_id = -1;
	passby_press = false;
	visibility = VISIBILITY_ALWAYS;
	shape_centered = true;
	shape_visible = true;
	unit_rect = Ref<RectangleShape2D>(memnew(RectangleShape2D));
	unit_rect->set_extents(Vector2(0.5, 0.5));
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" />

    <title>File BaseCurve.hxx — Clothoids v2.0.9
</title>
    <link rel="stylesheet" type="text/css" href="../_static/pygments.css" />
    <link rel="stylesheet" type="text/css" href="../_static/cloud.css" />
    <link rel="stylesheet" type="text/css" href="../_static/table_styling.css" />
    <link rel="stylesheet" type="text/css" href="../_static/collapsible-lists/css/tree_view.css" />
    <link rel="stylesheet" type="text/css" href="../_static/collapsible-lists/css/tree_view.css" />
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Noticia+Text:400,i,b,bi|Open+Sans:400,i,b,bi|Roboto+Mono:400,i,b,bi&display=swap" type="text/css" />

    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
        <meta name="viewport" content="width=device-width, initial-scale=1">

Navigation

          index

          toc

Clothoids »

File BaseCurve.hxx

File BaseCurve.hxx¶

↰ Parent directory (Clothoids)

Contents

Definition (Clothoids/BaseCurve.hxx)

Included By

Namespaces

Classes

Enums

Functions

Typedefs

Definition (Clothoids/BaseCurve.hxx)¶

Program Listing for File BaseCurve.hxx

Included By¶

File Clothoids.hh

Namespaces¶

Namespace G2lib

Classes¶

Class BaseCurve

Enums¶

Enum CurveType

Functions¶

Function G2lib::collision_SAE

Function G2lib::intersect_SAE

Typedefs¶

Typedef G2lib::IntersectList

Typedef G2lib::Ipair

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" aria-labelledby="searchlabel" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"/>
      <input type="submit" value="Go" />
    </form>

Table of Contents

Matlab Interface Manual

C++ API

MATLAB API

            <button class="sidebar-toggle" id="sidebar-hide" title="Hide the sidebar menu">
                 «
                hide menu

            </button>
            <button class="sidebar-toggle" id="sidebar-show" title="Show the sidebar menu">

                menu
                sidebar
                 »
            </button>

Navigation

          index

          toc

Clothoids »

File BaseCurve.hxx

        © Copyright 2021, Enrico Bertolazzi and Marco Frego.
      Created using Sphinx 4.2.0.

redpajama_set_name: RedPajamaGithub


text:
using FluentAssertions;
using Microsoft.VisualStudio.Shell;
using SonarLint.VisualStudio.Progress.Observation;
using SonarLint.VisualStudio.Progress.Observation.ViewModels;

namespace SonarLint.VisualStudio.Progress.UnitTests
{
    /// <summary>
    /// Partial class implementation of <see cref="IProgressVisualizer"/>
    /// </summary>
    public partial class ConfigurableProgressVisualizer : IProgressVisualizer
    {
        ProgressControllerViewModel IProgressVisualizer.ViewModel
        {
            get
            {
                this.CheckUIThread();

                return this.viewModel;
            }

            set
            {
                this.CheckUIThread();

                this.viewModel = value;
            }
        }

        void IProgressVisualizer.Show()
        {
            this.CheckUIThread();

            this.IsShown = true;
        }

        void IProgressVisualizer.Hide()
        {
            this.CheckUIThread();

            this.IsShown = false;
        }

        private void CheckUIThread()
        {
            if (this.ThrowIfAccessedNotFromUIThread)
            {
                ThreadHelper.CheckAccess().Should().BeTrue("Wasn't called on the UI thread");
            }
        }
    }
}


text:
<!DOCTYPE html>

		<title>three.js webgl - materials - compressed textures</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

			three.js - webgl - PVR compressed textures


text:
namespace gvisor {
namespace testing {

namespace {

using ::testing::AnyOf;
using ::testing::Eq;

TEST(NetdeviceTest, Loopback) {
  SKIP_IF(IsRunningWithHostinet());
  FileDescriptor sock =
      ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_DGRAM, 0));

  // Prepare the request.
  struct ifreq ifr;
  snprintf(ifr.ifr_name, IFNAMSIZ, "lo");

  // Check for a non-zero interface index.
  ASSERT_THAT(ioctl(sock.get(), SIOCGIFINDEX, &ifr), SyscallSucceeds());
  EXPECT_NE(ifr.ifr_ifindex, 0);

  // Check that the loopback is zero hardware address.
  ASSERT_THAT(ioctl(sock.get(), SIOCGIFHWADDR, &ifr), SyscallSucceeds());
  EXPECT_EQ(ifr.ifr_hwaddr.sa_family, ARPHRD_LOOPBACK);
  EXPECT_EQ(ifr.ifr_hwaddr.sa_data[0], 0);
  EXPECT_EQ(ifr.ifr_hwaddr.sa_data[1], 0);
  EXPECT_EQ(ifr.ifr_hwaddr.sa_data[2], 0);
  EXPECT_EQ(ifr.ifr_hwaddr.sa_data[3], 0);
  EXPECT_EQ(ifr.ifr_hwaddr.sa_data[4], 0);
  EXPECT_EQ(ifr.ifr_hwaddr.sa_data[5], 0);
}

TEST(NetdeviceTest, Netmask) {
  SKIP_IF(IsRunningWithHostinet());
  // We need an interface index to identify the loopback device.
  FileDescriptor sock =
      ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_DGRAM, 0));
  struct ifreq ifr;
  snprintf(ifr.ifr_name, IFNAMSIZ, "lo");
  ASSERT_THAT(ioctl(sock.get(), SIOCGIFINDEX, &ifr), SyscallSucceeds());
  EXPECT_NE(ifr.ifr_ifindex, 0);

  // Use a netlink socket to get the netmask, which we'll then compare to the
  // netmask obtained via ioctl.
  FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(NetlinkBoundSocket(NETLINK_ROUTE));
  uint32_t port = ASSERT_NO_ERRNO_AND_VALUE(NetlinkPortID(fd.get()));

  struct request {
    struct nlmsghdr hdr;
    struct rtgenmsg rgm;
  };

  constexpr uint32_t kSeq = 12345;

  struct request req;
  req.hdr.nlmsg_len = sizeof(req);
  req.hdr.nlmsg_type = RTM_GETADDR;
  req.hdr.nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP;
  req.hdr.nlmsg_seq = kSeq;
  req.rgm.rtgen_family = AF_UNSPEC;

  // Iterate through messages until we find the one containing the prefix length
  // (i.e. netmask) for the loopback device.
  int prefixlen = -1;
  ASSERT_NO_ERRNO(NetlinkRequestResponse(
      fd, &req, sizeof(req),
      [&](const struct nlmsghdr* hdr) {
        EXPECT_THAT(hdr->nlmsg_type, AnyOf(Eq(RTM_NEWADDR), Eq(NLMSG_DONE)));

        EXPECT_TRUE((hdr->nlmsg_flags & NLM_F_MULTI) == NLM_F_MULTI)
            << std::hex << hdr->nlmsg_flags;

        EXPECT_EQ(hdr->nlmsg_seq, kSeq);
        EXPECT_EQ(hdr->nlmsg_pid, port);

        if (hdr->nlmsg_type != RTM_NEWADDR) {
          return;
        }

        // RTM_NEWADDR contains at least the header and ifaddrmsg.
        EXPECT_GE(hdr->nlmsg_len, sizeof(*hdr) + sizeof(struct ifaddrmsg));

        struct ifaddrmsg* ifaddrmsg =
            reinterpret_cast<struct ifaddrmsg*>(NLMSG_DATA(hdr));
        if (ifaddrmsg->ifa_index == static_cast<uint32_t>(ifr.ifr_ifindex) &&
            ifaddrmsg->ifa_family == AF_INET) {
          prefixlen = ifaddrmsg->ifa_prefixlen;
        }
      },
      false));

  ASSERT_GE(prefixlen, 0);

  // Netmask is stored big endian in struct sockaddr_in, so we do the same for
  // comparison.
  uint32_t mask = 0xffffffff << (32 - prefixlen);
  mask = absl::gbswap_32(mask);

  // Check that the loopback interface has the correct subnet mask.
  snprintf(ifr.ifr_name, IFNAMSIZ, "lo");
  ASSERT_THAT(ioctl(sock.get(), SIOCGIFNETMASK, &ifr), SyscallSucceeds());
  EXPECT_EQ(ifr.ifr_netmask.sa_family, AF_INET);
  struct sockaddr_in* sin =
      reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_netmask);
  EXPECT_EQ(sin->sin_addr.s_addr, mask);
}

TEST(NetdeviceTest, InterfaceName) {
  SKIP_IF(IsRunningWithHostinet());
  FileDescriptor sock =
      ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_DGRAM, 0));

  // Prepare the request.
  struct ifreq ifr;
  snprintf(ifr.ifr_name, IFNAMSIZ, "lo");

  // Check for a non-zero interface index.
  ASSERT_THAT(ioctl(sock.get(), SIOCGIFINDEX, &ifr), SyscallSucceeds());
  EXPECT_NE(ifr.ifr_ifindex, 0);

  // Check that SIOCGIFNAME finds the loopback interface.
  snprintf(ifr.ifr_name, IFNAMSIZ, "foo");
  ASSERT_THAT(ioctl(sock.get(), SIOCGIFNAME, &ifr), SyscallSucceeds());
  EXPECT_STREQ(ifr.ifr_name, "lo");
}

TEST(NetdeviceTest, InterfaceFlags) {
  FileDescriptor sock =
      ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_DGRAM, 0));

  // Prepare the request.
  struct ifreq ifr;
  snprintf(ifr.ifr_name, IFNAMSIZ, "lo");

  // Check that SIOCGIFFLAGS marks the interface with IFF_LOOPBACK, IFF_UP, and
  // IFF_RUNNING.
  ASSERT_THAT(ioctl(sock.get(), SIOCGIFFLAGS, &ifr), SyscallSucceeds());
  EXPECT_EQ(ifr.ifr_flags & IFF_UP, IFF_UP);
  EXPECT_EQ(ifr.ifr_flags & IFF_RUNNING, IFF_RUNNING);
}

TEST(NetdeviceTest, InterfaceMTU) {
  SKIP_IF(IsRunningWithHostinet());
  FileDescriptor sock =
      ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_DGRAM, 0));

  // Prepare the request.
  struct ifreq ifr = {};
  snprintf(ifr.ifr_name, IFNAMSIZ, "lo");

  // Check that SIOCGIFMTU returns a nonzero MTU.
  ASSERT_THAT(ioctl(sock.get(), SIOCGIFMTU, &ifr), SyscallSucceeds());
  EXPECT_GT(ifr.ifr_mtu, 0);
}

TEST(NetdeviceTest, InterfaceQLEN) {
  FileDescriptor sock =
      ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_STREAM, 0));

  // Prepare the request.
  struct ifreq ifr = {};
  snprintf(ifr.ifr_name, IFNAMSIZ, "lo");

  // Check that SIOCGIFTXQLEN returns without error.
  ASSERT_THAT(ioctl(sock.get(), SIOCGIFTXQLEN, &ifr), SyscallSucceeds());

  // Gvisor network doesn't implement queues and always returns 0.
  // When exposing the host network, lo could have any queue length set.
  if (IsRunningOnGvisor() && !IsRunningWithHostinet()) {
    EXPECT_EQ(ifr.ifr_qlen, 0);
  }
}

TEST(NetdeviceTest, EthtoolGetTSInfo) {
  SKIP_IF(IsRunningWithHostinet());
  FileDescriptor sock =
      ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_DGRAM, 0));

  struct ethtool_ts_info tsi = {};
  tsi.cmd = ETHTOOL_GET_TS_INFO;  // Get NIC's Timestamping capabilities.

  // Prepare the request.
  struct ifreq ifr = {};
  snprintf(ifr.ifr_name, IFNAMSIZ, "lo");
  ifr.ifr_data = (void*)&tsi;

  // Check that SIOCGIFMTU returns a nonzero MTU.
  if (IsRunningOnGvisor()) {
    ASSERT_THAT(ioctl(sock.get(), SIOCETHTOOL, &ifr),
                SyscallFailsWithErrno(EOPNOTSUPP));
    return;
  }
  ASSERT_THAT(ioctl(sock.get(), SIOCETHTOOL, &ifr), SyscallSucceeds());
}

}  // namespace

}  // namespace testing
}  // namespace gvisor


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.devspaces.fluent.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.devspaces.models.ResourceProviderOperationDisplay;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

/** The ResourceProviderOperationDefinition model. */
@Fluent
public final class ResourceProviderOperationDefinitionInner {
    @JsonIgnore private final ClientLogger logger = new ClientLogger(ResourceProviderOperationDefinitionInner.class);

    /*
     * Resource provider operation name.
     */
    @JsonProperty(value = "name")
    private String name;

    /*
     * The display property.
     */
    @JsonProperty(value = "display")
    private ResourceProviderOperationDisplay display;

    /**
     * Get the name property: Resource provider operation name.
     *
     * @return the name value.
     */
    public String name() {
        return this.name;
    }

    /**
     * Set the name property: Resource provider operation name.
     *
     * @param name the name value to set.
     * @return the ResourceProviderOperationDefinitionInner object itself.
     */
    public ResourceProviderOperationDefinitionInner withName(String name) {
        this.name = name;
        return this;
    }

    /**
     * Get the display property: The display property.
     *
     * @return the display value.
     */
    public ResourceProviderOperationDisplay display() {
        return this.display;
    }

    /**
     * Set the display property: The display property.
     *
     * @param display the display value to set.
     * @return the ResourceProviderOperationDefinitionInner object itself.
     */
    public ResourceProviderOperationDefinitionInner withDisplay(ResourceProviderOperationDisplay display) {
        this.display = display;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (display() != null) {
            display().validate();
        }
    }
}


text:
#include "../Common/libModernAVC_Types.h"

#pragma once

#ifndef LIBMODERNAVC_ParseNAL_H
#define LIBMODERNAVC_ParseNAL_H

#ifdef __cplusplus
extern "C" {
#endif

    void ParseSequenceParameterSetData(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseNALSequenceParameterSetExtended(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseNALSubsetSPS(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseNALSequenceParameterSet(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseNALSequenceParameterSetSVC(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseNALSliceHeader(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseNALSliceData(DecodeAVC *Dec, BitBuffer *BitB, uint8_t Category);

    void ParseNALSlicePartitionA(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseNALSlicePartitionB(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseNALSlicePartitionC(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseVideoUsabilityInformation(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSVCVUIExtension(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSPSMVCDExtension(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSPS3DAVCExtension(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseHypotheticalReferenceDecoder(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseNALMVCExtension(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseNALSVCExtension(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseNAL3DAVCExtension(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseNALDepthParameterSet(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseNALSliceNonPartitioned(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseNALFillerData(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseNALPrefixUnit(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseNALAccessUnitDelimiter(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseMVCDVUIParametersExtension(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseMVCVUIParametersExtension(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseNALPictureParameterSet(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseNALPrefixUnitSVC(DecodeAVC *Dec, BitBuffer *BitB);

    /* Supplementary EnhancementInformation SEI */
    void ParseSEIBufferingPeriod(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIPictureTiming(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIPanScan(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIFiller(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIRegisteredUserData(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIUnregisteredUserData(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIRecoveryPoint(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIRepetitiveReferencePicture(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEISparePicture(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEISceneInfo(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEISubSequenceInfo(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEISubSequenceLayerProperties(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEISubSequenceProperties(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIFullFrameFreeze(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIFullFrameFreezeRelease(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIFullFrameSnapshot(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIProgressiveRefinementSegmentStart(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIProgressiveRefinementSegmentEnd(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIMotionConstrainedSliceGroupSet(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIFilmGrainCharacteristics(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIDeblockingFilterDisplayPreference(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIStereoVideoInfo(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIPostFilterHint(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIToneMappingInfo(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIScalabilityInfo(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEISubPictureScalableLayer(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEINonRequiredLayerRep(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIPriorityLayerInfo(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEILayersNotPresent(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEILayerDependencyChange(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIScalableNesting(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIBaseLayerTemporalHRD(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIQualityLayerIntegrityCheck(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIRedundantPicProperty(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEITemporalDependencyRepresentationIndex(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEITemporalLevelSwitchingPoint(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIParallelDecodingInfo(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIMVCScalableNesting(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIViewScalabilityInfo(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIMVCSceneInfo(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIMVCAcquisitionInfo(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEINonRequiredViewComponent(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIViewDependencyChange(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIOperationPointNotPresent(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIBaseViewTemporalHRD(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIFramePackingArrangement(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIMVCViewPosition(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIDisplayOrientation(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIDepthRepresentationInformation(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEI3DReferenceDisplayInfo(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIDepthTiming(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIDepthSamplingInfo(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIConstrainedDepthParameterSetID(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIMeteringDisplayColorVolume(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIMVCDScalableNesting(DecodeAVC *Dec, BitBuffer *BitB);

    /* Why are these here? */
    void ParseSEIDepthGridPosition(DecodeAVC *Dec, BitBuffer *BitB);

    void ParseSEIDepthRepresentationElement(BitBuffer *BitB, uint8_t OutSign, uint8_t OutExp, uint8_t OutMantissa, uint8_t OutManLen);

    void SkipSEIReservedMessage(BitBuffer *BitB, size_t SEISize);

    void ParseSEIMessage(DecodeAVC *Dec, BitBuffer *BitB);

#ifdef __cplusplus
}
#endif

#endif /* LIBMODERNAVC_ParseNAL_H */


text:
package com.bonorenof.translator.task;

import java.awt.HeadlessException;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.io.PrintStream;
import java.security.GeneralSecurityException;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.bonorenof.translator.display.Display;
import com.bonorenof.translator.display.TextAreaDisplayer;
import com.bonorenof.translator.trigger.KeyPressDetector;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;

import com.bonorenof.translator.engine.Translator;
import com.bonorenof.translator.engine.WebTranslator;

public class Testreader {

	public static void main(String[] args) throws Exception {
		new JFXPanel();
		PrintStream out = new PrintStream(System.out, true, "UTF-8");
		Translator translator = new WebTranslator();

		KeyPressDetector detector = new KeyPressDetector(NativeKeyEvent.VC_V, NativeKeyEvent.CTRL_MASK, true);

		// Get the logger for "org.jnativehook" and set the level to off.
		Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
		logger.setLevel(Level.OFF);

		// Don't forget to disable the parent handlers.
		logger.setUseParentHandlers(false);

		GlobalScreen.registerNativeHook();
		GlobalScreen.addNativeKeyListener(detector);

		Display display = TextAreaDisplayer.getUniqueInstance();
		runDisplay(display);

		while(true) {
			StringBuffer currentData = new StringBuffer();
			String clipboardText = null;
			String oldClipboardText = null;//
			try {
				clipboardText = (String) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor);
			}catch(UnsupportedFlavorException e) {
				cleanClipboard();
			}
			oldClipboardText = clipboardText;

			boolean firstSet = true;
			do {
				Thread.sleep(100);
				if(!firstSet) currentData.replace(0, currentData.length(), display.getUpdatedSourceText());
				try {
					clipboardText = (String) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor);
				}catch(UnsupportedFlavorException e) {
					cleanClipboard();
				}
				if(!clipboardText.equals(oldClipboardText)) {
					currentData.append(clipboardText);
					currentData.append(" ");
					oldClipboardText = clipboardText;

					display.setSourceText(currentData.toString());
					firstSet = false;
				}
			}while(currentData == null || currentData.toString().isEmpty());

			String translatedText = translator.translate("ja", "en", currentData.toString());
			out.println("Nouvelle chaîne dans presse-papier : " + currentData);
			out.println("Traduction chaîne dans presse-papier : " + translatedText);

			display.setTranslatedText(translatedText);

			out.println("retour");
		}
	}

	public static void runDisplay(Display display) {
		Platform.runLater(new Runnable() {

			@Override
			public void run() {
				display.display();
			}
		});
	}

	private static void cleanClipboard() {
		Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
		clipboard.setContents(new Transferable() {
								  public DataFlavor[] getTransferDataFlavors() {
									  return new DataFlavor[0];
								  }

								  public boolean isDataFlavorSupported(DataFlavor flavor) {
									  return false;
								  }

								  public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {
									  throw new UnsupportedFlavorException(flavor);
								  }
		}, null);
	}

/**private static void translate(String scrText, PrintStream out) throws IOException, GeneralSecurityException {
 // See comments on
 //   https://developers.google.com/resources/api-libraries/documentation/translate/v2/java/latest/
 // on options to set
 Translate t = new Translate.Builder(
 GoogleNetHttpTransport.newTrustedTransport()
 , GsonFactory.getDefaultInstance(), null)
 //Need to update this to your App-Name
 .setApplicationName("try-apis")
 .build();

 List list = t.new Translations().list(
 Arrays.asList(scrText),
 //Target language
 "EN");

 //Set your API-Key from https://console.developers.google.com/
 list.setKey("AIzaSyAGTDVqq_E6zSbB84Gj1mnwl22DpgmS_Rs");
 TranslationsListResponse response = list.execute();
 for(TranslationsResource tr : response.getTranslations()) {
 out.println(tr.getTranslatedText());
 }
 }*/
}


text:
$.cloudinary.config().cloud_name = 'hv2ibqtej';
$.cloudinary.config().upload_preset = 'hozil9ox';


text:
package com.svlada.ssh;

import com.jcraft.jsch.*;
import com.svlada.ssh.logger.JschLogger;
import org.apache.commons.lang3.Validate;

import java.nio.file.Path;
import java.nio.file.Paths;

public class PublicKeySshSession {

    final Session session;

    public PublicKeySshSession(final Builder builder) {
        this.session = builder.jschSession;
    }

    public void execute(String command) {
        if (session == null) {
            throw new IllegalArgumentException("Session object is null.");
        }

        if (command != null && command.isEmpty()) {
            throw new IllegalArgumentException("SSH command is blank.");
        }

        try {

            session.connect();

            Channel channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand(command);
            ((ChannelExec) channel).setPty(false);

            channel.connect();

            channel.disconnect();
            session.disconnect();

        } catch (JSchException e) {
            throw new RuntimeException("There was a problem executing the SSH command. Command: " + command);
        }
    }

    public static class Builder {
        private final String host;
        private final String username;
        private final int port;
        private final Path privateKeyPath;
        private com.jcraft.jsch.Logger logger;

        private Session jschSession;

        public Builder(String host, String username, int port, String path) {
            this.host = Validate.notBlank(host);
            this.username = Validate.notBlank(username);
            this.port = port;
            this.privateKeyPath = Paths.get(path);
        }

        private void validate() {
            if (port < 1) {
                throw new IllegalArgumentException("Port number must start with 1.");
            }
        }

        public PublicKeySshSession build() {
            validate();

            if (logger != null) {
                JSch.setLogger(new JschLogger());
            }

            JSch jsch = new JSch();

            Session session = null;

            try {

                jsch.addIdentity(privateKeyPath.toString());

                session = jsch.getSession(username, host, port);
                session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");

                java.util.Properties config = new java.util.Properties();
                config.put("StrictHostKeyChecking", "no");

                session.setConfig(config);

            } catch (JSchException e) {
                throw new RuntimeException("Failed to create Jsch Session object.", e);
            }

            this.jschSession = session;

            return new PublicKeySshSession(this);
        }

        public Builder logger(com.jcraft.jsch.Logger logger) {
            this.logger = logger;
            return this;
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Contact Us</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/business-casual.css" rel="stylesheet">

    <link href="http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Josefin+Slab:100,300,400,600,700,100italic,300italic,400italic,600italic,700italic" rel="stylesheet" type="text/css">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>

                APOG

                        About

                        Calendar

                        Join

                        Sponsors

                        Links

                        Contact

Contact
                        Us

The Analog Planetary Operations Group organizing committee can be reached at info@analogplantearyoperationsgroup.org.

Find
                        Us On Social Media

© 2012-14 Analog Planetary Operations Group. All rights reserved.


text:
import subprocess
import argparse
import os

from ui import ProgressController as pc
from alignment import Aligner

png_prefix = 'slide'
FNULL = open(os.devnull, 'w')

def convertToPNG(pdf):
    foldername, _ = os.path.splitext(pdf)
    foldername = os.path.basename(foldername)
    foldername = os.path.join('PNG_Seq', foldername)
    subprocess.call(['mkdir', '-p' ,foldername])
    subprocess.call(['convert', pdf, foldername, os.path.join(foldername, png_prefix + '.png')], stdout=FNULL, stderr=subprocess.STDOUT)
    return foldername

def align(folder_desc):
    foldername = os.path.basename(folder_desc)
    foldername = os.path.join('aligned/', foldername)
    outputname = os.path.join(foldername, "")
    aligner = Aligner(folder_desc, outputname, 0.2, [1,5])
    aligner.align_slides()
    return foldername

def stitch(sequence):
    subprocess.call(['./stitcher.sh', '-p', os.path.join(sequence, ''), '-f', 'png', '-i', '0', '-o', sequence], stdout=FNULL, stderr=subprocess.STDOUT)

if __name__ == "__main__":
    Parser = argparse.ArgumentParser(description="Generator")
    Parser.add_argument("slides", help="PDF files of the slides", nargs='+')
    Args = Parser.parse_args()
    progress = pc("Generating Videos", len(Args.slides))
    progress.start()
    counter = 0
    for slide in Args.slides:
        stitch(align(convertToPNG(slide)))
        counter += 1
        progress.update(counter)
    progress.finish()


text:
package org.jbpm.workbench.pr.client.editors.definition.details.basic;

import javax.enterprise.context.Dependent;
import javax.inject.Inject;

import com.google.gwt.user.client.ui.IsWidget;
import org.jboss.errai.common.client.api.Caller;
import org.jboss.errai.common.client.api.RemoteCallback;
import org.jbpm.workbench.pr.model.ProcessDefinitionKey;
import org.jbpm.workbench.pr.model.ProcessSummary;
import org.jbpm.workbench.pr.client.editors.definition.details.BaseProcessDefDetailsPresenter;
import org.jbpm.workbench.pr.service.ProcessRuntimeDataService;

@Dependent
public class BasicProcessDefDetailsPresenter extends BaseProcessDefDetailsPresenter {

    public interface BasicProcessDefDetailsView extends
            BaseProcessDefDetailsPresenter.BaseProcessDefDetailsView {

    }

    @Inject
    private BasicProcessDefDetailsView view;

    @Inject
    private Caller<ProcessRuntimeDataService> processRuntimeDataService;

    @Override
    public IsWidget getWidget() {
        return view;
    }

    @Override
    protected void refreshView(  final String serverTemplateId, String currentProcessDefId, String currentDeploymentId ) {
        view.getProcessIdText().setText( currentProcessDefId );
        view.getDeploymentIdText().setText( currentDeploymentId );
    }

    private void refreshProcessItems( final String serverTemplateId, final String deploymentId, final String processId ) {

        processRuntimeDataService.call(new RemoteCallback<ProcessSummary>() {

            @Override
            public void callback( ProcessSummary process ) {
                if (process != null) {
                    view.getProcessNameText().setText( process.getName() );

                    changeStyleRow( process.getName(), process.getVersion() );
                } else {
                    // set to empty to ensure it's clear state
                    view.getProcessNameText().setText( "" );
                }
            }
        } ).getProcess(serverTemplateId, new ProcessDefinitionKey(serverTemplateId, deploymentId, processId));

    }

    @Override
    protected void refreshProcessDef(  final String serverTemplateId, String deploymentId, String processId ) {
        refreshProcessItems( serverTemplateId, deploymentId, processId );
    }
}


text:
<?php
/**
 * Author: Maxim
 * Date: 06/02/14
 * Time: 13:33
 * Property of MCSuite
 */

namespace Maxim\CMSBundle\Helper;

use Doctrine\ORM\EntityManager;
use Maxim\CMSBundle\Entity\Purchase;
use Maxim\CMSBundle\Event\MinecraftSendEvent;
use Maxim\CMSBundle\Exception\CommandExecutionException;
use Monolog\Logger;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

class DeliverHelper
{

    private $eventDispatcher;
    private $minecraft;
    private $entityManager;
    private $config;
    private $logger;

    public function __construct(EventDispatcherInterface $eventDispatcher, MinecraftHelper $minecraft, EntityManager $entityManager, Logger $logger, $config)
    {
        $this->eventDispatcher = $eventDispatcher;
        $this->minecraft = $minecraft;
        $this->entityManager = $entityManager;
        $this->config = $config;
        $this->logger = $logger;
    }

    public function deliver(Purchase $purchase)
    {
        $item = $purchase->getStoreItem();

        try
        {
            switch($item->getType()) {
                case "COMMAND" :
                    $this->eventDispatcher->dispatch("minecraft.send", new MinecraftSendEvent(array($purchase)));
                    break;
                default:
                    $options = array(\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION);
                    $pdo = new \PDO('mysql:host='.$this->config["host"].';dbname='.$this->config["db"], $this->config["user"], $this->config["pass"], $options);
                    $pdo->query($this->minecraft->parseCommand($item->getCommand(), array("USER" => $purchase->getName(), "UUID" => $purchase->getUser()->getMcUuid())));
                    $pdo  = null;
                    $purchase->setStatus(Purchase::PURCHASE_COMPLETE);
                    $purchase->setItemDelivery(Purchase::ITEM_DELIVERY_SUCCESS);
                    $this->entityManager->flush();
            }
            return true;
        }
        catch(\PDOException $ex)
        {
            $this->logger->error("DELIVER:" . $ex->getMessage());
            $purchase->addDetail(Purchase::PURCHASE_ERROR_SQL, $ex->getMessage());
            $purchase->setStatus(Purchase::PURCHASE_ERROR_SQL);
            $purchase->setItemDelivery(Purchase::ITEM_DELIVERY_FAILED);
        }
        catch(CommandExecutionException $ex)
        {
            $this->logger->error("DELIVER:" . $ex->getMessage());
            $purchase->addDetail(Purchase::PURCHASE_ERROR_COMMAND, $ex->getMessage());
            $purchase->setStatus(Purchase::PURCHASE_ERROR_COMMAND);
            $purchase->setItemDelivery(Purchase::ITEM_DELIVERY_FAILED);
        }
        catch(\Exception $ex)
        {
            $this->logger->error("DELIVER:" . $ex->getMessage());
            $purchase->addDetail(Purchase::PURCHASE_ERROR_UNKNOWN, $ex->getMessage());
            $purchase->setStatus(Purchase::PURCHASE_ERROR_UNKNOWN);
            $purchase->setItemDelivery(Purchase::ITEM_DELIVERY_FAILED);
        }

        $this->entityManager->flush();
        return false;
    }
}


text:
@interface AlertEvent : NSObject

@property (weak) NSString *ident;
@property (weak, readonly) NSString *name;
@property (weak, readonly) id target;
@property (assign, readonly) SEL selector;
@property (strong, readonly) NSMutableArray *args;

- (id)initWithName:(NSString *)name target:(id)target selector:(SEL)selector args:(id)arg, ... NS_REQUIRES_NIL_TERMINATION;

@end


text:
from setuptools import setup, find_packages
from hlava import version

setup(
    name=version.__name__,
    version=version.__version__,
    packages=find_packages(),
    license='MIT',
    description='My personal wiki',
    long_description=open('README.md').read(),
    author=version.__author__,
    python_requires="~=3.6",
    author_email='jan.pipek@gmail.com',
    url='https://github.com/janpipek/hlava',
    install_requires = ['appdirs', 'requests', 'six', 'blinker', 'qtawesome', 'pygments', 'GitPython', 'lxml', 'markdown', 'docutils'],
    # Further requires: docx, pyqode, ...
    entry_points = {
        'console_scripts' : [
            'hlava = hlava.cli:console_app'
        ],
        'gui_scripts' : [
            'hlava-qt = hlava.qtui.app:run_app'
        ]
    }
)


text:
/**
 * Created by xiangwenwen on 2017/2/8.
 */

// { "framework": "Vue" }

var webpack = require('webpack');
var path = require('path');
var webacpkConfig = require('../config');
var FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
if (!process.env.NODE_ENV) {
  process.env.NODE_ENV = JSON.parse(config.weex.env.NODE_ENV)
}
var env = process.env.NODE_ENV;
function resolve (dir) {
  return path.join(__dirname, '..', dir)
}
var watch = false;
var plugins = [];
var filename = '[name].js';
if (env === 'production'){
  plugins = [
    new webpack.DefinePlugin({
      'process.env': JSON.stringify(env)
    }),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      }
    })
  ];
} else {
  if (env === 'watch'){
    watch = true;
    filename = '[name]-watch.js';
  } else {
    filename = '[name]-dev.js';
    plugins = [
      new FriendlyErrorsPlugin()
    ];
  }
}

plugins.push(
  new webpack.BannerPlugin({
   raw: true ,
   banner: '// { "framework": "Vue" }\n'
  }),
  new webpack.optimize.ModuleConcatenationPlugin()
);

var config = {
  entry: {
    'weex-bundle': './src/weex.entry.js?entry=true'
  },
  output: {
    path: path.resolve(__dirname, '../dist'),
    filename: filename
  },
  module: {
    rules: [
      {
        test: /\.vue(\?[^?]+)?$/,
        loaders: ['weex-loader'],
        exclude: /node_modules/
      },
      {
        test: /\.js$/,
        loaders: ['babel-loader'],
        exclude: /node_modules/
      }
    ]
  },
  plugins: plugins,
  resolve: {
    alias: {}
  },
  watch: watch
};

if (env !== 'production'){
  config.output.publicPath = webacpkConfig.weex.assetsPublicPath;
}

module.exports = config;


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2022] EMBL-European Bioinformatics Institute

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.

=cut

package XrefMapper::OfficialNaming;

use strict;
use warnings;
use Carp;
use Cwd;
use DBI;
use File::Basename;

use vars '@ISA';
use base qw( XrefMapper::BasicMapper);
#@ISA = qw{ XrefMapper::BasicMapper };

###############################################################################################
# Run the offical naming code.
#
#   At present this is done for the following species ONLY :-
#      ZebraFish (ZFIN_ID),
#      Human (HGNC)
#      Mouse (MGI)
#      Rat (RGD)
#      Pig (PIGGY)
#         There is currently no official domain source for pig, but it has manual annotation
#         We use PIGGY as a fake official naming source
#
#  1) So we find the best official name for each gene
#     order for this is:-
#               i)   official domain name source (HGNC, MGI, ZFIN_ID, RGD)
#               ii)  RFAM
#               iii) miRBase
#               iv)   EntrezGene
#
#      NOTE: for "i)" above, if more than one exists we find the "best" one if possible
#            and remove the other ones. If there is more than one "best" we keep all and
#            just choose the first one for the name
#
#            To find the "best" one we use the priority.
#            Priority should be set correctly in the xref_config.ini file to use
#            first any names coming from the official naming source
#
#      Set this as the display_xref for the gene.
#
#  2) Foreach Transcript of that gene
#
#     we assign a transcript extension (splice number?)
#     This is just a counter starting at 201 which is incremented each time
#     We add this to the name to get a "XXX_trans_name"xref  where XXX is the
#     type of source used to get the name. This is then added as an xref and
#     is set to the display_xref for that transcript.
#
##############################################################################################

####################################
# Create OfficialNaming object
# Get some info from the BasicMapper
####################################
sub new {
  my($class, $mapper) = @_;

  my $self ={};
  bless $self,$class;
  $self->core($mapper->core);
  $self->xref($mapper->xref);
  $self->get_official_name($mapper->get_official_name);
  return $self;
}

##################################################
# This will be the offical database name
# HGNC, MGI, ZFIN_ID or PIGGY, comes from BasicMapper
#################################################
sub get_official_name {
 my ($self, $arg) = @_;

  (defined $arg) &&
    ($self->{_official_name} = $arg );
  return $self->{_official_name};
}

##################################################
# This is the main subroutine that does everything
##################################################
sub run {
  my $self = shift;
  my $species_id = shift;

  my $dbname = $self->get_official_name();
  my $dbi = $self->xref->dbc;

  ###########################################################
  # If no offical name then we do not want to go any further
  # Just set status to official_naming_done and return
  ###########################################################
  if(!defined($dbname)){
    $self->update_process_status("official_naming_done");
    return;
  }
  $species_id = $self->get_id_from_species_name($self->core->species) unless defined $species_id;
  $self->species_id($species_id);

  ###########################################################
  # If there are any official names on transcripts or translations
  # move them onto gene level
  #
  # This is done for 2 reasons
  #  1) to make the code the same as HGNC is on a gene
  #     and it makes it easier to find.
  #  2) Later on these are copied to the canonical transcripts
  #     from the genes so move them now.
  ###########################################################

  if($dbname eq "MGI"){ # Copy MGI to Genes
    $self->biomart_fix("MGI","Translation","Gene");
    $self->biomart_fix("MGI","Transcript","Gene");
  }
  if($dbname eq "ZFIN_ID"){ # Copy ZFIN_ID to Genes
    $self->biomart_fix("ZFIN_ID","Translation","Gene");
    $self->biomart_fix("ZFIN_ID","Transcript","Gene");
  }
  if($dbname eq "RGD"){ # Copy RGD to Genes
    $self->biomart_fix("RGD","Translation","Gene");
    $self->biomart_fix("RGD","Transcript","Gene");
  }

  ######################################################
  # Get the current max values for xref and object_xref
  ######################################################
  my ($max_object_xref_id, $max_xref_id) = $self->find_max_ids($dbi);

  my %display_label_to_desc;
  $self->get_display_label_data(\%display_label_to_desc, $dbi);

  my %synonym;
  $self->get_synonyms(\%synonym, $dbi);

  # get the officail naming external_sources
  my $dbname_to_source_id = $self->get_new_dbname_sources($dbi); # reference to hash

  ###########################
  # Delete the old ones.
  ###########################
  $self->delete_old_data($dbname_to_source_id, $dbi);

  $self->reset_display_xrefs($dbi);

  my $db = new Bio::EnsEMBL::DBSQL::DBAdaptor(-dbconn => $self->core->dbc);
  my $ga = $db->get_GeneAdaptor();

  my %gene_to_transcripts;
  my %gene_id_to_stable_id;
  my %tran_id_to_stable_id;

  my $sql =(<<'SQ0');
SELECT gtt.gene_id, gtt.transcript_id, gsi.stable_id, tsi.stable_id
  FROM gene_transcript_translation gtt, gene_stable_id gsi, transcript_stable_id tsi
    WHERE gtt.gene_id = gsi.internal_id AND
          gtt.transcript_id = tsi.internal_id
    ORDER BY gsi.stable_id, tsi.stable_id
SQ0

  my $sth = $dbi->prepare($sql);

  $sth->execute;
  my ($gene_id, $tran_id, $gsi, $tsi);
  $sth->bind_columns(\$gene_id, \$tran_id, \$gsi, \$tsi);
  my @sorted_gene_ids;
  while ($sth->fetch){
    if(!defined($gene_to_transcripts{$gene_id})){
      push @sorted_gene_ids, $gene_id;
    }
    push @{$gene_to_transcripts{$gene_id}}, $tran_id;
    $gene_id_to_stable_id{$gene_id} = $gsi;
    $tran_id_to_stable_id{$tran_id} = $tsi;
  }

  my $dbentrie_sth = $self->get_dbentrie_sth($dbi);
  my $ins_xref_sth = $self->get_ins_xref_sth($dbi);
  my $ins_dep_ix_sth = $self->get_ins_dep_ix_sth($dbi);
  my $ins_object_xref_sth =  $self->get_ins_object_xref_sth($dbi);
  my $set_gene_display_xref_sth = $self->get_set_gene_display_xref_sth($dbi);

  my %xref_added; # store those added  $xref_added{$accession:$source_id} = $xref_id;
  my %seen_gene;

  my %official_name_used;

  my $ignore_sql =<<IEG;
  SELECT DISTINCT ox.object_xref_id
    FROM object_xref ox, dependent_xref dx,
       xref xmas, xref xdep,
       source smas, source sdep
    WHERE ox.xref_id = dx.dependent_xref_id AND
          dx.dependent_xref_id = xdep.xref_id AND
          dx.master_xref_id = xmas.xref_id AND
          xmas.source_id = smas.source_id AND
          xdep.source_id = sdep.source_id AND
          smas.name like "Refseq%predicted" AND
          sdep.name like "EntrezGene" AND
          ox.ox_status = "DUMP_OUT"
IEG

  my %ignore_object;
  my $ignore_sth = $dbi->prepare($ignore_sql);
  $ignore_sth->execute();
  my ($ignore_object_xref_id);
  $ignore_sth->bind_columns(\$ignore_object_xref_id);
  while($ignore_sth->fetch()){
    $ignore_object{$ignore_object_xref_id} = 1;
  }
  $ignore_sth->finish;

  while ( my $gene_id = shift @sorted_gene_ids){

    my $tran_source = $dbname;

    # symbols to set when found.
    my $gene_symbol = undef;
    my $gene_symbol_xref_id = undef;
    my $is_lrg = 0;

    ################################
    # Get offical name if it has one
    ################################
    ($gene_symbol, $gene_symbol_xref_id) =
      $self->get_official_domain_name({gene_id       => $gene_id,
				       gene_to_tran  => \%gene_to_transcripts,
				       gene_id_to_stable_id => \%gene_id_to_stable_id,
                                       official_name_used => \%official_name_used,
                                       dbi            => $dbi
				      });

    if (defined($gene_symbol_xref_id)) {
	$official_name_used{$gene_symbol_xref_id} = 1;
    }

    ############################################
    # If not found see if there is an LRG entry
    ############################################
    if(!defined($gene_symbol)){ # look for LRG
      ($gene_symbol, $gene_symbol_xref_id, $is_lrg) = $self->find_lrg_hgnc($gene_id, $dbi);
    }

    ####################################################
    # If not found look for other valid database sources
    # These are RFAM and miRBase, as well as EntrezGene
    ####################################################
    if(!defined($gene_symbol)){
      ($gene_symbol, $gene_symbol_xref_id) =
	  $self->find_from_other_sources(\%ignore_object,
                                     {gene_id       => $gene_id,
					label_to_desc => \%display_label_to_desc,
                                      dbi           => $dbi,
					tran_source   => \$tran_source});
    }

    if(defined($gene_symbol)){
      my $desc = $display_label_to_desc{$gene_symbol};
      $set_gene_display_xref_sth->execute($gene_symbol_xref_id, $gene_id);

      if (!$is_lrg) {
        $self->set_transcript_display_xrefs({ max_xref         => \$max_xref_id,
                                            max_object       => \$max_object_xref_id,
                                            gene_id          =>  $gene_id,
                                            gene_id_to_stable_id => \%gene_id_to_stable_id,
					    gene_symbol      => $gene_symbol,
					    desc             => $desc,
                                            dbi              => $dbi,
                                            source_id        => $dbname_to_source_id->{$tran_source."_trans_name"},
                                            xref_added       => \%xref_added,
                                            seen_gene        => \%seen_gene,
                                            gene_to_tran     => \%gene_to_transcripts,
                                            tran_source      => $tran_source,
					   });
      }
    }

  } # for each gene

  $self->update_process_status('official_naming_done');
  return;
}

####################################################################
# Get offical name if it has one
#
# Search gene for dbname entries.
# dbname (HGNC||MGI||ZFIN_ID|RGD) dependent on species
#
# Find the "best" one
# Remove the lesser ones (set status to MULTI_DELETE for object_xref)
#
# return the gene_symbol and xref_id of the best one
######################################################################

sub get_official_domain_name{
  my ($self, $arg_ref) = @_;

  my $gene_id              = $arg_ref->{gene_id};
  my $gene_id_to_stable_id = $arg_ref->{gene_id_to_stable_id};
  my $gene_to_transcripts  = $arg_ref->{gene_to_tran};
  my $official_name_used   = $arg_ref->{official_name_used};
  my $dbi                  = $arg_ref->{dbi};

  my $dbname = $self->get_official_name();
  my $gene_symbol = undef;
  my $gene_symbol_xref_id = undef;

  my $dbentrie_sth = $self->get_dbentrie_sth($dbi);

  my %ODN=();
  my %xref_id_to_display;

  $dbentrie_sth->execute($dbname, $gene_id, "Gene");
  my ($display, $xref_id, $object_xref_id, $level);
  $dbentrie_sth->bind_columns(\$display, \$xref_id, \$object_xref_id, \$level);
  my $best_level=999;

  my $count = 0;
  my @list=();
  my @list_ox=();

  while($dbentrie_sth->fetch){

    push @list, $xref_id;
    push @list_ox, $object_xref_id;
    $count++;
    $xref_id_to_display{$xref_id} = $display;
    if($level < $best_level){
      %ODN = ();
      $ODN{$xref_id} = 1;
      $best_level = $level;
    }
    elsif($level == $best_level){
      $ODN{$xref_id} = 1;
    }
  }

  if(($count > 1) and (scalar(keys %ODN) == 1)){ # found one that is "best" so set it and remove others
    print "For gene ".$gene_id_to_stable_id->{$gene_id}." we have mutiple ".$dbname."'s\n";
    ($gene_symbol, $gene_symbol_xref_id) = $self->set_the_best_odns(\%ODN, \@list, \@list_ox, \%xref_id_to_display, $dbi);
    if(defined($gene_symbol)){
      return $gene_symbol, $gene_symbol_xref_id;
    }
  }

  if(scalar(keys %ODN) == 1){  # one hgnc to this gene - perfect case :-)
      return $xref_id_to_display{(keys %ODN)[0]}, (keys %ODN)[0];
  }
  if(scalar(keys %ODN) > 1){

    #if we have  more than 1 xref, fail xrefs with worse % identity if we can (query or target identity whichever is greater)
    my $identity_sth = $self->get_best_identity_sth($dbi);
    $identity_sth->execute($dbname, $gene_id, "Gene");
    my ($xref_id, $best_identity);
    $identity_sth->bind_columns(\$xref_id, \$best_identity);
    my $temp_best_identity = 0;
    my %best_ids = ();

    while($identity_sth->fetch){

	if($best_identity > $temp_best_identity){
	     %best_ids = ();
	     $best_ids{$xref_id} = 1;
	     $temp_best_identity = $best_identity;
	}
	elsif($best_identity == $temp_best_identity){
	     $best_ids{$xref_id} = 1;
	}
	else {
	     last;
	}
    }

    my %best_list;
    foreach my $xref_id (keys %ODN){
      $best_list{$xref_id_to_display{$xref_id}} = 1;
    }

    # check if we were able to reduce the number of xrefs based on % identity
    if ( scalar(keys %best_ids) > 0 && scalar(keys %best_ids) < scalar(keys %ODN) ) {
	  %ODN = %best_ids;
	  print "For gene ".$gene_id_to_stable_id->{$gene_id}." we have mutiple ".$dbname."'s\n";
	  #set statuses for xrefs with worse % identity to MULTI_DELETE
	  ($gene_symbol, $gene_symbol_xref_id) = $self->set_the_best_odns(\%ODN, \@list, \@list_ox, \%xref_id_to_display, $dbi);
	  if( defined($gene_symbol) && scalar(keys %ODN == 1) ){
	      return $gene_symbol, $gene_symbol_xref_id;
	  }
    }

    # take the name which hasn't been already assigned to another gene, if possible

    my $xref_not_used;
    foreach my $x (keys %ODN){
	  if (!defined($official_name_used->{$x}) ) {
	      $xref_not_used = $x;
	  }
    }
    if ($xref_not_used) {
	  foreach my $x (keys %ODN){
	      print "\t".$xref_id_to_display{$x};
	      if ($x == $xref_not_used) {
		  print "    chosen\n";
		  $gene_symbol =  $xref_id_to_display{$x};
		  $gene_symbol_xref_id =  $x;
	      } else {
		  print "  (left as $dbname reference but not gene symbol)\n";
	      }
	  }

    } else {

	  my $i=0;
	  foreach my $x (keys %ODN){
	      print "\t".$xref_id_to_display{$x};
	      if(!$i){
		  print "  (chosen as first)\n";
		  $gene_symbol =  $xref_id_to_display{$x};
		  $gene_symbol_xref_id =  $x;
	      }
	      else{
		  print "  (left as $dbname reference but not gene symbol)\n";
	      }
	      $i++;
	  }

    }
  }
  return ($gene_symbol, $gene_symbol_xref_id);
}

###########################################################
# Set the transcript display xrefs
#
# Use the gene symbol to create a transcript display xref
# Add 201 and increment.
###########################################################
sub set_transcript_display_xrefs{
  my ($self, $arg_ref) = @_;

  my $max_xref_id =         $arg_ref->{max_xref};
  my $max_object_xref_id =  $arg_ref->{max_object};
  my $gene_id =             $arg_ref->{gene_id};
  my $gene_symbol =         $arg_ref->{gene_symbol};
  my $desc =                $arg_ref->{desc};
  my $source_id =           $arg_ref->{source_id};
  my $xref_added =          $arg_ref->{xref_added};
  my $seen_gene =           $arg_ref->{seen_gene};
  my $gene_to_transcripts = $arg_ref->{gene_to_tran};
  my $tran_source         = $arg_ref->{tran_source};
  my $gene_id_to_stable_id = $arg_ref->{gene_id_to_stable_id};
  my $dbi                  = $arg_ref->{dbi};

  # statement handles needed
  my $ins_xref_sth =              $self->get_ins_xref_sth($dbi);
  my $ins_dep_ix_sth =            $self->get_ins_dep_ix_sth($dbi);
  my $set_tran_display_xref_sth = $self->get_set_transcript_display_xref_sth($dbi);
  my $ins_object_xref_sth =       $self->get_ins_object_xref_sth($dbi);

  if ($gene_id_to_stable_id->{$gene_id} =~ /LRG/) { return; }

  my $ext = 201;
  if(defined($seen_gene->{$gene_symbol})){
    $ext = $seen_gene->{$gene_symbol};
  }

  foreach my $tran_id ( @{$gene_to_transcripts->{$gene_id}} ){
    my $id = $gene_symbol."-".$ext;
    if(!defined($source_id)){
      croak "id = $id\n but NO source_id for this entry for $tran_source???\n";
    }
    if(!defined($xref_added->{$id.":".$source_id})){
      $$max_xref_id++;
      $ins_xref_sth->execute($$max_xref_id, $source_id, $id, $id, "", $desc);
      $xref_added->{$id.":".$source_id} = $$max_xref_id;
    }
    $set_tran_display_xref_sth->execute($xref_added->{$id.":".$source_id}, $tran_id);
    $$max_object_xref_id++;
    $ins_object_xref_sth->execute($$max_object_xref_id, $tran_id, 'Transcript', $xref_added->{$id.":".$source_id},undef);
    $ins_dep_ix_sth->execute($$max_object_xref_id, 100, 100);
    $ext++;
  }
  $seen_gene->{$gene_symbol} = $ext;
  return;
}

#################################################
# Get statement handle to retrieve what xrefs
# are attached to a specific ensembl_id and type
# for a particular source name
#################################################
sub get_dbentrie_sth{
  my $self = shift;
  my $dbi = shift;

  my $sql =(<<"SQ1");
SELECT x.label, x.xref_id, ox.object_xref_id, s.priority
  FROM xref x, object_xref ox, source s
    WHERE x.xref_id = ox.xref_id AND
          x.source_id = s.source_id AND
          s.name = ? AND
          ox.ox_status = 'DUMP_OUT' AND
          ox.ensembl_id = ? AND
          ox.ensembl_object_type = ?
SQ1
  my $sth = $dbi->prepare($sql);
  return $sth;
}

#################################################
# Get statement handle to retrieve what xrefs
# are attached to a specific ensembl_id and type
# for a particular source name with description
#################################################
sub get_dbentrie_with_desc_sth{
  my $self = shift;
  my $dbi = shift;

  my $sql =(<<"SQD");
SELECT x.label, x.xref_id, ox.object_xref_id, s.priority, x.description
  FROM xref x, object_xref ox, source s
    WHERE x.xref_id = ox.xref_id AND
          x.source_id = s.source_id AND
          s.name = ? AND
          ox.ox_status = 'DUMP_OUT' AND
          ox.ensembl_id = ? AND
          ox.ensembl_object_type = ?
SQD
  my $sth = $dbi->prepare($sql);
  return $sth;
}

#################################################
# Get statement handle to retrieve average of query
# and target identity for xrefs
#################################################
sub get_best_identity_sth{
  my $self = shift;
  my $dbi = shift;

  my $sql =(<<"SQD");
SELECT x.xref_id, CASE WHEN ix.query_identity >= ix.target_identity
THEN ix.query_identity ELSE ix.target_identity END as best_identity
FROM xref x, object_xref ox, identity_xref ix, source s
WHERE x.xref_id = ox.xref_id AND x.source_id = s.source_id
 AND ox.object_xref_id = ix.object_xref_id AND s.name = ?
 AND ox.ox_status = 'DUMP_OUT' AND ox.ensembl_id = ?
 AND ox.ensembl_object_type = ? order by best_identity DESC
SQD
  my $sth = $dbi->prepare($sql);
  return $sth;
}

#################################################
# Get statement handle to set the display xref
# for a transcript in the xref database.
# Stored in the transcript_stable_id table.
#################################################
sub get_set_transcript_display_xref_sth {
  my $self = shift;
  my $dbi = shift;
  my $sth = $dbi->prepare('UPDATE transcript_stable_id SET display_xref_id =? where internal_id = ?');
  return $sth;
}

#################################################
# Get statement handle to set the display xref
# for a gene in the xref database.
# Stored in the gene_stable_id table.
#################################################
sub get_set_gene_display_xref_sth {
  my $self = shift;
  my $dbi = shift;
  my $sth = $dbi->prepare('UPDATE gene_stable_id SET display_xref_id =? where internal_id = ?');
  return $sth;
}

###############################################
# Get statement handle to insert an xref
###############################################
sub get_ins_xref_sth{
  my $self= shift;
  my $dbi = shift;

  my $sql = "insert ignore into xref (xref_id, source_id, accession, label, version, species_id, info_type, info_text, description) values (?, ?, ?, ?,  0, ".$self->species_id.", 'MISC', ?, ? )";
  my $sth = $dbi->prepare($sql);
  return $sth;
}

#################################################
# Get statement handle to insert an identity xref
#################################################
sub get_ins_dep_ix_sth{
  my $self= shift;
  my $dbi = shift;

  my $sql = "insert into identity_xref (object_xref_id, query_identity, target_identity) values(?, ?, ?)";
  my $sth = $dbi->prepare($sql);
  return $sth;
}

###############################################
# Get statement handle to insert an object_xref
###############################################
sub get_ins_object_xref_sth{
  my $self= shift;
  my $dbi = shift;

  my $sql = "insert into object_xref (object_xref_id, ensembl_id, ensembl_object_type, xref_id, linkage_type, ox_status, unused_priority) values (?, ?, ?, ?, 'MISC', 'DUMP_OUT', ?)";
  my $sth = $dbi->prepare($sql);
  return $sth;
}

sub find_max_ids{
  my $self = shift;
  my $dbi = shift;

  my ($max_object_xref_id, $max_object_xref_id2, $max_xref_id);

  my $sth = $dbi->prepare("SELECT MAX(object_xref_id) FROM object_xref");
  $sth->execute();
  $sth->bind_columns(\$max_object_xref_id);
  $sth->fetch;

  $sth = $dbi->prepare("SELECT MAX(object_xref_id) FROM identity_xref");
  $sth->execute();
  $sth->bind_columns(\$max_object_xref_id2);
  $sth->fetch;

  $sth = $dbi->prepare("SELECT MAX(xref_id) FROM xref");
  $sth->execute();
  $sth->bind_columns(\$max_xref_id);
  $sth->fetch;

  print "MAX xref_id = $max_xref_id MAX object_xref_id = $max_object_xref_id, max_object_xref from identity_xref = $max_object_xref_id2\n";
  return $max_object_xref_id, $max_xref_id;
}

sub get_synonyms{
  my ($self, $synonym, $dbi) = @_;

  my $dbname = $self->get_official_name();

  my $syn_sql = (<<"SYN");
SELECT es.synonym, x.label
  FROM synonym es, xref x, source s
    WHERE x.xref_id = es.xref_id AND
          x.source_id = s.source_id AND
           s.name = '$dbname'
SYN

  my $sth = $dbi->prepare($syn_sql);
  $sth->execute();
  my ($syn, $name);
  $sth->bind_columns(\$syn,\$name);
  while($sth->fetch){
    $synonym->{$syn} = $name;
  }
  $sth->finish;
  return;
}

sub get_display_label_data{
#  my ($self, $label_to_id, $label_to_desc) = @_;
  my ($self, $label_to_desc, $dbi) = @_;

  my $dbname = $self->get_official_name();

  my $gd1_sql = (<<"GD1");
SELECT x.accession, sy.synonym, x.description
  FROM synonym sy, xref x, source so
    WHERE x.xref_id = sy.xref_id AND
          so.source_id = x.source_id AND
           so.name like '$dbname'
GD1

  my $gd1_sth = $dbi->prepare($gd1_sql);

  $gd1_sth->execute();
  my ($display_label, $acc, $syn, $desc);
  $gd1_sth->bind_columns(\$acc,\$display_label, \$desc);
  while($gd1_sth->fetch){
#    $label_to_id->{$display_label} = $acc;
    $label_to_desc->{$display_label} = $desc;
  }
  $gd1_sth->finish;

  # get label to id from xref database to start with.
  my $gd2_sql = (<<"GD2");
SELECT x.accession, x.label, x.description
   FROM xref x, source s
     WHERE s.source_id = x.source_id AND
            s.name like '$dbname'
GD2

  my $gd2_sth = $dbi->prepare($gd2_sql);

  $gd2_sth->execute();
  $gd2_sth->bind_columns(\$acc,\$display_label, \$desc);
  while($gd2_sth->fetch){
#    $label_to_id->{$display_label} = $acc;
    if(!defined($desc)){
      warn "undef desc for $display_label\n";
    }
    else{
      $label_to_desc->{$display_label} = $desc;
    }
  }
  $gd2_sth->finish;
  return;
}

sub get_other_name_hash{
  my $self = shift;

  if(!defined($self->{'_other_name'})){
    my %hash;
    $self->{'_other_name'} = \%hash;
  }
  return  $self->{'_other_name'};
}

sub find_from_other_sources{
  my ($self, $ignore_object, $ref_args) = @_;
  my $tran_source           = $ref_args->{tran_source};
  my $gene_id               = $ref_args->{gene_id};
  my $display_label_to_desc = $ref_args->{label_to_desc};
  my $dbi                   = $ref_args->{dbi};
  my %ignore_object = %{$ignore_object};

  my ($gene_symbol, $gene_symbol_xref_id);
  my $dbentrie_sth = $self->get_dbentrie_with_desc_sth($dbi);
  my $other_name_num = $self->get_other_name_hash();

  my ($display, $xref_id, $object_xref_id, $level, $desc);
  my %found_gene;
  foreach my $ext_db_name (qw(miRBase RFAM EntrezGene)){
    $dbentrie_sth->execute($ext_db_name, $gene_id, "Gene");
    $dbentrie_sth->bind_columns(\$display, \$xref_id, \$object_xref_id, \$level, \$desc);
    while($dbentrie_sth->fetch){
      if (defined $found_gene{$gene_id}) {
        last;
      }
      if ($display =~ /^LOC/ || $display =~ /^SSC/) {
        next;
      }
      if (defined $ignore_object{$object_xref_id}) {
        next;
      }
      $gene_symbol = $display;
      $gene_symbol_xref_id = $xref_id;
      $$tran_source = $ext_db_name;
      $display_label_to_desc->{$display} = $desc;
      if(defined($other_name_num->{$gene_symbol})){
	$other_name_num->{$gene_symbol}++;
      }
      else{
	$other_name_num->{$gene_symbol} = 1;
      }
      if ($ext_db_name eq 'miRBase' || $ext_db_name eq 'RFAM') {
        $gene_symbol .= ".".$other_name_num->{$gene_symbol};
      }
      $found_gene{$gene_id} = 1;
      next;
    }
  }
  return ($gene_symbol, $gene_symbol_xref_id);
}

#
# We do not delete this but set the status to "MULTI_DELETE"
#

sub get_delete_odn_sth{
  my ($self, $dbi) = @_;

  my $sth = $dbi->prepare('UPDATE object_xref SET ox_status = "MULTI_DELETE" where object_xref_id = ?');
  return $sth;
}

sub set_the_best_odns{
  my ($self, $odn, $ref_list, $ref_list_ox, $ref_xref_id_to_display, $dbi) = @_;

  my $delete_odn_sth = $self->get_delete_odn_sth($dbi);
  my %ODN = %$odn;

  my $gene_symbol = undef;
  my $gene_symbol_xref_id = undef;
  my $i=0;
  while ($i < scalar(@{$ref_list})){
    my $x = $ref_list->[$i];
    if(!exists($ODN{$x})){
      print "\tremoving ".$ref_xref_id_to_display->{$x}." from gene\n";
      #remove object xref....
      $delete_odn_sth->execute($ref_list_ox->[$i])||
	croak "Could not set staus to MULTI_DELETE for object_xref ".$ref_list_ox->[$i]."\n";
    }
    else{
      print "\tKeeping the best one ".$ref_xref_id_to_display->{$x}."\n";
      $gene_symbol = $ref_xref_id_to_display->{$x};
      $gene_symbol_xref_id = $x;
    }
    $i++;
  }
  return ($gene_symbol, $gene_symbol_xref_id);
}

########################## START LRG BIT ######################################################

sub get_lrg_find_sth{
  my $self = shift;
  my $dbi = shift;

  my $sql=(<<'SQ2');
SELECT x.label, x.xref_id, ox.object_xref_id, s.priority
  FROM xref x, object_xref ox, source s
    WHERE x.xref_id = ox.xref_id AND
          x.source_id = s.source_id AND
          s.name = ? AND
          ox.ensembl_id = ? AND
          ox.ensembl_object_type = ?
SQ2
  my $sth = $dbi->prepare($sql);
  return $sth;
}

sub get_lrg_set_status_sth{
  my $self = shift;
  my $dbi = shift;

  my $sth = $dbi->prepare("update object_xref set ox_status = 'NO_DISPLAY' where object_xref_id = ?");
  return $sth;
}

sub get_lrg_to_hgnc_sth{
  my $self = shift;
  my $dbi = shift;

  my $sql=(<<'SQ4');
SELECT x.xref_id, s.priority
  FROM xref x,source s, object_xref ox
    WHERE x.xref_id = ox.xref_id AND
          x.source_id = s.source_id AND
          x.label = ? AND
          s.name = ? AND
          ox.ox_status = 'DUMP_OUT'
    ORDER BY s.priority
SQ4
  my $sth = $dbi->prepare($sql);
  return $sth;
}

sub find_lrg_hgnc{
  my ($self, $gene_id, $dbi) =@_;
  my $gene_symbol;
  my $gene_symbol_xref_id;
  my $is_lrg = 0;

  my $lrg_find_sth = $self->get_lrg_find_sth($dbi);
  my $lrg_set_status_sth = $self->get_lrg_set_status_sth($dbi);
  my $lrg_to_hgnc_sth = $self->get_lrg_to_hgnc_sth($dbi);

  # look for LRG_HGNC_notransfer, if found then find HGNC equiv and set to this
  #      print "LRG FOUND with no HGNC, should have gotten this via the alt allele table?? gene_id = $gene_id\n";
  $lrg_find_sth->execute("LRG_HGNC_notransfer", $gene_id, "Gene");
  my ($display, $xref_id, $object_xref_id, $level);
  $lrg_find_sth->bind_columns(\$display, \$xref_id, \$object_xref_id, \$level);
  while($lrg_find_sth->fetch){
    $lrg_set_status_sth->execute($object_xref_id); # set oc_status to no _display as we do not want this transferred,
                                                   # just the equivalent hgnc
    my $new_xref_id  = undef;
    my $pp;
    $lrg_to_hgnc_sth->execute($display,"HGNC");
	$lrg_to_hgnc_sth->bind_columns(\$new_xref_id,\$pp);
    $lrg_to_hgnc_sth->fetch;
    if(defined($new_xref_id)){
      $gene_symbol = $display;
      $gene_symbol_xref_id = $new_xref_id;
      $is_lrg = 1;
    }
  }
  return ($gene_symbol, $gene_symbol_xref_id, $is_lrg);
}

#############################END LRG BIT ################################################

#
# These are the ones added by official naming and hence
# Need to be removed incase they still exist from a previous run
#
sub get_new_dbname_sources{
  my $self = shift;
  my $dbi = shift;

  my %dbname_to_source_id;

  my $dbname = $self->get_official_name();

  my @list = qw(
Clone_based_ensembl_gene
Clone_based_ensembl_transcript
RFAM_trans_name
miRBase_trans_name
EntrezGene_trans_name);

  push @list, $dbname."_trans_name";
  push @list, $dbname;

  my $sth = $dbi->prepare("select source_id from source where name like ?");

  my $source_error = 0;
  foreach my $source (@list){
    my $id  = undef;
    $sth->execute($source);
    $sth->bind_columns(\$id);
    $sth->fetch();
    if(!defined($id)){
      warn "Could not find external database name $source\n";
      $source_error++;
    }
    else{
      $dbname_to_source_id{$source} = $id;
    }
  }
  if($source_error){
    carp "Could not find name for $source_error database name.\nTherefore Exiting.\nPlease add these sources";
  }
  return \%dbname_to_source_id;
}

sub delete_old_data{
  my ($self, $dbname_to_source_id, $dbi) = @_;

  my $dbname = $self->get_official_name();

 my @sources = qw(
Clone_based_ensembl_gene
Clone_based_ensembl_transcript
EntrezGene_trans_name
RFAM_trans_name
miRBase_trans_name);

  push @sources, $dbname."_trans_name";

  my @source_ids = map {$dbname_to_source_id->{$_}} @sources;
  my $list = join(", ",@source_ids);

  print "LIST to delete $list\n";

  my $sql =(<<"DE1");
DELETE s
  FROM synonym s, xref x
    WHERE s.xref_id = x.xref_id AND
          x.source_id in ( $list );
DE1

  my $sth = $dbi->prepare($sql);
  $sth->execute();

  my $del_identity_sql =(<<"DE2");
DELETE i
  FROM object_xref o, xref x, identity_xref i
    WHERE i.object_xref_id = o.object_xref_id AND
           x.xref_id = o.xref_id AND
            x.source_id in ( $list )
DE2
  $sth = $dbi->prepare($del_identity_sql);
  $sth->execute();

  my $del_ox_sql = (<<"DE3");
DELETE o
  FROM object_xref o, xref x
    WHERE x.xref_id = o.xref_id AND
           x.source_id in ( $list )
DE3
  $sth = $dbi->prepare($del_ox_sql);
  $sth->execute();

  my $del_x_sql = "delete x from xref x where x.source_id in ( $list )";

  $sth = $dbi->prepare($del_x_sql);
  $sth->execute();
  return;
}

sub reset_display_xrefs{
  my $self = shift;
  my $dbi = shift;

  my $sth =  $dbi->prepare("update transcript_stable_id set display_xref_id = null");
  $sth->execute;

  $sth = $self->xref->dbc->prepare("UPDATE gene_stable_id SET display_xref_id = null, desc_set =0");
  $sth->execute;

  return;
}

1;


text:
use super::frontend_prelude::*;

use crate::models::ApiToken;
use crate::schema::api_tokens;
use crate::util::read_fill;
use crate::views::EncodableApiTokenWithToken;

use conduit::{Body, Response};
use serde_json as json;

/// Handles the `GET /me/tokens` route.
pub fn list(req: &mut dyn RequestExt) -> EndpointResult {
    let authenticated_user = req.authenticate()?.forbid_api_token_auth()?;
    let conn = req.db_read_prefer_primary()?;
    let user = authenticated_user.user();

    let tokens: Vec<ApiToken> = ApiToken::belonging_to(&user)
        .filter(api_tokens::revoked.eq(false))
        .order(api_tokens::created_at.desc())
        .load(&*conn)?;

    Ok(req.json(&json!({ "api_tokens": tokens })))
}

/// Handles the `PUT /me/tokens` route.
pub fn new(req: &mut dyn RequestExt) -> EndpointResult {
    /// The incoming serialization format for the `ApiToken` model.
    #[derive(Deserialize, Serialize)]
    struct NewApiToken {
        name: String,
    }

    /// The incoming serialization format for the `ApiToken` model.
    #[derive(Deserialize, Serialize)]
    struct NewApiTokenRequest {
        api_token: NewApiToken,
    }

    let max_size = 2000;
    let length = req
        .content_length()
        .ok_or_else(|| bad_request("missing header: Content-Length"))?;

    if length > max_size {
        return Err(bad_request(&format!("max content length is: {max_size}")));
    }

    let mut json = vec![0; length as usize];
    read_fill(req.body(), &mut json)?;

    let json =
        String::from_utf8(json).map_err(|_| bad_request(&"json body was not valid utf-8"))?;

    let new: NewApiTokenRequest = json::from_str(&json)
        .map_err(|e| bad_request(&format!("invalid new token request: {e:?}")))?;

    let name = &new.api_token.name;
    if name.is_empty() {
        return Err(bad_request("name must have a value"));
    }

    let authenticated_user = req.authenticate()?;
    if authenticated_user.api_token_id().is_some() {
        return Err(bad_request(
            "cannot use an API token to create a new API token",
        ));
    }

    let conn = req.db_write()?;
    let user = authenticated_user.user();

    let max_token_per_user = 500;
    let count: i64 = ApiToken::belonging_to(&user).count().get_result(&*conn)?;
    if count >= max_token_per_user {
        return Err(bad_request(&format!(
            "maximum tokens per user is: {}",
            max_token_per_user
        )));
    }

    let api_token = ApiToken::insert(&conn, user.id, name)?;
    let api_token = EncodableApiTokenWithToken::from(api_token);

    Ok(req.json(&json!({ "api_token": api_token })))
}

/// Handles the `DELETE /me/tokens/:id` route.
pub fn revoke(req: &mut dyn RequestExt) -> EndpointResult {
    let id = req.params()["id"]
        .parse::<i32>()
        .map_err(|e| bad_request(&format!("invalid token id: {e:?}")))?;

    let authenticated_user = req.authenticate()?;
    let conn = req.db_write()?;
    let user = authenticated_user.user();
    diesel::update(ApiToken::belonging_to(&user).find(id))
        .set(api_tokens::revoked.eq(true))
        .execute(&*conn)?;

    Ok(req.json(&json!({})))
}

/// Handles the `DELETE /tokens/current` route.
pub fn revoke_current(req: &mut dyn RequestExt) -> EndpointResult {
    let authenticated_user = req.authenticate()?;
    let api_token_id = authenticated_user
        .api_token_id()
        .ok_or_else(|| bad_request("token not provided"))?;

    let conn = req.db_write()?;
    diesel::update(api_tokens::table.filter(api_tokens::id.eq(api_token_id)))
        .set(api_tokens::revoked.eq(true))
        .execute(&*conn)?;

    Ok(Response::builder().status(204).body(Body::empty()).unwrap())
}


text:
require 'dry/matcher'

module Dry
  class Matcher
    PatternMatch = ::Proc.new do |value, patterns|
      if patterns.empty?
        value
      elsif value.is_a?(::Array) && patterns.any? { |p| p === value[0] }
        value
      elsif patterns.any? { |p| p === value }
        value
      else
        Undefined
      end
    end
  end
end