repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
ashedwards/ILPO | models/vector_policy.py | <gh_stars>10-100
"""Runs a trained ILPO policy in an online manner and concurrently fixes action inconsistencies."""
from utils import *
from vector_ilpo import VectorILPO
from collections import deque
import gym
import cv2
import os
import random
sess = tf.Session()
class Policy(VectorILPO):
def __init__(self, sess, shape,verbose=False, use_encoding=False, experiment=False, exp_writer=None):
"""Initializes the ILPO policy network."""
self.sess = sess
self.verbose = verbose
self.use_encoding = use_encoding
self.inputs = tf.placeholder("float", shape)
self.targets = tf.placeholder("float", shape)
self.state = tf.placeholder("float", shape)
self.action = tf.placeholder("int32", [None])
self.fake_action = tf.placeholder("int32", [None])
self.reward = tf.placeholder("float", [None])
self.experiment = experiment
self.exp_writer = exp_writer
processed_inputs = self.process_inputs(self.inputs)
processed_targets = self.process_inputs(self.targets)
processed_state = self.process_inputs(self.state)
self.model = self.create_model(processed_inputs, processed_targets)
self.action_label, loss = self.action_remap_net(self.state, self.action, self.fake_action)
self.loss_summary = tf.summary.scalar("policy_loss", tf.squeeze(loss))
if not experiment:
self.reward_summary = tf.summary.scalar("reward", self.reward[0])
self.summary_writer = tf.summary.FileWriter("policy_logs", graph=tf.get_default_graph())
self.train_step = tf.train.AdamOptimizer(args.policy_lr).minimize(loss)
ilpo_var_list = []
policy_var_list = []
# Restore ILPO params and initialize policy params.
for var in tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES):
if "ilpo" in var.name:
ilpo_var_list.append(var)
else:
policy_var_list.append(var)
saver = tf.train.Saver(var_list=ilpo_var_list)
checkpoint = tf.train.latest_checkpoint(args.checkpoint)
saver.restore(sess, checkpoint)
sess.run(tf.variables_initializer(policy_var_list))
self.state_encoding = self.encode(processed_inputs)
def min_action(self, state, action, next_state):
"""Find the minimum action for training."""
# Given state and action, find the closest predicted next state to the real one.
# Use the real action as a training label for remapping the action label.
deprocessed_outputs = [output for output in self.model.outputs]
fake_next_states = sess.run(deprocessed_outputs, feed_dict={self.inputs: [state]})
if self.use_encoding:
next_state_encoding = sess.run(self.state_encoding, feed_dict={self.inputs: [next_state]})[0]
fake_state_encodings = [sess.run(
self.state_encoding,
feed_dict={self.inputs: fake_next_state})[0] for fake_next_state in fake_next_states]
distances = [np.linalg.norm(next_state_encoding - fake_state_encoding) for fake_state_encoding in fake_state_encodings]
else:
distances = [np.linalg.norm(next_state - fake_next_state) for fake_next_state in fake_next_states]
min_action = np.argmin(distances)
min_state = fake_next_states[min_action]
if self.verbose:
print("Next state", next_state)
print("Fake states", fake_next_states)
print("Distances", distances)
print("Action", action)
print("Min state", min_state)
print("\n")
return min_action
def action_remap_net(self, state, action, fake_action):
"""Network for remapping incorrect action labels."""
with tf.variable_scope("action_remap"):
fake_state_encoding = lrelu(slim.flatten(self.create_encoder(state)[-1]), .2)
fake_action_one_hot = tf.one_hot(fake_action, args.n_actions)
fake_action_one_hot = lrelu(fully_connected(fake_action_one_hot, int(fake_state_encoding.shape[-1])), .2)
real_action_one_hot = tf.one_hot(action, args.real_actions, dtype="int32")
fake_state_action = tf.concat([fake_state_encoding, fake_action_one_hot], axis=-1)
prediction = lrelu(fully_connected(fake_state_action, 64), .2)
prediction = lrelu(fully_connected(prediction, 32), .2)
prediction = fully_connected(prediction, args.real_actions)
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=real_action_one_hot, logits=prediction))
return tf.nn.softmax(prediction), loss
def P(self, state):
"""Returns the next_state probabilities for a state."""
return sess.run(self.model.actions, feed_dict={self.inputs: [state]})[0]
def greedy(self, state):
"""Returns the greedy remapped action for a state."""
p_state = self.P(state)
action = np.argmax(p_state)
remapped_action = self.sess.run(self.action_label, feed_dict={self.state: [state], self.fake_action: [action]})[0]
if self.verbose:
print(remapped_action)
return np.argmax(remapped_action)
def eval_policy(self, game, t):
"""Evaluate the policy."""
terminal = False
total_reward = 0
obs = game.reset()
while not terminal:
action = self.greedy(obs)
obs, reward, terminal, _ = game.step(action)
total_reward += reward
if not self.experiment:
reward_summary = sess.run([self.reward_summary], feed_dict={self.reward: [total_reward]})[0]
self.summary_writer.add_summary(reward_summary, t)
else:
self.exp_writer.write(str(t) + "," + str(total_reward) + "\n")
def run_policy(self, seed):
"""Run the policy."""
game = gym.make(args.env)
game.seed(seed)
obs = game.reset()
terminal = False
D = deque()
for t in range(0, 1000):
print(t)
#game.render()
if len(D) > 50000:
D.popleft()
if terminal:
obs = game.reset()
steps = 0.
prev_obs = np.copy(obs)
if np.random.uniform(0,1) < .8:
action = self.greedy(obs)
else:
action = game.action_space.sample()
obs, reward, terminal, _ = game.step(action)
fake_action = self.min_action(prev_obs, action, obs)
D.append((prev_obs, action, fake_action))
if len(D) >= args.batch_size:
minibatch = random.sample(D, args.batch_size)
obs_batch = [d[0] for d in minibatch]
action_batch = [d[1] for d in minibatch]
fake_action_batch = [d[2] for d in minibatch]
_, loss_summary = sess.run([self.train_step, self.loss_summary], feed_dict={
self.state: obs_batch,
self.action: action_batch,
self.fake_action: fake_action_batch})
if not self.experiment:
self.summary_writer.add_summary(loss_summary, t)
if t % 50 == 0:
self.eval_policy(game, t)
terminal = True
if not os.path.exists(args.exp_dir):
os.makedirs(args.exp_dir)
for exp in range(0, 50):
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
print("Running experiment", exp)
tf.reset_default_graph()
exp_writer = open(args.exp_dir + "/" + str(exp) + ".csv", "w")
sess = tf.Session(config=config)
np.random.seed(exp)
tf.set_random_seed(exp)
random.seed(exp)
with sess.as_default():
ilpo = Policy(sess=sess, shape=[None, args.n_dims], use_encoding=False, verbose=False, experiment=True, exp_writer=exp_writer)
ilpo.run_policy(seed=exp)
exp_writer.close()
|
KeltonHolsenTheDev/soundtrack | client/src/components/AddItem/AddItem.js | <reponame>KeltonHolsenTheDev/soundtrack
import React, { useState } from "react";
import axios from "axios";
import ItemForm from "../ItemForm";
import { useAuth } from "../../auth/auth";
import { useHistory } from "react-router-dom";
const AddItem = function () {
const [errors, setErrors] = useState([]);
useAuth();
const history = useHistory();
const addItem = function (item) {
// console.log(item);
axios
.post("/api/item", item)
.then(function (response) {
history.push("/");
})
.catch(function (error) {
// let errorMessage = "";
const newErrors = [];
for (let message of error.response.data) {
// errorMessage += message.defaultMessage + "\n";
newErrors.push(message.defaultMessage);
}
setErrors(newErrors);
// alert(errorMessage);
// console.log(error.response.data);
});
};
const blankItem = {
itemId: 0,
itemName: "",
description: "",
brand: "",
itemType: "",
itemCategory: "OTHER",
location: { locationId: 0, name: "blank", address: "blank" },
locationId: 0,
locationDescription: "",
broken: false,
notes: "",
};
return (
<ItemForm
defaultItem={blankItem}
submitFcn={addItem}
formTitle="Add"
errors={errors}
setErrors={setErrors}
/>
);
};
export default AddItem;
|
Fimbure/icebox-1 | third_party/virtualbox/src/VBox/Additions/x11/x11include/libXext-1.3.1/X11/extensions/sync.h | <gh_stars>100-1000
/*
Copyright 1991, 1993, 1994, 1998 The Open Group
Permission to use, copy, modify, distribute, and sell this software and its
documentation for any purpose is hereby granted without fee, provided that
the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation.
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of The Open Group shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from The Open Group.
*/
/***********************************************************
Copyright 1991,1993 by Digital Equipment Corporation, Maynard, Massachusetts,
and Olivetti Research Limited, Cambridge, England.
All Rights Reserved
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the names of Digital or Olivetti
not be used in advertising or publicity pertaining to distribution of the
software without specific, written prior permission.
DIGITAL AND OLIVETTI DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL THEY BE LIABLE FOR ANY SPECIAL, INDIRECT OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
******************************************************************/
#ifndef _SYNC_H_
#define _SYNC_H_
#include <X11/Xfuncproto.h>
#include <X11/extensions/syncconst.h>
#ifdef _SYNC_SERVER
#include <X11/extensions/syncproto.h>
#else
_XFUNCPROTOBEGIN
/* get rid of macros so we can define corresponding functions */
#undef XSyncIntToValue
#undef XSyncIntsToValue
#undef XSyncValueGreaterThan
#undef XSyncValueLessThan
#undef XSyncValueGreaterOrEqual
#undef XSyncValueLessOrEqual
#undef XSyncValueEqual
#undef XSyncValueIsNegative
#undef XSyncValueIsZero
#undef XSyncValueIsPositive
#undef XSyncValueLow32
#undef XSyncValueHigh32
#undef XSyncValueAdd
#undef XSyncValueSubtract
#undef XSyncMaxValue
#undef XSyncMinValue
extern void XSyncIntToValue(
XSyncValue* /*pv*/,
int /*i*/
);
extern void XSyncIntsToValue(
XSyncValue* /*pv*/,
unsigned int /*l*/,
int /*h*/
);
extern Bool XSyncValueGreaterThan(
XSyncValue /*a*/,
XSyncValue /*b*/
);
extern Bool XSyncValueLessThan(
XSyncValue /*a*/,
XSyncValue /*b*/
);
extern Bool XSyncValueGreaterOrEqual(
XSyncValue /*a*/,
XSyncValue /*b*/
);
extern Bool XSyncValueLessOrEqual(
XSyncValue /*a*/,
XSyncValue /*b*/
);
extern Bool XSyncValueEqual(
XSyncValue /*a*/,
XSyncValue /*b*/
);
extern Bool XSyncValueIsNegative(
XSyncValue /*v*/
);
extern Bool XSyncValueIsZero(
XSyncValue /*a*/
);
extern Bool XSyncValueIsPositive(
XSyncValue /*v*/
);
extern unsigned int XSyncValueLow32(
XSyncValue /*v*/
);
extern int XSyncValueHigh32(
XSyncValue /*v*/
);
extern void XSyncValueAdd(
XSyncValue* /*presult*/,
XSyncValue /*a*/,
XSyncValue /*b*/,
int* /*poverflow*/
);
extern void XSyncValueSubtract(
XSyncValue* /*presult*/,
XSyncValue /*a*/,
XSyncValue /*b*/,
int* /*poverflow*/
);
extern void XSyncMaxValue(
XSyncValue* /*pv*/
);
extern void XSyncMinValue(
XSyncValue* /*pv*/
);
_XFUNCPROTOEND
typedef struct _XSyncSystemCounter {
char *name; /* null-terminated name of system counter */
XSyncCounter counter; /* counter id of this system counter */
XSyncValue resolution; /* resolution of this system counter */
} XSyncSystemCounter;
typedef struct {
XSyncCounter counter; /* counter to trigger on */
XSyncValueType value_type; /* absolute/relative */
XSyncValue wait_value; /* value to compare counter to */
XSyncTestType test_type; /* pos/neg comparison/transtion */
} XSyncTrigger;
typedef struct {
XSyncTrigger trigger; /* trigger for await */
XSyncValue event_threshold; /* send event if past threshold */
} XSyncWaitCondition;
typedef struct {
XSyncTrigger trigger;
XSyncValue delta;
Bool events;
XSyncAlarmState state;
} XSyncAlarmAttributes;
/*
* Events
*/
typedef struct {
int type; /* event base + XSyncCounterNotify */
unsigned long serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
XSyncCounter counter; /* counter involved in await */
XSyncValue wait_value; /* value being waited for */
XSyncValue counter_value; /* counter value when this event was sent */
Time time; /* milliseconds */
int count; /* how many more events to come */
Bool destroyed; /* True if counter was destroyed */
} XSyncCounterNotifyEvent;
typedef struct {
int type; /* event base + XSyncCounterNotify */
unsigned long serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
XSyncAlarm alarm; /* alarm that triggered */
XSyncValue counter_value; /* value that triggered the alarm */
XSyncValue alarm_value; /* test value of trigger in alarm */
Time time; /* milliseconds */
XSyncAlarmState state; /* new state of alarm */
} XSyncAlarmNotifyEvent;
/*
* Errors
*/
typedef struct {
int type;
Display *display; /* Display the event was read from */
XSyncAlarm alarm; /* resource id */
unsigned long serial; /* serial number of failed request */
unsigned char error_code; /* error base + XSyncBadAlarm */
unsigned char request_code; /* Major op-code of failed request */
unsigned char minor_code; /* Minor op-code of failed request */
} XSyncAlarmError;
typedef struct {
int type;
Display *display; /* Display the event was read from */
XSyncCounter counter; /* resource id */
unsigned long serial; /* serial number of failed request */
unsigned char error_code; /* error base + XSyncBadCounter */
unsigned char request_code; /* Major op-code of failed request */
unsigned char minor_code; /* Minor op-code of failed request */
} XSyncCounterError;
/*
* Prototypes
*/
_XFUNCPROTOBEGIN
extern Status XSyncQueryExtension(
Display* /*dpy*/,
int* /*event_base_return*/,
int* /*error_base_return*/
);
extern Status XSyncInitialize(
Display* /*dpy*/,
int* /*major_version_return*/,
int* /*minor_version_return*/
);
extern XSyncSystemCounter *XSyncListSystemCounters(
Display* /*dpy*/,
int* /*n_counters_return*/
);
extern void XSyncFreeSystemCounterList(
XSyncSystemCounter* /*list*/
);
extern XSyncCounter XSyncCreateCounter(
Display* /*dpy*/,
XSyncValue /*initial_value*/
);
extern Status XSyncSetCounter(
Display* /*dpy*/,
XSyncCounter /*counter*/,
XSyncValue /*value*/
);
extern Status XSyncChangeCounter(
Display* /*dpy*/,
XSyncCounter /*counter*/,
XSyncValue /*value*/
);
extern Status XSyncDestroyCounter(
Display* /*dpy*/,
XSyncCounter /*counter*/
);
extern Status XSyncQueryCounter(
Display* /*dpy*/,
XSyncCounter /*counter*/,
XSyncValue* /*value_return*/
);
extern Status XSyncAwait(
Display* /*dpy*/,
XSyncWaitCondition* /*wait_list*/,
int /*n_conditions*/
);
extern XSyncAlarm XSyncCreateAlarm(
Display* /*dpy*/,
unsigned long /*values_mask*/,
XSyncAlarmAttributes* /*values*/
);
extern Status XSyncDestroyAlarm(
Display* /*dpy*/,
XSyncAlarm /*alarm*/
);
extern Status XSyncQueryAlarm(
Display* /*dpy*/,
XSyncAlarm /*alarm*/,
XSyncAlarmAttributes* /*values_return*/
);
extern Status XSyncChangeAlarm(
Display* /*dpy*/,
XSyncAlarm /*alarm*/,
unsigned long /*values_mask*/,
XSyncAlarmAttributes* /*values*/
);
extern Status XSyncSetPriority(
Display* /*dpy*/,
XID /*client_resource_id*/,
int /*priority*/
);
extern Status XSyncGetPriority(
Display* /*dpy*/,
XID /*client_resource_id*/,
int* /*return_priority*/
);
extern XSyncFence XSyncCreateFence(
Display* /*dpy*/,
Drawable /*d*/,
Bool /*initially_triggered*/
);
extern Bool XSyncTriggerFence(
Display* /*dpy*/,
XSyncFence /*fence*/
);
extern Bool XSyncResetFence(
Display* /*dpy*/,
XSyncFence /*fence*/
);
extern Bool XSyncDestroyFence(
Display* /*dpy*/,
XSyncFence /*fence*/
);
extern Bool XSyncQueryFence(
Display* /*dpy*/,
XSyncFence /*fence*/,
Bool* /*triggered*/
);
extern Bool XSyncAwaitFence(
Display* /*dpy*/,
const XSyncFence* /*fence_list*/,
int /*n_fences*/
);
_XFUNCPROTOEND
#endif /* _SYNC_SERVER */
#endif /* _SYNC_H_ */
|
Zoltan45/Mame-mkp119 | src/mame/video/munchmo.c | #include "driver.h"
UINT8 *mnchmobl_vreg;
UINT8 *mnchmobl_status_vram;
UINT8 *mnchmobl_sprite_xpos;
UINT8 *mnchmobl_sprite_attr;
UINT8 *mnchmobl_sprite_tile;
static int mnchmobl_palette_bank;
static int flipscreen;
PALETTE_INIT( mnchmobl )
{
int i;
for (i = 0;i < machine->drv->total_colors;i++)
{
int bit0,bit1,bit2,r,g,b;
/* red component */
bit0 = (color_prom[i] >> 0) & 0x01;
bit1 = (color_prom[i] >> 1) & 0x01;
bit2 = (color_prom[i] >> 2) & 0x01;
r = 0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2;
/* green component */
bit0 = (color_prom[i] >> 3) & 0x01;
bit1 = (color_prom[i] >> 4) & 0x01;
bit2 = (color_prom[i] >> 5) & 0x01;
g = 0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2;
/* blue component */
bit0 = (color_prom[i] >> 6) & 0x01;
bit1 = (color_prom[i] >> 7) & 0x01;
b = 0x4f * bit0 + 0xa8 * bit1;
palette_set_color(machine,i,MAKE_RGB(r,g,b));
}
}
WRITE8_HANDLER( mnchmobl_palette_bank_w )
{
if( mnchmobl_palette_bank!=(data&0x3) )
{
memset( dirtybuffer, 1, 0x100 );
mnchmobl_palette_bank = data&0x3;
}
}
WRITE8_HANDLER( mnchmobl_flipscreen_w )
{
if( flipscreen!=data )
{
memset( dirtybuffer, 1, 0x100 );
flipscreen = data;
}
}
READ8_HANDLER( mnchmobl_sprite_xpos_r ){ return mnchmobl_sprite_xpos[offset]; }
WRITE8_HANDLER( mnchmobl_sprite_xpos_w ){ mnchmobl_sprite_xpos[offset] = data; }
READ8_HANDLER( mnchmobl_sprite_attr_r ){ return mnchmobl_sprite_attr[offset]; }
WRITE8_HANDLER( mnchmobl_sprite_attr_w ){ mnchmobl_sprite_attr[offset] = data; }
READ8_HANDLER( mnchmobl_sprite_tile_r ){ return mnchmobl_sprite_tile[offset]; }
WRITE8_HANDLER( mnchmobl_sprite_tile_w ){ mnchmobl_sprite_tile[offset] = data; }
VIDEO_START( mnchmobl )
{
dirtybuffer = auto_malloc(0x100);
memset( dirtybuffer, 1, 0x100 );
tmpbitmap = auto_bitmap_alloc(512,512,machine->screen[0].format);
}
READ8_HANDLER( mnchmobl_videoram_r )
{
return videoram[offset];
}
WRITE8_HANDLER( mnchmobl_videoram_w )
{
offset = offset&0xff; /* mirror the two banks? */
if( videoram[offset]!=data )
{
videoram[offset] = data;
dirtybuffer[offset] = 1;
}
}
static void draw_status(running_machine *machine, mame_bitmap *bitmap, const rectangle *cliprect)
{
const gfx_element *gfx = machine->gfx[0];
int row;
for( row=0; row<4; row++ )
{
int sy,sx = (row&1)*8;
const UINT8 *source = mnchmobl_status_vram + (~row&1)*32;
if( row<=1 )
{
source+=2*32;
sx+=256+32+16;
}
for( sy=0; sy<256; sy+=8 )
{
drawgfx( bitmap, gfx,
*source++,
0, /* color */
0,0, /* no flip */
sx,sy,
cliprect,
TRANSPARENCY_NONE, 0 );
}
}
}
static void draw_background(running_machine *machine, mame_bitmap *bitmap, const rectangle *cliprect)
{
/*
ROM B1.2C contains 256 tilemaps defining 4x4 configurations of
the tiles in ROM B2.2B
*/
UINT8 *rom = memory_region(REGION_GFX2);
const gfx_element *gfx = machine->gfx[1];
int offs;
for( offs=0; offs<0x100; offs++ )
{
if( dirtybuffer[offs] )
{
int sy = (offs%16)*32;
int sx = (offs/16)*32;
int tile_number = videoram[offs];
int row,col;
dirtybuffer[offs] = 0;
for( row=0; row<4; row++ )
{
for( col=0; col<4; col++ )
{
drawgfx( tmpbitmap,gfx,
rom[col+tile_number*4+row*0x400],
mnchmobl_palette_bank,
0,0, /* flip */
sx+col*8, sy+row*8,
0, TRANSPARENCY_NONE, 0 );
}
}
}
}
{
int scrollx = -(mnchmobl_vreg[6]*2+(mnchmobl_vreg[7]>>7))-64-128-16;
int scrolly = 0;
copyscrollbitmap(bitmap,tmpbitmap,
1,&scrollx,1,&scrolly,
cliprect,TRANSPARENCY_NONE,0);
}
}
static void draw_sprites(running_machine *machine, mame_bitmap *bitmap, const rectangle *cliprect)
{
int scroll = mnchmobl_vreg[6];
int flags = mnchmobl_vreg[7]; /* XB?????? */
int xadjust = - 128-16 - ((flags&0x80)?1:0);
int bank = (flags&0x40)?1:0;
const gfx_element *gfx = machine->gfx[2+bank];
int color_base = mnchmobl_palette_bank*4+3;
int i;
for( i=0; i<0x200; i++ )
{
int tile_number = mnchmobl_sprite_tile[i]; /* ETTTTTTT */
int attributes = mnchmobl_sprite_attr[i]; /* XYYYYYCC */
int sx = mnchmobl_sprite_xpos[i]; /* XXXXXXX? */
int sy = (i/0x40)*0x20; /* Y YY------ */
sy += (attributes>>2)&0x1f;
if( tile_number != 0xff && (attributes&0x80) )
{
sx = (sx>>1) | (tile_number&0x80);
sx = 2*((-32-scroll - sx)&0xff)+xadjust;
drawgfx( bitmap, gfx,
0x7f - (tile_number&0x7f),
color_base-(attributes&0x03),
0,0, /* no flip */
sx,sy,
cliprect, TRANSPARENCY_PEN, 7 );
}
}
}
VIDEO_UPDATE( mnchmobl )
{
draw_background(machine, bitmap, cliprect);
draw_sprites(machine, bitmap, cliprect);
draw_status(machine, bitmap, cliprect);
return 0;
}
|
parada3desu/logbunker | logbunker/contexts/shared/domain/CommandHandler.py | from abc import abstractmethod
from typing import Any, NoReturn
from logbunker.contexts.shared.domain.Command import Command
from logbunker.contexts.shared.domain.Interface import Interface
class CommandHandler(Interface):
@abstractmethod
def subscribed_to(self) -> str:
raise NotImplementedError()
@abstractmethod
async def handle(self, command: Command) -> NoReturn:
raise NotImplementedError()
|
alexis-evelyn/nbt-crafting | src/main/java/de/siphalor/nbtcrafting/dollar/part/unary/NumberDollarPartDeserializer.java | <gh_stars>0
package de.siphalor.nbtcrafting.dollar.part.unary;
import de.siphalor.nbtcrafting.dollar.DollarDeserializationException;
import de.siphalor.nbtcrafting.dollar.DollarParser;
import de.siphalor.nbtcrafting.dollar.part.DollarPart;
import de.siphalor.nbtcrafting.dollar.part.ValueDollarPart;
public class NumberDollarPartDeserializer implements DollarPart.UnaryDeserializer {
@Override
public boolean matches(int character, DollarParser dollarParser) {
return Character.isDigit(character);
}
@Override
public DollarPart parse(DollarParser dollarParser) throws DollarDeserializationException {
StringBuilder stringBuilder = new StringBuilder(String.valueOf(Character.toChars(dollarParser.eat())));
boolean dot = false;
int character;
while (true) {
character = dollarParser.peek();
if (Character.isDigit(character)) {
dollarParser.skip();
stringBuilder.append(Character.toChars(character));
} else if (!dot && character == '.') {
dollarParser.skip();
stringBuilder.append('.');
dot = true;
} else {
break;
}
}
try {
if (dot)
return ValueDollarPart.of(Double.parseDouble(stringBuilder.toString()));
else
return ValueDollarPart.of(Integer.parseInt(stringBuilder.toString()));
} catch (NumberFormatException e) {
throw new DollarDeserializationException(e);
}
}
}
|
rjw57/tiw-computer | emulator/src/mame/drivers/usbilliards.cpp | // license:BSD-3-Clause
// copyright-holders:Stiletto
/***************************************************************************
US Billiards TTL Games
Game Name DATA
-------------------------------------
TV Tennis (1973/03,11?) NO
TV Hockey? (1973) UNKNOWN
Survival (1975/02-03?) UNKNOWN
Shark (1975/11) YES
Space Battle (1977/10-12?) UNKNOWN
Variety TV (1978/09) UNKNOWN
***************************************************************************/
#include "emu.h"
#include "machine/netlist.h"
#include "netlist/devices/net_lib.h"
#include "video/fixfreq.h"
// copied from Pong, not accurate for this driver!
// start
#define MASTER_CLOCK 7159000
#define V_TOTAL (0x105+1) // 262
#define H_TOTAL (0x1C6+1) // 454
#define HBSTART (H_TOTAL)
#define HBEND (80)
#define VBSTART (V_TOTAL)
#define VBEND (16)
#define HRES_MULT (1)
// end
class usbilliards_state : public driver_device
{
public:
usbilliards_state(const machine_config &mconfig, device_type type, const char *tag)
: driver_device(mconfig, type, tag),
m_maincpu(*this, "maincpu"),
m_video(*this, "fixfreq")
{
}
// devices
required_device<netlist_mame_device> m_maincpu;
required_device<fixedfreq_device> m_video;
void usbilliards(machine_config &config);
protected:
// driver_device overrides
virtual void machine_start() override;
virtual void machine_reset() override;
virtual void video_start() override;
private:
};
static NETLIST_START(usbilliards)
SOLVER(Solver, 48000)
// PARAM(Solver.FREQ, 48000)
PARAM(Solver.ACCURACY, 1e-4) // works and is sufficient
// schematics
//...
// NETDEV_ANALOG_CALLBACK(sound_cb, sound, usbilliards_state, sound_cb, "")
// NETDEV_ANALOG_CALLBACK(video_cb, videomix, fixedfreq_device, update_vid, "fixfreq")
NETLIST_END()
void usbilliards_state::machine_start()
{
}
void usbilliards_state::machine_reset()
{
}
void usbilliards_state::video_start()
{
}
MACHINE_CONFIG_START(usbilliards_state::usbilliards)
/* basic machine hardware */
MCFG_DEVICE_ADD("maincpu", NETLIST_CPU, NETLIST_CLOCK)
MCFG_NETLIST_SETUP(usbilliards)
/* video hardware */
MCFG_FIXFREQ_ADD("fixfreq", "screen")
MCFG_FIXFREQ_MONITOR_CLOCK(MASTER_CLOCK)
MCFG_FIXFREQ_HORZ_PARAMS(H_TOTAL-67,H_TOTAL-40,H_TOTAL-8,H_TOTAL)
MCFG_FIXFREQ_VERT_PARAMS(V_TOTAL-22,V_TOTAL-19,V_TOTAL-12,V_TOTAL)
MCFG_FIXFREQ_FIELDCOUNT(1)
MCFG_FIXFREQ_SYNC_THRESHOLD(0.30)
MACHINE_CONFIG_END
/***************************************************************************
Game driver(s)
***************************************************************************/
/*
Shark by <NAME>
Etched in copper on Top (C) 1975
010
1SCOOP J6 2SCOOP
Handwritten on top J0037
124
empty socket at 5M C etched in copper next to socket
*/
ROM_START( sharkusb )
ROM_REGION( 0x10000, "maincpu", ROMREGION_ERASE00 )
ROM_REGION( 0x0200, "roms", ROMREGION_ERASE00 )
ROM_LOAD( "82s123_b.5n", 0x0000, 0x0100, CRC(91b977b3) SHA1(37929f6049dea0ebed2c01ae20354e41c867b8f9) ) // 82s123 - handwritten B - B also etched in copper next to socket
ROM_LOAD( "82s123_a.6n", 0x0100, 0x0100, CRC(63f621cb) SHA1(6c6e6f22313db33afd069dae1b0180b5ccddfa56) ) // 82s123 - handwritten A - A also etched in copper next to socket
ROM_END
GAME( 1975, sharkusb, 0, usbilliards, 0, usbilliards_state, 0, ROT0, "US Billiards Inc.", "Shark [TTL]", MACHINE_IS_SKELETON )
|
nicolaskruger/camel-in-action | chapter5/splitter/src/test/java/my/split_aggregate/SpliterWord.java | <filename>chapter5/splitter/src/test/java/my/split_aggregate/SpliterWord.java
package my.split_aggregate;
import java.util.Arrays;
import java.util.List;
public class SpliterWord {
public List<String> split(String word){
return Arrays.asList(word.split(","));
}
}
|
JelenaKar/-job4j | trainee/chapter_001/src/test/java/ru/job4j/array/ArrayDuplicateTest.java | <filename>trainee/chapter_001/src/test/java/ru/job4j/array/ArrayDuplicateTest.java<gh_stars>0
package ru.job4j.array;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Test.
*
* @author <NAME> (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class ArrayDuplicateTest {
/**
* Тест удаления дублирующихся слов из массива.
*/
@Test
public void whenRemoveDuplicatesThenArrayWithoutDuplicate() {
ArrayDuplicate duplicate = new ArrayDuplicate();
String[] arr = {"Привет", "Мир", "Привет", "Супер", "Мир"};
arr = duplicate.remove(arr);
String[] expected = {"Привет", "Мир", "Супер"};
assertThat(arr, is(expected));
}
}
|
Dazzed/dental-front | app/containers/ActivationPage/sagas.js | <filename>app/containers/ActivationPage/sagas.js
import { takeEvery } from 'redux-saga';
import { call, put } from 'redux-saga/effects';
import { push } from 'react-router-redux';
import request from 'utils/request';
import { getItem } from 'utils/localStorage';
import {
activateSuccess,
activateError
} from 'containers/ActivationPage/actions';
import { ACTIVATE_REQUEST } from './constants';
// Bootstrap sagas
export default [
activateFlow
];
function* activateFlow () {
yield* takeEvery(ACTIVATE_REQUEST, activateUser);
}
function* activateUser (action) {
try {
// Don't allow logged-in users to activate again.
const authToken = getItem('auth_token');
if (authToken) {
yield put(push('/accounts/login'));
return;
}
yield call(request, `/api/v1/accounts/activate/${action.payload.key}`);
yield put(activateSuccess());
} catch (err) {
yield put(activateError(err));
}
}
|
lulululululu/cpp_client_telemetry | lib/http/HttpClient_CAPI.hpp | <gh_stars>1-10
//
// Copyright (c) 2015-2020 Microsoft Corporation and Contributors.
// SPDX-License-Identifier: Apache-2.0
//
#ifndef HTTPCLIENT_CAPI_HPP
#define HTTPCLIENT_CAPI_HPP
#include "IHttpClient.hpp"
#include "pal/PAL.hpp"
#include "mat.h"
#include <string>
namespace MAT_NS_BEGIN {
class HttpClient_CAPI : public IHttpClient {
public:
HttpClient_CAPI(http_send_fn_t sendFn, http_cancel_fn_t cancelFn);
virtual IHttpRequest* CreateRequest() override;
virtual void SendRequestAsync(IHttpRequest* request, IHttpResponseCallback* callback) override;
virtual void CancelRequestAsync(std::string const& id) override;
virtual void CancelAllRequests() override;
private:
http_send_fn_t m_sendFn;
http_cancel_fn_t m_cancelFn;
std::mutex m_requestsMutex;
};
} MAT_NS_END
#endif // HTTPCLIENT_CAPI_HPP
|
jofaval/tfcgs-daw | dist/client/scripts/js/Validator.js | <filename>dist/client/scripts/js/Validator.js
class Validator {
//Given input, rules pairs validates their content
static validate(validationParams, inputs) {
if (!Array.isArray(validationParams)) {
return false;
}
validationParams.forEach(validationInfo => {
var currentInput = inputs[validationInfo["fieldName"]];
var currentInputVal = currentInput.val();
var rulesToExecute = validationInfo["rules"].split(",");
rulesToExecute.array.forEach(validationRule => {
if (window["Validator"][validationRule](currentInputVal)) {
currentInput.removeClass("error");
} else {
currentInput.addClass("error");
return false;
}
});
});
return true;
}
static noEmpty(valor) {
return valor.toString().length != 0;
}
static numeric(valor) {
return isNaN(valor);
}
static email(valor) {
return /^[a-z]+([\.]?[a-z0-9\_\-]+)*@iesabastos\.org$/.test(valor);
}
static datetime(valor) {
return /^\d\d\d\d-(0?[1-9]|1[0-2])-(0?[1-9]|[12][0-9]|3[01]) (00|[0-9]|1[0-9]|2[0-3]):([0-9]|[0-5][0-9]):([0-9]|[0-5][0-9])$/.test(valor);
}
static date(valor) {
return /^([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))$/.test(valor);
}
static name(valor) {
return /^[a-zñºª ]+$/iu.test(valor);
}
static password(valor) {
return /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,24}$/i.test(valor);
}
static state(valor) {
return ["perfect", "on_repair", "left_out"].includes(valor);
}
static text(valor) {
return /^[a-zñ ]*$/iu.test(valor);
}
static username(valor) {
return /^[a-z0-9\_\-]{3,24}$/i.test(valor);
}
static image(valor) {
return /^.+[\.jpg|\.jpeg|\.png|\.gif]$/i.test(valor);
}
} |
soerenbe/py-ebrest | easybill_rest/resources/resource_documents.py | from __future__ import annotations
from enum import Enum
from typing import TYPE_CHECKING
from easybill_rest.helper import Helper
from easybill_rest.resources.resource_abstract import ResourceAbstract
if TYPE_CHECKING:
from easybill_rest import Client
class SendMethod(Enum):
EMAIL = "email"
FAX = "fax"
POST = "post"
class ResourceDocuments(ResourceAbstract):
__endpoint: str = "/documents"
__client: Client
def __init__(self, client: Client) -> None:
super().__init__()
self.__client = client
def get_resource_endpoint(self):
return self.__endpoint
def get_documents(self, params: dict = None) -> dict:
"""get_documents returns a dict with document objects"""
return self.__client.call(
"GET",
Helper.create_request_url_from_params(self.__endpoint, params),
self.__client.get_basic_headers_for_json()
)
def get_document(self, document_id: str) -> dict:
"""get_document returns the referenced (id) document"""
return self.__client.call(
"GET",
Helper.create_request_url_from_params(
self.__endpoint + "/" + document_id),
self.__client.get_basic_headers_for_json())
def create_document(self, payload: dict) -> dict:
"""create_document returns the document model as dict on success with the data from the passed payload"""
return self.__client.call(
"POST",
Helper.create_request_url_from_params(self.__endpoint),
self.__client.get_basic_headers_for_json(),
payload
)
def update_document(self, document_id: str, payload: dict) -> dict:
"""update_document updates the reference (id) document with the given payload. Returns the updated document"""
return self.__client.call(
"PUT",
Helper.create_request_url_from_params(
self.__endpoint +
"/" +
document_id),
self.__client.get_basic_headers_for_json(),
payload)
def delete_document(self, document_id: str) -> None:
"""delete_document returns None on success and raises an exception if the document couldn't be deleted"""
self.__client.call(
"DELETE",
Helper.create_request_url_from_params(
self.__endpoint + "/" + document_id),
self.__client.get_basic_headers())
def finalize_document(self, document_id: str) -> dict:
"""finalize_document returns the finalized document on success"""
return self.__client.call(
"PUT",
Helper.create_request_url_from_params(
self.__endpoint +
"/" +
document_id +
"/done"),
self.__client.get_basic_headers_for_json())
def cancel_document(self, document_id: str) -> dict:
"""cancel_document returns the canceled document on success"""
return self.__client.call(
"POST",
Helper.create_request_url_from_params(
self.__endpoint +
"/" +
document_id +
"/cancel"),
self.__client.get_basic_headers_for_json())
def send_document(
self,
document_id: str,
send_method: SendMethod,
payload: dict) -> None:
"""send_document returns None on success and rises exception on failure"""
self.__client.call(
"POST",
Helper.create_request_url_from_params(
self.__endpoint +
"/" +
document_id +
"/send/" +
str(send_method)),
self.__client.get_basic_headers_for_json(),
payload)
def download_document(self, document_id: str) -> bytes:
"""download_document returns the document as bytes on success"""
return self.__client.download(
Helper.create_request_url_from_params(
self.__endpoint +
"/" +
document_id +
"/pdf"),
self.__client.get_basic_headers_for_pdf(),
)
|
npocmaka/Windows-Server-2003 | drivers/storage/ide/atapi/chanfdo.h | /*++
Copyright (C) 1993-99 Microsoft Corporation
Module Name:
chanfdo.h
Abstract:
--*/
#if !defined (___chanfdo_h___)
#define ___chanfdo_h___
//
// work item
//
typedef struct _IDE_WORK_ITEM_CONTEXT {
PIO_WORKITEM WorkItem;
PIRP Irp;
} IDE_WORK_ITEM_CONTEXT, *PIDE_WORK_ITEM_CONTEXT;
NTSTATUS
ChannelAddDevice(
IN PDRIVER_OBJECT DriverObject,
IN PDEVICE_OBJECT PhysicalDeviceObject
);
NTSTATUS
ChannelAddChannel(
IN PDRIVER_OBJECT DriverObject,
IN PDEVICE_OBJECT PhysicalDeviceObject,
OUT PFDO_EXTENSION *FdoExtension
);
NTSTATUS
ChannelStartDevice (
IN PDEVICE_OBJECT DeviceObject,
IN OUT PIRP Irp
);
NTSTATUS
ChannelStartChannel (
PFDO_EXTENSION FdoExtension,
PCM_RESOURCE_LIST ResourceListToKeep
);
NTSTATUS
ChannelStartDeviceCompletionRoutine (
IN PDEVICE_OBJECT DeviceObject,
IN OUT PIRP Irp,
IN OUT PVOID Context
);
NTSTATUS
ChannelCreateSymblicLinks (
PFDO_EXTENSION FdoExtension
);
NTSTATUS
ChannelDeleteSymblicLinks (
PFDO_EXTENSION FdoExtension
);
NTSTATUS
ChannelSurpriseRemoveDevice (
IN PDEVICE_OBJECT DeviceObject,
IN OUT PIRP Irp
);
NTSTATUS
ChannelRemoveDevice (
IN PDEVICE_OBJECT DeviceObject,
IN OUT PIRP Irp
);
NTSTATUS
ChannelRemoveDeviceCompletionRoutine (
IN PDEVICE_OBJECT DeviceObject,
IN PIRP Irp,
IN PVOID Context
);
NTSTATUS
ChannelStopDevice (
IN PDEVICE_OBJECT DeviceObject,
IN OUT PIRP Irp
);
NTSTATUS
ChannelRemoveChannel (
PFDO_EXTENSION FdoExtension
);
NTSTATUS
ChannelStartDeviceCompletionRoutine (
IN PDEVICE_OBJECT DeviceObject,
IN PIRP Irp,
IN PVOID Context
);
NTSTATUS
ChannelQueryDeviceRelations (
IN PDEVICE_OBJECT DeviceObject,
IN OUT PIRP Irp
);
NTSTATUS
ChannelQueryBusRelation (
IN PDEVICE_OBJECT DeviceObject,
IN PIDE_WORK_ITEM_CONTEXT workItemContext
);
PDEVICE_RELATIONS
ChannelBuildDeviceRelationList (
PFDO_EXTENSION FdoExtension
);
NTSTATUS
ChannelQueryId (
IN PDEVICE_OBJECT DeviceObject,
IN OUT PIRP Irp
);
NTSTATUS
ChannelQueryIdCompletionRoutine(
PDEVICE_OBJECT DeviceObject,
PIRP Irp,
PVOID Context
);
NTSTATUS
ChannelUsageNotification (
IN PDEVICE_OBJECT DeviceObject,
IN OUT PIRP Irp
);
NTSTATUS
ChannelUsageNotificationCompletionRoutine (
IN PDEVICE_OBJECT DeviceObject,
IN PIRP Irp,
IN PVOID Context
);
NTSTATUS
ChannelDeviceIoControl(
IN PDEVICE_OBJECT DeviceObject,
IN PIRP Irp
);
VOID
ChannelQueryBusMasterInterface (
PFDO_EXTENSION FdoExtension
);
VOID
ChannelQueryTransferModeInterface (
PFDO_EXTENSION FdoExtension
);
VOID
ChannelUnbindBusMasterParent (
PFDO_EXTENSION FdoExtension
);
VOID
ChannelQuerySyncAccessInterface (
PFDO_EXTENSION FdoExtension
);
VOID
ChannelQueryRequestProperResourceInterface (
PFDO_EXTENSION FdoExtension
);
__inline
VOID
ChannelEnableInterrupt (
IN PFDO_EXTENSION FdoExtension
);
__inline
VOID
ChannelDisableInterrupt (
IN PFDO_EXTENSION FdoExtension
);
NTSTATUS
ChannelGetIdentifyData (
PFDO_EXTENSION FdoExtension,
ULONG DeviceNumber,
PIDENTIFY_DATA IdentifyData
);
NTSTATUS
ChannelAcpiTransferModeSelect (
IN PVOID Context,
PPCIIDE_TRANSFER_MODE_SELECT XferMode
);
NTSTATUS
ChannelRestoreTiming (
IN PFDO_EXTENSION FdoExtension,
IN PSET_ACPI_TIMING_COMPLETION_ROUTINE CallerCompletionRoutine,
IN PVOID CallerContext
);
NTSTATUS
ChannelRestoreTimingCompletionRoutine (
IN PDEVICE_OBJECT DeviceObject,
IN NTSTATUS Status,
IN PVOID Context
);
NTSTATUS
ChannelFilterResourceRequirements (
IN PDEVICE_OBJECT DeviceObject,
IN OUT PIRP Irp
);
BOOLEAN
ChannelQueryPcmciaParent (
PFDO_EXTENSION FdoExtension
);
#ifdef IDE_FILTER_PROMISE_TECH_RESOURCES
NTSTATUS
ChannelFilterPromiseTechResourceRequirements (
IN PDEVICE_OBJECT DeviceObject,
IN OUT PIRP Irp
);
#endif // IDE_FILTER_PROMISE_TECH_RESOURCES
NTSTATUS
ChannelQueryPnPDeviceState (
IN PDEVICE_OBJECT DeviceObject,
IN OUT PIRP Irp
);
#ifdef ENABLE_NATIVE_MODE
VOID
ChannelQueryInterruptInterface (
PFDO_EXTENSION FdoExtension
);
#endif
#endif // ___chanfdo_h___
|
IvarJonsson/Project-Unknown | ItemView.cpp | // Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved.
/*************************************************************************
-------------------------------------------------------------------------
$Id$
$DateTime$
-------------------------------------------------------------------------
History:
- 30:8:2005 12:52 : Created by <NAME>
*************************************************************************/
#include "StdAfx.h"
#include "Item.h"
#include "Actor.h"
#include "Player.h"
#include "GameCVars.h"
#include <IViewSystem.h>
#include "ItemSharedParams.h"
#include "ReplayActor.h"
//------------------------------------------------------------------------
void CItem::UpdateFPView(float frameTime)
{
if (m_stats.attachment == eIA_None && !m_stats.mounted)
return;
CheckViewChange();
}
//------------------------------------------------------------------------
bool CItem::FilterView(struct SViewParams &viewParams)
{
return false;
}
//------------------------------------------------------------------------
void CItem::PostFilterView(struct SViewParams &viewParams)
{
}
//------------------------------------------------------------------------
bool CItem::IsOwnerFP()
{
CActor *pOwner = GetOwnerActor();
if (pOwner)
{
if (m_pGameFramework->GetClientActor() != pOwner)
return false;
return !pOwner->IsThirdPerson();
}
else if (gEnv->bMultiplayer)
{
CReplayActor* pReplayActor = CReplayActor::GetReplayActor(GetOwner());
if (pReplayActor)
{
return !pReplayActor->IsThirdPerson();
}
}
return false;
}
//------------------------------------------------------------------------
void CItem::UpdateMounted(float frameTime)
{
CheckViewChange();
if (CActor *pActor = GetOwnerActor())
{
SMovementState info;
IMovementController* pMC = pActor->GetMovementController();
pMC->GetMovementState(info);
Matrix34 tm = Matrix33::CreateRotationVDir(info.aimDirection.GetNormalized());
Vec3 vGunXAxis = tm.GetColumn0();
UpdateIKMounted(pActor, vGunXAxis*0.1f);
}
RequireUpdate(eIUS_General);
}
//------------------------------------------------------------------------
void CItem::UpdateIKMounted(IActor* pActor, const Vec3& vGunXAxis)
{
if (SMountParams* pMountParams = m_sharedparams->pMountParams)
{
if (!pMountParams->left_hand_helper.empty() && !pMountParams->right_hand_helper.empty())
{
const Vec3 lhpos = GetSlotHelperPos(eIGS_FirstPerson, pMountParams->left_hand_helper.c_str(), true);
const Vec3 rhpos = GetSlotHelperPos(eIGS_FirstPerson, pMountParams->right_hand_helper.c_str(), true);
pActor->SetIKPos("leftArm", lhpos - vGunXAxis, 1);
pActor->SetIKPos("rightArm", rhpos + vGunXAxis, 1);
//gEnv->pRenderer->GetIRenderAuxGeom()->DrawSphere(lhpos, 0.075f, ColorB(255, 255, 255, 255));
//gEnv->pRenderer->GetIRenderAuxGeom()->DrawSphere(rhpos, 0.075f, ColorB(128, 128, 128, 255));
}
}
}
//------------------------------------------------------------------------
//------------------------------------------------------------------------
void CItem::CheckViewChange()
{
bool firstPerson = IsOwnerFP();
if (m_stats.mounted)
{
if (firstPerson!=m_stats.fp)
{
if (firstPerson)
OnEnterFirstPerson();
else
OnEnterThirdPerson();
//else if (!fp)
// AttachArms(false, false);
}
m_stats.fp = firstPerson;
return;
}
if (firstPerson)
{
if (!m_stats.fp || !(m_stats.viewmode&eIVM_FirstPerson))
OnEnterFirstPerson();
m_stats.fp = true;
}
else
{
if (m_stats.fp || !(m_stats.viewmode&eIVM_ThirdPerson))
OnEnterThirdPerson();
m_stats.fp = false;
}
}
//------------------------------------------------------------------------
void CItem::SetViewMode(int mode)
{
m_stats.viewmode = mode;
const int numAccessories = m_accessories.size();
for (int i = 0; i < numAccessories; i++)
{
if (CItem* pItem = static_cast<CItem*>(m_pGameFramework->GetIItemSystem()->GetItem(m_accessories[i].accessoryId)))
{
pItem->SetViewMode(mode);
}
}
if (mode & eIVM_FirstPerson)
{
SetHand(m_stats.hand);
if (m_parentId)
{
DrawSlot(eIGS_FirstPerson, false, false);
}
else if (IsAttachedToBack())
{
//--- Remove back attachments on switch to 1P
AttachToBack(false);
}
else if (IsAttachedToHand())
{
//--- Reattach to hand to switch model & binding style
AttachToHand(true);
}
}
else
{
SetGeometry(eIGS_FirstPerson, 0);
}
if (mode & eIVM_ThirdPerson)
{
//--- Reattach to hand to switch model & binding style
if (IsAttachedToHand())
AttachToHand(true);
DrawSlot(eIGS_ThirdPerson, (m_stats.attachment != eIA_WeaponCharacter));
if (!m_stats.mounted)
CopyRenderFlags(GetOwner());
}
else
{
DrawSlot(eIGS_ThirdPerson, false);
DrawSlot(eIGS_ThirdPersonAux, false);
}
AttachToShadowHand((mode&eIVM_FirstPerson) != 0);
}
//-----------------------------------------------------------------------
void CItem::AttachToShadowHand( bool attach )
{
if (m_stats.mounted)
return;
//--- Shadow character for FP mode
CActor *pOwner = GetOwnerActor();
ICharacterInstance *pOwnerShadowCharacter = NULL;
if (pOwner)
{
if (pOwner->IsPlayer())
{
CPlayer *ownerPlayer = (CPlayer*)pOwner;
pOwnerShadowCharacter = ownerPlayer->GetShadowCharacter();
}
}
else
{
IEntity* pEntity = gEnv->pEntitySystem->GetEntity(m_owner.GetId());
if (pEntity)
{
CReplayActor* pReplayActor = CReplayActor::GetReplayActor(pEntity);
if (pReplayActor)
{
pOwnerShadowCharacter = pReplayActor->GetShadowCharacter();
}
}
}
if (pOwnerShadowCharacter == NULL)
return;
bool showShadowChar = g_pGameCVars->g_showShadowChar != 0;
IAttachment *pAttachment = pOwnerShadowCharacter->GetIAttachmentManager()->GetInterfaceByName(m_sharedparams->params.attachment[m_stats.hand].c_str());
if (pAttachment != NULL)
{
if (attach)
{
if (ICharacterInstance *pTPChar = GetEntity()->GetCharacter(eIGS_ThirdPerson))
{
CSKELAttachment *pChrAttachment = new CSKELAttachment();
pChrAttachment->m_pCharInstance = pTPChar;
pAttachment->AddBinding(pChrAttachment);
pAttachment->HideAttachment(!showShadowChar);
pAttachment->HideInShadow(0);
}
else if(IStatObj* pTPObject = GetEntity()->GetStatObj(eIGS_ThirdPerson))
{
CCGFAttachment* pCGFAttachment = new CCGFAttachment();
pCGFAttachment->pObj = pTPObject;
pAttachment->AddBinding(pCGFAttachment);
pAttachment->HideAttachment(!showShadowChar);
pAttachment->HideInShadow(0);
}
}
else
{
if (m_stats.attachment == eIA_WeaponCharacter)
{
IAttachment *pAttachmentWeapon = GetOwnerAttachmentManager()->GetInterfaceByName(m_sharedparams->params.attachment[m_stats.hand].c_str());
if (pAttachmentWeapon)
pAttachmentWeapon->HideInShadow(false);
}
IAttachmentObject *pAttachmentObject = pAttachment->GetIAttachmentObject();
if (pAttachmentObject)
{
bool isThisBinding = false;
if (ICharacterInstance *pTPChar = GetEntity()->GetCharacter(eIGS_ThirdPerson))
{
isThisBinding = (pTPChar == pAttachmentObject->GetICharacterInstance());
}
else if (IStatObj* pTPObject = GetEntity()->GetStatObj(eIGS_ThirdPerson))
{
isThisBinding = (pTPObject == pAttachmentObject->GetIStatObj());
}
if (isThisBinding)
{
pAttachment->ClearBinding();
}
}
}
}
}
//------------------------------------------------------------------------
void CItem::CopyRenderFlags(IEntity *pOwner)
{
if (!pOwner || !GetRenderProxy())
return;
{
IEntityRender *pOwnerRenderProxy = (IEntityRender *)pOwner->GetRenderInterface();
IRenderNode *pOwnerRenderNode = pOwnerRenderProxy?pOwnerRenderProxy->GetRenderNode():NULL;
if (pOwnerRenderNode)
{
int viewDistRatio = pOwnerRenderNode->GetViewDistRatio();
int lodRatio = pOwnerRenderNode->GetLodRatio();
if (!gEnv->bMultiplayer)
{
viewDistRatio = (int)((float)viewDistRatio * g_pGameCVars->g_itemsViewDistanceRatioScale);
lodRatio = (int)((float)lodRatio * g_pGameCVars->g_itemsLodRatioScale);
}
GetEntity()->SetViewDistRatio(viewDistRatio);
GetEntity()->SetLodRatio(lodRatio);
uint32 flags = pOwner->GetFlags()&(ENTITY_FLAG_CASTSHADOW);
uint32 mflags = GetEntity()->GetFlags()&(~(ENTITY_FLAG_CASTSHADOW));
GetEntity()->SetFlags(mflags|flags);
}
}
}
|
liasica/Karabiner_CN | Tests/kext/FlagStatus/test.cpp | #include <ostream>
#include <gtest/gtest.h>
#include "Config.hpp"
#include "FlagStatus.hpp"
#include "KeyCode.hpp"
#include "KeyCodeModifierFlagPairs.hpp"
using namespace org_pqrs_Karabiner;
Config config;
std::ostream& operator<<(std::ostream& os, const EventType& v) { return os << v.get(); }
std::ostream& operator<<(std::ostream& os, const KeyboardType& v) { return os << v.get(); }
std::ostream& operator<<(std::ostream& os, const ModifierFlag& v) { return os << v.getRawBits(); }
std::ostream& operator<<(std::ostream& os, const Flags& v) { return os << v.get(); }
std::ostream& operator<<(std::ostream& os, const KeyCode& v) { return os << v.get(); }
std::ostream& operator<<(std::ostream& os, const ConsumerKeyCode& v) { return os << v.get(); }
std::ostream& operator<<(std::ostream& os, const PointingButton& v) { return os << v.get(); }
std::ostream& operator<<(std::ostream& os, const Buttons& v) { return os << v.get(); }
Flags operator|(ModifierFlag lhs, ModifierFlag rhs) { return Flags(lhs.getRawBits() | rhs.getRawBits()); }
TEST(Generic, setUp) {
KeyCodeModifierFlagPairs::clearVirtualModifiers();
}
TEST(FlagStatus, makeFlags) {
FlagStatus flagStatus;
EXPECT_EQ(Flags(), flagStatus.makeFlags());
flagStatus.set();
EXPECT_EQ(Flags(), flagStatus.makeFlags());
flagStatus.set(KeyCode::A, Flags(0));
EXPECT_EQ(Flags(), flagStatus.makeFlags());
// down SHIFT_L
flagStatus.set(KeyCode::SHIFT_L, Flags(ModifierFlag::SHIFT_L));
EXPECT_EQ(Flags(ModifierFlag::SHIFT_L), flagStatus.makeFlags());
// no effect with ModifierFlag::NONE
flagStatus.set(KeyCode::A, Flags(ModifierFlag::NONE));
EXPECT_EQ(Flags(ModifierFlag::SHIFT_L), flagStatus.makeFlags());
// down CONTROL_
flagStatus.set(KeyCode::CONTROL_L, ModifierFlag::CONTROL_L | ModifierFlag::SHIFT_L);
EXPECT_EQ(Flags(ModifierFlag::SHIFT_L | ModifierFlag::CONTROL_L), flagStatus.makeFlags());
// down A
flagStatus.set(KeyCode::A, ModifierFlag::CONTROL_L | ModifierFlag::SHIFT_L);
EXPECT_EQ(Flags(ModifierFlag::SHIFT_L | ModifierFlag::CONTROL_L), flagStatus.makeFlags());
// up SHIFT_L
flagStatus.set(KeyCode::SHIFT_L, Flags(ModifierFlag::CONTROL_L));
EXPECT_EQ(Flags(ModifierFlag::CONTROL_L), flagStatus.makeFlags());
// up CONTROL_L
flagStatus.set(KeyCode::CONTROL_L, Flags(0));
EXPECT_EQ(Flags(), flagStatus.makeFlags());
// All flags
flagStatus.reset();
flagStatus.set(KeyCode::CAPSLOCK, Flags(ModifierFlag::CAPSLOCK));
EXPECT_EQ(Flags(ModifierFlag::CAPSLOCK), flagStatus.makeFlags());
flagStatus.set(KeyCode::CAPSLOCK, Flags(0));
EXPECT_EQ(Flags(0), flagStatus.makeFlags());
flagStatus.reset();
flagStatus.set(KeyCode::SHIFT_L, Flags(ModifierFlag::SHIFT_L));
EXPECT_EQ(Flags(ModifierFlag::SHIFT_L), flagStatus.makeFlags());
flagStatus.reset();
flagStatus.set(KeyCode::SHIFT_R, Flags(ModifierFlag::SHIFT_R));
EXPECT_EQ(Flags(ModifierFlag::SHIFT_R), flagStatus.makeFlags());
flagStatus.reset();
flagStatus.set(KeyCode::CONTROL_L, Flags(ModifierFlag::CONTROL_L));
EXPECT_EQ(Flags(ModifierFlag::CONTROL_L), flagStatus.makeFlags());
flagStatus.reset();
flagStatus.set(KeyCode::CONTROL_R, Flags(ModifierFlag::CONTROL_R));
EXPECT_EQ(Flags(ModifierFlag::CONTROL_R), flagStatus.makeFlags());
flagStatus.reset();
flagStatus.set(KeyCode::OPTION_L, Flags(ModifierFlag::OPTION_L));
EXPECT_EQ(Flags(ModifierFlag::OPTION_L), flagStatus.makeFlags());
flagStatus.reset();
flagStatus.set(KeyCode::OPTION_R, Flags(ModifierFlag::OPTION_R));
EXPECT_EQ(Flags(ModifierFlag::OPTION_R), flagStatus.makeFlags());
flagStatus.reset();
flagStatus.set(KeyCode::COMMAND_L, Flags(ModifierFlag::COMMAND_L));
EXPECT_EQ(Flags(ModifierFlag::COMMAND_L), flagStatus.makeFlags());
flagStatus.reset();
flagStatus.set(KeyCode::COMMAND_R, Flags(ModifierFlag::COMMAND_R));
EXPECT_EQ(Flags(ModifierFlag::COMMAND_R), flagStatus.makeFlags());
flagStatus.reset();
flagStatus.set(KeyCode::FN, Flags(ModifierFlag::FN));
EXPECT_EQ(Flags(ModifierFlag::FN), flagStatus.makeFlags());
}
TEST(FlagStatus, getFlag) {
FlagStatus flagStatus;
EXPECT_EQ(ModifierFlag::CAPSLOCK, flagStatus.getFlag(0));
}
TEST(FlagStatus, increase) {
{
FlagStatus flagStatus;
// Do nothing with ModifierFlag::NONE.
flagStatus.increase(ModifierFlag::NONE);
EXPECT_EQ(Flags(0), flagStatus.makeFlags());
flagStatus.increase(ModifierFlag::SHIFT_L);
EXPECT_EQ(Flags(ModifierFlag::SHIFT_L), flagStatus.makeFlags());
{
Vector_ModifierFlag v;
v.push_back(ModifierFlag::COMMAND_L);
v.push_back(ModifierFlag::CONTROL_L);
flagStatus.increase(v);
EXPECT_EQ(Flags(ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L | ModifierFlag::SHIFT_L), flagStatus.makeFlags());
}
flagStatus.increase(ModifierFlag::NONE);
EXPECT_EQ(Flags(ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L | ModifierFlag::SHIFT_L), flagStatus.makeFlags());
}
{
FlagStatus flagStatus;
Vector_ModifierFlag v;
v.push_back(ModifierFlag::COMMAND_L);
v.push_back(ModifierFlag::CONTROL_L);
flagStatus.increase(ModifierFlag::SHIFT_L, v);
EXPECT_EQ(Flags(ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L | ModifierFlag::SHIFT_L), flagStatus.makeFlags());
}
{
FlagStatus flagStatus;
Vector_ModifierFlag v;
v.push_back(ModifierFlag::COMMAND_L);
v.push_back(ModifierFlag::CONTROL_L);
flagStatus.increase(ModifierFlag::COMMAND_L, v);
EXPECT_EQ(Flags(ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L), flagStatus.makeFlags());
flagStatus.decrease(v);
EXPECT_EQ(Flags(0), flagStatus.makeFlags());
}
}
TEST(FlagStatus, decrease) {
FlagStatus flagStatus;
{
Vector_ModifierFlag v;
v.push_back(ModifierFlag::COMMAND_L);
v.push_back(ModifierFlag::CONTROL_L);
flagStatus.increase(v);
EXPECT_EQ(Flags(ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L), flagStatus.makeFlags());
}
flagStatus.decrease(ModifierFlag::CONTROL_L);
EXPECT_EQ(Flags(ModifierFlag::COMMAND_L), flagStatus.makeFlags());
}
TEST(FlagStatus, temporary_increase) {
FlagStatus flagStatus;
// Do nothing with ModifierFlag::NONE.
flagStatus.temporary_increase(ModifierFlag::NONE);
EXPECT_EQ(Flags(0), flagStatus.makeFlags());
{
Vector_ModifierFlag v;
v.push_back(ModifierFlag::COMMAND_L);
v.push_back(ModifierFlag::CONTROL_L);
flagStatus.increase(v);
EXPECT_EQ(Flags(ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L), flagStatus.makeFlags());
}
flagStatus.temporary_increase(ModifierFlag::OPTION_L);
EXPECT_EQ(Flags(ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L | ModifierFlag::OPTION_L), flagStatus.makeFlags());
// temporary_increase will reset by flagStatus.set
flagStatus.set(KeyCode::COMMAND_L, Flags(ModifierFlag::COMMAND_L));
EXPECT_EQ(Flags(ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L), flagStatus.makeFlags());
}
TEST(FlagStatus, temporary_decrease) {
FlagStatus flagStatus;
{
Vector_ModifierFlag v;
v.push_back(ModifierFlag::COMMAND_L);
v.push_back(ModifierFlag::CONTROL_L);
flagStatus.increase(v);
EXPECT_EQ(Flags(ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L), flagStatus.makeFlags());
}
flagStatus.temporary_decrease(ModifierFlag::CONTROL_L);
EXPECT_EQ(Flags(ModifierFlag::COMMAND_L), flagStatus.makeFlags());
// temporary_increase will reset by flagStatus.set
flagStatus.set(KeyCode::COMMAND_L, Flags(ModifierFlag::COMMAND_L));
EXPECT_EQ(Flags(ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L), flagStatus.makeFlags());
}
TEST(FlagStatus, lock_increase) {
FlagStatus flagStatus;
// Do nothing with ModifierFlag::NONE.
flagStatus.lock_increase(ModifierFlag::NONE);
EXPECT_EQ(Flags(0), flagStatus.makeFlags());
flagStatus.lock_increase(ModifierFlag::COMMAND_L);
EXPECT_EQ(Flags(ModifierFlag::COMMAND_L), flagStatus.makeFlags());
// lock don't cancel by reset & set.
flagStatus.reset();
flagStatus.set(KeyCode::A, Flags(0));
EXPECT_EQ(Flags(ModifierFlag::COMMAND_L), flagStatus.makeFlags());
flagStatus.lock_decrease(ModifierFlag::COMMAND_L);
EXPECT_EQ(Flags(), flagStatus.makeFlags());
}
TEST(FlagStatus, negative_lock_increase) {
FlagStatus flagStatus;
// ----------------------------------------
flagStatus.negative_lock_increase(ModifierFlag::COMMAND_L);
EXPECT_EQ(Flags(0), flagStatus.makeFlags());
flagStatus.increase(ModifierFlag::COMMAND_L);
EXPECT_EQ(Flags(0), flagStatus.makeFlags());
flagStatus.increase(ModifierFlag::COMMAND_L);
EXPECT_EQ(Flags(ModifierFlag::COMMAND_L), flagStatus.makeFlags());
// ----------------------------------------
// lock don't cancel by reset & set.
flagStatus.reset();
flagStatus.set(KeyCode::A, Flags(0));
EXPECT_EQ(Flags(0), flagStatus.makeFlags());
flagStatus.increase(ModifierFlag::COMMAND_L);
EXPECT_EQ(Flags(0), flagStatus.makeFlags());
flagStatus.increase(ModifierFlag::COMMAND_L);
EXPECT_EQ(Flags(ModifierFlag::COMMAND_L), flagStatus.makeFlags());
// ----------------------------------------
flagStatus.reset();
flagStatus.negative_lock_decrease(ModifierFlag::COMMAND_L);
EXPECT_EQ(Flags(0), flagStatus.makeFlags());
flagStatus.increase(ModifierFlag::COMMAND_L);
EXPECT_EQ(Flags(ModifierFlag::COMMAND_L), flagStatus.makeFlags());
}
TEST(FlagStatus, lock_toggle) {
FlagStatus flagStatus;
flagStatus.lock_increase(ModifierFlag::COMMAND_L);
EXPECT_EQ(Flags(ModifierFlag::COMMAND_L), flagStatus.makeFlags());
flagStatus.lock_toggle(ModifierFlag::COMMAND_L);
EXPECT_EQ(Flags(0), flagStatus.makeFlags());
flagStatus.lock_toggle(ModifierFlag::COMMAND_L);
EXPECT_EQ(Flags(ModifierFlag::COMMAND_L), flagStatus.makeFlags());
}
TEST(FlagStatus, lock_clear) {
FlagStatus flagStatus;
{
Vector_ModifierFlag v;
v.push_back(ModifierFlag::COMMAND_L);
v.push_back(ModifierFlag::FN);
v.push_back(ModifierFlag::SHIFT_L);
flagStatus.lock_increase(v);
EXPECT_EQ(ModifierFlag::COMMAND_L | ModifierFlag::FN | ModifierFlag::SHIFT_L, flagStatus.makeFlags());
}
{
flagStatus.increase(ModifierFlag::CAPSLOCK);
EXPECT_EQ(ModifierFlag::CAPSLOCK | ModifierFlag::COMMAND_L | ModifierFlag::FN | ModifierFlag::SHIFT_L,
flagStatus.makeFlags());
}
flagStatus.lock_clear();
EXPECT_EQ(Flags(0), flagStatus.makeFlags());
}
TEST(FlagStatus, negative_lock_clear) {
FlagStatus flagStatus;
{
Vector_ModifierFlag v;
v.push_back(ModifierFlag::COMMAND_L);
v.push_back(ModifierFlag::FN);
v.push_back(ModifierFlag::SHIFT_L);
flagStatus.negative_lock_increase(v);
EXPECT_EQ(Flags(0), flagStatus.makeFlags());
flagStatus.increase(v);
EXPECT_EQ(Flags(0), flagStatus.makeFlags());
flagStatus.increase(v);
EXPECT_EQ(ModifierFlag::COMMAND_L | ModifierFlag::FN | ModifierFlag::SHIFT_L, flagStatus.makeFlags());
flagStatus.reset();
EXPECT_EQ(Flags(0), flagStatus.makeFlags());
flagStatus.increase(v);
EXPECT_EQ(Flags(0), flagStatus.makeFlags());
flagStatus.negative_lock_clear();
EXPECT_EQ(ModifierFlag::COMMAND_L | ModifierFlag::FN | ModifierFlag::SHIFT_L, flagStatus.makeFlags());
}
}
TEST(FlagStatus, sticky_increase) {
FlagStatus flagStatus;
// Do nothing with ModifierFlag::NONE.
flagStatus.sticky_increase(ModifierFlag::NONE);
EXPECT_EQ(Flags(0), flagStatus.makeFlags());
{
Vector_ModifierFlag v;
v.push_back(ModifierFlag::COMMAND_L);
v.push_back(ModifierFlag::FN);
flagStatus.sticky_increase(v);
EXPECT_EQ(Flags(ModifierFlag::COMMAND_L | ModifierFlag::FN), flagStatus.makeFlags());
}
flagStatus.sticky_decrease(ModifierFlag::COMMAND_L);
EXPECT_EQ(Flags(ModifierFlag::FN), flagStatus.makeFlags());
}
TEST(FlagStatus, sticky_toggle) {
FlagStatus flagStatus;
flagStatus.sticky_increase(ModifierFlag::COMMAND_L);
EXPECT_EQ(Flags(ModifierFlag::COMMAND_L), flagStatus.makeFlags());
flagStatus.sticky_toggle(ModifierFlag::COMMAND_L);
EXPECT_EQ(Flags(0), flagStatus.makeFlags());
flagStatus.sticky_toggle(ModifierFlag::COMMAND_L);
EXPECT_EQ(Flags(ModifierFlag::COMMAND_L), flagStatus.makeFlags());
}
TEST(FlagStatus, sticky_clear) {
FlagStatus flagStatus;
{
Vector_ModifierFlag v;
v.push_back(ModifierFlag::COMMAND_L);
v.push_back(ModifierFlag::FN);
v.push_back(ModifierFlag::SHIFT_L);
flagStatus.sticky_increase(v);
EXPECT_EQ(ModifierFlag::COMMAND_L | ModifierFlag::FN | ModifierFlag::SHIFT_L, flagStatus.makeFlags());
}
flagStatus.sticky_clear();
EXPECT_EQ(Flags(0), flagStatus.makeFlags());
}
TEST(FlagStatus, lazy_increase) {
FlagStatus flagStatus;
// +1 (total 1)
flagStatus.lazy_increase(ModifierFlag::SHIFT_L);
EXPECT_EQ(Flags(0), flagStatus.makeFlags());
// +0 (total 1)
flagStatus.lazy_enable();
EXPECT_EQ(Flags(ModifierFlag::SHIFT_L), flagStatus.makeFlags());
// -1 (total 0)
flagStatus.lazy_decrease(ModifierFlag::SHIFT_L);
EXPECT_EQ(Flags(0), flagStatus.makeFlags());
// +1 (total 1)
flagStatus.lazy_increase(ModifierFlag::SHIFT_L);
EXPECT_EQ(Flags(ModifierFlag::SHIFT_L), flagStatus.makeFlags());
flagStatus.lazy_disable_if_off();
EXPECT_EQ(Flags(ModifierFlag::SHIFT_L), flagStatus.makeFlags());
// +2 (total 2)
flagStatus.lazy_increase(ModifierFlag::SHIFT_L);
EXPECT_EQ(Flags(ModifierFlag::SHIFT_L), flagStatus.makeFlags());
// -1 (total 1)
flagStatus.lazy_decrease(ModifierFlag::SHIFT_L);
EXPECT_EQ(Flags(ModifierFlag::SHIFT_L), flagStatus.makeFlags());
// => 0 (lazy modifier is disabled when reset.)
flagStatus.reset();
// +1 (total 1)
flagStatus.lazy_increase(ModifierFlag::SHIFT_L);
EXPECT_EQ(Flags(0), flagStatus.makeFlags());
}
TEST(FlagStatus, CapsLock) {
FlagStatus flagStatus;
flagStatus.set(KeyCode::CAPSLOCK, Flags(ModifierFlag::CAPSLOCK));
EXPECT_EQ(Flags(ModifierFlag::CAPSLOCK), flagStatus.makeFlags());
flagStatus.reset();
flagStatus.set(KeyCode::A, Flags(ModifierFlag::CAPSLOCK));
EXPECT_EQ(Flags(ModifierFlag::CAPSLOCK), flagStatus.makeFlags());
// from other keyboard
flagStatus.set(KeyCode::A, Flags(0));
EXPECT_EQ(Flags(ModifierFlag::CAPSLOCK), flagStatus.makeFlags());
flagStatus.set(KeyCode::A, Flags(ModifierFlag::CAPSLOCK));
EXPECT_EQ(Flags(ModifierFlag::CAPSLOCK), flagStatus.makeFlags());
// reset
flagStatus.set(KeyCode::CAPSLOCK, Flags(0));
EXPECT_EQ(Flags(), flagStatus.makeFlags());
// soft caps
flagStatus.lock_increase(ModifierFlag::CAPSLOCK);
flagStatus.set(KeyCode::A, Flags(0));
EXPECT_EQ(Flags(ModifierFlag::CAPSLOCK), flagStatus.makeFlags());
// soft caps will be canceled by hardware caps
flagStatus.set(KeyCode::CAPSLOCK, Flags(0));
EXPECT_EQ(Flags(0), flagStatus.makeFlags());
}
TEST(FlagStatus, isOn) {
{
FlagStatus flagStatus;
{
Vector_ModifierFlag modifierFlags;
EXPECT_TRUE(flagStatus.isOn(modifierFlags));
}
{
Vector_ModifierFlag modifierFlags;
modifierFlags.push_back(ModifierFlag(ModifierFlag::ZERO));
EXPECT_TRUE(flagStatus.isOn(modifierFlags));
}
{
Vector_ModifierFlag modifierFlags;
modifierFlags.push_back(ModifierFlag::NONE);
EXPECT_TRUE(flagStatus.isOn(modifierFlags));
}
{
Vector_ModifierFlag modifierFlags;
modifierFlags.push_back(ModifierFlag::NONE);
modifierFlags.push_back(ModifierFlag::ZERO);
EXPECT_TRUE(flagStatus.isOn(modifierFlags));
}
}
{
FlagStatus flagStatus;
flagStatus.increase(ModifierFlag::SHIFT_L);
{
Vector_ModifierFlag modifierFlags;
modifierFlags.push_back(ModifierFlag::SHIFT_L);
EXPECT_TRUE(flagStatus.isOn(modifierFlags));
}
{
Vector_ModifierFlag modifierFlags;
modifierFlags.push_back(ModifierFlag::SHIFT_L);
modifierFlags.push_back(ModifierFlag::NONE);
EXPECT_TRUE(flagStatus.isOn(modifierFlags));
}
{
Vector_ModifierFlag modifierFlags;
modifierFlags.push_back(ModifierFlag::SHIFT_R);
EXPECT_FALSE(flagStatus.isOn(modifierFlags));
}
{
Vector_ModifierFlag modifierFlags;
modifierFlags.push_back(ModifierFlag::SHIFT_L);
modifierFlags.push_back(ModifierFlag::ZERO);
EXPECT_TRUE(flagStatus.isOn(modifierFlags));
}
}
{
FlagStatus flagStatus;
flagStatus.increase(ModifierFlag::SHIFT_L);
flagStatus.increase(ModifierFlag::ZERO);
{
Vector_ModifierFlag modifierFlags;
modifierFlags.push_back(ModifierFlag::SHIFT_L);
EXPECT_TRUE(flagStatus.isOn(modifierFlags));
}
{
Vector_ModifierFlag modifierFlags;
modifierFlags.push_back(ModifierFlag::SHIFT_L);
modifierFlags.push_back(ModifierFlag::NONE);
EXPECT_TRUE(flagStatus.isOn(modifierFlags));
}
{
Vector_ModifierFlag modifierFlags;
modifierFlags.push_back(ModifierFlag::SHIFT_R);
EXPECT_FALSE(flagStatus.isOn(modifierFlags));
}
{
Vector_ModifierFlag modifierFlags;
modifierFlags.push_back(ModifierFlag::SHIFT_L);
modifierFlags.push_back(ModifierFlag::ZERO);
EXPECT_TRUE(flagStatus.isOn(modifierFlags));
}
{
Vector_ModifierFlag modifierFlags;
modifierFlags.push_back(ModifierFlag::SHIFT_L);
modifierFlags.push_back(ModifierFlag::ZERO);
modifierFlags.push_back(ModifierFlag::NONE);
EXPECT_TRUE(flagStatus.isOn(modifierFlags));
}
}
{
FlagStatus flagStatus;
flagStatus.increase(ModifierFlag::SHIFT_L);
flagStatus.increase(ModifierFlag::CONTROL_R);
flagStatus.increase(ModifierFlag::COMMAND_R);
{
Vector_ModifierFlag modifierFlags;
modifierFlags.push_back(ModifierFlag::SHIFT_L);
EXPECT_TRUE(flagStatus.isOn(modifierFlags));
}
{
Vector_ModifierFlag modifierFlags;
modifierFlags.push_back(ModifierFlag::SHIFT_L);
modifierFlags.push_back(ModifierFlag::NONE);
EXPECT_FALSE(flagStatus.isOn(modifierFlags));
}
{
Vector_ModifierFlag modifierFlags;
modifierFlags.push_back(ModifierFlag::SHIFT_R);
EXPECT_FALSE(flagStatus.isOn(modifierFlags));
}
{
Vector_ModifierFlag modifierFlags;
modifierFlags.push_back(ModifierFlag::SHIFT_L);
modifierFlags.push_back(ModifierFlag::CONTROL_R);
modifierFlags.push_back(ModifierFlag::COMMAND_R);
modifierFlags.push_back(ModifierFlag::NONE);
EXPECT_TRUE(flagStatus.isOn(modifierFlags));
}
}
}
TEST(FlagStatus, isLocked) {
{
FlagStatus flagStatus;
{
Vector_ModifierFlag modifierFlags;
EXPECT_TRUE(flagStatus.isLocked(modifierFlags));
}
{
Vector_ModifierFlag modifierFlags;
modifierFlags.push_back(ModifierFlag(ModifierFlag::ZERO));
EXPECT_TRUE(flagStatus.isLocked(modifierFlags));
}
{
Vector_ModifierFlag modifierFlags;
modifierFlags.push_back(ModifierFlag::NONE);
EXPECT_TRUE(flagStatus.isLocked(modifierFlags));
}
{
Vector_ModifierFlag modifierFlags;
modifierFlags.push_back(ModifierFlag::NONE);
modifierFlags.push_back(ModifierFlag::ZERO);
EXPECT_TRUE(flagStatus.isLocked(modifierFlags));
}
{
Vector_ModifierFlag modifierFlags;
modifierFlags.push_back(ModifierFlag::SHIFT_L);
EXPECT_FALSE(flagStatus.isLocked(modifierFlags));
flagStatus.increase(ModifierFlag::SHIFT_L);
EXPECT_FALSE(flagStatus.isLocked(modifierFlags));
flagStatus.lock_increase(ModifierFlag::SHIFT_L);
EXPECT_TRUE(flagStatus.isLocked(modifierFlags));
}
}
}
TEST(FlagStatus, isStuck) {
{
FlagStatus flagStatus;
{
Vector_ModifierFlag modifierFlags;
EXPECT_TRUE(flagStatus.isStuck(modifierFlags));
}
{
Vector_ModifierFlag modifierFlags;
modifierFlags.push_back(ModifierFlag(ModifierFlag::ZERO));
EXPECT_TRUE(flagStatus.isStuck(modifierFlags));
}
{
Vector_ModifierFlag modifierFlags;
modifierFlags.push_back(ModifierFlag::NONE);
EXPECT_TRUE(flagStatus.isStuck(modifierFlags));
}
{
Vector_ModifierFlag modifierFlags;
modifierFlags.push_back(ModifierFlag::NONE);
modifierFlags.push_back(ModifierFlag::ZERO);
EXPECT_TRUE(flagStatus.isStuck(modifierFlags));
}
{
Vector_ModifierFlag modifierFlags;
modifierFlags.push_back(ModifierFlag::SHIFT_L);
EXPECT_FALSE(flagStatus.isStuck(modifierFlags));
flagStatus.increase(ModifierFlag::SHIFT_L);
EXPECT_FALSE(flagStatus.isStuck(modifierFlags));
flagStatus.sticky_increase(ModifierFlag::SHIFT_L);
EXPECT_TRUE(flagStatus.isStuck(modifierFlags));
flagStatus.sticky_clear();
EXPECT_FALSE(flagStatus.isStuck(modifierFlags));
}
}
}
TEST(FlagStatus, subtract) {
FlagStatus flagStatus1;
FlagStatus flagStatus2;
flagStatus1.increase(ModifierFlag::CONTROL_L);
flagStatus1.increase(ModifierFlag::OPTION_L);
flagStatus1.increase(ModifierFlag::SHIFT_L);
flagStatus1.increase(ModifierFlag::SHIFT_L);
flagStatus1.decrease(ModifierFlag::COMMAND_R);
flagStatus2.increase(ModifierFlag::CONTROL_L);
flagStatus2.increase(ModifierFlag::FN);
Vector_ModifierFlag v;
flagStatus1.subtract(flagStatus2, v);
EXPECT_EQ(3, v.size());
EXPECT_EQ(ModifierFlag::OPTION_L, v[0]);
EXPECT_EQ(ModifierFlag::SHIFT_L, v[1]);
EXPECT_EQ(ModifierFlag::SHIFT_L, v[2]);
flagStatus2.subtract(flagStatus1, v);
EXPECT_EQ(2, v.size());
EXPECT_EQ(ModifierFlag::COMMAND_R, v[0]);
EXPECT_EQ(ModifierFlag::FN, v[1]);
}
TEST(FlagStatus, ScopedSetter) {
FlagStatus flagStatus1;
FlagStatus flagStatus2;
flagStatus1.increase(ModifierFlag::CONTROL_L);
flagStatus1.increase(ModifierFlag::OPTION_L);
flagStatus1.increase(ModifierFlag::SHIFT_L);
flagStatus1.increase(ModifierFlag::SHIFT_L);
flagStatus1.decrease(ModifierFlag::COMMAND_R);
flagStatus2.increase(ModifierFlag::COMMAND_R);
flagStatus2.increase(ModifierFlag::CONTROL_L);
flagStatus2.increase(ModifierFlag::FN);
{
EXPECT_EQ(flagStatus1.makeFlags(),
ModifierFlag::CONTROL_L | ModifierFlag::OPTION_L | ModifierFlag::SHIFT_L);
EXPECT_EQ(flagStatus2.makeFlags(),
ModifierFlag::COMMAND_R | ModifierFlag::CONTROL_L | ModifierFlag::FN);
{
FlagStatus::ScopedSetter scopedSetter(flagStatus1, flagStatus2);
EXPECT_EQ(flagStatus1.makeFlags(),
ModifierFlag::COMMAND_R | ModifierFlag::CONTROL_L | ModifierFlag::FN);
EXPECT_EQ(flagStatus2.makeFlags(),
ModifierFlag::COMMAND_R | ModifierFlag::CONTROL_L | ModifierFlag::FN);
}
EXPECT_EQ(flagStatus1.makeFlags(),
ModifierFlag::CONTROL_L | ModifierFlag::OPTION_L | ModifierFlag::SHIFT_L);
EXPECT_EQ(flagStatus2.makeFlags(),
ModifierFlag::COMMAND_R | ModifierFlag::CONTROL_L | ModifierFlag::FN);
}
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
htczion/Zion-SKR-SDK | ZionSkrSdk/src/main/java/com/htc/wallet/skrsdk/action/BackupFullAction.java | package com.htc.wallet.skrsdk.action;
import static com.htc.wallet.skrsdk.verification.VerificationConstants.ACTION_NOTIFY_BACKUP_FULL;
import static com.htc.wallet.skrsdk.verification.VerificationConstants.ACTION_TRIGGER_BROADCAST;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.ArrayMap;
import com.htc.wallet.skrsdk.crypto.ChecksumUtil;
import com.htc.wallet.skrsdk.crypto.util.VerificationUtil;
import com.htc.wallet.skrsdk.messaging.MessageConstants;
import com.htc.wallet.skrsdk.sqlite.entity.BackupSourceEntity;
import com.htc.wallet.skrsdk.sqlite.entity.BackupTargetEntity;
import com.htc.wallet.skrsdk.sqlite.entity.RestoreSourceEntity;
import com.htc.wallet.skrsdk.sqlite.entity.RestoreTargetEntity;
import com.htc.wallet.skrsdk.sqlite.listener.DatabaseCompleteListener;
import com.htc.wallet.skrsdk.sqlite.listener.LoadDataListener;
import com.htc.wallet.skrsdk.sqlite.util.BackupSourceUtil;
import com.htc.wallet.skrsdk.util.LogUtil;
import com.htc.wallet.skrsdk.util.PhoneUtil;
import java.util.Map;
public class BackupFullAction extends Action {
private static final String TAG = "BackupFullAction";
@Override
int getMessageTypeId() {
return MessageConstants.TYPE_BACKUP_FULL;
}
// Amy need to notify Bob that her backupTargets are full
@Override
public void sendInternal(
@NonNull final Context context,
@Nullable final String receiverFcmToken,
@Nullable final String receiverWhisperPub,
@Nullable final String receiverPushyToken,
@NonNull final Map<String, String> messages) {
final String myEmailHash = PhoneUtil.getSKREmailHash(context);
final String myUUID = PhoneUtil.getSKRID(context);
final String publicKey = messages.get(KEY_PUBLIC_KEY);
if (TextUtils.isEmpty(publicKey)) {
LogUtil.logError(
TAG,
"publicKey is null or empty",
new IllegalStateException("publicKey is null or empty"));
return;
}
VerificationUtil verificationUtil = new VerificationUtil(false);
final String encUUID = verificationUtil.encryptMessage(myUUID, publicKey);
if (TextUtils.isEmpty(encUUID)) {
LogUtil.logError(
TAG,
"encUUID is null or empty",
new IllegalStateException("encUUID is null or empty"));
return;
}
Map<String, String> msgToSend = new ArrayMap<>();
msgToSend.put(KEY_EMAIL_HASH, myEmailHash);
msgToSend.put(KEY_ENCRYPTED_UUID, encUUID);
msgToSend.put(KEY_BACKUP_FULL, MSG_BACKUP_FULL);
sendMessage(context, receiverFcmToken, receiverWhisperPub, receiverPushyToken, msgToSend);
Intent intentToNotifyUpdateUI = new Intent(ACTION_TRIGGER_BROADCAST);
LocalBroadcastManager.getInstance(context).sendBroadcast(intentToNotifyUpdateUI);
}
// Bob will receive a notification (a dialog show up) about Amy's full info
@Override
void onReceiveInternal(
@NonNull final Context context,
@Nullable final String senderFcmToken,
@Nullable final String myFcmToken,
@Nullable final String senderWhisperPub,
@Nullable final String myWhisperPub,
@Nullable final String senderPushyToken,
@Nullable final String myPushyToken,
@NonNull final Map<String, String> messages) {
String backupFull = messages.get(KEY_BACKUP_FULL);
if (!backupFull.equals(MSG_BACKUP_FULL)) {
LogUtil.logError(TAG, "backupFull message doesn't match");
return;
}
final String emailHash = messages.get(KEY_EMAIL_HASH);
if (TextUtils.isEmpty(emailHash)) {
LogUtil.logError(
TAG,
"emailHash is null or empty",
new IllegalStateException("emailHash is null or empty"));
return;
}
VerificationUtil verificationUtil = new VerificationUtil(true);
String uuid = messages.get(KEY_ENCRYPTED_UUID);
if (TextUtils.isEmpty(uuid)) {
LogUtil.logError(
TAG,
"Encrypted UUID is null or empty",
new IllegalStateException("Encrypted UUID is null or empty"));
return;
} else {
uuid = verificationUtil.decryptMessage(uuid);
if (TextUtils.isEmpty(uuid)) {
LogUtil.logError(
TAG,
"UUID is null or empty",
new IllegalStateException("UUID is null or empty"));
return;
}
}
final String uuidHash = ChecksumUtil.generateChecksum(uuid);
if (TextUtils.isEmpty(uuidHash)) {
LogUtil.logError(
TAG,
"UUIDHash is null or empty",
new IllegalStateException("UUIDHash is null or empty"));
return;
}
BackupSourceUtil.getWithUUIDHash(
context,
emailHash,
uuidHash,
new LoadDataListener() {
@Override
public void onLoadFinished(
BackupSourceEntity backupSourceEntity,
BackupTargetEntity backupTargetEntity,
RestoreSourceEntity restoreSourceEntity,
RestoreTargetEntity restoreTargetEntity) {
if (backupSourceEntity == null) {
LogUtil.logError(
TAG,
"backupSource is null",
new IllegalStateException("backupSource is null"));
return;
}
LogUtil.logDebug(
TAG,
"Update the status of "
+ backupSourceEntity.getName()
+ "'s backupSource to BACKUP_SOURCE_STATUS_FULL");
backupSourceEntity.updateStatusToFull();
BackupSourceUtil.update(
context,
backupSourceEntity,
new DatabaseCompleteListener() {
@Override
public void onComplete() {
Intent intentNotifyFull =
new Intent(ACTION_NOTIFY_BACKUP_FULL);
intentNotifyFull.putExtra(KEY_EMAIL_HASH, emailHash);
intentNotifyFull.putExtra(KEY_UUID_HASH, uuidHash);
LocalBroadcastManager.getInstance(context)
.sendBroadcast(intentNotifyFull);
}
@Override
public void onError(Exception exception) {
LogUtil.logError(TAG, "update error, e= " + exception);
}
});
}
});
}
}
|
datafibers/Leetcode_Practice | src/main/java/com/fishercoder/solutions/_216.java | <filename>src/main/java/com/fishercoder/solutions/_216.java
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.List;
/**
* 216. Combination Sum III
*
* Find all possible combinations of k numbers that add up to a number n,
* given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.
Example 1:
Input: k = 3, n = 7
Output: [[1,2,4]]
Example 2:
Input: k = 3, n = 9
Output: [[1,2,6], [1,3,5], [2,3,4]]
*/
public class _216 {
public static class Solution1 {
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> result = new ArrayList();
int[] nums = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9};
backtracking(k, n, nums, 0, new ArrayList(), result);
return result;
}
void backtracking(int k, int n, int[] nums, int start, List<Integer> curr, List<List<Integer>> result) {
if (n > 0) {
for (int i = start; i < nums.length; i++) {
curr.add(nums[i]);
backtracking(k, n - nums[i], nums, i + 1, curr, result);
curr.remove(curr.size() - 1);
}
} else if (n == 0 && curr.size() == k) {
result.add(new ArrayList(curr));
}
}
}
}
|
allegro-actions/opbox-release-tools | compare-dependencies/new-dependencies-messages.js | <filename>compare-dependencies/new-dependencies-messages.js<gh_stars>0
const warningEmoji = ':warning:';
const npmLink = dependency => `[NPM](https://www.npmjs.com/package/${encodeURIComponent(dependency)})`;
const bundlephobiaLink = dependency => `[Bundlephobia](https://bundlephobia.com/package/${encodeURIComponent(dependency)})`;
function getLead(newDependencies) {
return newDependencies.length === 1
? `${warningEmoji} One new dependency was found!`
: `${warningEmoji} A couple of new dependencies are added by this PR!`;
}
function getSlackMessage(newDependencies) {
if (!newDependencies.length) {
return '';
}
return [
getLead(newDependencies),
...newDependencies.map(dependency => ` • ${dependency}`),
].join('\n');
}
function getCommentMessage(newDependencies) {
if (!newDependencies.length) {
return '';
}
return [
getLead(newDependencies),
...newDependencies.map(dependency => [
` * ${dependency}`,
`(${npmLink(dependency)} | ${bundlephobiaLink(dependency)})`,
].filter(Boolean).join(' ')),
].join('\n');
}
module.exports.getSlackMessage = getSlackMessage;
module.exports.getCommentMessage = getCommentMessage;
|
rayrobdod/fxfightstage | demo/src/main/java/name/rayrobdod/fightStage/previewer/PlayBattleAnimationEventHandler.java | /*
* Copyright 2018 <NAME>
*
* 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 name.rayrobdod.fightStage.previewer;
import java.util.List;
import java.util.function.DoubleSupplier;
import java.util.function.IntSupplier;
import java.util.function.Supplier;
import javafx.animation.Animation;
import javafx.beans.property.ObjectProperty;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Dimension2D;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import name.rayrobdod.fightStage.AggregateSideParams;
import name.rayrobdod.fightStage.BattleAnimation;
import name.rayrobdod.fightStage.NodeAnimationPair;
import name.rayrobdod.fightStage.SpellAnimationGroup;
import name.rayrobdod.fightStage.Strike;
import name.rayrobdod.fightStage.UnitAnimationGroup;
import name.rayrobdod.fightStage.background.Field;
/**
* Upon activation, plays a BattleAnimation based on the parameters in the provided StackPane
*/
final class PlayBattleAnimationEventHandler implements EventHandler<ActionEvent> {
private final StackPane gamePane;
private final ObjectProperty<Animation> currentAnimationProperty;
private final Supplier<UnitAnimationGroup> leftUnit;
private final Supplier<UnitAnimationGroup> rightUnit;
private final Supplier<SpellAnimationGroup> leftSpell;
private final Supplier<SpellAnimationGroup> rightSpell;
private final IntSupplier leftStartingHp;
private final IntSupplier rightStartingHp;
private final IntSupplier leftMaximumHp;
private final IntSupplier rightMaximumHp;
private final Supplier<List<Strike>> strikes;
private final DoubleSupplier distance;
public PlayBattleAnimationEventHandler(
StackPane gamePane
, ObjectProperty<Animation> currentAnimationProperty
, Supplier<UnitAnimationGroup> leftUnit
, Supplier<UnitAnimationGroup> rightUnit
, Supplier<SpellAnimationGroup> leftSpell
, Supplier<SpellAnimationGroup> rightSpell
, IntSupplier leftStartingHp
, IntSupplier rightStartingHp
, IntSupplier leftMaximumHp
, IntSupplier rightMaximumHp
, Supplier<List<Strike>> strikes
, DoubleSupplier distance
) {
this.gamePane = gamePane;
this.currentAnimationProperty = currentAnimationProperty;
this.leftUnit = leftUnit;
this.rightUnit = rightUnit;
this.leftSpell = leftSpell;
this.rightSpell = rightSpell;
this.leftStartingHp = leftStartingHp;
this.rightStartingHp = rightStartingHp;
this.leftMaximumHp = leftMaximumHp;
this.rightMaximumHp = rightMaximumHp;
this.strikes = strikes;
this.distance = distance;
}
public void handle(ActionEvent e) {
final NodeAnimationPair pair = BattleAnimation.buildAnimation(
Field::buildGroup,
new Dimension2D(gamePane.getWidth(), gamePane.getHeight()),
this.distance.getAsDouble(),
new AggregateSideParams(
leftUnit.get(), leftSpell.get(), Color.RED.darker(),
"Garnet", "Iron Thingy", new Circle(10),
leftMaximumHp.getAsInt(), leftStartingHp.getAsInt()
),
new AggregateSideParams(
rightUnit.get(), rightSpell.get(), Color.BLUE.darker(),
"ABCDEFGHIJKL", "ABCDEFGHIJKLMNOP", new Circle(10),
rightMaximumHp.getAsInt(), rightStartingHp.getAsInt()
),
strikes.get()
);
if (currentAnimationProperty.getValue() != null) {
currentAnimationProperty.getValue().getOnFinished().handle(null);
}
gamePane.getChildren().add(pair.node);
currentAnimationProperty.setValue(pair.animation);
pair.animation.setOnFinished(cleanUpPair(pair));
pair.animation.playFromStart();
}
private EventHandler<ActionEvent> cleanUpPair(final NodeAnimationPair pair) {
return new EventHandler<ActionEvent>() {
public void handle(ActionEvent ignored) {
gamePane.getChildren().remove(pair.node);
currentAnimationProperty.getValue().stop();
currentAnimationProperty.setValue(null);
}
};
}
}
|
jercas/offer66-leetcode-newcode | toTheMoon/leetcode_217_ContainsDuplicate.py | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 11 15:54:53 2019
@author: jercas
"""
"""
leetcode-217: 存在重复元素 EASY
'数组' '哈希表'
给定一个整数数组,判断是否存在重复元素。
如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。
PS: 不同于287寻找重复数,217中会出现负数,不可以用值匹配下标调换顺序的算法去解决,出现越界情况
"""
class Solution:
def containsDuplicate1(self, nums):
if len(set(nums)) < len(nums):
return True
return False
def containsDuplicate2(self, nums):
if len(nums) <2:
return False
hashT = {}
for ind, val in enumerate(nums):
if val in hashT:
return True
hashT[val] = ind
return False
if __name__ == "__main__":
Q1, Q2 = [1,2,3,1], [1,2,3,4]
A1, A2 = True, False
solution = Solution()
if A1 == solution.containsDuplicate1(Q1) and A2 == solution.containsDuplicate2(Q2):
print(Q1,'==>',A1)
print(Q2,'==>',A2)
print("AC") |
fanruan/swift-http | swift-proxy/src/main/java/com/fr/swift/cloud/basics/base/handler/AbstractProcessHandler.java | <reponame>fanruan/swift-http
package com.fr.swift.cloud.basics.base.handler;
import com.fr.swift.cloud.basics.AsyncRpcCallback;
import com.fr.swift.cloud.basics.Invoker;
import com.fr.swift.cloud.basics.InvokerCreator;
import com.fr.swift.cloud.basics.ProcessHandler;
import com.fr.swift.cloud.basics.RpcFuture;
import com.fr.swift.cloud.basics.annotation.Target;
import com.fr.swift.cloud.basics.base.SwiftInvocation;
import java.lang.reflect.Method;
import java.util.concurrent.CountDownLatch;
/**
* @author yee
* @date 2018/10/24
*/
public abstract class AbstractProcessHandler<T> implements ProcessHandler {
private static final String TO_STRING = "toString";
private static final String HASH_CODE = "hashCode";
private static final String EQUALS = "equals";
protected InvokerCreator invokerCreator;
public AbstractProcessHandler(InvokerCreator invokerCreator) {
this.invokerCreator = invokerCreator;
}
/**
* process targets url
* 只负责各种形式的url计算。
*
* @return
*/
protected abstract T processUrl(Target[] targets, Object... args) throws Exception;
/**
* @param invoker
* @param proxyClass
* @param method
* @param methodName 传了method还传methodName是不想有循环method.getName调几次
* @param parameterTypes
* @param args
* @return
* @throws Throwable
*/
protected Object invoke(Invoker invoker, Class proxyClass, Method method, String methodName, Class[] parameterTypes, Object... args) throws Throwable {
if (proxyClass == Object.class) {
return method.invoke(invoker, args);
}
if (TO_STRING.equals(methodName) && parameterTypes.length == 0) {
return invoker.toString();
}
if (HASH_CODE.equals(methodName) && parameterTypes.length == 0) {
return invoker.hashCode();
}
if (EQUALS.equals(methodName) && parameterTypes.length == 1) {
return invoker.equals(args[0]);
}
return invoker.invoke(new SwiftInvocation(method, args)).recreate();
}
protected Object handleAsyncResult(Object obj) throws Throwable {
if (obj instanceof RpcFuture) {
RpcFuture future = (RpcFuture) obj;
final CountDownLatch latch = new CountDownLatch(1);
final Object[] result = new Object[1];
future.addCallback(new AsyncRpcCallback() {
@Override
public void success(Object o) {
result[0] = o;
latch.countDown();
}
@Override
public void fail(Exception e) {
result[0] = e;
latch.countDown();
}
});
latch.await();
if (result[0] instanceof Exception) {
throw (Exception) result[0];
}
return result[0];
} else {
return obj;
}
}
}
|
AllaMaevskaya/AliRoot | test/vmctest/scripts/cluster/AliAnalysisTaskCluster.cxx | #include "TChain.h"
#include "TTree.h"
#include "TH1F.h"
#include "TH2F.h"
#include "TH3F.h"
#include "TCanvas.h"
#include "TList.h"
#include "TParticle.h"
#include "TParticlePDG.h"
#include "TProfile.h"
#include "TNtuple.h"
#include "TFile.h"
#include "AliAnalysisTask.h"
#include "AliAnalysisManager.h"
#include "AliESDEvent.h"
#include "AliLog.h"
#include "AliESDVertex.h"
#include "AliESDInputHandler.h"
#include "AliESDtrackCuts.h"
#include "AliMultiplicity.h"
#include "AliAnalysisTaskCluster.h"
#include "AliExternalTrackParam.h"
#include "AliTrackReference.h"
#include "AliHeader.h"
#include "AliGenEventHeader.h"
#include "AliGenDPMjetEventHeader.h"
// Analysis Task for basic QA on cluster numbers
// Authors: <NAME>
ClassImp(AliAnalysisTaskCluster)
//________________________________________________________________________
AliAnalysisTaskCluster::AliAnalysisTaskCluster(const char *name)
: AliAnalysisTaskSE(name)
,fTrackType(0)
,fFieldOn(kTRUE)
,fHists(0)
,fHistRECpt(0)
,fITSncl(0)
,fTPCncl(0)
,fTPCnclSA(0)
,fTRDncl(0)
,pEtaITSncl(0)
,pEtaTPCncl(0)
,pEtaTPCnclR(0)
,pEtaTRDncl(0)
,pPhiITSncl(0)
,pPhiTPCncl(0)
,pPhiTPCnclR(0)
,pPhiTRDncl(0)
,pPtITSncl(0)
,pPtTPCncl(0)
,pPtTPCnclR(0)
,pPtTRDncl(0)
,fITSlayer(0)
,fITSlayerPhi(0)
,fITSlayerEta(0)
,fCuts(0)
{
DefineOutput(1, TList::Class());
}
//________________________________________________________________________
void AliAnalysisTaskCluster::UserCreateOutputObjects()
{
// Create histograms
// Called once
Bool_t oldStatus = TH1::AddDirectoryStatus();
TH1::AddDirectory(kFALSE);
Double_t pt = 20.;
fHists = new TList();
fHistRECpt = new TH1F("fHistRECpt", " p_{T}", 100, 0., pt);
fITSncl = new TH1F("fITSncl", "fITSncl", 11, -1.5, 9.5);
fTPCncl = new TH1F("fTPCncl", "fTPCncl", 182, -1.5, 180.5);
fTPCnclSA = new TH1F("fTPCnclSA", "fTPCnclSA", 182, -1.5, 180.5);
fTRDncl = new TH1F("fTRDncl", "fTRDncl", 182, -1.5, 180.5);
//Create Profiles
pEtaITSncl = new TProfile("pEtaITSncl", "pEtaITSncl", 20, -2, 2);
pEtaTPCncl = new TProfile("pEtaTPCncl", "pEtaTPCncl", 20, -2, 2);
pEtaTPCnclR = new TProfile("pEtaTPCnclR", "pEtaTPCnclR", 20, -2, 2, 90, 180);
pEtaTRDncl = new TProfile("pEtaTRDncl", "pEtaTRDncl", 20, -2, 2);
pPhiITSncl = new TProfile("pPhiITSncl", "pPhiITSncl", 90, 0, 2*TMath::Pi());
pPhiTPCncl = new TProfile("pPhiTPCncl", "pPhiTPCncl", 90, 0, 2*TMath::Pi());
pPhiTPCnclR = new TProfile("pPhiTPCnclR", "pPhiTPCnclR", 90, 0, 2*TMath::Pi(), 90, 180);
pPhiTRDncl = new TProfile("pPhiTRDncl", "pPhiTRDncl", 90, 0, 2*TMath::Pi());
pPtITSncl = new TProfile("pPtITSncl", "pPtITSncl", 40, 0, 20);
pPtTPCncl = new TProfile("pPtTPCncl", "pPtTPCncl", 40, 0, 20);
pPtTPCnclR = new TProfile("pPtTPCnclR", "pPtTPCnclR", 40, 0, 20, 90, 180);
pPtTRDncl = new TProfile("pPtTRDncl", "pPtTRDncl", 40, 0, 20);
fITSlayer = new TH1F("fITSlayer", "fITSlayer", 8, -1.5, 6.5);
fITSlayerPhi = new TH2F("fITSlayerPhi", "fITSlayerPhi", 8, -1.5, 6.5,90, 0, 2*TMath::Pi());
fITSlayerEta = new TH2F("fITSlayerEta", "fITSlayerEta", 8, -1.5, 6.5,100, -2, 2);
fHists->SetOwner();
fHists->Add(fHistRECpt);
fHists->Add(fITSncl);
fHists->Add(fTPCncl);
fHists->Add(fTPCnclSA);
fHists->Add(fTRDncl);
fHists->Add(pEtaITSncl);
fHists->Add(pEtaTPCncl);
fHists->Add(pEtaTPCnclR);
fHists->Add(pEtaTRDncl);
fHists->Add(pPhiITSncl);
fHists->Add(pPhiTPCncl);
fHists->Add(pPhiTPCnclR);
fHists->Add(pPhiTRDncl);
fHists->Add(pPtITSncl);
fHists->Add(pPtTPCncl);
fHists->Add(pPtTPCnclR);
fHists->Add(pPtTRDncl);
fHists->Add(fITSlayer);
fHists->Add(fITSlayerPhi);
fHists->Add(fITSlayerEta);
// for (Int_t i=0; i<fHists->GetEntries(); ++i) {
// TH1 *h1 = dynamic_cast<TH1*>(fHists->At(i));
// if (h1){
// // Printf("%s ",h1->GetName());
// h1->Sumw2();
// }
// }
TH1::AddDirectory(oldStatus);
}
//__________________________________________________________
void AliAnalysisTaskCluster::UserExec(Option_t *)
{
AliVEvent *event = InputEvent();
if (!event) {
Printf("ERROR: Could not retrieve event");
return;
}
if(Entry()==0){
AliESDEvent* esd = dynamic_cast<AliESDEvent*>(event);
if(esd){
Printf("We are reading from ESD");
}
}
if(fDebug>1)Printf("There are %d tracks in this event", event->GetNumberOfTracks());
const AliVVertex* vertex = event->GetPrimaryVertex();
Float_t vz = vertex->GetZ();
if (TMath::Abs(vz) > 10.) return;
for (Int_t iTrack = 0; iTrack < event->GetNumberOfTracks(); iTrack++) {
AliVParticle *track = event->GetTrack(iTrack);
AliESDtrack *esdtrack = dynamic_cast<AliESDtrack*>(track);
if (!track) {
Printf("ERROR: Could not receive track %d", iTrack);
continue;
}
if (!fCuts->AcceptTrack(esdtrack)) continue;
fHistRECpt->Fill(esdtrack->Pt());
fITSncl->Fill(esdtrack->GetNcls(0)); //0=ITS
fTPCncl->Fill(esdtrack->GetNcls(1)); //1=TPC
fTRDncl->Fill(esdtrack->GetNcls(2)); //2=TRD
const AliExternalTrackParam *tpcP = 0x0;
tpcP = esdtrack->GetTPCInnerParam();
if(tpcP){
fTPCnclSA->Fill(esdtrack->GetNcls(1));
}
if(esdtrack->GetNcls(0)!=0){
for(Int_t layer=0;layer<6;layer++){
if(esdtrack->HasPointOnITSLayer(layer)){
fITSlayer->Fill(layer);
fITSlayerPhi->Fill(layer, esdtrack->Phi());
fITSlayerEta->Fill(layer, esdtrack->Eta());
}
}
pEtaITSncl->Fill(esdtrack->Eta(),esdtrack->GetNcls(0));
pPhiITSncl->Fill(esdtrack->Phi(),esdtrack->GetNcls(0));
pPtITSncl->Fill(esdtrack->Pt(),esdtrack->GetNcls(0));
}
if(esdtrack->GetNcls(1)!=0){
pEtaTPCncl->Fill(esdtrack->Eta(),esdtrack->GetNcls(1));
pPhiTPCncl->Fill(esdtrack->Phi(),esdtrack->GetNcls(1));
pPtTPCncl->Fill(esdtrack->Pt(),esdtrack->GetNcls(1));
pEtaTPCnclR->Fill(esdtrack->Eta(),esdtrack->GetNcls(1));
pPhiTPCnclR->Fill(esdtrack->Phi(),esdtrack->GetNcls(1));
pPtTPCnclR->Fill(esdtrack->Pt(),esdtrack->GetNcls(1));
}
if(esdtrack->GetNcls(2)!=0){
pPhiTRDncl->Fill(esdtrack->Phi(),esdtrack->GetNcls(2));
pEtaTRDncl->Fill(esdtrack->Eta(),esdtrack->GetNcls(2));
pPtTRDncl->Fill(esdtrack->Pt(),esdtrack->GetNcls(2));
}
}//first track loop
// Post output data.
// PostData(1, fHistPt);
PostData(1, fHists);
}
//________________________________________________________________________
void AliAnalysisTaskCluster::Terminate(Option_t *)
{
}
|
acanozturk/mbs-app | src/main/java/com/group5/mbs/controllers/DepartmentalBoardRepresentativeController.java | package com.group5.mbs.controllers;
import com.group5.mbs.api.dtos.Advisor;
import com.group5.mbs.api.dtos.DepartmentalBoardRepresentative;
import com.group5.mbs.api.dtos.Student;
import com.group5.mbs.api.model.request.DbrRecommendAdvisorRequest;
import com.group5.mbs.api.model.response.*;
import com.group5.mbs.services.interfaces.DepartmentalBoardRepresentativeService;
import com.group5.mbs.services.interfaces.MailService;
import com.group5.mbs.services.interfaces.RecommendationService;
import com.group5.mbs.services.interfaces.StudentService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@AllArgsConstructor
public class DepartmentalBoardRepresentativeController {
private final DepartmentalBoardRepresentativeService departmentalBoardRepresentativeService;
private final StudentService studentService;
private final RecommendationService recommendationService;
private final MailService mailService;
@GetMapping("/mbs/dbrs")
public DbrListResponse getAllDbrs() {
final List<DepartmentalBoardRepresentative> allDbrs = departmentalBoardRepresentativeService.getAllDbrs();
final DbrListResponse response = new DbrListResponse();
response.setDepartmentalBoardRepresentativeList(allDbrs);
return response;
}
@GetMapping("/mbs/dbrs/{dbrId}")
public DbrResponse getDbrById(@PathVariable("dbrId") final Integer dbrId) {
final DepartmentalBoardRepresentative dbr = departmentalBoardRepresentativeService.getDbrById(dbrId);
final DbrResponse response = new DbrResponse();
response.setDepartmentalBoardRepresentative(dbr);
return response;
}
@GetMapping("/mbs/dbrs/getStudentWithNoAdvisor")
public StudentListResponse getStudentWithNoAdvisor() {
final List<Student> studentsWithNoAdvisor = departmentalBoardRepresentativeService.findStudentsWithNoAdvisor();
final StudentListResponse response = new StudentListResponse();
response.setStudentList(studentsWithNoAdvisor);
return response;
}
@GetMapping("/mbs/dbrs/getAdvisors")
public AdvisorListResponse getAdvisors() {
final List<Advisor> advisors = departmentalBoardRepresentativeService.getAdvisors();
final AdvisorListResponse response = new AdvisorListResponse();
response.setAdvisorList(advisors);
return response;
}
@PutMapping("/mbs/dbrs/recommendAdvisor")
public DbrRecommendAdvisorsResponse recommend(@RequestBody final DbrRecommendAdvisorRequest request) {
final Integer studentId = request.getStudentId();
final List<Integer> advisorIds = request.getAdvisorIds();
final DbrRecommendAdvisorsResponse response = new DbrRecommendAdvisorsResponse();
recommendationService.recommendAdvisorsToStudent(studentId, advisorIds);
response.setSuccessMessage("Recommendation successful.");
mailService.sendMail("<EMAIL>", "Recommended Advisors",
"Recommended advisors to " + studentService.getStudentNameByStudentId(studentId) + ".");
return response;
}
}
|
ClockworkOrigins/m2etis | library/generated/GeneratedChannelConfiguration.h | /*
Copyright (2016) <NAME>, <NAME>, 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.
*/
#ifndef M2ETIS_GENERATEDCHANNELCONFIGURATION_H
#define M2ETIS_GENERATEDCHANNELCONFIGURATION_H
}}
// Todo: refactor (namespace opened by ChannelTypeDefinitions.h closed)
// namespace m2etis pubsub closed because of the following includes:
#include "m2etis/config/GeneratedEventTypes.h"
#include "m2etis/config/DetMergeConfigTest.h"
namespace m2etis {
namespace pubsub {
#include <map>
#include <vector>
#include "m2etis/pubsub/filter/AttributeTypeInformation.h"
#include "m2etis/pubsub/filter/AttributeAccessorBasic.h"
#include "m2etis/pubsub/filter/AttributeAccessor.h"
using ::m2etis::pubsub::filter::AttributeName;
using ::m2etis::pubsub::filter::AttributeAccessor_Basic;
using ::m2etis::pubsub::filter::AttributeAccessor;
// needed for serializing attribute value accessors for filters:
// maps attribute identifier to attribute value getter
// todo: maybe move to better place
enum attribute_names {
POSITION_X, POSITION_Y, POSITION_REGION, BOOK_TITLE, BOOK_PRICE, BOOK_CONDITION
};
M2ETIS_API std::map<AttributeName, std::shared_ptr<AttributeAccessor_Basic>> attributes_accessor_map = {
{POSITION_Y, std::make_shared<AttributeAccessor<Position, int>> (
[] (const Position& position)->int {return position.get_y();} )
},
{POSITION_X, std::make_shared<AttributeAccessor<Position, int>> (
[] (const Position& position)->int {return position.get_x();} )
},
{POSITION_REGION, std::make_shared<AttributeAccessor<Position, std::string>> (
[] (const Position& position)->std::string {return position.get_region();} )
},
{BOOK_TITLE, std::make_shared<AttributeAccessor<Book, std::string>> (
[] (const Book& book)->std::string {return book.title_;} )
},
{BOOK_CONDITION, std::make_shared<AttributeAccessor<Book, std::string>> (
[] (const Book& book)->std::string {return book.condition_;} )
},
{BOOK_PRICE, std::make_shared<AttributeAccessor<Book, double>> (
[] (const Book& book)->double {return book.price_;} )
}
};
#ifdef WITH_SIM
// SIM_Spreadit_Null_OMNET
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::OMNET>>
, NullFilter<SimulationEventType, net::NetworkType<net::OMNET>>
, NullOrder<net::NetworkType<net::OMNET>>
, NullDeliver<net::NetworkType<net::OMNET>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::OMNET>, SimulationEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::OMNET>,
SimulationEventType
> SIM_Spreadit_Null_OMNET_Null_Null_SimulationEventType;
template <>
struct ChannelT<SIM_Spreadit_Null_OMNET_Null_Null_Simulation> {
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new SIM_Spreadit_Null_OMNET_Null_Null_SimulationEventType(SIM_Spreadit_Null_OMNET_Null_Null_Simulation, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
// SIM_Spreadit_DetMerge_OMNET
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::OMNET>>
, NullFilter<SimulationEventType, net::NetworkType<net::OMNET>>
, DetMergeOrder<net::NetworkType<net::OMNET>, m2etis::pubsub::order::DetMergeConfig>
, NullDeliver<net::NetworkType<net::OMNET>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::OMNET>, SimulationEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::OMNET>,
SimulationEventType
> SIM_Spreadit_DetMerge_OMNET_Null_Null_SimulationEventType;
template <>
struct ChannelT<SIM_Spreadit_DetMerge_OMNET_Null_Null_Simulation> {
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new SIM_Spreadit_DetMerge_OMNET_Null_Null_SimulationEventType(SIM_Spreadit_DetMerge_OMNET_Null_Null_Simulation, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
// SIM_Spreadit_MTP_OMNET
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::OMNET>>
, NullFilter<SimulationEventType, net::NetworkType<net::OMNET>>
, MTPOrder<net::NetworkType<net::OMNET>, 1000000, LateDeliver::DROP>
, NullDeliver<net::NetworkType<net::OMNET>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::OMNET>, SimulationEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::OMNET>,
SimulationEventType
> SIM_Spreadit_MTP_OMNET_Null_Null_SimulationEventType;
template <>
struct ChannelT<SIM_Spreadit_MTP_OMNET_Null_Null_Simulation> {
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new SIM_Spreadit_MTP_OMNET_Null_Null_SimulationEventType(SIM_Spreadit_MTP_OMNET_Null_Null_Simulation, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
// SIM_Spreadit_GMS_OMNET
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::OMNET>>
, NullFilter<SimulationEventType, net::NetworkType<net::OMNET>>
, GMSOrder<net::NetworkType<net::OMNET>, 1000000>
, NullDeliver<net::NetworkType<net::OMNET>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::OMNET>, SimulationEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::OMNET>,
SimulationEventType
> SIM_Spreadit_GMS_OMNET_Null_Null_SimulationEventType;
template <>
struct ChannelT<SIM_Spreadit_GMS_OMNET_Null_Null_Simulation> {
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new SIM_Spreadit_GMS_OMNET_Null_Null_SimulationEventType(SIM_Spreadit_GMS_OMNET_Null_Null_Simulation, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
// SIM_Direct_Null_OMNET
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::OMNET>>
, NullFilter<SimulationEventType, net::NetworkType<net::OMNET>>
, NullOrder<net::NetworkType<net::OMNET>>
, NullDeliver<net::NetworkType<net::OMNET>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::OMNET>, SimulationEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::OMNET>,
SimulationEventType
> SIM_Direct_Null_OMNET_Null_Null_SimulationEventType;
template <>
struct ChannelT<SIM_Direct_Null_OMNET_Null_Null_Simulation> {
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new SIM_Direct_Null_OMNET_Null_Null_SimulationEventType(SIM_Direct_Null_OMNET_Null_Null_Simulation, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
// SIM_Direct_MTP_OMNET
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::OMNET>>
, NullFilter<SimulationEventType, net::NetworkType<net::OMNET>>
, MTPOrder<net::NetworkType<net::OMNET>, 1000000, LateDeliver::DROP>
, NullDeliver<net::NetworkType<net::OMNET>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::OMNET>, SimulationEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::OMNET>,
SimulationEventType
> SIM_Direct_MTP_OMNET_Null_Null_SimulationEventType;
template <>
struct ChannelT<SIM_Direct_MTP_OMNET_Null_Null_Simulation> {
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new SIM_Direct_MTP_OMNET_Null_Null_SimulationEventType(SIM_Direct_MTP_OMNET_Null_Null_Simulation, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
// SIM_Direct_DetMerge_OMNET
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::OMNET>>
, NullFilter<SimulationEventType, net::NetworkType<net::OMNET>>
, DetMergeOrder<net::NetworkType<net::OMNET>, DetMergeConfig>
, NullDeliver<net::NetworkType<net::OMNET>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::OMNET>, SimulationEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::OMNET>,
SimulationEventType
> SIM_Direct_DetMerge_OMNET_Null_Null_SimulationEventType;
template <>
struct ChannelT<SIM_Direct_DetMerge_OMNET_Null_Null_Simulation> {
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new SIM_Direct_DetMerge_OMNET_Null_Null_SimulationEventType(SIM_Direct_DetMerge_OMNET_Null_Null_Simulation, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
// SIM_Direct_GMS_OMNET
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::OMNET>>
, NullFilter<SimulationEventType, net::NetworkType<net::OMNET>>
, GMSOrder<net::NetworkType<net::OMNET>, 1000000>
, NullDeliver<net::NetworkType<net::OMNET>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::OMNET>, SimulationEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::OMNET>,
SimulationEventType
> SIM_Direct_GMS_OMNET_Null_Null_SimulationEventType;
template <>
struct ChannelT<SIM_Direct_GMS_OMNET_Null_Null_Simulation> {
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new SIM_Direct_GMS_OMNET_Null_Null_SimulationEventType(SIM_Direct_GMS_OMNET_Null_Null_Simulation, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
// SIM_DirectBroadcast_Null_OMNET
typedef Channel<
ChannelType<
DirectBroadcastRouting<net::NetworkType<net::OMNET>>
, NullFilter<SimulationEventType, net::NetworkType<net::OMNET>>
, NullOrder<net::NetworkType<net::OMNET>>
, NullDeliver<net::NetworkType<net::OMNET>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::OMNET>, SimulationEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::OMNET>,
SimulationEventType
> SIM_DirectBroadcast_Null_OMNET_Null_Null_SimulationEventType;
template <>
struct ChannelT<SIM_DirectBroadcast_Null_OMNET_Null_Null_Simulation> {
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new SIM_DirectBroadcast_Null_OMNET_Null_Null_SimulationEventType(SIM_DirectBroadcast_Null_OMNET_Null_Null_Simulation, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
// SIM_DirectBroadcast_MTP_OMNET
typedef Channel<
ChannelType<
DirectBroadcastRouting<net::NetworkType<net::OMNET>>
, NullFilter<SimulationEventType, net::NetworkType<net::OMNET>>
, MTPOrder<net::NetworkType<net::OMNET>, 1000000, LateDeliver::DROP>
, NullDeliver<net::NetworkType<net::OMNET>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::OMNET>, SimulationEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::OMNET>,
SimulationEventType
> SIM_DirectBroadcast_MTP_OMNET_Null_Null_SimulationEventType;
template <>
struct ChannelT<SIM_DirectBroadcast_MTP_OMNET_Null_Null_Simulation> {
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new SIM_DirectBroadcast_MTP_OMNET_Null_Null_SimulationEventType(SIM_DirectBroadcast_MTP_OMNET_Null_Null_Simulation, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
// SIM_DirectBroadcast_DetMerge_OMNET
typedef Channel<
ChannelType<
DirectBroadcastRouting<net::NetworkType<net::OMNET>>
, NullFilter<SimulationEventType, net::NetworkType<net::OMNET>>
, DetMergeOrder<net::NetworkType<net::OMNET>, DetMergeConfig>
, NullDeliver<net::NetworkType<net::OMNET>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::OMNET>, SimulationEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::OMNET>,
SimulationEventType
> SIM_DirectBroadcast_DetMerge_OMNET_Null_Null_SimulationEventType;
template <>
struct ChannelT<SIM_DirectBroadcast_DetMerge_OMNET_Null_Null_Simulation> {
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new SIM_DirectBroadcast_DetMerge_OMNET_Null_Null_SimulationEventType(SIM_DirectBroadcast_DetMerge_OMNET_Null_Null_Simulation, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
// SIM_DirectBroadcast_GMS_OMNET
typedef Channel<
ChannelType<
DirectBroadcastRouting<net::NetworkType<net::OMNET>>
, NullFilter<SimulationEventType, net::NetworkType<net::OMNET>>
, GMSOrder<net::NetworkType<net::OMNET>, 1000000>
, NullDeliver<net::NetworkType<net::OMNET>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::OMNET>, SimulationEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::OMNET>,
SimulationEventType
> SIM_DirectBroadcast_GMS_OMNET_Null_Null_SimulationEventType;
template <>
struct ChannelT<SIM_DirectBroadcast_GMS_OMNET_Null_Null_Simulation> {
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new SIM_DirectBroadcast_GMS_OMNET_Null_Null_SimulationEventType(SIM_DirectBroadcast_GMS_OMNET_Null_Null_Simulation, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
// SIM_Scribe_Null_OMNET
typedef Channel<
ChannelType<
ScribeRouting<net::NetworkType<net::OMNET>>
, NullFilter<SimulationEventType, net::NetworkType<net::OMNET>>
, MTPOrder<net::NetworkType<net::OMNET>, 1000000, m2etis::pubsub::order::LateDeliver::DROP>
, AckDeliver<net::NetworkType<net::OMNET>, 5, m2etis::pubsub::deliver::Amount::EXACTLY_ONCE>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::OMNET>, SimulationEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::OMNET>,
SimulationEventType
> SIM_Scribe_Null_OMNET_Null_Null_SimulationEventType;
template <>
struct ChannelT<SIM_Scribe_Null_OMNET_Null_Null_Simulation> {
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new SIM_Scribe_Null_OMNET_Null_Null_SimulationEventType(SIM_Scribe_Null_OMNET_Null_Null_Simulation, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
// SIM_Direct_Null_OMNET_Ack_Null
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::OMNET>>
, NullFilter<SimulationEventType, net::NetworkType<net::OMNET>>
, NullOrder<net::NetworkType<net::OMNET>>
, AckDeliver<net::NetworkType<net::OMNET>, 5, m2etis::pubsub::deliver::Amount::EXACTLY_ONCE>
, NullPersistence
, NullValidity, NullPartition<net::NetworkType<net::OMNET>, SimulationEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::OMNET>,
SimulationEventType
> SIM_Direct_Null_OMNET_Ack_Null_SimulationEventType;
template <>
struct ChannelT<SIM_Direct_Null_OMNET_Ack_Null_Simulation> {
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new SIM_Direct_Null_OMNET_Ack_Null_SimulationEventType(SIM_Direct_Null_OMNET_Ack_Null_Simulation, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
// SIM_Spreadit_Null_OMNET
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::OMNET>>
, NullFilter<SimulationEventType, net::NetworkType<net::OMNET>>
, NullOrder<net::NetworkType<net::OMNET>>
, NullDeliver<net::NetworkType<net::OMNET>>
, NullPersistence
, TimeValidity<0, 5000000>
, NullPartition<net::NetworkType<net::OMNET>, SimulationEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::OMNET>,
SimulationEventType
> SIM_Spreadit_Null_OMNET_Null_Time_SimulationEventType;
template <>
struct ChannelT<SIM_Spreadit_Null_OMNET_Null_Time_Simulation> {
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new SIM_Spreadit_Null_OMNET_Null_Time_SimulationEventType(SIM_Spreadit_Null_OMNET_Null_Time_Simulation, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::OMNET>>
, NullFilter<SimulationEventType, net::NetworkType<net::OMNET>>
, NullOrder<net::NetworkType<net::OMNET>>
, NullDeliver<net::NetworkType<net::OMNET>>
, NullPersistence
, NullValidity
, DirectBroadcastPartition<net::NetworkType<net::OMNET>, SimulationEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::OMNET>,
SimulationEventType
> SIM_Direct_Null_OMNET_Null_Null_DirectBroadcast_SimulationEventType;
template <>
struct ChannelT<SIM_Direct_Null_OMNET_Null_Null_DirectBroadcast_Simulation> {
ChannelT(const std::string & ip, const int port, const std::string & known_hostname, const int known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new SIM_Direct_Null_OMNET_Null_Null_DirectBroadcast_SimulationEventType(SIM_Direct_Null_OMNET_Null_Null_DirectBroadcast_Simulation, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::OMNET>>
, NullFilter<SimulationEventType, net::NetworkType<net::OMNET>>
, NullOrder<net::NetworkType<net::OMNET>>
, NackDeliver<net::NetworkType<net::OMNET>, 5, m2etis::pubsub::deliver::Amount::EXACTLY_ONCE>
, NullPersistence
, NullValidity, NullPartition<net::NetworkType<net::OMNET>, SimulationEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::OMNET>,
SimulationEventType
> SIM_Direct_Null_OMNET_Nack_Null_SimulationEventType;
template <>
struct ChannelT<SIM_Direct_Null_OMNET_Nack_Null_Simulation> {
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new SIM_Direct_Null_OMNET_Nack_Null_SimulationEventType(SIM_Direct_Null_OMNET_Nack_Null_Simulation, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
#else
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::TCP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, NullOrder<net::NetworkType<net::TCP>>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_Direct_Null_Null_Null_Null_Null_Null_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_Direct_Null_Null_Null_Null_Null_Null_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Direct_Null_Null_Null_Null_Null_Null_Null_CharVector_TCPType( TEST_Direct_Null_Null_Null_Null_Null_Null_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::UDP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, NullOrder<net::NetworkType<net::UDP>>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_Direct_Null_Null_Null_Null_Null_Null_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_Direct_Null_Null_Null_Null_Null_Null_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Direct_Null_Null_Null_Null_Null_Null_Null_CharVector_UDPType( TEST_Direct_Null_Null_Null_Null_Null_Null_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::TCP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, NullOrder<net::NetworkType<net::TCP>>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_Direct_Null_Null_Null_Null_Null_BruteForce_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_Direct_Null_Null_Null_Null_Null_BruteForce_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Direct_Null_Null_Null_Null_Null_BruteForce_Null_CharVector_TCPType( TEST_Direct_Null_Null_Null_Null_Null_BruteForce_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::UDP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, NullOrder<net::NetworkType<net::UDP>>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_Direct_Null_Null_Null_Null_Null_BruteForce_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_Direct_Null_Null_Null_Null_Null_BruteForce_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Direct_Null_Null_Null_Null_Null_BruteForce_Null_CharVector_UDPType( TEST_Direct_Null_Null_Null_Null_Null_BruteForce_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::TCP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, DetMergeOrder<net::NetworkType<net::TCP>, m2etis::config::order::DetMergeConfigTest>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_Direct_Null_DetMerge_Null_Null_Null_Null_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_Direct_Null_DetMerge_Null_Null_Null_Null_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Direct_Null_DetMerge_Null_Null_Null_Null_Null_CharVector_TCPType( TEST_Direct_Null_DetMerge_Null_Null_Null_Null_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::UDP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, DetMergeOrder<net::NetworkType<net::UDP>, m2etis::config::order::DetMergeConfigTest>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_Direct_Null_DetMerge_Null_Null_Null_Null_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_Direct_Null_DetMerge_Null_Null_Null_Null_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Direct_Null_DetMerge_Null_Null_Null_Null_Null_CharVector_UDPType( TEST_Direct_Null_DetMerge_Null_Null_Null_Null_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::TCP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, DetMergeOrder<net::NetworkType<net::TCP>, m2etis::config::order::DetMergeConfigTest>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_Direct_Null_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_Direct_Null_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Direct_Null_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_TCPType( TEST_Direct_Null_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::UDP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, DetMergeOrder<net::NetworkType<net::UDP>, m2etis::config::order::DetMergeConfigTest>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_Direct_Null_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_Direct_Null_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Direct_Null_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_UDPType( TEST_Direct_Null_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::TCP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, MTPOrder<net::NetworkType<net::TCP>, 1000000, LateDeliver::DROP>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_Direct_Null_MTP_Null_Null_Null_Null_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_Direct_Null_MTP_Null_Null_Null_Null_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Direct_Null_MTP_Null_Null_Null_Null_Null_CharVector_TCPType( TEST_Direct_Null_MTP_Null_Null_Null_Null_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::UDP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, MTPOrder<net::NetworkType<net::UDP>, 1000000, LateDeliver::DROP>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_Direct_Null_MTP_Null_Null_Null_Null_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_Direct_Null_MTP_Null_Null_Null_Null_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Direct_Null_MTP_Null_Null_Null_Null_Null_CharVector_UDPType( TEST_Direct_Null_MTP_Null_Null_Null_Null_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::TCP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, MTPOrder<net::NetworkType<net::TCP>, 1000000, LateDeliver::DROP>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_Direct_Null_MTP_Null_Null_Null_BruteForce_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_Direct_Null_MTP_Null_Null_Null_BruteForce_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Direct_Null_MTP_Null_Null_Null_BruteForce_Null_CharVector_TCPType( TEST_Direct_Null_MTP_Null_Null_Null_BruteForce_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::UDP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, MTPOrder<net::NetworkType<net::UDP>, 1000000, LateDeliver::DROP>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_Direct_Null_MTP_Null_Null_Null_BruteForce_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_Direct_Null_MTP_Null_Null_Null_BruteForce_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Direct_Null_MTP_Null_Null_Null_BruteForce_Null_CharVector_UDPType( TEST_Direct_Null_MTP_Null_Null_Null_BruteForce_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::TCP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, GMSOrder<net::NetworkType<net::TCP>, 1000000>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_Direct_Null_GMS_Null_Null_Null_Null_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_Direct_Null_GMS_Null_Null_Null_Null_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Direct_Null_GMS_Null_Null_Null_Null_Null_CharVector_TCPType( TEST_Direct_Null_GMS_Null_Null_Null_Null_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::UDP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, GMSOrder<net::NetworkType<net::UDP>, 1000000>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_Direct_Null_GMS_Null_Null_Null_Null_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_Direct_Null_GMS_Null_Null_Null_Null_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Direct_Null_GMS_Null_Null_Null_Null_Null_CharVector_UDPType( TEST_Direct_Null_GMS_Null_Null_Null_Null_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::TCP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, GMSOrder<net::NetworkType<net::TCP>, 1000000>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_Direct_Null_GMS_Null_Null_Null_BruteForce_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_Direct_Null_GMS_Null_Null_Null_BruteForce_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Direct_Null_GMS_Null_Null_Null_BruteForce_Null_CharVector_TCPType( TEST_Direct_Null_GMS_Null_Null_Null_BruteForce_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::UDP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, GMSOrder<net::NetworkType<net::UDP>, 1000000>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_Direct_Null_GMS_Null_Null_Null_BruteForce_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_Direct_Null_GMS_Null_Null_Null_BruteForce_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Direct_Null_GMS_Null_Null_Null_BruteForce_Null_CharVector_UDPType( TEST_Direct_Null_GMS_Null_Null_Null_BruteForce_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::TCP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, NullOrder<net::NetworkType<net::TCP>>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_Direct_BruteForce_Null_Null_Null_Null_Null_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_Direct_BruteForce_Null_Null_Null_Null_Null_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Direct_BruteForce_Null_Null_Null_Null_Null_Null_CharVector_TCPType( TEST_Direct_BruteForce_Null_Null_Null_Null_Null_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::UDP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, NullOrder<net::NetworkType<net::UDP>>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_Direct_BruteForce_Null_Null_Null_Null_Null_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_Direct_BruteForce_Null_Null_Null_Null_Null_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Direct_BruteForce_Null_Null_Null_Null_Null_Null_CharVector_UDPType( TEST_Direct_BruteForce_Null_Null_Null_Null_Null_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::TCP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, NullOrder<net::NetworkType<net::TCP>>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_Direct_BruteForce_Null_Null_Null_Null_BruteForce_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_Direct_BruteForce_Null_Null_Null_Null_BruteForce_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Direct_BruteForce_Null_Null_Null_Null_BruteForce_Null_CharVector_TCPType( TEST_Direct_BruteForce_Null_Null_Null_Null_BruteForce_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::UDP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, NullOrder<net::NetworkType<net::UDP>>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_Direct_BruteForce_Null_Null_Null_Null_BruteForce_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_Direct_BruteForce_Null_Null_Null_Null_BruteForce_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Direct_BruteForce_Null_Null_Null_Null_BruteForce_Null_CharVector_UDPType( TEST_Direct_BruteForce_Null_Null_Null_Null_BruteForce_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::TCP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, DetMergeOrder<net::NetworkType<net::TCP>, m2etis::config::order::DetMergeConfigTest>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_Direct_BruteForce_DetMerge_Null_Null_Null_Null_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_Direct_BruteForce_DetMerge_Null_Null_Null_Null_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Direct_BruteForce_DetMerge_Null_Null_Null_Null_Null_CharVector_TCPType( TEST_Direct_BruteForce_DetMerge_Null_Null_Null_Null_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::UDP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, DetMergeOrder<net::NetworkType<net::UDP>, m2etis::config::order::DetMergeConfigTest>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_Direct_BruteForce_DetMerge_Null_Null_Null_Null_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_Direct_BruteForce_DetMerge_Null_Null_Null_Null_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Direct_BruteForce_DetMerge_Null_Null_Null_Null_Null_CharVector_UDPType( TEST_Direct_BruteForce_DetMerge_Null_Null_Null_Null_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::TCP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, DetMergeOrder<net::NetworkType<net::TCP>, m2etis::config::order::DetMergeConfigTest>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_Direct_BruteForce_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_Direct_BruteForce_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Direct_BruteForce_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_TCPType( TEST_Direct_BruteForce_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::UDP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, DetMergeOrder<net::NetworkType<net::UDP>, m2etis::config::order::DetMergeConfigTest>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_Direct_BruteForce_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_Direct_BruteForce_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Direct_BruteForce_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_UDPType( TEST_Direct_BruteForce_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::TCP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, MTPOrder<net::NetworkType<net::TCP>, 1000000, LateDeliver::DROP>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_Direct_BruteForce_MTP_Null_Null_Null_Null_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_Direct_BruteForce_MTP_Null_Null_Null_Null_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Direct_BruteForce_MTP_Null_Null_Null_Null_Null_CharVector_TCPType( TEST_Direct_BruteForce_MTP_Null_Null_Null_Null_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::UDP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, MTPOrder<net::NetworkType<net::UDP>, 1000000, LateDeliver::DROP>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_Direct_BruteForce_MTP_Null_Null_Null_Null_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_Direct_BruteForce_MTP_Null_Null_Null_Null_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Direct_BruteForce_MTP_Null_Null_Null_Null_Null_CharVector_UDPType( TEST_Direct_BruteForce_MTP_Null_Null_Null_Null_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::TCP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, MTPOrder<net::NetworkType<net::TCP>, 1000000, LateDeliver::DROP>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_Direct_BruteForce_MTP_Null_Null_Null_BruteForce_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_Direct_BruteForce_MTP_Null_Null_Null_BruteForce_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Direct_BruteForce_MTP_Null_Null_Null_BruteForce_Null_CharVector_TCPType( TEST_Direct_BruteForce_MTP_Null_Null_Null_BruteForce_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::UDP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, MTPOrder<net::NetworkType<net::UDP>, 1000000, LateDeliver::DROP>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_Direct_BruteForce_MTP_Null_Null_Null_BruteForce_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_Direct_BruteForce_MTP_Null_Null_Null_BruteForce_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Direct_BruteForce_MTP_Null_Null_Null_BruteForce_Null_CharVector_UDPType( TEST_Direct_BruteForce_MTP_Null_Null_Null_BruteForce_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::TCP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, GMSOrder<net::NetworkType<net::TCP>, 1000000>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_Direct_BruteForce_GMS_Null_Null_Null_Null_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_Direct_BruteForce_GMS_Null_Null_Null_Null_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Direct_BruteForce_GMS_Null_Null_Null_Null_Null_CharVector_TCPType( TEST_Direct_BruteForce_GMS_Null_Null_Null_Null_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::UDP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, GMSOrder<net::NetworkType<net::UDP>, 1000000>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_Direct_BruteForce_GMS_Null_Null_Null_Null_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_Direct_BruteForce_GMS_Null_Null_Null_Null_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Direct_BruteForce_GMS_Null_Null_Null_Null_Null_CharVector_UDPType( TEST_Direct_BruteForce_GMS_Null_Null_Null_Null_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::TCP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, GMSOrder<net::NetworkType<net::TCP>, 1000000>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_Direct_BruteForce_GMS_Null_Null_Null_BruteForce_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_Direct_BruteForce_GMS_Null_Null_Null_BruteForce_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Direct_BruteForce_GMS_Null_Null_Null_BruteForce_Null_CharVector_TCPType( TEST_Direct_BruteForce_GMS_Null_Null_Null_BruteForce_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::UDP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, GMSOrder<net::NetworkType<net::UDP>, 1000000>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_Direct_BruteForce_GMS_Null_Null_Null_BruteForce_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_Direct_BruteForce_GMS_Null_Null_Null_BruteForce_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Direct_BruteForce_GMS_Null_Null_Null_BruteForce_Null_CharVector_UDPType( TEST_Direct_BruteForce_GMS_Null_Null_Null_BruteForce_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectBroadcastRouting<net::NetworkType<net::TCP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, NullOrder<net::NetworkType<net::TCP>>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_DirectBroadcast_Null_Null_Null_Null_Null_Null_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_DirectBroadcast_Null_Null_Null_Null_Null_Null_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_DirectBroadcast_Null_Null_Null_Null_Null_Null_Null_CharVector_TCPType( TEST_DirectBroadcast_Null_Null_Null_Null_Null_Null_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectBroadcastRouting<net::NetworkType<net::UDP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, NullOrder<net::NetworkType<net::UDP>>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_DirectBroadcast_Null_Null_Null_Null_Null_Null_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_DirectBroadcast_Null_Null_Null_Null_Null_Null_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_DirectBroadcast_Null_Null_Null_Null_Null_Null_Null_CharVector_UDPType( TEST_DirectBroadcast_Null_Null_Null_Null_Null_Null_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectBroadcastRouting<net::NetworkType<net::TCP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, NullOrder<net::NetworkType<net::TCP>>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_DirectBroadcast_Null_Null_Null_Null_Null_BruteForce_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_DirectBroadcast_Null_Null_Null_Null_Null_BruteForce_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_DirectBroadcast_Null_Null_Null_Null_Null_BruteForce_Null_CharVector_TCPType( TEST_DirectBroadcast_Null_Null_Null_Null_Null_BruteForce_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectBroadcastRouting<net::NetworkType<net::UDP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, NullOrder<net::NetworkType<net::UDP>>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_DirectBroadcast_Null_Null_Null_Null_Null_BruteForce_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_DirectBroadcast_Null_Null_Null_Null_Null_BruteForce_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_DirectBroadcast_Null_Null_Null_Null_Null_BruteForce_Null_CharVector_UDPType( TEST_DirectBroadcast_Null_Null_Null_Null_Null_BruteForce_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectBroadcastRouting<net::NetworkType<net::TCP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, DetMergeOrder<net::NetworkType<net::TCP>, m2etis::config::order::DetMergeConfigTest>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_DirectBroadcast_Null_DetMerge_Null_Null_Null_Null_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_DirectBroadcast_Null_DetMerge_Null_Null_Null_Null_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_DirectBroadcast_Null_DetMerge_Null_Null_Null_Null_Null_CharVector_TCPType( TEST_DirectBroadcast_Null_DetMerge_Null_Null_Null_Null_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectBroadcastRouting<net::NetworkType<net::UDP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, DetMergeOrder<net::NetworkType<net::UDP>, m2etis::config::order::DetMergeConfigTest>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_DirectBroadcast_Null_DetMerge_Null_Null_Null_Null_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_DirectBroadcast_Null_DetMerge_Null_Null_Null_Null_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_DirectBroadcast_Null_DetMerge_Null_Null_Null_Null_Null_CharVector_UDPType( TEST_DirectBroadcast_Null_DetMerge_Null_Null_Null_Null_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectBroadcastRouting<net::NetworkType<net::TCP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, DetMergeOrder<net::NetworkType<net::TCP>, m2etis::config::order::DetMergeConfigTest>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_DirectBroadcast_Null_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_DirectBroadcast_Null_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_DirectBroadcast_Null_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_TCPType( TEST_DirectBroadcast_Null_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectBroadcastRouting<net::NetworkType<net::UDP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, DetMergeOrder<net::NetworkType<net::UDP>, m2etis::config::order::DetMergeConfigTest>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_DirectBroadcast_Null_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_DirectBroadcast_Null_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_DirectBroadcast_Null_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_UDPType( TEST_DirectBroadcast_Null_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectBroadcastRouting<net::NetworkType<net::TCP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, MTPOrder<net::NetworkType<net::TCP>, 1000000, LateDeliver::DROP>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_DirectBroadcast_Null_MTP_Null_Null_Null_Null_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_DirectBroadcast_Null_MTP_Null_Null_Null_Null_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_DirectBroadcast_Null_MTP_Null_Null_Null_Null_Null_CharVector_TCPType( TEST_DirectBroadcast_Null_MTP_Null_Null_Null_Null_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectBroadcastRouting<net::NetworkType<net::UDP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, MTPOrder<net::NetworkType<net::UDP>, 1000000, LateDeliver::DROP>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_DirectBroadcast_Null_MTP_Null_Null_Null_Null_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_DirectBroadcast_Null_MTP_Null_Null_Null_Null_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_DirectBroadcast_Null_MTP_Null_Null_Null_Null_Null_CharVector_UDPType( TEST_DirectBroadcast_Null_MTP_Null_Null_Null_Null_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectBroadcastRouting<net::NetworkType<net::TCP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, MTPOrder<net::NetworkType<net::TCP>, 1000000, LateDeliver::DROP>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_DirectBroadcast_Null_MTP_Null_Null_Null_BruteForce_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_DirectBroadcast_Null_MTP_Null_Null_Null_BruteForce_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_DirectBroadcast_Null_MTP_Null_Null_Null_BruteForce_Null_CharVector_TCPType( TEST_DirectBroadcast_Null_MTP_Null_Null_Null_BruteForce_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectBroadcastRouting<net::NetworkType<net::UDP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, MTPOrder<net::NetworkType<net::UDP>, 1000000, LateDeliver::DROP>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_DirectBroadcast_Null_MTP_Null_Null_Null_BruteForce_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_DirectBroadcast_Null_MTP_Null_Null_Null_BruteForce_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_DirectBroadcast_Null_MTP_Null_Null_Null_BruteForce_Null_CharVector_UDPType( TEST_DirectBroadcast_Null_MTP_Null_Null_Null_BruteForce_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectBroadcastRouting<net::NetworkType<net::TCP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, NullOrder<net::NetworkType<net::TCP>>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_DirectBroadcast_BruteForce_Null_Null_Null_Null_Null_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_DirectBroadcast_BruteForce_Null_Null_Null_Null_Null_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_DirectBroadcast_BruteForce_Null_Null_Null_Null_Null_Null_CharVector_TCPType( TEST_DirectBroadcast_BruteForce_Null_Null_Null_Null_Null_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectBroadcastRouting<net::NetworkType<net::UDP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, NullOrder<net::NetworkType<net::UDP>>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_DirectBroadcast_BruteForce_Null_Null_Null_Null_Null_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_DirectBroadcast_BruteForce_Null_Null_Null_Null_Null_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_DirectBroadcast_BruteForce_Null_Null_Null_Null_Null_Null_CharVector_UDPType( TEST_DirectBroadcast_BruteForce_Null_Null_Null_Null_Null_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectBroadcastRouting<net::NetworkType<net::TCP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, NullOrder<net::NetworkType<net::TCP>>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_DirectBroadcast_BruteForce_Null_Null_Null_Null_BruteForce_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_DirectBroadcast_BruteForce_Null_Null_Null_Null_BruteForce_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_DirectBroadcast_BruteForce_Null_Null_Null_Null_BruteForce_Null_CharVector_TCPType( TEST_DirectBroadcast_BruteForce_Null_Null_Null_Null_BruteForce_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectBroadcastRouting<net::NetworkType<net::UDP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, NullOrder<net::NetworkType<net::UDP>>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_DirectBroadcast_BruteForce_Null_Null_Null_Null_BruteForce_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_DirectBroadcast_BruteForce_Null_Null_Null_Null_BruteForce_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_DirectBroadcast_BruteForce_Null_Null_Null_Null_BruteForce_Null_CharVector_UDPType( TEST_DirectBroadcast_BruteForce_Null_Null_Null_Null_BruteForce_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectBroadcastRouting<net::NetworkType<net::TCP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, DetMergeOrder<net::NetworkType<net::TCP>, m2etis::config::order::DetMergeConfigTest>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_DirectBroadcast_BruteForce_DetMerge_Null_Null_Null_Null_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_DirectBroadcast_BruteForce_DetMerge_Null_Null_Null_Null_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_DirectBroadcast_BruteForce_DetMerge_Null_Null_Null_Null_Null_CharVector_TCPType( TEST_DirectBroadcast_BruteForce_DetMerge_Null_Null_Null_Null_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectBroadcastRouting<net::NetworkType<net::UDP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, DetMergeOrder<net::NetworkType<net::UDP>, m2etis::config::order::DetMergeConfigTest>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_DirectBroadcast_BruteForce_DetMerge_Null_Null_Null_Null_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_DirectBroadcast_BruteForce_DetMerge_Null_Null_Null_Null_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_DirectBroadcast_BruteForce_DetMerge_Null_Null_Null_Null_Null_CharVector_UDPType( TEST_DirectBroadcast_BruteForce_DetMerge_Null_Null_Null_Null_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectBroadcastRouting<net::NetworkType<net::TCP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, DetMergeOrder<net::NetworkType<net::TCP>, m2etis::config::order::DetMergeConfigTest>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_DirectBroadcast_BruteForce_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_DirectBroadcast_BruteForce_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_DirectBroadcast_BruteForce_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_TCPType( TEST_DirectBroadcast_BruteForce_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectBroadcastRouting<net::NetworkType<net::UDP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, DetMergeOrder<net::NetworkType<net::UDP>, m2etis::config::order::DetMergeConfigTest>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_DirectBroadcast_BruteForce_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_DirectBroadcast_BruteForce_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_DirectBroadcast_BruteForce_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_UDPType( TEST_DirectBroadcast_BruteForce_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectBroadcastRouting<net::NetworkType<net::TCP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, MTPOrder<net::NetworkType<net::TCP>, 1000000, LateDeliver::DROP>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_DirectBroadcast_BruteForce_MTP_Null_Null_Null_Null_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_DirectBroadcast_BruteForce_MTP_Null_Null_Null_Null_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_DirectBroadcast_BruteForce_MTP_Null_Null_Null_Null_Null_CharVector_TCPType( TEST_DirectBroadcast_BruteForce_MTP_Null_Null_Null_Null_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectBroadcastRouting<net::NetworkType<net::UDP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, MTPOrder<net::NetworkType<net::UDP>, 1000000, LateDeliver::DROP>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_DirectBroadcast_BruteForce_MTP_Null_Null_Null_Null_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_DirectBroadcast_BruteForce_MTP_Null_Null_Null_Null_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_DirectBroadcast_BruteForce_MTP_Null_Null_Null_Null_Null_CharVector_UDPType( TEST_DirectBroadcast_BruteForce_MTP_Null_Null_Null_Null_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectBroadcastRouting<net::NetworkType<net::TCP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, MTPOrder<net::NetworkType<net::TCP>, 1000000, LateDeliver::DROP>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_DirectBroadcast_BruteForce_MTP_Null_Null_Null_BruteForce_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_DirectBroadcast_BruteForce_MTP_Null_Null_Null_BruteForce_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_DirectBroadcast_BruteForce_MTP_Null_Null_Null_BruteForce_Null_CharVector_TCPType( TEST_DirectBroadcast_BruteForce_MTP_Null_Null_Null_BruteForce_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectBroadcastRouting<net::NetworkType<net::UDP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, MTPOrder<net::NetworkType<net::UDP>, 1000000, LateDeliver::DROP>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_DirectBroadcast_BruteForce_MTP_Null_Null_Null_BruteForce_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_DirectBroadcast_BruteForce_MTP_Null_Null_Null_BruteForce_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_DirectBroadcast_BruteForce_MTP_Null_Null_Null_BruteForce_Null_CharVector_UDPType( TEST_DirectBroadcast_BruteForce_MTP_Null_Null_Null_BruteForce_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::TCP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, NullOrder<net::NetworkType<net::TCP>>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_Spreadit_Null_Null_Null_Null_Null_Null_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_Spreadit_Null_Null_Null_Null_Null_Null_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Spreadit_Null_Null_Null_Null_Null_Null_Null_CharVector_TCPType( TEST_Spreadit_Null_Null_Null_Null_Null_Null_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::UDP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, NullOrder<net::NetworkType<net::UDP>>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_Spreadit_Null_Null_Null_Null_Null_Null_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_Spreadit_Null_Null_Null_Null_Null_Null_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Spreadit_Null_Null_Null_Null_Null_Null_Null_CharVector_UDPType( TEST_Spreadit_Null_Null_Null_Null_Null_Null_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::TCP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, NullOrder<net::NetworkType<net::TCP>>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_Spreadit_Null_Null_Null_Null_Null_BruteForce_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_Spreadit_Null_Null_Null_Null_Null_BruteForce_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Spreadit_Null_Null_Null_Null_Null_BruteForce_Null_CharVector_TCPType( TEST_Spreadit_Null_Null_Null_Null_Null_BruteForce_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::UDP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, NullOrder<net::NetworkType<net::UDP>>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_Spreadit_Null_Null_Null_Null_Null_BruteForce_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_Spreadit_Null_Null_Null_Null_Null_BruteForce_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Spreadit_Null_Null_Null_Null_Null_BruteForce_Null_CharVector_UDPType( TEST_Spreadit_Null_Null_Null_Null_Null_BruteForce_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::TCP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, DetMergeOrder<net::NetworkType<net::TCP>, m2etis::config::order::DetMergeConfigTest>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_Spreadit_Null_DetMerge_Null_Null_Null_Null_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_Spreadit_Null_DetMerge_Null_Null_Null_Null_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Spreadit_Null_DetMerge_Null_Null_Null_Null_Null_CharVector_TCPType( TEST_Spreadit_Null_DetMerge_Null_Null_Null_Null_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::UDP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, DetMergeOrder<net::NetworkType<net::UDP>, m2etis::config::order::DetMergeConfigTest>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_Spreadit_Null_DetMerge_Null_Null_Null_Null_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_Spreadit_Null_DetMerge_Null_Null_Null_Null_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Spreadit_Null_DetMerge_Null_Null_Null_Null_Null_CharVector_UDPType( TEST_Spreadit_Null_DetMerge_Null_Null_Null_Null_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::TCP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, DetMergeOrder<net::NetworkType<net::TCP>, m2etis::config::order::DetMergeConfigTest>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_Spreadit_Null_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_Spreadit_Null_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Spreadit_Null_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_TCPType( TEST_Spreadit_Null_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::UDP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, DetMergeOrder<net::NetworkType<net::UDP>, m2etis::config::order::DetMergeConfigTest>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_Spreadit_Null_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_Spreadit_Null_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Spreadit_Null_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_UDPType( TEST_Spreadit_Null_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::TCP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, MTPOrder<net::NetworkType<net::TCP>, 1000000, LateDeliver::DROP>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_Spreadit_Null_MTP_Null_Null_Null_Null_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_Spreadit_Null_MTP_Null_Null_Null_Null_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Spreadit_Null_MTP_Null_Null_Null_Null_Null_CharVector_TCPType( TEST_Spreadit_Null_MTP_Null_Null_Null_Null_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::UDP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, MTPOrder<net::NetworkType<net::UDP>, 1000000, LateDeliver::DROP>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_Spreadit_Null_MTP_Null_Null_Null_Null_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_Spreadit_Null_MTP_Null_Null_Null_Null_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Spreadit_Null_MTP_Null_Null_Null_Null_Null_CharVector_UDPType( TEST_Spreadit_Null_MTP_Null_Null_Null_Null_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::TCP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, MTPOrder<net::NetworkType<net::TCP>, 1000000, LateDeliver::DROP>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_Spreadit_Null_MTP_Null_Null_Null_BruteForce_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_Spreadit_Null_MTP_Null_Null_Null_BruteForce_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Spreadit_Null_MTP_Null_Null_Null_BruteForce_Null_CharVector_TCPType( TEST_Spreadit_Null_MTP_Null_Null_Null_BruteForce_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::UDP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, MTPOrder<net::NetworkType<net::UDP>, 1000000, LateDeliver::DROP>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_Spreadit_Null_MTP_Null_Null_Null_BruteForce_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_Spreadit_Null_MTP_Null_Null_Null_BruteForce_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Spreadit_Null_MTP_Null_Null_Null_BruteForce_Null_CharVector_UDPType( TEST_Spreadit_Null_MTP_Null_Null_Null_BruteForce_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::TCP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, GMSOrder<net::NetworkType<net::TCP>, 1000000>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_Spreadit_Null_GMS_Null_Null_Null_Null_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_Spreadit_Null_GMS_Null_Null_Null_Null_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Spreadit_Null_GMS_Null_Null_Null_Null_Null_CharVector_TCPType( TEST_Spreadit_Null_GMS_Null_Null_Null_Null_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::UDP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, GMSOrder<net::NetworkType<net::UDP>, 1000000>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_Spreadit_Null_GMS_Null_Null_Null_Null_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_Spreadit_Null_GMS_Null_Null_Null_Null_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Spreadit_Null_GMS_Null_Null_Null_Null_Null_CharVector_UDPType( TEST_Spreadit_Null_GMS_Null_Null_Null_Null_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::TCP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, GMSOrder<net::NetworkType<net::TCP>, 1000000>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_Spreadit_Null_GMS_Null_Null_Null_BruteForce_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_Spreadit_Null_GMS_Null_Null_Null_BruteForce_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Spreadit_Null_GMS_Null_Null_Null_BruteForce_Null_CharVector_TCPType( TEST_Spreadit_Null_GMS_Null_Null_Null_BruteForce_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::UDP>>
, NullFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, GMSOrder<net::NetworkType<net::UDP>, 1000000>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_Spreadit_Null_GMS_Null_Null_Null_BruteForce_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_Spreadit_Null_GMS_Null_Null_Null_BruteForce_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Spreadit_Null_GMS_Null_Null_Null_BruteForce_Null_CharVector_UDPType( TEST_Spreadit_Null_GMS_Null_Null_Null_BruteForce_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::TCP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, NullOrder<net::NetworkType<net::TCP>>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_Spreadit_BruteForce_Null_Null_Null_Null_Null_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_Spreadit_BruteForce_Null_Null_Null_Null_Null_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Spreadit_BruteForce_Null_Null_Null_Null_Null_Null_CharVector_TCPType( TEST_Spreadit_BruteForce_Null_Null_Null_Null_Null_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::UDP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, NullOrder<net::NetworkType<net::UDP>>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_Spreadit_BruteForce_Null_Null_Null_Null_Null_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_Spreadit_BruteForce_Null_Null_Null_Null_Null_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Spreadit_BruteForce_Null_Null_Null_Null_Null_Null_CharVector_UDPType( TEST_Spreadit_BruteForce_Null_Null_Null_Null_Null_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::TCP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, NullOrder<net::NetworkType<net::TCP>>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_Spreadit_BruteForce_Null_Null_Null_Null_BruteForce_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_Spreadit_BruteForce_Null_Null_Null_Null_BruteForce_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Spreadit_BruteForce_Null_Null_Null_Null_BruteForce_Null_CharVector_TCPType( TEST_Spreadit_BruteForce_Null_Null_Null_Null_BruteForce_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::UDP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, NullOrder<net::NetworkType<net::UDP>>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_Spreadit_BruteForce_Null_Null_Null_Null_BruteForce_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_Spreadit_BruteForce_Null_Null_Null_Null_BruteForce_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Spreadit_BruteForce_Null_Null_Null_Null_BruteForce_Null_CharVector_UDPType( TEST_Spreadit_BruteForce_Null_Null_Null_Null_BruteForce_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::TCP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, DetMergeOrder<net::NetworkType<net::TCP>, m2etis::config::order::DetMergeConfigTest>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_Spreadit_BruteForce_DetMerge_Null_Null_Null_Null_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_Spreadit_BruteForce_DetMerge_Null_Null_Null_Null_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Spreadit_BruteForce_DetMerge_Null_Null_Null_Null_Null_CharVector_TCPType( TEST_Spreadit_BruteForce_DetMerge_Null_Null_Null_Null_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::UDP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, DetMergeOrder<net::NetworkType<net::UDP>, m2etis::config::order::DetMergeConfigTest>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_Spreadit_BruteForce_DetMerge_Null_Null_Null_Null_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_Spreadit_BruteForce_DetMerge_Null_Null_Null_Null_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Spreadit_BruteForce_DetMerge_Null_Null_Null_Null_Null_CharVector_UDPType( TEST_Spreadit_BruteForce_DetMerge_Null_Null_Null_Null_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::TCP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, DetMergeOrder<net::NetworkType<net::TCP>, m2etis::config::order::DetMergeConfigTest>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_Spreadit_BruteForce_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_Spreadit_BruteForce_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Spreadit_BruteForce_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_TCPType( TEST_Spreadit_BruteForce_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::UDP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, DetMergeOrder<net::NetworkType<net::UDP>, m2etis::config::order::DetMergeConfigTest>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_Spreadit_BruteForce_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_Spreadit_BruteForce_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Spreadit_BruteForce_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_UDPType( TEST_Spreadit_BruteForce_DetMerge_Null_Null_Null_BruteForce_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::TCP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, MTPOrder<net::NetworkType<net::TCP>, 1000000, LateDeliver::DROP>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_Spreadit_BruteForce_MTP_Null_Null_Null_Null_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_Spreadit_BruteForce_MTP_Null_Null_Null_Null_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Spreadit_BruteForce_MTP_Null_Null_Null_Null_Null_CharVector_TCPType( TEST_Spreadit_BruteForce_MTP_Null_Null_Null_Null_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::UDP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, MTPOrder<net::NetworkType<net::UDP>, 1000000, LateDeliver::DROP>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_Spreadit_BruteForce_MTP_Null_Null_Null_Null_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_Spreadit_BruteForce_MTP_Null_Null_Null_Null_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Spreadit_BruteForce_MTP_Null_Null_Null_Null_Null_CharVector_UDPType( TEST_Spreadit_BruteForce_MTP_Null_Null_Null_Null_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::TCP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, MTPOrder<net::NetworkType<net::TCP>, 1000000, LateDeliver::DROP>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_Spreadit_BruteForce_MTP_Null_Null_Null_BruteForce_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_Spreadit_BruteForce_MTP_Null_Null_Null_BruteForce_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Spreadit_BruteForce_MTP_Null_Null_Null_BruteForce_Null_CharVector_TCPType( TEST_Spreadit_BruteForce_MTP_Null_Null_Null_BruteForce_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::UDP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, MTPOrder<net::NetworkType<net::UDP>, 1000000, LateDeliver::DROP>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_Spreadit_BruteForce_MTP_Null_Null_Null_BruteForce_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_Spreadit_BruteForce_MTP_Null_Null_Null_BruteForce_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Spreadit_BruteForce_MTP_Null_Null_Null_BruteForce_Null_CharVector_UDPType( TEST_Spreadit_BruteForce_MTP_Null_Null_Null_BruteForce_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::TCP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, GMSOrder<net::NetworkType<net::TCP>, 1000000>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_Spreadit_BruteForce_GMS_Null_Null_Null_Null_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_Spreadit_BruteForce_GMS_Null_Null_Null_Null_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Spreadit_BruteForce_GMS_Null_Null_Null_Null_Null_CharVector_TCPType( TEST_Spreadit_BruteForce_GMS_Null_Null_Null_Null_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::UDP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, GMSOrder<net::NetworkType<net::UDP>, 1000000>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, NullPartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_Spreadit_BruteForce_GMS_Null_Null_Null_Null_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_Spreadit_BruteForce_GMS_Null_Null_Null_Null_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Spreadit_BruteForce_GMS_Null_Null_Null_Null_Null_CharVector_UDPType( TEST_Spreadit_BruteForce_GMS_Null_Null_Null_Null_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::TCP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::TCP>>
, GMSOrder<net::NetworkType<net::TCP>, 1000000>
, NullDeliver<net::NetworkType<net::TCP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::TCP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::TCP>,
CharVectorEventType
> TEST_Spreadit_BruteForce_GMS_Null_Null_Null_BruteForce_Null_CharVector_TCPType;
template <>
struct ChannelT<TEST_Spreadit_BruteForce_GMS_Null_Null_Null_BruteForce_Null_CharVector_TCP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Spreadit_BruteForce_GMS_Null_Null_Null_BruteForce_Null_CharVector_TCPType( TEST_Spreadit_BruteForce_GMS_Null_Null_Null_BruteForce_Null_CharVector_TCP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
SpreaditRouting<net::NetworkType<net::UDP>>
, BruteForceFilter<CharVectorEventType, net::NetworkType<net::UDP>>
, GMSOrder<net::NetworkType<net::UDP>, 1000000>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, BruteForcePartition<net::NetworkType<net::UDP>, CharVectorEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
CharVectorEventType
> TEST_Spreadit_BruteForce_GMS_Null_Null_Null_BruteForce_Null_CharVector_UDPType;
template <>
struct ChannelT<TEST_Spreadit_BruteForce_GMS_Null_Null_Null_BruteForce_Null_CharVector_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Spreadit_BruteForce_GMS_Null_Null_Null_BruteForce_Null_CharVector_UDPType( TEST_Spreadit_BruteForce_GMS_Null_Null_Null_BruteForce_Null_CharVector_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
typedef Channel<
ChannelType<
DirectRouting<net::NetworkType<net::UDP>>
, NullFilter<IntegrationTestEventType, net::NetworkType<net::UDP>>
, NullOrder<net::NetworkType<net::UDP>>
, NullDeliver<net::NetworkType<net::UDP>>
, NullPersistence
, NullValidity
, DirectBroadcastPartition<net::NetworkType<net::UDP>, IntegrationTestEventType>
, NullSecurity, NullRendezvous
>,
net::NetworkType<net::UDP>,
IntegrationTestEventType
> TEST_Direct_Integration_UDPType;
template <>
struct ChannelT<TEST_Direct_Integration_UDP>{
ChannelT(const std::string & ip, const unsigned short port, const std::string & known_hostname, const unsigned short known_hostport, PubSubSystemEnvironment * pssi, std::vector<ChannelEventInterface *> & map, const std::vector<std::string> & rootList)
{
map.push_back(new TEST_Direct_Integration_UDPType(TEST_Direct_Integration_UDP, ip, port, known_hostname, known_hostport, pssi, rootList));
}
};
#endif
#endif
|
gopherpit/gopherpit | server/routers_feapi.go | // Copyright (c) 2017, <NAME> <<EMAIL>>
// All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package server
import (
"net/http"
"resenje.org/web"
"github.com/gorilla/mux"
)
func newFrontendAPIRouter(s *Server) http.Handler {
frontendAPIRouter := mux.NewRouter().StrictSlash(true)
frontendAPIRouter.NotFoundHandler = http.HandlerFunc(jsonNotFoundHandler)
// Frontend API routes start
// ACME
frontendAPIRouter.Handle("/i/register-acme-user", jsonMethodHandler{
"POST": http.HandlerFunc(s.registerACMEUserFEAPIHandler),
})
// User public
frontendAPIRouter.Handle("/i/auth", jsonMethodHandler{
"POST": http.HandlerFunc(s.authLoginFEAPIHandler),
"DELETE": http.HandlerFunc(s.authLogoutFEAPIHandler),
})
frontendAPIRouter.Handle("/i/registration", jsonMethodHandler{
"POST": http.HandlerFunc(s.registrationFEAPIHandler),
})
frontendAPIRouter.Handle("/i/password-reset-token", jsonMethodHandler{
"POST": http.HandlerFunc(s.passwordResetTokenFEAPIHandler),
})
frontendAPIRouter.Handle("/i/password-reset", jsonMethodHandler{
"POST": http.HandlerFunc(s.passwordResetFEAPIHandler),
})
frontendAPIRouter.Handle(`/i/email/opt-out/{token:\w{27,}}`, jsonMethodHandler{
"POST": http.HandlerFunc(s.emailOptOutFEAPIHandler),
"DELETE": http.HandlerFunc(s.emailRemoveOptOutFEAPIHandler),
})
// Contact
frontendAPIRouter.Handle("/i/contact", jsonMethodHandler{
"POST": s.htmlLoginAltHandler(
http.HandlerFunc(s.contactPrivateFEAPIHandler),
http.HandlerFunc(s.contactFEAPIHandler),
),
})
// User settings
frontendAPIRouter.Handle("/i/user", web.ChainHandlers(
s.jsonLoginRequiredHandler,
web.FinalHandler(jsonMethodHandler{
"POST": http.HandlerFunc(s.userFEAPIHandler),
}),
))
frontendAPIRouter.Handle("/i/user/email", web.ChainHandlers(
s.jsonLoginRequiredHandler,
web.FinalHandler(jsonMethodHandler{
"POST": http.HandlerFunc(s.userEmailFEAPIHandler),
}),
))
frontendAPIRouter.Handle("/i/user/notifications", web.ChainHandlers(
s.jsonLoginRequiredHandler,
web.FinalHandler(jsonMethodHandler{
"POST": http.HandlerFunc(s.userNotificationsSettingsFEAPIHandler),
}),
))
frontendAPIRouter.Handle("/i/user/email/validation-email", web.ChainHandlers(
s.jsonLoginRequiredHandler,
web.FinalHandler(jsonMethodHandler{
"POST": http.HandlerFunc(s.userSendEmailValidationEmailFEAPIHandler),
}),
))
frontendAPIRouter.Handle("/i/user/password", web.ChainHandlers(
s.jsonLoginRequiredHandler,
web.FinalHandler(jsonMethodHandler{
"POST": http.HandlerFunc(s.userPasswordFEAPIHandler),
}),
))
frontendAPIRouter.Handle("/i/user/delete", web.ChainHandlers(
s.jsonLoginRequiredHandler,
web.FinalHandler(jsonMethodHandler{
"POST": http.HandlerFunc(s.userDeleteFEAPIHandler),
}),
))
// API settings
frontendAPIRouter.Handle(`/i/api/key`, web.ChainHandlers(
s.apiDisabledHandler,
s.jsonLoginRequiredHandler,
web.FinalHandler(jsonMethodHandler{
"POST": http.HandlerFunc(s.apiKeyFEAPIHandler),
"DELETE": http.HandlerFunc(s.apiKeyDeleteFEAPIHandler),
}),
))
frontendAPIRouter.Handle(`/i/api/networks`, web.ChainHandlers(
s.apiDisabledHandler,
s.jsonLoginRequiredHandler,
web.FinalHandler(jsonMethodHandler{
"POST": http.HandlerFunc(s.apiNetworksFEAPIHandler),
}),
))
frontendAPIRouter.Handle(`/i/api/secret`, web.ChainHandlers(
s.apiDisabledHandler,
s.jsonLoginRequiredHandler,
web.FinalHandler(jsonMethodHandler{
"POST": http.HandlerFunc(s.apiRegenerateSecretFEAPIHandler),
}),
))
// SSL Certificate
frontendAPIRouter.Handle(`/i/certificate/{id}`, web.ChainHandlers(
s.jsonLoginRequiredHandler,
s.jsonValidatedEmailRequiredHandler,
web.FinalHandler(jsonMethodHandler{
"POST": http.HandlerFunc(s.certificateFEAPIHandler),
}),
))
// Domain
frontendAPIRouter.Handle(`/i/domain`, web.ChainHandlers(
s.jsonLoginRequiredHandler,
s.jsonValidatedEmailRequiredHandler,
web.FinalHandler(jsonMethodHandler{
"POST": http.HandlerFunc(s.domainFEAPIHandler),
}),
))
frontendAPIRouter.Handle(`/i/domain/{id}`, web.ChainHandlers(
s.jsonLoginRequiredHandler,
s.jsonValidatedEmailRequiredHandler,
web.FinalHandler(jsonMethodHandler{
"POST": http.HandlerFunc(s.domainFEAPIHandler),
"DELETE": http.HandlerFunc(s.domainDeleteFEAPIHandler),
}),
))
frontendAPIRouter.Handle(`/i/domain/{id}/user`, web.ChainHandlers(
s.jsonLoginRequiredHandler,
s.jsonValidatedEmailRequiredHandler,
web.FinalHandler(jsonMethodHandler{
"POST": http.HandlerFunc(s.domainUserGrantFEAPIHandler),
"DELETE": http.HandlerFunc(s.domainUserRevokeFEAPIHandler),
}),
))
frontendAPIRouter.Handle(`/i/domain/{id}/owner`, web.ChainHandlers(
s.jsonLoginRequiredHandler,
s.jsonValidatedEmailRequiredHandler,
web.FinalHandler(jsonMethodHandler{
"POST": http.HandlerFunc(s.domainOwnerChangeFEAPIHandler),
}),
))
// Package
frontendAPIRouter.Handle(`/i/package`, web.ChainHandlers(
s.jsonLoginRequiredHandler,
s.jsonValidatedEmailRequiredHandler,
web.FinalHandler(jsonMethodHandler{
"POST": http.HandlerFunc(s.packageFEAPIHandler),
}),
))
frontendAPIRouter.Handle(`/i/package/{id}`, web.ChainHandlers(
s.jsonLoginRequiredHandler,
s.jsonValidatedEmailRequiredHandler,
web.FinalHandler(jsonMethodHandler{
"POST": http.HandlerFunc(s.packageFEAPIHandler),
"DELETE": http.HandlerFunc(s.packageDeleteFEAPIHandler),
}),
))
// Frontend API routes end
return frontendAPIRouter
}
|
upsidedownio/behivejs | src/decorators/UntilFailure.js | <filename>src/decorators/UntilFailure.js<gh_stars>1-10
const BaseDecorator = require('../core/BaseDecorator');
const {SUCCESS, FAILURE, ERROR, RUNNING} = require('../constants');
/**
* Class UntilFailure
* UntilFailure is a decorator that repeats the run signal until the
* node child returns `FAILURE`, `RUNNING` or `ERROR`. Optionally, a maximum
* number of repetitions can be defined.
*
* @extends BaseDecorator
* @category Decorators
**/
class UntilFailure extends BaseDecorator {
/**
* Creates an instance of UntilFailure.
* - **maxLoop** (*Integer*) Maximum number of repetitions. Default to -1 (infinite).
* - **child** (*BaseNode*) The child node.
* @constructor
* @param {object} params - Object with parameters.
* @param {BaseNode} params.child - The child node.
* @param {number} [params.maxLoop=-1] - Maximum number of repetitions.
* Default to -1 (infinite).
**/
constructor({maxLoop = -1, child = null} = {}) {
super({
child,
type: 'UntilFailure',
name: 'Until Failure',
properties: {maxLoop: -1},
});
this.maxLoop = maxLoop;
}
/**
* Open method.
* @param {Context} context A run instance.
**/
open(context) {
context.treeBoard.node(this.id).set('i', 0);
}
/**
* Context method.
* @param {Context} context A run instance.
* @return {NodeStatus} A state constant.
**/
run(context) {
if (!this.child) {
return ERROR;
}
let i = context.treeBoard.node(this.id).get('i');
let childStatus = RUNNING;
if (this.maxLoop < 0 || i < this.maxLoop) {
childStatus = this.child.tick(context);
if (childStatus === SUCCESS) {
i++;
} else if (childStatus === RUNNING) {
return RUNNING;
} else if (childStatus === FAILURE) {
// end condition
return SUCCESS;
} else {
return ERROR;
}
} else if (i >= this.maxLoop) {
return SUCCESS;
}
context.treeBoard.node(this.id).set('i', i);
return childStatus;
}
}
module.exports = UntilFailure;
|
ankurshukla1993/IOT-test | coeey/com/ihealth/communication/control/ae.java | package com.ihealth.communication.control;
import com.ihealth.communication.p001a.C2026d;
class ae implements C2026d {
final /* synthetic */ C2067n f1242a;
ae(C2067n c2067n) {
this.f1242a = c2067n;
}
public void mo5513a() {
Integer[] numArr = new Integer[6];
for (int i = 0; i < 6; i++) {
numArr[i] = Integer.valueOf((int) (Math.random() * 10.0d));
}
this.f1242a.f1014b.x09Ins(numArr);
}
}
|
robertvanloenhout/jwarc | src/org/netpreserve/jwarc/WarcFilterCompiler.java | <filename>src/org/netpreserve/jwarc/WarcFilterCompiler.java
package org.netpreserve.jwarc;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.regex.Pattern;
class WarcFilterCompiler {
private final WarcFilterLexer lexer;
WarcFilterCompiler(String expression) {
lexer = new WarcFilterLexer(expression);
}
/*
* predicate = unary
* | unary "&&" predicate
* | unary "||" predicate;
*/
Predicate<WarcRecord> predicate() {
Predicate<WarcRecord> lhs = unary();
if (lexer.atEnd()) return lhs;
String operator = lexer.peekOperator();
if (operator == null) throw lexer.error("expected operator");
switch (operator) {
case ")":
return lhs;
case "&&":
lexer.advance();
return lhs.and(predicate());
case "||":
lexer.advance();
return lhs.or(predicate());
default:
throw lexer.error("operator not allowed here: " + operator);
}
}
/*
* unary = comparison
* | "(" predicate ")"
* | "!(" predicate ")";
*/
private Predicate<WarcRecord> unary() {
String operator = lexer.peekOperator();
if (operator == null) {
return comparison();
} else if (operator.equals("!(") || operator.equals("(")) {
lexer.advance();
Predicate<WarcRecord> predicate = predicate();
if (!")".equals(lexer.operator())) {
throw lexer.error("')' expected");
}
return operator.startsWith("!") ? predicate.negate() : predicate;
} else {
throw lexer.error("operator not allowed here: " + operator);
}
}
/*
* comparison = field "==" (string/number)
* | field "!=" (string/number)
* | field "=~" string
* | field "!~" string
* | field "<" number
* | field ">" number
* | field "<=" number
* | field ">=" number;
*/
private Predicate<WarcRecord> comparison() {
Accessor lhs = accessor(lexer.token());
String operator = lexer.operator();
if (operator == null) throw lexer.error("expected operator");
switch (operator) {
case "==":
case "!=": {
Object rhs = lexer.stringOrNumber();
Predicate<WarcRecord> pred;
if (rhs instanceof String) {
pred = rec -> lhs.string(rec).equals(rhs);
} else {
long value = (Long) rhs;
pred = rec -> lhs.integer(rec) == value;
}
return operator.equals("!=") ? pred.negate() : pred;
}
case "=~": {
Pattern pattern = Pattern.compile(lexer.string());
return rec -> pattern.matcher(lhs.string(rec)).matches();
}
case "!~": {
Pattern pattern = Pattern.compile(lexer.string());
return rec -> !pattern.matcher(lhs.string(rec)).matches();
}
case "<": {
long value = Long.parseLong(lexer.token());
return rec -> lhs.integer(rec) < value;
}
case "<=": {
long value = Long.parseLong(lexer.token());
return rec -> lhs.integer(rec) <= value;
}
case ">=": {
long value = Long.parseLong(lexer.token());
return rec -> lhs.integer(rec) >= value;
}
case ">": {
long value = Long.parseLong(lexer.token());
return rec -> lhs.integer(rec) > value;
}
}
throw lexer.error("operator not allowed here: " + operator);
}
private interface Accessor {
Optional<String> raw(WarcRecord record);
default String string(WarcRecord record) {
return raw(record).orElse("");
}
default long integer(WarcRecord record) {
try {
return Long.parseLong(raw(record).orElse("0"));
} catch (NumberFormatException e) {
return 0;
}
}
}
private Accessor accessor(String token) {
if (":status".equals(token)) {
return record -> {
try {
if (!(record instanceof WarcResponse)) return Optional.empty();
if (!record.contentType().equals(MediaType.HTTP_RESPONSE)) return Optional.empty();
return Optional.of(Integer.toString(((WarcResponse) record).http().status()));
} catch (Exception e) {
return Optional.empty();
}
};
} else if (token.startsWith("http:")) {
String field = token.substring("http:".length());
return record -> {
try {
if (record instanceof WarcRequest && record.contentType().equals(MediaType.HTTP_REQUEST)) {
return ((WarcRequest) record).http().headers().first(field);
} else if (record instanceof WarcResponse && record.contentType().equals(MediaType.HTTP_RESPONSE)) {
return ((WarcResponse) record).http().headers().first(field);
} else {
return Optional.empty();
}
} catch (Exception e) {
return Optional.empty();
}
};
} else {
return record -> record.headers().first(token);
}
}
}
|
copslock/broadcom_cpri | sdk-6.5.20/libs/sdklt/bcmltx/bcmmon/bcmltx_mon_gen_index.c | /*! \file bcmltx_mon_gen_index.c
*
* Egress drop mask profile LT key combination to
* LTM track index transform handler.
*/
/*
* This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file.
*
* Copyright 2007-2020 Broadcom Inc. All rights reserved.
*/
#include <sal/sal_libc.h>
#include <shr/shr_debug.h>
#include <bsl/bsl.h>
#include <bcmltx/bcmmon/bcmltx_mon_gen_index.h>
/* BSL Module */
#define BSL_LOG_MODULE BSL_LS_BCMLTX_MON
/*******************************************************************************
* Public functions
*/
int
bcmltx_mon_gen_index_transform(int unit,
const bcmltd_fields_t *in,
bcmltd_fields_t *out,
const bcmltd_transform_arg_t *arg)
{
SHR_FUNC_ENTER(unit);
if ((in->count != 2)) {
SHR_ERR_EXIT(SHR_E_PARAM);
}
if (arg->values != 1) {
SHR_ERR_EXIT(SHR_E_PARAM);
}
out->field[0]->data = (in->field[0]->data << arg->value[0]) + in->field[1]->data;
out->field[0]->idx = 0;
out->field[0]->id = arg->rfield[0];
out->count = 1;
exit:
SHR_FUNC_EXIT();
return 0;
}
int
bcmltx_mon_gen_index_rev_transform(int unit,
const bcmltd_fields_t *in,
bcmltd_fields_t *out,
const bcmltd_transform_arg_t *arg)
{
uint32_t track_idx;
SHR_FUNC_ENTER(unit);
if ((in->count != 1)) {
SHR_ERR_EXIT(SHR_E_PARAM);
}
track_idx = in->field[0]->data;
/* First index */
out->field[0]->data = track_idx >> arg->value[0];
out->field[0]->id = arg->rfield[0];
out->field[0]->idx = 0;
/* Second index */
out->field[1]->data = track_idx & (( 1 << arg->value[0]) - 1);
out->field[1]->id = arg->rfield[1];
out->field[1]->idx = 0;
out->count = 2;
exit:
SHR_FUNC_EXIT();
}
|
shaojiankui/iOS10-Runtime-Headers | protocols/PUInterfaceTheme.h | <filename>protocols/PUInterfaceTheme.h
/* Generated by RuntimeBrowser.
*/
@protocol PUInterfaceTheme <NSObject>
@required
- (UIColor *)airPlayControllerBackgroundColor;
- (UIColor *)airPlayVideoPlaceholderBackgroundColor;
- (UIImage *)airPlayVideoPlaceholderIcon;
- (UIColor *)airPlayVideoPlaceholderIconTintColor;
- (UIFont *)airPlayVideoPlaceholderMessageFont;
- (UIColor *)airPlayVideoPlaceholderMessageTextColor;
- (UIFont *)airPlayVideoPlaceholderTitleFont;
- (UIColor *)airPlayVideoPlaceholderTitleTextColor;
- (UIColor *)albumBadgeInTitleColor;
- (UIColor *)albumCornersBackgroundColor;
- (UIColor *)albumListBackgroundColor;
- (double)albumListDisabledAlbumStackViewAlpha;
- (double)albumListDisabledAlbumTitleAlpha;
- (UIFont *)albumListSectionTitleLabelFont;
- (UIFont *)albumListSubtitleLabelFont;
- (UIFont *)albumListTitleLabelFont;
- (NSAttributedString *)attributedStringForCloudFeedGroupHeaderWithText:(NSString *)arg1;
- (UIColor *)badgeOverThumbnailColor;
- (UIColor *)bannerBackgroundColor;
- (double)bannerHeight;
- (UIColor *)cloudFeedBackgroundColor;
- (NSDictionary *)cloudFeedDefaultTextAttributes;
- (NSDictionary *)cloudFeedEmphasizedTextAttributes;
- (NSDictionary *)cloudFeedInteractionLargerTextAttributes;
- (NSDictionary *)cloudFeedInteractionTextAttributes;
- (NSDictionary *)cloudFeedInvitationSubtitleTextAttributes;
- (NSDictionary *)cloudFeedInvitationTitleTextAttributes;
- (NSDictionary *)cloudFeedLargerDefaultTextAttributes;
- (NSDictionary *)cloudFeedLargerEmphasizedTextAttributes;
- (UIImage *)cloudFeedMiniChevronImage;
- (UIImage *)cloudFeedSectionHeaderBackgroundImage;
- (UIColor *)cloudFeedSeparatorColor;
- (double)cloudFeedSeparatorHeight;
- (NSDictionary *)cloudFeedWhiteDefaultTextAttributes;
- (NSDictionary *)cloudFeedWhiteEmphasizedTextAttributes;
- (UIColor *)cloudStatusHighlightColor;
- (UIFont *)cloudWelcomeViewTitleLabelFontForSize:(double)arg1;
- (NSString *)commentsButtonStringForCount:(long long)arg1;
- (struct UIEdgeInsets { double x1; double x2; double x3; double x4; })commentsButtonTextInset;
- (UIImage *)compactLoadErrorIcon;
- (void)configureAlbumListDeleteButton:(UIButton *)arg1;
- (void)configureAlbumListEmptyStackViewPadPhotoDecoration:(PUPhotoDecoration *)arg1;
- (void)configureAlbumListEmptyStackViewPhonePhotoDecoration:(PUPhotoDecoration *)arg1;
- (void)configureAlbumListSectionTitleLabel:(UILabel *)arg1;
- (void)configureAlbumListStackViewPadPhotoDecoration:(PUPhotoDecoration *)arg1;
- (void)configureAlbumListStackViewPhonePhotoDecoration:(PUPhotoDecoration *)arg1;
- (void)configureAlbumListSubtitleLabel:(UILabel *)arg1 asOpaque:(bool)arg2;
- (void)configureAlbumListTitleLabel:(UILabel *)arg1 asOpaque:(bool)arg2;
- (void)configureAlbumListTitleTextField:(UITextField *)arg1 asOpaque:(bool)arg2;
- (void)configureBannerLabel:(UILabel *)arg1;
- (void)configureBannerStackView:(PUStackView *)arg1;
- (void)configureCloudFeedCommentButton:(UIButton *)arg1 withCount:(long long)arg2;
- (void)configureCloudFeedInvitationReplyButton:(UIButton *)arg1;
- (void)configureCloudFeedStackView:(PUStackView *)arg1 withStackSize:(struct CGSize { double x1; double x2; })arg2;
- (void)configureEditPluginListCellLabel:(UILabel *)arg1;
- (void)configureEditPluginListNavigationController:(UINavigationController *)arg1;
- (void)configureEditPluginNavigationController:(UINavigationController *)arg1;
- (void)configureEditPluginUserDefaultsAccessorySwitch:(UISwitch *)arg1;
- (void)configureEditPluginUserDefaultsCell:(UITableViewCell *)arg1 withIcon:(UIImage *)arg2 title:(NSString *)arg3;
- (void)configureEditPluginUserDefaultsTableView:(UITableView *)arg1;
- (void)configureMapViewAnnotationCountLabel:(UILabel *)arg1;
- (void)configurePhotoCollectionGlobalFooterSubtitleLabel:(UILabel *)arg1;
- (void)configurePhotoCollectionGlobalFooterTitleLabel:(UILabel *)arg1;
- (void)configurePhotoCollectionHeaderDateLabel:(UILabel *)arg1 forStyle:(long long)arg2;
- (void)configurePhotoCollectionHeaderLocationsLabel:(UILabel *)arg1 forStyle:(long long)arg2;
- (void)configurePhotoCollectionHeaderTitleLabel:(UILabel *)arg1 forStyle:(long long)arg2;
- (void)configureProgressIndicatorMessageLabel:(UILabel *)arg1;
- (void)configureSearchSubtitleLabel:(UILabel *)arg1;
- (void)configureSearchTitleLabel:(UILabel *)arg1;
- (void)configureSlideshowMusicHeaderTitleLabel:(UILabel *)arg1;
- (struct UIEdgeInsets { double x1; double x2; double x3; double x4; })contentCommentsButtonImageInset;
- (UIColor *)contentCommentsHiddenButtonImageColor;
- (NSDictionary *)contentCommentsHiddenButtonTextAttributes;
- (UIColor *)contentCommentsShownButtonImageColor;
- (NSDictionary *)contentCommentsShownButtonTextAttributes;
- (UIButton *)createCloudFeedCommentButton;
- (long long)defaultKeyboardAppearance;
- (unsigned long long)emptyPlaceholderStyle;
- (UIColor *)emptyPlaceholderViewBackgroundColor;
- (UIColor *)folderCellBackgroundColor;
- (UIColor *)gridViewCellBannerBackgroundColor;
- (UIImage *)gridViewCellBannerBackgroundImage;
- (UIColor *)gridViewCellBannerDestructiveTextColor;
- (UIColor *)gridViewCellBannerTextColor;
- (UIFont *)gridViewCellBannerTextFont;
- (double)padAlbumCornerRadius;
- (double)phoneAlbumCornerRadius;
- (long long)photoBrowserBarStyle;
- (UIColor *)photoBrowserChromeHiddenBackgroundColor;
- (UIColor *)photoBrowserChromeVisibleBackgroundColor;
- (UIFont *)photoBrowserPhotoPrimaryTitleFont;
- (UIFont *)photoBrowserPhotoSubtitleFont;
- (long long)photoBrowserStatusBarStyle;
- (UIFont *)photoBrowserTimeTitleFont;
- (UIColor *)photoBrowserTitleViewTappableTextColor;
- (UIColor *)photoBrowserTitleViewTextColor;
- (UIFontDescriptor *)photoCollectionGlobalFooterSubtitleLabelFontDescriptor;
- (UIFontDescriptor *)photoCollectionGlobalFooterTitleLabelFontDescriptor;
- (NSDictionary *)photoCollectionHeaderActionButtonAttributesForStyle:(long long)arg1;
- (UIFontDescriptor *)photoCollectionHeaderActionButtonFontDescriptorForStyle:(long long)arg1;
- (UIColor *)photoCollectionHeaderBackgroundColorForBackgroundStyle:(unsigned long long)arg1;
- (UIFontDescriptor *)photoCollectionHeaderDateLabelFontDescriptorForStyle:(long long)arg1;
- (UIImage *)photoCollectionHeaderDisclosureIconForStyle:(long long)arg1;
- (struct UIOffset { double x1; double x2; })photoCollectionHeaderLocationIconOffsetForStyle:(long long)arg1;
- (UIFontDescriptor *)photoCollectionHeaderLocationLabelFontDescriptorForStyle:(long long)arg1;
- (UIFontDescriptor *)photoCollectionHeaderTitleLabelFontDescriptorForStyle:(long long)arg1;
- (double)photoCollectionToolbarIconToTextSpacerWidth;
- (double)photoCollectionToolbarTextTitleSpacerWidth;
- (UIColor *)photoCollectionViewBackgroundColor;
- (int)photoCollectionViewBackgroundColorValue;
- (UIColor *)photoCollectionViewSecondScreenBackgroundColor;
- (UIColor *)photoEditingActiveFilterTitleColor;
- (UIColor *)photoEditingAdjustmentsBarBackgroundColor;
- (UIColor *)photoEditingAdjustmentsBarHighlightColor;
- (UIColor *)photoEditingAdjustmentsBarMainColor;
- (UIColor *)photoEditingAdjustmentsBarPlayheadColor;
- (UIColor *)photoEditingAdjustmentsModeLabelColor;
- (UIFont *)photoEditingAdjustmentsModeLabelFont;
- (UIFont *)photoEditingAdjustmentsModePickerFont;
- (UIColor *)photoEditingAdjustmentsModePickerValueColor;
- (UIFont *)photoEditingAdjustmentsModePickerValueFont;
- (UIColor *)photoEditingAdjustmentsToolBackgroundColor;
- (UIColor *)photoEditingBackgroundColor;
- (UIColor *)photoEditingCropButtonColor;
- (UIColor *)photoEditingCropButtonSelectedColor;
- (UIColor *)photoEditingCropTiltWheelColor;
- (UIFont *)photoEditingCropTiltWheelFont;
- (UIColor *)photoEditingCropToggleButtonColor;
- (UIFont *)photoEditingCropToggleButtonFont;
- (UIFont *)photoEditingFilterTitleFont;
- (UIColor *)photoEditingInactiveFilterTitleColor;
- (UIColor *)photoEditingIrisDisabledColor;
- (UIColor *)photoEditingIrisEnabledColor;
- (UIColor *)photoEditingOverlayBadgeBackgroundColor;
- (UIColor *)photoEditingOverlayBadgeColor;
- (UIFont *)photoEditingOverlayBadgeFont;
- (UIFont *)photoEditingToolbarButtonCompactFont;
- (UIFont *)photoEditingToolbarButtonNormalFont;
- (UIColor *)photoEditingToolbarDestructiveButtonColor;
- (UIColor *)photoEditingToolbarMainButtonColor;
- (UIColor *)photoEditingToolbarSecondaryButtonColor;
- (UIColor *)photoEditingTooltipColor;
- (UIFont *)photoEditingTooltipFont;
- (UIColor *)placeholderCellBackgroundColor;
- (UIColor *)playbackTimeLabelBackgroundColor;
- (UIFont *)playbackTimeLabelFont;
- (UIColor *)playheadBackgroundColor;
- (UIColor *)playheadColor;
- (UIImage *)regularLoadErrorIcon;
- (UIColor *)scrubberPlaceholderColor;
- (NSDictionary *)searchDefaultAttributes;
- (NSDictionary *)searchHighlightedAttributes;
- (UIFont *)searchRecentLabelFont;
- (UIColor *)searchRecentLabelTextColor;
- (UIFont *)searchSubtitleLabelFont;
- (UIColor *)searchSubtitleTextColor;
- (UIColor *)searchTableViewBackgroundColor;
- (UIFont *)searchTitleLabelFont;
- (UIFont *)sharedAlbumCommentCardAlbumTitleFont;
- (UIFont *)sharedAlbumCommentCardButtonFont;
- (UIFont *)sharedAlbumCommentCardTextFont;
- (UIFont *)sharedAlbumCommentCardTitleFont;
- (UIImage *)slideshowAirplayImage;
- (UIColor *)slideshowChromeBarTintColor;
- (UIColor *)slideshowMusicHeaderBackgroundColor;
- (UIColor *)slideshowMusicHeaderTextColor;
- (UIColor *)slideshowSeparatorColor;
- (struct UIEdgeInsets { double x1; double x2; double x3; double x4; })slideshowSeparatorInset;
- (UIColor *)tintColorForBarStyle:(long long)arg1;
- (UIColor *)toolbarAirPlayButtonColor;
- (UIColor *)toolbarCommentsHiddenButtonImageColor;
- (NSDictionary *)toolbarCommentsHiddenButtonTextAttributes;
- (UIColor *)toolbarCommentsShownButtonImageColor;
- (NSDictionary *)toolbarCommentsShownButtonTextAttributes;
- (UIImage *)topLevelNavigationBarBackButtonBackgroundImageForState:(unsigned long long)arg1 barMetrics:(long long)arg2;
- (UIImage *)topLevelNavigationBarButtonBackgroundImageForState:(unsigned long long)arg1 barMetrics:(long long)arg2;
- (UIColor *)topLevelNavigationBarButtonTintColor;
- (struct UIOffset { double x1; double x2; })topLevelNavigationBarButtonTitlePositionAdjustmentforBarMetrics:(long long)arg1;
- (NSDictionary *)topLevelNavigationBarButtonTitleTextAttributesForState:(unsigned long long)arg1;
- (UIImage *)topLevelNavigationBarDoneButtonBackgroundImageForState:(unsigned long long)arg1 barMetrics:(long long)arg2;
- (NSDictionary *)topLevelNavigationBarDoneButtonTitleTextAttributesForState:(unsigned long long)arg1;
- (long long)topLevelStatusBarStyle;
- (UIColor *)videoEditingBackgroundColor;
- (UIFont *)videoEditingToolbarButtonNormalFont;
- (UIColor *)videoEditingToolbarDestructiveButtonColor;
- (UIColor *)videoEditingToolbarMainButtonColor;
- (UIColor *)videoEditingToolbarSecondaryButtonColor;
- (UIColor *)videoEditingToolbarToolButtonColor;
- (double)videoPaletteBottomMargin;
- (double)videoPaletteSideMargin;
- (UIColor *)videoScrubberTileBackgroundColor;
- (UIFont *)wallpaperCategoryLabelFont;
@end
|
asap2Go/calibrationReader | a2l/display_identifier.go | package a2l
import (
"errors"
"github.com/rs/zerolog/log"
)
type DisplayIdentifier struct {
displayName string
displayNameSet bool
}
func parseDisplayIdentifier(tok *tokenGenerator) (DisplayIdentifier, error) {
di := DisplayIdentifier{}
var err error
tok.next()
if tok.current() == emptyToken {
err = errors.New("unexpected end of file")
log.Err(err).Msg("displayIdentifier could not be parsed")
} else if isKeyword(tok.current()) {
err = errors.New("unexpected token " + tok.current())
log.Err(err).Msg("displayIdentifier could not be parsed")
} else if !di.displayNameSet {
di.displayName = tok.current()
di.displayNameSet = true
log.Info().Msg("displayIdentifier displayName successfully parsed")
}
return di, err
}
|
AsdMonio/rr-external_skia | tests/Test.cpp | /*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "Test.h"
#include "SkCommandLineFlags.h"
#include "SkError.h"
#include "SkString.h"
#include "SkTime.h"
DEFINE_string2(tmpDir, t, nullptr, "Temp directory to use.");
void skiatest::Reporter::bumpTestCount() {}
bool skiatest::Reporter::allowExtendedTest() const { return false; }
bool skiatest::Reporter::verbose() const { return false; }
SkString skiatest::Failure::toString() const {
SkString result = SkStringPrintf("%s:%d\t", this->fileName, this->lineNo);
if (!this->message.isEmpty()) {
result.append(this->message);
if (strlen(this->condition) > 0) {
result.append(": ");
}
}
result.append(this->condition);
return result;
}
SkString skiatest::GetTmpDir() {
const char* tmpDir = FLAGS_tmpDir.isEmpty() ? nullptr : FLAGS_tmpDir[0];
return SkString(tmpDir);
}
|
ricbartm/homebrew-core | Formula/libosinfo.rb | <gh_stars>1-10
class Libosinfo < Formula
desc "The Operating System information database"
homepage "https://libosinfo.org/"
url "https://releases.pagure.org/libosinfo/libosinfo-1.2.0.tar.gz"
sha256 "ee254fcf3f92447787a87b3f6df190c694a787de46348c45101e8dc7b29b5a78"
bottle do
sha256 "99c9327eb8634f81affaa415b339357eb61a1b5d00cd47551ba97f3bdd9286af" => :high_sierra
sha256 "2e1a9e6ab753ae8cccc9e899faa7aa53e83e0c2495f14b49af784a0c1a700e8b" => :sierra
sha256 "bd0ccbaa102b45b745ee3ac97efab1cac6ad35e42e5660c63598fd31e0ff9357" => :el_capitan
end
depends_on "gobject-introspection" => :build
depends_on "intltool" => :build
depends_on "pkg-config" => :build
depends_on "vala" => :optional
depends_on "check"
depends_on "gettext"
depends_on "glib"
depends_on "libsoup"
depends_on "libxml2"
def install
# avoid wget dependency
inreplace "Makefile.in", "wget -q -O", "curl -o"
args = %W[
--prefix=#{prefix}
--localstatedir=#{var}
--mandir=#{man}
--sysconfdir=#{etc}
--disable-silent-rules
--disable-udev
--enable-tests
--enable-introspection
]
if build.with? "vala"
args << "--enable-vala"
else
args << "--disable-vala"
end
system "./configure", *args
# Compilation of docs doesn't get done if we jump straight to "make install"
system "make"
system "make", "install"
end
test do
(testpath/"test.c").write <<~EOS
#include <osinfo/osinfo.h>
int main(int argc, char *argv[]) {
OsinfoPlatformList *list = osinfo_platformlist_new();
return 0;
}
EOS
gettext = Formula["gettext"]
glib = Formula["glib"]
flags = %W[
-I#{gettext.opt_include}
-I#{glib.opt_include}/glib-2.0
-I#{glib.opt_lib}/glib-2.0/include
-I#{include}/libosinfo-1.0
-L#{gettext.opt_lib}
-L#{glib.opt_lib}
-L#{lib}
-losinfo-1.0
-lglib-2.0
-lgobject-2.0
-lintl
]
system ENV.cc, "test.c", "-o", "test", *flags
system "./test"
end
end
|
lsx888/Spring-Boot-Book | 15/JD_Demo/src/main/java/com/example/demo/controller/shop/CancelOrderController.java | <filename>15/JD_Demo/src/main/java/com/example/demo/controller/shop/CancelOrderController.java<gh_stars>100-1000
package com.example.demo.controller.shop;
import com.example.demo.module.mq.CancelOrderSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author longzhonghua
* @data 2/25/2019 7:35 PM
*/
@RestController
public class CancelOrderController {
@Autowired
private CancelOrderSender cancelOrderSender;
int orderId = 1;
@GetMapping("/customSend")
public void send() {
cancelOrderSender.sendMsg("delay_queue_1", orderId);
}
}
|
erinloy/GraphEngine | src/Trinity.C/include/Trinity/Events.h | <filename>src/Trinity.C/include/Trinity/Events.h
// Graph Engine
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
#pragma once
#include <TrinityCommon.h>
#if defined(TRINITY_PLATFORM_WINDOWS)
#include <winsock2.h>
#endif
namespace Trinity
{
namespace Network
{
struct sock_t;
}
namespace Events
{
enum worktype_t : uint32_t
{
Receive,
Send,
Shutdown,
Compute,
Continuation,
};
// Forward definitions
struct message_t;
struct work_t;
typedef work_t*(message_handler_t)(message_t* pmessage);
typedef work_t*(compute_handler_t)(void* pdata);
typedef work_t*(continuation_handler_t)(void* pdata, work_t* pcompleted);
// This is for data exchange between Events subsystem and message handlers.
struct message_t
{
// RECV: allocated after receiving the message header
// SEND: allocated by a message handler
char* buf;
uint32_t len;
};
struct work_t
{
#if defined(TRINITY_PLATFORM_WINDOWS)
WSAOVERLAPPED Overlapped;
#endif
/**
* record the work type when issuing an async op,
* e.g., Send, Recv, Wakeup, etc.
*/
worktype_t type; // size: 4
union
{
struct
{
Network::sock_t* psock;
TrinityErrorCode esock_op;
};
struct
{
compute_handler_t* pcompute;
void* pcompute_data;
};
struct
{
// executed when dependency is completed (or null)
continuation_handler_t* pcontinuation;
// associated data for pcontinuation
void* pcontinuation_data;
// when non-null, should be executed before pcontinuation
work_t* pdependency;
};
};
// when non-null, should be executed after the current work.
work_t* pwait_chain;
};
}
}
|
yoav-steinberg/bazel | src/test/java/com/google/devtools/build/lib/syntax/EvaluationTestCase.java | <reponame>yoav-steinberg/bazel
// Copyright 2006 The Bazel 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.
package com.google.devtools.build.lib.syntax;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableMap;
import java.util.LinkedList;
import java.util.List;
/** Helper class for tests that evaluate Starlark code. */
// TODO(adonovan): simplify this class out of existence.
// Most of its callers should be using the script-based test harness in net.starlark.java.eval.
// TODO(adonovan): extended only by StarlarkFlagGuardingTest; specialize that one test instead.
class EvaluationTestCase {
private StarlarkSemantics semantics = StarlarkSemantics.DEFAULT;
private StarlarkThread thread = null; // created lazily by getStarlarkThread
private Module module = null; // created lazily by getModule
/**
* Updates the semantics used to filter predeclared bindings, and carried by subsequently created
* threads. Causes a new StarlarkThread and Module to be created when next needed.
*/
private final void setSemantics(StarlarkSemantics semantics) {
this.semantics = semantics;
// Re-initialize the thread and module with the new semantics when needed.
this.thread = null;
this.module = null;
}
// TODO(adonovan): don't let subclasses inherit vaguely specified "helpers".
// Separate all the tests clearly into tests of the scanner, parser, resolver,
// and evaluation.
/** Updates a global binding in the module. */
// TODO(adonovan): rename setGlobal.
final EvaluationTestCase update(String varname, Object value) throws Exception {
getModule().setGlobal(varname, value);
return this;
}
/** Returns the value of a global binding in the module. */
// TODO(adonovan): rename getGlobal.
final Object lookup(String varname) throws Exception {
return getModule().getGlobal(varname);
}
/** Joins the lines, parses them as an expression, and evaluates it. */
final Object eval(String... lines) throws Exception {
ParserInput input = ParserInput.fromLines(lines);
return Starlark.eval(input, FileOptions.DEFAULT, getModule(), getStarlarkThread());
}
/** Joins the lines, parses them as a file, and executes it. */
final void exec(String... lines)
throws SyntaxError.Exception, EvalException, InterruptedException {
ParserInput input = ParserInput.fromLines(lines);
Starlark.execFile(input, FileOptions.DEFAULT, getModule(), getStarlarkThread());
}
// A hook for subclasses to alter the created module.
// Implementations may add to the predeclared environment,
// and return the module's client data value.
// TODO(adonovan): only used in StarlarkFlagGuardingTest; move there.
protected Object newModuleHook(ImmutableMap.Builder<String, Object> predeclared) {
return null; // no client data
}
private StarlarkThread getStarlarkThread() {
if (this.thread == null) {
Mutability mu = Mutability.create("test");
this.thread = new StarlarkThread(mu, semantics);
}
return this.thread;
}
private Module getModule() {
if (this.module == null) {
ImmutableMap.Builder<String, Object> predeclared = ImmutableMap.builder();
newModuleHook(predeclared); // see StarlarkFlagGuardingTest
this.module = Module.withPredeclared(semantics, predeclared.build());
}
return this.module;
}
final void checkEvalError(String msg, String... input) throws Exception {
try {
exec(input);
fail("Expected error '" + msg + "' but got no error");
} catch (SyntaxError.Exception | EvalException e) {
assertThat(e).hasMessageThat().isEqualTo(msg);
}
}
final void checkEvalErrorContains(String msg, String... input) throws Exception {
try {
exec(input);
fail("Expected error containing '" + msg + "' but got no error");
} catch (SyntaxError.Exception | EvalException e) {
assertThat(e).hasMessageThat().contains(msg);
}
}
final void checkEvalErrorDoesNotContain(String msg, String... input) throws Exception {
try {
exec(input);
} catch (SyntaxError.Exception | EvalException e) {
assertThat(e).hasMessageThat().doesNotContain(msg);
}
}
/** Encapsulates a separate test which can be executed by a Scenario. */
private interface Testable {
void run() throws Exception;
}
/**
* A test scenario (a script of steps). Beware: Scenario is an inner class that mutates its
* enclosing EvaluationTestCase as it executes the script.
*/
final class Scenario {
private final SetupActions setup = new SetupActions();
private final StarlarkSemantics semantics;
Scenario() {
this(StarlarkSemantics.DEFAULT);
}
Scenario(StarlarkSemantics semantics) {
this.semantics = semantics;
}
private void run(Testable testable) throws Exception {
EvaluationTestCase.this.setSemantics(semantics);
testable.run();
}
/** Allows the execution of several statements before each following test. */
Scenario setUp(String... lines) {
setup.registerExec(lines);
return this;
}
/**
* Allows the update of the specified variable before each following test
*
* @param name The name of the variable that should be updated
* @param value The new value of the variable
* @return This {@code Scenario}
*/
Scenario update(String name, Object value) {
setup.registerUpdate(name, value);
return this;
}
/**
* Evaluates two expressions and asserts that their results are equal.
*
* @param src The source expression to be evaluated
* @param expectedEvalString The expression of the expected result
* @return This {@code Scenario}
* @throws Exception
*/
Scenario testEval(String src, String expectedEvalString) throws Exception {
runTest(createComparisonTestable(src, expectedEvalString, true));
return this;
}
/** Evaluates an expression and compares its result to the expected object. */
Scenario testExpression(String src, Object expected) throws Exception {
runTest(createComparisonTestable(src, expected, false));
return this;
}
/** Evaluates an expression and compares its result to the ordered list of expected objects. */
Scenario testExactOrder(String src, Object... items) throws Exception {
runTest(collectionTestable(src, items));
return this;
}
/** Evaluates an expression and checks whether it fails with the expected error. */
Scenario testIfExactError(String expectedError, String... lines) throws Exception {
runTest(errorTestable(true, expectedError, lines));
return this;
}
/** Evaluates the expresson and checks whether it fails with the expected error. */
Scenario testIfErrorContains(String expectedError, String... lines) throws Exception {
runTest(errorTestable(false, expectedError, lines));
return this;
}
/** Looks up the value of the specified variable and compares it to the expected value. */
Scenario testLookup(String name, Object expected) throws Exception {
runTest(createLookUpTestable(name, expected));
return this;
}
/**
* Creates a Testable that checks whether the evaluation of the given expression fails with the
* expected error.
*
* @param exactMatch whether the error message must be identical to the expected error.
*/
private Testable errorTestable(
final boolean exactMatch, final String error, final String... lines) {
return new Testable() {
@Override
public void run() throws Exception {
if (exactMatch) {
checkEvalError(error, lines);
} else {
checkEvalErrorContains(error, lines);
}
}
};
}
/**
* Creates a Testable that checks whether the value of the expression is a sequence containing
* the expected elements.
*/
private Testable collectionTestable(final String src, final Object... expected) {
return new Testable() {
@Override
public void run() throws Exception {
assertThat((Iterable<?>) eval(src)).containsExactly(expected).inOrder();
}
};
}
/**
* Creates a testable that compares the value of the expression to a specified result.
*
* @param src The expression to be evaluated
* @param expected Either the expected object or an expression whose evaluation leads to the
* expected object
* @param expectedIsExpression Signals whether {@code expected} is an object or an expression
* @return An instance of Testable that runs the comparison
*/
private Testable createComparisonTestable(
final String src, final Object expected, final boolean expectedIsExpression) {
return new Testable() {
@Override
public void run() throws Exception {
Object actual = eval(src);
Object realExpected = expected;
// We could also print the actual object and compare the string to the expected
// expression, but then the order of elements would matter.
if (expectedIsExpression) {
realExpected = eval((String) expected);
}
assertThat(actual).isEqualTo(realExpected);
}
};
}
/**
* Creates a Testable that looks up the given variable and compares its value to the expected
* value
*
* @param name
* @param expected
* @return An instance of Testable that does both lookup and comparison
*/
private Testable createLookUpTestable(final String name, final Object expected) {
return new Testable() {
@Override
public void run() throws Exception {
assertThat(lookup(name)).isEqualTo(expected);
}
};
}
/**
* Executes the given Testable
* @param testable
* @throws Exception
*/
protected void runTest(Testable testable) throws Exception {
run(new TestableDecorator(setup, testable));
}
}
/**
* A simple decorator that allows the execution of setup actions before running a {@code Testable}
*/
static final class TestableDecorator implements Testable {
private final SetupActions setup;
private final Testable decorated;
TestableDecorator(SetupActions setup, Testable decorated) {
this.setup = setup;
this.decorated = decorated;
}
/**
* Executes all stored actions and updates plus the actual {@code Testable}
*/
@Override
public void run() throws Exception {
setup.executeAll();
decorated.run();
}
}
/** A container for collection actions that should be executed before a test */
private final class SetupActions {
private List<Testable> setup;
SetupActions() {
setup = new LinkedList<>();
}
/**
* Registers an update to a module variable to be bound before a test
*
* @param name
* @param value
*/
void registerUpdate(final String name, final Object value) {
setup.add(
new Testable() {
@Override
public void run() throws Exception {
EvaluationTestCase.this.update(name, value);
}
});
}
/** Registers a sequence of statements for execution prior to a test. */
void registerExec(final String... lines) {
setup.add(
new Testable() {
@Override
public void run() throws Exception {
EvaluationTestCase.this.exec(lines);
}
});
}
/**
* Executes all stored actions and updates
*
* @throws Exception
*/
void executeAll() throws Exception {
for (Testable testable : setup) {
testable.run();
}
}
}
}
|
simonzcx/quinn-service-framework | quinn-service-api/src/main/java/com/quinn/framework/api/EntityServiceInterceptor.java | package com.quinn.framework.api;
import com.quinn.framework.api.methodflag.MethodFlag;
import com.quinn.framework.component.EntityServiceInterceptorChain;
import com.quinn.framework.model.methodinvorker.AbstractMethodInvoker;
import com.quinn.util.base.model.BaseResult;
/**
* 实体操作拦截器
*
* @author Qunhua.Liao
* @since 2020-03-27
*/
public interface EntityServiceInterceptor {
/**
* 拦截接口列表
*
* @return 拦截接口列表
*/
Class<? extends MethodFlag>[] interceptBean();
/**
* 拦截接口列表
*
* @return 拦截接口列表
*/
Class<? extends MethodFlag>[] interceptMethod();
/**
* 拦截操作
*
* @param chain 拦截链
* @param methodInvoker 操作对象
* @param <T> 实体泛型
*/
default <T> void intercept(EntityServiceInterceptorChain chain, AbstractMethodInvoker<T> methodInvoker) {
before(chain, methodInvoker.getData(), methodInvoker.getResult());
if (!methodInvoker.getResult().wantContinue()) {
return;
}
chain.doChain(methodInvoker);
if (!methodInvoker.isDone()) {
methodInvoker.invoke();
methodInvoker.setDone(true);
}
after(chain, methodInvoker.getData(), methodInvoker.getResult());
}
/**
* 在新增之前的操作
*
* @param chain 拦截链
* @param t 保存实体
* @param result 结果
* @param <D> 实体泛型
*/
default <D> void before(EntityServiceInterceptorChain chain, D t, BaseResult result) {
}
/**
* 在新增之后的操作
*
* @param chain 拦截链
* @param t 保存实体
* @param result 结果
* @param <V> 实体泛型
*/
default <V> void after(EntityServiceInterceptorChain chain, V t, BaseResult result) {
}
}
|
BrianApple/HXAPIGate | HXAPIGate/src/main/java/hx/apigate/util/RouteSelectUtil.java | package hx.apigate.util;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.ignite.IgniteSemaphore;
import org.apache.ignite.binary.BinaryObjectException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import hx.apigate.databridge.NodeInfo;
import hx.apigate.databridge.SemphareException;
import hx.apigate.databridge.xmlBean.Route;
import hx.apigate.databridge.xmlBean.RouteAll;
import hx.apigate.databridge.xmlBean.RouteNode;
import hx.apigate.socket.handlers.GatewayServerHandler;
import io.netty.handler.codec.http.HttpMethod;
/**
* <p>Description: 路由选择工具类</p>
* <p>Copyright: Copyright (c) 2019</p>
* <p>Company: www.uiotcp.com</p>
* @author yangcheng
* @date 2019年10月29日
* @version 1.0
*/
public class RouteSelectUtil {
private static Logger logger = LoggerFactory.getLogger(RouteSelectUtil.class);
public static String HTTP = "http";
public static String DUBBO = "dubbo";
public static String CIRCLE = "circle";
public static String WEIGHT = "weight";
public static String pathSeparator = "/";
/**
* 根据url以及轮寻策略 选择路由的Node
* @param httpMethod
* @param url 路径名称
* @return [0]为资源名称 [1]为节点对象;if not exists return null
* @throws Exception
*/
public static Object[] selectOneNode(String sourceUrl, HttpMethod httpMethod) throws SemphareException{
String sourceUrlTemp = sourceUrl.contains("?") ? sourceUrl.split("\\?")[0] : sourceUrl;
String pattern = getMatchedPattern(sourceUrlTemp,httpMethod);
if(pattern == null) {
return null;
}
Object[] ret =new Object[2];
ret[0] = pattern;
NodeInfo info = getRouteByPattern(sourceUrl,sourceUrlTemp,pattern);
if(info != null) {
ret[1] = info;
}
return ret;
}
public static IgniteSemaphore selectRouteByUri(String patternUri,String version){
RouteAll routeAll = LocalCache.intimeRouteCache.get(patternUri);
int len = routeAll.getRoutes().size();
for(int i = 0 ; i < len ; i ++) {
if(version.equals(routeAll.getRoutes().get(i).getVersion())) {
return routeAll.getRoutes().get(i).getTps();
}
}
return null;
}
public static NodeInfo getRouteByPattern(String sourceUrl,String sourceUrlTemp,String pattern) throws SemphareException{
RouteAll routeAll = getRouteAll4lvs(pattern) ;//IgniteUtil.getAPIRouteCache().get("ALL_ROUTE").get(pattern);
Route route = routeAll.nextRoute();
System.out.println(pattern+"的信号量是:"+route.getTps().availablePermits() + ";version = " +route.getVersion());
if(!route.getTps().removed() && route.getTps().tryAcquire()) {
if(HTTP.equals(route.getProtocal())) {
int routeNum = route.getRouteNodes().size();
for(int i = 0 ; i < routeNum ; i ++) {
if(RouteSelectUtil.WEIGHT.equals(route.getStratege()) || route.getStratege() == null){
RouteNode node = route.nextNodeByWeight();
if(!route.getTps().removed() && node.getTps().tryAcquire()) {
//权重
return new NodeInfo(route.getVersion(),route.getProtocal(), node,route.isNeedAuth());
}
}else{
//轮寻
if(routeNum > 0){
int nextIndex = route.getIndex().addAndGet(1) % routeNum;
route.getIndex().set(nextIndex);
RouteNode node = route.getRouteNodes().get(nextIndex);
System.out.println(sourceUrl+"的node信号量为"+node.getTps().availablePermits() + "; host = " + node.getIp() +":"+ node.getPort());
if(!route.getTps().removed() && node.getTps().tryAcquire()) {
return new NodeInfo(route.getVersion(),route.getProtocal(), node,route.isNeedAuth());
}
}
}
}
}else if(DUBBO.equals(route.getProtocal())) {
String[] urls = sourceUrlTemp.substring(1).split("\\/");
int size = route.getRouteNodes().size();
if(size>1) {
for(int i = 0 ; i < size ; i ++) {
int nextIndex = route.getIndex().addAndGet(1) % size;
route.getIndex().set(nextIndex);
RouteNode node = route.getRouteNodes().get(nextIndex);
if(!route.getTps().removed() && node.getTps().tryAcquire()) {
return new NodeInfo(route.getVersion(),route.getProtocal(),urls[1], node,sourceUrl,route.isNeedAuth());
}
}
}else {
RouteNode node = route.getRouteNodes().get(0);
System.out.println(sourceUrl+"的node信号量为"+node.getTps().availablePermits());
if(!route.getTps().removed() && node.getTps().tryAcquire()) {
return new NodeInfo(route.getVersion(),route.getProtocal(),urls[1],node,sourceUrl,route.isNeedAuth());
}
}
}
route.getTps().release();
throw new SemphareException(false,"Access to current Node is limited. Please try again later !");
}
throw new SemphareException(true,"Access to current Route is limited. Please try again later !");
}
/**
* 获取RouteAll
* @return
*/
public static RouteAll getRouteAll4lvs(String pattern) {
Map<String, RouteAll> map = IgniteUtil.getAPIRouteCache().get("ALL_ROUTE");
RouteAll routeAll = map.get(pattern);
if(routeAll.isUpdated()) {
LocalCache.intimeRouteCache.put(pattern, routeAll);
routeAll.setUpdated(false);
map.put(pattern, routeAll);
IgniteUtil.getAPIRouteCache().putAsync("ALL_ROUTE", map);
return routeAll;
}else {
return LocalCache.intimeRouteCache.putIfAbsent(pattern, routeAll);
}
}
/**
* 根据url获取route
* @param sourceUrl
* @param httpMethod
* @return
*/
private static String getMatchedPattern(String sourceUrl, HttpMethod httpMethod){
Iterator<String> it = null;
try {
it = IgniteUtil.getAPIRouteCache().get("ALL_ROUTE").keySet().iterator();
}catch (BinaryObjectException e) {
logger.error(e.getMessage());
}
if(it != null) {
String pattern = null;
String temp = null;
while(it.hasNext()){
temp = it.next();
String[] uriInfo = temp.split("==");
if(doMatch(uriInfo[0], sourceUrl ,true) && uriInfo[1].equals(httpMethod.toString())){
pattern = temp;
break;
}
}
return pattern;
}
return null;
}
/**
* 选择路由
* @param pattern
* @param path
* @param fullMatch 是否需要完全模式匹配
* @return
*/
private static boolean doMatch(String pattern, String path, boolean fullMatch) {
if (path.startsWith(RouteSelectUtil.pathSeparator) != pattern.startsWith(RouteSelectUtil.pathSeparator)) {
return false;
}
String[] pattDirs = StringUtils.tokenizeToStringArray(pattern, RouteSelectUtil.pathSeparator);
String[] pathDirs = StringUtils.tokenizeToStringArray(path, RouteSelectUtil.pathSeparator);
int pattIdxStart = 0;
int pattIdxEnd = pattDirs.length - 1;
int pathIdxStart = 0;
int pathIdxEnd = pathDirs.length - 1;
// Match all elements up to the first **
while (pattIdxStart <= pattIdxEnd && pathIdxStart <= pathIdxEnd) {
String patDir = pattDirs[pattIdxStart];
if ("**".equals(patDir)) {
break;
}
if (!matchStrings(patDir, pathDirs[pathIdxStart])) {
return false;
}
pattIdxStart++;
pathIdxStart++;
}
if (pathIdxStart > pathIdxEnd) {
// Path is exhausted, only match if rest of pattern is * or **'s
if (pattIdxStart > pattIdxEnd) {
return (pattern.endsWith(RouteSelectUtil.pathSeparator) ?
path.endsWith(RouteSelectUtil.pathSeparator) : !path.endsWith(RouteSelectUtil.pathSeparator));
}
if (!fullMatch) {
return true;
}
if (pattIdxStart == pattIdxEnd && pattDirs[pattIdxStart].equals("*") &&
path.endsWith(RouteSelectUtil.pathSeparator)) {
return true;
}
for (int i = pattIdxStart; i <= pattIdxEnd; i++) {
if (!pattDirs[i].equals("**")) {
return false;
}
}
return true;
} else if (pattIdxStart > pattIdxEnd) {
// String not exhausted, but pattern is. Failure.
return false;
} else if (!fullMatch && "**".equals(pattDirs[pattIdxStart])) {
// Path start definitely matches due to "**" part in pattern.
return true;
}
// up to last '**'
while (pattIdxStart <= pattIdxEnd && pathIdxStart <= pathIdxEnd) {
String patDir = pattDirs[pattIdxEnd];
if (patDir.equals("**")) {
break;
}
if (!matchStrings(patDir, pathDirs[pathIdxEnd])) {
return false;
}
pattIdxEnd--;
pathIdxEnd--;
}
if (pathIdxStart > pathIdxEnd) {
// String is exhausted
for (int i = pattIdxStart; i <= pattIdxEnd; i++) {
if (!pattDirs[i].equals("**")) {
return false;
}
}
return true;
}
while (pattIdxStart != pattIdxEnd && pathIdxStart <= pathIdxEnd) {
int patIdxTmp = -1;
for (int i = pattIdxStart + 1; i <= pattIdxEnd; i++) {
if (pattDirs[i].equals("**")) {
patIdxTmp = i;
break;
}
}
if (patIdxTmp == pattIdxStart + 1) {
// '**/**' situation, so skip one
pattIdxStart++;
continue;
}
// Find the pattern between padIdxStart & padIdxTmp in str between
// strIdxStart & strIdxEnd
int patLength = (patIdxTmp - pattIdxStart - 1);
int strLength = (pathIdxEnd - pathIdxStart + 1);
int foundIdx = -1;
strLoop:
for (int i = 0; i <= strLength - patLength; i++) {
for (int j = 0; j < patLength; j++) {
String subPat = (String) pattDirs[pattIdxStart + j + 1];
String subStr = (String) pathDirs[pathIdxStart + i + j];
if (!matchStrings(subPat, subStr)) {
continue strLoop;
}
}
foundIdx = pathIdxStart + i;
break;
}
if (foundIdx == -1) {
return false;
}
pattIdxStart = patIdxTmp;
pathIdxStart = foundIdx + patLength;
}
for (int i = pattIdxStart; i <= pattIdxEnd; i++) {
if (!pattDirs[i].equals("**")) {
return false;
}
}
return true;
}
/**
* Tests whether or not a string matches against a pattern.
* The pattern may contain two special characters:<br>
* '*' means zero or more characters<br>
* '?' means one and only one character
*
* @param pattern pattern to match against.
* Must not be <code>null</code>.
* @param str string which must be matched against the pattern.
* Must not be <code>null</code>.
* @return <code>true</code> if the string matches against the
* pattern, or <code>false</code> otherwise.
*/
private static boolean matchStrings(String pattern, String str) {
char[] patArr = pattern.toCharArray();
char[] strArr = str.toCharArray();
int patIdxStart = 0;
int patIdxEnd = patArr.length - 1;
int strIdxStart = 0;
int strIdxEnd = strArr.length - 1;
char ch;
boolean containsStar = false;
for (char aPatArr : patArr) {
if (aPatArr == '*') {
containsStar = true;
break;
}
}
if (!containsStar) {
// No '*'s, so we make a shortcut
if (patIdxEnd != strIdxEnd) {
return false; // Pattern and string do not have the same size
}
for (int i = 0; i <= patIdxEnd; i++) {
ch = patArr[i];
if (ch != '?') {
if (ch != strArr[i]) {
return false;// Character mismatch
}
}
}
return true; // String matches against pattern
}
if (patIdxEnd == 0) {
return true; // Pattern contains only '*', which matches anything
}
// Process characters before first star
while ((ch = patArr[patIdxStart]) != '*' && strIdxStart <= strIdxEnd) {
if (ch != '?') {
if (ch != strArr[strIdxStart]) {
return false;// Character mismatch
}
}
patIdxStart++;
strIdxStart++;
}
if (strIdxStart > strIdxEnd) {
// All characters in the string are used. Check if only '*'s are
// left in the pattern. If so, we succeeded. Otherwise failure.
for (int i = patIdxStart; i <= patIdxEnd; i++) {
if (patArr[i] != '*') {
return false;
}
}
return true;
}
// Process characters after last star
while ((ch = patArr[patIdxEnd]) != '*' && strIdxStart <= strIdxEnd) {
if (ch != '?') {
if (ch != strArr[strIdxEnd]) {
return false;// Character mismatch
}
}
patIdxEnd--;
strIdxEnd--;
}
if (strIdxStart > strIdxEnd) {
// All characters in the string are used. Check if only '*'s are
// left in the pattern. If so, we succeeded. Otherwise failure.
for (int i = patIdxStart; i <= patIdxEnd; i++) {
if (patArr[i] != '*') {
return false;
}
}
return true;
}
// process pattern between stars. padIdxStart and patIdxEnd point
// always to a '*'.
while (patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd) {
int patIdxTmp = -1;
for (int i = patIdxStart + 1; i <= patIdxEnd; i++) {
if (patArr[i] == '*') {
patIdxTmp = i;
break;
}
}
if (patIdxTmp == patIdxStart + 1) {
// Two stars next to each other, skip the first one.
patIdxStart++;
continue;
}
// Find the pattern between padIdxStart & padIdxTmp in str between
// strIdxStart & strIdxEnd
int patLength = (patIdxTmp - patIdxStart - 1);
int strLength = (strIdxEnd - strIdxStart + 1);
int foundIdx = -1;
strLoop:
for (int i = 0; i <= strLength - patLength; i++) {
for (int j = 0; j < patLength; j++) {
ch = patArr[patIdxStart + j + 1];
if (ch != '?') {
if (ch != strArr[strIdxStart + i + j]) {
continue strLoop;
}
}
}
foundIdx = strIdxStart + i;
break;
}
if (foundIdx == -1) {
return false;
}
patIdxStart = patIdxTmp;
strIdxStart = foundIdx + patLength;
}
// All characters in the string are used. Check if only '*'s are left
// in the pattern. If so, we succeeded. Otherwise failure.
for (int i = patIdxStart; i <= patIdxEnd; i++) {
if (patArr[i] != '*') {
return false;
}
}
return true;
}
}
|
WANdisco/j | org.eclipse.jgit.test/tst/org/eclipse/jgit/api/NotesCommandTest.java | <filename>org.eclipse.jgit.test/tst/org/eclipse/jgit/api/NotesCommandTest.java
/*
* Copyright (C) 2011, <NAME> <<EMAIL>>
* and other copyright owners as documented in the project's IP log.
*
* This program and the accompanying materials are made available
* under the terms of the Eclipse Distribution License v1.0 which
* accompanies this distribution, is reproduced below, and is
* available at http://www.eclipse.org/org/documents/edl-v10.php
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* - Neither the name of the Eclipse Foundation, Inc. nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.eclipse.jgit.api;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.eclipse.jgit.junit.RepositoryTestCase;
import org.eclipse.jgit.notes.Note;
import org.eclipse.jgit.revwalk.RevCommit;
import org.junit.Before;
import org.junit.Test;
public class NotesCommandTest extends RepositoryTestCase {
private Git git;
private RevCommit commit1, commit2;
private static final String FILE = "test.txt";
@Override
@Before
public void setUp() throws Exception {
super.setUp();
git = new Git(db);
// commit something
writeTrashFile(FILE, "Hello world");
git.add().addFilepattern(FILE).call();
commit1 = git.commit().setMessage("Initial commit").call();
git.rm().addFilepattern(FILE).call();
commit2 = git.commit().setMessage("Removed file").call();
git.notesAdd().setObjectId(commit1)
.setMessage("data").call();
}
@Test
public void testListNotes() throws Exception {
List<Note> notes = git.notesList().call();
assertEquals(1, notes.size());
}
@Test
public void testAddAndRemoveNote() throws Exception {
git.notesAdd().setObjectId(commit2).setMessage("data").call();
Note note = git.notesShow().setObjectId(commit2).call();
String content = new String(db.open(note.getData()).getCachedBytes(),
UTF_8);
assertEquals(content, "data");
git.notesRemove().setObjectId(commit2).call();
List<Note> notes = git.notesList().call();
assertEquals(1, notes.size());
}
}
|
zzisun/stupid-week-2021 | 2021/07/04/kerochuu/가희와자원놀이.java | <gh_stars>10-100
package baekjoon;
import java.io.*;
import java.util.*;
// @author : blog.naver.com/kerochuu
// @date : 2021. 7. 3.
public class 가희와자원놀이 {
private static class Node {
boolean isAcquire;
int idx, target;
Node(int idx, String type, int target) {
this.idx = idx;
this.isAcquire = type.equals("acquire");
this.target = target;
}
}
static int N, T, idx = 0;
static int[] order;
static Node[] draw;
static String[] card;
static HashSet<Integer> picked = new HashSet<>();
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = stoi(st.nextToken());
T = stoi(st.nextToken());
init();
st = new StringTokenizer(br.readLine());
for (int i = 0; i < T; i++) {
order[i] = stoi(st.nextToken()) - 1;
}
for (int i = 0; i < T; i++) {
card[i] = br.readLine();
}
simulation();
System.out.print(sb.toString());
}
private static void simulation() {
for (int t = 0; t < T; t++) {
if (draw[order[t]] == null) {
String[] cardInfo = card[idx++].split(" ");
if (cardInfo[1].equals("next")) {
sb.append(cardInfo[0] + "\n");
continue;
} else {
draw[order[t]] = new Node(stoi(cardInfo[0]), cardInfo[1], stoi(cardInfo[2]));
}
}
sb.append(draw[order[t]].idx + "\n");
if (draw[order[t]].isAcquire) {
if (!picked.contains(draw[order[t]].target)) { // acquire 가능 할 때
picked.add(draw[order[t]].target);
draw[order[t]] = null;
}
} else { // release는 항상 가능함이 보장됨
picked.remove(draw[order[t]].target);
draw[order[t]] = null;
}
}
}
private static void init() {
order = new int[T];
card = new String[T];
draw = new Node[N];
}
private static int stoi(String input) {
return Integer.parseInt(input);
}
}
|
tlubitz/rba | simulator/static/python/rbatools/rba/core/metabolism.py | <reponame>tlubitz/rba<gh_stars>0
"""Module defining Metabolism class."""
# python 2/3 compatibility
from __future__ import division, print_function, absolute_import
# global imports
import numpy
from scipy.sparse import lil_matrix, hstack
from itertools import chain
# local imports
from .parameter_vector import ParameterVector
from . import functions
class Metabolism(object):
"""
Class computing metabolism-related substructures.
Attributes
----------
internal : list of str
Identifiers of internal metabolites.
external : list of str
Identifiers of external metabolites.
reactions: list of str
Identifiers of reactions.
reversibility: list of bool
Reversibility of reactions.
S : sparse matrix
Stoichiometry matrix (with only internal metabolites).
zero_lb : list
Indices of reactions with lower bound forced to zero because of
medium.
zero_ub : list
Indices of reactions with upper bound forced to zero because of
medium.
"""
def __init__(self, metabolites, reactions):
"""
Constructor.
Parameters
----------
metabolites: rba.xml.ListOfSpecies
Data structure with metabolite information.
reactions: rba.xml.ListOfReactions
Data structure with metabolite information.
"""
self.internal = [m.id for m in metabolites if not m.boundary_condition]
self.external = [m.id for m in metabolites if m.boundary_condition]
self.reactions = [r.id for r in reactions]
full_S = build_S(self.external + self.internal, reactions)
S_ext = full_S[:len(self.external), ]
self.S = full_S[len(self.external):, ]
# default lower bounds and upper bounds
nb_reactions = len(self.reactions)
self._lb = [] * nb_reactions
for r in reactions:
if r.reversible:
self._lb.append(functions.default_lb)
else:
self._lb.append(functions.zero_function)
self._ub = [functions.default_ub] * nb_reactions
# find boundary reactions (involving external metabolites)
self._boundary_lb = {}
self._boundary_ub = {}
for met_id, r_indices, values \
in zip(self.external, S_ext.rows, S_ext.data):
met_prefix = met_id.rsplit('_', 1)[0]
self._boundary_lb[met_prefix] = [
i for i, v in zip(r_indices, values) if v > 0
]
self._boundary_ub[met_prefix] = [
i for i, v in zip(r_indices, values) if v < 0
]
self._zero_lb = []
self._zero_ub = []
self.f = numpy.zeros(nb_reactions)
def set_boundary_fluxes(self, medium):
"""
Find zero lower and upper bounds imposed by external medium.
Parameters
----------
medium : dict
Dictionary where keys are metabolite prefixes and values are
concentrations in external medium.
"""
zero_metabolites = [m for m, c in medium.items() if c == 0]
self._zero_lb = list(set(
chain.from_iterable(self._boundary_lb[m] for m in zero_metabolites)
))
self._zero_ub = list(set(
chain.from_iterable(self._boundary_ub[m] for m in zero_metabolites)
))
def add_reactions(self, reactions, names, reversibility):
"""
Add reactions.
Parameters
----------
reactions : list of vectors
Reactions in vector format where order must match order of
internal metabolites.
names : list of str
Identifiers of reactions.
reversibility : list of bool
Reversibility of reactions.
"""
assert(len(reactions) == len(names) == len(reversibility))
self.S = hstack([self.S] + reactions)
self.reactions += names
for reversible in reversibility:
if reversible:
self._lb.append(functions.default_lb)
else:
self._lb.append(functions.zero_function)
self._ub += [functions.default_ub] * len(reactions)
self.f = numpy.concatenate([self.f, numpy.zeros(len(reactions))])
def lb(self):
result = numpy.fromiter((lb.value for lb in self._lb),
'float', len(self._lb))
result[self._zero_lb] = 0
return result
def ub(self):
result = numpy.fromiter((ub.value for ub in self._ub),
'float', len(self._lb))
result[self._zero_ub] = 0
return result
def build_S(metabolites, reactions):
"""
Build stoichiometry matrix from metabolites and reactions.
Parameters
----------
metabolites:
Metabolite identifiers (used to define row order).
reactions: rba.xml.ListOfReactions
Reaction data.
Returns
-------
scipy.sparse.lil_matrix
Stoichiometry matrix.
"""
m_index = {m: i for i, m in enumerate(metabolites)}
S = lil_matrix((len(metabolites), len(reactions)))
for r_index, reaction in enumerate(reactions):
for reactant in reaction.reactants:
S[m_index[reactant.species], r_index] = -reactant.stoichiometry
for product in reaction.products:
S[m_index[product.species], r_index] = product.stoichiometry
return S
|
mcleo-d/App-Integrations-Core | integration-pod-api-client/src/test/java/org/symphonyoss/integration/pod/api/client/RelayApiClientTest.java | /**
* Copyright 2016-2017 Symphony Integrations - Symphony 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.
*/
package org.symphonyoss.integration.pod.api.client;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.symphonyoss.integration.api.client.HttpApiClient;
import org.symphonyoss.integration.exception.RemoteApiException;
import org.symphonyoss.integration.exception.authentication.ForbiddenAuthException;
import org.symphonyoss.integration.exception.authentication.UnauthorizedUserException;
import org.symphonyoss.integration.exception.authentication.UnexpectedAuthException;
import org.symphonyoss.integration.logging.LogMessageSource;
import org.symphonyoss.integration.model.UserKeyManagerData;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.core.Response;
/**
* Unit test for {@link RelayApiClient}
* Created by campidelli on 19/11/17.
*/
@RunWith(MockitoJUnitRunner.class)
public class RelayApiClientTest {
private static final String MOCK_SESSION_TOKEN = "sessionToken";
private static final String MOCK_KM_TOKEN = "kmToken";
private static final String API_PATH = "/relay/keys/me";
private static final UserKeyManagerData MOCK_DATA = new UserKeyManagerData();
@Mock
private LogMessageSource logMessage;
@Mock
private HttpApiClient apiClient;
private RelayApiClient relayApiClient;
@Before
public void init() {
relayApiClient = new RelayApiClient(apiClient, logMessage);
}
private Map<String, String> hParams() {
StringBuffer cookie = new StringBuffer("skey=");
cookie.append(MOCK_SESSION_TOKEN).append("; kmsession=").append(MOCK_KM_TOKEN);
Map<String, String> headerParams = new HashMap<>();
headerParams.put("sessionToken", MOCK_SESSION_TOKEN);
headerParams.put("Cookie", cookie.toString());
return headerParams;
}
private Map<String, String> qParams() {
return new HashMap<>();
}
@Test
public void testGetBotUserAccountKey() throws RemoteApiException {
doReturn(MOCK_DATA).when(apiClient)
.doGet(API_PATH, hParams(), qParams(), UserKeyManagerData.class);
UserKeyManagerData data = relayApiClient.getUserAccountKeyManagerData(MOCK_SESSION_TOKEN, MOCK_KM_TOKEN);
assertEquals(MOCK_DATA, data);
}
@Test
public void testGetBotUserAccountKeyInvalidKmSession() {
String failMsg =
"Should have thrown UnexpectedAuthException containing a RemoteApiException (400).";
try {
relayApiClient.getUserAccountKeyManagerData(MOCK_SESSION_TOKEN, null);
fail(failMsg);
} catch (UnexpectedAuthException e) {
assertTrue(e.getCause() instanceof RemoteApiException);
RemoteApiException rae = (RemoteApiException) e.getCause();
assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), rae.getCode());
} catch (Exception e) {
fail(failMsg);
}
}
@Test(expected = UnauthorizedUserException.class)
public void testGetBotUserAccountKeyUnauthorized() throws RemoteApiException {
RemoteApiException rae = new RemoteApiException(Response.Status.UNAUTHORIZED.getStatusCode(),
"UNAUTHORIZED");
doThrow(rae).when(apiClient).doGet(API_PATH, hParams(), qParams(), UserKeyManagerData.class);
relayApiClient.getUserAccountKeyManagerData(MOCK_SESSION_TOKEN, MOCK_KM_TOKEN);
fail("Should have thrown UnauthorizedUserException.");
}
@Test(expected = ForbiddenAuthException.class)
public void testGetBotUserAccountKeyForbidden() throws RemoteApiException {
RemoteApiException rae = new RemoteApiException(Response.Status.FORBIDDEN.getStatusCode(),
"FORBIDDEN");
doThrow(rae).when(apiClient).doGet(API_PATH, hParams(), qParams(), UserKeyManagerData.class);
relayApiClient.getUserAccountKeyManagerData(MOCK_SESSION_TOKEN, MOCK_KM_TOKEN);
fail("Should have thrown ForbiddenAuthException.");
}
}
|
toly1994328/DS4Android | app/src/main/java/com/toly1994/ds4android/view/LinkedView.java | <reponame>toly1994328/DS4Android<filename>app/src/main/java/com/toly1994/ds4android/view/LinkedView.java
package com.toly1994.ds4android.view;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Picture;
import android.graphics.Point;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.LinearInterpolator;
import com.toly1994.ds4android.analyze.ColUtils;
import com.toly1994.ds4android.analyze.L;
import com.toly1994.ds4android.analyze.gold12.HelpDraw;
import com.toly1994.ds4android.analyze.gold12.JudgeMan;
import com.toly1994.ds4android.ds.impl.chart.LinkedChart;
import com.toly1994.ds4android.ds.itf.IChart;
import com.toly1994.ds4android.model.LinkedNode;
import com.toly1994.ds4android.view.other.Cons;
import com.toly1994.ds4android.view.other.OnCtrlClickListener;
/**
* 作者:张风捷特烈<br/>
* 时间:2018/11/21 0021:8:01<br/>
* 邮箱:<EMAIL><br/>
* 说明:双链表实现表结构---测试视图
*/
public class LinkedView<E> extends View {
private Point mCoo = new Point(200, 200);//坐标系
private Picture mCooPicture;//坐标系canvas元件
private Picture mGridPicture;//网格canvas元件
private Path mPath;//主路径
private Paint mPaint;//主画笔
private Paint mTxtPaint;//数字画笔
private Paint mPathPaint;//路径画笔
private Paint mCtrlPaint;//几个圆的画笔
private IChart<LinkedNode<E>> mArrayBoxes = new LinkedChart<>();
private OnCtrlClickListener<LinkedView<E>> mOnCtrlClickListener;
private int selectIndex = -1;//当前选中的索引
private ValueAnimator mAnimator;
private static final int OFFSET_X = 100;//X空隙
private static final int OFFSET_Y = 250;//Y空隙
private static final int OFFSET_OF_TXT_Y = 10;//文字的偏移
private static final int LINE_ITEM_NUM = 5;//每行的单体个数
private static final int BOX_RADIUS = 10;//数组盒子的圆角
private static final Point[] CTRL_POS = new Point[]{//控制按钮的点位
new Point(-100, 100),//添加
new Point(-100, 300),//更新
new Point(-100, 500),//查看
new Point(-100, 700),//删除
new Point(700, -70),//定点添加
new Point(700 + 300, -70),//定值查询
new Point(700 + 300 * 2, -70),//定点删除
new Point(700 + 300 * 3, -70),//清除
};
private static int[] CTRL_COLOR = new int[]{//控制按钮的颜色
0xff1EF519,//添加
0xff2992F2,//更新
0xffB946F4,//添加
0xffF50C0C,//删除
0xff1EF519,//定点添加
0xffB946F4,//定值查询
0xffF50C0C,//定点删除
0xffF46410,//清除
};
private static final String[] CTRL_TXT = new String[]{//控制按钮的文字
"添加",//添加
"更新",//更新
"查寻",//添加
"删除",//删除
"定点+",//定点添加
"值查",//定值查询
"定点-",//定点删除
"清空",//清除按键
};
private static final int CTRL_RADIUS = 50;//控制按钮的半径
public void setOnCtrlClickListener(OnCtrlClickListener<LinkedView<E>> onCtrlClickListener) {
mOnCtrlClickListener = onCtrlClickListener;
}
public LinkedView(Context context) {
this(context, null);
}
public LinkedView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();//初始化
}
private void init() {
//初始化主画笔
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setColor(Color.BLUE);
mPaint.setStrokeWidth(5);
mPaint.setTextAlign(Paint.Align.CENTER);
mPaint.setTextSize(50);
//初始化主路径
mPath = new Path();
//初始化文字画笔
mTxtPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTxtPaint.setColor(Color.WHITE);
mTxtPaint.setTextAlign(Paint.Align.CENTER);
mTxtPaint.setTextSize(40);
//初始化路径画笔
mPathPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPathPaint.setColor(0xff810DF3);
mPathPaint.setStrokeWidth(4);
mPathPaint.setStyle(Paint.Style.STROKE);
mCooPicture = HelpDraw.getCoo(getContext(), mCoo, false);
mGridPicture = HelpDraw.getGrid(getContext());
//初始化圆球按钮画笔
mCtrlPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mCtrlPaint.setColor(Color.RED);
mCtrlPaint.setTextAlign(Paint.Align.CENTER);
mCtrlPaint.setTextSize(30);
//初始化时间流ValueAnimator
mAnimator = ValueAnimator.ofFloat(0, 1);
mAnimator.setRepeatCount(-1);
mAnimator.setDuration(2000);
mAnimator.setRepeatMode(ValueAnimator.REVERSE);
mAnimator.setInterpolator(new LinearInterpolator());
mAnimator.addUpdateListener(animation -> {
updateBall();//更新小球位置
invalidate();
});
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
HelpDraw.draw(canvas, mGridPicture);
canvas.save();
canvas.translate(mCoo.x, mCoo.y);//画布移到坐标原点
mTxtPaint.setColor(Color.WHITE);
dataView(canvas);//核心操作展示
ctrlView(canvas);//操作按钮
helpView(canvas);//辅助视图
canvas.restore();
HelpDraw.draw(canvas, mCooPicture);
}
/**
* 绘制表结构
*
* @param canvas
*/
private void dataView(Canvas canvas) {
mPaint.setColor(Color.BLUE);
mPaint.setStyle(Paint.Style.FILL);
mPath.reset();
for (int i = 0; i < mArrayBoxes.size(); i++) {
LinkedNode box = mArrayBoxes.get(i);
mPaint.setColor(box.color);
canvas.drawRoundRect(
box.x, box.y, box.x + Cons.BOX_WIDTH, box.y + Cons.BOX_HEIGHT,
BOX_RADIUS, BOX_RADIUS, mPaint);
mPath.moveTo(box.x, box.y);
mPath.rCubicTo(Cons.BOX_WIDTH / 2, Cons.BOX_HEIGHT / 2,
Cons.BOX_WIDTH / 2, Cons.BOX_HEIGHT / 2, Cons.BOX_WIDTH, 0);
if (i < mArrayBoxes.size() - 1 ) {
LinkedNode box_next = mArrayBoxes.get(i + 1);
LinkedNode box_now = mArrayBoxes.get(i);
if (i % LINE_ITEM_NUM == LINE_ITEM_NUM - 1) {//边界情况
mPath.rLineTo(0, Cons.BOX_HEIGHT);
mPath.lineTo(box_next.x + Cons.BOX_WIDTH, box_next.y);
mPath.rLineTo(Cons.ARROW_DX, -Cons.ARROW_DX);
mPath.moveTo(box_next.x, box_next.y);
mPath.lineTo(box_now.x, box_now.y+Cons.BOX_HEIGHT);
mPath.rLineTo(-Cons.ARROW_DX, Cons.ARROW_DX);
} else {
mPath.rLineTo(0, Cons.BOX_HEIGHT / 2.2f);
mPath.lineTo(box_next.x+Cons.BOX_WIDTH * 0.2f, box_next.y + Cons.BOX_HEIGHT / 2f);
mPath.rLineTo(-Cons.ARROW_DX, -Cons.ARROW_DX);
mPath.moveTo(box_next.x, box_next.y);
mPath.rLineTo(0, Cons.BOX_HEIGHT / 1.2f);
mPath.lineTo(box_now.x + Cons.BOX_WIDTH * 0.8f, box_now.y + Cons.BOX_HEIGHT * 0.8f);
mPath.rLineTo(Cons.ARROW_DX, Cons.ARROW_DX);
}
}
canvas.drawPath(mPath, mPathPaint);
canvas.drawText(box.index + "",
box.x + Cons.BOX_WIDTH / 2,
box.y + 3 * OFFSET_OF_TXT_Y, mTxtPaint);
canvas.drawText(box.data + "",
box.x + Cons.BOX_WIDTH / 2,
box.y + Cons.BOX_HEIGHT / 2 + 3 * OFFSET_OF_TXT_Y, mTxtPaint);
}
}
/**
* 绘制数组的长度个空白矩形
*
* @param canvas
*/
private void helpView(Canvas canvas) {
mPaint.setStyle(Paint.Style.FILL);
canvas.drawText("线性表", -100, -50, mPaint);
canvas.drawText("当前选中点:" + selectIndex, 250, -50, mPaint);
}
/**
* 控制面板--圆球
*
* @param canvas 画布
*/
private void ctrlView(Canvas canvas) {
for (int i = 0; i < CTRL_POS.length; i++) {
mCtrlPaint.setColor(CTRL_COLOR[i]);
canvas.drawCircle(CTRL_POS[i].x, CTRL_POS[i].y, CTRL_RADIUS, mCtrlPaint);
canvas.drawText(CTRL_TXT[i], CTRL_POS[i].x, CTRL_POS[i].y + OFFSET_OF_TXT_Y, mTxtPaint);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
float downX = event.getX() - mCoo.x;
float downY = event.getY() - mCoo.y;
updateSelectIndex(downX, downY);//更新selectIndex
for (int i = 0; i < CTRL_POS.length; i++) {
//区域判定
if (JudgeMan.judgeCircleArea(
CTRL_POS[i].x, CTRL_POS[i].y,
downX, downY, CTRL_RADIUS * 1.2f)) {
if (mOnCtrlClickListener != null) {
switch (i) {
case 0://插入尾部
mOnCtrlClickListener.onAdd(this);
if (selectIndex > 0) {
mArrayBoxes.get(selectIndex).color = 0xff43A3FA;
selectIndex = -1;
}
break;
case 1://更新
mOnCtrlClickListener.onSet(this);
break;
case 2://查找
mOnCtrlClickListener.onFind(this);
break;
case 3://删除尾部
if (selectIndex > 0) {//如果有选中的颜色,先复原
mArrayBoxes.get(selectIndex).color = 0xff43A3FA;
}
selectIndex = mArrayBoxes.size() - 1;
mAnimator.start();
break;
case 4://定点添加
if (selectIndex >= 0) {
mArrayBoxes.get(selectIndex).color = 0xff43A3FA;
mOnCtrlClickListener.onAddByIndex(this);
selectIndex = -1;
}
break;
case 5://定值查询
mOnCtrlClickListener.onFindByData(this);
break;
case 6://定点移除
mAnimator.start();
break;
case 7://清空
mOnCtrlClickListener.onClear(this);
selectIndex = -1;
break;
}
CTRL_COLOR[i] = 0xff54E1F8;//点击更换颜色
}
}
}
break;
case MotionEvent.ACTION_UP://还原颜色
CTRL_COLOR[0] = 0xff1EF519;
CTRL_COLOR[1] = 0xff2992F2;
CTRL_COLOR[2] = 0xffB946F4;
CTRL_COLOR[3] = 0xffF50C0C;
CTRL_COLOR[4] = 0xff1EF519;
CTRL_COLOR[5] = 0xffB946F4;
CTRL_COLOR[6] = 0xffF50C0C;
CTRL_COLOR[7] = 0xffF46410;
break;
}
invalidate();
return true;
}
/**
* 点击时动态更新选中值
*
* @param downX 按下点X
* @param downY 按下点Y
*/
private void updateSelectIndex(float downX, float downY) {
float x = downX / (Cons.BOX_WIDTH + OFFSET_X) - 0.5f;
float y = downY / (Cons.BOX_HEIGHT + OFFSET_Y) - 0.5f;
if (x > -0.5 && y > -0.5) {
if (selectIndex != -1) {
mArrayBoxes.get(selectIndex).color = 0xff43A3FA;//还原之前选中的颜色
}
int indexOfData = Math.round(y) * LINE_ITEM_NUM + Math.round(x);//逆向求取点中的数据索引
if (indexOfData < mArrayBoxes.size()) {
mArrayBoxes.get(indexOfData).color = ColUtils.randomRGB();
selectIndex = indexOfData;
}
}
}
/**
* 更新小球
*/
private void updateBall() {
if (mArrayBoxes.size() > 0 && selectIndex != -1) {
L.d(selectIndex + L.l());
LinkedNode ball = mArrayBoxes.get(selectIndex);
ball.x += ball.vX;
ball.y += ball.vY;
if (ball.y > 600) {
if (mOnCtrlClickListener != null) {
mOnCtrlClickListener.onRemoveByIndex(this);//移除监听放在这里了!!
mAnimator.pause();
}
}
}
}
/**
* 视图的数据操作接口方法--添加
*
* @param data 数据
*/
public void addData(E data) {
LinkedNode<E> LinkedNode = new LinkedNode<>(0, 0);
LinkedNode.data = data;
mArrayBoxes.add(LinkedNode);
updatePosOfData();
}
/**
* 视图的数据操作接口方法--根据索引添加
*
* @param index 索引
* @param data 数据
*/
public void addDataById(int index, E data) {
L.d("addDataById:" + index + L.l());
if (mArrayBoxes.size() > 0 && index < mArrayBoxes.size() && index >= 0) {
LinkedNode<E> LinkedNode = new LinkedNode<>(0, 0);
LinkedNode.data = data;
mArrayBoxes.add(index, LinkedNode);
updatePosOfData();
}
}
/**
* 视图的数据操作接口方法--根据id查询操作
*
* @param index 索引
* @return
*/
public E findData(int index) {
if (mArrayBoxes.size() > 0 && index < mArrayBoxes.size() && index >= 0) {
return mArrayBoxes.get(index).data;
}
return null;
}
/**
* 视图的数据操作接口方法--根据数据查询操作
*
* @param data 数据
* @return
*/
public int[] findData(E data) {
if (selectIndex != -1) {
LinkedNode<E> LinkedNode = new LinkedNode<>(0, 0);
LinkedNode.data = data;
return mArrayBoxes.getIndex(LinkedNode);
}
return null;
}
/**
* 视图的数据操作接口方法--更新数据
*
* @param index 索引
* @param data 数据
*/
public void setData(int index, E data) {
if (mArrayBoxes.size() > 0 && index < mArrayBoxes.size() && index >= 0) {
mArrayBoxes.get(index).data = data;
}
}
/**
* 视图的数据操作接口方法--移除末尾
*/
public void removeData() {
if (mArrayBoxes.size() > 0) {
mArrayBoxes.remove();
updatePosOfData();
}
}
/**
* 视图的数据操作接口方法--定索引删除操作
*
* @param index 索引
*/
public void removeData(int index) {
if (mArrayBoxes.size() > 0 && index < mArrayBoxes.size() && index >= 0) {
//更新后面的索引
for (int i = index; i < mArrayBoxes.size(); i++) {
mArrayBoxes.get(i).index -= 1;
}
mArrayBoxes.remove(index);
selectIndex = -1;
updatePosOfData();
}
}
/**
* 视图的数据操作接口方法--清空操作
*/
public void clearData() {
mArrayBoxes.clear();
}
/**
* 更新绘制单体的点位
*/
private void updatePosOfData() {
for (int i = 0; i < mArrayBoxes.size(); i++) {
int y = i / LINE_ITEM_NUM;//行坐标
int x = i % LINE_ITEM_NUM;//列坐标
LinkedNode box = mArrayBoxes.get(i);
box.x = (Cons.BOX_WIDTH + OFFSET_X) * x;
box.y = (Cons.BOX_HEIGHT + OFFSET_Y) * y;
box.index = i;
box.vY = 50;
box.vX = 0;
}
}
/**
* 获取选中索引
*
* @return
*/
public int getSelectIndex() {
return selectIndex;
}
/**
* 获取选中值
*
* @return
*/
public E getSelectData() {
if (selectIndex >= 0) {
return mArrayBoxes.get(selectIndex).data;
}
return null;
}
} |
PhotoNomad0/tCore-Electronite | src/js/helpers/migrationHelpers.js | <filename>src/js/helpers/migrationHelpers.js
import path from 'path-extra';
import fs from 'fs-extra';
export function migrateAppsToDotApps(projectPath) {
let projectDir = fs.readdirSync(projectPath);
if (projectDir.includes('apps') && projectDir.includes('.apps')) {
fs.removeSync(path.join(projectPath, '.apps'));
}
if (projectDir.includes('apps')) {
fs.renameSync(path.join(projectPath, 'apps'), path.join(projectPath, '.apps'));
}
}
|
arunkbharathan/EPI2 | Chapter6_Arrays/primesUpToN.go | <reponame>arunkbharathan/EPI2
package main
import "math"
func primesUpto(num int) []int {
if num < 2 {
return []int{}
} else if num < 3 {
return []int{2}
} else if num < 5 {
return []int{2, 3}
}
primes := primesUpto(int(math.Sqrt(float64(num))))
retPrime := []int{}
for i := 2; i <= num; i++ {
retPrime = append(retPrime, i)
}
for _, val := range primes {
for i := 4; i < len(retPrime); i++ {
if val == retPrime[i] {
continue
}
if retPrime[i]%val == 0 {
retPrime[i] = 0
}
}
}
newList := []int{}
for _, val := range retPrime {
if val != 0 {
newList = append(newList, val)
}
}
return newList
}
|
mengxy/swc | crates/swc_webpack_ast/tests/fixture/react-dom/dev/output.js | exports, module, exports, require("react"), define, define.amd, define([
"exports",
"react"
], factory);
|
pesto-students/n3-doccords-frontend-iota-iota | src/components/shared/upload/uploadAvatar.js | import React, { useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";
import Spinner from "components/shared/spinner";
import { Typography, Button } from "@material-ui/core";
import { setUploadedImageURL } from "redux/actions/common";
import CameraAltIcon from "@material-ui/icons/CameraAlt";
const UploadAvatar = () => {
const [selectedFile, setSelectedFile] = useState(null);
// const [fileName, setFileName] = useState(null);
const [preview, setPreview] = useState(null);
const [isDisabled, setIsDisabled] = useState(true);
const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(false);
const [isSuccess, setIsSuccess] = useState(false);
const [buttonText, setButtonText] = useState("Select your file first");
const dispatch = useDispatch();
const uploadedLink = useSelector((state) => state.common.uploadedLink);
const onFileSelected = (e) => {
if (e.target.files[0]) {
setSelectedFile(e.target.files[0]);
// setFileName(e.target.files[0].name);
setPreview(URL.createObjectURL(event.target.files[0]));
setIsDisabled(false); // Enabling upload button
setButtonText("Let's upload this!");
}
};
const handleFileUpload = async (e) => {
e.preventDefault();
setIsLoading(true);
setIsDisabled(true);
setButtonText("Wait we're uploading your file...");
try {
if (selectedFile !== "") {
// Creating a FormData object
const fileData = new FormData();
fileData.set(
"image",
selectedFile,
`${Date.now()}-${selectedFile.name}`
);
const token = JSON.parse(
localStorage.getItem("doccords_user")
).accessToken;
const res = await axios({
method: "post",
url: "https://doccords-api.herokuapp.com/api/v1/users/upload/file",
data: fileData,
headers: {
"Content-Type": "multipart/form-data",
Authorization: "Bearer " + token,
},
});
await setIsLoading(false);
await setIsSuccess(true);
dispatch(setUploadedImageURL(res.data.fileLocation));
}
} catch (error) {
setIsLoading(false);
setIsError(true);
// setFileName(null);
}
};
const deleteUploadedUrl = () => {
dispatch(setUploadedImageURL(""));
setSelectedFile(null);
setPreview(null);
setIsSuccess(false);
// setFileName(null);
setButtonText("Select your file first");
};
if (!uploadedLink.length > 0) {
return (
<div className="photo_upload">
<Typography variant="h5" style={{ marginTop: "1rem" }}>
Add a profile
</Typography>
<main style={{ marginTop: "1rem" }}>
<form
onSubmit={(e) => handleFileUpload(e)}
style={{
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
}}
>
<label className="uploader" style={{ width: "15rem" }}>
<div className="upload-space">
{isLoading ? (
<Spinner />
) : (
<>
{isError || isSuccess ? (
<i
className={`icon-${isSuccess ? "success" : "error"}`}
></i>
) : (
<>
{preview ? (
<div className="preview">
<img
src={preview}
alt="Preview of the file to be uploaded"
/>
</div>
) : (
// <i className="icon-upload"></i>
<CameraAltIcon />
)}
<input
type="file"
onChange={onFileSelected}
accept="image/*"
/>
</>
)}
</>
)}
</div>
{isError ||
(isSuccess && (
<p className={isSuccess ? "success" : "error"}>
{isSuccess
? "Upload successful!"
: "Something went wrong ..."}
</p>
))}
</label>
<Button
type="submit"
variant="contained"
color="primary"
disabled={isDisabled}
style={{
textTransform: "none",
marginTop: "1rem",
}}
>
{buttonText}
</Button>
</form>
</main>
</div>
);
} else {
return (
<div style={{ display: "flex", flexDirection: "column" }}>
<div style={{ width: "8rem", height: "8rem" }}>
<img
src={uploadedLink}
alt="avatar"
style={{
width: "100%",
height: "100%",
borderRadius: "100%",
}}
/>
</div>
<Button
variant="contained"
color="secondary"
style={{
color: "#ffffff",
textTransform: "none",
width: "fit-content",
marginTop: "1rem",
}}
onClick={deleteUploadedUrl}
width="auto"
>
Delete uploaded file
</Button>
</div>
);
}
};
export default UploadAvatar;
|
FuyaoLi2017/leetcode | Array/leetcode_1157_OnlineMajorityElementInSubarray.java | <reponame>FuyaoLi2017/leetcode<gh_stars>1-10
/*
Implementing the class MajorityChecker, which has the following API:
MajorityChecker(int[] arr) constructs an instance of MajorityChecker with the given array arr;
int query(int left, int right, int threshold) has arguments such that:
0 <= left <= right < arr.length representing a subarray of arr;
2 * threshold > right - left + 1, ie. the threshold is always a strict majority of the length of the subarray
Each query(...) returns the element in arr[left], arr[left+1], ..., arr[right] that occurs at least threshold times, or -1 if no such element exists.
Example:
MajorityChecker majorityChecker = new MajorityChecker([1,1,2,2,1,1]);
majorityChecker.query(0,5,4); // returns 1
majorityChecker.query(0,3,3); // returns -1
majorityChecker.query(2,3,2); // returns 2
Constraints:
1 <= arr.length <= 20000
1 <= arr[i] <= 20000
For each query, 0 <= left <= right < len(arr)
For each query, 2 * threshold > right - left + 1
The number of queries is at most 10000
*/
// intuitive solution, moore's voting algorithm, TLE
class MajorityChecker {
int[] arr;
public MajorityChecker(int[] arr) {
this.arr = arr;
}
public int query(int left, int right, int threshold) {
int vote = -1; int cnt = 0;
for(int i = left; i <= right; i++) {
if(cnt == 0) {
vote = arr[i];
}
if(vote == arr[i]){
cnt++;
} else {
cnt--;
}
}
cnt = 0;
for(int i = left; i <= right; i++) {
if(arr[i] == vote) {
cnt++;
}
}
return cnt >= threshold ? vote : -1;
}
}
// RANDOM PICK solution
// https://leetcode.com/problems/online-majority-element-in-subarray/discuss/356227/C%2B%2B-Codes-of-different-approaches-(Random-Pick-Trade-off-Segment-Tree-Bucket)
class MajorityChecker {
int[] arr;
HashMap<Integer,ArrayList<Integer>> map = new HashMap<>();
public MajorityChecker(int[] arr) {
this.arr = arr;
for(int i = 0;i<arr.length;i++){
ArrayList<Integer> temp = map.getOrDefault(arr[i],new ArrayList<Integer>());
temp.add(i);
map.put(arr[i],temp);
}
}
public int query(int left, int right, int threshold) {
for(int i = 0;i<20;i++){
int min = left, max = right;
int candidate = arr[min + (int)(Math.random() * (max-min+1))];
ArrayList<Integer> temp = map.get(candidate);
if(temp.size() < threshold) continue;
// the range will be [low,high]
int low = Collections.binarySearch(temp,left);
int high = Collections.binarySearch(temp,right);
//if low or high is negative, means not found, will return (-insert postion - 1);
if(low < 0) low = - low - 1;
if(high < 0) high = (- high - 1) - 1;//make high positive, then high--
if(high - low + 1 >= threshold) return candidate;
}
return -1;
}
}s
|
Joshua-Anderson/fprime-sphinx-drivers | fprime-sphinx-drivers/ADC/test/ut/TesterBase.hpp | // ======================================================================
// \title ADC/test/ut/TesterBase.hpp
// \author Auto-generated
// \brief hpp file for ADC component test harness base class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef ADC_TESTER_BASE_HPP
#define ADC_TESTER_BASE_HPP
#include <fprime-sphinx-drivers/ADC/ADCComponentAc.hpp>
#include <Fw/Types/Assert.hpp>
#include <Fw/Comp/PassiveComponentBase.hpp>
#include <stdio.h>
#include <Fw/Port/InputSerializePort.hpp>
namespace Drv {
//! \class ADCTesterBase
//! \brief Auto-generated base class for ADC component test harness
//!
class ADCTesterBase :
public Fw::PassiveComponentBase
{
public:
// ----------------------------------------------------------------------
// Initialization
// ----------------------------------------------------------------------
//! Initialize object ADCTesterBase
//!
virtual void init(
const NATIVE_INT_TYPE instance = 0 /*!< The instance number*/
);
public:
// ----------------------------------------------------------------------
// Connectors for 'to' ports
// Connect these output ports to the input ports under test
// ----------------------------------------------------------------------
//! Connect schedIn to to_schedIn[portNum]
//!
void connect_to_schedIn(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
Svc::InputSchedPort *const schedIn /*!< The port*/
);
//! Connect cmdIn to to_cmdIn[portNum]
//!
void connect_to_cmdIn(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::InputCmdPort *const cmdIn /*!< The port*/
);
//! Connect PingRecv to to_PingRecv[portNum]
//!
void connect_to_PingRecv(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
Svc::InputPingPort *const PingRecv /*!< The port*/
);
public:
// ----------------------------------------------------------------------
// Getters for 'from' ports
// Connect these input ports to the output ports under test
// ----------------------------------------------------------------------
//! Get the port that receives input from cmdReg
//!
//! \return from_cmdReg[portNum]
//!
Fw::InputCmdRegPort* get_from_cmdReg(
const NATIVE_INT_TYPE portNum /*!< The port number*/
);
//! Get the port that receives input from timeCaller
//!
//! \return from_timeCaller[portNum]
//!
Fw::InputTimePort* get_from_timeCaller(
const NATIVE_INT_TYPE portNum /*!< The port number*/
);
//! Get the port that receives input from eventOut
//!
//! \return from_eventOut[portNum]
//!
Fw::InputLogPort* get_from_eventOut(
const NATIVE_INT_TYPE portNum /*!< The port number*/
);
//! Get the port that receives input from cmdResponse
//!
//! \return from_cmdResponse[portNum]
//!
Fw::InputCmdResponsePort* get_from_cmdResponse(
const NATIVE_INT_TYPE portNum /*!< The port number*/
);
//! Get the port that receives input from PingResponse
//!
//! \return from_PingResponse[portNum]
//!
Svc::InputPingPort* get_from_PingResponse(
const NATIVE_INT_TYPE portNum /*!< The port number*/
);
//! Get the port that receives input from adcOut
//!
//! \return from_adcOut[portNum]
//!
Drv::InputApidPort* get_from_adcOut(
const NATIVE_INT_TYPE portNum /*!< The port number*/
);
//! Get the port that receives input from tlmOut
//!
//! \return from_tlmOut[portNum]
//!
Fw::InputTlmPort* get_from_tlmOut(
const NATIVE_INT_TYPE portNum /*!< The port number*/
);
#if FW_ENABLE_TEXT_LOGGING == 1
//! Get the port that receives input from LogText
//!
//! \return from_LogText[portNum]
//!
Fw::InputLogTextPort* get_from_LogText(
const NATIVE_INT_TYPE portNum /*!< The port number*/
);
#endif
protected:
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
//! Construct object ADCTesterBase
//!
ADCTesterBase(
#if FW_OBJECT_NAMES == 1
const char *const compName, /*!< The component name*/
const U32 maxHistorySize /*!< The maximum size of each history*/
#else
const U32 maxHistorySize /*!< The maximum size of each history*/
#endif
);
//! Destroy object ADCTesterBase
//!
virtual ~ADCTesterBase(void);
// ----------------------------------------------------------------------
// Test history
// ----------------------------------------------------------------------
protected:
//! \class History
//! \brief A history of port inputs
//!
template <typename T> class History {
public:
//! Create a History
//!
History(
const U32 maxSize /*!< The maximum history size*/
) :
numEntries(0),
maxSize(maxSize)
{
this->entries = new T[maxSize];
}
//! Destroy a History
//!
~History() {
delete[] this->entries;
}
//! Clear the history
//!
void clear() { this->numEntries = 0; }
//! Push an item onto the history
//!
void push_back(
T entry /*!< The item*/
) {
FW_ASSERT(this->numEntries < this->maxSize);
entries[this->numEntries++] = entry;
}
//! Get an item at an index
//!
//! \return The item at index i
//!
T at(
const U32 i /*!< The index*/
) const {
FW_ASSERT(i < this->numEntries);
return entries[i];
}
//! Get the number of entries in the history
//!
//! \return The number of entries in the history
//!
U32 size(void) const { return this->numEntries; }
private:
//! The number of entries in the history
//!
U32 numEntries;
//! The maximum history size
//!
const U32 maxSize;
//! The entries
//!
T *entries;
};
//! Clear all history
//!
void clearHistory(void);
protected:
// ----------------------------------------------------------------------
// Handler prototypes for typed from ports
// ----------------------------------------------------------------------
//! Handler prototype for from_PingResponse
//!
virtual void from_PingResponse_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
U32 key /*!< Value to return to pinger*/
) = 0;
//! Handler base function for from_PingResponse
//!
void from_PingResponse_handlerBase(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
U32 key /*!< Value to return to pinger*/
);
//! Handler prototype for from_adcOut
//!
virtual void from_adcOut_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::Time timetag,
U16 apid,
Fw::FileBuffer &data,
U16 apid_rec
) = 0;
//! Handler base function for from_adcOut
//!
void from_adcOut_handlerBase(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::Time timetag,
U16 apid,
Fw::FileBuffer &data,
U16 apid_rec
);
protected:
// ----------------------------------------------------------------------
// Histories for typed from ports
// ----------------------------------------------------------------------
//! Clear from port history
//!
void clearFromPortHistory(void);
//! The total number of from port entries
//!
U32 fromPortHistorySize;
//! Push an entry on the history for from_PingResponse
void pushFromPortEntry_PingResponse(
U32 key /*!< Value to return to pinger*/
);
//! A history entry for from_PingResponse
//!
typedef struct {
U32 key;
} FromPortEntry_PingResponse;
//! The history for from_PingResponse
//!
History<FromPortEntry_PingResponse>
*fromPortHistory_PingResponse;
//! Push an entry on the history for from_adcOut
void pushFromPortEntry_adcOut(
Fw::Time timetag,
U16 apid,
Fw::FileBuffer &data,
U16 apid_rec
);
//! A history entry for from_adcOut
//!
typedef struct {
Fw::Time timetag;
U16 apid;
Fw::FileBuffer data;
U16 apid_rec;
} FromPortEntry_adcOut;
//! The history for from_adcOut
//!
History<FromPortEntry_adcOut>
*fromPortHistory_adcOut;
protected:
// ----------------------------------------------------------------------
// Invocation functions for to ports
// ----------------------------------------------------------------------
//! Invoke the to port connected to schedIn
//!
void invoke_to_schedIn(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
NATIVE_UINT_TYPE context /*!< The call order*/
);
//! Invoke the to port connected to PingRecv
//!
void invoke_to_PingRecv(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
U32 key /*!< Value to return to pinger*/
);
public:
// ----------------------------------------------------------------------
// Getters for port counts
// ----------------------------------------------------------------------
//! Get the number of from_cmdReg ports
//!
//! \return The number of from_cmdReg ports
//!
NATIVE_INT_TYPE getNum_from_cmdReg(void) const;
//! Get the number of from_timeCaller ports
//!
//! \return The number of from_timeCaller ports
//!
NATIVE_INT_TYPE getNum_from_timeCaller(void) const;
//! Get the number of from_eventOut ports
//!
//! \return The number of from_eventOut ports
//!
NATIVE_INT_TYPE getNum_from_eventOut(void) const;
//! Get the number of from_cmdResponse ports
//!
//! \return The number of from_cmdResponse ports
//!
NATIVE_INT_TYPE getNum_from_cmdResponse(void) const;
//! Get the number of to_schedIn ports
//!
//! \return The number of to_schedIn ports
//!
NATIVE_INT_TYPE getNum_to_schedIn(void) const;
//! Get the number of to_cmdIn ports
//!
//! \return The number of to_cmdIn ports
//!
NATIVE_INT_TYPE getNum_to_cmdIn(void) const;
//! Get the number of from_PingResponse ports
//!
//! \return The number of from_PingResponse ports
//!
NATIVE_INT_TYPE getNum_from_PingResponse(void) const;
//! Get the number of from_adcOut ports
//!
//! \return The number of from_adcOut ports
//!
NATIVE_INT_TYPE getNum_from_adcOut(void) const;
//! Get the number of to_PingRecv ports
//!
//! \return The number of to_PingRecv ports
//!
NATIVE_INT_TYPE getNum_to_PingRecv(void) const;
//! Get the number of from_tlmOut ports
//!
//! \return The number of from_tlmOut ports
//!
NATIVE_INT_TYPE getNum_from_tlmOut(void) const;
#if FW_ENABLE_TEXT_LOGGING == 1
//! Get the number of from_LogText ports
//!
//! \return The number of from_LogText ports
//!
NATIVE_INT_TYPE getNum_from_LogText(void) const;
#endif
protected:
// ----------------------------------------------------------------------
// Connection status for to ports
// ----------------------------------------------------------------------
//! Check whether port is connected
//!
//! Whether to_schedIn[portNum] is connected
//!
bool isConnected_to_schedIn(
const NATIVE_INT_TYPE portNum /*!< The port number*/
);
//! Check whether port is connected
//!
//! Whether to_cmdIn[portNum] is connected
//!
bool isConnected_to_cmdIn(
const NATIVE_INT_TYPE portNum /*!< The port number*/
);
//! Check whether port is connected
//!
//! Whether to_PingRecv[portNum] is connected
//!
bool isConnected_to_PingRecv(
const NATIVE_INT_TYPE portNum /*!< The port number*/
);
// ----------------------------------------------------------------------
// Functions for sending commands
// ----------------------------------------------------------------------
protected:
// send command buffers directly - used for intentional command encoding errors
void sendRawCmd(FwOpcodeType opcode, U32 cmdSeq, Fw::CmdArgBuffer& args);
//! Send a ADC_SOC_SET_RATE command
//!
void sendCmd_ADC_SOC_SET_RATE(
const NATIVE_INT_TYPE instance, /*!< The instance number*/
const U32 cmdSeq, /*!< The command sequence number*/
U8 rate /*!< Rate of acquisition. Rate of 0 will set ADC to 0.1Hz, anything else will set it to 1Hz */
);
//! Send a ADC_SOC_SET_RUN command
//!
void sendCmd_ADC_SOC_SET_RUN(
const NATIVE_INT_TYPE instance, /*!< The instance number*/
const U32 cmdSeq, /*!< The command sequence number*/
U8 run_mode /*!< Set run mode. 0 will stop ADC. Anything else will have ADC running. */
);
//! Send a ADC_SOC_SET_PWR_CTRL command
//!
void sendCmd_ADC_SOC_SET_PWR_CTRL(
const NATIVE_INT_TYPE instance, /*!< The instance number*/
const U32 cmdSeq, /*!< The command sequence number*/
U8 pwr_ctrl /*!< Set power mode. 0 will disable power. Anything else will enable power. */
);
//! Send a ADC_SOC_SET_TLM_TIMEOUT command
//!
void sendCmd_ADC_SOC_SET_TLM_TIMEOUT(
const NATIVE_INT_TYPE instance, /*!< The instance number*/
const U32 cmdSeq, /*!< The command sequence number*/
U32 timeout /*!< Timeout value in tick units -- based on connected rategroup connection. */
);
protected:
// ----------------------------------------------------------------------
// Command response handling
// ----------------------------------------------------------------------
//! Handle a command response
//!
virtual void cmdResponseIn(
const FwOpcodeType opCode, /*!< The opcode*/
const U32 cmdSeq, /*!< The command sequence number*/
const Fw::CommandResponse response /*!< The command response*/
);
//! A type representing a command response
//!
typedef struct {
FwOpcodeType opCode;
U32 cmdSeq;
Fw::CommandResponse response;
} CmdResponse;
//! The command response history
//!
History<CmdResponse> *cmdResponseHistory;
protected:
// ----------------------------------------------------------------------
// Event dispatch
// ----------------------------------------------------------------------
//! Dispatch an event
//!
void dispatchEvents(
const FwEventIdType id, /*!< The event ID*/
Fw::Time& timeTag, /*!< The time*/
const Fw::LogSeverity severity, /*!< The severity*/
Fw::LogBuffer& args /*!< The serialized arguments*/
);
//! Clear event history
//!
void clearEvents(void);
//! The total number of events seen
//!
U32 eventsSize;
#if FW_ENABLE_TEXT_LOGGING
protected:
// ----------------------------------------------------------------------
// Text events
// ----------------------------------------------------------------------
//! Handle a text event
//!
virtual void textLogIn(
const FwEventIdType id, /*!< The event ID*/
Fw::Time& timeTag, /*!< The time*/
const Fw::TextLogSeverity severity, /*!< The severity*/
const Fw::TextLogString& text /*!< The event string*/
);
//! A history entry for the text log
//!
typedef struct {
U32 id;
Fw::Time timeTag;
Fw::TextLogSeverity severity;
Fw::TextLogString text;
} TextLogEntry;
//! The history of text log events
//!
History<TextLogEntry> *textLogHistory;
//! Print a text log history entry
//!
static void printTextLogHistoryEntry(
const TextLogEntry& e,
FILE* file
);
//! Print the text log history
//!
void printTextLogHistory(FILE *const file);
#endif
protected:
// ----------------------------------------------------------------------
// Event: ADC_SOC_SetRate
// ----------------------------------------------------------------------
//! Handle event ADC_SOC_SetRate
//!
virtual void logIn_ACTIVITY_HI_ADC_SOC_SetRate(
U8 rate, /*!< The rate ground sent up*/
U8 rate_bit /*!< The rate to set ADC SOC*/
);
//! A history entry for event ADC_SOC_SetRate
//!
typedef struct {
U8 rate;
U8 rate_bit;
} EventEntry_ADC_SOC_SetRate;
//! The history of ADC_SOC_SetRate events
//!
History<EventEntry_ADC_SOC_SetRate>
*eventHistory_ADC_SOC_SetRate;
protected:
// ----------------------------------------------------------------------
// Event: ADC_SOC_SetRun
// ----------------------------------------------------------------------
//! Handle event ADC_SOC_SetRun
//!
virtual void logIn_ACTIVITY_HI_ADC_SOC_SetRun(
U8 run /*!< The run to set ADC SOC*/
);
//! A history entry for event ADC_SOC_SetRun
//!
typedef struct {
U8 run;
} EventEntry_ADC_SOC_SetRun;
//! The history of ADC_SOC_SetRun events
//!
History<EventEntry_ADC_SOC_SetRun>
*eventHistory_ADC_SOC_SetRun;
protected:
// ----------------------------------------------------------------------
// Event: ADC_SOC_SetPwrCtrl
// ----------------------------------------------------------------------
//! Handle event ADC_SOC_SetPwrCtrl
//!
virtual void logIn_ACTIVITY_HI_ADC_SOC_SetPwrCtrl(
U8 pwr_ctrl /*!< The power control to set ADC SOC*/
);
//! A history entry for event ADC_SOC_SetPwrCtrl
//!
typedef struct {
U8 pwr_ctrl;
} EventEntry_ADC_SOC_SetPwrCtrl;
//! The history of ADC_SOC_SetPwrCtrl events
//!
History<EventEntry_ADC_SOC_SetPwrCtrl>
*eventHistory_ADC_SOC_SetPwrCtrl;
protected:
// ----------------------------------------------------------------------
// Event: ADC_SOC_CouldNotSetPwrCtrlBit
// ----------------------------------------------------------------------
//! Handle event ADC_SOC_CouldNotSetPwrCtrlBit
//!
virtual void logIn_ACTIVITY_HI_ADC_SOC_CouldNotSetPwrCtrlBit(
void
);
//! Size of history for event ADC_SOC_CouldNotSetPwrCtrlBit
//!
U32 eventsSize_ADC_SOC_CouldNotSetPwrCtrlBit;
protected:
// ----------------------------------------------------------------------
// Event: ADC_SOC_CouldNotSetRunBit
// ----------------------------------------------------------------------
//! Handle event ADC_SOC_CouldNotSetRunBit
//!
virtual void logIn_ACTIVITY_HI_ADC_SOC_CouldNotSetRunBit(
void
);
//! Size of history for event ADC_SOC_CouldNotSetRunBit
//!
U32 eventsSize_ADC_SOC_CouldNotSetRunBit;
protected:
// ----------------------------------------------------------------------
// Event: ADC_SOC_CouldNotSetRate
// ----------------------------------------------------------------------
//! Handle event ADC_SOC_CouldNotSetRate
//!
virtual void logIn_ACTIVITY_HI_ADC_SOC_CouldNotSetRate(
void
);
//! Size of history for event ADC_SOC_CouldNotSetRate
//!
U32 eventsSize_ADC_SOC_CouldNotSetRate;
protected:
// ----------------------------------------------------------------------
// Event: ADC_SOC_TimedOut
// ----------------------------------------------------------------------
//! Handle event ADC_SOC_TimedOut
//!
virtual void logIn_WARNING_HI_ADC_SOC_TimedOut(
U32 ticks /*!< The number of ticks until ADC SOC times out*/
);
//! A history entry for event ADC_SOC_TimedOut
//!
typedef struct {
U32 ticks;
} EventEntry_ADC_SOC_TimedOut;
//! The history of ADC_SOC_TimedOut events
//!
History<EventEntry_ADC_SOC_TimedOut>
*eventHistory_ADC_SOC_TimedOut;
protected:
// ----------------------------------------------------------------------
// Event: ADC_SOC_SetTimeout
// ----------------------------------------------------------------------
//! Handle event ADC_SOC_SetTimeout
//!
virtual void logIn_ACTIVITY_HI_ADC_SOC_SetTimeout(
U32 timeout /*!< The ADC's Telemetry timeout value*/
);
//! A history entry for event ADC_SOC_SetTimeout
//!
typedef struct {
U32 timeout;
} EventEntry_ADC_SOC_SetTimeout;
//! The history of ADC_SOC_SetTimeout events
//!
History<EventEntry_ADC_SOC_SetTimeout>
*eventHistory_ADC_SOC_SetTimeout;
protected:
// ----------------------------------------------------------------------
// Telemetry dispatch
// ----------------------------------------------------------------------
//! Dispatch telemetry
//!
void dispatchTlm(
const FwChanIdType id, /*!< The channel ID*/
const Fw::Time& timeTag, /*!< The time*/
Fw::TlmBuffer& val /*!< The channel value*/
);
//! Clear telemetry history
//!
void clearTlm(void);
//! The total number of telemetry inputs seen
//!
U32 tlmSize;
protected:
// ----------------------------------------------------------------------
// Channel: ADC_o_a2d_tlm0
// ----------------------------------------------------------------------
//! Handle channel ADC_o_a2d_tlm0
//!
virtual void tlmInput_ADC_o_a2d_tlm0(
const Fw::Time& timeTag, /*!< The time*/
const U32& val /*!< The channel value*/
);
//! A telemetry entry for channel ADC_o_a2d_tlm0
//!
typedef struct {
Fw::Time timeTag;
U32 arg;
} TlmEntry_ADC_o_a2d_tlm0;
//! The history of ADC_o_a2d_tlm0 values
//!
History<TlmEntry_ADC_o_a2d_tlm0>
*tlmHistory_ADC_o_a2d_tlm0;
protected:
// ----------------------------------------------------------------------
// Channel: ADC_o_a2d_tlm1
// ----------------------------------------------------------------------
//! Handle channel ADC_o_a2d_tlm1
//!
virtual void tlmInput_ADC_o_a2d_tlm1(
const Fw::Time& timeTag, /*!< The time*/
const U32& val /*!< The channel value*/
);
//! A telemetry entry for channel ADC_o_a2d_tlm1
//!
typedef struct {
Fw::Time timeTag;
U32 arg;
} TlmEntry_ADC_o_a2d_tlm1;
//! The history of ADC_o_a2d_tlm1 values
//!
History<TlmEntry_ADC_o_a2d_tlm1>
*tlmHistory_ADC_o_a2d_tlm1;
protected:
// ----------------------------------------------------------------------
// Channel: ADC_o_a2d_tlm2
// ----------------------------------------------------------------------
//! Handle channel ADC_o_a2d_tlm2
//!
virtual void tlmInput_ADC_o_a2d_tlm2(
const Fw::Time& timeTag, /*!< The time*/
const U32& val /*!< The channel value*/
);
//! A telemetry entry for channel ADC_o_a2d_tlm2
//!
typedef struct {
Fw::Time timeTag;
U32 arg;
} TlmEntry_ADC_o_a2d_tlm2;
//! The history of ADC_o_a2d_tlm2 values
//!
History<TlmEntry_ADC_o_a2d_tlm2>
*tlmHistory_ADC_o_a2d_tlm2;
protected:
// ----------------------------------------------------------------------
// Channel: ADC_o_a2d_tlm3
// ----------------------------------------------------------------------
//! Handle channel ADC_o_a2d_tlm3
//!
virtual void tlmInput_ADC_o_a2d_tlm3(
const Fw::Time& timeTag, /*!< The time*/
const U32& val /*!< The channel value*/
);
//! A telemetry entry for channel ADC_o_a2d_tlm3
//!
typedef struct {
Fw::Time timeTag;
U32 arg;
} TlmEntry_ADC_o_a2d_tlm3;
//! The history of ADC_o_a2d_tlm3 values
//!
History<TlmEntry_ADC_o_a2d_tlm3>
*tlmHistory_ADC_o_a2d_tlm3;
protected:
// ----------------------------------------------------------------------
// Channel: ADC_o_a2d_tlm4
// ----------------------------------------------------------------------
//! Handle channel ADC_o_a2d_tlm4
//!
virtual void tlmInput_ADC_o_a2d_tlm4(
const Fw::Time& timeTag, /*!< The time*/
const U32& val /*!< The channel value*/
);
//! A telemetry entry for channel ADC_o_a2d_tlm4
//!
typedef struct {
Fw::Time timeTag;
U32 arg;
} TlmEntry_ADC_o_a2d_tlm4;
//! The history of ADC_o_a2d_tlm4 values
//!
History<TlmEntry_ADC_o_a2d_tlm4>
*tlmHistory_ADC_o_a2d_tlm4;
protected:
// ----------------------------------------------------------------------
// Channel: ADC_o_a2d_tlm5
// ----------------------------------------------------------------------
//! Handle channel ADC_o_a2d_tlm5
//!
virtual void tlmInput_ADC_o_a2d_tlm5(
const Fw::Time& timeTag, /*!< The time*/
const U32& val /*!< The channel value*/
);
//! A telemetry entry for channel ADC_o_a2d_tlm5
//!
typedef struct {
Fw::Time timeTag;
U32 arg;
} TlmEntry_ADC_o_a2d_tlm5;
//! The history of ADC_o_a2d_tlm5 values
//!
History<TlmEntry_ADC_o_a2d_tlm5>
*tlmHistory_ADC_o_a2d_tlm5;
protected:
// ----------------------------------------------------------------------
// Channel: ADC_o_a2d_tlm6
// ----------------------------------------------------------------------
//! Handle channel ADC_o_a2d_tlm6
//!
virtual void tlmInput_ADC_o_a2d_tlm6(
const Fw::Time& timeTag, /*!< The time*/
const U32& val /*!< The channel value*/
);
//! A telemetry entry for channel ADC_o_a2d_tlm6
//!
typedef struct {
Fw::Time timeTag;
U32 arg;
} TlmEntry_ADC_o_a2d_tlm6;
//! The history of ADC_o_a2d_tlm6 values
//!
History<TlmEntry_ADC_o_a2d_tlm6>
*tlmHistory_ADC_o_a2d_tlm6;
protected:
// ----------------------------------------------------------------------
// Channel: ADC_o_a2d_tlm7
// ----------------------------------------------------------------------
//! Handle channel ADC_o_a2d_tlm7
//!
virtual void tlmInput_ADC_o_a2d_tlm7(
const Fw::Time& timeTag, /*!< The time*/
const U32& val /*!< The channel value*/
);
//! A telemetry entry for channel ADC_o_a2d_tlm7
//!
typedef struct {
Fw::Time timeTag;
U32 arg;
} TlmEntry_ADC_o_a2d_tlm7;
//! The history of ADC_o_a2d_tlm7 values
//!
History<TlmEntry_ADC_o_a2d_tlm7>
*tlmHistory_ADC_o_a2d_tlm7;
protected:
// ----------------------------------------------------------------------
// Channel: ADC_a2d_stat
// ----------------------------------------------------------------------
//! Handle channel ADC_a2d_stat
//!
virtual void tlmInput_ADC_a2d_stat(
const Fw::Time& timeTag, /*!< The time*/
const U32& val /*!< The channel value*/
);
//! A telemetry entry for channel ADC_a2d_stat
//!
typedef struct {
Fw::Time timeTag;
U32 arg;
} TlmEntry_ADC_a2d_stat;
//! The history of ADC_a2d_stat values
//!
History<TlmEntry_ADC_a2d_stat>
*tlmHistory_ADC_a2d_stat;
protected:
// ----------------------------------------------------------------------
// Test time
// ----------------------------------------------------------------------
//! Set the test time for events and telemetry
//!
void setTestTime(
const Fw::Time& timeTag /*!< The time*/
);
private:
// ----------------------------------------------------------------------
// To ports
// ----------------------------------------------------------------------
//! To port connected to schedIn
//!
Svc::OutputSchedPort m_to_schedIn[1];
//! To port connected to cmdIn
//!
Fw::OutputCmdPort m_to_cmdIn[1];
//! To port connected to PingRecv
//!
Svc::OutputPingPort m_to_PingRecv[1];
private:
// ----------------------------------------------------------------------
// From ports
// ----------------------------------------------------------------------
//! From port connected to cmdReg
//!
Fw::InputCmdRegPort m_from_cmdReg[1];
//! From port connected to timeCaller
//!
Fw::InputTimePort m_from_timeCaller[1];
//! From port connected to eventOut
//!
Fw::InputLogPort m_from_eventOut[1];
//! From port connected to cmdResponse
//!
Fw::InputCmdResponsePort m_from_cmdResponse[1];
//! From port connected to PingResponse
//!
Svc::InputPingPort m_from_PingResponse[1];
//! From port connected to adcOut
//!
Drv::InputApidPort m_from_adcOut[1];
//! From port connected to tlmOut
//!
Fw::InputTlmPort m_from_tlmOut[1];
#if FW_ENABLE_TEXT_LOGGING == 1
//! From port connected to LogText
//!
Fw::InputLogTextPort m_from_LogText[1];
#endif
private:
// ----------------------------------------------------------------------
// Static functions for output ports
// ----------------------------------------------------------------------
//! Static function for port from_cmdReg
//!
static void from_cmdReg_static(
Fw::PassiveComponentBase *const callComp, /*!< The component instance*/
const NATIVE_INT_TYPE portNum, /*!< The port number*/
FwOpcodeType opCode /*!< Command Op Code*/
);
//! Static function for port from_timeCaller
//!
static void from_timeCaller_static(
Fw::PassiveComponentBase *const callComp, /*!< The component instance*/
const NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::Time &time /*!< The U32 cmd argument*/
);
//! Static function for port from_eventOut
//!
static void from_eventOut_static(
Fw::PassiveComponentBase *const callComp, /*!< The component instance*/
const NATIVE_INT_TYPE portNum, /*!< The port number*/
FwEventIdType id, /*!< Log ID*/
Fw::Time &timeTag, /*!< Time Tag*/
Fw::LogSeverity severity, /*!< The severity argument*/
Fw::LogBuffer &args /*!< Buffer containing serialized log entry*/
);
//! Static function for port from_cmdResponse
//!
static void from_cmdResponse_static(
Fw::PassiveComponentBase *const callComp, /*!< The component instance*/
const NATIVE_INT_TYPE portNum, /*!< The port number*/
FwOpcodeType opCode, /*!< Command Op Code*/
U32 cmdSeq, /*!< Command Sequence*/
Fw::CommandResponse response /*!< The command response argument*/
);
//! Static function for port from_PingResponse
//!
static void from_PingResponse_static(
Fw::PassiveComponentBase *const callComp, /*!< The component instance*/
const NATIVE_INT_TYPE portNum, /*!< The port number*/
U32 key /*!< Value to return to pinger*/
);
//! Static function for port from_adcOut
//!
static void from_adcOut_static(
Fw::PassiveComponentBase *const callComp, /*!< The component instance*/
const NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::Time timetag,
U16 apid,
Fw::FileBuffer &data,
U16 apid_rec
);
//! Static function for port from_tlmOut
//!
static void from_tlmOut_static(
Fw::PassiveComponentBase *const callComp, /*!< The component instance*/
const NATIVE_INT_TYPE portNum, /*!< The port number*/
FwChanIdType id, /*!< Telemetry Channel ID*/
Fw::Time &timeTag, /*!< Time Tag*/
Fw::TlmBuffer &val /*!< Buffer containing serialized telemetry value*/
);
#if FW_ENABLE_TEXT_LOGGING == 1
//! Static function for port from_LogText
//!
static void from_LogText_static(
Fw::PassiveComponentBase *const callComp, /*!< The component instance*/
const NATIVE_INT_TYPE portNum, /*!< The port number*/
FwEventIdType id, /*!< Log ID*/
Fw::Time &timeTag, /*!< Time Tag*/
Fw::TextLogSeverity severity, /*!< The severity argument*/
Fw::TextLogString &text /*!< Text of log message*/
);
#endif
private:
// ----------------------------------------------------------------------
// Test time
// ----------------------------------------------------------------------
//! Test time stamp
//!
Fw::Time m_testTime;
};
} // end namespace Drv
#endif
|
DragonJoker/Ashes | source/ashes/renderer/GlRenderer/Core/GlAutoIdIcdObject.cpp | <reponame>DragonJoker/Ashes
/**
*\file
* InlineUniformBlocks.cpp
*\author
* <NAME>
*/
#include "renderer/GlRenderer/Core/GlAutoIdIcdObject.hpp"
namespace ashes::gl
{
}
|
eugeneilyin/mdi-norm | lib/Portrait.js | <reponame>eugeneilyin/mdi-norm<filename>lib/Portrait.js
"use strict";
exports.__esModule = true;
var _createThemedIcon = require("./utils/createThemedIcon");
var _FilledPortrait = require("./FilledPortrait");
var _OutlinePortrait = require("./OutlinePortrait");
var _RoundPortrait = require("./RoundPortrait");
var _SharpPortrait = require("./SharpPortrait");
var _TwoTonePortrait = require("./TwoTonePortrait");
var Portrait =
/*#__PURE__*/
function Portrait(props) {
return (0, _createThemedIcon.createThemedIcon)(props, _FilledPortrait.FilledPortrait, _OutlinePortrait.OutlinePortrait, _RoundPortrait.RoundPortrait, _SharpPortrait.SharpPortrait, _TwoTonePortrait.TwoTonePortrait);
};
exports.Portrait = Portrait; |
kiteco/kiteco-public | kite-python/kite_common/kite/clustering/kmeans.py | import numpy as np
from sklearn.cluster import KMeans
def top_down_cluster(data, ids, max_members):
"""
This function bisects the data set until the size of each cluster is smaller than max_members.
It returns an array of clusters, and each cluster consists of the index of the data point.
"""
clusters = bisect_cluster(data)
found_clusters = []
for label in range(clusters.cluster_centers_.shape[0]):
indices, subset_ids = zip(*[(i, ids[i]) for i, x in enumerate(clusters.labels_) if x == label])
if len(indices) > max_members:
subset = data[indices, :]
if identical(subset):
found_clusters.append(subset_ids)
else:
found_clusters.extend(top_down_cluster(subset, subset_ids, max_members))
else:
found_clusters.append(subset_ids)
return found_clusters
def cluster(data, ids, num_clusters=30):
"""
This function uses kmeans clustering to cluster the data set into k clusters.
It returns an array of clusters, and each cluster consists of the index of the data point.
"""
clusters = KMeans(num_clusters)
clusters.fit(data)
found_clusters = []
for label in range(clusters.cluster_centers_.shape[0]):
indices, subset_ids = zip(*[(i, ids[i]) for i, x in enumerate(clusters.labels_) if x == label])
found_clusters.append(subset_ids)
return found_clusters
def bisect_cluster(data):
kmeans = KMeans(n_clusters=2)
kmeans.fit(data)
return kmeans
def identical(data):
return all(np.array_equal(d, data[0]) for d in data)
|
semmerson/hycast | main/p2p-old/ServerPool.cpp | <gh_stars>0
/**
* A pool of remote servers for creating remote peers.
*
* File: ServerPool.cpp
* Created on: Jun 29, 2019
* Author: <NAME>
*
* Copyright 2021 University Corporation for Atmospheric Research
*
* 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.
*/
#include "config.h"
#include "ServerPool.h"
#include "DelayQueue.h"
#include "LinkedMap.h"
namespace hycast {
class ServerPool::Impl {
public:
virtual ~Impl() =0;
virtual bool ready() const noexcept =0;
/**
* @exceptionsafety Strong guarantee
* @cancellationpoint
*/
virtual SockAddr pop() =0;
virtual void consider(SockAddr& server) =0;
virtual void close() =0;
virtual bool empty() const =0;
};
ServerPool::Impl::~Impl()
{}
/******************************************************************************/
class ServerQueue final : public ServerPool::Impl
{
private:
DelayQueue<SockAddr, std::chrono::seconds> servers;
const unsigned delay;
public:
ServerQueue()
: servers()
, delay(0)
{}
ServerQueue(
const std::set<SockAddr>& servers,
const unsigned delay)
: servers()
, delay{delay}
{
for (const SockAddr sockAddr : servers)
this->servers.push(sockAddr); // No delay
}
bool ready() const noexcept override
{
return servers.ready();
}
/**
* @exceptionsafety Strong guarantee
* @cancellationpoint
*/
SockAddr pop() override
{
return servers.pop();
}
void consider(SockAddr& server) override
{
servers.push(server, delay);
}
void close() override {
servers.close();
}
bool empty() const override
{
return servers.empty();
}
};
/******************************************************************************/
#if 0
/**
* Thread-safe set of server addresses.
*/
class ServerSet final : public ServerPool::Impl
{
private:
using Mutex = std::mutex;
using Guard = std::lock_guard<Mutex>;
using Lock = std::unique_lock<Mutex>;
using Cond = std::condition_variable;
using Index = unsigned;
mutable Mutex mutex;
mutable Cond cond;
LinkedMap<Index, SockAddr> servers;
const Index maxServers;
Index nextIndex;
bool closed;
public:
/**
* @param[in] maxServers Maximum number of servers to track
* @throw InvalidArgument `maxServers == 0`
* @throw InvalidArgument `maxServers` is too large
*/
ServerSet(const Index maxServers)
: mutex{}
, cond{}
, servers(maxServers)
, maxServers(maxServers)
, nextIndex(0)
, closed{false}
{
if (maxServers == 0)
throw INVALID_ARGUMENT("Maximum number of servers is zero");
}
void consider(SockAddr& server) override {
Guard guard{mutex};
if (servers.add(nextIndex, server).second) {
++nextIndex;
while (servers.size() > maxServers)
servers.pop();
cond.notify_all();
}
}
bool ready() const noexcept override {
Guard guard{mutex};
return !servers.empty();
}
/**
* @exceptionsafety Strong guarantee
* @cancellationpoint
*/
SockAddr pop() override {
Lock lock{mutex};
while (!closed && servers.empty())
cond.wait(lock);
if (closed)
throw DOMAIN_ERROR("ServerSet is closed");
return servers.pop();
}
void close() override {
Guard guard{mutex};
closed = true;
cond.notify_all();
}
bool empty() const override {
Guard guard{mutex};
return servers.empty();
}
};
#endif
/******************************************************************************/
ServerPool::ServerPool()
: pImpl{std::make_shared<ServerQueue>()} {
}
ServerPool::ServerPool(
const std::set<SockAddr>& servers,
const unsigned delay)
: pImpl{std::make_shared<ServerQueue>(servers, delay)} {
}
//ServerPool::ServerPool(const unsigned maxServers)
//: pImpl{std::make_shared<ServerSet>(maxServers)} {
//}
bool ServerPool::ready() const noexcept {
return pImpl->ready();
}
SockAddr ServerPool::pop() const {
try {
return pImpl->pop();
}
catch (const std::exception& ex) {
//LOG_DEBUG("Caught std::exception");
throw;
}
catch (...) {
//LOG_DEBUG("Caught ... exception");
throw;
}
}
void ServerPool::consider(SockAddr& server) const {
pImpl->consider(server);
}
void ServerPool::close() {
pImpl->close();
}
bool ServerPool::empty() const {
return pImpl->empty();
}
} // namespace
|
StanfordGeometryLab/artemis | artemis/language/language_preprocessing.py | """
A set of functions that are useful for pre-processing textual data: uniformizing the words, spelling, etc.
The MIT License (MIT)
Copyright (c) 2021 <NAME> (<EMAIL>) & Stanford Geometric Computing Lab
"""
import re
contractions_dict = {
"ain't": "am not",
"aren't": "are not",
"can't": "cannot",
"can't've": "cannot have",
"'cause": "because",
"could've": "could have",
"couldn't": "could not",
"couldn't've": "could not have",
"didn't": "did not",
"doesn't": "does not",
"don't": "do not",
"hadn't": "had not",
"hadn't've": "had not have",
"hasn't": "has not",
"haven't": "have not",
"he'd": "he had",
"he'd've": "he would have",
"he'll": "he will",
"he'll've": "he will have",
"he's": "he is",
"how'd": "how did",
"how'd'y": "how do you",
"how'll": "how will",
"how's": "how is",
"i'd": "I had",
"i'd've": "I would have",
"i'll": "I will",
"i'll've": "I will have",
"i'm": "I am",
"i've": "I have",
"isn't": "is not",
"it'd": "it had",
"it'd've": "it would have",
"it'll": "it will",
"it'll've": "iit will have",
"it's": "it is",
"let's": "let us",
"ma'am": "madam",
"mayn't": "may not",
"might've": "might have",
"mightn't": "might not",
"mightn't've": "might not have",
"must've": "must have",
"mustn't": "must not",
"mustn't've": "must not have",
"needn't": "need not",
"needn't've": "need not have",
"o'clock": "of the clock",
"oughtn't": "ought not",
"oughtn't've": "ought not have",
"shan't": "shall not",
"sha'n't": "shall not",
"shan't've": "shall not have",
"she'd": "she had",
"she'd've": "she would have",
"she'll": "she will",
"she'll've": "she will have",
"she's": "she is",
"should've": "should have",
"shouldn't": "should not",
"shouldn't've": "should not have",
"so've": "so have",
"so's": "so is",
"that'd": "that had",
"that'd've": "that would have",
"that's": "that is",
"there'd": "there had",
"there'd've": "there would have",
"there's": "there is",
"they'd": "they had",
"they'd've": "they would have",
"they'll": "they will",
"they'll've": "they will have",
"they're": "they are",
"they've": "they have",
"to've": "to have",
"wasn't": "was not",
"we'd": "we had",
"we'd've": "we would have",
"we'll": "we will",
"we'll've": "we will have",
"we're": "we are",
"we've": "we have",
"weren't": "were not",
"what'll": "what will",
"what'll've": "what will have",
"what're": "what are",
"what's": "what is",
"what've": "what have",
"when's": "when is",
"when've": "when have",
"where'd": "where did",
"where's": "where is",
"where've": "where have",
"who'll": "who will",
"who'll've": "who will have",
"who's": "who is",
"who've": "who have",
"why's": "why is",
"why've": "why have",
"will've": "will have",
"won't": "will not",
"won't've": "will not have",
"would've": "would have",
"wouldn't": "would not",
"wouldn't've": "would not have",
"y'all": "you all",
"y'all'd": "you all would",
"y'all'd've": "you all would have",
"y'all're": "you all are",
"y'all've": "you all have",
"you'd": "you had",
"you'd've": "you would have",
"you'll": "you will",
"you'll've": "you will have",
"you're": "you are",
"you've": "you have",
"do'nt": "do not",
"does\'nt": "does not"
}
CONTRACTION_RE = re.compile('({})'.format('|'.join(contractions_dict.keys())),
flags=re.IGNORECASE | re.DOTALL)
def expand_contractions(text, contractions=None, lower_i=True):
""" Expand the contractions of the text (if any).
Example: You're a good father. -> you are a good father.
:param text: (string)
:param contractions: (dict)
:param lower_i: boolean, if True (I'm -> 'i am' not 'I am')
:return: (string)
Note:
Side-effect: lower-casing. E.g., You're -> you are.
"""
if contractions is None:
contractions = contractions_dict # Use one define in this .py
def expand_match(contraction):
match = contraction.group(0)
expanded_contraction = contractions.get(match)
if expanded_contraction is None:
expanded_contraction = contractions.get(match.lower())
if lower_i:
expanded_contraction = expanded_contraction.lower()
return expanded_contraction
expanded_text = CONTRACTION_RE.sub(expand_match, text)
return expanded_text
QUOTES_RE_STR = r"""(?:['|"][\w]+['|"])""" # Words encapsulated in apostrophes.
QUOTES_RE = re.compile(r"(%s)" % QUOTES_RE_STR, flags=re.VERBOSE | re.IGNORECASE | re.UNICODE)
def unquote_words(s):
""" 'king' - > king, "queen" -> queen """
iterator = QUOTES_RE.finditer(s)
new_sentence = list(s)
for match in iterator:
start, end = match.span()
new_sentence[start] = ' '
new_sentence[end-1] = ' '
new_sentence = "".join(new_sentence)
return new_sentence
def manual_sentence_spelling(x, spelling_dictionary):
"""
Applies spelling on an entire string, if x is a key of the spelling_dictionary.
:param x: (string) sentence to potentially be corrected
:param spelling_dictionary: correction map
:return: the sentence corrected
"""
if x in spelling_dictionary:
return spelling_dictionary[x]
else:
return x
def manual_tokenized_sentence_spelling(tokens, spelling_dictionary):
"""
:param tokens: (list of tokens) to potentially be corrected
:param spelling_dictionary: correction map
:return: a list of corrected tokens
"""
new_tokens = []
for token in tokens:
if token in spelling_dictionary:
res = spelling_dictionary[token]
if type(res) == list:
new_tokens.extend(res)
else:
new_tokens.append(res)
else:
new_tokens.append(token)
return new_tokens
# noinspection PyInterpreter
if __name__ == "__main__":
import pandas as pd
text = pd.DataFrame({'data': ["I'm a 'good' MAN", "You can't be likee this."]})
print("Original Text:")
print(text.data)
manual_speller = {'You can\'t be likee this.': 'You can\'t be like this.'}
text.data = text.data.apply(lambda x: manual_sentence_spelling(x, manual_speller))
text.data = text.data.apply(lambda x: x.lower())
text.data = text.data.apply(unquote_words)
text.data = text.data.apply(expand_contractions)
print("Corrected Text:")
print(text.data) |
soonhokong/ace | lib/ace/worker/worker_test.js | /* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2010, Ajax.org B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Ajax.org B.V. nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ***** END LICENSE BLOCK ***** */
// The loading of ace/worker/worker is complicated, because when we need to load
// it via RequireJS, it needs a shim to make it into a AMD-module.
// When using the AMD-loader it's just works, so we just it load the file now
require("amd-loader");
define(function(require, exports, module) {
"use strict";
var assert = require("../test/assertions");
var worker = require("./worker")
module.exports = {
setUp : function() {
// And define a few mock dependency modules
worker.define("depA", [], function(require, exports, module) {
module.exports = 'dependency A';
})
worker.define("depB", [], function(require, exports, module) {
module.exports = 'dependency B';
})
},
"test: define() with no dependencies, and CommonJS-compatability require()-calls" : function() {
// We want to be able to call define without an id or deps, but
// since we aren't loading an external file, we must explicitly give
// it some kind of id, in this case 'test1'.
worker.require.id = 'test1';
// Now define out module
worker.define(function(require, exports, module) {
var depA = require("depA");
var depB = require("depB");
assert.equal("dependency A", depA);
assert.equal("dependency B", depB);
module.exports = 'test 1';
})
// And then try and require it
var res = worker.require("test1")
assert.equal("test 1", res)
},
"test: define() with dependencies" : function() {
// We want to be able to call define without an id, but since we aren't
// loading an external file, we must explicitly give it some kind of
// id, in this case 'test2'.
worker.require.id = 'test2';
// Now define our module
worker.define(['depA', 'depB'], function(depA, depB) {
assert.equal("dependency A", depA);
assert.equal("dependency B", depB);
return 'test 2';
})
// And then try and require it
var res = worker.require("test2");
assert.equal("test 2", res);
},
"test: define() used require, exports and module as a dependency": function() {
// We want to be able to call define without an id, but since we aren't
// loading an external file, we must explicitly give it some kind of
// id, in this case 'test3'.
worker.require.id = 'test3';
// Now define our module
worker.define(['require', 'exports', 'module', 'depA', 'depB'], function(require, exports, module) {
var depA = require("depA");
var depB = require("depB");
assert.equal("dependency A", depA);
assert.equal("dependency B", depB);
module.exports = 'test 3';
})
// And then try and require it
var res = worker.require("test3");
assert.equal("test 3", res);
},
"test: define() with a mix of require and actual dependecies": function() {
// We want to be able to call define without an id, but since we aren't
// loading an external file, we must explicitly give it some kind of
// id, in this case 'test4'.
worker.require.id = 'test4';
// Now define our module
worker.define(['depA', 'require'], function(depA, require) {
var depB = require("depB");
assert.equal("dependency A", depA);
assert.equal("dependency B", depB);
return 'test 4';
})
// And then try and require it
var res = worker.require("test4");
assert.equal("test 4", res);
}
}
});
if (typeof module !== "undefined" && module === require.main) {
require("asyncjs").test.testcase(module.exports).exec()
} |
zhaomengxiao/MITK | Plugins/org.blueberry.ui.qt/src/internal/berryEvaluationReference.cpp | /*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "berryEvaluationReference.h"
#include <berryIPropertyChangeListener.h>
namespace berry {
EvaluationReference::EvaluationReference(const SmartPointer<Expression>& expression,
IPropertyChangeListener* listener,
const QString& property)
: EvaluationResultCache(expression),
listener(listener), property(property), postingChanges(true)
{
}
IPropertyChangeListener* EvaluationReference::GetListener() const
{
return listener;
}
QString EvaluationReference::GetProperty() const
{
return property;
}
void EvaluationReference::SetPostingChanges(bool evaluationEnabled)
{
this->postingChanges = evaluationEnabled;
}
bool EvaluationReference::IsPostingChanges() const
{
return postingChanges;
}
}
|
imxiangpeng/webrtc | base/fileutils_unittest.cc | <reponame>imxiangpeng/webrtc<filename>base/fileutils_unittest.cc
/*
* Copyright 2004 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <memory>
#include "webrtc/base/fileutils.h"
#include "webrtc/base/gunit.h"
#include "webrtc/base/pathutils.h"
#include "webrtc/base/stream.h"
namespace rtc {
#if defined (WEBRTC_ANDROID)
// Fails on Android: https://bugs.chromium.org/p/webrtc/issues/detail?id=4364.
#define MAYBE_FilesystemTest DISABLED_FilesystemTest
#else
#define MAYBE_FilesystemTest FilesystemTest
#endif
// Make sure we can get a temp folder for the later tests.
TEST(MAYBE_FilesystemTest, GetTemporaryFolder) {
Pathname path;
EXPECT_TRUE(Filesystem::GetTemporaryFolder(path, true, nullptr));
}
// Test creating a temp file, reading it back in, and deleting it.
TEST(MAYBE_FilesystemTest, TestOpenFile) {
Pathname path;
EXPECT_TRUE(Filesystem::GetTemporaryFolder(path, true, nullptr));
path.SetPathname(Filesystem::TempFilename(path, "ut"));
FileStream* fs;
char buf[256];
size_t bytes;
fs = Filesystem::OpenFile(path, "wb");
ASSERT_TRUE(fs != nullptr);
EXPECT_EQ(SR_SUCCESS, fs->Write("test", 4, &bytes, nullptr));
EXPECT_EQ(4U, bytes);
delete fs;
EXPECT_TRUE(Filesystem::IsFile(path));
fs = Filesystem::OpenFile(path, "rb");
ASSERT_TRUE(fs != nullptr);
EXPECT_EQ(SR_SUCCESS, fs->Read(buf, sizeof(buf), &bytes, nullptr));
EXPECT_EQ(4U, bytes);
delete fs;
EXPECT_TRUE(Filesystem::DeleteFile(path));
EXPECT_FALSE(Filesystem::IsFile(path));
}
// Test opening a non-existent file.
TEST(MAYBE_FilesystemTest, TestOpenBadFile) {
Pathname path;
EXPECT_TRUE(Filesystem::GetTemporaryFolder(path, true, nullptr));
path.SetFilename("not an actual file");
EXPECT_FALSE(Filesystem::IsFile(path));
FileStream* fs = Filesystem::OpenFile(path, "rb");
EXPECT_FALSE(fs != nullptr);
}
} // namespace rtc
|
smalls12/Discord.CPP | docs/search/variables_c.js | var searchData=
[
['member_5fcount',['member_count',['../class_discord_c_p_p_1_1_guild.html#ab10c1ad384ac012715e48ac0a56bde82',1,'DiscordCPP::Guild']]],
['members',['members',['../class_discord_c_p_p_1_1_guild.html#a7860e5065378f6b23b3e22004a55d253',1,'DiscordCPP::Guild']]],
['mention_5feveryone',['mention_everyone',['../class_discord_c_p_p_1_1_message.html#aa889a6c31f4b9a8777bdd9e7f60c2c18',1,'DiscordCPP::Message']]],
['mentions',['mentions',['../class_discord_c_p_p_1_1_message.html#a68a3c7cb7dcc025b826e2befcd8c4c9d',1,'DiscordCPP::Message']]],
['mfa_5fenabled',['mfa_enabled',['../class_discord_c_p_p_1_1_user.html#a1dbf0ab8ecf94b596d2884be3e04638f',1,'DiscordCPP::User']]],
['mfa_5flevel',['mfa_level',['../class_discord_c_p_p_1_1_guild.html#a0f2630d2a346b5b87a094763cbd8cf67',1,'DiscordCPP::Guild']]],
['mute',['mute',['../class_discord_c_p_p_1_1_member.html#a7e46ccab614ca562b9a682b38eeaa190',1,'DiscordCPP::Member']]]
];
|
MrRaffo/raytracer | src/geometry/g_object.c | <reponame>MrRaffo/raytracer<filename>src/geometry/g_object.c
#include <stdio.h>
#include <geometry/g_object.h>
#include <geometry/matrix.h>
#include <scene/material.h>
#include <util/mem.h>
#include <util/log.h>
/* OPERATIONS */
/* create a generic object for testing with no defined shape */
struct g_object *test_object()
{
struct g_object *obj = (struct g_object *)mem_alloc(sizeof(struct g_object));
obj->type = SHAPE_UNASSIGNED;
obj->material = test_material();
obj->transform = matrix_identity(4);
obj->inverse_transform = matrix_identity(4);
obj->transpose_inverse = matrix_identity(4);
return obj;
}
/* set the objects transform and inverse matrix */
void object_transform(struct g_object *shape, struct matrix m)
{
if (shape->transform.matrix != NULL) {
mem_free(shape->transform.matrix);
mem_free(shape->inverse_transform.matrix);
}
shape->transform = m;
// saving the inverse here prevents needing every ray to calculate it
shape->inverse_transform = matrix_inverse(m);
// this is useful for translating world->object space for surface normals
shape->transpose_inverse = matrix_transpose(shape->inverse_transform);
}
/* calculate the surface normal on an object at the given point */
const struct tuple object_normal_at(struct g_object *obj, struct tuple point)
{
switch(obj->type) {
case SHAPE_ORIGIN:
log_err("Invalid object type: ORIGIN");
return tuple_zero();
break;
case SHAPE_PLANE:
return plane_normal_at(obj, point);
break;
case SHAPE_SPHERE:
return sphere_normal_at(obj, point);
break;
case SHAPE_UNASSIGNED:
log_wrn("Invalid object type: UNASSIGNED");
return tuple_zero();
break;
default:
return tuple_zero();
log_wrn("Unrecognised object type");
}
return tuple_zero();
}
/* assign material properties to an object */
void object_set_material(struct g_object *obj, const struct material m)
{
obj->material = m;
}
/* return 1 if objects are identical */
int object_equal(struct g_object *obj1, struct g_object *obj2)
{
return (obj1->type == obj2->type &&
material_equal(obj1->material, obj2->material) &&
matrix_equal(obj1->transform, obj2->transform));
}
/* PRIMITIVES */
/* SPHERE */
/* create a sphere object, used for testing functions */
struct g_object *test_sphere()
{
struct material material = test_material();
struct matrix transform = matrix_identity(4);
struct matrix inverse_transform = matrix_identity(4);
struct matrix transpose_inverse = matrix_identity(4);
struct g_object *sphere = (struct g_object *)mem_alloc(sizeof(struct g_object));
sphere->type = SHAPE_SPHERE;
sphere->material = material;
object_transform(sphere, transform);
//sphere->inverse_transform = inverse_transform;
//sphere->transpose_inverse = transpose_inverse;
return sphere;
}
/* create a sphere with given properties */
struct g_object *sphere(struct material material, struct matrix matrix)
{
struct g_object *sphere = (struct g_object *)mem_alloc(sizeof(struct g_object));
sphere->material = material;
object_transform(sphere, matrix);
sphere->type = SHAPE_SPHERE;
return sphere;
}
/* get the normal at the point the ray hits the sphere */
const struct tuple sphere_normal_at(struct g_object *obj, const struct tuple point)
{
struct tuple obj_point = matrix_transform(obj->inverse_transform, point);
struct tuple obj_normal = tuple_subtract(obj_point, tuple_point(0.0, 0.0, 0.0));
struct tuple world_normal = matrix_transform(obj->transpose_inverse, obj_normal);
world_normal.w = 0.0; // ensure it's treated as a vector
return vector_normal(world_normal);
}
/* PLANE */
/* create a plane object for testing functions */
struct g_object *test_plane()
{
struct g_object *plane = (struct g_object *)mem_alloc(sizeof(struct g_object));
plane->type = SHAPE_PLANE;
object_transform(plane, matrix_identity(4));
return plane;
}
/* returns a normal vector pointing along positive y axis: (0.0, 1.0, 0.0, 0.0) */
const struct tuple plane_normal_at(struct g_object *obj, const struct tuple point)
{
return tuple_vector(0.0, 1.0, 0.0);
}
|
nbv3/voogasalad_CS308 | src/com/syntacticsugar/vooga/gameplayer/attribute/weapons/BasicAutoFireWeaponAttribute.java | package com.syntacticsugar.vooga.gameplayer.attribute.weapons;
import com.syntacticsugar.vooga.authoring.parameters.EditableClass;
import com.syntacticsugar.vooga.authoring.parameters.EditableField;
import com.syntacticsugar.vooga.authoring.parameters.InputParser;
import com.syntacticsugar.vooga.authoring.parameters.InputTypeException;
import com.syntacticsugar.vooga.gameplayer.attribute.IAttribute;
import com.syntacticsugar.vooga.gameplayer.objects.IGameObject;
import com.syntacticsugar.vooga.gameplayer.objects.items.bullets.BulletParams;
import com.syntacticsugar.vooga.gameplayer.objects.items.bullets.TowerBasicBullet;
import com.syntacticsugar.vooga.gameplayer.universe.IGameUniverse;
import javafx.geometry.Point2D;
@EditableClass (
className = "Basic Auto Fire Weapon Attribute"
)
public class BasicAutoFireWeaponAttribute extends AbstractWeaponAttribute {
private int fireRate;
private int myFrameCount;
public BasicAutoFireWeaponAttribute() {
super();
myFrameCount = 0;
}
private BasicAutoFireWeaponAttribute(BasicAutoFireWeaponAttribute toCopy) {
super(toCopy);
this.fireRate = toCopy.fireRate;
this.myFrameCount = toCopy.myFrameCount;
}
@Override
protected IGameObject makeBullet() {
TowerBasicBullet bullet = null;
System.out.println(getParent().getBoundingBox().getWidth());
//getParent().getBoundingBox().get
Point2D bulletInitPos = new Point2D(getParent().getBoundingBox().getPoint().getX() + getParent().getBoundingBox().getWidth()/2.0,
getParent().getBoundingBox().getPoint().getY() + getParent().getBoundingBox().getHeight()/2.0);
BulletParams params = makeParams(bulletInitPos);
bullet = new TowerBasicBullet(params);
return bullet;
}
@Override
public void updateSelf(IGameUniverse universe) {
if (fireConditionsMet()) {
IGameObject bullet = makeBullet();
fireBullet(universe, bullet);
myFrameCount = 0;
}
myFrameCount++;
}
protected boolean fireConditionsMet() {
return (myFrameCount >= fireRate);
}
/** EDIT TAGS **/
/** *************************************** **/
@EditableField
( inputLabel = "Fire rate",
defaultVal = "30" )
private void editFireRate(String arg) {
try {
this.fireRate = InputParser.parseAsInt(arg);
} catch (InputTypeException e) { }
}
@Override
public IAttribute copyAttribute() {
return new BasicAutoFireWeaponAttribute(this);
}
}
|
Rain0193/zafira | sources/zafira-web/angular/client/app/app.module.js | (function () {
'use strict';
angular.module('app', [
// Core modules
'app.core'
// Custom Feature modules
,'app.page'
,'app.services'
,'app.auth'
,'app.dashboard'
,'app.user'
,'app.scm'
,'app.testcase'
,'app.testruninfo'
,'app.testsRuns'
,'app.testDetails'
,'app.view'
,'app.settings'
,'app.monitors'
,'app.integrations'
,'app.certification'
,'app.sidebar'
,'app.common'
,'app.testRunCard'
,'app.testsRunsFilter'
// 3rd party feature modules
,'ngImgCrop'
,'ngecharts'
,'ui.ace'
,'elasticsearch'
,'md.data.table'
,'timer'
,'n3-line-chart'
,'n3-pie-chart'
,'ngSanitize'
,'chieffancypants.loadingBar'
,'textAngular'
,'gridstack-angular'
,'ngMaterialDateRangePicker'
,'angular-jwt'
])
.config(['$httpProvider', '$anchorScrollProvider', function($httpProvider, $anchorScrollProvider) {
$anchorScrollProvider.disableAutoScrolling();
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
// var $window = $(window);
//
// $window.scroll(onScroll);
// $window.resize(onResize);
//
// function onScroll() {
// };
//
// function onResize() {
// };
Array.prototype.indexOfId = function(id) {
for (var i = 0; i < this.length; i++)
if (this[i].id === id)
return i;
return -1;
};
Array.prototype.indexOfName = function(name) {
for (var i = 0; i < this.length; i++)
if (this[i].name === name)
return i;
return -1;
};
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
size++;
}
}
return size;
};
String.prototype.copyToClipboard = function() {
var node = document.createElement('pre');
node.textContent = this;
document.body.appendChild(node);
var selection = getSelection();
selection.removeAllRanges();
var range = document.createRange();
range.selectNodeContents(node);
selection.addRange(range);
document.execCommand('copy');
selection.removeAllRanges();
document.body.removeChild(node);
};
String.prototype.format = function(){
var args = arguments;
return this.replace(/{(\d+)}/g, function(m,n){
return args[n] ? args[n] : m;
});
};
String.prototype.isJsonValid = function(pretty) {
var json = this;
if(pretty) {
json = json.replace(/(['"])?([a-z0-9A-Z_]+)(['"])?:/g, '"$2": ');
json = json.replace(/\'/g, "\"");
}
try {
JSON.parse(json);
} catch (e) {
return false;
}
return true;
};
String.prototype.toJson = function() {
var jsonText = this.replace(/(['"])?([a-z0-9A-Z_]+)(['"])?:/g, '"$2": ');
jsonText = jsonText.replace(/\'/g, "\"");
return JSON.parse(jsonText);
};
Array.prototype.indexOfField = function(fieldName, fieldValue) {
var path = fieldName.split('.');
fieldName = path[path.length - 1];
for (var i = 0; i < this.length; i++) {
var item = this[i];
for (var j = 0; j < path.length - 1; j++) {
item = item[path[j]];
}
if (item && item[fieldName] === fieldValue) {
return i;
}
}
return -1;
};
Array.prototype.indexOfContainsField = function(fieldName, fieldValue) {
for (var i = 0; i < this.length; i++) {
var field = this[i];
if (field && field[fieldName].includes(fieldValue)) {
return i;
}
}
return -1;
};
Array.prototype.equalsByField = function(arrayToCompare, fieldName) {
if(this.length != arrayToCompare.length)
return false;
for(var arrArgIndex = 0; arrArgIndex < this.length; arrArgIndex++) {
var arrArg = this[arrArgIndex];
if(arrayToCompare.indexOfField(fieldName, arrArg[fieldName]) == -1)
return false;
}
return true;
};
Blob.prototype.download = function (filename) {
var link = angular.element('<a>')
.attr('style', 'display: none')
.attr('href', window.URL.createObjectURL(this))
.attr('download', filename.getValidFilename())
.appendTo('body');
link[0].click();
link.remove();
};
String.prototype.zip = function (objectArray) {
var name = this;
var zip = new JSZip();
var data = zip.folder(name);
angular.forEach(objectArray, function (blob, blobName) {
data.file(blobName.getValidFilename(), blob, {base64: true});
});
zip.generateAsync({type:"blob"})
.then(function(content) {
content.download(name + '.zip');
});
};
String.prototype.getValidFilename = function () {
return this.replace(/[/\\?%*:|"<>]/g, '-');
};
}
]).directive('ngReallyClick', [function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('click', function(e) {
e.stopPropagation();
var message = attrs.ngReallyMessage;
if (message && confirm(message)) {
scope.$apply(attrs.ngReallyClick);
}
});
}
}
}]).directive('nonautocomplete', function () {
return {
restrict: 'A',
link:function($scope, element, attrs) {
var firstDivElement = element.parent().closest('div');
angular.element('<input type="password" name="password" class="hide"/>').insertBefore(firstDivElement);
}
};
}).directive('showMore', ['$location', '$anchorScroll', '$timeout', function(location, anchorScroll, timeout) {
return {
restrict: 'AE',
replace: true,
scope: {
text: '=?',
textInline: '@?',
limit:'=',
elementId: '='
},
template: '<div class="wrap"><div ng-show="largeText"> {{ textToEdit | limitTo :end :0 }}.... <a href="javascript:;" ng-click="showMore()" id="more{{ elementId }}" ng-show="isShowMore">Show more</a><a href="javascript:;" id="less{{ elementId }}" ng-click="showLess()" ng-hide="isShowMore">Show less </a></div><div ng-hide="largeText">{{ textToEdit }}</div></div> ',
link: function(scope, iElement, iAttrs) {
anchorScroll.yOffset = 100;
scope.end = scope.limit;
scope.isShowMore = true;
scope.largeText = true;
var showMoreOffset = 0;
var showMoreElementId = 'more' + scope.elementId;
var showLessElementId = 'less' + scope.elementId;
scope.$watchGroup(['text', 'textInline'], function (newValues) {
if(newValues[0] || newValues[1]) {
scope.textToEdit = scope.text ? scope.text : scope.textInline;
if (scope.textToEdit.length <= scope.limit) {
scope.largeText = false;
}
}
});
scope.showMore = function() {
showMoreOffset = angular.element('#' + showMoreElementId).offset().top;
scope.end = scope.textToEdit.length;
scope.isShowMore = false;
};
scope.showLess = function(elementId) {
scope.end = scope.limit;
scope.isShowMore = true;
timeout(function () {
if (window.pageYOffset > showMoreOffset) {
/*if (location.hash() !== showMoreElementId) {
location.hash(showMoreElementId);
} else {*/
anchorScroll(showMoreElementId);
/*}*/
}
}, 80);
};
}
};
}]).directive('showPart', function() {
"use strict";
return {
restrict: 'E',
template: '<span class="zf-show-part"><span>{{ text.substring(0, limit + 1) }}</span><span ng-if="text.length > limit">{{ symbols }}</span></span>',
replace: true,
scope: {
text: '=',
limit: '=',
symbols: '=?'
},
compile: function(element, attrs){
return {
pre: function preLink(scope, iElement, iAttrs, controller) {
if (!attrs.symbols) { scope.symbols = '....'; }
},
post: function postLink(scope, iElement, iAttrs, controller) {
}
}
}
};
}).directive('codeTextarea', ['$timeout', '$interval', '$rootScope', function ($timeout, $interval, $rootScope) {
"use strict";
return {
restrict: 'E',
template: '<span>' +
'<i style="float: right" data-ng-click="refreshHighlighting()" class="fa fa-refresh" data-toggle="tooltip" title="Highlight code syntax" aria-hidden="true"></i>' +
'<i style="float: right" data-ng-click="showWidget()" data-ng-if="codeClass != sql" class="fa fa-pie-chart" data-toggle="tooltip" title="Show widget preview" aria-hidden="true">  </i>' +
'<i style="float: right" data-ng-click="executeSQL()" data-ng-if="codeClass != sql" class="fa fa-flash" data-toggle="tooltip" title="Execute SQL query " aria-hidden="true">  </i>' +
'<pre class="code"><code data-ng-class="{{ codeClass }}" ng-dblclick="refreshHighlighting()" ng-transclude contenteditable="true">{{ codeData }}</code></pre><hr style="margin-top: 0"></span>',
replace: true,
require: 'ngModel',
transclude: true,
scope: {
ngModel: '=',
codeData: '@',
codeClass: '@'
},
link: function (scope, iElement, iAttrs, ngModel) {
var initHighlight = function() {
var myScope = scope.codeClass;
hljs.configure({
tabReplace: ' '
});
scope.refreshHighlighting();
};
scope.refreshHighlighting = function () {
$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
};
scope.executeSQL = function () {
$rootScope.$broadcast('$event:executeSQL');
};
scope.showWidget = function () {
$rootScope.$broadcast('$event:showWidget');
};
$timeout(initHighlight, 100);
iElement.bind("blur keyup change", function() {
ngModel.$setViewValue(iElement[0].innerText.trim());
});
}
};
}]).directive('zafiraBackgroundTheme', ['$rootScope', function ($rootScope) {
return {
restrict: 'A',
link:function($scope, iElement, attrs) {
var element = attrs.zafiraBackgroundTheme;
var darkThemes = $rootScope.darkThemes;
var addTheme = function (mainSkinValue) {
iElement.addClass(getTheme(mainSkinValue));
};
var getTheme = function (mainSkinValue) {
var themeBackgroundClass;
switch (element) {
case 'header':
themeBackgroundClass = darkThemes.indexOf(mainSkinValue) >= 0 ? 'background-darkgreen' : 'background-green';
break;
case 'graph':
themeBackgroundClass = darkThemes.indexOf(mainSkinValue) >= 0 ? 'gray-container' : 'background-clear-white';
break;
case 'table':
themeBackgroundClass = darkThemes.indexOf(mainSkinValue) >= 0 ? 'gray-container' : 'background-clear-white';
break;
case 'modal':
themeBackgroundClass = darkThemes.indexOf(mainSkinValue) >= 0 ? 'gray-container' : 'background-clear-white';
break;
case 'pagination':
themeBackgroundClass = darkThemes.indexOf(mainSkinValue) >= 0 ? 'gray-container' : 'background-clear-white';
break;
default:
themeBackgroundClass = darkThemes.indexOf(mainSkinValue) >= 0 ? 'gray-container' : 'background-clear-white';
break;
}
return themeBackgroundClass;
};
$scope.$watch("main.skin",function(newValue,oldValue) {
if(! newValue && !oldValue) {
newValue = $rootScope.main.skin;
oldValue = $rootScope.main.skin;
} else if($rootScope.main) {
$rootScope.main.skin = newValue;
$rootScope.main.isDark = darkThemes.indexOf(newValue) >= 0;
$scope.main.theme = $rootScope.main.isDark ? 'dark' : '';
$scope.main.default = $rootScope.main.isDark ? 'default' : 'default';
}
iElement[0].classList.remove(getTheme(oldValue));
addTheme(newValue);
});
}
};
}]).directive('sortItem', function () {
"use strict";
return {
restrict: 'A',
template: '<span ng-transclude></span><md-icon class="md-sort-icon" md-svg-icon="arrow-up.svg"></md-icon>',
replace: false,
transclude: true,
scope: {
sortItem: '@'
},
link: function (scope, iElement, iAttrs) {
iElement.bind("click",function() {
switchMode();
});
scope.$watch('sortItem', function (newVal) {
if(newVal) {
switchMode();
}
});
function switchMode() {
var classToAdd = scope.sortItem === 'true' ? 'md-asc' : 'md-desc';
var classToDelete = scope.sortItem === 'true' ? 'md-desc' : 'md-asc';
iElement.children('md-icon')[0].classList.remove(classToDelete);
iElement.children('md-icon').addClass(classToAdd);
};
}
};
}).directive('formErrorValidation', function($q, $timeout, $compile) {
"use strict";
return {
require: 'ngModel',
transclusion: true,
restrict: 'A',
scope: {
ngModel: '=',
formErrorValidation: '='
},
link: function(scope, elm, attrs, ctrl) {
var dataArray = angular.copy(eval(scope.formErrorValidation));
dataArray.splice(dataArray.indexOfName(scope.ngModel), 1);
ctrl.$asyncValidators[elm[0].name] = function(modelValue, viewValue) {
if (ctrl.$isEmpty(modelValue)) {
return $q.resolve();
}
var def = $q.defer();
$timeout(function() {
if (dataArray.indexOfName(modelValue) === -1) {
def.resolve();
} else {
def.reject();
}
}, 200);
return def.promise;
};
}
};
}).directive('photoUpload', ['$timeout', '$rootScope', function ($timeout, $rootScope) {
"use strict";
return {
restrict: 'E',
template: '<div class="page-profile">\n' +
' <div class="container">\n' +
' <div class="bottom-block" md-ink-ripple="grey">\n' +
' <input type="file" id="fileInput" class="content-input" ng-class="{\'not-empty\': myImage}"/>\n' +
' <div ng-if="!fileName || !fileName.length" class="upload-zone-label">Click or drop here</div>' +
' <div ng-if="fileName && fileName.length" class="upload-zone-label">{{fileName}}</div>\n' +
' <img-crop image="myImage" ng-show="otherType == undefined" result-image="myCroppedImage" change-on-fly="true" area-type="{{areaType}}" on-change="onChange()" on-load-done="onDone()"></img-crop>\n' +
' </div>\n' +
' </div>\n' +
' </div>',
require: 'ngModel',
replace: true,
transclude: true,
scope: {
ngModel: '=',
areaType: '@',
otherType: '@'
},
link: function ($scope, iElement, iAttrs, ngModel) {
$scope.myImage = '';
$scope.myCroppedImage = '';
$scope.fileName = '';
var canRecognize = false;
var otherType = $scope.otherType != undefined;
var handleFileSelect=function(evt) {
var file=evt.currentTarget.files[0];
$scope.fileName = file.name;
var reader = new FileReader();
if(! otherType) {
reader.onload = function (evt) {
$scope.imageLoading = true;
$scope.$apply(function($scope){
$scope.myImage=evt.target.result;
});
$scope.imageLoading = false;
};
reader.readAsDataURL(file);
} else {
reader.onload = function (evt) {
$scope.$apply(function($scope){
$scope.file=evt.target.result;
});
$scope.fileName = file.name;
ngModel.$setViewValue(fileToFormData(file));
};
reader.readAsText(file);
}
};
$timeout(function () {
angular.element('#fileInput').on('change',handleFileSelect);
}, 100);
function dataURItoBlob(dataURI) {
var binary = atob(dataURI.split(',')[1]);
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
var array = [];
for(var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], {type: mimeString});
}
function textToBlob(data) {
return new Blob([data], { type: 'application/json' });
}
function blobToFormData() {
var formData = new FormData();
var croppedImage = dataURItoBlob($scope.myCroppedImage);
formData.append("file", croppedImage, $scope.fileName);
return formData;
};
function fileToFormData(file) {
var formData = new FormData();
var blobFile = textToBlob(file);
formData.append('file', blobFile, $scope.fileName);
return formData;
};
$scope.onChange = function (event) {
if(canRecognize) {
ngModel.$setViewValue(blobToFormData());
}
};
$scope.onDone = function () {
canRecognize = true;
$scope.onChange();
};
}
};
}]).directive('fieldError', function($q, $timeout, $compile) {
"use strict";
return {
require: 'ngModel',
transclusion: true,
restrict: 'A',
scope: {
ngModel: '=',
fieldError: '=',
responseField: '@'
},
link: function(scope, elm, attrs, ctrl) {
scope.$watch('fieldError', function (newValue, oldValue) {
if(newValue) {
var result;
newValue.error.data.validationErrors.forEach(function(error) {
if(error.field == scope.responseField)
result = error;
});
if(result) {
ctrl.$setValidity(scope.responseField, false);
}
}
})
scope.$watch('ngModel', function (newVal) {
ctrl.$setValidity(scope.responseField, true);
})
}
};
}).directive('profilePhoto', ['$rootScope', function ($rootScope) {
"use strict";
return {
restrict: 'E',
template: '<span>' +
' <img alt="avatar" ng-src="{{ngModel}}" ng-class="{\'imageRotateHorizontal\': rotateHorizontal}" class="img-circle profile-hovered" ng-if="ngModel && ngModel.length && ngModel.split(\'?\')[0]" style="width: {{imageSize}}px">' +
' <i class="material-icons profile-hovered" style="font-size: {{size}}px; vertical-align: middle; color: #777777" ng-if="icon && iconVisible && !(ngModel && ngModel.length && ngModel.split(\'?\')[0])">{{icon}}</i>' +
' <md-icon class="profile-hovered profile-hovered-full" ng-if="src && !icon && iconVisible && !(ngModel && ngModel.length && ngModel.split(\'?\')[0])" md-svg-src="{{src}}" aria-label="icon" style="width: {{imageSize}}px; height: {{imageSize}}px; color: white;"></md-icon>' +
' <md-tooltip ng-if="label" md-direction="right">{{ label }}</md-tooltip>' +
' </span>',
require: 'ngModel',
replace: true,
transclude: true,
scope: {
ngModel: '=',
size: '=?',
autoResize: '=?',
icon: '@',
iconVisible: '=?',
label: '@',
rotateHorisontal: '=?',
src: '@'
},
compile: function(element, attrs){
return {
pre: function preLink(scope, iElement, iAttrs, controller) {
if (!attrs.size) { scope.size = 120; }
if (!attrs.icon && ! attrs.src) { scope.icon = 'account_circle'; }
if (!attrs.iconVisible) { scope.iconVisible = true; }
if (!attrs.autoResize) { scope.autoResize = true; }
if (!attrs.rotateHorisontal) { scope.rotateHorisontal = false; } else { scope.autoResize = scope.autoResize == 'true' }
scope.imageSize = scope.autoResize ? scope.size - 4 : scope.size;
},
post: function postLink(scope, iElement, iAttrs, controller) {
}
}
}
};
}]).directive('autoHeight', ['$window', function ($window) {
"use strict";
return {
restrict: 'A',
link: function(scope, element, attrs) {
function isMin() {
return angular.element('.nav-collapsed-min').length != 0;
};
var mouseOnElement = false;
var elementClicked = false;
var wasInit = false;
var initOn = attrs.autoHeight;
var trigger = angular.element('*[auto-height-trigger=\'' + initOn + '\']')[0];
trigger.onmouseenter = function () {
mouseOnElement = true;
};
trigger.onmouseleave = function () {
mouseOnElement = false;
};
trigger.onclick = function (event) {
elementClicked = !elementClicked;
var isMin = angular.element('.nav-collapsed-min').length != 0;
if(! isMin && elementClicked && wasInit) {
// timeout need to content animation complete waiting
setTimeout(function () {
if(elementClicked) {
initHeight(element[0]);
}
}, 500);
}
};
function initHeight(el) {
var windowHeight = $window.innerHeight;
var boundingBox = el.getBoundingClientRect();
el.style['height'] = (boundingBox.top + boundingBox.height) > windowHeight ? windowHeight - boundingBox.top - 65 + 'px' : boundingBox.height >= 65 ? boundingBox.height + 'px' : '65px';
el.style['overflow-y'] = 'auto';
};
if(initOn) {
scope.$watch(initOn, function (newVal, oldVal) {
var isMin = angular.element('.nav-collapsed-min').length != 0;
if (newVal) {
wasInit = true;
if (isMin) {
if (mouseOnElement) {
initHeight(element[0]);
}
}
}
});
}
}
};
}]).directive('resize', ['$window', function ($window) {
"use strict";
return {
restrict: 'A',
scope: {
onResizeCallback: '='
},
link: function(scope, element, attrs) {
var DIRECTIONS = {
top: {
min: 65,
func: resizeTop
},
bottom: {
min: 0,
func: resizeBottom
},
right: {
min: 0,
func: resizeRight
},
left: {
min: 60,
func: resizeLeft
}
};
var resizeDirection = attrs.resizeDirection;
var DIRECTION = DIRECTIONS[resizeDirection];
var rightElementStart;
var topElementStart;
var bottomElementStart;
var leftElementStart;
setTimeout(function () {
getDirectionParameters();
var resizeIcon = angular.element('#' + attrs.resize)[0];
resizeIcon.onmousedown = function (mousedownevent) {
element[0].style.position = 'absolute';
element[0].style.right = '0';
$window.onmousemove = function (mouseoverevent) {
DIRECTION.func.call(this, element[0], mouseoverevent);
scope.onResizeCallback.call();
}
};
$window.onmouseup = function () {
$window.onmousemove = undefined;
};
}, 2000);
function getDirectionParameters() {
var elementRect = element[0].getBoundingClientRect();
rightElementStart = $window.innerWidth - elementRect.right;
topElementStart = elementRect.top;
bottomElementStart = $window.innerHeight - elementRect.bottom;
leftElementStart = elementRect.left;
};
function resizeRight(element, event) {
if(event.clientX <= DIRECTION.min) {
element.style.width = event.clientX - $window.innerWidth + leftElementStart + 'px';
}
};
function resizeBottom(element, event) {
if(event.clientY <= DIRECTION.min) {
element.style.height = event.clientY - $window.innerHeight + topElementStart + 'px';
}
};
function resizeTop(element, event) {
if(event.clientY >= DIRECTION.min) {
element.style.height = $window.innerHeight - event.clientY - bottomElementStart + 'px';
}
};
function resizeLeft(element, event) {
if(event.clientX >= DIRECTION.min) {
element.style.width = $window.innerWidth - event.clientX - rightElementStart + 'px';
}
};
}
};
}]).directive('tableLoupe', function () {
"use strict";
return {
restrict: 'A',
scope: {
tableLoupe: '=',
tableLoupeTrigger: '='
},
link: function(scope, element, attrs) {
var currentLoupeElement;
scope.$watch('tableLoupe', function (newVal, oldValue) {
if(newVal) {
if(newVal != oldValue) {
if(currentLoupeElement) {
currentLoupeElement.removeClass('table-loupe-target');
}
currentLoupeElement = doAction(newVal);
}
}
});
scope.$watch('tableLoupeTrigger', function (newVal, oldValue) {
if(newVal) {
element.addClass('table-loupe');
} else {
element.removeClass('table-loupe');
}
});
var tableBody = element[0].getElementsByTagName('tbody')[0];
function doAction(index) {
var logRowElement = angular.element(element.find('tbody tr')[index]);
var logRowElementRect = logRowElement[0].getBoundingClientRect();
var elementRect = tableBody.getBoundingClientRect();
var containerMiddlePoint = elementRect.height / 2;
if(logRowElementRect.top > (elementRect.top + containerMiddlePoint) || (logRowElementRect.top - containerMiddlePoint) < tableBody.scrollTop) {
tableBody.scrollTop = logRowElement[0].offsetTop - containerMiddlePoint;
}
logRowElement.addClass('table-loupe-target');
return logRowElement;
};
}
};
}).directive('passwordEye', function () {
"use strict";
return {
restrict: 'A',
replace: false,
transclude: false,
link: function (scope, iElement, iAttrs, ngModel) {
var eyeElement = angular.element('<i style="position: absolute; right: 20px; bottom: 60%;" class="fa fa-eye"></i>');
iElement.after(eyeElement);
var currentMode = 'password';
var actions = iAttrs.passwordEye.split('-');
if(actions.length == 2) {
eyeElement.on(actions[1].trim(), function () {
iElement[0].type = 'password';
});
eyeElement.on(actions[0].trim(), function () {
iElement[0].type = 'text';
});
}
eyeElement.on(iAttrs.passwordEye, function () {
currentMode = currentMode == 'text' ? 'password' : 'text';
iElement[0].type = currentMode;
});
}
};
}).directive('statusButtons', ['$timeout', function ($timeout) {
"use strict";
return {
restrict: 'AE',
scope: {
onButtonClick: '&onButtonClick',
multi: '=',
options: '='
},
template:
' <div class="test-run-group_group-items">\n' +
' <div name="failed" class="test-run-group_group-items_item FAILED" ng-click="changeStatus($event);"></div>\n' +
' <div name="skipped" class="test-run-group_group-items_item SKIPPED" ng-click="changeStatus($event);"></div>\n' +
' <div name="passed" class="test-run-group_group-items_item PASSED" ng-click="changeStatus($event);"></div>\n' +
' <div name="aborted" class="test-run-group_group-items_item ABORTED" ng-click="changeStatus($event);"></div>\n' +
' <div name="queued" class="test-run-group_group-items_item QUEUED" ng-click="changeStatus($event);"></div>\n' +
' <div name="in_progress" class="test-run-group_group-items_item IN_PROGRESS" ng-click="changeStatus($event);"></div>\n' +
' </div>',
replace: true,
link: function (scope, iElement, iAttrs, ngModel) {
var previousChecked = {};
angular.extend(scope.options, {
reset: function(){
angular.element('.test-run-group_group-items_item').removeClass('item-checked');
previousChecked = {};
scope.options.initValues = [];
scope.onButtonClick({'$statuses': []});
}
});
scope.changeStatus = function (event) {
var elementStatus = angular.element(event.target);
if(previousChecked && (! iAttrs.multi || ! iAttrs.multi == 'true')) {
angular.forEach(previousChecked, function (previousElement) {
previousElement.removeClass('item-checked');
});
previousChecked = {};
}
var value =elementStatus[0].attributes['name'].value;
var removed;
if(previousChecked && iAttrs.multi == 'true' && elementStatus.hasClass('item-checked')) {
elementStatus.removeClass('item-checked');
delete previousChecked[value];
removed = true;
}
if(! removed) {
elementStatus.addClass('item-checked');
previousChecked[value] = elementStatus;
}
var values = collectValues(previousChecked);
scope.onButtonClick({'$statuses': values});
};
function collectValues(elements) {
var result = [];
angular.forEach(elements, function (element) {
result.push(element[0].attributes['name'].value);
});
return result;
};
scope.$watch('options.initValues', function (newVal, oldVal) {
if(newVal) {
if(scope.options && scope.options.initValues) {
scope.options.initValues.forEach(function (value) {
var chipTemplates = angular.element('*[name = ' + value + ']');
chipTemplates.addClass('item-checked');
});
$timeout(function () {
scope.onButtonClick({'$statuses': scope.options.initValues});
}, 0, false);
}
if(scope.options && scope.options.values) {
scope.options.values.forEach(function (value) {
var chipTemplates = angular.element('*[name = ' + value + ']');
chipTemplates.addClass('item-checked');
});
$timeout(function () {
scope.onButtonClick({'$statuses': scope.options.values});
}, 0, false);
}
}
});
}
};
}]).directive('chipsArray', ['$timeout', function ($timeout) {
"use strict";
return {
restrict: 'E',
scope: {
onSelect: '&',
multi: '=',
chips: '=',
countToShow: '=',
options: '='
},
template:
' <div class="test-run-group_tags">\n' +
' <md-chips ng-model="showingChips" md-removable="false" readonly="true">\n' +
' <input disabled>\n' +
' <md-chip-template>\n' +
' <div ng-class="{\'item-default\': $chip.default}" class="chip-item-template" name="{{$chip.value.split(\' \').join(\'\')}}" style="display: inline-block;" ng-click="selectGroup($event, $chip, $index);">\n' +
' <span><span ng-if="! options.hashSymbolHide">#</span>{{$chip.value}}</span>\n' +
' </div>\n' +
' </md-chip-template>\n' +
' </md-chips>\n' +
' <md-menu ng-if="chips.length > countToShow" md-position-mode="left bottom">\n' +
' <md-button aria-label="More tags" ng-click="$mdMenu.open($event);" md-ink-ripple="false" class="md-icon-button no-padding">\n' +
' <i class="fa fa-angle-double-up" aria-hidden="true"></i>\n' +
' </md-button>\n' +
' <md-menu-content class="test-run-group_menu" style="z-index:99;" width="3">\n' +
' <md-list class="md-dense">\n' +
' <md-list-item id="clearProject" class="md-2-line" ng-repeat="chip in chips" md-prevent-menu-close>\n' +
' <md-checkbox md-prevent-menu-close class="md-primary" ng-model="chip.checked" aria-label="tag"></md-checkbox>\n' +
' <div class="md-list-item-text">\n' +
' {{chip.value}}\n' +
' </div>\n' +
' </md-list-item>\n' +
' <md-list-item>\n' +
' <button md-prevent-menu-close style="margin-right: 8px" class="md-button md-raised md-dark md-ink-ripple" type="button" ng-click="resetCheckedTags();">\n' +
' RESET\n' +
' </button>\n' +
' <button class="md-button md-primary md-raised md-ink-ripple" type="button" ng-click="addCheckedTags();">\n' +
' APPLY\n' +
' </button>\n' +
' </md-list-item>\n' +
' </md-list>\n' +
' </md-menu-content>\n' +
' </md-menu>\n' +
' </div>',
replace: true,
link: function (scope, iElement, iAttrs, ngModel) {
scope.showingChips = [];
var selectedTags = {};
angular.extend(scope.options, {
reset: function(onSwitch){
angular.element('md-chip').removeClass('md-focused');
if(! onSwitch) {
angular.element('md-chip:has(.chip-item-template.item-default)').addClass('md-focused');
}
scope.chips.filter(function (chip) {
return chip.default && ! onSwitch;
}).forEach(function (chip) {
selectedTags[chip.name + chip.value] = chip.value;
});
selectedTags = ! onSwitch ? selectedTags : {};
scope.options.initValues = [];
scope.onSelect({'$tags': selectedTags});
}
});
scope.selectGroup = function(event, currentChip, index) {
var chip = angular.element(event.target.closest('md-chip'));
if(! scope.multi) {
scope.options.reset(true);
}
if(chip.hasClass('md-focused')) {
chip.removeClass('md-focused');
delete selectedTags[currentChip.name + currentChip.value];
} else {
chip.addClass('md-focused');
selectedTags[currentChip.name + currentChip.value] = currentChip.value;
}
scope.onSelect({'$tags': collectSelectedTags()});
};
function collectSelectedTags() {
var result = [];
angular.forEach(selectedTags, function (value) {
result.push(value);
});
return result;
};
function collectTagsToShow() {
return scope.chips.filter(function (chip) {
return chip.checked;
});
};
scope.resetCheckedTags = function () {
scope.chips.forEach(function (chip) {
chip.checked = false;
});
};
scope.addCheckedTags = function () {
scope.showingChips = collectTagsToShow();
};
scope.$watch('chips', function (newVal) {
if(newVal) {
if(scope.countToShow > 0 && scope.chips) {
scope.chips.forEach(function (chip, index) {
if(scope.countToShow > index) {
chip.checked = true;
}
});
scope.addCheckedTags();
}
}
});
scope.$watch('options.initValues', function (newVal, oldVal) {
if(newVal && newVal.length) {
$timeout(function () {
if (scope.options && scope.options.initValues) {
scope.options.initValues.forEach(function (value) {
var chipTemplates = angular.element('*[name = ' + value.split(' ').join('') + ']');
angular.forEach(chipTemplates, function (element) {
angular.element(element.closest('md-chip')).addClass('md-focused');
});
});
scope.onSelect({'$tags': scope.options.initValues});
}
}, 0, false);
}
});
}
};
}])
.directive('windowWidth', function ($window, windowWidthService) {
"use strict";
return {
restrict: 'A',
link: function($scope) {
angular.element($window).on('resize', function() {
windowWidthService.windowWidth = $window.innerWidth;
windowWidthService.windowHeight = $window.innerHeight;
$scope.$digest();
$scope.$emit('resize.getWindowSize', {
innerWidth: windowWidthService.windowWidth,
innerHeight: windowWidthService.windowHeight
});
});
}
};
})
.filter('orderObjectBy', ['$sce', function($sce) {
var STATUSES_ORDER = {
'PASSED': 0,
'FAILED': 1,
'SKIPPED': 2,
'IN_PROGRESS': 3,
'ABORTED': 4,
'QUEUED': 5
};
return function(items, field, reverse) {
if(field) {
var filtered = [];
angular.forEach(items, function (item) {
filtered.push(item);
});
filtered.sort(function (a, b) {
var aValue = a;
var bValue = b;
// cause field has a complex structure (with '.')
field.split('.').forEach(function(item) {
aValue = aValue[item];
bValue = bValue[item];
});
// cause field is html - we should to compare by inner text
try {
$sce.parseAsHtml(aValue);
$sce.parseAsHtml(bValue);
} catch(e) {
aValue = aValue ? String(aValue).replace(/<[^>]+>/gm, '') : '';
bValue = bValue ? String(bValue).replace(/<[^>]+>/gm, '') : '';
}
if(aValue == null || bValue == null) {
return aValue == null ? -1 : 1;
}
return field == 'status' ? (STATUSES_ORDER[aValue] > STATUSES_ORDER[bValue] ? 1 : -1) :
typeof aValue == 'string' ? (aValue.toLowerCase() > bValue.toLowerCase() ? 1 : -1) : (aValue > bValue ? 1 : -1);
});
if (reverse) filtered.reverse();
return filtered;
}
return items
};
}]).filter('isEmpty', [function() {
return function(object) {
return angular.equals({}, object);
}
}])
.run(['$rootScope',
'$location',
'$cookies',
'$http',
'$transitions',
'AuthService',
'$document',
'UserService',
function($rootScope, $location, $cookies, $http, $transitions, AuthService,
$document, UserService) {
$transitions.onBefore({}, function(trans) {
var toState = trans.to();
var toStateParams = trans.params();
var loginRequired = !!(toState.data && toState.data.requireLogin);
var onlyGuests = !!(toState.data && toState.data.onlyGuests);
var isAuthorized = AuthService.isAuthorized();
var currentUser = UserService.getCurrentUser();
//Redirect to login page if authorization is required and user is not authorized
if (loginRequired && !isAuthorized) {
return trans.router.stateService.target('signin', {referrer: toState.name, referrerParams: toStateParams});
} else if (onlyGuests) {
if (isAuthorized) {
if (currentUser) {
return trans.router.stateService.target('dashboard', {id: currentUser.defaultDashboardId});
} else {
var authData = AuthService.getAuthData();
if (authData) {
$rootScope.$broadcast('event:auth-loginSuccess', {auth: authData});
}
return false;
}
}
}
});
$transitions.onSuccess({}, function() {
$document.scrollTo(0, 0);
});
}
])
})();
|
kkrampa/commcare-hq | corehq/messaging/smsbackends/telerivet/admin.py | from __future__ import absolute_import
from __future__ import unicode_literals
from django.contrib import admin
from corehq.messaging.smsbackends.telerivet.models import IncomingRequest
class IncomingRequestAdmin(admin.ModelAdmin):
list_display = [
'event',
'message_id',
'message_type',
'from_number',
'from_number_e164',
'to_number',
'time_created',
'time_sent',
]
search_fields = [
'message_id',
'from_number',
'from_number_e164',
'to_number',
'time_created',
'time_sent',
]
admin.site.register(IncomingRequest, IncomingRequestAdmin)
|
mamacmm/lemon | src/main/java/com/mossle/ext/store/StoreHelper.java | package com.mossle.ext.store;
import java.io.InputStream;
import javax.activation.DataSource;
import org.springframework.core.io.Resource;
public interface StoreHelper {
StoreResult getStore(String model, String key) throws Exception;
void removeStore(String model, String key) throws Exception;
StoreResult saveStore(String model, DataSource dataSource) throws Exception;
StoreResult saveStore(String model, String key, DataSource dataSource)
throws Exception;
}
|
focusunsink/study_python | np/10_SciPy/3_4_stats.py | # -*- coding:utf-8 -*-
"""
Project : numpy
File Name : 3_4_stats
Author : Focus
Date : 8/24/2021 10:39 PM
Keywords :
Abstract :
Param :
Usage : py 3_4_stats
Reference :
"""
import numpy as np
import matplotlib.pyplot as plt
import sys
from scipy import stats
generated = stats.norm.rvs(size=900)
print("Mean", "std", stats.norm.fit(generated))
print("Skewtest", "pvalue", stats.skewtest(generated))
print("Kurtosistest", "pvalue", stats.kurtosistest(generated))
print("Normality test", stats.normaltest(generated))
print("95 Percentile", stats.scoreatpercentile(generated, 95))
print("95 Percentile", stats.percentileofscore(generated, 1))
plt.hist(generated)
plt.show() |
turbot/steampipe-plugin-jira | jira/table_jira_project.go | package jira
import (
"context"
"fmt"
"github.com/andygrunwald/go-jira"
"github.com/turbot/steampipe-plugin-sdk/grpc/proto"
"github.com/turbot/steampipe-plugin-sdk/plugin/transform"
"github.com/turbot/steampipe-plugin-sdk/plugin"
)
//// TABLE DEFINITION
func tableProject(_ context.Context) *plugin.Table {
return &plugin.Table{
Name: "jira_project",
Description: "Project is a collection of issues (stories, bugs, tasks, etc).",
Get: &plugin.GetConfig{
KeyColumns: plugin.SingleColumn("id"),
Hydrate: getProject,
},
List: &plugin.ListConfig{
Hydrate: listProjects,
},
Columns: []*plugin.Column{
{
Name: "id",
Description: "The ID of the project.",
Type: proto.ColumnType_STRING,
Transform: transform.FromGo(),
},
{
Name: "name",
Description: "The name of the project.",
Type: proto.ColumnType_STRING,
},
{
Name: "key",
Description: "The key of the project.",
Type: proto.ColumnType_STRING,
},
{
Name: "self",
Description: "The URL of the project details.",
Type: proto.ColumnType_STRING,
},
{
Name: "description",
Description: "A brief description of the project.",
Type: proto.ColumnType_STRING,
Hydrate: getProject,
Transform: transform.FromCamel().NullIfZero(),
},
{
Name: "email",
Description: "An email address associated with the project.",
Type: proto.ColumnType_STRING,
Hydrate: getProject,
Transform: transform.FromCamel().NullIfZero(),
},
{
Name: "lead_account_id",
Description: "The user account id of the project lead.",
Type: proto.ColumnType_STRING,
Hydrate: getProject,
Transform: transform.FromField("Lead.AccountID"),
},
{
Name: "lead_display_name",
Description: "The user display name of the project lead.",
Type: proto.ColumnType_STRING,
Hydrate: getProject,
Transform: transform.FromField("Lead.DisplayName"),
},
{
Name: "project_type_key",
Description: "The project type of the project. Valid values are software, service_desk and business.",
Type: proto.ColumnType_STRING,
},
{
Name: "url",
Description: "A link to information about this project, such as project documentation.",
Type: proto.ColumnType_STRING,
Hydrate: getProject,
},
// json fields
// {
// Name: "avatar_urls",
// Description: "The URLs of the project's avatars.",
// Type: proto.ColumnType_JSON,
// },
{
Name: "component_ids",
Description: "List of the components contained in the project.",
Type: proto.ColumnType_JSON,
Hydrate: getProject,
Transform: transform.FromField("Components").Transform(extractProjectComponentIds),
},
{
Name: "issue_types",
Description: "List of the issue types available in the project.",
Type: proto.ColumnType_JSON,
},
{
Name: "project_category",
Description: "The category the project belongs to.",
Type: proto.ColumnType_JSON,
Transform: transform.FromCamel().NullIfZero(),
},
// Standard columns
{
Name: "title",
Description: ColumnDescriptionTitle,
Type: proto.ColumnType_STRING,
Transform: transform.FromField("Name"),
},
},
}
}
//// LIST FUNCTION
func listProjects(ctx context.Context, d *plugin.QueryData, _ *plugin.HydrateData) (interface{}, error) {
logger := plugin.Logger(ctx)
logger.Trace("listProjects")
client, err := connect(ctx, d)
if err != nil {
return nil, err
}
req, err := client.NewRequest("GET", "/rest/api/3/project", nil)
if err != nil {
return nil, err
}
projectList := new(ProjectList)
_, err = client.Do(req, projectList)
if err != nil {
logger.Error("listProjects", "Error", err)
return nil, err
}
for _, project := range *projectList {
d.StreamListItem(ctx, project)
}
return nil, nil
}
//// HYDRATE FUNCTION
func getProject(ctx context.Context, d *plugin.QueryData, h *plugin.HydrateData) (interface{}, error) {
logger := plugin.Logger(ctx)
logger.Trace("getProject")
var projectId string
if h.Item != nil {
projectId = h.Item.(Project).ID
} else {
projectId = d.KeyColumnQuals["id"].GetStringValue()
}
if projectId == "" {
return nil, nil
}
client, err := connect(ctx, d)
if err != nil {
return nil, err
}
apiEndpoint := fmt.Sprintf("/rest/api/3/project/%s", projectId)
req, err := client.NewRequest("GET", apiEndpoint, nil)
if err != nil {
return nil, err
}
project := new(Project)
_, err = client.Do(req, project)
if err != nil {
if isNotFoundError(err) {
return nil, nil
}
logger.Error("getUserGroups", "Error", err)
return nil, err
}
return project, err
}
//// TRANSFORM FUNCTION
func extractProjectComponentIds(_ context.Context, d *transform.TransformData) (interface{}, error) {
var componentIds []string
for _, item := range d.Value.([]jira.ProjectComponent) {
componentIds = append(componentIds, item.ID)
}
return componentIds, nil
}
//// Custom Structs
type ProjectList []Project
// Project represents a Jira Project.
type Project struct {
Expand string `json:"expand,omitempty" structs:"expand,omitempty"`
Self string `json:"self,omitempty" structs:"self,omitempty"`
ID string `json:"id,omitempty" structs:"id,omitempty"`
Key string `json:"key,omitempty" structs:"key,omitempty"`
Description string `json:"description,omitempty" structs:"description,omitempty"`
Lead jira.User `json:"lead,omitempty" structs:"lead,omitempty"`
Components []jira.ProjectComponent `json:"components,omitempty" structs:"components,omitempty"`
IssueTypes []jira.IssueType `json:"issueTypes,omitempty" structs:"issueTypes,omitempty"`
URL string `json:"url,omitempty" structs:"url,omitempty"`
Email string `json:"email,omitempty" structs:"email,omitempty"`
AssigneeType string `json:"assigneeType,omitempty" structs:"assigneeType,omitempty"`
Versions []jira.Version `json:"versions,omitempty" structs:"versions,omitempty"`
Name string `json:"name,omitempty" structs:"name,omitempty"`
Roles map[string]string `json:"roles,omitempty" structs:"roles,omitempty"`
AvatarUrls jira.AvatarUrls `json:"avatarUrls,omitempty" structs:"avatarUrls,omitempty"`
ProjectCategory jira.ProjectCategory `json:"projectCategory,omitempty" structs:"projectCategory,omitempty"`
ProjectTypeKey string `json:"projectTypeKey" structs:"projectTypeKey"`
}
|
silhavyj/inode-based-file-system | doc/doxygen/html/search/all_9.js | var searchData=
[
['kb_88',['KB',['../class_disk.html#a8343bf2c626fc6076f0a4fefae42726d',1,'Disk']]]
];
|
SwerveRoboticsTeams/FtcRobotController | Team6220_2020/src/main/java/org/firstinspires/ftc/team6220_2020/TestClasses/OpenCVTest.java | package org.firstinspires.ftc.team6220_2020.TestClasses;
import android.graphics.Rect;
import android.graphics.YuvImage;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import org.firstinspires.ftc.robotcore.external.hardware.camera.WebcamName;
import org.firstinspires.ftc.team6220_2020.MasterTeleOp;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.imgproc.Imgproc;
import org.openftc.easyopencv.OpenCvCamera;
import org.openftc.easyopencv.OpenCvCameraFactory;
import org.openftc.easyopencv.OpenCvCameraRotation;
import org.openftc.easyopencv.OpenCvPipeline;
import java.util.ArrayList;
import java.util.List;
@TeleOp(name = "OpenCV Test", group = "TeleOp")
public class OpenCVTest extends MasterTeleOp {
OpenCvCamera webcam;
public double ringStackSize = 0;
@Override
public void runOpMode() throws InterruptedException {
Initialize();
int cameraMonitorViewId = hardwareMap.appContext.getResources().getIdentifier("cameraMonitorViewId", "id", hardwareMap.appContext.getPackageName());
webcam = OpenCvCameraFactory.getInstance().createWebcam(hardwareMap.get(WebcamName.class, "Webcam 1"), cameraMonitorViewId);
webcam.setPipeline(new RingDetectionPipeline());
webcam.openCameraDeviceAsync(new OpenCvCamera.AsyncCameraOpenListener()
{
@Override
public void onOpened()
{
webcam.startStreaming(320, 240, OpenCvCameraRotation.UPRIGHT);
}
});
telemetry.addLine("Waiting for start");
telemetry.update();
waitForStart();
while(opModeIsActive()){
telemetry.addData("Frame Count", webcam.getFrameCount());
telemetry.addData("FPS", String.format("%.2f", webcam.getFps()));
telemetry.addData("Total frame time ms", webcam.getTotalFrameTimeMs());
telemetry.addData("Pipeline time ms", webcam.getPipelineTimeMs());
telemetry.addData("Overhead time ms", webcam.getOverheadTimeMs());
telemetry.addData("Theoretical max FPS", webcam.getCurrentPipelineMaxFps());
telemetry.update();
if(gamepad1.a)
{
webcam.stopStreaming();
webcam.closeCameraDevice();
}
sleep(100);
idle();
}
}
/*
* An example image processing pipeline to be run upon receipt of each frame from the camera.
* Note that the processFrame() method is called serially from the frame worker thread -
* that is, a new camera frame will not come in while you're still processing a previous one.
* In other words, the processFrame() method will never be called multiple times simultaneously.
*
* However, the rendering of your processed image to the viewport is done in parallel to the
* frame worker thread. That is, the amount of time it takes to render the image to the
* viewport does NOT impact the amount of frames per second that your pipeline can process.
*
* IMPORTANT NOTE: this pipeline is NOT invoked on your OpMode thread. It is invoked on the
* frame worker thread. This should not be a problem in the vast majority of cases. However,
* if you're doing something weird where you do need it synchronized with your OpMode thread,
* then you will need to account for that accordingly.
*/
class RingDetectionPipeline extends OpenCvPipeline
{
boolean viewportPaused;
/*
* NOTE: if you wish to use additional Mat objects in your processing pipeline, it is
* highly recommended to declare them here as instance variables and re-use them for
* each invocation of processFrame(), rather than declaring them as new local variables
* each time through processFrame(). This removes the danger of causing a memory leak
* by forgetting to call mat.release(), and it also reduces memory pressure by not
* constantly allocating and freeing large chunks of memory.
*/
@Override
public Mat processFrame(Mat input)
{
/*
* IMPORTANT NOTE: the input Mat that is passed in as a parameter to this method
* will only dereference to the same image for the duration of this particular
* invocation of this method. That is, if for some reason you'd like to save a copy
* of this particular frame for later use, you will need to either clone it or copy
* it to another Mat.
*/
double maxArea;
int maxAreaContour;
Mat originalInput = input;
Imgproc.cvtColor(input, input, Imgproc.COLOR_BGR2YUV);
Imgproc.medianBlur(input, input, 11);
List<Mat> yuvSplit = new ArrayList<>();
Core.split(input, yuvSplit);
Mat u = yuvSplit.get(1);
Imgproc.threshold(u,u, 147,255, Imgproc.THRESH_BINARY);
telemetry.addData("Thresh", gamepad1.right_trigger * 90);
List<MatOfPoint> contours = new ArrayList<>();
Mat hierarchy = new Mat();
Imgproc.findContours(u, contours, hierarchy, Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE);
if(contours.size() > 0){
maxArea = 0.0;
maxAreaContour = -1;
for(int i = 0; i < contours.size(); i++){
if(Imgproc.contourArea(contours.get(i)) > maxArea){
maxArea = Imgproc.contourArea(contours.get(i));
maxAreaContour = i;
}
}
Imgproc.rectangle(u, Imgproc.boundingRect(contours.get(maxAreaContour)), new Scalar(255, 0, 0));
ringStackSize = maxArea;
}
/**
* NOTE: to see how to get data from your pipeline to your OpMode as well as how
* to change which stage of the pipeline is rendered to the viewport when it is
* tapped, please see {@link PipelineStageSwitchingExample}
*/
return u;
}
@Override
public void onViewportTapped()
{
/*
* The viewport (if one was specified in the constructor) can also be dynamically "paused"
* and "resumed". The primary use case of this is to reduce CPU, memory, and power load
* when you need your vision pipeline running, but do not require a live preview on the
* robot controller screen. For instance, this could be useful if you wish to see the live
* camera preview as you are initializing your robot, but you no longer require the live
* preview after you have finished your initialization process; pausing the viewport does
* not stop running your pipeline.
*
* Here we demonstrate dynamically pausing/resuming the viewport when the user taps it
*/
viewportPaused = !viewportPaused;
if(viewportPaused)
{
webcam.pauseViewport();
}
else
{
webcam.resumeViewport();
}
}
}
}
|
shaojiankui/iOS10-Runtime-Headers | Frameworks/WebKit.framework/_WKWebsiteDataSize.h | <filename>Frameworks/WebKit.framework/_WKWebsiteDataSize.h
/* Generated by RuntimeBrowser
Image: /System/Library/Frameworks/WebKit.framework/WebKit
*/
@interface _WKWebsiteDataSize : NSObject {
struct Size {
unsigned long long totalSize;
struct HashMap<unsigned int, unsigned long long, WTF::IntHash<unsigned int>, WTF::HashTraits<unsigned int>, WTF::HashTraits<unsigned long long> > {
struct HashTable<unsigned int, WTF::KeyValuePair<unsigned int, unsigned long long>, WTF::KeyValuePairKeyExtractor<WTF::KeyValuePair<unsigned int, unsigned long long> >, WTF::IntHash<unsigned int>, WTF::HashMap<unsigned int, unsigned long long, WTF::IntHash<unsigned int>, WTF::HashTraits<unsigned int>, WTF::HashTraits<unsigned long long> >::KeyValuePairTraits, WTF::HashTraits<unsigned int> > {
struct KeyValuePair<unsigned int, unsigned long long> {} *m_table;
unsigned int m_tableSize;
unsigned int m_tableSizeMask;
unsigned int m_keyCount;
unsigned int m_deletedCount;
} m_impl;
} typeSizes;
} _size;
}
@property (nonatomic, readonly) unsigned long long totalSize;
- (id).cxx_construct;
- (void).cxx_destruct;
- (id)initWithSize:(const struct Size { unsigned long long x1; struct HashMap<unsigned int, unsigned long long, WTF::IntHash<unsigned int>, WTF::HashTraits<unsigned int>, WTF::HashTraits<unsigned long long> > { struct HashTable<unsigned int, WTF::KeyValuePair<unsigned int, unsigned long long>, WTF::KeyValuePairKeyExtractor<WTF::KeyValuePair<unsigned int, unsigned long long> >, WTF::IntHash<unsigned int>, WTF::HashMap<unsigned int, unsigned long long, WTF::IntHash<unsigned int>, WTF::HashTraits<unsigned int>, WTF::HashTraits<unsigned long long> >::KeyValuePairTraits, WTF::HashTraits<unsigned int> > { struct KeyValuePair<unsigned int, unsigned long long> {} *x_1_2_1; unsigned int x_1_2_2; unsigned int x_1_2_3; unsigned int x_1_2_4; unsigned int x_1_2_5; } x_2_1_1; } x2; }*)arg1;
- (unsigned long long)sizeOfDataTypes:(id)arg1;
- (unsigned long long)totalSize;
@end
|
vjmadrid/enmilocalfunciona-kafka | architecture/architecture-kafka-common/src/main/java/com/acme/architecture/kafka/common/consumer/enumeration/SeekToTypeEnumeration.java | <reponame>vjmadrid/enmilocalfunciona-kafka<filename>architecture/architecture-kafka-common/src/main/java/com/acme/architecture/kafka/common/consumer/enumeration/SeekToTypeEnumeration.java
package com.acme.architecture.kafka.common.consumer.enumeration;
public enum SeekToTypeEnumeration {
NONE, START, END, LOCATION
}
|
CaliStyle/trailpack-proxy-generics | lib/schemas/geolocationProvider/index.js | exports.locate = require('./locate')
exports.locateSuccess = require('./locateSuccess')
|
rgcl/dgrid | test/intern/core/createDestroy.js | define([
'intern!tdd',
'intern/chai!assert',
'dojo/_base/declare',
'dojo/on',
'dgrid/List',
'dgrid/OnDemandList',
'dstore/Memory'
], function (test, assert, declare, on, List, OnDemandList, Memory) {
test.suite('createDestroy', function () {
test.test('no params list', function () {
var list = new List();
document.body.appendChild(list.domNode);
list.startup();
list.renderArray([ 'foo', 'bar', 'baz' ]);
assert.strictEqual(list.contentNode.children.length, 3,
'List\'s contentNode has expected number of children after renderArray');
list.destroy();
assert.notStrictEqual(document.body, list.parentNode,
'List is removed from body after destroy');
});
// Test for issue #1030
test.test('OnDemandList#refresh should not throw error if domNode is nullified when destroyed', function () {
var CustomList = declare(OnDemandList, {
destroy: function () {
this.inherited(arguments);
// If dgrid is mixed in with dijit hierarchy, destroy() may unset domNode
this.domNode = null;
}
});
var dfd = this.async();
var grid = new CustomList({
collection: new Memory({ data: [
{ id: 1 },
{ id: 2 },
{ id: 3 }
] })
});
document.body.appendChild(grid.domNode);
grid.startup();
assert.strictEqual(grid.contentNode.children.length, 5,
'Grid\'s contentNode has expected number of children after renderArray');
grid.destroy();
assert.notStrictEqual(document.body, grid.parentNode, 'Grid is removed from body after destroy');
// Start watching for global error. There should be none.
// (Can't use assert.doesNotThrow since this will be thrown asynchronously)
var errorCatchingHandle = on(window, 'error', function (error) {
dfd.reject(error);
});
// The error had been happening in a callback queued with setTimeout(0) in
// refresh(). Here we queue another which will run after that one to close
// out the test.
setTimeout(dfd.callback(function () {
errorCatchingHandle.remove();
}), 0);
});
});
});
|
DianaAssistant/DIANA | redemption/src/utils/traits/static_array_desc.hpp | /*
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 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 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., 675 Mass Ave, Cambridge, MA 02139, USA.
Product name: redemption, a FLOSS RDP proxy
Copyright (C) Wallix 2021
Author(s): Proxies Team
*/
#pragma once
#include "utils/sugar/bounded_sequence.hpp"
template<bool IsStatic, std::size_t Size>
struct static_array_desc
{
static const bool is_static = IsStatic;
static const std::size_t size = Size;
};
template<class Bounds>
using bounds_to_static_array_desc
= static_array_desc<Bounds::at_least == Bounds::at_most, Bounds::at_most>;
namespace detail
{
template<class T, class = void>
struct to_static_array_desc_impl
{
using type = static_array_desc<false, 0>;
};
template<class T>
struct to_static_array_desc_impl<T, std::void_t<
typename sequence_to_size_bounds_impl<T>::type
>>
{
using type = bounds_to_static_array_desc<typename sequence_to_size_bounds_impl<T>::type>;
};
} // namespace detail
template<class T>
using to_static_array_desc = typename detail::to_static_array_desc_impl<
std::remove_cv_t<std::remove_reference_t<T>>
>::type;
|
Iowa-Sate-Senior-Design-Dec-2021-Team-7/BBGreenZigbeeCape | firmware/daughterboard/tests/zed_temperaturesensor_CC1352R1_LAUNCHXL_tirtos_ccs/Common/zcl/zcl_port.c | <reponame>Iowa-Sate-Senior-Design-Dec-2021-Team-7/BBGreenZigbeeCape
/******************************************************************************
Filename: zcl_port.c
Revised: $Date: 2015-02-12 12:55:11 -0800 (Thu, 12 Feb 2015) $
Revision: $Revision: 42532 $
Description: This file contains the ZCL porting layer.
Copyright (c) 2019, Texas Instruments Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Texas Instruments Incorporated nor the names of
its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
/*********************************************************************
* INCLUDES
*/
#include <xdc/std.h>
#include <xdc/runtime/Error.h>
#include <xdc/runtime/System.h>
#include <ti/sysbios/BIOS.h>
#include <ti/sysbios/knl/Clock.h>
#include <ti/sysbios/knl/Semaphore.h>
#include <ti/drivers/Power.h>
#include <ti/drivers/power/PowerCC26XX.h>
#include <string.h>
#include <inc/hw_ints.h>
#include "zstackapi.h"
#include "zcl.h"
#include "zcl_general.h"
#include "zcl_port.h"
#include "bdb_reporting.h"
#include "rom_jt_154.h"
#include "zglobals.h"
#include "ti_zstack_config.h"
/*********************************************************************
* MACROS
*/
/*********************************************************************
* CONSTANTS
*/
#define EXT_ADDR_LEN 8
/*********************************************************************
* TYPEDEFS
*/
typedef struct
{
uint8_t entity;
endPointDesc_t *pEpDesc;
#if defined (ZCL_SCENES)
zclGeneral_Scene_t scene;
#endif
} zclPort_entityEPDesc_t;
#if defined (ZCL_SCENES)
// Scene NV types
typedef struct zclGenSceneNVItem
{
uint8_t endpoint;
zclGeneral_Scene_t scene;
}zclGenSceneNVItem_t;
#endif
typedef struct
{
void *next;
uint8_t endpoint;
zclport_pFnZclHandleExternal pfn;
} zclHandleExternalList_t;
/*********************************************************************
* GLOBAL VARIABLES
*/
/*********************************************************************
* EXTERNAL VARIABLES
*/
/*********************************************************************
* EXTERNAL FUNCTIONS
*/
/*********************************************************************
* LOCAL VARIABLES
*/
static NVINTF_nvFuncts_t *pfnZclPortNV = NULL;
#if defined (ZCL_SCENES)
static uint16_t zclSceneNVID = ZCL_PORT_SCENE_TABLE_NV_ID;
#endif
#if defined (ZCL_GROUPS)
static aps_Group_t foundGrp;
#endif
static zclPort_entityEPDesc_t entityEPDescs[MAX_SUPPORTED_ENDPOINTS] = {0};
static zstack_sysNwkInfoReadRsp_t nwkInfo =
{
0xFFFE,
{ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF },
zstack_DevState_HOLD,
0xFFFF,
{ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF },
0xFFFE,
{ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF },
{ 0, 0, 0 },
0
};
#if defined (ZCL_SCENES)
static uint8_t lastFindSceneEndpoint = 0xFF;
#endif
// Function pointer for applications to ZCL Handle External
static zclHandleExternalList_t *zclHandleExternalList = NULL;
/*********************************************************************
* LOCAL FUNCTIONS
*/
static void convertTxOptions(zstack_TransOptions_t *pOptions, uint8_t options);
endPointDesc_t *zcl_afFindEndPointDesc(uint8_t EndPoint);
uint8_t zclPortFindEntity(uint8_t EndPoint);
/*********************************************************************
* PUBLIC FUNCTIONS
*********************************************************************/
/*********************************************************************
* API Functions
*********************************************************************/
/**
* Register an AF Endpoint. This is needed by the ZCL code
* to find an AF endpoint descriptor.
*
* Public function defined in zcl_port.h
*/
bool zclport_registerEndpoint(uint8_t entity, endPointDesc_t *pEpDesc)
{
uint8_t x;
// Register endpoint that does not exist already
if( zcl_afFindEndPointDesc(pEpDesc->endPoint) == NULL )
{
for(x = 0; x < MAX_SUPPORTED_ENDPOINTS; x++)
{
if(entityEPDescs[x].pEpDesc == NULL)
{
zstack_afRegisterReq_t regReq = {0};
zstack_SimpleDescriptor_t simpleDesc;
// Save information to local table
entityEPDescs[x].entity = entity;
entityEPDescs[x].pEpDesc = pEpDesc;
// Register an endpoint with the stack thread
simpleDesc.endpoint = pEpDesc->endPoint;
simpleDesc.profileID = pEpDesc->simpleDesc->AppProfId;
simpleDesc.deviceID = pEpDesc->simpleDesc->AppDeviceId;
simpleDesc.deviceVer = pEpDesc->simpleDesc->AppDevVer;
simpleDesc.n_inputClusters = pEpDesc->simpleDesc->AppNumInClusters;
simpleDesc.pInputClusters = pEpDesc->simpleDesc->pAppInClusterList;
simpleDesc.n_outputClusters =
pEpDesc->simpleDesc->AppNumOutClusters;
simpleDesc.pOutputClusters =
pEpDesc->simpleDesc->pAppOutClusterList;
regReq.endpoint = pEpDesc->endPoint;
regReq.pSimpleDesc = &simpleDesc;
regReq.latencyReq = zstack_NetworkLatency_NO_LATENCY_REQS;
(void)Zstackapi_AfRegisterReq(entity, ®Req);
return(true);
}
}
}
return(false);
}
/**
* Call to register the functions pointers for the NV driver.
*
* Public function defined in zcl_port.h
*/
void zclport_registerNV(NVINTF_nvFuncts_t *pfnNV, uint16_t sceneNVID)
{
pfnZclPortNV = pfnNV;
#if defined (ZCL_SCENES)
zclSceneNVID = sceneNVID;
#endif
}
/**
* Call to register a function pointer to handle zcl_HandleExternal() messages.
*
* Public function defined in zcl_port.h
*/
bool zclport_registerZclHandleExternal( uint8_t endpoint, zclport_pFnZclHandleExternal pfn)
{
zclHandleExternalList_t *find = zclHandleExternalList;
zclHandleExternalList_t *tail = NULL;
if( zcl_afFindEndPointDesc(endpoint) != NULL )
{
// Find matching endpoint or tail
while( find != NULL )
{
if( find->endpoint == endpoint)
{
find->pfn = pfn;
return true;
}
if( find->next == NULL )
{
tail = find;
}
find = find->next;
}
// Add new item
zclHandleExternalList_t *newItem = zcl_mem_alloc( sizeof(zclHandleExternalList_t) );
if(newItem)
{
newItem->next = NULL;
newItem->endpoint = endpoint;
newItem->pfn = pfn;
if( zclHandleExternalList == NULL )
{
zclHandleExternalList = newItem;
}
else
{
tail->next = newItem;
}
return true;
}
}
return false;
}
/**
* Call to get Device Information.
*
* Public function defined in zcl_port.h
*/
zstack_sysNwkInfoReadRsp_t *zclport_getDeviceInfo(uint8_t entity)
{
Zstackapi_sysNwkInfoReadReq(entity, &nwkInfo);
return(&nwkInfo);
}
/**
* Determines if the device is already part of a network by asking the
* stack thread.
*
* Public function defined in zcl_port.h
*/
bool zclport_isAlreadyPartOfNetwork(uint8_t entity)
{
zstack_sysConfigReadReq_t readReq = {0};
zstack_sysConfigReadRsp_t readRsp = {0};
// Ask if the device is already part of a network
readReq.devPartOfNetwork = true;
(void)Zstackapi_sysConfigReadReq(entity, &readReq, &readRsp);
return(readRsp.devPartOfNetwork);
}
/**
* If the NV item does not already exist, it is created and
* initialized with the data passed to the function, if any.
*
* Public function defined in zcl_port.h
*/
uint8_t zclport_initializeNVItem(uint16_t id, uint16_t subId, uint16_t len,
void *buf)
{
if(pfnZclPortNV && pfnZclPortNV->createItem)
{
uint32_t nvLen = 0;
NVINTF_itemID_t nvId;
nvId.systemID = NVINTF_SYSID_APP;
nvId.itemID = (uint16_t)id;
nvId.subID = (uint16_t)subId;
if(pfnZclPortNV->getItemLen)
{
nvLen = pfnZclPortNV->getItemLen(nvId);
}
if(nvLen == len)
{
// Already exists and length is good
return(SUCCESS);
}
if(pfnZclPortNV->createItem(nvId, len, buf) == NVINTF_FAILURE)
{
// Operation failed
return(NV_OPER_FAILED);
}
}
// NV was created
return(NV_ITEM_UNINIT);
}
/**
* Write a data item to NV. Function can write an entire item to NV or
* an element of an item by indexing into the item with an offset.
*
* Public function defined in zcl_port.h
*/
uint8_t zclport_writeNV(uint16_t id, uint16_t subId,
uint16_t len,
void *buf)
{
uint8_t rtrn = SUCCESS;
if(pfnZclPortNV && pfnZclPortNV->writeItem)
{
uint32_t nvLen = 0;
NVINTF_itemID_t nvId;
nvId.systemID = NVINTF_SYSID_APP;
nvId.itemID = (uint16_t)id;
nvId.subID = (uint16_t)subId;
if(pfnZclPortNV->getItemLen)
{
nvLen = pfnZclPortNV->getItemLen(nvId);
}
if(nvLen > 0)
{
if(pfnZclPortNV->writeItem(nvId, len, buf)
== NVINTF_FAILURE)
{
rtrn = NV_OPER_FAILED;
}
}
else
{
rtrn = NV_ITEM_UNINIT;
}
}
return rtrn;
}
/**
* Read data from NV. This function can be used to read an entire item
* from NV or an element of an item by indexing into the item with an
* offset. Read data is copied into buf.
*
* Public function defined in zcl_port.h
*/
uint8_t zclport_readNV(uint16_t id, uint16_t subId, uint16_t ndx, uint16_t len,
void *buf)
{
uint8_t ret = SUCCESS;
if(pfnZclPortNV && pfnZclPortNV->readItem)
{
NVINTF_itemID_t nvId;
nvId.systemID = NVINTF_SYSID_APP;
nvId.itemID = (uint16_t)id;
nvId.subID = (uint16_t)subId;
if(pfnZclPortNV->readItem(nvId, ndx, len, buf) == NVINTF_FAILURE)
{
ret = NV_OPER_FAILED;
}
}
return(ret);
}
/********************************************************************
* @fn zclport_deleteNV
*
* @brief Delete item from NV. This function will fail if the length
* parameter does not match the length of the item in NV.
*
* @param id - Valid NV item Id.
* @param subId - Valid NV item sub Id.
* @param len - Length of item to delete.
*
* @return SUCCESS if item was deleted,
* NV_ITEM_UNINIT if item did not exist in NV,
* NV_BAD_ITEM_LEN if length parameter not correct,
* NV_OPER_FAILED if attempted deletion failed.
*/
uint8_t zclport_deleteNV(uint16_t id, uint16_t subId, uint16_t len)
{
uint8_t ret = SUCCESS;
if (pfnZclPortNV && pfnZclPortNV->deleteItem)
{
uint32_t nvLen = 0;
NVINTF_itemID_t nvId;
nvId.systemID = NVINTF_SYSID_APP;
nvId.itemID = (uint16_t)id;
nvId.subID = (uint16_t)subId;
if(pfnZclPortNV->getItemLen)
{
nvLen = pfnZclPortNV->getItemLen(nvId);
}
if(nvLen == 0)
{
ret = NV_ITEM_UNINIT;
}
else if(nvLen != len)
{
ret = NV_BAD_ITEM_LEN;
}
else if(pfnZclPortNV->deleteItem(nvId) == NVINTF_FAILURE)
{
ret = NV_OPER_FAILED;
}
}
return(ret);
}
/*********************************************************************
* @fn zcl_HandleExternal
*
* @brief Callback function to handle messages externally
*
* @param pInMsg - incoming message to process
*
* @return TRUE
*/
uint8_t zcl_HandleExternal(zclIncoming_t *pInMsg)
{
#ifdef BDB_REPORTING
zclIncomingMsg_t *pCmd;
pCmd = (zclIncomingMsg_t *)OsalPort_msgAllocate( sizeof ( zclIncomingMsg_t ) );
if ( pCmd != NULL )
{
// fill in the message
pCmd->hdr.event = ZCL_INCOMING_MSG;
pCmd->zclHdr = pInMsg->hdr;
pCmd->clusterId = pInMsg->msg->clusterId;
pCmd->srcAddr = pInMsg->msg->srcAddr;
pCmd->endPoint = pInMsg->msg->endPoint;
pCmd->attrCmd = pInMsg->attrCmd;
if(pCmd->zclHdr.commandID == ZCL_CMD_CONFIG_REPORT)
{
zstack_bdbProcessInConfigReportReq_t Req = {0};
Req.pZclIncommingMsg = pCmd;
Zstackapi_bdbProcessInConfigReportCmd(zclPortFindEntity(pCmd->endPoint),&Req);
OsalPort_msgDeallocate((uint8_t*)pCmd);
return TRUE;
}
if(pCmd->zclHdr.commandID == ZCL_CMD_READ_REPORT_CFG)
{
zstack_bdbProcessInReadReportCfgReq_t Req = {0};
Req.pZclIncommingMsg = pCmd;
Zstackapi_bdbProcessInReadReportCfgCmd(zclPortFindEntity(pCmd->endPoint),&Req);
OsalPort_msgDeallocate((uint8_t*)pCmd);
return TRUE;
}
OsalPort_msgDeallocate((uint8_t*)pCmd);
}
#endif
// Did the application register to handle this message
zclHandleExternalList_t *find = zclHandleExternalList;
while( find )
{
// Find matching endpoint with defined handle
if( ( find->endpoint == pInMsg->msg->endPoint ) && ( find->pfn ) )
{
// Let the application handle it
return(find->pfn(pInMsg));
}
find = find->next;
}
return(TRUE);
}
/*********************************************************************
* @fn zcl_mem_alloc
*
* @brief Abstraction function to allocate memory
*
* @param size - size in bytes needed
*
* @return pointer to allocated buffer, NULL if nothing allocated.
*/
void *zcl_mem_alloc(uint16_t size)
{
return( (void *)OsalPort_malloc(size) );
}
/*********************************************************************
* @fn zcl_memset
*
* @brief Abstract function to memset
*
* @param dest - buffer to set
* @param value - value to set into memory
* @param len - length to set in memory
*
* @return pointer to buffer after set
*/
void *zcl_memset(void *dest, uint8_t value, int len)
{
return( (void *)memset(dest, value, len) );
}
/*********************************************************************
* @fn zcl_memcpy
*
* @brief Generic memory copy.
*
* Note: This function differs from the standard OsalPort_memcpy(), since
* it returns the pointer to the next destination uint8_t. The
* standard OsalPort_memcpy() returns the original destination address.
*
* @param dst - pointer to destination memory
* @param src - pointer to source memory
* @param len - length to copy
*
* @return pointer to buffer after set
*/
void *zcl_memcpy(void *dst, void *src, unsigned int len)
{
uint8_t *pDst = dst;
uint8_t *pSrc = src;
while(len--)
{
*pDst++ = *pSrc++;
}
return(pDst);
}
/*********************************************************************
* @fn zcl_memcmp
*
* @brief
*
* Generic memory compare.
*
* * Note: This function differs from the standard memcmp(), since
* it returns the TRUE to when memory is the same and FALSE when
* the memory is different.
*
* @param src1 - source 1 address
* @param src2 - source 2 address
* @param len - number of bytes to compare
*
* @return TRUE - same, FALSE - different
*/
uint8_t zcl_memcmp(const void *src1, const void *src2, unsigned int len)
{
const uint8_t *pSrc1;
const uint8_t *pSrc2;
pSrc1 = src1;
pSrc2 = src2;
while ( len-- )
{
if( *pSrc1++ != *pSrc2++ )
return FALSE;
}
return TRUE;
}
/*********************************************************************
* @fn zcl_cpyExtAddr
*
* @brief Copy an extended address.
*
* @param dst - pointer to destination memory
* @param src - pointer to source memory
*
* @return pointer to buffer after set
*/
void *zcl_cpyExtAddr(uint8_t *pDest, const uint8_t *pSrc)
{
return zcl_memcpy( (void *)pDest, (void *)pSrc, EXT_ADDR_LEN );
}
/*********************************************************************
* @fn zcl_mem_free
*
* @brief Abstract function to free allocated memory
*
* @param ptr - pointer to allocated memory
*/
void zcl_mem_free(void *ptr)
{
if(ptr != NULL)
{
OsalPort_free(ptr);
}
}
/*********************************************************************
* @fn zcl_buffer_uint32
*
* @brief Abstract function to break a uin32 into a buffer
*
* @param buf - pointer to destination memory
* @param val - value to break
*
* @return pointer to buffer after set
*/
uint8_t *zcl_buffer_uint32(uint8_t *buf, uint32_t val)
{
*buf++ = BREAK_UINT32(val, 0);
*buf++ = BREAK_UINT32(val, 1);
*buf++ = BREAK_UINT32(val, 2);
*buf++ = BREAK_UINT32(val, 3);
return buf;
}
/*********************************************************************
* @fn zcl_build_uint32
*
* @brief Abstract function to build a uint32_t from an array of bytes
*
* @param swapped - array of bytes
* @param len - length of array
*
* @return uint32_t value
*/
uint32_t zcl_build_uint32(uint8_t *swapped, uint8_t len)
{
if(len == 2)
{
return( BUILD_UINT32(swapped[0], swapped[1], 0L, 0L) );
}
else if(len == 3)
{
return( BUILD_UINT32(swapped[0], swapped[1], swapped[2], 0L) );
}
else if(len == 4)
{
return( BUILD_UINT32(swapped[0], swapped[1], swapped[2], swapped[3]) );
}
else
{
return( (uint32_t)swapped[0] );
}
}
/*********************************************************************
* @fn zclPortFind
*
* @brief Find the endpoint descriptor from endpoint
*
* @param EndPoint - endpoint
*
* @return pointer to found endpoint descriptor, NULL if not found
*/
zclPort_entityEPDesc_t *zclPortFind(uint8_t EndPoint)
{
uint8_t x;
for(x = 0; x < MAX_SUPPORTED_ENDPOINTS; x++)
{
if( entityEPDescs[x].pEpDesc
&& (EndPoint == entityEPDescs[x].pEpDesc->endPoint) )
{
return(&entityEPDescs[x]);
}
}
return( (zclPort_entityEPDesc_t *)NULL );
}
/*********************************************************************
* @fn zclPortFindEntity
*
* @brief Find the Task ID from endpoint
*
* @param EndPoint - endpoint
*
* @return Task ID
*/
uint8_t zclPortFindEntity(uint8_t EndPoint)
{
uint8_t x;
for(x = 0; x < MAX_SUPPORTED_ENDPOINTS; x++)
{
if( (entityEPDescs[x].pEpDesc)
&& (EndPoint == entityEPDescs[x].pEpDesc->endPoint) )
{
return(entityEPDescs[x].entity);
}
}
return 0U;
}
/*********************************************************************
* @fn afFindEndPointDesc
*
* @brief Find the endpoint descriptor from endpoint
*
* @param EndPoint - endpoint
*
* @return pointer to found endpoint descriptor, NULL if not found
*/
endPointDesc_t *zcl_afFindEndPointDesc(uint8_t EndPoint)
{
uint8_t x;
for(x = 0; x < MAX_SUPPORTED_ENDPOINTS; x++)
{
if( (entityEPDescs[x].pEpDesc)
&& (EndPoint == entityEPDescs[x].pEpDesc->endPoint) )
{
return(entityEPDescs[x].pEpDesc);
}
}
return( (endPointDesc_t *)NULL );
}
/*********************************************************************
* @fn zcl_AF_DataRequest
*
* @brief Common functionality for invoking APSDE_DataReq() for both
* SendMulti and MSG-Send.
*
* NOTE: this is a conversion function
*
* input parameters
*
* @param *dstAddr - Full ZB destination address: Nwk Addr + End Point.
* @param *srcEP - Origination (i.e. respond to or ack to) End Point Descr.
* @param cID - A valid cluster ID as specified by the Profile.
* @param bufLen - Number of bytes of data pointed to by next param.
* @param *buf - A pointer to the data bytes to send.
* @param *transID - A pointer to a byte which can be modified and which will
* be used as the transaction sequence number of the msg.
* @param options - Valid bit mask of Tx options.
* @param radius - Normally set to AF_DEFAULT_RADIUS.
*
* output parameters
*
* @param *transID - Incremented by one if the return value is success.
*
* @return afStatus_t - See previous definition of afStatus_... types.
*/
afStatus_t zcl_AF_DataRequest(afAddrType_t *dstAddr, endPointDesc_t *srcEP,
uint16_t cID, uint16_t bufLen, uint8_t *buf,
uint8_t *transID, uint8_t options,
uint8_t radius)
{
afStatus_t status;
zstack_afDataReq_t req;
memset(&req, 0, sizeof(zstack_afDataReq_t));
req.dstAddr.addrMode = (zstack_AFAddrMode)dstAddr->addrMode;
if(req.dstAddr.addrMode == zstack_AFAddrMode_EXT)
{
OsalPort_memcpy(req.dstAddr.addr.extAddr, dstAddr->addr.extAddr, EXT_ADDR_LEN);
}
else if(req.dstAddr.addrMode != zstack_AFAddrMode_NONE)
{
req.dstAddr.addr.shortAddr = dstAddr->addr.shortAddr;
}
req.dstAddr.endpoint = dstAddr->endPoint;
req.dstAddr.panID = dstAddr->panId;
convertTxOptions(&(req.options), options);
req.srcEndpoint = srcEP->endPoint;
req.clusterID = cID;
req.transID = transID;
req.radius = radius;
req.n_payload = bufLen;
req.pPayload = buf;
status = Zstackapi_AfDataReq(zclPortFindEntity(srcEP->endPoint), &req);
return(status);
}
/******************************************************************************
* @fn convertTxOptions
*
* @brief Convert uint8_t txOptions into PB TransOptions data type
*
* @param pOptions - TransOptions pointer
* @param options - txOptions
*
* @return none
******************************************************************************/
static void convertTxOptions(zstack_TransOptions_t *pOptions, uint8_t options)
{
if(options & AF_WILDCARD_PROFILEID)
{
pOptions->wildcardProfileID = TRUE;
}
if(options & AF_ACK_REQUEST)
{
pOptions->ackRequest = TRUE;
}
if(options & AF_LIMIT_CONCENTRATOR)
{
pOptions->limitConcentrator = TRUE;
}
if(options & AF_SUPRESS_ROUTE_DISC_NETWORK)
{
pOptions->suppressRouteDisc = TRUE;
}
if(options & AF_EN_SECURITY)
{
pOptions->apsSecurity = TRUE;
}
if(options & AF_SKIP_ROUTING)
{
pOptions->skipRouting = TRUE;
}
}
#if defined (ZCL_GROUPS)
/*********************************************************************
* APS Interface messages
*********************************************************************/
/*********************************************************************
* @fn zclport_aps_RemoveGroup
*
* @brief Remove a group with endpoint and groupID
*
* @param endpoint -
* @param groupID - ID to look forw group
*
* @return TRUE if removed, FALSE if not found
*/
uint8_t zclport_aps_RemoveGroup(uint8_t endpoint, uint16_t groupID)
{
uint8_t status;
zstack_apsRemoveGroup_t req;
req.endpoint = endpoint;
req.groupID = groupID;
status = Zstackapi_ApsRemoveGroupReq(zclPortFindEntity(endpoint), &req);
return(status);
}
/*********************************************************************
* @fn zclport_aps_RemoveAllGroup
*
* @brief Remove a groups with an endpoint
*
* @param endpoint -
* @param groupID - ID to look for group
*
* @return none
*/
void zclport_aps_RemoveAllGroup(uint8_t endpoint)
{
zstack_apsRemoveAllGroups_t req;
req.endpoint = endpoint;
Zstackapi_ApsRemoveAllGroupsReq(zclPortFindEntity(endpoint), &req);
}
/*********************************************************************
* @fn zclport_aps_FindAllGroupsForEndpoint
*
* @brief Find all the groups with endpoint
*
* @param endpoint - endpoint to look for
* @param groupList - List to hold group IDs (should hold
* APS_MAX_GROUPS entries)
*
* @return number of groups copied to groupList
*/
uint8_t zclport_aps_FindAllGroupsForEndpoint(uint8_t endpoint, uint16_t *groupList)
{
zstack_apsFindAllGroupsReq_t req;
zstack_apsFindAllGroupsRsp_t rsp = {0};
req.endpoint = endpoint;
if( (groupList)
&& (Zstackapi_ApsFindAllGroupsReq(
zclPortFindEntity(endpoint),
&req, &rsp) == zstack_ZStatusValues_ZSuccess) )
{
uint8_t x;
for(x = 0; x < rsp.numGroups; x++)
{
groupList[x] = rsp.pGroupList[x];
}
if(rsp.pGroupList)
{
OsalPort_free(rsp.pGroupList);
}
}
return( (uint8_t)rsp.numGroups );
}
/*********************************************************************
* @fn zclport_aps_FindGroup
*
* @brief Find a group with endpoint and groupID
*
* @param endpoint -
* @param groupID - ID to look forw group
*
* @return a pointer to the group information, NULL if not found
*/
aps_Group_t *zclport_aps_FindGroup(uint8_t endpoint, uint16_t groupID)
{
aps_Group_t *pFound = (aps_Group_t *)NULL;
zstack_apsFindGroupReq_t req;
zstack_apsFindGroupRsp_t rsp;
req.endpoint = endpoint;
req.groupID = groupID;
if(Zstackapi_ApsFindGroupReq(zclPortFindEntity(endpoint),
&req, &rsp) == zstack_ZStatusValues_ZSuccess)
{
memset( &foundGrp, 0, sizeof(aps_Group_t) );
foundGrp.ID = rsp.groupID;
if(rsp.pName)
{
if(rsp.n_name <= APS_GROUP_NAME_LEN)
{
OsalPort_memcpy(foundGrp.name, rsp.pName, rsp.n_name);
}
OsalPort_free(rsp.pName);
}
pFound = &foundGrp;
}
return(pFound);
}
/*********************************************************************
* @fn zclport_aps_AddGroup
*
* @brief Add a group for an endpoint
*
* @param endpoint -
* @param group - new group
*
* @return ZStatus_t
*/
ZStatus_t zclport_aps_AddGroup(uint8_t endpoint, aps_Group_t *group)
{
uint8_t status = zstack_ZStatusValues_ZFailure;
zstack_apsAddGroup_t req;
memset( &req, 0, sizeof(zstack_apsAddGroup_t) );
req.endpoint = endpoint;
if(group)
{
uint8_t len;
req.groupID = group->ID;
len = strlen( (const char *)group->name );
if(len)
{
req.n_name = len;
req.pName = group->name;
}
status = Zstackapi_ApsAddGroupReq(zclPortFindEntity(endpoint), &req);
}
return(status);
}
/*********************************************************************
* @fn zclport_aps_CountAllGroups
*
* @brief Count the total number of groups
*
* @param none
*
* @return number of groups
*/
uint8_t zclport_aps_CountAllGroups(void)
{
// Slight cheat, don't know the endpoint - use first entity
return( Zstackapi_ApsCountAllGroupsReq(entityEPDescs[0].entity) );
}
#endif // defined(ZCL_GROUPS)
#if defined (ZCL_SCENES)
/*********************************************************************
* @fn sceneRecEmpty
*
* @brief Checks for an empty record
*
* @param pNvItem - pointer to scene NV record
*
* @return true if all bytes where 0xFF, false otherwise
*/
static bool sceneRecEmpty(zclGenSceneNVItem_t *pNvItem)
{
uint8_t *pBuf = (uint8_t *)pNvItem;
uint16_t x;
for(x = 0; x < sizeof(zclGenSceneNVItem_t); x++)
{
if(*pBuf++ != 0xFF)
{
return(false);
}
}
return(true);
}
/*********************************************************************
* @fn zclGeneral_ScenesInit
*
* @brief Initialize the Scenes Table
*/
void zclGeneral_ScenesInit(void)
{
uint16_t x;
zclGenSceneNVItem_t temp;
memset(&temp, 0xFF, sizeof(zclGenSceneNVItem_t));
for(x = 0; x < ZCL_GENERAL_MAX_SCENES; x++)
{
zclport_initializeNVItem(zclSceneNVID, x,
sizeof(zclGenSceneNVItem_t), &temp);
}
}
/*********************************************************************
* @fn zclGeneral_RemoveAllScenes
*
* @brief Remove all scenes for an endpoint and groupID
*
* @param endpoint - endpoint to filter with
* @param groupID - group ID looking for
*/
void zclGeneral_RemoveAllScenes(uint8_t endpoint, uint16_t groupID)
{
uint16_t x;
zclGenSceneNVItem_t nvItem;
for(x = 0; x < ZCL_GENERAL_MAX_SCENES; x++)
{
if(zclport_readNV(zclSceneNVID, x, 0,
sizeof(zclGenSceneNVItem_t), &nvItem) == SUCCESS)
{
if( (sceneRecEmpty(&nvItem) == false)
&& ( (nvItem.endpoint == endpoint) || (endpoint == 0xFF) )
&& (nvItem.scene.groupID == groupID) )
{
// Remove the item by setting it all to 0xFF
memset( &nvItem, 0xFF, sizeof(zclGenSceneNVItem_t) );
zclport_writeNV(zclSceneNVID, x,
sizeof(zclGenSceneNVItem_t), &nvItem);
}
}
}
}
/*********************************************************************
* @fn zclGeneral_RemoveScene
*
* @brief Remove a scene
*
* @param endpoint - endpoint to filter with
* @param groupID - group ID looking for
* @param sceneID - scene ID
*
* @return TRUE if removed, FALSE if not found
*/
uint8_t zclGeneral_RemoveScene(uint8_t endpoint, uint16_t groupID, uint8_t sceneID)
{
uint16_t x;
zclGenSceneNVItem_t nvItem;
for(x = 0; x < ZCL_GENERAL_MAX_SCENES; x++)
{
if(zclport_readNV(zclSceneNVID, x, 0,
sizeof(zclGenSceneNVItem_t), &nvItem) == SUCCESS)
{
if( (sceneRecEmpty(&nvItem) == false)
&& ( (nvItem.endpoint == endpoint) || (endpoint == 0xFF) )
&& (nvItem.scene.groupID == groupID)
&& (nvItem.scene.ID == sceneID) )
{
// Remove the item by setting it all to 0xFF
memset( &nvItem, 0xFF, sizeof(zclGenSceneNVItem_t) );
if(zclport_writeNV(zclSceneNVID, x,
sizeof(zclGenSceneNVItem_t),
&nvItem) == SUCCESS)
{
return(TRUE);
}
else
{
return(FALSE);
}
}
}
}
return(FALSE);
}
/*********************************************************************
* @fn zclGeneral_FindScene
*
* @brief Find a scene with endpoint and sceneID
*
* @param endpoint - endpoint filter to find scene
* @param groupID - what group the scene belongs to
* @param sceneID - ID to look for scene
*
* @return a pointer to the scene information, NULL if not found
*/
zclGeneral_Scene_t *zclGeneral_FindScene(uint8_t endpoint, uint16_t groupID,
uint8_t sceneID)
{
uint16_t x;
zclGenSceneNVItem_t nvItem;
zclPort_entityEPDesc_t *pEPDesc = zclPortFind(endpoint);
if(pEPDesc != NULL)
{
for(x = 0; x < ZCL_GENERAL_MAX_SCENES; x++)
{
if(zclport_readNV(zclSceneNVID, x, 0,
sizeof(zclGenSceneNVItem_t),
&nvItem) == SUCCESS)
{
if( (sceneRecEmpty(&nvItem) == false)
&& ( (nvItem.endpoint == endpoint) || (endpoint == 0xFF) )
&& (nvItem.scene.groupID == groupID)
&& (nvItem.scene.ID == sceneID) )
{
lastFindSceneEndpoint = endpoint;
// Copy to a temp area
OsalPort_memcpy( &(pEPDesc->scene), &(nvItem.scene),
sizeof(zclGeneral_Scene_t) );
return( &(pEPDesc->scene) );
}
}
}
}
return( (zclGeneral_Scene_t *)NULL );
}
/*********************************************************************
* @fn zclGeneral_AddScene
*
* @brief Add a scene for an endpoint
*
* @param endpoint -
* @param scene - new scene item
*
* @return ZStatus_t
*/
ZStatus_t zclGeneral_AddScene(uint8_t endpoint, zclGeneral_Scene_t *scene)
{
uint16_t x;
zclGenSceneNVItem_t nvItem;
// See if the item exists already
for(x = 0; x < ZCL_GENERAL_MAX_SCENES; x++)
{
if(zclport_readNV(zclSceneNVID, x, 0,
sizeof(zclGenSceneNVItem_t), &nvItem) == SUCCESS)
{
if( (sceneRecEmpty(&nvItem) == false)
&& (nvItem.endpoint == endpoint)
&& (nvItem.scene.groupID == scene->groupID)
&& (nvItem.scene.ID == scene->ID) )
{
break;
}
}
}
// Find an empty slot
if(x == ZCL_GENERAL_MAX_SCENES)
{
for(x = 0; x < ZCL_GENERAL_MAX_SCENES; x++)
{
if(zclport_readNV(zclSceneNVID, x, 0,
sizeof(zclGenSceneNVItem_t),
&nvItem) == SUCCESS)
{
if( sceneRecEmpty(&nvItem) )
{
break;
}
}
}
}
if(x == ZCL_GENERAL_MAX_SCENES)
{
return(ZFailure);
}
// Item found or empty slot found
nvItem.endpoint = endpoint;
OsalPort_memcpy( &(nvItem.scene), scene, sizeof(zclGeneral_Scene_t) );
if(zclport_writeNV(zclSceneNVID, x,
sizeof(zclGenSceneNVItem_t), &nvItem) == SUCCESS)
{
return(ZSuccess);
}
else
{
return(ZFailure);
}
}
/*********************************************************************
* @fn zclGeneral_CountAllScenes
*
* @brief Count the number of scenes
*
* @return number of scenes found
*/
uint8_t zclGeneral_CountAllScenes(void)
{
uint16_t x;
zclGenSceneNVItem_t nvItem;
uint8_t cnt = 0;
for(x = 0; x < ZCL_GENERAL_MAX_SCENES; x++)
{
if(zclport_readNV(zclSceneNVID, x, 0,
sizeof(zclGenSceneNVItem_t), &nvItem) == SUCCESS)
{
if(sceneRecEmpty(&nvItem) == false)
{
cnt++;
}
}
}
return(cnt);
}
/*********************************************************************
* @fn zclGeneral_FindAllScenesForGroup
*
* @brief Get all the scenes with groupID
*
* @param endpoint - endpoint to filter with
* @param groupID - group ID looking for
*
* @return number of scenes found
*/
uint8_t zclGeneral_FindAllScenesForGroup(uint8_t endpoint, uint16_t groupID,
uint8_t *sceneList)
{
uint16_t x;
zclGenSceneNVItem_t nvItem;
uint8_t cnt = 0;
for(x = 0; x < ZCL_GENERAL_MAX_SCENES; x++)
{
if(zclport_readNV(zclSceneNVID, x, 0,
sizeof(zclGenSceneNVItem_t), &nvItem) == SUCCESS)
{
if( (sceneRecEmpty(&nvItem) == false)
&& (nvItem.endpoint == endpoint) &&
(nvItem.scene.groupID == groupID) )
{
sceneList[cnt++] = nvItem.scene.ID;
}
}
}
return(cnt);
}
/*********************************************************************
* @fn zclGeneral_ScenesSave
*
* @brief Save the Scenes Table - Something has changed.
* This function is only called if zclGeneral_FindScene()
* was called and the found information was changed.
*/
void zclGeneral_ScenesSave(void)
{
if(lastFindSceneEndpoint != 0xFF)
{
zclPort_entityEPDesc_t *pEPDesc = zclPortFind(lastFindSceneEndpoint);
if(pEPDesc)
{
zclGeneral_AddScene( lastFindSceneEndpoint, &(pEPDesc->scene) );
lastFindSceneEndpoint = 0xFF;
}
}
}
#endif // ZCL_SCENES
/*********************************************************************
*********************************************************************/
|
FuzzyAshton/APCS | src/unit7/Day1.java | package unit7;
public class Day1 {
public static void main(String[] args) {
int[][] arr1 = new int[3][4];
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr1[i].length; j++) {
arr1[i][j] = i + j;
System.out.print(arr1[i][j] + " ");
}
System.out.println();
}
}
}
|
ibadsiddiqui/FYP-Automation | client/src/views/Pages/Register/Register.js | <gh_stars>0
import React, { Component } from 'react';
import { Link } from 'react-router-dom'
import { Button, Card, CardBody, CardFooter, Col, Container, Form, Input, InputGroup, InputGroupAddon, InputGroupText, Row } from 'reactstrap';
class Register extends Component {
constructor(props) {
super(props);
this.onRegister = this.onRegister.bind(this)
this.state = {
name: '',
email: '',
accepted: false,
status: '',
username: '',
password: '',
profession: '',
professionValid: null,
confirmPassword: null,
hasUserBeenRegistered: false,
doesUserNameExist: false,
isEmailValid: null,
isPasswordValid: null,
};
}
async setProfession(event) {
await this.setState({
profession: event.target.value
})
if (this.state.profession === "student" || this.state.profession === "Student"
|| this.state.profession === "Teacher" || this.state.profession === "teacher") {
this.setState({
professionValid: true
})
} else if (this.state.profession.length === 0) {
this.setState({
profession: null
})
}
else {
this.setState({
professionValid: false
})
}
}
setName(event) {
this.setState({
name: event.target.value
})
}
setEmail(event) {
if (/^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@(([0-9a-zA-Z])+([-\w]*[0-9a-zA-Z])*\.)+[a-zA-Z]{2,9})$/.test(event.target.value)) {
this.setState({
email: event.target.value,
isEmailValid: true
})
} else {
this.setState({
email: event.target.value,
isEmailValid: false
})
}
}
setPassword(event) {
// var passwordRegex = event.target.value.replace(/^((?=(.*[A-Z]){1})(?=(.*[0-9]){1})(?=.*[a-zA-Z0-9])).{8,}$/, '');
if (/^((?=(.*[A-Z]){1})(?=(.*[0-9]){1})(?=.*[a-zA-Z0-9])).{8,}$/.test(event.target.value)) {
this.setState({
password: event.target.value,
isPasswordValid: true
})
} else {
this.setState({
password: event.target.value,
isPasswordValid: false,
})
}
}
checkPassword(event) {
if (this.state.password === event.target.value) {
this.setState({
confirmPassword: true
})
} else {
this.setState({
confirmPassword: false
})
}
}
checkEligibility() {
if (this.state.profession.toLowerCase() !== "teacher" && this.state.username !== "")
fetch('/checkElgibilityStatus', {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
},
body: JSON.stringify({
cms_id: this.state.username,
}),
}).then(res => res.json())
.then(res => {
if (res.hasOwnProperty("accepted") === true) {
if (res.accepted === true && res.status === 'accepted') {
this.setState({
accepted: true,
status: "accepted"
})
} else {
this.setState({
accepted: false,
status: "rejected"
})
}
} else {
this.setState({
status: "pending"
})
}
})
}
setUsername(event) {
this.setState({
username: event.target.value
});
if (event.target.value.toLowerCase() !== "teacher")
fetch('/getusername', {
method: "POST", // *GET, POST, PUT, DELETE, etc.
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
},
body: JSON.stringify({
username: event.target.value,
}),
})
.then(async res => await res.json())
.then(res => this.setState({
doesUserNameExist: res.response
}))
}
onRegister() {
fetch('/register', {
method: "POST", // *GET, POST, PUT, DELETE, etc.
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
},
body: JSON.stringify({
name: this.state.name.toLowerCase(),
email: this.state.email.toLowerCase(),
username: this.state.username,
password: <PASSWORD>,
profession: this.state.profession.toLowerCase()
}),
}).then(res => res.json())
.then(res => this.setState({
hasUserBeenRegistered: res.registration
}))
.catch(err => console.log(err));
alert('Registration Successful. Now you can login.')
}
componentWillUnmount() {
this.setState({
...null
})
}
render() {
return (
<div className="app flex-row align-items-center">
<Container>
<Row className="justify-content-center">
<Col md="6">
<Card className="mx-4">
<CardBody className="p-4">
<Form>
<h1>Register</h1>
<p className="text-muted">Create your account</p>
{
this.state.doesUserNameExist === true
&&
<div className="alert alert-danger text-center">
<strong>Sorry!</strong> This username already exist.
</div>
}
{
this.state.professionValid === false
&&
<div className="alert alert-danger text-center">
<strong>Sorry!</strong> Profession can only be between Teacher and Student
</div>
}
{
this.state.isEmailValid === false
&&
<div className="alert alert-danger text-center">
<strong>Sorry!</strong> Please Enter Correct Email.
</div>
}
{
this.state.isPasswordValid === false
&&
<div className="alert alert-danger text-center">
<strong>Sorry!</strong> Please enter a password of 8-letters. It should have first 1 capital letter, then numbers and characters .
</div>
}
{
this.state.confirmPassword === false
&&
<div className="alert alert-danger text-center">
<strong>Sorry!</strong> Password does not match.
</div>
}
{
this.state.status === 'rejected'
&&
<div className="alert alert-danger text-center">
<strong>Sorry!</strong> You need to submit your eligibility form again.
</div>
}
{
this.state.status === 'pending'
&&
<div className="alert alert-warning text-center">
<strong>Wait!</strong> While the admin confirms your eligibility.
</div>
}
<InputGroup className="mb-3">
<InputGroupAddon addonType="prepend">
<InputGroupText>
<i className="icon-user"></i>
</InputGroupText>
</InputGroupAddon>
<Input type="text"
placeholder="Enter Your Full Name"
required="required"
autoFocus="autofocus"
value={this.state.name}
onChange={(event) => this.setName(event)}
/>
</InputGroup>
<InputGroup className="mb-3">
<InputGroupAddon addonType="prepend">
<InputGroupText>
<i className="icon-user"></i>
</InputGroupText>
</InputGroupAddon>
<Input type="text"
placeholder="Enter Your Profession | Student | Teacher "
required="required"
autoFocus="autofocus"
value={this.state.profession}
onChange={(event) => this.setProfession(event)}
/>
</InputGroup>
<InputGroup className="mb-3">
<InputGroupAddon addonType="prepend">
<InputGroupText>
<i className="icon-user"></i>
</InputGroupText>
</InputGroupAddon>
<Input type="text"
placeholder="Username - Your CMS-ID"
required="required"
value={this.state.username}
onChange={(event) => this.setUsername(event)} autoComplete="username"
onBlur={(event) => this.checkEligibility()}
/>
</InputGroup>
<InputGroup className="mb-3">
<InputGroupAddon addonType="prepend">
<InputGroupText>@</InputGroupText>
</InputGroupAddon>
<Input type="text"
placeholder="Email address"
required="required"
value={this.state.email}
onChange={(event) => this.setEmail(event)} autoComplete="email"
/>
</InputGroup>
<InputGroup className="mb-3">
<InputGroupAddon addonType="prepend">
<InputGroupText>
<i className="icon-lock"></i>
</InputGroupText>
</InputGroupAddon>
<Input type="password"
placeholder="Password"
required="required"
value={this.state.password}
onChange={(event) => this.setPassword(event)}
/>
</InputGroup>
<InputGroup className="mb-4">
<InputGroupAddon addonType="prepend">
<InputGroupText>
<i className="icon-lock"></i>
</InputGroupText>
</InputGroupAddon>
<Input type="password"
placeholder="Confirm password"
required="required"
onChange={(event) => this.checkPassword(event)} autoComplete="new-password"
/>
</InputGroup>
{
this.state.isEmailValid === true
&& this.state.doesUserNameExist === false
&& this.state.username !== ''
&& this.state.isPasswordValid === true
&& this.state.confirmPassword === true
&& !this.state.doesUserNameExist
&& (this.state.status === 'accepted' || this.state.profession.toLowerCase() === "teacher")
&&
<Link to="/login">
<Button color="success" block onClick={this.onRegister}>Create Account</Button>
</Link>
}
</Form>
</CardBody>
<CardFooter className="p-4">
<Row>
<Col xs="12" sm="12">
<Link to="/login">
<Button className="btn-facebook" block><span>Already have an account? Click here.</span></Button>
</Link>
</Col>
</Row>
</CardFooter>
</Card>
</Col>
</Row>
</Container>
</div>
);
}
}
export default Register; |
HarisAli-git/DinnerDashROR | db/migrate/20210828130151_change_status_of_orders.rb | # frozen_string_literal: true
class ChangeStatusOfOrders < ActiveRecord::Migration[6.1]
def change
change_column :orders, :status, :integer
end
end
|
mwitkow/kfe | pkg/kedge/http/integration.go | package http_integration
/** Go doesn't allow you to have a single package with a test without a test. */
|
gchure/phd | presentation/code/slide09_induction_plots.py | <reponame>gchure/phd
#%%
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import pickle
import phd.viz
import phd.thermo
colors, palette = phd.viz.phd_style()
constants = phd.thermo.load_constants()
# Define the identifiers
SLIDE = 9
FIT_DATA = True
FIT_CURVE = True
ALL_PREDICTIONS = True
ALL_DATA = True
# Load the induction paper dataset
data = pd.read_csv('../../src/data/ch2_induction/RazoMejia_2018.csv', comment='#')
data['repressors'] *= 2
data = data[data['repressors'] > 0]
data = data.groupby(['repressors', 'operator',
'IPTG_uM'])['fold_change_A'].agg(('mean', 'sem')).reset_index()
# Load the sampling information
with open('../../src/data/ch2_induction/mcmc/main_text_KaKi.pkl', 'rb') as file:
unpickler = pickle.Unpickler(file)
gauss_flatchain = unpickler.load()
ka_fc = np.exp(-gauss_flatchain[:, 0])[::100]
ki_fc = np.exp(-gauss_flatchain[:, 1])[::100]
# Set up the figure canvas.
fig, ax = plt.subplots(1, 3, figsize=(7, 2), sharex=True, sharey=True)
for a in ax:
phd.viz.despine(a)
a.set_xscale('log')
a.set_xlim([1E-2, 1E4])
a.set_ylim([-0.05, 1.15])
# Define the colors
rep_colors = {22: colors['red'],
60: colors['brown'],
124: colors['green'],
260: colors['orange'],
1220: colors['purple'],
1740: colors['blue']}
# Define the axes
axes = {'O1':ax[0], 'O2':ax[1], 'O3':ax[2]}
# Add labels as necessary
for i, a in enumerate(ax):
phd.viz.titlebox(a, f'operator O{i+1}', color=colors['black'], size=6)
a.set_xlabel('IPTG [µM]')
ax[0].set_ylabel('fold-change')
# plot the data and curves if desired
for g, d in data.groupby(['operator', 'repressors']):
if (g[0] == 'O2') & (g[1] == 260):
face = colors['grey']
edge = rep_colors[g[1]]
_ = axes[g[0]].errorbar(d['IPTG_uM'], d['mean'], d['sem'], fmt='o',
linestyle='none', color=rep_colors[g[1]],
markeredgecolor=edge, markerfacecolor=face,
markeredgewidth=0.75, ms=3, label=int(g[1]))
else:
face = rep_colors[g[1]]
edge = colors['grey']
if ALL_DATA:
_ = axes[g[0]].errorbar(d['IPTG_uM'], d['mean'], d['sem'], fmt='o',
linestyle='none', color=rep_colors[g[1]],
markeredgecolor=edge, markerfacecolor=face,
markeredgewidth=0.75, ms=4, label='__nolegend__')
# Plot curves as necessary
c_range = np.logspace(-2, 4, 200)
if (FIT_CURVE != False) | (ALL_PREDICTIONS != False):
for g, d in data.groupby(['operator', 'repressors']):
cred_region = np.zeros((2, len(c_range)))
for i, c in enumerate(c_range):
arch = phd.thermo.SimpleRepression(g[1], ep_r=constants[g[0]],
ka=ka_fc, ki=ki_fc,
ep_ai=constants['ep_AI'],
effector_conc=c).fold_change()
cred_region[:, i] = phd.stats.compute_hpd(arch, 0.95)
if (g[0] == 'O2') & (g[1] == 260) & (FIT_CURVE != False):
axes[g[0]].fill_between(c_range, cred_region[0, :], cred_region[1, :],
color=rep_colors[g[1]], alpha=0.5, label=int(g[1]))
elif ALL_PREDICTIONS == True:
axes[g[0]].fill_between(c_range, cred_region[0, :], cred_region[1, :],
color=rep_colors[g[1]], alpha=0.5, label=int(g[1]))
leg = ax[1].legend(title='repressors')
leg.get_title().set_fontsize(6)
name = ''
if (FIT_DATA == True):
name += 'fitdata_'
if (FIT_CURVE == True):
name += 'fitcurve_'
if (ALL_PREDICTIONS==True):
name += 'allcurve_'
if (ALL_DATA == True):
name += 'alldata_'
plt.savefig(f'../figs/slide_{SLIDE}_induction_{name}.pdf', bbox_inches='tight')
# %%
# %%
|
alexgithubber/XLE-Another-Fork | ColladaConversion/OpenCollada/OCMisc.h | <filename>ColladaConversion/OpenCollada/OCMisc.h
// Copyright 2015 XLGAMES Inc.
//
// Distributed under the MIT License (See
// accompanying file "LICENSE" or the website
// http://www.opensource.org/licenses/mit-license.php)
#pragma once
#include "../ConversionCore.h"
#include "../../Math/Matrix.h"
#include "../../Math/Vector.h"
#include "../../RenderCore/Assets/RawAnimationCurve.h"
namespace COLLADABU
{
namespace Math { class Matrix4; class Vector3; }
}
namespace COLLADAFW { class Animation; class UniqueId; class Image; class SkinControllerData; }
namespace RenderCore { namespace Assets { class RawAnimationCurve; } }
namespace RenderCore { namespace Assets { using AnimationParameterId = uint32; }}
namespace RenderCore { namespace ColladaConversion
{
class ReferencedTexture;
class ReferencedMaterial;
class UnboundSkinController;
Float4x4 AsFloat4x4 (const COLLADABU::Math::Matrix4& matrix);
Float3 AsFloat3 (const COLLADABU::Math::Vector3& vector);
Assets::RawAnimationCurve Convert(const COLLADAFW::Animation& animation);
ObjectGuid Convert(const COLLADAFW::UniqueId& input);
ReferencedTexture Convert(const COLLADAFW::Image* image);
UnboundSkinController Convert(const COLLADAFW::SkinControllerData* input);
Assets::AnimationParameterId BuildAnimParameterId(const COLLADAFW::UniqueId& input);
}}
|
Rachel4858/Algorithm | leetcode/amazon/linkedList/2-MergeTwoSortedLists.js | // Input: 1->2->4, 1->3->4
// Output: 1->1->2->3->4->4
function solution(l1, l2) {
let head = new ListNode(1);
let dummy = head;
while (l1 !== null && l2 !== null) {
if (l1.val <= l2.val) {
dummy.next = l1;
l1 = l1.next;
} else {
dummy.next = l2;
l2 = l2.next;
}
dummy = dummy.next;
}
dummy.next = l1 ? l1 : l2;
return head.next;
}
|
rlwhitcomb/utilities | java/info/rlwhitcomb/tester/Tester.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2012-2021 <NAME>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Unit test engine.
*
* History:
* 29-Aug-2012 (rlwhitcomb)
* Created.
* 30-Aug-2012 (rlwhitcomb)
* Allow comments in the test description file;
* report the number of tests and the composite results.
* 16-Oct-2012 (rlwhitcomb)
* Add a proper diff output when the results don't compare.
* 30-Oct-2012 (rlwhitcomb)
* Add initialization of text resources.
* 01-Nov-2012 (rlwhitcomb)
* And more text resources.
* 13-Nov-2012 (rlwhitcomb)
* Send test class the private "-echo:true" flag so
* the input is echoed to the output (to make the
* canons more readable).
* 15-Nov-2012 (rlwhitcomb)
* Allow blank lines in the test description file, and
* C++ style line comments.
* 15-Nov-2012 (rlwhitcomb)
* Add "-log" option to at least print the test names.
* 20-Dec-2012 (rlwhitcomb)
* Add "-time" option to print test timing also.
* 10-Jan-2013 (rlwhitcomb)
* Add options to use different canon lines for
* different platforms and different versions.
* 22-Feb-2013 (rlwhitcomb)
* New feature: $echo to annotate the test result log.
* 16-May-2013 (rlwhitcomb)
* Fix the regexp for description line so the canon charset
* works correctly (one extra group to not include the comma).
* 28-Jun-2013 (rlwhitcomb)
* Use new automatic method to initialize the package resources.
* 21-Jan-2014 (rlwhitcomb)
* Default to ".canon" extension for the canon files. Add "$inputDir"
* directive to default the canon file directory. Move error message
* text to the resource file.
* 04-Mar-2014 (rlwhitcomb)
* Add option to specify an arbitrary class name instead of the default
* to support other types of tests that basically need a command line,
* output canons, and diffs.
* 12-Mar-2014 (rlwhitcomb)
* Allow "-" in canon file names.
* 18-Apr-2014 (rlwhitcomb)
* Expand the version checks to allow a range of version or the major[.minor]+
* syntax.
* 19-Jun-2014 (rlwhitcomb)
* Allow a "$scriptDir" directive in the test description file and send that
* to test class as a "-d dir" parameter. Tidy up the final result message.
* 08-Sep-2014 (rlwhitcomb)
* Set the flag saying this is a desktop application.
* 13-Oct-2014 (rlwhitcomb)
* As a result of using -D for defining variables on the command line, we have
* to use "-dir" now for specifying the default script directory.
* 12-Mar-2015 (rlwhitcomb)
* Use new FileUtilities method for generating temp files.
* 24-Mar-2015 (rlwhitcomb)
* Change the way we add the "-echo:true" parameter to the command line so the new
* "-exec" flag can safely eat the remainder of the command line
* without getting this extra string.
* 24-Apr-2015 (rlwhitcomb)
* Trap any exceptions loading/unloading the instance to determine the version.
* 27-Apr-2015 (rlwhitcomb)
* Make that any Throwables (the real problems are class loading issues not derived
* from Exception).
* 31-Aug-2015 (rlwhitcomb)
* Javadoc cleanup (found by Java 8).
* 06-Jan-2016 (rlwhitcomb)
* More of the same. Use try-with-resources in some places.
* 09-Aug-2016 (rlwhitcomb)
* We need to allow an empty command line (that is the tests can be run by
* just invoking the class with no arguments). Changed for use with TestSqlFormatter.
* 11-Aug-2016 (rlwhitcomb)
* Print an "underline" at the end of the results to separate tests in the nightly build.
* Display the test name inside a starting banner also.
* 23-Aug-2016 (rlwhitcomb)
* Add an option to display help.
* 30-Sep-2016 (rlwhitcomb)
* Need to be able to switch canon lines based on the charset.
* 11-Oct-2016 (rlwhitcomb)
* Use the Options class for command line argument processing.
* 11-Oct-2016 (rlwhitcomb)
* Refactor to support "$include" processing. Make a recursive procedure that can be
* called at any level for one description file. Add processing for the directive.
* 03-Nov-2016 (rlwhitcomb)
* Add code to generate canons instead of comparing them. Use common code in FileUtilities
* to read the file in as a single string.
* 27-Dec-2016 (rlwhitcomb)
* Allow "!" and "//" also as comment indicators (in addition to "#") in canon files.
* 07-Feb-2017 (rlwhitcomb)
* For convenience in creating new test canons, allow lines that don't begin with any
* of the regular prefixes to be counted as output lines (the most common case). This way
* the canon could be created simply by capturing the valid output with no postprocessing
* (most of the time).
* 28-Feb-2017 (rlwhitcomb)
* Add metadata to a test desription to allow a successful result even if the test itself
* exits unsuccessfully (in other words, "success" means the program exited abnormally).
* 28-Feb-2017 (rlwhitcomb)
* Update the last change by allowing whitespace around the exit code metadata.
* 13-Jun-2017 (rlwhitcomb)
* Make explicit checks in "driveOneTest" for file existence, etc. instead of relying
* on an IOException to tell us the file doesn't exist or is not readable, etc.
* 28-Jul-2017 (rlwhitcomb)
* As part of cleanup for users of the Intl class, move the default
* package resource initialization into Intl itself, so all the callers
* don't have to do it.
* 31-May-2018 (rlwhitcomb)
* Implement "{^platform}" checks as well.
* 14-Feb-2019 (rlwhitcomb)
* Incidental to some new tests, fix case where "{}" in test file outputs empty line to canon.
* 15-Mar-2019 (rlwhitcomb)
* Don't use FileInputStream/FileOutputStream due to GC problems b/c of the finalize
* method in these classes. Had to rename our internal "Files" class to avoid conflict with
* the system class of that name.
* 06-May-2019 (rlwhitcomb)
* Add "$file", "$endfile" and "$delete" statements to create / delete script files for use.
* Allow (and strip) double quotes around argument(s) of internal commands (to allow leading/
* trailing blanks if desired).
* 21-May-2019 (rlwhitcomb)
* Implement "-version" command.
* 10-Jul-2019 (rlwhitcomb)
* Add the Java version / bitness to the "-version" output. Move those strings out to
* the intl resources.
* 11-Jul-2019 (rlwhitcomb)
* Set the product name, and then display that with "-version".
* 07-Aug-2019 (rlwhitcomb)
* Support "-locale" option, which doesn't help a lot, but does test the Japanese resource files.
* Fix parsing of "-log" option.
* 06-Jan-2020 (rlwhitcomb)
* Add copyright notice.
* 13-Feb-2020 (rlwhitcomb)
* Move locale parsing to CharUtil; move message to util resources.
* 25-Mar-2020 (rlwhitcomb)
* Add a new command-line option AND a new config file option to fail on the first error.
* 31-Mar-2020 (rlwhitcomb)
* Tweak the underlines in the output.
* 20-Nov-2020 (rlwhitcomb)
* Prepare for GitHub.
* 18-Jan-2021 (rlwhitcomb)
* Add a directive for default options; work nicely with the new Testable interface.
* 23-Jan-2021 (rlwhitcomb)
* Fix obsolete HTML constructs in Javadoc. Add aliases for a couple of the directives.
* Switch description comments to include "--" and use "!" as an alias for commands.
* 25-Jan-2021 (rlwhitcomb)
* Add "-inputDir" command line option; use that to find input scripts (defaultScriptDir).
* Switch to Environment.printProgramInfo.
* 29-Jan-2021 (rlwhitcomb)
* Move standard platform code to Environment; one other code tweak.
* 11-Feb-2021 (rlwhitcomb)
* Get version from test class so version checks work; refactor MajorMinor to Version.
* 18-Feb-2021 (rlwhitcomb)
* Allow spaces before colon in test description lines.
* 24-Feb-2021 (rlwhitcomb)
* Allow directives in test description files to start with ":" in addition to "$" or "!".
* 24-Feb-2021 (rlwhitcomb)
* Tweak some of the initial error messages. Make some errors in the description file fatal
* to abort the whole process.
* 02-Mar-2021 (rlwhitcomb)
* Another error for empty "-dir:" (which I seem to do often b/c of the different syntax here).
* 15-Mar-2021 (rlwhitcomb)
* Actually return a failure exit code if any tests fail.
* 13-Jul-2021 (rlwhitcomb)
* Add "-testclass" option to the command line.
* 21-Oct-2021 (rlwhitcomb)
* Use new method in Intl to get/test the locale value.
* #36: Implement TESTER_OPTIONS from the environment. Make all function parameters final.
* 20-Nov-2021 (rlwhitcomb)
* #97: Implement charset for each description file.
* 01-Dec-2021 (rlwhitcomb)
* #119: Allow default canon charset in description file.
*/
package info.rlwhitcomb.tester;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.MalformedURLException;
import java.net.URLClassLoader;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import name.fraser.neil.plaintext.diff_match_patch;
import info.rlwhitcomb.Testable;
import info.rlwhitcomb.util.CharUtil;
import info.rlwhitcomb.util.EchoInputStream;
import info.rlwhitcomb.util.Environment;
import info.rlwhitcomb.util.ExceptionUtil;
import info.rlwhitcomb.util.FileUtilities;
import info.rlwhitcomb.util.Intl;
import info.rlwhitcomb.util.Options;
/**
* Unit test framework.
* <p> Reads a test description file that consists of multiple
* lines, each corresponding to one test. Each line contains
* the name of a canon file (with optional character set)
* and a command line for the test class.
* <p> There is a command line option to specify the test class
* name, or it can be supplied (before any tests) in the test
* description file, and different test classes can be specified
* this way.
*/
public class Tester
implements Testable
{
private static final Pattern DESCRIPTION = Pattern.compile("^(\\s*\\{\\s*(\\d+)\\s*\\}\\s*)?([a-zA-Z0-9_/\\-\\\\\\$\\.]+)(,([\\w\\-]+))?\\s*\\:\\s*(.*)$");
private static final Pattern DIRECTIVE = Pattern.compile("^([a-zA-Z]+)(\\s+(.*)\\s*)?$");
private static final Charset DEFAULT_CHARSET = Charset.defaultCharset();
private boolean createCanons = false;
private boolean verbose = false;
private boolean log = false;
private boolean timing = false;
private boolean abortOnFirstError = false;
private boolean defaultAbortOnFirstError = false;
private long totalElapsedTime = 0L;
private String currentPlatform;
private Version currentVersion;
private File defaultInputDir = null;
private File defaultScriptDir = null;
private String defaultOptions = "";
private String defaultInputExt = ".canon";
private String defaultCanonCharset = "";
private Class<?> testClass = null;
private Charset currentCharset = null;
/**
* Consists of a file name and character set to use to read it.
*/
private static class DescriptionFile
{
public String descriptionFileName;
public Charset charset;
public DescriptionFile(final String descFile, final Charset cs) {
this.descriptionFileName = descFile;
this.charset = cs;
}
@Override
public String toString() {
return descriptionFileName;
}
}
List<DescriptionFile> testDescriptionFiles = null;
private FileWriter outputFileWriter = null;
/** Options both for the command line and in description files to turn on the "abort on first error" option. */
private static final String[] ABORT_OPTIONS = {
"abortonfirsterror", "abortfirsterror", "aborterror", "abortfirst", "firsterror", "abort", "first"
};
/** Options both for the command line and in description files to turn off the "abort on first error" option. */
private static final String[] NO_ABORT_OPTIONS = {
"noabortonfirsterror", "noabortfirsterror", "noaborterror", "noabortfirst", "nofirsterror", "noabort", "nofirst"
};
/** Options for description files only to restore the "abort on first error" option to the default default, or what was
* specified on the command line (if anything).
*/
private static final String[] DEFAULT_ABORT_OPTIONS = {
"defaultabortonfirsterror", "defaultabortfirsterror", "defaultaborterror", "defaultabortfirst", "defaultfirsterror", "defaultabort", "defaultfirst",
"defaborterror", "defabortfirst", "deffirsterror", "defabort", "deffirst"
};
/**
* An object to hold the multiple file-related objects that need to be passed around
* during operation.
*/
private static class TestFiles
{
public File inputFile = null;
public File outputFile = null;
public File errorFile = null;
public BufferedWriter inputWriter = null;
public BufferedWriter outputWriter = null;
public BufferedWriter errorWriter = null;
public void createStreams(final Charset cs)
throws IOException
{
inputFile = FileUtilities.createTempFile("canoninput");
outputFile = FileUtilities.createTempFile("canonoutput");
errorFile = FileUtilities.createTempFile("canonerror");
inputWriter = Files.newBufferedWriter(inputFile.toPath(), cs);
outputWriter = Files.newBufferedWriter(outputFile.toPath(), cs);
errorWriter = Files.newBufferedWriter(errorFile.toPath(), cs);
}
public void writeInputLine(final String line)
throws IOException
{
inputWriter.write(line);
inputWriter.newLine();
}
public void writeOutputLine(final String line)
throws IOException
{
outputWriter.write(line);
outputWriter.newLine();
}
public void writeErrorLine(final String line)
throws IOException
{
errorWriter.write(line);
errorWriter.newLine();
}
public void closeStreams()
throws IOException
{
inputWriter.flush();
inputWriter.close();
inputWriter = null;
outputWriter.flush();
outputWriter.close();
outputWriter = null;
errorWriter.flush();
errorWriter.close();
errorWriter = null;
}
public void abort()
throws IOException
{
if (inputWriter != null)
inputWriter.close();
if (outputWriter != null)
outputWriter.close();
if (errorWriter != null)
errorWriter.close();
}
public void deleteFiles()
throws IOException
{
inputFile.delete();
outputFile.delete();
errorFile.delete();
}
}
/**
* Do a file compare between the two files.
*
* @param testName The name of this test (parsed from the description file).
* @param canonFile The file containing the expected results.
* @param realFile The file containing the actual results.
* @param cs The charset used to encode these files originally.
* @return {@link #SUCCESS} for success, {@link #MISMATCH} if
* there were differences, {@link #INPUT_IO_ERROR} if
* an I/O error occurred.
*/
private int compareFiles(final String testName, final File canonFile, final File realFile, final Charset cs) {
if (verbose)
Intl.outFormat("tester#compareFiles", testName, canonFile.getPath(), realFile.getPath());
try {
String file1 = FileUtilities.readFileAsString(canonFile, cs, 0);
String file2 = FileUtilities.readFileAsString(realFile, cs, 0);
diff_match_patch differ = new diff_match_patch();
List<diff_match_patch.Patch> patches = differ.patch_make(file1, file2);
if (!patches.isEmpty()) {
Intl.errFormat("tester#mismatch", testName, canonFile.getPath(), realFile.getPath());
for (diff_match_patch.Patch patch : patches) {
System.err.println(patch.toString());
}
return MISMATCH;
}
}
catch (IOException ioe) {
Intl.errFormat("tester#compareError",
ioe.getMessage(), canonFile.getPath(), realFile.getPath());
return INPUT_IO_ERROR;
}
return SUCCESS;
}
/**
* Compare the real output with the canon output.
*
* @param testName The name of this particular test.
* @param canonOut The file of the expected output from the test.
* @param realOut The actual output of the test.
* @param canonErr The file of the expected error ({@link System#err}) output of the test.
* @param realErr The actual error output.
* @param cs The charset used to encode these files.
* @return The return from {@link #compareFiles}.
*/
private int compareCanons(
final String testName,
final File canonOut,
final File realOut,
final File canonErr,
final File realErr,
final Charset cs)
{
int ret = compareFiles(testName, canonOut, realOut, cs);
if (ret != SUCCESS)
return ret;
return compareFiles(testName, canonErr, realErr, cs);
}
/**
* Parse the command line into an array of arguments (hopefully the same way Java does it).
*
* @param commandLine The complete command line string.
* @return The array of parsed arguments.
*/
private String[] parseCommandLine(final String commandLine) {
// For now, until we think this through, just split on spaces
return commandLine.split("\\s");
}
private void logTestName(final PrintStream origOut, final String testName, final String altTestName, final String commandLine) {
if (!CharUtil.isNullOrEmpty(altTestName) && !testName.equals(altTestName)) {
if (log && verbose)
origOut.print(Intl.formatString("tester#logVerboseAlt", testName, altTestName, commandLine));
else if (log)
origOut.print(Intl.formatString("tester#logAlt", testName, altTestName));
else if (verbose)
origOut.print(Intl.formatString("tester#verbose", commandLine));
}
else {
if (log && verbose)
origOut.print(Intl.formatString("tester#logVerbose", testName, commandLine));
else if (log)
origOut.print(Intl.formatString("tester#log", testName));
else if (verbose)
origOut.print(Intl.formatString("tester#verbose", commandLine));
}
}
/**
* Run the test and compare results with the canons or just create the canon files
* from the current output.
*
* @param testName The name of this particular test.
* @param files Object containing the file-related objects to pass around.
* @param cs The charset to use for input, output, and error files.
* @param commandLine The complete command line for the test.
* @param expectedExitCode Usually zero, but could be an expected "error", so a non-zero value for that.
* @return The result of {@link #compareCanons} or some other precheck errors
* (or zero for {@link #createCanons} mode).
*/
private int runTestAndCompareOrCreateCanons(
final String testName,
final TestFiles files,
final Charset cs,
final String commandLine,
final int expectedExitCode)
{
InputStream origIn = System.in;
PrintStream origOut = System.out;
PrintStream origErr = System.err;
File testIn = null;
File testOut = null;
File testErr = null;
InputStream newIn = null;
PrintStream newOut = null;
PrintStream newErr = null;
long elapsedTime;
int exitCode = SUCCESS;
try {
testOut = FileUtilities.createTempFile("testoutput");
testErr = FileUtilities.createTempFile("testerror");
// Note: significant problems with charsets here on input!!
if (createCanons) {
testIn = FileUtilities.createTempFile("testinput");
newIn = new EchoInputStream(origIn, Files.newOutputStream(testIn.toPath()));
}
else {
newIn = Files.newInputStream(files.inputFile.toPath());
}
System.setIn(newIn);
System.setOut(newOut = new PrintStream(testOut, cs.name()));
System.setErr(newErr = new PrintStream(testErr, cs.name()));
long startTime = Environment.highResTimer();
try {
if (testClass == null) {
origErr.println(Intl.getString("tester#noTestClass"));
return CLASS_NOT_FOUND;
}
else {
try {
Constructor<?> constructor = testClass.getDeclaredConstructor();
Object testObject = constructor.newInstance();
if (Testable.class.isInstance(testObject)) {
Testable testableObject = (Testable) testObject;
currentVersion = new Version(testableObject.getVersion());
exitCode = testableObject.setup(parseCommandLine(commandLine));
logTestName(origOut, testName, testableObject.getTestName(), commandLine);
if (exitCode == SUCCESS) {
exitCode = testableObject.execute();
}
}
else {
Method main = testClass.getDeclaredMethod("main", String[].class);
currentVersion = new Version();
logTestName(origOut, testName, null, commandLine);
main.invoke(null, (Object) parseCommandLine(commandLine));
}
}
catch (NoSuchMethodException nsme) {
origErr.println(Intl.formatString("tester#noMainMethod", ExceptionUtil.toString(nsme)));
return OTHER_ERROR;
}
catch (IllegalAccessException | IllegalArgumentException | InstantiationException ex) {
origErr.println(Intl.formatString("tester#mainInvokeError", ExceptionUtil.toString(ex)));
return OTHER_ERROR;
}
catch (InvocationTargetException ite) {
origErr.println(Intl.formatString("tester#abnormalExitString", ExceptionUtil.toString(ite.getTargetException())));
return OTHER_ERROR;
}
}
}
catch (Exception e) {
origErr.println(Intl.formatString("tester#abnormalExitString", ExceptionUtil.toString(e)));
exitCode = OTHER_ERROR;
}
finally {
elapsedTime = Environment.highResTimer() - startTime;
totalElapsedTime += elapsedTime;
System.setIn(origIn);
origIn = null;
System.setOut(origOut);
origOut = null;
System.setErr(origErr);
origErr = null;
newIn.close();
newIn = null;
newOut.flush();
newOut.close();
newOut = null;
newErr.flush();
newErr.close();
newErr = null;
}
// For "successful failures" compare to the expected exit code
if (exitCode != expectedExitCode) {
Intl.outFormat("tester#abnormalExit", exitCode);
return exitCode;
}
int ret = SUCCESS;
if (createCanons) {
// TODO: Read and merge testIn, testOut and testErr into the new canon file
if (ret == SUCCESS) {
testIn.delete();
testOut.delete();
testErr.delete();
}
}
else {
ret = compareCanons(testName, files.outputFile, testOut, files.errorFile, testErr, cs);
if (ret == SUCCESS) {
testOut.delete();
testErr.delete();
}
}
double elapsedSecs = (double)elapsedTime / (double)Environment.highResTimerResolution();
if (log && !verbose) {
String status = (ret == SUCCESS) ? "tester#statusPassed" : "tester#statusFailed";
if (!timing)
Intl.outPrintln(status);
else
Intl.outFormat("tester#statusAndTiming", Intl.getString(status), elapsedSecs);
}
else if (timing) {
Intl.outFormat("tester#timing", elapsedSecs);
}
return ret;
}
catch (IOException ioe) {
Intl.errFormat("tester#errTempCreate", ioe.getMessage());
return OUTPUT_IO_ERROR;
}
finally {
try {
if (newIn != null)
newIn.close();
if (newOut != null)
newOut.close();
if (newErr != null)
newErr.close();
if (origIn != null)
System.setIn(origIn);
if (origOut != null)
System.setOut(origOut);
if (origErr != null)
System.setErr(origErr);
}
catch (IOException ignore) { }
}
}
private class Version implements Comparable<Version>
{
/** Major version (or -1 if empty) */
int major;
/** Minor version (or -1 if empty or equal "x" or "*") */
int minor;
public Version() {
this(-1, -1);
}
public Version(final int maj, final int min) {
major = maj;
minor = min;
}
public Version(final String input) {
String vers[] = input.split("\\.");
if (vers[0].isEmpty())
major = -1;
else
major = Integer.parseInt(vers[0]);
if (vers.length > 1) {
if (vers[1].equalsIgnoreCase("x") ||
vers[1].equals("*"))
minor = -1;
else
minor = Integer.parseInt(vers[1]);
}
else {
minor = -1;
}
}
/**
* @param other The other version to compare to.
* @return -1 if version is < other
* 0 if versions are equal
* +1 if version is > other
* will return 0 if major is -1 or major is equal and minor is -1
*/
@Override
public int compareTo(final Version other) {
if (major == -1)
return 0;
if (major != other.major) {
return Integer.signum(major - other.major);
}
if (minor == -1)
return 0;
return Integer.signum(minor - other.minor);
}
}
private boolean platformCheck(final String platformCheck) {
if (!platformCheck.isEmpty()) {
if (platformCheck.startsWith("^")) {
if (platformCheck.length() > 1) {
if (platformCheck.substring(1).equalsIgnoreCase(currentPlatform))
return false;
}
else {
// "Not anything" means nothing matches
return false;
}
}
else {
if (!platformCheck.equalsIgnoreCase(currentPlatform))
return false;
}
}
return true;
}
/**
* Check a potential canon line for platform, version and charset values
* specified as <code>{<i>platform</i>}</code> or <code>{,<i>major</i>.<i>minor</i>}</code> or <code>{<i>platform</i>,<i>major</i>.<i>minor</i>}</code>.
* <p>Platform can be <code>"windows"</code>, <code>"linux"</code>, <code>"unix"</code>, or <code>"osx"</code>. Also, <code>"^platform"</code> will match any
* platform EXCEPT the given one.
* <p>Version can also be <code><i>major</i></code>, <code><i>major</i>.<i>x</i></code> or <code><i>major</i>.*</code> or any of these
* followed by <code>+</code> or <code><i>major</i></code>[<code>.<i>minor</i></code>]<code>-<i>major</i></code>[<code>.<i>minor</i></code>] with either one omitted.
* <p>Charset is specified by <code>[charset]</code>, and can be given as <code>[*]</code> to match any character set (same as leaving out the check),
* or by <code>[^name]</code> which matches any charset BUT the given one.
* <p>Either a platform/version or charset check can be given (or both, in either order) and all the given checks must pass for the canon
* line to be included in the final canon test file.
*
* @param input The input line, with a potential platform/version or charset specification.
* @return {@code null} if the platform/version or charset spec exists and we don't pass the test, or the
* input line (less the version part) if the spec doesn't exist or if it does and we pass the
* tests, and thus the line should be part of the test.
*/
private String platformAndVersionCheck(final String input) {
if (input.startsWith("{")) {
int end = input.indexOf("}");
if (end > 0) {
String spec = input.substring(1, end);
if (spec.isEmpty())
return input;
String canonLine = input.substring(end + 1);
String[] parts = spec.split("\\,");
if (parts.length == 1) {
// platform only
if (!platformCheck(parts[0]))
return null;
return platformAndVersionCheck(canonLine);
}
else if (parts.length == 2) {
// platform + version
// either could be empty, which means all
if (!platformCheck(parts[0]))
return null;
if (!parts[1].isEmpty()) {
String version = parts[1];
int ix;
if ((ix = version.indexOf("-")) >= 0) {
// Range of versions: major[.minor]-major[.minor]
String first = version.substring(0, ix);
String second = version.substring(ix + 1);
if (first.isEmpty()) {
if (second.isEmpty()) {
return input; // will give mismatch error....
}
// -major[.minor] = anything up to that major[.minor]
Version secondVersion = new Version(second);
return (secondVersion.compareTo(currentVersion) < 0) ? null : platformAndVersionCheck(canonLine);
}
else if (second.isEmpty()) {
// major[.minor]- = anything beyond that major[.minor]
Version firstVersion = new Version(first);
return (firstVersion.compareTo(currentVersion) > 0) ? null : platformAndVersionCheck(canonLine);
}
else {
// major[.minor]-major[.minor] = anything in between
Version firstVersion = new Version(first);
Version secondVersion = new Version(second);
int firstCompare = firstVersion.compareTo(currentVersion);
int secondCompare = secondVersion.compareTo(currentVersion);
return (firstCompare > 0 || secondCompare < 0) ? null : platformAndVersionCheck(canonLine);
}
}
else {
boolean andBeyond = false;
if (version.endsWith("+")) {
andBeyond = true;
version = version.substring(0, version.length() - 1);
}
Version ver = new Version(version);
int compare = ver.compareTo(currentVersion);
if (andBeyond) {
return (compare > 0) ? null : platformAndVersionCheck(canonLine);
}
else {
return (compare != 0) ? null : platformAndVersionCheck(canonLine);
}
}
}
return platformAndVersionCheck(canonLine);
}
// else syntax error, just return the whole line which
// should generate a diff to highlight the problem
// TODO: better solution??
}
// Not a valid spec -- should this be an error?
return input;
}
else if (input.startsWith("[")) {
// [charset]...
int end = input.indexOf("]");
if (end > 0) {
String charsetName = input.substring(1, end);
if (charsetName.isEmpty())
return input;
String canonLine = input.substring(end + 1);
// "*" means any/all charsets (not necessary, but for annotation if desired)
if (charsetName.equals("*")) {
return platformAndVersionCheck(canonLine);
}
// If the name is "^name" then this will match anything BUT that name
if (charsetName.startsWith("^")) {
try {
Charset charset = Charset.forName(charsetName.substring(1));
return charset.equals(DEFAULT_CHARSET) ? null : platformAndVersionCheck(canonLine);
}
catch (UnsupportedCharsetException uce) {
return input;
}
}
else {
try {
Charset charset = Charset.forName(charsetName);
return charset.equals(DEFAULT_CHARSET) ? platformAndVersionCheck(canonLine) : null;
}
catch (UnsupportedCharsetException uce) {
return input;
}
}
}
// Not valid syntax
return input;
}
// No check (most common case), just return the input unchanged
return input;
}
/**
* Run one test with the given parameters.
* <p> In {@link #createCanons} mode, the canon file will be created in the input
* directory if specified, or the current directory if not. Otherwise the canon
* file will be parsed and the results compared to it.
*
* @param canonFileName The canon file name (which contains input, output and error lines).
* @param canonCharsetName Charset name for this file (can be {@code null} to use the platform default).
* @param commandLine The complete command line for the test.
* @param expectedExitCode Usually zero, but some tests can "fail successfully" by annotating the test
* description with the expected exit code.
* @return Test result (0 = success, or an error code).
*/
private int runOneTest(
final String canonFileName,
final String canonCharsetName,
final String commandLine,
final int expectedExitCode)
{
Charset cs = null;
try {
cs = CharUtil.isNullOrEmpty(canonCharsetName) ?
DEFAULT_CHARSET : Charset.forName(canonCharsetName);
}
catch (IllegalArgumentException iae) {
Intl.errFormat("tester#errBadCanonCharset", canonCharsetName);
return BAD_ARGUMENT;
}
BufferedReader canonReader = null;
BufferedWriter canonWriter = null;
TestFiles files = new TestFiles();
try {
// Assume the input file is named "xxx.canon" and is in the input directory (if given)
// For now, just use a File object to parse the name into path + name
File canonFile = new File(canonFileName);
String testName = FileUtilities.nameOnly(canonFile);
// Get the default file we would like to use: $inputDir + testName + $inputExt
// (assuming the "canonFileName" does not have a path and/or extension)
canonFile = FileUtilities.decorate(canonFileName, defaultInputDir, defaultInputExt);
if (createCanons) {
boolean created = canonFile.createNewFile();
if (!created) {
Intl.errFormat("tester#warnOverwriteCanon", canonFile.getPath());
// TODO: should we prompt to overwrite? Or halt here? Or what??
}
// This is the combined input/output/error stream
// TODO: what about input to the script???????
canonWriter = Files.newBufferedWriter(canonFile.toPath(), cs);
files.createStreams(cs);
// TODO: pass in canonWriter somehow for this case
int ret = runTestAndCompareOrCreateCanons(testName, files, cs, commandLine, expectedExitCode);
if (ret == 0) {
files.deleteFiles();
}
return ret;
}
else {
// If our preferred file doesn't exist, then try both the bare name in the input dir,
// and the bare name itself
boolean canRead = FileUtilities.canRead(canonFile);
if (!canRead) {
if (defaultInputDir != null) {
canonFile = FileUtilities.decorate(canonFileName, defaultInputDir, null);
canRead = FileUtilities.canRead(canonFile);
if (!canRead) {
// One last try with just the name as given
canonFile = new File(canonFileName);
canRead = FileUtilities.canRead(canonFile);
}
}
else {
canonFile = FileUtilities.decorate(canonFileName, null, defaultInputExt);
canRead = FileUtilities.canRead(canonFile);
}
}
if (!canRead) {
Intl.errFormat("tester#cannotOpenFile", canonFileName);
return 2;
}
canonReader = Files.newBufferedReader(canonFile.toPath(), cs);
files.createStreams(cs);
// Parse the canon file into options, input stream, output stream and error stream
// and write the respective stream files
String line = null;
while ((line = canonReader.readLine()) != null) {
if (line.startsWith(">>")) {
String outLine = platformAndVersionCheck(line.substring(2));
if (outLine != null) {
files.writeErrorLine(outLine);
}
}
else if (line.startsWith(">")) {
String outLine = platformAndVersionCheck(line.substring(1));
if (outLine != null) {
files.writeOutputLine(outLine);
}
}
else if (line.startsWith("<")) {
String outLine = platformAndVersionCheck(line.substring(1));
if (outLine != null) {
files.writeInputLine(outLine);
}
}
// Comments are allowed (and ignored)
else if (line.startsWith("#") ||
line.startsWith("!") ||
line.startsWith("//")) {
continue;
}
else if (line.startsWith("$")) {
// TODO: process options
}
else if (!line.isEmpty()) {
// Default is to treat the line as regular output
String outLine = platformAndVersionCheck(line);
if (outLine != null) {
files.writeOutputLine(outLine);
}
}
else {
files.writeOutputLine("");
}
}
canonReader.close();
canonReader = null;
files.closeStreams();
int ret = runTestAndCompareOrCreateCanons(testName, files, cs, commandLine, expectedExitCode);
if (ret == 0) {
files.deleteFiles();
}
return ret;
}
}
catch (IOException ioe) {
Intl.errFormat("tester#errCanonFiles", canonFileName, ioe.getMessage());
return 2;
}
finally {
try {
if (canonReader != null)
canonReader.close();
if (canonWriter != null)
canonWriter.close();
files.abort();
}
catch (IOException ignore) { }
}
}
/**
* Process the description file lines that begin with "$", "!", or ":".
*
* @param line The internal instruction input line (without the leading "$").
* @return {@code false} to abort processing of this file (fatal error).
*/
private boolean processInternalCommand(final String line) {
boolean error = false;
Matcher m = DIRECTIVE.matcher(line);
if (m.matches()) {
String command = m.group(1).toLowerCase();
String argument = m.group(3);
argument = argument == null ? null : CharUtil.stripDoubleQuotes(argument);
switch (command) {
case "echo":
if (!CharUtil.isNullOrEmpty(argument)) {
System.out.println(argument);
}
else {
System.out.println();
}
break;
case "inputdir":
case "canondir":
if (!CharUtil.isNullOrEmpty(argument)) {
File inputDir = new File(argument);
if (!inputDir.exists() || !inputDir.isDirectory()) {
Intl.errFormat("tester#badInputDir", argument);
return false;
}
else {
defaultInputDir = inputDir;
}
}
else {
Intl.errFormat("tester#emptyInputDir");
return false;
}
break;
case "scriptdir":
case "sourcedir":
if (!CharUtil.isNullOrEmpty(argument)) {
File scriptDir = new File(argument);
if (!scriptDir.exists() || !scriptDir.isDirectory()) {
Intl.errFormat("tester#badScriptDir", argument);
return false;
}
else {
defaultScriptDir = scriptDir;
}
}
else {
Intl.errFormat("tester#emptyScriptDir");
return false;
}
break;
case "testclass":
if (!CharUtil.isNullOrEmpty(argument)) {
try {
testClass = Class.forName(argument);
}
catch (NoClassDefFoundError | ClassNotFoundException | ExceptionInInitializerError ex) {
Intl.errFormat("tester#testClassNotFound", argument, ExceptionUtil.toString(ex));
return false;
}
}
else {
Intl.errFormat("tester#emptyTestClass");
return false;
}
break;
case "defaultoptions":
if (!CharUtil.isNullOrEmpty(argument)) {
defaultOptions = argument;
}
else {
error = true;
}
break;
case "canoncharset":
case "canoncs":
if (!CharUtil.isNullOrEmpty(argument)) {
defaultCanonCharset = argument;
}
else {
error = true;
}
break;
case "inputext":
if (!CharUtil.isNullOrEmpty(argument)) {
defaultInputExt = argument;
}
else {
error = true;
}
break;
case "include":
if (!CharUtil.isNullOrEmpty(argument)) {
driveOneTest(new DescriptionFile(argument, currentCharset));
}
else {
Intl.errFormat("tester#emptyInclude");
}
break;
case "file":
error = true;
if (!CharUtil.isNullOrEmpty(argument)) {
try {
outputFileWriter = new FileWriter(argument);
error = false;
}
catch (IOException ioe) {
// TODO: could be a better error message here
}
}
break;
case "delete":
error = true;
if (!CharUtil.isNullOrEmpty(argument)) {
if (new File(argument).delete())
error = false;
}
break;
default:
for (String option : ABORT_OPTIONS) {
if (line.equalsIgnoreCase(option)) {
abortOnFirstError = true;
return true;
}
}
for (String option : NO_ABORT_OPTIONS) {
if (line.equalsIgnoreCase(option)) {
abortOnFirstError = false;
return true;
}
}
for (String option : DEFAULT_ABORT_OPTIONS) {
if (line.equalsIgnoreCase(option)) {
abortOnFirstError = defaultAbortOnFirstError;
return true;
}
}
error = true;
break;
}
}
if (error)
Intl.errFormat("tester#badCommand", "$" + line);
return true;
}
private BufferedReader fileReader(final File file, final Charset cs)
throws IOException
{
if (cs == null)
return Files.newBufferedReader(file.toPath());
else
return Files.newBufferedReader(file.toPath(), cs);
}
private int numberTests = 0;
private int numberPassed = 0;
private int numberFailed = 0;
/**
* Read and process one test description file (can be recursive
* for included files).
*
* @param desc The test description file attributes.
*/
private void driveOneTest(final DescriptionFile desc) {
String name = desc.toString();
File f = new File(name);
if (!FileUtilities.canRead(f) && defaultScriptDir != null) {
f = FileUtilities.decorate(name, defaultScriptDir, null);
if (!FileUtilities.canRead(f)) {
Intl.errFormat("tester#cannotOpenFile", name);
return;
}
}
try (BufferedReader reader = fileReader(f, desc.charset))
{
String line = null;
int lineNo = 0;
while ((line = reader.readLine()) != null) {
lineNo++;
if (outputFileWriter != null) {
if (line.equalsIgnoreCase("$endfile") || line.equalsIgnoreCase("!endfile")) {
outputFileWriter.flush();
outputFileWriter.close();
outputFileWriter = null;
}
else {
outputFileWriter.write(line);
outputFileWriter.write(Environment.lineSeparator());
}
continue;
}
line = line.trim();
if (line.isEmpty() ||
line.startsWith("#") ||
line.startsWith("--") ||
line.startsWith("//"))
continue;
if (line.startsWith("$") || line.startsWith("!") || line.startsWith(":")) {
if (processInternalCommand(line.substring(1)))
continue;
else
break;
}
numberTests++;
Matcher m = DESCRIPTION.matcher(line);
if (m.matches()) {
String commandLine;
commandLine = m.group(6);
if (!CharUtil.isNullOrEmpty(defaultOptions)) {
commandLine = String.format("%1$s %2$s", defaultOptions, commandLine);
}
// Some tests "fail successfully" so account for the exit code here
String exit = m.group(2);
int expectedExitCode = 0;
if (!CharUtil.isNullOrEmpty(exit)) {
expectedExitCode = Integer.parseInt(exit);
}
String charset = m.group(5);
if (charset == null)
charset = defaultCanonCharset;
int ret = runOneTest(m.group(3), charset, commandLine, expectedExitCode);
if (ret == 0) {
numberPassed++;
}
else {
numberFailed++;
if (abortOnFirstError)
break;
}
}
else {
Intl.errFormat("tester#badSyntax", lineNo, line);
numberFailed++;
break;
}
}
}
catch (IOException ioe) {
Intl.errFormat("tester#readError", name, ioe.getMessage());
}
}
/**
* Drive all the tests from the given test description file.
*
* @param desc The test description file attributes.
*/
private void driveTests(final DescriptionFile desc) {
Intl.outPrintln(timing ? "tester#finalUnderlineTiming" : "tester#finalUnderline");
Intl.outFormat("tester#initialFile", desc.toString());
if (timing || verbose || log)
Intl.outPrintln(timing ? "tester#finalBreakTiming" : "tester#finalBreak");
driveOneTest(desc);
String totalTiming = "";
if (timing) {
double elapsedSecs = (double)totalElapsedTime / (double)Environment.highResTimerResolution();
totalTiming = Intl.formatString("tester#totalTime", elapsedSecs);
}
Intl.outPrintln(timing ? "tester#finalBreakTiming" : "tester#finalBreak");
Intl.outFormat(numberTests == 1 ? "tester#finalResultOne" : "tester#finalResults",
numberTests, numberPassed, numberFailed, totalTiming);
Intl.outPrintln(timing ? "tester#finalUnderlineTiming" : "tester#finalUnderline");
Intl.outPrintln();
}
/**
* Reset all the options back to default values (used by "-ignoreoptions" command-line argument
* to ignore any TESTER_OPTIONS specified in the environment.
*/
private void resetToInitialOptions() {
createCanons = false;
verbose = false;
log = false;
timing = false;
abortOnFirstError = defaultAbortOnFirstError = false;
defaultScriptDir = null;
testClass = null;
testDescriptionFiles.clear();
}
/**
* Process a single command-line option.
*
* @param arg The option to process (without the leading "-", or whatever).
*/
private void processOption(final String arg) {
if (Options.isOption(arg) == null) {
testDescriptionFiles.add(new DescriptionFile(arg, currentCharset));
return;
}
String opt = null, arg1 = null;
int splitIndex = arg.indexOf(':');
if (splitIndex >= 0) {
opt = arg.substring(0, splitIndex);
if (splitIndex < arg.length()) {
arg1 = arg.substring(splitIndex + 1);
}
}
else {
opt = arg;
}
if (Options.matchesOption(opt, "verbose", "v"))
verbose = true;
else if (Options.matchesOption(opt, "log", "l"))
log = true;
else if (Options.matchesOption(opt, true, "timing", "time", "t"))
timing = log = true;
else if (Options.matchesOption(opt, true, "createcanons", "create", "c"))
createCanons = true;
else if (Options.matchesOption(opt, true, ABORT_OPTIONS))
abortOnFirstError = defaultAbortOnFirstError = true;
else if (Options.matchesOption(opt, true, NO_ABORT_OPTIONS))
abortOnFirstError = defaultAbortOnFirstError = false;
else if (Options.matchesOption(opt, true, "directory", "inputdirectory", "inputdir", "dir", "d")) {
if (CharUtil.isNullOrEmpty(arg1)) {
Intl.errPrintln("tester#emptyInputDirArg");
System.exit(2);
}
File dir = new File(arg1);
if (dir.exists() && dir.isDirectory()) {
defaultScriptDir = dir;
}
else {
Intl.errFormat("tester#badInputDirArg", arg1);
System.exit(2);
}
}
else if (Options.matchesOption(opt, "locale", "loc")) {
String localeName = arg1;
Locale locale = null;
try {
locale = Intl.getValidLocale(localeName);
}
catch (IllegalArgumentException iae) {
System.err.println(ExceptionUtil.toString(iae));
System.exit(2);
}
Locale.setDefault(locale);
Intl.initAllPackageResources(locale);
}
else if (Options.matchesOption(opt, true, "charset", "char", "cs")) {
String charsetName = arg1;
Charset charset = null;
try {
charset = Charset.forName(charsetName);
currentCharset = charset;
}
catch (Exception ex) {
System.err.println(ExceptionUtil.toString(ex));
System.exit(2);
}
}
else if (Options.matchesOption(opt, true, "testclass", "class", "test")) {
try {
testClass = Class.forName(arg1);
}
catch (NoClassDefFoundError | ClassNotFoundException | ExceptionInInitializerError ex) {
Intl.errFormat("tester#testClassNotFound", arg1, ExceptionUtil.toString(ex));
System.exit(2);
}
}
else if (Options.matchesOption(opt, true, "ignoreoptions", "ignoreopt", "ignore", "ign", "i")) {
resetToInitialOptions();
}
else if (Options.matchesOption(opt, true, "version", "vers", "ver")) {
Environment.printProgramInfo();
System.exit(0);
}
else if (Options.matchesOption(opt, true, "help", "h", "?")) {
Environment.printProgramInfo();
Intl.printHelp("tester#");
System.exit(0);
}
else {
Intl.errFormat("tester#badOption", opt);
System.exit(2);
}
}
@Override
public String getVersion() {
return Environment.getAppVersion();
}
@Override
public String getTestName() {
return CharUtil.makeFileStringList(testDescriptionFiles);
}
private void processArgs(final String[] args) {
for (String arg : args) {
processOption(arg);
}
}
@Override
public int setup(final String[] args) {
testDescriptionFiles = new ArrayList<>(args.length);
// Preprocess the TESTER_OPTIONS environment variable (if present)
String testerOptions = System.getenv("TESTER_OPTIONS");
if (!CharUtil.isNullOrEmpty(testerOptions)) {
String[] parts = testerOptions.split("[;,]\\s*|\\s+");
processArgs(parts);
}
// Now the regular command-line arguments
processArgs(args);
if (testDescriptionFiles.size() == 0) {
Intl.errPrintln("tester#missingDescFile");
Intl.printHelp("tester#");
return MISSING_OPTION;
}
// Setup the canonical platform string
currentPlatform = Environment.platformIdentifier();
return SUCCESS;
}
@Override
public int execute() {
try {
testDescriptionFiles.forEach(n -> driveTests(n));
}
catch (Exception err) {
Intl.errFormat("tester#exception", ExceptionUtil.toString(err));
return OTHER_ERROR;
}
return numberFailed == 0 ? 0 : NUMBER_OF_ERRORS + numberFailed;
}
/**
* Standard no-arg constructor.
*/
public Tester() {
}
/**
* The main class method, meant to be invoked from the command line.
* The only inputs are the paths of test description files that
* provide the input to drive each individual test. Plus some
* basic options are accepted.
* <p> Each line of one of these files has the name of a "canon"
* file used to provide input to the test and which provides the
* expected output and error results. The test description line
* also lists the command-line options needed for each test.
* <p> The test description files may also contain directives to
* guide the test operation (such as the location of files)
* and comments to explain things.
*
* @param args The command line arguments from the user.
*/
public static void main(final String[] args) {
Environment.setDesktopApp(true);
Environment.loadProgramInfo(Tester.class);
int result = SUCCESS;
Tester instance = new Tester();
if ((result = instance.setup(args)) == SUCCESS)
result = instance.execute();
Testable.exit(result);
}
}
|
jacobvv/android-samples | app/src/main/java/org/jacobvv/androidsamples/recycler/cursor/model/Camera.java | <reponame>jacobvv/android-samples
package org.jacobvv.androidsamples.recycler.cursor.model;
/**
* @author jacob
* @date 19-4-20
*/
public class Camera {
}
|
TrustedBSD/sebsd | tools/tools/net80211/wlandebug/wlandebug.c | <reponame>TrustedBSD/sebsd
/*-
* Copyright (c) 2002-2004 <NAME>, <NAME>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* similar to the "NO WARRANTY" disclaimer below ("Disclaimer") and any
* redistribution must be conditioned upon including a substantially
* similar Disclaimer requirement for further binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* NO WARRANTY
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF NONINFRINGEMENT, MERCHANTIBILITY
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGES.
*
* $FreeBSD: src/tools/tools/net80211/wlandebug/wlandebug.c,v 1.1 2005/12/11 23:13:53 sam Exp $
*/
/*
* wlandebug [-i interface] flags
* (default interface is wlan.0).
*/
#include <sys/types.h>
#include <stdio.h>
#include <ctype.h>
#include <getopt.h>
#include <string.h>
#define N(a) (sizeof(a)/sizeof(a[0]))
const char *progname;
#define IEEE80211_MSG_DEBUG 0x40000000 /* IFF_DEBUG equivalent */
#define IEEE80211_MSG_DUMPPKTS 0x20000000 /* IFF_LINK2 equivalant */
#define IEEE80211_MSG_CRYPTO 0x10000000 /* crypto work */
#define IEEE80211_MSG_INPUT 0x08000000 /* input handling */
#define IEEE80211_MSG_XRATE 0x04000000 /* rate set handling */
#define IEEE80211_MSG_ELEMID 0x02000000 /* element id parsing */
#define IEEE80211_MSG_NODE 0x01000000 /* node handling */
#define IEEE80211_MSG_ASSOC 0x00800000 /* association handling */
#define IEEE80211_MSG_AUTH 0x00400000 /* authentication handling */
#define IEEE80211_MSG_SCAN 0x00200000 /* scanning */
#define IEEE80211_MSG_OUTPUT 0x00100000 /* output handling */
#define IEEE80211_MSG_STATE 0x00080000 /* state machine */
#define IEEE80211_MSG_POWER 0x00040000 /* power save handling */
#define IEEE80211_MSG_DOT1X 0x00020000 /* 802.1x authenticator */
#define IEEE80211_MSG_DOT1XSM 0x00010000 /* 802.1x state machine */
#define IEEE80211_MSG_RADIUS 0x00008000 /* 802.1x radius client */
#define IEEE80211_MSG_RADDUMP 0x00004000 /* dump 802.1x radius packets */
#define IEEE80211_MSG_RADKEYS 0x00002000 /* dump 802.1x keys */
#define IEEE80211_MSG_WPA 0x00001000 /* WPA/RSN protocol */
#define IEEE80211_MSG_ACL 0x00000800 /* ACL handling */
#define IEEE80211_MSG_WME 0x00000400 /* WME protocol */
#define IEEE80211_MSG_SUPERG 0x00000200 /* Atheros SuperG protocol */
#define IEEE80211_MSG_DOTH 0x00000100 /* 802.11h support */
#define IEEE80211_MSG_INACT 0x00000080 /* inactivity handling */
#define IEEE80211_MSG_ROAM 0x00000040 /* sta-mode roaming */
static struct {
const char *name;
u_int bit;
} flags[] = {
{ "debug", IEEE80211_MSG_DEBUG },
{ "dumppkts", IEEE80211_MSG_DUMPPKTS },
{ "crypto", IEEE80211_MSG_CRYPTO },
{ "input", IEEE80211_MSG_INPUT },
{ "xrate", IEEE80211_MSG_XRATE },
{ "elemid", IEEE80211_MSG_ELEMID },
{ "node", IEEE80211_MSG_NODE },
{ "assoc", IEEE80211_MSG_ASSOC },
{ "auth", IEEE80211_MSG_AUTH },
{ "scan", IEEE80211_MSG_SCAN },
{ "output", IEEE80211_MSG_OUTPUT },
{ "state", IEEE80211_MSG_STATE },
{ "power", IEEE80211_MSG_POWER },
{ "dotx1", IEEE80211_MSG_DOT1X },
{ "dot1xsm", IEEE80211_MSG_DOT1XSM },
{ "radius", IEEE80211_MSG_RADIUS },
{ "raddump", IEEE80211_MSG_RADDUMP },
{ "radkeys", IEEE80211_MSG_RADKEYS },
{ "wpa", IEEE80211_MSG_WPA },
{ "acl", IEEE80211_MSG_ACL },
{ "wme", IEEE80211_MSG_WME },
{ "superg", IEEE80211_MSG_SUPERG },
{ "doth", IEEE80211_MSG_DOTH },
{ "inact", IEEE80211_MSG_INACT },
{ "roam", IEEE80211_MSG_ROAM },
};
static u_int
getflag(const char *name, int len)
{
int i;
for (i = 0; i < N(flags); i++)
if (strncasecmp(flags[i].name, name, len) == 0)
return flags[i].bit;
return 0;
}
static const char *
getflagname(u_int flag)
{
int i;
for (i = 0; i < N(flags); i++)
if (flags[i].bit == flag)
return flags[i].name;
return "???";
}
static void
usage(void)
{
int i;
fprintf(stderr, "usage: %s [-i device] [flags]\n", progname);
fprintf(stderr, "where flags are:\n");
for (i = 0; i < N(flags); i++)
printf("%s\n", flags[i].name);
exit(-1);
}
int
main(int argc, char *argv[])
{
const char *ifname = "ath0";
const char *cp, *tp;
const char *sep;
int c, op, i, unit;
u_int32_t debug, ndebug;
size_t debuglen, parentlen;
char oid[256], parent[256];
progname = argv[0];
if (argc > 1) {
if (strcmp(argv[1], "-i") == 0) {
if (argc < 2)
errx(1, "missing interface name for -i option");
ifname = argv[2];
argc -= 2, argv += 2;
} else if (strcmp(argv[1], "-?") == 0)
usage();
}
for (unit = 0; unit < 10; unit++) {
#ifdef __linux__
snprintf(oid, sizeof(oid), "net.wlan%d.%%parent", unit);
#else
snprintf(oid, sizeof(oid), "net.wlan.%d.%%parent", unit);
#endif
parentlen = sizeof(parent);
if (sysctlbyname(oid, parent, &parentlen, NULL, 0) >= 0 &&
strncmp(parent, ifname, parentlen) == 0)
break;
}
if (unit == 10)
errx(1, "%s: cannot locate wlan sysctl node.", ifname);
#ifdef __linux__
snprintf(oid, sizeof(oid), "net.wlan%d.debug", unit);
#else
snprintf(oid, sizeof(oid), "net.wlan.%d.debug", unit);
#endif
debuglen = sizeof(debug);
if (sysctlbyname(oid, &debug, &debuglen, NULL, 0) < 0)
err(1, "sysctl-get(%s)", oid);
ndebug = debug;
for (; argc > 1; argc--, argv++) {
cp = argv[1];
do {
u_int bit;
if (*cp == '-') {
cp++;
op = -1;
} else if (*cp == '+') {
cp++;
op = 1;
} else
op = 0;
for (tp = cp; *tp != '\0' && *tp != '+' && *tp != '-';)
tp++;
bit = getflag(cp, tp-cp);
if (op < 0)
ndebug &= ~bit;
else if (op > 0)
ndebug |= bit;
else {
if (bit == 0) {
if (isdigit(*cp))
bit = strtoul(cp, NULL, 0);
else
errx(1, "unknown flag %.*s",
tp-cp, cp);
}
ndebug = bit;
}
} while (*(cp = tp) != '\0');
}
if (debug != ndebug) {
printf("%s: 0x%x => ", oid, debug);
if (sysctlbyname(oid, NULL, NULL, &ndebug, sizeof(ndebug)) < 0)
err(1, "sysctl-set(%s)", oid);
printf("0x%x", ndebug);
debug = ndebug;
} else
printf("%s: 0x%x", oid, debug);
sep = "<";
for (i = 0; i < N(flags); i++)
if (debug & flags[i].bit) {
printf("%s%s", sep, flags[i].name);
sep = ",";
}
printf("%s\n", *sep != '<' ? ">" : "");
return 0;
}
|
hackerlank/SourceCode | Game/OGRE/RenderSystems/GL/src/atifs/src/ATI_FS_GLGpuProgram.cpp | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.stevestreeting.com/ogre/
Copyright (c) 2000-2005 The OGRE Team
Also see acknowledgements in Readme.html
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 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 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., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/gpl.html.
-----------------------------------------------------------------------------
*/
#include "ps_1_4.h"
#include "OgreException.h"
#include "OgreRoot.h"
#include "OgreRenderSystem.h"
#include "OgreRenderSystemCapabilities.h"
#include "OgreLogManager.h"
#include "ATI_FS_GLGpuProgram.h"
using namespace Ogre;
ATI_FS_GLGpuProgram::ATI_FS_GLGpuProgram(ResourceManager* creator,
const String& name, ResourceHandle handle,
const String& group, bool isManual, ManualResourceLoader* loader) :
GLGpuProgram(creator, name, handle, group, isManual, loader)
{
mProgramType = GL_FRAGMENT_SHADER_ATI;
mProgramID = glGenFragmentShadersATI(1);
}
ATI_FS_GLGpuProgram::~ATI_FS_GLGpuProgram()
{
// have to call this here reather than in Resource destructor
// since calling virtual methods in base destructors causes crash
unload();
}
void ATI_FS_GLGpuProgram::bindProgram(void)
{
glEnable(mProgramType);
glBindFragmentShaderATI(mProgramID);
}
void ATI_FS_GLGpuProgram::unbindProgram(void)
{
glDisable(mProgramType);
}
void ATI_FS_GLGpuProgram::bindProgramParameters(GpuProgramParametersSharedPtr params)
{
// program constants done internally by compiler for local
if (params->hasRealConstantParams())
{
// Iterate over params and set the relevant ones
GpuProgramParameters::RealConstantIterator realIt =
params->getRealConstantIterator();
unsigned int index = 0;
// test
while (realIt.hasMoreElements())
{
const GpuProgramParameters::RealConstantEntry* e = realIt.peekNextPtr();
if (e->isSet)
{
glSetFragmentShaderConstantATI( GL_CON_0_ATI + index, e->val);
}
index++;
realIt.moveNext();
}
}
}
void ATI_FS_GLGpuProgram::bindProgramPassIterationParameters(GpuProgramParametersSharedPtr params)
{
GpuProgramParameters::RealConstantEntry* realEntry = params->getPassIterationEntry();
if (realEntry)
{
glSetFragmentShaderConstantATI( GL_CON_0_ATI + (GLuint)params->getPassIterationEntryIndex(), realEntry->val);
}
}
void ATI_FS_GLGpuProgram::unloadImpl(void)
{
glDeleteFragmentShaderATI(mProgramID);
}
void ATI_FS_GLGpuProgram::loadFromSource(void)
{
PS_1_4 PS1_4Assembler;
// attempt to compile the source
#ifdef _DEBUG
PS1_4Assembler.test(); // run compiler tests in debug mode
#endif
bool Error = !PS1_4Assembler.compile(mSource.c_str());
if(!Error) {
glBindFragmentShaderATI(mProgramID);
glBeginFragmentShaderATI();
// compile was successfull so send the machine instructions thru GL to GPU
Error = !PS1_4Assembler.bindAllMachineInstToFragmentShader();
glEndFragmentShaderATI();
// check GL for GPU machine instruction bind erros
if (Error)
{
OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR,
"Cannot Bind ATI fragment shader :" + mName, mName);
}
}
else
{
// an error occured when compiling the ps_1_4 source code
char buff[50];
sprintf(buff,"error on line %d in pixel shader source\n", PS1_4Assembler.mCurrentLine);
LogManager::getSingleton().logMessage("Warning: atifs compiler reported the following errors:");
LogManager::getSingleton().logMessage(buff + mName);
OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR,
"Cannot Compile ATI fragment shader : " + mName + "\n\n" + buff , mName);// +
}
}
|
xtforgame/reduxtful | test/test-data/index.js | <reponame>xtforgame/reduxtful<gh_stars>1-10
/* eslint-disable import/prefer-default-export */
import testData01 from './testData01';
export {
testData01,
};
|
nextworks-it/slicer-catalogue | EVE_BLUEPRINTS_CATALOGUE/src/main/java/it/nextworks/nfvmano/catalogue/blueprint/services/TcBlueprintCatalogueService.java | <reponame>nextworks-it/slicer-catalogue
/*
* Copyright 2018 Nextworks s.r.l.
*
* 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 it.nextworks.nfvmano.catalogue.blueprint.services;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import it.nextworks.nfvmano.catalogue.blueprint.elements.TestCaseBlueprint;
import it.nextworks.nfvmano.catalogue.blueprint.elements.TestCaseBlueprintInfo;
import it.nextworks.nfvmano.catalogue.blueprint.interfaces.TestCaseBlueprintCatalogueInterface;
import it.nextworks.nfvmano.catalogue.blueprint.messages.OnboardTestCaseBlueprintRequest;
import it.nextworks.nfvmano.catalogue.blueprint.messages.QueryTestCaseBlueprintResponse;
import it.nextworks.nfvmano.catalogue.blueprint.repo.TestCaseBlueprintInfoRepository;
import it.nextworks.nfvmano.catalogue.blueprint.repo.TestCaseBlueprintRepository;
import it.nextworks.nfvmano.libs.ifa.common.elements.Filter;
import it.nextworks.nfvmano.libs.ifa.common.exceptions.AlreadyExistingEntityException;
import it.nextworks.nfvmano.libs.ifa.common.exceptions.FailedOperationException;
import it.nextworks.nfvmano.libs.ifa.common.exceptions.MalformattedElementException;
import it.nextworks.nfvmano.libs.ifa.common.exceptions.MethodNotImplementedException;
import it.nextworks.nfvmano.libs.ifa.common.exceptions.NotExistingEntityException;
import it.nextworks.nfvmano.libs.ifa.common.messages.GeneralizedQueryRequest;
@Service
public class TcBlueprintCatalogueService implements TestCaseBlueprintCatalogueInterface {
private static final Logger log = LoggerFactory.getLogger(TcBlueprintCatalogueService.class);
@Autowired
private TestCaseBlueprintRepository testCaseBlueprintRepository;
@Autowired
private TestCaseBlueprintInfoRepository testCaseBlueprintInfoRepository;
public TcBlueprintCatalogueService() { }
@Override
public synchronized String onboardTestCaseBlueprint(OnboardTestCaseBlueprintRequest request)
throws MethodNotImplementedException, MalformattedElementException, AlreadyExistingEntityException, FailedOperationException {
log.debug("Process Test Case Blueprint Onboard request");
request.isValid();
TestCaseBlueprint tcb = request.getTestCaseBlueprint();
String testCaseBlueprintId = storeTestCaseBlueprint(tcb);
return testCaseBlueprintId;
}
@Override
public QueryTestCaseBlueprintResponse queryTestCaseBlueprint(GeneralizedQueryRequest request)
throws MethodNotImplementedException, MalformattedElementException, NotExistingEntityException, FailedOperationException {
log.debug("Processing request to query a test case blueprint");
request.isValid();
//At the moment the only filters accepted are:
//1. Test Case Blueprint name and version
//TCB_NAME & TCB_VERSION
//2. Test Case Blueprint ID
//TCB_ID
//No attribute selector is supported at the moment
List<TestCaseBlueprintInfo> tcbInfos = new ArrayList<>();
Filter filter = request.getFilter();
List<String> attributeSelector = request.getAttributeSelector();
if ((attributeSelector == null) || (attributeSelector.isEmpty())) {
Map<String, String> fp = filter.getParameters();
if (fp.size() == 1 && fp.containsKey("TCB_ID")) {
String tcbId = fp.get("TCB_ID");
TestCaseBlueprintInfo tcbi = getTestCaseBlueprintInfo(tcbId);
tcbInfos.add(tcbi);
log.debug("Added Test Case Blueprint info for TCB ID " + tcbId);
} else if (fp.size() == 2 && fp.containsKey("TCB_NAME") && fp.containsKey("TCB_VERSION")) {
String tcbName = fp.get("TCB_NAME");
String tcbVersion = fp.get("TCB_VERSION");
TestCaseBlueprintInfo tcbi = getTestCaseBlueprintInfo(tcbName, tcbVersion);
tcbInfos.add(tcbi);
log.debug("Added Test Case Blueprint info for TCB with name " + tcbName + " and version " + tcbVersion);
} else if (fp.isEmpty()) {
tcbInfos = getAllTestCaseBlueprintInfos();
log.debug("Addes all the VSB info available in DB.");
}
return new QueryTestCaseBlueprintResponse(tcbInfos);
} else {
log.error("Received query Test Case Blueprint with attribute selector. Not supported at the moment.");
throw new MethodNotImplementedException("Received query Test Case Blueprint with attribute selector. Not supported at the moment.");
}
}
@Override
public void deleteTestCaseBlueprint(String testCaseBlueprintId)
throws MethodNotImplementedException, MalformattedElementException, NotExistingEntityException, FailedOperationException {
log.debug("Processing request to delete a test case blueprint with ID " + testCaseBlueprintId);
if (testCaseBlueprintId == null) throw new MalformattedElementException("The test case blueprint ID is null");
TestCaseBlueprintInfo tcbi = getTestCaseBlueprintInfo(testCaseBlueprintId);
if (!(tcbi.getActiveTcdId().isEmpty())) {
log.error("There are some test case descriptors associated to the Test Case Blueprint. Impossible to remove it.");
throw new FailedOperationException("There are some test case descriptors associated to the Test Case Blueprint. Impossible to remove it.");
}
testCaseBlueprintInfoRepository.delete(tcbi.getId());
log.debug("Removed test case blueprint info from DB.");
TestCaseBlueprint tcb = getTestCaseBlueprint(testCaseBlueprintId);
testCaseBlueprintRepository.delete(tcb);
log.debug("Removed test case blueprint from DB.");
}
private TestCaseBlueprint getTestCaseBlueprint(String blueprintId) throws NotExistingEntityException {
Optional<TestCaseBlueprint> testCaseBlueprintOpt = testCaseBlueprintRepository.findByTestcaseBlueprintId(blueprintId);
if (testCaseBlueprintOpt.isPresent()) return testCaseBlueprintOpt.get();
else throw new NotExistingEntityException("Test Case Blueprint with ID " + blueprintId + " not found in DB.");
}
private TestCaseBlueprint getTestCaseBlueprint(String name, String version) throws NotExistingEntityException {
Optional<TestCaseBlueprint> testCaseBlueprintOpt = testCaseBlueprintRepository.findByNameAndVersion(name, version);
if (testCaseBlueprintOpt.isPresent()) return testCaseBlueprintOpt.get();
else throw new NotExistingEntityException("Test Case Blueprint with name " + name + " and version " + version + " not found in DB.");
}
private TestCaseBlueprintInfo getTestCaseBlueprintInfo(String blueprintId) throws NotExistingEntityException {
TestCaseBlueprintInfo testCaseBlueprintInfo;
Optional<TestCaseBlueprintInfo> testCaseBlueprintInfoOpt = testCaseBlueprintInfoRepository.findByTestCaseBlueprintId(blueprintId);
if (testCaseBlueprintInfoOpt.isPresent()) testCaseBlueprintInfo = testCaseBlueprintInfoOpt.get();
else throw new NotExistingEntityException("Test Case Blueprint info for test case blueprint with ID " + blueprintId + " not found in DB.");
TestCaseBlueprint tcb = getTestCaseBlueprint(blueprintId);
testCaseBlueprintInfo.setTestCaseBlueprint(tcb);
return testCaseBlueprintInfo;
}
private TestCaseBlueprintInfo getTestCaseBlueprintInfo(String name, String version) throws NotExistingEntityException {
TestCaseBlueprintInfo testCaseBlueprintInfo;
Optional<TestCaseBlueprintInfo> testCaseBlueprintInfoOpt = testCaseBlueprintInfoRepository.findByNameAndVersion(name, version);
if (testCaseBlueprintInfoOpt.isPresent()) testCaseBlueprintInfo = testCaseBlueprintInfoOpt.get();
else throw new NotExistingEntityException("Test Case Blueprint info for test case blueprint with name " + name + " and version " + version + " not found in DB.");
TestCaseBlueprint tcb = getTestCaseBlueprint(name, version);
testCaseBlueprintInfo.setTestCaseBlueprint(tcb);
return testCaseBlueprintInfo;
}
private List<TestCaseBlueprintInfo> getAllTestCaseBlueprintInfos() throws NotExistingEntityException {
List<TestCaseBlueprintInfo> tcbis = testCaseBlueprintInfoRepository.findAll();
for (TestCaseBlueprintInfo tcbi : tcbis) {
String name = tcbi.getName();
String version = tcbi.getVersion();
TestCaseBlueprint tcb = getTestCaseBlueprint(name, version);
tcbi.setTestCaseBlueprint(tcb);
}
return tcbis;
}
private String storeTestCaseBlueprint(TestCaseBlueprint tcb) throws AlreadyExistingEntityException {
log.debug("Onboarding test case blueprint with name " + tcb.getName() + " and version " + tcb.getVersion());
if ( (testCaseBlueprintInfoRepository.findByNameAndVersion(tcb.getName(), tcb.getVersion()).isPresent()) ||
(testCaseBlueprintRepository.findByNameAndVersion(tcb.getName(), tcb.getVersion()).isPresent())) {
log.error("Test Case Blueprint with name " + tcb.getName() + " and version " + tcb.getVersion() + " already present in DB.");
throw new AlreadyExistingEntityException("Test Case Blueprint with name " + tcb.getName() + " and version " + tcb.getVersion() + " already present in DB.");
}
TestCaseBlueprint target = new TestCaseBlueprint(null,
tcb.getName(),
tcb.getVersion(),
tcb.getDescription(),
tcb.getScript(),
tcb.getUserParameters(),
tcb.getInfrastructureParameters());
testCaseBlueprintRepository.saveAndFlush(target);
Long tcbId = target.getId();
String tcbIdString = String.valueOf(tcbId);
target.setTestcaseBlueprintId(tcbIdString);
testCaseBlueprintRepository.saveAndFlush(target);
log.debug("Added Test Case Blueprint with ID " + tcbIdString);
TestCaseBlueprintInfo tcbInfo = new TestCaseBlueprintInfo(tcbIdString, tcb.getVersion(), tcb.getName());
testCaseBlueprintInfoRepository.saveAndFlush(tcbInfo);
log.debug("Added Test Case Blueprint Info with ID " + tcbIdString);
return tcbIdString;
}
public synchronized void addTcdInBlueprint(String tcBlueprintId, String tcdId)
throws NotExistingEntityException {
log.debug("Adding TCD " + tcdId + " to blueprint " + tcBlueprintId);
TestCaseBlueprintInfo tcbi = getTestCaseBlueprintInfo(tcBlueprintId);
tcbi.addTcd(tcdId);
testCaseBlueprintInfoRepository.saveAndFlush(tcbi);
log.debug("Added TCD " + tcdId + " to blueprint " + tcBlueprintId);
}
public synchronized void removeTcdInBlueprint(String tcBlueprintId, String tcdId)
throws NotExistingEntityException {
log.debug("Removing TCD " + tcdId + " from blueprint " + tcBlueprintId);
TestCaseBlueprintInfo tcbi = getTestCaseBlueprintInfo(tcBlueprintId);
tcbi.removeTcd(tcdId);
testCaseBlueprintInfoRepository.saveAndFlush(tcbi);
log.debug("Removed TCD " + tcdId + " to blueprint " + tcBlueprintId);
}
}
|
mastrayer/CSM | src/CSMGameProject/CSMGameProject/TypeA.h | <reponame>mastrayer/CSM
#pragma once
#include "Effect.h"
#include "NNAnimation.h"
#include "Player.h"
class ATypeSkillEffect : public IEffect
{
public:
ATypeSkillEffect(float angle, NNPoint startPosition);
virtual ~ATypeSkillEffect();
void Render();
void Update(float dTime);
private:
NNAnimation *mExplosion[3];
float mDistance;
float mDirection;
float mExplosionTerm;
float mTimeCount;
NNPoint mNextExplosionPoint;
int mIndex;
};
class ATypeAttackEffect : public IEffect
{
public :
ATypeAttackEffect(float angle, NNPoint startPoint, int index);
virtual ~ATypeAttackEffect();
void Render();
void Update(float dTime);
void Explose();
int GetIndex(){ return mIndex; }
private :
bool mIsCrash;
int mIndex;
NNAnimation *mBullet;
NNAnimation *mExplosion;
float mAngle;
float mSpeed;
CPlayer *mFollower;
}; |
venkatramanm/humbhionline | src/main/java/in/succinct/mandi/extensions/OnOrderLineDelivery.java | <gh_stars>1-10
package in.succinct.mandi.extensions;
import com.venky.extension.Extension;
import com.venky.extension.Registry;
import com.venky.swf.db.model.Model;
import in.succinct.mandi.db.model.Item;
import in.succinct.mandi.db.model.Order;
import in.succinct.mandi.db.model.User;
import in.succinct.plugins.ecommerce.db.model.attributes.AssetCode;
import in.succinct.plugins.ecommerce.db.model.catalog.UnitOfMeasure;
import in.succinct.plugins.ecommerce.db.model.catalog.UnitOfMeasureConversionTable;
import in.succinct.plugins.ecommerce.db.model.inventory.Sku;
import in.succinct.plugins.ecommerce.db.model.order.OrderLine;
public class OnOrderLineDelivery implements Extension {
static {
Registry.instance().registerExtension("OrderLine."+ Order.FULFILLMENT_STATUS_DELIVERED +".quantity", new OnOrderLineDelivery());
}
@Override
public void invoke(Object... context) {
OrderLine orderLine = ((Model)context[0]).getRawRecord().getAsProxy(OrderLine.class);
double qtyDeliveredNow = orderLine.getReflector().getJdbcTypeHelper().getTypeRef(Double.class).getTypeConverter().valueOf(context[1]);
Sku sku = orderLine.getSku();
Item item = sku.getItem().getRawRecord().getAsProxy(Item.class);
AssetCode assetCode = item.getAssetCode();
if (qtyDeliveredNow > 0 && assetCode != null && assetCode.isSac() &&
(item.isHumBhiOnlineSubscriptionItem() || assetCode.isDeliveredElectronically())){
Order order = orderLine.getOrder().getRawRecord().getAsProxy(Order.class);
if (order.getAmountPendingPayment() > 0){
throw new RuntimeException("Once payment is done by customer, delivery happens automatically");
}
if (item.isHumBhiOnlineSubscriptionItem()) {
User creator = orderLine.getCreatorUser().getRawRecord().getAsProxy(User.class);
UnitOfMeasure pack = sku.getPackagingUOM();
double numberOfLines = UnitOfMeasureConversionTable.convert(qtyDeliveredNow, pack.getMeasures(), pack.getName() ,"Single");
creator.setBalanceOrderLineCount(creator.getBalanceOrderLineCount() + numberOfLines);
creator.setBalanceBelowThresholdAlertSent(false);
creator.save();
}
}
}
}
|
janstey/fuse-1 | components/camel-sap/camel-sap-component/src/test/java/org/fusesource/camel/component/sap/integration/MeThrowUp.java | package org.fusesource.camel.component.sap.integration;
import org.apache.camel.Exchange;
public class MeThrowUp {
public void throwUp(Exchange exchange) throws Exception {
throw new Exception("I threw up!");
}
}
|
doncat99/FinanceDataCenter | findy/database/plugins/eastmoney/__init__.py | # -*- coding: utf-8 -*-
from findy.database.plugins.eastmoney.dividend_financing import *
from findy.database.plugins.eastmoney.finance import *
from findy.database.plugins.eastmoney.holder import *
from findy.database.plugins.eastmoney.meta import *
from findy.database.plugins.eastmoney.quotes import *
from findy.database.plugins.eastmoney.trading import *
|
hissy/saelos | resources/assets/js/modules/roles/store/actions.js | <filename>resources/assets/js/modules/roles/store/actions.js
import * as types from "./action-types";
export const fetchingRole = () => ({
type: types.FETCHING_SINGLE_ROLE
});
export const fetchingRoleSuccess = payload => ({
type: types.FETCHING_SINGLE_ROLE_SUCCESS,
data: payload
});
export const fetchingRoleFailure = () => ({
type: types.FETCHING_SINGLE_ROLE_FAILURE
});
export const fetchingRoles = () => ({
type: types.FETCHING_ROLES
});
export const fetchingRolesSuccess = payload => ({
type: types.FETCHING_ROLES_SUCCESS,
data: payload
});
export const fetchingRolesFailure = () => ({
type: types.FETCHING_ROLES_FAILURE
});
export const postingRole = () => ({
type: types.POSTING_ROLE
});
export const postingRoleSuccess = payload => ({
type: types.POSTING_ROLE_SUCCESS,
data: payload
});
export const postingRoleFailure = () => ({
type: types.POSTING_ROLE_FAILURE
});
export const deletingRole = () => ({
type: types.DELETING_ROLE
});
export const deletingRoleSuccess = payload => ({
type: types.DELETING_ROLE_SUCCESS,
data: payload
});
export const deletingRoleFailure = () => ({
type: types.DELETING_ROLE_FAILURE
});
|
PhilipsOnFhir/bulk-data-proxy | src/main/java/com/philips/research/philipsonfhir/fhirproxy/support/proxy/service/IFhirServer.java | <filename>src/main/java/com/philips/research/philipsonfhir/fhirproxy/support/proxy/service/IFhirServer.java<gh_stars>0
package com.philips.research.philipsonfhir.fhirproxy.support.proxy.service;
import ca.uhn.fhir.context.FhirContext;
import org.hl7.fhir.dstu3.model.Bundle;
import org.hl7.fhir.dstu3.model.CapabilityStatement;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.instance.model.api.IBaseOperationOutcome;
import org.hl7.fhir.instance.model.api.IBaseResource;
import java.util.Map;
public interface IFhirServer {
CapabilityStatement getCapabilityStatement();
IBaseResource searchResource(String resourceType, Map<String, String> queryParams);
IBaseResource getResource(String resourceType, String id, Map<String, String> queryParams) throws FHIRException;
IBaseResource getResourceOperation(String resourceType, String operationName, Map<String, String> queryParams) throws FHIRException;
IBaseResource getResource(String resourceType, String id, String params, Map<String, String> queryParams) throws FHIRException;
Bundle loadPage(Bundle resultBundle) throws FHIRException;
IBaseOperationOutcome putResource(IBaseResource iBaseResource) throws FHIRException;
IBaseOperationOutcome postResource(IBaseResource iBaseResource) throws FHIRException;
IBaseResource postResource(
String resourceType,
String id,
IBaseResource parseResource,
String params,
Map<String, String> queryParams
) throws FHIRException;
FhirContext getCtx();
}
|
GreenCubes-org/GreenCubesOldClient | src/minecraft/net/minecraft/src/StructureNetherBridgePieceWeight.java | <reponame>GreenCubes-org/GreenCubesOldClient<gh_stars>1-10
// Decompiled by Jad v1.5.8g. Copyright 2001 <NAME>.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) braces deadcode fieldsfirst
package net.minecraft.src;
class StructureNetherBridgePieceWeight {
public Class field_40699_a;
public final int field_40697_b;
public int field_40698_c;
public int field_40695_d;
public boolean field_40696_e;
public StructureNetherBridgePieceWeight(Class class1, int i, int j, boolean flag) {
field_40699_a = class1;
field_40697_b = i;
field_40695_d = j;
field_40696_e = flag;
}
public StructureNetherBridgePieceWeight(Class class1, int i, int j) {
this(class1, i, j, false);
}
public boolean func_40693_a(int i) {
return field_40695_d == 0 || field_40698_c < field_40695_d;
}
public boolean func_40694_a() {
return field_40695_d == 0 || field_40698_c < field_40695_d;
}
}
|
willdunklin/kwiver | vital/algo/data_serializer.cxx | <reponame>willdunklin/kwiver
// This file is part of KWIVER, and is distributed under the
// OSI-approved BSD 3-Clause License. See top-level LICENSE file or
// https://github.com/Kitware/kwiver/blob/master/LICENSE for details.
/// \file
/// \brief data_serializer algorithm definition instantiation
#include <vital/algo/algorithm.txx>
#include <vital/algo/data_serializer.h>
#include <vital/util/string.h>
#include <sstream>
#include <stdexcept>
#include <vector>
namespace kwiver {
namespace vital {
namespace algo {
// ----------------------------------------------------------------------------
data_serializer
::data_serializer()
{
attach_logger( "data_serializer" );
}
} // namespace algo
} // namespace vital
} // namespace kwiver
/// \cond DoxygenSuppress
INSTANTIATE_ALGORITHM_DEF( kwiver::vital::algo::data_serializer );
/// \endcond
|
zachard/python-parent | hello_python/chapter04/python_code_format.py | <reponame>zachard/python-parent
# PEP8建议每级缩进都使用四个空格, 这既可提高可读性, 又留下了足够的多级缩进空间.
# 很多Python程序员都建议每行不超过80字符.
# 最初制定这样的指南时, 在大多数计算机中, 终端窗口每行只能容纳79字符
# PEP8还建议注释的行长都不超过72字符
# 要将程序的不同部分分开, 可使用空行. 你应该使用空行来组织程序文件, 但也不能滥用. |
oharasteve/eagle | src/com/eagle/programmar/CSharp/Directives/CSharp_RegionDirective.java | // Copyright Eagle Legacy Modernization LLC, 2010-date
// Original author: <NAME>, Oct 5, 2014
package com.eagle.programmar.CSharp.Directives;
import com.eagle.programmar.CSharp.CSharp_Class.CSharp_ClassElement;
import com.eagle.programmar.CSharp.Terminals.CSharp_CommentToEndOfLine;
import com.eagle.programmar.CSharp.Terminals.CSharp_Keyword;
import com.eagle.programmar.CSharp.Terminals.CSharp_Punctuation;
import com.eagle.tokens.TokenList;
import com.eagle.tokens.TokenSequence;
public class CSharp_RegionDirective extends TokenSequence
{
public CSharp_Punctuation pound1 = new CSharp_Punctuation('#');
public CSharp_Keyword REGION = new CSharp_Keyword("region");
public CSharp_CommentToEndOfLine regionName;
public TokenList<CSharp_ClassElement> elements;
public CSharp_Punctuation pound2 = new CSharp_Punctuation('#');
public CSharp_Keyword ENDREGION = new CSharp_Keyword("endregion");
}
|
arvindkalra/CruxAug-01 | Lecture8/RecursionCtd.java | package Lecture8;
import java.util.ArrayList;
public class RecursionCtd {
public static void main(String[] args) {
// TODO Auto-generated method stub
// System.out.println(getSS("abcd"));
// System.out.println(getSSWithAscii("ab"));
System.out.println(getMazePathDiagonal(2, 2, 0, 0));
}
public static ArrayList<String> getSS(String str) {
if (str.length() == 0) {
ArrayList<String> baseResult = new ArrayList<>();
baseResult.add("");
return baseResult;
}
char cc = str.charAt(0);
String ros = str.substring(1);
ArrayList<String> rosResult = getSS(ros);
ArrayList<String> myResult = new ArrayList<>();
for (int i = 0; i < rosResult.size(); i++) {
myResult.add(rosResult.get(i));
myResult.add(cc + rosResult.get(i));
}
return myResult;
}
public static ArrayList<String> getSSWithAscii(String str) {
if (str.length() == 0) {
ArrayList<String> baseResult = new ArrayList<>();
baseResult.add("");
return baseResult;
}
char cc = str.charAt(0);
String ros = str.substring(1);
ArrayList<String> rosResult = getSSWithAscii(ros);
ArrayList<String> myResult = new ArrayList<>();
for (int i = 0; i < rosResult.size(); i++) {
myResult.add(rosResult.get(i));
myResult.add(cc + rosResult.get(i));
myResult.add(((int) cc) + rosResult.get(i));
}
return myResult;
}
public static int countMazePath(int tr, int tc, int cr, int cc) {
int count = 0;
if(cr == tr && cc == tc){
return 1;
}
if (cc < tc) {
count += countMazePath(tr, tc, cr, cc + 1);
}
if (cr < tr) {
count += countMazePath(tr, tc, cr + 1, cc);
}
return count;
}
public static ArrayList<String> getMazePath(int tr, int tc, int cr, int cc) {
if (tr == cr && tc == cc) {
ArrayList<String> baseResult = new ArrayList<>();
baseResult.add("");
return baseResult;
}
ArrayList<String> rowResult = new ArrayList<>();
ArrayList<String> colResult = new ArrayList<>();
ArrayList<String> myResult = new ArrayList<>();
if(cc < tc){
colResult = getMazePath(tr, tc, cr, cc + 1);
}
if(cr < tr){
rowResult = getMazePath(tr, tc, cr + 1, cc);
}
for(int i = 0; i < colResult.size(); i++){
myResult.add("H" + colResult.get(i));
}
for(int i = 0; i < rowResult.size(); i++){
myResult.add("V" + rowResult.get(i));
}
return myResult;
}
public static int countMazePathDiagonal(int tr, int tc, int cr, int cc) {
int count = 0;
if(cr == tr && cc == tc){
return 1;
}
else if(cr == tr){
count += countMazePathDiagonal(tr, tc, cr, cc + 1);
}
else if(cc == tc){
count += countMazePathDiagonal(tr, tc, cr + 1, cc);
}
else{
count += countMazePathDiagonal(tr, tc, cr, cc + 1);
count += countMazePathDiagonal(tr, tc, cr + 1, cc);
count += countMazePathDiagonal(tr, tc, cr + 1, cc + 1);
}
return count;
}
public static ArrayList<String> getMazePathDiagonal(int tr, int tc, int cr, int cc) {
ArrayList<String> myResult = new ArrayList<>();
ArrayList<String> colResult = new ArrayList<>();
ArrayList<String> rowResult = new ArrayList<>();
ArrayList<String> diagResult = new ArrayList<>();
if(cr == tr && cc == tc){
ArrayList<String> baseResult = new ArrayList<>();
baseResult.add("");
return baseResult;
}
else if(cr == tr){
colResult = getMazePathDiagonal(tr, tc, cr, cc + 1);
}
else if(cc == tc){
rowResult = getMazePathDiagonal(tr, tc, cr + 1, cc);
}
else{
colResult = getMazePathDiagonal(tr, tc, cr, cc + 1);
rowResult = getMazePathDiagonal(tr, tc, cr + 1, cc);
diagResult = getMazePathDiagonal(tr, tc, cr + 1, cc + 1);
}
for(int i = 0; i < colResult.size(); i++){
myResult.add("H" + colResult.get(i));
}
for(int i = 0; i < rowResult.size(); i++){
myResult.add("V" + rowResult.get(i));
}
for(int i = 0; i < diagResult.size(); i++){
myResult.add("D" + diagResult.get(i));
}
return myResult;
}
}
|
u-wave/web | src/components/PlaylistManager/Menu/PlaylistImportRow.js | import cx from 'clsx';
import React from 'react';
import PropTypes from 'prop-types';
import { useTranslator } from '@u-wave/react-translate';
import CircularProgress from '@mui/material/CircularProgress';
import MenuItem from '@mui/material/MenuItem';
import ImportIcon from '@mui/icons-material/Input';
function PlaylistImportRow({
className,
importing,
onClick,
}) {
const { t } = useTranslator();
let icon;
if (importing) {
icon = (
<div className="PlaylistMenuRow-loading">
<CircularProgress size="100%" />
</div>
);
} else {
icon = (
<div className="PlaylistMenuRow-active-icon">
<ImportIcon />
</div>
);
}
return (
<MenuItem
className={cx('PlaylistMenuRow', 'PlaylistMenuRow--import', className)}
onClick={onClick}
>
<div className="PlaylistMenuRow-title">
{icon}
{t('playlists.import.title')}
</div>
</MenuItem>
);
}
PlaylistImportRow.propTypes = {
className: PropTypes.string,
importing: PropTypes.bool,
onClick: PropTypes.func.isRequired,
};
export default PlaylistImportRow;
|
iDube/leetcode | JZ_Offer/ms_20/m5_test.go | <filename>JZ_Offer/ms_20/m5_test.go
package ms_20
import (
"github.com/stretchr/testify/assert"
"strings"
"testing"
)
// 面试题05. 替换空格
// 请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
// 1. 暴力法?
// 2. 用api嘛?这没意思吧,还能偷偷看api怎么做的,哈哈
// 3. 用数组做?在同一个数据数组上,不用额外空间?
// 4. 用切片做?不同语言有各自特色的数据结构,貌似实现起来也有差异
// 5. 现在内存便宜,应该用更节省cpu的做法?
// 6. copy数据,用string相加来做,和用api有啥区别嘛?感觉这题不复合时代背景了,应该加更多的限制条件才行
func replaceSpace(s string) string {
return strings.ReplaceAll(s, " ", "%20")
}
func Test_replaceSpace(t *testing.T) {
ast := assert.New(t)
ast.Equal(replaceSpace("We are happy."), "We%20are%20happy.")
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.