code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 3 1.01M |
|---|---|---|---|---|---|
/*
* Copyright (C) 2014-2015 Freie Universität Berlin
*
* This file is subject to the terms and conditions of the GNU Lesser General
* Public License v2.1. See the file LICENSE in the top level directory for more
* details.
*/
/**
* @defgroup boards_iotlab-m3 IoT-LAB M3 open node
* @ingroup boards
* @brief Support for the iotlab-m3 board
* @{
*
* @file
* @brief Board specific definitions for the iotlab-m3 board
*
*/
#ifndef BOARD_H
#define BOARD_H
#include <stdint.h>
#include "cpu.h"
#include "periph_conf.h"
#include "board_common.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @name Define the interface for the L3G4200D gyroscope
* @{
*/
#define L3G4200D_I2C I2C_0
#define L3G4200D_ADDR 0x68
#define L3G4200D_DRDY GPIO_PIN(PORT_C,9)
#define L3G4200D_INT GPIO_PIN(PORT_C,6)
/** @} */
/**
* @name Define the interface to the LSM303DLHC accelerometer and magnetometer
* @{
*/
#define LSM303DLHC_I2C I2C_0
#define LSM303DLHC_ACC_ADDR (0x19)
#define LSM303DLHC_MAG_ADDR (0x1e)
#define LSM303DLHC_INT1 GPIO_PIN(PORT_B,12)
#define LSM303DLHC_INT2 GPIO_PIN(PORT_B,2)
#define LSM303DLHC_DRDY GPIO_PIN(PORT_A,11)
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* BOARD_H */
/** @} */
| LudwigKnuepfer/RIOT | boards/iotlab-a8-m3/include/board.h | C | lgpl-2.1 | 1,274 |
/**
* @class UITile
* @extends UIElement
* 是瓦片游戏地图控件,只需要放一个UITile到场景中,地图自动与场景关联。UITile支持由Map Editor Tiled制作的地图。场景中有多个地图时,可以通过UITile的setEnable函数,或用场景的setMap来设置场景当前的地图。
*
* 注意:
*
* 1.在新建地图时请选择CSV格式作为tile layer format,保存时使用JSON格式保存,图片与数据放在同一目录下。
*
* 2.启用物理引擎的方法:在tiled中新建立一个图层,给图层加几个自定义的属性。physics为true表示启用物理引擎,friction表示刚体的摩擦力系数,restitution表示刚体的弹力系数。
*
* 参考:http://www.mapeditor.org
*
*/
/**
* @method getMapWidth
* 获取地图的宽度。
* @return {Number} 返回地图的宽度。
*
*/
/**
* @method getMapHeight
* 获取地图的高度。
* @return {Number} 返回地图的高度。
*
*/
/**
* @method getLayerNr
* 获取地图的层数。
* @return {Number} 返回地图的层数。
*
*/
/**
* @method getLayerByIndex
* 获取地图某层的数据。
* @param {Number} index 层数索引。
* @return {Object} 返回地图某层的数据。layer.info里是tiled生成的原始数据。
*
*/
/**
* @method setClipRegion
* 只显示指定区域的地图。有的游戏中只显示玩家视力范围类的地图,这时可以用本函数实现。
* @param {Array} rects
* @return {UIElement} 返回控件本身。
*
* @example small frame
* var tile = this.win.find("tile");
* tile.setClipRegion([{x:40, y:50, w:100, h:200},{x:200, y:200, w:100, h:200}]);
*/
| drawapp8/cantk | cantk/docs/source/backup/2016_02_29/zh/ui-tile.js | JavaScript | lgpl-2.1 | 1,684 |
/*
* Copyright (C) 2008-2012 Free Software Foundation, Inc.
*
* Author: Simon Josefsson
*
* This file is part of GnuTLS.
*
* GnuTLS is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GnuTLS is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GnuTLS; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <gnutls/gnutls.h>
#include "utils.h"
#include "eagain-common.h"
const char *side;
static void tls_log_func(int level, const char *str)
{
fprintf(stderr, "%s|<%d>| %s", side, level, str);
}
static unsigned char ca_cert_pem[] =
"-----BEGIN CERTIFICATE-----\n"
"MIIC4DCCAcigAwIBAgIBADANBgkqhkiG9w0BAQsFADAPMQ0wCwYDVQQDEwRDQS0w\n"
"MCIYDzIwMTQwNDA0MTk1OTA1WhgPOTk5OTEyMzEyMzU5NTlaMA8xDTALBgNVBAMT\n"
"BENBLTAwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQD46JAPKrTsNTHl\n"
"zD06eIYBF/8Z+TR0wukp9Cdh8Sw77dODLjy/QrVKiDgDZZdyUc8Agsdr86i95O0p\n"
"w19Np3a0wja0VC9uwppZrpuHsrWukwxIBXoViyBc20Y6Ce8j0scCbR10SP565qXC\n"
"i8vr86S4xmQMRZMtwohP/GWQzt45jqkHPYHjdKzwo2b2XI7joDq0dvbr3MSONkGs\n"
"z7A/1Bl3iH5keDTWjqpJRWqXE79IhGOhELy+gG4VLJDGHWCr2mq24b9Kirp+TTxl\n"
"lUwJRbchqUqerlFdt1NgDoGaJyd73Sh0qcZzmEiOI2hGvBtG86tdQ6veC9dl05et\n"
"pM+6RMABAgMBAAGjQzBBMA8GA1UdEwEB/wQFMAMBAf8wDwYDVR0PAQH/BAUDAwcE\n"
"ADAdBgNVHQ4EFgQUGD0RYr2H7kfjQUcBMxSTCDQnhu0wDQYJKoZIhvcNAQELBQAD\n"
"ggEBALnHMubZ6WJ/XOFyDuo0imwg2onrPas3MuKT4+y0aHY943BgAOEc3jKitRjc\n"
"qhb0IUD+NS7itRwNtCgI3v5Ym5nnQoVk+aOD/D724TjJ9XaPQJzOnuGaZX99VN2F\n"
"sgwAtDXedlDQ+I6KLzLd6VW+UyWTG4qiRjOGDnG2kM1wAEOM27TzHV/YWleGjhtA\n"
"bRHxkioOni5goNlTzazxF4v9VD2uinWrIFyZmF6vQuMm6rKFgq6higAU8uesFo7+\n"
"3qpeRjNrPC4fNJUBvv+PC0WnP0PLnD/rY/ZcTYjLb/vJp1fiMJ5fU7jJklBhX2TE\n"
"tstcP7FUV5HA/s9BxgAh0Z2wyyY=\n"
"-----END CERTIFICATE-----\n";
const gnutls_datum_t ca_cert = { ca_cert_pem,
sizeof(ca_cert_pem)
};
static unsigned char server_cert_pem[] =
"-----BEGIN CERTIFICATE-----\n"
"MIIDIzCCAgugAwIBAgIMUz8PCR2sdRK56V6OMA0GCSqGSIb3DQEBCwUAMA8xDTAL\n"
"BgNVBAMTBENBLTEwIhgPMjAxNDA0MDQxOTU5MDVaGA85OTk5MTIzMTIzNTk1OVow\n"
"EzERMA8GA1UEAxMIc2VydmVyLTIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK\n"
"AoIBAQDZ3dCzh9gOTOiOb2dtrPu91fYYgC/ey0ACYjQxaru7FZwnuXPhQK9KHsIV\n"
"YRIyo49wjKZddkHet2sbpFAAeETZh8UUWLRb/mupyaSJMycaYCNjLZCUJTztvXxJ\n"
"CCNfbtgvKC+Vu1mu94KBPatslgvnsamH7AiL5wmwRRqdH/Z93XaEvuRG6Zk0Sh9q\n"
"ZMdCboGfjtmGEJ1V+z5CR+IyH4sckzd8WJW6wBSEwgliGaXnc75xKtFWBZV2njNr\n"
"8V1TOYOdLEbiF4wduVExL5TKq2ywNkRpUfK2I1BcWS5D9Te/QT7aSdE08rL6ztmZ\n"
"IhILSrMOfoLnJ4lzXspz3XLlEuhnAgMBAAGjdzB1MAwGA1UdEwEB/wQCMAAwFAYD\n"
"VR0RBA0wC4IJbG9jYWxob3N0MA8GA1UdDwEB/wQFAwMHoAAwHQYDVR0OBBYEFJXR\n"
"raRS5MVhEqaRE42A3S2BIj7UMB8GA1UdIwQYMBaAFP6S7AyMRO2RfkANgo8YsCl8\n"
"JfJkMA0GCSqGSIb3DQEBCwUAA4IBAQCQ62+skMVZYrGbpab8RI9IG6xH8kEndvFj\n"
"J7wBBZCOlcjOj+HQ7a2buF5zGKRwAOSznKcmvZ7l5DPdsd0t5/VT9LKSbQ6+CfGr\n"
"Xs5qPaDJnRhZkOILCvXJ9qyO+79WNMsg9pWnxkTK7aWR5OYE+1Qw1jG681HMkWTm\n"
"nt7et9bdiNNpvA+L55569XKbdtJLs3hn5gEQFgS7EaEj59aC4vzSTFcidowCoa43\n"
"7JmfSfC9YaAIFH2vriyU0QNf2y7cG5Hpkge+U7uMzQrsT77Q3SDB9WkyPAFNSB4Q\n"
"B/r+OtZXOnQhLlMV7h4XGlWruFEaOBVjFHSdMGUh+DtaLvd1bVXI\n"
"-----END CERTIFICATE-----\n"
"-----BEGIN CERTIFICATE-----\n"
"MIIDATCCAemgAwIBAgIBATANBgkqhkiG9w0BAQsFADAPMQ0wCwYDVQQDEwRDQS0w\n"
"MCIYDzIwMTQwNDA0MTk1OTA1WhgPOTk5OTEyMzEyMzU5NTlaMA8xDTALBgNVBAMT\n"
"BENBLTEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDvhyQfsUm3T0xK\n"
"jiBXO3H6Y27b7lmCRYZQCmXCl2sUsGDL7V9biavTt3+sorWtH542/cTGDh5n8591\n"
"7rVxAB/VASmN55O3fjZyFGrjusjhXBla0Yxe5rZ/7/Pjrq84T7gc/IXiX9Sums/c\n"
"o9AeoykfhsjV2ubhh4h+8uPsHDTcAFTxq3mQaoldwnW2nmjDFzaKLtQdnyFf41o6\n"
"nsJCK/J9PtpdCID5Zb+eQfu5Yhk1iUHe8a9TOstCHtgBq61YzufDHUQk3zsT+VZM\n"
"20lDvSBnHdWLjxoea587JbkvtH8xRR8ThwABSb98qPnhJ8+A7mpO89QO1wxZM85A\n"
"xEweQlMHAgMBAAGjZDBiMA8GA1UdEwEB/wQFMAMBAf8wDwYDVR0PAQH/BAUDAwcE\n"
"ADAdBgNVHQ4EFgQU/pLsDIxE7ZF+QA2CjxiwKXwl8mQwHwYDVR0jBBgwFoAUGD0R\n"
"Yr2H7kfjQUcBMxSTCDQnhu0wDQYJKoZIhvcNAQELBQADggEBANEXLUV+Z1PGTn7M\n"
"3rPT/m/EamcrZJ3vFWrnfN91ws5llyRUKNhx6222HECh3xRSxH9YJONsbv2zY6sd\n"
"ztY7lvckL4xOgWAjoCVTx3hqbZjDxpLRsvraw1PlqBHlRQVWLKlEQ55+tId2zgMX\n"
"Z+wxM7FlU/6yWVPODIxrqYQd2KqaEp4aLIklw6Hi4HD6DnQJikjsJ6Noe0qyX1Tx\n"
"uZ8mgP/G47Fe2d2H29kJ1iJ6hp1XOqyWrVIh/jONcnTvWS8aMqS3MU0EJH2Pb1Qa\n"
"KGIvbd/3H9LykFTP/b7Imdv2fZxXIK8jC+jbF1w6rdBCVNA0p30X/jonoC3vynEK\n"
"5cK0cgs=\n"
"-----END CERTIFICATE-----\n";
const gnutls_datum_t server_cert = { server_cert_pem,
sizeof(server_cert_pem)
};
static unsigned char server_key_pem[] =
"-----BEGIN RSA PRIVATE KEY-----\n"
"MIIEpQIBAAKCAQEA2d3Qs4fYDkzojm9nbaz7vdX2GIAv3stAAmI0MWq7uxWcJ7lz\n"
"4UCvSh7CFWESMqOPcIymXXZB3rdrG6RQAHhE2YfFFFi0W/5rqcmkiTMnGmAjYy2Q\n"
"lCU87b18SQgjX27YLygvlbtZrveCgT2rbJYL57Gph+wIi+cJsEUanR/2fd12hL7k\n"
"RumZNEofamTHQm6Bn47ZhhCdVfs+QkfiMh+LHJM3fFiVusAUhMIJYhml53O+cSrR\n"
"VgWVdp4za/FdUzmDnSxG4heMHblRMS+UyqtssDZEaVHytiNQXFkuQ/U3v0E+2knR\n"
"NPKy+s7ZmSISC0qzDn6C5yeJc17Kc91y5RLoZwIDAQABAoIBAQCRXAu5HPOsZufq\n"
"0K2DYZz9BdqSckR+M8HbVUZZiksDAeIUJwoHyi6qF2eK+B86JiK4Bz+gsBw2ys3t\n"
"vW2bQqM9N/boIl8D2fZfbCgZWkXGtUonC+mgzk+el4Rq/cEMFVqr6/YDwuKNeJpc\n"
"PJc5dcsvpTvlcjgpj9bJAvJEz2SYiIUpvtG4WNMGGapVZZPDvWn4/isY+75T5oDf\n"
"1X5jG0lN9uoUjcuGuThN7gxjwlRkcvEOPHjXc6rxfrWIDdiz/91V46PwpqVDpRrg\n"
"ig6U7+ckS0Oy2v32x0DaDhwAfDJ2RNc9az6Z+11lmY3LPkjG/p8Klcmgvt4/lwkD\n"
"OYRC5QGRAoGBAPFdud6nmVt9h1DL0o4R6snm6P3K81Ds765VWVmpzJkK3+bwe4PQ\n"
"GQQ0I0zN4hXkDMwHETS+EVWllqkK/d4dsE3volYtyTti8zthIATlgSEJ81x/ChAQ\n"
"vvXxgx+zPUnb1mUwy+X+6urTHe4bxN2ypg6ROIUmT+Hx1ITG40LRRiPTAoGBAOcT\n"
"WR8DTrj42xbxAUpz9vxJ15ZMwuIpk3ShE6+CWqvaXHF22Ju4WFwRNlW2zVLH6UMt\n"
"nNfOzyDoryoiu0+0mg0wSmgdJbtCSHoI2GeiAnjGn5i8flQlPQ8bdwwmU6g6I/EU\n"
"QRbGK/2XLmlrGN52gVy9UX0NsAA5fEOsAJiFj1CdAoGBAN9i3nbq6O2bNVSa/8mL\n"
"XaD1vGe/oQgh8gaIaYSpuXlfbjCAG+C4BZ81XgJkfj3CbfGbDNqimsqI0fKsAJ/F\n"
"HHpVMgrOn3L+Np2bW5YMj0Fzwy+1SCvsQ8C+gJwjOLMV6syGp/+6udMSB55rRv3k\n"
"rPnIf+YDumUke4tTw9wAcgkPAoGASHMkiji7QfuklbjSsslRMyDj21gN8mMevH6U\n"
"cX7pduBsA5dDqu9NpPAwnQdHsSDE3i868d8BykuqQAfLut3hPylY6vPYlLHfj4Oe\n"
"dj+xjrSX7YeMBE34qvfth32s1R4FjtzO25keyc/Q2XSew4FcZftlxVO5Txi3AXC4\n"
"bxnRKXECgYEAva+og7/rK+ZjboJVNxhFrwHp9bXhz4tzrUaWNvJD2vKJ5ZcThHcX\n"
"zCig8W7eXHLPLDhi9aWZ3kUZ1RLhrFc/6dujtVtU9z2w1tmn1I+4Zi6D6L4DzKdg\n"
"nMRLFoXufs/qoaJTqa8sQvKa+ceJAF04+gGtw617cuaZdZ3SYRLR2dk=\n"
"-----END RSA PRIVATE KEY-----\n";
const gnutls_datum_t server_key = { server_key_pem,
sizeof(server_key_pem)
};
void doit(void)
{
int exit_code = EXIT_SUCCESS;
int ret;
/* Server stuff. */
gnutls_certificate_credentials_t serverx509cred;
gnutls_session_t server;
int sret = GNUTLS_E_AGAIN;
/* Client stuff. */
gnutls_certificate_credentials_t clientx509cred;
gnutls_session_t client;
int cret = GNUTLS_E_AGAIN;
/* General init. */
global_init();
gnutls_global_set_log_function(tls_log_func);
if (debug)
gnutls_global_set_log_level(6);
/* Init server */
gnutls_certificate_allocate_credentials(&serverx509cred);
gnutls_certificate_set_x509_key_mem(serverx509cred,
&server_cert, &server_key,
GNUTLS_X509_FMT_PEM);
gnutls_init(&server, GNUTLS_SERVER);
gnutls_credentials_set(server, GNUTLS_CRD_CERTIFICATE,
serverx509cred);
gnutls_priority_set_direct(server,
#ifndef ENABLE_FIPS140
"NORMAL:-CIPHER-ALL:+ARCFOUR-128",
#else
"NORMAL:-CIPHER-ALL:+AES-128-CBC",
#endif
NULL);
gnutls_transport_set_push_function(server, server_push);
gnutls_transport_set_pull_function(server, server_pull);
gnutls_transport_set_ptr(server, server);
/* Init client */
ret = gnutls_certificate_allocate_credentials(&clientx509cred);
if (ret < 0)
exit(1);
ret = gnutls_certificate_set_x509_trust_mem(clientx509cred, &ca_cert, GNUTLS_X509_FMT_PEM);
if (ret < 0)
exit(1);
ret = gnutls_init(&client, GNUTLS_CLIENT);
if (ret < 0)
exit(1);
ret = gnutls_credentials_set(client, GNUTLS_CRD_CERTIFICATE,
clientx509cred);
if (ret < 0)
exit(1);
gnutls_priority_set_direct(client, "NORMAL:+ARCFOUR-128", NULL);
gnutls_transport_set_push_function(client, client_push);
gnutls_transport_set_pull_function(client, client_pull);
gnutls_transport_set_ptr(client, client);
HANDSHAKE(client, server);
/* check gnutls_certificate_get_ours() - client side */
{
const gnutls_datum_t *mcert;
mcert = gnutls_certificate_get_ours(client);
if (mcert != NULL) {
fail("gnutls_certificate_get_ours(): failed\n");
exit(1);
}
}
/* check the number of certificates received */
{
unsigned cert_list_size = 0;
gnutls_typed_vdata_st data[2];
unsigned status;
memset(data, 0, sizeof(data));
data[0].type = GNUTLS_DT_DNS_HOSTNAME;
data[0].data = (void*)"localhost1";
data[1].type = GNUTLS_DT_KEY_PURPOSE_OID;
data[1].data = (void*)GNUTLS_KP_TLS_WWW_SERVER;
gnutls_certificate_get_peers(client, &cert_list_size);
if (cert_list_size < 2) {
fprintf(stderr, "received a certificate list of %d!\n", cert_list_size);
exit(1);
}
ret = gnutls_certificate_verify_peers(client, data, 2, &status);
if (ret < 0) {
fprintf(stderr, "could not verify certificate: %s\n", gnutls_strerror(ret));
exit(1);
}
if (status == 0) {
fprintf(stderr, "should not have accepted!\n");
exit(1);
}
data[0].type = GNUTLS_DT_DNS_HOSTNAME;
data[0].data = (void*)"localhost";
ret = gnutls_certificate_verify_peers(client, data, 2, &status);
if (ret < 0) {
fprintf(stderr, "could not verify certificate: %s\n", gnutls_strerror(ret));
exit(1);
}
if (status != 0) {
fprintf(stderr, "could not verify certificate: %.4x\n", status);
exit(1);
}
}
ret = gnutls_session_ext_master_secret_status(client);
if (ret != 1) {
fprintf(stderr, "Extended master secret wasn't negotiated by default (client ret: %d)\n", ret);
exit(1);
}
ret = gnutls_session_ext_master_secret_status(server);
if (ret != 1) {
fprintf(stderr, "Extended master secret wasn't negotiated by default (server ret: %d)\n", ret);
exit(1);
}
gnutls_bye(client, GNUTLS_SHUT_RDWR);
gnutls_bye(server, GNUTLS_SHUT_RDWR);
gnutls_deinit(client);
gnutls_deinit(server);
gnutls_certificate_free_credentials(serverx509cred);
gnutls_certificate_free_credentials(clientx509cred);
gnutls_global_deinit();
if (debug > 0) {
if (exit_code == 0)
puts("Self-test successful");
else
puts("Self-test failed");
}
}
| komh/gnutls-os2 | tests/mini-x509.c | C | lgpl-2.1 | 10,744 |
#!/usr/bin/env python
import sys, math
if len(sys.argv) != 3:
print("Usage:")
print("%s [RA HH:MM:SS] [DEC Deg:Arcmin:Arcsec] " % sys.argv[0])
exit(0)
ra = sys.argv[1]
dec = sys.argv[2]
rai = ra.split(":")
deci = dec.split(":")
radeg = float(rai[0]) * 15.0 + float(rai[1]) * (1.0 / 60.0) + float(rai[2]) * (1.0 / 3600)
decdeg = float(deci[0]) + float(deci[1]) * (1.0 / 60.0) + float(deci[2]) * (1.0 / 3600.0)
print("RA,DEC: %f,%f deg" % (radeg, decdeg))
| ari-zah/gaiasky | core/scripts/radec-conv.py | Python | lgpl-3.0 | 472 |
/* mpfr_signbit -- Signbit of a MPFR number
Copyright 2007-2016 Free Software Foundation, Inc.
Contributed by the AriC and Caramba projects, INRIA.
This file is part of the GNU MPFR Library.
The GNU MPFR Library is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
The GNU MPFR Library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License for more details.
You should have received a copy of the GNU Lesser General Public License
along with the GNU MPFR Library; see the file COPYING.LESSER. If not, see
http://www.gnu.org/licenses/ or write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */
#include "mpfr-impl.h"
#undef mpfr_signbit
int
mpfr_signbit (mpfr_srcptr x)
{
return MPFR_SIGN (x) < 0;
}
| comius/haskell-mpfr | deps/mpfr/src/signbit.c | C | lgpl-3.0 | 1,095 |
/*
SnoreNotify is a Notification Framework based on Qt
Copyright (C) 2014-2015 Hannah von Reth <vonreth@kde.org>
SnoreNotify is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SnoreNotify is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with SnoreNotify. If not, see <http://www.gnu.org/licenses/>.
*/
#include "alert_p.h"
using namespace Snore;
AlertData::AlertData(const QString &key, const QString &name, const Icon &icon):
m_key(key),
m_name(name),
m_icon(icon)
{
}
AlertData::~AlertData()
{
}
| KDE/snorenotify | src/libsnore/alert_p.cpp | C++ | lgpl-3.0 | 1,009 |
package com.arcusys.learn.persistence.liferay.service.persistence;
import com.arcusys.learn.persistence.liferay.model.LFConditionRule;
import com.arcusys.learn.persistence.liferay.service.LFConditionRuleLocalServiceUtil;
import com.liferay.portal.kernel.dao.orm.BaseActionableDynamicQuery;
import com.liferay.portal.kernel.exception.SystemException;
/**
* @author Brian Wing Shun Chan
* @generated
*/
public abstract class LFConditionRuleActionableDynamicQuery
extends BaseActionableDynamicQuery {
public LFConditionRuleActionableDynamicQuery() throws SystemException {
setBaseLocalService(LFConditionRuleLocalServiceUtil.getService());
setClass(LFConditionRule.class);
setClassLoader(com.arcusys.learn.persistence.liferay.service.ClpSerializer.class.getClassLoader());
setPrimaryKeyPropertyName("id");
}
}
| ViLPy/Valamis | learn-persistence-liferay620/src/main/java/com/arcusys/learn/persistence/liferay/service/persistence/LFConditionRuleActionableDynamicQuery.java | Java | lgpl-3.0 | 859 |
/*
* @BEGIN LICENSE
*
* Psi4: an open-source quantum chemistry software package
*
* Copyright (c) 2007-2019 The Psi4 Developers.
*
* The copyrights for code used from other parties are included in
* the corresponding files.
*
* This file is part of Psi4.
*
* Psi4 is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, version 3.
*
* Psi4 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along
* with Psi4; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* @END LICENSE
*/
/*! \file
\ingroup DPD
\brief Enter brief description of file here
*/
#include <cstdio>
#include <cstdlib>
#include "psi4/libqt/qt.h"
#include "dpd.h"
namespace psi {
/* dpd_buf4_mat_irrep_rd(): Reads an entire irrep from disk into a dpd
** four-index buffer using the "rules" specified when the buffer was
** initialized by dpd_buf4_init().
**
** Arguments:
** dpdbuf4 *Buf: A pointer to the dpdbuf4 where the data will
** be stored.
** int irrep: The irrep number to be read.
**
** Tested methods: 11,12,22,31,44. (12/3/96)
**
** There are definitely some problems with the read routines here.
** Mainly in the case of unpacking bra indices, there is a danger that
** the input row buffer won't be filled with new values or zeros. See,
** e.g., method 21.
**
** T. Daniel Crawford
** December 1996
**
** Minor modifications for newest dpd version.
** TDC
** October 1997
**
** Converted to latest version.
** TDC
** September 1999
*/
int DPD::buf4_mat_irrep_rd(dpdbuf4 *Buf, int irrep) {
int method=0;
int filerow, all_buf_irrep;
int pq, rs; /* dpdbuf row and column indices */
int p, q, r, s; /* orbital indices */
int filepq, filers, filesr; /* Input dpdfile row and column indices */
int rowtot, coltot; /* dpdbuf row and column dimensions */
int b_perm_pq, b_perm_rs, b_peq, b_res;
int f_perm_pq, f_perm_rs, f_peq, f_res;
int pq_permute, permute;
double value;
long int size;
#ifdef DPD_TIMER
timer_on("buf_rd");
#endif
all_buf_irrep = Buf->file.my_irrep;
rowtot = Buf->params->rowtot[irrep];
coltot = Buf->params->coltot[irrep ^ all_buf_irrep];
size = ((long)rowtot) * ((long)coltot);
b_perm_pq = Buf->params->perm_pq;
b_perm_rs = Buf->params->perm_rs;
f_perm_pq = Buf->file.params->perm_pq;
f_perm_rs = Buf->file.params->perm_rs;
b_peq = Buf->params->peq;
b_res = Buf->params->res;
f_peq = Buf->file.params->peq;
f_res = Buf->file.params->res;
if ((b_perm_pq == f_perm_pq) && (b_perm_rs == f_perm_rs) && (b_peq == f_peq) && (b_res == f_res)) {
if (Buf->anti)
method = 11;
else
method = 12;
} else if ((b_perm_pq != f_perm_pq) && (b_perm_rs == f_perm_rs) && (b_res == f_res)) {
if (f_perm_pq && !b_perm_pq) {
if (Buf->anti) {
printf("\n\tUnpack pq and antisymmetrize?\n");
exit(PSI_RETURN_FAILURE);
}
method = 21;
} else if (!f_perm_pq && b_perm_pq) {
if (Buf->anti)
method = 22;
else
method = 23;
} else {
printf("\n\tInvalid second-level method!\n");
exit(PSI_RETURN_FAILURE);
}
} else if ((b_perm_pq == f_perm_pq) && (b_perm_rs != f_perm_rs) && (b_peq == f_peq)) {
if (f_perm_rs && !b_perm_rs) {
if (Buf->anti) {
printf("\n\tUnpack rs and antisymmetrize?\n");
exit(PSI_RETURN_FAILURE);
}
method = 31;
} else if (!f_perm_rs && b_perm_rs) {
if (Buf->anti)
method = 32;
else
method = 33;
} else {
printf("\n\tInvalid third-level method!\n");
exit(PSI_RETURN_FAILURE);
}
} else if ((b_perm_pq != f_perm_pq) && (b_perm_rs != f_perm_rs)) {
if (f_perm_pq && !b_perm_pq) {
if (f_perm_rs && !b_perm_rs) {
if (Buf->anti) {
printf("\n\tUnpack pq and rs and antisymmetrize?\n");
exit(PSI_RETURN_FAILURE);
} else
method = 41;
} else if (!f_perm_rs && b_perm_rs) {
if (Buf->anti) {
printf("\n\tUnpack pq and antisymmetrize?\n");
exit(PSI_RETURN_FAILURE);
} else
method = 42;
}
} else if (!f_perm_pq && b_perm_pq) {
if (f_perm_rs && !b_perm_rs) {
if (Buf->anti) {
printf("\n\tUnpack rs and antisymmetrize?\n");
exit(PSI_RETURN_FAILURE);
} else
method = 43;
} else if (!f_perm_rs && b_perm_rs) {
if (Buf->anti)
method = 44;
else
method = 45;
}
} else {
printf("\n\tInvalid fourth-level method!\n");
exit(PSI_RETURN_FAILURE);
}
} else {
printf("\n\tInvalid method in dpd_buf_mat_irrep_rd!\n");
exit(PSI_RETURN_FAILURE);
}
switch (method) {
case 11: /* No change in pq or rs; antisymmetrize */
#ifdef DPD_TIMER
timer_on("buf_rd_11");
#endif
/* Prepare the input buffer from the input file */
file4_mat_irrep_row_init(&(Buf->file), irrep);
/* Loop over rows in the dpdbuf/dpdfile */
for (pq = 0; pq < rowtot; pq++) {
/* Fill the buffer */
file4_mat_irrep_row_rd(&(Buf->file), irrep, pq);
filerow = Buf->file.incore ? pq : 0;
/* Loop over the columns in the dpdbuf */
for (rs = 0; rs < coltot; rs++) {
r = Buf->params->colorb[irrep ^ all_buf_irrep][rs][0];
s = Buf->params->colorb[irrep ^ all_buf_irrep][rs][1];
/* Column indices in the dpdfile */
filers = rs;
filesr = Buf->file.params->colidx[s][r];
value = Buf->file.matrix[irrep][filerow][filers];
value -= Buf->file.matrix[irrep][filerow][filesr];
/* Assign the value */
Buf->matrix[irrep][pq][rs] = value;
}
}
/* Close the input buffer */
file4_mat_irrep_row_close(&(Buf->file), irrep);
#ifdef DPD_TIMER
timer_off("buf_rd_11");
#endif
break;
case 12: /* No change in pq or rs */
#ifdef DPD_TIMER
timer_on("buf_rd_12");
#endif
// if(Buf->file.incore && size) {
// /* We shouldn't actually have to do anything here since the
// pointer to the data should already have been copied in
// buf4_mat_irrep_init(). */
// continue;
// }
// else {
// Buf->file.matrix[irrep] = Buf->matrix[irrep];
// dpd_file4_mat_irrep_rd(&(Buf->file), irrep);
// }
if (!(Buf->file.incore && size)) {
Buf->file.matrix[irrep] = Buf->matrix[irrep];
file4_mat_irrep_rd(&(Buf->file), irrep);
}
#ifdef DPD_TIMER
timer_off("buf_rd_12");
#endif
break;
case 21: /* Unpack pq; no change in rs */
#ifdef DPD_TIMER
timer_on("buf_rd_21");
#endif
/* Prepare the input buffer from the input file */
file4_mat_irrep_row_init(&(Buf->file), irrep);
/* Loop over rows in the dpdbuf */
for (pq = 0; pq < rowtot; pq++) {
p = Buf->params->roworb[irrep][pq][0];
q = Buf->params->roworb[irrep][pq][1];
filepq = Buf->file.params->rowidx[p][q];
filerow = Buf->file.incore ? filepq : 0;
/* Set the permutation operator's value */
permute = ((p < q) && (f_perm_pq < 0) ? -1 : 1);
/* Fill the buffer */
if (filepq >= 0)
file4_mat_irrep_row_rd(&(Buf->file), irrep, filepq);
else
file4_mat_irrep_row_zero(&(Buf->file), irrep, filepq);
/* Loop over the columns in the dpdbuf */
for (rs = 0; rs < coltot; rs++) {
filers = rs;
if (filepq >= 0)
value = Buf->file.matrix[irrep][filerow][filers];
else
value = 0;
/* Assign the value, keeping track of the sign */
Buf->matrix[irrep][pq][rs] = permute * value;
}
}
/* Close the input buffer */
file4_mat_irrep_row_close(&(Buf->file), irrep);
#ifdef DPD_TIMER
timer_off("buf_rd_21");
#endif
break;
case 22: /* Pack pq; no change in rs; antisymmetrize */
#ifdef DPD_TIMER
timer_on("buf_rd_22");
#endif
/* Prepare the input buffer from the input file */
file4_mat_irrep_row_init(&(Buf->file), irrep);
/* Loop over rows in the dpdbuf */
for (pq = 0; pq < rowtot; pq++) {
p = Buf->params->roworb[irrep][pq][0];
q = Buf->params->roworb[irrep][pq][1];
filepq = Buf->file.params->rowidx[p][q];
filerow = Buf->file.incore ? filepq : 0;
/* Fill the buffer */
file4_mat_irrep_row_rd(&(Buf->file), irrep, filepq);
/* Loop over the columns in the dpdbuf */
for (rs = 0; rs < coltot; rs++) {
r = Buf->params->colorb[irrep ^ all_buf_irrep][rs][0];
s = Buf->params->colorb[irrep ^ all_buf_irrep][rs][1];
/* Column indices in the dpdfile */
filers = rs;
filesr = Buf->file.params->colidx[s][r];
value = Buf->file.matrix[irrep][filerow][filers];
value -= Buf->file.matrix[irrep][filerow][filesr];
/* Assign the value */
Buf->matrix[irrep][pq][rs] = value;
}
}
/* Close the input buffer */
file4_mat_irrep_row_close(&(Buf->file), irrep);
#ifdef DPD_TIMER
timer_off("buf_rd_22");
#endif
break;
case 23: /* Pack pq; no change in rs */
#ifdef DPD_TIMER
timer_on("buf_rd_23");
#endif
/* Prepare the input buffer from the input file */
file4_mat_irrep_row_init(&(Buf->file), irrep);
/* Loop over rows in the dpdbuf */
for (pq = 0; pq < rowtot; pq++) {
p = Buf->params->roworb[irrep][pq][0];
q = Buf->params->roworb[irrep][pq][1];
filepq = Buf->file.params->rowidx[p][q];
filerow = Buf->file.incore ? filepq : 0;
file4_mat_irrep_row_rd(&(Buf->file), irrep, filepq);
/* Loop over the columns in the dpdbuf */
for (rs = 0; rs < coltot; rs++) {
filers = rs;
value = Buf->file.matrix[irrep][filerow][filers];
/* Assign the value */
Buf->matrix[irrep][pq][rs] = value;
}
}
/* Close the input buffer */
file4_mat_irrep_row_close(&(Buf->file), irrep);
#ifdef DPD_TIMER
timer_off("buf_rd_23");
#endif
break;
case 31: /* No change in pq; unpack rs */
#ifdef DPD_TIMER
timer_on("buf_rd_31");
#endif
/* Prepare the input buffer from the input file */
file4_mat_irrep_row_init(&(Buf->file), irrep);
/* Loop over rows in the dpdbuf/dpdfile */
for (pq = 0; pq < rowtot; pq++) {
filepq = pq;
filerow = Buf->file.incore ? filepq : 0;
/* Fill the buffer */
file4_mat_irrep_row_rd(&(Buf->file), irrep, filepq);
/* Loop over the columns in the dpdbuf */
for (rs = 0; rs < coltot; rs++) {
r = Buf->params->colorb[irrep ^ all_buf_irrep][rs][0];
s = Buf->params->colorb[irrep ^ all_buf_irrep][rs][1];
filers = Buf->file.params->colidx[r][s];
/* rs permutation operator */
permute = ((r < s) && (f_perm_rs < 0) ? -1 : 1);
/* Is this fast enough? */
value = ((filers < 0) ? 0 : Buf->file.matrix[irrep][filerow][filers]);
/* Assign the value */
Buf->matrix[irrep][pq][rs] = permute * value;
}
}
/* Close the input buffer */
file4_mat_irrep_row_close(&(Buf->file), irrep);
#ifdef DPD_TIMER
timer_off("buf_rd_31");
#endif
break;
case 32: /* No change in pq; pack rs; antisymmetrize */
#ifdef DPD_TIMER
timer_on("buf_rd_32");
#endif
/* Prepare the input buffer from the input file */
file4_mat_irrep_row_init(&(Buf->file), irrep);
/* Loop over rows in the dpdbuf/dpdfile */
for (pq = 0; pq < rowtot; pq++) {
filepq = pq;
filerow = Buf->file.incore ? filepq : 0;
/* Fill the buffer */
file4_mat_irrep_row_rd(&(Buf->file), irrep, filepq);
/* Loop over the columns in the dpdbuf */
for (rs = 0; rs < coltot; rs++) {
r = Buf->params->colorb[irrep ^ all_buf_irrep][rs][0];
s = Buf->params->colorb[irrep ^ all_buf_irrep][rs][1];
/* Column indices in the dpdfile */
filers = Buf->file.params->colidx[r][s];
filesr = Buf->file.params->colidx[s][r];
value = Buf->file.matrix[irrep][filerow][filers];
value -= Buf->file.matrix[irrep][filerow][filesr];
/* Assign the value */
Buf->matrix[irrep][pq][rs] = value;
}
}
/* Close the input buffer */
file4_mat_irrep_row_close(&(Buf->file), irrep);
#ifdef DPD_TIMER
timer_off("buf_rd_32");
#endif
break;
case 33: /* No change in pq; pack rs */
#ifdef DPD_TIMER
timer_on("buf_rd_33");
#endif
/* Prepare the input buffer from the input file */
file4_mat_irrep_row_init(&(Buf->file), irrep);
/* Loop over rows in the dpdbuf/dpdfile */
for (pq = 0; pq < rowtot; pq++) {
filepq = pq;
filerow = Buf->file.incore ? filepq : 0;
/* Fill the buffer */
file4_mat_irrep_row_rd(&(Buf->file), irrep, filepq);
/* Loop over the columns in the dpdbuf */
for (rs = 0; rs < coltot; rs++) {
r = Buf->params->colorb[irrep ^ all_buf_irrep][rs][0];
s = Buf->params->colorb[irrep ^ all_buf_irrep][rs][1];
filers = Buf->file.params->colidx[r][s];
value = Buf->file.matrix[irrep][filerow][filers];
/* Assign the value */
Buf->matrix[irrep][pq][rs] = value;
}
}
/* Close the input buffer */
file4_mat_irrep_row_close(&(Buf->file), irrep);
#ifdef DPD_TIMER
timer_off("buf_rd_33");
#endif
break;
case 41: /* Unpack pq and rs */
#ifdef DPD_TIMER
timer_on("buf_rd_41");
#endif
/* Prepare the input buffer from the input file */
file4_mat_irrep_row_init(&(Buf->file), irrep);
/* Loop over rows in the dpdbuf */
for (pq = 0; pq < rowtot; pq++) {
p = Buf->params->roworb[irrep][pq][0];
q = Buf->params->roworb[irrep][pq][1];
filepq = Buf->file.params->rowidx[p][q];
filerow = Buf->file.incore ? filepq : 0;
/* Set the value of the pq permutation operator */
pq_permute = ((p < q) && (f_perm_pq < 0) ? -1 : 1);
/* Fill the buffer */
if (filepq >= 0)
file4_mat_irrep_row_rd(&(Buf->file), irrep, filepq);
else
file4_mat_irrep_row_zero(&(Buf->file), irrep, filepq);
/* Loop over the columns in the dpdbuf */
for (rs = 0; rs < coltot; rs++) {
r = Buf->params->colorb[irrep ^ all_buf_irrep][rs][0];
s = Buf->params->colorb[irrep ^ all_buf_irrep][rs][1];
filers = Buf->file.params->colidx[r][s];
/* Set the value of the pqrs permutation operator */
permute = ((r < s) && (f_perm_rs < 0) ? -1 : 1) * pq_permute;
value = 0;
if (filers >= 0 && filepq >= 0) value = Buf->file.matrix[irrep][filerow][filers];
/* Assign the value */
Buf->matrix[irrep][pq][rs] = permute * value;
}
}
/* Close the input buffer */
file4_mat_irrep_row_close(&(Buf->file), irrep);
#ifdef DPD_TIMER
timer_off("buf_rd_41");
#endif
break;
case 42: /* Pack pq; unpack rs */
printf("\n\tHaven't programmed method 42 yet!\n");
exit(PSI_RETURN_FAILURE);
break;
case 43: /* Unpack pq; pack rs */
printf("\n\tHaven't programmed method 43 yet!\n");
exit(PSI_RETURN_FAILURE);
break;
case 44: /* Pack pq; pack rs; antisymmetrize */
#ifdef DPD_TIMER
timer_on("buf_rd_44");
#endif
/* Prepare the input buffer from the input file */
file4_mat_irrep_row_init(&(Buf->file), irrep);
/* Loop over rows in the dpdbuf */
for (pq = 0; pq < rowtot; pq++) {
p = Buf->params->roworb[irrep][pq][0];
q = Buf->params->roworb[irrep][pq][1];
filepq = Buf->file.params->rowidx[p][q];
filerow = Buf->file.incore ? filepq : 0;
/* Fill the buffer */
file4_mat_irrep_row_rd(&(Buf->file), irrep, filepq);
/* Loop over the columns in the dpdbuf */
for (rs = 0; rs < coltot; rs++) {
r = Buf->params->colorb[irrep ^ all_buf_irrep][rs][0];
s = Buf->params->colorb[irrep ^ all_buf_irrep][rs][1];
/* Column indices in the dpdfile */
filers = Buf->file.params->colidx[r][s];
filesr = Buf->file.params->colidx[s][r];
value = Buf->file.matrix[irrep][filerow][filers];
value -= Buf->file.matrix[irrep][filerow][filesr];
/* Assign the value */
Buf->matrix[irrep][pq][rs] = value;
}
}
/* Close the input buffer */
file4_mat_irrep_row_close(&(Buf->file), irrep);
#ifdef DPD_TIMER
timer_off("buf_rd_44");
#endif
break;
case 45: /* Pack pq and rs */
#ifdef DPD_TIMER
timer_on("buf_rd_45");
#endif
/* Prepare the input buffer from the input file */
file4_mat_irrep_row_init(&(Buf->file), irrep);
/* Loop over rows in the dpdbuf */
for (pq = 0; pq < rowtot; pq++) {
p = Buf->params->roworb[irrep][pq][0];
q = Buf->params->roworb[irrep][pq][1];
filepq = Buf->file.params->rowidx[p][q];
filerow = Buf->file.incore ? filepq : 0;
file4_mat_irrep_row_rd(&(Buf->file), irrep, filepq);
/* Loop over the columns in the dpdbuf */
for (rs = 0; rs < coltot; rs++) {
r = Buf->params->colorb[irrep ^ all_buf_irrep][rs][0];
s = Buf->params->colorb[irrep ^ all_buf_irrep][rs][1];
filers = Buf->file.params->colidx[r][s];
if (filers < 0) {
printf("\n\tNegative colidx in method 44?\n");
exit(PSI_RETURN_FAILURE);
}
value = Buf->file.matrix[irrep][filerow][filers];
/* Assign the value */
Buf->matrix[irrep][pq][rs] = value;
}
}
/* Close the input buffer */
file4_mat_irrep_row_close(&(Buf->file), irrep);
#ifdef DPD_TIMER
timer_off("buf_rd_45");
#endif
break;
default: /* Error trapping */
printf("\n\tInvalid switch case in dpd_buf_mat_irrep_rd!\n");
exit(PSI_RETURN_FAILURE);
break;
}
#ifdef DPD_TIMER
timer_off("buf_rd");
#endif
return 0;
}
} // namespace psi
| dgasmith/psi4 | psi4/src/psi4/libdpd/buf4_mat_irrep_rd.cc | C++ | lgpl-3.0 | 21,803 |
/**
* This file was auto-generated by mofcomp -j version 1.0.0 on Wed Jan 12
* 09:21:06 CET 2011.
*/
package org.opennaas.extensions.router.model;
import java.io.*;
import java.lang.Exception;
/**
* This Class contains accessor and mutator methods for all properties defined in the CIM class PeerIDPayloadFilterEntry as well as methods comparable
* to the invokeMethods defined for this class. This Class implements the PeerIDPayloadFilterEntryBean Interface. The CIM class
* PeerIDPayloadFilterEntry is described as follows:
*
* PeerIDPayloadFilterEntry defines filters used to match the Identification Type field in the ID Payload of the IKE protocol exchange. It permits the
* specification of ID values such as "*@example.com" or "192.0.2.0/24".
*/
public class PeerIDPayloadFilterEntry extends FilterEntryBase implements
Serializable {
/**
* This constructor creates a PeerIDPayloadFilterEntryBeanImpl Class which implements the PeerIDPayloadFilterEntryBean Interface, and encapsulates
* the CIM class PeerIDPayloadFilterEntry in a Java Bean. The CIM class PeerIDPayloadFilterEntry is described as follows:
*
* PeerIDPayloadFilterEntry defines filters used to match the Identification Type field in the ID Payload of the IKE protocol exchange. It permits
* the specification of ID values such as "*@example.com" or "192.0.2.0/24".
*/
public PeerIDPayloadFilterEntry() {
};
/**
* The following constants are defined for use with the ValueMap/Values qualified property MatchIdentityType.
*/
public enum MatchIdentityType {
OTHER,
IPV4_ADDRESS,
FQDN,
USER_FQDN,
IPV4_SUBNET_ADDRESS,
IPV6_ADDRESS,
IPV6_SUBNET_ADDRESS,
IPV4_ADDRESS_RANGE,
IPV6_ADDRESS_RANGE,
DER_ASN1_DN,
DER_ASN1_GN,
KEY_ID,
DMTF_RESERVED,
VENDOR_RESERVED
}
private MatchIdentityType matchIdentityType;
/**
* This method returns the PeerIDPayloadFilterEntry.matchIdentityType property value. This property is described as follows:
*
* MatchIdentityType specifies the Identification Type provided by the peer in the payload. The list of identities was generated from Section
* 4.6.2.1 of RFC2407. Note that the enumeration is different than the RFC list, since the value 'Other' is taken into account.
*
* @return int current matchIdentityType property value
* @exception Exception
*/
public MatchIdentityType getMatchIdentityType() {
return this.matchIdentityType;
} // getMatchIdentityType
/**
* This method sets the PeerIDPayloadFilterEntry.matchIdentityType property value. This property is described as follows:
*
* MatchIdentityType specifies the Identification Type provided by the peer in the payload. The list of identities was generated from Section
* 4.6.2.1 of RFC2407. Note that the enumeration is different than the RFC list, since the value 'Other' is taken into account.
*
* @param int new matchIdentityType property value
* @exception Exception
*/
public void setMatchIdentityType(MatchIdentityType matchIdentityType) {
this.matchIdentityType = matchIdentityType;
} // setMatchIdentityType
/**
* The following constants are defined for use with the ValueMap/Values qualified property matchIdentityValue.
*/
private String matchIdentityValue;
/**
* This method returns the PeerIDPayloadFilterEntry.matchIdentityValue property value. This property is described as follows:
*
* MatchIdentityValue is the filter value for comparison with the ID payload, e,g, "*@company.com". The syntax may need to be converted for
* comparison. For example, if the type of identity is a DER-encoded distinguished name, (for example, MatchIdentityType = 10, "DER_ASN1_DN"), the
* MatchIdentityValue MUST be converted into a DER-encoded string. This allows it to be matched against the values extracted from the ID payload
* at runtime. Note that a wildcard mechanism may be used when MatchIdentityType specifies a general character string (for example, if
* MatchIdentityType=3, 'FQDN'). MatchFieldValue may contain a wildcard character, '*', in the pattern match specification. For example, for
* 'FQDN', a MatchFieldValue of '*@example.com' will successfully match an ID payload of 'janedoe@example.com'. A wildcard can be used to
* represent 0 or more characters as is appropriate for the type specified in MatchIdentityType.
*
* @return String current matchIdentityValue property value
* @exception Exception
*/
public String getMatchIdentityValue() {
return this.matchIdentityValue;
} // getMatchIdentityValue
/**
* This method sets the PeerIDPayloadFilterEntry.matchIdentityValue property value. This property is described as follows:
*
* MatchIdentityValue is the filter value for comparison with the ID payload, e,g, "*@company.com". The syntax may need to be converted for
* comparison. For example, if the type of identity is a DER-encoded distinguished name, (for example, MatchIdentityType = 10, "DER_ASN1_DN"), the
* MatchIdentityValue MUST be converted into a DER-encoded string. This allows it to be matched against the values extracted from the ID payload
* at runtime. Note that a wildcard mechanism may be used when MatchIdentityType specifies a general character string (for example, if
* MatchIdentityType=3, 'FQDN'). MatchFieldValue may contain a wildcard character, '*', in the pattern match specification. For example, for
* 'FQDN', a MatchFieldValue of '*@example.com' will successfully match an ID payload of 'janedoe@example.com'. A wildcard can be used to
* represent 0 or more characters as is appropriate for the type specified in MatchIdentityType.
*
* @param String
* new matchIdentityValue property value
* @exception Exception
*/
public void setMatchIdentityValue(String matchIdentityValue) {
this.matchIdentityValue = matchIdentityValue;
} // setMatchIdentityValue
} // Class PeerIDPayloadFilterEntry
| eenbp/OpenNaaS-0.14-Marketplace | utils/old-cim/PeerIDPayloadFilterEntry.java | Java | lgpl-3.0 | 5,913 |
/****************************************************************************
**
** Copyright (C) 2015 Klaralvdalens Datakonsult AB (KDAB).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt3D module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL3$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPLv3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or later as published by the Free
** Software Foundation and appearing in the file LICENSE.GPL included in
** the packaging of this file. Please review the following information to
** ensure the GNU General Public License version 2.0 requirements will be
** met: http://www.gnu.org/licenses/gpl-2.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QT3D_QGEOMETRYCOLLIDER_P_H
#define QT3D_QGEOMETRYCOLLIDER_P_H
#include <Qt3DCollision/private/qabstractcollider_p.h>
QT_BEGIN_NAMESPACE
namespace Qt3D {
class QGeometryCollider;
class QGeometryColliderPrivate : public QAbstractColliderPrivate
{
QGeometryColliderPrivate();
Q_DECLARE_PUBLIC(QGeometryCollider)
};
} // namespace Qt3D
QT_END_NAMESPACE
#endif // QT3D_QGEOMETRYCOLLIDER_P_H
| alesegdia/qt3d | src/collision/qgeometrycollider_p.h | C | lgpl-3.0 | 2,155 |
-- Copyright (c) 2014 James King [metapyziks@gmail.com]
--
-- This file is part of Final Frontier.
--
-- Final Frontier is free software: you can redistribute it and/or modify
-- it under the terms of the GNU Lesser General Public License as
-- published by the Free Software Foundation, either version 3 of
-- the License, or (at your option) any later version.
--
-- Final Frontier is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public License
-- along with Final Frontier. If not, see <http://www.gnu.org/licenses/>.
ENT.Type = "point"
ENT.Base = "base_point"
ENT._index = 0
ENT._roomName = nil
function ENT:KeyValue(key, value)
if key == "room" then
self._roomName = tostring(value)
elseif key == "index" then
self._index = tonumber(value)
end
end
function ENT:InitPostEntity()
if self._roomName then
local rooms = ents.FindByName(self._roomName)
if #rooms > 0 then
local room = rooms[1]
local pos = self:GetPos()
room:AddCorner(self._index, pos.x, pos.y)
end
end
self:Remove()
end
| benloz10/FinalFrontier | gamemodes/finalfrontier/entities/entities/info_ff_roomcorner/init.lua | Lua | lgpl-3.0 | 1,345 |
package android.database.sqlite;
//import android.os.ParcelFileDescriptor;
public final class SQLiteStatement
extends SQLiteProgram
{
SQLiteStatement()
{
throw new RuntimeException("Stub!");
}
public void execute()
{
throw new RuntimeException("Stub!");
}
public int executeUpdateDelete()
{
throw new RuntimeException("Stub!");
}
public long executeInsert()
{
throw new RuntimeException("Stub!");
}
public long simpleQueryForLong()
{
throw new RuntimeException("Stub!");
}
public String simpleQueryForString()
{
throw new RuntimeException("Stub!");
}
// public ParcelFileDescriptor simpleQueryForBlobFileDescriptor()
// {
// throw new RuntimeException("Stub!");
// }
public String toString()
{
throw new RuntimeException("Stub!");
}
}
| MaxNad/find-sec-bugs | plugin-deps/src/main/java/android/database/sqlite/SQLiteStatement.java | Java | lgpl-3.0 | 908 |
/**
* Copyright (C) 2013 Inera AB (http://www.inera.se)
*
* This file is part of Inera Axel (http://code.google.com/p/inera-axel).
*
* Inera Axel is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Inera Axel is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package se.inera.axel.shs.xml.agreement;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.NormalizedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.io.Serializable;
/**
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"shs",
"general"
})
@XmlRootElement(name = "shs.agreement")
public class ShsAgreement implements Serializable {
@XmlAttribute(name = "version")
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String version;
@XmlAttribute(name = "uuid", required = true)
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
protected String uuid;
@XmlAttribute(name = "transfer-type", required = true)
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
protected String transferType;
@XmlAttribute(name = "contract")
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String contract;
@XmlElement(required = true)
protected Shs shs;
@XmlElement(required = true)
protected General general;
/**
* Gets the value of the version property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVersion() {
if (version == null) {
return "1.2";
} else {
return version;
}
}
/**
* Sets the value of the version property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVersion(String value) {
this.version = value;
}
/**
* Gets the value of the uuid property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUuid() {
return uuid;
}
/**
* Sets the value of the uuid property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUuid(String value) {
this.uuid = value;
}
/**
* Gets the value of the transferType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTransferType() {
return transferType;
}
/**
* Sets the value of the transferType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTransferType(String value) {
this.transferType = value;
}
/**
* Gets the value of the contract property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getContract() {
return contract;
}
/**
* Sets the value of the contract property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setContract(String value) {
this.contract = value;
}
/**
* Gets the value of the shs property.
*
* @return
* possible object is
* {@link Shs }
*
*/
public Shs getShs() {
return shs;
}
/**
* Sets the value of the shs property.
*
* @param value
* allowed object is
* {@link Shs }
*
*/
public void setShs(Shs value) {
this.shs = value;
}
/**
* Gets the value of the general property.
*
* @return
* possible object is
* {@link General }
*
*/
public General getGeneral() {
return general;
}
/**
* Sets the value of the general property.
*
* @param value
* allowed object is
* {@link General }
*
*/
public void setGeneral(General value) {
this.general = value;
}
}
| sklaxel/inera-axel | shs/shs-protocol/src/main/java/se/inera/axel/shs/xml/agreement/ShsAgreement.java | Java | lgpl-3.0 | 4,780 |
/** \file
\brief Definition of basic types used by muParserX
<pre>
__________ ____ ___
_____ __ _\______ \_____ _______ ______ __________\ \/ /
/ \| | \ ___/\__ \\_ __ \/ ___// __ \_ __ \ /
| Y Y \ | / | / __ \| | \/\___ \\ ___/| | \/ \
|__|_| /____/|____| (____ /__| /____ >\___ >__| /___/\ \
\/ \/ \/ \/ \_/
muParserX - A C++ math parser library with array and string support
Copyright 2010 Ingo Berg
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU LESSER GENERAL PUBLIC LICENSE
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see http://www.gnu.org/licenses.
</pre>
*/
#ifndef MUP_SCRIPT_TOKENS_H
#define MUP_SCRIPT_TOKENS_H
#include "mpIToken.h"
MUP_NAMESPACE_START
//---------------------------------------------------------------------------
/** \brief A class for encapsulation a newline token. */
class TokenNewline : public IToken
{
public:
TokenNewline();
//---------------------------------------------
// IToken interface
//---------------------------------------------
virtual IToken* Clone() const;
virtual string_type AsciiDump() const;
int GetStackOffset() const;
void SetStackOffset(int nOffset);
private:
int m_nOffset;
};
MUP_NAMESPACE_END
#endif | shouze/muparser | parser/mpScriptTokens.h | C | lgpl-3.0 | 1,974 |
define(function (require) {
var bdd = require('intern!bdd');
require('../helpers/test-page');
bdd.describe('Custom Measures Page', function () {
var projectId = 'eb294572-a6a4-43cf-acc2-33c2fe37c02e';
bdd.it('should show list', function () {
return this.remote
.open()
.mockFromFile('/api/custom_measures/search', 'custom-measures-spec/search.json',
{ data: { projectId: projectId } })
.startAppBrowserify('custom-measures')
.checkElementCount('#custom-measures-list tr[data-id]', 4)
.checkElementInclude('#custom-measures-list .js-custom-measure-value', '35')
.checkElementInclude('#custom-measures-list .js-custom-measure-metric-name', 'Distribution')
.checkElementInclude('#custom-measures-list .js-custom-measure-domain', 'Management')
.checkElementInclude('#custom-measures-list .js-custom-measure-description', 'Description...')
.checkElementInclude('#custom-measures-list .js-custom-measure-created-at', '2015')
.checkElementInclude('#custom-measures-list .js-custom-measure-user', 'Administrator')
.checkElementCount('#custom-measures-list .js-custom-measure-pending', 4)
.checkElementCount('#custom-measures-list .js-custom-measure-update', 4)
.checkElementCount('#custom-measures-list .js-custom-measure-delete', 4)
.checkElementInclude('#custom-measures-list-footer', '4/4');
});
bdd.it('should show more', function () {
return this.remote
.open()
.mockFromFile('/api/custom_measures/search', 'custom-measures-spec/search-big-1.json',
{ data: { projectId: projectId } })
.startAppBrowserify('custom-measures')
.checkElementCount('#custom-measures-list tr[data-id]', 2)
.checkElementNotExist('[data-id="3"]')
.clearMocks()
.mockFromFile('/api/custom_measures/search', 'custom-measures-spec/search-big-2.json',
{ data: { projectId: projectId, p: 2 } })
.clickElement('#custom-measures-fetch-more')
.checkElementExist('[data-id="3"]')
.checkElementCount('#custom-measures-list tr[data-id]', 4);
});
bdd.it('should create a new custom measure', function () {
return this.remote
.open()
.mockFromFile('/api/custom_measures/search', 'custom-measures-spec/search.json',
{ data: { projectId: projectId } })
.mockFromFile('/api/metrics/search', 'custom-measures-spec/metrics.json', { data: { isCustom: true } })
.startAppBrowserify('custom-measures')
.checkElementCount('#custom-measures-list tr[data-id]', 4)
.clickElement('#custom-measures-create')
.checkElementExist('#create-custom-measure-form')
.clearMocks()
.mockFromFile('/api/custom_measures/search', 'custom-measures-spec/search-created.json',
{ data: { projectId: projectId } })
.mockFromString('/api/custom_measures/create', '{}', { data: {
metricId: '156',
value: '17',
description: 'example',
projectId: projectId
} })
.fillElement('#create-custom-measure-metric', '156')
.fillElement('#create-custom-measure-value', '17')
.fillElement('#create-custom-measure-description', 'example')
.clickElement('#create-custom-measure-submit')
.checkElementExist('[data-id="6"]')
.checkElementCount('#custom-measures-list tr[data-id]', 5)
.checkElementInclude('[data-id="6"] .js-custom-measure-value', '17');
});
bdd.it('should filter available metrics', function () {
return this.remote
.open()
.mockFromFile('/api/custom_measures/search', 'custom-measures-spec/search.json',
{ data: { projectId: projectId } })
.mockFromFile('/api/metrics/search', 'custom-measures-spec/metrics.json', { data: { isCustom: true } })
.startAppBrowserify('custom-measures')
.clickElement('#custom-measures-create')
.checkElementExist('#create-custom-measure-form')
.checkElementCount('#create-custom-measure-metric option', 1)
.checkElementExist('#create-custom-measure-metric option[value="156"]');
});
bdd.it('should show warning when there are no available metrics', function () {
return this.remote
.open()
.mockFromFile('/api/custom_measures/search', 'custom-measures-spec/search.json',
{ data: { projectId: projectId } })
.mockFromFile('/api/metrics/search', 'custom-measures-spec/metrics-limited.json',
{ data: { isCustom: true } })
.startAppBrowserify('custom-measures')
.clickElement('#custom-measures-create')
.checkElementExist('#create-custom-measure-form')
.checkElementNotExist('#create-custom-measure-metric')
.checkElementExist('#create-custom-measure-form .alert-warning')
.checkElementExist('#create-custom-measure-submit[disabled]');
});
bdd.it('should update a custom measure', function () {
return this.remote
.open()
.mockFromFile('/api/custom_measures/search', 'custom-measures-spec/search.json',
{ data: { projectId: projectId } })
.mockFromFile('/api/metrics/search', 'custom-measures-spec/metrics.json', { data: { isCustom: true } })
.startAppBrowserify('custom-measures')
.clickElement('[data-id="5"] .js-custom-measure-update')
.checkElementExist('#create-custom-measure-form')
.clearMocks()
.mockFromFile('/api/custom_measures/search', 'custom-measures-spec/search-updated.json',
{ data: { projectId: projectId } })
.mockFromString('/api/custom_measures/update', '{}', { data: {
id: '5',
value: '2',
description: 'new!'
} })
.fillElement('#create-custom-measure-value', '2')
.fillElement('#create-custom-measure-description', 'new!')
.clickElement('#create-custom-measure-submit')
.checkElementExist('[data-id="5"]')
.checkElementInclude('[data-id="5"] .js-custom-measure-value', 'B')
.checkElementInclude('[data-id="5"] .js-custom-measure-description', 'new!');
});
bdd.it('should delete a custom measure', function () {
return this.remote
.open()
.mockFromFile('/api/custom_measures/search', 'custom-measures-spec/search.json',
{ data: { projectId: projectId } })
.startAppBrowserify('custom-measures')
.clickElement('[data-id="5"] .js-custom-measure-delete')
.checkElementExist('#delete-custom-measure-form', 1)
.clearMocks()
.mockFromFile('/api/custom_measures/search', 'custom-measures-spec/search-deleted.json',
{ data: { projectId: projectId } })
.mockFromString('/api/custom_measures/delete', '{}', { data: { id: '5' } })
.clickElement('#delete-custom-measure-submit')
.checkElementNotExist('[data-id="5"]');
});
});
});
| abbeyj/sonarqube | server/sonar-web/test/medium/custom-measures.spec.js | JavaScript | lgpl-3.0 | 7,167 |
<!-- WallacePOS: Copyright (c) 2014 WallaceIT <micwallace@gmx.com> <https://www.gnu.org/licenses/lgpl.html> -->
<div class="page-header">
<h1>
Invoice Settings
<small>
<i class="icon-double-angle-right"></i>
Manage invoice & accounts settings
</small>
</h1>
</div><!-- /.page-header -->
<div class="row">
<div class="col-sm-6">
<div class="widget-box transparent">
<div class="widget-header widget-header-flat">
<h4 class="lighter">General</h4>
</div>
<div class="widget-body" style="padding-top: 10px;">
<form class="form-horizontal">
<div class="form-group">
<div class="col-sm-5"><label>Default Due Date:</label></div>
<div class="col-sm-5">
<select id="defaultduedtnum">
<option value="+1 ">1</option>
<option value="+2 ">2</option>
<option value="+3 ">3</option>
<option value="+4 ">4</option>
<option value="+5 ">5</option>
<option value="+5 ">6</option>
<option value="+5 ">7</option>
<option value="+5 ">8</option>
<option value="+5 ">9</option>
<option value="+5 ">10</option>
<option value="+5 ">11</option>
<option value="+5 ">12</option>
</select>
<select id="defaultduedtunit">
<option value="days">Days</option>
<option value="weeks">Weeks</option>
<option value="months">Months</option>
</select>
</div>
</div>
<div class="space-4"></div>
<div class="form-group">
<div class="col-sm-5"><label>Payment Instructions:</label></div>
<div class="col-sm-7">
<div id="payinst" style="height: 175px; border: 1px solid #E5E5E5;" class="wysiwyg-editor">
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-5"><label>Email Message:</label></div>
<div class="col-sm-7">
<div id="emailmsg" style="height: 175px; border: 1px solid #E5E5E5;" class="wysiwyg-editor">
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="col-sm-6" style="display: none;">
<div class="widget-box transparent">
<div class="widget-header widget-header-flat">
<h4 class="lighter">Invoice Template</h4>
</div>
<div class="widget-body" style="padding-top: 10px;">
<form class="form-horizontal">
<div class="space-4"></div>
</form>
</div>
</div>
</div>
<div class="col-sm-12 align-center form-actions">
<button class="btn btn-success" type="button" onclick="saveSettings();"><i class="icon-save align-top bigger-125"></i>Save</button>
</div>
</div>
<script type="text/javascript">
var options;
function saveSettings(){
// show loader
WPOS.util.showLoader();
var data = {};
$("form :input").each(function(){
if ($(this).prop('id')=="defaultduedtnum" || $(this).prop('id')=="defaultduedtunit") {
if ($(this).prop('id')=="defaultduedtnum")
data['defaultduedt'] = $(this).val()+$("#defaultduedtunit").val();
} else {
if ($(this).prop('id')!=="")
data[$(this).prop('id')] = $(this).val();
}
});
data['payinst'] = $("#payinst").html();
data['emailmsg'] = $("#emailmsg").html();
WPOS.sendJsonData("settings/invoice/set", JSON.stringify(data));
// hide loader
WPOS.util.hideLoader();
}
function loadSettings(){
options = WPOS.getJsonData("settings/invoice/get");
// load option values into the form
for (var i in options){
if (i=="defaultduedt"){
var parts = options[i].split(" ");
$("#defaultduedtnum").val(parts[0]+" ");
$("#defaultduedtunit").val(parts[1]);
} else {
$("#"+i).val(options[i]);
}
}
$("#payinst").html(options.payinst);
$("#emailmsg").html(options.emailmsg);
$("#bizlogoprev").attr("src", options.bizlogo);
}
$('#bizlogofile').on('change',uploadLogo);
$('#bizlogo').on('change',function(e){
$("#bizlogoprev").prop("src", $(e.target).val());
});
function uploadLogo(event){
WPOS.uploadFile(event, function(data){
$("#bizlogo").val(data.path);
$("#bizlogoprev").prop("src", data.path);
saveSettings();
}); // Start file upload, passing a callback to fire if it completes successfully
}
$(function(){
// email wysiwyg
$('.wysiwyg-toolbar').remove();
$('.wysiwyg-editor').ace_wysiwyg();
$(".wysiwyg-toolbar").addClass('wysiwyg-style2');
loadSettings();
// hide loader
WPOS.util.hideLoader();
})
</script> | farukham/wallacepos | admin/content/invoicesettings.php | PHP | lgpl-3.0 | 5,623 |
#include "testutils/FuseFlushTest.h"
using ::testing::Eq;
using ::testing::WithParamInterface;
using ::testing::Values;
using ::testing::Return;
using std::string;
// The fuse behaviour is: For each open(), there will be exactly one call to release().
// Directly before this call to release(), flush() will be called. After flush() returns,
// the ::close() syscall (in the process using the filesystem) returns. So the fuse release() call is
// called asynchronously afterwards. Errors have to be returned in the implementation of flush().
// Citing FUSE spec:
// 1) Flush is called on each close() of a file descriptor.
// 2) Filesystems shouldn't assume that flush will always be called after some writes, or that if will be called at all.
// I can't get these sentences together. For the test cases here, I go with the first one and assume that
// flush() will ALWAYS be called on a file close.
class FuseFlushFileDescriptorTest: public FuseFlushTest, public WithParamInterface<int> {
};
INSTANTIATE_TEST_SUITE_P(FuseFlushFileDescriptorTest, FuseFlushFileDescriptorTest, Values(0, 1, 2, 100, 1024*1024*1024));
TEST_P(FuseFlushFileDescriptorTest, FlushOnCloseFile) {
ReturnIsFileOnLstat(FILENAME);
EXPECT_CALL(*fsimpl, openFile(Eq(FILENAME), testing::_)).WillOnce(Return(GetParam()));
EXPECT_CALL(*fsimpl, flush(Eq(GetParam()))).Times(1);
OpenAndCloseFile(FILENAME);
}
| davesteele/cryfs | test/fspp/fuse/flush/FuseFlushFileDescriptorTest.cpp | C++ | lgpl-3.0 | 1,391 |
/* ode-initval/rk8pd.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Runge-Kutta 8(9), Prince-Dormand
*
* High Order Embedded Runge-Kutta Formulae
* P.J. Prince and J.R. Dormand
* J. Comp. Appl. Math.,7, pp. 67-75, 1981
*/
/* Author: G. Jungman
*/
#include "gsl__config.h"
#include <stdlib.h>
#include <string.h>
#include "gsl_errno.h"
#include "gsl_odeiv.h"
#include "gsl_ode-initval__odeiv_util.h"
/* Prince-Dormand constants */
static const double Abar[] = {
14005451.0 / 335480064.0,
0.0,
0.0,
0.0,
0.0,
-59238493.0 / 1068277825.0,
181606767.0 / 758867731.0,
561292985.0 / 797845732.0,
-1041891430.0 / 1371343529.0,
760417239.0 / 1151165299.0,
118820643.0 / 751138087.0,
-528747749.0 / 2220607170.0,
1.0 / 4.0
};
static const double A[] = {
13451932.0 / 455176623.0,
0.0,
0.0,
0.0,
0.0,
-808719846.0 / 976000145.0,
1757004468.0 / 5645159321.0,
656045339.0 / 265891186.0,
-3867574721.0 / 1518517206.0,
465885868.0 / 322736535.0,
53011238.0 / 667516719.0,
2.0 / 45.0
};
static const double ah[] = {
1.0 / 18.0,
1.0 / 12.0,
1.0 / 8.0,
5.0 / 16.0,
3.0 / 8.0,
59.0 / 400.0,
93.0 / 200.0,
5490023248.0 / 9719169821.0,
13.0 / 20.0,
1201146811.0 / 1299019798.0
};
static const double b21 = 1.0 / 18.0;
static const double b3[] = { 1.0 / 48.0, 1.0 / 16.0 };
static const double b4[] = { 1.0 / 32.0, 0.0, 3.0 / 32.0 };
static const double b5[] = { 5.0 / 16.0, 0.0, -75.0 / 64.0, 75.0 / 64.0 };
static const double b6[] = { 3.0 / 80.0, 0.0, 0.0, 3.0 / 16.0, 3.0 / 20.0 };
static const double b7[] = {
29443841.0 / 614563906.0,
0.0,
0.0,
77736538.0 / 692538347.0,
-28693883.0 / 1125000000.0,
23124283.0 / 1800000000.0
};
static const double b8[] = {
16016141.0 / 946692911.0,
0.0,
0.0,
61564180.0 / 158732637.0,
22789713.0 / 633445777.0,
545815736.0 / 2771057229.0,
-180193667.0 / 1043307555.0
};
static const double b9[] = {
39632708.0 / 573591083.0,
0.0,
0.0,
-433636366.0 / 683701615.0,
-421739975.0 / 2616292301.0,
100302831.0 / 723423059.0,
790204164.0 / 839813087.0,
800635310.0 / 3783071287.0
};
static const double b10[] = {
246121993.0 / 1340847787.0,
0.0,
0.0,
-37695042795.0 / 15268766246.0,
-309121744.0 / 1061227803.0,
-12992083.0 / 490766935.0,
6005943493.0 / 2108947869.0,
393006217.0 / 1396673457.0,
123872331.0 / 1001029789.0
};
static const double b11[] = {
-1028468189.0 / 846180014.0,
0.0,
0.0,
8478235783.0 / 508512852.0,
1311729495.0 / 1432422823.0,
-10304129995.0 / 1701304382.0,
-48777925059.0 / 3047939560.0,
15336726248.0 / 1032824649.0,
-45442868181.0 / 3398467696.0,
3065993473.0 / 597172653.0
};
static const double b12[] = {
185892177.0 / 718116043.0,
0.0,
0.0,
-3185094517.0 / 667107341.0,
-477755414.0 / 1098053517.0,
-703635378.0 / 230739211.0,
5731566787.0 / 1027545527.0,
5232866602.0 / 850066563.0,
-4093664535.0 / 808688257.0,
3962137247.0 / 1805957418.0,
65686358.0 / 487910083.0
};
static const double b13[] = {
403863854.0 / 491063109.0,
0.0,
0.0,
-5068492393.0 / 434740067.0,
-411421997.0 / 543043805.0,
652783627.0 / 914296604.0,
11173962825.0 / 925320556.0,
-13158990841.0 / 6184727034.0,
3936647629.0 / 1978049680.0,
-160528059.0 / 685178525.0,
248638103.0 / 1413531060.0,
0.0
};
typedef struct
{
double *k[13];
double *ytmp;
double *y0;
}
rk8pd_state_t;
static void *
rk8pd_alloc (size_t dim)
{
rk8pd_state_t *state = (rk8pd_state_t *) malloc (sizeof (rk8pd_state_t));
int i, j;
if (state == 0)
{
GSL_ERROR_NULL ("failed to allocate space for rk8pd_state", GSL_ENOMEM);
}
state->ytmp = (double *) malloc (dim * sizeof (double));
if (state->ytmp == 0)
{
free (state);
GSL_ERROR_NULL ("failed to allocate space for ytmp", GSL_ENOMEM);
}
state->y0 = (double *) malloc (dim * sizeof (double));
if (state->y0 == 0)
{
free (state->ytmp);
free (state);
GSL_ERROR_NULL ("failed to allocate space for y0", GSL_ENOMEM);
}
for (i = 0; i < 13; i++)
{
state->k[i] = (double *) malloc (dim * sizeof (double));
if (state->k[i] == 0)
{
for (j = 0; j < i; j++)
{
free (state->k[j]);
}
free (state->y0);
free (state->ytmp);
free (state);
GSL_ERROR_NULL ("failed to allocate space for k's", GSL_ENOMEM);
}
}
return state;
}
static int
rk8pd_apply (void *vstate,
size_t dim,
double t,
double h,
double y[],
double yerr[],
const double dydt_in[],
double dydt_out[], const gsl_odeiv_system * sys)
{
rk8pd_state_t *state = (rk8pd_state_t *) vstate;
size_t i;
double *const ytmp = state->ytmp;
double *const y0 = state->y0;
/* Note that k1 is stored in state->k[0] due to zero-based indexing */
double *const k1 = state->k[0];
double *const k2 = state->k[1];
double *const k3 = state->k[2];
double *const k4 = state->k[3];
double *const k5 = state->k[4];
double *const k6 = state->k[5];
double *const k7 = state->k[6];
double *const k8 = state->k[7];
double *const k9 = state->k[8];
double *const k10 = state->k[9];
double *const k11 = state->k[10];
double *const k12 = state->k[11];
double *const k13 = state->k[12];
DBL_MEMCPY (y0, y, dim);
/* k1 step */
if (dydt_in != NULL)
{
DBL_MEMCPY (k1, dydt_in, dim);
}
else
{
int s = GSL_ODEIV_FN_EVAL (sys, t, y, k1);
if (s != GSL_SUCCESS)
{
return s;
}
}
for (i = 0; i < dim; i++)
ytmp[i] = y[i] + b21 * h * k1[i];
/* k2 step */
{
int s = GSL_ODEIV_FN_EVAL (sys, t + ah[0] * h, ytmp, k2);
if (s != GSL_SUCCESS)
{
return s;
}
}
for (i = 0; i < dim; i++)
ytmp[i] = y[i] + h * (b3[0] * k1[i] + b3[1] * k2[i]);
/* k3 step */
{
int s = GSL_ODEIV_FN_EVAL (sys, t + ah[1] * h, ytmp, k3);
if (s != GSL_SUCCESS)
{
return s;
}
}
for (i = 0; i < dim; i++)
ytmp[i] = y[i] + h * (b4[0] * k1[i] + b4[2] * k3[i]);
/* k4 step */
{
int s = GSL_ODEIV_FN_EVAL (sys, t + ah[2] * h, ytmp, k4);
if (s != GSL_SUCCESS)
{
return s;
}
}
for (i = 0; i < dim; i++)
ytmp[i] = y[i] + h * (b5[0] * k1[i] + b5[2] * k3[i] + b5[3] * k4[i]);
/* k5 step */
{
int s = GSL_ODEIV_FN_EVAL (sys, t + ah[3] * h, ytmp, k5);
if (s != GSL_SUCCESS)
{
return s;
}
}
for (i = 0; i < dim; i++)
ytmp[i] = y[i] + h * (b6[0] * k1[i] + b6[3] * k4[i] + b6[4] * k5[i]);
/* k6 step */
{
int s = GSL_ODEIV_FN_EVAL (sys, t + ah[4] * h, ytmp, k6);
if (s != GSL_SUCCESS)
{
return s;
}
}
for (i = 0; i < dim; i++)
ytmp[i] =
y[i] + h * (b7[0] * k1[i] + b7[3] * k4[i] + b7[4] * k5[i] +
b7[5] * k6[i]);
/* k7 step */
{
int s = GSL_ODEIV_FN_EVAL (sys, t + ah[5] * h, ytmp, k7);
if (s != GSL_SUCCESS)
{
return s;
}
}
for (i = 0; i < dim; i++)
ytmp[i] =
y[i] + h * (b8[0] * k1[i] + b8[3] * k4[i] + b8[4] * k5[i] +
b8[5] * k6[i] + b8[6] * k7[i]);
/* k8 step */
{
int s = GSL_ODEIV_FN_EVAL (sys, t + ah[6] * h, ytmp, k8);
if (s != GSL_SUCCESS)
{
return s;
}
}
for (i = 0; i < dim; i++)
ytmp[i] =
y[i] + h * (b9[0] * k1[i] + b9[3] * k4[i] + b9[4] * k5[i] +
b9[5] * k6[i] + b9[6] * k7[i] + b9[7] * k8[i]);
/* k9 step */
{
int s = GSL_ODEIV_FN_EVAL (sys, t + ah[7] * h, ytmp, k9);
if (s != GSL_SUCCESS)
{
return s;
}
}
for (i = 0; i < dim; i++)
ytmp[i] =
y[i] + h * (b10[0] * k1[i] + b10[3] * k4[i] + b10[4] * k5[i] +
b10[5] * k6[i] + b10[6] * k7[i] + b10[7] * k8[i] +
b10[8] * k9[i]);
/* k10 step */
{
int s = GSL_ODEIV_FN_EVAL (sys, t + ah[8] * h, ytmp, k10);
if (s != GSL_SUCCESS)
{
return s;
}
}
for (i = 0; i < dim; i++)
ytmp[i] =
y[i] + h * (b11[0] * k1[i] + b11[3] * k4[i] + b11[4] * k5[i] +
b11[5] * k6[i] + b11[6] * k7[i] + b11[7] * k8[i] +
b11[8] * k9[i] + b11[9] * k10[i]);
/* k11 step */
{
int s = GSL_ODEIV_FN_EVAL (sys, t + ah[9] * h, ytmp, k11);
if (s != GSL_SUCCESS)
{
return s;
}
}
for (i = 0; i < dim; i++)
ytmp[i] =
y[i] + h * (b12[0] * k1[i] + b12[3] * k4[i] + b12[4] * k5[i] +
b12[5] * k6[i] + b12[6] * k7[i] + b12[7] * k8[i] +
b12[8] * k9[i] + b12[9] * k10[i] + b12[10] * k11[i]);
/* k12 step */
{
int s = GSL_ODEIV_FN_EVAL (sys, t + h, ytmp, k12);
if (s != GSL_SUCCESS)
{
return s;
}
}
for (i = 0; i < dim; i++)
ytmp[i] =
y[i] + h * (b13[0] * k1[i] + b13[3] * k4[i] + b13[4] * k5[i] +
b13[5] * k6[i] + b13[6] * k7[i] + b13[7] * k8[i] +
b13[8] * k9[i] + b13[9] * k10[i] + b13[10] * k11[i] +
b13[11] * k12[i]);
/* k13 step */
{
int s = GSL_ODEIV_FN_EVAL (sys, t + h, ytmp, k13);
if (s != GSL_SUCCESS)
{
return s;
}
}
/* final sum */
for (i = 0; i < dim; i++)
{
const double ksum8 =
Abar[0] * k1[i] + Abar[5] * k6[i] + Abar[6] * k7[i] +
Abar[7] * k8[i] + Abar[8] * k9[i] + Abar[9] * k10[i] +
Abar[10] * k11[i] + Abar[11] * k12[i] + Abar[12] * k13[i];
y[i] += h * ksum8;
}
/* Evaluate dydt_out[]. */
if (dydt_out != NULL)
{
int s = GSL_ODEIV_FN_EVAL (sys, t + h, y, dydt_out);
if (s != GSL_SUCCESS)
{
/* Restore initial values */
DBL_MEMCPY (y, y0, dim);
return s;
}
}
/* error estimate */
for (i = 0; i < dim; i++)
{
const double ksum8 =
Abar[0] * k1[i] + Abar[5] * k6[i] + Abar[6] * k7[i] +
Abar[7] * k8[i] + Abar[8] * k9[i] + Abar[9] * k10[i] +
Abar[10] * k11[i] + Abar[11] * k12[i] + Abar[12] * k13[i];
const double ksum7 =
A[0] * k1[i] + A[5] * k6[i] + A[6] * k7[i] + A[7] * k8[i] +
A[8] * k9[i] + A[9] * k10[i] + A[10] * k11[i] + A[11] * k12[i];
yerr[i] = h * (ksum7 - ksum8);
}
return GSL_SUCCESS;
}
static int
rk8pd_reset (void *vstate, size_t dim)
{
rk8pd_state_t *state = (rk8pd_state_t *) vstate;
int i;
for (i = 0; i < 13; i++)
{
DBL_ZERO_MEMSET (state->k[i], dim);
}
DBL_ZERO_MEMSET (state->y0, dim);
DBL_ZERO_MEMSET (state->ytmp, dim);
return GSL_SUCCESS;
}
static unsigned int
rk8pd_order (void *vstate)
{
rk8pd_state_t *state = (rk8pd_state_t *) vstate;
state = 0; /* prevent warnings about unused parameters */
return 8;
}
static void
rk8pd_free (void *vstate)
{
rk8pd_state_t *state = (rk8pd_state_t *) vstate;
int i;
for (i = 0; i < 13; i++)
{
free (state->k[i]);
}
free (state->y0);
free (state->ytmp);
free (state);
}
static const gsl_odeiv_step_type rk8pd_type = { "rk8pd", /* name */
1, /* can use dydt_in */
1, /* gives exact dydt_out */
&rk8pd_alloc,
&rk8pd_apply,
&rk8pd_reset,
&rk8pd_order,
&rk8pd_free
};
const gsl_odeiv_step_type *gsl_odeiv_step_rk8pd = &rk8pd_type;
| PeterWolf-tw/NeoPraat | sources_5401/external/gsl/gsl_ode-initval__rk8pd.c | C | lgpl-3.0 | 12,064 |
/* -*-c++-*- */
/* osgEarth - Dynamic map generation toolkit for OpenSceneGraph
* Copyright 2008-2010 Pelican Mapping
* http://osgearth.org
*
* osgEarth is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
#include <osgEarthFeatures/LabelSource>
#include <osgEarth/DepthOffset>
#include <osgEarthAnnotation/LabelNode>
#include <osgEarthAnnotation/Decluttering>
#include <osgDB/FileNameUtils>
#include <osgUtil/Optimizer>
using namespace osgEarth;
using namespace osgEarth::Annotation;
using namespace osgEarth::Features;
class AnnotationLabelSource : public LabelSource
{
public:
AnnotationLabelSource( const LabelSourceOptions& options )
: LabelSource( options )
{
//nop
}
/**
* Creates a simple label. The caller is responsible for placing it in the scene.
*/
osg::Node* createNode(
const std::string& text,
const Style& style )
{
return 0L; // no support
}
/**
* Creates a complete set of positioned label nodes from a feature list.
*/
osg::Node* createNode(
const FeatureList& input,
const Style& style,
const FilterContext& context )
{
const TextSymbol* text = style.get<TextSymbol>();
if ( !text )
return 0L;
osg::Group* group = new osg::Group();
Decluttering::setEnabled( group->getOrCreateStateSet(), true );
if ( text->priority().isSet() )
{
DeclutteringOptions dco = Decluttering::getOptions();
dco.sortByPriority() = text->priority().isSet();
Decluttering::setOptions( dco );
}
StringExpression contentExpr ( *text->content() );
NumericExpression priorityExpr( *text->priority() );
if ( text->removeDuplicateLabels() == true )
{
// in remove-duplicates mode, make a list of unique features, selecting
// the one with the largest area as the one we'll use for labeling.
typedef std::pair<double, osg::ref_ptr<const Feature> > Entry;
typedef std::map<std::string, Entry> EntryMap;
EntryMap used;
for( FeatureList::const_iterator i = input.begin(); i != input.end(); ++i )
{
Feature* feature = i->get();
if ( feature && feature->getGeometry() )
{
const std::string& value = feature->eval( contentExpr );
if ( !value.empty() )
{
double area = feature->getGeometry()->getBounds().area2d();
if ( used.find(value) == used.end() )
{
used[value] = Entry(area, feature);
}
else
{
Entry& biggest = used[value];
if ( area > biggest.first )
{
biggest.first = area;
biggest.second = feature;
}
}
}
}
}
for( EntryMap::iterator i = used.begin(); i != used.end(); ++i )
{
const std::string& value = i->first;
const Feature* feature = i->second.second.get();
group->addChild( makeLabelNode(context, feature, value, text, priorityExpr) );
}
}
else
{
for( FeatureList::const_iterator i = input.begin(); i != input.end(); ++i )
{
const Feature* feature = i->get();
if ( !feature )
continue;
const Geometry* geom = feature->getGeometry();
if ( !geom )
continue;
const std::string& value = feature->eval( contentExpr, &context );
if ( value.empty() )
continue;
group->addChild( makeLabelNode(context, feature, value, text, priorityExpr) );
}
}
#if 0 // good idea but needs work.
DepthOffsetGroup* dog = new DepthOffsetGroup();
dog->setMinimumOffset( 500.0 );
dog->addChild( group );
return dog;
#endif
return group;
}
osg::Node* makeLabelNode(const FilterContext& context,
const Feature* feature,
const std::string& value,
const TextSymbol* text,
NumericExpression& priorityExpr )
{
LabelNode* labelNode = new LabelNode(
context.getSession()->getMapInfo().getProfile()->getSRS(),
GeoPoint(feature->getSRS(), feature->getGeometry()->getBounds().center()),
value,
text );
if ( text->priority().isSet() )
{
AnnotationData* data = new AnnotationData();
data->setPriority( feature->eval(priorityExpr, &context) );
labelNode->setAnnotationData( data );
}
return labelNode;
}
};
//------------------------------------------------------------------------
class AnnotationLabelSourceDriver : public LabelSourceDriver
{
public:
AnnotationLabelSourceDriver()
{
supportsExtension( "osgearth_label_annotation", "osgEarth annotation label plugin" );
}
virtual const char* className()
{
return "osgEarth Annotation Label Plugin";
}
virtual ReadResult readObject(const std::string& file_name, const Options* options) const
{
if ( !acceptsExtension(osgDB::getLowerCaseFileExtension( file_name )))
return ReadResult::FILE_NOT_HANDLED;
return new AnnotationLabelSource( getLabelSourceOptions(options) );
}
};
REGISTER_OSGPLUGIN(osgearth_label_annotation, AnnotationLabelSourceDriver)
| airwzz999/osgearth-for-android | src/osgEarthDrivers/label_annotation/AnnotationLabelSource.cpp | C++ | lgpl-3.0 | 6,635 |
/************************************************************
**
** file: btreeif.cpp
** author: Andreas Steffens
** license: LGPL v3
**
** description:
**
** This file contains code for the b-tree frameworks base class
** on the iterator interface level.
**
************************************************************/
#ifndef BTREEBASEITERIF_CPP
#define BTREEBASEITERIF_CPP
#include "btreeif.h"
template<class _t_data, class _t_sizetype>
CBTreeIf<_t_data, _t_sizetype>::CBTreeIf ()
: CBTreeSuper ()
{
}
template<class _t_data, class _t_sizetype>
CBTreeIf<_t_data, _t_sizetype>::CBTreeIf (const CBTreeIf<_t_data, _t_sizetype> &rContainer)
: CBTreeSuper ()
{
}
template<class _t_data, class _t_sizetype>
CBTreeIf<_t_data, _t_sizetype>::CBTreeIf (CBTreeIf<_t_data, _t_sizetype> &&rRhsContainer)
: CBTreeSuper (dynamic_cast <CBTreeSuper &&> (rRhsContainer))
{
}
template<class _t_data, class _t_sizetype>
CBTreeIf<_t_data, _t_sizetype>::~CBTreeIf ()
{
}
/*
operator= - assignment operator overload
rContainer - is a reference of a container that will have its content be assigned to this instance
The result is a reference to this instance.
*/
template<class _t_data, class _t_sizetype>
CBTreeIf<_t_data, _t_sizetype> &
CBTreeIf<_t_data, _t_sizetype>::operator=
(const CBTreeIf<_t_data, _t_sizetype> &rContainer)
{
// if this is not the same instance as the right hand side container ...
if (this != &rContainer)
{
// ... then assign all data from right hand side to left hand side container
this->_assign (rContainer);
}
return (*this);
}
#endif // BTREEBASEITERIF_CPP
| andreas-steffens/btree-framework-demonstration | src/btreetest/btree_framework/base_class_stack/btreeif.cpp | C++ | lgpl-3.0 | 1,598 |
/*
* Copyright (C) 1999-2001 Harri Porten (porten@kde.org)
* Copyright (C) 2001 Peter Kelly (pmk@post.com)
* Copyright (C) 2003, 2007, 2008 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#include "config.h"
#include "JSCell.h"
#include "JSFunction.h"
#include "JSString.h"
#include "JSObject.h"
#include "NumberObject.h"
#include <wtf/MathExtras.h>
namespace JSC {
ASSERT_HAS_TRIVIAL_DESTRUCTOR(JSCell);
void JSCell::destroy(JSCell* cell)
{
cell->JSCell::~JSCell();
}
void JSCell::copyBackingStore(JSCell*, CopyVisitor&)
{
}
bool JSCell::getString(ExecState* exec, String& stringValue) const
{
if (!isString())
return false;
stringValue = static_cast<const JSString*>(this)->value(exec);
return true;
}
String JSCell::getString(ExecState* exec) const
{
return isString() ? static_cast<const JSString*>(this)->value(exec) : String();
}
JSObject* JSCell::getObject()
{
return isObject() ? asObject(this) : 0;
}
const JSObject* JSCell::getObject() const
{
return isObject() ? static_cast<const JSObject*>(this) : 0;
}
CallType JSCell::getCallData(JSCell*, CallData&)
{
return CallTypeNone;
}
ConstructType JSCell::getConstructData(JSCell*, ConstructData&)
{
return ConstructTypeNone;
}
bool JSCell::getOwnPropertySlot(JSCell* cell, ExecState* exec, PropertyName identifier, PropertySlot& slot)
{
// This is not a general purpose implementation of getOwnPropertySlot.
// It should only be called by JSValue::get.
// It calls getPropertySlot, not getOwnPropertySlot.
JSObject* object = cell->toObject(exec, exec->lexicalGlobalObject());
slot.setBase(object);
if (!object->getPropertySlot(exec, identifier, slot))
slot.setUndefined();
return true;
}
bool JSCell::getOwnPropertySlotByIndex(JSCell* cell, ExecState* exec, unsigned identifier, PropertySlot& slot)
{
// This is not a general purpose implementation of getOwnPropertySlot.
// It should only be called by JSValue::get.
// It calls getPropertySlot, not getOwnPropertySlot.
JSObject* object = cell->toObject(exec, exec->lexicalGlobalObject());
slot.setBase(object);
if (!object->getPropertySlot(exec, identifier, slot))
slot.setUndefined();
return true;
}
void JSCell::put(JSCell* cell, ExecState* exec, PropertyName identifier, JSValue value, PutPropertySlot& slot)
{
if (cell->isString()) {
JSValue(cell).putToPrimitive(exec, identifier, value, slot);
return;
}
JSObject* thisObject = cell->toObject(exec, exec->lexicalGlobalObject());
thisObject->methodTable()->put(thisObject, exec, identifier, value, slot);
}
void JSCell::putByIndex(JSCell* cell, ExecState* exec, unsigned identifier, JSValue value, bool shouldThrow)
{
if (cell->isString()) {
PutPropertySlot slot(shouldThrow);
JSValue(cell).putToPrimitive(exec, Identifier::from(exec, identifier), value, slot);
return;
}
JSObject* thisObject = cell->toObject(exec, exec->lexicalGlobalObject());
thisObject->methodTable()->putByIndex(thisObject, exec, identifier, value, shouldThrow);
}
bool JSCell::deleteProperty(JSCell* cell, ExecState* exec, PropertyName identifier)
{
JSObject* thisObject = cell->toObject(exec, exec->lexicalGlobalObject());
return thisObject->methodTable()->deleteProperty(thisObject, exec, identifier);
}
bool JSCell::deletePropertyByIndex(JSCell* cell, ExecState* exec, unsigned identifier)
{
JSObject* thisObject = cell->toObject(exec, exec->lexicalGlobalObject());
return thisObject->methodTable()->deletePropertyByIndex(thisObject, exec, identifier);
}
JSObject* JSCell::toThisObject(JSCell* cell, ExecState* exec)
{
return cell->toObject(exec, exec->lexicalGlobalObject());
}
JSValue JSCell::toPrimitive(ExecState* exec, PreferredPrimitiveType preferredType) const
{
if (isString())
return static_cast<const JSString*>(this)->toPrimitive(exec, preferredType);
return static_cast<const JSObject*>(this)->toPrimitive(exec, preferredType);
}
bool JSCell::getPrimitiveNumber(ExecState* exec, double& number, JSValue& value) const
{
if (isString())
return static_cast<const JSString*>(this)->getPrimitiveNumber(exec, number, value);
return static_cast<const JSObject*>(this)->getPrimitiveNumber(exec, number, value);
}
double JSCell::toNumber(ExecState* exec) const
{
if (isString())
return static_cast<const JSString*>(this)->toNumber(exec);
return static_cast<const JSObject*>(this)->toNumber(exec);
}
JSObject* JSCell::toObject(ExecState* exec, JSGlobalObject* globalObject) const
{
if (isString())
return static_cast<const JSString*>(this)->toObject(exec, globalObject);
ASSERT(isObject());
return jsCast<JSObject*>(const_cast<JSCell*>(this));
}
void slowValidateCell(JSCell* cell)
{
ASSERT_GC_OBJECT_LOOKS_VALID(cell);
}
JSValue JSCell::defaultValue(const JSObject*, ExecState*, PreferredPrimitiveType)
{
ASSERT_NOT_REACHED();
return jsUndefined();
}
void JSCell::getOwnPropertyNames(JSObject*, ExecState*, PropertyNameArray&, EnumerationMode)
{
ASSERT_NOT_REACHED();
}
void JSCell::getOwnNonIndexPropertyNames(JSObject*, ExecState*, PropertyNameArray&, EnumerationMode)
{
ASSERT_NOT_REACHED();
}
String JSCell::className(const JSObject*)
{
ASSERT_NOT_REACHED();
return String();
}
const char* JSCell::className()
{
return classInfo()->className;
}
void JSCell::getPropertyNames(JSObject*, ExecState*, PropertyNameArray&, EnumerationMode)
{
ASSERT_NOT_REACHED();
}
bool JSCell::customHasInstance(JSObject*, ExecState*, JSValue)
{
ASSERT_NOT_REACHED();
return false;
}
void JSCell::putDirectVirtual(JSObject*, ExecState*, PropertyName, JSValue, unsigned)
{
ASSERT_NOT_REACHED();
}
bool JSCell::defineOwnProperty(JSObject*, ExecState*, PropertyName, PropertyDescriptor&, bool)
{
ASSERT_NOT_REACHED();
return false;
}
bool JSCell::getOwnPropertyDescriptor(JSObject*, ExecState*, PropertyName, PropertyDescriptor&)
{
ASSERT_NOT_REACHED();
return false;
}
} // namespace JSC
| nawawi/wkhtmltopdf | webkit/Source/JavaScriptCore/runtime/JSCell.cpp | C++ | lgpl-3.0 | 6,870 |
/*
WARNING: THIS FILE IS AUTO-GENERATED. DO NOT MODIFY.
This file was generated from MessageHeader.idl using "rtiddsgen".
The rtiddsgen tool is part of the RTI Connext distribution.
For more information, type 'rtiddsgen -help' at a command shell
or consult the RTI Connext manual.
*/
#ifndef MessageHeaderPlugin_953112912_h
#define MessageHeaderPlugin_953112912_h
#include "MessageHeader.h"
struct RTICdrStream;
#ifndef pres_typePlugin_h
#include "pres/pres_typePlugin.h"
#endif
#if (defined(RTI_WIN32) || defined (RTI_WINCE)) && defined(NDDS_USER_DLL_EXPORT)
/* If the code is building on Windows, start exporting symbols.
*/
#undef NDDSUSERDllExport
#define NDDSUSERDllExport __declspec(dllexport)
#endif
#define UnknownOperationPlugin_get_sample PRESTypePluginDefaultEndpointData_getSample
#define UnknownOperationPlugin_get_buffer PRESTypePluginDefaultEndpointData_getBuffer
#define UnknownOperationPlugin_return_buffer PRESTypePluginDefaultEndpointData_returnBuffer
#define UnknownOperationPlugin_create_sample PRESTypePluginDefaultEndpointData_createSample
#define UnknownOperationPlugin_destroy_sample PRESTypePluginDefaultEndpointData_deleteSample
/* --------------------------------------------------------------------------------------
Support functions:
* -------------------------------------------------------------------------------------- */
NDDSUSERDllExport extern UnknownOperation*
UnknownOperationPluginSupport_create_data_w_params(
const struct DDS_TypeAllocationParams_t * alloc_params);
NDDSUSERDllExport extern UnknownOperation*
UnknownOperationPluginSupport_create_data_ex(RTIBool allocate_pointers);
NDDSUSERDllExport extern UnknownOperation*
UnknownOperationPluginSupport_create_data(void);
NDDSUSERDllExport extern RTIBool
UnknownOperationPluginSupport_copy_data(
UnknownOperation *out,
const UnknownOperation *in);
NDDSUSERDllExport extern void
UnknownOperationPluginSupport_destroy_data_w_params(
UnknownOperation *sample,
const struct DDS_TypeDeallocationParams_t * dealloc_params);
NDDSUSERDllExport extern void
UnknownOperationPluginSupport_destroy_data_ex(
UnknownOperation *sample,RTIBool deallocate_pointers);
NDDSUSERDllExport extern void
UnknownOperationPluginSupport_destroy_data(
UnknownOperation *sample);
NDDSUSERDllExport extern void
UnknownOperationPluginSupport_print_data(
const UnknownOperation *sample,
const char *desc,
unsigned int indent);
NDDSUSERDllExport extern RTIBool
UnknownOperationPlugin_copy_sample(
PRESTypePluginEndpointData endpoint_data,
UnknownOperation *out,
const UnknownOperation *in);
/* --------------------------------------------------------------------------------------
(De)Serialize functions:
* -------------------------------------------------------------------------------------- */
NDDSUSERDllExport extern RTIBool
UnknownOperationPlugin_serialize(
PRESTypePluginEndpointData endpoint_data,
const UnknownOperation *sample,
struct RTICdrStream *stream,
RTIBool serialize_encapsulation,
RTIEncapsulationId encapsulation_id,
RTIBool serialize_sample,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern RTIBool
UnknownOperationPlugin_deserialize_sample(
PRESTypePluginEndpointData endpoint_data,
UnknownOperation *sample,
struct RTICdrStream *stream,
RTIBool deserialize_encapsulation,
RTIBool deserialize_sample,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern RTIBool
UnknownOperationPlugin_skip(
PRESTypePluginEndpointData endpoint_data,
struct RTICdrStream *stream,
RTIBool skip_encapsulation,
RTIBool skip_sample,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern unsigned int
UnknownOperationPlugin_get_serialized_sample_max_size(
PRESTypePluginEndpointData endpoint_data,
RTIBool include_encapsulation,
RTIEncapsulationId encapsulation_id,
unsigned int current_alignment);
NDDSUSERDllExport extern unsigned int
UnknownOperationPlugin_get_serialized_sample_min_size(
PRESTypePluginEndpointData endpoint_data,
RTIBool include_encapsulation,
RTIEncapsulationId encapsulation_id,
unsigned int current_alignment);
NDDSUSERDllExport extern unsigned int
UnknownOperationPlugin_get_serialized_sample_size(
PRESTypePluginEndpointData endpoint_data,
RTIBool include_encapsulation,
RTIEncapsulationId encapsulation_id,
unsigned int current_alignment,
const UnknownOperation * sample);
/* --------------------------------------------------------------------------------------
Key Management functions:
* -------------------------------------------------------------------------------------- */
NDDSUSERDllExport extern PRESTypePluginKeyKind
UnknownOperationPlugin_get_key_kind(void);
NDDSUSERDllExport extern unsigned int
UnknownOperationPlugin_get_serialized_key_max_size(
PRESTypePluginEndpointData endpoint_data,
RTIBool include_encapsulation,
RTIEncapsulationId encapsulation_id,
unsigned int current_alignment);
NDDSUSERDllExport extern RTIBool
UnknownOperationPlugin_serialize_key(
PRESTypePluginEndpointData endpoint_data,
const UnknownOperation *sample,
struct RTICdrStream *stream,
RTIBool serialize_encapsulation,
RTIEncapsulationId encapsulation_id,
RTIBool serialize_key,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern RTIBool
UnknownOperationPlugin_deserialize_key_sample(
PRESTypePluginEndpointData endpoint_data,
UnknownOperation * sample,
struct RTICdrStream *stream,
RTIBool deserialize_encapsulation,
RTIBool deserialize_key,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern RTIBool
UnknownOperationPlugin_serialized_sample_to_key(
PRESTypePluginEndpointData endpoint_data,
UnknownOperation *sample,
struct RTICdrStream *stream,
RTIBool deserialize_encapsulation,
RTIBool deserialize_key,
void *endpoint_plugin_qos);
#define UnknownExceptionPlugin_get_sample PRESTypePluginDefaultEndpointData_getSample
#define UnknownExceptionPlugin_get_buffer PRESTypePluginDefaultEndpointData_getBuffer
#define UnknownExceptionPlugin_return_buffer PRESTypePluginDefaultEndpointData_returnBuffer
#define UnknownExceptionPlugin_create_sample PRESTypePluginDefaultEndpointData_createSample
#define UnknownExceptionPlugin_destroy_sample PRESTypePluginDefaultEndpointData_deleteSample
/* --------------------------------------------------------------------------------------
Support functions:
* -------------------------------------------------------------------------------------- */
NDDSUSERDllExport extern UnknownException*
UnknownExceptionPluginSupport_create_data_w_params(
const struct DDS_TypeAllocationParams_t * alloc_params);
NDDSUSERDllExport extern UnknownException*
UnknownExceptionPluginSupport_create_data_ex(RTIBool allocate_pointers);
NDDSUSERDllExport extern UnknownException*
UnknownExceptionPluginSupport_create_data(void);
NDDSUSERDllExport extern RTIBool
UnknownExceptionPluginSupport_copy_data(
UnknownException *out,
const UnknownException *in);
NDDSUSERDllExport extern void
UnknownExceptionPluginSupport_destroy_data_w_params(
UnknownException *sample,
const struct DDS_TypeDeallocationParams_t * dealloc_params);
NDDSUSERDllExport extern void
UnknownExceptionPluginSupport_destroy_data_ex(
UnknownException *sample,RTIBool deallocate_pointers);
NDDSUSERDllExport extern void
UnknownExceptionPluginSupport_destroy_data(
UnknownException *sample);
NDDSUSERDllExport extern void
UnknownExceptionPluginSupport_print_data(
const UnknownException *sample,
const char *desc,
unsigned int indent);
NDDSUSERDllExport extern RTIBool
UnknownExceptionPlugin_copy_sample(
PRESTypePluginEndpointData endpoint_data,
UnknownException *out,
const UnknownException *in);
/* --------------------------------------------------------------------------------------
(De)Serialize functions:
* -------------------------------------------------------------------------------------- */
NDDSUSERDllExport extern RTIBool
UnknownExceptionPlugin_serialize(
PRESTypePluginEndpointData endpoint_data,
const UnknownException *sample,
struct RTICdrStream *stream,
RTIBool serialize_encapsulation,
RTIEncapsulationId encapsulation_id,
RTIBool serialize_sample,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern RTIBool
UnknownExceptionPlugin_deserialize_sample(
PRESTypePluginEndpointData endpoint_data,
UnknownException *sample,
struct RTICdrStream *stream,
RTIBool deserialize_encapsulation,
RTIBool deserialize_sample,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern RTIBool
UnknownExceptionPlugin_skip(
PRESTypePluginEndpointData endpoint_data,
struct RTICdrStream *stream,
RTIBool skip_encapsulation,
RTIBool skip_sample,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern unsigned int
UnknownExceptionPlugin_get_serialized_sample_max_size(
PRESTypePluginEndpointData endpoint_data,
RTIBool include_encapsulation,
RTIEncapsulationId encapsulation_id,
unsigned int current_alignment);
NDDSUSERDllExport extern unsigned int
UnknownExceptionPlugin_get_serialized_sample_min_size(
PRESTypePluginEndpointData endpoint_data,
RTIBool include_encapsulation,
RTIEncapsulationId encapsulation_id,
unsigned int current_alignment);
NDDSUSERDllExport extern unsigned int
UnknownExceptionPlugin_get_serialized_sample_size(
PRESTypePluginEndpointData endpoint_data,
RTIBool include_encapsulation,
RTIEncapsulationId encapsulation_id,
unsigned int current_alignment,
const UnknownException * sample);
/* --------------------------------------------------------------------------------------
Key Management functions:
* -------------------------------------------------------------------------------------- */
NDDSUSERDllExport extern PRESTypePluginKeyKind
UnknownExceptionPlugin_get_key_kind(void);
NDDSUSERDllExport extern unsigned int
UnknownExceptionPlugin_get_serialized_key_max_size(
PRESTypePluginEndpointData endpoint_data,
RTIBool include_encapsulation,
RTIEncapsulationId encapsulation_id,
unsigned int current_alignment);
NDDSUSERDllExport extern RTIBool
UnknownExceptionPlugin_serialize_key(
PRESTypePluginEndpointData endpoint_data,
const UnknownException *sample,
struct RTICdrStream *stream,
RTIBool serialize_encapsulation,
RTIEncapsulationId encapsulation_id,
RTIBool serialize_key,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern RTIBool
UnknownExceptionPlugin_deserialize_key_sample(
PRESTypePluginEndpointData endpoint_data,
UnknownException * sample,
struct RTICdrStream *stream,
RTIBool deserialize_encapsulation,
RTIBool deserialize_key,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern RTIBool
UnknownExceptionPlugin_serialized_sample_to_key(
PRESTypePluginEndpointData endpoint_data,
UnknownException *sample,
struct RTICdrStream *stream,
RTIBool deserialize_encapsulation,
RTIBool deserialize_key,
void *endpoint_plugin_qos);
/* ------------------------------------------------------------------------
* (De)Serialization Methods
* ------------------------------------------------------------------------ */
NDDSUSERDllExport extern RTIBool
SystemExceptionCodePlugin_serialize(
PRESTypePluginEndpointData endpoint_data,
const SystemExceptionCode *sample, struct RTICdrStream *stream,
RTIBool serialize_encapsulation,
RTIEncapsulationId encapsulation_id,
RTIBool serialize_sample,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern RTIBool
SystemExceptionCodePlugin_deserialize_sample(
PRESTypePluginEndpointData endpoint_data,
SystemExceptionCode *sample,
struct RTICdrStream *stream,
RTIBool deserialize_encapsulation,
RTIBool deserialize_sample,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern RTIBool
SystemExceptionCodePlugin_skip(
PRESTypePluginEndpointData endpoint_data,
struct RTICdrStream *stream,
RTIBool skip_encapsulation,
RTIBool skip_sample,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern unsigned int
SystemExceptionCodePlugin_get_serialized_sample_max_size(
PRESTypePluginEndpointData endpoint_data,
RTIBool include_encapsulation,
RTIEncapsulationId encapsulation_id,
unsigned int current_alignment);
NDDSUSERDllExport extern unsigned int
SystemExceptionCodePlugin_get_serialized_sample_min_size(
PRESTypePluginEndpointData endpoint_data,
RTIBool include_encapsulation,
RTIEncapsulationId encapsulation_id,
unsigned int current_alignment);
NDDSUSERDllExport extern unsigned int
SystemExceptionCodePlugin_get_serialized_sample_size(
PRESTypePluginEndpointData endpoint_data,
RTIBool include_encapsulation,
RTIEncapsulationId encapsulation_id,
unsigned int current_alignment,
const SystemExceptionCode * sample);
/* ------------------------------------------------------------------------
Key Management functions:
* ------------------------------------------------------------------------ */
NDDSUSERDllExport extern RTIBool
SystemExceptionCodePlugin_serialize_key(
PRESTypePluginEndpointData endpoint_data,
const SystemExceptionCode *sample,
struct RTICdrStream *stream,
RTIBool serialize_encapsulation,
RTIEncapsulationId encapsulation_id,
RTIBool serialize_key,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern RTIBool
SystemExceptionCodePlugin_deserialize_key_sample(
PRESTypePluginEndpointData endpoint_data,
SystemExceptionCode *sample,
struct RTICdrStream *stream,
RTIBool deserialize_encapsulation,
RTIBool deserialize_key,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern unsigned int
SystemExceptionCodePlugin_get_serialized_key_max_size(
PRESTypePluginEndpointData endpoint_data,
RTIBool include_encapsulation,
RTIEncapsulationId encapsulation_id,
unsigned int current_alignment);
NDDSUSERDllExport extern RTIBool
SystemExceptionCodePlugin_serialized_sample_to_key(
PRESTypePluginEndpointData endpoint_data,
SystemExceptionCode *sample,
struct RTICdrStream *stream,
RTIBool deserialize_encapsulation,
RTIBool deserialize_key,
void *endpoint_plugin_qos);
/* ----------------------------------------------------------------------------
Support functions:
* ---------------------------------------------------------------------------- */
NDDSUSERDllExport extern void
SystemExceptionCodePluginSupport_print_data(
const SystemExceptionCode *sample, const char *desc, int indent_level);
#define GUID_tPlugin_get_sample PRESTypePluginDefaultEndpointData_getSample
#define GUID_tPlugin_get_buffer PRESTypePluginDefaultEndpointData_getBuffer
#define GUID_tPlugin_return_buffer PRESTypePluginDefaultEndpointData_returnBuffer
#define GUID_tPlugin_create_sample PRESTypePluginDefaultEndpointData_createSample
#define GUID_tPlugin_destroy_sample PRESTypePluginDefaultEndpointData_deleteSample
/* --------------------------------------------------------------------------------------
Support functions:
* -------------------------------------------------------------------------------------- */
NDDSUSERDllExport extern GUID_t*
GUID_tPluginSupport_create_data_w_params(
const struct DDS_TypeAllocationParams_t * alloc_params);
NDDSUSERDllExport extern GUID_t*
GUID_tPluginSupport_create_data_ex(RTIBool allocate_pointers);
NDDSUSERDllExport extern GUID_t*
GUID_tPluginSupport_create_data(void);
NDDSUSERDllExport extern RTIBool
GUID_tPluginSupport_copy_data(
GUID_t *out,
const GUID_t *in);
NDDSUSERDllExport extern void
GUID_tPluginSupport_destroy_data_w_params(
GUID_t *sample,
const struct DDS_TypeDeallocationParams_t * dealloc_params);
NDDSUSERDllExport extern void
GUID_tPluginSupport_destroy_data_ex(
GUID_t *sample,RTIBool deallocate_pointers);
NDDSUSERDllExport extern void
GUID_tPluginSupport_destroy_data(
GUID_t *sample);
NDDSUSERDllExport extern void
GUID_tPluginSupport_print_data(
const GUID_t *sample,
const char *desc,
unsigned int indent);
NDDSUSERDllExport extern RTIBool
GUID_tPlugin_copy_sample(
PRESTypePluginEndpointData endpoint_data,
GUID_t *out,
const GUID_t *in);
/* --------------------------------------------------------------------------------------
(De)Serialize functions:
* -------------------------------------------------------------------------------------- */
NDDSUSERDllExport extern RTIBool
GUID_tPlugin_serialize(
PRESTypePluginEndpointData endpoint_data,
const GUID_t *sample,
struct RTICdrStream *stream,
RTIBool serialize_encapsulation,
RTIEncapsulationId encapsulation_id,
RTIBool serialize_sample,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern RTIBool
GUID_tPlugin_deserialize_sample(
PRESTypePluginEndpointData endpoint_data,
GUID_t *sample,
struct RTICdrStream *stream,
RTIBool deserialize_encapsulation,
RTIBool deserialize_sample,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern RTIBool
GUID_tPlugin_deserialize(
PRESTypePluginEndpointData endpoint_data,
GUID_t **sample,
RTIBool * drop_sample,
struct RTICdrStream *stream,
RTIBool deserialize_encapsulation,
RTIBool deserialize_sample,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern RTIBool
GUID_tPlugin_skip(
PRESTypePluginEndpointData endpoint_data,
struct RTICdrStream *stream,
RTIBool skip_encapsulation,
RTIBool skip_sample,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern unsigned int
GUID_tPlugin_get_serialized_sample_max_size(
PRESTypePluginEndpointData endpoint_data,
RTIBool include_encapsulation,
RTIEncapsulationId encapsulation_id,
unsigned int current_alignment);
NDDSUSERDllExport extern unsigned int
GUID_tPlugin_get_serialized_sample_min_size(
PRESTypePluginEndpointData endpoint_data,
RTIBool include_encapsulation,
RTIEncapsulationId encapsulation_id,
unsigned int current_alignment);
NDDSUSERDllExport extern unsigned int
GUID_tPlugin_get_serialized_sample_size(
PRESTypePluginEndpointData endpoint_data,
RTIBool include_encapsulation,
RTIEncapsulationId encapsulation_id,
unsigned int current_alignment,
const GUID_t * sample);
/* --------------------------------------------------------------------------------------
Key Management functions:
* -------------------------------------------------------------------------------------- */
NDDSUSERDllExport extern PRESTypePluginKeyKind
GUID_tPlugin_get_key_kind(void);
NDDSUSERDllExport extern unsigned int
GUID_tPlugin_get_serialized_key_max_size(
PRESTypePluginEndpointData endpoint_data,
RTIBool include_encapsulation,
RTIEncapsulationId encapsulation_id,
unsigned int current_alignment);
NDDSUSERDllExport extern RTIBool
GUID_tPlugin_serialize_key(
PRESTypePluginEndpointData endpoint_data,
const GUID_t *sample,
struct RTICdrStream *stream,
RTIBool serialize_encapsulation,
RTIEncapsulationId encapsulation_id,
RTIBool serialize_key,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern RTIBool
GUID_tPlugin_deserialize_key_sample(
PRESTypePluginEndpointData endpoint_data,
GUID_t * sample,
struct RTICdrStream *stream,
RTIBool deserialize_encapsulation,
RTIBool deserialize_key,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern RTIBool
GUID_tPlugin_deserialize_key(
PRESTypePluginEndpointData endpoint_data,
GUID_t ** sample,
RTIBool * drop_sample,
struct RTICdrStream *stream,
RTIBool deserialize_encapsulation,
RTIBool deserialize_key,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern RTIBool
GUID_tPlugin_serialized_sample_to_key(
PRESTypePluginEndpointData endpoint_data,
GUID_t *sample,
struct RTICdrStream *stream,
RTIBool deserialize_encapsulation,
RTIBool deserialize_key,
void *endpoint_plugin_qos);
#define SampleIdentity_tPlugin_get_sample PRESTypePluginDefaultEndpointData_getSample
#define SampleIdentity_tPlugin_get_buffer PRESTypePluginDefaultEndpointData_getBuffer
#define SampleIdentity_tPlugin_return_buffer PRESTypePluginDefaultEndpointData_returnBuffer
#define SampleIdentity_tPlugin_create_sample PRESTypePluginDefaultEndpointData_createSample
#define SampleIdentity_tPlugin_destroy_sample PRESTypePluginDefaultEndpointData_deleteSample
/* --------------------------------------------------------------------------------------
Support functions:
* -------------------------------------------------------------------------------------- */
NDDSUSERDllExport extern SampleIdentity_t*
SampleIdentity_tPluginSupport_create_data_w_params(
const struct DDS_TypeAllocationParams_t * alloc_params);
NDDSUSERDllExport extern SampleIdentity_t*
SampleIdentity_tPluginSupport_create_data_ex(RTIBool allocate_pointers);
NDDSUSERDllExport extern SampleIdentity_t*
SampleIdentity_tPluginSupport_create_data(void);
NDDSUSERDllExport extern RTIBool
SampleIdentity_tPluginSupport_copy_data(
SampleIdentity_t *out,
const SampleIdentity_t *in);
NDDSUSERDllExport extern void
SampleIdentity_tPluginSupport_destroy_data_w_params(
SampleIdentity_t *sample,
const struct DDS_TypeDeallocationParams_t * dealloc_params);
NDDSUSERDllExport extern void
SampleIdentity_tPluginSupport_destroy_data_ex(
SampleIdentity_t *sample,RTIBool deallocate_pointers);
NDDSUSERDllExport extern void
SampleIdentity_tPluginSupport_destroy_data(
SampleIdentity_t *sample);
NDDSUSERDllExport extern void
SampleIdentity_tPluginSupport_print_data(
const SampleIdentity_t *sample,
const char *desc,
unsigned int indent);
/* ----------------------------------------------------------------------------
Callback functions:
* ---------------------------------------------------------------------------- */
NDDSUSERDllExport extern PRESTypePluginParticipantData
SampleIdentity_tPlugin_on_participant_attached(
void *registration_data,
const struct PRESTypePluginParticipantInfo *participant_info,
RTIBool top_level_registration,
void *container_plugin_context,
RTICdrTypeCode *typeCode);
NDDSUSERDllExport extern void
SampleIdentity_tPlugin_on_participant_detached(
PRESTypePluginParticipantData participant_data);
NDDSUSERDllExport extern PRESTypePluginEndpointData
SampleIdentity_tPlugin_on_endpoint_attached(
PRESTypePluginParticipantData participant_data,
const struct PRESTypePluginEndpointInfo *endpoint_info,
RTIBool top_level_registration,
void *container_plugin_context);
NDDSUSERDllExport extern void
SampleIdentity_tPlugin_on_endpoint_detached(
PRESTypePluginEndpointData endpoint_data);
NDDSUSERDllExport extern void
SampleIdentity_tPlugin_return_sample(
PRESTypePluginEndpointData endpoint_data,
SampleIdentity_t *sample,
void *handle);
NDDSUSERDllExport extern RTIBool
SampleIdentity_tPlugin_copy_sample(
PRESTypePluginEndpointData endpoint_data,
SampleIdentity_t *out,
const SampleIdentity_t *in);
/* --------------------------------------------------------------------------------------
(De)Serialize functions:
* -------------------------------------------------------------------------------------- */
NDDSUSERDllExport extern RTIBool
SampleIdentity_tPlugin_serialize(
PRESTypePluginEndpointData endpoint_data,
const SampleIdentity_t *sample,
struct RTICdrStream *stream,
RTIBool serialize_encapsulation,
RTIEncapsulationId encapsulation_id,
RTIBool serialize_sample,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern RTIBool
SampleIdentity_tPlugin_deserialize_sample(
PRESTypePluginEndpointData endpoint_data,
SampleIdentity_t *sample,
struct RTICdrStream *stream,
RTIBool deserialize_encapsulation,
RTIBool deserialize_sample,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern RTIBool
SampleIdentity_tPlugin_deserialize(
PRESTypePluginEndpointData endpoint_data,
SampleIdentity_t **sample,
RTIBool * drop_sample,
struct RTICdrStream *stream,
RTIBool deserialize_encapsulation,
RTIBool deserialize_sample,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern RTIBool
SampleIdentity_tPlugin_skip(
PRESTypePluginEndpointData endpoint_data,
struct RTICdrStream *stream,
RTIBool skip_encapsulation,
RTIBool skip_sample,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern unsigned int
SampleIdentity_tPlugin_get_serialized_sample_max_size(
PRESTypePluginEndpointData endpoint_data,
RTIBool include_encapsulation,
RTIEncapsulationId encapsulation_id,
unsigned int current_alignment);
NDDSUSERDllExport extern unsigned int
SampleIdentity_tPlugin_get_serialized_sample_min_size(
PRESTypePluginEndpointData endpoint_data,
RTIBool include_encapsulation,
RTIEncapsulationId encapsulation_id,
unsigned int current_alignment);
NDDSUSERDllExport extern unsigned int
SampleIdentity_tPlugin_get_serialized_sample_size(
PRESTypePluginEndpointData endpoint_data,
RTIBool include_encapsulation,
RTIEncapsulationId encapsulation_id,
unsigned int current_alignment,
const SampleIdentity_t * sample);
/* --------------------------------------------------------------------------------------
Key Management functions:
* -------------------------------------------------------------------------------------- */
NDDSUSERDllExport extern PRESTypePluginKeyKind
SampleIdentity_tPlugin_get_key_kind(void);
NDDSUSERDllExport extern unsigned int
SampleIdentity_tPlugin_get_serialized_key_max_size(
PRESTypePluginEndpointData endpoint_data,
RTIBool include_encapsulation,
RTIEncapsulationId encapsulation_id,
unsigned int current_alignment);
NDDSUSERDllExport extern RTIBool
SampleIdentity_tPlugin_serialize_key(
PRESTypePluginEndpointData endpoint_data,
const SampleIdentity_t *sample,
struct RTICdrStream *stream,
RTIBool serialize_encapsulation,
RTIEncapsulationId encapsulation_id,
RTIBool serialize_key,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern RTIBool
SampleIdentity_tPlugin_deserialize_key_sample(
PRESTypePluginEndpointData endpoint_data,
SampleIdentity_t * sample,
struct RTICdrStream *stream,
RTIBool deserialize_encapsulation,
RTIBool deserialize_key,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern RTIBool
SampleIdentity_tPlugin_deserialize_key(
PRESTypePluginEndpointData endpoint_data,
SampleIdentity_t ** sample,
RTIBool * drop_sample,
struct RTICdrStream *stream,
RTIBool deserialize_encapsulation,
RTIBool deserialize_key,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern RTIBool
SampleIdentity_tPlugin_serialized_sample_to_key(
PRESTypePluginEndpointData endpoint_data,
SampleIdentity_t *sample,
struct RTICdrStream *stream,
RTIBool deserialize_encapsulation,
RTIBool deserialize_key,
void *endpoint_plugin_qos);
/* Plugin Functions */
NDDSUSERDllExport extern struct PRESTypePlugin*
SampleIdentity_tPlugin_new(void);
NDDSUSERDllExport extern void
SampleIdentity_tPlugin_delete(struct PRESTypePlugin *);
#define RequestHeaderPlugin_get_sample PRESTypePluginDefaultEndpointData_getSample
#define RequestHeaderPlugin_get_buffer PRESTypePluginDefaultEndpointData_getBuffer
#define RequestHeaderPlugin_return_buffer PRESTypePluginDefaultEndpointData_returnBuffer
#define RequestHeaderPlugin_create_sample PRESTypePluginDefaultEndpointData_createSample
#define RequestHeaderPlugin_destroy_sample PRESTypePluginDefaultEndpointData_deleteSample
/* --------------------------------------------------------------------------------------
Support functions:
* -------------------------------------------------------------------------------------- */
NDDSUSERDllExport extern RequestHeader*
RequestHeaderPluginSupport_create_data_w_params(
const struct DDS_TypeAllocationParams_t * alloc_params);
NDDSUSERDllExport extern RequestHeader*
RequestHeaderPluginSupport_create_data_ex(RTIBool allocate_pointers);
NDDSUSERDllExport extern RequestHeader*
RequestHeaderPluginSupport_create_data(void);
NDDSUSERDllExport extern RTIBool
RequestHeaderPluginSupport_copy_data(
RequestHeader *out,
const RequestHeader *in);
NDDSUSERDllExport extern void
RequestHeaderPluginSupport_destroy_data_w_params(
RequestHeader *sample,
const struct DDS_TypeDeallocationParams_t * dealloc_params);
NDDSUSERDllExport extern void
RequestHeaderPluginSupport_destroy_data_ex(
RequestHeader *sample,RTIBool deallocate_pointers);
NDDSUSERDllExport extern void
RequestHeaderPluginSupport_destroy_data(
RequestHeader *sample);
NDDSUSERDllExport extern void
RequestHeaderPluginSupport_print_data(
const RequestHeader *sample,
const char *desc,
unsigned int indent);
NDDSUSERDllExport extern RTIBool
RequestHeaderPlugin_copy_sample(
PRESTypePluginEndpointData endpoint_data,
RequestHeader *out,
const RequestHeader *in);
/* --------------------------------------------------------------------------------------
(De)Serialize functions:
* -------------------------------------------------------------------------------------- */
NDDSUSERDllExport extern RTIBool
RequestHeaderPlugin_serialize(
PRESTypePluginEndpointData endpoint_data,
const RequestHeader *sample,
struct RTICdrStream *stream,
RTIBool serialize_encapsulation,
RTIEncapsulationId encapsulation_id,
RTIBool serialize_sample,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern RTIBool
RequestHeaderPlugin_deserialize_sample(
PRESTypePluginEndpointData endpoint_data,
RequestHeader *sample,
struct RTICdrStream *stream,
RTIBool deserialize_encapsulation,
RTIBool deserialize_sample,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern RTIBool
RequestHeaderPlugin_deserialize(
PRESTypePluginEndpointData endpoint_data,
RequestHeader **sample,
RTIBool * drop_sample,
struct RTICdrStream *stream,
RTIBool deserialize_encapsulation,
RTIBool deserialize_sample,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern RTIBool
RequestHeaderPlugin_skip(
PRESTypePluginEndpointData endpoint_data,
struct RTICdrStream *stream,
RTIBool skip_encapsulation,
RTIBool skip_sample,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern unsigned int
RequestHeaderPlugin_get_serialized_sample_max_size(
PRESTypePluginEndpointData endpoint_data,
RTIBool include_encapsulation,
RTIEncapsulationId encapsulation_id,
unsigned int current_alignment);
NDDSUSERDllExport extern unsigned int
RequestHeaderPlugin_get_serialized_sample_min_size(
PRESTypePluginEndpointData endpoint_data,
RTIBool include_encapsulation,
RTIEncapsulationId encapsulation_id,
unsigned int current_alignment);
NDDSUSERDllExport extern unsigned int
RequestHeaderPlugin_get_serialized_sample_size(
PRESTypePluginEndpointData endpoint_data,
RTIBool include_encapsulation,
RTIEncapsulationId encapsulation_id,
unsigned int current_alignment,
const RequestHeader * sample);
/* --------------------------------------------------------------------------------------
Key Management functions:
* -------------------------------------------------------------------------------------- */
NDDSUSERDllExport extern PRESTypePluginKeyKind
RequestHeaderPlugin_get_key_kind(void);
NDDSUSERDllExport extern unsigned int
RequestHeaderPlugin_get_serialized_key_max_size(
PRESTypePluginEndpointData endpoint_data,
RTIBool include_encapsulation,
RTIEncapsulationId encapsulation_id,
unsigned int current_alignment);
NDDSUSERDllExport extern RTIBool
RequestHeaderPlugin_serialize_key(
PRESTypePluginEndpointData endpoint_data,
const RequestHeader *sample,
struct RTICdrStream *stream,
RTIBool serialize_encapsulation,
RTIEncapsulationId encapsulation_id,
RTIBool serialize_key,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern RTIBool
RequestHeaderPlugin_deserialize_key_sample(
PRESTypePluginEndpointData endpoint_data,
RequestHeader * sample,
struct RTICdrStream *stream,
RTIBool deserialize_encapsulation,
RTIBool deserialize_key,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern RTIBool
RequestHeaderPlugin_deserialize_key(
PRESTypePluginEndpointData endpoint_data,
RequestHeader ** sample,
RTIBool * drop_sample,
struct RTICdrStream *stream,
RTIBool deserialize_encapsulation,
RTIBool deserialize_key,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern RTIBool
RequestHeaderPlugin_serialized_sample_to_key(
PRESTypePluginEndpointData endpoint_data,
RequestHeader *sample,
struct RTICdrStream *stream,
RTIBool deserialize_encapsulation,
RTIBool deserialize_key,
void *endpoint_plugin_qos);
#define ReplyHeaderPlugin_get_sample PRESTypePluginDefaultEndpointData_getSample
#define ReplyHeaderPlugin_get_buffer PRESTypePluginDefaultEndpointData_getBuffer
#define ReplyHeaderPlugin_return_buffer PRESTypePluginDefaultEndpointData_returnBuffer
#define ReplyHeaderPlugin_create_sample PRESTypePluginDefaultEndpointData_createSample
#define ReplyHeaderPlugin_destroy_sample PRESTypePluginDefaultEndpointData_deleteSample
/* --------------------------------------------------------------------------------------
Support functions:
* -------------------------------------------------------------------------------------- */
NDDSUSERDllExport extern ReplyHeader*
ReplyHeaderPluginSupport_create_data_w_params(
const struct DDS_TypeAllocationParams_t * alloc_params);
NDDSUSERDllExport extern ReplyHeader*
ReplyHeaderPluginSupport_create_data_ex(RTIBool allocate_pointers);
NDDSUSERDllExport extern ReplyHeader*
ReplyHeaderPluginSupport_create_data(void);
NDDSUSERDllExport extern RTIBool
ReplyHeaderPluginSupport_copy_data(
ReplyHeader *out,
const ReplyHeader *in);
NDDSUSERDllExport extern void
ReplyHeaderPluginSupport_destroy_data_w_params(
ReplyHeader *sample,
const struct DDS_TypeDeallocationParams_t * dealloc_params);
NDDSUSERDllExport extern void
ReplyHeaderPluginSupport_destroy_data_ex(
ReplyHeader *sample,RTIBool deallocate_pointers);
NDDSUSERDllExport extern void
ReplyHeaderPluginSupport_destroy_data(
ReplyHeader *sample);
NDDSUSERDllExport extern void
ReplyHeaderPluginSupport_print_data(
const ReplyHeader *sample,
const char *desc,
unsigned int indent);
NDDSUSERDllExport extern RTIBool
ReplyHeaderPlugin_copy_sample(
PRESTypePluginEndpointData endpoint_data,
ReplyHeader *out,
const ReplyHeader *in);
/* --------------------------------------------------------------------------------------
(De)Serialize functions:
* -------------------------------------------------------------------------------------- */
NDDSUSERDllExport extern RTIBool
ReplyHeaderPlugin_serialize(
PRESTypePluginEndpointData endpoint_data,
const ReplyHeader *sample,
struct RTICdrStream *stream,
RTIBool serialize_encapsulation,
RTIEncapsulationId encapsulation_id,
RTIBool serialize_sample,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern RTIBool
ReplyHeaderPlugin_deserialize_sample(
PRESTypePluginEndpointData endpoint_data,
ReplyHeader *sample,
struct RTICdrStream *stream,
RTIBool deserialize_encapsulation,
RTIBool deserialize_sample,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern RTIBool
ReplyHeaderPlugin_deserialize(
PRESTypePluginEndpointData endpoint_data,
ReplyHeader **sample,
RTIBool * drop_sample,
struct RTICdrStream *stream,
RTIBool deserialize_encapsulation,
RTIBool deserialize_sample,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern RTIBool
ReplyHeaderPlugin_skip(
PRESTypePluginEndpointData endpoint_data,
struct RTICdrStream *stream,
RTIBool skip_encapsulation,
RTIBool skip_sample,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern unsigned int
ReplyHeaderPlugin_get_serialized_sample_max_size(
PRESTypePluginEndpointData endpoint_data,
RTIBool include_encapsulation,
RTIEncapsulationId encapsulation_id,
unsigned int current_alignment);
NDDSUSERDllExport extern unsigned int
ReplyHeaderPlugin_get_serialized_sample_min_size(
PRESTypePluginEndpointData endpoint_data,
RTIBool include_encapsulation,
RTIEncapsulationId encapsulation_id,
unsigned int current_alignment);
NDDSUSERDllExport extern unsigned int
ReplyHeaderPlugin_get_serialized_sample_size(
PRESTypePluginEndpointData endpoint_data,
RTIBool include_encapsulation,
RTIEncapsulationId encapsulation_id,
unsigned int current_alignment,
const ReplyHeader * sample);
/* --------------------------------------------------------------------------------------
Key Management functions:
* -------------------------------------------------------------------------------------- */
NDDSUSERDllExport extern PRESTypePluginKeyKind
ReplyHeaderPlugin_get_key_kind(void);
NDDSUSERDllExport extern unsigned int
ReplyHeaderPlugin_get_serialized_key_max_size(
PRESTypePluginEndpointData endpoint_data,
RTIBool include_encapsulation,
RTIEncapsulationId encapsulation_id,
unsigned int current_alignment);
NDDSUSERDllExport extern RTIBool
ReplyHeaderPlugin_serialize_key(
PRESTypePluginEndpointData endpoint_data,
const ReplyHeader *sample,
struct RTICdrStream *stream,
RTIBool serialize_encapsulation,
RTIEncapsulationId encapsulation_id,
RTIBool serialize_key,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern RTIBool
ReplyHeaderPlugin_deserialize_key_sample(
PRESTypePluginEndpointData endpoint_data,
ReplyHeader * sample,
struct RTICdrStream *stream,
RTIBool deserialize_encapsulation,
RTIBool deserialize_key,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern RTIBool
ReplyHeaderPlugin_deserialize_key(
PRESTypePluginEndpointData endpoint_data,
ReplyHeader ** sample,
RTIBool * drop_sample,
struct RTICdrStream *stream,
RTIBool deserialize_encapsulation,
RTIBool deserialize_key,
void *endpoint_plugin_qos);
NDDSUSERDllExport extern RTIBool
ReplyHeaderPlugin_serialized_sample_to_key(
PRESTypePluginEndpointData endpoint_data,
ReplyHeader *sample,
struct RTICdrStream *stream,
RTIBool deserialize_encapsulation,
RTIBool deserialize_key,
void *endpoint_plugin_qos);
#if (defined(RTI_WIN32) || defined (RTI_WINCE)) && defined(NDDS_USER_DLL_EXPORT)
/* If the code is building on Windows, stop exporting symbols.
*/
#undef NDDSUSERDllExport
#define NDDSUSERDllExport
#endif
#endif /* MessageHeaderPlugin_953112912_h */
| osrf/librpcdds | examples/C++/ddsTypes/CalculatorTCP/MessageHeaderPlugin.h | C | lgpl-3.0 | 39,291 |
FROM frolvlad/alpine-oraclejdk8:slim
VOLUME /tmp
ADD listen-1.0-SNAPSHOT.jar app.jar
RUN sh -c 'touch /app.jar'
ENV JAVA_OPTS=""
ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar" ] | AJauffre/trackr | listen/src/main/docker/Dockerfile | Dockerfile | unlicense | 227 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.6.0_30) on Sat Mar 22 15:15:54 EDT 2014 -->
<title>SeriesChangeEvent (JFreeChart Class Library (version 1.0.17))</title>
<meta name="date" content="2014-03-22">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="SeriesChangeEvent (JFreeChart Class Library (version 1.0.17))";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/SeriesChangeEvent.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/jfree/data/general/Series.html" title="class in org.jfree.data.general"><span class="strong">PREV CLASS</span></a></li>
<li><a href="../../../../org/jfree/data/general/SeriesChangeListener.html" title="interface in org.jfree.data.general"><span class="strong">NEXT CLASS</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/jfree/data/general/SeriesChangeEvent.html" target="_top">FRAMES</a></li>
<li><a href="SeriesChangeEvent.html" target="_top">NO FRAMES</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>SUMMARY: </li>
<li>NESTED | </li>
<li><a href="#fields_inherited_from_class_java.util.EventObject">FIELD</a> | </li>
<li><a href="#constructor_summary">CONSTR</a> | </li>
<li><a href="#methods_inherited_from_class_java.util.EventObject">METHOD</a></li>
</ul>
<ul class="subNavList">
<li>DETAIL: </li>
<li>FIELD | </li>
<li><a href="#constructor_detail">CONSTR</a> | </li>
<li>METHOD</li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<p class="subTitle">org.jfree.data.general</p>
<h2 title="Class SeriesChangeEvent" class="title">Class SeriesChangeEvent</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>java.util.EventObject</li>
<li>
<ul class="inheritance">
<li>org.jfree.data.general.SeriesChangeEvent</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd>java.io.Serializable</dd>
</dl>
<hr>
<br>
<pre>public class <a href="../../../../src-html/org/jfree/data/general/SeriesChangeEvent.html#line.50">SeriesChangeEvent</a>
extends java.util.EventObject
implements java.io.Serializable</pre>
<div class="block">An event with details of a change to a series.</div>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../serialized-form.html#org.jfree.data.general.SeriesChangeEvent">Serialized Form</a></dd></dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<ul class="blockList">
<li class="blockList"><a name="fields_inherited_from_class_java.util.EventObject">
<!-- -->
</a>
<h3>Fields inherited from class java.util.EventObject</h3>
<code>source</code></li>
</ul>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../org/jfree/data/general/SeriesChangeEvent.html#SeriesChangeEvent(java.lang.Object)">SeriesChangeEvent</a></strong>(java.lang.Object source)</code>
<div class="block">Constructs a new event.</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.util.EventObject">
<!-- -->
</a>
<h3>Methods inherited from class java.util.EventObject</h3>
<code>getSource, toString</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="SeriesChangeEvent(java.lang.Object)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>SeriesChangeEvent</h4>
<pre>public <a href="../../../../src-html/org/jfree/data/general/SeriesChangeEvent.html#line.60">SeriesChangeEvent</a>(java.lang.Object source)</pre>
<div class="block">Constructs a new event.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>source</code> - the source of the change event.</dd></dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/SeriesChangeEvent.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/jfree/data/general/Series.html" title="class in org.jfree.data.general"><span class="strong">PREV CLASS</span></a></li>
<li><a href="../../../../org/jfree/data/general/SeriesChangeListener.html" title="interface in org.jfree.data.general"><span class="strong">NEXT CLASS</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/jfree/data/general/SeriesChangeEvent.html" target="_top">FRAMES</a></li>
<li><a href="SeriesChangeEvent.html" target="_top">NO FRAMES</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>SUMMARY: </li>
<li>NESTED | </li>
<li><a href="#fields_inherited_from_class_java.util.EventObject">FIELD</a> | </li>
<li><a href="#constructor_summary">CONSTR</a> | </li>
<li><a href="#methods_inherited_from_class_java.util.EventObject">METHOD</a></li>
</ul>
<ul class="subNavList">
<li>DETAIL: </li>
<li>FIELD | </li>
<li><a href="#constructor_detail">CONSTR</a> | </li>
<li>METHOD</li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| GliderWinchItems/GliderWinchj2 | lib/JFreeChart-1.0.17/javadoc/org/jfree/data/general/SeriesChangeEvent.html | HTML | unlicense | 9,103 |
/*
_____ __ ___ __ ____ _ __
/ ___/__ ___ _ ___ / |/ /__ ___ / /_____ __ __/ __/_______(_)__ / /_
/ (_ / _ `/ ' \/ -_) /|_/ / _ \/ _ \/ '_/ -_) // /\ \/ __/ __/ / _ \/ __/
\___/\_,_/_/_/_/\__/_/ /_/\___/_//_/_/\_\\__/\_, /___/\__/_/ /_/ .__/\__/
/___/ /_/
See Copyright Notice in gmMachine.h
*/
#ifndef _GMBYTECODE_H_
#define _GMBYTECODE_H_
#include "gmConfig.h"
/// \enum gmByteCode
/// \brief gmByteCode are the op codes for the game monkey scripting. The first byte codes MUST match the gmOperator
/// enum.
enum gmByteCode
{
// BC_GETDOT to BC_NOP MUST MATCH ENUM GMOPERATOR
BC_GETDOT = 0, // tos '.' opptr, push result
BC_SETDOT, // tos-1 '.' opptr = tos, tos -= 2
BC_GETIND, // tos-1 = tos-1 [tos], --tos
BC_SETIND, // tos-2 [tos-1] = tos, tos -= 3
// math
BC_OP_ADD,
BC_OP_SUB,
BC_OP_MUL,
BC_OP_DIV,
BC_OP_REM,
#if GM_USE_INCDECOPERATORS
BC_OP_INC,
BC_OP_DEC,
#endif //GM_USE_INCDECOPERATORS
// bit
BC_BIT_OR,
BC_BIT_XOR,
BC_BIT_AND,
BC_BIT_SHL,
BC_BIT_SHR,
BC_BIT_INV,
// compare
BC_OP_LT,
BC_OP_GT,
BC_OP_LTE,
BC_OP_GTE,
BC_OP_EQ,
BC_OP_NEQ,
// unary
BC_OP_NEG,
BC_OP_POS,
BC_OP_NOT,
BC_NOP,
BC_LINE, // indicates instruction is on a new code line to the last executed instruction. used in debug mode
// branch
BC_BRA, // branch always
BC_BRZ, // branch tos equal to zero, --tos
BC_BRNZ, // branch tos not equal to zero, --tos
BC_BRZK, // branch tos equal to zero keep value on stack
BC_BRNZK, // branch tos not equal to zero keep value on stack
BC_CALL, // call op16 num parameters
BC_RET, // return null, ++tos
BC_RETV, // return tos
BC_FOREACH, // op16 op16, table, iterator, leave loop complete bool on stack.
// stack
BC_POP, // --tos
BC_POP2, // tos -=2
BC_DUP, // tos + 1 = tos, ++tos
BC_DUP2, // tos + 1 = tos -1, tos + 2 = tos, tos += 2
BC_SWAP, //
BC_PUSHNULL, // push null,
BC_PUSHINT, // push int opptr
BC_PUSHINT0, // push 0
BC_PUSHINT1, // push 1
BC_PUSHFP, // push floating point op32
BC_PUSHSTR, // push string opptr
BC_PUSHTBL, // push table
BC_PUSHFN, // push function opptr
BC_PUSHTHIS, // push this
// get set
BC_GETLOCAL, // get local op16 (stack offset) ++tos
BC_SETLOCAL, // set local op16 (stack offset) --tos
BC_GETGLOBAL, // get global opptr (symbol id) ++tos
BC_SETGLOBAL, // set global opptr (symbol id) --tos
BC_GETTHIS, // get this opptr (symbol id) ++tos
BC_SETTHIS, // set this opptr (symbol id) --tos
#if GM_USE_FORK
BC_FORK, // Fork
#endif //GM_USE_FORK
};
#if GM_COMPILE_DEBUG
void gmByteCodePrint(FILE * a_fp, const void * a_byteCode, int a_byteCodeLength);
#endif // GM_COMPILE_DEBUG
#endif
| r-lyeh/scriptorium | gamemonkey/src/gm/gmByteCode.h | C | unlicense | 3,241 |
package com.dstevens.user.patronage;
import com.dstevens.utilities.Identified;
public enum PaymentType implements Identified<Integer> {
OTHER(0),
PAYPAL(1),
AWARD(2),
GIFT(3)
;
public static PaymentType forId(int id) {
for (PaymentType paymentType : values()) {
if(paymentType.id == id) {
return paymentType;
}
}
throw new IllegalArgumentException("No payment type found for id " + id);
}
private final int id;
private PaymentType(int id) {
this.id = id;
}
@Override
public Integer getId() {
return id;
}
}
| tsal/ElysiumFrontend | src/java/com/dstevens/user/patronage/PaymentType.java | Java | unlicense | 585 |
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#if !defined(AFX_STDAFX_H__B8C4E1DD_5404_4CDD_B748_AFC934CC44BC__INCLUDED_)
#define AFX_STDAFX_H__B8C4E1DD_5404_4CDD_B748_AFC934CC44BC__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers
#include <afxwin.h> // MFC core and standard components
#include <afxext.h> // MFC extensions
#include <afxdisp.h> // MFC Automation classes
#include <afxdtctl.h> // MFC support for Internet Explorer 4 Common Controls
#ifndef _AFX_NO_AFXCMN_SUPPORT
#include <afxcmn.h> // MFC support for Windows Common Controls
#endif // _AFX_NO_AFXCMN_SUPPORT
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_STDAFX_H__B8C4E1DD_5404_4CDD_B748_AFC934CC44BC__INCLUDED_)
| hyller/CodeLibrary | Visual C++ Example/第17章 多媒体开发/实例394——在OpenGL中,使用纹理显示图形/OpenGLTexture/StdAfx.h | C | unlicense | 1,054 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
export { default } from './DateFilterLabel';
| mistercrunch/panoramix | superset-frontend/src/explore/components/controls/DateFilterControl/index.ts | TypeScript | apache-2.0 | 854 |
/**
* InventoryServiceSoapBindingStub.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.dfp.axis.v201405;
public class InventoryServiceSoapBindingStub extends org.apache.axis.client.Stub implements com.google.api.ads.dfp.axis.v201405.InventoryServiceInterface {
private java.util.Vector cachedSerClasses = new java.util.Vector();
private java.util.Vector cachedSerQNames = new java.util.Vector();
private java.util.Vector cachedSerFactories = new java.util.Vector();
private java.util.Vector cachedDeserFactories = new java.util.Vector();
static org.apache.axis.description.OperationDesc [] _operations;
static {
_operations = new org.apache.axis.description.OperationDesc[5];
_initOperationDesc1();
}
private static void _initOperationDesc1(){
org.apache.axis.description.OperationDesc oper;
org.apache.axis.description.ParameterDesc param;
oper = new org.apache.axis.description.OperationDesc();
oper.setName("createAdUnits");
param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "adUnits"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "AdUnit"), com.google.api.ads.dfp.axis.v201405.AdUnit[].class, false, false);
param.setOmittable(true);
oper.addParameter(param);
oper.setReturnType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "AdUnit"));
oper.setReturnClass(com.google.api.ads.dfp.axis.v201405.AdUnit[].class);
oper.setReturnQName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "rval"));
oper.setStyle(org.apache.axis.constants.Style.WRAPPED);
oper.setUse(org.apache.axis.constants.Use.LITERAL);
oper.addFault(new org.apache.axis.description.FaultDesc(
new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "ApiExceptionFault"),
"com.google.api.ads.dfp.axis.v201405.ApiException",
new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "ApiException"),
true
));
_operations[0] = oper;
oper = new org.apache.axis.description.OperationDesc();
oper.setName("getAdUnitSizesByStatement");
param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "filterStatement"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "Statement"), com.google.api.ads.dfp.axis.v201405.Statement.class, false, false);
param.setOmittable(true);
oper.addParameter(param);
oper.setReturnType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "AdUnitSize"));
oper.setReturnClass(com.google.api.ads.dfp.axis.v201405.AdUnitSize[].class);
oper.setReturnQName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "rval"));
oper.setStyle(org.apache.axis.constants.Style.WRAPPED);
oper.setUse(org.apache.axis.constants.Use.LITERAL);
oper.addFault(new org.apache.axis.description.FaultDesc(
new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "ApiExceptionFault"),
"com.google.api.ads.dfp.axis.v201405.ApiException",
new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "ApiException"),
true
));
_operations[1] = oper;
oper = new org.apache.axis.description.OperationDesc();
oper.setName("getAdUnitsByStatement");
param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "filterStatement"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "Statement"), com.google.api.ads.dfp.axis.v201405.Statement.class, false, false);
param.setOmittable(true);
oper.addParameter(param);
oper.setReturnType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "AdUnitPage"));
oper.setReturnClass(com.google.api.ads.dfp.axis.v201405.AdUnitPage.class);
oper.setReturnQName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "rval"));
oper.setStyle(org.apache.axis.constants.Style.WRAPPED);
oper.setUse(org.apache.axis.constants.Use.LITERAL);
oper.addFault(new org.apache.axis.description.FaultDesc(
new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "ApiExceptionFault"),
"com.google.api.ads.dfp.axis.v201405.ApiException",
new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "ApiException"),
true
));
_operations[2] = oper;
oper = new org.apache.axis.description.OperationDesc();
oper.setName("performAdUnitAction");
param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "adUnitAction"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "AdUnitAction"), com.google.api.ads.dfp.axis.v201405.AdUnitAction.class, false, false);
param.setOmittable(true);
oper.addParameter(param);
param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "filterStatement"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "Statement"), com.google.api.ads.dfp.axis.v201405.Statement.class, false, false);
param.setOmittable(true);
oper.addParameter(param);
oper.setReturnType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "UpdateResult"));
oper.setReturnClass(com.google.api.ads.dfp.axis.v201405.UpdateResult.class);
oper.setReturnQName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "rval"));
oper.setStyle(org.apache.axis.constants.Style.WRAPPED);
oper.setUse(org.apache.axis.constants.Use.LITERAL);
oper.addFault(new org.apache.axis.description.FaultDesc(
new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "ApiExceptionFault"),
"com.google.api.ads.dfp.axis.v201405.ApiException",
new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "ApiException"),
true
));
_operations[3] = oper;
oper = new org.apache.axis.description.OperationDesc();
oper.setName("updateAdUnits");
param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "adUnits"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "AdUnit"), com.google.api.ads.dfp.axis.v201405.AdUnit[].class, false, false);
param.setOmittable(true);
oper.addParameter(param);
oper.setReturnType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "AdUnit"));
oper.setReturnClass(com.google.api.ads.dfp.axis.v201405.AdUnit[].class);
oper.setReturnQName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "rval"));
oper.setStyle(org.apache.axis.constants.Style.WRAPPED);
oper.setUse(org.apache.axis.constants.Use.LITERAL);
oper.addFault(new org.apache.axis.description.FaultDesc(
new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "ApiExceptionFault"),
"com.google.api.ads.dfp.axis.v201405.ApiException",
new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "ApiException"),
true
));
_operations[4] = oper;
}
public InventoryServiceSoapBindingStub() throws org.apache.axis.AxisFault {
this(null);
}
public InventoryServiceSoapBindingStub(java.net.URL endpointURL, javax.xml.rpc.Service service) throws org.apache.axis.AxisFault {
this(service);
super.cachedEndpoint = endpointURL;
}
public InventoryServiceSoapBindingStub(javax.xml.rpc.Service service) throws org.apache.axis.AxisFault {
if (service == null) {
super.service = new org.apache.axis.client.Service();
} else {
super.service = service;
}
((org.apache.axis.client.Service)super.service).setTypeMappingVersion("1.2");
java.lang.Class cls;
javax.xml.namespace.QName qName;
javax.xml.namespace.QName qName2;
java.lang.Class beansf = org.apache.axis.encoding.ser.BeanSerializerFactory.class;
java.lang.Class beandf = org.apache.axis.encoding.ser.BeanDeserializerFactory.class;
java.lang.Class enumsf = org.apache.axis.encoding.ser.EnumSerializerFactory.class;
java.lang.Class enumdf = org.apache.axis.encoding.ser.EnumDeserializerFactory.class;
java.lang.Class arraysf = org.apache.axis.encoding.ser.ArraySerializerFactory.class;
java.lang.Class arraydf = org.apache.axis.encoding.ser.ArrayDeserializerFactory.class;
java.lang.Class simplesf = org.apache.axis.encoding.ser.SimpleSerializerFactory.class;
java.lang.Class simpledf = org.apache.axis.encoding.ser.SimpleDeserializerFactory.class;
java.lang.Class simplelistsf = org.apache.axis.encoding.ser.SimpleListSerializerFactory.class;
java.lang.Class simplelistdf = org.apache.axis.encoding.ser.SimpleListDeserializerFactory.class;
addBindings0();
addBindings1();
}
private void addBindings0() {
java.lang.Class cls;
javax.xml.namespace.QName qName;
javax.xml.namespace.QName qName2;
java.lang.Class beansf = org.apache.axis.encoding.ser.BeanSerializerFactory.class;
java.lang.Class beandf = org.apache.axis.encoding.ser.BeanDeserializerFactory.class;
java.lang.Class enumsf = org.apache.axis.encoding.ser.EnumSerializerFactory.class;
java.lang.Class enumdf = org.apache.axis.encoding.ser.EnumDeserializerFactory.class;
java.lang.Class arraysf = org.apache.axis.encoding.ser.ArraySerializerFactory.class;
java.lang.Class arraydf = org.apache.axis.encoding.ser.ArrayDeserializerFactory.class;
java.lang.Class simplesf = org.apache.axis.encoding.ser.SimpleSerializerFactory.class;
java.lang.Class simpledf = org.apache.axis.encoding.ser.SimpleDeserializerFactory.class;
java.lang.Class simplelistsf = org.apache.axis.encoding.ser.SimpleListSerializerFactory.class;
java.lang.Class simplelistdf = org.apache.axis.encoding.ser.SimpleListDeserializerFactory.class;
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "ActivateAdUnits");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.ActivateAdUnits.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "AdSenseAccountError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.AdSenseAccountError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "AdSenseAccountError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.AdSenseAccountErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "AdSenseSettings");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.AdSenseSettings.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "AdSenseSettings.AdType");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.AdSenseSettingsAdType.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "AdSenseSettings.BorderStyle");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.AdSenseSettingsBorderStyle.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "AdSenseSettings.FontFamily");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.AdSenseSettingsFontFamily.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "AdSenseSettings.FontSize");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.AdSenseSettingsFontSize.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "AdSenseSettingsInheritedProperty");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.AdSenseSettingsInheritedProperty.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "AdUnit");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.AdUnit.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "AdUnit.TargetWindow");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.AdUnitTargetWindow.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "AdUnitAction");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.AdUnitAction.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "AdUnitAfcSizeError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.AdUnitAfcSizeError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "AdUnitAfcSizeError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.AdUnitAfcSizeErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "AdUnitCodeError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.AdUnitCodeError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "AdUnitCodeError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.AdUnitCodeErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "AdUnitHierarchyError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.AdUnitHierarchyError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "AdUnitHierarchyError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.AdUnitHierarchyErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "AdUnitPage");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.AdUnitPage.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "AdUnitParent");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.AdUnitParent.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "AdUnitSize");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.AdUnitSize.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "AdUnitTypeError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.AdUnitTypeError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "AdUnitTypeError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.AdUnitTypeErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "ApiError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.ApiError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "ApiException");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.ApiException.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "ApiVersionError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.ApiVersionError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "ApiVersionError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.ApiVersionErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "ApplicationException");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.ApplicationException.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "AppliedLabel");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.AppliedLabel.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "ArchiveAdUnits");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.ArchiveAdUnits.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "AssignAdUnitsToPlacement");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.AssignAdUnitsToPlacement.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "AuthenticationError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.AuthenticationError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "AuthenticationError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.AuthenticationErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "BooleanValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.BooleanValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "CollectionSizeError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.CollectionSizeError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "CollectionSizeError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.CollectionSizeErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "CommonError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.CommonError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "CommonError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.CommonErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "CreativeWrapperError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.CreativeWrapperError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "CreativeWrapperError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.CreativeWrapperErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "CrossSellError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.CrossSellError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "CrossSellError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.CrossSellErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "Date");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.Date.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "DateTime");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.DateTime.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "DateTimeValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.DateTimeValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "DateValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.DateValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "DeactivateAdUnits");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.DeactivateAdUnits.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "EntityLimitReachedError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.EntityLimitReachedError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "EnvironmentType");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.EnvironmentType.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "FeatureError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.FeatureError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "FeatureError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.FeatureErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "FrequencyCap");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.FrequencyCap.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "FrequencyCapError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.FrequencyCapError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "FrequencyCapError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.FrequencyCapErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "InternalApiError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.InternalApiError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "InternalApiError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.InternalApiErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "InvalidColorError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.InvalidColorError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "InvalidColorError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.InvalidColorErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "InventoryStatus");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.InventoryStatus.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "InventoryUnitError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.InventoryUnitError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "InventoryUnitError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.InventoryUnitErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "InventoryUnitPartnerAssociationError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.InventoryUnitPartnerAssociationError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "InventoryUnitPartnerAssociationError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.InventoryUnitPartnerAssociationErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "InventoryUnitSizesError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.InventoryUnitSizesError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "InventoryUnitSizesError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.InventoryUnitSizesErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "LabelFrequencyCap");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.LabelFrequencyCap.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "MobilePlatform");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.MobilePlatform.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "NotNullError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.NotNullError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "NotNullError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.NotNullErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "NullError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.NullError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "NullError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.NullErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "NumberValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.NumberValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "ParseError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.ParseError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "ParseError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.ParseErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "PermissionError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.PermissionError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "PermissionError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.PermissionErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "PublisherQueryLanguageContextError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.PublisherQueryLanguageContextError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "PublisherQueryLanguageContextError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.PublisherQueryLanguageContextErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "PublisherQueryLanguageSyntaxError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.PublisherQueryLanguageSyntaxError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "PublisherQueryLanguageSyntaxError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.PublisherQueryLanguageSyntaxErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "QuotaError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.QuotaError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "QuotaError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.QuotaErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "RegExError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.RegExError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "RegExError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.RegExErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "RemoveAdUnitsFromPlacement");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.RemoveAdUnitsFromPlacement.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "RequiredCollectionError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.RequiredCollectionError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "RequiredCollectionError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.RequiredCollectionErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "RequiredError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.RequiredError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "RequiredError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.RequiredErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "RequiredNumberError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.RequiredNumberError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "RequiredNumberError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.RequiredNumberErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "ServerError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.ServerError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "ServerError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.ServerErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "SetValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.SetValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "Size");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.Size.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "Size_StringMapEntry");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.Size_StringMapEntry.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "SmartSizeMode");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.SmartSizeMode.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "SoapRequestHeader");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.SoapRequestHeader.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "SoapResponseHeader");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.SoapResponseHeader.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "Statement");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.Statement.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
}
private void addBindings1() {
java.lang.Class cls;
javax.xml.namespace.QName qName;
javax.xml.namespace.QName qName2;
java.lang.Class beansf = org.apache.axis.encoding.ser.BeanSerializerFactory.class;
java.lang.Class beandf = org.apache.axis.encoding.ser.BeanDeserializerFactory.class;
java.lang.Class enumsf = org.apache.axis.encoding.ser.EnumSerializerFactory.class;
java.lang.Class enumdf = org.apache.axis.encoding.ser.EnumDeserializerFactory.class;
java.lang.Class arraysf = org.apache.axis.encoding.ser.ArraySerializerFactory.class;
java.lang.Class arraydf = org.apache.axis.encoding.ser.ArrayDeserializerFactory.class;
java.lang.Class simplesf = org.apache.axis.encoding.ser.SimpleSerializerFactory.class;
java.lang.Class simpledf = org.apache.axis.encoding.ser.SimpleDeserializerFactory.class;
java.lang.Class simplelistsf = org.apache.axis.encoding.ser.SimpleListSerializerFactory.class;
java.lang.Class simplelistdf = org.apache.axis.encoding.ser.SimpleListDeserializerFactory.class;
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "StatementError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.StatementError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "StatementError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.StatementErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "String_ValueMapEntry");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.String_ValueMapEntry.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "StringLengthError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.StringLengthError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "StringLengthError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.StringLengthErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "TargetPlatform");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.TargetPlatform.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "TeamError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.TeamError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "TeamError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.TeamErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "TextValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.TextValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "TimeUnit");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.TimeUnit.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "TypeError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.TypeError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "UniqueError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.UniqueError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "UpdateResult");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.UpdateResult.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "Value");
cachedSerQNames.add(qName);
cls = com.google.api.ads.dfp.axis.v201405.Value.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
}
protected org.apache.axis.client.Call createCall() throws java.rmi.RemoteException {
try {
org.apache.axis.client.Call _call = super._createCall();
if (super.maintainSessionSet) {
_call.setMaintainSession(super.maintainSession);
}
if (super.cachedUsername != null) {
_call.setUsername(super.cachedUsername);
}
if (super.cachedPassword != null) {
_call.setPassword(super.cachedPassword);
}
if (super.cachedEndpoint != null) {
_call.setTargetEndpointAddress(super.cachedEndpoint);
}
if (super.cachedTimeout != null) {
_call.setTimeout(super.cachedTimeout);
}
if (super.cachedPortName != null) {
_call.setPortName(super.cachedPortName);
}
java.util.Enumeration keys = super.cachedProperties.keys();
while (keys.hasMoreElements()) {
java.lang.String key = (java.lang.String) keys.nextElement();
_call.setProperty(key, super.cachedProperties.get(key));
}
// All the type mapping information is registered
// when the first call is made.
// The type mapping information is actually registered in
// the TypeMappingRegistry of the service, which
// is the reason why registration is only needed for the first call.
synchronized (this) {
if (firstCall()) {
// must set encoding style before registering serializers
_call.setEncodingStyle(null);
for (int i = 0; i < cachedSerFactories.size(); ++i) {
java.lang.Class cls = (java.lang.Class) cachedSerClasses.get(i);
javax.xml.namespace.QName qName =
(javax.xml.namespace.QName) cachedSerQNames.get(i);
java.lang.Object x = cachedSerFactories.get(i);
if (x instanceof Class) {
java.lang.Class sf = (java.lang.Class)
cachedSerFactories.get(i);
java.lang.Class df = (java.lang.Class)
cachedDeserFactories.get(i);
_call.registerTypeMapping(cls, qName, sf, df, false);
}
else if (x instanceof javax.xml.rpc.encoding.SerializerFactory) {
org.apache.axis.encoding.SerializerFactory sf = (org.apache.axis.encoding.SerializerFactory)
cachedSerFactories.get(i);
org.apache.axis.encoding.DeserializerFactory df = (org.apache.axis.encoding.DeserializerFactory)
cachedDeserFactories.get(i);
_call.registerTypeMapping(cls, qName, sf, df, false);
}
}
}
}
return _call;
}
catch (java.lang.Throwable _t) {
throw new org.apache.axis.AxisFault("Failure trying to get the Call object", _t);
}
}
public com.google.api.ads.dfp.axis.v201405.AdUnit[] createAdUnits(com.google.api.ads.dfp.axis.v201405.AdUnit[] adUnits) throws java.rmi.RemoteException, com.google.api.ads.dfp.axis.v201405.ApiException {
if (super.cachedEndpoint == null) {
throw new org.apache.axis.NoEndPointException();
}
org.apache.axis.client.Call _call = createCall();
_call.setOperation(_operations[0]);
_call.setUseSOAPAction(true);
_call.setSOAPActionURI("");
_call.setEncodingStyle(null);
_call.setProperty(org.apache.axis.client.Call.SEND_TYPE_ATTR, Boolean.FALSE);
_call.setProperty(org.apache.axis.AxisEngine.PROP_DOMULTIREFS, Boolean.FALSE);
_call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS);
_call.setOperationName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "createAdUnits"));
setRequestHeaders(_call);
setAttachments(_call);
try { java.lang.Object _resp = _call.invoke(new java.lang.Object[] {adUnits});
if (_resp instanceof java.rmi.RemoteException) {
throw (java.rmi.RemoteException)_resp;
}
else {
extractAttachments(_call);
try {
return (com.google.api.ads.dfp.axis.v201405.AdUnit[]) _resp;
} catch (java.lang.Exception _exception) {
return (com.google.api.ads.dfp.axis.v201405.AdUnit[]) org.apache.axis.utils.JavaUtils.convert(_resp, com.google.api.ads.dfp.axis.v201405.AdUnit[].class);
}
}
} catch (org.apache.axis.AxisFault axisFaultException) {
if (axisFaultException.detail != null) {
if (axisFaultException.detail instanceof java.rmi.RemoteException) {
throw (java.rmi.RemoteException) axisFaultException.detail;
}
if (axisFaultException.detail instanceof com.google.api.ads.dfp.axis.v201405.ApiException) {
throw (com.google.api.ads.dfp.axis.v201405.ApiException) axisFaultException.detail;
}
}
throw axisFaultException;
}
}
public com.google.api.ads.dfp.axis.v201405.AdUnitSize[] getAdUnitSizesByStatement(com.google.api.ads.dfp.axis.v201405.Statement filterStatement) throws java.rmi.RemoteException, com.google.api.ads.dfp.axis.v201405.ApiException {
if (super.cachedEndpoint == null) {
throw new org.apache.axis.NoEndPointException();
}
org.apache.axis.client.Call _call = createCall();
_call.setOperation(_operations[1]);
_call.setUseSOAPAction(true);
_call.setSOAPActionURI("");
_call.setEncodingStyle(null);
_call.setProperty(org.apache.axis.client.Call.SEND_TYPE_ATTR, Boolean.FALSE);
_call.setProperty(org.apache.axis.AxisEngine.PROP_DOMULTIREFS, Boolean.FALSE);
_call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS);
_call.setOperationName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "getAdUnitSizesByStatement"));
setRequestHeaders(_call);
setAttachments(_call);
try { java.lang.Object _resp = _call.invoke(new java.lang.Object[] {filterStatement});
if (_resp instanceof java.rmi.RemoteException) {
throw (java.rmi.RemoteException)_resp;
}
else {
extractAttachments(_call);
try {
return (com.google.api.ads.dfp.axis.v201405.AdUnitSize[]) _resp;
} catch (java.lang.Exception _exception) {
return (com.google.api.ads.dfp.axis.v201405.AdUnitSize[]) org.apache.axis.utils.JavaUtils.convert(_resp, com.google.api.ads.dfp.axis.v201405.AdUnitSize[].class);
}
}
} catch (org.apache.axis.AxisFault axisFaultException) {
if (axisFaultException.detail != null) {
if (axisFaultException.detail instanceof java.rmi.RemoteException) {
throw (java.rmi.RemoteException) axisFaultException.detail;
}
if (axisFaultException.detail instanceof com.google.api.ads.dfp.axis.v201405.ApiException) {
throw (com.google.api.ads.dfp.axis.v201405.ApiException) axisFaultException.detail;
}
}
throw axisFaultException;
}
}
public com.google.api.ads.dfp.axis.v201405.AdUnitPage getAdUnitsByStatement(com.google.api.ads.dfp.axis.v201405.Statement filterStatement) throws java.rmi.RemoteException, com.google.api.ads.dfp.axis.v201405.ApiException {
if (super.cachedEndpoint == null) {
throw new org.apache.axis.NoEndPointException();
}
org.apache.axis.client.Call _call = createCall();
_call.setOperation(_operations[2]);
_call.setUseSOAPAction(true);
_call.setSOAPActionURI("");
_call.setEncodingStyle(null);
_call.setProperty(org.apache.axis.client.Call.SEND_TYPE_ATTR, Boolean.FALSE);
_call.setProperty(org.apache.axis.AxisEngine.PROP_DOMULTIREFS, Boolean.FALSE);
_call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS);
_call.setOperationName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "getAdUnitsByStatement"));
setRequestHeaders(_call);
setAttachments(_call);
try { java.lang.Object _resp = _call.invoke(new java.lang.Object[] {filterStatement});
if (_resp instanceof java.rmi.RemoteException) {
throw (java.rmi.RemoteException)_resp;
}
else {
extractAttachments(_call);
try {
return (com.google.api.ads.dfp.axis.v201405.AdUnitPage) _resp;
} catch (java.lang.Exception _exception) {
return (com.google.api.ads.dfp.axis.v201405.AdUnitPage) org.apache.axis.utils.JavaUtils.convert(_resp, com.google.api.ads.dfp.axis.v201405.AdUnitPage.class);
}
}
} catch (org.apache.axis.AxisFault axisFaultException) {
if (axisFaultException.detail != null) {
if (axisFaultException.detail instanceof java.rmi.RemoteException) {
throw (java.rmi.RemoteException) axisFaultException.detail;
}
if (axisFaultException.detail instanceof com.google.api.ads.dfp.axis.v201405.ApiException) {
throw (com.google.api.ads.dfp.axis.v201405.ApiException) axisFaultException.detail;
}
}
throw axisFaultException;
}
}
public com.google.api.ads.dfp.axis.v201405.UpdateResult performAdUnitAction(com.google.api.ads.dfp.axis.v201405.AdUnitAction adUnitAction, com.google.api.ads.dfp.axis.v201405.Statement filterStatement) throws java.rmi.RemoteException, com.google.api.ads.dfp.axis.v201405.ApiException {
if (super.cachedEndpoint == null) {
throw new org.apache.axis.NoEndPointException();
}
org.apache.axis.client.Call _call = createCall();
_call.setOperation(_operations[3]);
_call.setUseSOAPAction(true);
_call.setSOAPActionURI("");
_call.setEncodingStyle(null);
_call.setProperty(org.apache.axis.client.Call.SEND_TYPE_ATTR, Boolean.FALSE);
_call.setProperty(org.apache.axis.AxisEngine.PROP_DOMULTIREFS, Boolean.FALSE);
_call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS);
_call.setOperationName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "performAdUnitAction"));
setRequestHeaders(_call);
setAttachments(_call);
try { java.lang.Object _resp = _call.invoke(new java.lang.Object[] {adUnitAction, filterStatement});
if (_resp instanceof java.rmi.RemoteException) {
throw (java.rmi.RemoteException)_resp;
}
else {
extractAttachments(_call);
try {
return (com.google.api.ads.dfp.axis.v201405.UpdateResult) _resp;
} catch (java.lang.Exception _exception) {
return (com.google.api.ads.dfp.axis.v201405.UpdateResult) org.apache.axis.utils.JavaUtils.convert(_resp, com.google.api.ads.dfp.axis.v201405.UpdateResult.class);
}
}
} catch (org.apache.axis.AxisFault axisFaultException) {
if (axisFaultException.detail != null) {
if (axisFaultException.detail instanceof java.rmi.RemoteException) {
throw (java.rmi.RemoteException) axisFaultException.detail;
}
if (axisFaultException.detail instanceof com.google.api.ads.dfp.axis.v201405.ApiException) {
throw (com.google.api.ads.dfp.axis.v201405.ApiException) axisFaultException.detail;
}
}
throw axisFaultException;
}
}
public com.google.api.ads.dfp.axis.v201405.AdUnit[] updateAdUnits(com.google.api.ads.dfp.axis.v201405.AdUnit[] adUnits) throws java.rmi.RemoteException, com.google.api.ads.dfp.axis.v201405.ApiException {
if (super.cachedEndpoint == null) {
throw new org.apache.axis.NoEndPointException();
}
org.apache.axis.client.Call _call = createCall();
_call.setOperation(_operations[4]);
_call.setUseSOAPAction(true);
_call.setSOAPActionURI("");
_call.setEncodingStyle(null);
_call.setProperty(org.apache.axis.client.Call.SEND_TYPE_ATTR, Boolean.FALSE);
_call.setProperty(org.apache.axis.AxisEngine.PROP_DOMULTIREFS, Boolean.FALSE);
_call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS);
_call.setOperationName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "updateAdUnits"));
setRequestHeaders(_call);
setAttachments(_call);
try { java.lang.Object _resp = _call.invoke(new java.lang.Object[] {adUnits});
if (_resp instanceof java.rmi.RemoteException) {
throw (java.rmi.RemoteException)_resp;
}
else {
extractAttachments(_call);
try {
return (com.google.api.ads.dfp.axis.v201405.AdUnit[]) _resp;
} catch (java.lang.Exception _exception) {
return (com.google.api.ads.dfp.axis.v201405.AdUnit[]) org.apache.axis.utils.JavaUtils.convert(_resp, com.google.api.ads.dfp.axis.v201405.AdUnit[].class);
}
}
} catch (org.apache.axis.AxisFault axisFaultException) {
if (axisFaultException.detail != null) {
if (axisFaultException.detail instanceof java.rmi.RemoteException) {
throw (java.rmi.RemoteException) axisFaultException.detail;
}
if (axisFaultException.detail instanceof com.google.api.ads.dfp.axis.v201405.ApiException) {
throw (com.google.api.ads.dfp.axis.v201405.ApiException) axisFaultException.detail;
}
}
throw axisFaultException;
}
}
}
| ya7lelkom/googleads-java-lib | modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201405/InventoryServiceSoapBindingStub.java | Java | apache-2.0 | 69,915 |
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/* Copyright 2014 Mozilla Foundation
*
* 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.
*/
/* globals PDFJS, Util, AnnotationType, AnnotationBorderStyleType, warn,
CustomStyle, isExternalLinkTargetSet, LinkTargetStringMap */
'use strict';
var ANNOT_MIN_SIZE = 10; // px
var AnnotationUtils = (function AnnotationUtilsClosure() {
// TODO(mack): This dupes some of the logic in CanvasGraphics.setFont()
function setTextStyles(element, item, fontObj) {
var style = element.style;
style.fontSize = item.fontSize + 'px';
style.direction = item.fontDirection < 0 ? 'rtl': 'ltr';
if (!fontObj) {
return;
}
style.fontWeight = fontObj.black ?
(fontObj.bold ? 'bolder' : 'bold') :
(fontObj.bold ? 'bold' : 'normal');
style.fontStyle = fontObj.italic ? 'italic' : 'normal';
var fontName = fontObj.loadedName;
var fontFamily = fontName ? '"' + fontName + '", ' : '';
// Use a reasonable default font if the font doesn't specify a fallback
var fallbackName = fontObj.fallbackName || 'Helvetica, sans-serif';
style.fontFamily = fontFamily + fallbackName;
}
function initContainer(item) {
var container = document.createElement('section');
var cstyle = container.style;
var width = item.rect[2] - item.rect[0];
var height = item.rect[3] - item.rect[1];
// Border
if (item.borderStyle.width > 0) {
// Border width
container.style.borderWidth = item.borderStyle.width + 'px';
if (item.borderStyle.style !== AnnotationBorderStyleType.UNDERLINE) {
// Underline styles only have a bottom border, so we do not need
// to adjust for all borders. This yields a similar result as
// Adobe Acrobat/Reader.
width = width - 2 * item.borderStyle.width;
height = height - 2 * item.borderStyle.width;
}
// Horizontal and vertical border radius
var horizontalRadius = item.borderStyle.horizontalCornerRadius;
var verticalRadius = item.borderStyle.verticalCornerRadius;
if (horizontalRadius > 0 || verticalRadius > 0) {
var radius = horizontalRadius + 'px / ' + verticalRadius + 'px';
CustomStyle.setProp('borderRadius', container, radius);
}
// Border style
switch (item.borderStyle.style) {
case AnnotationBorderStyleType.SOLID:
container.style.borderStyle = 'solid';
break;
case AnnotationBorderStyleType.DASHED:
container.style.borderStyle = 'dashed';
break;
case AnnotationBorderStyleType.BEVELED:
warn('Unimplemented border style: beveled');
break;
case AnnotationBorderStyleType.INSET:
warn('Unimplemented border style: inset');
break;
case AnnotationBorderStyleType.UNDERLINE:
container.style.borderBottomStyle = 'solid';
break;
default:
break;
}
// Border color
if (item.color) {
container.style.borderColor =
Util.makeCssRgb(item.color[0] | 0,
item.color[1] | 0,
item.color[2] | 0);
} else {
// Transparent (invisible) border, so do not draw it at all.
container.style.borderWidth = 0;
}
}
cstyle.width = width + 'px';
cstyle.height = height + 'px';
return container;
}
function getHtmlElementForTextWidgetAnnotation(item, commonObjs) {
var element = document.createElement('div');
var width = item.rect[2] - item.rect[0];
var height = item.rect[3] - item.rect[1];
element.style.width = width + 'px';
element.style.height = height + 'px';
element.style.display = 'table';
var content = document.createElement('div');
content.textContent = item.fieldValue;
var textAlignment = item.textAlignment;
content.style.textAlign = ['left', 'center', 'right'][textAlignment];
content.style.verticalAlign = 'middle';
content.style.display = 'table-cell';
var fontObj = item.fontRefName ?
commonObjs.getData(item.fontRefName) : null;
setTextStyles(content, item, fontObj);
element.appendChild(content);
return element;
}
function getHtmlElementForTextAnnotation(item) {
var rect = item.rect;
// sanity check because of OOo-generated PDFs
if ((rect[3] - rect[1]) < ANNOT_MIN_SIZE) {
rect[3] = rect[1] + ANNOT_MIN_SIZE;
}
if ((rect[2] - rect[0]) < ANNOT_MIN_SIZE) {
rect[2] = rect[0] + (rect[3] - rect[1]); // make it square
}
var container = initContainer(item);
container.className = 'annotText';
var image = document.createElement('img');
image.style.height = container.style.height;
image.style.width = container.style.width;
var iconName = item.name;
image.src = PDFJS.imageResourcesPath + 'annotation-' +
iconName.toLowerCase() + '.svg';
image.alt = '[{{type}} Annotation]';
image.dataset.l10nId = 'text_annotation_type';
image.dataset.l10nArgs = JSON.stringify({type: iconName});
var contentWrapper = document.createElement('div');
contentWrapper.className = 'annotTextContentWrapper';
contentWrapper.style.left = Math.floor(rect[2] - rect[0] + 5) + 'px';
contentWrapper.style.top = '-10px';
var content = document.createElement('div');
content.className = 'annotTextContent';
content.setAttribute('hidden', true);
var i, ii;
if (item.hasBgColor && item.color) {
var color = item.color;
// Enlighten the color (70%)
var BACKGROUND_ENLIGHT = 0.7;
var r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];
var g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];
var b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];
content.style.backgroundColor = Util.makeCssRgb(r | 0, g | 0, b | 0);
}
var title = document.createElement('h1');
var text = document.createElement('p');
title.textContent = item.title;
if (!item.content && !item.title) {
content.setAttribute('hidden', true);
} else {
var e = document.createElement('span');
var lines = item.content.split(/(?:\r\n?|\n)/);
for (i = 0, ii = lines.length; i < ii; ++i) {
var line = lines[i];
e.appendChild(document.createTextNode(line));
if (i < (ii - 1)) {
e.appendChild(document.createElement('br'));
}
}
text.appendChild(e);
var pinned = false;
var showAnnotation = function showAnnotation(pin) {
if (pin) {
pinned = true;
}
if (content.hasAttribute('hidden')) {
container.style.zIndex += 1;
content.removeAttribute('hidden');
}
};
var hideAnnotation = function hideAnnotation(unpin) {
if (unpin) {
pinned = false;
}
if (!content.hasAttribute('hidden') && !pinned) {
container.style.zIndex -= 1;
content.setAttribute('hidden', true);
}
};
var toggleAnnotation = function toggleAnnotation() {
if (pinned) {
hideAnnotation(true);
} else {
showAnnotation(true);
}
};
image.addEventListener('click', function image_clickHandler() {
toggleAnnotation();
}, false);
image.addEventListener('mouseover', function image_mouseOverHandler() {
showAnnotation();
}, false);
image.addEventListener('mouseout', function image_mouseOutHandler() {
hideAnnotation();
}, false);
content.addEventListener('click', function content_clickHandler() {
hideAnnotation(true);
}, false);
}
content.appendChild(title);
content.appendChild(text);
contentWrapper.appendChild(content);
container.appendChild(image);
container.appendChild(contentWrapper);
return container;
}
function getHtmlElementForLinkAnnotation(item) {
var container = initContainer(item);
container.className = 'annotLink';
var link = document.createElement('a');
link.href = link.title = item.url || '';
if (item.url && isExternalLinkTargetSet()) {
link.target = LinkTargetStringMap[PDFJS.externalLinkTarget];
}
container.appendChild(link);
return container;
}
function getHtmlElement(data, objs) {
switch (data.annotationType) {
case AnnotationType.WIDGET:
return getHtmlElementForTextWidgetAnnotation(data, objs);
case AnnotationType.TEXT:
return getHtmlElementForTextAnnotation(data);
case AnnotationType.LINK:
return getHtmlElementForLinkAnnotation(data);
default:
throw new Error('Unsupported annotationType: ' + data.annotationType);
}
}
return {
getHtmlElement: getHtmlElement
};
})();
PDFJS.AnnotationUtils = AnnotationUtils;
| kalley/pdf.js | src/display/annotation_helper.js | JavaScript | apache-2.0 | 9,506 |
#!/usr/bin/python
#
# Copyright 2013 Google Inc. All Rights Reserved.
#
# 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.
"""This code example deactivates all active placements. To determine which
placements exist, run get_all_placements.py."""
__author__ = 'api.shamjeff@gmail.com (Jeff Sham)'
# Locate the client library. If module was installed via "setup.py" script, then
# the following two lines are not needed.
import os
import sys
sys.path.insert(0, os.path.join('..', '..', '..', '..'))
# Import appropriate classes from the client library.
from adspygoogle import DfpClient
from adspygoogle.dfp import DfpUtils
# Initialize client object.
client = DfpClient(path=os.path.join('..', '..', '..', '..'))
# Initialize appropriate service.
placement_service = client.GetService('PlacementService', version='v201306')
# Create query.
values = [{
'key': 'status',
'value': {
'xsi_type': 'TextValue',
'value': 'ACTIVE'
}
}]
query = 'WHERE status = :status'
# Get placements by statement.
placements = DfpUtils.GetAllEntitiesByStatementWithService(
placement_service, query=query, bind_vars=values)
for placement in placements:
print ('Placement with id \'%s\', name \'%s\', and status \'%s\' will be '
'deactivated.' % (placement['id'], placement['name'],
placement['status']))
print 'Number of placements to be deactivated: %s' % len(placements)
# Perform action.
result = placement_service.PerformPlacementAction(
{'type': 'DeactivatePlacements'}, {'query': query, 'values': values})[0]
# Display results.
if result and int(result['numChanges']) > 0:
print 'Number of placements deactivated: %s' % result['numChanges']
else:
print 'No placements were deactivated.'
| caioserra/apiAdwords | examples/adspygoogle/dfp/v201306/deactivate_placements.py | Python | apache-2.0 | 2,253 |
/*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; 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.
*/
package org.camunda.bpm.model.bpmn;
import static org.assertj.core.api.Assertions.assertThat;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.BUSINESS_RULE_TASK;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.CALL_ACTIVITY_ID;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.END_EVENT_ID;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.PROCESS_ID;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.SCRIPT_TASK_ID;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.SEND_TASK_ID;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.SEQUENCE_FLOW_ID;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.SERVICE_TASK_ID;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.START_EVENT_ID;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.TEST_CLASS_API;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.TEST_CLASS_XML;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.TEST_DELEGATE_EXPRESSION_API;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.TEST_DELEGATE_EXPRESSION_XML;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.TEST_DUE_DATE_API;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.TEST_DUE_DATE_XML;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.TEST_EXECUTION_EVENT_API;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.TEST_EXECUTION_EVENT_XML;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.TEST_EXPRESSION_API;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.TEST_EXPRESSION_XML;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.TEST_FLOW_NODE_JOB_PRIORITY;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.TEST_GROUPS_API;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.TEST_GROUPS_LIST_API;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.TEST_GROUPS_LIST_XML;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.TEST_GROUPS_XML;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.TEST_HISTORY_TIME_TO_LIVE;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.TEST_PRIORITY_API;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.TEST_PRIORITY_XML;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.TEST_PROCESS_JOB_PRIORITY;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.TEST_PROCESS_TASK_PRIORITY;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.TEST_SERVICE_TASK_PRIORITY;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.TEST_STRING_API;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.TEST_STRING_XML;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.TEST_TASK_EVENT_API;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.TEST_TASK_EVENT_XML;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.TEST_TYPE_API;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.TEST_TYPE_XML;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.TEST_USERS_API;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.TEST_USERS_LIST_API;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.TEST_USERS_LIST_XML;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.TEST_USERS_XML;
import static org.camunda.bpm.model.bpmn.BpmnTestConstants.USER_TASK_ID;
import static org.camunda.bpm.model.bpmn.impl.BpmnModelConstants.ACTIVITI_NS;
import static org.camunda.bpm.model.bpmn.impl.BpmnModelConstants.CAMUNDA_ATTRIBUTE_ERROR_CODE_VARIABLE;
import static org.camunda.bpm.model.bpmn.impl.BpmnModelConstants.CAMUNDA_ATTRIBUTE_ERROR_MESSAGE_VARIABLE;
import static org.camunda.bpm.model.bpmn.impl.BpmnModelConstants.CAMUNDA_NS;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.camunda.bpm.model.bpmn.instance.BaseElement;
import org.camunda.bpm.model.bpmn.instance.BpmnModelElementInstance;
import org.camunda.bpm.model.bpmn.instance.BusinessRuleTask;
import org.camunda.bpm.model.bpmn.instance.CallActivity;
import org.camunda.bpm.model.bpmn.instance.EndEvent;
import org.camunda.bpm.model.bpmn.instance.Error;
import org.camunda.bpm.model.bpmn.instance.ErrorEventDefinition;
import org.camunda.bpm.model.bpmn.instance.Expression;
import org.camunda.bpm.model.bpmn.instance.MessageEventDefinition;
import org.camunda.bpm.model.bpmn.instance.ParallelGateway;
import org.camunda.bpm.model.bpmn.instance.Process;
import org.camunda.bpm.model.bpmn.instance.ScriptTask;
import org.camunda.bpm.model.bpmn.instance.SendTask;
import org.camunda.bpm.model.bpmn.instance.SequenceFlow;
import org.camunda.bpm.model.bpmn.instance.ServiceTask;
import org.camunda.bpm.model.bpmn.instance.StartEvent;
import org.camunda.bpm.model.bpmn.instance.TimerEventDefinition;
import org.camunda.bpm.model.bpmn.instance.UserTask;
import org.camunda.bpm.model.bpmn.instance.camunda.CamundaConnector;
import org.camunda.bpm.model.bpmn.instance.camunda.CamundaConnectorId;
import org.camunda.bpm.model.bpmn.instance.camunda.CamundaConstraint;
import org.camunda.bpm.model.bpmn.instance.camunda.CamundaEntry;
import org.camunda.bpm.model.bpmn.instance.camunda.CamundaExecutionListener;
import org.camunda.bpm.model.bpmn.instance.camunda.CamundaFailedJobRetryTimeCycle;
import org.camunda.bpm.model.bpmn.instance.camunda.CamundaField;
import org.camunda.bpm.model.bpmn.instance.camunda.CamundaFormData;
import org.camunda.bpm.model.bpmn.instance.camunda.CamundaFormField;
import org.camunda.bpm.model.bpmn.instance.camunda.CamundaFormProperty;
import org.camunda.bpm.model.bpmn.instance.camunda.CamundaIn;
import org.camunda.bpm.model.bpmn.instance.camunda.CamundaInputOutput;
import org.camunda.bpm.model.bpmn.instance.camunda.CamundaInputParameter;
import org.camunda.bpm.model.bpmn.instance.camunda.CamundaList;
import org.camunda.bpm.model.bpmn.instance.camunda.CamundaMap;
import org.camunda.bpm.model.bpmn.instance.camunda.CamundaOut;
import org.camunda.bpm.model.bpmn.instance.camunda.CamundaOutputParameter;
import org.camunda.bpm.model.bpmn.instance.camunda.CamundaPotentialStarter;
import org.camunda.bpm.model.bpmn.instance.camunda.CamundaProperties;
import org.camunda.bpm.model.bpmn.instance.camunda.CamundaProperty;
import org.camunda.bpm.model.bpmn.instance.camunda.CamundaScript;
import org.camunda.bpm.model.bpmn.instance.camunda.CamundaTaskListener;
import org.camunda.bpm.model.bpmn.instance.camunda.CamundaValue;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
/**
* @author Sebastian Menski
* @author Ronny Bräunlich
*/
@RunWith(Parameterized.class)
public class CamundaExtensionsTest {
private Process process;
private StartEvent startEvent;
private SequenceFlow sequenceFlow;
private UserTask userTask;
private ServiceTask serviceTask;
private SendTask sendTask;
private ScriptTask scriptTask;
private CallActivity callActivity;
private BusinessRuleTask businessRuleTask;
private EndEvent endEvent;
private MessageEventDefinition messageEventDefinition;
private ParallelGateway parallelGateway;
private String namespace;
private BpmnModelInstance originalModelInstance;
private BpmnModelInstance modelInstance;
private Error error;
@Parameters(name="Namespace: {0}")
public static Collection<Object[]> parameters(){
return Arrays.asList(new Object[][]{
{CAMUNDA_NS, Bpmn.readModelFromStream(CamundaExtensionsTest.class.getResourceAsStream("CamundaExtensionsTest.xml"))},
//for compatability reasons we gotta check the old namespace, too
{ACTIVITI_NS, Bpmn.readModelFromStream(CamundaExtensionsTest.class.getResourceAsStream("CamundaExtensionsCompatabilityTest.xml"))}
});
}
public CamundaExtensionsTest(String namespace, BpmnModelInstance modelInstance) {
this.namespace = namespace;
this.originalModelInstance = modelInstance;
}
@Before
public void setUp(){
modelInstance = originalModelInstance.clone();
process = modelInstance.getModelElementById(PROCESS_ID);
startEvent = modelInstance.getModelElementById(START_EVENT_ID);
sequenceFlow = modelInstance.getModelElementById(SEQUENCE_FLOW_ID);
userTask = modelInstance.getModelElementById(USER_TASK_ID);
serviceTask = modelInstance.getModelElementById(SERVICE_TASK_ID);
sendTask = modelInstance.getModelElementById(SEND_TASK_ID);
scriptTask = modelInstance.getModelElementById(SCRIPT_TASK_ID);
callActivity = modelInstance.getModelElementById(CALL_ACTIVITY_ID);
businessRuleTask = modelInstance.getModelElementById(BUSINESS_RULE_TASK);
endEvent = modelInstance.getModelElementById(END_EVENT_ID);
messageEventDefinition = (MessageEventDefinition) endEvent.getEventDefinitions().iterator().next();
parallelGateway = modelInstance.getModelElementById("parallelGateway");
error = modelInstance.getModelElementById("error");
}
@Test
public void testAssignee() {
assertThat(userTask.getCamundaAssignee()).isEqualTo(TEST_STRING_XML);
userTask.setCamundaAssignee(TEST_STRING_API);
assertThat(userTask.getCamundaAssignee()).isEqualTo(TEST_STRING_API);
}
@Test
public void testAsync() {
assertThat(startEvent.isCamundaAsync()).isFalse();
assertThat(userTask.isCamundaAsync()).isTrue();
assertThat(parallelGateway.isCamundaAsync()).isTrue();
startEvent.setCamundaAsync(true);
userTask.setCamundaAsync(false);
parallelGateway.setCamundaAsync(false);
assertThat(startEvent.isCamundaAsync()).isTrue();
assertThat(userTask.isCamundaAsync()).isFalse();
assertThat(parallelGateway.isCamundaAsync()).isFalse();
}
@Test
public void testAsyncBefore() {
assertThat(startEvent.isCamundaAsyncBefore()).isTrue();
assertThat(endEvent.isCamundaAsyncBefore()).isTrue();
assertThat(userTask.isCamundaAsyncBefore()).isTrue();
assertThat(parallelGateway.isCamundaAsyncBefore()).isTrue();
startEvent.setCamundaAsyncBefore(false);
endEvent.setCamundaAsyncBefore(false);
userTask.setCamundaAsyncBefore(false);
parallelGateway.setCamundaAsyncBefore(false);
assertThat(startEvent.isCamundaAsyncBefore()).isFalse();
assertThat(endEvent.isCamundaAsyncBefore()).isFalse();
assertThat(userTask.isCamundaAsyncBefore()).isFalse();
assertThat(parallelGateway.isCamundaAsyncBefore()).isFalse();
}
@Test
public void testAsyncAfter() {
assertThat(startEvent.isCamundaAsyncAfter()).isTrue();
assertThat(endEvent.isCamundaAsyncAfter()).isTrue();
assertThat(userTask.isCamundaAsyncAfter()).isTrue();
assertThat(parallelGateway.isCamundaAsyncAfter()).isTrue();
startEvent.setCamundaAsyncAfter(false);
endEvent.setCamundaAsyncAfter(false);
userTask.setCamundaAsyncAfter(false);
parallelGateway.setCamundaAsyncAfter(false);
assertThat(startEvent.isCamundaAsyncAfter()).isFalse();
assertThat(endEvent.isCamundaAsyncAfter()).isFalse();
assertThat(userTask.isCamundaAsyncAfter()).isFalse();
assertThat(parallelGateway.isCamundaAsyncAfter()).isFalse();
}
@Test
public void testFlowNodeJobPriority() {
assertThat(startEvent.getCamundaJobPriority()).isEqualTo(TEST_FLOW_NODE_JOB_PRIORITY);
assertThat(endEvent.getCamundaJobPriority()).isEqualTo(TEST_FLOW_NODE_JOB_PRIORITY);
assertThat(userTask.getCamundaJobPriority()).isEqualTo(TEST_FLOW_NODE_JOB_PRIORITY);
assertThat(parallelGateway.getCamundaJobPriority()).isEqualTo(TEST_FLOW_NODE_JOB_PRIORITY);
}
@Test
public void testProcessJobPriority() {
assertThat(process.getCamundaJobPriority()).isEqualTo(TEST_PROCESS_JOB_PRIORITY);
}
@Test
public void testProcessTaskPriority() {
assertThat(process.getCamundaTaskPriority()).isEqualTo(TEST_PROCESS_TASK_PRIORITY);
}
@Test
public void testHistoryTimeToLive() {
assertThat(process.getCamundaHistoryTimeToLive()).isEqualTo(TEST_HISTORY_TIME_TO_LIVE);
}
@Test
public void testIsStartableInTasklist() {
assertThat(process.isCamundaStartableInTasklist()).isEqualTo(false);
}
@Test
public void testVersionTag() {
assertThat(process.getCamundaVersionTag()).isEqualTo("v1.0.0");
}
@Test
public void testServiceTaskPriority() {
assertThat(serviceTask.getCamundaTaskPriority()).isEqualTo(TEST_SERVICE_TASK_PRIORITY);
}
@Test
public void testCalledElementBinding() {
assertThat(callActivity.getCamundaCalledElementBinding()).isEqualTo(TEST_STRING_XML);
callActivity.setCamundaCalledElementBinding(TEST_STRING_API);
assertThat(callActivity.getCamundaCalledElementBinding()).isEqualTo(TEST_STRING_API);
}
@Test
public void testCalledElementVersion() {
assertThat(callActivity.getCamundaCalledElementVersion()).isEqualTo(TEST_STRING_XML);
callActivity.setCamundaCalledElementVersion(TEST_STRING_API);
assertThat(callActivity.getCamundaCalledElementVersion()).isEqualTo(TEST_STRING_API);
}
@Test
public void testCalledElementVersionTag() {
assertThat(callActivity.getCamundaCalledElementVersionTag()).isEqualTo(TEST_STRING_XML);
callActivity.setCamundaCalledElementVersionTag(TEST_STRING_API);
assertThat(callActivity.getCamundaCalledElementVersionTag()).isEqualTo(TEST_STRING_API);
}
@Test
public void testCalledElementTenantId() {
assertThat(callActivity.getCamundaCalledElementTenantId()).isEqualTo(TEST_STRING_XML);
callActivity.setCamundaCalledElementTenantId(TEST_STRING_API);
assertThat(callActivity.getCamundaCalledElementTenantId()).isEqualTo(TEST_STRING_API);
}
@Test
public void testCaseRef() {
assertThat(callActivity.getCamundaCaseRef()).isEqualTo(TEST_STRING_XML);
callActivity.setCamundaCaseRef(TEST_STRING_API);
assertThat(callActivity.getCamundaCaseRef()).isEqualTo(TEST_STRING_API);
}
@Test
public void testCaseBinding() {
assertThat(callActivity.getCamundaCaseBinding()).isEqualTo(TEST_STRING_XML);
callActivity.setCamundaCaseBinding(TEST_STRING_API);
assertThat(callActivity.getCamundaCaseBinding()).isEqualTo(TEST_STRING_API);
}
@Test
public void testCaseVersion() {
assertThat(callActivity.getCamundaCaseVersion()).isEqualTo(TEST_STRING_XML);
callActivity.setCamundaCaseVersion(TEST_STRING_API);
assertThat(callActivity.getCamundaCaseVersion()).isEqualTo(TEST_STRING_API);
}
@Test
public void testCaseTenantId() {
assertThat(callActivity.getCamundaCaseTenantId()).isEqualTo(TEST_STRING_XML);
callActivity.setCamundaCaseTenantId(TEST_STRING_API);
assertThat(callActivity.getCamundaCaseTenantId()).isEqualTo(TEST_STRING_API);
}
@Test
public void testDecisionRef() {
assertThat(businessRuleTask.getCamundaDecisionRef()).isEqualTo(TEST_STRING_XML);
businessRuleTask.setCamundaDecisionRef(TEST_STRING_API);
assertThat(businessRuleTask.getCamundaDecisionRef()).isEqualTo(TEST_STRING_API);
}
@Test
public void testDecisionRefBinding() {
assertThat(businessRuleTask.getCamundaDecisionRefBinding()).isEqualTo(TEST_STRING_XML);
businessRuleTask.setCamundaDecisionRefBinding(TEST_STRING_API);
assertThat(businessRuleTask.getCamundaDecisionRefBinding()).isEqualTo(TEST_STRING_API);
}
@Test
public void testDecisionRefVersion() {
assertThat(businessRuleTask.getCamundaDecisionRefVersion()).isEqualTo(TEST_STRING_XML);
businessRuleTask.setCamundaDecisionRefVersion(TEST_STRING_API);
assertThat(businessRuleTask.getCamundaDecisionRefVersion()).isEqualTo(TEST_STRING_API);
}
@Test
public void testDecisionRefVersionTag() {
assertThat(businessRuleTask.getCamundaDecisionRefVersionTag()).isEqualTo(TEST_STRING_XML);
businessRuleTask.setCamundaDecisionRefVersionTag(TEST_STRING_API);
assertThat(businessRuleTask.getCamundaDecisionRefVersionTag()).isEqualTo(TEST_STRING_API);
}
@Test
public void testDecisionRefTenantId() {
assertThat(businessRuleTask.getCamundaDecisionRefTenantId()).isEqualTo(TEST_STRING_XML);
businessRuleTask.setCamundaDecisionRefTenantId(TEST_STRING_API);
assertThat(businessRuleTask.getCamundaDecisionRefTenantId()).isEqualTo(TEST_STRING_API);
}
@Test
public void testMapDecisionResult() {
assertThat(businessRuleTask.getCamundaMapDecisionResult()).isEqualTo(TEST_STRING_XML);
businessRuleTask.setCamundaMapDecisionResult(TEST_STRING_API);
assertThat(businessRuleTask.getCamundaMapDecisionResult()).isEqualTo(TEST_STRING_API);
}
@Test
public void testTaskPriority() {
assertThat(businessRuleTask.getCamundaTaskPriority()).isEqualTo(TEST_STRING_XML);
businessRuleTask.setCamundaTaskPriority(TEST_SERVICE_TASK_PRIORITY);
assertThat(businessRuleTask.getCamundaTaskPriority()).isEqualTo(TEST_SERVICE_TASK_PRIORITY);
}
@Test
public void testCandidateGroups() {
assertThat(userTask.getCamundaCandidateGroups()).isEqualTo(TEST_GROUPS_XML);
assertThat(userTask.getCamundaCandidateGroupsList()).containsAll(TEST_GROUPS_LIST_XML);
userTask.setCamundaCandidateGroups(TEST_GROUPS_API);
assertThat(userTask.getCamundaCandidateGroups()).isEqualTo(TEST_GROUPS_API);
assertThat(userTask.getCamundaCandidateGroupsList()).containsAll(TEST_GROUPS_LIST_API);
userTask.setCamundaCandidateGroupsList(TEST_GROUPS_LIST_XML);
assertThat(userTask.getCamundaCandidateGroups()).isEqualTo(TEST_GROUPS_XML);
assertThat(userTask.getCamundaCandidateGroupsList()).containsAll(TEST_GROUPS_LIST_XML);
}
@Test
public void testCandidateStarterGroups() {
assertThat(process.getCamundaCandidateStarterGroups()).isEqualTo(TEST_GROUPS_XML);
assertThat(process.getCamundaCandidateStarterGroupsList()).containsAll(TEST_GROUPS_LIST_XML);
process.setCamundaCandidateStarterGroups(TEST_GROUPS_API);
assertThat(process.getCamundaCandidateStarterGroups()).isEqualTo(TEST_GROUPS_API);
assertThat(process.getCamundaCandidateStarterGroupsList()).containsAll(TEST_GROUPS_LIST_API);
process.setCamundaCandidateStarterGroupsList(TEST_GROUPS_LIST_XML);
assertThat(process.getCamundaCandidateStarterGroups()).isEqualTo(TEST_GROUPS_XML);
assertThat(process.getCamundaCandidateStarterGroupsList()).containsAll(TEST_GROUPS_LIST_XML);
}
@Test
public void testCandidateStarterUsers() {
assertThat(process.getCamundaCandidateStarterUsers()).isEqualTo(TEST_USERS_XML);
assertThat(process.getCamundaCandidateStarterUsersList()).containsAll(TEST_USERS_LIST_XML);
process.setCamundaCandidateStarterUsers(TEST_USERS_API);
assertThat(process.getCamundaCandidateStarterUsers()).isEqualTo(TEST_USERS_API);
assertThat(process.getCamundaCandidateStarterUsersList()).containsAll(TEST_USERS_LIST_API);
process.setCamundaCandidateStarterUsersList(TEST_USERS_LIST_XML);
assertThat(process.getCamundaCandidateStarterUsers()).isEqualTo(TEST_USERS_XML);
assertThat(process.getCamundaCandidateStarterUsersList()).containsAll(TEST_USERS_LIST_XML);
}
@Test
public void testCandidateUsers() {
assertThat(userTask.getCamundaCandidateUsers()).isEqualTo(TEST_USERS_XML);
assertThat(userTask.getCamundaCandidateUsersList()).containsAll(TEST_USERS_LIST_XML);
userTask.setCamundaCandidateUsers(TEST_USERS_API);
assertThat(userTask.getCamundaCandidateUsers()).isEqualTo(TEST_USERS_API);
assertThat(userTask.getCamundaCandidateUsersList()).containsAll(TEST_USERS_LIST_API);
userTask.setCamundaCandidateUsersList(TEST_USERS_LIST_XML);
assertThat(userTask.getCamundaCandidateUsers()).isEqualTo(TEST_USERS_XML);
assertThat(userTask.getCamundaCandidateUsersList()).containsAll(TEST_USERS_LIST_XML);
}
@Test
public void testClass() {
assertThat(serviceTask.getCamundaClass()).isEqualTo(TEST_CLASS_XML);
assertThat(messageEventDefinition.getCamundaClass()).isEqualTo(TEST_CLASS_XML);
serviceTask.setCamundaClass(TEST_CLASS_API);
messageEventDefinition.setCamundaClass(TEST_CLASS_API);
assertThat(serviceTask.getCamundaClass()).isEqualTo(TEST_CLASS_API);
assertThat(messageEventDefinition.getCamundaClass()).isEqualTo(TEST_CLASS_API);
}
@Test
public void testDelegateExpression() {
assertThat(serviceTask.getCamundaDelegateExpression()).isEqualTo(TEST_DELEGATE_EXPRESSION_XML);
assertThat(messageEventDefinition.getCamundaDelegateExpression()).isEqualTo(TEST_DELEGATE_EXPRESSION_XML);
serviceTask.setCamundaDelegateExpression(TEST_DELEGATE_EXPRESSION_API);
messageEventDefinition.setCamundaDelegateExpression(TEST_DELEGATE_EXPRESSION_API);
assertThat(serviceTask.getCamundaDelegateExpression()).isEqualTo(TEST_DELEGATE_EXPRESSION_API);
assertThat(messageEventDefinition.getCamundaDelegateExpression()).isEqualTo(TEST_DELEGATE_EXPRESSION_API);
}
@Test
public void testDueDate() {
assertThat(userTask.getCamundaDueDate()).isEqualTo(TEST_DUE_DATE_XML);
userTask.setCamundaDueDate(TEST_DUE_DATE_API);
assertThat(userTask.getCamundaDueDate()).isEqualTo(TEST_DUE_DATE_API);
}
@Test
public void testErrorCodeVariable(){
ErrorEventDefinition errorEventDefinition = startEvent.getChildElementsByType(ErrorEventDefinition.class).iterator().next();
assertThat(errorEventDefinition.getAttributeValueNs(namespace, CAMUNDA_ATTRIBUTE_ERROR_CODE_VARIABLE)).isEqualTo("errorVariable");
}
@Test
public void testErrorMessageVariable(){
ErrorEventDefinition errorEventDefinition = startEvent.getChildElementsByType(ErrorEventDefinition.class).iterator().next();
assertThat(errorEventDefinition.getAttributeValueNs(namespace, CAMUNDA_ATTRIBUTE_ERROR_MESSAGE_VARIABLE)).isEqualTo("errorMessageVariable");
}
@Test
public void testErrorMessage() {
assertThat(error.getCamundaErrorMessage()).isEqualTo(TEST_STRING_XML);
error.setCamundaErrorMessage(TEST_STRING_API);
assertThat(error.getCamundaErrorMessage()).isEqualTo(TEST_STRING_API);
}
@Test
public void testExclusive() {
assertThat(startEvent.isCamundaExclusive()).isTrue();
assertThat(userTask.isCamundaExclusive()).isFalse();
userTask.setCamundaExclusive(true);
assertThat(userTask.isCamundaExclusive()).isTrue();
assertThat(parallelGateway.isCamundaExclusive()).isTrue();
parallelGateway.setCamundaExclusive(false);
assertThat(parallelGateway.isCamundaExclusive()).isFalse();
assertThat(callActivity.isCamundaExclusive()).isFalse();
callActivity.setCamundaExclusive(true);
assertThat(callActivity.isCamundaExclusive()).isTrue();
}
@Test
public void testExpression() {
assertThat(serviceTask.getCamundaExpression()).isEqualTo(TEST_EXPRESSION_XML);
assertThat(messageEventDefinition.getCamundaExpression()).isEqualTo(TEST_EXPRESSION_XML);
serviceTask.setCamundaExpression(TEST_EXPRESSION_API);
messageEventDefinition.setCamundaExpression(TEST_EXPRESSION_API);
assertThat(serviceTask.getCamundaExpression()).isEqualTo(TEST_EXPRESSION_API);
assertThat(messageEventDefinition.getCamundaExpression()).isEqualTo(TEST_EXPRESSION_API);
}
@Test
public void testFormHandlerClass() {
assertThat(startEvent.getCamundaFormHandlerClass()).isEqualTo(TEST_CLASS_XML);
assertThat(userTask.getCamundaFormHandlerClass()).isEqualTo(TEST_CLASS_XML);
startEvent.setCamundaFormHandlerClass(TEST_CLASS_API);
userTask.setCamundaFormHandlerClass(TEST_CLASS_API);
assertThat(startEvent.getCamundaFormHandlerClass()).isEqualTo(TEST_CLASS_API);
assertThat(userTask.getCamundaFormHandlerClass()).isEqualTo(TEST_CLASS_API);
}
@Test
public void testFormKey() {
assertThat(startEvent.getCamundaFormKey()).isEqualTo(TEST_STRING_XML);
assertThat(userTask.getCamundaFormKey()).isEqualTo(TEST_STRING_XML);
startEvent.setCamundaFormKey(TEST_STRING_API);
userTask.setCamundaFormKey(TEST_STRING_API);
assertThat(startEvent.getCamundaFormKey()).isEqualTo(TEST_STRING_API);
assertThat(userTask.getCamundaFormKey()).isEqualTo(TEST_STRING_API);
}
@Test
public void testInitiator() {
assertThat(startEvent.getCamundaInitiator()).isEqualTo(TEST_STRING_XML);
startEvent.setCamundaInitiator(TEST_STRING_API);
assertThat(startEvent.getCamundaInitiator()).isEqualTo(TEST_STRING_API);
}
@Test
public void testPriority() {
assertThat(userTask.getCamundaPriority()).isEqualTo(TEST_PRIORITY_XML);
userTask.setCamundaPriority(TEST_PRIORITY_API);
assertThat(userTask.getCamundaPriority()).isEqualTo(TEST_PRIORITY_API);
}
@Test
public void testResultVariable() {
assertThat(serviceTask.getCamundaResultVariable()).isEqualTo(TEST_STRING_XML);
assertThat(messageEventDefinition.getCamundaResultVariable()).isEqualTo(TEST_STRING_XML);
serviceTask.setCamundaResultVariable(TEST_STRING_API);
messageEventDefinition.setCamundaResultVariable(TEST_STRING_API);
assertThat(serviceTask.getCamundaResultVariable()).isEqualTo(TEST_STRING_API);
assertThat(messageEventDefinition.getCamundaResultVariable()).isEqualTo(TEST_STRING_API);
}
@Test
public void testType() {
assertThat(serviceTask.getCamundaType()).isEqualTo(TEST_TYPE_XML);
assertThat(messageEventDefinition.getCamundaType()).isEqualTo(TEST_STRING_XML);
serviceTask.setCamundaType(TEST_TYPE_API);
messageEventDefinition.setCamundaType(TEST_STRING_API);
assertThat(serviceTask.getCamundaType()).isEqualTo(TEST_TYPE_API);
assertThat(messageEventDefinition.getCamundaType()).isEqualTo(TEST_STRING_API);
}
@Test
public void testTopic() {
assertThat(serviceTask.getCamundaTopic()).isEqualTo(TEST_STRING_XML);
assertThat(messageEventDefinition.getCamundaTopic()).isEqualTo(TEST_STRING_XML);
serviceTask.setCamundaTopic(TEST_TYPE_API);
messageEventDefinition.setCamundaTopic(TEST_STRING_API);
assertThat(serviceTask.getCamundaTopic()).isEqualTo(TEST_TYPE_API);
assertThat(messageEventDefinition.getCamundaTopic()).isEqualTo(TEST_STRING_API);
}
@Test
public void testVariableMappingClass() {
assertThat(callActivity.getCamundaVariableMappingClass()).isEqualTo(TEST_CLASS_XML);
callActivity.setCamundaVariableMappingClass(TEST_CLASS_API);
assertThat(callActivity.getCamundaVariableMappingClass()).isEqualTo(TEST_CLASS_API);
}
@Test
public void testVariableMappingDelegateExpression() {
assertThat(callActivity.getCamundaVariableMappingDelegateExpression()).isEqualTo(TEST_DELEGATE_EXPRESSION_XML);
callActivity.setCamundaVariableMappingDelegateExpression(TEST_DELEGATE_EXPRESSION_API);
assertThat(callActivity.getCamundaVariableMappingDelegateExpression()).isEqualTo(TEST_DELEGATE_EXPRESSION_API);
}
@Test
public void testExecutionListenerExtension() {
CamundaExecutionListener processListener = process.getExtensionElements().getElementsQuery().filterByType(CamundaExecutionListener.class).singleResult();
CamundaExecutionListener startEventListener = startEvent.getExtensionElements().getElementsQuery().filterByType(CamundaExecutionListener.class).singleResult();
CamundaExecutionListener serviceTaskListener = serviceTask.getExtensionElements().getElementsQuery().filterByType(CamundaExecutionListener.class).singleResult();
assertThat(processListener.getCamundaClass()).isEqualTo(TEST_CLASS_XML);
assertThat(processListener.getCamundaEvent()).isEqualTo(TEST_EXECUTION_EVENT_XML);
assertThat(startEventListener.getCamundaExpression()).isEqualTo(TEST_EXPRESSION_XML);
assertThat(startEventListener.getCamundaEvent()).isEqualTo(TEST_EXECUTION_EVENT_XML);
assertThat(serviceTaskListener.getCamundaDelegateExpression()).isEqualTo(TEST_DELEGATE_EXPRESSION_XML);
assertThat(serviceTaskListener.getCamundaEvent()).isEqualTo(TEST_EXECUTION_EVENT_XML);
processListener.setCamundaClass(TEST_CLASS_API);
processListener.setCamundaEvent(TEST_EXECUTION_EVENT_API);
startEventListener.setCamundaExpression(TEST_EXPRESSION_API);
startEventListener.setCamundaEvent(TEST_EXECUTION_EVENT_API);
serviceTaskListener.setCamundaDelegateExpression(TEST_DELEGATE_EXPRESSION_API);
serviceTaskListener.setCamundaEvent(TEST_EXECUTION_EVENT_API);
assertThat(processListener.getCamundaClass()).isEqualTo(TEST_CLASS_API);
assertThat(processListener.getCamundaEvent()).isEqualTo(TEST_EXECUTION_EVENT_API);
assertThat(startEventListener.getCamundaExpression()).isEqualTo(TEST_EXPRESSION_API);
assertThat(startEventListener.getCamundaEvent()).isEqualTo(TEST_EXECUTION_EVENT_API);
assertThat(serviceTaskListener.getCamundaDelegateExpression()).isEqualTo(TEST_DELEGATE_EXPRESSION_API);
assertThat(serviceTaskListener.getCamundaEvent()).isEqualTo(TEST_EXECUTION_EVENT_API);
}
@Test
public void testCamundaScriptExecutionListener() {
CamundaExecutionListener sequenceFlowListener = sequenceFlow.getExtensionElements().getElementsQuery().filterByType(CamundaExecutionListener.class).singleResult();
CamundaScript script = sequenceFlowListener.getCamundaScript();
assertThat(script.getCamundaScriptFormat()).isEqualTo("groovy");
assertThat(script.getCamundaResource()).isNull();
assertThat(script.getTextContent()).isEqualTo("println 'Hello World'");
CamundaScript newScript = modelInstance.newInstance(CamundaScript.class);
newScript.setCamundaScriptFormat("groovy");
newScript.setCamundaResource("test.groovy");
sequenceFlowListener.setCamundaScript(newScript);
script = sequenceFlowListener.getCamundaScript();
assertThat(script.getCamundaScriptFormat()).isEqualTo("groovy");
assertThat(script.getCamundaResource()).isEqualTo("test.groovy");
assertThat(script.getTextContent()).isEmpty();
}
@Test
public void testFailedJobRetryTimeCycleExtension() {
CamundaFailedJobRetryTimeCycle timeCycle = sendTask.getExtensionElements().getElementsQuery().filterByType(CamundaFailedJobRetryTimeCycle.class).singleResult();
assertThat(timeCycle.getTextContent()).isEqualTo(TEST_STRING_XML);
timeCycle.setTextContent(TEST_STRING_API);
assertThat(timeCycle.getTextContent()).isEqualTo(TEST_STRING_API);
}
@Test
public void testFieldExtension() {
CamundaField field = sendTask.getExtensionElements().getElementsQuery().filterByType(CamundaField.class).singleResult();
assertThat(field.getCamundaName()).isEqualTo(TEST_STRING_XML);
assertThat(field.getCamundaExpression()).isEqualTo(TEST_EXPRESSION_XML);
assertThat(field.getCamundaStringValue()).isEqualTo(TEST_STRING_XML);
assertThat(field.getCamundaExpressionChild().getTextContent()).isEqualTo(TEST_EXPRESSION_XML);
assertThat(field.getCamundaString().getTextContent()).isEqualTo(TEST_STRING_XML);
field.setCamundaName(TEST_STRING_API);
field.setCamundaExpression(TEST_EXPRESSION_API);
field.setCamundaStringValue(TEST_STRING_API);
field.getCamundaExpressionChild().setTextContent(TEST_EXPRESSION_API);
field.getCamundaString().setTextContent(TEST_STRING_API);
assertThat(field.getCamundaName()).isEqualTo(TEST_STRING_API);
assertThat(field.getCamundaExpression()).isEqualTo(TEST_EXPRESSION_API);
assertThat(field.getCamundaStringValue()).isEqualTo(TEST_STRING_API);
assertThat(field.getCamundaExpressionChild().getTextContent()).isEqualTo(TEST_EXPRESSION_API);
assertThat(field.getCamundaString().getTextContent()).isEqualTo(TEST_STRING_API);
}
@Test
public void testFormData() {
CamundaFormData formData = userTask.getExtensionElements().getElementsQuery().filterByType(CamundaFormData.class).singleResult();
CamundaFormField formField = formData.getCamundaFormFields().iterator().next();
assertThat(formField.getCamundaId()).isEqualTo(TEST_STRING_XML);
assertThat(formField.getCamundaLabel()).isEqualTo(TEST_STRING_XML);
assertThat(formField.getCamundaType()).isEqualTo(TEST_STRING_XML);
assertThat(formField.getCamundaDatePattern()).isEqualTo(TEST_STRING_XML);
assertThat(formField.getCamundaDefaultValue()).isEqualTo(TEST_STRING_XML);
formField.setCamundaId(TEST_STRING_API);
formField.setCamundaLabel(TEST_STRING_API);
formField.setCamundaType(TEST_STRING_API);
formField.setCamundaDatePattern(TEST_STRING_API);
formField.setCamundaDefaultValue(TEST_STRING_API);
assertThat(formField.getCamundaId()).isEqualTo(TEST_STRING_API);
assertThat(formField.getCamundaLabel()).isEqualTo(TEST_STRING_API);
assertThat(formField.getCamundaType()).isEqualTo(TEST_STRING_API);
assertThat(formField.getCamundaDatePattern()).isEqualTo(TEST_STRING_API);
assertThat(formField.getCamundaDefaultValue()).isEqualTo(TEST_STRING_API);
CamundaProperty property = formField.getCamundaProperties().getCamundaProperties().iterator().next();
assertThat(property.getCamundaId()).isEqualTo(TEST_STRING_XML);
assertThat(property.getCamundaValue()).isEqualTo(TEST_STRING_XML);
property.setCamundaId(TEST_STRING_API);
property.setCamundaValue(TEST_STRING_API);
assertThat(property.getCamundaId()).isEqualTo(TEST_STRING_API);
assertThat(property.getCamundaValue()).isEqualTo(TEST_STRING_API);
CamundaConstraint constraint = formField.getCamundaValidation().getCamundaConstraints().iterator().next();
assertThat(constraint.getCamundaName()).isEqualTo(TEST_STRING_XML);
assertThat(constraint.getCamundaConfig()).isEqualTo(TEST_STRING_XML);
constraint.setCamundaName(TEST_STRING_API);
constraint.setCamundaConfig(TEST_STRING_API);
assertThat(constraint.getCamundaName()).isEqualTo(TEST_STRING_API);
assertThat(constraint.getCamundaConfig()).isEqualTo(TEST_STRING_API);
CamundaValue value = formField.getCamundaValues().iterator().next();
assertThat(value.getCamundaId()).isEqualTo(TEST_STRING_XML);
assertThat(value.getCamundaName()).isEqualTo(TEST_STRING_XML);
value.setCamundaId(TEST_STRING_API);
value.setCamundaName(TEST_STRING_API);
assertThat(value.getCamundaId()).isEqualTo(TEST_STRING_API);
assertThat(value.getCamundaName()).isEqualTo(TEST_STRING_API);
}
@Test
public void testFormProperty() {
CamundaFormProperty formProperty = startEvent.getExtensionElements().getElementsQuery().filterByType(CamundaFormProperty.class).singleResult();
assertThat(formProperty.getCamundaId()).isEqualTo(TEST_STRING_XML);
assertThat(formProperty.getCamundaName()).isEqualTo(TEST_STRING_XML);
assertThat(formProperty.getCamundaType()).isEqualTo(TEST_STRING_XML);
assertThat(formProperty.isCamundaRequired()).isFalse();
assertThat(formProperty.isCamundaReadable()).isTrue();
assertThat(formProperty.isCamundaWriteable()).isTrue();
assertThat(formProperty.getCamundaVariable()).isEqualTo(TEST_STRING_XML);
assertThat(formProperty.getCamundaExpression()).isEqualTo(TEST_EXPRESSION_XML);
assertThat(formProperty.getCamundaDatePattern()).isEqualTo(TEST_STRING_XML);
assertThat(formProperty.getCamundaDefault()).isEqualTo(TEST_STRING_XML);
formProperty.setCamundaId(TEST_STRING_API);
formProperty.setCamundaName(TEST_STRING_API);
formProperty.setCamundaType(TEST_STRING_API);
formProperty.setCamundaRequired(true);
formProperty.setCamundaReadable(false);
formProperty.setCamundaWriteable(false);
formProperty.setCamundaVariable(TEST_STRING_API);
formProperty.setCamundaExpression(TEST_EXPRESSION_API);
formProperty.setCamundaDatePattern(TEST_STRING_API);
formProperty.setCamundaDefault(TEST_STRING_API);
assertThat(formProperty.getCamundaId()).isEqualTo(TEST_STRING_API);
assertThat(formProperty.getCamundaName()).isEqualTo(TEST_STRING_API);
assertThat(formProperty.getCamundaType()).isEqualTo(TEST_STRING_API);
assertThat(formProperty.isCamundaRequired()).isTrue();
assertThat(formProperty.isCamundaReadable()).isFalse();
assertThat(formProperty.isCamundaWriteable()).isFalse();
assertThat(formProperty.getCamundaVariable()).isEqualTo(TEST_STRING_API);
assertThat(formProperty.getCamundaExpression()).isEqualTo(TEST_EXPRESSION_API);
assertThat(formProperty.getCamundaDatePattern()).isEqualTo(TEST_STRING_API);
assertThat(formProperty.getCamundaDefault()).isEqualTo(TEST_STRING_API);
}
@Test
public void testInExtension() {
CamundaIn in = callActivity.getExtensionElements().getElementsQuery().filterByType(CamundaIn.class).singleResult();
assertThat(in.getCamundaSource()).isEqualTo(TEST_STRING_XML);
assertThat(in.getCamundaSourceExpression()).isEqualTo(TEST_EXPRESSION_XML);
assertThat(in.getCamundaVariables()).isEqualTo(TEST_STRING_XML);
assertThat(in.getCamundaTarget()).isEqualTo(TEST_STRING_XML);
assertThat(in.getCamundaBusinessKey()).isEqualTo(TEST_EXPRESSION_XML);
assertThat(in.getCamundaLocal()).isTrue();
in.setCamundaSource(TEST_STRING_API);
in.setCamundaSourceExpression(TEST_EXPRESSION_API);
in.setCamundaVariables(TEST_STRING_API);
in.setCamundaTarget(TEST_STRING_API);
in.setCamundaBusinessKey(TEST_EXPRESSION_API);
in.setCamundaLocal(false);
assertThat(in.getCamundaSource()).isEqualTo(TEST_STRING_API);
assertThat(in.getCamundaSourceExpression()).isEqualTo(TEST_EXPRESSION_API);
assertThat(in.getCamundaVariables()).isEqualTo(TEST_STRING_API);
assertThat(in.getCamundaTarget()).isEqualTo(TEST_STRING_API);
assertThat(in.getCamundaBusinessKey()).isEqualTo(TEST_EXPRESSION_API);
assertThat(in.getCamundaLocal()).isFalse();
}
@Test
public void testOutExtension() {
CamundaOut out = callActivity.getExtensionElements().getElementsQuery().filterByType(CamundaOut.class).singleResult();
assertThat(out.getCamundaSource()).isEqualTo(TEST_STRING_XML);
assertThat(out.getCamundaSourceExpression()).isEqualTo(TEST_EXPRESSION_XML);
assertThat(out.getCamundaVariables()).isEqualTo(TEST_STRING_XML);
assertThat(out.getCamundaTarget()).isEqualTo(TEST_STRING_XML);
assertThat(out.getCamundaLocal()).isTrue();
out.setCamundaSource(TEST_STRING_API);
out.setCamundaSourceExpression(TEST_EXPRESSION_API);
out.setCamundaVariables(TEST_STRING_API);
out.setCamundaTarget(TEST_STRING_API);
out.setCamundaLocal(false);
assertThat(out.getCamundaSource()).isEqualTo(TEST_STRING_API);
assertThat(out.getCamundaSourceExpression()).isEqualTo(TEST_EXPRESSION_API);
assertThat(out.getCamundaVariables()).isEqualTo(TEST_STRING_API);
assertThat(out.getCamundaTarget()).isEqualTo(TEST_STRING_API);
assertThat(out.getCamundaLocal()).isFalse();
}
@Test
public void testPotentialStarter() {
CamundaPotentialStarter potentialStarter = startEvent.getExtensionElements().getElementsQuery().filterByType(CamundaPotentialStarter.class).singleResult();
Expression expression = potentialStarter.getResourceAssignmentExpression().getExpression();
assertThat(expression.getTextContent()).isEqualTo(TEST_GROUPS_XML);
expression.setTextContent(TEST_GROUPS_API);
assertThat(expression.getTextContent()).isEqualTo(TEST_GROUPS_API);
}
@Test
public void testTaskListener() {
CamundaTaskListener taskListener = userTask.getExtensionElements().getElementsQuery().filterByType(CamundaTaskListener.class).list().get(0);
assertThat(taskListener.getCamundaEvent()).isEqualTo(TEST_TASK_EVENT_XML);
assertThat(taskListener.getCamundaClass()).isEqualTo(TEST_CLASS_XML);
assertThat(taskListener.getCamundaExpression()).isEqualTo(TEST_EXPRESSION_XML);
assertThat(taskListener.getCamundaDelegateExpression()).isEqualTo(TEST_DELEGATE_EXPRESSION_XML);
taskListener.setCamundaEvent(TEST_TASK_EVENT_API);
taskListener.setCamundaClass(TEST_CLASS_API);
taskListener.setCamundaExpression(TEST_EXPRESSION_API);
taskListener.setCamundaDelegateExpression(TEST_DELEGATE_EXPRESSION_API);
assertThat(taskListener.getCamundaEvent()).isEqualTo(TEST_TASK_EVENT_API);
assertThat(taskListener.getCamundaClass()).isEqualTo(TEST_CLASS_API);
assertThat(taskListener.getCamundaExpression()).isEqualTo(TEST_EXPRESSION_API);
assertThat(taskListener.getCamundaDelegateExpression()).isEqualTo(TEST_DELEGATE_EXPRESSION_API);
CamundaField field = taskListener.getCamundaFields().iterator().next();
assertThat(field.getCamundaName()).isEqualTo(TEST_STRING_XML);
assertThat(field.getCamundaString().getTextContent()).isEqualTo(TEST_STRING_XML);
Collection<TimerEventDefinition> timeouts = taskListener.getTimeouts();
assertThat(timeouts.size()).isEqualTo(1);
TimerEventDefinition timeout = timeouts.iterator().next();
assertThat(timeout.getTimeCycle()).isNull();
assertThat(timeout.getTimeDate()).isNull();
assertThat(timeout.getTimeDuration()).isNotNull();
assertThat(timeout.getTimeDuration().getRawTextContent()).isEqualTo("PT1H");
}
@Test
public void testCamundaScriptTaskListener() {
CamundaTaskListener taskListener = userTask.getExtensionElements().getElementsQuery().filterByType(CamundaTaskListener.class).list().get(1);
CamundaScript script = taskListener.getCamundaScript();
assertThat(script.getCamundaScriptFormat()).isEqualTo("groovy");
assertThat(script.getCamundaResource()).isEqualTo("test.groovy");
assertThat(script.getTextContent()).isEmpty();
CamundaScript newScript = modelInstance.newInstance(CamundaScript.class);
newScript.setCamundaScriptFormat("groovy");
newScript.setTextContent("println 'Hello World'");
taskListener.setCamundaScript(newScript);
script = taskListener.getCamundaScript();
assertThat(script.getCamundaScriptFormat()).isEqualTo("groovy");
assertThat(script.getCamundaResource()).isNull();
assertThat(script.getTextContent()).isEqualTo("println 'Hello World'");
}
@Test
public void testCamundaModelerProperties() {
CamundaProperties camundaProperties = endEvent.getExtensionElements().getElementsQuery().filterByType(CamundaProperties.class).singleResult();
assertThat(camundaProperties).isNotNull();
assertThat(camundaProperties.getCamundaProperties()).hasSize(2);
for (CamundaProperty camundaProperty : camundaProperties.getCamundaProperties()) {
assertThat(camundaProperty.getCamundaId()).isNull();
assertThat(camundaProperty.getCamundaName()).startsWith("name");
assertThat(camundaProperty.getCamundaValue()).startsWith("value");
}
}
@Test
public void testGetNonExistingCamundaCandidateUsers() {
userTask.removeAttributeNs(namespace, "candidateUsers");
assertThat(userTask.getCamundaCandidateUsers()).isNull();
assertThat(userTask.getCamundaCandidateUsersList()).isEmpty();
}
@Test
public void testSetNullCamundaCandidateUsers() {
assertThat(userTask.getCamundaCandidateUsers()).isNotEmpty();
assertThat(userTask.getCamundaCandidateUsersList()).isNotEmpty();
userTask.setCamundaCandidateUsers(null);
assertThat(userTask.getCamundaCandidateUsers()).isNull();
assertThat(userTask.getCamundaCandidateUsersList()).isEmpty();
}
@Test
public void testEmptyCamundaCandidateUsers() {
assertThat(userTask.getCamundaCandidateUsers()).isNotEmpty();
assertThat(userTask.getCamundaCandidateUsersList()).isNotEmpty();
userTask.setCamundaCandidateUsers("");
assertThat(userTask.getCamundaCandidateUsers()).isNull();
assertThat(userTask.getCamundaCandidateUsersList()).isEmpty();
}
@Test
public void testSetNullCamundaCandidateUsersList() {
assertThat(userTask.getCamundaCandidateUsers()).isNotEmpty();
assertThat(userTask.getCamundaCandidateUsersList()).isNotEmpty();
userTask.setCamundaCandidateUsersList(null);
assertThat(userTask.getCamundaCandidateUsers()).isNull();
assertThat(userTask.getCamundaCandidateUsersList()).isEmpty();
}
@Test
public void testEmptyCamundaCandidateUsersList() {
assertThat(userTask.getCamundaCandidateUsers()).isNotEmpty();
assertThat(userTask.getCamundaCandidateUsersList()).isNotEmpty();
userTask.setCamundaCandidateUsersList(Collections.<String>emptyList());
assertThat(userTask.getCamundaCandidateUsers()).isNull();
assertThat(userTask.getCamundaCandidateUsersList()).isEmpty();
}
@Test
public void testScriptResource() {
assertThat(scriptTask.getScriptFormat()).isEqualTo("groovy");
assertThat(scriptTask.getCamundaResource()).isEqualTo("test.groovy");
}
@Test
public void testCamundaConnector() {
CamundaConnector camundaConnector = serviceTask.getExtensionElements().getElementsQuery().filterByType(CamundaConnector.class).singleResult();
assertThat(camundaConnector).isNotNull();
CamundaConnectorId camundaConnectorId = camundaConnector.getCamundaConnectorId();
assertThat(camundaConnectorId).isNotNull();
assertThat(camundaConnectorId.getTextContent()).isEqualTo("soap-http-connector");
CamundaInputOutput camundaInputOutput = camundaConnector.getCamundaInputOutput();
Collection<CamundaInputParameter> inputParameters = camundaInputOutput.getCamundaInputParameters();
assertThat(inputParameters).hasSize(1);
CamundaInputParameter inputParameter = inputParameters.iterator().next();
assertThat(inputParameter.getCamundaName()).isEqualTo("endpointUrl");
assertThat(inputParameter.getTextContent()).isEqualTo("http://example.com/webservice");
Collection<CamundaOutputParameter> outputParameters = camundaInputOutput.getCamundaOutputParameters();
assertThat(outputParameters).hasSize(1);
CamundaOutputParameter outputParameter = outputParameters.iterator().next();
assertThat(outputParameter.getCamundaName()).isEqualTo("result");
assertThat(outputParameter.getTextContent()).isEqualTo("output");
}
@Test
public void testCamundaInputOutput() {
CamundaInputOutput camundaInputOutput = serviceTask.getExtensionElements().getElementsQuery().filterByType(CamundaInputOutput.class).singleResult();
assertThat(camundaInputOutput).isNotNull();
assertThat(camundaInputOutput.getCamundaInputParameters()).hasSize(6);
assertThat(camundaInputOutput.getCamundaOutputParameters()).hasSize(1);
}
@Test
public void testCamundaInputParameter() {
// find existing
CamundaInputParameter inputParameter = findInputParameterByName(serviceTask, "shouldBeConstant");
// modify existing
inputParameter.setCamundaName("hello");
inputParameter.setTextContent("world");
inputParameter = findInputParameterByName(serviceTask, "hello");
assertThat(inputParameter.getTextContent()).isEqualTo("world");
// add new one
inputParameter = modelInstance.newInstance(CamundaInputParameter.class);
inputParameter.setCamundaName("abc");
inputParameter.setTextContent("def");
serviceTask.getExtensionElements().getElementsQuery().filterByType(CamundaInputOutput.class).singleResult()
.addChildElement(inputParameter);
// search for new one
inputParameter = findInputParameterByName(serviceTask, "abc");
assertThat(inputParameter.getCamundaName()).isEqualTo("abc");
assertThat(inputParameter.getTextContent()).isEqualTo("def");
}
@Test
public void testCamundaNullInputParameter() {
CamundaInputParameter inputParameter = findInputParameterByName(serviceTask, "shouldBeNull");
assertThat(inputParameter.getCamundaName()).isEqualTo("shouldBeNull");
assertThat(inputParameter.getTextContent()).isEmpty();
}
@Test
public void testCamundaConstantInputParameter() {
CamundaInputParameter inputParameter = findInputParameterByName(serviceTask, "shouldBeConstant");
assertThat(inputParameter.getCamundaName()).isEqualTo("shouldBeConstant");
assertThat(inputParameter.getTextContent()).isEqualTo("foo");
}
@Test
public void testCamundaExpressionInputParameter() {
CamundaInputParameter inputParameter = findInputParameterByName(serviceTask, "shouldBeExpression");
assertThat(inputParameter.getCamundaName()).isEqualTo("shouldBeExpression");
assertThat(inputParameter.getTextContent()).isEqualTo("${1 + 1}");
}
@Test
public void testCamundaListInputParameter() {
CamundaInputParameter inputParameter = findInputParameterByName(serviceTask, "shouldBeList");
assertThat(inputParameter.getCamundaName()).isEqualTo("shouldBeList");
assertThat(inputParameter.getTextContent()).isNotEmpty();
assertThat(inputParameter.getUniqueChildElementByNameNs(CAMUNDA_NS, "list")).isNotNull();
CamundaList list = inputParameter.getValue();
assertThat(list.getValues()).hasSize(3);
for (BpmnModelElementInstance values : list.getValues()) {
assertThat(values.getTextContent()).isIn("a", "b", "c");
}
list = modelInstance.newInstance(CamundaList.class);
for (int i = 0; i < 4; i++) {
CamundaValue value = modelInstance.newInstance(CamundaValue.class);
value.setTextContent("test");
list.getValues().add(value);
}
Collection<CamundaValue> testValues = Arrays.asList(modelInstance.newInstance(CamundaValue.class), modelInstance.newInstance(CamundaValue.class));
list.getValues().addAll(testValues);
inputParameter.setValue(list);
list = inputParameter.getValue();
assertThat(list.getValues()).hasSize(6);
list.getValues().removeAll(testValues);
ArrayList<BpmnModelElementInstance> camundaValues = new ArrayList<BpmnModelElementInstance>(list.getValues());
assertThat(camundaValues).hasSize(4);
for (BpmnModelElementInstance value : camundaValues) {
assertThat(value.getTextContent()).isEqualTo("test");
}
list.getValues().remove(camundaValues.get(1));
assertThat(list.getValues()).hasSize(3);
list.getValues().removeAll(Arrays.asList(camundaValues.get(0), camundaValues.get(3)));
assertThat(list.getValues()).hasSize(1);
list.getValues().clear();
assertThat(list.getValues()).isEmpty();
// test standard list interactions
Collection<BpmnModelElementInstance> elements = list.getValues();
CamundaValue value = modelInstance.newInstance(CamundaValue.class);
elements.add(value);
List<CamundaValue> newValues = new ArrayList<CamundaValue>();
newValues.add(modelInstance.newInstance(CamundaValue.class));
newValues.add(modelInstance.newInstance(CamundaValue.class));
elements.addAll(newValues);
assertThat(elements).hasSize(3);
assertThat(elements).doesNotContain(modelInstance.newInstance(CamundaValue.class));
assertThat(elements.containsAll(Arrays.asList(modelInstance.newInstance(CamundaValue.class)))).isFalse();
assertThat(elements.remove(modelInstance.newInstance(CamundaValue.class))).isFalse();
assertThat(elements).hasSize(3);
assertThat(elements.remove(value)).isTrue();
assertThat(elements).hasSize(2);
assertThat(elements.removeAll(newValues)).isTrue();
assertThat(elements).isEmpty();
elements.add(modelInstance.newInstance(CamundaValue.class));
elements.clear();
assertThat(elements).isEmpty();
inputParameter.removeValue();
assertThat((Object) inputParameter.getValue()).isNull();
}
@Test
public void testCamundaMapInputParameter() {
CamundaInputParameter inputParameter = findInputParameterByName(serviceTask, "shouldBeMap");
assertThat(inputParameter.getCamundaName()).isEqualTo("shouldBeMap");
assertThat(inputParameter.getTextContent()).isNotEmpty();
assertThat(inputParameter.getUniqueChildElementByNameNs(CAMUNDA_NS, "map")).isNotNull();
CamundaMap map = inputParameter.getValue();
assertThat(map.getCamundaEntries()).hasSize(2);
for (CamundaEntry entry : map.getCamundaEntries()) {
if (entry.getCamundaKey().equals("foo")) {
assertThat(entry.getTextContent()).isEqualTo("bar");
}
else {
assertThat(entry.getCamundaKey()).isEqualTo("hello");
assertThat(entry.getTextContent()).isEqualTo("world");
}
}
map = modelInstance.newInstance(CamundaMap.class);
CamundaEntry entry = modelInstance.newInstance(CamundaEntry.class);
entry.setCamundaKey("test");
entry.setTextContent("value");
map.getCamundaEntries().add(entry);
inputParameter.setValue(map);
map = inputParameter.getValue();
assertThat(map.getCamundaEntries()).hasSize(1);
entry = map.getCamundaEntries().iterator().next();
assertThat(entry.getCamundaKey()).isEqualTo("test");
assertThat(entry.getTextContent()).isEqualTo("value");
Collection<CamundaEntry> entries = map.getCamundaEntries();
entries.add(modelInstance.newInstance(CamundaEntry.class));
assertThat(entries).hasSize(2);
inputParameter.removeValue();
assertThat((Object) inputParameter.getValue()).isNull();
}
@Test
public void testCamundaScriptInputParameter() {
CamundaInputParameter inputParameter = findInputParameterByName(serviceTask, "shouldBeScript");
assertThat(inputParameter.getCamundaName()).isEqualTo("shouldBeScript");
assertThat(inputParameter.getTextContent()).isNotEmpty();
assertThat(inputParameter.getUniqueChildElementByNameNs(CAMUNDA_NS, "script")).isNotNull();
assertThat(inputParameter.getUniqueChildElementByType(CamundaScript.class)).isNotNull();
CamundaScript script = inputParameter.getValue();
assertThat(script.getCamundaScriptFormat()).isEqualTo("groovy");
assertThat(script.getCamundaResource()).isNull();
assertThat(script.getTextContent()).isEqualTo("1 + 1");
script = modelInstance.newInstance(CamundaScript.class);
script.setCamundaScriptFormat("python");
script.setCamundaResource("script.py");
inputParameter.setValue(script);
script = inputParameter.getValue();
assertThat(script.getCamundaScriptFormat()).isEqualTo("python");
assertThat(script.getCamundaResource()).isEqualTo("script.py");
assertThat(script.getTextContent()).isEmpty();
inputParameter.removeValue();
assertThat((Object) inputParameter.getValue()).isNull();
}
@Test
public void testCamundaNestedOutputParameter() {
CamundaOutputParameter camundaOutputParameter = serviceTask.getExtensionElements().getElementsQuery().filterByType(CamundaInputOutput.class).singleResult().getCamundaOutputParameters().iterator().next();
assertThat(camundaOutputParameter).isNotNull();
assertThat(camundaOutputParameter.getCamundaName()).isEqualTo("nested");
CamundaList list = camundaOutputParameter.getValue();
assertThat(list).isNotNull();
assertThat(list.getValues()).hasSize(2);
Iterator<BpmnModelElementInstance> iterator = list.getValues().iterator();
// nested list
CamundaList nestedList = (CamundaList) iterator.next().getUniqueChildElementByType(CamundaList.class);
assertThat(nestedList).isNotNull();
assertThat(nestedList.getValues()).hasSize(2);
for (BpmnModelElementInstance value : nestedList.getValues()) {
assertThat(value.getTextContent()).isEqualTo("list");
}
// nested map
CamundaMap nestedMap = (CamundaMap) iterator.next().getUniqueChildElementByType(CamundaMap.class);
assertThat(nestedMap).isNotNull();
assertThat(nestedMap.getCamundaEntries()).hasSize(2);
Iterator<CamundaEntry> mapIterator = nestedMap.getCamundaEntries().iterator();
// nested list in nested map
CamundaEntry nestedListEntry = mapIterator.next();
assertThat(nestedListEntry).isNotNull();
assertThat(nestedListEntry.getCamundaKey()).isEqualTo("list");
CamundaList nestedNestedList = nestedListEntry.getValue();
for (BpmnModelElementInstance value : nestedNestedList.getValues()) {
assertThat(value.getTextContent()).isEqualTo("map");
}
// nested map in nested map
CamundaEntry nestedMapEntry = mapIterator.next();
assertThat(nestedMapEntry).isNotNull();
assertThat(nestedMapEntry.getCamundaKey()).isEqualTo("map");
CamundaMap nestedNestedMap = nestedMapEntry.getValue();
CamundaEntry entry = nestedNestedMap.getCamundaEntries().iterator().next();
assertThat(entry.getCamundaKey()).isEqualTo("so");
assertThat(entry.getTextContent()).isEqualTo("nested");
}
protected CamundaInputParameter findInputParameterByName(BaseElement baseElement, String name) {
Collection<CamundaInputParameter> camundaInputParameters = baseElement.getExtensionElements().getElementsQuery()
.filterByType(CamundaInputOutput.class).singleResult().getCamundaInputParameters();
for (CamundaInputParameter camundaInputParameter : camundaInputParameters) {
if (camundaInputParameter.getCamundaName().equals(name)) {
return camundaInputParameter;
}
}
throw new BpmnModelException("Unable to find camunda:inputParameter with name '" + name + "' for element with id '" + baseElement.getId() + "'");
}
@After
public void validateModel() {
Bpmn.validateModel(modelInstance);
}
}
| camunda/camunda-bpm-platform | model-api/bpmn-model/src/test/java/org/camunda/bpm/model/bpmn/CamundaExtensionsTest.java | Java | apache-2.0 | 57,428 |
/*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; 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.
*/
package org.camunda.bpm.engine.test.jobexecutor;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.List;
import org.camunda.bpm.engine.impl.bpmn.parser.BpmnParse;
import org.camunda.bpm.engine.impl.jobexecutor.AsyncContinuationJobHandler;
import org.camunda.bpm.engine.impl.jobexecutor.MessageJobDeclaration;
import org.camunda.bpm.engine.impl.jobexecutor.TimerCatchIntermediateEventJobHandler;
import org.camunda.bpm.engine.impl.jobexecutor.TimerExecuteNestedActivityJobHandler;
import org.camunda.bpm.engine.impl.jobexecutor.TimerStartEventJobHandler;
import org.camunda.bpm.engine.management.JobDefinition;
import org.camunda.bpm.engine.management.JobDefinitionQuery;
import org.camunda.bpm.engine.repository.ProcessDefinition;
import org.camunda.bpm.engine.runtime.Job;
import org.camunda.bpm.engine.test.Deployment;
import org.camunda.bpm.engine.test.util.PluggableProcessEngineTest;
import org.junit.Test;
/**
* These testcases verify that job definitions are created upon deployment of the process definition.
*
* @author Daniel Meyer
*
*/
public class JobDefinitionDeploymentTest extends PluggableProcessEngineTest {
@Deployment
@Test
public void testTimerStartEvent() {
// given
ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().singleResult();
JobDefinition jobDefinition = managementService.createJobDefinitionQuery().processDefinitionKey("testProcess").singleResult();
// then assert
assertNotNull(jobDefinition);
assertEquals(TimerStartEventJobHandler.TYPE, jobDefinition.getJobType());
assertEquals("theStart", jobDefinition.getActivityId());
assertEquals("DATE: 2036-11-14T11:12:22", jobDefinition.getJobConfiguration());
assertEquals(processDefinition.getId(), jobDefinition.getProcessDefinitionId());
// there exists a job with the correct job definition id:
Job timerStartJob = managementService.createJobQuery().singleResult();
assertEquals(jobDefinition.getId(), timerStartJob.getJobDefinitionId());
}
@Deployment
@Test
public void testTimerBoundaryEvent() {
// given
ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().singleResult();
JobDefinition jobDefinition = managementService.createJobDefinitionQuery().processDefinitionKey("testProcess").singleResult();
// then assert
assertNotNull(jobDefinition);
assertEquals(TimerExecuteNestedActivityJobHandler.TYPE, jobDefinition.getJobType());
assertEquals("theBoundaryEvent", jobDefinition.getActivityId());
assertEquals("DATE: 2036-11-14T11:12:22", jobDefinition.getJobConfiguration());
assertEquals(processDefinition.getId(), jobDefinition.getProcessDefinitionId());
}
@Deployment
@Test
public void testMultipleTimerBoundaryEvents() {
// given
ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().singleResult();
JobDefinitionQuery jobDefinitionQuery = managementService.createJobDefinitionQuery().processDefinitionKey("testProcess");
// then assert
assertEquals(2, jobDefinitionQuery.count());
JobDefinition jobDefinition = jobDefinitionQuery.activityIdIn("theBoundaryEvent1").singleResult();
assertNotNull(jobDefinition);
assertEquals(TimerExecuteNestedActivityJobHandler.TYPE, jobDefinition.getJobType());
assertEquals("theBoundaryEvent1", jobDefinition.getActivityId());
assertEquals("DATE: 2036-11-14T11:12:22", jobDefinition.getJobConfiguration());
assertEquals(processDefinition.getId(), jobDefinition.getProcessDefinitionId());
jobDefinition = jobDefinitionQuery.activityIdIn("theBoundaryEvent2").singleResult();
assertNotNull(jobDefinition);
assertEquals(TimerExecuteNestedActivityJobHandler.TYPE, jobDefinition.getJobType());
assertEquals("theBoundaryEvent2", jobDefinition.getActivityId());
assertEquals("DURATION: PT5M", jobDefinition.getJobConfiguration());
assertEquals(processDefinition.getId(), jobDefinition.getProcessDefinitionId());
}
@Deployment
@Test
public void testEventBasedGateway() {
// given
ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().singleResult();
JobDefinitionQuery jobDefinitionQuery = managementService.createJobDefinitionQuery().processDefinitionKey("testProcess");
// then assert
assertEquals(2, jobDefinitionQuery.count());
JobDefinition jobDefinition = jobDefinitionQuery.activityIdIn("timer1").singleResult();
assertNotNull(jobDefinition);
assertEquals(TimerCatchIntermediateEventJobHandler.TYPE, jobDefinition.getJobType());
assertEquals("timer1", jobDefinition.getActivityId());
assertEquals("DURATION: PT5M", jobDefinition.getJobConfiguration());
assertEquals(processDefinition.getId(), jobDefinition.getProcessDefinitionId());
jobDefinition = jobDefinitionQuery.activityIdIn("timer2").singleResult();
assertNotNull(jobDefinition);
assertEquals(TimerCatchIntermediateEventJobHandler.TYPE, jobDefinition.getJobType());
assertEquals("timer2", jobDefinition.getActivityId());
assertEquals("DURATION: PT10M", jobDefinition.getJobConfiguration());
assertEquals(processDefinition.getId(), jobDefinition.getProcessDefinitionId());
}
@Deployment
@Test
public void testTimerIntermediateEvent() {
// given
ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().singleResult();
JobDefinition jobDefinition = managementService.createJobDefinitionQuery().processDefinitionKey("testProcess").singleResult();
// then assert
assertNotNull(jobDefinition);
assertEquals(TimerCatchIntermediateEventJobHandler.TYPE, jobDefinition.getJobType());
assertEquals("timer", jobDefinition.getActivityId());
assertEquals("DURATION: PT5M", jobDefinition.getJobConfiguration());
assertEquals(processDefinition.getId(), jobDefinition.getProcessDefinitionId());
}
@Deployment
@Test
public void testAsyncContinuation() {
// given
ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().singleResult();
JobDefinition jobDefinition = managementService.createJobDefinitionQuery().processDefinitionKey("testProcess").singleResult();
// then assert
assertNotNull(jobDefinition);
assertEquals(AsyncContinuationJobHandler.TYPE, jobDefinition.getJobType());
assertEquals("theService", jobDefinition.getActivityId());
assertEquals(MessageJobDeclaration.ASYNC_BEFORE, jobDefinition.getJobConfiguration());
assertEquals(processDefinition.getId(), jobDefinition.getProcessDefinitionId());
}
@Deployment
@Test
public void testAsyncContinuationOfMultiInstance() {
// given
ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().singleResult();
JobDefinition jobDefinition = managementService.createJobDefinitionQuery().processDefinitionKey("testProcess").singleResult();
// then assert
assertNotNull(jobDefinition);
assertEquals(AsyncContinuationJobHandler.TYPE, jobDefinition.getJobType());
assertEquals("theService" + BpmnParse.MULTI_INSTANCE_BODY_ID_SUFFIX, jobDefinition.getActivityId());
assertEquals(MessageJobDeclaration.ASYNC_AFTER, jobDefinition.getJobConfiguration());
assertEquals(processDefinition.getId(), jobDefinition.getProcessDefinitionId());
}
@Deployment
@Test
public void testAsyncContinuationOfActivityWrappedInMultiInstance() {
// given
ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().singleResult();
JobDefinition jobDefinition = managementService.createJobDefinitionQuery().processDefinitionKey("testProcess").singleResult();
// then assert
assertNotNull(jobDefinition);
assertEquals(AsyncContinuationJobHandler.TYPE, jobDefinition.getJobType());
assertEquals("theService", jobDefinition.getActivityId());
assertEquals(MessageJobDeclaration.ASYNC_AFTER, jobDefinition.getJobConfiguration());
assertEquals(processDefinition.getId(), jobDefinition.getProcessDefinitionId());
}
@Deployment(resources = {"org/camunda/bpm/engine/test/jobexecutor/JobDefinitionDeploymentTest.testAsyncContinuation.bpmn20.xml",
"org/camunda/bpm/engine/test/jobexecutor/JobDefinitionDeploymentTest.testMultipleProcessesWithinDeployment.bpmn20.xml"})
@Test
public void testMultipleProcessDeployment() {
JobDefinitionQuery query = managementService.createJobDefinitionQuery();
List<JobDefinition> jobDefinitions = query.list();
assertEquals(3, jobDefinitions.size());
assertEquals(1, query.processDefinitionKey("testProcess").list().size());
assertEquals(2, query.processDefinitionKey("anotherTestProcess").list().size());
}
}
| camunda/camunda-bpm-platform | engine/src/test/java/org/camunda/bpm/engine/test/jobexecutor/JobDefinitionDeploymentTest.java | Java | apache-2.0 | 9,640 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package org.apache.camel.component.atomix.client.map;
import java.util.Collections;
import java.util.Map;
import java.util.UUID;
import io.atomix.collections.DistributedMap;
import org.apache.camel.Component;
import org.apache.camel.EndpointInject;
import org.apache.camel.FluentProducerTemplate;
import org.apache.camel.Message;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.atomix.client.AtomixClientConstants;
import org.apache.camel.component.atomix.client.AtomixClientTestSupport;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
public class AtomixMapNodesProducerTest extends AtomixClientTestSupport {
private static final String MAP_NAME = UUID.randomUUID().toString();
private DistributedMap<Object, Object> map;
@EndpointInject("direct:start")
private FluentProducerTemplate fluent;
// ************************************
// Setup
// ************************************
@Override
protected Map<String, Component> createComponents() {
return Collections.emptyMap();
}
@Override
protected void doPreSetup() throws Exception {
super.doPreSetup();
map = getClient().getMap(MAP_NAME).join();
}
@Override
@AfterEach
public void tearDown() throws Exception {
map.close();
super.tearDown();
}
// ************************************
// Test
// ************************************
@Test
void testPut() {
final String key = context().getUuidGenerator().generateUuid();
final String val = context().getUuidGenerator().generateUuid();
Message result;
result = fluent.clearAll()
.withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixMap.Action.PUT)
.withHeader(AtomixClientConstants.RESOURCE_KEY, key)
.withBody(val)
.request(Message.class);
assertFalse(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
assertEquals(val, result.getBody());
assertEquals(val, map.get(key).join());
}
// ************************************
// Routes
// ************************************
@Override
protected RoutesBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("direct:start")
.toF("atomix-map:%s?nodes=%s:%d", MAP_NAME, replicaAddress.host(), replicaAddress.port());
}
};
}
}
| DariusX/camel | components/camel-atomix/src/test/java/org/apache/camel/component/atomix/client/map/AtomixMapNodesProducerTest.java | Java | apache-2.0 | 3,520 |
package com.ibm.kdd.core;
public enum DataType {
STR,
INT,
FLOAT,
DATE,
TIME,
TIMESTAMP,
UNKNOWN;
public static DataType getDataType(String typeName) {
if (typeName.equalsIgnoreCase("string") || typeName.equalsIgnoreCase("str")) {
return STR;
}
else if (typeName.equalsIgnoreCase("integer") || typeName.equalsIgnoreCase("int")) {
return INT;
}
else if (typeName.equalsIgnoreCase("float")) {
return FLOAT;
}
else if (typeName.equalsIgnoreCase("date")) {
return DATE;
}
else if (typeName.equalsIgnoreCase("time")) {
return TIME;
}
else if (typeName.equalsIgnoreCase("timestamp")) {
return TIMESTAMP;
}
else {
return UNKNOWN;
}
}
public static boolean isNumeric(DataType type) {
if (type == INT || type == FLOAT) {
return true;
}
else {
return false;
}
}
public static boolean isCategorical(DataType type) {
return !isNumeric(type);
}
}
| wliu015/event_miner | pages/temporal-pattern/WEB-INF/classes/com/ibm/kdd/core/DataType.java | Java | apache-2.0 | 967 |
"""The tests for hls streams."""
from datetime import timedelta
from io import BytesIO
from unittest.mock import patch
from homeassistant.setup import async_setup_component
from homeassistant.components.stream.core import Segment
from homeassistant.components.stream.recorder import recorder_save_worker
import homeassistant.util.dt as dt_util
from tests.common import async_fire_time_changed
from tests.components.stream.common import (
generate_h264_video, preload_stream)
async def test_record_stream(hass, hass_client):
"""
Test record stream.
Purposefully not mocking anything here to test full
integration with the stream component.
"""
await async_setup_component(hass, 'stream', {
'stream': {}
})
with patch(
'homeassistant.components.stream.recorder.recorder_save_worker'):
# Setup demo track
source = generate_h264_video()
stream = preload_stream(hass, source)
recorder = stream.add_provider('recorder')
stream.start()
segments = 0
while True:
segment = await recorder.recv()
if not segment:
break
segments += 1
stream.stop()
assert segments > 1
async def test_recorder_timeout(hass, hass_client):
"""Test recorder timeout."""
await async_setup_component(hass, 'stream', {
'stream': {}
})
with patch(
'homeassistant.components.stream.recorder.RecorderOutput.cleanup'
) as mock_cleanup:
# Setup demo track
source = generate_h264_video()
stream = preload_stream(hass, source)
recorder = stream.add_provider('recorder')
stream.start()
await recorder.recv()
# Wait a minute
future = dt_util.utcnow() + timedelta(minutes=1)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
assert mock_cleanup.called
async def test_recorder_save():
"""Test recorder save."""
# Setup
source = generate_h264_video()
output = BytesIO()
output.name = 'test.mp4'
# Run
recorder_save_worker(output, [Segment(1, source, 4)])
# Assert
assert output.getvalue()
| auduny/home-assistant | tests/components/stream/test_recorder.py | Python | apache-2.0 | 2,235 |
/*
* Copyright 2014 JBoss Inc
*
* 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.
*/
package org.jbpm.console.ng.es.client.editors.servicesettings;
import javax.enterprise.context.Dependent;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Widget;
import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.client.ui.FormGroup;
import org.gwtbootstrap3.client.ui.HelpBlock;
import org.gwtbootstrap3.client.ui.IntegerBox;
import org.gwtbootstrap3.client.ui.Label;
import org.gwtbootstrap3.client.ui.TextBox;
import org.gwtbootstrap3.client.ui.constants.ButtonType;
import org.gwtbootstrap3.client.ui.constants.ValidationState;
import org.jboss.errai.common.client.api.Caller;
import org.jboss.errai.common.client.api.RemoteCallback;
import org.jbpm.console.ng.es.client.i18n.Constants;
import org.jbpm.console.ng.es.service.ExecutorServiceEntryPoint;
import org.uberfire.ext.widgets.common.client.common.popups.BaseModal;
import org.uberfire.ext.widgets.common.client.common.popups.footers.GenericModalFooter;
import org.uberfire.mvp.Command;
import org.uberfire.workbench.events.NotificationEvent;
@Dependent
public class JobServiceSettingsPopup extends BaseModal {
interface Binder
extends
UiBinder<Widget, JobServiceSettingsPopup> {
}
@UiField
public IntegerBox numberOfExecutorsIntegerText;
@UiField
public TextBox frequencyText;
@UiField
public Label startedLabel;
@UiField
public FormGroup numberOfExecutorsControlGroup;
@UiField
public FormGroup frequencyControlGroup;
@UiField
public FormGroup startedControlGroup;
@UiField
public HelpBlock frequencyHelpInline;
@UiField
public HelpBlock numberOfExecutorsHelpInline;
@UiField
public HelpBlock errorMessages;
@UiField
public FormGroup errorMessagesGroup;
@Inject
private Event<NotificationEvent> notification;
@Inject
private Caller<ExecutorServiceEntryPoint> executorServices;
final GenericModalFooter footer = new GenericModalFooter();
private static Binder uiBinder = GWT.create( Binder.class );
private boolean serviceStarted = false;
public JobServiceSettingsPopup() {
setTitle( Constants.INSTANCE.Job_Service_Settings() );
setBody( uiBinder.createAndBindUi( this ) );
footer.addButton( Constants.INSTANCE.Start(),
new Command() {
@Override
public void execute() {
okButton();
}
}, null,
ButtonType.PRIMARY );
add( footer );
}
public void show() {
cleanForm();
cleanErrorMessages();
super.show();
}
private void okButton() {
if ( validateForm() ) {
startStopService();
}
}
private void cleanErrorMessages() {
numberOfExecutorsHelpInline.setText( "" );
numberOfExecutorsControlGroup.setValidationState( ValidationState.NONE );
frequencyHelpInline.setText( "" );
frequencyControlGroup.setValidationState( ValidationState.NONE );
errorMessages.setText( "" );
errorMessagesGroup.setValidationState( ValidationState.NONE );
}
public void closePopup() {
cleanForm();
hide();
}
private boolean validateForm() {
boolean valid = true;
cleanErrorMessages();
if ( !serviceStarted ) {
numberOfExecutorsControlGroup.setValidationState( ValidationState.SUCCESS );
frequencyControlGroup.setValidationState( ValidationState.SUCCESS );
if ( numberOfExecutorsIntegerText.getText() == null || numberOfExecutorsIntegerText.getText().trim().isEmpty() ) {
numberOfExecutorsControlGroup.setValidationState( ValidationState.ERROR );
numberOfExecutorsHelpInline.setText( Constants.INSTANCE.Please_Provide_The_Number_Of_Executors() );
valid = false;
} else {
if ( !( numberOfExecutorsIntegerText.getValue() != null && numberOfExecutorsIntegerText.getValue() > 0 ) ) {
numberOfExecutorsControlGroup.setValidationState( ValidationState.ERROR );
numberOfExecutorsHelpInline.setText( Constants.INSTANCE.Please_Provide_A_Valid_Number_Of_Executors() );
valid = false;
}
}
if ( frequencyText.getText() == null || frequencyText.getText().trim().isEmpty() ) {
frequencyControlGroup.setValidationState( ValidationState.ERROR );
frequencyHelpInline.setText( Constants.INSTANCE.Please_Provide_A_Valid_Frequency() );
valid = false;
} else {
try {
if ( fromFrequencyToInterval( frequencyText.getText() ) < 0 ) {
throw new NumberFormatException();
}
} catch ( Exception e ) {
frequencyControlGroup.setValidationState( ValidationState.ERROR );
frequencyHelpInline.setText( Constants.INSTANCE.Please_Provide_A_Valid_Frequency() );
}
}
}
return valid;
}
public void displayNotification( String text ) {
notification.fire( new NotificationEvent( text ) );
}
public void cleanForm() {
executorServices.call( new RemoteCallback<Integer>() {
@Override
public void callback( Integer interval ) {
frequencyText.setText( fromIntervalToFrequency( interval ) );
}
} ).getInterval();
executorServices.call( new RemoteCallback<Integer>() {
@Override
public void callback( Integer threadPoolSize ) {
numberOfExecutorsIntegerText.setValue( threadPoolSize );
}
} ).getThreadPoolSize();
executorServices.call( new RemoteCallback<Boolean>() {
@Override
public void callback( Boolean started ) {
setStartedLabel( started );
if ( started ) {
( (Button) footer.getWidget( 0 ) ).setText( Constants.INSTANCE.Stop() );
frequencyText.setEnabled( false );
numberOfExecutorsIntegerText.setEnabled( false );
} else {
frequencyText.setEnabled( true );
numberOfExecutorsIntegerText.setEnabled( true );
( (Button) footer.getWidget( 0 ) ).setText( Constants.INSTANCE.Start() );
}
}
} ).isActive();
}
public void startStopService() {
Integer frequency = fromFrequencyToInterval( frequencyText.getText() );
Integer numberOfExecutors = numberOfExecutorsIntegerText.getValue();
executorServices.call( new RemoteCallback<Boolean>() {
@Override
public void callback( Boolean serviceStatus ) {
displayNotification( serviceStatus ? Constants.INSTANCE.ServiceStarted() : Constants.INSTANCE.ServiceStopped() );
closePopup();
}
} ).startStopService( frequency, numberOfExecutors );
}
public String fromIntervalToFrequency( Integer interval ) {
int seconds = interval % 60;
int minutes = ( interval / 60 ) % 60;
int hours = ( interval / 3600 ) % 24;
int days = ( interval / 86400 );
StringBuilder frequencyText = new StringBuilder();
if ( days > 0 ) {
frequencyText.append( days ).append( "d " );
}
if ( hours > 0 ) {
frequencyText.append( hours ).append( "h " );
}
if ( minutes > 0 ) {
frequencyText.append( minutes ).append( "m " );
}
if ( seconds > 0 ) {
frequencyText.append( seconds ).append( "s" );
}
return frequencyText.toString();
}
public Integer fromFrequencyToInterval( String frequency ) throws NumberFormatException {
String[] sections = frequency.split( " " );
int interval = 0;
for ( String section : sections ) {
if ( section.trim().endsWith( "d" ) ) {
int value = Integer.parseInt( section.replace( "d", "" ) );
interval += ( value * 86400 );
} else if ( section.trim().endsWith( "h" ) ) {
int value = Integer.parseInt( section.replace( "h", "" ) );
interval += ( value * 3600 );
} else if ( section.trim().endsWith( "m" ) ) {
int value = Integer.parseInt( section.replace( "m", "" ) );
interval += ( value * 60 );
} else if ( section.trim().endsWith( "s" ) ) {
int value = Integer.parseInt( section.replace( "s", "" ) );
interval += value;
} else {
throw new NumberFormatException();
}
}
return interval;
}
public void setStartedLabel( Boolean started ) {
this.startedLabel.setText( started ? Constants.INSTANCE.Started() : Constants.INSTANCE.Stopped() );
this.serviceStarted = started;
}
}
| emilianoandre/jbpm-console-ng | jbpm-console-ng-executor-service/jbpm-console-ng-executor-service-client/src/main/java/org/jbpm/console/ng/es/client/editors/servicesettings/JobServiceSettingsPopup.java | Java | apache-2.0 | 9,936 |
#ifndef BWA_H_
#define BWA_H_
#include <stdint.h>
#include "bntseq.h"
#include "bwt.h"
#define BWA_IDX_BWT 0x1
#define BWA_IDX_BNS 0x2
#define BWA_IDX_PAC 0x4
#define BWA_IDX_ALL 0x7
typedef struct {
bwt_t *bwt; // FM-index
bntseq_t *bns; // information on the reference sequences
uint8_t *pac; // the actual 2-bit encoded reference sequences with 'N' converted to a random base
} bwaidx_t;
typedef struct {
int l_seq;
char *name, *comment, *seq, *qual, *sam;
} bseq1_t;
extern int bwa_verbose;
extern char bwa_rg_id[256];
#ifdef __cplusplus
extern "C" {
#endif
bseq1_t *bseq_read(int chunk_size, int *n_, void *ks1_, void *ks2_);
void bwa_fill_scmat(int a, int b, int8_t mat[25]);
uint32_t *bwa_gen_cigar(const int8_t mat[25], int q, int r, int w_, int64_t l_pac, const uint8_t *pac, int l_query, uint8_t *query, int64_t rb, int64_t re, int *score, int *n_cigar, int *NM);
uint32_t *bwa_gen_cigar2(const int8_t mat[25], int o_del, int e_del, int o_ins, int e_ins, int w_, int64_t l_pac, const uint8_t *pac, int l_query, uint8_t *query, int64_t rb, int64_t re, int *score, int *n_cigar, int *NM);
int bwa_fix_xref(const int8_t mat[25], int q, int r, int w, const bntseq_t *bns, const uint8_t *pac, uint8_t *query, int *qb, int *qe, int64_t *rb, int64_t *re);
int bwa_fix_xref2(const int8_t mat[25], int o_del, int e_del, int o_ins, int e_ins, int w, const bntseq_t *bns, const uint8_t *pac, uint8_t *query, int *qb, int *qe, int64_t *rb, int64_t *re);
char *bwa_idx_infer_prefix(const char *hint);
bwt_t *bwa_idx_load_bwt(const char *hint);
bwaidx_t *bwa_idx_load(const char *hint, int which);
void bwa_idx_destroy(bwaidx_t *idx);
void bwa_print_sam_hdr(const bntseq_t *bns, const char *rg_line);
char *bwa_set_rg(const char *s);
#ifdef __cplusplus
}
#endif
#endif
| ytchen0323/cloud-scale-bwamem | src/main/native/bwa.h | C | apache-2.0 | 1,799 |
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#include "kwsysPrivate.h"
#include KWSYS_HEADER(MD5.h)
/* Work-around CMake dependency scanning limitation. This must
duplicate the above list of headers. */
#if 0
# include "MD5.h.in"
#endif
#include <stddef.h> /* size_t */
#include <stdlib.h> /* malloc, free */
#include <string.h> /* memcpy, strlen */
/* This MD5 implementation has been taken from a third party. Slight
modifications to the arrangement of the code have been made to put
it in a single source file instead of a separate header and
implementation file. */
#if defined(__clang__) && !defined(__INTEL_COMPILER)
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wcast-align"
#endif
/*
Copyright (C) 1999, 2000, 2002 Aladdin Enterprises. All rights reserved.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
L. Peter Deutsch
ghost@aladdin.com
*/
/*
Independent implementation of MD5 (RFC 1321).
This code implements the MD5 Algorithm defined in RFC 1321, whose
text is available at
http://www.ietf.org/rfc/rfc1321.txt
The code is derived from the text of the RFC, including the test suite
(section A.5) but excluding the rest of Appendix A. It does not include
any code or documentation that is identified in the RFC as being
copyrighted.
The original and principal author of md5.c is L. Peter Deutsch
<ghost@aladdin.com>. Other authors are noted in the change history
that follows (in reverse chronological order):
2002-04-13 lpd Clarified derivation from RFC 1321; now handles byte order
either statically or dynamically; added missing #include <string.h>
in library.
2002-03-11 lpd Corrected argument list for main(), and added int return
type, in test program and T value program.
2002-02-21 lpd Added missing #include <stdio.h> in test program.
2000-07-03 lpd Patched to eliminate warnings about "constant is
unsigned in ANSI C, signed in traditional"; made test program
self-checking.
1999-11-04 lpd Edited comments slightly for automatic TOC extraction.
1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5).
1999-05-03 lpd Original version.
*/
/*
* This package supports both compile-time and run-time determination of CPU
* byte order. If ARCH_IS_BIG_ENDIAN is defined as 0, the code will be
* compiled to run only on little-endian CPUs; if ARCH_IS_BIG_ENDIAN is
* defined as non-zero, the code will be compiled to run only on big-endian
* CPUs; if ARCH_IS_BIG_ENDIAN is not defined, the code will be compiled to
* run on either big- or little-endian CPUs, but will run slightly less
* efficiently on either one than if ARCH_IS_BIG_ENDIAN is defined.
*/
typedef unsigned char md5_byte_t; /* 8-bit byte */
typedef unsigned int md5_word_t; /* 32-bit word */
/* Define the state of the MD5 Algorithm. */
typedef struct md5_state_s
{
md5_word_t count[2]; /* message length in bits, lsw first */
md5_word_t abcd[4]; /* digest buffer */
md5_byte_t buf[64]; /* accumulate block */
} md5_state_t;
#undef BYTE_ORDER /* 1 = big-endian, -1 = little-endian, 0 = unknown */
#ifdef ARCH_IS_BIG_ENDIAN
# define BYTE_ORDER (ARCH_IS_BIG_ENDIAN ? 1 : -1)
#else
# define BYTE_ORDER 0
#endif
#define T_MASK ((md5_word_t)~0)
#define T1 /* 0xd76aa478 */ (T_MASK ^ 0x28955b87)
#define T2 /* 0xe8c7b756 */ (T_MASK ^ 0x173848a9)
#define T3 0x242070db
#define T4 /* 0xc1bdceee */ (T_MASK ^ 0x3e423111)
#define T5 /* 0xf57c0faf */ (T_MASK ^ 0x0a83f050)
#define T6 0x4787c62a
#define T7 /* 0xa8304613 */ (T_MASK ^ 0x57cfb9ec)
#define T8 /* 0xfd469501 */ (T_MASK ^ 0x02b96afe)
#define T9 0x698098d8
#define T10 /* 0x8b44f7af */ (T_MASK ^ 0x74bb0850)
#define T11 /* 0xffff5bb1 */ (T_MASK ^ 0x0000a44e)
#define T12 /* 0x895cd7be */ (T_MASK ^ 0x76a32841)
#define T13 0x6b901122
#define T14 /* 0xfd987193 */ (T_MASK ^ 0x02678e6c)
#define T15 /* 0xa679438e */ (T_MASK ^ 0x5986bc71)
#define T16 0x49b40821
#define T17 /* 0xf61e2562 */ (T_MASK ^ 0x09e1da9d)
#define T18 /* 0xc040b340 */ (T_MASK ^ 0x3fbf4cbf)
#define T19 0x265e5a51
#define T20 /* 0xe9b6c7aa */ (T_MASK ^ 0x16493855)
#define T21 /* 0xd62f105d */ (T_MASK ^ 0x29d0efa2)
#define T22 0x02441453
#define T23 /* 0xd8a1e681 */ (T_MASK ^ 0x275e197e)
#define T24 /* 0xe7d3fbc8 */ (T_MASK ^ 0x182c0437)
#define T25 0x21e1cde6
#define T26 /* 0xc33707d6 */ (T_MASK ^ 0x3cc8f829)
#define T27 /* 0xf4d50d87 */ (T_MASK ^ 0x0b2af278)
#define T28 0x455a14ed
#define T29 /* 0xa9e3e905 */ (T_MASK ^ 0x561c16fa)
#define T30 /* 0xfcefa3f8 */ (T_MASK ^ 0x03105c07)
#define T31 0x676f02d9
#define T32 /* 0x8d2a4c8a */ (T_MASK ^ 0x72d5b375)
#define T33 /* 0xfffa3942 */ (T_MASK ^ 0x0005c6bd)
#define T34 /* 0x8771f681 */ (T_MASK ^ 0x788e097e)
#define T35 0x6d9d6122
#define T36 /* 0xfde5380c */ (T_MASK ^ 0x021ac7f3)
#define T37 /* 0xa4beea44 */ (T_MASK ^ 0x5b4115bb)
#define T38 0x4bdecfa9
#define T39 /* 0xf6bb4b60 */ (T_MASK ^ 0x0944b49f)
#define T40 /* 0xbebfbc70 */ (T_MASK ^ 0x4140438f)
#define T41 0x289b7ec6
#define T42 /* 0xeaa127fa */ (T_MASK ^ 0x155ed805)
#define T43 /* 0xd4ef3085 */ (T_MASK ^ 0x2b10cf7a)
#define T44 0x04881d05
#define T45 /* 0xd9d4d039 */ (T_MASK ^ 0x262b2fc6)
#define T46 /* 0xe6db99e5 */ (T_MASK ^ 0x1924661a)
#define T47 0x1fa27cf8
#define T48 /* 0xc4ac5665 */ (T_MASK ^ 0x3b53a99a)
#define T49 /* 0xf4292244 */ (T_MASK ^ 0x0bd6ddbb)
#define T50 0x432aff97
#define T51 /* 0xab9423a7 */ (T_MASK ^ 0x546bdc58)
#define T52 /* 0xfc93a039 */ (T_MASK ^ 0x036c5fc6)
#define T53 0x655b59c3
#define T54 /* 0x8f0ccc92 */ (T_MASK ^ 0x70f3336d)
#define T55 /* 0xffeff47d */ (T_MASK ^ 0x00100b82)
#define T56 /* 0x85845dd1 */ (T_MASK ^ 0x7a7ba22e)
#define T57 0x6fa87e4f
#define T58 /* 0xfe2ce6e0 */ (T_MASK ^ 0x01d3191f)
#define T59 /* 0xa3014314 */ (T_MASK ^ 0x5cfebceb)
#define T60 0x4e0811a1
#define T61 /* 0xf7537e82 */ (T_MASK ^ 0x08ac817d)
#define T62 /* 0xbd3af235 */ (T_MASK ^ 0x42c50dca)
#define T63 0x2ad7d2bb
#define T64 /* 0xeb86d391 */ (T_MASK ^ 0x14792c6e)
static void md5_process(md5_state_t* pms, const md5_byte_t* data /*[64]*/)
{
md5_word_t a = pms->abcd[0];
md5_word_t b = pms->abcd[1];
md5_word_t c = pms->abcd[2];
md5_word_t d = pms->abcd[3];
md5_word_t t;
#if BYTE_ORDER > 0
/* Define storage only for big-endian CPUs. */
md5_word_t X[16];
#else
/* Define storage for little-endian or both types of CPUs. */
md5_word_t xbuf[16];
const md5_word_t* X;
#endif
{
#if BYTE_ORDER == 0
/*
* Determine dynamically whether this is a big-endian or
* little-endian machine, since we can use a more efficient
* algorithm on the latter.
*/
static const int w = 1;
if (*((const md5_byte_t*)&w)) /* dynamic little-endian */
#endif
#if BYTE_ORDER <= 0 /* little-endian */
{
/*
* On little-endian machines, we can process properly aligned
* data without copying it.
*/
if (!((data - (const md5_byte_t*)0) & 3)) {
/* data are properly aligned */
X = (const md5_word_t*)data;
} else {
/* not aligned */
memcpy(xbuf, data, 64);
X = xbuf;
}
}
#endif
#if BYTE_ORDER == 0
else /* dynamic big-endian */
#endif
#if BYTE_ORDER >= 0 /* big-endian */
{
/*
* On big-endian machines, we must arrange the bytes in the
* right order.
*/
const md5_byte_t* xp = data;
int i;
# if BYTE_ORDER == 0
X = xbuf; /* (dynamic only) */
# else
# define xbuf X /* (static only) */
# endif
for (i = 0; i < 16; ++i, xp += 4) {
xbuf[i] =
(md5_word_t)(xp[0] + (xp[1] << 8) + (xp[2] << 16) + (xp[3] << 24));
}
}
#endif
}
#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32 - (n))))
/* Round 1. */
/* Let [abcd k s i] denote the operation
a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s). */
#define F(x, y, z) (((x) & (y)) | (~(x) & (z)))
#define SET(a, b, c, d, k, s, Ti) \
t = a + F(b, c, d) + X[k] + (Ti); \
a = ROTATE_LEFT(t, s) + b
/* Do the following 16 operations. */
SET(a, b, c, d, 0, 7, T1);
SET(d, a, b, c, 1, 12, T2);
SET(c, d, a, b, 2, 17, T3);
SET(b, c, d, a, 3, 22, T4);
SET(a, b, c, d, 4, 7, T5);
SET(d, a, b, c, 5, 12, T6);
SET(c, d, a, b, 6, 17, T7);
SET(b, c, d, a, 7, 22, T8);
SET(a, b, c, d, 8, 7, T9);
SET(d, a, b, c, 9, 12, T10);
SET(c, d, a, b, 10, 17, T11);
SET(b, c, d, a, 11, 22, T12);
SET(a, b, c, d, 12, 7, T13);
SET(d, a, b, c, 13, 12, T14);
SET(c, d, a, b, 14, 17, T15);
SET(b, c, d, a, 15, 22, T16);
#undef SET
/* Round 2. */
/* Let [abcd k s i] denote the operation
a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s). */
#define G(x, y, z) (((x) & (z)) | ((y) & ~(z)))
#define SET(a, b, c, d, k, s, Ti) \
t = a + G(b, c, d) + X[k] + (Ti); \
a = ROTATE_LEFT(t, s) + b
/* Do the following 16 operations. */
SET(a, b, c, d, 1, 5, T17);
SET(d, a, b, c, 6, 9, T18);
SET(c, d, a, b, 11, 14, T19);
SET(b, c, d, a, 0, 20, T20);
SET(a, b, c, d, 5, 5, T21);
SET(d, a, b, c, 10, 9, T22);
SET(c, d, a, b, 15, 14, T23);
SET(b, c, d, a, 4, 20, T24);
SET(a, b, c, d, 9, 5, T25);
SET(d, a, b, c, 14, 9, T26);
SET(c, d, a, b, 3, 14, T27);
SET(b, c, d, a, 8, 20, T28);
SET(a, b, c, d, 13, 5, T29);
SET(d, a, b, c, 2, 9, T30);
SET(c, d, a, b, 7, 14, T31);
SET(b, c, d, a, 12, 20, T32);
#undef SET
/* Round 3. */
/* Let [abcd k s t] denote the operation
a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s). */
#define H(x, y, z) ((x) ^ (y) ^ (z))
#define SET(a, b, c, d, k, s, Ti) \
t = a + H(b, c, d) + X[k] + (Ti); \
a = ROTATE_LEFT(t, s) + b
/* Do the following 16 operations. */
SET(a, b, c, d, 5, 4, T33);
SET(d, a, b, c, 8, 11, T34);
SET(c, d, a, b, 11, 16, T35);
SET(b, c, d, a, 14, 23, T36);
SET(a, b, c, d, 1, 4, T37);
SET(d, a, b, c, 4, 11, T38);
SET(c, d, a, b, 7, 16, T39);
SET(b, c, d, a, 10, 23, T40);
SET(a, b, c, d, 13, 4, T41);
SET(d, a, b, c, 0, 11, T42);
SET(c, d, a, b, 3, 16, T43);
SET(b, c, d, a, 6, 23, T44);
SET(a, b, c, d, 9, 4, T45);
SET(d, a, b, c, 12, 11, T46);
SET(c, d, a, b, 15, 16, T47);
SET(b, c, d, a, 2, 23, T48);
#undef SET
/* Round 4. */
/* Let [abcd k s t] denote the operation
a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s). */
#define I(x, y, z) ((y) ^ ((x) | ~(z)))
#define SET(a, b, c, d, k, s, Ti) \
t = a + I(b, c, d) + X[k] + (Ti); \
a = ROTATE_LEFT(t, s) + b
/* Do the following 16 operations. */
SET(a, b, c, d, 0, 6, T49);
SET(d, a, b, c, 7, 10, T50);
SET(c, d, a, b, 14, 15, T51);
SET(b, c, d, a, 5, 21, T52);
SET(a, b, c, d, 12, 6, T53);
SET(d, a, b, c, 3, 10, T54);
SET(c, d, a, b, 10, 15, T55);
SET(b, c, d, a, 1, 21, T56);
SET(a, b, c, d, 8, 6, T57);
SET(d, a, b, c, 15, 10, T58);
SET(c, d, a, b, 6, 15, T59);
SET(b, c, d, a, 13, 21, T60);
SET(a, b, c, d, 4, 6, T61);
SET(d, a, b, c, 11, 10, T62);
SET(c, d, a, b, 2, 15, T63);
SET(b, c, d, a, 9, 21, T64);
#undef SET
/* Then perform the following additions. (That is increment each
of the four registers by the value it had before this block
was started.) */
pms->abcd[0] += a;
pms->abcd[1] += b;
pms->abcd[2] += c;
pms->abcd[3] += d;
}
/* Initialize the algorithm. */
static void md5_init(md5_state_t* pms)
{
pms->count[0] = pms->count[1] = 0;
pms->abcd[0] = 0x67452301;
pms->abcd[1] = /*0xefcdab89*/ T_MASK ^ 0x10325476;
pms->abcd[2] = /*0x98badcfe*/ T_MASK ^ 0x67452301;
pms->abcd[3] = 0x10325476;
}
/* Append a string to the message. */
static void md5_append(md5_state_t* pms, const md5_byte_t* data, size_t nbytes)
{
const md5_byte_t* p = data;
size_t left = nbytes;
size_t offset = (pms->count[0] >> 3) & 63;
md5_word_t nbits = (md5_word_t)(nbytes << 3);
if (nbytes <= 0) {
return;
}
/* Update the message length. */
pms->count[1] += (md5_word_t)(nbytes >> 29);
pms->count[0] += nbits;
if (pms->count[0] < nbits) {
pms->count[1]++;
}
/* Process an initial partial block. */
if (offset) {
size_t copy = (offset + nbytes > 64 ? 64 - offset : nbytes);
memcpy(pms->buf + offset, p, copy);
if (offset + copy < 64) {
return;
}
p += copy;
left -= copy;
md5_process(pms, pms->buf);
}
/* Process full blocks. */
for (; left >= 64; p += 64, left -= 64) {
md5_process(pms, p);
}
/* Process a final partial block. */
if (left) {
memcpy(pms->buf, p, left);
}
}
/* Finish the message and return the digest. */
static void md5_finish(md5_state_t* pms, md5_byte_t digest[16])
{
static const md5_byte_t pad[64] = { 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
md5_byte_t data[8];
int i;
/* Save the length before padding. */
for (i = 0; i < 8; ++i) {
data[i] = (md5_byte_t)(pms->count[i >> 2] >> ((i & 3) << 3));
}
/* Pad to 56 bytes mod 64. */
md5_append(pms, pad, ((55 - (pms->count[0] >> 3)) & 63) + 1);
/* Append the length. */
md5_append(pms, data, 8);
for (i = 0; i < 16; ++i) {
digest[i] = (md5_byte_t)(pms->abcd[i >> 2] >> ((i & 3) << 3));
}
}
#if defined(__clang__) && !defined(__INTEL_COMPILER)
# pragma clang diagnostic pop
#endif
/* Wrap up the MD5 state in our opaque structure. */
struct kwsysMD5_s
{
md5_state_t md5_state;
};
kwsysMD5* kwsysMD5_New(void)
{
/* Allocate a process control structure. */
kwsysMD5* md5 = (kwsysMD5*)malloc(sizeof(kwsysMD5));
if (!md5) {
return 0;
}
return md5;
}
void kwsysMD5_Delete(kwsysMD5* md5)
{
/* Make sure we have an instance. */
if (!md5) {
return;
}
/* Free memory. */
free(md5);
}
void kwsysMD5_Initialize(kwsysMD5* md5)
{
md5_init(&md5->md5_state);
}
void kwsysMD5_Append(kwsysMD5* md5, unsigned char const* data, int length)
{
size_t dlen;
if (length < 0) {
dlen = strlen((char const*)data);
} else {
dlen = (size_t)length;
}
md5_append(&md5->md5_state, (md5_byte_t const*)data, dlen);
}
void kwsysMD5_Finalize(kwsysMD5* md5, unsigned char digest[16])
{
md5_finish(&md5->md5_state, (md5_byte_t*)digest);
}
void kwsysMD5_FinalizeHex(kwsysMD5* md5, char buffer[32])
{
unsigned char digest[16];
kwsysMD5_Finalize(md5, digest);
kwsysMD5_DigestToHex(digest, buffer);
}
void kwsysMD5_DigestToHex(unsigned char const digest[16], char buffer[32])
{
/* Map from 4-bit index to hexadecimal representation. */
static char const hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
/* Map each 4-bit block separately. */
char* out = buffer;
int i;
for (i = 0; i < 16; ++i) {
*out++ = hex[digest[i] >> 4];
*out++ = hex[digest[i] & 0xF];
}
}
| LucasGandel/ITK | Modules/ThirdParty/KWSys/src/KWSys/MD5.c | C | apache-2.0 | 16,195 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
package org.apache.beam.runners.core.construction;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.apache.beam.runners.core.construction.PTransformTranslation.PAR_DO_TRANSFORM_URN;
import static org.apache.beam.sdk.transforms.reflect.DoFnSignatures.getStateSpecOrThrow;
import static org.apache.beam.sdk.transforms.reflect.DoFnSignatures.getTimerSpecOrThrow;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.apache.beam.model.pipeline.v1.RunnerApi;
import org.apache.beam.model.pipeline.v1.RunnerApi.Components;
import org.apache.beam.model.pipeline.v1.RunnerApi.FunctionSpec;
import org.apache.beam.model.pipeline.v1.RunnerApi.ParDoPayload;
import org.apache.beam.model.pipeline.v1.RunnerApi.Parameter.Type;
import org.apache.beam.model.pipeline.v1.RunnerApi.SdkFunctionSpec;
import org.apache.beam.model.pipeline.v1.RunnerApi.SideInput;
import org.apache.beam.model.pipeline.v1.RunnerApi.SideInput.Builder;
import org.apache.beam.runners.core.construction.PTransformTranslation.TransformPayloadTranslator;
import org.apache.beam.runners.core.construction.PTransformTranslation.TransformTranslator;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.coders.Coder;
import org.apache.beam.sdk.coders.KvCoder;
import org.apache.beam.sdk.coders.VoidCoder;
import org.apache.beam.sdk.runners.AppliedPTransform;
import org.apache.beam.sdk.state.StateSpec;
import org.apache.beam.sdk.state.StateSpecs;
import org.apache.beam.sdk.state.TimeDomain;
import org.apache.beam.sdk.state.TimerSpec;
import org.apache.beam.sdk.transforms.Combine;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.PTransform;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.transforms.ParDo.MultiOutput;
import org.apache.beam.sdk.transforms.ViewFn;
import org.apache.beam.sdk.transforms.reflect.DoFnInvokers;
import org.apache.beam.sdk.transforms.reflect.DoFnSignature;
import org.apache.beam.sdk.transforms.reflect.DoFnSignature.Parameter;
import org.apache.beam.sdk.transforms.reflect.DoFnSignature.Parameter.Cases;
import org.apache.beam.sdk.transforms.reflect.DoFnSignature.Parameter.RestrictionTrackerParameter;
import org.apache.beam.sdk.transforms.reflect.DoFnSignature.Parameter.WindowParameter;
import org.apache.beam.sdk.transforms.reflect.DoFnSignature.StateDeclaration;
import org.apache.beam.sdk.transforms.reflect.DoFnSignature.TimerDeclaration;
import org.apache.beam.sdk.transforms.reflect.DoFnSignatures;
import org.apache.beam.sdk.transforms.windowing.WindowMappingFn;
import org.apache.beam.sdk.util.DoFnAndMainOutput;
import org.apache.beam.sdk.util.SerializableUtils;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.PCollectionView;
import org.apache.beam.sdk.values.TupleTag;
import org.apache.beam.sdk.values.TupleTagList;
import org.apache.beam.vendor.grpc.v1_13_1.com.google.protobuf.ByteString;
import org.apache.beam.vendor.grpc.v1_13_1.com.google.protobuf.InvalidProtocolBufferException;
/** Utilities for interacting with {@link ParDo} instances and {@link ParDoPayload} protos. */
public class ParDoTranslation {
/** The URN for an unknown Java {@link DoFn}. */
public static final String CUSTOM_JAVA_DO_FN_URN = "urn:beam:dofn:javasdk:0.1";
/** The URN for an unknown Java {@link ViewFn}. */
public static final String CUSTOM_JAVA_VIEW_FN_URN = "urn:beam:viewfn:javasdk:0.1";
/** The URN for an unknown Java {@link WindowMappingFn}. */
public static final String CUSTOM_JAVA_WINDOW_MAPPING_FN_URN =
"urn:beam:windowmappingfn:javasdk:0.1";
/** A {@link TransformPayloadTranslator} for {@link ParDo}. */
public static class ParDoTranslator implements TransformTranslator<MultiOutput<?, ?>> {
public static TransformTranslator create() {
return new ParDoTranslator();
}
private ParDoTranslator() {}
@Override
public String getUrn(ParDo.MultiOutput<?, ?> transform) {
return PAR_DO_TRANSFORM_URN;
}
@Override
public boolean canTranslate(PTransform<?, ?> pTransform) {
return pTransform instanceof ParDo.MultiOutput;
}
@Override
public RunnerApi.PTransform translate(
AppliedPTransform<?, ?, ?> appliedPTransform,
List<AppliedPTransform<?, ?, ?>> subtransforms,
SdkComponents components)
throws IOException {
RunnerApi.PTransform.Builder builder =
PTransformTranslation.translateAppliedPTransform(
appliedPTransform, subtransforms, components);
ParDoPayload payload =
translateParDo(
(ParDo.MultiOutput) appliedPTransform.getTransform(),
appliedPTransform.getPipeline(),
components);
builder.setSpec(
RunnerApi.FunctionSpec.newBuilder()
.setUrn(PAR_DO_TRANSFORM_URN)
.setPayload(payload.toByteString())
.build());
String mainInputName = getMainInputName(builder, payload);
PCollection<KV<?, ?>> mainInput =
(PCollection) appliedPTransform.getInputs().get(new TupleTag(mainInputName));
// https://s.apache.org/beam-portability-timers
// Add a PCollection and coder for each timer. Also treat them as inputs and outputs.
for (String localTimerName : payload.getTimerSpecsMap().keySet()) {
PCollection<?> timerPCollection =
PCollection.createPrimitiveOutputInternal(
// Create a dummy pipeline since we don't want to modify the current
// users view of the pipeline they have constructed.
Pipeline.create(),
mainInput.getWindowingStrategy(),
mainInput.isBounded(),
KvCoder.of(
((KvCoder) mainInput.getCoder()).getKeyCoder(),
// TODO: Add support for timer payloads to the SDK
// We currently assume that all payloads are unspecified.
Timer.Coder.of(VoidCoder.of())));
timerPCollection.setName(
String.format("%s.%s", appliedPTransform.getFullName(), localTimerName));
String timerPCollectionId = components.registerPCollection(timerPCollection);
builder.putInputs(localTimerName, timerPCollectionId);
builder.putOutputs(localTimerName, timerPCollectionId);
}
return builder.build();
}
}
public static ParDoPayload translateParDo(
final ParDo.MultiOutput<?, ?> parDo, Pipeline pipeline, SdkComponents components)
throws IOException {
final DoFn<?, ?> doFn = parDo.getFn();
final DoFnSignature signature = DoFnSignatures.getSignature(doFn.getClass());
final String restrictionCoderId;
if (signature.processElement().isSplittable()) {
final Coder<?> restrictionCoder =
DoFnInvokers.invokerFor(doFn).invokeGetRestrictionCoder(pipeline.getCoderRegistry());
restrictionCoderId = components.registerCoder(restrictionCoder);
} else {
restrictionCoderId = "";
}
return payloadForParDoLike(
new ParDoLike() {
@Override
public SdkFunctionSpec translateDoFn(SdkComponents newComponents) {
return ParDoTranslation.translateDoFn(
parDo.getFn(), parDo.getMainOutputTag(), newComponents);
}
@Override
public List<RunnerApi.Parameter> translateParameters() {
return ParDoTranslation.translateParameters(
signature.processElement().extraParameters());
}
@Override
public Map<String, SideInput> translateSideInputs(SdkComponents components) {
Map<String, SideInput> sideInputs = new HashMap<>();
for (PCollectionView<?> sideInput : parDo.getSideInputs()) {
sideInputs.put(
sideInput.getTagInternal().getId(), translateView(sideInput, components));
}
return sideInputs;
}
@Override
public Map<String, RunnerApi.StateSpec> translateStateSpecs(SdkComponents components)
throws IOException {
Map<String, RunnerApi.StateSpec> stateSpecs = new HashMap<>();
for (Map.Entry<String, StateDeclaration> state :
signature.stateDeclarations().entrySet()) {
RunnerApi.StateSpec spec =
translateStateSpec(getStateSpecOrThrow(state.getValue(), doFn), components);
stateSpecs.put(state.getKey(), spec);
}
return stateSpecs;
}
@Override
public Map<String, RunnerApi.TimerSpec> translateTimerSpecs(SdkComponents newComponents) {
Map<String, RunnerApi.TimerSpec> timerSpecs = new HashMap<>();
for (Map.Entry<String, TimerDeclaration> timer :
signature.timerDeclarations().entrySet()) {
RunnerApi.TimerSpec spec =
translateTimerSpec(getTimerSpecOrThrow(timer.getValue(), doFn), newComponents);
timerSpecs.put(timer.getKey(), spec);
}
return timerSpecs;
}
@Override
public boolean isSplittable() {
return signature.processElement().isSplittable();
}
@Override
public String translateRestrictionCoderId(SdkComponents newComponents) {
return restrictionCoderId;
}
},
components);
}
public static List<RunnerApi.Parameter> translateParameters(List<Parameter> params) {
List<RunnerApi.Parameter> parameters = new ArrayList<>();
for (Parameter parameter : params) {
RunnerApi.Parameter protoParameter = translateParameter(parameter);
if (protoParameter != null) {
parameters.add(protoParameter);
}
}
return parameters;
}
public static DoFn<?, ?> getDoFn(ParDoPayload payload) throws InvalidProtocolBufferException {
return doFnAndMainOutputTagFromProto(payload.getDoFn()).getDoFn();
}
public static DoFn<?, ?> getDoFn(AppliedPTransform<?, ?, ?> application) throws IOException {
PTransform<?, ?> transform = application.getTransform();
if (transform instanceof ParDo.MultiOutput) {
return ((ParDo.MultiOutput<?, ?>) transform).getFn();
}
return getDoFn(getParDoPayload(application));
}
public static TupleTag<?> getMainOutputTag(ParDoPayload payload)
throws InvalidProtocolBufferException {
return doFnAndMainOutputTagFromProto(payload.getDoFn()).getMainOutputTag();
}
public static TupleTag<?> getMainOutputTag(AppliedPTransform<?, ?, ?> application)
throws IOException {
PTransform<?, ?> transform = application.getTransform();
if (transform instanceof ParDo.MultiOutput) {
return ((ParDo.MultiOutput<?, ?>) transform).getMainOutputTag();
}
return getMainOutputTag(getParDoPayload(application));
}
public static TupleTagList getAdditionalOutputTags(AppliedPTransform<?, ?, ?> application)
throws IOException {
PTransform<?, ?> transform = application.getTransform();
if (transform instanceof ParDo.MultiOutput) {
return ((ParDo.MultiOutput<?, ?>) transform).getAdditionalOutputTags();
}
RunnerApi.PTransform protoTransform =
PTransformTranslation.toProto(
application, SdkComponents.create(application.getPipeline().getOptions()));
ParDoPayload payload = ParDoPayload.parseFrom(protoTransform.getSpec().getPayload());
TupleTag<?> mainOutputTag = getMainOutputTag(payload);
Set<String> outputTags =
Sets.difference(
protoTransform.getOutputsMap().keySet(), Collections.singleton(mainOutputTag.getId()));
ArrayList<TupleTag<?>> additionalOutputTags = new ArrayList<>();
for (String outputTag : outputTags) {
additionalOutputTags.add(new TupleTag<>(outputTag));
}
return TupleTagList.of(additionalOutputTags);
}
public static Map<TupleTag<?>, Coder<?>> getOutputCoders(AppliedPTransform<?, ?, ?> application) {
return application
.getOutputs()
.entrySet()
.stream()
.filter(e -> e.getValue() instanceof PCollection)
.collect(Collectors.toMap(e -> e.getKey(), e -> ((PCollection) e.getValue()).getCoder()));
}
public static List<PCollectionView<?>> getSideInputs(AppliedPTransform<?, ?, ?> application)
throws IOException {
PTransform<?, ?> transform = application.getTransform();
if (transform instanceof ParDo.MultiOutput) {
return ((ParDo.MultiOutput<?, ?>) transform).getSideInputs();
}
SdkComponents sdkComponents = SdkComponents.create(application.getPipeline().getOptions());
RunnerApi.PTransform parDoProto = PTransformTranslation.toProto(application, sdkComponents);
ParDoPayload payload = ParDoPayload.parseFrom(parDoProto.getSpec().getPayload());
List<PCollectionView<?>> views = new ArrayList<>();
RehydratedComponents components =
RehydratedComponents.forComponents(sdkComponents.toComponents());
for (Map.Entry<String, SideInput> sideInputEntry : payload.getSideInputsMap().entrySet()) {
String sideInputTag = sideInputEntry.getKey();
RunnerApi.SideInput sideInput = sideInputEntry.getValue();
PCollection<?> originalPCollection =
checkNotNull(
(PCollection<?>) application.getInputs().get(new TupleTag<>(sideInputTag)),
"no input with tag %s",
sideInputTag);
views.add(
PCollectionViewTranslation.viewFromProto(
sideInput, sideInputTag, originalPCollection, parDoProto, components));
}
return views;
}
public static RunnerApi.PCollection getMainInput(
RunnerApi.PTransform ptransform, Components components) throws IOException {
checkArgument(
ptransform.getSpec().getUrn().equals(PAR_DO_TRANSFORM_URN),
"Unexpected payload type %s",
ptransform.getSpec().getUrn());
return components.getPcollectionsOrThrow(
ptransform.getInputsOrThrow(getMainInputName(ptransform)));
}
/** Returns the name of the main input of the ptransform. */
public static String getMainInputName(RunnerApi.PTransformOrBuilder ptransform)
throws IOException {
checkArgument(
ptransform.getSpec().getUrn().equals(PAR_DO_TRANSFORM_URN),
"Unexpected payload type %s",
ptransform.getSpec().getUrn());
ParDoPayload payload = ParDoPayload.parseFrom(ptransform.getSpec().getPayload());
return getMainInputName(ptransform, payload);
}
/** Returns the name of the main input of the ptransform. */
private static String getMainInputName(
RunnerApi.PTransformOrBuilder ptransform, RunnerApi.ParDoPayload payload) {
return Iterables.getOnlyElement(
Sets.difference(
ptransform.getInputsMap().keySet(),
Sets.union(payload.getSideInputsMap().keySet(), payload.getTimerSpecsMap().keySet())));
}
public static RunnerApi.StateSpec translateStateSpec(
StateSpec<?> stateSpec, final SdkComponents components) throws IOException {
final RunnerApi.StateSpec.Builder builder = RunnerApi.StateSpec.newBuilder();
return stateSpec.match(
new StateSpec.Cases<RunnerApi.StateSpec>() {
@Override
public RunnerApi.StateSpec dispatchValue(Coder<?> valueCoder) {
return builder
.setValueSpec(
RunnerApi.ValueStateSpec.newBuilder()
.setCoderId(registerCoderOrThrow(components, valueCoder)))
.build();
}
@Override
public RunnerApi.StateSpec dispatchBag(Coder<?> elementCoder) {
return builder
.setBagSpec(
RunnerApi.BagStateSpec.newBuilder()
.setElementCoderId(registerCoderOrThrow(components, elementCoder)))
.build();
}
@Override
public RunnerApi.StateSpec dispatchCombining(
Combine.CombineFn<?, ?, ?> combineFn, Coder<?> accumCoder) {
return builder
.setCombiningSpec(
RunnerApi.CombiningStateSpec.newBuilder()
.setAccumulatorCoderId(registerCoderOrThrow(components, accumCoder))
.setCombineFn(CombineTranslation.toProto(combineFn, components)))
.build();
}
@Override
public RunnerApi.StateSpec dispatchMap(Coder<?> keyCoder, Coder<?> valueCoder) {
return builder
.setMapSpec(
RunnerApi.MapStateSpec.newBuilder()
.setKeyCoderId(registerCoderOrThrow(components, keyCoder))
.setValueCoderId(registerCoderOrThrow(components, valueCoder)))
.build();
}
@Override
public RunnerApi.StateSpec dispatchSet(Coder<?> elementCoder) {
return builder
.setSetSpec(
RunnerApi.SetStateSpec.newBuilder()
.setElementCoderId(registerCoderOrThrow(components, elementCoder)))
.build();
}
});
}
@VisibleForTesting
static StateSpec<?> fromProto(RunnerApi.StateSpec stateSpec, RehydratedComponents components)
throws IOException {
switch (stateSpec.getSpecCase()) {
case VALUE_SPEC:
return StateSpecs.value(components.getCoder(stateSpec.getValueSpec().getCoderId()));
case BAG_SPEC:
return StateSpecs.bag(components.getCoder(stateSpec.getBagSpec().getElementCoderId()));
case COMBINING_SPEC:
FunctionSpec combineFnSpec = stateSpec.getCombiningSpec().getCombineFn().getSpec();
if (!combineFnSpec.getUrn().equals(CombineTranslation.JAVA_SERIALIZED_COMBINE_FN_URN)) {
throw new UnsupportedOperationException(
String.format(
"Cannot create %s from non-Java %s: %s",
StateSpec.class.getSimpleName(),
Combine.CombineFn.class.getSimpleName(),
combineFnSpec.getUrn()));
}
Combine.CombineFn<?, ?, ?> combineFn =
(Combine.CombineFn<?, ?, ?>)
SerializableUtils.deserializeFromByteArray(
combineFnSpec.getPayload().toByteArray(),
Combine.CombineFn.class.getSimpleName());
// Rawtype coder cast because it is required to be a valid accumulator coder
// for the CombineFn, by construction
return StateSpecs.combining(
(Coder) components.getCoder(stateSpec.getCombiningSpec().getAccumulatorCoderId()),
combineFn);
case MAP_SPEC:
return StateSpecs.map(
components.getCoder(stateSpec.getMapSpec().getKeyCoderId()),
components.getCoder(stateSpec.getMapSpec().getValueCoderId()));
case SET_SPEC:
return StateSpecs.set(components.getCoder(stateSpec.getSetSpec().getElementCoderId()));
case SPEC_NOT_SET:
default:
throw new IllegalArgumentException(
String.format("Unknown %s: %s", RunnerApi.StateSpec.class.getName(), stateSpec));
}
}
private static String registerCoderOrThrow(SdkComponents components, Coder coder) {
try {
return components.registerCoder(coder);
} catch (IOException exc) {
throw new RuntimeException("Failure to register coder", exc);
}
}
public static RunnerApi.TimerSpec translateTimerSpec(TimerSpec timer, SdkComponents components) {
return RunnerApi.TimerSpec.newBuilder()
.setTimeDomain(translateTimeDomain(timer.getTimeDomain()))
// TODO: Add support for timer payloads to the SDK
// We currently assume that all payloads are unspecified.
.setTimerCoderId(registerCoderOrThrow(components, Timer.Coder.of(VoidCoder.of())))
.build();
}
private static RunnerApi.TimeDomain.Enum translateTimeDomain(TimeDomain timeDomain) {
switch (timeDomain) {
case EVENT_TIME:
return RunnerApi.TimeDomain.Enum.EVENT_TIME;
case PROCESSING_TIME:
return RunnerApi.TimeDomain.Enum.PROCESSING_TIME;
case SYNCHRONIZED_PROCESSING_TIME:
return RunnerApi.TimeDomain.Enum.SYNCHRONIZED_PROCESSING_TIME;
default:
throw new IllegalArgumentException("Unknown time domain");
}
}
public static SdkFunctionSpec translateDoFn(
DoFn<?, ?> fn, TupleTag<?> tag, SdkComponents components) {
return SdkFunctionSpec.newBuilder()
.setEnvironmentId(components.getOnlyEnvironmentId())
.setSpec(
FunctionSpec.newBuilder()
.setUrn(CUSTOM_JAVA_DO_FN_URN)
.setPayload(
ByteString.copyFrom(
SerializableUtils.serializeToByteArray(DoFnAndMainOutput.of(fn, tag))))
.build())
.build();
}
public static DoFnAndMainOutput doFnAndMainOutputTagFromProto(SdkFunctionSpec fnSpec) {
checkArgument(
fnSpec.getSpec().getUrn().equals(CUSTOM_JAVA_DO_FN_URN),
"Expected %s to be %s with URN %s, but URN was %s",
DoFn.class.getSimpleName(),
FunctionSpec.class.getSimpleName(),
CUSTOM_JAVA_DO_FN_URN,
fnSpec.getSpec().getUrn());
byte[] serializedFn = fnSpec.getSpec().getPayload().toByteArray();
return (DoFnAndMainOutput)
SerializableUtils.deserializeFromByteArray(serializedFn, "Custom DoFn And Main Output tag");
}
/**
* Translates a Java DoFn parameter to a proto representation.
*
* <p>Returns {@code null} rather than crashing for parameters that are not yet supported, to
* allow legacy Java-based runners to perform a proto round-trip and afterwards use {@link
* DoFnSignatures} to analyze.
*
* <p>The proto definition for parameters is provisional and those parameters that are not needed
* for portability will be removed from the enum.
*/
// Using nullability instead of optional because of shading
public static @Nullable RunnerApi.Parameter translateParameter(Parameter parameter) {
return parameter.match(
new Cases.WithDefault</* @Nullable in Java 8 */ RunnerApi.Parameter>() {
@Override
public RunnerApi.Parameter dispatch(WindowParameter p) {
return RunnerApi.Parameter.newBuilder().setType(Type.Enum.WINDOW).build();
}
@Override
public RunnerApi.Parameter dispatch(RestrictionTrackerParameter p) {
return RunnerApi.Parameter.newBuilder().setType(Type.Enum.RESTRICTION_TRACKER).build();
}
@Override
// Java 7 + findbugs limitation. The return type is nullable.
protected @Nullable RunnerApi.Parameter dispatchDefault(Parameter p) {
return null;
}
});
}
public static Map<String, SideInput> translateSideInputs(
List<PCollectionView<?>> views, SdkComponents components) {
Map<String, SideInput> sideInputs = new HashMap<>();
for (PCollectionView<?> sideInput : views) {
sideInputs.put(
sideInput.getTagInternal().getId(),
ParDoTranslation.translateView(sideInput, components));
}
return sideInputs;
}
public static SideInput translateView(PCollectionView<?> view, SdkComponents components) {
Builder builder = SideInput.newBuilder();
builder.setAccessPattern(
FunctionSpec.newBuilder().setUrn(view.getViewFn().getMaterialization().getUrn()).build());
builder.setViewFn(translateViewFn(view.getViewFn(), components));
builder.setWindowMappingFn(translateWindowMappingFn(view.getWindowMappingFn(), components));
return builder.build();
}
public static SdkFunctionSpec translateViewFn(ViewFn<?, ?> viewFn, SdkComponents components) {
return SdkFunctionSpec.newBuilder()
.setEnvironmentId(components.getOnlyEnvironmentId())
.setSpec(
FunctionSpec.newBuilder()
.setUrn(CUSTOM_JAVA_VIEW_FN_URN)
.setPayload(ByteString.copyFrom(SerializableUtils.serializeToByteArray(viewFn)))
.build())
.build();
}
private static <T> ParDoPayload getParDoPayload(AppliedPTransform<?, ?, ?> transform)
throws IOException {
SdkComponents components = SdkComponents.create(transform.getPipeline().getOptions());
RunnerApi.PTransform parDoPTransform =
PTransformTranslation.toProto(transform, Collections.emptyList(), components);
return ParDoPayload.parseFrom(parDoPTransform.getSpec().getPayload());
}
public static boolean usesStateOrTimers(AppliedPTransform<?, ?, ?> transform) throws IOException {
ParDoPayload payload = getParDoPayload(transform);
return payload.getStateSpecsCount() > 0 || payload.getTimerSpecsCount() > 0;
}
public static boolean isSplittable(AppliedPTransform<?, ?, ?> transform) throws IOException {
ParDoPayload payload = getParDoPayload(transform);
return payload.getSplittable();
}
public static SdkFunctionSpec translateWindowMappingFn(
WindowMappingFn<?> windowMappingFn, SdkComponents components) {
return SdkFunctionSpec.newBuilder()
.setEnvironmentId(components.getOnlyEnvironmentId())
.setSpec(
FunctionSpec.newBuilder()
.setUrn(CUSTOM_JAVA_WINDOW_MAPPING_FN_URN)
.setPayload(
ByteString.copyFrom(SerializableUtils.serializeToByteArray(windowMappingFn)))
.build())
.build();
}
/** These methods drive to-proto translation from Java and from rehydrated ParDos. */
public interface ParDoLike {
SdkFunctionSpec translateDoFn(SdkComponents newComponents);
List<RunnerApi.Parameter> translateParameters();
Map<String, RunnerApi.SideInput> translateSideInputs(SdkComponents components);
Map<String, RunnerApi.StateSpec> translateStateSpecs(SdkComponents components)
throws IOException;
Map<String, RunnerApi.TimerSpec> translateTimerSpecs(SdkComponents newComponents);
boolean isSplittable();
String translateRestrictionCoderId(SdkComponents newComponents);
}
public static ParDoPayload payloadForParDoLike(ParDoLike parDo, SdkComponents components)
throws IOException {
return ParDoPayload.newBuilder()
.setDoFn(parDo.translateDoFn(components))
.addAllParameters(parDo.translateParameters())
.putAllStateSpecs(parDo.translateStateSpecs(components))
.putAllTimerSpecs(parDo.translateTimerSpecs(components))
.putAllSideInputs(parDo.translateSideInputs(components))
.setSplittable(parDo.isSplittable())
.setRestrictionCoderId(parDo.translateRestrictionCoderId(components))
.build();
}
}
| mxm/incubator-beam | runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/ParDoTranslation.java | Java | apache-2.0 | 28,033 |
---
title: Jesus College MCR (Private)
superTitle: This is where you
subTitle: for Jesus MCR events and services
layout: private
---
<!-- Navigation -->
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header page-scroll">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand page-scroll" href="#page-top">{{site.title}}</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li class="hidden">
<a href="#page-top"></a>
</li>
<li>
<a class="page-scroll" href="#services">Sign Ups</a>
</li>
<li>
<a class="page-scroll" href="#calendar_nav">Calendar</a>
</li>
<li>
<a class="page-scroll" href="#team">Team</a>
</li>
<li>
<a class="page-scroll" href="#freshers">Freshers FAQ</a>
</li>
<li>
<a class="page-scroll" href="#documents">Documents</a>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container-fluid -->
</nav>
<!-- Header -->
<header>
<div class="container">
<div class="intro-text">
<div class="intro-lead-in">Welcome to current students of the</div>
<div class="intro-heading">Jesus College MCR</div>
<a href="#servicesModal2" class="page-scroll btn btn-xl" data-toggle="modal">Book the Punt</a>
</br></br>
<a href="../mcrwiki/index.php" class="page-scroll btn btn-xl">MCR Wiki</a>
</br></br>
<a href="../index.html" class="page-scroll btn btn-xl">Public Page</a>
</div>
</div>
</header>
<!--
{% for page in site.pages %}
{% if page.title %}<a class="page-link" href="{{ page.url | prepend: site.baseurl }}">{{ page.title }}</a>{% endif %}
{% endfor %}
-->
<!-- Grid Section -->
<section id="services" class="bg-light-gray">
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<h2 class="section-heading">Sign Ups</h2>
<h3 class="section-subheading text-muted">Get Involved!</h3>
</div>
</div>
<div class="row">
{% for post in site.categories.signups %}
<div class="col-md-4 col-sm-6 services-item">
<a href="#servicesModal{{ post.modal-id }}" class="services-link" data-toggle="modal">
<div class="services-hover">
<div class="services-hover-content">
<i class="fa fa-plus fa-3x"></i>
</div>
</div>
<img src="{{ site.baseurl }}img/services/{{ post.thumbnail }}" class="img-responsive" alt="" width="400">
</a>
<div class="services-caption">
<h4>{{ post.title }}</h4>
<p class="text-muted">{{ post.subtitle }}</p>
</div>
</div>
{% endfor %}
</div>
</div>
</section>
{% include calendar.html %}
{% include fellows.html %}
{% include team.html %}
{% include freshers.html %}
{% include documents.html %}
| JCMCR/JesusMCRsite | private/index.html | HTML | apache-2.0 | 4,159 |
require 'spec_helper'
describe Capistrano::DSL do
let(:dsl) { Class.new.extend Capistrano::DSL }
before do
Capistrano::Configuration.reset!
end
describe 'setting and fetching hosts' do
describe 'when defining a host using the `server` syntax' do
before do
dsl.server 'example1.com', roles: %w{web}, active: true
dsl.server 'example2.com', roles: %w{web}
dsl.server 'example3.com', roles: %w{app web}, active: true
dsl.server 'example4.com', roles: %w{app}, primary: true
dsl.server 'example5.com', roles: %w{db}, no_release: true, active:true
end
describe 'fetching all servers' do
subject { dsl.roles(:all) }
it 'returns all servers' do
expect(subject.map(&:hostname)).to eq %w{example1.com example2.com example3.com example4.com example5.com}
end
end
describe 'fetching all release servers' do
context 'with no additional options' do
subject { dsl.release_roles(:all) }
it 'returns all release servers' do
expect(subject.map(&:hostname)).to eq %w{example1.com example2.com example3.com example4.com}
end
end
context 'with property filter options' do
subject { dsl.release_roles(:all, filter: :active) }
it 'returns all release servers that match the property filter' do
expect(subject.map(&:hostname)).to eq %w{example1.com example3.com}
end
end
end
describe 'fetching servers by multiple roles' do
it "does not confuse the last role with options" do
expect(dsl.roles(:app, :web).count).to eq 4
expect(dsl.roles(:app, :web, filter: :active).count).to eq 2
end
end
describe 'fetching servers by role' do
subject { dsl.roles(:app) }
it 'returns the servers' do
expect(subject.map(&:hostname)).to eq %w{example3.com example4.com}
end
end
describe 'fetching servers by an array of roles' do
subject { dsl.roles([:app]) }
it 'returns the servers' do
expect(subject.map(&:hostname)).to eq %w{example3.com example4.com}
end
end
describe 'fetching filtered servers by role' do
subject { dsl.roles(:app, filter: :active) }
it 'returns the servers' do
expect(subject.map(&:hostname)).to eq %w{example3.com}
end
end
describe 'fetching selected servers by role' do
subject { dsl.roles(:app, select: :active) }
it 'returns the servers' do
expect(subject.map(&:hostname)).to eq %w{example3.com}
end
end
describe 'fetching the primary server by role' do
context 'when inferring primary status based on order' do
subject { dsl.primary(:web) }
it 'returns the servers' do
expect(subject.hostname).to eq 'example1.com'
end
end
context 'when the attribute `primary` is explicitly set' do
subject { dsl.primary(:app) }
it 'returns the servers' do
expect(subject.hostname).to eq 'example4.com'
end
end
end
describe 'setting an internal host filter' do
subject { dsl.roles(:app) }
it 'is ignored' do
dsl.set :filter, { host: 'example3.com' }
expect(subject.map(&:hostname)).to eq(['example3.com', 'example4.com'])
end
end
describe 'setting an internal role filter' do
subject { dsl.roles(:app) }
it 'ignores it' do
dsl.set :filter, { role: :web }
expect(subject.map(&:hostname)).to eq(['example3.com','example4.com'])
end
end
describe 'setting an internal host and role filter' do
subject { dsl.roles(:app) }
it 'ignores it' do
dsl.set :filter, { role: :web, host: 'example1.com' }
expect(subject.map(&:hostname)).to eq(['example3.com','example4.com'])
end
end
describe 'setting an internal regexp host filter' do
subject { dsl.roles(:all) }
it 'is ignored' do
dsl.set :filter, { host: /1/ }
expect(subject.map(&:hostname)).to eq(%w{example1.com example2.com example3.com example4.com example5.com})
end
end
end
describe 'when defining role with reserved name' do
it 'fails with ArgumentError' do
expect {
dsl.role :all, %w{example1.com}
}.to raise_error(ArgumentError, "all reserved name for role. Please choose another name")
end
end
describe 'when defining hosts using the `role` syntax' do
before do
dsl.role :web, %w{example1.com example2.com example3.com}
dsl.role :web, %w{example1.com}, active: true
dsl.role :app, %w{example3.com example4.com}
dsl.role :app, %w{example3.com}, active: true
dsl.role :app, %w{example4.com}, primary: true
dsl.role :db, %w{example5.com}, no_release: true
end
describe 'fetching all servers' do
subject { dsl.roles(:all) }
it 'returns all servers' do
expect(subject.map(&:hostname)).to eq %w{example1.com example2.com example3.com example4.com example5.com}
end
end
describe 'fetching all release servers' do
context 'with no additional options' do
subject { dsl.release_roles(:all) }
it 'returns all release servers' do
expect(subject.map(&:hostname)).to eq %w{example1.com example2.com example3.com example4.com}
end
end
context 'with filter options' do
subject { dsl.release_roles(:all, filter: :active) }
it 'returns all release servers that match the filter' do
expect(subject.map(&:hostname)).to eq %w{example1.com example3.com}
end
end
end
describe 'fetching servers by role' do
subject { dsl.roles(:app) }
it 'returns the servers' do
expect(subject.map(&:hostname)).to eq %w{example3.com example4.com}
end
end
describe 'fetching servers by an array of roles' do
subject { dsl.roles([:app]) }
it 'returns the servers' do
expect(subject.map(&:hostname)).to eq %w{example3.com example4.com}
end
end
describe 'fetching filtered servers by role' do
subject { dsl.roles(:app, filter: :active) }
it 'returns the servers' do
expect(subject.map(&:hostname)).to eq %w{example3.com}
end
end
describe 'fetching selected servers by role' do
subject { dsl.roles(:app, select: :active) }
it 'returns the servers' do
expect(subject.map(&:hostname)).to eq %w{example3.com}
end
end
describe 'fetching the primary server by role' do
context 'when inferring primary status based on order' do
subject { dsl.primary(:web) }
it 'returns the servers' do
expect(subject.hostname).to eq 'example1.com'
end
end
context 'when the attribute `primary` is explicity set' do
subject { dsl.primary(:app) }
it 'returns the servers' do
expect(subject.hostname).to eq 'example4.com'
end
end
end
end
describe 'when defining a host using a combination of the `server` and `role` syntax' do
before do
dsl.server 'db@example1.com:1234', roles: %w{db}, active: true
dsl.server 'root@example1.com:1234', roles: %w{web}, active: true
dsl.server 'example1.com:5678', roles: %w{web}, active: true
dsl.role :app, %w{deployer@example1.com:1234}
dsl.role :app, %w{example1.com:5678}
end
describe 'fetching all servers' do
it 'creates one server per hostname, ignoring user and port combinations' do
expect(dsl.roles(:all).size).to eq(1)
end
end
describe 'fetching servers for a role' do
it 'roles defined using the `server` syntax are included' do
as = dsl.roles(:web).map { |server| "#{server.user}@#{server.hostname}:#{server.port}" }
expect(as.size).to eq(1)
expect(as[0]).to eq("deployer@example1.com:5678")
end
it 'roles defined using the `role` syntax are included' do
as = dsl.roles(:app).map { |server| "#{server.user}@#{server.hostname}:#{server.port}" }
expect(as.size).to eq(1)
expect(as[0]).to eq("deployer@example1.com:5678")
end
end
end
describe 'when setting user and port' do
subject { dsl.roles(:all).map { |server| "#{server.user}@#{server.hostname}:#{server.port}" }.first }
describe "using the :user property" do
it "takes precedence over in the host string" do
dsl.server 'db@example1.com:1234', roles: %w{db}, active: true, user: 'brian'
expect(subject).to eq("brian@example1.com:1234")
end
end
describe "using the :port property" do
it "takes precedence over in the host string" do
dsl.server 'db@example1.com:9090', roles: %w{db}, active: true, port: 1234
expect(subject).to eq("db@example1.com:1234")
end
end
end
end
describe 'setting and fetching variables' do
before do
dsl.set :scm, :git
end
context 'without a default' do
context 'when the variables is defined' do
it 'returns the variable' do
expect(dsl.fetch(:scm)).to eq :git
end
end
context 'when the variables is undefined' do
it 'returns nil' do
expect(dsl.fetch(:source_control)).to be_nil
end
end
end
context 'with a default' do
context 'when the variables is defined' do
it 'returns the variable' do
expect(dsl.fetch(:scm, :svn)).to eq :git
end
end
context 'when the variables is undefined' do
it 'returns the default' do
expect(dsl.fetch(:source_control, :svn)).to eq :svn
end
end
end
context 'with a block' do
context 'when the variables is defined' do
it 'returns the variable' do
expect(dsl.fetch(:scm) { :svn }).to eq :git
end
end
context 'when the variables is undefined' do
it 'calls the block' do
expect(dsl.fetch(:source_control) { :svn }).to eq :svn
end
end
end
end
describe 'asking for a variable' do
before do
dsl.ask(:scm, :svn)
$stdout.stubs(:print)
end
context 'variable is provided' do
before do
$stdin.expects(:gets).returns('git')
end
it 'sets the input as the variable' do
expect(dsl.fetch(:scm)).to eq 'git'
end
end
context 'variable is not provided' do
before do
$stdin.expects(:gets).returns('')
end
it 'sets the variable as the default' do
expect(dsl.fetch(:scm)).to eq :svn
end
end
end
describe 'checking for presence' do
subject { dsl.any? :linked_files }
before do
dsl.set(:linked_files, linked_files)
end
context 'variable is an non-empty array' do
let(:linked_files) { %w{1} }
it { expect(subject).to be_truthy }
end
context 'variable is an empty array' do
let(:linked_files) { [] }
it { expect(subject).to be_falsey }
end
context 'variable exists, is not an array' do
let(:linked_files) { stub }
it { expect(subject).to be_truthy }
end
context 'variable is nil' do
let(:linked_files) { nil }
it { expect(subject).to be_falsey }
end
end
describe 'configuration SSHKit' do
let(:config) { SSHKit.config }
let(:backend) { SSHKit.config.backend.config }
let(:default_env) { { rails_env: :production } }
before do
dsl.set(:format, :dot)
dsl.set(:log_level, :debug)
dsl.set(:default_env, default_env)
dsl.set(:pty, true)
dsl.set(:connection_timeout, 10)
dsl.set(:ssh_options, {
keys: %w(/home/user/.ssh/id_rsa),
forward_agent: false,
auth_methods: %w(publickey password)
})
dsl.configure_backend
end
it 'sets the output' do
expect(config.output).to be_a SSHKit::Formatter::Dot
end
it 'sets the output verbosity' do
expect(config.output_verbosity).to eq 0
end
it 'sets the default env' do
expect(config.default_env).to eq default_env
end
it 'sets the backend pty' do
expect(backend.pty).to be_truthy
end
it 'sets the backend connection timeout' do
expect(backend.connection_timeout).to eq 10
end
it 'sets the backend ssh_options' do
expect(backend.ssh_options[:keys]).to eq %w(/home/user/.ssh/id_rsa)
expect(backend.ssh_options[:forward_agent]).to eq false
expect(backend.ssh_options[:auth_methods]).to eq %w(publickey password)
end
end
describe 'local_user' do
before do
dsl.set :local_user, -> { Etc.getlogin }
end
describe 'fetching local_user' do
subject { dsl.local_user }
context 'where a local_user is not set' do
before do
Etc.expects(:getlogin).returns('login')
end
it 'returns the login name' do
expect(subject.to_s).to eq 'login'
end
end
context 'where a local_user is set' do
before do
dsl.set(:local_user, -> { 'custom login' })
end
it 'returns the custom name' do
expect(subject.to_s).to eq 'custom login'
end
end
end
end
describe 'on()' do
before do
dsl.server 'example1.com', roles: %w{web}, active: true
dsl.server 'example2.com', roles: %w{web}
dsl.server 'example3.com', roles: %w{app web}, active: true
dsl.server 'example4.com', roles: %w{app}, primary: true
dsl.server 'example5.com', roles: %w{db}, no_release: true
@coordinator = mock('coordinator')
@coordinator.expects(:each).returns(nil)
ENV.delete 'ROLES'
ENV.delete 'HOSTS'
end
it 'filters by role from the :filter variable' do
hosts = dsl.roles(:web)
all = dsl.roles(:all)
SSHKit::Coordinator.expects(:new).with(hosts).returns(@coordinator)
dsl.set :filter, { role: 'web' }
dsl.on(all)
end
it 'filters by host and role from the :filter variable' do
all = dsl.roles(:all)
SSHKit::Coordinator.expects(:new).with([]).returns(@coordinator)
dsl.set :filter, { role: 'db', host: 'example3.com' }
dsl.on(all)
end
it 'filters from ENV[ROLES]' do
hosts = dsl.roles(:db)
all = dsl.roles(:all)
SSHKit::Coordinator.expects(:new).with(hosts).returns(@coordinator)
ENV['ROLES'] = 'db'
dsl.on(all)
end
it 'filters from ENV[HOSTS]' do
hosts = dsl.roles(:db)
all = dsl.roles(:all)
SSHKit::Coordinator.expects(:new).with(hosts).returns(@coordinator)
ENV['HOSTS'] = 'example5.com'
dsl.on(all)
end
it 'filters by ENV[HOSTS] && ENV[ROLES]' do
all = dsl.roles(:all)
SSHKit::Coordinator.expects(:new).with([]).returns(@coordinator)
ENV['HOSTS'] = 'example5.com'
ENV['ROLES'] = 'web'
dsl.on(all)
end
end
describe 'role_properties()' do
before do
dsl.role :redis, %w[example1.com example2.com], redis: { port: 6379, type: :slave }
dsl.server 'example1.com', roles: %w{web}, active: true, web: { port: 80 }
dsl.server 'example2.com', roles: %w{web redis}, web: { port: 81 }, redis: { type: :master }
dsl.server 'example3.com', roles: %w{app}, primary: true
end
it 'retrieves properties for a single role as a set' do
rps = dsl.role_properties(:app)
expect(rps).to eq(Set[{ hostname: 'example3.com', role: :app}])
end
it 'retrieves properties for multiple roles as a set' do
rps = dsl.role_properties(:app, :web)
expect(rps).to eq(Set[{ hostname: 'example3.com', role: :app},{ hostname: 'example1.com', role: :web, port: 80},{ hostname: 'example2.com', role: :web, port: 81}])
end
it 'yields the properties for a single role' do
recipient = mock('recipient')
recipient.expects(:doit).with('example1.com', :redis, { port: 6379, type: :slave})
recipient.expects(:doit).with('example2.com', :redis, { port: 6379, type: :master})
dsl.role_properties(:redis) do |host, role, props|
recipient.doit(host, role, props)
end
end
it 'yields the properties for multiple roles' do
recipient = mock('recipient')
recipient.expects(:doit).with('example1.com', :redis, { port: 6379, type: :slave})
recipient.expects(:doit).with('example2.com', :redis, { port: 6379, type: :master})
recipient.expects(:doit).with('example3.com', :app, nil)
dsl.role_properties(:redis, :app) do |host, role, props|
recipient.doit(host, role, props)
end
end
it 'yields the merged properties for multiple roles' do
recipient = mock('recipient')
recipient.expects(:doit).with('example1.com', :redis, { port: 6379, type: :slave})
recipient.expects(:doit).with('example2.com', :redis, { port: 6379, type: :master})
recipient.expects(:doit).with('example1.com', :web, { port: 80 })
recipient.expects(:doit).with('example2.com', :web, { port: 81 })
dsl.role_properties(:redis, :web) do |host, role, props|
recipient.doit(host, role, props)
end
end
it 'honours a property filter before yielding' do
recipient = mock('recipient')
recipient.expects(:doit).with('example1.com', :redis, { port: 6379, type: :slave})
recipient.expects(:doit).with('example1.com', :web, { port: 80 })
dsl.role_properties(:redis, :web, select: :active) do |host, role, props|
recipient.doit(host, role, props)
end
end
end
end
| Coolnesss/Coordinates | vendor/cache/ruby/2.2.0/gems/capistrano-3.4.0/spec/integration/dsl_spec.rb | Ruby | apache-2.0 | 18,027 |
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test which of the builtin types are considered sendable. The tests
// in this file all test region bound and lifetime violations that are
// detected during type check.
fn assert_send<T:Send>() { }
trait Dummy { }
// lifetime pointers with 'static lifetime are ok
fn static_lifime_ok<'a,T,U:Send>(_: &'a int) {
assert_send::<&'static int>();
assert_send::<&'static str>();
assert_send::<&'static [int]>();
// whether or not they are mutable
assert_send::<&'static mut int>();
}
// otherwise lifetime pointers are not ok
fn param_not_ok<'a>(x: &'a int) {
assert_send::<&'a int>(); //~ ERROR does not fulfill
}
fn param_not_ok1<'a>(_: &'a int) {
assert_send::<&'a str>(); //~ ERROR does not fulfill
}
fn param_not_ok2<'a>(_: &'a int) {
assert_send::<&'a [int]>(); //~ ERROR does not fulfill
}
// boxes are ok
fn box_ok() {
assert_send::<Box<int>>();
assert_send::<String>();
assert_send::<Vec<int>>();
}
// but not if they own a bad thing
fn box_with_region_not_ok<'a>() {
assert_send::<Box<&'a int>>(); //~ ERROR does not fulfill
}
// objects with insufficient bounds no ok
fn object_with_random_bound_not_ok<'a>() {
assert_send::<&'a (Dummy+'a)>();
//~^ ERROR not implemented
}
fn object_with_send_bound_not_ok<'a>() {
assert_send::<&'a (Dummy+Send)>();
//~^ ERROR does not fulfill
}
fn proc_with_lifetime_not_ok<'a>() {
assert_send::<proc():'a>();
//~^ ERROR not implemented
}
fn closure_with_lifetime_not_ok<'a>() {
assert_send::<||:'a>();
//~^ ERROR not implemented
}
// unsafe pointers are ok unless they point at unsendable things
fn unsafe_ok1<'a>(_: &'a int) {
assert_send::<*const int>();
assert_send::<*mut int>();
}
fn unsafe_ok2<'a>(_: &'a int) {
assert_send::<*const &'a int>(); //~ ERROR does not fulfill
}
fn unsafe_ok3<'a>(_: &'a int) {
assert_send::<*mut &'a int>(); //~ ERROR does not fulfill
}
fn main() {
}
| emk/rust | src/test/compile-fail/regions-bounded-by-send.rs | Rust | apache-2.0 | 2,414 |
/* $Id: QueryRetrieveScpService.java 1004 2004-02-21 22:32:43Z gunterze $
* Copyright (c) 2002,2003 by TIANI MEDGRAPH AG
*
* This file is part of dcm4che.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.dcm4chex.service;
import java.beans.PropertyEditor;
import javax.management.ObjectName;
import javax.sql.DataSource;
import org.dcm4che.dict.UIDs;
import org.dcm4che.net.AcceptorPolicy;
import org.dcm4che.net.DcmServiceRegistry;
import org.dcm4chex.service.util.AETsEditor;
import org.dcm4chex.service.util.ConfigurationException;
/**
* @jmx.mbean
* extends="org.jboss.system.ServiceMBean"
*
* @author Gunter.Zeilinger@tiani.com
* @version $Revision: 1004 $ $Date: 2004-02-22 06:32:43 +0800 (周日, 22 2月 2004) $
* @since 31.08.2003
*/
public class QueryRetrieveScpService
extends AbstractScpService
implements org.dcm4chex.service.QueryRetrieveScpServiceMBean
{
private DataSourceFactory dsf = new DataSourceFactory(log);
private FindScp findScp = new FindScp(this);
private MoveScp moveScp = new MoveScp(this);
private String[] callingAETs;
private boolean sendPendingMoveRSP = true;
private boolean retrieveLastReceived = true;
private int acTimeout = 5000;
private String patientRootFind;
private String studyRootFind;
private String patientStudyOnlyFind;
private String patientRootMove;
private String studyRootMove;
private String patientStudyOnlyMove;
/**
* @jmx.managed-attribute
*/
public ObjectName getDcmServerName()
{
return dcmServerName;
}
/**
* @jmx.managed-attribute
*/
public void setDcmServerName(ObjectName dcmServerName)
{
this.dcmServerName = dcmServerName;
}
DataSource getDS() throws ConfigurationException
{
return dsf.getDataSource();
}
/**
* @jmx.managed-attribute
*/
public String getDataSource()
{
return dsf.getJNDIName();
}
/**
* @jmx.managed-attribute
*/
public void setDataSource(String jndiName)
{
dsf.setJNDIName(jndiName);
}
/**
* @jmx.managed-attribute
*/
public String getCallingAETs()
{
PropertyEditor pe = new AETsEditor();
pe.setValue(callingAETs);
return pe.getAsText();
}
/**
* @jmx.managed-attribute
*/
public void setCallingAETs(String newCallingAETs)
{
PropertyEditor pe = new AETsEditor();
pe.setAsText(newCallingAETs);
callingAETs = (String[]) pe.getValue();
if (getState() == STARTED)
{
updatePolicy();
}
}
/**
* @jmx.managed-attribute
*/
public final String getPatientRootFind()
{
return patientRootFind;
}
/**
* @jmx.managed-attribute
*/
public final void setPatientRootFind(String patientRootFind)
{
this.patientRootFind = patientRootFind;
if (getState() == STARTED)
{
updatePolicy();
}
}
/**
* @jmx.managed-attribute
*/
public final String getPatientRootMove()
{
return patientRootMove;
}
/**
* @jmx.managed-attribute
*/
public final void setPatientRootMove(String patientRootMove)
{
this.patientRootMove = patientRootMove;
if (getState() == STARTED)
{
updatePolicy();
}
}
/**
* @jmx.managed-attribute
*/
public final String getPatientStudyOnlyFind()
{
return patientStudyOnlyFind;
}
/**
* @jmx.managed-attribute
*/
public final void setPatientStudyOnlyFind(String patientStudyOnlyFind)
{
this.patientStudyOnlyFind = patientStudyOnlyFind;
if (getState() == STARTED)
{
updatePolicy();
}
}
/**
* @jmx.managed-attribute
*/
public final String getPatientStudyOnlyMove()
{
return patientStudyOnlyMove;
}
/**
* @jmx.managed-attribute
*/
public final void setPatientStudyOnlyMove(String patientStudyOnlyMove)
{
this.patientStudyOnlyMove = patientStudyOnlyMove;
if (getState() == STARTED)
{
updatePolicy();
}
}
/**
* @jmx.managed-attribute
*/
public final String getStudyRootFind()
{
return studyRootFind;
}
/**
* @jmx.managed-attribute
*/
public final void setStudyRootFind(String studyRootFind)
{
this.studyRootFind = studyRootFind;
if (getState() == STARTED)
{
updatePolicy();
}
}
/**
* @jmx.managed-attribute
*/
public final String getStudyRootMove()
{
return studyRootMove;
}
/**
* @jmx.managed-attribute
*/
public final void setStudyRootMove(String studyRootMove)
{
this.studyRootMove = studyRootMove;
if (getState() == STARTED)
{
updatePolicy();
}
}
/**
* @jmx.managed-attribute
*/
public final int getAcTimeout() {
return acTimeout;
}
/**
* @jmx.managed-attribute
*/
public final void setAcTimeout(int acTimeout) {
this.acTimeout = acTimeout;
}
/**
* @jmx.managed-attribute
*/
public final boolean isSendPendingMoveRSP() {
return sendPendingMoveRSP;
}
/**
* @jmx.managed-attribute
*/
public final void setSendPendingMoveRSP(boolean sendPendingMoveRSP) {
this.sendPendingMoveRSP = sendPendingMoveRSP;
}
/**
* @jmx.managed-attribute
*/
public final boolean isRetrieveLastReceived() {
return retrieveLastReceived;
}
/**
* @jmx.managed-attribute
*/
public final void setRetrieveLastReceived(boolean retrieveLastReceived) {
this.retrieveLastReceived = retrieveLastReceived;
}
protected void bindDcmServices(DcmServiceRegistry services)
{
services.bind(
UIDs.PatientRootQueryRetrieveInformationModelFIND,
findScp);
services.bind(UIDs.StudyRootQueryRetrieveInformationModelFIND, findScp);
services.bind(
UIDs.PatientStudyOnlyQueryRetrieveInformationModelFIND,
findScp);
services.bind(
UIDs.PatientRootQueryRetrieveInformationModelMOVE,
moveScp);
services.bind(UIDs.StudyRootQueryRetrieveInformationModelMOVE, moveScp);
services.bind(
UIDs.PatientStudyOnlyQueryRetrieveInformationModelMOVE,
moveScp);
}
protected void unbindDcmServices(DcmServiceRegistry services)
{
services.unbind(UIDs.PatientRootQueryRetrieveInformationModelFIND);
services.unbind(UIDs.StudyRootQueryRetrieveInformationModelFIND);
services.unbind(UIDs.PatientStudyOnlyQueryRetrieveInformationModelFIND);
services.unbind(UIDs.PatientRootQueryRetrieveInformationModelFIND);
services.unbind(UIDs.StudyRootQueryRetrieveInformationModelFIND);
services.unbind(UIDs.PatientStudyOnlyQueryRetrieveInformationModelFIND);
}
protected AcceptorPolicy getAcceptorPolicy()
{
AcceptorPolicy policy = asf.newAcceptorPolicy();
policy.setCallingAETs(callingAETs);
putPresContext(
policy,
UIDs.PatientRootQueryRetrieveInformationModelFIND,
patientRootFind);
putPresContext(
policy,
UIDs.StudyRootQueryRetrieveInformationModelFIND,
studyRootFind);
putPresContext(
policy,
UIDs.PatientStudyOnlyQueryRetrieveInformationModelFIND,
patientStudyOnlyFind);
putPresContext(
policy,
UIDs.PatientRootQueryRetrieveInformationModelMOVE,
patientRootMove);
putPresContext(
policy,
UIDs.StudyRootQueryRetrieveInformationModelMOVE,
studyRootMove);
putPresContext(
policy,
UIDs.PatientStudyOnlyQueryRetrieveInformationModelMOVE,
patientStudyOnlyMove);
return policy;
}
}
| medicayun/medicayundicom | dcm4jboss-all/tags/dcm4jboss_0_7_1/dcm4jboss-sar/src/java/org/dcm4chex/service/QueryRetrieveScpService.java | Java | apache-2.0 | 8,887 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="ko-KR">
<title>Revisit | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | 0xkasun/security-tools | src/org/zaproxy/zap/extension/revisit/resources/help_ko_KR/helpset_ko_KR.hs | Haskell | apache-2.0 | 969 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
#import <Foundation/Foundation.h>
/*!
@category NSURLConnection (Apigee)
@discussion This category provides methods that capture network performance
metrics on built-in NSURLConnection methods that perform network calls.
*/
typedef void (^NSURLConnectionAsyncRequestCompletionHandler)(NSURLResponse* response, NSData* data, NSError* connectionError);
@interface NSURLConnection (Apigee)
/*!
@abstract Creates and returns an initialized URL connection and begins to load
the data for the URL request.
@param request The URL request to load.
@param delegate The delegate object for the connection.
@return The URL connection for the URL request. Returns nil if a connection
can't be created.
@discussion This method simply calls the NSURLConnection class method
connectionWithRequest:delegate: while capturing the network performance
metrics for that call.
*/
+ (NSURLConnection*) timedConnectionWithRequest:(NSURLRequest *) request
delegate:(id < NSURLConnectionDelegate >) delegate;
/*!
@abstract Performs a synchronous load of the specified URL request.
@param request The URL request to load.
@param response Out parameter for the URL response returned by the server.
@param error Out parameter used if an error occurs while processing the
request. May be NULL.
@return The downloaded data for the URL request. Returns nil if a connection
could not be created or if the download fails.
@discussion This method simply calls the NSURLConnection class method
sendSynchronousRequest:returningResponse:error: while capturing the network
performance metrics for that call.
*/
+ (NSData *) timedSendSynchronousRequest:(NSURLRequest *) request
returningResponse:(NSURLResponse **)response
error:(NSError **)error;
/*!
@abstract Loads the data for a URL request and executes a handler block on an
operation queue when the request completes or fails.
@param request The URL request to load.
@param queue The operation queue to which the handler block is dispatched when
the request completes or failed.
@param handler The handler block to execute.
@discussion This method simply calls the NSURLConnection class method
sendAsynchronousRequest:queue:completionHandler: while capturing the network
performance metrics for that call.
*/
+ (void) timedSendAsynchronousRequest:(NSURLRequest *)request
queue:(NSOperationQueue *)queue
completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))handler;
/*!
@abstract Returns an initialized URL connection and begins to load the data
for the URL request.
@param request The URL request to load.
@param delegate The delegate object for the connection.
@return The URL connection for the URL request. Returns nil if a connection
can't be initialized.
@discussion This method simply calls the NSURLConnection instance method
initWithRequest:delegate: while capturing the network performance metrics
for that call.
*/
- (id) initTimedConnectionWithRequest:(NSURLRequest *)request
delegate:(id < NSURLConnectionDelegate >)delegate;
/*!
@abstract Returns an initialized URL connection and begins to load the data
for the URL request, if specified.
@param request The URL request to load.
@param delegate The delegate object for the connection.
@param startImmediately YES if the connection should being loading data
immediately, otherwise NO.
@return The URL connection for the URL request. Returns nil if a connection
can't be initialized.
@discussion This method simply calls the NSURLConnection instance method
initWithRequest:delegate:startImmediately: while capturing the network
performance metrics for that call.
*/
- (id) initTimedConnectionWithRequest:(NSURLRequest *)request
delegate:(id < NSURLConnectionDelegate >) delegate
startImmediately:(BOOL) startImmediately;
// ****** swizzling *******
+ (BOOL)apigeeSwizzlingSetup;
@end
| apigee/apigee-ios-sdk | source/Classes/Services/NSURLConnection+Apigee.h | C | apache-2.0 | 4,939 |
import { NodeMaterialBlock } from '../nodeMaterialBlock';
import { NodeMaterialBlockConnectionPointTypes } from '../Enums/nodeMaterialBlockConnectionPointTypes';
import { NodeMaterialBuildState } from '../nodeMaterialBuildState';
import { NodeMaterialConnectionPoint } from '../nodeMaterialBlockConnectionPoint';
import { NodeMaterialBlockTargets } from '../Enums/nodeMaterialBlockTargets';
import { RegisterClass } from '../../../Misc/typeStore';
import { Scene } from '../../../scene';
/**
* Operations supported by the Wave block
*/
export enum WaveBlockKind {
/** SawTooth */
SawTooth,
/** Square */
Square,
/** Triangle */
Triangle
}
/**
* Block used to apply wave operation to floats
*/
export class WaveBlock extends NodeMaterialBlock {
/**
* Gets or sets the kibnd of wave to be applied by the block
*/
public kind = WaveBlockKind.SawTooth;
/**
* Creates a new WaveBlock
* @param name defines the block name
*/
public constructor(name: string) {
super(name, NodeMaterialBlockTargets.Neutral);
this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect);
this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput);
this._outputs[0]._typeConnectionSource = this._inputs[0];
this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);
}
/**
* Gets the current class name
* @returns the class name
*/
public getClassName() {
return "WaveBlock";
}
/**
* Gets the input component
*/
public get input(): NodeMaterialConnectionPoint {
return this._inputs[0];
}
/**
* Gets the output component
*/
public get output(): NodeMaterialConnectionPoint {
return this._outputs[0];
}
protected _buildBlock(state: NodeMaterialBuildState) {
super._buildBlock(state);
let output = this._outputs[0];
switch (this.kind) {
case WaveBlockKind.SawTooth: {
state.compilationString += this._declareOutput(output, state) + ` = ${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName});\r\n`;
break;
}
case WaveBlockKind.Square: {
state.compilationString += this._declareOutput(output, state) + ` = 1.0 - 2.0 * round(fract(${this.input.associatedVariableName}));\r\n`;
break;
}
case WaveBlockKind.Triangle: {
state.compilationString += this._declareOutput(output, state) + ` = 2.0 * abs(2.0 * (${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}))) - 1.0;\r\n`;
break;
}
}
return this;
}
public serialize(): any {
let serializationObject = super.serialize();
serializationObject.kind = this.kind;
return serializationObject;
}
public _deserialize(serializationObject: any, scene: Scene, rootUrl: string) {
super._deserialize(serializationObject, scene, rootUrl);
this.kind = serializationObject.kind;
}
}
RegisterClass("BABYLON.WaveBlock", WaveBlock); | RaananW/Babylon.js | src/Materials/Node/Blocks/waveBlock.ts | TypeScript | apache-2.0 | 3,379 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you 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.
*/
package org.elasticsearch.client.benchmark.metrics;
public final class Sample {
private final String operation;
private final long startTimestamp;
private final long stopTimestamp;
private final boolean success;
public Sample(String operation, long startTimestamp, long stopTimestamp, boolean success) {
this.operation = operation;
this.startTimestamp = startTimestamp;
this.stopTimestamp = stopTimestamp;
this.success = success;
}
public String getOperation() {
return operation;
}
public boolean isSuccess() {
return success;
}
public long getStartTimestamp() {
return startTimestamp;
}
public long getStopTimestamp() {
return stopTimestamp;
}
public long getServiceTime() {
// this is *not* latency, we're not including wait time in the queue (on purpose)
return stopTimestamp - startTimestamp;
}
}
| dpursehouse/elasticsearch | client/benchmark/src/main/java/org/elasticsearch/client/benchmark/metrics/Sample.java | Java | apache-2.0 | 1,742 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Package com.google.zxing.datamatrix.detector (ZXing 3.4.1 API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Package com.google.zxing.datamatrix.detector (ZXing 3.4.1 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Use</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/google/zxing/datamatrix/detector/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Uses of Package com.google.zxing.datamatrix.detector" class="title">Uses of Package<br>com.google.zxing.datamatrix.detector</h1>
</div>
<div class="contentContainer">No usage of com.google.zxing.datamatrix.detector</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Use</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/google/zxing/datamatrix/detector/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2007–2020. All rights reserved.</small></p>
</body>
</html>
| zxing/zxing | docs/apidocs/com/google/zxing/datamatrix/detector/package-use.html | HTML | apache-2.0 | 4,246 |
/*
* Copyright (C) 2013 Manuel Peinado
*
* 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.
*/
package com.manuelpeinado.refreshactionitem;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.graphics.Xfermode;
import android.util.AttributeSet;
import android.view.View;
/**
* Class used internally by {@link RefreshActionItem} to show a determinate progress
* indicator. Two display modes are supported "wheel" and "pie"
*/
class ProgressIndicator extends View {
private final RectF mRect = new RectF();
private final RectF mRectInner = new RectF();
private final Paint mPaintForeground = new Paint();
private final Paint mPaintBackground = new Paint();
private final Paint mPaintErase = new Paint();
private static final Xfermode PORTER_DUFF_CLEAR = new PorterDuffXfermode(PorterDuff.Mode.CLEAR);
private int mColorForeground = Color.WHITE;
private int mColorBackground = Color.BLACK;
private float mValue;
private boolean mPieStyle;
/**
* Value which makes our custom drawn indicator have roughly the same size
* as the built-in ProgressBar indicator. Unit: dp
*/
private static final float PADDING = 4;
private float mPadding;
private Bitmap mBitmap;
/**
* Value which makes our custom drawn indicator have roughly the same
* thickness as the built-in ProgressBar indicator. Expressed as the ration
* between the inner and outer radiuses
*/
private static final float INNER_RADIUS_RATIO = 0.84f;
public ProgressIndicator(Context context) {
this(context, null);
}
public ProgressIndicator(Context context, AttributeSet attrs) {
super(context, attrs);
Resources r = context.getResources();
float scale = r.getDisplayMetrics().density;
mPadding = scale * PADDING + r.getDimension(R.dimen.rai__action_bar_icon_vertical_padding);
mPaintForeground.setColor(mColorForeground);
mPaintForeground.setAntiAlias(true);
mPaintBackground.setColor(mColorBackground);
mPaintBackground.setAntiAlias(true);
mPaintErase.setXfermode(PORTER_DUFF_CLEAR);
mPaintErase.setAntiAlias(true);
}
/**
* Set the style of this indicator.The two supported styles are "wheel" and "pie"
* @param style One of {@link STYLE_WHEEL} or {@link STYLE_PIE}
*/
public void setPieStyle(boolean pieStyle) {
if (mPieStyle == pieStyle) {
return;
}
mPieStyle = pieStyle;
updateBitmap();
}
/**
* Return the current style of this indicator.
*
* @return <tt>True</tt> if the indicator has the "pie" style
*/
public boolean getIsPieStyle() {
return mPieStyle;
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(mBitmap, getWidth() / 2 - mBitmap.getWidth() / 2,
getHeight() / 2 - mBitmap.getHeight() / 2, null);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
float bitmapWidth = w - 2 * mPadding;
float bitmapHeight = h - 2 * mPadding;
float radius = Math.min(bitmapWidth / 2, bitmapHeight / 2);
mRect.set(0, 0, bitmapWidth, bitmapHeight);
radius *= INNER_RADIUS_RATIO;
mRectInner.set(bitmapWidth / 2f - radius, bitmapHeight / 2f - radius, bitmapWidth / 2f + radius, bitmapHeight / 2f + radius);
updateBitmap();
}
/**
* Set the foreground color for this indicator. The foreground is the part
* of the indicator that shows the actual progress
*/
public void setForegroundColor(int color) {
this.mColorForeground = color;
mPaintForeground.setColor(color);
invalidate();
}
/**
* Set the background color for this indicator. The background is a dim and subtle
* part of the indicator that appears below the actual progress
*/
public void setBackgroundColor(int color) {
this.mColorBackground = color;
mPaintBackground.setColor(color);
invalidate();
}
/**
* @param value A number between 0 and 1
*/
public synchronized void setValue(float value) {
mValue = value;
updateBitmap();
}
private void updateBitmap() {
if (mRect == null || mRect.width() == 0) {
return;
}
mBitmap = Bitmap.createBitmap((int) mRect.width(), (int) mRect.height(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(mBitmap);
canvas.drawArc(mRect, -90, 360, true, mPaintBackground);
if (mValue < 0.01f) {
canvas.drawLine(mRect.width() / 2, mRect.height() / 2, mRect.width() / 2, 0, mPaintForeground);
}
float angle = mValue * 360;
canvas.drawArc(mRect, -90, angle, true, mPaintForeground);
if (!mPieStyle) {
canvas.drawArc(mRectInner, -90, 360, true, mPaintErase);
}
postInvalidate();
}
}
| fedefernandez/RefreshActionItem-ActionBarCompat | library/src/main/java/com/manuelpeinado/refreshactionitem/ProgressIndicator.java | Java | apache-2.0 | 5,766 |
/**
* Copyright (c) 2016-present, RxJava Contributors.
*
* 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.
*/
package io.reactivex.internal.operators.single;
import io.reactivex.Single;
import io.reactivex.SingleSource;
import io.reactivex.TestHelper;
import io.reactivex.exceptions.TestException;
import io.reactivex.functions.Action;
import io.reactivex.functions.Function;
import io.reactivex.internal.functions.Functions;
import io.reactivex.observers.TestObserver;
import io.reactivex.plugins.RxJavaPlugins;
import io.reactivex.subjects.PublishSubject;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class SingleDoAfterTerminateTest {
private final int[] call = { 0 };
private final Action afterTerminate = new Action() {
@Override
public void run() throws Exception {
call[0]++;
}
};
private final TestObserver<Integer> to = new TestObserver<Integer>();
@Test
public void just() {
Single.just(1)
.doAfterTerminate(afterTerminate)
.subscribeWith(to)
.assertResult(1);
assertAfterTerminateCalledOnce();
}
@Test
public void error() {
Single.<Integer>error(new TestException())
.doAfterTerminate(afterTerminate)
.subscribeWith(to)
.assertFailure(TestException.class);
assertAfterTerminateCalledOnce();
}
@Test(expected = NullPointerException.class)
public void afterTerminateActionNull() {
Single.just(1).doAfterTerminate(null);
}
@Test
public void justConditional() {
Single.just(1)
.doAfterTerminate(afterTerminate)
.filter(Functions.alwaysTrue())
.subscribeWith(to)
.assertResult(1);
assertAfterTerminateCalledOnce();
}
@Test
public void errorConditional() {
Single.<Integer>error(new TestException())
.doAfterTerminate(afterTerminate)
.filter(Functions.alwaysTrue())
.subscribeWith(to)
.assertFailure(TestException.class);
assertAfterTerminateCalledOnce();
}
@Test
public void actionThrows() {
List<Throwable> errors = TestHelper.trackPluginErrors();
try {
Single.just(1)
.doAfterTerminate(new Action() {
@Override
public void run() throws Exception {
throw new TestException();
}
})
.test()
.assertResult(1);
TestHelper.assertUndeliverable(errors, 0, TestException.class);
} finally {
RxJavaPlugins.reset();
}
}
@Test
public void dispose() {
TestHelper.checkDisposed(PublishSubject.<Integer>create().singleOrError().doAfterTerminate(afterTerminate));
}
@Test
public void doubleOnSubscribe() {
TestHelper.checkDoubleOnSubscribeSingle(new Function<Single<Integer>, SingleSource<Integer>>() {
@Override
public SingleSource<Integer> apply(Single<Integer> m) throws Exception {
return m.doAfterTerminate(afterTerminate);
}
});
}
private void assertAfterTerminateCalledOnce() {
assertEquals(1, call[0]);
}
}
| akarnokd/RxJava | src/test/java/io/reactivex/internal/operators/single/SingleDoAfterTerminateTest.java | Java | apache-2.0 | 3,785 |
table.sortable1 {
font-family: verdana, arial, sans-serif;
font-size: 11px;
color: #333333;
align: center;
}
table.sortable1 td {
vertical-align: top;
}
table.sortable {
font-family: verdana, arial, sans-serif;
font-size: 11px;
color: #333333;
border-width: 1px;
border-color: #999999;
align: center;
border-collapse: collapse;
}
table.sortable thead {
cursor: pointer;
}
table.sortable th {
background-color: #A5A1A0;
border-width: 1.5px;
padding: 5px;
border-style: solid;
border-color: #a9c6c9;
}
table.sortable td {
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #a9c6c9;
}
table.sortable tr:nth-child(odd) {
background-color: #eee;
}
table.sortable tr:nth-child(even) {
background-color: #fff;
}
table.sortable input {
border-color: #3C3CFF;
}
table.sortable textarea {
border-color: #3C3CFF;
}
table.sortable select {
border-color: #3C3CFF;
}
.overlay {
position: absolute;
top: 25%;
left: 40%;
width: 25%;
height: 25%;
text-align: center;
cursor: wait;
}
#loading_image {
opacity: 0.8;
filter: alpha(opacity = 80); /* For IE8 and earlier */
}
.changeButtonUI:hover {
font-family: verdana, arial, sans-serif;
font-size: 11px;
color: #ffffff;
text-decoration: none;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
-webkit-box-shadow: 0px 2px 9px #666666;
-moz-box-shadow: 0px 2px 9px #666666;
box-shadow: 0px 2px 9px #666666;
text-shadow: 0px 0px 5px #666666;
border: solid #121011 1px;
background: -webkit-gradient(linear, left top, left bottom, color-stop(0.05, #3d94f6
), color-stop(1, #1e62d0) ); background : -moz-linear-gradient( center
top, #3d94f6 5%, #1e62d0 100%); filter : progid :
DXImageTransform.Microsoft.gradient ( startColorstr = '#3d94f6',
endColorstr = '#1e62d0');
height: 100%;
background: -moz-linear-gradient(center top, #3d94f6 5%, #1e62d0 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#3d94f6',
endColorstr='#1e62d0' );
} | calsoftcapella/MedecisionTimeEffort | MedecisionTimeEffort/WebContent/css/time_entry_page_style.css | CSS | apache-2.0 | 1,996 |
//! # Token Streams
//!
//! `TokenStream`s represent syntactic objects before they are converted into ASTs.
//! A `TokenStream` is, roughly speaking, a sequence of [`TokenTree`]s,
//! which are themselves a single [`Token`] or a `Delimited` subsequence of tokens.
//!
//! ## Ownership
//!
//! `TokenStream`s are persistent data structures constructed as ropes with reference
//! counted-children. In general, this means that calling an operation on a `TokenStream`
//! (such as `slice`) produces an entirely new `TokenStream` from the borrowed reference to
//! the original. This essentially coerces `TokenStream`s into "views" of their subparts,
//! and a borrowed `TokenStream` is sufficient to build an owned `TokenStream` without taking
//! ownership of the original.
use crate::token::{self, DelimToken, Token, TokenKind};
use crate::AttrVec;
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_data_structures::sync::{self, Lrc};
use rustc_macros::HashStable_Generic;
use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
use rustc_span::{Span, DUMMY_SP};
use smallvec::{smallvec, SmallVec};
use std::{fmt, iter, mem};
/// When the main Rust parser encounters a syntax-extension invocation, it
/// parses the arguments to the invocation as a token tree. This is a very
/// loose structure, such that all sorts of different AST fragments can
/// be passed to syntax extensions using a uniform type.
///
/// If the syntax extension is an MBE macro, it will attempt to match its
/// LHS token tree against the provided token tree, and if it finds a
/// match, will transcribe the RHS token tree, splicing in any captured
/// `macro_parser::matched_nonterminals` into the `SubstNt`s it finds.
///
/// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
/// Nothing special happens to misnamed or misplaced `SubstNt`s.
#[derive(Debug, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
pub enum TokenTree {
/// A single token.
Token(Token),
/// A delimited sequence of token trees.
Delimited(DelimSpan, DelimToken, TokenStream),
}
#[derive(Copy, Clone)]
pub enum CanSynthesizeMissingTokens {
Yes,
No,
}
// Ensure all fields of `TokenTree` is `Send` and `Sync`.
#[cfg(parallel_compiler)]
fn _dummy()
where
Token: Send + Sync,
DelimSpan: Send + Sync,
DelimToken: Send + Sync,
TokenStream: Send + Sync,
{
}
impl TokenTree {
/// Checks if this `TokenTree` is equal to the other, regardless of span information.
pub fn eq_unspanned(&self, other: &TokenTree) -> bool {
match (self, other) {
(TokenTree::Token(token), TokenTree::Token(token2)) => token.kind == token2.kind,
(TokenTree::Delimited(_, delim, tts), TokenTree::Delimited(_, delim2, tts2)) => {
delim == delim2 && tts.eq_unspanned(&tts2)
}
_ => false,
}
}
/// Retrieves the `TokenTree`'s span.
pub fn span(&self) -> Span {
match self {
TokenTree::Token(token) => token.span,
TokenTree::Delimited(sp, ..) => sp.entire(),
}
}
/// Modify the `TokenTree`'s span in-place.
pub fn set_span(&mut self, span: Span) {
match self {
TokenTree::Token(token) => token.span = span,
TokenTree::Delimited(dspan, ..) => *dspan = DelimSpan::from_single(span),
}
}
pub fn token(kind: TokenKind, span: Span) -> TokenTree {
TokenTree::Token(Token::new(kind, span))
}
/// Returns the opening delimiter as a token tree.
pub fn open_tt(span: DelimSpan, delim: DelimToken) -> TokenTree {
TokenTree::token(token::OpenDelim(delim), span.open)
}
/// Returns the closing delimiter as a token tree.
pub fn close_tt(span: DelimSpan, delim: DelimToken) -> TokenTree {
TokenTree::token(token::CloseDelim(delim), span.close)
}
pub fn uninterpolate(self) -> TokenTree {
match self {
TokenTree::Token(token) => TokenTree::Token(token.uninterpolate().into_owned()),
tt => tt,
}
}
}
impl<CTX> HashStable<CTX> for TokenStream
where
CTX: crate::HashStableContext,
{
fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
for sub_tt in self.trees() {
sub_tt.hash_stable(hcx, hasher);
}
}
}
pub trait CreateTokenStream: sync::Send + sync::Sync {
fn create_token_stream(&self) -> AttrAnnotatedTokenStream;
}
impl CreateTokenStream for AttrAnnotatedTokenStream {
fn create_token_stream(&self) -> AttrAnnotatedTokenStream {
self.clone()
}
}
/// A lazy version of [`TokenStream`], which defers creation
/// of an actual `TokenStream` until it is needed.
/// `Box` is here only to reduce the structure size.
#[derive(Clone)]
pub struct LazyTokenStream(Lrc<Box<dyn CreateTokenStream>>);
impl LazyTokenStream {
pub fn new(inner: impl CreateTokenStream + 'static) -> LazyTokenStream {
LazyTokenStream(Lrc::new(Box::new(inner)))
}
pub fn create_token_stream(&self) -> AttrAnnotatedTokenStream {
self.0.create_token_stream()
}
}
impl fmt::Debug for LazyTokenStream {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "LazyTokenStream({:?})", self.create_token_stream())
}
}
impl<S: Encoder> Encodable<S> for LazyTokenStream {
fn encode(&self, s: &mut S) -> Result<(), S::Error> {
// Used by AST json printing.
Encodable::encode(&self.create_token_stream(), s)
}
}
impl<D: Decoder> Decodable<D> for LazyTokenStream {
fn decode(_d: &mut D) -> Result<Self, D::Error> {
panic!("Attempted to decode LazyTokenStream");
}
}
impl<CTX> HashStable<CTX> for LazyTokenStream {
fn hash_stable(&self, _hcx: &mut CTX, _hasher: &mut StableHasher) {
panic!("Attempted to compute stable hash for LazyTokenStream");
}
}
/// A `AttrAnnotatedTokenStream` is similar to a `TokenStream`, but with extra
/// information about the tokens for attribute targets. This is used
/// during expansion to perform early cfg-expansion, and to process attributes
/// during proc-macro invocations.
#[derive(Clone, Debug, Default, Encodable, Decodable)]
pub struct AttrAnnotatedTokenStream(pub Lrc<Vec<(AttrAnnotatedTokenTree, Spacing)>>);
/// Like `TokenTree`, but for `AttrAnnotatedTokenStream`
#[derive(Clone, Debug, Encodable, Decodable)]
pub enum AttrAnnotatedTokenTree {
Token(Token),
Delimited(DelimSpan, DelimToken, AttrAnnotatedTokenStream),
/// Stores the attributes for an attribute target,
/// along with the tokens for that attribute target.
/// See `AttributesData` for more information
Attributes(AttributesData),
}
impl AttrAnnotatedTokenStream {
pub fn new(tokens: Vec<(AttrAnnotatedTokenTree, Spacing)>) -> AttrAnnotatedTokenStream {
AttrAnnotatedTokenStream(Lrc::new(tokens))
}
/// Converts this `AttrAnnotatedTokenStream` to a plain `TokenStream
/// During conversion, `AttrAnnotatedTokenTree::Attributes` get 'flattened'
/// back to a `TokenStream` of the form `outer_attr attr_target`.
/// If there are inner attributes, they are inserted into the proper
/// place in the attribute target tokens.
pub fn to_tokenstream(&self) -> TokenStream {
let trees: Vec<_> = self
.0
.iter()
.flat_map(|tree| match &tree.0 {
AttrAnnotatedTokenTree::Token(inner) => {
smallvec![(TokenTree::Token(inner.clone()), tree.1)].into_iter()
}
AttrAnnotatedTokenTree::Delimited(span, delim, stream) => smallvec![(
TokenTree::Delimited(*span, *delim, stream.to_tokenstream()),
tree.1,
)]
.into_iter(),
AttrAnnotatedTokenTree::Attributes(data) => {
let mut outer_attrs = Vec::new();
let mut inner_attrs = Vec::new();
for attr in &data.attrs {
match attr.style {
crate::AttrStyle::Outer => {
outer_attrs.push(attr);
}
crate::AttrStyle::Inner => {
inner_attrs.push(attr);
}
}
}
let mut target_tokens: Vec<_> = data
.tokens
.create_token_stream()
.to_tokenstream()
.0
.iter()
.cloned()
.collect();
if !inner_attrs.is_empty() {
let mut found = false;
// Check the last two trees (to account for a trailing semi)
for (tree, _) in target_tokens.iter_mut().rev().take(2) {
if let TokenTree::Delimited(span, delim, delim_tokens) = tree {
// Inner attributes are only supported on extern blocks, functions, impls,
// and modules. All of these have their inner attributes placed at
// the beginning of the rightmost outermost braced group:
// e.g. fn foo() { #![my_attr} }
//
// Therefore, we can insert them back into the right location
// without needing to do any extra position tracking.
//
// Note: Outline modules are an exception - they can
// have attributes like `#![my_attr]` at the start of a file.
// Support for custom attributes in this position is not
// properly implemented - we always synthesize fake tokens,
// so we never reach this code.
let mut builder = TokenStreamBuilder::new();
for inner_attr in inner_attrs {
builder.push(inner_attr.tokens().to_tokenstream());
}
builder.push(delim_tokens.clone());
*tree = TokenTree::Delimited(*span, *delim, builder.build());
found = true;
break;
}
}
assert!(
found,
"Failed to find trailing delimited group in: {:?}",
target_tokens
);
}
let mut flat: SmallVec<[_; 1]> = SmallVec::new();
for attr in outer_attrs {
// FIXME: Make this more efficient
flat.extend(attr.tokens().to_tokenstream().0.clone().iter().cloned());
}
flat.extend(target_tokens);
flat.into_iter()
}
})
.collect();
TokenStream::new(trees)
}
}
/// Stores the tokens for an attribute target, along
/// with its attributes.
///
/// This is constructed during parsing when we need to capture
/// tokens.
///
/// For example, `#[cfg(FALSE)] struct Foo {}` would
/// have an `attrs` field containing the `#[cfg(FALSE)]` attr,
/// and a `tokens` field storing the (unparesd) tokens `struct Foo {}`
#[derive(Clone, Debug, Encodable, Decodable)]
pub struct AttributesData {
/// Attributes, both outer and inner.
/// These are stored in the original order that they were parsed in.
pub attrs: AttrVec,
/// The underlying tokens for the attribute target that `attrs`
/// are applied to
pub tokens: LazyTokenStream,
}
/// A `TokenStream` is an abstract sequence of tokens, organized into [`TokenTree`]s.
///
/// The goal is for procedural macros to work with `TokenStream`s and `TokenTree`s
/// instead of a representation of the abstract syntax tree.
/// Today's `TokenTree`s can still contain AST via `token::Interpolated` for
/// backwards compatibility.
#[derive(Clone, Debug, Default, Encodable, Decodable)]
pub struct TokenStream(pub(crate) Lrc<Vec<TreeAndSpacing>>);
pub type TreeAndSpacing = (TokenTree, Spacing);
// `TokenStream` is used a lot. Make sure it doesn't unintentionally get bigger.
#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
rustc_data_structures::static_assert_size!(TokenStream, 8);
#[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable)]
pub enum Spacing {
Alone,
Joint,
}
impl TokenStream {
/// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream`
/// separating the two arguments with a comma for diagnostic suggestions.
pub fn add_comma(&self) -> Option<(TokenStream, Span)> {
// Used to suggest if a user writes `foo!(a b);`
let mut suggestion = None;
let mut iter = self.0.iter().enumerate().peekable();
while let Some((pos, ts)) = iter.next() {
if let Some((_, next)) = iter.peek() {
let sp = match (&ts, &next) {
(_, (TokenTree::Token(Token { kind: token::Comma, .. }), _)) => continue,
(
(TokenTree::Token(token_left), Spacing::Alone),
(TokenTree::Token(token_right), _),
) if ((token_left.is_ident() && !token_left.is_reserved_ident())
|| token_left.is_lit())
&& ((token_right.is_ident() && !token_right.is_reserved_ident())
|| token_right.is_lit()) =>
{
token_left.span
}
((TokenTree::Delimited(sp, ..), Spacing::Alone), _) => sp.entire(),
_ => continue,
};
let sp = sp.shrink_to_hi();
let comma = (TokenTree::token(token::Comma, sp), Spacing::Alone);
suggestion = Some((pos, comma, sp));
}
}
if let Some((pos, comma, sp)) = suggestion {
let mut new_stream = Vec::with_capacity(self.0.len() + 1);
let parts = self.0.split_at(pos + 1);
new_stream.extend_from_slice(parts.0);
new_stream.push(comma);
new_stream.extend_from_slice(parts.1);
return Some((TokenStream::new(new_stream), sp));
}
None
}
}
impl From<(AttrAnnotatedTokenTree, Spacing)> for AttrAnnotatedTokenStream {
fn from((tree, spacing): (AttrAnnotatedTokenTree, Spacing)) -> AttrAnnotatedTokenStream {
AttrAnnotatedTokenStream::new(vec![(tree, spacing)])
}
}
impl From<TokenTree> for TokenStream {
fn from(tree: TokenTree) -> TokenStream {
TokenStream::new(vec![(tree, Spacing::Alone)])
}
}
impl From<TokenTree> for TreeAndSpacing {
fn from(tree: TokenTree) -> TreeAndSpacing {
(tree, Spacing::Alone)
}
}
impl iter::FromIterator<TokenTree> for TokenStream {
fn from_iter<I: IntoIterator<Item = TokenTree>>(iter: I) -> Self {
TokenStream::new(iter.into_iter().map(Into::into).collect::<Vec<TreeAndSpacing>>())
}
}
impl Eq for TokenStream {}
impl PartialEq<TokenStream> for TokenStream {
fn eq(&self, other: &TokenStream) -> bool {
self.trees().eq(other.trees())
}
}
impl TokenStream {
pub fn new(streams: Vec<TreeAndSpacing>) -> TokenStream {
TokenStream(Lrc::new(streams))
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn from_streams(mut streams: SmallVec<[TokenStream; 2]>) -> TokenStream {
match streams.len() {
0 => TokenStream::default(),
1 => streams.pop().unwrap(),
_ => {
// We are going to extend the first stream in `streams` with
// the elements from the subsequent streams. This requires
// using `make_mut()` on the first stream, and in practice this
// doesn't cause cloning 99.9% of the time.
//
// One very common use case is when `streams` has two elements,
// where the first stream has any number of elements within
// (often 1, but sometimes many more) and the second stream has
// a single element within.
// Determine how much the first stream will be extended.
// Needed to avoid quadratic blow up from on-the-fly
// reallocations (#57735).
let num_appends = streams.iter().skip(1).map(|ts| ts.len()).sum();
// Get the first stream. If it's `None`, create an empty
// stream.
let mut iter = streams.drain(..);
let mut first_stream_lrc = iter.next().unwrap().0;
// Append the elements to the first stream, after reserving
// space for them.
let first_vec_mut = Lrc::make_mut(&mut first_stream_lrc);
first_vec_mut.reserve(num_appends);
for stream in iter {
first_vec_mut.extend(stream.0.iter().cloned());
}
// Create the final `TokenStream`.
TokenStream(first_stream_lrc)
}
}
}
pub fn trees(&self) -> Cursor {
self.clone().into_trees()
}
pub fn into_trees(self) -> Cursor {
Cursor::new(self)
}
/// Compares two `TokenStream`s, checking equality without regarding span information.
pub fn eq_unspanned(&self, other: &TokenStream) -> bool {
let mut t1 = self.trees();
let mut t2 = other.trees();
for (t1, t2) in iter::zip(&mut t1, &mut t2) {
if !t1.eq_unspanned(&t2) {
return false;
}
}
t1.next().is_none() && t2.next().is_none()
}
pub fn map_enumerated<F: FnMut(usize, &TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
TokenStream(Lrc::new(
self.0
.iter()
.enumerate()
.map(|(i, (tree, is_joint))| (f(i, tree), *is_joint))
.collect(),
))
}
}
// 99.5%+ of the time we have 1 or 2 elements in this vector.
#[derive(Clone)]
pub struct TokenStreamBuilder(SmallVec<[TokenStream; 2]>);
impl TokenStreamBuilder {
pub fn new() -> TokenStreamBuilder {
TokenStreamBuilder(SmallVec::new())
}
pub fn push<T: Into<TokenStream>>(&mut self, stream: T) {
let mut stream = stream.into();
// If `self` is not empty and the last tree within the last stream is a
// token tree marked with `Joint`...
if let Some(TokenStream(ref mut last_stream_lrc)) = self.0.last_mut() {
if let Some((TokenTree::Token(last_token), Spacing::Joint)) = last_stream_lrc.last() {
// ...and `stream` is not empty and the first tree within it is
// a token tree...
let TokenStream(ref mut stream_lrc) = stream;
if let Some((TokenTree::Token(token), spacing)) = stream_lrc.first() {
// ...and the two tokens can be glued together...
if let Some(glued_tok) = last_token.glue(&token) {
// ...then do so, by overwriting the last token
// tree in `self` and removing the first token tree
// from `stream`. This requires using `make_mut()`
// on the last stream in `self` and on `stream`,
// and in practice this doesn't cause cloning 99.9%
// of the time.
// Overwrite the last token tree with the merged
// token.
let last_vec_mut = Lrc::make_mut(last_stream_lrc);
*last_vec_mut.last_mut().unwrap() = (TokenTree::Token(glued_tok), *spacing);
// Remove the first token tree from `stream`. (This
// is almost always the only tree in `stream`.)
let stream_vec_mut = Lrc::make_mut(stream_lrc);
stream_vec_mut.remove(0);
// Don't push `stream` if it's empty -- that could
// block subsequent token gluing, by getting
// between two token trees that should be glued
// together.
if !stream.is_empty() {
self.0.push(stream);
}
return;
}
}
}
}
self.0.push(stream);
}
pub fn build(self) -> TokenStream {
TokenStream::from_streams(self.0)
}
}
/// By-reference iterator over a [`TokenStream`].
#[derive(Clone)]
pub struct CursorRef<'t> {
stream: &'t TokenStream,
index: usize,
}
impl<'t> CursorRef<'t> {
fn next_with_spacing(&mut self) -> Option<&'t TreeAndSpacing> {
self.stream.0.get(self.index).map(|tree| {
self.index += 1;
tree
})
}
}
impl<'t> Iterator for CursorRef<'t> {
type Item = &'t TokenTree;
fn next(&mut self) -> Option<&'t TokenTree> {
self.next_with_spacing().map(|(tree, _)| tree)
}
}
/// Owning by-value iterator over a [`TokenStream`].
// FIXME: Many uses of this can be replaced with by-reference iterator to avoid clones.
#[derive(Clone)]
pub struct Cursor {
pub stream: TokenStream,
index: usize,
}
impl Iterator for Cursor {
type Item = TokenTree;
fn next(&mut self) -> Option<TokenTree> {
self.next_with_spacing().map(|(tree, _)| tree)
}
}
impl Cursor {
fn new(stream: TokenStream) -> Self {
Cursor { stream, index: 0 }
}
pub fn next_with_spacing(&mut self) -> Option<TreeAndSpacing> {
if self.index < self.stream.len() {
self.index += 1;
Some(self.stream.0[self.index - 1].clone())
} else {
None
}
}
pub fn index(&self) -> usize {
self.index
}
pub fn append(&mut self, new_stream: TokenStream) {
if new_stream.is_empty() {
return;
}
let index = self.index;
let stream = mem::take(&mut self.stream);
*self = TokenStream::from_streams(smallvec![stream, new_stream]).into_trees();
self.index = index;
}
pub fn look_ahead(&self, n: usize) -> Option<&TokenTree> {
self.stream.0[self.index..].get(n).map(|(tree, _)| tree)
}
}
#[derive(Debug, Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
pub struct DelimSpan {
pub open: Span,
pub close: Span,
}
impl DelimSpan {
pub fn from_single(sp: Span) -> Self {
DelimSpan { open: sp, close: sp }
}
pub fn from_pair(open: Span, close: Span) -> Self {
DelimSpan { open, close }
}
pub fn dummy() -> Self {
Self::from_single(DUMMY_SP)
}
pub fn entire(self) -> Span {
self.open.with_hi(self.close.hi())
}
}
| graydon/rust | compiler/rustc_ast/src/tokenstream.rs | Rust | apache-2.0 | 23,640 |
// Copyright 2016, EMC, Inc.
/* jshint node: true */
'use strict';
describe(require('path').basename(__filename), function() {
var schemaFileName = 'install-esxi.json';
var canonical = {
"osType": "esx",
"profile": "install-esx.ipxe",
"installScript": "esx-ks",
"installScriptUri": "http://172.31.128.9090/api/current/templates/esx-ks",
"version": "5.5",
"repo": "http://172.31.128.1:9080/esxi/5.5",
"rootPassword": "RackHDRocks!",
"hostname": "rackhd-node",
"domain": "example.com",
"users": [
{
"name": "rackhd1",
"password": "123456",
"sshKey": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDJQ631/sw3D40h/6JfA+PFVy5Ofza6"
},
{
"name": "rackhd2",
"password": "123456",
}
],
"rootSshKey": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDJQ631/sw3D40h/6JfA+PFVy5Ofz6eu7ca",
"dnsServers": [
"172.12.88.91",
"192.168.20.77"
],
"ntpServers": [
"0.vmware.pool.ntp.org",
"1.vmware.pool.ntp.org"
],
"networkDevices": [
{
"device": "vmnic0",
"ipv4": {
"ipAddr": "192.168.1.29",
"gateway": "192.168.1.1",
"netmask": "255.255.255.0",
"vlanIds": [
104,
105
]
},
"ipv6": {
"ipAddr": "fec0::6ab4:0:5efe:157.60.14.21",
"gateway": "fe80::5efe:131.107.25.1",
"netmask": "ffff.ffff.ffff.ffff.0.0.0.0",
"vlanIds": [
101,
106
]
},
"esxSwitchName": "vSwitch0"
},
{
"device": "aa:bb:cc:11:22:33",
"ipv4": {
"ipAddr": "192.168.11.89",
"gateway": "192.168.11.1",
"netmask": "255.255.255.0"
}
},
{
"device": "vmnic4",
"ipv6": {
"ipAddr": "fec0::6ab4:0:5efe:157.60.14.21",
"gateway": "fe80::5efe:131.107.25.1",
"netmask": "ffff.ffff.ffff.ffff.0.0.0.0"
}
},
],
"installDisk": "naa.123456",
"postInstallCommands": [
"cd /var/log",
"ls -l"
],
"switchDevices": [
{
"switchName": "vSwitch0",
"uplinks": [ "vmnic0", "vmnic4" ]
},
{
"switchName": "vSwitch1"
}
],
"rackhdCallbackScript": "esx.rackhdcallback",
"esxBootConfigTemplate": "esx-boot-cfg",
"esxBootConfigTemplateUri": "http://172.31.128.1:9080/api/current/templates/esx-boot-cfg",
"comport": "com1",
"comportaddress": "0x3f8",
"gdbPort":"none",
"logPort":"none",
"debugLogToSerial":"0",
"progressMilestones": {
"m1": { "value": 1, "description": "do task 1" },
"m__2": { "value": 2, "description": "do task 2" },
"completed": { "value": 3, "description": "task finished" }
}
};
var positiveSetParam = {
"comportaddress": ["0x3f8", "0x2f8", "0x3e8", "0x2e8"],
"networkDevices[0].device": "90:e2:ba:91:1b:e4",
"gdbPort":["com1","com2","default"],
"logPort":["com1","com2","default"],
"switchDevices[0].uplinks[0]": "90:e2:ba:91:1b:e4"
};
var negativeSetParam = {
"comportaddress": ["com1", "com2", 1, 0x3f8],
"gdbPort":"ttys0",
"debugLogToSerial":"3",
"switchDevices[0].uplinks[1]": "vmnic0", //cannot set duplicated uplinks
"switchDevices[0]": { "switchName": "vSwitch1" }, //cannot set duplicated switchDevice
"ntpServers[0]": "1.vmware.pool.ntp.org" //cannot set duplicated ntpServers
};
var positiveUnsetParam = [
"postInstallCommands",
"switchDevices",
"debugLogToSerial",
"networkDevices[0].esxSwitchName"
];
var negativeUnsetParam = [
"rackhdCallbackScript",
"esxBootConfigTemplate",
"esxBootConfigTemplateUri",
"comportaddress",
"switchDevices[0].switchName"
];
require('./install-os-schema-ut-helper').test(schemaFileName, canonical);
var SchemaUtHelper = require('./schema-ut-helper');
new SchemaUtHelper(schemaFileName, canonical).batchTest(
positiveSetParam, negativeSetParam, positiveUnsetParam, negativeUnsetParam);
});
| nortonluo/on-tasks | spec/lib/task-data/schemas/install-esxi-spec.js | JavaScript | apache-2.0 | 4,856 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Context</title>
<link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="index.html" title="Context">
<link rel="next" href="context/overview.html" title="Overview">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td>
<td align="center"><a href="../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav"><a accesskey="n" href="context/overview.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a></div>
<div class="article">
<div class="titlepage">
<div>
<div><h2 class="title">
<a name="context"></a>Context</h2></div>
<div><div class="authorgroup"><div class="author"><h3 class="author">
<span class="firstname">Oliver</span> <span class="surname">Kowalke</span>
</h3></div></div></div>
<div><p class="copyright">Copyright © 2009 Oliver Kowalke</p></div>
<div><div class="legalnotice">
<a name="context.legal"></a><p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></div>
</div>
<hr>
</div>
<div class="toc">
<p><b>Table of Contents</b></p>
<dl class="toc">
<dt><span class="section"><a href="context/overview.html">Overview</a></span></dt>
<dt><span class="section"><a href="context/requirements.html">Requirements</a></span></dt>
<dt><span class="section"><a href="context/context.html">Context</a></span></dt>
<dd><dl><dt><span class="section"><a href="context/context/boost_fcontext.html">Struct <code class="computeroutput"><span class="identifier">fcontext_t</span></code> and related functions</a></span></dt></dl></dd>
<dt><span class="section"><a href="context/stack.html">Stack allocation</a></span></dt>
<dt><span class="section"><a href="context/performance.html">Performance</a></span></dt>
<dt><span class="section"><a href="context/rationale.html">Rationale</a></span></dt>
<dd><dl>
<dt><span class="section"><a href="context/rationale/other_apis_.html">Other APIs </a></span></dt>
<dt><span class="section"><a href="context/rationale/x86_and_floating_point_env.html">x86 and
floating-point env</a></span></dt>
</dl></dd>
<dt><span class="section"><a href="context/reference.html">Reference</a></span></dt>
<dt><span class="section"><a href="context/todo.html">Todo</a></span></dt>
<dt><span class="section"><a href="context/acknowledgements.html">Acknowledgments</a></span></dt>
</dl>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"><p><small>Last revised: June 25, 2013 at 22:03:37 GMT</small></p></td>
<td align="right"><div class="copyright-footer"></div></td>
</tr></table>
<hr>
<div class="spirit-nav"><a accesskey="n" href="context/overview.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a></div>
</body>
</html>
| ryancoleman/autodock-vina | boost_1_54_0/libs/context/doc/html/index.html | HTML | apache-2.0 | 3,581 |
/*
* 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.
*/
package com.facebook.presto.metadata;
import com.facebook.presto.Session;
import com.facebook.presto.spi.CatalogSchemaName;
import com.facebook.presto.spi.ColumnMetadata;
import com.facebook.presto.spi.ConnectorTableMetadata;
import com.facebook.presto.spi.PrestoException;
import com.facebook.presto.spi.SchemaTableName;
import com.facebook.presto.spi.security.PrestoPrincipal;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.sql.analyzer.SemanticException;
import com.facebook.presto.sql.tree.GrantorSpecification;
import com.facebook.presto.sql.tree.Node;
import com.facebook.presto.sql.tree.PrincipalSpecification;
import com.facebook.presto.sql.tree.QualifiedName;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.Optional;
import static com.facebook.presto.spi.StandardErrorCode.SYNTAX_ERROR;
import static com.facebook.presto.spi.security.PrincipalType.ROLE;
import static com.facebook.presto.spi.security.PrincipalType.USER;
import static com.facebook.presto.sql.analyzer.SemanticErrorCode.CATALOG_NOT_SPECIFIED;
import static com.facebook.presto.sql.analyzer.SemanticErrorCode.INVALID_SCHEMA_NAME;
import static com.facebook.presto.sql.analyzer.SemanticErrorCode.SCHEMA_NOT_SPECIFIED;
import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.String.format;
import static java.util.Locale.ENGLISH;
import static java.util.Objects.requireNonNull;
public final class MetadataUtil
{
private MetadataUtil() {}
public static void checkTableName(String catalogName, Optional<String> schemaName, Optional<String> tableName)
{
checkCatalogName(catalogName);
schemaName.ifPresent(name -> checkLowerCase(name, "schemaName"));
tableName.ifPresent(name -> checkLowerCase(name, "tableName"));
checkArgument(schemaName.isPresent() || !tableName.isPresent(), "tableName specified but schemaName is missing");
}
public static String checkCatalogName(String catalogName)
{
return checkLowerCase(catalogName, "catalogName");
}
public static String checkSchemaName(String schemaName)
{
return checkLowerCase(schemaName, "schemaName");
}
public static String checkTableName(String tableName)
{
return checkLowerCase(tableName, "tableName");
}
public static void checkObjectName(String catalogName, String schemaName, String objectName)
{
checkLowerCase(catalogName, "catalogName");
checkLowerCase(schemaName, "schemaName");
checkLowerCase(objectName, "objectName");
}
public static String checkLowerCase(String value, String name)
{
if (value == null) {
throw new NullPointerException(format("%s is null", name));
}
checkArgument(value.equals(value.toLowerCase(ENGLISH)), "%s is not lowercase: %s", name, value);
return value;
}
public static ColumnMetadata findColumnMetadata(ConnectorTableMetadata tableMetadata, String columnName)
{
for (ColumnMetadata columnMetadata : tableMetadata.getColumns()) {
if (columnName.equals(columnMetadata.getName())) {
return columnMetadata;
}
}
return null;
}
public static String createCatalogName(Session session, Node node)
{
Optional<String> sessionCatalog = session.getCatalog();
if (!sessionCatalog.isPresent()) {
throw new SemanticException(CATALOG_NOT_SPECIFIED, node, "Session catalog must be set");
}
return sessionCatalog.get();
}
public static CatalogSchemaName createCatalogSchemaName(Session session, Node node, Optional<QualifiedName> schema)
{
String catalogName = session.getCatalog().orElse(null);
String schemaName = session.getSchema().orElse(null);
if (schema.isPresent()) {
List<String> parts = schema.get().getParts();
if (parts.size() > 2) {
throw new SemanticException(INVALID_SCHEMA_NAME, node, "Too many parts in schema name: %s", schema.get());
}
if (parts.size() == 2) {
catalogName = parts.get(0);
}
schemaName = schema.get().getSuffix();
}
if (catalogName == null) {
throw new SemanticException(CATALOG_NOT_SPECIFIED, node, "Catalog must be specified when session catalog is not set");
}
if (schemaName == null) {
throw new SemanticException(SCHEMA_NOT_SPECIFIED, node, "Schema must be specified when session schema is not set");
}
return new CatalogSchemaName(catalogName, schemaName);
}
public static QualifiedObjectName createQualifiedObjectName(Session session, Node node, QualifiedName name)
{
requireNonNull(session, "session is null");
requireNonNull(name, "name is null");
if (name.getParts().size() > 3) {
throw new PrestoException(SYNTAX_ERROR, format("Too many dots in table name: %s", name));
}
List<String> parts = Lists.reverse(name.getParts());
String objectName = parts.get(0);
String schemaName = (parts.size() > 1) ? parts.get(1) : session.getSchema().orElseThrow(() ->
new SemanticException(SCHEMA_NOT_SPECIFIED, node, "Schema must be specified when session schema is not set"));
String catalogName = (parts.size() > 2) ? parts.get(2) : session.getCatalog().orElseThrow(() ->
new SemanticException(CATALOG_NOT_SPECIFIED, node, "Catalog must be specified when session catalog is not set"));
return new QualifiedObjectName(catalogName, schemaName, objectName);
}
public static QualifiedName createQualifiedName(QualifiedObjectName name)
{
return QualifiedName.of(name.getCatalogName(), name.getSchemaName(), name.getObjectName());
}
public static PrestoPrincipal createPrincipal(Session session, GrantorSpecification specification)
{
GrantorSpecification.Type type = specification.getType();
switch (type) {
case PRINCIPAL:
return createPrincipal(specification.getPrincipal().get());
case CURRENT_USER:
return new PrestoPrincipal(USER, session.getIdentity().getUser());
case CURRENT_ROLE:
// TODO: will be implemented once the "SET ROLE" statement is introduced
throw new UnsupportedOperationException("CURRENT_ROLE is not yet supported");
default:
throw new IllegalArgumentException("Unsupported type: " + type);
}
}
public static PrestoPrincipal createPrincipal(PrincipalSpecification specification)
{
PrincipalSpecification.Type type = specification.getType();
switch (type) {
case UNSPECIFIED:
case USER:
return new PrestoPrincipal(USER, specification.getName().getValue());
case ROLE:
return new PrestoPrincipal(ROLE, specification.getName().getValue());
default:
throw new IllegalArgumentException("Unsupported type: " + type);
}
}
public static boolean tableExists(Metadata metadata, Session session, String table)
{
if (!session.getCatalog().isPresent() || !session.getSchema().isPresent()) {
return false;
}
QualifiedObjectName name = new QualifiedObjectName(session.getCatalog().get(), session.getSchema().get(), table);
return metadata.getTableHandle(session, name).isPresent();
}
public static class SchemaMetadataBuilder
{
public static SchemaMetadataBuilder schemaMetadataBuilder()
{
return new SchemaMetadataBuilder();
}
private final ImmutableMap.Builder<SchemaTableName, ConnectorTableMetadata> tables = ImmutableMap.builder();
public SchemaMetadataBuilder table(ConnectorTableMetadata tableMetadata)
{
tables.put(tableMetadata.getTable(), tableMetadata);
return this;
}
public ImmutableMap<SchemaTableName, ConnectorTableMetadata> build()
{
return tables.build();
}
}
public static class TableMetadataBuilder
{
public static TableMetadataBuilder tableMetadataBuilder(String schemaName, String tableName)
{
return new TableMetadataBuilder(new SchemaTableName(schemaName, tableName));
}
public static TableMetadataBuilder tableMetadataBuilder(SchemaTableName tableName)
{
return new TableMetadataBuilder(tableName);
}
private final SchemaTableName tableName;
private final ImmutableList.Builder<ColumnMetadata> columns = ImmutableList.builder();
private final ImmutableMap.Builder<String, Object> properties = ImmutableMap.builder();
private final Optional<String> comment;
private TableMetadataBuilder(SchemaTableName tableName)
{
this(tableName, Optional.empty());
}
private TableMetadataBuilder(SchemaTableName tableName, Optional<String> comment)
{
this.tableName = tableName;
this.comment = comment;
}
public TableMetadataBuilder column(String columnName, Type type)
{
columns.add(new ColumnMetadata(columnName, type));
return this;
}
public TableMetadataBuilder property(String name, Object value)
{
properties.put(name, value);
return this;
}
public ConnectorTableMetadata build()
{
return new ConnectorTableMetadata(tableName, columns.build(), properties.build(), comment);
}
}
}
| stewartpark/presto | presto-main/src/main/java/com/facebook/presto/metadata/MetadataUtil.java | Java | apache-2.0 | 10,472 |
namespace FluentAssertions.Equivalency
{
/// <summary>
/// Provides information on a particular property during an assertion for structural equality of two object graphs.
/// </summary>
public interface IEquivalencyValidationContext : ISubjectInfo
{
/// <summary>
/// Gets the value of the <see cref="MatchingExpectationProperty"/>.
/// </summary>
object Expectation { get; }
/// <summary>
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </summary>
string Because { get; }
/// <summary>
/// Zero or more objects to format using the placeholders in <see cref="Because"/>.
/// </summary>
object[] BecauseArgs { get; }
/// <summary>
/// Gets a value indicating whether the current context represents the root of the object graph.
/// </summary>
bool IsRoot { get; }
/// <summary>
/// Gets the value of the <see cref="ISelectionContext.PropertyInfo"/>
/// </summary>
object Subject { get; }
/// <summary>
/// Gets or sets a value indicating that the root of the graph is a collection so all type-specific options apply on
/// the collection type and not on the root itself.
/// </summary>
bool RootIsCollection { get; set; }
}
} | ben-m-lucas/FluentAssertions | Src/Core/Equivalency/IEquivalencyValidationContext.cs | C# | apache-2.0 | 1,540 |
---
id: version-2.7.3-admin-api-namespaces
title: Managing Namespaces
sidebar_label: Namespaces
original_id: admin-api-namespaces
---
Pulsar [namespaces](reference-terminology.md#namespace) are logical groupings of [topics](reference-terminology.md#topic).
Namespaces can be managed via:
* The [`namespaces`](reference-pulsar-admin.md#clusters) command of the [`pulsar-admin`](reference-pulsar-admin.md) tool
* The `/admin/v2/namespaces` endpoint of the admin {@inject: rest:REST:/} API
* The `namespaces` method of the {@inject: javadoc:PulsarAdmin:/admin/org/apache/pulsar/client/admin/PulsarAdmin} object in the [Java API](client-libraries-java.md)
## Namespaces resources
### Create namespaces
You can create new namespaces under a given [tenant](reference-terminology.md#tenant).
<!--DOCUSAURUS_CODE_TABS-->
<!--pulsar-admin-->
Use the [`create`](reference-pulsar-admin.md#namespaces-create) subcommand and specify the namespace by name:
```shell
$ pulsar-admin namespaces create test-tenant/test-namespace
```
<!--REST API-->
{@inject: endpoint|PUT|/admin/v2/namespaces/:tenant/:namespace|operation/createNamespace?version=[[pulsar:version_number]]}
<!--Java-->
```java
admin.namespaces().createNamespace(namespace);
```
<!--END_DOCUSAURUS_CODE_TABS-->
### Get policies
You can fetch the current policies associated with a namespace at any time.
<!--DOCUSAURUS_CODE_TABS-->
<!--pulsar-admin-->
Use the [`policies`](reference-pulsar-admin.md#namespaces-policies) subcommand and specify the namespace:
```shell
$ pulsar-admin namespaces policies test-tenant/test-namespace
{
"auth_policies": {
"namespace_auth": {},
"destination_auth": {}
},
"replication_clusters": [],
"bundles_activated": true,
"bundles": {
"boundaries": [
"0x00000000",
"0xffffffff"
],
"numBundles": 1
},
"backlog_quota_map": {},
"persistence": null,
"latency_stats_sample_rate": {},
"message_ttl_in_seconds": 0,
"retention_policies": null,
"deleted": false
}
```
<!--REST API-->
{@inject: endpoint|GET|/admin/v2/namespaces/:tenant/:namespace|operation/getPolicies?version=[[pulsar:version_number]]}
<!--Java-->
```java
admin.namespaces().getPolicies(namespace);
```
<!--END_DOCUSAURUS_CODE_TABS-->
### List namespaces
You can list all namespaces within a given Pulsar [tenant](reference-terminology.md#tenant).
<!--DOCUSAURUS_CODE_TABS-->
<!--pulsar-admin-->
Use the [`list`](reference-pulsar-admin.md#namespaces-list) subcommand and specify the tenant:
```shell
$ pulsar-admin namespaces list test-tenant
test-tenant/ns1
test-tenant/ns2
```
<!--REST API-->
{@inject: endpoint|GET|/admin/v2/namespaces/:tenant|operation/getTenantNamespaces?version=[[pulsar:version_number]]}
<!--Java-->
```java
admin.namespaces().getNamespaces(tenant);
```
<!--END_DOCUSAURUS_CODE_TABS-->
### Delete namespaces
You can delete existing namespaces from a tenant.
<!--DOCUSAURUS_CODE_TABS-->
<!--pulsar-admin-->
Use the [`delete`](reference-pulsar-admin.md#namespaces-delete) subcommand and specify the namespace:
```shell
$ pulsar-admin namespaces delete test-tenant/ns1
```
<!--REST API-->
{@inject: endpoint|DELETE|/admin/v2/namespaces/:tenant/:namespace|operation/deleteNamespace?version=[[pulsar:version_number]]}
<!--Java-->
```java
admin.namespaces().deleteNamespace(namespace);
```
<!--END_DOCUSAURUS_CODE_TABS-->
### Configure replication clusters
#### Set replication cluster
It sets replication clusters for a namespace, so Pulsar can internally replicate publish message from one colo to another colo.
<!--DOCUSAURUS_CODE_TABS-->
<!--pulsar-admin-->
```
$ pulsar-admin namespaces set-clusters test-tenant/ns1 \
--clusters cl1
```
<!--REST API-->
```
{@inject: endpoint|POST|/admin/v2/namespaces/:tenant/:namespace/replication|operation/setNamespaceReplicationClusters?version=[[pulsar:version_number]]}
```
<!--Java-->
```java
admin.namespaces().setNamespaceReplicationClusters(namespace, clusters);
```
<!--END_DOCUSAURUS_CODE_TABS-->
#### Get replication cluster
It gives a list of replication clusters for a given namespace.
<!--DOCUSAURUS_CODE_TABS-->
<!--pulsar-admin-->
```
$ pulsar-admin namespaces get-clusters test-tenant/cl1/ns1
```
```
cl2
```
<!--REST API-->
```
{@inject: endpoint|GET|/admin/v2/namespaces/:tenant/:namespace/replication|operation/getNamespaceReplicationClusters?version=[[pulsar:version_number]]}
```
<!--Java-->
```java
admin.namespaces().getNamespaceReplicationClusters(namespace)
```
<!--END_DOCUSAURUS_CODE_TABS-->
### Configure backlog quota policies
#### Set backlog quota policies
Backlog quota helps the broker to restrict bandwidth/storage of a namespace once it reaches a certain threshold limit. Admin can set the limit and take corresponding action after the limit is reached.
1. producer_request_hold: broker will hold and not persist produce request payload
2. producer_exception: broker disconnects with the client by giving an exception.
3. consumer_backlog_eviction: broker will start discarding backlog messages
Backlog quota restriction can be taken care by defining restriction of backlog-quota-type: destination_storage
<!--DOCUSAURUS_CODE_TABS-->
<!--pulsar-admin-->
```
$ pulsar-admin namespaces set-backlog-quota --limit 10 --policy producer_request_hold test-tenant/ns1
```
```
N/A
```
<!--REST API-->
```
{@inject: endpoint|POST|/admin/v2/namespaces/:tenant/:namespace/backlogQuota|operation/setBacklogQuota?version=[[pulsar:version_number]]}
```
<!--Java-->
```java
admin.namespaces().setBacklogQuota(namespace, new BacklogQuota(limit, policy))
```
<!--END_DOCUSAURUS_CODE_TABS-->
#### Get backlog quota policies
It shows a configured backlog quota for a given namespace.
<!--DOCUSAURUS_CODE_TABS-->
<!--pulsar-admin-->
```
$ pulsar-admin namespaces get-backlog-quotas test-tenant/ns1
```
```json
{
"destination_storage": {
"limit": 10,
"policy": "producer_request_hold"
}
}
```
<!--REST API-->
```
{@inject: endpoint|GET|/admin/v2/namespaces/:tenant/:namespace/backlogQuotaMap|operation/getBacklogQuotaMap?version=[[pulsar:version_number]]}
```
<!--Java-->
```java
admin.namespaces().getBacklogQuotaMap(namespace);
```
<!--END_DOCUSAURUS_CODE_TABS-->
#### Remove backlog quota policies
It removes backlog quota policies for a given namespace
<!--DOCUSAURUS_CODE_TABS-->
<!--pulsar-admin-->
```
$ pulsar-admin namespaces remove-backlog-quota test-tenant/ns1
```
```
N/A
```
<!--REST API-->
```
{@inject: endpoint|DELETE|/admin/v2/namespaces/:tenant/:namespace/backlogQuota|operation/removeBacklogQuota?version=[[pulsar:version_number]]}
```
<!--Java-->
```java
admin.namespaces().removeBacklogQuota(namespace, backlogQuotaType)
```
<!--END_DOCUSAURUS_CODE_TABS-->
### Configure persistence policies
#### Set persistence policies
Persistence policies allow to configure persistency-level for all topic messages under a given namespace.
- Bookkeeper-ack-quorum: Number of acks (guaranteed copies) to wait for each entry, default: 0
- Bookkeeper-ensemble: Number of bookies to use for a topic, default: 0
- Bookkeeper-write-quorum: How many writes to make of each entry, default: 0
- Ml-mark-delete-max-rate: Throttling rate of mark-delete operation (0 means no throttle), default: 0.0
<!--DOCUSAURUS_CODE_TABS-->
<!--pulsar-admin-->
```
$ pulsar-admin namespaces set-persistence --bookkeeper-ack-quorum 2 --bookkeeper-ensemble 3 --bookkeeper-write-quorum 2 --ml-mark-delete-max-rate 0 test-tenant/ns1
```
```
N/A
```
<!--REST API-->
```
{@inject: endpoint|POST|/admin/v2/namespaces/:tenant/:namespace/persistence|operation/setPersistence?version=[[pulsar:version_number]]}
```
<!--Java-->
```java
admin.namespaces().setPersistence(namespace,new PersistencePolicies(bookkeeperEnsemble, bookkeeperWriteQuorum,bookkeeperAckQuorum,managedLedgerMaxMarkDeleteRate))
```
<!--END_DOCUSAURUS_CODE_TABS-->
#### Get persistence policies
It shows the configured persistence policies of a given namespace.
<!--DOCUSAURUS_CODE_TABS-->
<!--pulsar-admin-->
```
$ pulsar-admin namespaces get-persistence test-tenant/ns1
```
```json
{
"bookkeeperEnsemble": 3,
"bookkeeperWriteQuorum": 2,
"bookkeeperAckQuorum": 2,
"managedLedgerMaxMarkDeleteRate": 0
}
```
<!--REST API-->
```
{@inject: endpoint|GET|/admin/v2/namespaces/:tenant/:namespace/persistence|operation/getPersistence?version=[[pulsar:version_number]]}
```
<!--Java-->
```java
admin.namespaces().getPersistence(namespace)
```
<!--END_DOCUSAURUS_CODE_TABS-->
### Configure namespace bundles
#### Unload namespace bundles
The namespace bundle is a virtual group of topics which belong to the same namespace. If the broker gets overloaded with the number of bundles, this command can help unload a bundle from that broker, so it can be served by some other less-loaded brokers. The namespace bundle ID ranges from 0x00000000 to 0xffffffff.
<!--DOCUSAURUS_CODE_TABS-->
<!--pulsar-admin-->
```
$ pulsar-admin namespaces unload --bundle 0x00000000_0xffffffff test-tenant/ns1
```
```
N/A
```
<!--REST API-->
```
{@inject: endpoint|PUT|/admin/v2/namespaces/:tenant/:namespace/{bundle}/unload|operation/unloadNamespaceBundle?version=[[pulsar:version_number]]}
```
<!--Java-->
```java
admin.namespaces().unloadNamespaceBundle(namespace, bundle)
```
<!--END_DOCUSAURUS_CODE_TABS-->
#### Split namespace bundles
Each namespace bundle can contain multiple topics and each bundle can be served by only one broker.
If a single bundle is creating an excessive load on a broker, an admin splits the bundle using this command permitting one or more of the new bundles to be unloaded thus spreading the load across the brokers.
<!--DOCUSAURUS_CODE_TABS-->
<!--pulsar-admin-->
```
$ pulsar-admin namespaces split-bundle --bundle 0x00000000_0xffffffff test-tenant/ns1
```
```
N/A
```
<!--REST API-->
```
{@inject: endpoint|PUT|/admin/v2/namespaces/:tenant/:namespace/{bundle}/split|operation/splitNamespaceBundle?version=[[pulsar:version_number]]}
```
<!--Java-->
```java
admin.namespaces().splitNamespaceBundle(namespace, bundle)
```
<!--END_DOCUSAURUS_CODE_TABS-->
### Configure message TTL
#### Set message-ttl
It configures message’s time to live (in seconds) duration.
<!--DOCUSAURUS_CODE_TABS-->
<!--pulsar-admin-->
```
$ pulsar-admin namespaces set-message-ttl --messageTTL 100 test-tenant/ns1
```
```
N/A
```
<!--REST API-->
```
{@inject: endpoint|POST|/admin/v2/namespaces/:tenant/:namespace/messageTTL|operation/setNamespaceMessageTTL?version=[[pulsar:version_number]]}
```
<!--Java-->
```java
admin.namespaces().setNamespaceMessageTTL(namespace, messageTTL)
```
<!--END_DOCUSAURUS_CODE_TABS-->
#### Get message-ttl
It gives a message ttl of configured namespace.
<!--DOCUSAURUS_CODE_TABS-->
<!--pulsar-admin-->
```
$ pulsar-admin namespaces get-message-ttl test-tenant/ns1
```
```
100
```
<!--REST API-->
```
{@inject: endpoint|GET|/admin/v2/namespaces/:tenant/:namespace/messageTTL|operation/getNamespaceMessageTTL?version=[[pulsar:version_number]]}
```
<!--Java-->
```java
admin.namespaces().getNamespaceMessageTTL(namespace)
```
<!--END_DOCUSAURUS_CODE_TABS-->
#### Remove message-ttl
Remove a message TTL of the configured namespace.
<!--DOCUSAURUS_CODE_TABS-->
<!--pulsar-admin-->
```
$ pulsar-admin namespaces remove-message-ttl test-tenant/ns1
```
```
100
```
<!--REST API-->
```
{@inject: endpoint|DELETE|/admin/v2/namespaces/:tenant/:namespace/messageTTL|operation/removeNamespaceMessageTTL?version=[[pulsar:version_number]]}
```
<!--Java-->
```java
admin.namespaces().removeNamespaceMessageTTL(namespace)
```
<!--END_DOCUSAURUS_CODE_TABS-->
### Clear backlog
#### Clear namespace backlog
It clears all message backlog for all the topics that belong to a specific namespace. You can also clear backlog for a specific subscription as well.
<!--DOCUSAURUS_CODE_TABS-->
<!--pulsar-admin-->
```
$ pulsar-admin namespaces clear-backlog --sub my-subscription test-tenant/ns1
```
```
N/A
```
<!--REST API-->
```
{@inject: endpoint|POST|/admin/v2/namespaces/:tenant/:namespace/clearBacklog|operation/clearNamespaceBacklogForSubscription?version=[[pulsar:version_number]]}
```
<!--Java-->
```java
admin.namespaces().clearNamespaceBacklogForSubscription(namespace, subscription)
```
<!--END_DOCUSAURUS_CODE_TABS-->
#### Clear bundle backlog
It clears all message backlog for all the topics that belong to a specific NamespaceBundle. You can also clear backlog for a specific subscription as well.
<!--DOCUSAURUS_CODE_TABS-->
<!--pulsar-admin-->
```
$ pulsar-admin namespaces clear-backlog --bundle 0x00000000_0xffffffff --sub my-subscription test-tenant/ns1
```
```
N/A
```
<!--REST API-->
```
{@inject: endpoint|POST|/admin/v2/namespaces/:tenant/:namespace/{bundle}/clearBacklog|operation?version=[[pulsar:version_number]]/clearNamespaceBundleBacklogForSubscription}
```
<!--Java-->
```java
admin.namespaces().clearNamespaceBundleBacklogForSubscription(namespace, bundle, subscription)
```
<!--END_DOCUSAURUS_CODE_TABS-->
### Configure retention
#### Set retention
Each namespace contains multiple topics and the retention size (storage size) of each topic should not exceed a specific threshold or it should be stored for a certain period. This command helps configure the retention size and time of topics in a given namespace.
<!--DOCUSAURUS_CODE_TABS-->
<!--pulsar-admin-->
```
$ pulsar-admin set-retention --size 10 --time 100 test-tenant/ns1
```
```
N/A
```
<!--REST API-->
```
{@inject: endpoint|POST|/admin/v2/namespaces/:tenant/:namespace/retention|operation/setRetention?version=[[pulsar:version_number]]}
```
<!--Java-->
```java
admin.namespaces().setRetention(namespace, new RetentionPolicies(retentionTimeInMin, retentionSizeInMB))
```
<!--END_DOCUSAURUS_CODE_TABS-->
#### Get retention
It shows retention information of a given namespace.
<!--DOCUSAURUS_CODE_TABS-->
<!--pulsar-admin-->
```
$ pulsar-admin namespaces get-retention test-tenant/ns1
```
```json
{
"retentionTimeInMinutes": 10,
"retentionSizeInMB": 100
}
```
<!--REST API-->
```
{@inject: endpoint|GET|/admin/v2/namespaces/:tenant/:namespace/retention|operation/getRetention?version=[[pulsar:version_number]]}
```
<!--Java-->
```java
admin.namespaces().getRetention(namespace)
```
<!--END_DOCUSAURUS_CODE_TABS-->
### Configure dispatch throttling for topics
#### Set dispatch throttling for topics
It sets message dispatch rate for all the topics under a given namespace.
The dispatch rate can be restricted by the number of messages per X seconds (`msg-dispatch-rate`) or by the number of message-bytes per X second (`byte-dispatch-rate`).
dispatch rate is in second and it can be configured with `dispatch-rate-period`. Default value of `msg-dispatch-rate` and `byte-dispatch-rate` is -1 which
disables the throttling.
> **Note**
> - If neither `clusterDispatchRate` nor `topicDispatchRate` is configured, dispatch throttling is disabled.
> >
> - If `topicDispatchRate` is not configured, `clusterDispatchRate` takes effect.
> >
> - If `topicDispatchRate` is configured, `topicDispatchRate` takes effect.
<!--DOCUSAURUS_CODE_TABS-->
<!--pulsar-admin-->
```
$ pulsar-admin namespaces set-dispatch-rate test-tenant/ns1 \
--msg-dispatch-rate 1000 \
--byte-dispatch-rate 1048576 \
--dispatch-rate-period 1
```
<!--REST API-->
```
{@inject: endpoint|POST|/admin/v2/namespaces/:tenant/:namespace/dispatchRate|operation/setDispatchRate?version=[[pulsar:version_number]]}
```
<!--Java-->
```java
admin.namespaces().setDispatchRate(namespace, new DispatchRate(1000, 1048576, 1))
```
<!--END_DOCUSAURUS_CODE_TABS-->
#### Get configured message-rate for topics
It shows configured message-rate for the namespace (topics under this namespace can dispatch this many messages per second)
<!--DOCUSAURUS_CODE_TABS-->
<!--pulsar-admin-->
```
$ pulsar-admin namespaces get-dispatch-rate test-tenant/ns1
```
```json
{
"dispatchThrottlingRatePerTopicInMsg" : 1000,
"dispatchThrottlingRatePerTopicInByte" : 1048576,
"ratePeriodInSecond" : 1
}
```
<!--REST API-->
```
{@inject: endpoint|GET|/admin/v2/namespaces/:tenant/:namespace/dispatchRate|operation/getDispatchRate?version=[[pulsar:version_number]]}
```
<!--Java-->
```java
admin.namespaces().getDispatchRate(namespace)
```
<!--END_DOCUSAURUS_CODE_TABS-->
### Configure dispatch throttling for subscription
#### Set dispatch throttling for subscription
It sets message dispatch rate for all the subscription of topics under a given namespace.
The dispatch rate can be restricted by the number of messages per X seconds (`msg-dispatch-rate`) or by the number of message-bytes per X second (`byte-dispatch-rate`).
dispatch rate is in second and it can be configured with `dispatch-rate-period`. Default value of `msg-dispatch-rate` and `byte-dispatch-rate` is -1 which
disables the throttling.
<!--DOCUSAURUS_CODE_TABS-->
<!--pulsar-admin-->
```
$ pulsar-admin namespaces set-subscription-dispatch-rate test-tenant/ns1 \
--msg-dispatch-rate 1000 \
--byte-dispatch-rate 1048576 \
--dispatch-rate-period 1
```
<!--REST API-->
```
{@inject: endpoint|POST|/admin/v2/namespaces/:tenant/:namespace/subscriptionDispatchRate|operation/setDispatchRate?version=[[pulsar:version_number]]}
```
<!--Java-->
```java
admin.namespaces().setSubscriptionDispatchRate(namespace, new DispatchRate(1000, 1048576, 1))
```
<!--END_DOCUSAURUS_CODE_TABS-->
#### Get configured message-rate for subscription
It shows configured message-rate for the namespace (topics under this namespace can dispatch this many messages per second)
<!--DOCUSAURUS_CODE_TABS-->
<!--pulsar-admin-->
```
$ pulsar-admin namespaces get-subscription-dispatch-rate test-tenant/ns1
```
```json
{
"dispatchThrottlingRatePerTopicInMsg" : 1000,
"dispatchThrottlingRatePerTopicInByte" : 1048576,
"ratePeriodInSecond" : 1
}
```
<!--REST API-->
```
{@inject: endpoint|GET|/admin/v2/namespaces/:tenant/:namespace/subscriptionDispatchRate|operation/getDispatchRate?version=[[pulsar:version_number]]}
```
<!--Java-->
```java
admin.namespaces().getSubscriptionDispatchRate(namespace)
```
<!--END_DOCUSAURUS_CODE_TABS-->
### Configure dispatch throttling for replicator
#### Set dispatch throttling for replicator
It sets message dispatch rate for all the replicator between replication clusters under a given namespace.
The dispatch rate can be restricted by the number of messages per X seconds (`msg-dispatch-rate`) or by the number of message-bytes per X second (`byte-dispatch-rate`).
dispatch rate is in second and it can be configured with `dispatch-rate-period`. Default value of `msg-dispatch-rate` and `byte-dispatch-rate` is -1 which
disables the throttling.
<!--DOCUSAURUS_CODE_TABS-->
<!--pulsar-admin-->
```
$ pulsar-admin namespaces set-replicator-dispatch-rate test-tenant/ns1 \
--msg-dispatch-rate 1000 \
--byte-dispatch-rate 1048576 \
--dispatch-rate-period 1
```
<!--REST API-->
```
{@inject: endpoint|POST|/admin/v2/namespaces/:tenant/:namespace/replicatorDispatchRate|operation/setDispatchRate?version=[[pulsar:version_number]]}
```
<!--Java-->
```java
admin.namespaces().setReplicatorDispatchRate(namespace, new DispatchRate(1000, 1048576, 1))
```
<!--END_DOCUSAURUS_CODE_TABS-->
#### Get configured message-rate for replicator
It shows configured message-rate for the namespace (topics under this namespace can dispatch this many messages per second)
<!--DOCUSAURUS_CODE_TABS-->
<!--pulsar-admin-->
```
$ pulsar-admin namespaces get-replicator-dispatch-rate test-tenant/ns1
```
```json
{
"dispatchThrottlingRatePerTopicInMsg" : 1000,
"dispatchThrottlingRatePerTopicInByte" : 1048576,
"ratePeriodInSecond" : 1
}
```
<!--REST API-->
```
{@inject: endpoint|GET|/admin/v2/namespaces/:tenant/:namespace/replicatorDispatchRate|operation/getDispatchRate?version=[[pulsar:version_number]]}
```
<!--Java-->
```java
admin.namespaces().getReplicatorDispatchRate(namespace)
```
<!--END_DOCUSAURUS_CODE_TABS-->
### Configure deduplication snapshot interval
#### Get deduplication snapshot interval
It shows configured `deduplicationSnapshotInterval` for a namespace (Each topic under the namespace will take a deduplication snapshot according to this interval)
<!--DOCUSAURUS_CODE_TABS-->
<!--pulsar-admin-->
```
$ pulsar-admin namespaces get-deduplication-snapshot-interval test-tenant/ns1
```
<!--REST API-->
```
{@inject: endpoint|GET|/admin/v2/namespaces/:tenant/:namespace/deduplicationSnapshotInterval?version=[[pulsar:version_number]]}
```
<!--Java-->
```java
admin.namespaces().getDeduplicationSnapshotInterval(namespace)
```
<!--END_DOCUSAURUS_CODE_TABS-->
#### Set deduplication snapshot interval
Set configured `deduplicationSnapshotInterval` for a namespace. Each topic under the namespace will take a deduplication snapshot according to this interval.
`brokerDeduplicationEnabled` must be set to `true` for this property to take effect.
<!--DOCUSAURUS_CODE_TABS-->
<!--pulsar-admin-->
```
$ pulsar-admin namespaces set-deduplication-snapshot-interval test-tenant/ns1 --interval 1000
```
<!--REST API-->
```
{@inject: endpoint|POST|/admin/v2/namespaces/:tenant/:namespace/deduplicationSnapshotInterval?version=[[pulsar:version_number]]}
```
```json
{
"interval": 1000
}
```
<!--Java-->
```java
admin.namespaces().setDeduplicationSnapshotInterval(namespace, 1000)
```
<!--END_DOCUSAURUS_CODE_TABS-->
#### Remove deduplication snapshot interval
Remove configured `deduplicationSnapshotInterval` of a namespace (Each topic under the namespace will take a deduplication snapshot according to this interval)
<!--DOCUSAURUS_CODE_TABS-->
<!--pulsar-admin-->
```
$ pulsar-admin namespaces remove-deduplication-snapshot-interval test-tenant/ns1
```
<!--REST API-->
```
{@inject: endpoint|POST|/admin/v2/namespaces/:tenant/:namespace/deduplicationSnapshotInterval?version=[[pulsar:version_number]]}
```
<!--Java-->
```java
admin.namespaces().removeDeduplicationSnapshotInterval(namespace)
```
<!--END_DOCUSAURUS_CODE_TABS-->
### Namespace isolation
You can use the [Pulsar isolation policy](administration-isolation.md) to allocate resources (broker and bookie) for a namespace.
### Unload namespaces from a broker
You can unload a namespace, or a [namespace bundle](reference-terminology.md#namespace-bundle), from the Pulsar [broker](reference-terminology.md#broker) that is currently responsible for it.
#### pulsar-admin
Use the [`unload`](reference-pulsar-admin.md#unload) subcommand of the [`namespaces`](reference-pulsar-admin.md#namespaces) command.
<!--DOCUSAURUS_CODE_TABS-->
<!--pulsar-admin-->
```shell
$ pulsar-admin namespaces unload my-tenant/my-ns
```
<!--REST-->
```
{@inject: endpoint|PUT|/admin/v2/namespaces/:tenant/:namespace/unload|operation/unloadNamespace?version=[[pulsar:version_number]]}
```
<!--Java-->
```java
admin.namespaces().unload(namespace)
```
<!--END_DOCUSAURUS_CODE_TABS-->
| massakam/pulsar | site2/website/versioned_docs/version-2.7.3/admin-api-namespaces.md | Markdown | apache-2.0 | 22,974 |
/*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* 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.
*/
package org.kie.workbench.common.stunner.cm.factory;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.workbench.common.stunner.bpmn.factory.BPMNDiagramFactory;
import org.kie.workbench.common.stunner.cm.CaseManagementDefinitionSet;
import org.kie.workbench.common.stunner.cm.definition.CaseManagementDiagram;
import org.kie.workbench.common.stunner.core.diagram.Metadata;
import org.kie.workbench.common.stunner.core.graph.Graph;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@RunWith(MockitoJUnitRunner.class)
public class CaseManagementDiagramFactoryImplTest {
private static final String NAME = "diagram1";
@Mock
private Graph graph;
@Mock
private Metadata metadata;
@Mock
private BPMNDiagramFactory bpmnDiagramFactory;
private CaseManagementDiagramFactoryImpl factory;
@Before
public void setup() {
factory = new CaseManagementDiagramFactoryImpl(bpmnDiagramFactory);
}
@Test
public void assertSetDiagramType() {
factory.init();
verify(bpmnDiagramFactory,
times(1)).setDiagramType(eq(CaseManagementDiagram.class));
}
@Test
public void assertDefSetType() {
assertEquals(CaseManagementDefinitionSet.class,
factory.getDefinitionSetType());
}
@Test
public void assertMetadataType() {
assertEquals(Metadata.class,
factory.getMetadataType());
}
@Test
@SuppressWarnings("unchecked")
public void testBuild() {
factory.init();
factory.build(NAME,
metadata,
graph);
verify(bpmnDiagramFactory,
times(1)).build(eq(NAME),
eq(metadata),
eq(graph));
}
}
| etirelli/kie-wb-common | kie-wb-common-stunner/kie-wb-common-stunner-sets/kie-wb-common-stunner-case-mgmt/kie-wb-common-stunner-case-mgmt-api/src/test/java/org/kie/workbench/common/stunner/cm/factory/CaseManagementDiagramFactoryImplTest.java | Java | apache-2.0 | 2,654 |
package netlink
import (
"fmt"
"net"
)
type Filter interface {
Attrs() *FilterAttrs
Type() string
}
// FilterAttrs represents a netlink filter. A filter is associated with a link,
// has a handle and a parent. The root filter of a device should have a
// parent == HANDLE_ROOT.
type FilterAttrs struct {
LinkIndex int
Handle uint32
Parent uint32
Priority uint16 // lower is higher priority
Protocol uint16 // unix.ETH_P_*
}
func (q FilterAttrs) String() string {
return fmt.Sprintf("{LinkIndex: %d, Handle: %s, Parent: %s, Priority: %d, Protocol: %d}", q.LinkIndex, HandleStr(q.Handle), HandleStr(q.Parent), q.Priority, q.Protocol)
}
type TcAct int32
const (
TC_ACT_UNSPEC TcAct = -1
TC_ACT_OK TcAct = 0
TC_ACT_RECLASSIFY TcAct = 1
TC_ACT_SHOT TcAct = 2
TC_ACT_PIPE TcAct = 3
TC_ACT_STOLEN TcAct = 4
TC_ACT_QUEUED TcAct = 5
TC_ACT_REPEAT TcAct = 6
TC_ACT_REDIRECT TcAct = 7
TC_ACT_JUMP TcAct = 0x10000000
)
func (a TcAct) String() string {
switch a {
case TC_ACT_UNSPEC:
return "unspec"
case TC_ACT_OK:
return "ok"
case TC_ACT_RECLASSIFY:
return "reclassify"
case TC_ACT_SHOT:
return "shot"
case TC_ACT_PIPE:
return "pipe"
case TC_ACT_STOLEN:
return "stolen"
case TC_ACT_QUEUED:
return "queued"
case TC_ACT_REPEAT:
return "repeat"
case TC_ACT_REDIRECT:
return "redirect"
case TC_ACT_JUMP:
return "jump"
}
return fmt.Sprintf("0x%x", int32(a))
}
type TcPolAct int32
const (
TC_POLICE_UNSPEC TcPolAct = TcPolAct(TC_ACT_UNSPEC)
TC_POLICE_OK TcPolAct = TcPolAct(TC_ACT_OK)
TC_POLICE_RECLASSIFY TcPolAct = TcPolAct(TC_ACT_RECLASSIFY)
TC_POLICE_SHOT TcPolAct = TcPolAct(TC_ACT_SHOT)
TC_POLICE_PIPE TcPolAct = TcPolAct(TC_ACT_PIPE)
)
func (a TcPolAct) String() string {
switch a {
case TC_POLICE_UNSPEC:
return "unspec"
case TC_POLICE_OK:
return "ok"
case TC_POLICE_RECLASSIFY:
return "reclassify"
case TC_POLICE_SHOT:
return "shot"
case TC_POLICE_PIPE:
return "pipe"
}
return fmt.Sprintf("0x%x", int32(a))
}
type ActionAttrs struct {
Index int
Capab int
Action TcAct
Refcnt int
Bindcnt int
}
func (q ActionAttrs) String() string {
return fmt.Sprintf("{Index: %d, Capab: %x, Action: %s, Refcnt: %d, Bindcnt: %d}", q.Index, q.Capab, q.Action.String(), q.Refcnt, q.Bindcnt)
}
// Action represents an action in any supported filter.
type Action interface {
Attrs() *ActionAttrs
Type() string
}
type GenericAction struct {
ActionAttrs
}
func (action *GenericAction) Type() string {
return "generic"
}
func (action *GenericAction) Attrs() *ActionAttrs {
return &action.ActionAttrs
}
type BpfAction struct {
ActionAttrs
Fd int
Name string
}
func (action *BpfAction) Type() string {
return "bpf"
}
func (action *BpfAction) Attrs() *ActionAttrs {
return &action.ActionAttrs
}
type ConnmarkAction struct {
ActionAttrs
Zone uint16
}
func (action *ConnmarkAction) Type() string {
return "connmark"
}
func (action *ConnmarkAction) Attrs() *ActionAttrs {
return &action.ActionAttrs
}
func NewConnmarkAction() *ConnmarkAction {
return &ConnmarkAction{
ActionAttrs: ActionAttrs{
Action: TC_ACT_PIPE,
},
}
}
type MirredAct uint8
func (a MirredAct) String() string {
switch a {
case TCA_EGRESS_REDIR:
return "egress redir"
case TCA_EGRESS_MIRROR:
return "egress mirror"
case TCA_INGRESS_REDIR:
return "ingress redir"
case TCA_INGRESS_MIRROR:
return "ingress mirror"
}
return "unknown"
}
const (
TCA_EGRESS_REDIR MirredAct = 1 /* packet redirect to EGRESS*/
TCA_EGRESS_MIRROR MirredAct = 2 /* mirror packet to EGRESS */
TCA_INGRESS_REDIR MirredAct = 3 /* packet redirect to INGRESS*/
TCA_INGRESS_MIRROR MirredAct = 4 /* mirror packet to INGRESS */
)
type MirredAction struct {
ActionAttrs
MirredAction MirredAct
Ifindex int
}
func (action *MirredAction) Type() string {
return "mirred"
}
func (action *MirredAction) Attrs() *ActionAttrs {
return &action.ActionAttrs
}
func NewMirredAction(redirIndex int) *MirredAction {
return &MirredAction{
ActionAttrs: ActionAttrs{
Action: TC_ACT_STOLEN,
},
MirredAction: TCA_EGRESS_REDIR,
Ifindex: redirIndex,
}
}
type TunnelKeyAct int8
const (
TCA_TUNNEL_KEY_SET TunnelKeyAct = 1 // set tunnel key
TCA_TUNNEL_KEY_UNSET TunnelKeyAct = 2 // unset tunnel key
)
type TunnelKeyAction struct {
ActionAttrs
Action TunnelKeyAct
SrcAddr net.IP
DstAddr net.IP
KeyID uint32
DestPort uint16
}
func (action *TunnelKeyAction) Type() string {
return "tunnel_key"
}
func (action *TunnelKeyAction) Attrs() *ActionAttrs {
return &action.ActionAttrs
}
func NewTunnelKeyAction() *TunnelKeyAction {
return &TunnelKeyAction{
ActionAttrs: ActionAttrs{
Action: TC_ACT_PIPE,
},
}
}
type SkbEditAction struct {
ActionAttrs
QueueMapping *uint16
PType *uint16
Priority *uint32
Mark *uint32
}
func (action *SkbEditAction) Type() string {
return "skbedit"
}
func (action *SkbEditAction) Attrs() *ActionAttrs {
return &action.ActionAttrs
}
func NewSkbEditAction() *SkbEditAction {
return &SkbEditAction{
ActionAttrs: ActionAttrs{
Action: TC_ACT_PIPE,
},
}
}
type PoliceAction struct {
ActionAttrs
Rate uint32 // in byte per second
Burst uint32 // in byte
RCellLog int
Mtu uint32
Mpu uint16 // in byte
PeakRate uint32 // in byte per second
PCellLog int
AvRate uint32 // in byte per second
Overhead uint16
LinkLayer int
ExceedAction TcPolAct
NotExceedAction TcPolAct
}
func (action *PoliceAction) Type() string {
return "police"
}
func (action *PoliceAction) Attrs() *ActionAttrs {
return &action.ActionAttrs
}
func NewPoliceAction() *PoliceAction {
return &PoliceAction{
RCellLog: -1,
PCellLog: -1,
LinkLayer: 1, // ETHERNET
ExceedAction: TC_POLICE_RECLASSIFY,
NotExceedAction: TC_POLICE_OK,
}
}
// MatchAll filters match all packets
type MatchAll struct {
FilterAttrs
ClassId uint32
Actions []Action
}
func (filter *MatchAll) Attrs() *FilterAttrs {
return &filter.FilterAttrs
}
func (filter *MatchAll) Type() string {
return "matchall"
}
type FwFilter struct {
FilterAttrs
ClassId uint32
InDev string
Mask uint32
Police *PoliceAction
}
func (filter *FwFilter) Attrs() *FilterAttrs {
return &filter.FilterAttrs
}
func (filter *FwFilter) Type() string {
return "fw"
}
type BpfFilter struct {
FilterAttrs
ClassId uint32
Fd int
Name string
DirectAction bool
Id int
Tag string
}
func (filter *BpfFilter) Type() string {
return "bpf"
}
func (filter *BpfFilter) Attrs() *FilterAttrs {
return &filter.FilterAttrs
}
// GenericFilter filters represent types that are not currently understood
// by this netlink library.
type GenericFilter struct {
FilterAttrs
FilterType string
}
func (filter *GenericFilter) Attrs() *FilterAttrs {
return &filter.FilterAttrs
}
func (filter *GenericFilter) Type() string {
return filter.FilterType
}
| cilium/cilium | vendor/github.com/vishvananda/netlink/filter.go | GO | apache-2.0 | 7,078 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>basic_raw_socket::message_peek</title>
<link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../basic_raw_socket.html" title="basic_raw_socket">
<link rel="prev" href="message_out_of_band.html" title="basic_raw_socket::message_out_of_band">
<link rel="next" href="native.html" title="basic_raw_socket::native">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td>
<td align="center"><a href="../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="message_out_of_band.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../basic_raw_socket.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="native.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h4 class="title">
<a name="boost_asio.reference.basic_raw_socket.message_peek"></a><a class="link" href="message_peek.html" title="basic_raw_socket::message_peek">basic_raw_socket::message_peek</a>
</h4></div></div></div>
<p>
<span class="emphasis"><em>Inherited from socket_base.</em></span>
</p>
<p>
<a class="indexterm" name="idp61856200"></a>
Peek at incoming data without removing it from
the input queue.
</p>
<pre class="programlisting"><span class="keyword">static</span> <span class="keyword">const</span> <span class="keyword">int</span> <span class="identifier">message_peek</span> <span class="special">=</span> <span class="identifier">implementation_defined</span><span class="special">;</span>
</pre>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2013 Christopher M. Kohlhoff<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="message_out_of_band.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../basic_raw_socket.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="native.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| NixaSoftware/CVis | venv/bin/doc/html/boost_asio/reference/basic_raw_socket/message_peek.html | HTML | apache-2.0 | 3,508 |
/**
* Licensed to Big Data Genomics (BDG) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The BDG licenses this file
* to you 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.
*/
package org.bdgenomics.adam.algorithms.consensus
import org.apache.spark.rdd.RDD
import org.bdgenomics.adam.rdd.ADAMContext._
import org.bdgenomics.adam.rich.RichAlignmentRecord
import org.bdgenomics.adam.util.ADAMFunSuite
import org.bdgenomics.formats.avro.AlignmentRecord
class ConsensusGeneratorFromReadsSuite extends ADAMFunSuite {
val cg = new ConsensusGeneratorFromReads
def artificial_reads: RDD[AlignmentRecord] = {
val path = resourcePath("artificial.sam")
sc.loadAlignments(path)
}
sparkTest("checking search for consensus list for artificial reads") {
val consensus = cg.findConsensus(artificial_reads.map(new RichAlignmentRecord(_))
.collect()
.toSeq)
assert(consensus.size === 2)
}
}
| allenday/adam | adam-core/src/test/scala/org/bdgenomics/adam/algorithms/consensus/ConsensusGeneratorFromReadsSuite.scala | Scala | apache-2.0 | 1,536 |
/*
* #%L
* SparkCommerce Common Libraries
* %%
* Copyright (C) 2015 Spark Commerce
* %%
*/
package org.sparkcommerce.common.email.service.message;
import java.util.Map;
public interface EmailServiceProducer {
public void send(final Map props);
}
| akdasari/SparkCommon | src/main/java/org/sparkcommerce/common/email/service/message/EmailServiceProducer.java | Java | apache-2.0 | 265 |
// Note: Consider the API unstable until the code supports at least three different image formats or transports.
// NOTE: Keep this in sync with docs/atomic-signature.md and docs/atomic-signature-embedded.json!
package signature
import (
"encoding/json"
"fmt"
"time"
"github.com/containers/image/v5/version"
digest "github.com/opencontainers/go-digest"
"github.com/pkg/errors"
)
const (
signatureType = "atomic container signature"
)
// InvalidSignatureError is returned when parsing an invalid signature.
type InvalidSignatureError struct {
msg string
}
func (err InvalidSignatureError) Error() string {
return err.msg
}
// Signature is a parsed content of a signature.
// The only way to get this structure from a blob should be as a return value from a successful call to verifyAndExtractSignature below.
type Signature struct {
DockerManifestDigest digest.Digest
DockerReference string // FIXME: more precise type?
}
// untrustedSignature is a parsed content of a signature.
type untrustedSignature struct {
UntrustedDockerManifestDigest digest.Digest
UntrustedDockerReference string // FIXME: more precise type?
UntrustedCreatorID *string
// This is intentionally an int64; the native JSON float64 type would allow to represent _some_ sub-second precision,
// but not nearly enough (with current timestamp values, a single unit in the last place is on the order of hundreds of nanoseconds).
// So, this is explicitly an int64, and we reject fractional values. If we did need more precise timestamps eventually,
// we would add another field, UntrustedTimestampNS int64.
UntrustedTimestamp *int64
}
// UntrustedSignatureInformation is information available in an untrusted signature.
// This may be useful when debugging signature verification failures,
// or when managing a set of signatures on a single image.
//
// WARNING: Do not use the contents of this for ANY security decisions,
// and be VERY CAREFUL about showing this information to humans in any way which suggest that these values “are probably” reliable.
// There is NO REASON to expect the values to be correct, or not intentionally misleading
// (including things like “✅ Verified by $authority”)
type UntrustedSignatureInformation struct {
UntrustedDockerManifestDigest digest.Digest
UntrustedDockerReference string // FIXME: more precise type?
UntrustedCreatorID *string
UntrustedTimestamp *time.Time
UntrustedShortKeyIdentifier string
}
// newUntrustedSignature returns an untrustedSignature object with
// the specified primary contents and appropriate metadata.
func newUntrustedSignature(dockerManifestDigest digest.Digest, dockerReference string) untrustedSignature {
// Use intermediate variables for these values so that we can take their addresses.
// Golang guarantees that they will have a new address on every execution.
creatorID := "atomic " + version.Version
timestamp := time.Now().Unix()
return untrustedSignature{
UntrustedDockerManifestDigest: dockerManifestDigest,
UntrustedDockerReference: dockerReference,
UntrustedCreatorID: &creatorID,
UntrustedTimestamp: ×tamp,
}
}
// Compile-time check that untrustedSignature implements json.Marshaler
var _ json.Marshaler = (*untrustedSignature)(nil)
// MarshalJSON implements the json.Marshaler interface.
func (s untrustedSignature) MarshalJSON() ([]byte, error) {
if s.UntrustedDockerManifestDigest == "" || s.UntrustedDockerReference == "" {
return nil, errors.New("Unexpected empty signature content")
}
critical := map[string]interface{}{
"type": signatureType,
"image": map[string]string{"docker-manifest-digest": s.UntrustedDockerManifestDigest.String()},
"identity": map[string]string{"docker-reference": s.UntrustedDockerReference},
}
optional := map[string]interface{}{}
if s.UntrustedCreatorID != nil {
optional["creator"] = *s.UntrustedCreatorID
}
if s.UntrustedTimestamp != nil {
optional["timestamp"] = *s.UntrustedTimestamp
}
signature := map[string]interface{}{
"critical": critical,
"optional": optional,
}
return json.Marshal(signature)
}
// Compile-time check that untrustedSignature implements json.Unmarshaler
var _ json.Unmarshaler = (*untrustedSignature)(nil)
// UnmarshalJSON implements the json.Unmarshaler interface
func (s *untrustedSignature) UnmarshalJSON(data []byte) error {
err := s.strictUnmarshalJSON(data)
if err != nil {
if formatErr, ok := err.(jsonFormatError); ok {
err = InvalidSignatureError{msg: formatErr.Error()}
}
}
return err
}
// strictUnmarshalJSON is UnmarshalJSON, except that it may return the internal jsonFormatError error type.
// Splitting it into a separate function allows us to do the jsonFormatError → InvalidSignatureError in a single place, the caller.
func (s *untrustedSignature) strictUnmarshalJSON(data []byte) error {
var critical, optional json.RawMessage
if err := paranoidUnmarshalJSONObjectExactFields(data, map[string]interface{}{
"critical": &critical,
"optional": &optional,
}); err != nil {
return err
}
var creatorID string
var timestamp float64
var gotCreatorID, gotTimestamp = false, false
if err := paranoidUnmarshalJSONObject(optional, func(key string) interface{} {
switch key {
case "creator":
gotCreatorID = true
return &creatorID
case "timestamp":
gotTimestamp = true
return ×tamp
default:
var ignore interface{}
return &ignore
}
}); err != nil {
return err
}
if gotCreatorID {
s.UntrustedCreatorID = &creatorID
}
if gotTimestamp {
intTimestamp := int64(timestamp)
if float64(intTimestamp) != timestamp {
return InvalidSignatureError{msg: "Field optional.timestamp is not is not an integer"}
}
s.UntrustedTimestamp = &intTimestamp
}
var t string
var image, identity json.RawMessage
if err := paranoidUnmarshalJSONObjectExactFields(critical, map[string]interface{}{
"type": &t,
"image": &image,
"identity": &identity,
}); err != nil {
return err
}
if t != signatureType {
return InvalidSignatureError{msg: fmt.Sprintf("Unrecognized signature type %s", t)}
}
var digestString string
if err := paranoidUnmarshalJSONObjectExactFields(image, map[string]interface{}{
"docker-manifest-digest": &digestString,
}); err != nil {
return err
}
s.UntrustedDockerManifestDigest = digest.Digest(digestString)
return paranoidUnmarshalJSONObjectExactFields(identity, map[string]interface{}{
"docker-reference": &s.UntrustedDockerReference,
})
}
// Sign formats the signature and returns a blob signed using mech and keyIdentity
// (If it seems surprising that this is a method on untrustedSignature, note that there
// isn’t a good reason to think that a key used by the user is trusted by any component
// of the system just because it is a private key — actually the presence of a private key
// on the system increases the likelihood of an a successful attack on that private key
// on that particular system.)
func (s untrustedSignature) sign(mech SigningMechanism, keyIdentity string, passphrase string) ([]byte, error) {
json, err := json.Marshal(s)
if err != nil {
return nil, err
}
if newMech, ok := mech.(signingMechanismWithPassphrase); ok {
return newMech.SignWithPassphrase(json, keyIdentity, passphrase)
}
if passphrase != "" {
return nil, errors.New("signing mechanism does not support passphrases")
}
return mech.Sign(json, keyIdentity)
}
// signatureAcceptanceRules specifies how to decide whether an untrusted signature is acceptable.
// We centralize the actual parsing and data extraction in verifyAndExtractSignature; this supplies
// the policy. We use an object instead of supplying func parameters to verifyAndExtractSignature
// because the functions have the same or similar types, so there is a risk of exchanging the functions;
// named members of this struct are more explicit.
type signatureAcceptanceRules struct {
validateKeyIdentity func(string) error
validateSignedDockerReference func(string) error
validateSignedDockerManifestDigest func(digest.Digest) error
}
// verifyAndExtractSignature verifies that unverifiedSignature has been signed, and that its principal components
// match expected values, both as specified by rules, and returns it
func verifyAndExtractSignature(mech SigningMechanism, unverifiedSignature []byte, rules signatureAcceptanceRules) (*Signature, error) {
signed, keyIdentity, err := mech.Verify(unverifiedSignature)
if err != nil {
return nil, err
}
if err := rules.validateKeyIdentity(keyIdentity); err != nil {
return nil, err
}
var unmatchedSignature untrustedSignature
if err := json.Unmarshal(signed, &unmatchedSignature); err != nil {
return nil, InvalidSignatureError{msg: err.Error()}
}
if err := rules.validateSignedDockerManifestDigest(unmatchedSignature.UntrustedDockerManifestDigest); err != nil {
return nil, err
}
if err := rules.validateSignedDockerReference(unmatchedSignature.UntrustedDockerReference); err != nil {
return nil, err
}
// signatureAcceptanceRules have accepted this value.
return &Signature{
DockerManifestDigest: unmatchedSignature.UntrustedDockerManifestDigest,
DockerReference: unmatchedSignature.UntrustedDockerReference,
}, nil
}
// GetUntrustedSignatureInformationWithoutVerifying extracts information available in an untrusted signature,
// WITHOUT doing any cryptographic verification.
// This may be useful when debugging signature verification failures,
// or when managing a set of signatures on a single image.
//
// WARNING: Do not use the contents of this for ANY security decisions,
// and be VERY CAREFUL about showing this information to humans in any way which suggest that these values “are probably” reliable.
// There is NO REASON to expect the values to be correct, or not intentionally misleading
// (including things like “✅ Verified by $authority”)
func GetUntrustedSignatureInformationWithoutVerifying(untrustedSignatureBytes []byte) (*UntrustedSignatureInformation, error) {
// NOTE: This should eventually do format autodetection.
mech, _, err := NewEphemeralGPGSigningMechanism([]byte{})
if err != nil {
return nil, err
}
defer mech.Close()
untrustedContents, shortKeyIdentifier, err := mech.UntrustedSignatureContents(untrustedSignatureBytes)
if err != nil {
return nil, err
}
var untrustedDecodedContents untrustedSignature
if err := json.Unmarshal(untrustedContents, &untrustedDecodedContents); err != nil {
return nil, InvalidSignatureError{msg: err.Error()}
}
var timestamp *time.Time // = nil
if untrustedDecodedContents.UntrustedTimestamp != nil {
ts := time.Unix(*untrustedDecodedContents.UntrustedTimestamp, 0)
timestamp = &ts
}
return &UntrustedSignatureInformation{
UntrustedDockerManifestDigest: untrustedDecodedContents.UntrustedDockerManifestDigest,
UntrustedDockerReference: untrustedDecodedContents.UntrustedDockerReference,
UntrustedCreatorID: untrustedDecodedContents.UntrustedCreatorID,
UntrustedTimestamp: timestamp,
UntrustedShortKeyIdentifier: shortKeyIdentifier,
}, nil
}
| TomSweeneyRedHat/buildah | vendor/github.com/containers/image/v5/signature/signature.go | GO | apache-2.0 | 11,181 |
package gov.hhs.onc.dcdt.data;
import org.springframework.dao.DataAccessException;
public class ToolBeanDataAccessException extends DataAccessException {
private final static long serialVersionUID = 0L;
public ToolBeanDataAccessException() {
super(null);
}
public ToolBeanDataAccessException(Throwable cause) {
super(null, cause);
}
public ToolBeanDataAccessException(String msg) {
super(msg);
}
public ToolBeanDataAccessException(String msg, Throwable cause) {
super(msg, cause);
}
}
| mkotelba/dcdt | dcdt-core/src/main/java/gov/hhs/onc/dcdt/data/ToolBeanDataAccessException.java | Java | apache-2.0 | 559 |
/*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you 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.
*/
package org.jboss.netty.handler.codec.http;
import static org.jboss.netty.handler.codec.http.HttpConstants.*;
import org.jboss.netty.buffer.ChannelBuffer;
/**
* Encodes an {@link HttpResponse} or an {@link HttpChunk} into
* a {@link ChannelBuffer}.
*/
public class HttpResponseEncoder extends HttpMessageEncoder {
@Override
protected void encodeInitialLine(ChannelBuffer buf, HttpMessage message) throws Exception {
HttpResponse response = (HttpResponse) message;
encodeAscii(response.getProtocolVersion().toString(), buf);
buf.writeByte(SP);
encodeAscii(String.valueOf(response.getStatus().getCode()), buf);
buf.writeByte(SP);
encodeAscii(String.valueOf(response.getStatus().getReasonPhrase()), buf);
buf.writeByte(CR);
buf.writeByte(LF);
}
}
| KeyNexus/netty | src/main/java/org/jboss/netty/handler/codec/http/HttpResponseEncoder.java | Java | apache-2.0 | 1,462 |
/*
* ******************************************************************************
* Copyright 2014-2019 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file 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.
* ****************************************************************************
*/
// This code is auto-generated, do not modify
package com.spectralogic.ds3client.commands.parsers;
import com.spectralogic.ds3client.commands.parsers.interfaces.AbstractResponseParser;
import com.spectralogic.ds3client.commands.parsers.utils.ResponseParserUtils;
import com.spectralogic.ds3client.commands.spectrads3.ClearSuspectBlobTapesSpectraS3Response;
import com.spectralogic.ds3client.networking.WebResponse;
import java.io.IOException;
public class ClearSuspectBlobTapesSpectraS3ResponseParser extends AbstractResponseParser<ClearSuspectBlobTapesSpectraS3Response> {
private final int[] expectedStatusCodes = new int[]{204};
@Override
public ClearSuspectBlobTapesSpectraS3Response parseXmlResponse(final WebResponse response) throws IOException {
final int statusCode = response.getStatusCode();
if (ResponseParserUtils.validateStatusCode(statusCode, expectedStatusCodes)) {
switch (statusCode) {
case 204:
//There is no payload, return an empty response handler
return new ClearSuspectBlobTapesSpectraS3Response(this.getChecksum(), this.getChecksumType());
default:
assert false: "validateStatusCode should have made it impossible to reach this line";
}
}
throw ResponseParserUtils.createFailedRequest(response, expectedStatusCodes);
}
} | rpmoore/ds3_java_sdk | ds3-sdk/src/main/java/com/spectralogic/ds3client/commands/parsers/ClearSuspectBlobTapesSpectraS3ResponseParser.java | Java | apache-2.0 | 2,153 |
/**
* Copyright 2007-2015, Kaazing Corporation. All rights reserved.
*
* 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.
*/
package org.kaazing.k3po.driver.internal.netty.bootstrap.agrona;
import static org.kaazing.k3po.driver.internal.netty.bootstrap.agrona.AgronaChannel.NATIVE_BUFFER_FACTORY;
import org.kaazing.k3po.driver.internal.netty.bootstrap.channel.DefaultServerChannelConfig;
public class DefaultAgronaServerChannelConfig extends DefaultServerChannelConfig implements AgronaChannelConfig {
public DefaultAgronaServerChannelConfig() {
super();
setBufferFactory(NATIVE_BUFFER_FACTORY);
}
}
| jfallows/k3po | driver/src/main/java/org/kaazing/k3po/driver/internal/netty/bootstrap/agrona/DefaultAgronaServerChannelConfig.java | Java | apache-2.0 | 1,132 |
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) > [puppeteer](./puppeteer.md) > [Page](./puppeteer.page.md) > [mouse](./puppeteer.page.mouse.md)
## Page.mouse property
<b>Signature:</b>
```typescript
get mouse(): Mouse;
```
| puppeteer/puppeteer | website/versioned_docs/version-9.1.1/puppeteer.page.mouse.md | Markdown | apache-2.0 | 289 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
package org.apache.xml.security.test.dom.transforms;
import org.apache.xml.security.Init;
import org.apache.xml.security.exceptions.AlgorithmAlreadyRegisteredException;
import org.apache.xml.security.transforms.Transform;
import org.apache.xml.security.transforms.Transforms;
import org.apache.xml.security.transforms.implementations.TransformC14N11;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class TransformTest {
static {
Init.init();
}
@org.junit.jupiter.api.Test
public void testAlreadyRegisteredException() throws Exception {
assertThrows(AlgorithmAlreadyRegisteredException.class, () ->
Transform.register(Transforms.TRANSFORM_C14N11_OMIT_COMMENTS, TransformC14N11.class)
);
}
@org.junit.jupiter.api.Test
public void testAlreadyRegisteredExceptionFromString() throws Exception {
assertThrows(AlgorithmAlreadyRegisteredException.class, () ->
Transform.register(Transforms.TRANSFORM_C14N11_OMIT_COMMENTS,
TransformC14N11.class.getName())
);
}
} | apache/santuario-java | src/test/java/org/apache/xml/security/test/dom/transforms/TransformTest.java | Java | apache-2.0 | 1,911 |
<?php
/**
* COSPLAYPROP.COM 字符集转换类
* @author: 未知
* @version: v2.2
* ---------------------------------------------
* $Id: cls_iconv.php 17063 2010-03-25 06:35:46Z liuhui $
*/
class Chinese
{
/**
* 存放 GB <-> UNICODE 对照表的内容
* @变量类型
* @访问 内部
*/
var $unicode_table = array();
/**
* 访问中文繁简互换表的文件指针
*
* @变量类型 对象
* @访问 内部
*/
var $ctf;
/**
* 等待转换的字符串
* @变量类型
* @访问 内部
*/
var $SourceText = '';
/**
* Chinese 的运行配置
*
* @变量类型 数组
* @访问 公开
*/
var $config = array(
'codetable_dir' => '', // 存放各种语言互换表的目录
'source_lang' => '', // 字符的原编码
'target_lang' => '', // 转换后的编码
'GBtoBIG5_table' => 'gb-big5.table', // 简体中文转换为繁体中文的对照表
'BIG5toGB_table' => 'big5-gb.table', // 繁体中文转换为简体中文的对照表
'GBtoUTF8_table' => 'gb_utf8.php', // 简体中文转换为UTF-8的对照表
'BIG5toUTF8_table' => 'big5_utf8.php' // 繁体中文转换为UTF-8的对照表
);
var $iconv_enabled = false; // 是否存在 ICONV 模块,默认为否
var $mbstring_enabled = false; // 是否存在 MBSTRING 模块,默认为否
/**
* Chinese 的悉构函数
*
* 详细说明
* @形参 字符串 $source_lang 为需要转换的字符串的原编码
* 字符串 $target_lang 为转换的目标编码
* 字符串 $SourceText 为等待转换的字符串
* @访问 公开
* @返回值 无
* @throws
*/
function Chinese($dir = './')
{
$this->config['codetable_dir'] = dirname(__FILE__)."/codetable/";
if (function_exists('iconv'))
{
$this->iconv_enabled = true;
}
if (PHP_VERSION >= '5.0' && function_exists('mb_convert_encoding') && function_exists('mb_list_encodings'))
{
$encodings = mb_list_encodings();
if (in_array('UTF-8', $encodings) == true && in_array('BIG-5', $encodings) == true && in_array('CP936', $encodings) == true) // CP936 就是 GBK 字符集的别名
{
$this->mbstring_enabled = true;
}
}
}
function Convert($source_lang, $target_lang, $source_string = '')
{
/* 如果字符串为空或者字符串不需要转换,直接返回 */
/*if ($source_string == '' || preg_match("/[\x80-\xFF]+/", $source_string) == 0)
{
return $source_string;
}*/
if ($source_lang)
{
$this->config['source_lang'] = $this->_lang($source_lang);
}
if ($target_lang)
{
$this->config['target_lang'] = $this->_lang($target_lang);
}
/* 如果编码相同,直接返回 */
if ($this->config['source_lang'] == $this->config['target_lang'])
{
return $source_string;
}
$this->SourceText = $source_string;
if (($this->iconv_enabled || $this->mbstring_enabled) && !($this->config['source_lang'] == 'GBK' && $this->config['target_lang'] == 'BIG-5'))
{
if ($this->config['target_lang'] != 'UNICODE')
{
$string = $this->_convert_iconv_mbstring($this->SourceText, $this->config['target_lang'], $this->config['source_lang']);
/* 如果正确转换 */
if ($string)
{
return $string;
}
}
else
{
$string = '';
$text = $SourceText;
while ($text)
{
if (ord(substr($text, 0, 1)) > 127)
{
if ($this->config['source_lang'] != 'UTF-8')
{
$char = $this->_convert_iconv_mbstring(substr($text, 0, 2), 'UTF-8', $this->config['source_lang']);
}
else
{
$char = substr($text, 0, 3);
}
/* 如果转换出错 */
if ($char == '')
{
$string = '';
break;
}
switch (strlen($char))
{
case 1:
$uchar = ord($char);
break;
case 2:
$uchar = (ord($char[0]) & 0x3f) << 6;
$uchar += ord($char[1]) & 0x3f;
break;
case 3:
$uchar = (ord($char[0]) & 0x1f) << 12;
$uchar += (ord($char[1]) & 0x3f) << 6;
$uchar += ord($char[2]) & 0x3f;
break;
case 4:
$uchar = (ord($char[0]) & 0x0f) << 18;
$uchar += (ord($char[1]) & 0x3f) << 12;
$uchar += (ord($char[2]) & 0x3f) << 6;
$uchar += ord($char[3]) & 0x3f;
break;
}
$string .= '&#x' . dechex($uchar) . ';';
if ($this->config['source_lang'] != 'UTF-8')
{
$text = substr($text, 2);
}
else
{
$text = substr($text, 3);
}
}
else
{
$string .= substr($text, 0, 1);
$text = substr($text, 1);
}
}
/* 如果正确转换 */
if ($string)
{
return $string;
}
}
}
$this->OpenTable();
// 判断是否为中文繁、简转换
if (($this->config['source_lang'] == 'GBK' || $this->config['source_lang'] == 'BIG-5') && ($this->config['target_lang'] == 'GBK' || $this->config['target_lang'] == 'BIG-5'))
{
return $this->GBtoBIG5();
}
// 判断是否为简体、繁体中文与UTF8转换
if (($this->config['source_lang'] == 'GBK' || $this->config['source_lang'] == 'BIG-5' || $this->config['source_lang'] == 'UTF-8') && ($this->config['target_lang'] == 'UTF-8' || $this->config['target_lang'] == 'GBK' || $this->config['target_lang'] == 'BIG-5'))
{
return $this->CHStoUTF8();
}
// 判断是否为简体、繁体中文与UNICODE转换
if (($this->config['source_lang'] == 'GBK' || $this->config['source_lang'] == 'BIG-5') && $this->config['target_lang'] == 'UNICODE')
{
return $this->CHStoUNICODE();
}
}
function _lang($lang)
{
$lang = strtoupper($lang);
if (substr($lang, 0, 2) == 'GB')
{
return 'GBK';
}
else
{
switch(substr($lang, 0, 3))
{
case 'BIG':
return 'BIG-5';
case 'UTF':
return 'UTF-8';
case 'UNI':
return 'UNICODE';
default:
return '';
}
}
}
function _convert_iconv_mbstring($string, $target_lang, $source_lang)
{
if ($this->iconv_enabled)
{
$return_string = @iconv($source_lang, $target_lang, $string);
if ($return_string !== false)
{
return $return_string;
}
}
if ($this->mbstring_enabled)
{
if ($source_lang == 'GBK')
{
$source_lang = 'CP936';
}
if ($target_lang == 'GBK')
{
$target_lang = 'CP936';
}
$return_string = @mb_convert_encoding($string, $target_lang, $source_lang);
if ($return_string !== false)
{
return $return_string;
}
else
{
return false;
}
}
}
/**
* 将 16 进制转换为 2 进制字符
*
* 详细说明
* @形参 $hexdata 为16进制的编码
* @访问 内部
* @返回 字符串
* @throws
*/
function _hex2bin($hexdata)
{
$bindata = '';
for ($i = 0, $count = strlen($hexdata); $i < $count; $i += 2)
{
$bindata .= chr(hexdec($hexdata{$i} . $hexdata{$i + 1}));
}
return $bindata;
}
/**
* 打开对照表
*
* 详细说明
* @形参
* @访问 内部
* @返回 无
* @throws
*/
function OpenTable()
{
static $gb_utf8_table = NULL;
static $gb_unicode_table = NULL;
static $utf8_gb_table = NULL;
static $big5_utf8_table = NULL;
static $big5_unicode_table = NULL;
static $utf8_big5_table = NULL;
// 假如原编码为简体中文的话
if ($this->config['source_lang'] == 'GBK')
{
// 假如转换目标编码为繁体中文的话
if ($this->config['target_lang'] == 'BIG-5')
{
$this->ctf = @fopen($this->config['codetable_dir'] . $this->config['GBtoBIG5_table'], 'rb');
if (is_null($this->ctf))
{
echo '打开打开转换表文件失败!';
exit;
}
}
// 假如转换目标编码为 UTF8 的话
if ($this->config['target_lang'] == 'UTF-8')
{
if ($gb_utf8_table === NULL)
{
require_once($this->config['codetable_dir'] . $this->config['GBtoUTF8_table']);
}
$this->unicode_table = $gb_utf8_table;
}
// 假如转换目标编码为 UNICODE 的话
if ($this->config['target_lang'] == 'UNICODE')
{
if ($gb_unicode_table === NULL)
{
if (isset($gb_utf8_table) === false)
{
require_once($this->config['codetable_dir'] . $this->config['GBtoUTF8_table']);
}
foreach ($gb_utf8_table AS $key => $value)
{
$gb_unicode_table[$key] = substr($value, 2);
}
}
$this->unicode_table = $gb_unicode_table;
}
}
// 假如原编码为繁体中文的话
if ($this->config['source_lang'] == 'BIG-5')
{
// 假如转换目标编码为简体中文的话
if ($this->config['target_lang'] == 'GBK')
{
$this->ctf = @fopen($this->config['codetable_dir'] . $this->config['BIG5toGB_table'], 'rb');
if (is_null($this->ctf))
{
echo '打开打开转换表文件失败!';
exit;
}
}
// 假如转换目标编码为 UTF8 的话
if ($this->config['target_lang'] == 'UTF-8')
{
if ($big5_utf8_table === NULL)
{
require_once($this->config['codetable_dir'] . $this->config['BIG5toUTF8_table']);
}
$this->unicode_table = $big5_utf8_table;
}
// 假如转换目标编码为 UNICODE 的话
if ($this->config['target_lang'] == 'UNICODE')
{
if ($big5_unicode_table === NULL)
{
if (isset($big5_utf8_table) === false)
{
require_once($this->config['codetable_dir'] . $this->config['BIG5toUTF8_table']);
}
foreach ($big5_utf8_table AS $key => $value)
{
$big5_unicode_table[$key] = substr($value, 2);
}
}
$this->unicode_table = $big5_unicode_table;
}
}
// 假如原编码为 UTF8 的话
if ($this->config['source_lang'] == 'UTF-8')
{
// 假如转换目标编码为 GBK 的话
if ($this->config['target_lang'] == 'GBK')
{
if ($utf8_gb_table === NULL)
{
if (isset($gb_utf8_table) === false)
{
require_once($this->config['codetable_dir'] . $this->config['GBtoUTF8_table']);
}
foreach ($gb_utf8_table AS $key => $value)
{
$utf8_gb_table[hexdec($value)] = '0x' . dechex($key);
}
}
$this->unicode_table = $utf8_gb_table;
}
// 假如转换目标编码为 BIG5 的话
if ($this->config['target_lang'] == 'BIG-5')
{
if ($utf8_big5_table === NULL)
{
if (isset($big5_utf8_table) === false)
{
require_once($this->config['codetable_dir'] . $this->config['BIG5toUTF8_table']);
}
foreach ($big5_utf8_table AS $key => $value)
{
$utf8_big5_table[hexdec($value)] = '0x' . dechex($key);
}
}
$this->unicode_table = $utf8_big5_table;
}
}
}
/**
* 将简体、繁体中文的 UNICODE 编码转换为 UTF8 字符
*
* 详细说明
* @形参 数字 $c 简体中文汉字的UNICODE编码的10进制
* @访问 内部
* @返回 字符串
* @throws
*/
function CHSUtoUTF8($c)
{
$str='';
if ($c < 0x80)
{
$str .= $c;
}
elseif ($c < 0x800)
{
$str .= (0xC0 | $c >> 6);
$str .= (0x80 | $c & 0x3F);
}
elseif ($c < 0x10000)
{
$str .= (0xE0 | $c >> 12);
$str .= (0x80 | $c >> 6 & 0x3F);
$str .= (0x80 | $c & 0x3F);
}
elseif ($c < 0x200000)
{
$str .= (0xF0 | $c >> 18);
$str .= (0x80 | $c >> 12 & 0x3F);
$str .= (0x80 | $c >> 6 & 0x3F);
$str .= (0x80 | $c & 0x3F);
}
return $str;
}
/**
* 简体、繁体中文 <-> UTF8 互相转换的函数
*
* 详细说明
* @形参
* @访问 内部
* @返回 字符串
* @throws
*/
function CHStoUTF8()
{
if ($this->config['source_lang'] == 'BIG-5' || $this->config['source_lang'] == 'GBK')
{
$ret = '';
while ($this->SourceText)
{
if (ord($this->SourceText{0}) > 127)
{
if ($this->config['source_lang'] == 'BIG-5')
{
$utf8 = $this->CHSUtoUTF8(hexdec(@$this->unicode_table[hexdec(bin2hex($this->SourceText{0} . $this->SourceText{1}))]));
}
if ($this->config['source_lang'] == 'GBK')
{
$utf8 = $this->CHSUtoUTF8(hexdec(@$this->unicode_table[hexdec(bin2hex($this->SourceText{0} . $this->SourceText{1})) - 0x8080]));
}
for ($i = 0, $count = strlen($utf8); $i < $count; $i += 3)
{
$ret .= chr(substr($utf8, $i, 3));
}
$this->SourceText = substr($this->SourceText, 2, strlen($this->SourceText));
}
else
{
$ret .= $this->SourceText{0};
$this->SourceText = substr($this->SourceText, 1, strlen($this->SourceText));
}
}
$this->unicode_table = array();
$this->SourceText = '';
return $ret;
}
if ($this->config['source_lang'] == 'UTF-8')
{
$i = 0;
$out = '';
$len = strlen($this->SourceText);
while ($i < $len)
{
$c = ord($this->SourceText{$i++});
switch($c >> 4)
{
case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
// 0xxxxxxx
$out .= $this->SourceText{$i - 1};
break;
case 12: case 13:
// 110x xxxx 10xx xxxx
$char2 = ord($this->SourceText{$i++});
$char3 = @$this->unicode_table[(($c & 0x1F) << 6) | ($char2 & 0x3F)];
if ($this->config['target_lang'] == 'GBK')
{
$out .= $this->_hex2bin(dechex($char3 + 0x8080));
}
elseif ($this->config['target_lang'] == 'BIG-5')
{
$out .= $this->_hex2bin(dechex($char3 + 0x0000));
}
break;
case 14:
// 1110 xxxx 10xx xxxx 10xx xxxx
$char2 = ord($this->SourceText{$i++});
$char3 = ord($this->SourceText{$i++});
$char4 = @$this->unicode_table[(($c & 0x0F) << 12) | (($char2 & 0x3F) << 6) | (($char3 & 0x3F) << 0)];
if ($this->config['target_lang'] == 'GBK')
{
$out .= $this->_hex2bin(dechex($char4 + 0x8080));
} elseif ($this->config['target_lang'] == 'BIG-5')
{
$out .= $this->_hex2bin(dechex($char4 + 0x0000));
}
break;
}
}
// 返回结果
return $out;
}
}
/**
* 简体、繁体中文转换为 UNICODE编码
*
* 详细说明
* @形参
* @访问 内部
* @返回 字符串
* @throws
*/
function CHStoUNICODE()
{
$utf = '';
while ($this->SourceText)
{
if (ord($this->SourceText{0}) > 127)
{
if ($this->config['source_lang'] == 'GBK')
{
$utf .= '&#x' . $this->unicode_table[hexdec(bin2hex($this->SourceText{0} . $this->SourceText{1})) - 0x8080] . ';';
}
elseif ($this->config['source_lang'] == 'BIG-5')
{
$utf .= '&#x' . $this->unicode_table[hexdec(bin2hex($this->SourceText{0} . $this->SourceText{1}))] . ';';
}
$this->SourceText = substr($this->SourceText, 2, strlen($this->SourceText));
}
else
{
$utf .= $this->SourceText{0};
$this->SourceText = substr($this->SourceText, 1, strlen($this->SourceText));
}
}
return $utf;
}
/**
* 简体中文 <-> 繁体中文 互相转换的函数
*
* 详细说明
* @访问 内部
* @返回值 经过编码的utf8字符
* @throws
*/
function GBtoBIG5()
{
// 获取等待转换的字符串的总长度
$max = strlen($this->SourceText) - 1;
for ($i = 0; $i < $max; $i++)
{
$h = ord($this->SourceText{$i});
if ($h >= 160)
{
$l = ord($this->SourceText{$i + 1});
if ($h == 161 && $l == 64)
{
$gb = ' ';
}
else
{
fseek($this->ctf, ($h - 160) * 510 + ($l - 1) * 2);
$gb = fread($this->ctf, 2);
}
$this->SourceText{$i} = $gb{0};
$this->SourceText{$i + 1} = $gb{1};
$i++;
}
}
fclose($this->ctf);
// 将转换后的结果赋予 $result;
$result = $this->SourceText;
// 清空 $thisSourceText
$this->SourceText = '';
// 返回转换结果
return $result;
}
//编码转换
function ec_iconv($source_lang, $target_lang, $source_string = '')
{
/* 如果字符串为空或者字符串不需要转换,直接返回 */
if ($source_lang == $target_lang || $source_string == '' /*|| $this->is_utf8_1($source_string) preg_match("/[\x80-\xFF]+/", $source_string) == 0*/)
{
return $source_string;
}
return $this->Convert($source_lang, $target_lang, $source_string);
}
//检查UFT8编码方法1
function mb_is_utf8($string)
{
return mb_detect_encoding($string, 'UTF-8') === 'UTF-8';//新发现
}
//检查UFT8编码方法2
function preg_is_utf8($string)
{
return preg_match('/^.*$/u', $string) > 0;//preg_match('/^./u', $string)
}
//检查UFT8编码方法3
function is_utf8_1($str)
{
$c=0; $b=0;
$bits=0;
$len=strlen($str);
for($i=0; $i<$len; $i++){
$c=ord($str[$i]);
if($c > 128){
if(($c >= 254)) return false;
elseif($c >= 252) $bits=6;
elseif($c >= 248) $bits=5;
elseif($c >= 240) $bits=4;
elseif($c >= 224) $bits=3;
elseif($c >= 192) $bits=2;
else return false;
if(($i+$bits) > $len) return false;
while($bits > 1){
$i++;
$b=ord($str[$i]);
if($b < 128 || $b > 191) return false;
$bits--;
}
}
}
return true;
}
//检查UFT8编码方法4
function is_utf8_2($string) {
// From http://w3.org/International/questions/qa-forms-utf-8.html
return preg_match('%^(?:
[\x09\x0A\x0D\x20-\x7E] # ASCII
| [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
| \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
| \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
| \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
| [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
| \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
)*$%xs', $string);
} // function is_utf8
}
?>
| zhaoshengloveqingqing/fenxiao | lib/class/class-iconv.php | PHP | apache-2.0 | 24,435 |
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/robomaker/model/SourceConfig.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace RoboMaker
{
namespace Model
{
SourceConfig::SourceConfig() :
m_s3BucketHasBeenSet(false),
m_s3KeyHasBeenSet(false),
m_architecture(Architecture::NOT_SET),
m_architectureHasBeenSet(false)
{
}
SourceConfig::SourceConfig(JsonView jsonValue) :
m_s3BucketHasBeenSet(false),
m_s3KeyHasBeenSet(false),
m_architecture(Architecture::NOT_SET),
m_architectureHasBeenSet(false)
{
*this = jsonValue;
}
SourceConfig& SourceConfig::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("s3Bucket"))
{
m_s3Bucket = jsonValue.GetString("s3Bucket");
m_s3BucketHasBeenSet = true;
}
if(jsonValue.ValueExists("s3Key"))
{
m_s3Key = jsonValue.GetString("s3Key");
m_s3KeyHasBeenSet = true;
}
if(jsonValue.ValueExists("architecture"))
{
m_architecture = ArchitectureMapper::GetArchitectureForName(jsonValue.GetString("architecture"));
m_architectureHasBeenSet = true;
}
return *this;
}
JsonValue SourceConfig::Jsonize() const
{
JsonValue payload;
if(m_s3BucketHasBeenSet)
{
payload.WithString("s3Bucket", m_s3Bucket);
}
if(m_s3KeyHasBeenSet)
{
payload.WithString("s3Key", m_s3Key);
}
if(m_architectureHasBeenSet)
{
payload.WithString("architecture", ArchitectureMapper::GetNameForArchitecture(m_architecture));
}
return payload;
}
} // namespace Model
} // namespace RoboMaker
} // namespace Aws
| awslabs/aws-sdk-cpp | aws-cpp-sdk-robomaker/source/model/SourceConfig.cpp | C++ | apache-2.0 | 1,729 |
// Autogenerated by gameplay-luagen
#ifndef LUA_MATERIAL_H_
#define LUA_MATERIAL_H_
namespace gameplay
{
void luaRegister_Material();
}
#endif
| reven86/GamePlay | gameplay/src/lua/lua_Material.h | C | apache-2.0 | 147 |
# Copyright 2019 The Oppia Authors. All Rights Reserved.
#
# 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.
"""This script runs the following tests in all cases.
- Javascript and Python Linting
- Backend Python tests
Only when frontend files are changed will it run Frontend Karma unit tests.
"""
from __future__ import annotations
import argparse
import subprocess
from . import common
from . import run_backend_tests
from . import run_frontend_tests
from .linters import pre_commit_linter
_PARSER = argparse.ArgumentParser(
description="""
Run this script from the oppia root folder prior to opening a PR:
python -m scripts.run_presubmit_checks
Set the origin branch to compare against by adding
--branch=your_branch or -b=your_branch
By default, if the current branch tip exists on remote origin,
the current branch is compared against its tip on GitHub.
Otherwise it's compared against 'develop'.
This script runs the following tests in all cases.
- Javascript and Python Linting
- Backend Python tests
Only when frontend files are changed will it run Frontend Karma unit tests.
If any of these tests result in errors, this script will terminate.
Note: The test scripts are arranged in increasing order of time taken. This
enables a broken build to be detected as quickly as possible.
""")
_PARSER.add_argument(
'--branch', '-b',
help='optional; if specified, the origin branch to compare against.')
def main(args=None):
"""Run the presubmit checks."""
parsed_args = _PARSER.parse_args(args=args)
# Run Javascript and Python linters.
print('Linting files since the last commit')
pre_commit_linter.main(args=[])
print('Linting passed.')
print('')
current_branch = subprocess.check_output([
'git', 'rev-parse', '--abbrev-ref', 'HEAD'])
# If the current branch exists on remote origin, matched_branch_num=1
# else matched_branch_num=0.
matched_branch_num = subprocess.check_output([
'git', 'ls-remote', '--heads', 'origin', current_branch, '|', 'wc',
'-l'])
# Set the origin branch to develop if it's not specified.
if parsed_args.branch:
branch = parsed_args.branch
elif matched_branch_num == '1':
branch = 'origin/%s' % current_branch
else:
branch = 'develop'
print('Comparing the current branch with %s' % branch)
all_changed_files = subprocess.check_output([
'git', 'diff', '--cached', '--name-only', '--diff-filter=ACM', branch])
if common.FRONTEND_DIR in all_changed_files:
# Run frontend unit tests.
print('Running frontend unit tests')
run_frontend_tests.main(args=['--run_minified_tests'])
print('Frontend tests passed.')
else:
# If files in common.FRONTEND_DIR were not changed, skip the tests.
common.print_each_string_after_two_new_lines([
'No frontend files were changed.',
'Skipped frontend tests'])
# Run backend tests.
print('Running backend tests')
run_backend_tests.main(args=[])
print('Backend tests passed.')
if __name__ == '__main__':
main()
| kevinlee12/oppia | scripts/run_presubmit_checks.py | Python | apache-2.0 | 3,619 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package opennlp.tools.util;
public class StringUtil {
/**
* Determines if the specified character is a whitespace.
*
* A character is considered a whitespace when one
* of the following conditions is meet:
*
* <ul>
* <li>Its a {@link Character#isWhitespace(int)} whitespace.</li>
* <li>Its a part of the Unicode Zs category ({@link Character#SPACE_SEPARATOR}).</li>
* </ul>
*
* <code>Character.isWhitespace(int)</code> does not include no-break spaces.
* In OpenNLP no-break spaces are also considered as white spaces.
*
* @param charCode
* @return true if white space otherwise false
*/
public static boolean isWhitespace(char charCode) {
return Character.isWhitespace(charCode) ||
Character.getType(charCode) == Character.SPACE_SEPARATOR;
}
/**
* Determines if the specified character is a whitespace.
*
* A character is considered a whitespace when one
* of the following conditions is meet:
*
* <ul>
* <li>Its a {@link Character#isWhitespace(int)} whitespace.</li>
* <li>Its a part of the Unicode Zs category ({@link Character#SPACE_SEPARATOR}).</li>
* </ul>
*
* <code>Character.isWhitespace(int)</code> does not include no-break spaces.
* In OpenNLP no-break spaces are also considered as white spaces.
*
* @param charCode
* @return true if white space otherwise false
*/
public static boolean isWhitespace(int charCode) {
return Character.isWhitespace(charCode) ||
Character.getType(charCode) == Character.SPACE_SEPARATOR;
}
/**
* Converts to lower case independent of the current locale via
* {@link Character#toLowerCase(int)} which uses mapping information
* from the UnicodeData file.
*
* @param string
* @return lower cased String
*/
public static String toLowerCase(CharSequence string) {
int[] cp = string.codePoints().map(Character::toLowerCase).toArray();
return new String(cp, 0, cp.length);
}
/**
* Converts to upper case independent of the current locale via
* {@link Character#toUpperCase(char)} which uses mapping information
* from the UnicodeData file.
*
* @param string
* @return upper cased String
*/
public static String toUpperCase(CharSequence string) {
char[] upperCaseChars = new char[string.length()];
for (int i = 0; i < string.length(); i++) {
upperCaseChars[i] = Character.toUpperCase(string.charAt(i));
}
return new String(upperCaseChars);
}
/**
* Returns {@code true} if {@link CharSequence#length()} is
* {@code 0} or {@code null}.
*
* @return {@code true} if {@link CharSequence#length()} is {@code 0}, otherwise
* {@code false}
*
* @since 1.5.1
*/
public static boolean isEmpty(CharSequence theString) {
return theString.length() == 0;
}
/**
* Get mininum of three values.
* @param a number a
* @param b number b
* @param c number c
* @return the minimum
*/
private static int minimum(int a, int b, int c) {
int minValue;
minValue = a;
if (b < minValue) {
minValue = b;
}
if (c < minValue) {
minValue = c;
}
return minValue;
}
/**
* Computes the Levenshtein distance of two strings in a matrix.
* Based on pseudo-code provided here:
* https://en.wikipedia.org/wiki/Levenshtein_distance#Computing_Levenshtein_distance
* which in turn is based on the paper Wagner, Robert A.; Fischer, Michael J. (1974),
* "The String-to-String Correction Problem", Journal of the ACM 21 (1): 168-173
* @param wordForm the form
* @param lemma the lemma
* @return the distance
*/
public static int[][] levenshteinDistance(String wordForm, String lemma) {
int wordLength = wordForm.length();
int lemmaLength = lemma.length();
int cost;
int[][] distance = new int[wordLength + 1][lemmaLength + 1];
if (wordLength == 0) {
return distance;
}
if (lemmaLength == 0) {
return distance;
}
//fill in the rows of column 0
for (int i = 0; i <= wordLength; i++) {
distance[i][0] = i;
}
//fill in the columns of row 0
for (int j = 0; j <= lemmaLength; j++) {
distance[0][j] = j;
}
//fill in the rest of the matrix calculating the minimum distance
for (int i = 1; i <= wordLength; i++) {
int s_i = wordForm.charAt(i - 1);
for (int j = 1; j <= lemmaLength; j++) {
if (s_i == lemma.charAt(j - 1)) {
cost = 0;
} else {
cost = 1;
}
//obtain minimum distance from calculating deletion, insertion, substitution
distance[i][j] = minimum(distance[i - 1][j] + 1, distance[i][j - 1]
+ 1, distance[i - 1][j - 1] + cost);
}
}
return distance;
}
/**
* Computes the Shortest Edit Script (SES) to convert a word into its lemma.
* This is based on Chrupala's PhD thesis (2008).
* @param wordForm the token
* @param lemma the target lemma
* @param distance the levenshtein distance
* @param permutations the number of permutations
*/
public static void computeShortestEditScript(String wordForm, String lemma,
int[][] distance, StringBuffer permutations) {
int n = distance.length;
int m = distance[0].length;
int wordFormLength = n - 1;
int lemmaLength = m - 1;
while (true) {
if (distance[wordFormLength][lemmaLength] == 0) {
break;
}
if ((lemmaLength > 0 && wordFormLength > 0) && (distance[wordFormLength - 1][lemmaLength - 1]
< distance[wordFormLength][lemmaLength])) {
permutations.append('R').append(Integer.toString(wordFormLength - 1))
.append(wordForm.charAt(wordFormLength - 1)).append(lemma.charAt(lemmaLength - 1));
lemmaLength--;
wordFormLength--;
continue;
}
if (lemmaLength > 0 && (distance[wordFormLength][lemmaLength - 1]
< distance[wordFormLength][lemmaLength])) {
permutations.append('I').append(Integer.toString(wordFormLength))
.append(lemma.charAt(lemmaLength - 1));
lemmaLength--;
continue;
}
if (wordFormLength > 0 && (distance[wordFormLength - 1][lemmaLength]
< distance[wordFormLength][lemmaLength])) {
permutations.append('D').append(Integer.toString(wordFormLength - 1))
.append(wordForm.charAt(wordFormLength - 1));
wordFormLength--;
continue;
}
if ((wordFormLength > 0 && lemmaLength > 0) && (distance[wordFormLength - 1][lemmaLength - 1]
== distance[wordFormLength][lemmaLength])) {
wordFormLength--;
lemmaLength--;
continue ;
}
if (wordFormLength > 0 && (distance[wordFormLength - 1][lemmaLength]
== distance[wordFormLength][lemmaLength])) {
wordFormLength--;
continue;
}
if (lemmaLength > 0 && (distance[wordFormLength][lemmaLength - 1]
== distance[wordFormLength][lemmaLength])) {
lemmaLength--;
}
}
}
/**
* Read predicted SES by the lemmatizer model and apply the
* permutations to obtain the lemma from the wordForm.
* @param wordForm the wordForm
* @param permutations the permutations predicted by the lemmatizer model
* @return the lemma
*/
public static String decodeShortestEditScript(String wordForm, String permutations) {
StringBuffer lemma = new StringBuffer(wordForm).reverse();
int permIndex = 0;
while (true) {
if (permutations.length() <= permIndex) {
break;
}
//read first letter of permutation string
char nextOperation = permutations.charAt(permIndex);
//System.err.println("-> NextOP: " + nextOperation);
//go to the next permutation letter
permIndex++;
if (nextOperation == 'R') {
String charAtPerm = Character.toString(permutations.charAt(permIndex));
int charIndex = Integer.parseInt(charAtPerm);
// go to the next character in the permutation buffer
// which is the replacement character
permIndex++;
char replace = permutations.charAt(permIndex);
//go to the next char in the permutation buffer
// which is the candidate character
permIndex++;
char with = permutations.charAt(permIndex);
if (lemma.length() <= charIndex) {
return wordForm;
}
if (lemma.charAt(charIndex) == replace) {
lemma.setCharAt(charIndex, with);
}
//System.err.println("-> ROP: " + lemma.toString());
//go to next permutation
permIndex++;
} else if (nextOperation == 'I') {
String charAtPerm = Character.toString(permutations.charAt(permIndex));
int charIndex = Integer.parseInt(charAtPerm);
permIndex++;
//character to be inserted
char in = permutations.charAt(permIndex);
if (lemma.length() < charIndex) {
return wordForm;
}
lemma.insert(charIndex, in);
//System.err.println("-> IOP " + lemma.toString());
//go to next permutation
permIndex++;
} else if (nextOperation == 'D') {
String charAtPerm = Character.toString(permutations.charAt(permIndex));
int charIndex = Integer.parseInt(charAtPerm);
if (lemma.length() <= charIndex) {
return wordForm;
}
lemma.deleteCharAt(charIndex);
permIndex++;
// go to next permutation
permIndex++;
}
}
return lemma.reverse().toString();
}
/**
* Get the SES required to go from a word to a lemma.
* @param wordForm the word
* @param lemma the lemma
* @return the shortest edit script
*/
public static String getShortestEditScript(String wordForm, String lemma) {
String reversedWF = new StringBuffer(wordForm.toLowerCase()).reverse().toString();
String reversedLemma = new StringBuffer(lemma.toLowerCase()).reverse().toString();
StringBuffer permutations = new StringBuffer();
String ses;
if (!reversedWF.equals(reversedLemma)) {
int[][]levenDistance = StringUtil.levenshteinDistance(reversedWF, reversedLemma);
StringUtil.computeShortestEditScript(reversedWF, reversedLemma, levenDistance, permutations);
ses = permutations.toString();
} else {
ses = "O";
}
return ses;
}
}
| jzonthemtn/opennlp | opennlp-tools/src/main/java/opennlp/tools/util/StringUtil.java | Java | apache-2.0 | 11,195 |
//------------------------------------------------------------------------------
// <auto-generated>
// このコードはツールによって生成されました。
// ランタイム バージョン:4.0.30319.34209
//
// このファイルへの変更は、以下の状況下で不正な動作の原因になったり、
// コードが再生成されるときに損失したりします。
// </auto-generated>
//------------------------------------------------------------------------------
namespace MsgPack.Serialization.GeneratedSerializers.MapBased {
[System.CodeDom.Compiler.GeneratedCodeAttribute("MsgPack.Serialization.CodeDomSerializers.CodeDomSerializerBuilder", "0.6.0.0")]
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
public class MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_PrimitiveReadWriteFieldAsObjectSerializer : MsgPack.Serialization.MessagePackSerializer<MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_PrimitiveReadWriteFieldAsObject> {
private MsgPack.Serialization.MessagePackSerializer<string> _serializer0;
private MsgPack.Serialization.MessagePackSerializer<object> _serializer1;
public MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_PrimitiveReadWriteFieldAsObjectSerializer(MsgPack.Serialization.SerializationContext context) :
base(context) {
MsgPack.Serialization.PolymorphismSchema schema0 = default(MsgPack.Serialization.PolymorphismSchema);
schema0 = null;
this._serializer0 = context.GetSerializer<string>(schema0);
MsgPack.Serialization.PolymorphismSchema schema1 = default(MsgPack.Serialization.PolymorphismSchema);
schema1 = null;
this._serializer1 = context.GetSerializer<object>(schema1);
}
protected internal override void PackToCore(MsgPack.Packer packer, MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_PrimitiveReadWriteFieldAsObject objectTree) {
packer.PackMapHeader(1);
this._serializer0.PackTo(packer, "Primitive");
this._serializer1.PackTo(packer, objectTree.Primitive);
}
protected internal override MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_PrimitiveReadWriteFieldAsObject UnpackFromCore(MsgPack.Unpacker unpacker) {
MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_PrimitiveReadWriteFieldAsObject result = default(MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_PrimitiveReadWriteFieldAsObject);
result = new MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_PrimitiveReadWriteFieldAsObject();
if (unpacker.IsArrayHeader) {
int unpacked = default(int);
int itemsCount = default(int);
itemsCount = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker);
object nullable = default(object);
if ((unpacked < itemsCount)) {
if ((unpacker.Read() == false)) {
throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(0);
}
if (((unpacker.IsArrayHeader == false)
&& (unpacker.IsMapHeader == false))) {
nullable = this._serializer1.UnpackFrom(unpacker);
}
else {
MsgPack.Unpacker disposable = default(MsgPack.Unpacker);
disposable = unpacker.ReadSubtree();
try {
nullable = this._serializer1.UnpackFrom(disposable);
}
finally {
if (((disposable == null)
== false)) {
disposable.Dispose();
}
}
}
}
if (((nullable == null)
== false)) {
result.Primitive = nullable;
}
unpacked = (unpacked + 1);
}
else {
int itemsCount0 = default(int);
itemsCount0 = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker);
for (int i = 0; (i < itemsCount0); i = (i + 1)) {
string key = default(string);
string nullable0 = default(string);
nullable0 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_PrimitiveReadWriteFieldAsObject), "MemberName");
if (((nullable0 == null)
== false)) {
key = nullable0;
}
else {
throw MsgPack.Serialization.SerializationExceptions.NewNullIsProhibited("MemberName");
}
if ((key == "Primitive")) {
object nullable1 = default(object);
if ((unpacker.Read() == false)) {
throw MsgPack.Serialization.SerializationExceptions.NewMissingItem(i);
}
if (((unpacker.IsArrayHeader == false)
&& (unpacker.IsMapHeader == false))) {
nullable1 = this._serializer1.UnpackFrom(unpacker);
}
else {
MsgPack.Unpacker disposable0 = default(MsgPack.Unpacker);
disposable0 = unpacker.ReadSubtree();
try {
nullable1 = this._serializer1.UnpackFrom(disposable0);
}
finally {
if (((disposable0 == null)
== false)) {
disposable0.Dispose();
}
}
}
if (((nullable1 == null)
== false)) {
result.Primitive = nullable1;
}
}
else {
unpacker.Skip();
}
}
}
return result;
}
private static T @__Conditional<T>(bool condition, T whenTrue, T whenFalse)
{
if (condition) {
return whenTrue;
}
else {
return whenFalse;
}
}
}
}
| modulexcite/msgpack-cli | test/MsgPack.UnitTest/gen/map/MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_PrimitiveReadWriteFieldAsObjectSerializer.cs | C# | apache-2.0 | 6,892 |
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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.
*/
package org.wso2.carbon.mss.examples.petstore.util.fe.client;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import org.wso2.carbon.mss.examples.petstore.util.fe.model.Configuration;
import org.wso2.carbon.mss.examples.petstore.util.fe.view.LoginBean;
import org.wso2.carbon.mss.examples.petstore.util.model.Category;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* Client to access PetCategoryServiceClient.
*/
@ManagedBean
@ApplicationScoped
public class PetCategoryServiceClient extends AbstractServiceClient {
private static final Logger LOGGER = Logger.getLogger(PetCategoryServiceClient.class.getName());
@Nullable
@ManagedProperty("#{configuration}")
private Configuration configuration;
public boolean addPetCategory(Category category) throws IOException {
final Client client = ClientBuilder.newBuilder().build();
final WebTarget target = client.target(configuration.getPetServiceEP() + "/category");
Gson gson = new Gson();
LOGGER.info("Connecting to pet service on " + configuration.getPetServiceEP());
final Response response = target.request().header(LoginBean.X_JWT_ASSERTION, getJWTToken())
.post(Entity.entity(gson.toJson(category), MediaType.APPLICATION_JSON));
LOGGER.info("Returned from pet service " + configuration.getPetServiceEP());
if (Response.Status.OK.getStatusCode() == response.getStatus()) {
return true;
}
LOGGER.log(Level.SEVERE, "Pet service return code is " + response.getStatus() + " , " +
"hence can't proceed with the response");
return false;
}
public boolean removePetCategory(Category category) throws IOException {
final Client client = ClientBuilder.newBuilder().build();
final WebTarget target = client.target(configuration.getPetServiceEP() + "/category/" + category.getName());
LOGGER.info("Connecting to pet service on " + configuration.getPetServiceEP());
final Response response = target.request().header(LoginBean.X_JWT_ASSERTION, getJWTToken()).delete();
LOGGER.info("Returned from pet service " + configuration.getPetServiceEP());
if (Response.Status.OK.getStatusCode() == response.getStatus()) {
return true;
}
LOGGER.log(Level.SEVERE, "Pet service return code is " + response.getStatus() + " , " +
"hence can't proceed with the response");
return false;
}
public List<Category> list() {
final Client client = ClientBuilder.newBuilder().build();
final WebTarget target = client.target(configuration.getPetServiceEP() + "/category/all");
LOGGER.info("Connecting to pet service on " + configuration.getPetServiceEP());
final Response response = target.request().header(LoginBean.X_JWT_ASSERTION, getJWTToken()).get();
LOGGER.info("Returned from pet service " + configuration.getPetServiceEP());
if (Response.Status.OK.getStatusCode() == response.getStatus()) {
String body = response.readEntity(String.class);
Gson gson = new Gson();
Type listType = new CategoryTypeToken().getType();
return gson.fromJson(body, listType);
}
LOGGER.log(Level.SEVERE, "Pet service return code is " + response.getStatus() + " , " +
"hence can't proceed with the response");
return Collections.emptyList();
}
public Configuration getConfiguration() {
return configuration;
}
public void setConfiguration(Configuration configuration) {
this.configuration = configuration;
}
static class CategoryTypeToken extends TypeToken<List<Category>> {
private static final long serialVersionUID = 4534722069729160047L;
}
}
| susinda/product-mss | samples/petstore/frontend-util/src/main/java/org/wso2/carbon/mss/examples/petstore/util/fe/client/PetCategoryServiceClient.java | Java | apache-2.0 | 5,196 |
package ca.uhn.fhir.rest.server;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.Assert.*;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.model.api.Bundle;
import ca.uhn.fhir.model.api.IResource;
import ca.uhn.fhir.model.dstu.resource.Binary;
import ca.uhn.fhir.model.primitive.IdDt;
import ca.uhn.fhir.rest.annotation.Create;
import ca.uhn.fhir.rest.annotation.IdParam;
import ca.uhn.fhir.rest.annotation.Read;
import ca.uhn.fhir.rest.annotation.ResourceParam;
import ca.uhn.fhir.rest.annotation.Search;
import ca.uhn.fhir.rest.api.MethodOutcome;
import ca.uhn.fhir.util.PortUtil;
import ca.uhn.fhir.util.TestUtil;
public class BinaryTest {
private static CloseableHttpClient ourClient;
private static FhirContext ourCtx = FhirContext.forDstu1();
private static Binary ourLast;
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(BinaryTest.class);
private static int ourPort;
private static Server ourServer;
@Before
public void before() {
ourLast=null;
}
@Test
public void testCreate() throws Exception {
HttpPost http = new HttpPost("http://localhost:" + ourPort + "/Binary");
http.setEntity(new ByteArrayEntity(new byte[] {1,2,3,4}, ContentType.create("foo/bar", "UTF-8")));
HttpResponse status = ourClient.execute(http);
assertEquals(201, status.getStatusLine().getStatusCode());
assertEquals("foo/bar; charset=UTF-8", ourLast.getContentType());
assertArrayEquals(new byte[] { 1, 2, 3, 4 }, ourLast.getContent());
}
public void testCreateWrongType() throws Exception {
Binary res = new Binary();
res.setContent(new byte[] { 1, 2, 3, 4 });
res.setContentType("text/plain");
String stringContent = ourCtx.newJsonParser().encodeResourceToString(res);
HttpPost http = new HttpPost("http://localhost:" + ourPort + "/Binary");
http.setEntity(new StringEntity(stringContent, ContentType.create(Constants.CT_FHIR_JSON, "UTF-8")));
HttpResponse status = ourClient.execute(http);
assertEquals(201, status.getStatusLine().getStatusCode());
assertEquals("text/plain", ourLast.getContentType());
assertArrayEquals(new byte[] { 1, 2, 3, 4 }, ourLast.getContent());
}
@Test
public void testRead() throws Exception {
HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Binary/foo");
HttpResponse status = ourClient.execute(httpGet);
byte[] responseContent = IOUtils.toByteArray(status.getEntity().getContent());
IOUtils.closeQuietly(status.getEntity().getContent());
assertEquals(200, status.getStatusLine().getStatusCode());
assertEquals("foo", status.getFirstHeader("content-type").getValue());
assertArrayEquals(new byte[] { 1, 2, 3, 4 }, responseContent);
}
@Test
public void testReadWithExplicitTypeJson() throws Exception {
HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Binary/foo?_format=json");
HttpResponse status = ourClient.execute(httpGet);
String responseContent = IOUtils.toString(status.getEntity().getContent(), "UTF-8");
IOUtils.closeQuietly(status.getEntity().getContent());
ourLog.info(responseContent);
assertEquals(200, status.getStatusLine().getStatusCode());
assertThat(status.getFirstHeader("content-type").getValue(), startsWith(Constants.CT_FHIR_JSON + ";"));
Binary bin = ourCtx.newJsonParser().parseResource(Binary.class, responseContent);
assertEquals("foo", bin.getContentType());
assertArrayEquals(new byte[] { 1, 2, 3, 4 }, bin.getContent());
}
@Test
public void testReadWithExplicitTypeXml() throws Exception {
HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Binary/foo?_format=xml");
HttpResponse status = ourClient.execute(httpGet);
String responseContent = IOUtils.toString(status.getEntity().getContent(), "UTF-8");
IOUtils.closeQuietly(status.getEntity().getContent());
ourLog.info(responseContent);
assertEquals(200, status.getStatusLine().getStatusCode());
assertThat(status.getFirstHeader("content-type").getValue(), startsWith(Constants.CT_FHIR_XML + ";"));
Binary bin = ourCtx.newXmlParser().parseResource(Binary.class, responseContent);
assertEquals("foo", bin.getContentType());
assertArrayEquals(new byte[] { 1, 2, 3, 4 }, bin.getContent());
}
@Test
public void testSearch() throws Exception {
HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Binary?");
HttpResponse status = ourClient.execute(httpGet);
String responseContent = IOUtils.toString(status.getEntity().getContent());
IOUtils.closeQuietly(status.getEntity().getContent());
assertEquals(200, status.getStatusLine().getStatusCode());
assertEquals(Constants.CT_ATOM_XML + ";charset=utf-8", status.getFirstHeader("content-type").getValue().replace(" ", "").replace("UTF", "utf"));
ourLog.info(responseContent);
Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent);
Binary bin = (Binary) bundle.getEntries().get(0).getResource();
assertEquals("text/plain", bin.getContentType());
assertArrayEquals(new byte[] { 1, 2, 3, 4 }, bin.getContent());
}
@AfterClass
public static void afterClassClearContext() throws Exception {
ourServer.stop();
TestUtil.clearAllStaticFieldsForUnitTest();
}
@BeforeClass
public static void beforeClass() throws Exception {
ourPort = PortUtil.findFreePort();
ourServer = new Server(ourPort);
ResourceProvider patientProvider = new ResourceProvider();
ServletHandler proxyHandler = new ServletHandler();
RestfulServer servlet = new RestfulServer(ourCtx);
servlet.setResourceProviders(patientProvider);
ServletHolder servletHolder = new ServletHolder(servlet);
proxyHandler.addServletWithMapping(servletHolder, "/*");
ourServer.setHandler(proxyHandler);
ourServer.start();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS);
HttpClientBuilder builder = HttpClientBuilder.create();
builder.setConnectionManager(connectionManager);
ourClient = builder.build();
}
/**
* Created by dsotnikov on 2/25/2014.
*/
public static class ResourceProvider implements IResourceProvider {
@Create
public MethodOutcome create(@ResourceParam Binary theBinary) {
ourLast = theBinary;
return new MethodOutcome(new IdDt("1"));
}
@Override
public Class<? extends IResource> getResourceType() {
return Binary.class;
}
@Read
public Binary read(@IdParam IdDt theId) {
Binary retVal = new Binary();
retVal.setId("1");
retVal.setContent(new byte[] { 1, 2, 3, 4 });
retVal.setContentType(theId.getIdPart());
return retVal;
}
@Search
public List<Binary> search() {
Binary retVal = new Binary();
retVal.setId("1");
retVal.setContent(new byte[] { 1, 2, 3, 4 });
retVal.setContentType("text/plain");
return Collections.singletonList(retVal);
}
}
}
| eug48/hapi-fhir | hapi-fhir-structures-dstu/src/test/java/ca/uhn/fhir/rest/server/BinaryTest.java | Java | apache-2.0 | 7,677 |
# Copyright 2015-2017 Capital One Services, LLC
#
# 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.
from __future__ import absolute_import, division, print_function, unicode_literals
import datetime
import json
import os
from dateutil import zoneinfo
from mock import mock
from .common import BaseTest, instance
from c7n.filters import FilterValidationError
from c7n.filters.offhours import OffHour, OnHour, ScheduleParser, Time
# Per http://blog.xelnor.net/python-mocking-datetime/
# naive implementation has issues with pypy
real_datetime_class = datetime.datetime
def mock_datetime_now(tgt, dt):
class DatetimeSubclassMeta(type):
@classmethod
def __instancecheck__(mcs, obj):
return isinstance(obj, real_datetime_class)
class BaseMockedDatetime(real_datetime_class):
target = tgt
@classmethod
def now(cls, tz=None):
return cls.target.replace(tzinfo=tz)
@classmethod
def utcnow(cls):
return cls.target
# Python2 & Python3 compatible metaclass
MockedDatetime = DatetimeSubclassMeta(
b'datetime' if str is bytes else 'datetime', # hack Python2/3 port
(BaseMockedDatetime,), {})
return mock.patch.object(dt, 'datetime', MockedDatetime)
class OffHoursFilterTest(BaseTest):
"""[off|on] hours testing"""
def test_offhours_records(self):
session_factory = self.replay_flight_data('test_offhours_records')
t = datetime.datetime.now(zoneinfo.gettz('America/New_York'))
t = t.replace(year=2016, month=8, day=14, hour=19, minute=00)
with mock_datetime_now(t, datetime):
p = self.load_policy({
'name': 'offhours-records',
'resource': 'ec2',
'filters': [
{'State.Name': 'running'},
{'type': 'offhour',
'offhour': 19,
'tag': 'custodian_downtime',
'default_tz': 'est',
'weekends': False}]
}, session_factory=session_factory)
resources = p.run()
self.assertEqual(resources, [])
with open(os.path.join(
p.options['output_dir'],
'offhours-records',
'parse_errors.json')) as fh:
data = json.load(fh)
self.assertEqual(len(data), 1)
self.assertEqual(data[0][0], 'i-0ee3a9bc2eeed269f')
self.assertEqual(data[0][1], 'off=[m-f,8];on=[n-f,5];pz=est')
with open(os.path.join(
p.options['output_dir'],
'offhours-records',
'opted_out.json')) as fh:
data = json.load(fh)
self.assertEqual(len(data), 1)
self.assertEqual(data[0]['InstanceId'], 'i-0a619b58a7e704a9f')
def test_validate(self):
self.assertRaises(
FilterValidationError, OffHour({'default_tz': 'zmta'}).validate)
self.assertRaises(
FilterValidationError, OffHour({'offhour': 25}).validate)
i = OffHour({})
self.assertEqual(i.validate(), i)
def test_process(self):
f = OffHour({'opt-out': True})
instances = [
instance(Tags=[]),
instance(
Tags=[{'Key': 'maid_offhours', 'Value': ''}]),
instance(
Tags=[{'Key': 'maid_offhours', 'Value': 'on'}]),
instance(
Tags=[{'Key': 'maid_offhours', 'Value': 'off'}]),
instance(
Tags=[
{'Key': 'maid_offhours',
'Value': "off=(m-f,5);zebrablue,on=(t-w,5)"}])]
t = datetime.datetime(
year=2015, month=12, day=1, hour=19, minute=5,
tzinfo=zoneinfo.gettz('America/New_York'))
with mock_datetime_now(t, datetime):
self.assertEqual(
f.process(instances), [instances[0], instances[1], instances[2]]
)
def test_opt_out_behavior(self):
# Some users want to match based on policy filters to
# a resource subset with default opt out behavior
t = datetime.datetime(
year=2015, month=12, day=1, hour=19, minute=5,
tzinfo=zoneinfo.gettz('America/New_York'))
f = OffHour({'opt-out': True})
with mock_datetime_now(t, datetime):
i = instance(Tags=[])
self.assertEqual(f(i), True)
i = instance(
Tags=[{'Key': 'maid_offhours', 'Value': ''}]
)
self.assertEqual(f(i), True)
i = instance(
Tags=[{'Key': 'maid_offhours', 'Value': 'on'}]
)
self.assertEqual(f(i), True)
i = instance(
Tags=[{'Key': 'maid_offhours', 'Value': 'off'}])
self.assertEqual(f(i), False)
self.assertEqual(f.opted_out, [i])
def test_opt_in_behavior(self):
# Given the addition of opt out behavior, verify if its
# not configured that we don't touch an instance that
# has no downtime tag
i = instance(Tags=[])
i2 = instance(Tags=[{'Key': 'maid_offhours', 'Value': ''}])
i3 = instance(Tags=[{'Key': 'maid_offhours', 'Value': 'on'}])
t = datetime.datetime(
year=2015, month=12, day=1, hour=19, minute=5,
tzinfo=zoneinfo.gettz('America/New_York'))
f = OffHour({})
with mock_datetime_now(t, datetime):
self.assertEqual(f(i), False)
self.assertEqual(f(i2), True)
self.assertEqual(f(i3), True)
t = datetime.datetime(
year=2015, month=12, day=1, hour=7, minute=5,
tzinfo=zoneinfo.gettz('America/New_York'))
f = OnHour({})
with mock_datetime_now(t, datetime):
self.assertEqual(f(i), False)
self.assertEqual(f(i2), True)
self.assertEqual(f(i3), True)
def xtest_time_match_stops_after_skew(self):
hour = 7
t = datetime.datetime(
year=2015, month=12, day=1, hour=hour, minute=5,
tzinfo=zoneinfo.gettz('America/New_York'))
i = instance(Tags=[
{'Key': 'maid_offhours', 'Value': 'tz=est'}])
f = OnHour({'skew': 1})
results = []
with mock_datetime_now(t, datetime) as dt:
for n in range(0, 4):
dt.target = t.replace(hour=hour + n)
results.append(f(i))
self.assertEqual(results, [True, True, False, False])
def test_resource_schedule_error(self):
t = datetime.datetime.now(zoneinfo.gettz('America/New_York'))
t = t.replace(year=2015, month=12, day=1, hour=19, minute=5)
f = OffHour({})
f.process_resource_schedule = lambda: False
with mock_datetime_now(t, datetime):
i = instance(Tags=[
{'Key': 'maid_offhours', 'Value': 'tz=est'}])
self.assertEqual(f(i), False)
def test_time_filter_usage_errors(self):
self.assertRaises(NotImplementedError, Time, {})
def test_everyday_onhour(self):
# weekends on means we match times on the weekend
start_day = 14 # sunday
t = datetime.datetime(
year=2016, day=start_day, month=8, hour=7, minute=20)
i = instance(Tags=[{'Key': 'maid_offhours', 'Value': 'tz=est'}])
f = OnHour({'weekends': False})
results = []
with mock_datetime_now(t, datetime) as dt:
for n in range(7):
dt.target = t.replace(day=start_day + n)
results.append(f(i))
self.assertEqual(results, [True] * 7)
def test_everyday_offhour(self):
# weekends on means we match times on the weekend
start_day = 14 # sunday
t = datetime.datetime(
year=2016, day=start_day, month=8, hour=19, minute=20)
i = instance(Tags=[{'Key': 'maid_offhours', 'Value': 'tz=est'}])
f = OffHour({'weekends': False})
results = []
with mock_datetime_now(t, datetime) as dt:
for n in range(7):
dt.target = t.replace(day=start_day + n)
results.append(f(i))
self.assertEqual(results, [True] * 7)
def test_weekends_only_onhour_support(self):
# start day is a sunday, weekend only means we only start
# on monday morning.
start_day = 14
t = datetime.datetime(
year=2016, day=start_day, month=8, hour=7, minute=20)
i = instance(Tags=[{'Key': 'maid_offhours', 'Value': 'tz=est'}])
f = OnHour({'weekends-only': True})
results = []
with mock_datetime_now(t, datetime) as dt:
for n in range(7):
dt.target = t.replace(day=start_day + n)
results.append(f(i))
self.assertEqual(results, [
False, True, False, False, False, False, False])
def test_weekends_only_offhour_support(self):
# start day is a sunday, weekend only means we only stop
# on friday evening.
start_day = 14
t = datetime.datetime(
year=2016, day=start_day, month=8, hour=7, minute=20)
i = instance(Tags=[{'Key': 'maid_offhours', 'Value': 'tz=est'}])
f = OnHour({'weekends-only': True})
results = []
with mock_datetime_now(t, datetime) as dt:
for n in range(7):
dt.target = t.replace(day=start_day + n)
results.append(f(i))
self.assertEqual(results, [
False, True, False, False, False, False, False])
def test_onhour_weekend_support(self):
start_day = 14
t = datetime.datetime(
year=2016, day=start_day, month=2, hour=19, minute=20)
i = instance(Tags=[{'Key': 'maid_offhours', 'Value': 'tz=est'}])
f = OffHour({'weekends-only': True})
results = []
with mock_datetime_now(t, datetime) as dt:
for n in range(7):
dt.target = t.replace(day=start_day + n)
results.append(f(i))
self.assertEqual(
results,
[False, False, False, False, False, True, False])
def test_offhour_weekend_support(self):
start_day = 26
t = datetime.datetime(
year=2016, day=start_day, month=2, hour=19, minute=20)
i = instance(Tags=[{'Key': 'maid_offhours', 'Value': 'tz=est'}])
f = OffHour({})
results = []
with mock_datetime_now(t, datetime) as dt:
for n in range(0, 4):
dt.target = t.replace(day=start_day + n)
results.append(f(i))
self.assertEqual(results, [True, False, False, True])
def test_current_time_test(self):
t = datetime.datetime.now(zoneinfo.gettz('America/New_York'))
t = t.replace(year=2015, month=12, day=1, hour=19, minute=5)
with mock_datetime_now(t, datetime):
i = instance(Tags=[
{'Key': 'maid_offhours', 'Value': 'tz=est'}])
f = OffHour({})
p = f.get_tag_value(i)
self.assertEqual(p, 'tz=est')
tz = f.get_tz('est')
self.assertTrue(str(tz) in (
"tzfile('US/Eastern')",
"tzfile('America/New_York')"))
self.assertEqual(
datetime.datetime.now(tz), t)
self.assertEqual(t.hour, 19)
def test_offhours_real_world_values(self):
t = datetime.datetime.now(zoneinfo.gettz('America/New_York'))
t = t.replace(year=2015, month=12, day=1, hour=19, minute=5)
with mock_datetime_now(t, datetime):
results = [OffHour({})(i) for i in [
instance(Tags=[
{'Key': 'maid_offhours', 'Value': ''}]),
instance(Tags=[
{'Key': 'maid_offhours', 'Value': 'on'}]),
instance(Tags=[
{'Key': 'maid_offhours', 'Value': '"Offhours tz=ET"'}]),
instance(Tags=[
{'Key': 'maid_offhours', 'Value': 'Offhours tz=PT'}])]]
# unclear what this is really checking
self.assertEqual(results, [True, True, True, True])
def test_offhours_get_value(self):
off = OffHour({'default_tz': 'ct'})
i = instance(Tags=[
{'Key': 'maid_offhours', 'Value': 'Offhours tz=PT'}])
self.assertEqual(off.get_tag_value(i), "offhours tz=pt")
self.assertFalse(off.parser.has_resource_schedule(
off.get_tag_value(i), 'off'))
self.assertTrue(off.parser.keys_are_valid(
off.get_tag_value(i)))
self.assertEqual(off.parser.raw_data(
off.get_tag_value(i)), {'tz': 'pt'})
def test_offhours(self):
t = datetime.datetime(year=2015, month=12, day=1, hour=19, minute=5,
tzinfo=zoneinfo.gettz('America/New_York'))
with mock_datetime_now(t, datetime):
i = instance(Tags=[
{'Key': 'maid_offhours', 'Value': 'tz=est'}])
self.assertEqual(OffHour({})(i), True)
def test_onhour(self):
t = datetime.datetime(year=2015, month=12, day=1, hour=7, minute=5,
tzinfo=zoneinfo.gettz('America/New_York'))
with mock_datetime_now(t, datetime):
i = instance(Tags=[
{'Key': 'maid_offhours', 'Value': 'tz=est'}])
self.assertEqual(OnHour({})(i), True)
self.assertEqual(OnHour({'onhour': 8})(i), False)
def test_cant_parse_tz(self):
i = instance(Tags=[
{'Key': 'maid_offhours', 'Value': 'tz=evt'}])
self.assertEqual(OffHour({})(i), False)
def test_custom_offhours(self):
t = datetime.datetime.now(zoneinfo.gettz('America/New_York'))
t = t.replace(year=2016, month=5, day=26, hour=19, minute=00)
results = []
with mock_datetime_now(t, datetime):
for i in [instance(Tags=[{'Key': 'maid_offhours',
'Value': 'off=(m-f,19);on=(m-f,7);tz=et'}]),
instance(Tags=[{'Key': 'maid_offhours',
'Value': 'off=(m-f,20);on=(m-f,7);tz=et'}])]:
results.append(OffHour({})(i))
self.assertEqual(results, [True, False])
def test_custom_onhours(self):
t = datetime.datetime.now(zoneinfo.gettz('America/New_York'))
t = t.replace(year=2016, month=5, day=26, hour=7, minute=00)
results = []
with mock_datetime_now(t, datetime):
for i in [instance(Tags=[{'Key': 'maid_offhours',
'Value': 'off=(m-f,19);on=(m-f,7);tz=et'}]),
instance(Tags=[{'Key': 'maid_offhours',
'Value': 'off=(m-f,20);on=(m-f,9);tz=et'}])]:
results.append(OnHour({})(i))
self.assertEqual(results, [True, False])
def test_arizona_tz(self):
t = datetime.datetime.now(zoneinfo.gettz('America/New_York'))
t = t.replace(year=2016, month=5, day=26, hour=7, minute=00)
with mock_datetime_now(t, datetime):
i = instance(Tags=[{'Key': 'maid_offhours',
'Value': 'off=(m-f,19);on=(m-f,7);tz=at'}])
self.assertEqual(OnHour({})(i), True)
i = instance(Tags=[{'Key': 'maid_offhours',
'Value': 'off=(m-f,20);on=(m-f,6);tz=ast'}])
self.assertEqual(OnHour({})(i), False)
def test_custom_bad_tz(self):
t = datetime.datetime.now(zoneinfo.gettz('America/New_York'))
t = t.replace(year=2016, month=5, day=26, hour=7, minute=00)
with mock_datetime_now(t, datetime):
i = instance(Tags=[{'Key': 'maid_offhours',
'Value': 'off=(m-f,19);on=(m-f,7);tz=et'}])
self.assertEqual(OnHour({})(i), True)
i = instance(Tags=[{'Key': 'maid_offhours',
'Value': 'off=(m-f,20);on=(m-f,7);tz=abc'}])
self.assertEqual(OnHour({})(i), False)
def test_custom_bad_hours(self):
t = datetime.datetime.now(zoneinfo.gettz('America/New_York'))
t = t.replace(year=2016, month=5, day=26, hour=19, minute=00)
# default error handling is to exclude the resource
with mock_datetime_now(t, datetime):
# This isn't considered a bad value, its basically omitted.
i = instance(Tags=[{'Key': 'maid_offhours',
'Value': 'off=();tz=et'}])
self.assertEqual(OffHour({})(i), False)
i = instance(Tags=[{'Key': 'maid_offhours',
'Value': 'off=(m-f,90);on=(m-f,7);tz=et'}])
# malformed value
self.assertEqual(OffHour({})(i), False)
t = t.replace(year=2016, month=5, day=26, hour=13, minute=00)
with mock_datetime_now(t, datetime):
i = instance(Tags=[{'Key': 'maid_offhours',
'Value': 'off=();tz=et'}])
# will go to default values, but not work due to default time
self.assertEqual(OffHour({})(i), False)
i = instance(Tags=[{'Key': 'maid_offhours',
'Value': 'off=(m-f,90);on=(m-f,7);tz=et'}])
self.assertEqual(OffHour({})(i), False)
def test_tz_only(self):
t = datetime.datetime.now(zoneinfo.gettz('America/New_York'))
t = t.replace(year=2016, month=5, day=26, hour=7, minute=00)
with mock_datetime_now(t, datetime):
i = instance(Tags=[{'Key': 'maid_offhours',
'Value': 'tz=est'}])
self.assertEqual(OnHour({})(i), True)
def test_empty_tag(self):
t = datetime.datetime.now(zoneinfo.gettz('America/New_York'))
t = t.replace(year=2016, month=5, day=26, hour=7, minute=00)
with mock_datetime_now(t, datetime):
i = instance(Tags=[{'Key': 'maid_offhours',
'Value': ''}])
self.assertEqual(OnHour({})(i), True)
def test_on_tag(self):
t = datetime.datetime.now(zoneinfo.gettz('America/New_York'))
t = t.replace(year=2016, month=5, day=26, hour=7, minute=00)
with mock_datetime_now(t, datetime):
i = instance(Tags=[{'Key': 'maid_offhours',
'Value': 'on'}])
self.assertEqual(OnHour({})(i), True)
class ScheduleParserTest(BaseTest):
# table style test
# list of (tag value, parse result)
table = [
################
# Standard cases
('off=(m-f,10);on=(m-f,7);tz=et',
{'off': [{'days': [0, 1, 2, 3, 4], 'hour': 10}],
'on': [{'days': [0, 1, 2, 3, 4], 'hour': 7}],
'tz': 'et'}),
("off=[(m-f,9)];on=(m-s,10);tz=pt",
{'off': [{'days': [0, 1, 2, 3, 4], 'hour': 9}],
'on': [{'days': [0, 1, 2, 3, 4, 5], 'hour': 10}],
'tz': 'pt'}),
("off=[(m-f,23)];on=(m-s,10);tz=pt",
{'off': [{'days': [0, 1, 2, 3, 4], 'hour': 23}],
'on': [{'days': [0, 1, 2, 3, 4, 5], 'hour': 10}],
'tz': 'pt'}),
('off=(m-f,19);on=(m-f,7);tz=pst',
{'off': [{'days': [0, 1, 2, 3, 4], 'hour': 19}],
'on': [{'days': [0, 1, 2, 3, 4], 'hour': 7}],
'tz': 'pst'}),
# wrap around days (saturday, sunday, monday)
('on=[(s-m,10)];off=(s-m,19)',
{'on': [{'days': [5, 6, 0], 'hour': 10}],
'off': [{'days': [5, 6, 0], 'hour': 19}],
'tz': 'et'}),
# multiple single days specified
('on=[(m,9),(t,10),(w,7)];off=(m-u,19)',
{'on': [{'days': [0], 'hour': 9},
{'days': [1], 'hour': 10},
{'days': [2], 'hour': 7}],
'off': [{'days': [0, 1, 2, 3, 4, 5, 6], 'hour': 19}],
'tz': 'et'}),
# using brackets also works, if only single time set
('off=[m-f,20];on=[m-f,5];tz=est',
{'on': [{'days': [0, 1, 2, 3, 4], 'hour': 5}],
'off': [{'days': [0, 1, 2, 3, 4], 'hour': 20}],
'tz': 'est'}),
# same string, exercise cache lookup.
('off=[m-f,20];on=[m-f,5];tz=est',
{'on': [{'days': [0, 1, 2, 3, 4], 'hour': 5}],
'off': [{'days': [0, 1, 2, 3, 4], 'hour': 20}],
'tz': 'est'}),
################
# Invalid Cases
('', None),
# invalid day
('off=(1-2,12);on=(m-f,10);tz=est', None),
# invalid hour
('off=(m-f,a);on=(m-f,10);tz=est', None),
('off=(m-f,99);on=(m-f,7);tz=pst', None),
# invalid day
('off=(x-f,10);on=(m-f,10);tz=est', None),
# no hour specified for on
('off=(m-f);on=(m-f,10);tz=est', None),
# invalid day spec
('off=(m-t-f,12);on=(m-f,10);tz=est', None),
# random extra
('off=(m-f,5);zebra=blue,on=(t-w,5)', None),
('off=(m-f,5);zebra=blue;on=(t-w,5)', None),
# random extra again
('off=(m-f,5);zebrablue,on=(t-w,5)', None),
('bar;off=(m-f,5);zebrablue,on=(t-w,5)', None),
]
def test_schedule_parser(self):
self.maxDiff = None
parser = ScheduleParser({'tz': 'et'})
for value, expected in self.table:
self.assertEqual(parser.parse(value), expected)
| jimmyraywv/cloud-custodian | tests/test_offhours.py | Python | apache-2.0 | 21,903 |
/**
* Package contains filter for wicket data tables
*/
package org.orienteer.core.component.table.component; | OrienteerBAP/Orienteer | orienteer-core/src/main/java/org/orienteer/core/component/table/component/package-info.java | Java | apache-2.0 | 111 |
/**
* Copyright 2005-2014 Red Hat, Inc.
*
* Red Hat licenses this file to you 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.
*/
package io.fabric8.etcd.core;
import io.fabric8.etcd.api.Builder;
import io.fabric8.etcd.api.Node;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
public class ImmutableNode implements Node<ImmutableNode> {
public static class NodeBuilder implements Builder<ImmutableNode> {
private String key;
private long createdIndex;
private long modifiedIndex;
private String value;
private String expiration;
private int ttl;
private Set<ImmutableNode> nodes = new LinkedHashSet<ImmutableNode>();
private boolean dir;
public NodeBuilder key(String key) {
this.key = key;
return this;
}
public NodeBuilder createIndex(long createdIndex) {
this.createdIndex = createdIndex;
return this;
}
public NodeBuilder modifiedIndex(long modifiedIndex) {
this.modifiedIndex = modifiedIndex;
return this;
}
public NodeBuilder value(String value) {
this.value = value;
return this;
}
public NodeBuilder expiration(String expiration) {
this.expiration = expiration;
return this;
}
public NodeBuilder ttl(int ttl) {
this.ttl = ttl;
return this;
}
public NodeBuilder nodes(Set<ImmutableNode> nodes) {
this.nodes = nodes;
return this;
}
public NodeBuilder addNode(ImmutableNode node) {
this.nodes.add(node);
return this;
}
NodeBuilder dir(boolean dir) {
this.dir = dir;
return this;
}
@Override
public ImmutableNode build() {
return new ImmutableNode(key, createdIndex, modifiedIndex, value, expiration, ttl, nodes, nodes.size() > 0 || dir);
}
}
public static NodeBuilder builder() {
return new NodeBuilder();
}
private final String key;
private final long createdIndex;
private final long modifiedIndex;
private final String value;
private final String expiration;
private final int ttl;
private final Set<ImmutableNode> nodes;
private final boolean dir;
public ImmutableNode(Node<?> node) {
this.key = node.getKey();
this.createdIndex = node.getCreatedIndex();
this.modifiedIndex = node.getModifiedIndex();
this.value = node.getValue();
this.expiration = node.getExpiration();
this.ttl = node.getTtl();
Set<ImmutableNode> transformedNodes = new LinkedHashSet<>();
if (node.getNodes() != null) {
for (Node n : node.getNodes()) {
transformedNodes.add(new ImmutableNode(n));
}
}
this.nodes = Collections.unmodifiableSet(transformedNodes);
this.dir = node.isDir();
}
public ImmutableNode(String key, long createdIndex, long modifiedIndex, String value, String expiration, int ttl, Set<ImmutableNode> nodes, boolean dir) {
this.key = key;
this.createdIndex = createdIndex;
this.modifiedIndex = modifiedIndex;
this.value = value;
this.expiration = expiration;
this.ttl = ttl;
this.nodes = nodes != null ? Collections.unmodifiableSet(nodes) : Collections.<ImmutableNode>emptySet();
this.dir = dir;
}
public String getKey() {
return key;
}
public long getCreatedIndex() {
return createdIndex;
}
public long getModifiedIndex() {
return modifiedIndex;
}
public String getValue() {
return value;
}
public String getExpiration() {
return expiration;
}
public int getTtl() {
return ttl;
}
public Set<ImmutableNode> getNodes() {
return nodes;
}
public boolean isDir() {
return dir;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ImmutableNode node = (ImmutableNode) o;
if (createdIndex != node.createdIndex) return false;
if (modifiedIndex != node.modifiedIndex) return false;
if (key != null ? !key.equals(node.key) : node.key != null) return false;
if (value != null ? !value.equals(node.value) : node.value != null) return false;
return true;
}
@Override
public int hashCode() {
return key != null ? key.hashCode() : 0;
}
@Override
public String toString() {
return "ImmutableNode{" +
"key='" + key + '\'' +
", createdIndex=" + createdIndex +
", modifiedIndex=" + modifiedIndex +
", value='" + value + '\'' +
", expiration='" + expiration + '\'' +
", ttl=" + ttl +
", nodes=" + nodes +
", dir=" + dir +
'}';
}
}
| hekonsek/fabric8 | sandbox/fabric8-etcd/core/src/main/java/io/fabric8/etcd/core/ImmutableNode.java | Java | apache-2.0 | 5,684 |
/*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. 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.
*/
#ifndef WORKLOAD_STENCIL_APPLICATION_H_
#define WORKLOAD_STENCIL_APPLICATION_H_
#include <json/json.h>
#include <prim/prim.h>
#include <string>
#include <vector>
#include "event/Component.h"
#include "workload/Application.h"
#include "workload/Workload.h"
class MetadataHandler;
namespace Stencil {
class Application : public ::Application {
public:
Application(const std::string& _name, const Component* _parent, u32 _id,
Workload* _workload, MetadataHandler* _metadataHandler,
Json::Value _settings);
~Application();
f64 percentComplete() const override;
void start() override;
void stop() override;
void kill() override;
void terminalComplete(u32 _id);
void processEvent(void* _event, s32 _type) override;
private:
u32 completedTerminals_;
u32 doneTerminals_;
std::vector<u32> termToProc_;
std::vector<u32> procToTerm_;
};
} // namespace Stencil
#endif // WORKLOAD_STENCIL_APPLICATION_H_
| hpelabs/supersim | src/workload/stencil/Application.h | C | apache-2.0 | 1,626 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package org.apache.camel.component.zookeeper;
import static java.lang.String.format;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.component.zookeeper.operations.CreateOperation;
import org.apache.camel.component.zookeeper.operations.GetChildrenOperation;
import org.apache.camel.component.zookeeper.operations.OperationResult;
import org.apache.camel.component.zookeeper.operations.SetDataOperation;
import org.apache.camel.impl.DefaultProducer;
import org.apache.camel.util.ExchangeHelper;
import org.apache.zookeeper.AsyncCallback.StatCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException.Code;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import static org.apache.camel.component.zookeeper.ZooKeeperUtils.getAclListFromMessage;
import static org.apache.camel.component.zookeeper.ZooKeeperUtils.getCreateMode;
import static org.apache.camel.component.zookeeper.ZooKeeperUtils.getCreateModeFromString;
import static org.apache.camel.component.zookeeper.ZooKeeperUtils.getNodeFromMessage;
import static org.apache.camel.component.zookeeper.ZooKeeperUtils.getPayloadFromExchange;
import static org.apache.camel.component.zookeeper.ZooKeeperUtils.getVersionFromMessage;
/**
* <code>ZookeeperProducer</code> attempts to set the content of nodes in the
* {@link ZooKeeper} cluster with the payloads of the of the exchanges it
* receives.
*/
@SuppressWarnings("rawtypes")
public class ZookeeperProducer extends DefaultProducer {
private ZooKeeperConfiguration configuration;
private ZooKeeperConnectionManager zkm;
public ZookeeperProducer(ZooKeeperEndpoint endpoint) {
super(endpoint);
this.configuration = endpoint.getConfiguration();
this.zkm = endpoint.getConnectionManager();
}
public void process(Exchange exchange) throws Exception {
ZooKeeper connection = zkm.getConnection();
ProductionContext context = new ProductionContext(connection, exchange);
if (ExchangeHelper.isOutCapable(exchange)) {
if (log.isDebugEnabled()) {
log.debug(format("Storing data to znode '%s', waiting for confirmation", context.node));
}
OperationResult result = synchronouslySetData(context);
if (configuration.listChildren()) {
result = listChildren(context);
}
updateExchangeWithResult(context, result);
} else {
asynchronouslySetDataOnNode(connection, context);
}
}
private void asynchronouslySetDataOnNode(ZooKeeper connection, ProductionContext context) {
if (log.isDebugEnabled()) {
log.debug(format("Storing data to node '%s', not waiting for confirmation", context.node));
}
connection.setData(context.node, context.payload, context.version, new AsyncSetDataCallback(), context);
}
private void updateExchangeWithResult(ProductionContext context, OperationResult result) {
ZooKeeperMessage out = new ZooKeeperMessage(context.node, result.getStatistics(), context.in.getHeaders());
if (result.isOk()) {
out.setBody(result.getResult());
} else {
context.exchange.setException(result.getException());
}
context.exchange.setOut(out);
}
private OperationResult listChildren(ProductionContext context) throws Exception {
return new GetChildrenOperation(context.connection, configuration.getPath()).get();
}
/** Simple container to avoid passing all these around as parameters */
private class ProductionContext {
ZooKeeper connection;
Exchange exchange;
Message in;
byte[] payload;
int version;
String node;
public ProductionContext(ZooKeeper connection, Exchange exchange) {
this.connection = connection;
this.exchange = exchange;
this.in = exchange.getIn();
this.node = getNodeFromMessage(in, configuration.getPath());
this.version = getVersionFromMessage(in);
this.payload = getPayloadFromExchange(exchange);
}
}
private class AsyncSetDataCallback implements StatCallback {
public void processResult(int rc, String node, Object ctx, Stat statistics) {
if (Code.NONODE.equals(Code.get(rc))) {
if (configuration.shouldCreate()) {
log.warn(format("Node '%s' did not exist, creating it...", node));
ProductionContext context = (ProductionContext)ctx;
OperationResult<String> result = null;
try {
result = createNode(context);
} catch (Exception e) {
log.error(format("Error trying to create node '%s'", node), e);
}
if (result == null || !result.isOk()) {
log.error(format("Error creating node '%s'", node), result.getException());
}
}
} else {
logStoreComplete(node, statistics);
}
}
}
private OperationResult<String> createNode(ProductionContext ctx) throws Exception {
CreateOperation create = new CreateOperation(ctx.connection, ctx.node);
create.setPermissions(getAclListFromMessage(ctx.exchange.getIn()));
CreateMode mode = null;
String modeString = configuration.getCreateMode();
if (modeString != null) {
try {
mode = getCreateModeFromString(modeString, CreateMode.EPHEMERAL);
} catch (Exception e) { }
} else {
mode = getCreateMode(ctx.exchange.getIn(), CreateMode.EPHEMERAL);
}
create.setCreateMode(mode == null ? CreateMode.EPHEMERAL : mode);
create.setData(ctx.payload);
return create.get();
}
/**
* Tries to set the data first and if a no node error is received then an
* attempt will be made to create it instead.
*/
private OperationResult synchronouslySetData(ProductionContext ctx) throws Exception {
SetDataOperation setData = new SetDataOperation(ctx.connection, ctx.node, ctx.payload);
setData.setVersion(ctx.version);
OperationResult result = setData.get();
if (!result.isOk() && configuration.shouldCreate() && result.failedDueTo(Code.NONODE)) {
log.warn(format("Node '%s' did not exist, creating it.", ctx.node));
result = createNode(ctx);
}
return result;
}
private void logStoreComplete(String path, Stat statistics) {
if (log.isDebugEnabled()) {
if (log.isTraceEnabled()) {
log.trace(format("Stored data to node '%s', and receive statistics %s", path, statistics));
} else {
log.debug(format("Stored data to node '%s'", path));
}
}
}
}
| aaronwalker/camel | components/camel-zookeeper/src/main/java/org/apache/camel/component/zookeeper/ZookeeperProducer.java | Java | apache-2.0 | 7,870 |
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/fms/model/SecurityGroupRemediationAction.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace FMS
{
namespace Model
{
SecurityGroupRemediationAction::SecurityGroupRemediationAction() :
m_remediationActionType(RemediationActionType::NOT_SET),
m_remediationActionTypeHasBeenSet(false),
m_descriptionHasBeenSet(false),
m_remediationResultHasBeenSet(false),
m_isDefaultAction(false),
m_isDefaultActionHasBeenSet(false)
{
}
SecurityGroupRemediationAction::SecurityGroupRemediationAction(JsonView jsonValue) :
m_remediationActionType(RemediationActionType::NOT_SET),
m_remediationActionTypeHasBeenSet(false),
m_descriptionHasBeenSet(false),
m_remediationResultHasBeenSet(false),
m_isDefaultAction(false),
m_isDefaultActionHasBeenSet(false)
{
*this = jsonValue;
}
SecurityGroupRemediationAction& SecurityGroupRemediationAction::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("RemediationActionType"))
{
m_remediationActionType = RemediationActionTypeMapper::GetRemediationActionTypeForName(jsonValue.GetString("RemediationActionType"));
m_remediationActionTypeHasBeenSet = true;
}
if(jsonValue.ValueExists("Description"))
{
m_description = jsonValue.GetString("Description");
m_descriptionHasBeenSet = true;
}
if(jsonValue.ValueExists("RemediationResult"))
{
m_remediationResult = jsonValue.GetObject("RemediationResult");
m_remediationResultHasBeenSet = true;
}
if(jsonValue.ValueExists("IsDefaultAction"))
{
m_isDefaultAction = jsonValue.GetBool("IsDefaultAction");
m_isDefaultActionHasBeenSet = true;
}
return *this;
}
JsonValue SecurityGroupRemediationAction::Jsonize() const
{
JsonValue payload;
if(m_remediationActionTypeHasBeenSet)
{
payload.WithString("RemediationActionType", RemediationActionTypeMapper::GetNameForRemediationActionType(m_remediationActionType));
}
if(m_descriptionHasBeenSet)
{
payload.WithString("Description", m_description);
}
if(m_remediationResultHasBeenSet)
{
payload.WithObject("RemediationResult", m_remediationResult.Jsonize());
}
if(m_isDefaultActionHasBeenSet)
{
payload.WithBool("IsDefaultAction", m_isDefaultAction);
}
return payload;
}
} // namespace Model
} // namespace FMS
} // namespace Aws
| awslabs/aws-sdk-cpp | aws-cpp-sdk-fms/source/model/SecurityGroupRemediationAction.cpp | C++ | apache-2.0 | 2,555 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
package org.apache.aries.proxy.impl.interfaces;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.aries.proxy.UnableToProxyException;
import org.apache.aries.proxy.impl.ProxyUtils;
import org.apache.aries.proxy.impl.common.AbstractWovenProxyAdapter;
import org.apache.aries.proxy.impl.common.OSGiFriendlyClassVisitor;
import org.apache.aries.proxy.impl.common.OSGiFriendlyClassWriter;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.Method;
/**
* This class is used to aggregate several interfaces into a real class which implements all of them
*/
final class InterfaceCombiningClassAdapter extends ClassVisitor implements Opcodes {
/** The superclass we should use */
private final Class<?> superclass;
/** The interfaces we need to implement */
private final Collection<Class<?>> interfaces;
/** The {@link ClassWriter} we use to write our class */
private final ClassWriter writer;
/** The adapter we use to weave in our method implementations */
private final AbstractWovenProxyAdapter adapter;
/** Whether we have already written the class bytes */
private boolean done = false;
/**
* Construct an {@link InterfaceCombiningClassAdapter} to combine the supplied
* interfaces into a class with the supplied name using the supplied classloader
* @param className
* @param loader
* @param interfaces
*/
InterfaceCombiningClassAdapter(String className,
ClassLoader loader, Class<?> superclass, Collection<Class<?>> interfaces) {
super(Opcodes.ASM9);
writer = new OSGiFriendlyClassWriter(ClassWriter.COMPUTE_FRAMES, loader);
ClassVisitor cv = new OSGiFriendlyClassVisitor(writer, ClassWriter.COMPUTE_FRAMES);
adapter = new InterfaceUsingWovenProxyAdapter(cv, className, loader);
this.interfaces = interfaces;
this.superclass = superclass;
String[] interfaceNames = new String[interfaces.size()];
int i = 0;
for(Class<?> in : interfaces) {
interfaceNames[i] = Type.getInternalName(in);
i++;
}
adapter.visit(ProxyUtils.getWeavingJavaVersion(), ACC_PUBLIC | ACC_SYNTHETIC, className, null,
(superclass == null) ? AbstractWovenProxyAdapter.OBJECT_TYPE.getInternalName() :
Type.getInternalName(superclass), interfaceNames);
}
@Override
public final MethodVisitor visitMethod(int access, String name, String desc,
String sig, String[] arg4) {
//If we already implement this method (from another interface) then we don't
//want a duplicate. We also don't want to copy any static init blocks (these
//initialize static fields on the interface that we don't copy
if(adapter.getKnownMethods().contains(new Method(name, desc)) ||
"<clinit>".equals(name)) {
return null;
}
else if(((access & (ACC_PRIVATE|ACC_SYNTHETIC)) == (ACC_PRIVATE|ACC_SYNTHETIC))) {
// private, synthetic methods on interfaces don't need to be proxied.
return null;
} else if (((access & (ACC_STATIC)) == (ACC_STATIC))) {
//static methods on interfaces don't need to be proxied
return null;
}
else {//We're going to implement this method, so make it non abstract!
return adapter.visitMethod(access, name, desc, null, arg4);
}
}
/**
* Generate the byte[] for our class
* @return
* @throws UnableToProxyException
*/
final byte[] generateBytes() throws UnableToProxyException {
if(!!!done) {
for(Class<?> c : interfaces) {
adapter.setCurrentMethodDeclaringType(Type.getType(c), true);
try {
AbstractWovenProxyAdapter.readClass(c, this);
} catch (IOException e) {
throw new UnableToProxyException(c, e);
}
}
Class<?> clazz = superclass;
while(clazz != null && (clazz.getModifiers() & Modifier.ABSTRACT) != 0) {
adapter.setCurrentMethodDeclaringType(Type.getType(clazz), false);
visitAbstractMethods(clazz);
clazz = clazz.getSuperclass();
}
adapter.setCurrentMethodDeclaringType(AbstractWovenProxyAdapter.OBJECT_TYPE, false);
visitObjectMethods();
adapter.visitEnd();
done = true;
}
return writer.toByteArray();
}
private void visitAbstractMethods(Class<?> clazz) {
for(java.lang.reflect.Method m : clazz.getDeclaredMethods()) {
int modifiers = m.getModifiers();
if((modifiers & Modifier.ABSTRACT) != 0) {
List<String> exceptions = new ArrayList<String>();
for(Class<?> c : m.getExceptionTypes()) {
exceptions.add(Type.getInternalName(c));
}
MethodVisitor visitor = visitMethod(modifiers, m.getName(), Method.getMethod(m).getDescriptor(),
null, exceptions.toArray(new String[exceptions.size()]));
if (visitor != null) visitor.visitEnd();
}
}
}
/**
* Make sure that the three common Object methods toString, equals and hashCode are redirected to the delegate
* even if they are not on any of the interfaces
*/
private void visitObjectMethods() {
MethodVisitor visitor = visitMethod(ACC_PUBLIC | ACC_ABSTRACT, "toString", "()Ljava/lang/String;", null, null);
if (visitor != null) visitor.visitEnd();
visitor = visitMethod(ACC_PUBLIC | ACC_ABSTRACT, "equals", "(Ljava/lang/Object;)Z", null, null);
if (visitor != null) visitor.visitEnd();
visitor = visitMethod(ACC_PUBLIC | ACC_ABSTRACT, "hashCode", "()I", null, null);
if (visitor != null) visitor.visitEnd();
}
}
| apache/aries | proxy/proxy-impl/src/main/java/org/apache/aries/proxy/impl/interfaces/InterfaceCombiningClassAdapter.java | Java | apache-2.0 | 6,805 |
// @flow
import * as React from 'react'
import { shallow } from 'enzyme'
import { SlotMap } from '../SlotMap'
import { Icon } from '../../icons'
describe('SlotMap', () => {
it('component renders 11 slots', () => {
const wrapper = shallow(<SlotMap occupiedSlots={['1']} />)
expect(wrapper.find('rect')).toHaveLength(11)
})
it('component renders crash info icon when collision slots present', () => {
const wrapper = shallow(
<SlotMap occupiedSlots={['1']} collisionSlots={['4']} />
)
expect(wrapper.find(Icon)).toHaveLength(1)
})
it('component applies occupied and error styles', () => {
const wrapperDefault = shallow(<SlotMap occupiedSlots={['1']} />)
const wrapperWithError = shallow(
<SlotMap occupiedSlots={['1']} isError={true} />
)
expect(wrapperDefault.find('.slot_occupied')).toHaveLength(1)
expect(wrapperWithError.find('.slot_occupied')).toHaveLength(1)
expect(wrapperWithError.find('.slot_occupied.slot_error')).toHaveLength(1)
})
})
| Opentrons/labware | components/src/slotmap/__tests__/SlotMap.test.js | JavaScript | apache-2.0 | 1,020 |
import { Nullable } from "babylonjs/types";
import * as React from "react";
import { GlobalState } from "../../../../../../globalState";
import { Context, IActiveAnimationChangedOptions } from "../context";
import { Observer } from "babylonjs/Misc/observable";
// x distance between consecutive ticks on the frame
const baseTickDistance = 25;
const minTickDistance = 35;
interface IFrameBarComponentProps {
globalState: GlobalState;
context: Context;
}
interface IFrameBarComponentState {}
export class FrameBarComponent extends React.Component<IFrameBarComponentProps, IFrameBarComponentState> {
private readonly _GraphAbsoluteWidth = 788;
private _svgHost: React.RefObject<SVGSVGElement>;
private _viewWidth = 748;
private _viewScale = 1;
private _offsetX = 0;
private _onActiveAnimationChangedObserver: Nullable<Observer<IActiveAnimationChangedOptions>>;
constructor(props: IFrameBarComponentProps) {
super(props);
this.state = {};
this._svgHost = React.createRef();
this.props.context.onHostWindowResized.add(() => {
this._computeSizes();
});
this._onActiveAnimationChangedObserver = this.props.context.onActiveAnimationChanged.add(() => {
this._computeSizes();
this.forceUpdate();
});
this.props.context.onGraphMoved.add((x) => {
this._offsetX = x;
this.forceUpdate();
});
this.props.context.onGraphScaled.add((scale) => {
this._viewScale = scale;
this.forceUpdate();
});
}
componentWillUnmount() {
if (this._onActiveAnimationChangedObserver) {
this.props.context.onActiveAnimationChanged.remove(this._onActiveAnimationChangedObserver);
}
}
private _computeSizes() {
if (!this._svgHost.current) {
return;
}
this._viewWidth = this._svgHost.current.clientWidth;
this.forceUpdate();
}
private _buildFrames() {
if (this.props.context.activeAnimations.length === 0) {
return null;
}
let minFrame = this.props.context.referenceMinFrame;
let maxFrame = this.props.context.referenceMaxFrame;
let range = maxFrame - minFrame;
let convertRatio = range / this._GraphAbsoluteWidth;
const dist = Math.max(baseTickDistance * this._viewScale, minTickDistance) ; // x distance between consecutive ticks
let offset = Math.floor(dist * convertRatio);
let steps = [];
if (offset === 0) {
offset = 1;
}
let startPosition = this._offsetX * convertRatio;
let start = minFrame - ((startPosition / offset) | 0) * offset;
let end = start + this._viewWidth * this._viewScale * convertRatio;
for (var step = start - offset; step <= end + offset; step += offset) {
steps.push(step);
}
return steps.map((s, i) => {
let x = (s - minFrame) / convertRatio;
return (
<g key={"axis" + s}>
<line
key={"line" + s}
x1={x}
y1={`${5 * this._viewScale}px`}
x2={x}
y2={`${30 * this._viewScale}px`}
style={{
stroke: "#333333",
strokeWidth: 0.5,
}}
></line>
<text
key={"label" + s}
x={x}
y={0}
dx={`${7 * this._viewScale}px`}
textAnchor="middle"
dy={`${15 * this._viewScale}px`}
style={{
fontFamily: "acumin-pro-condensed",
fontSize: `${10 * this._viewScale}px`,
fill: "#555555",
textAlign: "center",
}}
>
{s.toFixed(0)}
</text>
</g>
);
});
}
public render() {
const viewBox = `${-this._offsetX} 0 ${Math.round(this._viewWidth * this._viewScale)} ${Math.round(30 * this._viewScale)}`;
return (
<div id="frame-bar">
{this.props.context.activeAnimations.length > 0 && <div id="angle-unit"></div>}
<div id="frames">
<svg id="svg-frames" viewBox={viewBox} ref={this._svgHost}>
{this._buildFrames()}
</svg>
</div>
</div>
);
}
}
| RaananW/Babylon.js | inspector/src/components/actionTabs/tabs/propertyGrids/animations/curveEditor/graph/frameBarComponent.tsx | TypeScript | apache-2.0 | 4,934 |
// Copyright (c) 2012 Ecma International. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es5id: 15.2.3.6-4-62
description: >
Object.defineProperty - both desc.value and name.value are null
(8.12.9 step 6)
includes: [propertyHelper.js]
---*/
var obj = {};
Object.defineProperty(obj, "foo", { value: null });
Object.defineProperty(obj, "foo", { value: null });
verifyEqualTo(obj, "foo", null);
verifyNotWritable(obj, "foo");
verifyNotEnumerable(obj, "foo");
verifyNotConfigurable(obj, "foo");
| m0ppers/arangodb | 3rdParty/V8/V8-5.0.71.39/test/test262/data/test/built-ins/Object/defineProperty/15.2.3.6-4-62.js | JavaScript | apache-2.0 | 560 |
// Lucene version compatibility level 8.2.0
using System;
using Lucene.Net.TestFramework;
#if TESTFRAMEWORK_MSTEST
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
using Assert = Lucene.Net.TestFramework.Assert;
#elif TESTFRAMEWORK_NUNIT
using Test = NUnit.Framework.TestAttribute;
using Assert = NUnit.Framework.Assert;
#elif TESTFRAMEWORK_XUNIT
using Test = Lucene.Net.TestFramework.SkippableFactAttribute;
using Assert = Lucene.Net.TestFramework.Assert;
#endif
namespace Lucene.Net.Analysis
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
#if TESTFRAMEWORK_MSTEST
[Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute]
#endif
public class TestMockCharFilter : BaseTokenStreamTestCase
#if TESTFRAMEWORK_XUNIT
, Xunit.IClassFixture<BeforeAfterClass>
{
public TestMockCharFilter(BeforeAfterClass beforeAfter)
: base(beforeAfter)
{
}
#else
{
#endif
[Test]
public void Test()
{
Analyzer analyzer = Analyzer.NewAnonymous(createComponents: (fieldName, reader) =>
{
Tokenizer tokenizer = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false);
return new TokenStreamComponents(tokenizer, tokenizer);
},
initReader: (fieldName, reader) =>
{
return new MockCharFilter(reader, 7);
});
AssertAnalyzesTo(analyzer, "ab",
new String[] { "aab" },
new int[] { 0 },
new int[] { 2 }
);
AssertAnalyzesTo(analyzer, "aba",
new String[] { "aabaa" },
new int[] { 0 },
new int[] { 3 }
);
AssertAnalyzesTo(analyzer, "abcdefga",
new String[] { "aabcdefgaa" },
new int[] { 0 },
new int[] { 8 }
);
}
}
}
| jeme/lucenenet | src/Lucene.Net.Tests.TestFramework/Analysis/TestMockCharFilter.cs | C# | apache-2.0 | 2,771 |
/*
* Copyright 2002-2012 the original author or authors.
*
* 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.
*/
package org.springframework.tests.sample.beans;
public class Employee extends TestBean {
private String co;
public String getCompany() {
return co;
}
public void setCompany(String co) {
this.co = co;
}
}
| qobel/esoguproject | spring-framework/spring-context/src/test/java/org/springframework/tests/sample/beans/Employee.java | Java | apache-2.0 | 840 |
package net.sourceforge.squirrel_sql.client;
/*
* Copyright (C) 2001-2006 Colin Bell
* colbell@users.sourceforge.net
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
import net.sourceforge.squirrel_sql.client.plugin.DefaultPlugin;
/**
* Dummy plugin used by the application.
*/
public class DummyAppPlugin extends DefaultPlugin
{
/**
* Return the internal name of this plugin.
*
* @return the internal name of this plugin.
*/
public String getInternalName()
{
return "app";
}
/**
* Return the descriptive name of this plugin.
*
* @return the descriptive name of this plugin.
*/
public String getDescriptiveName()
{
return "Dummy Application Plugin";
}
/**
* Returns the current version of this plugin.
*
* @return the current version of this plugin.
*/
public String getVersion()
{
return "0.1";
}
/**
* Returns the authors name.
*
* @return the authors name.
*/
public String getAuthor()
{
return "Colin Bell";
}
}
| sdgdsffdsfff/bigtable-sql | src/main/java/net/sourceforge/squirrel_sql/client/DummyAppPlugin.java | Java | apache-2.0 | 1,677 |
<?php
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/cloud/contactcenterinsights/v1/contact_center_insights.proto
namespace Google\Cloud\ContactCenterInsights\V1;
use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;
/**
* The response of listing issue models.
*
* Generated from protobuf message <code>google.cloud.contactcenterinsights.v1.ListIssueModelsResponse</code>
*/
class ListIssueModelsResponse extends \Google\Protobuf\Internal\Message
{
/**
* The issue models that match the request.
*
* Generated from protobuf field <code>repeated .google.cloud.contactcenterinsights.v1.IssueModel issue_models = 1;</code>
*/
private $issue_models;
/**
* Constructor.
*
* @param array $data {
* Optional. Data for populating the Message object.
*
* @type \Google\Cloud\ContactCenterInsights\V1\IssueModel[]|\Google\Protobuf\Internal\RepeatedField $issue_models
* The issue models that match the request.
* }
*/
public function __construct($data = NULL) {
\GPBMetadata\Google\Cloud\Contactcenterinsights\V1\ContactCenterInsights::initOnce();
parent::__construct($data);
}
/**
* The issue models that match the request.
*
* Generated from protobuf field <code>repeated .google.cloud.contactcenterinsights.v1.IssueModel issue_models = 1;</code>
* @return \Google\Protobuf\Internal\RepeatedField
*/
public function getIssueModels()
{
return $this->issue_models;
}
/**
* The issue models that match the request.
*
* Generated from protobuf field <code>repeated .google.cloud.contactcenterinsights.v1.IssueModel issue_models = 1;</code>
* @param \Google\Cloud\ContactCenterInsights\V1\IssueModel[]|\Google\Protobuf\Internal\RepeatedField $var
* @return $this
*/
public function setIssueModels($var)
{
$arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Cloud\ContactCenterInsights\V1\IssueModel::class);
$this->issue_models = $arr;
return $this;
}
}
| googleapis/google-cloud-php-contact-center-insights | src/V1/ListIssueModelsResponse.php | PHP | apache-2.0 | 2,228 |
# rfkill tests
# Copyright (c) 2014, Jouni Malinen <j@w1.fi>
#
# This software may be distributed under the terms of the BSD license.
# See README for more details.
import logging
logger = logging.getLogger()
import time
import hostapd
from hostapd import HostapdGlobal
import hwsim_utils
from wpasupplicant import WpaSupplicant
from rfkill import RFKill
from utils import HwsimSkip
def get_rfkill(dev):
phy = dev.get_driver_status_field("phyname")
try:
for r, s, h in RFKill.list():
if r.name == phy:
return r
except Exception, e:
raise HwsimSkip("No rfkill available: " + str(e))
raise HwsimSkip("No rfkill match found for the interface")
def test_rfkill_open(dev, apdev):
"""rfkill block/unblock during open mode connection"""
rfk = get_rfkill(dev[0])
hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid": "open" })
dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
try:
logger.info("rfkill block")
rfk.block()
dev[0].wait_disconnected(timeout=10,
error="Missing disconnection event on rfkill block")
if "FAIL" not in dev[0].request("REASSOCIATE"):
raise Exception("REASSOCIATE accepted while disabled")
if "FAIL" not in dev[0].request("REATTACH"):
raise Exception("REATTACH accepted while disabled")
if "FAIL" not in dev[0].request("RECONNECT"):
raise Exception("RECONNECT accepted while disabled")
if "FAIL" not in dev[0].request("FETCH_OSU"):
raise Exception("FETCH_OSU accepted while disabled")
logger.info("rfkill unblock")
rfk.unblock()
dev[0].wait_connected(timeout=10,
error="Missing connection event on rfkill unblock")
hwsim_utils.test_connectivity(dev[0], hapd)
finally:
rfk.unblock()
def test_rfkill_wpa2_psk(dev, apdev):
"""rfkill block/unblock during WPA2-PSK connection"""
rfk = get_rfkill(dev[0])
ssid = "test-wpa2-psk"
passphrase = 'qwertyuiop'
params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
hapd = hostapd.add_ap(apdev[0]['ifname'], params)
dev[0].connect(ssid, psk=passphrase, scan_freq="2412")
try:
logger.info("rfkill block")
rfk.block()
dev[0].wait_disconnected(timeout=10,
error="Missing disconnection event on rfkill block")
logger.info("rfkill unblock")
rfk.unblock()
dev[0].wait_connected(timeout=10,
error="Missing connection event on rfkill unblock")
hwsim_utils.test_connectivity(dev[0], hapd)
finally:
rfk.unblock()
def test_rfkill_autogo(dev, apdev):
"""rfkill block/unblock for autonomous P2P GO"""
rfk0 = get_rfkill(dev[0])
rfk1 = get_rfkill(dev[1])
dev[0].p2p_start_go()
dev[1].request("SET p2p_no_group_iface 0")
dev[1].p2p_start_go()
try:
logger.info("rfkill block 0")
rfk0.block()
ev = dev[0].wait_global_event(["P2P-GROUP-REMOVED"], timeout=10)
if ev is None:
raise Exception("Group removal not reported")
if "reason=UNAVAILABLE" not in ev:
raise Exception("Unexpected group removal reason: " + ev)
if "FAIL" not in dev[0].request("P2P_LISTEN 1"):
raise Exception("P2P_LISTEN accepted unexpectedly")
if "FAIL" not in dev[0].request("P2P_LISTEN"):
raise Exception("P2P_LISTEN accepted unexpectedly")
logger.info("rfkill block 1")
rfk1.block()
ev = dev[1].wait_global_event(["P2P-GROUP-REMOVED"], timeout=10)
if ev is None:
raise Exception("Group removal not reported")
if "reason=UNAVAILABLE" not in ev:
raise Exception("Unexpected group removal reason: " + ev)
logger.info("rfkill unblock 0")
rfk0.unblock()
logger.info("rfkill unblock 1")
rfk1.unblock()
time.sleep(1)
finally:
rfk0.unblock()
rfk1.unblock()
def test_rfkill_hostapd(dev, apdev):
"""rfkill block/unblock during and prior to hostapd operations"""
hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid": "open" })
rfk = get_rfkill(hapd)
try:
rfk.block()
ev = hapd.wait_event(["INTERFACE-DISABLED"], timeout=5)
if ev is None:
raise Exception("INTERFACE-DISABLED event not seen")
rfk.unblock()
ev = hapd.wait_event(["INTERFACE-ENABLED"], timeout=5)
if ev is None:
raise Exception("INTERFACE-ENABLED event not seen")
# hostapd does not current re-enable beaconing automatically
hapd.disable()
hapd.enable()
dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
rfk.block()
ev = hapd.wait_event(["INTERFACE-DISABLED"], timeout=5)
if ev is None:
raise Exception("INTERFACE-DISABLED event not seen")
dev[0].wait_disconnected(timeout=10)
dev[0].request("DISCONNECT")
hapd.disable()
hglobal = HostapdGlobal()
hglobal.flush()
hglobal.remove(apdev[0]['ifname'])
hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid": "open2" },
no_enable=True)
if "FAIL" not in hapd.request("ENABLE"):
raise Exception("ENABLE succeeded unexpectedly (rfkill)")
finally:
rfk.unblock()
def test_rfkill_wpas(dev, apdev):
"""rfkill block prior to wpa_supplicant start"""
wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
wpas.interface_add("wlan5")
rfk = get_rfkill(wpas)
wpas.interface_remove("wlan5")
try:
rfk.block()
wpas.interface_add("wlan5")
time.sleep(0.5)
state = wpas.get_status_field("wpa_state")
if state != "INTERFACE_DISABLED":
raise Exception("Unexpected state with rfkill blocked: " + state)
rfk.unblock()
time.sleep(0.5)
state = wpas.get_status_field("wpa_state")
if state == "INTERFACE_DISABLED":
raise Exception("Unexpected state with rfkill unblocked: " + state)
finally:
rfk.unblock()
| wangybgit/Chameleon | hostapd-OpenWrt/tests/hwsim/test_rfkill.py | Python | apache-2.0 | 6,236 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Collections.Generic;
namespace Azure.Management.Network.Models
{
/// <summary> Private dns zone group resource. </summary>
public partial class PrivateDnsZoneGroup : SubResource
{
/// <summary> Initializes a new instance of PrivateDnsZoneGroup. </summary>
public PrivateDnsZoneGroup()
{
}
/// <summary> Initializes a new instance of PrivateDnsZoneGroup. </summary>
/// <param name="id"> Resource ID. </param>
/// <param name="name"> Name of the resource that is unique within a resource group. This name can be used to access the resource. </param>
/// <param name="etag"> A unique read-only string that changes whenever the resource is updated. </param>
/// <param name="provisioningState"> The provisioning state of the private dns zone group resource. </param>
/// <param name="privateDnsZoneConfigs"> A collection of private dns zone configurations of the private dns zone group. </param>
internal PrivateDnsZoneGroup(string id, string name, string etag, ProvisioningState? provisioningState, IList<PrivateDnsZoneConfig> privateDnsZoneConfigs) : base(id)
{
Name = name;
Etag = etag;
ProvisioningState = provisioningState;
PrivateDnsZoneConfigs = privateDnsZoneConfigs;
}
/// <summary> Name of the resource that is unique within a resource group. This name can be used to access the resource. </summary>
public string Name { get; set; }
/// <summary> A unique read-only string that changes whenever the resource is updated. </summary>
public string Etag { get; }
/// <summary> The provisioning state of the private dns zone group resource. </summary>
public ProvisioningState? ProvisioningState { get; }
/// <summary> A collection of private dns zone configurations of the private dns zone group. </summary>
public IList<PrivateDnsZoneConfig> PrivateDnsZoneConfigs { get; set; }
}
}
| stankovski/azure-sdk-for-net | sdk/testcommon/Azure.Management.Network.2020_04/src/Generated/Models/PrivateDnsZoneGroup.cs | C# | apache-2.0 | 2,172 |
/*
*
* Copyright 2013 the original author or authors.
* Copyright 2013 SorcerSoft.org.
*
* 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.
*/
package sorcer.core.exertion;
import net.jini.core.transaction.Transaction;
import sorcer.core.context.ServiceContext;
import sorcer.core.context.ThrowableTrace;
import sorcer.service.*;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* The alternative Exertion that executes sequentially a collection of optional
* exertions. It executes the first optExertion in the collection such that its
* condition is true.
*
* @author Mike Sobolewski
*/
@SuppressWarnings("unchecked")
public class AltMogram extends ConditionalMogram {
private static final long serialVersionUID = 4012356285896459828L;
protected List<OptMogram> optExertions;
public AltMogram(OptMogram... optExertions) {
super();
this.optExertions = Arrays.asList(optExertions);
}
public AltMogram(String name, OptMogram... optExertions) {
super(name);
this.optExertions = Arrays.asList(optExertions);
}
public AltMogram(String name, List<OptMogram> optExertions) {
super(name);
this.optExertions = optExertions;
}
@Override
public Task doTask(Transaction txn, Arg... args) throws ExertionException,
SignatureException, RemoteException {
OptMogram opt = null;
try {
for (int i = 0; i < optExertions.size(); i++) {
opt = optExertions.get(i);
if (opt.getCondition().isTrue()) {
opt.isActive = true;
Context cxt = opt.getCondition().getConditionalContext();
if (cxt != null) {
Condition.clenupContextScripts(cxt);
opt.getTarget().getDataContext().updateEntries(cxt);
}
Exertion out = opt.getTarget().exert(txn, args);
opt.setTarget(out);
dataContext = (ServiceContext) out.getContext();
controlContext.append(out.getControlContext());
dataContext.putValue(Condition.CONDITION_VALUE, true);
dataContext.putValue(Condition.CONDITION_TARGET, opt.getName());
return this;
}
}
dataContext.putValue(Condition.CONDITION_VALUE, false);
dataContext.putValue(Condition.CONDITION_TARGET, opt.getName());
dataContext.setExertion(null);
} catch (Exception e) {
e.printStackTrace();
throw new ExertionException(e);
}
return this;
}
public OptMogram getActiveOptExertion() {
OptMogram active = null;
for (OptMogram oe : optExertions) {
if (oe.isActive())
return oe;
}
return active;
}
public List<OptMogram> getOptExertions() {
return optExertions;
}
public void setOptExertions(List<OptMogram> optExertions) {
this.optExertions = optExertions;
}
public OptMogram getOptExertion(int index) {
return optExertions.get(index);
}
public boolean isConditional() {
return true;
}
public void reset(int state) {
for (ServiceExertion e : optExertions)
e.reset(state);
this.setStatus(state);
}
/* (non-Javadoc)
* @see sorcer.service.Conditional#getConditions()
*/
@Override
public List<Conditional> getConditions() {
List<Conditional> cs = new ArrayList<Conditional>(optExertions.size());
for (OptMogram oe : optExertions)
cs.add(oe.getCondition());
return cs;
}
@Override
public List<ThrowableTrace> getExceptions(List<ThrowableTrace> exceptions) {
for (Exertion ext : optExertions) {
exceptions.addAll(((ServiceExertion)ext).getExceptions(exceptions));
}
exceptions.addAll(this.getExceptions());
return exceptions;
}
/*
* (non-Javadoc)
*
* @see sorcer.service.Exertion#getMograms()
*/
@Override
public List<Mogram> getMograms() {
ArrayList<Mogram> list = new ArrayList<Mogram>(1);
list.addAll(optExertions);
return list;
}
public List<Mogram> getMograms(List<Mogram> exs) {
for (Exertion e : optExertions)
((ServiceExertion) e).getMograms(exs);
exs.add(this);
return exs;
}
/* (non-Javadoc)
* @see sorcer.service.ConditionalExertion#getTargets()
*/
@Override
public List<Mogram> getTargets() {
List<Mogram> tl = new ArrayList<Mogram>(optExertions.size());
for (OptMogram oe : optExertions)
tl.add(oe.getTarget());
return tl;
}
/* (non-Javadoc)
* @see sorcer.service.Exertion#isCompound()
*/
@Override
public boolean isCompound() {
return false;
}
}
| s13372/SORCER | core/sorcer-platform/src/main/java/sorcer/core/exertion/AltMogram.java | Java | apache-2.0 | 4,815 |
package com.s4game.server.bus.stagecontroll;
import com.s4game.server.bus.stagecontroll.position.AbsRolePosition;
import com.s4game.server.bus.stagecontroll.position.RoleNormalPosition;
public class RoleState {
private String roleId;
private AbsRolePosition curPosition;
private AbsRolePosition readyForPosition;
private RoleNormalPosition roleNormalPosition;
public RoleState(String roleId) {
this.roleId = roleId;
}
public AbsRolePosition getCurPosition() {
return this.curPosition;
}
public void setCurPosition(AbsRolePosition curPosition) {
this.curPosition = curPosition;
}
public AbsRolePosition getReadyToPosition() {
return this.readyForPosition;
}
public void setReadyForPosition(AbsRolePosition readyForPosition) {
this.readyForPosition = readyForPosition;
}
public void setOfflineSavePosition(RoleNormalPosition roleNormalPosition) {
this.roleNormalPosition = roleNormalPosition;
}
public RoleNormalPosition getOfflineSavePosition() {
return this.roleNormalPosition;
}
public String getRoleId() {
return roleId;
}
} | zuesgooogle/HappyMj | mj-game/src/main/java/com/s4game/server/bus/stagecontroll/RoleState.java | Java | apache-2.0 | 1,193 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package org.apache.uima.tools.cfe.config;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EReference;
/**
* <!-- begin-user-doc -->
* The <b>Package</b> for the model.
* It contains accessors for the meta objects to represent
* <ul>
* <li>each class,</li>
* <li>each feature of each class,</li>
* <li>each enum,</li>
* <li>and each data type</li>
* </ul>
* <!-- end-user-doc -->
* @see org.apache.uima.tools.cfe.config.ConfigFactory
* @model kind="package"
* @generated
*/
public interface ConfigPackage extends EPackage
{
/**
* The package name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String eNAME = "config";
/**
* The package namespace URI.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String eNS_URI = "http://www.apache.org/uima/tools/cfe/config";
/**
* The package namespace name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String eNS_PREFIX = "config";
/**
* The singleton instance of the package.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
ConfigPackage eINSTANCE = org.apache.uima.tools.cfe.config.impl.ConfigPackageImpl.init();
/**
* The meta object id for the '{@link org.apache.uima.tools.cfe.config.impl.BitsetFeatureValuesXMLImpl <em>Bitset Feature Values XML</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.apache.uima.tools.cfe.config.impl.BitsetFeatureValuesXMLImpl
* @see org.apache.uima.tools.cfe.config.impl.ConfigPackageImpl#getBitsetFeatureValuesXML()
* @generated
*/
int BITSET_FEATURE_VALUES_XML = 0;
/**
* The feature id for the '<em><b>Bitmask</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int BITSET_FEATURE_VALUES_XML__BITMASK = 0;
/**
* The feature id for the '<em><b>Exact Match</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int BITSET_FEATURE_VALUES_XML__EXACT_MATCH = 1;
/**
* The number of structural features of the '<em>Bitset Feature Values XML</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int BITSET_FEATURE_VALUES_XML_FEATURE_COUNT = 2;
/**
* The meta object id for the '{@link org.apache.uima.tools.cfe.config.impl.CFEDescriptorXMLImpl <em>CFE Descriptor XML</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.apache.uima.tools.cfe.config.impl.CFEDescriptorXMLImpl
* @see org.apache.uima.tools.cfe.config.impl.ConfigPackageImpl#getCFEDescriptorXML()
* @generated
*/
int CFE_DESCRIPTOR_XML = 1;
/**
* The feature id for the '<em><b>Target Annotations</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int CFE_DESCRIPTOR_XML__TARGET_ANNOTATIONS = 0;
/**
* The feature id for the '<em><b>Null Value Image</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int CFE_DESCRIPTOR_XML__NULL_VALUE_IMAGE = 1;
/**
* The number of structural features of the '<em>CFE Descriptor XML</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int CFE_DESCRIPTOR_XML_FEATURE_COUNT = 2;
/**
* The meta object id for the '{@link org.apache.uima.tools.cfe.config.impl.DocumentRootImpl <em>Document Root</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.apache.uima.tools.cfe.config.impl.DocumentRootImpl
* @see org.apache.uima.tools.cfe.config.impl.ConfigPackageImpl#getDocumentRoot()
* @generated
*/
int DOCUMENT_ROOT = 2;
/**
* The feature id for the '<em><b>Mixed</b></em>' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int DOCUMENT_ROOT__MIXED = 0;
/**
* The feature id for the '<em><b>XMLNS Prefix Map</b></em>' map.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int DOCUMENT_ROOT__XMLNS_PREFIX_MAP = 1;
/**
* The feature id for the '<em><b>XSI Schema Location</b></em>' map.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int DOCUMENT_ROOT__XSI_SCHEMA_LOCATION = 2;
/**
* The feature id for the '<em><b>CFE Config</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int DOCUMENT_ROOT__CFE_CONFIG = 3;
/**
* The number of structural features of the '<em>Document Root</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int DOCUMENT_ROOT_FEATURE_COUNT = 4;
/**
* The meta object id for the '{@link org.apache.uima.tools.cfe.config.impl.EnumFeatureValuesXMLImpl <em>Enum Feature Values XML</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.apache.uima.tools.cfe.config.impl.EnumFeatureValuesXMLImpl
* @see org.apache.uima.tools.cfe.config.impl.ConfigPackageImpl#getEnumFeatureValuesXML()
* @generated
*/
int ENUM_FEATURE_VALUES_XML = 3;
/**
* The feature id for the '<em><b>Values</b></em>' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ENUM_FEATURE_VALUES_XML__VALUES = 0;
/**
* The feature id for the '<em><b>Case Sensitive</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ENUM_FEATURE_VALUES_XML__CASE_SENSITIVE = 1;
/**
* The number of structural features of the '<em>Enum Feature Values XML</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ENUM_FEATURE_VALUES_XML_FEATURE_COUNT = 2;
/**
* The meta object id for the '{@link org.apache.uima.tools.cfe.config.impl.PartialObjectMatcherXMLImpl <em>Partial Object Matcher XML</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.apache.uima.tools.cfe.config.impl.PartialObjectMatcherXMLImpl
* @see org.apache.uima.tools.cfe.config.impl.ConfigPackageImpl#getPartialObjectMatcherXML()
* @generated
*/
int PARTIAL_OBJECT_MATCHER_XML = 7;
/**
* The feature id for the '<em><b>Group Feature Matchers</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int PARTIAL_OBJECT_MATCHER_XML__GROUP_FEATURE_MATCHERS = 0;
/**
* The feature id for the '<em><b>Annotation Type Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int PARTIAL_OBJECT_MATCHER_XML__ANNOTATION_TYPE_NAME = 1;
/**
* The feature id for the '<em><b>Full Path</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int PARTIAL_OBJECT_MATCHER_XML__FULL_PATH = 2;
/**
* The number of structural features of the '<em>Partial Object Matcher XML</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int PARTIAL_OBJECT_MATCHER_XML_FEATURE_COUNT = 3;
/**
* The meta object id for the '{@link org.apache.uima.tools.cfe.config.impl.FeatureObjectMatcherXMLImpl <em>Feature Object Matcher XML</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.apache.uima.tools.cfe.config.impl.FeatureObjectMatcherXMLImpl
* @see org.apache.uima.tools.cfe.config.impl.ConfigPackageImpl#getFeatureObjectMatcherXML()
* @generated
*/
int FEATURE_OBJECT_MATCHER_XML = 4;
/**
* The feature id for the '<em><b>Group Feature Matchers</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int FEATURE_OBJECT_MATCHER_XML__GROUP_FEATURE_MATCHERS = PARTIAL_OBJECT_MATCHER_XML__GROUP_FEATURE_MATCHERS;
/**
* The feature id for the '<em><b>Annotation Type Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int FEATURE_OBJECT_MATCHER_XML__ANNOTATION_TYPE_NAME = PARTIAL_OBJECT_MATCHER_XML__ANNOTATION_TYPE_NAME;
/**
* The feature id for the '<em><b>Full Path</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int FEATURE_OBJECT_MATCHER_XML__FULL_PATH = PARTIAL_OBJECT_MATCHER_XML__FULL_PATH;
/**
* The feature id for the '<em><b>Distance</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int FEATURE_OBJECT_MATCHER_XML__DISTANCE = PARTIAL_OBJECT_MATCHER_XML_FEATURE_COUNT + 0;
/**
* The feature id for the '<em><b>Orientation</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int FEATURE_OBJECT_MATCHER_XML__ORIENTATION = PARTIAL_OBJECT_MATCHER_XML_FEATURE_COUNT + 1;
/**
* The feature id for the '<em><b>Window Flags</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int FEATURE_OBJECT_MATCHER_XML__WINDOW_FLAGS = PARTIAL_OBJECT_MATCHER_XML_FEATURE_COUNT + 2;
/**
* The feature id for the '<em><b>Windowsize Enclosed</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int FEATURE_OBJECT_MATCHER_XML__WINDOWSIZE_ENCLOSED = PARTIAL_OBJECT_MATCHER_XML_FEATURE_COUNT + 3;
/**
* The feature id for the '<em><b>Windowsize Inside</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int FEATURE_OBJECT_MATCHER_XML__WINDOWSIZE_INSIDE = PARTIAL_OBJECT_MATCHER_XML_FEATURE_COUNT + 4;
/**
* The feature id for the '<em><b>Windowsize Left</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int FEATURE_OBJECT_MATCHER_XML__WINDOWSIZE_LEFT = PARTIAL_OBJECT_MATCHER_XML_FEATURE_COUNT + 5;
/**
* The feature id for the '<em><b>Windowsize Right</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int FEATURE_OBJECT_MATCHER_XML__WINDOWSIZE_RIGHT = PARTIAL_OBJECT_MATCHER_XML_FEATURE_COUNT + 6;
/**
* The number of structural features of the '<em>Feature Object Matcher XML</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int FEATURE_OBJECT_MATCHER_XML_FEATURE_COUNT = PARTIAL_OBJECT_MATCHER_XML_FEATURE_COUNT + 7;
/**
* The meta object id for the '{@link org.apache.uima.tools.cfe.config.impl.GroupFeatureMatcherXMLImpl <em>Group Feature Matcher XML</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.apache.uima.tools.cfe.config.impl.GroupFeatureMatcherXMLImpl
* @see org.apache.uima.tools.cfe.config.impl.ConfigPackageImpl#getGroupFeatureMatcherXML()
* @generated
*/
int GROUP_FEATURE_MATCHER_XML = 5;
/**
* The feature id for the '<em><b>Feature Matchers</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int GROUP_FEATURE_MATCHER_XML__FEATURE_MATCHERS = 0;
/**
* The feature id for the '<em><b>Exclude</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int GROUP_FEATURE_MATCHER_XML__EXCLUDE = 1;
/**
* The number of structural features of the '<em>Group Feature Matcher XML</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int GROUP_FEATURE_MATCHER_XML_FEATURE_COUNT = 2;
/**
* The meta object id for the '{@link org.apache.uima.tools.cfe.config.impl.ObjectPathFeatureValuesXMLImpl <em>Object Path Feature Values XML</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.apache.uima.tools.cfe.config.impl.ObjectPathFeatureValuesXMLImpl
* @see org.apache.uima.tools.cfe.config.impl.ConfigPackageImpl#getObjectPathFeatureValuesXML()
* @generated
*/
int OBJECT_PATH_FEATURE_VALUES_XML = 6;
/**
* The feature id for the '<em><b>Object Path</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int OBJECT_PATH_FEATURE_VALUES_XML__OBJECT_PATH = 0;
/**
* The number of structural features of the '<em>Object Path Feature Values XML</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int OBJECT_PATH_FEATURE_VALUES_XML_FEATURE_COUNT = 1;
/**
* The meta object id for the '{@link org.apache.uima.tools.cfe.config.impl.PatternFeatureValuesXMLImpl <em>Pattern Feature Values XML</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.apache.uima.tools.cfe.config.impl.PatternFeatureValuesXMLImpl
* @see org.apache.uima.tools.cfe.config.impl.ConfigPackageImpl#getPatternFeatureValuesXML()
* @generated
*/
int PATTERN_FEATURE_VALUES_XML = 8;
/**
* The feature id for the '<em><b>Pattern</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int PATTERN_FEATURE_VALUES_XML__PATTERN = 0;
/**
* The number of structural features of the '<em>Pattern Feature Values XML</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int PATTERN_FEATURE_VALUES_XML_FEATURE_COUNT = 1;
/**
* The meta object id for the '{@link org.apache.uima.tools.cfe.config.impl.RangeFeatureValuesXMLImpl <em>Range Feature Values XML</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.apache.uima.tools.cfe.config.impl.RangeFeatureValuesXMLImpl
* @see org.apache.uima.tools.cfe.config.impl.ConfigPackageImpl#getRangeFeatureValuesXML()
* @generated
*/
int RANGE_FEATURE_VALUES_XML = 9;
/**
* The feature id for the '<em><b>Lower Boundary</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int RANGE_FEATURE_VALUES_XML__LOWER_BOUNDARY = 0;
/**
* The feature id for the '<em><b>Lower Boundary Inclusive</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int RANGE_FEATURE_VALUES_XML__LOWER_BOUNDARY_INCLUSIVE = 1;
/**
* The feature id for the '<em><b>Upper Boundary</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int RANGE_FEATURE_VALUES_XML__UPPER_BOUNDARY = 2;
/**
* The feature id for the '<em><b>Upper Boundary Inclusive</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int RANGE_FEATURE_VALUES_XML__UPPER_BOUNDARY_INCLUSIVE = 3;
/**
* The number of structural features of the '<em>Range Feature Values XML</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int RANGE_FEATURE_VALUES_XML_FEATURE_COUNT = 4;
/**
* The meta object id for the '{@link org.apache.uima.tools.cfe.config.impl.SingleFeatureMatcherXMLImpl <em>Single Feature Matcher XML</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.apache.uima.tools.cfe.config.impl.SingleFeatureMatcherXMLImpl
* @see org.apache.uima.tools.cfe.config.impl.ConfigPackageImpl#getSingleFeatureMatcherXML()
* @generated
*/
int SINGLE_FEATURE_MATCHER_XML = 10;
/**
* The feature id for the '<em><b>Range Feature Values</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SINGLE_FEATURE_MATCHER_XML__RANGE_FEATURE_VALUES = 0;
/**
* The feature id for the '<em><b>Enum Feature Values</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SINGLE_FEATURE_MATCHER_XML__ENUM_FEATURE_VALUES = 1;
/**
* The feature id for the '<em><b>Bitset Feature Values</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SINGLE_FEATURE_MATCHER_XML__BITSET_FEATURE_VALUES = 2;
/**
* The feature id for the '<em><b>Object Path Feature Values</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SINGLE_FEATURE_MATCHER_XML__OBJECT_PATH_FEATURE_VALUES = 3;
/**
* The feature id for the '<em><b>Pattern Feature Values</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SINGLE_FEATURE_MATCHER_XML__PATTERN_FEATURE_VALUES = 4;
/**
* The feature id for the '<em><b>Exclude</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SINGLE_FEATURE_MATCHER_XML__EXCLUDE = 5;
/**
* The feature id for the '<em><b>Feature Path</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SINGLE_FEATURE_MATCHER_XML__FEATURE_PATH = 6;
/**
* The feature id for the '<em><b>Feature Type Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SINGLE_FEATURE_MATCHER_XML__FEATURE_TYPE_NAME = 7;
/**
* The feature id for the '<em><b>Quiet</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SINGLE_FEATURE_MATCHER_XML__QUIET = 8;
/**
* The number of structural features of the '<em>Single Feature Matcher XML</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SINGLE_FEATURE_MATCHER_XML_FEATURE_COUNT = 9;
/**
* The meta object id for the '{@link org.apache.uima.tools.cfe.config.impl.TargetAnnotationXMLImpl <em>Target Annotation XML</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.apache.uima.tools.cfe.config.impl.TargetAnnotationXMLImpl
* @see org.apache.uima.tools.cfe.config.impl.ConfigPackageImpl#getTargetAnnotationXML()
* @generated
*/
int TARGET_ANNOTATION_XML = 11;
/**
* The feature id for the '<em><b>Target Annotation Matcher</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int TARGET_ANNOTATION_XML__TARGET_ANNOTATION_MATCHER = 0;
/**
* The feature id for the '<em><b>Feature Annotation Matchers</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int TARGET_ANNOTATION_XML__FEATURE_ANNOTATION_MATCHERS = 1;
/**
* The feature id for the '<em><b>Class Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int TARGET_ANNOTATION_XML__CLASS_NAME = 2;
/**
* The feature id for the '<em><b>Enclosing Annotation</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int TARGET_ANNOTATION_XML__ENCLOSING_ANNOTATION = 3;
/**
* The number of structural features of the '<em>Target Annotation XML</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int TARGET_ANNOTATION_XML_FEATURE_COUNT = 4;
/**
* Returns the meta object for class '{@link org.apache.uima.tools.cfe.config.BitsetFeatureValuesXML <em>Bitset Feature Values XML</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Bitset Feature Values XML</em>'.
* @see org.apache.uima.tools.cfe.config.BitsetFeatureValuesXML
* @generated
*/
EClass getBitsetFeatureValuesXML();
/**
* Returns the meta object for the attribute '{@link org.apache.uima.tools.cfe.config.BitsetFeatureValuesXML#getBitmask <em>Bitmask</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Bitmask</em>'.
* @see org.apache.uima.tools.cfe.config.BitsetFeatureValuesXML#getBitmask()
* @see #getBitsetFeatureValuesXML()
* @generated
*/
EAttribute getBitsetFeatureValuesXML_Bitmask();
/**
* Returns the meta object for the attribute '{@link org.apache.uima.tools.cfe.config.BitsetFeatureValuesXML#isExactMatch <em>Exact Match</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Exact Match</em>'.
* @see org.apache.uima.tools.cfe.config.BitsetFeatureValuesXML#isExactMatch()
* @see #getBitsetFeatureValuesXML()
* @generated
*/
EAttribute getBitsetFeatureValuesXML_ExactMatch();
/**
* Returns the meta object for class '{@link org.apache.uima.tools.cfe.config.CFEDescriptorXML <em>CFE Descriptor XML</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>CFE Descriptor XML</em>'.
* @see org.apache.uima.tools.cfe.config.CFEDescriptorXML
* @generated
*/
EClass getCFEDescriptorXML();
/**
* Returns the meta object for the containment reference list '{@link org.apache.uima.tools.cfe.config.CFEDescriptorXML#getTargetAnnotations <em>Target Annotations</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference list '<em>Target Annotations</em>'.
* @see org.apache.uima.tools.cfe.config.CFEDescriptorXML#getTargetAnnotations()
* @see #getCFEDescriptorXML()
* @generated
*/
EReference getCFEDescriptorXML_TargetAnnotations();
/**
* Returns the meta object for the attribute '{@link org.apache.uima.tools.cfe.config.CFEDescriptorXML#getNullValueImage <em>Null Value Image</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Null Value Image</em>'.
* @see org.apache.uima.tools.cfe.config.CFEDescriptorXML#getNullValueImage()
* @see #getCFEDescriptorXML()
* @generated
*/
EAttribute getCFEDescriptorXML_NullValueImage();
/**
* Returns the meta object for class '{@link org.apache.uima.tools.cfe.config.DocumentRoot <em>Document Root</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Document Root</em>'.
* @see org.apache.uima.tools.cfe.config.DocumentRoot
* @generated
*/
EClass getDocumentRoot();
/**
* Returns the meta object for the attribute list '{@link org.apache.uima.tools.cfe.config.DocumentRoot#getMixed <em>Mixed</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute list '<em>Mixed</em>'.
* @see org.apache.uima.tools.cfe.config.DocumentRoot#getMixed()
* @see #getDocumentRoot()
* @generated
*/
EAttribute getDocumentRoot_Mixed();
/**
* Returns the meta object for the map '{@link org.apache.uima.tools.cfe.config.DocumentRoot#getXMLNSPrefixMap <em>XMLNS Prefix Map</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the map '<em>XMLNS Prefix Map</em>'.
* @see org.apache.uima.tools.cfe.config.DocumentRoot#getXMLNSPrefixMap()
* @see #getDocumentRoot()
* @generated
*/
EReference getDocumentRoot_XMLNSPrefixMap();
/**
* Returns the meta object for the map '{@link org.apache.uima.tools.cfe.config.DocumentRoot#getXSISchemaLocation <em>XSI Schema Location</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the map '<em>XSI Schema Location</em>'.
* @see org.apache.uima.tools.cfe.config.DocumentRoot#getXSISchemaLocation()
* @see #getDocumentRoot()
* @generated
*/
EReference getDocumentRoot_XSISchemaLocation();
/**
* Returns the meta object for the containment reference '{@link org.apache.uima.tools.cfe.config.DocumentRoot#getCFEConfig <em>CFE Config</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference '<em>CFE Config</em>'.
* @see org.apache.uima.tools.cfe.config.DocumentRoot#getCFEConfig()
* @see #getDocumentRoot()
* @generated
*/
EReference getDocumentRoot_CFEConfig();
/**
* Returns the meta object for class '{@link org.apache.uima.tools.cfe.config.EnumFeatureValuesXML <em>Enum Feature Values XML</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Enum Feature Values XML</em>'.
* @see org.apache.uima.tools.cfe.config.EnumFeatureValuesXML
* @generated
*/
EClass getEnumFeatureValuesXML();
/**
* Returns the meta object for the attribute list '{@link org.apache.uima.tools.cfe.config.EnumFeatureValuesXML#getValues <em>Values</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute list '<em>Values</em>'.
* @see org.apache.uima.tools.cfe.config.EnumFeatureValuesXML#getValues()
* @see #getEnumFeatureValuesXML()
* @generated
*/
EAttribute getEnumFeatureValuesXML_Values();
/**
* Returns the meta object for the attribute '{@link org.apache.uima.tools.cfe.config.EnumFeatureValuesXML#isCaseSensitive <em>Case Sensitive</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Case Sensitive</em>'.
* @see org.apache.uima.tools.cfe.config.EnumFeatureValuesXML#isCaseSensitive()
* @see #getEnumFeatureValuesXML()
* @generated
*/
EAttribute getEnumFeatureValuesXML_CaseSensitive();
/**
* Returns the meta object for class '{@link org.apache.uima.tools.cfe.config.FeatureObjectMatcherXML <em>Feature Object Matcher XML</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Feature Object Matcher XML</em>'.
* @see org.apache.uima.tools.cfe.config.FeatureObjectMatcherXML
* @generated
*/
EClass getFeatureObjectMatcherXML();
/**
* Returns the meta object for the attribute '{@link org.apache.uima.tools.cfe.config.FeatureObjectMatcherXML#isDistance <em>Distance</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Distance</em>'.
* @see org.apache.uima.tools.cfe.config.FeatureObjectMatcherXML#isDistance()
* @see #getFeatureObjectMatcherXML()
* @generated
*/
EAttribute getFeatureObjectMatcherXML_Distance();
/**
* Returns the meta object for the attribute '{@link org.apache.uima.tools.cfe.config.FeatureObjectMatcherXML#isOrientation <em>Orientation</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Orientation</em>'.
* @see org.apache.uima.tools.cfe.config.FeatureObjectMatcherXML#isOrientation()
* @see #getFeatureObjectMatcherXML()
* @generated
*/
EAttribute getFeatureObjectMatcherXML_Orientation();
/**
* Returns the meta object for the attribute '{@link org.apache.uima.tools.cfe.config.FeatureObjectMatcherXML#getWindowFlags <em>Window Flags</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Window Flags</em>'.
* @see org.apache.uima.tools.cfe.config.FeatureObjectMatcherXML#getWindowFlags()
* @see #getFeatureObjectMatcherXML()
* @generated
*/
EAttribute getFeatureObjectMatcherXML_WindowFlags();
/**
* Returns the meta object for the attribute '{@link org.apache.uima.tools.cfe.config.FeatureObjectMatcherXML#getWindowsizeEnclosed <em>Windowsize Enclosed</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Windowsize Enclosed</em>'.
* @see org.apache.uima.tools.cfe.config.FeatureObjectMatcherXML#getWindowsizeEnclosed()
* @see #getFeatureObjectMatcherXML()
* @generated
*/
EAttribute getFeatureObjectMatcherXML_WindowsizeEnclosed();
/**
* Returns the meta object for the attribute '{@link org.apache.uima.tools.cfe.config.FeatureObjectMatcherXML#getWindowsizeInside <em>Windowsize Inside</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Windowsize Inside</em>'.
* @see org.apache.uima.tools.cfe.config.FeatureObjectMatcherXML#getWindowsizeInside()
* @see #getFeatureObjectMatcherXML()
* @generated
*/
EAttribute getFeatureObjectMatcherXML_WindowsizeInside();
/**
* Returns the meta object for the attribute '{@link org.apache.uima.tools.cfe.config.FeatureObjectMatcherXML#getWindowsizeLeft <em>Windowsize Left</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Windowsize Left</em>'.
* @see org.apache.uima.tools.cfe.config.FeatureObjectMatcherXML#getWindowsizeLeft()
* @see #getFeatureObjectMatcherXML()
* @generated
*/
EAttribute getFeatureObjectMatcherXML_WindowsizeLeft();
/**
* Returns the meta object for the attribute '{@link org.apache.uima.tools.cfe.config.FeatureObjectMatcherXML#getWindowsizeRight <em>Windowsize Right</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Windowsize Right</em>'.
* @see org.apache.uima.tools.cfe.config.FeatureObjectMatcherXML#getWindowsizeRight()
* @see #getFeatureObjectMatcherXML()
* @generated
*/
EAttribute getFeatureObjectMatcherXML_WindowsizeRight();
/**
* Returns the meta object for class '{@link org.apache.uima.tools.cfe.config.GroupFeatureMatcherXML <em>Group Feature Matcher XML</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Group Feature Matcher XML</em>'.
* @see org.apache.uima.tools.cfe.config.GroupFeatureMatcherXML
* @generated
*/
EClass getGroupFeatureMatcherXML();
/**
* Returns the meta object for the containment reference list '{@link org.apache.uima.tools.cfe.config.GroupFeatureMatcherXML#getFeatureMatchers <em>Feature Matchers</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference list '<em>Feature Matchers</em>'.
* @see org.apache.uima.tools.cfe.config.GroupFeatureMatcherXML#getFeatureMatchers()
* @see #getGroupFeatureMatcherXML()
* @generated
*/
EReference getGroupFeatureMatcherXML_FeatureMatchers();
/**
* Returns the meta object for the attribute '{@link org.apache.uima.tools.cfe.config.GroupFeatureMatcherXML#isExclude <em>Exclude</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Exclude</em>'.
* @see org.apache.uima.tools.cfe.config.GroupFeatureMatcherXML#isExclude()
* @see #getGroupFeatureMatcherXML()
* @generated
*/
EAttribute getGroupFeatureMatcherXML_Exclude();
/**
* Returns the meta object for class '{@link org.apache.uima.tools.cfe.config.ObjectPathFeatureValuesXML <em>Object Path Feature Values XML</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Object Path Feature Values XML</em>'.
* @see org.apache.uima.tools.cfe.config.ObjectPathFeatureValuesXML
* @generated
*/
EClass getObjectPathFeatureValuesXML();
/**
* Returns the meta object for the attribute '{@link org.apache.uima.tools.cfe.config.ObjectPathFeatureValuesXML#getObjectPath <em>Object Path</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Object Path</em>'.
* @see org.apache.uima.tools.cfe.config.ObjectPathFeatureValuesXML#getObjectPath()
* @see #getObjectPathFeatureValuesXML()
* @generated
*/
EAttribute getObjectPathFeatureValuesXML_ObjectPath();
/**
* Returns the meta object for class '{@link org.apache.uima.tools.cfe.config.PartialObjectMatcherXML <em>Partial Object Matcher XML</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Partial Object Matcher XML</em>'.
* @see org.apache.uima.tools.cfe.config.PartialObjectMatcherXML
* @generated
*/
EClass getPartialObjectMatcherXML();
/**
* Returns the meta object for the containment reference list '{@link org.apache.uima.tools.cfe.config.PartialObjectMatcherXML#getGroupFeatureMatchers <em>Group Feature Matchers</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference list '<em>Group Feature Matchers</em>'.
* @see org.apache.uima.tools.cfe.config.PartialObjectMatcherXML#getGroupFeatureMatchers()
* @see #getPartialObjectMatcherXML()
* @generated
*/
EReference getPartialObjectMatcherXML_GroupFeatureMatchers();
/**
* Returns the meta object for the attribute '{@link org.apache.uima.tools.cfe.config.PartialObjectMatcherXML#getAnnotationTypeName <em>Annotation Type Name</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Annotation Type Name</em>'.
* @see org.apache.uima.tools.cfe.config.PartialObjectMatcherXML#getAnnotationTypeName()
* @see #getPartialObjectMatcherXML()
* @generated
*/
EAttribute getPartialObjectMatcherXML_AnnotationTypeName();
/**
* Returns the meta object for the attribute '{@link org.apache.uima.tools.cfe.config.PartialObjectMatcherXML#getFullPath <em>Full Path</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Full Path</em>'.
* @see org.apache.uima.tools.cfe.config.PartialObjectMatcherXML#getFullPath()
* @see #getPartialObjectMatcherXML()
* @generated
*/
EAttribute getPartialObjectMatcherXML_FullPath();
/**
* Returns the meta object for class '{@link org.apache.uima.tools.cfe.config.PatternFeatureValuesXML <em>Pattern Feature Values XML</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Pattern Feature Values XML</em>'.
* @see org.apache.uima.tools.cfe.config.PatternFeatureValuesXML
* @generated
*/
EClass getPatternFeatureValuesXML();
/**
* Returns the meta object for the attribute '{@link org.apache.uima.tools.cfe.config.PatternFeatureValuesXML#getPattern <em>Pattern</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Pattern</em>'.
* @see org.apache.uima.tools.cfe.config.PatternFeatureValuesXML#getPattern()
* @see #getPatternFeatureValuesXML()
* @generated
*/
EAttribute getPatternFeatureValuesXML_Pattern();
/**
* Returns the meta object for class '{@link org.apache.uima.tools.cfe.config.RangeFeatureValuesXML <em>Range Feature Values XML</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Range Feature Values XML</em>'.
* @see org.apache.uima.tools.cfe.config.RangeFeatureValuesXML
* @generated
*/
EClass getRangeFeatureValuesXML();
/**
* Returns the meta object for the attribute '{@link org.apache.uima.tools.cfe.config.RangeFeatureValuesXML#getLowerBoundary <em>Lower Boundary</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Lower Boundary</em>'.
* @see org.apache.uima.tools.cfe.config.RangeFeatureValuesXML#getLowerBoundary()
* @see #getRangeFeatureValuesXML()
* @generated
*/
EAttribute getRangeFeatureValuesXML_LowerBoundary();
/**
* Returns the meta object for the attribute '{@link org.apache.uima.tools.cfe.config.RangeFeatureValuesXML#isLowerBoundaryInclusive <em>Lower Boundary Inclusive</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Lower Boundary Inclusive</em>'.
* @see org.apache.uima.tools.cfe.config.RangeFeatureValuesXML#isLowerBoundaryInclusive()
* @see #getRangeFeatureValuesXML()
* @generated
*/
EAttribute getRangeFeatureValuesXML_LowerBoundaryInclusive();
/**
* Returns the meta object for the attribute '{@link org.apache.uima.tools.cfe.config.RangeFeatureValuesXML#getUpperBoundary <em>Upper Boundary</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Upper Boundary</em>'.
* @see org.apache.uima.tools.cfe.config.RangeFeatureValuesXML#getUpperBoundary()
* @see #getRangeFeatureValuesXML()
* @generated
*/
EAttribute getRangeFeatureValuesXML_UpperBoundary();
/**
* Returns the meta object for the attribute '{@link org.apache.uima.tools.cfe.config.RangeFeatureValuesXML#isUpperBoundaryInclusive <em>Upper Boundary Inclusive</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Upper Boundary Inclusive</em>'.
* @see org.apache.uima.tools.cfe.config.RangeFeatureValuesXML#isUpperBoundaryInclusive()
* @see #getRangeFeatureValuesXML()
* @generated
*/
EAttribute getRangeFeatureValuesXML_UpperBoundaryInclusive();
/**
* Returns the meta object for class '{@link org.apache.uima.tools.cfe.config.SingleFeatureMatcherXML <em>Single Feature Matcher XML</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Single Feature Matcher XML</em>'.
* @see org.apache.uima.tools.cfe.config.SingleFeatureMatcherXML
* @generated
*/
EClass getSingleFeatureMatcherXML();
/**
* Returns the meta object for the containment reference '{@link org.apache.uima.tools.cfe.config.SingleFeatureMatcherXML#getRangeFeatureValues <em>Range Feature Values</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference '<em>Range Feature Values</em>'.
* @see org.apache.uima.tools.cfe.config.SingleFeatureMatcherXML#getRangeFeatureValues()
* @see #getSingleFeatureMatcherXML()
* @generated
*/
EReference getSingleFeatureMatcherXML_RangeFeatureValues();
/**
* Returns the meta object for the containment reference '{@link org.apache.uima.tools.cfe.config.SingleFeatureMatcherXML#getEnumFeatureValues <em>Enum Feature Values</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference '<em>Enum Feature Values</em>'.
* @see org.apache.uima.tools.cfe.config.SingleFeatureMatcherXML#getEnumFeatureValues()
* @see #getSingleFeatureMatcherXML()
* @generated
*/
EReference getSingleFeatureMatcherXML_EnumFeatureValues();
/**
* Returns the meta object for the containment reference '{@link org.apache.uima.tools.cfe.config.SingleFeatureMatcherXML#getBitsetFeatureValues <em>Bitset Feature Values</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference '<em>Bitset Feature Values</em>'.
* @see org.apache.uima.tools.cfe.config.SingleFeatureMatcherXML#getBitsetFeatureValues()
* @see #getSingleFeatureMatcherXML()
* @generated
*/
EReference getSingleFeatureMatcherXML_BitsetFeatureValues();
/**
* Returns the meta object for the containment reference '{@link org.apache.uima.tools.cfe.config.SingleFeatureMatcherXML#getObjectPathFeatureValues <em>Object Path Feature Values</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference '<em>Object Path Feature Values</em>'.
* @see org.apache.uima.tools.cfe.config.SingleFeatureMatcherXML#getObjectPathFeatureValues()
* @see #getSingleFeatureMatcherXML()
* @generated
*/
EReference getSingleFeatureMatcherXML_ObjectPathFeatureValues();
/**
* Returns the meta object for the containment reference '{@link org.apache.uima.tools.cfe.config.SingleFeatureMatcherXML#getPatternFeatureValues <em>Pattern Feature Values</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference '<em>Pattern Feature Values</em>'.
* @see org.apache.uima.tools.cfe.config.SingleFeatureMatcherXML#getPatternFeatureValues()
* @see #getSingleFeatureMatcherXML()
* @generated
*/
EReference getSingleFeatureMatcherXML_PatternFeatureValues();
/**
* Returns the meta object for the attribute '{@link org.apache.uima.tools.cfe.config.SingleFeatureMatcherXML#isExclude <em>Exclude</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Exclude</em>'.
* @see org.apache.uima.tools.cfe.config.SingleFeatureMatcherXML#isExclude()
* @see #getSingleFeatureMatcherXML()
* @generated
*/
EAttribute getSingleFeatureMatcherXML_Exclude();
/**
* Returns the meta object for the attribute '{@link org.apache.uima.tools.cfe.config.SingleFeatureMatcherXML#getFeaturePath <em>Feature Path</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Feature Path</em>'.
* @see org.apache.uima.tools.cfe.config.SingleFeatureMatcherXML#getFeaturePath()
* @see #getSingleFeatureMatcherXML()
* @generated
*/
EAttribute getSingleFeatureMatcherXML_FeaturePath();
/**
* Returns the meta object for the attribute '{@link org.apache.uima.tools.cfe.config.SingleFeatureMatcherXML#getFeatureTypeName <em>Feature Type Name</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Feature Type Name</em>'.
* @see org.apache.uima.tools.cfe.config.SingleFeatureMatcherXML#getFeatureTypeName()
* @see #getSingleFeatureMatcherXML()
* @generated
*/
EAttribute getSingleFeatureMatcherXML_FeatureTypeName();
/**
* Returns the meta object for the attribute '{@link org.apache.uima.tools.cfe.config.SingleFeatureMatcherXML#isQuiet <em>Quiet</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Quiet</em>'.
* @see org.apache.uima.tools.cfe.config.SingleFeatureMatcherXML#isQuiet()
* @see #getSingleFeatureMatcherXML()
* @generated
*/
EAttribute getSingleFeatureMatcherXML_Quiet();
/**
* Returns the meta object for class '{@link org.apache.uima.tools.cfe.config.TargetAnnotationXML <em>Target Annotation XML</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Target Annotation XML</em>'.
* @see org.apache.uima.tools.cfe.config.TargetAnnotationXML
* @generated
*/
EClass getTargetAnnotationXML();
/**
* Returns the meta object for the containment reference '{@link org.apache.uima.tools.cfe.config.TargetAnnotationXML#getTargetAnnotationMatcher <em>Target Annotation Matcher</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference '<em>Target Annotation Matcher</em>'.
* @see org.apache.uima.tools.cfe.config.TargetAnnotationXML#getTargetAnnotationMatcher()
* @see #getTargetAnnotationXML()
* @generated
*/
EReference getTargetAnnotationXML_TargetAnnotationMatcher();
/**
* Returns the meta object for the containment reference list '{@link org.apache.uima.tools.cfe.config.TargetAnnotationXML#getFeatureAnnotationMatchers <em>Feature Annotation Matchers</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference list '<em>Feature Annotation Matchers</em>'.
* @see org.apache.uima.tools.cfe.config.TargetAnnotationXML#getFeatureAnnotationMatchers()
* @see #getTargetAnnotationXML()
* @generated
*/
EReference getTargetAnnotationXML_FeatureAnnotationMatchers();
/**
* Returns the meta object for the attribute '{@link org.apache.uima.tools.cfe.config.TargetAnnotationXML#getClassName <em>Class Name</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Class Name</em>'.
* @see org.apache.uima.tools.cfe.config.TargetAnnotationXML#getClassName()
* @see #getTargetAnnotationXML()
* @generated
*/
EAttribute getTargetAnnotationXML_ClassName();
/**
* Returns the meta object for the attribute '{@link org.apache.uima.tools.cfe.config.TargetAnnotationXML#getEnclosingAnnotation <em>Enclosing Annotation</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Enclosing Annotation</em>'.
* @see org.apache.uima.tools.cfe.config.TargetAnnotationXML#getEnclosingAnnotation()
* @see #getTargetAnnotationXML()
* @generated
*/
EAttribute getTargetAnnotationXML_EnclosingAnnotation();
/**
* Returns the factory that creates the instances of the model.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the factory that creates the instances of the model.
* @generated
*/
ConfigFactory getConfigFactory();
/**
* <!-- begin-user-doc -->
* Defines literals for the meta objects that represent
* <ul>
* <li>each class,</li>
* <li>each feature of each class,</li>
* <li>each enum,</li>
* <li>and each data type</li>
* </ul>
* <!-- end-user-doc -->
* @generated
*/
interface Literals
{
/**
* The meta object literal for the '{@link org.apache.uima.tools.cfe.config.impl.BitsetFeatureValuesXMLImpl <em>Bitset Feature Values XML</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.apache.uima.tools.cfe.config.impl.BitsetFeatureValuesXMLImpl
* @see org.apache.uima.tools.cfe.config.impl.ConfigPackageImpl#getBitsetFeatureValuesXML()
* @generated
*/
EClass BITSET_FEATURE_VALUES_XML = eINSTANCE.getBitsetFeatureValuesXML();
/**
* The meta object literal for the '<em><b>Bitmask</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute BITSET_FEATURE_VALUES_XML__BITMASK = eINSTANCE.getBitsetFeatureValuesXML_Bitmask();
/**
* The meta object literal for the '<em><b>Exact Match</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute BITSET_FEATURE_VALUES_XML__EXACT_MATCH = eINSTANCE.getBitsetFeatureValuesXML_ExactMatch();
/**
* The meta object literal for the '{@link org.apache.uima.tools.cfe.config.impl.CFEDescriptorXMLImpl <em>CFE Descriptor XML</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.apache.uima.tools.cfe.config.impl.CFEDescriptorXMLImpl
* @see org.apache.uima.tools.cfe.config.impl.ConfigPackageImpl#getCFEDescriptorXML()
* @generated
*/
EClass CFE_DESCRIPTOR_XML = eINSTANCE.getCFEDescriptorXML();
/**
* The meta object literal for the '<em><b>Target Annotations</b></em>' containment reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference CFE_DESCRIPTOR_XML__TARGET_ANNOTATIONS = eINSTANCE.getCFEDescriptorXML_TargetAnnotations();
/**
* The meta object literal for the '<em><b>Null Value Image</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute CFE_DESCRIPTOR_XML__NULL_VALUE_IMAGE = eINSTANCE.getCFEDescriptorXML_NullValueImage();
/**
* The meta object literal for the '{@link org.apache.uima.tools.cfe.config.impl.DocumentRootImpl <em>Document Root</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.apache.uima.tools.cfe.config.impl.DocumentRootImpl
* @see org.apache.uima.tools.cfe.config.impl.ConfigPackageImpl#getDocumentRoot()
* @generated
*/
EClass DOCUMENT_ROOT = eINSTANCE.getDocumentRoot();
/**
* The meta object literal for the '<em><b>Mixed</b></em>' attribute list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute DOCUMENT_ROOT__MIXED = eINSTANCE.getDocumentRoot_Mixed();
/**
* The meta object literal for the '<em><b>XMLNS Prefix Map</b></em>' map feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference DOCUMENT_ROOT__XMLNS_PREFIX_MAP = eINSTANCE.getDocumentRoot_XMLNSPrefixMap();
/**
* The meta object literal for the '<em><b>XSI Schema Location</b></em>' map feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference DOCUMENT_ROOT__XSI_SCHEMA_LOCATION = eINSTANCE.getDocumentRoot_XSISchemaLocation();
/**
* The meta object literal for the '<em><b>CFE Config</b></em>' containment reference feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference DOCUMENT_ROOT__CFE_CONFIG = eINSTANCE.getDocumentRoot_CFEConfig();
/**
* The meta object literal for the '{@link org.apache.uima.tools.cfe.config.impl.EnumFeatureValuesXMLImpl <em>Enum Feature Values XML</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.apache.uima.tools.cfe.config.impl.EnumFeatureValuesXMLImpl
* @see org.apache.uima.tools.cfe.config.impl.ConfigPackageImpl#getEnumFeatureValuesXML()
* @generated
*/
EClass ENUM_FEATURE_VALUES_XML = eINSTANCE.getEnumFeatureValuesXML();
/**
* The meta object literal for the '<em><b>Values</b></em>' attribute list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ENUM_FEATURE_VALUES_XML__VALUES = eINSTANCE.getEnumFeatureValuesXML_Values();
/**
* The meta object literal for the '<em><b>Case Sensitive</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ENUM_FEATURE_VALUES_XML__CASE_SENSITIVE = eINSTANCE.getEnumFeatureValuesXML_CaseSensitive();
/**
* The meta object literal for the '{@link org.apache.uima.tools.cfe.config.impl.FeatureObjectMatcherXMLImpl <em>Feature Object Matcher XML</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.apache.uima.tools.cfe.config.impl.FeatureObjectMatcherXMLImpl
* @see org.apache.uima.tools.cfe.config.impl.ConfigPackageImpl#getFeatureObjectMatcherXML()
* @generated
*/
EClass FEATURE_OBJECT_MATCHER_XML = eINSTANCE.getFeatureObjectMatcherXML();
/**
* The meta object literal for the '<em><b>Distance</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute FEATURE_OBJECT_MATCHER_XML__DISTANCE = eINSTANCE.getFeatureObjectMatcherXML_Distance();
/**
* The meta object literal for the '<em><b>Orientation</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute FEATURE_OBJECT_MATCHER_XML__ORIENTATION = eINSTANCE.getFeatureObjectMatcherXML_Orientation();
/**
* The meta object literal for the '<em><b>Window Flags</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute FEATURE_OBJECT_MATCHER_XML__WINDOW_FLAGS = eINSTANCE.getFeatureObjectMatcherXML_WindowFlags();
/**
* The meta object literal for the '<em><b>Windowsize Enclosed</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute FEATURE_OBJECT_MATCHER_XML__WINDOWSIZE_ENCLOSED = eINSTANCE.getFeatureObjectMatcherXML_WindowsizeEnclosed();
/**
* The meta object literal for the '<em><b>Windowsize Inside</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute FEATURE_OBJECT_MATCHER_XML__WINDOWSIZE_INSIDE = eINSTANCE.getFeatureObjectMatcherXML_WindowsizeInside();
/**
* The meta object literal for the '<em><b>Windowsize Left</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute FEATURE_OBJECT_MATCHER_XML__WINDOWSIZE_LEFT = eINSTANCE.getFeatureObjectMatcherXML_WindowsizeLeft();
/**
* The meta object literal for the '<em><b>Windowsize Right</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute FEATURE_OBJECT_MATCHER_XML__WINDOWSIZE_RIGHT = eINSTANCE.getFeatureObjectMatcherXML_WindowsizeRight();
/**
* The meta object literal for the '{@link org.apache.uima.tools.cfe.config.impl.GroupFeatureMatcherXMLImpl <em>Group Feature Matcher XML</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.apache.uima.tools.cfe.config.impl.GroupFeatureMatcherXMLImpl
* @see org.apache.uima.tools.cfe.config.impl.ConfigPackageImpl#getGroupFeatureMatcherXML()
* @generated
*/
EClass GROUP_FEATURE_MATCHER_XML = eINSTANCE.getGroupFeatureMatcherXML();
/**
* The meta object literal for the '<em><b>Feature Matchers</b></em>' containment reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference GROUP_FEATURE_MATCHER_XML__FEATURE_MATCHERS = eINSTANCE.getGroupFeatureMatcherXML_FeatureMatchers();
/**
* The meta object literal for the '<em><b>Exclude</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute GROUP_FEATURE_MATCHER_XML__EXCLUDE = eINSTANCE.getGroupFeatureMatcherXML_Exclude();
/**
* The meta object literal for the '{@link org.apache.uima.tools.cfe.config.impl.ObjectPathFeatureValuesXMLImpl <em>Object Path Feature Values XML</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.apache.uima.tools.cfe.config.impl.ObjectPathFeatureValuesXMLImpl
* @see org.apache.uima.tools.cfe.config.impl.ConfigPackageImpl#getObjectPathFeatureValuesXML()
* @generated
*/
EClass OBJECT_PATH_FEATURE_VALUES_XML = eINSTANCE.getObjectPathFeatureValuesXML();
/**
* The meta object literal for the '<em><b>Object Path</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute OBJECT_PATH_FEATURE_VALUES_XML__OBJECT_PATH = eINSTANCE.getObjectPathFeatureValuesXML_ObjectPath();
/**
* The meta object literal for the '{@link org.apache.uima.tools.cfe.config.impl.PartialObjectMatcherXMLImpl <em>Partial Object Matcher XML</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.apache.uima.tools.cfe.config.impl.PartialObjectMatcherXMLImpl
* @see org.apache.uima.tools.cfe.config.impl.ConfigPackageImpl#getPartialObjectMatcherXML()
* @generated
*/
EClass PARTIAL_OBJECT_MATCHER_XML = eINSTANCE.getPartialObjectMatcherXML();
/**
* The meta object literal for the '<em><b>Group Feature Matchers</b></em>' containment reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference PARTIAL_OBJECT_MATCHER_XML__GROUP_FEATURE_MATCHERS = eINSTANCE.getPartialObjectMatcherXML_GroupFeatureMatchers();
/**
* The meta object literal for the '<em><b>Annotation Type Name</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute PARTIAL_OBJECT_MATCHER_XML__ANNOTATION_TYPE_NAME = eINSTANCE.getPartialObjectMatcherXML_AnnotationTypeName();
/**
* The meta object literal for the '<em><b>Full Path</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute PARTIAL_OBJECT_MATCHER_XML__FULL_PATH = eINSTANCE.getPartialObjectMatcherXML_FullPath();
/**
* The meta object literal for the '{@link org.apache.uima.tools.cfe.config.impl.PatternFeatureValuesXMLImpl <em>Pattern Feature Values XML</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.apache.uima.tools.cfe.config.impl.PatternFeatureValuesXMLImpl
* @see org.apache.uima.tools.cfe.config.impl.ConfigPackageImpl#getPatternFeatureValuesXML()
* @generated
*/
EClass PATTERN_FEATURE_VALUES_XML = eINSTANCE.getPatternFeatureValuesXML();
/**
* The meta object literal for the '<em><b>Pattern</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute PATTERN_FEATURE_VALUES_XML__PATTERN = eINSTANCE.getPatternFeatureValuesXML_Pattern();
/**
* The meta object literal for the '{@link org.apache.uima.tools.cfe.config.impl.RangeFeatureValuesXMLImpl <em>Range Feature Values XML</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.apache.uima.tools.cfe.config.impl.RangeFeatureValuesXMLImpl
* @see org.apache.uima.tools.cfe.config.impl.ConfigPackageImpl#getRangeFeatureValuesXML()
* @generated
*/
EClass RANGE_FEATURE_VALUES_XML = eINSTANCE.getRangeFeatureValuesXML();
/**
* The meta object literal for the '<em><b>Lower Boundary</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute RANGE_FEATURE_VALUES_XML__LOWER_BOUNDARY = eINSTANCE.getRangeFeatureValuesXML_LowerBoundary();
/**
* The meta object literal for the '<em><b>Lower Boundary Inclusive</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute RANGE_FEATURE_VALUES_XML__LOWER_BOUNDARY_INCLUSIVE = eINSTANCE.getRangeFeatureValuesXML_LowerBoundaryInclusive();
/**
* The meta object literal for the '<em><b>Upper Boundary</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute RANGE_FEATURE_VALUES_XML__UPPER_BOUNDARY = eINSTANCE.getRangeFeatureValuesXML_UpperBoundary();
/**
* The meta object literal for the '<em><b>Upper Boundary Inclusive</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute RANGE_FEATURE_VALUES_XML__UPPER_BOUNDARY_INCLUSIVE = eINSTANCE.getRangeFeatureValuesXML_UpperBoundaryInclusive();
/**
* The meta object literal for the '{@link org.apache.uima.tools.cfe.config.impl.SingleFeatureMatcherXMLImpl <em>Single Feature Matcher XML</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.apache.uima.tools.cfe.config.impl.SingleFeatureMatcherXMLImpl
* @see org.apache.uima.tools.cfe.config.impl.ConfigPackageImpl#getSingleFeatureMatcherXML()
* @generated
*/
EClass SINGLE_FEATURE_MATCHER_XML = eINSTANCE.getSingleFeatureMatcherXML();
/**
* The meta object literal for the '<em><b>Range Feature Values</b></em>' containment reference feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference SINGLE_FEATURE_MATCHER_XML__RANGE_FEATURE_VALUES = eINSTANCE.getSingleFeatureMatcherXML_RangeFeatureValues();
/**
* The meta object literal for the '<em><b>Enum Feature Values</b></em>' containment reference feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference SINGLE_FEATURE_MATCHER_XML__ENUM_FEATURE_VALUES = eINSTANCE.getSingleFeatureMatcherXML_EnumFeatureValues();
/**
* The meta object literal for the '<em><b>Bitset Feature Values</b></em>' containment reference feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference SINGLE_FEATURE_MATCHER_XML__BITSET_FEATURE_VALUES = eINSTANCE.getSingleFeatureMatcherXML_BitsetFeatureValues();
/**
* The meta object literal for the '<em><b>Object Path Feature Values</b></em>' containment reference feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference SINGLE_FEATURE_MATCHER_XML__OBJECT_PATH_FEATURE_VALUES = eINSTANCE.getSingleFeatureMatcherXML_ObjectPathFeatureValues();
/**
* The meta object literal for the '<em><b>Pattern Feature Values</b></em>' containment reference feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference SINGLE_FEATURE_MATCHER_XML__PATTERN_FEATURE_VALUES = eINSTANCE.getSingleFeatureMatcherXML_PatternFeatureValues();
/**
* The meta object literal for the '<em><b>Exclude</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute SINGLE_FEATURE_MATCHER_XML__EXCLUDE = eINSTANCE.getSingleFeatureMatcherXML_Exclude();
/**
* The meta object literal for the '<em><b>Feature Path</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute SINGLE_FEATURE_MATCHER_XML__FEATURE_PATH = eINSTANCE.getSingleFeatureMatcherXML_FeaturePath();
/**
* The meta object literal for the '<em><b>Feature Type Name</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute SINGLE_FEATURE_MATCHER_XML__FEATURE_TYPE_NAME = eINSTANCE.getSingleFeatureMatcherXML_FeatureTypeName();
/**
* The meta object literal for the '<em><b>Quiet</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute SINGLE_FEATURE_MATCHER_XML__QUIET = eINSTANCE.getSingleFeatureMatcherXML_Quiet();
/**
* The meta object literal for the '{@link org.apache.uima.tools.cfe.config.impl.TargetAnnotationXMLImpl <em>Target Annotation XML</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.apache.uima.tools.cfe.config.impl.TargetAnnotationXMLImpl
* @see org.apache.uima.tools.cfe.config.impl.ConfigPackageImpl#getTargetAnnotationXML()
* @generated
*/
EClass TARGET_ANNOTATION_XML = eINSTANCE.getTargetAnnotationXML();
/**
* The meta object literal for the '<em><b>Target Annotation Matcher</b></em>' containment reference feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference TARGET_ANNOTATION_XML__TARGET_ANNOTATION_MATCHER = eINSTANCE.getTargetAnnotationXML_TargetAnnotationMatcher();
/**
* The meta object literal for the '<em><b>Feature Annotation Matchers</b></em>' containment reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference TARGET_ANNOTATION_XML__FEATURE_ANNOTATION_MATCHERS = eINSTANCE.getTargetAnnotationXML_FeatureAnnotationMatchers();
/**
* The meta object literal for the '<em><b>Class Name</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute TARGET_ANNOTATION_XML__CLASS_NAME = eINSTANCE.getTargetAnnotationXML_ClassName();
/**
* The meta object literal for the '<em><b>Enclosing Annotation</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute TARGET_ANNOTATION_XML__ENCLOSING_ANNOTATION = eINSTANCE.getTargetAnnotationXML_EnclosingAnnotation();
}
} //ConfigPackage
| apache/uima-addons | ConfigurableFeatureExtractor/src/main/java/org/apache/uima/tools/cfe/config/ConfigPackage.java | Java | apache-2.0 | 67,486 |
# Copyright 2014 The Oppia Authors. All Rights Reserved.
#
# 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.
"""Installation script for Oppia third-party libraries."""
import contextlib
import json
import os
import shutil
import StringIO
import sys
import tarfile
import urllib
import urllib2
import zipfile
import common
TOOLS_DIR = os.path.join('..', 'oppia_tools')
THIRD_PARTY_DIR = os.path.join('.', 'third_party')
THIRD_PARTY_STATIC_DIR = os.path.join(THIRD_PARTY_DIR, 'static')
MANIFEST_FILE_PATH = os.path.join(os.getcwd(), 'manifest.json')
# Place to download zip files for temporary storage.
TMP_UNZIP_PATH = os.path.join('.', 'tmp_unzip.zip')
# Check that the current directory is correct.
common.require_cwd_to_be_oppia(allow_deploy_dir=True)
TARGET_DOWNLOAD_DIRS = {
'frontend': THIRD_PARTY_STATIC_DIR,
'backend': THIRD_PARTY_DIR,
'oppiaTools': TOOLS_DIR
}
_DOWNLOAD_FORMAT_ZIP = 'zip'
_DOWNLOAD_FORMAT_TAR = 'tar'
_DOWNLOAD_FORMAT_FILES = 'files'
DOWNLOAD_FORMATS_TO_MANIFEST_KEYS = {
'zip': {
'mandatory_keys': ['version', 'url', 'downloadFormat'],
'optional_key_pairs': [
['rootDir', 'rootDirPrefix'], ['targetDir', 'targetDirPrefix']]
},
'files': {
'mandatory_keys': [
'version', 'url', 'files',
'targetDirPrefix', 'downloadFormat'],
'optional_key_pairs': []
},
'tar': {
'mandatory_keys': [
'version', 'url', 'tarRootDirPrefix',
'targetDirPrefix', 'downloadFormat'],
'optional_key_pairs': []
}
}
def download_files(source_url_root, target_dir, source_filenames):
"""Downloads a group of files and saves them to a given directory.
Each file is downloaded only if it does not already exist.
Args:
source_url_root: the URL to prepend to all the filenames.
target_dir: the directory to save the files to.
source_filenames: a list of filenames. Each filename is appended to the
end of the source_url_root in order to give the URL from which to
download the file. The downloaded file is then placed in target_dir,
and retains the same filename.
"""
assert isinstance(source_filenames, list)
common.ensure_directory_exists(target_dir)
for filename in source_filenames:
if not os.path.exists(os.path.join(target_dir, filename)):
print 'Downloading file %s to %s' % (filename, target_dir)
urllib.urlretrieve(
'%s/%s' % (source_url_root, filename),
os.path.join(target_dir, filename))
def download_and_unzip_files(
source_url, target_parent_dir, zip_root_name, target_root_name):
"""Downloads a zip file, unzips it, and saves the result in a given dir.
The download occurs only if the target directory that the zip file unzips
to does not exist.
NB: This function assumes that the root level of the zip file has exactly
one folder.
Args:
source_url: the URL from which to download the zip file.
target_parent_dir: the directory to save the contents of the zip file to.
zip_root_name: the name of the top-level folder in the zip directory.
target_root_name: the name that the top-level folder should be renamed to
in the local directory.
"""
if not os.path.exists(os.path.join(target_parent_dir, target_root_name)):
print 'Downloading and unzipping file %s to %s' % (
zip_root_name, target_parent_dir)
common.ensure_directory_exists(target_parent_dir)
urllib.urlretrieve(source_url, TMP_UNZIP_PATH)
try:
with zipfile.ZipFile(TMP_UNZIP_PATH, 'r') as zfile:
zfile.extractall(target_parent_dir)
os.remove(TMP_UNZIP_PATH)
except Exception:
if os.path.exists(TMP_UNZIP_PATH):
os.remove(TMP_UNZIP_PATH)
# Some downloads (like jqueryui-themes) may require a user-agent.
req = urllib2.Request(source_url)
req.add_header('User-agent', 'python')
# This is needed to get a seekable filestream that can be used
# by zipfile.ZipFile.
file_stream = StringIO.StringIO(urllib2.urlopen(req).read())
with zipfile.ZipFile(file_stream, 'r') as zfile:
zfile.extractall(target_parent_dir)
# Rename the target directory.
os.rename(
os.path.join(target_parent_dir, zip_root_name),
os.path.join(target_parent_dir, target_root_name))
def download_and_untar_files(
source_url, target_parent_dir, tar_root_name, target_root_name):
"""Downloads a tar file, untars it, and saves the result in a given dir.
The download occurs only if the target directory that the tar file untars
to does not exist.
NB: This function assumes that the root level of the tar file has exactly
one folder.
Args:
source_url: the URL from which to download the tar file.
target_parent_dir: the directory to save the contents of the tar file to.
tar_root_name: the name of the top-level folder in the tar directory.
target_root_name: the name that the top-level folder should be renamed to
in the local directory.
"""
if not os.path.exists(os.path.join(target_parent_dir, target_root_name)):
print 'Downloading and untarring file %s to %s' % (
tar_root_name, target_parent_dir)
common.ensure_directory_exists(target_parent_dir)
urllib.urlretrieve(source_url, TMP_UNZIP_PATH)
with contextlib.closing(tarfile.open(TMP_UNZIP_PATH, 'r:gz')) as tfile:
tfile.extractall(target_parent_dir)
os.remove(TMP_UNZIP_PATH)
# Rename the target directory.
os.rename(
os.path.join(target_parent_dir, tar_root_name),
os.path.join(target_parent_dir, target_root_name))
def get_file_contents(filepath, mode='r'):
"""Gets the contents of a file, given a relative filepath from oppia/."""
with open(filepath, mode) as f:
return f.read().decode('utf-8')
def return_json(filepath):
"""Return json object when provided url
Args:
filepath: the path to the json file.
Return:
a parsed json objects
"""
response = get_file_contents(filepath)
return json.loads(response)
def test_manifest_syntax(dependency_type, dependency_dict):
"""This checks syntax of the manifest.json dependencies.
Display warning message when there is an error and terminate the program.
Args:
dependency_type: dependency download format.
dependency_dict: manifest.json dependency dict
"""
keys = dependency_dict.keys()
mandatory_keys = DOWNLOAD_FORMATS_TO_MANIFEST_KEYS[
dependency_type]['mandatory_keys']
# Optional keys requires exactly one member of the pair
# to be available as a key in the dependency_dict
optional_key_pairs = DOWNLOAD_FORMATS_TO_MANIFEST_KEYS[
dependency_type]['optional_key_pairs']
for key in mandatory_keys:
if key not in keys:
print '------------------------------------------'
print 'There is syntax error in this dependency'
print dependency_dict
print 'This key is missing or misspelled: "%s".' % key
print 'Exiting'
sys.exit(1)
if optional_key_pairs:
for optional_keys in optional_key_pairs:
optional_keys_in_dict = [
key for key in optional_keys if key in keys]
if len(optional_keys_in_dict) != 1:
print '------------------------------------------'
print 'There is syntax error in this dependency'
print dependency_dict
print (
'Only one of these keys pair must be used: "%s".'
% str(optional_keys))
print 'Exiting'
sys.exit(1)
# Checks the validity of the URL corresponding to the file format.
dependency_url = dependency_dict['url']
if '#' in dependency_url:
dependency_url = dependency_url.rpartition('#')[0]
is_zip_file_format = dependency_type == _DOWNLOAD_FORMAT_ZIP
is_tar_file_format = dependency_type == _DOWNLOAD_FORMAT_TAR
if (dependency_url.endswith('.zip') and not is_zip_file_format or
is_zip_file_format and not dependency_url.endswith('.zip') or
dependency_url.endswith('.tar.gz') and not is_tar_file_format or
is_tar_file_format and not dependency_url.endswith('.tar.gz')):
print '------------------------------------------'
print 'There is syntax error in this dependency'
print dependency_dict
print 'This url %s is invalid for %s file format.' % (
dependency_url, dependency_type)
print 'Exiting.'
sys.exit(1)
def validate_manifest(filepath):
"""This validates syntax of the manifest.json
Args:
filepath: the path to the json file.
"""
manifest_data = return_json(filepath)
dependencies = manifest_data['dependencies']
for _, dependency in dependencies.items():
for _, dependency_contents in dependency.items():
download_format = dependency_contents['downloadFormat']
test_manifest_syntax(download_format, dependency_contents)
def download_manifest_files(filepath):
"""This download all files to the required folders
Args:
filepath: the path to the json file.
"""
validate_manifest(filepath)
manifest_data = return_json(filepath)
dependencies = manifest_data['dependencies']
for data, dependency in dependencies.items():
for _, dependency_contents in dependency.items():
dependency_rev = dependency_contents['version']
dependency_url = dependency_contents['url']
download_format = dependency_contents['downloadFormat']
if download_format == _DOWNLOAD_FORMAT_FILES:
dependency_files = dependency_contents['files']
target_dirname = (
dependency_contents['targetDirPrefix'] + dependency_rev)
dependency_dst = os.path.join(
TARGET_DOWNLOAD_DIRS[data], target_dirname)
download_files(dependency_url, dependency_dst, dependency_files)
elif download_format == _DOWNLOAD_FORMAT_ZIP:
if 'rootDir' in dependency_contents:
dependency_zip_root_name = dependency_contents['rootDir']
else:
dependency_zip_root_name = (
dependency_contents['rootDirPrefix'] + dependency_rev)
if 'targetDir' in dependency_contents:
dependency_target_root_name = (
dependency_contents['targetDir'])
else:
dependency_target_root_name = (
dependency_contents['targetDirPrefix'] + dependency_rev)
download_and_unzip_files(
dependency_url, TARGET_DOWNLOAD_DIRS[data],
dependency_zip_root_name, dependency_target_root_name)
elif download_format == _DOWNLOAD_FORMAT_TAR:
dependency_tar_root_name = (
dependency_contents['tarRootDirPrefix'] + dependency_rev)
dependency_target_root_name = (
dependency_contents['targetDirPrefix'] + dependency_rev)
download_and_untar_files(
dependency_url, TARGET_DOWNLOAD_DIRS[data],
dependency_tar_root_name, dependency_target_root_name)
MATHJAX_REV = '2.6.0'
MATHJAX_ROOT_NAME = 'MathJax-%s' % MATHJAX_REV
MATHJAX_TARGET_ROOT_NAME = MATHJAX_ROOT_NAME
MATHJAX_DIR_PREFIX = os.path.join(
THIRD_PARTY_STATIC_DIR, MATHJAX_TARGET_ROOT_NAME)
MATHJAX_SUBDIRS_TO_REMOVE = [
'unpacked', os.path.join('fonts', 'HTML-CSS', 'TeX', 'png')]
def _install_third_party_libs():
download_manifest_files(MANIFEST_FILE_PATH)
# MathJax is too big. Remove many unneeded files by following these
# instructions:
# https://github.com/mathjax/MathJax/wiki/Shrinking-MathJax-for-%22local%22-installation pylint: disable=line-too-long
for subdir in MATHJAX_SUBDIRS_TO_REMOVE:
full_dir = os.path.join(MATHJAX_DIR_PREFIX, subdir)
if os.path.isdir(full_dir):
print 'Removing unnecessary MathJax directory \'%s\'' % subdir
shutil.rmtree(full_dir)
if __name__ == '__main__':
_install_third_party_libs()
| kennho/oppia | scripts/install_third_party.py | Python | apache-2.0 | 13,118 |
package spork.internal;
import java.util.ArrayList;
import java.util.List;
import spork.extension.FieldBinder;
import spork.extension.MethodBinder;
import spork.extension.TypeBinder;
/**
* The Catalog holds a reference to all known field/method/type binder instances.
*/
public final class Catalog {
private final List<FieldBinder> fieldBinders = new ArrayList<>();
private final List<MethodBinder> methodBinders = new ArrayList<>();
private final List<TypeBinder> typeBinders = new ArrayList<>();
public void add(FieldBinder<?> fieldBinder) {
fieldBinders.add(fieldBinder);
}
public void add(MethodBinder<?> methodBinder) {
methodBinders.add(methodBinder);
}
public void add(TypeBinder<?> typeBinder) {
typeBinders.add(typeBinder);
}
/**
* @return all registered FieldBinder instances
*/
List<FieldBinder> getFieldBinders() {
return fieldBinders;
}
/**
* @return all registered MethodBinder instances
*/
List<MethodBinder> getMethodBinders() {
return methodBinders;
}
/**
* @return all registered TypeBinder instances
*/
List<TypeBinder> getTypeBinders() {
return typeBinders;
}
} | SporkLibrary/Spork-Android | spork/src/main/java/spork/internal/Catalog.java | Java | apache-2.0 | 1,135 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You 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.
-->
<!-- start the processing -->
<html>
<head>
<link rel="stylesheet" type="text/css" href="./../docs/css/style.css"/>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="author" value="Apache JMeter Project">
<meta name="email" value="dev.AT.jmeter.DOT.apache.DOT.org">
<title>Apache JMeter - Mailing Lists</title>
<style>
.code { font-weight: bold; }
</style>
</head>
<body bgcolor="#ffffff" text="#000000" link="#525D76">
<table border="0" cellspacing="0">
<tr>
<td align="left">
<a href="http://www.apache.org"><img style="margin: 0px 30px 0px 0px" title="Apache Software Foundation" width="261" height="106" src="./../docs/images/asf-logo.png" border="0"/></a>
</td>
<td align="right">
<a href="http://jmeter.apache.org/"><img width="259" height="88" src="./../docs/images/jmeter.png" alt="Apache JMeter" title="Apache JMeter" border="0"/></a>
</td>
</tr>
</table>
<table border="0" cellspacing="4">
<tr><td>
<hr noshade size="1"/>
</td></tr>
<tr>
<td align="left" valign="top">
<br>
<table border="0" cellspacing="0" cellpadding="2" width="100%">
<tr><td bgcolor="#525D76">
<font color="#ffffff" face="arial,helvetica,sanserif">
<strong>Mailing Lists - Guidelines</strong></font>
</td></tr>
<tr><td>
<blockquote>
<p>
<strong>
Before subscribing to any of the mailing lists, please make sure that you have
read and understand the
<a href="mail.html">
guidelines
</a>
</strong>
.
</p>
<p>
Please note that usage of these mailing lists is subject to the
<a href="http://www.apache.org/foundation/public-archives.html">
Public Forum Archive Policy
</a>
.
</p>
<p>
For details of how to subscribe/unsubscribe please read
<a href="http://www.apache.org/foundation/mailinglists.html#subscribing">
Subscribing and Unsubscribing
</a>
</p>
</blockquote>
</p>
</td></tr>
<tr><td><br></td></tr>
</table>
<table border="0" cellspacing="0" cellpadding="2" width="100%">
<tr><td bgcolor="#525D76">
<font color="#ffffff" face="arial,helvetica,sanserif">
<strong>JMeter lists and archives at the ASF</strong></font>
</td></tr>
<tr><td>
<blockquote>
<table border="0" cellspacing="0" cellpadding="2" width="100%">
<tr><td bgcolor="#828DA6">
<font color="#ffffff" face="arial,helvetica,sanserif">
<a name="JMeterUser"><strong>Apache JMeter User</strong></a>
</font>
</td></tr>
<tr><td>
<blockquote>
<p>
This is the list where users of Apache JMeter meet and discuss issues.
</p>
<p>
Developers are also expected to be lurking on this list to offer support to users of JMeter.
</p>
<p>
This list starts part-way through Nov 2011, when JMeter became an independent Apache project.
For earlier postings, please see the Jakarta JMeter User list, below.
</p>
<ul>
<li>
Subscribe at
<a href="mailto:user-subscribe@jmeter.apache.org">
user-subscribe@jmeter.apache.org
</a>
</li>
<li>
Send your message to:
<a href="mailto:user@jmeter.apache.org">
user@jmeter.apache.org
</a>
(after the subscription process)
</li>
<li>
Unsubscribe at
<a href="mailto:user-unsubscribe@jmeter.apache.org">
user-unsubscribe@jmeter.apache.org
</a>
</li>
<li>
All old mails at
<a href="http://mail-archives.apache.org/mod_mbox/jmeter-user/">
jmeter-user Archive
</a>
</li>
</ul>
</blockquote>
</td></tr>
<tr><td><br></td></tr>
</table>
<table border="0" cellspacing="0" cellpadding="2" width="100%">
<tr><td bgcolor="#828DA6">
<font color="#ffffff" face="arial,helvetica,sanserif">
<a name="JakartaJMeterUser"><strong>Jakarta JMeter User</strong></a>
</font>
</td></tr>
<tr><td>
<blockquote>
<ul>
<li>
All old mails at
<a href="http://mail-archives.apache.org/mod_mbox/jakarta-jmeter-user/">
jakarta-jmeter-user Archive
</a>
</li>
</ul>
</blockquote>
</td></tr>
<tr><td><br></td></tr>
</table>
<table border="0" cellspacing="0" cellpadding="2" width="100%">
<tr><td bgcolor="#828DA6">
<font color="#ffffff" face="arial,helvetica,sanserif">
<a name="JMeterDev"><strong>Apache JMeter Developer</strong></a>
</font>
</td></tr>
<tr><td>
<blockquote>
<p>
This is the list where participating developers meet and discuss issues, code changes/additions etc.
</p>
<p>
<table border="1" bgcolor="#bbbb00" width="50%" cellspacing="0" cellpadding="2">
<tr><td>Please do not send usage questions to this list, see user list above.
</td></tr>
</table>
</p>
<p>
This list also collects Wiki update messages.
</p>
<p>
This list starts part-way through Nov 2011, when JMeter became an independent Apache project.
For earlier postings, please see below.
</p>
<ul>
<li>
Subscribe at
<a href="mailto:dev-subscribe@jmeter.apache.org">
dev-subscribe@jmeter.apache.org
</a>
</li>
<li>
Send your message to:
<a href="mailto:dev@jmeter.apache.org">
dev@jmeter.apache.org
</a>
(after the subscription process)
</li>
<li>
Unsubscribe at
<a href="mailto:dev-unsubscribe@jmeter.apache.org">
dev-unsubscribe@jmeter.apache.org
</a>
</li>
<li>
All old mails at
<a href="http://mail-archives.apache.org/mod_mbox/jmeter-dev/">
jmeter-dev Archive
</a>
</li>
</ul>
</blockquote>
</td></tr>
<tr><td><br></td></tr>
</table>
<table border="0" cellspacing="0" cellpadding="2" width="100%">
<tr><td bgcolor="#828DA6">
<font color="#ffffff" face="arial,helvetica,sanserif">
<a name="JMeterCommits"><strong>Apache JMeter Commits</strong></a>
</font>
</td></tr>
<tr><td>
<blockquote>
<p>
SVN commit messages are sent here.
</p>
<ul>
<li>
Subscribe at
<a href="mailto:commits-subscribe@jmeter.apache.org">
commits-subscribe@jmeter.apache.org
</a>
</li>
<li>
Unsubscribe at
<a href="mailto:commits-unsubscribe@jmeter.apache.org">
commits-unsubscribe@jmeter.apache.org
</a>
</li>
<li>
All old mails at
<a href="http://mail-archives.apache.org/mod_mbox/jmeter-commits/">
jmeter-commits Archive
</a>
</li>
</ul>
</blockquote>
</td></tr>
<tr><td><br></td></tr>
</table>
<table border="0" cellspacing="0" cellpadding="2" width="100%">
<tr><td bgcolor="#828DA6">
<font color="#ffffff" face="arial,helvetica,sanserif">
<a name="JMeterIssues"><strong>Apache JMeter Issues</strong></a>
</font>
</td></tr>
<tr><td>
<blockquote>
<p>
<a href="https://bz.apache.org/bugzilla/">
Bugzilla
</a>
messages are sent here.
</p>
<p>
Prior to Nov 2011, they were sent to the Jakarta Notifications list, see below.
</p>
<ul>
<li>
Subscribe at
<a href="mailto:issues-subscribe@jmeter.apache.org">
issues-subscribe@jmeter.apache.org
</a>
</li>
<li>
Unsubscribe at
<a href="mailto:issues-unsubscribe@jmeter.apache.org">
issues-unsubscribe@jmeter.apache.org
</a>
</li>
<li>
All old mails at
<a href="http://mail-archives.apache.org/mod_mbox/jmeter-issues/">
jmeter-issues Archive
</a>
</li>
</ul>
</blockquote>
</td></tr>
<tr><td><br></td></tr>
</table>
<table border="0" cellspacing="0" cellpadding="2" width="100%">
<tr><td bgcolor="#828DA6">
<font color="#ffffff" face="arial,helvetica,sanserif">
<a name="JakartaDev"><strong>Jakarta Developer</strong></a>
</font>
</td></tr>
<tr><td>
<blockquote>
<p>
Combined Jakarta developer list, April 2010 to November 2011
</p>
<ul>
<li>
All old mails at
<a href="http://mail-archives.apache.org/mod_mbox/jakarta-dev/">
jakarta-dev Archive
</a>
</li>
</ul>
</blockquote>
</td></tr>
<tr><td><br></td></tr>
</table>
<table border="0" cellspacing="0" cellpadding="2" width="100%">
<tr><td bgcolor="#828DA6">
<font color="#ffffff" face="arial,helvetica,sanserif">
<a name="JakartaJMeterDev"><strong>Jakarta JMeter Developer</strong></a>
</font>
</td></tr>
<tr><td>
<blockquote>
<ul>
<li>
All old mails at
<a href="http://mail-archives.apache.org/mod_mbox/jakarta-jmeter-dev/">
jakarta-jmeter-dev Archive
</a>
</li>
</ul>
</blockquote>
</td></tr>
<tr><td><br></td></tr>
</table>
<table border="0" cellspacing="0" cellpadding="2" width="100%">
<tr><td bgcolor="#828DA6">
<font color="#ffffff" face="arial,helvetica,sanserif">
<a name="JakartaNotif"><strong>Jakarta Notifications</strong></a>
</font>
</td></tr>
<tr><td>
<blockquote>
<ul>
<li>
All old mails at
<a href="http://mail-archives.apache.org/mod_mbox/jakarta-notifications/">
jakarta-notifications Archive
</a>
</li>
</ul>
</blockquote>
</td></tr>
<tr><td><br></td></tr>
</table>
</blockquote>
</p>
</td></tr>
<tr><td><br></td></tr>
</table>
<table border="0" cellspacing="0" cellpadding="2" width="100%">
<tr><td bgcolor="#525D76">
<font color="#ffffff" face="arial,helvetica,sanserif">
<strong>Other Archives and Searching</strong></font>
</td></tr>
<tr><td>
<blockquote>
<p>
There are several 3rd party sites that archive and provide searching for our mailing lists:
</p>
<p>
<ul>
<li>
<a href="http://mail-archives.apache.org/mod_mbox/">
mail-archives.apache.org
</a>
</li>
<li>
<a href="http://jmeter.markmail.org/">
Mark Mail
</a>
</li>
<li>
<a href="http://www.mail-archive.com/">
mail-archive.com
</a>
</li>
<li>
<a href="http://marc.theaimsgroup.com/">
marc.theaimsgroup.com
</a>
</li>
</ul>
</p>
</blockquote>
</p>
</td></tr>
<tr><td><br></td></tr>
</table>
<br>
</td>
</tr>
<tr><td>
<hr noshade size="1"/>
</td></tr>
<tr>
<td>
<table width=100%>
<tr>
<td align="center">
<font color="#525D76" size="-1"><em>
Copyright © 1999-2016, Apache Software Foundation
</em></font>
</td>
</tr>
<tr><td colspan="2">
<div align="center"><font color="#525D76" size="-1">
Apache, Apache JMeter, JMeter, the Apache feather, and the Apache JMeter logo are
trademarks of the Apache Software Foundation.
</font>
</div>
</td></tr>
</table>
</td>
</tr>
</table>
</body>
</html>
<!-- end the processing -->
| Resly/pipeline | loadtest.ml/apache-jmeter-3.0/printable_docs/mail2.html | HTML | apache-2.0 | 10,380 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.