repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
MyMelodyUwU/comp1010SemTwo
|
comp1010_s2_2021_source_codes_for_students_v1/comp1010_s2_2021_source_codes_for_students_v1/src/ServiceClasses/Card.java
|
<reponame>MyMelodyUwU/comp1010SemTwo<gh_stars>0
package ServiceClasses;
import java.util.Random;
public class Card {
public String suit;
public int rank;
// suits organized from more powerful to less powerful
public static final String[] SUITS = { "dragons", "tigers", "snakes", "mice", "cats", "lions", "bees", "ladybirds",
"possums", "goannas" };
public static final int POSSIBLE_RANKS = 13;
public Card(int rank, int suitIdx) {
this.rank = rank;
this.suit = SUITS[suitIdx];
}
public Card(Card other) {
this.rank=other.rank;
this.suit=other.suit;
}
public String getSuit() {
return suit;
}
public int getRank() {
return rank;
}
public void setSuit(String s) {
String source = s.toLowerCase();
for (int i = 0; i < SUITS.length; i++) {
if (source.equals(SUITS[i])) {
suit = source;
return;
}
}
Random r = new Random();
int index = r.nextInt(SUITS.length);
suit = SUITS[index];
}
public void setRank(int r) {
if (r < 1)
rank = 1;
else if (r > POSSIBLE_RANKS)
rank = POSSIBLE_RANKS;
else // r was in the range 1 to POSSIBLE_RANKS
rank = r;
// rank = Math.max(1, Math.min(POSSIBLE_RANKS, r));
}
public String toString() {
if (rank == 1)
return "ace of " + suit;
if (rank == POSSIBLE_RANKS - 2)
return "jack of " + suit;
if (rank == POSSIBLE_RANKS - 1)
return "queen of " + suit;
if (rank == POSSIBLE_RANKS)
return "king of " + suit;
return rank + " of " + suit;
}
public int compareTo(Card other) {
if (this.rank > other.rank)
return 1;
if (this.rank < other.rank)
return -1;
return 0;
}
public int compareToV2(Card other) {
if (this.rank > other.rank)
return 1;
if (this.rank < other.rank)
return -1;
for (int i = 0; i < SUITS.length; i++) {
String s = SUITS[i];
if (this.suit.equals(s) && !other.suit.equals(s))
return 1;
if (!this.suit.equals(s) && other.suit.equals(s))
return -1;
if (this.suit.equals(s) && other.suit.equals(s))
return 0;
}
return 0; // will never really be reached
}
public static int possibleCardCount() {
return SUITS.length * POSSIBLE_RANKS;
}
@Override
public boolean equals(Object other) {
Card otherCard = (Card) other;
return this.rank == otherCard.rank && this.suit.equals(otherCard.suit);
}
}
|
AsahiOS/gate
|
usr/src/uts/common/os/serializer.c
|
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License, Version 1.0 only
* (the "License"). You may not use this file except in compliance
* with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2004 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
#pragma ident "%Z%%M% %I% %E% SMI"
/*
* Kernel protection serializers: general purpose synchronization mechanism.
*
* Serializers provide a simple way to serialize access to some resource. They
* can be used as an alternative to locks or STREAMS perimeters. They scale
* much better than STREAMS outer serializers.
*
* Serializer is an abstraction that guarantees that all functions executed
* within the serializer are serialized: they are executed in the order they
* entered serializer one at a time.
*
* INTERFACES:
*
* serializer_t *serializer_create(flags);
*
* Create a serializer. The flags may be either SER_SLEEP or SER_NOSLEEP
* which are the same as KM_SLEEP and KM_NOSLEEP respectively.
*
* serializer_enter(serializer, proc, mblk, arg);
*
* Execute 'proc(mblk, arg)' within the serializer.
*
* serializer_wait(serializer);
*
* Wait for pending serializer jobs to complete. This function should never
* be called within the serializer or it will deadlock.
*
* serializer_destroy(serializer);
*
* Destroy serializer.
*
* Serializers export three DTrace SDT probes:
*
* serializer-enqueue(serializer, mblk, arg, proc)
*
* The probe triggers when serializer is busy and the request is
* queued.
*
* serializer-exec-start(serializer, mblk, arg, proc)
*
* The probe triggers before the request is executed
*
* serializer-exec-end(serializer, mblk, arg, proc)
*
* The probe triggers after the request is executed
*
*
* IMPLEMENTATION.
*
* Serializer consists of a "owner" and a list of queued jobs. The first thread
* entering serializer sets the owner and executes its job directly without
* context switch. Then it processes jobs which may have been enqueued while it
* was executing a job and drops the owner, leaving the serializer empty. Any
* thread entering an owned serializer enqueues its job and returns immediately.
*
* Serializer data structure holds several fields used for debugging only. They
* are not relevant for the proper serializer functioning.
*
* When new requests arrive faster then they are processed it is possible that a
* thread that started processing serializer will continue doing so for a long
* time. To avoid such pathological behavior the amount of requests drained by
* serializer_enter() is limited by `serializer_credit' value. After the credit
* is expired serializer_enter() schedules a taskq request to continue draining.
* The taskq thread draining is not limited by serializer_credit. Note that it
* is possible that another serializer_enter() will drain the serializer before
* a taskq thread will get to it.
*/
#include <sys/types.h>
#include <sys/kmem.h>
#include <sys/thread.h>
#include <sys/mutex.h>
#include <sys/systm.h>
#include <sys/debug.h>
#include <sys/taskq.h>
#include <sys/sdt.h>
#include <sys/serializer.h>
#define SERIALIZER_NAMELEN 31
/*
* Serializer abstraction.
* Fields marked (D) are used for debugging purposes only.
*/
struct serializer_s {
kmutex_t ser_lock; /* Protects state and the list */
kthread_t *ser_owner; /* Thread executing serializer */
ushort_t ser_taskq; /* Serializer scheduled for taskq */
kcondvar_t ser_cv; /* For serializer-wait */
uint_t ser_count; /* # of queued requests (D) */
mblk_t *ser_first; /* First message in the queue */
mblk_t *ser_last; /* Last message in the queue */
srproc_t *ser_proc; /* Currently executing proc (D) */
mblk_t *ser_curr; /* Currently executing msg (D) */
void *ser_arg; /* Currently executing arg (D) */
};
static kmem_cache_t *serializer_cache;
/*
* How many drains are allowed before we switch to taskq processing.
*/
#define SERIALIZER_CREDIT 10
static int serializer_credit = SERIALIZER_CREDIT;
/* Statistics for debugging */
static int perim_context_swtch = 0;
static int serializer_constructor(void *, void *, int);
static void serializer_destructor(void *, void *);
static void serializer_exec(serializer_t *, srproc_t, mblk_t *, void *);
static void serializer_enqueue(serializer_t *, srproc_t, mblk_t *, void *);
static void serializer_drain(serializer_t *, int);
static void serializer_drain_completely(serializer_t *);
/*
* SERIALIZER Implementation.
*/
/*
* Record debugging information and execute single request.
*/
static void
serializer_exec(serializer_t *s, srproc_t proc, mblk_t *mp, void *arg)
{
ASSERT(MUTEX_NOT_HELD(&s->ser_lock));
ASSERT(s->ser_owner == curthread);
ASSERT(proc != NULL);
ASSERT(mp != NULL);
s->ser_curr = mp;
s->ser_arg = arg;
s->ser_proc = proc;
proc(mp, arg);
}
/*
* Enqueue a single request on serializer.
*/
static void
serializer_enqueue(serializer_t *s, srproc_t proc, mblk_t *mp, void *arg)
{
ASSERT(MUTEX_HELD(&s->ser_lock));
DTRACE_PROBE4(serializer__enqueue, serializer_t *, s,
mblk_t *, mp, void *, arg, srproc_t, proc);
s->ser_count++;
mp->b_queue = (queue_t *)proc;
mp->b_prev = (mblk_t *)arg;
if (s->ser_last != NULL)
s->ser_last->b_next = mp;
else
s->ser_first = mp;
s->ser_last = mp;
}
/*
* Drain serializer, limiting drain to `credit' requests at most.
*/
static void
serializer_drain(serializer_t *s, int credit)
{
mblk_t *mp = s->ser_first;
ASSERT(MUTEX_HELD(&s->ser_lock));
ASSERT(s->ser_owner == curthread);
for (; mp != NULL && credit-- != 0; mp = s->ser_first) {
srproc_t *proc = (srproc_t *)mp->b_queue;
void *arg = mp->b_prev;
if ((s->ser_first = s->ser_first->b_next) == NULL) {
s->ser_last = NULL;
} else {
mp->b_next = NULL;
}
ASSERT(s->ser_count != 0);
s->ser_count--;
mp->b_queue = NULL;
mp->b_prev = NULL;
mutex_exit(&s->ser_lock);
DTRACE_PROBE4(serializer__exec__start, serializer_t *, s,
mblk_t *, mp, void *, arg, srproc_t, proc);
serializer_exec(s, proc, mp, arg);
DTRACE_PROBE4(serializer__exec__end, serializer_t *, s,
mblk_t *, mp, void *, arg, srproc_t, proc);
mutex_enter(&s->ser_lock);
}
}
/*
* Drain serializer completely if serializer is free.
*/
static void
serializer_drain_completely(serializer_t *s)
{
mutex_enter(&s->ser_lock);
ASSERT(s->ser_taskq);
if (s->ser_owner == NULL) {
s->ser_owner = curthread;
while (s->ser_first != NULL)
serializer_drain(s, INT_MAX);
s->ser_owner = NULL;
s->ser_curr = NULL;
s->ser_proc = NULL;
s->ser_arg = NULL;
}
s->ser_taskq = B_FALSE;
/*
* Wake up serializer_wait().
*/
cv_signal(&s->ser_cv);
mutex_exit(&s->ser_lock);
}
/*
* Call proc(mp, arg) within serializer.
*
* If serializer is empty and not owned, proc(mp, arg) is called right
* away. Otherwise the request is queued.
*/
void
serializer_enter(serializer_t *s, srproc_t proc, mblk_t *mp, void *arg)
{
ASSERT(proc != NULL);
ASSERT(mp != NULL);
ASSERT(mp->b_next == NULL);
ASSERT(mp->b_prev == NULL);
ASSERT(MUTEX_NOT_HELD(&s->ser_lock));
mutex_enter(&s->ser_lock);
if (s->ser_owner != NULL) {
/*
* Serializer is owned. Enqueue and return.
*/
serializer_enqueue(s, proc, mp, arg);
} else {
taskqid_t tid = TASKQID_INVALID;
/*
* If the request list is empty, can process right away,
* otherwise enqueue and process.
*/
s->ser_owner = curthread;
if (s->ser_first != NULL) {
ASSERT(s->ser_count != 0);
serializer_enqueue(s, proc, mp, arg);
} else {
ASSERT(s->ser_count == 0);
mutex_exit(&s->ser_lock);
/*
* Execute request
*/
DTRACE_PROBE4(serializer__exec__start,
serializer_t *, s, mblk_t *, mp,
void *, arg, srproc_t, proc);
serializer_exec(s, proc, mp, arg);
DTRACE_PROBE4(serializer__exec__end,
serializer_t *, s, mblk_t *, mp,
void *, arg, srproc_t, proc);
mutex_enter(&s->ser_lock);
}
/*
* Drain whatever has arrived in the meantime.
* If we spend too much time draining, continue draining by the
* taskq thread.
*/
while ((s->ser_first != NULL) && (tid == 0)) {
serializer_drain(s, serializer_credit);
if (s->ser_first != NULL) {
perim_context_swtch++;
/*
* If there is a taskq pending for this
* serializer, no need to schedule a new one.
*/
if (s->ser_taskq) {
break;
} else {
tid = taskq_dispatch(system_taskq,
(task_func_t *)
serializer_drain_completely,
s, TQ_NOSLEEP | TQ_NOQUEUE);
if (tid != TASKQID_INVALID)
s->ser_taskq = B_TRUE;
}
}
}
s->ser_owner = NULL;
s->ser_curr = NULL;
s->ser_proc = NULL;
s->ser_arg = NULL;
}
/*
* Wakeup serializer_wait().
*/
cv_signal(&s->ser_cv);
mutex_exit(&s->ser_lock);
}
/*
* Wait for pending serializer jobs to complete. This function should never be
* called within the serializer or it will deadlock.
*/
void
serializer_wait(serializer_t *s)
{
mutex_enter(&s->ser_lock);
ASSERT(s->ser_owner != curthread);
while ((s->ser_owner != NULL) || s->ser_taskq || (s->ser_first != NULL))
cv_wait(&s->ser_cv, &s->ser_lock);
ASSERT((s->ser_first == NULL) && (s->ser_last == NULL));
/*
* Wakeup other potential waiters.
*/
cv_signal(&s->ser_cv);
mutex_exit(&s->ser_lock);
}
/*
* Create a new serializer.
*/
serializer_t *
serializer_create(int flags)
{
return (kmem_cache_alloc(serializer_cache, flags));
}
/*
* Wait for all pending entries to drain and then destroy serializer.
*/
void
serializer_destroy(serializer_t *s)
{
serializer_wait(s);
ASSERT(s->ser_owner == NULL);
ASSERT(s->ser_taskq == 0);
ASSERT(s->ser_count == 0);
ASSERT(s->ser_first == NULL);
ASSERT(s->ser_last == NULL);
kmem_cache_free(serializer_cache, s);
}
/*ARGSUSED*/
static int
serializer_constructor(void *buf, void *cdrarg, int kmflags)
{
serializer_t *s = buf;
mutex_init(&s->ser_lock, NULL, MUTEX_DEFAULT, NULL);
cv_init(&s->ser_cv, NULL, CV_DEFAULT, NULL);
s->ser_taskq = 0;
s->ser_count = 0;
s->ser_first = s->ser_last = s->ser_curr = NULL;
s->ser_proc = NULL;
s->ser_arg = NULL;
s->ser_owner = NULL;
return (0);
}
/*ARGSUSED*/
static void
serializer_destructor(void *buf, void *cdrarg)
{
serializer_t *s = buf;
mutex_destroy(&s->ser_lock);
cv_destroy(&s->ser_cv);
}
void
serializer_init(void)
{
serializer_cache = kmem_cache_create("serializer_cache",
sizeof (serializer_t), 0, serializer_constructor,
serializer_destructor, NULL, NULL, NULL, 0);
}
|
paulromano/celeritas
|
src/comm/detail/LoggerMessage.cc
|
//----------------------------------*-C++-*----------------------------------//
// Copyright 2020 UT-Battelle, LLC, and other Celeritas developers.
// See the top-level COPYRIGHT file for details.
// SPDX-License-Identifier: (Apache-2.0 OR MIT)
//---------------------------------------------------------------------------//
//! \file LoggerMessage.cc
//---------------------------------------------------------------------------//
#include "LoggerMessage.hh"
#include <sstream>
#include "base/Assert.hh"
namespace celeritas
{
namespace detail
{
//---------------------------------------------------------------------------//
/*!
* Construct with reference to function object, etc.
*/
LoggerMessage::LoggerMessage(LogHandler* handle, Provenance prov, LogLevel lev)
: handle_(handle), prov_(prov), lev_(lev)
{
REQUIRE(!handle_ || *handle_);
if (handle_)
{
// std::function is defined, so create the output stream
os_ = std::make_unique<std::ostringstream>();
}
ENSURE(bool(handle_) == bool(os_));
}
//---------------------------------------------------------------------------//
/*!
* Flush message on destruction.
*/
LoggerMessage::~LoggerMessage()
{
if (os_)
{
try
{
auto& os = dynamic_cast<std::ostringstream&>(*os_);
// Write to the handler
(*handle_)(prov_, lev_, os.str());
}
catch (const std::exception& e)
{
std::cerr
<< "An error occurred writing a log message: " << e.what()
<< std::endl;
}
}
}
//---------------------------------------------------------------------------//
} // namespace detail
} // namespace celeritas
|
mykolaf/sonic-mgmt
|
tests/testbed_setup/conftest.py
|
from args.populate_fdb_args import add_populate_fdb_args
from common.fixtures.populate_fdb import populate_fdb
# FDB pytest arguments
def pytest_addoption(parser):
"""
Adds option to FDB pytest
Args:
parser: pytest parser object
Returns:
None
"""
add_populate_fdb_args(parser)
|
mahendra1904/pythod-programs
|
prog20_gen.py
|
radius=int(input("Enter the radius of the circle"))
area=22/7*radius*radius
print("The area of the circle with radius ",radius,"is",area)
|
shivharis/pybind
|
pybind/nos/v7_1_0/nas/server_ip/__init__.py
|
<gh_stars>0
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from decimal import Decimal
from bitarray import bitarray
import __builtin__
import vrf
import vlan
class server_ip(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module brocade-qos - based on the path /nas/server-ip. Each member element of
the container is represented as a class variable - with a specific
YANG type.
"""
__slots__ = ('_pybind_generated_by', '_path_helper', '_yang_name', '_rest_name', '_extmethods', '__server_ip','__vrf','__vlan',)
_yang_name = 'server-ip'
_rest_name = 'server-ip'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
path_helper_ = kwargs.pop("path_helper", None)
if path_helper_ is False:
self._path_helper = False
elif path_helper_ is not None and isinstance(path_helper_, xpathhelper.YANGPathHelper):
self._path_helper = path_helper_
elif hasattr(self, "_parent"):
path_helper_ = getattr(self._parent, "_path_helper", False)
self._path_helper = path_helper_
else:
self._path_helper = False
extmethods = kwargs.pop("extmethods", None)
if extmethods is False:
self._extmethods = False
elif extmethods is not None and isinstance(extmethods, dict):
self._extmethods = extmethods
elif hasattr(self, "_parent"):
extmethods = getattr(self._parent, "_extmethods", None)
self._extmethods = extmethods
else:
self._extmethods = False
self.__vlan = YANGDynClass(base=YANGListType("vlan_number",vlan.vlan, yang_name="vlan", rest_name="vlan", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='vlan-number', extensions={u'tailf-common': {u'info': u'Virtual LAN', u'cli-suppress-mode': None, u'callpoint': u'qos_nas_serverip_vlan'}}), is_container='list', yang_name="vlan", rest_name="vlan", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Virtual LAN', u'cli-suppress-mode': None, u'callpoint': u'qos_nas_serverip_vlan'}}, namespace='urn:brocade.com:mgmt:brocade-qos', defining_module='brocade-qos', yang_type='list', is_config=True)
self.__vrf = YANGDynClass(base=YANGListType("vrf_name",vrf.vrf, yang_name="vrf", rest_name="vrf", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='vrf-name', extensions={u'tailf-common': {u'info': u'Virtual Routing and Forwarding', u'cli-suppress-mode': None, u'callpoint': u'qos_nas_serverip_vrf'}}), is_container='list', yang_name="vrf", rest_name="vrf", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Virtual Routing and Forwarding', u'cli-suppress-mode': None, u'callpoint': u'qos_nas_serverip_vrf'}}, namespace='urn:brocade.com:mgmt:brocade-qos', defining_module='brocade-qos', yang_type='list', is_config=True)
self.__server_ip = YANGDynClass(base=[RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])/(([0-9])|([1-2][0-9])|(3[0-2]))'}),RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))(/(([0-9])|([0-9]{2})|(1[0-1][0-9])|(12[0-8])))'}),], is_leaf=True, yang_name="server-ip", rest_name="server-ip", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-qos', defining_module='brocade-qos', yang_type='nas-ip-prefix', is_config=True)
load = kwargs.pop("load", None)
if args:
if len(args) > 1:
raise TypeError("cannot create a YANG container with >1 argument")
all_attr = True
for e in self._pyangbind_elements:
if not hasattr(args[0], e):
all_attr = False
break
if not all_attr:
raise ValueError("Supplied object did not have the correct attributes")
for e in self._pyangbind_elements:
nobj = getattr(args[0], e)
if nobj._changed() is False:
continue
setmethod = getattr(self, "_set_%s" % e)
if load is None:
setmethod(getattr(args[0], e))
else:
setmethod(getattr(args[0], e), load=load)
def _path(self):
if hasattr(self, "_parent"):
return self._parent._path()+[self._yang_name]
else:
return [u'nas', u'server-ip']
def _rest_path(self):
if hasattr(self, "_parent"):
if self._rest_name:
return self._parent._rest_path()+[self._rest_name]
else:
return self._parent._rest_path()
else:
return [u'nas', u'server-ip']
def _get_server_ip(self):
"""
Getter method for server_ip, mapped from YANG variable /nas/server_ip/server_ip (nas-ip-prefix)
"""
return self.__server_ip
def _set_server_ip(self, v, load=False):
"""
Setter method for server_ip, mapped from YANG variable /nas/server_ip/server_ip (nas-ip-prefix)
If this variable is read-only (config: false) in the
source YANG file, then _set_server_ip is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_server_ip() directly.
"""
parent = getattr(self, "_parent", None)
if parent is not None and load is False:
raise AttributeError("Cannot set keys directly when" +
" within an instantiated list")
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=[RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])/(([0-9])|([1-2][0-9])|(3[0-2]))'}),RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))(/(([0-9])|([0-9]{2})|(1[0-1][0-9])|(12[0-8])))'}),], is_leaf=True, yang_name="server-ip", rest_name="server-ip", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-qos', defining_module='brocade-qos', yang_type='nas-ip-prefix', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """server_ip must be of a type compatible with nas-ip-prefix""",
'defined-type': "brocade-qos:nas-ip-prefix",
'generated-type': """YANGDynClass(base=[RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])/(([0-9])|([1-2][0-9])|(3[0-2]))'}),RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))(/(([0-9])|([0-9]{2})|(1[0-1][0-9])|(12[0-8])))'}),], is_leaf=True, yang_name="server-ip", rest_name="server-ip", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-qos', defining_module='brocade-qos', yang_type='nas-ip-prefix', is_config=True)""",
})
self.__server_ip = t
if hasattr(self, '_set'):
self._set()
def _unset_server_ip(self):
self.__server_ip = YANGDynClass(base=[RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])/(([0-9])|([1-2][0-9])|(3[0-2]))'}),RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))(/(([0-9])|([0-9]{2})|(1[0-1][0-9])|(12[0-8])))'}),], is_leaf=True, yang_name="server-ip", rest_name="server-ip", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-qos', defining_module='brocade-qos', yang_type='nas-ip-prefix', is_config=True)
def _get_vrf(self):
"""
Getter method for vrf, mapped from YANG variable /nas/server_ip/vrf (list)
"""
return self.__vrf
def _set_vrf(self, v, load=False):
"""
Setter method for vrf, mapped from YANG variable /nas/server_ip/vrf (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_vrf is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_vrf() directly.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("vrf_name",vrf.vrf, yang_name="vrf", rest_name="vrf", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='vrf-name', extensions={u'tailf-common': {u'info': u'Virtual Routing and Forwarding', u'cli-suppress-mode': None, u'callpoint': u'qos_nas_serverip_vrf'}}), is_container='list', yang_name="vrf", rest_name="vrf", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Virtual Routing and Forwarding', u'cli-suppress-mode': None, u'callpoint': u'qos_nas_serverip_vrf'}}, namespace='urn:brocade.com:mgmt:brocade-qos', defining_module='brocade-qos', yang_type='list', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """vrf must be of a type compatible with list""",
'defined-type': "list",
'generated-type': """YANGDynClass(base=YANGListType("vrf_name",vrf.vrf, yang_name="vrf", rest_name="vrf", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='vrf-name', extensions={u'tailf-common': {u'info': u'Virtual Routing and Forwarding', u'cli-suppress-mode': None, u'callpoint': u'qos_nas_serverip_vrf'}}), is_container='list', yang_name="vrf", rest_name="vrf", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Virtual Routing and Forwarding', u'cli-suppress-mode': None, u'callpoint': u'qos_nas_serverip_vrf'}}, namespace='urn:brocade.com:mgmt:brocade-qos', defining_module='brocade-qos', yang_type='list', is_config=True)""",
})
self.__vrf = t
if hasattr(self, '_set'):
self._set()
def _unset_vrf(self):
self.__vrf = YANGDynClass(base=YANGListType("vrf_name",vrf.vrf, yang_name="vrf", rest_name="vrf", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='vrf-name', extensions={u'tailf-common': {u'info': u'Virtual Routing and Forwarding', u'cli-suppress-mode': None, u'callpoint': u'qos_nas_serverip_vrf'}}), is_container='list', yang_name="vrf", rest_name="vrf", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Virtual Routing and Forwarding', u'cli-suppress-mode': None, u'callpoint': u'qos_nas_serverip_vrf'}}, namespace='urn:brocade.com:mgmt:brocade-qos', defining_module='brocade-qos', yang_type='list', is_config=True)
def _get_vlan(self):
"""
Getter method for vlan, mapped from YANG variable /nas/server_ip/vlan (list)
"""
return self.__vlan
def _set_vlan(self, v, load=False):
"""
Setter method for vlan, mapped from YANG variable /nas/server_ip/vlan (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_vlan is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_vlan() directly.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("vlan_number",vlan.vlan, yang_name="vlan", rest_name="vlan", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='vlan-number', extensions={u'tailf-common': {u'info': u'Virtual LAN', u'cli-suppress-mode': None, u'callpoint': u'qos_nas_serverip_vlan'}}), is_container='list', yang_name="vlan", rest_name="vlan", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Virtual LAN', u'cli-suppress-mode': None, u'callpoint': u'qos_nas_serverip_vlan'}}, namespace='urn:brocade.com:mgmt:brocade-qos', defining_module='brocade-qos', yang_type='list', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """vlan must be of a type compatible with list""",
'defined-type': "list",
'generated-type': """YANGDynClass(base=YANGListType("vlan_number",vlan.vlan, yang_name="vlan", rest_name="vlan", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='vlan-number', extensions={u'tailf-common': {u'info': u'Virtual LAN', u'cli-suppress-mode': None, u'callpoint': u'qos_nas_serverip_vlan'}}), is_container='list', yang_name="vlan", rest_name="vlan", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Virtual LAN', u'cli-suppress-mode': None, u'callpoint': u'qos_nas_serverip_vlan'}}, namespace='urn:brocade.com:mgmt:brocade-qos', defining_module='brocade-qos', yang_type='list', is_config=True)""",
})
self.__vlan = t
if hasattr(self, '_set'):
self._set()
def _unset_vlan(self):
self.__vlan = YANGDynClass(base=YANGListType("vlan_number",vlan.vlan, yang_name="vlan", rest_name="vlan", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='vlan-number', extensions={u'tailf-common': {u'info': u'Virtual LAN', u'cli-suppress-mode': None, u'callpoint': u'qos_nas_serverip_vlan'}}), is_container='list', yang_name="vlan", rest_name="vlan", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Virtual LAN', u'cli-suppress-mode': None, u'callpoint': u'qos_nas_serverip_vlan'}}, namespace='urn:brocade.com:mgmt:brocade-qos', defining_module='brocade-qos', yang_type='list', is_config=True)
server_ip = __builtin__.property(_get_server_ip, _set_server_ip)
vrf = __builtin__.property(_get_vrf, _set_vrf)
vlan = __builtin__.property(_get_vlan, _set_vlan)
_pyangbind_elements = {'server_ip': server_ip, 'vrf': vrf, 'vlan': vlan, }
|
lucid-at-dream/citylife
|
legacy/auth/authenticator.c
|
#include "authenticator.h"
#include "logger/logger.h"
#include <stdlib.h>
#include <string.h>
authenticator *authenticator_new()
{
info("authenticator.c: creating a new authenticator struct");
authenticator *auth = (authenticator *)calloc(1, sizeof(authenticator));
auth->auth_table = map_new(16);
return auth;
}
void authenticator_destroy(authenticator *auth)
{
info("authenticator.c: destroying authenticator struct");
map_destroy_dealloc(auth->auth_table, 1, 1);
free(auth);
}
result add_user(authenticator *auth, char *user, char *password)
{
result r;
if (map_get(auth->auth_table, user) != NULL)
{
info("authenticator.c: attempt to add user %s, which already exists", user);
r.result = AUTH_ERROR;
r.message = "The username is already registered.";
return r;
}
map_set(auth->auth_table, user, password);
info("authenticator.c: user %s added with success", user);
r.result = AUTH_SUCCESS;
r.message = "User has been added with success.";
return r;
}
result authenticate(authenticator *auth, char *user, char *token)
{
result r;
char *stored_password = map_get(auth->auth_table, user);
if (stored_password == NULL)
{
info("authenticator.c: attempt to authenticate user %s, which does not exist", user);
r.result = AUTH_ERROR;
r.message = "The provided username does not exist";
return r;
}
int match = strcmp(stored_password, token);
if (match == 0)
{
info("authenticator.c: successfully authenticated user %s", user);
r.result = AUTH_SUCCESS;
r.message = "User authentication was successful";
}
else
{
info("authenticator.c: attempt to authenticate user %s with a wrong password", user);
r.result = AUTH_ERROR;
r.message = "The wrong password has been provided for that username.";
}
return r;
}
result change_password(authenticator *auth, char *user, char *token, char *new_password)
{
result r;
if (authenticate(auth, user, token).result == AUTH_SUCCESS)
{
map_set(auth->auth_table, user, new_password);
info("authenticator.c: user %s's password successfully modified", user);
r.result = AUTH_SUCCESS;
r.message = "Successfully changed the user password.";
}
else
{
info("authenticator.c: Unable to change password for user %s because old password doesn't match", user);
r.result = AUTH_ERROR;
r.message = "The provided password does not match the one associated to this user.";
}
return r;
}
result del_user(authenticator *auth, char *user, char *token)
{
result r;
if (authenticate(auth, user, token).result == AUTH_SUCCESS)
{
map_del(auth->auth_table, user);
info("authenticator.c: user %s's successfully deleted", user);
r.result = AUTH_SUCCESS;
r.message = "User successfully deleted.";
}
else
{
info("authenticator.c: user %s was not deleted because the password did not match", user);
r.result = AUTH_ERROR;
r.message = "The provided password does not match the one associated to this user.";
}
return r;
}
|
Baek2back/kanban
|
src/redux/applyMiddleware.js
|
export default function applyMiddleware(...middlewareFactories) {
return function enhancer(createStore) {
return function newCreateStore(reducer) {
let store = createStore(reducer);
let dispatch = store.dispatch;
middlewareFactories.forEach((factory) => {
dispatch = factory(store)(dispatch);
});
store.dispatch = dispatch;
return store;
};
};
}
|
candrews/gradle
|
subprojects/dependency-management/src/main/java/org/gradle/api/internal/artifacts/ivyservice/projectmodule/DefaultProjectPublication.java
|
<reponame>candrews/gradle<gh_stars>1-10
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api.internal.artifacts.ivyservice.projectmodule;
import org.gradle.api.internal.component.SoftwareComponentInternal;
import org.gradle.internal.DisplayName;
import javax.annotation.Nullable;
public class DefaultProjectPublication implements ProjectComponentPublication {
private final DisplayName displayName;
private final Object id;
private final boolean legacy;
public DefaultProjectPublication(DisplayName displayName, Object id, boolean legacy) {
this.displayName = displayName;
this.id = id;
this.legacy = legacy;
}
@Override
public DisplayName getDisplayName() {
return displayName;
}
@Override
public boolean isLegacy() {
return legacy;
}
@Nullable
@Override
public <T> T getCoordinates(Class<T> type) {
if (type.isInstance(id)) {
return type.cast(id);
}
return null;
}
@Nullable
@Override
public SoftwareComponentInternal getComponent() {
return null;
}
@Override
public boolean isAlias() {
return false;
}
}
|
sodicarus/channels
|
channels/altadefinizionezone.py
|
<reponame>sodicarus/channels
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# Thegroove360 - XBMC Plugin
# Canale altadefinizione01casa
# ------------------------------------------------------------
import re
import urlparse
from core import config
from core import httptools
from core import logger
from core import scrapertools
from core import servertools
from core.item import Item
from core.tmdb import infoSod
__channel__ = "altadefinizionezone"
host = "https://www.altadefinizione01.casa"
headers = [['Referer', host]]
def mainlist(item):
logger.info("[tregroove360.altadefinizione01casa] mainlist")
itemlist = [Item(channel=__channel__,
title="[COLOR azure]Film [COLOR orange]- Cinema[/COLOR]",
action="peliculas",
url="%s/cinema/" % host,
extra="movie",
thumbnail="https://raw.githubusercontent.com/stesev1/channels/master/images/channels_icon/popcorn_serie_P.png"),
Item(channel=__channel__,
title="[COLOR azure]Film [COLOR orange]- Novita'[/COLOR]",
action="peliculas_update",
url=host,
thumbnail="https://raw.githubusercontent.com/stesev1/channels/master/images/channels_icon/movie_new_P.png"),
Item(channel=__channel__,
title="[COLOR azure]Film [COLOR orange]- Categorie[/COLOR]",
action="categorias",
url=host,
thumbnail="https://raw.githubusercontent.com/stesev1/channels/master/images/channels_icon/genres_P.png"),
Item(channel=__channel__,
title="[COLOR azure]Film [COLOR orange]- Attori consigliati[/COLOR]",
action="actors_list",
url="%s/attori/" % host,
thumbnail="https://raw.githubusercontent.com/stesev1/channels/master/images/channels_icon/movie_actors_P.png"),
Item(channel=__channel__,
title="[COLOR azure]Film [COLOR orange]- Archivio[/COLOR]",
action="peliculas_list",
url="%s/catalog/a/" % host,
thumbnail="https://raw.githubusercontent.com/stesev1/channels/master/images/channels_icon/all_movies_P.png"),
Item(channel=__channel__,
title="[COLOR azure]Film [COLOR orange]- Lista A-Z[/COLOR]",
action="list_az",
url="%s/catalog/a/" % host,
thumbnail="https://raw.githubusercontent.com/stesev1/channels/master/images/channels_icon/a-z_P.png"),
Item(channel=__channel__,
title="[COLOR yellow]Cerca Film...[/COLOR]",
action="search",
extra="movie",
thumbnail="https://raw.githubusercontent.com/stesev1/channels/master/images/channels_icon/search_P.png")]
return itemlist
# ==================================================================================================================================================
def categorias(item):
logger.info("[tregroove360.altadefinizione01casa] categorias")
itemlist = []
# Descarga la pagina
data = httptools.downloadpage(item.url, headers=headers).data
bloque = scrapertools.get_match(data, '<ul class="kategori_list">(.*?)</ul>\s*</div>\s*</div>\s*</div>')
# Extrae las entradas (carpetas)
patron = '<li><a href="([^"]+)">([^<]+)</a></li>'
matches = re.compile(patron, re.DOTALL).findall(bloque)
for scrapedurl, scrapedtitle in matches:
scrapedurl = host + scrapedurl
if "Altadefinizione01" in scrapedtitle:
continue
itemlist.append(
Item(channel=__channel__,
action="peliculas",
title="[COLOR azure]" + scrapedtitle + "[/COLOR]",
url=scrapedurl,
thumbnail="https://raw.githubusercontent.com/stesev1/channels/master/images/channels_icon/genre_P.png",
folder=True))
return itemlist
# ==================================================================================================================================================
def categorias_year(item):
logger.info("[tregroove360.altadefinizione01casa] categorias")
itemlist = []
# Descarga la pagina
data = httptools.downloadpage(item.url, headers=headers).data
bloque = scrapertools.get_match(data, '<ul class="kategori_list">(.*?)</ul>')
# Extrae las entradas (carpetas)
patron = '<li><a href="([^"]+)">([^<]+)</a></li>'
matches = re.compile(patron, re.DOTALL).findall(bloque)
for scrapedurl, scrapedtitle in matches:
scrapedurl = host + scrapedurl
if "Altadefinizione01" in scrapedtitle:
continue
itemlist.append(
Item(channel=__channel__,
action="peliculas",
title="[COLOR azure]" + scrapedtitle + "[/COLOR]",
url=scrapedurl,
thumbnail="https://raw.githubusercontent.com/stesev1/channels/master/images/channels_icon/genre_P.png",
folder=True))
return itemlist
# ==================================================================================================================================================
def list_az(item):
logger.info("[tregroove360.altadefinizione01casa] list_az")
itemlist = []
# Descarga la pagina
data = httptools.downloadpage(item.url, headers=headers).data
# Extrae las entradas (carpetas)
patron = '<a title=".*?" href="([^"]+)"><span>([^<]+)</span></a>'
matches = re.compile(patron, re.DOTALL).findall(data)
for scrapedurl, scrapedtitle in matches:
scrapedurl = host + scrapedurl
itemlist.append(
Item(channel=__channel__,
action="peliculas_list",
title="[COLOR azure]" + scrapedtitle + "[/COLOR]",
url=scrapedurl,
thumbnail="https://raw.githubusercontent.com/stesev1/channels/master/images/channels_icon/a-z_P.png",
folder=True))
return itemlist
# ==================================================================================================================================================
def actors_list(item):
logger.info("[tregroove360.altadefinizione01casa] actors_list")
itemlist = []
numpage = 999
p = 1
if '{}' in item.url:
item.url, p = item.url.split('{}')
p = int(p)
data = httptools.downloadpage(item.url, headers=headers).data
patron = '<h2>Attori consigliati su Altadefinizione01:</h2>(.*?)</div></div>'
data = scrapertools.find_single_match(data, patron)
patron = '<a href="([^"]+)" title="[^>]+">([^<]+)</a>'
matches = re.compile(patron, re.DOTALL).findall(data)
scrapertools.printMatches(matches)
for i, (scrapedurl, scrapedtitle) in enumerate(matches):
if (p - 1) * numpage > i: continue
if i >= p * numpage: break
itemlist.append(
Item(channel=__channel__,
action="peliculas",
title=scrapedtitle,
url=scrapedurl,
thumbnail="https://raw.githubusercontent.com/stesev1/channels/master/images/channels_icon/movie_actors_P.png",
folder=True))
# Extrae el paginador
if len(matches) >= p * numpage:
scrapedurl = item.url + '{}' + str(p + 1)
itemlist.append(
Item(channel=__channel__,
extra=item.extra,
action="actors_list",
title="[COLOR orange]Successivi >>[/COLOR]",
url=scrapedurl,
thumbnail="https://raw.githubusercontent.com/stesev1/channels/master/images/channels_icon/next_1.png",
folder=True))
return itemlist
# ==================================================================================================================================================
def peliculas_list(item):
logger.info("[tregroove360.altadefinizione01casa] peliculas_list")
itemlist = []
# Descarga la pagina
data = httptools.downloadpage(item.url, headers=headers).data
# Extrae las entradas (carpetas)
patron = '<img\s*[^>]+src="([^"]+)[^>]+>\s*</a>\s*</td>\s*[^>]+>'
patron += '<h2>\s*<a href="([^"]+)"\s*title=".*?">([^<]+)</a>\s*</h2></td>.*?'
patron += '<td class="mlnh-3">(.*?)</td>.*?<td class="mlnh-4">(.*?)</td>'
matches = re.compile(patron, re.DOTALL).finditer(data)
for match in matches:
scrapedplot = ""
quality = scrapertools.unescape(match.group(5))
year = scrapertools.unescape(match.group(4))
scrapedtitle = scrapertools.unescape(match.group(3))
scrapedurl = scrapertools.unescape(match.group(2))
scrapedthumbnail = urlparse.urljoin(item.url, match.group(1))
if year:
scrapetitle=scrapedtitle.strip() + " (" + year + ")"
else:
scrapetitle=scrapedtitle
if quality:
quality = " ([COLOR yellow]" + quality + "[/COLOR])"
if year:
year = " ([COLOR yellow]" + year + "[/COLOR])"
itemlist.append(infoSod(
Item(channel=__channel__,
action="findvideos",
contentType="movie",
fulltitle=scrapetitle,
show=scrapetitle,
title="[COLOR azure]" + scrapedtitle + "[/COLOR]" + year + quality,
url=scrapedurl,
thumbnail=scrapedthumbnail,
plot=scrapedplot,
folder=True), tipo='movie'))
# Extrae el paginador
patronvideos = 'href="([^"]+)">»</a></i>'
matches = re.compile(patronvideos, re.DOTALL).findall(data)
if len(matches) > 0:
scrapedurl = urlparse.urljoin(item.url, matches[0])
itemlist.append(
Item(channel=__channel__,
action="peliculas_list",
title="[COLOR orange]Successivi >>[/COLOR]",
url=scrapedurl,
thumbnail="https://raw.githubusercontent.com/stesev1/channels/master/images/channels_icon/next_1.png",
folder=True))
return itemlist
# ==================================================================================================================================================
def peliculas_update(item):
logger.info("[tregroove360.altadefinizione01casa] peliculas_update")
itemlist = []
# Descarga la pagina
data = httptools.downloadpage(item.url, headers=headers).data
patron = '<div class="son_eklenen">.*?<div class="son_eklenen_head"></div>(.*?)<div class="son_eklenen">'
data = scrapertools.find_single_match(data, patron)
# Extrae las entradas (carpetas)
patron = '</div>\s*<a href="([^"]+)">\s*' \
'<img width=".*?"\s*height=".*?" src="([^"]+)" [^>]+ alt="([^<]+)"\s*title="".*?/>.*?' \
'</a>\s*<div class="trdublaj">\s*(.*?)</div>\s*[^>]+>(.*?)\s*<' \
'.*?<li>\s*<span class="ml[^"]+">(.*?)<\/.*?span>\s*<\/li>\s*' \
'<li><span class="ml-label">([^<]+)</span></li>.*?<p>(.*?)</p>'
matches = re.compile(patron, re.DOTALL).finditer(data)
for match in matches:
scrapedplot = scrapertools.unescape(match.group(8))
year = scrapertools.unescape(match.group(7))
rating = scrapertools.unescape(match.group(6))
sub = scrapertools.unescape(match.group(5))
quality = scrapertools.unescape(match.group(4))
scrapedtitle = scrapertools.unescape(match.group(3))
scrapedthumbnail = urlparse.urljoin(item.url, match.group(2))
scrapedurl = scrapertools.unescape(match.group(1))
if year:
scrapetitle=scrapedtitle.strip() + " (" + year + ")"
else:
scrapetitle=scrapedtitle
if sub:
sub = " ([COLOR yellow]" + sub + "[/COLOR])"
if quality:
quality = " ([COLOR yellow]" + quality + "[/COLOR])"
if year:
year = " ([COLOR yellow]" + year + "[/COLOR])"
scrapetitle=scrapedtitle + " (" + year + ")"
if rating:
rating=rating.replace("<b>", "")
rating = " ([COLOR yellow]" + rating + "[/COLOR])"
itemlist.append(infoSod(
Item(channel=__channel__,
action="findvideos",
contentType="movie",
fulltitle=scrapetitle,
show=scrapetitle,
title="[COLOR azure]" + scrapedtitle + "[/COLOR] " + sub + year + quality + rating,
url=scrapedurl,
thumbnail=scrapedthumbnail,
plot=scrapedplot,
folder=True), tipo='movie'))
# Extrae el paginador
patronvideos = 'href="([^"]+)">»</a></i>'
matches = re.compile(patronvideos, re.DOTALL).findall(data)
if len(matches) > 0:
scrapedurl = urlparse.urljoin(item.url, matches[0])
itemlist.append(
Item(channel=__channel__,
action="peliculas_update",
title="[COLOR orange]Successivi >>[/COLOR]",
url=scrapedurl,
thumbnail="https://raw.githubusercontent.com/stesev1/channels/master/images/channels_icon/next_1.png",
folder=True))
return itemlist
# ==================================================================================================================================================
def peliculas(item):
logger.info("[tregroove360.altadefinizione01casa] peliculas")
itemlist = []
# Descarga la pagina
data = httptools.downloadpage(item.url, headers=headers).data
# Extrae las entradas (carpetas)
patron = '<h2>\s*<a href="([^"]+)">([^"]+)<\/a>\s*<\/h2>\s*[^>]+>[^>]+.*?\s*'
patron += '</div>\s*<a href[^>]+>[^>]+src="([^"]+)"[^>]+>\s*</a>\s*'
patron += '<div class="trdublaj">\s*(.*?)</div>\s*[^>]+>(.*?)\s*<'
patron += '.*?<li>\s*<span class="ml[^"]+">(.*?)<\/.*?span>\s*<\/li>\s*'
patron += '<li><span class="ml-label">([^<]+)</span></li>.*?<p>(.*?)</p>'
matches = re.compile(patron, re.DOTALL).finditer(data)
for match in matches:
scrapedplot = scrapertools.unescape(match.group(8))
year = scrapertools.unescape(match.group(7))
rating = scrapertools.unescape(match.group(6))
sub = scrapertools.unescape(match.group(5))
quality = scrapertools.unescape(match.group(4))
scrapedthumbnail = urlparse.urljoin(item.url, match.group(3))
scrapedtitle = scrapertools.unescape(match.group(2))
scrapedurl = scrapertools.unescape(match.group(1))
if year:
scrapetitle=scrapedtitle.strip() + " (" + year + ")"
else:
scrapetitle=scrapedtitle
if sub:
sub = " ([COLOR yellow]" + sub + "[/COLOR])"
if quality:
quality = " ([COLOR yellow]" + quality + "[/COLOR])"
if year:
year = " ([COLOR yellow]" + year + "[/COLOR])"
if rating:
rating=rating.replace("<b>", "")
rating = " ([COLOR yellow]" + rating + "[/COLOR])"
itemlist.append(infoSod(
Item(channel=__channel__,
action="findvideos",
contentType="movie",
fulltitle=scrapetitle,
show=scrapetitle,
title="[COLOR azure]" + scrapedtitle + "[/COLOR] " + sub + year + quality + rating,
url=scrapedurl,
thumbnail=scrapedthumbnail,
plot=scrapedplot,
folder=True), tipo='movie'))
# Extrae el paginador
patronvideos = 'href="([^"]+)">»</a></i>'
matches = re.compile(patronvideos, re.DOTALL).findall(data)
if len(matches) > 0:
scrapedurl = urlparse.urljoin(item.url, matches[0])
itemlist.append(
Item(channel=__channel__,
action="peliculas",
title="[COLOR orange]Successivi >>[/COLOR]",
url=scrapedurl,
thumbnail="https://raw.githubusercontent.com/stesev1/channels/master/images/channels_icon/next_1.png",
folder=True))
return itemlist
# ==================================================================================================================================================
def findvideos(item):
logger.info("[tregroove360.altadefinizione01casa] findvideos")
itemlist = []
# Descarga la pagina
data = httptools.downloadpage(item.url, headers=headers).data
# Estrae i contenuti
patron = '</a>\s*<a href="[^>]+" data-link="([^"]+)">\s*<li class="part">'
matches = re.compile(patron, re.DOTALL).findall(data)
for scrapedurl in matches:
if not "http" in scrapedurl:
scrapedurl = "http:" + scrapedurl
data += httptools.downloadpage(scrapedurl).data
for videoitem in servertools.find_video_items(data=data):
servername = re.sub(r'[-\[\]\s]+', '', videoitem.title)
videoitem.title = "".join(['[COLOR azure][[COLOR orange]' + servername.capitalize() + '[/COLOR]] - ', item.title])
videoitem.fulltitle = item.fulltitle
videoitem.thumbnail = item.thumbnail
videoitem.show = item.show
videoitem.plot = item.plot
videoitem.channel = __channel__
itemlist.append(videoitem)
return itemlist
# ==================================================================================================================================================
def search(item, texto):
logger.info("[tregroove360.altadefinizione01casa] " + item.url + " search " + texto)
item.url = host + "/?do=search&subaction=search&story=" + texto
try:
return peliculas(item)
# Se captura la excepción, para no interrumpir al buscador global si un canal falla
except:
import sys
for line in sys.exc_info():
logger.error("%s" % line)
return []
# ==================================================================================================================================================
|
cable5881/algorithm
|
src/com/lqb/offer/mark/MinNumberInRotateArray.java
|
<reponame>cable5881/algorithm
package com.lqb.offer.mark;
/**
* 旋转数组的最小数字
* 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
* 输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。
* 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。
* NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
*/
public class MinNumberInRotateArray {
public static void main(String[] args) {
System.out.println("1: " + findMin(new int[]{1}));
System.out.println("2: " + findMin(new int[]{1,3}));
System.out.println("3: " + findMin(new int[]{3,1}));
System.out.println("4: " + findMin(new int[]{3,1,2}));
System.out.println("5: " + findMin(new int[]{1,2,3}));
System.out.println("6: " + findMin(new int[]{4,6,8,9,10,1,2,3}));
System.out.println("7: " + findMin(new int[]{8,9,10,1,2,3,4,6}));
System.out.println("8: " + findMin(new int[]{9,10,1,2,3,4,6,8}));
System.out.println("9: " + findMin(new int[]{6,8,9,10,1,2,3,4}));
System.out.println("10: " + findMin(new int[]{1,2,3,4,6,8,9,10}));
System.out.println("11: " + findMin2(new int[]{2,2,2,1,2}));
}
/**
* [8,9,10,1,2,3,4,6] mid=1 < left && mid < right >>> right=mid
* [9,10,1,2,3,4,6,8] mid=2 < left && mid < right >>> right=mid
* [1,2,3,4,6,8,9,10] mid=4 > left && mid < right >>> right=mid
* [4,6,8,9,10,1,2,3] mid=9 > left && mid > right >>> left=mid
* [6,8,9,10,1,2,3,4] mid=10 > left && mid > right >>> left=mid
* 可以总结出规律,凡是nums[mid] < nums[right],都是需要right=mid的
*/
public static int findMin(int[] nums) {
if (nums.length <= 0) {
return -1;
}
int left = 0;
int right = nums.length - 1;
while (left < right) {
int mid = (left + right) / 2;
if (nums[mid] <= nums[right]) {
right = mid;
} else {
//这里注意需要mid + 1。不然像[3,1]这种会一直死循环
left = mid + 1;
}
}
return nums[right];
}
/**
* 考虑重复的情况
* [2,2,2,1,2]
*
* 实际提示复杂度有点高
*/
public static int findMin2(int[] nums) {
if (nums.length <= 0) {
return -1;
}
int left = 0;
int right = nums.length - 1;
while (left < right) {
//考虑提前退出
if (nums[left] < nums[right]) {
return nums[left];
}
int mid = (left + right) / 2;
if (mid > left && nums[mid] == nums[left]) {
left = filterDuplicate(nums, left, mid);
} else if (mid < right && nums[mid] == nums[right]) {
right = filterDuplicate(nums, mid, right);
} else if (nums[mid] <= nums[right]) {
right = mid;
} else {
//这里注意需要mid + 1。不然像[3,1]这种会一直死循环
left = mid + 1;
}
}
return nums[right];
}
private static int filterDuplicate(int[] nums, int start, int end) {
int i = start;
while (i < end) {
if (nums[i] == nums[end]) {
i++;
} else {
return i;
}
}
return end;
}
//官方解法
public static int findMin3(int[] nums) {
if (nums.length <= 0) {
return -1;
}
int left = 0;
int right = nums.length - 1;
while (left < right) {
//考虑提前退出
if (nums[left] < nums[right]) {
return nums[left];
}
int mid = (left + right) / 2;
if (nums[mid] < nums[right]) {
right = mid;
} else if (nums[mid] > nums[right]){
//这里注意需要mid + 1。不然像[3,1]这种会一直死循环
left = mid + 1;
} else {
//考虑重复的情况
//1 0 1 1 1
//1 1 1 0 1
//这种情况,不能确定答案在左边还是右边,那么就让 right = right - 1;慢慢缩少区间,同时也不会错过答案。
right--;
}
}
return nums[right];
}
}
|
shuigedeng/taotao-cloud-paren
|
taotao-cloud-microservice/taotao-cloud-starter/taotao-cloud-starter-feign/src/main/java/com/taotao/cloud/feign/configuration/FeignInterceptorConfiguration.java
|
/*
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.taotao.cloud.feign.configuration;
import cn.hutool.core.util.StrUtil;
import com.taotao.cloud.common.constant.CommonConstant;
import com.taotao.cloud.common.constant.ContextConstant;
import com.taotao.cloud.common.constant.StarterName;
import com.taotao.cloud.common.context.TenantContextHolder;
import com.taotao.cloud.common.utils.LogUtil;
import com.taotao.cloud.feign.properties.FeignInterceptorProperties;
import feign.RequestInterceptor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.Objects;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.MDC;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
* feign拦截器,只包含http相关数据
*
* @author shuigedeng
* @version 1.0.0
* @since 2020/4/5 13:33
*/
@Configuration
@ConditionalOnProperty(prefix = FeignInterceptorProperties.PREFIX, name = "enabled", havingValue = "true")
public class FeignInterceptorConfiguration implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
LogUtil.started(FeignInterceptorConfiguration.class, StarterName.FEIGN_STARTER);
}
protected List<String> requestHeaders = new ArrayList<>();
public static final List<String> HEADER_NAME_LIST = Arrays.asList(
ContextConstant.JWT_KEY_TENANT,
ContextConstant.JWT_KEY_SUB_TENANT,
ContextConstant.JWT_KEY_USER_ID,
ContextConstant.JWT_KEY_ACCOUNT,
ContextConstant.JWT_KEY_NAME,
ContextConstant.GRAY_VERSION,
ContextConstant.TRACE_ID_HEADER,
"X-Real-IP",
"x-forwarded-for"
);
@PostConstruct
public void initialize() {
requestHeaders.add(CommonConstant.TAOTAO_CLOUD_USER_ID_HEADER);
requestHeaders.add(CommonConstant.TAOTAO_CLOUD_USER_NAME_HEADER);
requestHeaders.add(CommonConstant.TAOTAO_CLOUD_USER_ROLE_HEADER);
requestHeaders.add(CommonConstant.TAOTAO_CLOUD_VERSION);
}
/**
* 使用feign client访问别的微服务时,将上游传过来的access_token、username、roles等信息放入header传递给下一个服务
*/
@Bean
public RequestInterceptor httpFeignInterceptor() {
LogUtil.started(RequestInterceptor.class, StarterName.FEIGN_STARTER);
return template -> {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes != null) {
ServletRequestAttributes attributes = (ServletRequestAttributes) Objects
.requireNonNull(requestAttributes);
RequestContextHolder.setRequestAttributes(attributes, true);
HttpServletRequest request = attributes.getRequest();
Enumeration<String> headerNames = request.getHeaderNames();
if (headerNames != null) {
String headerName;
String headerValue;
while (headerNames.hasMoreElements()) {
headerName = headerNames.nextElement();
if (requestHeaders.contains(headerName)) {
headerValue = request.getHeader(headerName);
template.header(headerName, headerValue);
}
}
}
//传递client
//传递access_token,无网络隔离时需要传递
String tenant = TenantContextHolder.getTenant();
if (StrUtil.isNotEmpty(tenant)) {
template.header(CommonConstant.TAOTAO_CLOUD_TENANT_HEADER, tenant);
}
//传递日志traceId
String traceId = MDC.get(CommonConstant.TAOTAO_CLOUD_TRACE_ID);
if (StrUtil.isNotEmpty(traceId)) {
template.header(CommonConstant.TAOTAO_CLOUD_TRACE_HEADER, traceId);
}
String token = extractHeaderToken(request);
if (StrUtil.isEmpty(token)) {
token = request.getParameter(CommonConstant.TAOTAO_CLOUD_ACCESS_TOKEN);
}
if (StrUtil.isNotEmpty(token)) {
template.header(CommonConstant.TAOTAO_CLOUD_TOKEN_HEADER,
CommonConstant.BEARER_TYPE + " " + token);
}
}
};
}
/**
* 解析head中的token
*
* @param request request
*/
private String extractHeaderToken(HttpServletRequest request) {
Enumeration<String> headers = request.getHeaders(CommonConstant.TAOTAO_CLOUD_TOKEN_HEADER);
while (headers.hasMoreElements()) {
String value = headers.nextElement();
if (value.startsWith(CommonConstant.BEARER_TYPE)) {
String authHeaderValue = value.substring(CommonConstant.BEARER_TYPE.length())
.trim();
int commaIndex = authHeaderValue.indexOf(',');
if (commaIndex > 0) {
authHeaderValue = authHeaderValue.substring(0, commaIndex);
}
return authHeaderValue;
}
}
return null;
}
}
|
eric-wieser/graphology
|
src/utils/index.js
|
<gh_stars>100-1000
/**
* Graphology Utils
* =================
*
* Library endpoint.
*/
var addEdgeModule = require('./add-edge');
var addNodeModule = require('./add-node');
exports.addEdge = addEdgeModule.addEdge;
exports.copyEdge = addEdgeModule.copyEdge;
exports.mergeEdge = addEdgeModule.mergeEdge;
exports.updateEdge = addEdgeModule.updateEdge;
exports.copyNode = addNodeModule.updateNode;
exports.inferType = require('./infer-type.js');
exports.isGraph = require('./is-graph.js');
exports.isGraphConstructor = require('./is-graph-constructor.js');
exports.mergeClique = require('./merge-clique.js');
exports.mergeCycle = require('./merge-cycle.js');
exports.mergePath = require('./merge-path.js');
exports.mergeStar = require('./merge-star.js');
exports.renameGraphKeys = require('./rename-graph-keys.js');
exports.updateGraphKeys = require('./update-graph-keys.js');
exports.memoizedForEach = require('./memoized-for-each.js');
|
thaisacs/oi-dbt
|
doc/html/class_e_l_f_i_o_1_1elfio_1_1_sections.js
|
var class_e_l_f_i_o_1_1elfio_1_1_sections =
[
[ "Sections", "class_e_l_f_i_o_1_1elfio_1_1_sections.html#a77095b63b7e9e56e40cfc94dad24c45e", null ],
[ "add", "class_e_l_f_i_o_1_1elfio_1_1_sections.html#af60206f1e95ae37985df476419ce875e", null ],
[ "begin", "class_e_l_f_i_o_1_1elfio_1_1_sections.html#ac64b4742bb8fb0eb2bc821ae2958ecec", null ],
[ "end", "class_e_l_f_i_o_1_1elfio_1_1_sections.html#ab78a91bb0162c7cf27185a16ba508c53", null ],
[ "operator[]", "class_e_l_f_i_o_1_1elfio_1_1_sections.html#a79aba75793609c2a85409478cb0fe1f8", null ],
[ "operator[]", "class_e_l_f_i_o_1_1elfio_1_1_sections.html#a441cba399775295f6cc876c779937ade", null ],
[ "size", "class_e_l_f_i_o_1_1elfio_1_1_sections.html#a5c66bdb3ab662752c4968d8cd1a1a490", null ]
];
|
playbar/android-ndk
|
jnitest/app/src/main/cpp/Sample2.c
|
<gh_stars>1-10
// Sample2.c
#include <stdio.h>
#include "com_study_jnilearn_Sample2.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_study_jnilearn_Sample2
* Method: instanceMethod
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_com_study_jnilearn_Sample2_accessStaticField
(JNIEnv *env, jobject obj)
{
jfieldID fid;
jint num;
// 获取引用这个实例对象的class
jclass cls = (*env)->GetObjectClass(env,obj);
fid = (*env)->GetStaticFieldID(env,cls,"num","I");
if (fid == NULL)
{
return; // 找不到字段
}
printf("In C:\n");
num = (*env)->GetStaticIntField(env,obj,fid);
printf("Sample2.num:%d\n",num);
// 设置静态字段的值
(*env)->SetStaticIntField(env,cls,fid,200);
}
/*
* Class: com_study_jnilearn_Sample2
* Method: staticMethod
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_com_study_jnilearn_Sample2_accessStaticMethod
(JNIEnv *env, jclass cls)
{
jmethodID mid;
mid = (*env)->GetStaticMethodID(env,cls,"nativeMethod","(I)V");
if (mid == NULL)
{
return;
}
(*env)->CallStaticVoidMethod(env,cls,mid,50);
}
/*
* Class: com_study_jnilearn_Sample2
* Method: accessPrimaryInstanceMethod
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_com_study_jnilearn_Sample2_accessPrimaryInstanceMethod
(JNIEnv *env, jclass cls)
{
// 创建Sample2的实例
jmethodID mid;
jobject obj;
jfieldID fid;
jint int_result;
jfloat float_result;
jboolean boolean_result;
jdouble double_result;
jchar char_result;
jobject person_obj;
jclass person_cls;
jstring j_str;
mid = (*env)->GetMethodID(env,cls,"<init>","()V");
if (mid == NULL)
{
return; // 没有无参的构造函数
}
obj = (*env)->NewObject(env,cls,mid);
if (obj == NULL)
{
return; // 内存不足,创建对象失败
}
// 调用Sample2实例的相关实例函数
// 1.带int参数int返回值的函数
mid = (*env)->GetMethodID(env,cls,"intMethod","(I)I");
if (mid == NULL)
{
return; // 找不到int intMethod(int)这个函数
}
int_result = (*env)->CallIntMethod(env,obj,mid,10);
printf("In C Call intMethod:%d\n", int_result);
// 2.带float参数float返回值的函数
mid = (*env)->GetMethodID(env,cls,"floatMethod","(F)F");
if (mid == NULL)
{
return;
}
float_result = (*env)->CallFloatMethod(env,obj,mid,10.5f);
printf("In C Call floatMethod:%.2f\n",float_result);
// 3.double参数和返回值函数
mid = (*env)->GetMethodID(env,cls,"doubleMethod","(D)D");
if (mid == NULL)
{
return;
}
double_result = (*env)->CallDoubleMethod(env,obj,mid,15.5);
printf("In C Call doubleMethod:%.2f\n",double_result);
// 4.booleal参数和返回值函数
mid = (*env)->GetMethodID(env,cls,"booleanMethod","(Z)Z");
if (mid == NULL)
{
return;
}
boolean_result = (*env)->CallBooleanMethod(env,obj,mid,1);
printf("In C Call booleanMethod:%d\n",boolean_result);
// 5.char参数和返回值函数
mid = (*env)->GetMethodID(env,cls,"charMethod","(C)C");
if (mid == NULL)
{
return;
}
char_result = (*env)->CallCharMethod(env,obj,mid,'C');
printf("In C Call charMethod:%c\n",char_result);
// 6.java对象boolean返回值函数
person_cls = (*env)->FindClass(env,"com/study/jnilearn/Person"); // 和方法参数中引用类型的写不支不同,只需要将.换成/就行
if (cls == NULL)
{
return; // 在虚拟机中没有找到com.study.jnilearn.Person这个类
}
mid = (*env)->GetMethodID(env,person_cls,"<init>","()V");
if (mid == NULL)
{
return; // 没有找到构造函数
}
person_obj = (*env)->NewObject(env,person_cls,mid);
if (person_obj == NULL) {
return; // 创建对象失败,内存不足
}
// 封装数据
fid = (*env)->GetFieldID(env,person_cls,"name","Ljava/lang/String;"); // 找到name字段
if (fid == NULL) {
return; // 没有找到name这个字段
}
j_str = (*env)->NewStringUTF(env,"刘备"); // 创建一个unicode字符串
if (j_str == NULL) {
return; // 内存不足
}
(*env)->SetObjectField(env,person_obj,fid,j_str); // 设置对Person对象name字段的值
mid = (*env)->GetMethodID(env,cls,"queryPerson","(Lcom/study/jnilearn/Person;)Z"); // 获取Person类的Class对象
if (mid == NULL)
{
return; // 没有找到boolean queryPerson(com.study.jnilearn.Person p)这个方法
}
boolean_result = (*env)->CallBooleanMethod(env,obj,mid,person_obj); // 调用queryPerson方法,并将jni中创建的person对象传进去
printf("%s person",boolean_result ? "find" : "not find");
}
#ifdef __cplusplus
}
#endif
|
630461866/hhh-shop
|
shop-basic/shop-common/src/main/java/com/qf/dto/TProductAddDTO.java
|
<reponame>630461866/hhh-shop<gh_stars>1-10
package com.qf.dto;
import com.qf.entity.TProduct;
import java.io.Serializable;
public class TProductAddDTO extends TProduct implements Serializable {
private String pdesc;
public String getPdesc() {
return pdesc;
}
public void setPdesc(String pdesc) {
this.pdesc = pdesc;
}
}
|
hhucn/tbus-applications
|
TbusTestAppNT/src/de/hhu/tbus/applications/nt/emergencywarning/message/EmergencyWarningMessage.java
|
/**
*
*/
package de.hhu.tbus.applications.nt.emergencywarning.message;
import java.util.UUID;
import com.dcaiti.vsimrti.rti.objects.v2x.EncodedV2XMessage;
import com.dcaiti.vsimrti.rti.objects.v2x.MessageRouting;
import de.hhu.tbus.applications.nt.geoserver.message.EmbeddedMessage;
import de.hhu.tbus.applications.nt.message.TbusLogMessage;
/**
* @author bialon
*
*/
public class EmergencyWarningMessage extends EmbeddedMessage implements TbusLogMessage {
/**
*
*/
private static final long serialVersionUID = 3051425906236801637L;
/**
* Minimum message length in Byte
*/
private static final int minLength = 40;
private final EncodedV2XMessage encodedMessage;
public enum EmergencyType {
POLICE,
FIRE_BRIGADE,
AMBULANCE,
MILITARY,
OTHER
};
private final EmergencyType emergencyType;
/**
* Constructor inherited by EmbeddedMessage
* @param routing Message routing
* @param timestamp Message original timestamp
* @param timeout Message timeout
*/
public EmergencyWarningMessage(MessageRouting routing, EmergencyType emergencyType, long timestamp, long timeout, UUID uuid) {
super(routing, timestamp, timeout, uuid);
this.emergencyType = emergencyType;
this.encodedMessage = new EncodedV2XMessage(getLength());
}
/**
* @see de.hhu.tbus.applications.nt.geoserver.message.EmbeddedMessage#createEmbeddedMessageWithRoutingAndTimestamp(com.dcaiti.vsimrti.rti.objects.v2x.MessageRouting, long)
*/
@Override
public EmbeddedMessage copy(MessageRouting routing, long timestamp) {
EmbeddedMessage copyMessage = new EmergencyWarningMessage(routing, this.emergencyType, timestamp, this.timeout, this.uuid);
copyMessage.originalTimestamp = this.timestamp;
return copyMessage;
}
/**
* The messages' emergency type
* @return Emergency type
*/
public EmergencyType getEmergencyType() {
return emergencyType;
}
/**
* @see de.hhu.tbus.applications.nt.geoserver.message.EmbeddedMessage#getLength()
*/
@Override
public int getLength() {
// Super length and 1 byte for the enum
int length = super.getLength() + 1;
return (length < minLength) ? minLength : length;
}
/**
* @see com.dcaiti.vsimrti.rti.objects.v2x.V2XMessage#getEncodedV2XMessage()
*/
@Override
public EncodedV2XMessage getEncodedV2XMessage() {
return encodedMessage;
}
public String getLog() {
return this.getClass().getSimpleName() + " id " + getId() + " from (" + super.getLog() + ") emergencyType " + emergencyType.toString();
}
}
|
535205856/summerframework
|
summerframework-lock/platform-lock-database/src/main/java/com/bkjk/platform/lock/database/DatabaseLock.java
|
<filename>summerframework-lock/platform-lock-database/src/main/java/com/bkjk/platform/lock/database/DatabaseLock.java<gh_stars>10-100
package com.bkjk.platform.lock.database;
import javax.sql.DataSource;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
/**
* @Program: summerframework2
* @Description:
* @Author: shaoze.wang
* @Create: 2019/5/16 19:38
**/
public class DatabaseLock implements Lock {
private DataSource dataSource;
private String tableName;
/**
* 要锁定的业务key的表字段名称,合同号、用户号等
*/
private String keyColumnName;
/**
* 备注字段的名称
*/
private String memoColumnName;
/**
* 过期字段的名称
*/
private String expireColumnName;
public static final String lock_sql="update %s set %s = %s where %s =%s";
@Override
public void lock() {
}
@Override
public void lockInterruptibly() throws InterruptedException {
throw new UnsupportedOperationException();
}
@Override
public boolean tryLock() {
return false;
}
@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
return false;
}
@Override
public void unlock() {
}
@Override
public Condition newCondition() {
throw new UnsupportedOperationException();
}
}
|
awatson1978/wcdt-forms
|
webapp/tests/nightwatch/commands/components/reviewHistologyResearchRow.js
|
<reponame>awatson1978/wcdt-forms<filename>webapp/tests/nightwatch/commands/components/reviewHistologyResearchRow.js
/*var histologyResearchRecord = {
sampleId: "",
mutatedGenes: "",
immunohistochemistry: "",
histologyCall: "",
adeno: "",
smallCell: "",
trichotomy: ""
}*/
exports.command = function(histologyResearchRecord, rowIndex) {
this
.verify.elementPresent("table tbody tr")
.verify.elementPresent("table tbody tr:nth-child(" + rowIndex + ")")
if(histologyResearchRecord){
this
.verify.elementPresent("table tbody tr:nth-child(" + rowIndex + ") .Sample_ID")
.verify.elementPresent("table tbody tr:nth-child(" + rowIndex + ") .Histology_Call")
.verify.elementPresent("table tbody tr:nth-child(" + rowIndex + ") .Adeno")
.verify.elementPresent("table tbody tr:nth-child(" + rowIndex + ") .Small_Cell")
.verify.elementPresent("table tbody tr:nth-child(" + rowIndex + ") .Trichotomy")
//.verify.containsText("table tbody tr:nth-child(" + rowIndex + ") .Sample_ID", histologyResearchRecord.sampleId )
.verify.containsText("table tbody tr:nth-child(" + rowIndex + ") .Histology_Call", histologyResearchRecord.histologyCall )
.verify.containsText("table tbody tr:nth-child(" + rowIndex + ") .Adeno", histologyResearchRecord.adeno )
.verify.containsText("table tbody tr:nth-child(" + rowIndex + ") .Small_Cell", histologyResearchRecord.smallCell )
.verify.containsText("table tbody tr:nth-child(" + rowIndex + ") .Trichotomy", histologyResearchRecord.trichotomy )
.verify.elementPresent('button[type="submit"]')
.click('button[type="submit"]').pause(500)
}
return this;
};
|
maxiko/gitlabhq
|
lib/gitlab/auth/otp/strategies/base.rb
|
# frozen_string_literal: true
module Gitlab
module Auth
module Otp
module Strategies
class Base
def initialize(user)
@user = user
end
private
attr_reader :user
def success
{ status: :success }
end
def error(message, http_status = nil)
result = { message: message,
status: :error }
result[:http_status] = http_status if http_status
result
end
end
end
end
end
end
|
fbrandt/Ceva
|
src/test/java/de/felixbrandt/ceva/queue/QueueJobClientControllerTest.java
|
package de.felixbrandt.ceva.queue;
import static org.junit.Assert.assertEquals;
import java.util.LinkedList;
import org.junit.Before;
import org.junit.Test;
import de.felixbrandt.ceva.controller.MockDataSource;
import de.felixbrandt.ceva.controller.MockExecutable;
import de.felixbrandt.ceva.queue.BaseQueueWriter;
import de.felixbrandt.ceva.queue.Job;
import de.felixbrandt.ceva.queue.QueueJobClientController;
public class QueueJobClientControllerTest
{
LinkedList<Job> queue;
QueueJobClientController controller;
@Before
public void setUp () throws Exception
{
queue = new LinkedList<Job>();
controller = new QueueJobClientController(new BaseQueueWriter(queue));
}
@Test
public void testSubmit ()
{
final MockExecutable executable = new MockExecutable();
final MockDataSource source = new MockDataSource();
controller.run(executable, source);
assertEquals(1, queue.size());
assertEquals(executable, queue.get(0).getExecutable());
assertEquals(source, queue.get(0).getSource());
}
}
|
AllanKerr/Services
|
containers/authorization/app/cmd/root.go
|
<reponame>AllanKerr/Services
package cmd
import (
"github.com/spf13/cobra"
"app/oauth2"
"os"
"github.com/sirupsen/logrus"
)
var config *oauth2.Config
var RootCmd = &cobra.Command{
Use: "app",
}
func init() {
// secret used as the key for hashing
secret := os.Getenv("SYSTEM_SECRET")
if secret == "" {
logrus.WithField("secret", secret).Fatal("invalid system secret")
}
// The root client credentials created at startup
clientId := os.Getenv("CLIENT_ID")
clientSecret := os.Getenv("CLIENT_SECRET")
config = oauth2.NewConfig(clientId, clientSecret, nil, nil, []byte(secret))
}
|
fenomenalfunds/fenomenal-funds-frontend
|
components/not-found.js
|
import styles from './../styles/components/not-found.module.scss';
import Link from 'next/link';
const NotFound = ({link, text}) => {
return <div className={styles.notFound}>
<h1>404 <br/> Not Found</h1>
<p>Yeah, well... this is awkward!!! <br/>
We can't find what you are looking for.</p>
<p>
<Link href={`${link ? link : '/'}`}>
<a className="btn">{`${text ? text : 'Go back home'}`}</a>
</Link>
</p>
</div>
}
export default NotFound;
|
simpago/rsnano-node
|
nano/node/rsnano_callbacks.cpp
|
#include <nano/crypto/blake2/blake2.h>
#include <nano/lib/logger_mt.hpp>
#include <nano/lib/rsnano.hpp>
#include <nano/lib/rsnanoutils.hpp>
#include <nano/lib/stream.hpp>
#include <nano/lib/threading.hpp>
#include <nano/lib/tomlconfig.hpp>
#include <nano/node/blockprocessor.hpp>
#include <nano/node/bootstrap/bootstrap.hpp>
#include <nano/node/rsnano_callbacks.hpp>
#include <nano/node/websocket.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <iostream>
int32_t write_u8 (void * stream, const uint8_t value)
{
auto s{ static_cast<nano::stream *> (stream) };
try
{
nano::write<uint8_t> (*s, value);
}
catch (...)
{
return -1;
}
return 0;
}
int32_t write_bytes (void * stream, const uint8_t * value, size_t len)
{
auto s{ static_cast<nano::stream *> (stream) };
try
{
nano::write_bytes_raw (*s, value, len);
}
catch (...)
{
return -1;
}
return 0;
}
int32_t read_u8 (void * stream, uint8_t * value)
{
auto s{ static_cast<nano::stream *> (stream) };
try
{
nano::read<uint8_t> (*s, *value);
}
catch (...)
{
return -1;
}
return 0;
}
int32_t read_bytes (void * stream, uint8_t * buffer, size_t len)
{
auto s{ static_cast<nano::stream *> (stream) };
try
{
if (nano::try_read_raw (*s, buffer, len) != 0)
{
return -1;
}
}
catch (...)
{
return -1;
}
return 0;
}
size_t in_avail (void * stream, int32_t * error)
{
auto s{ static_cast<nano::stream *> (stream) };
try
{
*error = 0;
return s->in_avail ();
}
catch (...)
{
*error = 1;
return 0;
}
}
void ptree_put_string (void * ptree, const char * path, uintptr_t path_len, const char * value, uintptr_t value_len)
{
auto tree (static_cast<boost::property_tree::ptree *> (ptree));
std::string path_str (path, path_len);
std::string value_str (value, value_len);
tree->put (path_str, value_str);
}
void ptree_put_u64 (void * ptree, const char * path, uintptr_t path_len, uint64_t value)
{
auto tree (static_cast<boost::property_tree::ptree *> (ptree));
std::string path_str (path, path_len);
tree->put (path_str, value);
}
void ptree_add (void * ptree, const char * path, uintptr_t path_len, const char * value, uintptr_t value_len)
{
auto tree (static_cast<boost::property_tree::ptree *> (ptree));
std::string path_str (path, path_len);
std::string value_str (value, value_len);
tree->add (path_str, value_str);
}
int32_t ptree_get_string (const void * ptree, const char * path, uintptr_t path_len, char * result, uintptr_t result_size)
{
try
{
auto tree (static_cast<const boost::property_tree::ptree *> (ptree));
std::string path_str (path, path_len);
auto value (tree->get<std::string> (path_str));
if (value.length () >= result_size)
{
return -1;
}
strcpy (result, value.c_str ());
return value.length ();
}
catch (...)
{
return -1;
}
}
void * ptree_create ()
{
return new boost::property_tree::ptree ();
}
void ptree_destroy (void * handle)
{
delete static_cast<boost::property_tree::ptree *> (handle);
}
void ptree_push_back (void * parent_handle, const char * name, const void * child_handle)
{
auto parent_tree{ static_cast<boost::property_tree::ptree *> (parent_handle) };
auto child_tree{ static_cast<const boost::property_tree::ptree *> (child_handle) };
std::string name_l (name);
parent_tree->push_back (std::make_pair (name_l, *child_tree));
}
void ptree_add_child (void * parent_handle, const char * name, const void * child_handle)
{
auto parent_tree{ static_cast<boost::property_tree::ptree *> (parent_handle) };
auto child_tree{ static_cast<const boost::property_tree::ptree *> (child_handle) };
std::string name_l (name);
parent_tree->add_child (name_l, *child_tree);
}
void ptree_put_child (void * parent_handle, const char * name, const void * child_handle)
{
auto parent_tree{ static_cast<boost::property_tree::ptree *> (parent_handle) };
auto child_tree{ static_cast<const boost::property_tree::ptree *> (child_handle) };
std::string name_l (name);
parent_tree->put_child (name_l, *child_tree);
}
void ptree_clear (void * handle)
{
auto tree{ static_cast<boost::property_tree::ptree *> (handle) };
tree->clear ();
}
void * ptree_to_json (void * handle)
{
auto tree{ static_cast<boost::property_tree::ptree *> (handle) };
std::ostringstream sstr;
boost::property_tree::write_json (sstr, *tree);
return new std::string (sstr.str ());
}
const char * string_chars (void * handle)
{
auto s{ static_cast<std::string *> (handle) };
return s->c_str ();
}
void string_delete (void * handle)
{
auto s{ static_cast<std::string *> (handle) };
delete s;
}
int32_t toml_put_u64 (void * toml_a, const uint8_t * key_a, uintptr_t key_len_a, uint64_t value, const uint8_t * documentation_a, uintptr_t documentation_len_a)
{
try
{
auto toml{ static_cast<nano::tomlconfig *> (toml_a) };
std::string key (reinterpret_cast<const char *> (key_a), key_len_a);
std::string documentation (reinterpret_cast<const char *> (documentation_a), documentation_len_a);
toml->put (key, value, documentation.c_str ());
}
catch (...)
{
return -1;
}
return 0;
}
int32_t toml_put_i64 (void * toml_a, const uint8_t * key_a, uintptr_t key_len_a, int64_t value, const uint8_t * documentation_a, uintptr_t documentation_len_a)
{
try
{
auto toml{ static_cast<nano::tomlconfig *> (toml_a) };
std::string key (reinterpret_cast<const char *> (key_a), key_len_a);
std::string documentation (reinterpret_cast<const char *> (documentation_a), documentation_len_a);
toml->put (key, value, documentation.c_str ());
}
catch (...)
{
return -1;
}
return 0;
}
int32_t toml_put_f64 (void * toml_a, const uint8_t * key_a, uintptr_t key_len_a, double value, const uint8_t * documentation_a, uintptr_t documentation_len_a)
{
try
{
auto toml{ static_cast<nano::tomlconfig *> (toml_a) };
std::string key (reinterpret_cast<const char *> (key_a), key_len_a);
std::string documentation (reinterpret_cast<const char *> (documentation_a), documentation_len_a);
toml->put (key, value, documentation.c_str ());
}
catch (...)
{
return -1;
}
return 0;
}
int32_t toml_put_str (void * toml_a, const uint8_t * key_a, uintptr_t key_len_a, const uint8_t * value_a, uintptr_t value_len_a, const uint8_t * documentation_a, uintptr_t documentation_len_a)
{
try
{
auto toml{ static_cast<nano::tomlconfig *> (toml_a) };
std::string key (reinterpret_cast<const char *> (key_a), key_len_a);
std::string documentation (reinterpret_cast<const char *> (documentation_a), documentation_len_a);
std::string value (reinterpret_cast<const char *> (value_a), value_len_a);
toml->put (key, value, documentation.c_str ());
}
catch (...)
{
return -1;
}
return 0;
}
int32_t toml_put_bool (void * toml_a, const uint8_t * key_a, uintptr_t key_len_a, bool value, const uint8_t * documentation_a, uintptr_t documentation_len_a)
{
try
{
auto toml{ static_cast<nano::tomlconfig *> (toml_a) };
std::string key (reinterpret_cast<const char *> (key_a), key_len_a);
std::string documentation (reinterpret_cast<const char *> (documentation_a), documentation_len_a);
toml->put (key, value, documentation.c_str ());
}
catch (...)
{
return -1;
}
return 0;
}
struct TomlArrayHandle
{
TomlArrayHandle (std::shared_ptr<cpptoml::array> ptr_a) :
ptr{ ptr_a }
{
}
std::shared_ptr<cpptoml::array> ptr;
};
void * toml_create_array (void * toml_a, const uint8_t * key_a, uintptr_t key_len_a, const uint8_t * documentation_a, uintptr_t documentation_len_a)
{
try
{
auto toml{ static_cast<nano::tomlconfig *> (toml_a) };
std::string key (reinterpret_cast<const char *> (key_a), key_len_a);
std::string documentation (reinterpret_cast<const char *> (documentation_a), documentation_len_a);
auto arr{ toml->create_array (key, documentation.c_str ()) };
auto result = new TomlArrayHandle (arr);
return result;
}
catch (...)
{
return nullptr;
}
}
void toml_drop_array (void * handle_a)
{
auto handle = reinterpret_cast<TomlArrayHandle *> (handle_a);
delete handle;
}
void toml_array_put_str (void * handle_a, const uint8_t * value_a, uintptr_t value_len)
{
auto handle = reinterpret_cast<TomlArrayHandle *> (handle_a);
std::string val (reinterpret_cast<const char *> (value_a), value_len);
handle->ptr->push_back (val);
}
void * toml_create_config ()
{
return new nano::tomlconfig ();
}
void toml_drop_config (void * handle)
{
delete static_cast<nano::tomlconfig *> (handle);
}
void toml_put_child (void * handle_a, const uint8_t * key_a, uintptr_t key_len_a, void * child_a)
{
auto parent = static_cast<nano::tomlconfig *> (handle_a);
auto child = static_cast<nano::tomlconfig *> (child_a);
std::string key (reinterpret_cast<const char *> (key_a), key_len_a);
parent->put_child (key, *child);
}
bool logger_try_log (void * handle_a, const uint8_t * message_a, size_t len_a)
{
auto logger = static_cast<nano::logger_mt *> (handle_a);
auto message_string = std::string (reinterpret_cast<const char *> (message_a), len_a);
return logger->try_log (message_string);
}
void logger_always_log (void * handle_a, const uint8_t * message_a, size_t len_a)
{
auto logger = static_cast<nano::logger_mt *> (handle_a);
auto message_string = std::string (reinterpret_cast<const char *> (message_a), len_a);
return logger->always_log (message_string);
}
bool listener_broadcast (void * handle_a, rsnano::MessageDto const * message_a)
{
try
{
auto ptree = static_cast<boost::property_tree::ptree const *> (message_a->contents);
nano::websocket::message message_l (static_cast<nano::websocket::topic> (message_a->topic));
message_l.contents = *ptree;
auto listener = static_cast<nano::websocket::listener *> (handle_a);
listener->broadcast (message_l);
return true;
}
catch (...)
{
return false;
}
}
void blockprocessor_add (void * handle_a, rsnano::UncheckedInfoHandle * info_a)
{
auto processor = static_cast<nano::block_processor *> (handle_a);
nano::unchecked_info info{ info_a };
processor->add (info);
}
bool ledger_block_or_pruned_exists (void * handle_a, uint8_t const * block_hash_a)
{
auto ledger{ static_cast<nano::ledger *> (handle_a) };
nano::block_hash hash;
std::copy (block_hash_a, block_hash_a + 32, std::begin (hash.bytes));
return ledger->block_or_pruned_exists (hash);
}
void bootstrap_initiator_clear_pulls (void * handle_a, uint64_t bootstrap_id_a)
{
auto bootstrap_initiator{ static_cast<nano::bootstrap_initiator *> (handle_a) };
bootstrap_initiator->clear_pulls (bootstrap_id_a);
}
class void_fn_callback_wrapper
{
public:
void_fn_callback_wrapper (rsnano::VoidFnCallbackHandle * callback_a) :
callback_m{ callback_a }
{
}
void_fn_callback_wrapper (void_fn_callback_wrapper const &) = delete;
~void_fn_callback_wrapper ()
{
rsnano::rsn_void_fn_callback_destroy (callback_m);
}
void execute ()
{
rsnano::rsn_void_fn_callback_call (callback_m);
}
private:
rsnano::VoidFnCallbackHandle * callback_m;
};
void
add_timed_task (void * handle_a, uint64_t delay_ms, rsnano::VoidFnCallbackHandle * callback_a)
{
auto callback_wrapper {std::make_shared<void_fn_callback_wrapper> (callback_a)};
auto pool{ static_cast<nano::thread_pool *> (handle_a) };
pool->add_timed_task (std::chrono::steady_clock::now () + std::chrono::milliseconds (delay_ms), [callback_wrapper] () {
callback_wrapper->execute ();
});
}
class async_connect_callback_wrapper
{
public:
async_connect_callback_wrapper (rsnano::AsyncConnectCallbackHandle * callback_a) :
callback_m{ callback_a }
{
}
async_connect_callback_wrapper (async_connect_callback_wrapper const &) = delete;
~async_connect_callback_wrapper ()
{
rsnano::rsn_async_connect_callback_destroy (callback_m);
}
void execute (const boost::system::error_code & ec)
{
auto ec_dto{ rsnano::error_code_to_dto (ec) };
rsnano::rsn_async_connect_callback_execute (callback_m, &ec_dto);
}
private:
rsnano::AsyncConnectCallbackHandle * callback_m;
};
void tcp_socket_async_connect (void * handle_a, rsnano::EndpointDto const * endpoint_a, rsnano::AsyncConnectCallbackHandle * callback_a)
{
auto callback_wrapper = std::make_shared<async_connect_callback_wrapper> (callback_a);
auto endpoint{ rsnano::dto_to_endpoint (*endpoint_a) };
auto socket{ static_cast<std::shared_ptr<nano::tcp_socket_facade> *> (handle_a) };
(*socket)->async_connect (endpoint, [callback = std::move (callback_wrapper)] (const boost::system::error_code & ec) {
callback->execute (ec);
});
}
class async_read_callback_wrapper
{
public:
async_read_callback_wrapper (rsnano::AsyncReadCallbackHandle * callback_a) :
callback_m{ callback_a }
{
}
async_read_callback_wrapper (async_read_callback_wrapper const &) = delete;
~async_read_callback_wrapper ()
{
rsnano::rsn_async_read_callback_destroy (callback_m);
}
void execute (const boost::system::error_code & ec, std::size_t size)
{
auto ec_dto{ rsnano::error_code_to_dto (ec) };
rsnano::rsn_async_read_callback_execute (callback_m, &ec_dto, size);
}
private:
rsnano::AsyncReadCallbackHandle * callback_m;
};
void tcp_socket_async_read (void * handle_a, void * buffer_a, std::size_t size_a, rsnano::AsyncReadCallbackHandle * callback_a)
{
auto socket{ static_cast<std::shared_ptr<nano::tcp_socket_facade> *> (handle_a) };
auto buffer{ static_cast<std::shared_ptr<std::vector<uint8_t>> *> (buffer_a) };
auto callback_wrapper{ std::make_shared<async_read_callback_wrapper>(callback_a)};
(*socket)->async_read (*buffer, size_a, [callback_wrapper] (const boost::system::error_code & ec, std::size_t size) {
callback_wrapper->execute(ec, size);
});
}
void tcp_socket_remote_endpoint (void * handle_a, rsnano::EndpointDto * endpoint_a, rsnano::ErrorCodeDto * ec_a)
{
auto socket{ static_cast<std::shared_ptr<nano::tcp_socket_facade> *> (handle_a) };
boost::system::error_code ec;
auto endpoint{ (*socket)->remote_endpoint (ec) };
*endpoint_a = rsnano::endpoint_to_dto (endpoint);
*ec_a = rsnano::error_code_to_dto (ec);
}
void tcp_socket_dispatch (void * handle_a, rsnano::VoidFnCallbackHandle * callback_a)
{
auto socket{ static_cast<std::shared_ptr<nano::tcp_socket_facade> *> (handle_a) };
auto callback_wrapper{ std::make_shared<void_fn_callback_wrapper>(callback_a)};
(*socket)->dispatch ([callback_wrapper] () {
callback_wrapper->execute();
});
}
void tcp_socket_close (void * handle_a, rsnano::ErrorCodeDto * ec_a)
{
auto socket{ static_cast<std::shared_ptr<nano::tcp_socket_facade> *> (handle_a) };
boost::system::error_code ec;
(*socket)->close (ec);
*ec_a = rsnano::error_code_to_dto (ec);
}
void tcp_socket_destroy (void * handle_a)
{
auto ptr{ static_cast<std::shared_ptr<nano::tcp_socket_facade> *> (handle_a) };
delete ptr;
}
void buffer_destroy (void * handle_a)
{
auto ptr{ static_cast<std::shared_ptr<std::vector<uint8_t>> *> (handle_a) };
delete ptr;
}
std::size_t buffer_size (void * handle_a)
{
auto ptr{ static_cast<std::shared_ptr<std::vector<uint8_t>> *> (handle_a) };
return (*ptr)->size ();
}
static bool callbacks_set = false;
void rsnano::set_rsnano_callbacks ()
{
if (callbacks_set)
return;
rsnano::rsn_callback_write_u8 (write_u8);
rsnano::rsn_callback_write_bytes (write_bytes);
rsnano::rsn_callback_read_u8 (read_u8);
rsnano::rsn_callback_read_bytes (read_bytes);
rsnano::rsn_callback_in_avail (in_avail);
rsnano::rsn_callback_blake2b_init (reinterpret_cast<Blake2BInitCallback> (blake2b_init));
rsnano::rsn_callback_blake2b_update (reinterpret_cast<Blake2BUpdateCallback> (blake2b_update));
rsnano::rsn_callback_blake2b_final (reinterpret_cast<Blake2BFinalCallback> (blake2b_final));
rsnano::rsn_callback_property_tree_put_string (ptree_put_string);
rsnano::rsn_callback_property_tree_put_u64 (ptree_put_u64);
rsnano::rsn_callback_property_tree_add (ptree_add);
rsnano::rsn_callback_property_tree_get_string (ptree_get_string);
rsnano::rsn_callback_property_tree_create (ptree_create);
rsnano::rsn_callback_property_tree_destroy (ptree_destroy);
rsnano::rsn_callback_property_tree_push_back (ptree_push_back);
rsnano::rsn_callback_property_tree_add_child (ptree_add_child);
rsnano::rsn_callback_property_tree_put_child (ptree_put_child);
rsnano::rsn_callback_property_tree_clear (ptree_clear);
rsnano::rsn_callback_property_tree_to_json (ptree_to_json);
rsnano::rsn_callback_string_chars (string_chars);
rsnano::rsn_callback_string_delete (string_delete);
rsnano::rsn_callback_toml_put_u64 (toml_put_u64);
rsnano::rsn_callback_toml_put_i64 (toml_put_i64);
rsnano::rsn_callback_toml_put_str (toml_put_str);
rsnano::rsn_callback_toml_put_bool (toml_put_bool);
rsnano::rsn_callback_toml_put_f64 (toml_put_f64);
rsnano::rsn_callback_toml_create_array (toml_create_array);
rsnano::rsn_callback_toml_array_put_str (toml_array_put_str);
rsnano::rsn_callback_toml_create_config (toml_create_config);
rsnano::rsn_callback_toml_drop_config (toml_drop_config);
rsnano::rsn_callback_toml_put_child (toml_put_child);
rsnano::rsn_callback_toml_drop_array (toml_drop_array);
rsnano::rsn_callback_try_log (logger_try_log);
rsnano::rsn_callback_always_log (logger_always_log);
rsnano::rsn_callback_listener_broadcast (listener_broadcast);
rsnano::rsn_callback_block_processor_add (blockprocessor_add);
rsnano::rsn_callback_ledger_block_or_pruned_exists (ledger_block_or_pruned_exists);
rsnano::rsn_callback_block_bootstrap_initiator_clear_pulls (bootstrap_initiator_clear_pulls);
rsnano::rsn_callback_add_timed_task (add_timed_task);
rsnano::rsn_callback_tcp_socket_async_connect (tcp_socket_async_connect);
rsnano::rsn_callback_tcp_socket_async_read (tcp_socket_async_read);
rsnano::rsn_callback_tcp_socket_remote_endpoint (tcp_socket_remote_endpoint);
rsnano::rsn_callback_tcp_socket_dispatch (tcp_socket_dispatch);
rsnano::rsn_callback_tcp_socket_close (tcp_socket_close);
rsnano::rsn_callback_tcp_socket_destroy (tcp_socket_destroy);
rsnano::rsn_callback_buffer_destroy (buffer_destroy);
rsnano::rsn_callback_buffer_size (buffer_size);
callbacks_set = true;
}
|
zerenlu/primer_Cpp
|
chapter10/exercise10_37.cpp
|
#include<iterator>
#include<vector>
#include<algorithm>
#include<list>
#include<iostream>
using namespace std;
int main()
{
vector<int> v_i{ 1,2,3,4,5,6,7,8,9,10 };
list<int> l_i;
copy(v_i.crbegin() + 3, v_i.crend()-2, back_inserter(l_i));
ostream_iterator<int> out(cout, " ");
copy(l_i.cbegin(), l_i.cend(), out);
}
|
prateek-s/mesos
|
3rdparty/aws-sdk-cpp-master/aws-cpp-sdk-redshift/include/aws/redshift/model/EventInfoMap.h
|
/*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/redshift/Redshift_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSStreamFwd.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
namespace Aws
{
namespace Utils
{
namespace Xml
{
class XmlNode;
} // namespace Xml
} // namespace Utils
namespace Redshift
{
namespace Model
{
/**
* <p>Describes event information.</p>
*/
class AWS_REDSHIFT_API EventInfoMap
{
public:
EventInfoMap();
EventInfoMap(const Aws::Utils::Xml::XmlNode& xmlNode);
EventInfoMap& operator=(const Aws::Utils::Xml::XmlNode& xmlNode);
void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const;
void OutputToStream(Aws::OStream& oStream, const char* location) const;
/**
* <p>The identifier of an Amazon Redshift event.</p>
*/
inline const Aws::String& GetEventId() const{ return m_eventId; }
/**
* <p>The identifier of an Amazon Redshift event.</p>
*/
inline void SetEventId(const Aws::String& value) { m_eventIdHasBeenSet = true; m_eventId = value; }
/**
* <p>The identifier of an Amazon Redshift event.</p>
*/
inline void SetEventId(Aws::String&& value) { m_eventIdHasBeenSet = true; m_eventId = value; }
/**
* <p>The identifier of an Amazon Redshift event.</p>
*/
inline void SetEventId(const char* value) { m_eventIdHasBeenSet = true; m_eventId.assign(value); }
/**
* <p>The identifier of an Amazon Redshift event.</p>
*/
inline EventInfoMap& WithEventId(const Aws::String& value) { SetEventId(value); return *this;}
/**
* <p>The identifier of an Amazon Redshift event.</p>
*/
inline EventInfoMap& WithEventId(Aws::String&& value) { SetEventId(value); return *this;}
/**
* <p>The identifier of an Amazon Redshift event.</p>
*/
inline EventInfoMap& WithEventId(const char* value) { SetEventId(value); return *this;}
/**
* <p>The category of an Amazon Redshift event.</p>
*/
inline const Aws::Vector<Aws::String>& GetEventCategories() const{ return m_eventCategories; }
/**
* <p>The category of an Amazon Redshift event.</p>
*/
inline void SetEventCategories(const Aws::Vector<Aws::String>& value) { m_eventCategoriesHasBeenSet = true; m_eventCategories = value; }
/**
* <p>The category of an Amazon Redshift event.</p>
*/
inline void SetEventCategories(Aws::Vector<Aws::String>&& value) { m_eventCategoriesHasBeenSet = true; m_eventCategories = value; }
/**
* <p>The category of an Amazon Redshift event.</p>
*/
inline EventInfoMap& WithEventCategories(const Aws::Vector<Aws::String>& value) { SetEventCategories(value); return *this;}
/**
* <p>The category of an Amazon Redshift event.</p>
*/
inline EventInfoMap& WithEventCategories(Aws::Vector<Aws::String>&& value) { SetEventCategories(value); return *this;}
/**
* <p>The category of an Amazon Redshift event.</p>
*/
inline EventInfoMap& AddEventCategories(const Aws::String& value) { m_eventCategoriesHasBeenSet = true; m_eventCategories.push_back(value); return *this; }
/**
* <p>The category of an Amazon Redshift event.</p>
*/
inline EventInfoMap& AddEventCategories(Aws::String&& value) { m_eventCategoriesHasBeenSet = true; m_eventCategories.push_back(value); return *this; }
/**
* <p>The category of an Amazon Redshift event.</p>
*/
inline EventInfoMap& AddEventCategories(const char* value) { m_eventCategoriesHasBeenSet = true; m_eventCategories.push_back(value); return *this; }
/**
* <p>The description of an Amazon Redshift event.</p>
*/
inline const Aws::String& GetEventDescription() const{ return m_eventDescription; }
/**
* <p>The description of an Amazon Redshift event.</p>
*/
inline void SetEventDescription(const Aws::String& value) { m_eventDescriptionHasBeenSet = true; m_eventDescription = value; }
/**
* <p>The description of an Amazon Redshift event.</p>
*/
inline void SetEventDescription(Aws::String&& value) { m_eventDescriptionHasBeenSet = true; m_eventDescription = value; }
/**
* <p>The description of an Amazon Redshift event.</p>
*/
inline void SetEventDescription(const char* value) { m_eventDescriptionHasBeenSet = true; m_eventDescription.assign(value); }
/**
* <p>The description of an Amazon Redshift event.</p>
*/
inline EventInfoMap& WithEventDescription(const Aws::String& value) { SetEventDescription(value); return *this;}
/**
* <p>The description of an Amazon Redshift event.</p>
*/
inline EventInfoMap& WithEventDescription(Aws::String&& value) { SetEventDescription(value); return *this;}
/**
* <p>The description of an Amazon Redshift event.</p>
*/
inline EventInfoMap& WithEventDescription(const char* value) { SetEventDescription(value); return *this;}
/**
* <p>The severity of the event.</p> <p>Values: ERROR, INFO</p>
*/
inline const Aws::String& GetSeverity() const{ return m_severity; }
/**
* <p>The severity of the event.</p> <p>Values: ERROR, INFO</p>
*/
inline void SetSeverity(const Aws::String& value) { m_severityHasBeenSet = true; m_severity = value; }
/**
* <p>The severity of the event.</p> <p>Values: ERROR, INFO</p>
*/
inline void SetSeverity(Aws::String&& value) { m_severityHasBeenSet = true; m_severity = value; }
/**
* <p>The severity of the event.</p> <p>Values: ERROR, INFO</p>
*/
inline void SetSeverity(const char* value) { m_severityHasBeenSet = true; m_severity.assign(value); }
/**
* <p>The severity of the event.</p> <p>Values: ERROR, INFO</p>
*/
inline EventInfoMap& WithSeverity(const Aws::String& value) { SetSeverity(value); return *this;}
/**
* <p>The severity of the event.</p> <p>Values: ERROR, INFO</p>
*/
inline EventInfoMap& WithSeverity(Aws::String&& value) { SetSeverity(value); return *this;}
/**
* <p>The severity of the event.</p> <p>Values: ERROR, INFO</p>
*/
inline EventInfoMap& WithSeverity(const char* value) { SetSeverity(value); return *this;}
private:
Aws::String m_eventId;
bool m_eventIdHasBeenSet;
Aws::Vector<Aws::String> m_eventCategories;
bool m_eventCategoriesHasBeenSet;
Aws::String m_eventDescription;
bool m_eventDescriptionHasBeenSet;
Aws::String m_severity;
bool m_severityHasBeenSet;
};
} // namespace Model
} // namespace Redshift
} // namespace Aws
|
igorariza/JavaMedicCenterJDBC
|
src/main/java/data/CausasDAO.java
|
package data;
import static data.Conexion.*;
import domain.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class CausasDAO implements IDAO<Causas> {
//para las consultas SQL............
private PreparedStatement insertar = null;
private PreparedStatement eliminar = null;
private PreparedStatement actualizar = null;
private PreparedStatement buscar = null;
private PreparedStatement listar = null;
private Connection conn = null;
private Connection conexionTransaccional;
private static CausasDAO instacia;
public static CausasDAO getInstance() {
if (instacia == null) {
instacia = new CausasDAO();
}
return instacia;
}
public void insertar(Causas entidad) throws SQLException {
String query = "INSERT INTO Causas(codigo, nombre, descripcion) VALUES "
+ "(?,?,?);";
conn = this.conexionTransaccional != null ? this.conexionTransaccional : getConnection();
if (insertar == null) {
insertar = conn.prepareStatement(query);
}
insertar.setString(1, entidad.getCodigo());
insertar.setString(2, entidad.getNombre());
insertar.setString(3, entidad.getDescripcion());
insertar.executeUpdate();
}
public void eliminar(String id) throws SQLException {
String query = "DELETE FROM Causas WHERE codigo = ? ;";
conn = this.conexionTransaccional != null ? this.conexionTransaccional : getConnection();
if (eliminar == null) {
eliminar = conn.prepareStatement(query);
}
eliminar.setString(1, id);
eliminar.executeUpdate();
}
public Causas cargar(ResultSet set) throws SQLException {
Causas Causas = new Causas();
Causas.setCodigo(set.getString("codigo"));
Causas.setNombre(set.getString("nombre"));
Causas.setDescripcion(set.getString("descripcion"));
return Causas;
}
public List<Causas> listar() throws SQLException {
String query = "SELECT *\n"
+ "FROM Causas\n";
conn = this.conexionTransaccional != null ? this.conexionTransaccional : getConnection();
if (listar == null) {
listar = conn.prepareStatement(query);
}
ResultSet set = listar.executeQuery();
ArrayList<Causas> result = new ArrayList<>();
while (set.next()) {
result.add(cargar(set));
}
return result;
}
public Causas buscar(String id) throws SQLException {
String query = "SELECT * \n"
+ "FROM Causas\n"
+ "WHERE Causas.codigo= ? ;";
conn = this.conexionTransaccional != null ? this.conexionTransaccional : getConnection();
if (buscar == null) {
buscar = conn.prepareStatement(query);
}
buscar.setString(1, id);
ResultSet set = buscar.executeQuery();
return set != null && set.next() ? cargar(set) : null;
}
public void actualizar(Causas entidad) throws SQLException {
String query = "UPDATE Causas SET nombre = ?, descripcion = ? WHERE codigo = ?;";
conn = this.conexionTransaccional != null ? this.conexionTransaccional : getConnection();
if (actualizar == null) {
actualizar = conn.prepareStatement(query);
}
actualizar.setString(1, entidad.getNombre());
actualizar.setString(2, entidad.getDescripcion());
actualizar.setString(3, entidad.getCodigo());
actualizar.executeUpdate();
}
}
|
bidhata/EquationGroupLeaks
|
Leak #5 - Lost In Translation/windows/Resources/Pc/PyScripts/Lib/pc/pc/cmd/pcstatus/errors.py
|
# uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: errors.py
import mcl.status
ERR_SUCCESS = mcl.status.MCL_SUCCESS
ERR_INVALID_PARAM = mcl.status.framework.ERR_START
ERR_MARSHAL_FAILED = mcl.status.framework.ERR_START + 1
ERR_FIND_FAILED = mcl.status.framework.ERR_START + 2
ERR_OPEN_FAILED = mcl.status.framework.ERR_START + 3
ERR_READ_FAILED = mcl.status.framework.ERR_START + 4
ERR_DATA_NOT_VALID = mcl.status.framework.ERR_START + 5
errorStrings = {ERR_INVALID_PARAM: 'Invalid parameter(s)',
ERR_MARSHAL_FAILED: 'Failed to marshal data',
ERR_FIND_FAILED: 'Failed to find status from id',
ERR_OPEN_FAILED: 'Failed to open status location',
ERR_READ_FAILED: 'Failed to read data from status location',
ERR_DATA_NOT_VALID: "Status data doesn't match expected format"
}
|
Havunen/karma-jasmine-diff-reporter
|
test/helpers/mark.js
|
<reponame>Havunen/karma-jasmine-diff-reporter<filename>test/helpers/mark.js<gh_stars>10-100
'use strict';
var marker = require('../../src/marker');
module.exports = function mark(string) {
return marker.wrapString(string);
};
|
n-junge/phasar
|
include/phasar/PhasarLLVM/DataFlowSolver/Mono/Problems/InterMonoTaintAnalysis.h
|
<gh_stars>0
/******************************************************************************
* Copyright (c) 2017 <NAME>.
* All rights reserved. This program and the accompanying materials are made
* available under the terms of LICENSE.txt.
*
* Contributors:
* <NAME> and others
*****************************************************************************/
/*
* InterMonoTaintAnalysis.h
*
* Created on: 22.08.2018
* Author: <NAME>
*/
#ifndef PHASAR_PHASARLLVM_MONO_PROBLEMS_INTERMONOTAINTANALYSIS_H_
#define PHASAR_PHASARLLVM_MONO_PROBLEMS_INTERMONOTAINTANALYSIS_H_
#include <map>
#include <set>
#include <string>
#include "phasar/PhasarLLVM/ControlFlow/LLVMBasedICFG.h"
#include "phasar/PhasarLLVM/DataFlowSolver/Mono/InterMonoProblem.h"
#include "phasar/PhasarLLVM/Utils/TaintConfiguration.h"
#include "phasar/Utils/BitVectorSet.h"
namespace llvm {
class Instruction;
class Value;
class Function;
class StructType;
} // namespace llvm
namespace psr {
class LLVMPointsToInfo;
class LLVMTypeHierarchy;
class InterMonoTaintAnalysis
: public InterMonoProblem<const llvm::Instruction *, const llvm::Value *,
const llvm::Function *, const llvm::StructType *,
const llvm::Value *, LLVMBasedICFG> {
private:
const TaintConfiguration<const llvm::Value *> &TSF;
std::map<const llvm::Instruction *, std::set<const llvm::Value *>> Leaks;
public:
typedef const llvm::Instruction *n_t;
typedef const llvm::Value *d_t;
typedef const llvm::Function *f_t;
typedef const llvm::StructType *t_t;
typedef const llvm::Value *v_t;
typedef LLVMBasedICFG i_t;
using ConfigurationTy = TaintConfiguration<const llvm::Value *>;
InterMonoTaintAnalysis(const ProjectIRDB *IRDB, const LLVMTypeHierarchy *TH,
const LLVMBasedICFG *ICF, const LLVMPointsToInfo *PT,
const TaintConfiguration<const llvm::Value *> &TSF,
std::set<std::string> EntryPoints = {});
~InterMonoTaintAnalysis() override = default;
BitVectorSet<const llvm::Value *>
join(const BitVectorSet<const llvm::Value *> &Lhs,
const BitVectorSet<const llvm::Value *> &Rhs) override;
bool sqSubSetEqual(const BitVectorSet<const llvm::Value *> &Lhs,
const BitVectorSet<const llvm::Value *> &Rhs) override;
BitVectorSet<const llvm::Value *>
normalFlow(const llvm::Instruction *Stmt,
const BitVectorSet<const llvm::Value *> &In) override;
BitVectorSet<const llvm::Value *>
callFlow(const llvm::Instruction *CallSite, const llvm::Function *Callee,
const BitVectorSet<const llvm::Value *> &In) override;
BitVectorSet<const llvm::Value *>
returnFlow(const llvm::Instruction *CallSite, const llvm::Function *Callee,
const llvm::Instruction *ExitStmt,
const llvm::Instruction *RetSite,
const BitVectorSet<const llvm::Value *> &In) override;
BitVectorSet<const llvm::Value *>
callToRetFlow(const llvm::Instruction *CallSite,
const llvm::Instruction *RetSite,
std::set<const llvm::Function *> Callees,
const BitVectorSet<const llvm::Value *> &In) override;
std::unordered_map<const llvm::Instruction *,
BitVectorSet<const llvm::Value *>>
initialSeeds() override;
void printNode(std::ostream &os, const llvm::Instruction *n) const override;
void printDataFlowFact(std::ostream &os, const llvm::Value *d) const override;
void printFunction(std::ostream &os, const llvm::Function *m) const override;
const std::map<const llvm::Instruction *, std::set<const llvm::Value *>> &
getAllLeaks() const;
};
} // namespace psr
#endif
|
redcamel/RedRnd
|
~2017/2016/prototype/src/sheet.js
|
<reponame>redcamel/RedRnd
"use strict";
{
let fn
const MATERIAL = RedGL.CONST.MATERIAL
const GEOMETRY = RedGL.CONST.GEOMETRY
// TODO 시트는 음 메쉬의 확장이고
// TODO 맵은 비트맵관련모든것을 쓸 수 있도록 한다.
// TODO 렌더링 설정값은 객체가 먹어야하는군...
class Sheet extends Mesh{
constructor(geometry,material,maxRows = 1,maxCols = 1,totalFrame = 1,startFrame = 0,time = 1,x = 0,y = 0,z = -10){
super(geometry,material,x,y,z)
this.maxRow = maxRows
this.maxCols = maxCols
this.totalFrame = totalFrame
this.startFrame = startFrame
this.time = time
}
set material(v){
this[MATERIAL] = v
}
set geometry(v){
this[GEOMETRY] = v
}
}
RedGL.cls('Sheet',Sheet)
fn = RedGL.Sheet['fn']
}
|
mdavid626/checkers
|
src/src/ija/projekt/game/Log.java
|
<filename>src/src/ija/projekt/game/Log.java
/**
*
*/
package ija.projekt.game;
import ija.projekt.basis.Round;
import ija.projekt.basis.Step;
import java.util.ArrayList;
import java.util.List;
/**
* @author <NAME>
*/
public class Log {
/**
*
*/
protected int n;
/**
*
*/
protected List<Round> rounds;
/**
*
*/
public Log() {
this.n = 0;
this.rounds = new ArrayList<Round>();
}
/**
*
* @param newLog
* @param game
*/
public Log(Log newLog, Game game) {
this();
this.n = newLog.n;
for (Round round : newLog.rounds) {
this.rounds.add(new Round(round, game));
}
}
/**
*
* @param step
* @return
*/
public Round add(Step step) {
Round r = null;
if (rounds.size() > 0) {
r = rounds.get(rounds.size() - 1);
}
if (r != null && r.getStep2() == null) {
r.setStep2(step);
} else {
r = new Round(n);
this.n += 1;
r.setStep1(step);
rounds.add(r);
}
return r;
}
/**
*
*/
public void clear() {
this.n = 0;
this.rounds.clear();
}
/**
*
* @return
*/
public Round getLastRound() {
if (this.rounds != null && this.rounds.size() > 0) {
return this.rounds.get(this.rounds.size() - 1);
}
return null;
}
/**
*
* @return
*/
public Step getLastStep() {
if (this.rounds != null && this.rounds.size() > 0) {
Round round = this.rounds.get(this.rounds.size() - 1);
Step white = round.getStep1();
Step black = round.getStep2();
return black == null ? white : black;
}
return null;
}
/**
*
* @return
*/
public List<Round> getLog() {
return rounds;
}
/**
*
* @return
*/
public List<Step> getSteps() {
List<Step> steps = new ArrayList<Step>();
if (this.rounds != null) {
for (Round round : rounds) {
Step step1 = round.getStep1();
Step step2 = round.getStep2();
if (step1 != null) {
steps.add(step1);
}
if (step2 != null) {
steps.add(step2);
}
}
}
return steps;
}
}
|
devibizsys/unip
|
app_app_pub/src/main/webapp/app/js/common/potalControllerBase.js
|
var potal_db_myworklistBase = IBizListPortlet.extend({
construct: function(config) {
arguments.callee.$.construct.call(this,config);
}
});
var potal_db_tzggBase = IBizListPortlet.extend({
construct: function(config) {
arguments.callee.$.construct.call(this,config);
}
});
var potal_db_qxjtbBase = IBizChartPortlet.extend({
construct: function(config) {
arguments.callee.$.construct.call(this,config);
}
});
var potal_db_ccsqtbBase = IBizChartPortlet.extend({
construct: function(config) {
arguments.callee.$.construct.call(this,config);
}
});
var potalControllerBase = PortalViewControllerBase.extend({
construct: function(config) {
if(!config)config={};
if(!config.appctx)config.appctx='';
if(!config.containerid)config.containerid='';
arguments.callee.$.construct.call(this,this.getDefaultCfg(config));
this.regCodeLists(config);
this.regUICounters(config);
this.regUIActions(config);
this.regUpdatePanels(config);
this.regControllers(config);
}
,regCodeLists:function(config)
{
}
,regUICounters:function(config)
{
}
,regUpdatePanels:function(config)
{
var me=this;
}
,regControllers:function(config)
{
var cid=config.containerid;
if(cid!='')cid=cid+'_';
}
,regUIActions:function(config)
{
}
,getDefaultCfg:function(cfg){
var me=this;
var config={backendurl:cfg.appctx+'/common/potal.do?'+'srfcid='+cfg.containerid+'&'
,viewurl:'/common/potal.jsp?'+'srfcid='+cfg.containerid+'&'
,ctrls:{}};
return $.extend({},config,cfg);
}
,onInit:function(){
arguments.callee.$.onInit.call(this);
this.db_myworklist= new potal_db_myworklist({ctrler:this,id:this.getCId2()+'db_myworklist',refname:'db_myworklist',url:this.getBackendUrl()+'srfctrlid=db_myworklist&',listcfg:{id:this.getCId2()+'db_myworklist_list',refname:'db_myworklist_list',url:this.getBackendUrl()+'srfctrlid=db_myworklist_list&',render: function(items,config){
strContent = '<ul>';
var maxLength = 10;
if(items.length<10){
maxLength = items.length;
}
for(var i=0;i<maxLength;i++){
var createdate = items[i].createdate;
var wfinstancename = "";
if(items[i].wfinstancename){
wfinstancename = items[i].wfinstancename.substring(0,items[i].wfinstancename.indexOf("["));
}
var wfstepname = items[i].wfstepname?items[i].wfstepname:"";
var userdatainfo = items[i].userdatainfo?items[i].userdatainfo:"";
strContent += '<li><a href="../../ibizutil/wfredirectview.jsp?srfkey='+items[i].userdata+'&srfdeid='+items[i].userdata4+'" target="_blank">'+' ['+wfinstancename+'] '+wfstepname+' '+userdatainfo+' '+createdate+'</a></li>';
}
strContent += '</ul>';
return strContent;
}}});
this.db_tzgg= new potal_db_tzgg({ctrler:this,id:this.getCId2()+'db_tzgg',refname:'db_tzgg',url:this.getBackendUrl()+'srfctrlid=db_tzgg&',listcfg:{id:this.getCId2()+'db_tzgg_list',refname:'db_tzgg_list',url:this.getBackendUrl()+'srfctrlid=db_tzgg_list&',render: function(items,config){
strContent = '<ul>';
var maxLength = 10;
if(items.length<10){
maxLength = items.length;
}
for(var i=0;i<maxLength;i++){
var createdate = items[i].createdate;
var tzggname = items[i].tzggname;
var content = items[i].content;
var tzggid = items[i].tzggid;
strContent += '<li><a href="../../jsp/xxtz/oa_tzggeditview.jsp?srfkey='+tzggid+'" target="_blank">'+' '+tzggname+' '+content+' '+createdate+'</a></li>';
}
strContent += '</ul>';
return strContent;
}}});
this.db_qxjtb= new potal_db_qxjtb({ctrler:this,id:this.getCId2()+'db_qxjtb',name:'db_qxjtb',url:this.getBackendUrl()+'srfctrlid=db_qxjtb&',chartcfg:{}});
this.db_qxjtb.chart.load();
this.db_ccsqtb= new potal_db_ccsqtb({ctrler:this,id:this.getCId2()+'db_ccsqtb',name:'db_ccsqtb',url:this.getBackendUrl()+'srfctrlid=db_ccsqtb&',chartcfg:{}});
this.db_ccsqtb.chart.load();
}
});
|
paitoon/netra.ai-client
|
netra/face_detector.py
|
from scipy.spatial import distance as dist
import cv2
import dlib
import imutils
from imutils import face_utils
import logging
from . import shape_predictor_68_model
log = logging.getLogger(__name__)
class FaceDetector:
def __init__(self):
self.detector = dlib.get_frontal_face_detector()
self.predictor = dlib.shape_predictor(shape_predictor_68_model())
# grab the indexes of the facial landmarks for the left and
# right eye, respectively
(self.lStart, self.lEnd) = face_utils.FACIAL_LANDMARKS_IDXS["left_eye"]
(self.rStart, self.rEnd) = face_utils.FACIAL_LANDMARKS_IDXS["right_eye"]
# define two constants, one for the eye aspect ratio to indicate
# blink and then a second constant for the number of consecutive
# frames the eye must be below the threshold
self.EYE_AR_THRESH = 0.22
self.EYE_AR_CONSEC_FRAMES = 3
# initialize the frame counters and the total number of blinks
self.COUNTER = 0
self.TOTAL = 0
def _eye_aspect_ratio(self, eye):
# compute the euclidean distances between the two sets of
# vertical eye landmarks (x, y)-coordinates
A = dist.euclidean(eye[1], eye[5])
B = dist.euclidean(eye[2], eye[4])
# compute the euclidean distance between the horizontal
# eye landmark (x, y)-coordinates
C = dist.euclidean(eye[0], eye[3])
# compute the eye aspect ratio
ear = (A + B) / (2.0 * C)
# return the eye aspect ratio
return ear
def detectEyeBlink(self, image):
image = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# detect faces in the grayscale frame
rects = self.detector(gray, 0)
# loop over the face detections
for rect in rects:
# determine the facial landmarks for the face region, then
# convert the facial landmark (x, y)-coordinates to a NumPy
# array
shape = self.predictor(gray, rect)
shape = face_utils.shape_to_np(shape)
# extract the left and right eye coordinates, then use the
# coordinates to compute the eye aspect ratio for both eyes
leftEye = shape[self.lStart:self.lEnd]
rightEye = shape[self.rStart:self.rEnd]
leftEAR = self._eye_aspect_ratio(leftEye)
rightEAR = self._eye_aspect_ratio(rightEye)
# average the eye aspect ratio together for both eyes
ear = (leftEAR + rightEAR) / 2.0
# compute the convex hull for the left and right eye, then
# visualize each of the eyes
leftEyeHull = cv2.convexHull(leftEye)
rightEyeHull = cv2.convexHull(rightEye)
cv2.drawContours(image, [leftEyeHull], -1, (0, 255, 0), 1)
cv2.drawContours(image, [rightEyeHull], -1, (0, 255, 0), 1)
# check to see if the eye aspect ratio is below the blink
# threshold, and if so, increment the blink frame counter
log.info('ear = {}'.format(ear))
if ear < self.EYE_AR_THRESH:
self.COUNTER += 1
log.info("below threshold count = {}".format(self.COUNTER))
# otherwise, the eye aspect ratio is not below the blink
# threshold
else:
# if the eyes were closed for a sufficient number of
# then increment the total number of blinks
if self.COUNTER >= self.EYE_AR_CONSEC_FRAMES:
self.TOTAL += 1
log.info("ear below threshold more than consequence, count eye blink = {}".format(self.TOTAL))
# reset the eye frame counter
self.COUNTER = 0
# draw the total number of blinks on the frame along with
# the computed eye aspect ratio for the frame
cv2.putText(image, "Blinks: {}".format(self.TOTAL), (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
cv2.putText(image, "EAR: {:.2f}".format(ear), (300, 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
return (image, self.TOTAL)
def resetEyeBlink(self):
self.TOTAL = 0
def detectFace(self, image, oneFace=False):
markedImage = image.copy()
resizedImage = imutils.resize(markedImage, width=320)
r = markedImage.shape[1] / float(resizedImage.shape[1])
gray = cv2.cvtColor(resizedImage, cv2.COLOR_BGR2GRAY)
# detect faces in the grayscale frame
rects = self.detector(gray, 0)
originRects = []
if not oneFace:
status = True
# loop over the face detections
for rect in rects:
left = int(rect.left() * r)
top = int(rect.top() * r)
right = int(rect.right() * r)
bottom = int(rect.bottom() * r)
cv2.rectangle(markedImage, (left, top), (right, bottom), (0, 255, 0), 2)
originRects.append({ 'left': left, 'top': top, 'right': right, 'bottom': bottom })
else:
status = False
if len(rects) > 0:
areas = [(abs(rect.right()-rect.left())*abs(rect.bottom()-rect.top()), rect) for rect in rects]
areas.sort(reverse=True)
log.info('Area = ' + str(areas[0][0]))
color = (0, 0, 255)
if areas[0][0] > 7000:
color = (0, 255, 0)
status = True
rect = areas[0][1]
left = int(rect.left() * r)
top = int(rect.top() * r)
right = int(rect.right() * r)
bottom = int(rect.bottom() * r)
cv2.rectangle(markedImage, (left, top), (right, bottom), color, 2)
originRects = [{'left': left, 'top': top, 'right': right, 'bottom': bottom}]
return markedImage, originRects, status
|
mervin0502/Lizard
|
src/me/mervin/util/PairMap.java
|
package me.mervin.util;
import java.util.HashMap;
public class PairMap<T1,T2> extends HashMap<Pair<T1>, T2> {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
PairMap<Integer, Integer> p = new PairMap<Integer, Integer>();
p.put(new Pair<Integer>(1, 2), 1);
p.put(new Pair<Integer>(1, 2), 2);
p.put(new Pair<Integer>(2, 2), 2);
p.put(new Pair<Integer>(3, 2), 90);
D.p(p.size());
D.p(p.get(new Pair<Integer>(3, 2)));
if(p.containsKey(new Pair<Integer>(3, 2))){
D.m();
}
}
}
|
Batandwa-mgutsi/MyJava
|
assignment2/SumCosts.java
|
import java.util.Scanner;
/**
* Program to calculate the sum of entered amounts.
*
* The user has to enter D or Done to print out the sum.
*/
public class SumCosts {
public static void main(String[] args) {
final Scanner keyboard = new Scanner(System.in);
final Currency rand = new Currency("R", "ZAR", 100);
Money sum = new Money("R0", rand);
boolean quit = false;
do {
System.out.println("Enter an amount or '[D]one' to print the sum and quit:");
final String input = keyboard.nextLine();
if (input.toLowerCase().equals("d") || input.toLowerCase().equals("done")) {
quit = true;
} else if (input.trim().length() != 0) {
final Money amount = new Money(input, rand);
sum = sum.add(amount);
}
} while (!quit);
System.out.printf("Total: %s", sum.toString());
keyboard.close();
}
}
|
open-alchemy/OpenAlchemyPackage
|
api/library/helpers/spec.py
|
<reponame>open-alchemy/OpenAlchemyPackage<gh_stars>0
"""Helpers for spec."""
import dataclasses
import json
import typing
import open_alchemy
import yaml
from open_alchemy import build
from packaging import version as packaging_version
from yaml import parser, scanner
from .. import exceptions, types
TSpec = typing.Dict[str, typing.Any]
def load(*, spec_str: str, language: str) -> TSpec:
"""
Load the spec from a string using a particular language.
Raises LoadSpecError if loading the spec fails.
Args:
spec_str: The string of the spec.
language: The language to use for loading.
Returns:
The loaded spec.
"""
if language == "YAML":
try:
return yaml.safe_load(spec_str)
except (parser.ParserError, scanner.ScannerError) as exc:
raise exceptions.LoadSpecError("body must be valid YAML") from exc
elif language == "JSON":
try:
return json.loads(spec_str)
except json.JSONDecodeError as exc:
raise exceptions.LoadSpecError("body must be valid JSON") from exc
raise exceptions.LoadSpecError(
f"unsupported language {language}, supported languages are JSON and YAML"
)
@dataclasses.dataclass
class TSpecInfo:
"""
Key information about a spec.
Attrs:
spec_str: The spec in string format
version: The version of the spec
title: The title of the spec
description: The description of the spec
model_count: The number of models in the spec
"""
spec_str: types.TSpecValue
version: types.TSpecVersion
title: types.TSpecOptTitle
description: types.TSpecOptDescription
model_count: types.TSpecModelCount
def calc_version(value: types.TSpecVersion) -> str:
"""
Validate the version.
Args:
value: The version to validate.
Returns:
Whether the version is valid.
"""
try:
return packaging_version.Version(value).public
except packaging_version.InvalidVersion:
return str(int.from_bytes(value[0:5].encode(), "big"))
def process(*, spec_str: str, language: str) -> TSpecInfo:
"""
Check that the spec is valid and calculates the version.
Args:
spec_str: The string to process.
language: The language of the spec, either YAML or JSON.
"""
spec = load(spec_str=spec_str, language=language)
try:
schemas = build.get_schemas(spec=spec)
except open_alchemy.exceptions.MalformedSchemaError as exc:
raise exceptions.LoadSpecError(f"the schema is not valid, {exc}") from exc
spec_info = build.calculate_spec_info(schemas=schemas, spec=spec)
version = calc_version(spec_info.version)
model_count = spec_info.spec_str.count('"x-tablename":')
return TSpecInfo(
spec_str=spec_info.spec_str,
version=version,
title=spec_info.title,
description=spec_info.description,
model_count=model_count,
)
def prepare(*, spec_str: str, version: str) -> str:
"""
Prepare a stored spec to be returned to the user.
De-serializes using JSON, adds version and serializes using YAML.
Args:
spec_str: The spec as it is stored.
version: The version of the spec.
Returns:
The spec in a user friendly form.
"""
spec = json.loads(spec_str)
info = {"version": version}
if "info" in spec:
info = {**info, **spec["info"]}
components = spec["components"]
return yaml.dump({"info": info}) + yaml.dump({"components": components})
|
Alx-l/portfolio
|
src/store.js
|
import { Container } from 'unstated'
import lift from 'space-lift'
export class FilterStore extends Container {
state = {
filters: []
}
updateFilters(key) {
const keyIndex = lift(this.state.filters)
.findIndex(k => k === key)
.getOrElse(-1)
this.setState({
filters:
keyIndex > -1
? lift(this.state.filters)
.removeAt(keyIndex)
.value()
: lift(this.state.filters)
.append(key)
.value()
})
}
}
export const filterStore = new FilterStore()
|
jmvallet/viky-ai
|
nlp/sources/ogm_ltras/lib/ltrasmmodule.c
|
/*
* ltrasmmodule.c
*
* Created on: 29 oct. 2014
* Author: caroline
*/
/*
* Handling score structures
* Copyright (c) 2009-2010 Pertimm by <NAME>
* Dev: November 2009, January 2010
* Version 1.0
*/
#include "ogm_ltras.h"
static int LtrasTrfAllocModule(struct og_ctrl_ltras *ctrl_ltras, struct og_ltra_trfs *trfs, struct og_ltra_module **pmodule);
int LtrasAddModule(struct og_ctrl_ltras *ctrl_ltras, struct og_ltra_trfs *trfs, struct og_ltra_trf *trf, int module_id)
{
int Imodule;
struct og_ltra_module *module;
IFE(Imodule = LtrasTrfAllocModule(ctrl_ltras, trfs, &module));
if (trf->start_module < 0)
{
trf->start_module = Imodule;
trf->nb_modules = 1;
}
else trf->nb_modules++;
module->module_id = module_id;
DONE;
}
static int LtrasTrfAllocModule(struct og_ctrl_ltras *ctrl_ltras, struct og_ltra_trfs *trfs, struct og_ltra_module **pmodule)
{
char erreur[DOgErrorSize];
struct og_ltra_module *module = 0;
int i=trfs->ModuleNumber;
beginAllocModule:
if (trfs->ModuleUsed < trfs->ModuleNumber) {
i = trfs->ModuleUsed++;
}
if (i == trfs->ModuleNumber) {
unsigned a, b; struct og_ltra_module *og_trf;
if (ctrl_ltras->loginfo->trace & DOgLtrasTraceMemory) {
OgMsg(ctrl_ltras->hmsg,"",DOgMsgDestInLog
, "AllocModule: max Module number (%d) reached"
, trfs->ModuleNumber);
}
a = trfs->ModuleNumber; b = a + (a>>2) + 1;
IFn(og_trf=(struct og_ltra_module *)malloc(b*sizeof(struct og_ltra_module))) {
sprintf(erreur,"AllocModule: malloc error on Module");
OgErr(ctrl_ltras->herr,erreur); DPcErr;
}
memcpy( og_trf, trfs->Module, a*sizeof(struct og_ltra_module));
DPcFree(trfs->Module); trfs->Module = og_trf;
trfs->ModuleNumber = b;
if (ctrl_ltras->loginfo->trace & DOgLtrasTraceMemory) {
OgMsg(ctrl_ltras->hmsg,"",DOgMsgDestInLog
, "AllocModule: new Module number is %d\n", trfs->ModuleNumber);
}
#ifdef DOgNoMainBufferReallocation
sprintf(erreur,"AllocModule: ModuleNumber reached (%d)",trfs->ModuleNumber);
OgErr(ctrl_ltras->herr,erreur); DPcErr;
#endif
goto beginAllocModule;
}
module = trfs->Module + i;
memset(module,0,sizeof(struct og_ltra_module));
if (pmodule) *pmodule = module;
return(i);
}
|
fake-name/ReadableWebProxy
|
WebMirror/management/rss_parser_funcs/feed_parse_extractYorasuNovels.py
|
<filename>WebMirror/management/rss_parser_funcs/feed_parse_extractYorasuNovels.py
def extractYorasuNovels(item):
"""
Parser for 'Yorasu Novels'
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
if 'Fallen God Records' in item['tags']:
return buildReleaseMessageWithType(item, 'Fallen God Records', vol, chp, frag=frag, postfix=postfix)
if 'Godly Model Creator' in item['tags']:
return buildReleaseMessageWithType(item, 'Godly Model Creator', vol, chp, frag=frag, postfix=postfix)
if 'Super Brain Telekinesis' in item['tags']:
return buildReleaseMessageWithType(item, 'Super Brain Telekinesis', vol, chp, frag=frag, postfix=postfix)
if 'hacker' in item['tags']:
return buildReleaseMessageWithType(item, 'Hacker', vol, chp, frag=frag, postfix=postfix)
return False
|
damienfamed75/gowall
|
cmd/gowall/schemaAdmin.go
|
<filename>cmd/gowall/schemaAdmin.go
package main
import (
"encoding/json"
"github.com/gin-gonic/gin"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"time"
)
type Admin struct {
ID bson.ObjectId `bson:"_id,omitempty" json:"_id"`
User struct {
ID bson.ObjectId `bson:"id,omitempty" json:"id"`
Name string `bson:"name" json:"name"`
} `bson:"user" json:"user"`
Name struct {
First string `bson:"first" json:"first"`
Middle string `bson:"middle" json:"middle"`
Last string `bson:"last" json:"last"`
Full string `bson:"full" json:"full"`
} `bson:"name" json:"name"`
Groups []string `bson:"groups" json:"-"` // drywall author used mutable objects
GroupsJS []AdminGroup `json:"groups" bson:"-"` // I separate types for mongoDB and json
Permissions []Permission `bson:"permissions" json:"permissions"`
TimeCreated time.Time `bson:"timeCreated" json:"timeCreated"`
Search []string `bson:"search" json:"search"`
}
func (u *Admin) Flow() {
}
func (a *Admin) DecodeRequest(c *gin.Context) {
err := json.NewDecoder(c.Request.Body).Decode(a)
if err != nil {
EXCEPTION(err)
}
return
}
func (admin *Admin) HasPermissionTo(requiredPermission string) (hasPermission bool) {
hasPermission = false
//check group permissions
/*
for _, adminGroup := range admin.Groups{
for _, permission := range adminGroup.Permissions{
if permission.Name == requiredPermission {
hasPermission = true
break
}
}
if hasPermission {
break
}
}
*/
//check admin permissions
for _, permission := range admin.Permissions {
if permission.Name == requiredPermission {
if permission.Permit {
return true
}
return false
}
}
return
}
func (admin *Admin) IsMemberOf(groupName string) bool {
for _, group := range admin.Groups {
if group == groupName {
return true
}
}
return false
}
var AdminsIndex mgo.Index = mgo.Index{
Key: []string{"user.id", "search"},
}
func (admin *Admin) linkUser(db *mgo.Database, user *User) (err error) {
// patchUser
collection := db.C(USERS)
err = collection.UpdateId(user.ID, bson.M{
"$set": bson.M{"roles.admin": admin.ID},
})
if err != nil {
if err != mgo.ErrNotFound {
EXCEPTION(err)
}
return
}
// patchAdministrator
collection = db.C(ADMINS)
err = collection.UpdateId(admin.ID, bson.M{
"$set": bson.M{"user": bson.M{
"id": user.ID,
"name": user.Username,
}},
})
if err != nil {
if err != mgo.ErrNotFound {
EXCEPTION(err)
}
return
}
return
}
func (admin *Admin) unlinkUser(db *mgo.Database, user *User) (err error) {
// patchUser
collection := db.C(USERS)
err = collection.Update(bson.M{"roles.admin": user.Roles.Admin}, bson.M{
"$set": bson.M{"roles.admin": ""},
})
if err != nil {
if err != mgo.ErrNotFound {
EXCEPTION(err)
}
return
}
// patchAdministrator
collection = db.C(ADMINS)
err = collection.UpdateId(user.Roles.Admin, bson.M{
"$set": bson.M{"user": bson.M{}},
})
if err != nil {
if err != mgo.ErrNotFound {
EXCEPTION(err)
}
return
}
return
}
func (admin *Admin) populateGroups(db *mgo.Database) (adminGroups []AdminGroup, err error) {
// populateGroups
collection := db.C(ADMINGROUPS)
adminGroups = []AdminGroup{}
err = collection.Find(nil).All(&adminGroups)
if err != nil {
return
}
admin.GroupsJS = []AdminGroup{}
for _, adminGroupID := range admin.Groups {
for _, adminGroup := range adminGroups {
if adminGroupID == adminGroup.ID {
admin.GroupsJS = append(admin.GroupsJS, adminGroup)
}
}
}
return
}
|
kindlychung/mediasoup-sfu-cpp
|
deps/boost/include/boost/predef/language/cuda.h
|
/*
Copyright <NAME> 2018
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_PREDEF_LANGUAGE_CUDA_H
#define BOOST_PREDEF_LANGUAGE_CUDA_H
#include <boost/predef/version_number.h>
#include <boost/predef/make.h>
/* tag::reference[]
= `BOOST_LANG_CUDA`
https://en.wikipedia.org/wiki/CUDA[CUDA C/{CPP}] language.
If available, the version is detected as VV.RR.P.
[options="header"]
|===
| {predef_symbol} | {predef_version}
| `+__CUDACC__+` | {predef_detection}
| `+__CUDA__+` | {predef_detection}
| `CUDA_VERSION` | VV.RR.P
|===
*/ // end::reference[]
#define BOOST_LANG_CUDA BOOST_VERSION_NUMBER_NOT_AVAILABLE
#if defined(__CUDACC__) || defined(__CUDA__)
# undef BOOST_LANG_CUDA
# include <cuda.h>
# if defined(CUDA_VERSION)
# define BOOST_LANG_CUDA BOOST_PREDEF_MAKE_10_VVRRP(CUDA_VERSION)
# else
# define BOOST_LANG_CUDA BOOST_VERSION_NUMBER_AVAILABLE
# endif
#endif
#if BOOST_LANG_CUDA
# define BOOST_LANG_CUDA_AVAILABLE
#endif
#define BOOST_LANG_CUDA_NAME "CUDA C/C++"
#endif
#include <boost/predef/detail/test.h>
BOOST_PREDEF_DECLARE_TEST(BOOST_LANG_CUDA,BOOST_LANG_CUDA_NAME)
|
torodb/mongowp
|
server/src/main/java/com/torodb/mongowp/server/wp/NettyMongoServer.java
|
<reponame>torodb/mongowp<filename>server/src/main/java/com/torodb/mongowp/server/wp/NettyMongoServer.java<gh_stars>10-100
/*
* Copyright 2014 8Kdata Technology
*
* 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.torodb.mongowp.server.wp;
import com.google.common.util.concurrent.AbstractIdleService;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.torodb.mongowp.MongoConstants;
import com.torodb.mongowp.MongoServerConfig;
import com.torodb.mongowp.annotations.MongoWp;
import com.torodb.mongowp.server.util.LengthFieldPrependerLittleEndian;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.nio.ByteOrder;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadFactory;
import javax.inject.Inject;
import javax.inject.Provider;
/**
*
*/
//TODO: Modify this server to be able to stop the thread that runs it
public class NettyMongoServer extends AbstractIdleService {
private static final Logger LOGGER = LogManager.getLogger(NettyMongoServer.class);
private final int port;
private EventLoopGroup connectionGroup;
private EventLoopGroup workerGroup;
private final RequestMessageObjectHandler requestMessageObjectHandler;
private final Provider<RequestMessageByteHandler> requestMessageByteHandler;
private final Provider<ReplyMessageObjectHandler> replyMessageObjectHandler;
private final LengthFieldPrependerLittleEndian lengthFieldPrependerLittleEndian;
private final ThreadFactory threadFactory;
@Inject
public NettyMongoServer(@MongoWp ThreadFactory threadFactory, MongoServerConfig mongoServerConfig,
Provider<RequestMessageByteHandler> requestMessageByteHandler,
Provider<ReplyMessageObjectHandler> replyMessageObjectHandler,
RequestMessageObjectHandler requestMessageObjectHandler) {
this.lengthFieldPrependerLittleEndian = new LengthFieldPrependerLittleEndian(
MongoConstants.MESSAGE_LENGTH_FIELD_BYTES, true);
this.port = mongoServerConfig.getPort();
this.requestMessageByteHandler = requestMessageByteHandler;
this.replyMessageObjectHandler = replyMessageObjectHandler;
this.requestMessageObjectHandler = requestMessageObjectHandler;
this.threadFactory = threadFactory;
}
@Override
protected Executor executor() {
return (Runnable command) -> {
Thread thread = threadFactory.newThread(command);
thread.setName(serviceName() + " " + state());
thread.start();
};
}
private void buildChildHandlerPipeline(ChannelPipeline pipeline) {
pipeline.addLast(new LengthFieldBasedFrameDecoder(
ByteOrder.LITTLE_ENDIAN, MongoConstants.MAX_MESSAGE_SIZE_BYTES, 0,
MongoConstants.MESSAGE_LENGTH_FIELD_BYTES, -MongoConstants.MESSAGE_LENGTH_FIELD_BYTES,
MongoConstants.MESSAGE_LENGTH_FIELD_BYTES, true
));
pipeline.addLast(requestMessageByteHandler.get());
pipeline.addLast(lengthFieldPrependerLittleEndian);
pipeline.addLast(replyMessageObjectHandler.get());
pipeline.addLast(requestMessageObjectHandler);
}
@Override
protected void startUp() throws Exception {
LOGGER.info("Listening MongoDB requests on port " + port);
connectionGroup = new NioEventLoopGroup(0, new ThreadFactoryBuilder().setNameFormat(
"netty-connection-%d").build());
workerGroup = new NioEventLoopGroup(0, new ThreadFactoryBuilder().setNameFormat(
"netty-worker-%d").build());
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(connectionGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
buildChildHandlerPipeline(socketChannel.pipeline());
}
}) // TODO: set TCP channel options?
;
ChannelFuture channelFuture = bootstrap.bind(port).awaitUninterruptibly();
if (!channelFuture.isSuccess()) {
workerGroup.shutdownGracefully();
connectionGroup.shutdownGracefully();
}
}
@Override
protected void shutDown() throws Exception {
LOGGER.debug("Shutting down " + this.getClass().getSimpleName());
if (workerGroup != null) {
workerGroup.shutdownGracefully().syncUninterruptibly();
}
if (connectionGroup != null) {
connectionGroup.shutdownGracefully().syncUninterruptibly();
}
}
public int getPort() {
return port;
}
}
|
mariannehagaseth/CreationToolEcompliance
|
fixture/src/main/java/org/isisaddons/wicket/summernote/fixture/dom/regulation/FreeText.java
|
<filename>fixture/src/main/java/org/isisaddons/wicket/summernote/fixture/dom/regulation/FreeText.java
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.isisaddons.wicket.summernote.fixture.dom.regulation;
//import java.math.BigDecimal;
import com.google.common.collect.Ordering;
import org.apache.isis.applib.DomainObjectContainer;
import org.apache.isis.applib.Identifier;
import org.apache.isis.applib.annotation.*;
import org.apache.isis.applib.services.eventbus.ActionInteractionEvent;
import org.apache.isis.applib.services.eventbus.EventBusService;
import org.apache.isis.applib.services.wrapper.WrapperFactory;
import org.apache.isis.applib.util.ObjectContracts;
import org.apache.isis.applib.util.TitleBuffer;
import org.isisaddons.wicket.summernote.fixture.dom.generated.xml.skos.*;
import org.isisaddons.wicket.summernote.fixture.dom.regulation.Chapter.ChapterAnnex;
import javax.jdo.JDOHelper;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.VersionStrategy;
import java.util.*;
@javax.jdo.annotations.PersistenceCapable(identityType=IdentityType.DATASTORE)
@javax.jdo.annotations.DatastoreIdentity(
strategy=javax.jdo.annotations.IdGeneratorStrategy.IDENTITY,
column="id")
@javax.jdo.annotations.Version(
strategy=VersionStrategy.VERSION_NUMBER,
column="version")
@javax.jdo.annotations.Queries( {
@javax.jdo.annotations.Query(
name = "findByOwnedBy", language = "JDOQL",
value = "SELECT "
+ "FROM org.isisaddons.wicket.summernote.fixture.dom.regulation.FreeText "
+ "WHERE ownedBy == :ownedBy"),
@javax.jdo.annotations.Query(
name = "findFreeTexts", language = "JDOQL",
value = "SELECT "
+ "FROM org.isisaddons.wicket.summernote.fixture.dom.regulation.FreeText "),
@javax.jdo.annotations.Query(
name = "findByOwnedByAndCompleteIsFalse", language = "JDOQL",
value = "SELECT "
+ "FROM org.isisaddons.wicket.summernote.fixture.dom.regulation.FreeText "
+ "WHERE ownedBy == :ownedBy "
+ " && finalized == false")
})
@DomainObject(objectType="FREETEXT",autoCompleteRepository=FreeTexts.class, autoCompleteAction="autoComplete")
// default unless overridden by autoCompleteNXxx() method
@DomainObjectLayout(bookmarking= BookmarkPolicy.AS_ROOT)
@MemberGroupLayout (
columnSpans={6,0,0,6},
left={"Section", "Annotation","List","List of Items","SubSections","Ship Classes (Applicability)","SKOS Terms (Select)", "RDF"},
middle={},
right={})
public class FreeText implements Categorized, Comparable<FreeText> {
//region > LOG
/**
* It isn't common for entities to log, but they can if required.
* Isis uses slf4j API internally (with log4j as implementation), and is the recommended API to use.
*/
private final static org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(FreeText.class);
//endregion
// region > title, icon
public String title() {
final TitleBuffer buf = new TitleBuffer();
if (getRegulationLink().getChapterAnnexArticle().equals(ChapterAnnex.CHAPTER)) {
buf.append("SOLAS CHAPTER ");
}
if (getRegulationLink().getChapterAnnexArticle().equals(ChapterAnnex.ANNEX)) {
buf.append("SOLAS ANNEX ");
}
if (getRegulationLink().getChapterAnnexArticle().equals(ChapterAnnex.DIRECTIVE)) {
buf.append("EU DIRECTIVE ");
}
buf.append(getRegulationLink().getChapterNumber());
if (!getRegulationLink().getPartNumber().equalsIgnoreCase("-")) {
if ((getRegulationLink().getChapterAnnexArticle().equals(ChapterAnnex.CHAPTER)) || (getRegulationLink().getChapterAnnexArticle().equals(ChapterAnnex.ANNEX))) {
buf.append(" PART ");
}
if ((getRegulationLink().getChapterAnnexArticle().equals(ChapterAnnex.DIRECTIVE))) {
buf.append(" TITLE ");
}
}
buf.append(getRegulationLink().getPartNumber());
if (getRegulationLink().getChapterAnnexArticle().equals(ChapterAnnex.CHAPTER)) {
buf.append(" REGULATION ");
}
if (getRegulationLink().getChapterAnnexArticle().equals(ChapterAnnex.ANNEX)) {
buf.append(" CHAPTER ");
}
if (getRegulationLink().getChapterAnnexArticle().equals(ChapterAnnex.DIRECTIVE)) {
buf.append(" ARTICLE ");
}
buf.append(getRegulationLink().getRegulationNumber());
buf.append("SECTION ");
buf.append(getSectionNo());
return buf.toString();
}
//endregion
// Region sectionNo
private String sectionNo;
@javax.jdo.annotations.Column(allowsNull = "false", length = 10)
// @Property(regexPattern="\\w[@&:\\-\\,\\.\\+ \\w]*")
@MemberOrder(name = "Section", sequence = "10")
@PropertyLayout(typicalLength = 10)
public String getSectionNo() {
return sectionNo;
}
public void setSectionNo(final String sectionNo) {
this.sectionNo = sectionNo;
}
public void modifySectionNo(final String sectionNo) {
this.sectionNo = sectionNo;
}
public void clearSectionNo() {
setSectionNo(null);
}
//endregion
// Region plainRegulationText
private String sectionTitle;
@javax.jdo.annotations.Column(allowsNull = "true", length = 100)
@MemberOrder(name = "Section", sequence = "14")
@PropertyLayout(typicalLength = 100, named = "Title")
public String getSectionTitle() {
return sectionTitle;
}
public void setSectionTitle(final String sectionTitle) {
this.sectionTitle = sectionTitle;
}
//endregion
// Region plainRegulationText
private String plainRegulationText;
@javax.jdo.annotations.Column(allowsNull = "true", length = 10000)
@MemberOrder(name = "Section", sequence = "15")
@PropertyLayout(typicalLength = 10000, multiLine = 4, named = "Text")
public String getPlainRegulationText() {
return plainRegulationText;
}
public void setPlainRegulationText(final String plainRegulationText) {
this.plainRegulationText = plainRegulationText;
}
public void modifyPlainRegulationText(final String plainRegulationText) {
setPlainRegulationText(plainRegulationText);
}
public void clearPlainRegulationText() {
setPlainRegulationText(null);
}
//endregion
// BEGIN REGION ANNOTATED TEXT
private String annotatedText;
@javax.jdo.annotations.Column(allowsNull = "true", length = 10000)
@MemberOrder(name = "Annotation", sequence = "10")
@PropertyLayout(typicalLength = 10000, multiLine = 3, hidden = Where.ALL_TABLES)
@Property(editing = Editing.DISABLED, editingDisabledReason = "Update using action that calls an API from the consolidation services")
// @SummernoteEditor(height = 100, maxHeight = 300)
public String getAnnotatedText() {
return annotatedText;
}
public void setAnnotatedText(final String annotatedText) {
this.annotatedText = annotatedText;
}
public void modifyAnnotatedText(final String annotatedText) {
setAnnotatedText(annotatedText);
}
public void clearAnnotatedText() {
setAnnotatedText(null);
}
// END REGION ANNOTATED TEXT
private String skosTerms;
@javax.jdo.annotations.Column(allowsNull = "true", length = 10000)
@MemberOrder(name = "Annotation", sequence = "20")
@PropertyLayout(typicalLength = 10000, multiLine = 3, named = "Terms", hidden = Where.ALL_TABLES)
//@Property(editing = Editing.DISABLED,editingDisabledReason = "Update using action that calls an API from the consolidation services")
public String getSkosTerms() {
return skosTerms;
}
public void setSkosTerms(final String skosTerms) {
this.skosTerms = skosTerms;
}
public void modifySkosTerms(final String skosTerms) {
setSkosTerms(skosTerms);
}
public void clearSkosTerms() {
setSkosTerms(null);
}
@Action()
@ActionLayout(position = ActionLayout.Position.PANEL)
@MemberOrder(name = "Terms", sequence = "20")
public FreeText CheckTerms() {
FragmentSKOSConceptOccurrences fragment = restClient.GetSkos(plainRegulationText);
System.out.println("FREETEXT: fragment OK");
List<String> annotation = new ArrayList<String>();
setSkosTerms(creationController.ShowTerms(plainRegulationText, fragment).get(0));
// SummernoteEditor: setAnnotatedText(creationController.ShowTerms(plainRegulationText, fragment).get(1));
setAnnotatedText(plainRegulationText);
System.out.println("FREETEXT: skosTerms=" + skosTerms);
System.out.println("FREETEXT: annotatedText=" + annotatedText);
container.flush();
container.informUser("Fetched SKOS terms completed for " + container.titleOf(this));
return this;
}
//endregion
//BEGIN show Region target
private String target;
@javax.jdo.annotations.Column(allowsNull = "true", length = 10000)
@MemberOrder(name = "Annotation", sequence = "30")
@PropertyLayout(typicalLength = 10000, multiLine = 3, named = "Target", hidden = Where.ALL_TABLES)
//@Property(editing = Editing.DISABLED,editingDisabledReason = "Update using action that calls an API from the consolidation services")
public String getTarget() {
return target;
}
public void setTarget(final String target) {
this.target = target;
}
public void modifyTarget(final String target) {
setTarget(target);
}
public void clearTarget() {
setTarget(null);
}
//@Action(semantics = SemanticsOf.IDEMPOTENT)
@Action()
// @ActionLayout(named = "Check Terms", position = ActionLayout.Position.PANEL)
@ActionLayout(position = ActionLayout.Position.PANEL)
@MemberOrder(name = "Terms", sequence = "20")
public FreeText ShowTarget() {
ShipClass shipClassFound = null;
// CALLS THE TARGET API
shipClassFound = restClient.GetTarget(plainRegulationText);
// shipClassFound = restClient.GetApplicability(plainRegulationText);
System.out.println("FREETEXT:shipclassfound OK");
setTarget(creationController.ShowShipClass(plainRegulationText, shipClassFound));
System.out.println("FREETEXT: target=" + target);
container.flush();
container.informUser("Fetched Target completed for " + container.titleOf(this));
return this;
}
// END SHOW target
//BEGIN show applicability
private String applicability;
@javax.jdo.annotations.Column(allowsNull = "true", length = 10000)
@MemberOrder(name = "Annotation", sequence = "35")
@PropertyLayout(typicalLength = 10000, multiLine = 3, named = "Applicability", hidden = Where.ALL_TABLES)
//@Property(editing = Editing.DISABLED,editingDisabledReason = "Update using action that calls an API from the consolidation services")
public String getApplicability() {
return applicability;
}
public void setApplicability(final String applicability) {
this.applicability = applicability;
}
public void modifyApplicability(final String applicability) {
setApplicability(applicability);
}
public void clearApplicability() {
setApplicability(null);
}
//@Action(semantics = SemanticsOf.IDEMPOTENT)
@Action()
// @ActionLayout(named = "Check Terms", position = ActionLayout.Position.PANEL)
@ActionLayout(position = ActionLayout.Position.PANEL)
@MemberOrder(name = "Terms", sequence = "30")
public FreeText ShowApplicability() {
ShipClass shipClassFound = null;
// CALLS THE APPLICABILITY API
shipClassFound = restClient.GetApplicability(plainRegulationText);
System.out.println("FREETEXT:applicability shipclassfound OK");
setApplicability(creationController.ShowShipClass(plainRegulationText, shipClassFound));
System.out.println("FREETEXT: applicability=" + applicability);
container.flush();
container.informUser("Fetched Target Ship Class completed for " + container.titleOf(this));
return this;
}
// END SHOW applicability
//region > ownedBy (property)
@javax.jdo.annotations.Persistent(defaultFetchGroup = "true")
private String ownedBy;
@PropertyLayout(hidden = Where.EVERYWHERE)
@ActionLayout(hidden = Where.EVERYWHERE)
@javax.jdo.annotations.Column(allowsNull = "false")
@Property(editing = Editing.DISABLED, editingDisabledReason = "OwnedBy is static")
public String getOwnedBy() {
return ownedBy;
}
@ActionLayout(hidden = Where.EVERYWHERE)
public void setOwnedBy(final String ownedBy) {
this.ownedBy = ownedBy;
}
//endregion
/*
// Add FreeText to SOLASchapter
// department=regulation=SOLASchapter
//empolyee=RegulationRule=FreeText
// mapping is done to this property:
@javax.jdo.annotations.Column(allowsNull="true")
@Property(editing= Editing.DISABLED,editingDisabledReason="SOLAS Chapter cannot be updated from here")
@PropertyLayout(hidden=Where.REFERENCES_PARENT, named = "SOLAS Link")
@MemberOrder(name="Section", sequence="50")
private SolasChapter solasChapter;
@javax.jdo.annotations.Column(allowsNull="true")
public SolasChapter getSolasChapter() { return solasChapter; }
@javax.jdo.annotations.Column(allowsNull="true")
public void setSolasChapter(SolasChapter solasChapter) { this.solasChapter = solasChapter; }
// End Regulation to RegulationRule
*/
// Add FreeText to REGULATION
// mapping is done to this property:
@javax.jdo.annotations.Column(allowsNull = "true")
@Property(editing = Editing.DISABLED, editingDisabledReason = "REGULATION cannot be updated from here")
@PropertyLayout(hidden = Where.REFERENCES_PARENT, named = "Parent Link")
@MemberOrder(name = "Section", sequence = "50")
private Regulation regulationLink;
@javax.jdo.annotations.Column(allowsNull = "true")
public Regulation getRegulationLink() {
return regulationLink;
}
@javax.jdo.annotations.Column(allowsNull = "true")
public void setRegulationLink(Regulation regulationLink) {
this.regulationLink = regulationLink;
}
// End Regulation to RegulationRule
// Region regulationAND
private boolean regulationAND;
@javax.jdo.annotations.Column(allowsNull = "true")
@javax.jdo.annotations.Persistent(defaultFetchGroup = "true")
@PropertyLayout(hidden = Where.ALL_TABLES)
@MemberOrder(name = "List", sequence = "40")
public boolean getRegulationAND() {
return regulationAND;
}
public void setRegulationAND(final boolean regulationAND) {
this.regulationAND = regulationAND;
}
//end region
// BEGIN REGION Link to TextItems, a list of text items.
@javax.jdo.annotations.Persistent(mappedBy = "freeText")
@javax.jdo.annotations.Join // Make a separate join table.
private SortedSet<TextItem> textItems = new TreeSet<TextItem>();
@SuppressWarnings("deprecation")
@CollectionLayout(named = "List of Items", sortedBy = TextItemComparator.class, render = RenderType.EAGERLY)
@MemberOrder(name = "List of Items", sequence = "10")
// @MemberOrder( sequence = "10")
public SortedSet<TextItem> getTextItems() {
return textItems;
}
public void setTextItems(SortedSet<TextItem> textItem) {
this.textItems = textItem;
}
public void removeFromTextItems(final TextItem item) {
if (item == null || !getTextItems().contains(item)) return;
getTextItems().remove(item);
}
// / overrides the natural ordering
public static class TextItemComparator implements Comparator<TextItem> {
int parseInt(String str) {
try{ return Integer.parseInt(str); } catch(Exception ex) { return -1; }
}
@Override
public int compare(TextItem p, TextItem q) {
Ordering<TextItem> byItemNo = new Ordering<TextItem>() {
public int compare(final TextItem p, final TextItem q) {
if ((parseInt(p.getItemNo()) == -1)||(parseInt(q.getItemNo()) == -1)) {
return Ordering.natural().nullsFirst().compare(p.getItemNo(), q.getItemNo());
}
return Ordering.natural().nullsFirst().compare(parseInt(p.getItemNo()),parseInt(q.getItemNo()));
}
};
return byItemNo
.compound(Ordering.<TextItem>natural())
.compare(p, q);
}
}
//This is the add-Button!!!
@Action()
@ActionLayout(named = "Add New Item")
@MemberOrder(name = "List of Items", sequence = "10")
public FreeText addNewTextItem(final @ParameterLayout(typicalLength = 10, named = "Item No") String itemNo,
final @ParameterLayout(typicalLength = 1000, multiLine = 8, named = "Text") String plainRegulationText
) {
getTextItems().add(newTextItemCall.newTextItem(itemNo, plainRegulationText));
return this;
}
//This is the Remove-Button!!
@MemberOrder(name = "List of Items", sequence = "20")
@ActionLayout(named = "Delete Item")
public FreeText removeTextItem(final @ParameterLayout(typicalLength = 30) TextItem item) {
// By wrapping the call, Isis will detect that the collection is modified
// and it will automatically send a CollectionInteractionEvent to the Event Bus.
// ToDoItemSubscriptions is a demo subscriber to this event
wrapperFactory.wrapSkipRules(this).removeFromTextItems(item);
container.removeIfNotAlready(item);
return this;
}
// disable action dependent on state of object
public String disableRemoveTextItem(final TextItem item) {
return getTextItems().isEmpty() ? "No Item to remove" : null;
}
// validate the provided argument prior to invoking action
public String validateRemoveTextItem(final TextItem item) {
if (!getTextItems().contains(item)) {
return "Not an Item";
}
return null;
}
// provide a drop-down
public java.util.Collection<TextItem> choices0RemoveTextItem() {
return getTextItems();
}
//END REGION Link FreeText (Section) --> to (several) TextItems
// BEGIN REGION Link to SubSections
@javax.jdo.annotations.Persistent(mappedBy = "freeTextSection")
@javax.jdo.annotations.Join // Make a separate join table.
@MemberOrder(name = "SubSections", sequence = "20")
private SortedSet<SubSection> subSections = new TreeSet<SubSection>();
@SuppressWarnings("deprecation")
@CollectionLayout(named = "Sub Sections", sortedBy = SubSectionsComparator.class, render = RenderType.EAGERLY)
@MemberOrder(name = "SubSections", sequence = "20")
// @MemberOrder(sequence = "20")
public SortedSet<SubSection> getSubSections() {
return subSections;
}
public void setSubSections(SortedSet<SubSection> subSection) {
this.subSections = subSection;
}
public void removeFromSubSections(final SubSection subSection) {
if (subSection == null || !getSubSections().contains(subSection)) return;
getSubSections().remove(subSection);
}
// / overrides the natural ordering
public static class SubSectionsComparator implements Comparator<SubSection> {
int parseInt(String str) {
try{ return Integer.parseInt(str); } catch(Exception ex) { return -1; }
}
@Override
public int compare(SubSection p, SubSection q) {
Ordering<SubSection> bySubSectionNo = new Ordering<SubSection>() {
public int compare(final SubSection p, final SubSection q) {
if ((parseInt(p.getSubSectionNo()) == -1) || (parseInt(q.getSubSectionNo()) == -1)) {
// This is not a number.
return Ordering.natural().nullsFirst().compare(p.getSubSectionNo(), q.getSubSectionNo());
}
return Ordering.natural().nullsFirst().compare(parseInt(p.getSubSectionNo()), parseInt(q.getSubSectionNo()));
}
};
return bySubSectionNo
.compound(Ordering.<SubSection>natural())
.compare(p, q);
}
}
//This is the add-Button!!!
@Action()
@ActionLayout(named = "Add New SubSection")
@MemberOrder(name = "subSections", sequence = "15")
public FreeText addNewSubSection(final @Parameter(optionality=Optionality.MANDATORY) @ParameterLayout(typicalLength = 10, named = "Sub Section No") String subSectionNo,
final @Parameter(optionality=Optionality.OPTIONAL) @ParameterLayout( typicalLength = 10, named = "Title") String subSectionTitle,
final @Parameter(optionality=Optionality.OPTIONAL) @ParameterLayout(typicalLength = 1000, multiLine = 8, named = "Regulation Text") String plainRegulationText
) {
getSubSections().add(newSubSectionCall.newSubSection(subSectionNo, subSectionTitle, plainRegulationText));
return this;
}
//This is the Remove-Button!!
@MemberOrder(name = "subSections", sequence = "20")
@ActionLayout(named = "Delete SubSection")
public FreeText removeSubSection(final @ParameterLayout(typicalLength = 30) SubSection subSection) {
// By wrapping the call, Isis will detect that the collection is modified
// and it will automatically send a CollectionInteractionEvent to the Event Bus.
// ToDoItemSubscriptions is a demo subscriber to this event
wrapperFactory.wrapSkipRules(this).removeFromSubSections(subSection);
container.removeIfNotAlready(subSection);
return this;
}
// disable action dependent on state of object
public String disableRemoveSubSection(final SubSection subSection) {
return getSubSections().isEmpty() ? "No Text to remove" : null;
}
// validate the provided argument prior to invoking action
public String validateRemoveSubSection(final SubSection subSection) {
if (!getSubSections().contains(subSection)) {
return "Not a SubSection";
}
return null;
}
// provide a drop-down
public java.util.Collection<SubSection> choices0RemoveSubSection() {
return getSubSections();
}
//ENDREGION Link FreeText (Section) --> to (several) SubSections
// BEGIN REGION Link to ShipClassType, a list of ship classes that this text is applicable to.
@javax.jdo.annotations.Persistent(mappedBy = "applicableLink")
@javax.jdo.annotations.Join // Make a separate join table.
private SortedSet<ShipClassType> shipClasses = new TreeSet<ShipClassType>();
@SuppressWarnings("deprecation")
@MemberOrder(name = "Ship Classes (Applicability)", sequence = "90")
// @MemberOrder(sequence = "90")
@CollectionLayout(named = "Ship Classes (Applicability)", sortedBy = ShipClassTypeComparator.class, render = RenderType.EAGERLY)
public SortedSet<ShipClassType> getShipClasses() {
return shipClasses;
}
public void setShipClasses(SortedSet<ShipClassType> shipClass) {
this.shipClasses = shipClass;
}
public void removeFromShipClasses(final ShipClassType shipClass) {
if (shipClass == null || !getShipClasses().contains(shipClass)) return;
getShipClasses().remove(shipClass);
}
// / overrides the natural ordering
public static class ShipClassTypeComparator implements Comparator<ShipClassType> {
@Override
public int compare(ShipClassType p, ShipClassType q) {
Ordering<ShipClassType> byShiptype = new Ordering<ShipClassType>() {
public int compare(final ShipClassType p, final ShipClassType q) {
return Ordering.natural().nullsFirst().compare(p.getType(), q.getType());
}
};
return byShiptype
.compound(Ordering.<ShipClassType>natural())
.compare(p, q);
}
}
// BEGIN fetch Applicability classes.
@Action()
@MemberOrder(name = "Ship Classes (Applicability)", sequence = "60")
@ActionLayout(named = "Fetch")
public FreeText FetchApplicability() {
// SHOW the ship class in the collection:
// CALLS THE TARGET API
ShipClassType newShipClass = null;
ShipClassType shipClassFoundList = null;
// THIS CAN BE CHANGED TO APPLICABILITY, IF NEEDED!!::
shipClassFoundList = restClient.GetShipClass(plainRegulationText);
System.out.println("FetchApplicability:applicability shipclassfoundList OK");
if (!shipClassFoundList.equals(null)){
newShipClass = creationController.ShowFoundShipClass(plainRegulationText, shipClassFoundList);
System.out.println("FetchApplicability: applicability=" + applicability);}
// setShipClasses(null); // Fetch the ship classes each time, so set to null in between/first.
container.flush();
if (!newShipClass.equals(null)) {
if (newShipClass.getType().length() == 0) {
container.warnUser("NO TARGET SHIP CLASS FOUND for " + container.titleOf(this));
} else {
getShipClasses().add(newShipClass);
container.informUser("Fetched Target Ship Class completed for " + container.titleOf(this));
}
}
return this;
}
// END FETCH applicability
//This is the add-Button!!!
@Action()
@MemberOrder(name = "Ship Classes (Applicability)", sequence = "70")
@ActionLayout(named = "Add")
public FreeText addNewShipClassType(
final @Parameter(optionality = Optionality.MANDATORY) @ParameterLayout(typicalLength = 100, named = "Name") String type,
final @Parameter(optionality = Optionality.OPTIONAL) @ParameterLayout(typicalLength = 100, named = "Tonnage >") double minTonnageIn,
final @Parameter(optionality = Optionality.OPTIONAL) @ParameterLayout(typicalLength = 100, named = "Tonnage >=") double minTonnageEx,
final @Parameter(optionality = Optionality.OPTIONAL) @ParameterLayout(typicalLength = 100, named = "Tonnage <") double maxTonnageIn,
final @Parameter(optionality = Optionality.OPTIONAL) @ParameterLayout(typicalLength = 100, named = "Tonnage <= ") double maxTonnageEx,
final @Parameter(optionality = Optionality.OPTIONAL) @ParameterLayout(typicalLength = 100, named = "Length >") double minLengthIn,
final @Parameter(optionality = Optionality.OPTIONAL) @ParameterLayout(typicalLength = 100, named = "Length >=") double minLengthEx,
final @Parameter(optionality = Optionality.OPTIONAL) @ParameterLayout(typicalLength = 100, named = "Length <") double maxLengthIn,
final @Parameter(optionality = Optionality.OPTIONAL) @ParameterLayout(typicalLength = 100, named = "Length <=") double maxLengthEx,
final @Parameter(optionality = Optionality.OPTIONAL) @ParameterLayout(typicalLength = 100, named = "Draught >") double minDraughtIn,
final @Parameter(optionality = Optionality.OPTIONAL) @ParameterLayout(typicalLength = 100, named = "Draught >=") double minDraughtEx,
final @Parameter(optionality = Optionality.OPTIONAL) @ParameterLayout(typicalLength = 100, named = "Draught <") double maxDraughtIn,
final @Parameter(optionality = Optionality.OPTIONAL) @ParameterLayout(typicalLength = 100, named = "Draught <=") double maxDraughtEx,
final @Parameter(optionality = Optionality.OPTIONAL) @ParameterLayout(typicalLength = 100, named = "No of Passengers >") int minPassengersIn,
final @Parameter(optionality = Optionality.OPTIONAL) @ParameterLayout(typicalLength = 100, named = "No of Passengers >=") int minPassengersEx,
final @Parameter(optionality = Optionality.OPTIONAL) @ParameterLayout(typicalLength = 100, named = "No of Passengers <") int maxPassengerIn,
final @Parameter(optionality = Optionality.OPTIONAL) @ParameterLayout(typicalLength = 100, named = "No of Passengers <=") int maxPassengersEx,
final @Parameter(optionality = Optionality.OPTIONAL) @ParameterLayout(typicalLength = 100, named = "Keel Laid Date >") int minKeelLaidIn,
final @Parameter(optionality = Optionality.OPTIONAL) @ParameterLayout(typicalLength = 100, named = "Keel Laid Date >=") int minKeelLaidEx,
final @Parameter(optionality = Optionality.OPTIONAL) @ParameterLayout(typicalLength = 100, named = "Keel Laid Date <") int maxKeelLaidIn,
final @Parameter(optionality = Optionality.OPTIONAL) @ParameterLayout(typicalLength = 100, named = "Keel Laid Date <=") int maxKeelLaidEx,
final @Parameter(optionality = Optionality.OPTIONAL) @ParameterLayout(typicalLength = 100, named = "Length Unit") String lengthUnit,
final @Parameter(optionality = Optionality.OPTIONAL) @ParameterLayout(typicalLength = 100, named = "Tonnage Unit") String tonnageUnit,
final @Parameter(optionality = Optionality.OPTIONAL) @ParameterLayout(typicalLength = 100, named = "Draught Unit") String draughtUnit
) {
getShipClasses().add(newShipClassTypeCall.newShipClassType(
type,
minTonnageIn,
minTonnageEx,
maxTonnageIn,
maxTonnageEx,
minLengthIn,
minLengthEx,
maxLengthIn,
maxLengthEx,
minDraughtIn,
minDraughtEx,
maxDraughtIn,
maxDraughtEx,
minPassengersIn,
minPassengersEx,
maxPassengerIn,
maxPassengersEx,
minKeelLaidIn,
minKeelLaidEx,
maxKeelLaidIn,
maxKeelLaidEx,
lengthUnit,
tonnageUnit,
draughtUnit
)
);
return this;
}
public double default1AddNewShipClassType() {
return 0;
}
public double default2AddNewShipClassType() {
return 0;
}
public double default3AddNewShipClassType() {
return 0;
}
public double default4AddNewShipClassType() {
return 0;
}
public double default5AddNewShipClassType() {
return 0;
}
public double default6AddNewShipClassType() {
return 0;
}
public double default7AddNewShipClassType() {
return 0;
}
public double default8AddNewShipClassType() {
return 0;
}
public double default9AddNewShipClassType() {
return 0;
}
public double default10AddNewShipClassType() {
return 0;
}
public double default11AddNewShipClassType() {
return 0;
}
public double default12AddNewShipClassType() {
return 0;
}
public int default13AddNewShipClassType() {
return 0;
}
public int default14AddNewShipClassType() {
return 0;
}
public int default15AddNewShipClassType() {
return 0;
}
public int default16AddNewShipClassType() {
return 0;
}
public int default17AddNewShipClassType() {
return 0;
}
public int default18AddNewShipClassType() {
return 0;
}
public int default19AddNewShipClassType() {
return 0;
}
public int default20AddNewShipClassType() {
return 0;
}
public String default21AddNewShipClassType() {
return "M";
}
public String default22AddNewShipClassType() {
return "GT";
}
public String default23AddNewShipClassType() {
return "M";
}
@MemberOrder(name = "Ship Classes (Applicability)", sequence = "90")
@ActionLayout(named = "Remove")
public FreeText removeShipClass(final @ParameterLayout(typicalLength = 30) ShipClassType shipClassType) {
wrapperFactory.wrapSkipRules(this).removeFromShipClasses(shipClassType);
container.removeIfNotAlready(shipClassType);
return this;
}
// disable action dependent on state of object
public String disableRemoveShipClass(final ShipClassType shipClassType) {
return getShipClasses().isEmpty() ? "No Ship Classes to remove" : null;
}
// validate the provided argument prior to invoking action
public String validateRemoveShipClass(final ShipClassType shipClassType) {
if (!getShipClasses().contains(shipClassType)) {
return "Not a Ship Class";
}
return null;
}
// provide a drop-down
public java.util.Collection<ShipClassType> choices0RemoveShipClass() {
return getShipClasses();
}
@MemberOrder(name = "Ship Classes (Applicability)", sequence = "80")
@ActionLayout(named = "Update")
public FreeText applicableShipClass() {
// By wrapping the call, Isis will detect that the collection is modified
// and it will automatically send a CollectionInteractionEvent to the Event Bus.
// ToDoItemSubscriptions is a demo subscriber to this event
// Call REST API:
//Create an instance of the interface class
// OntologyInterface oi = new OntologyInterface();
//The create function takes lists of ships as input - in this case, there is only one ship
Set<ShipClass> shipset = new HashSet<ShipClass>();
ShipClass oneShipClass = new ShipClass();
if (getShipClasses().size() == 0) {
// No applicability on this text exists!!
container.warnUser("No target ship class exists for " + container.titleOf(this) + ". You must ADD a ship class before updating the APPLICABILITY of the text.");
}
else
{
Iterator it =getShipClasses().iterator();
while (it.hasNext()) {
ShipClassType thisShipClassType = (ShipClassType) it.next();
// Only handles the first ship type on the list!!
oneShipClass.setType(thisShipClassType.getType());
oneShipClass.setMinTonnageEx(thisShipClassType.getMinTonnageEx());
oneShipClass.setMaxTonnageEx(thisShipClassType.getMaxTonnageEx());
oneShipClass.setMinTonnageIn(thisShipClassType.getMinTonnageIn());
oneShipClass.setMaxTonnageIn(thisShipClassType.getMaxTonnageIn());
oneShipClass.setMinLengthEx(thisShipClassType.getMinLengthEx());
oneShipClass.setMaxLengthEx(thisShipClassType.getMaxLengthEx());
oneShipClass.setMinLengthIn(thisShipClassType.getMinLengthIn());
oneShipClass.setMaxLengthIn(thisShipClassType.getMaxLengthIn());
oneShipClass.setMinDraughtEx(thisShipClassType.getMinDraughtEx());
oneShipClass.setMaxDraughtEx(thisShipClassType.getMaxDraughtEx());
oneShipClass.setMinDraughtIn(thisShipClassType.getMinDraughtIn());
oneShipClass.setMaxDraughtIn(thisShipClassType.getMaxDraughtIn());
oneShipClass.setMinPassengerEx(thisShipClassType.getMinPassengersEx());
oneShipClass.setMaxPassengerEx(thisShipClassType.getMaxPassengersEx());
oneShipClass.setMinPassengerIn(thisShipClassType.getMinPassengersIn());
oneShipClass.setMaxPassengerIn(thisShipClassType.getMaxPassengerIn());
oneShipClass.setMinKeelLaidEx(thisShipClassType.getMinKeelLaidEx());
oneShipClass.setMaxKeelLaidEx(thisShipClassType.getMaxKeelLaidEx());
oneShipClass.setMinKeelLaidIn(thisShipClassType.getMinKeelLaidIn());
oneShipClass.setMaxKeelLaidIn(thisShipClassType.getMaxPassengerIn());
oneShipClass.setLengthUnit(thisShipClassType.getLengthUnit());
oneShipClass.setTonnageUnit(thisShipClassType.getTonnageUnit());
oneShipClass.setDraughtUnit(thisShipClassType.getDraughtUnit());
shipset.add(oneShipClass);
}
container.informUser("APPLICABILITY is updated for regulation " + container.titleOf(this));
}
// CREATE TARGETSHIPCLASS
// PLUS: NEED TO LINK TO THE REGULATION TEXT ITSELF!!
String targetShipClassURI = restClient.CreateTargetShipClass(oneShipClass);
setTargetShipClassURI(targetShipClassURI);
System.out.println("targetShipClassURI has been found!=" + targetShipClassURI);
return this;
}
// disable action dependent on state of object
public String disableApplicableShipClass() {
return getShipClasses().isEmpty()? "No Ship Classes to Update": null;
}
//END REGION Link FreeText (Section) --> to (several) ShipClassTypes (APPLICABILITY)
// BEGIN REGION Link to ShipClassType, a list of ship classes that this text is applicable to.
@javax.jdo.annotations.Persistent(mappedBy = "skosLink")
@javax.jdo.annotations.Join // Make a separate join table.
private SortedSet<SKOS> skoses = new TreeSet<SKOS>();
@SuppressWarnings("deprecation")
@MemberOrder(name = "SKOS Terms (Select)", sequence = "90")
// @MemberOrder(sequence = "90")
@CollectionLayout(named = "SKOS Terms (Select)", sortedBy = SKOSComparator.class, render = RenderType.EAGERLY)
public SortedSet<SKOS> getSkoses() {
return skoses;
}
public void setSkoses(SortedSet<SKOS> skoses) {
this.skoses = skoses;
}
public void removeFromSkoses(final SKOS skos) {
if (skos == null || !getSkoses().contains(skos)) return;
getSkoses().remove(skos);
}
// / overrides the natural ordering
public static class SKOSComparator implements Comparator<SKOS> {
@Override
public int compare(SKOS p, SKOS q) {
Ordering<SKOS> bySkos= new Ordering<SKOS>() {
public int compare(final SKOS p, final SKOS q) {
return Ordering.natural().nullsFirst().compare(p.getUri(), q.getUri());
}
};
return bySkos
.compound(Ordering.<SKOS>natural())
.compare(p, q);
}
}
// BEGIN fetch SKOSs
@Action()
@MemberOrder(name = "SKOS Terms (Select)", sequence = "60")
@ActionLayout(named = "Fetch")
public FreeText FetchSkosShow() {
FragmentSKOSConceptOccurrences fragment = restClient.GetSkos(plainRegulationText);
System.out.println("FREETEXT: fragment OK");
List<SKOS> skosTermList = creationController.ShowSKOSlist(plainRegulationText,fragment);
Iterator it = skosTermList.iterator();
while (it.hasNext()) {
SKOS thisSkos = (SKOS) it.next();
getSkoses().add(thisSkos);
}
container.flush();
container.informUser("SKOS LIST fetched for" + container.titleOf(this));
return this;
}
// END FETCH applicability
@MemberOrder(name = "SKOS Terms (Select)", sequence = "90")
@ActionLayout(named = "Remove")
public FreeText removeSkos(final @ParameterLayout(typicalLength = 30) SKOS skos) {
wrapperFactory.wrapSkipRules(this).removeFromSkoses(skos);
container.removeIfNotAlready(skos);
return this;
}
// disable action dependent on state of object
public String disableRemoveSkos(final SKOS skos) {
return getSkoses().isEmpty() ? "No SKOSs to remove" : null;
}
// validate the provided argument prior to invoking action
public String validateRemoveSkos(final SKOS skos) {
if (!getSkoses().contains(skos)) {
return "Not a SKOS";
}
return null;
}
// BEGIN update SKOSs
@Action()
@MemberOrder(name = "SKOS Terms (Select)", sequence = "80")
@ActionLayout(named = "Update")
public FreeText updateSKOS() {
// CODE IS MISSING HERE to select the actual SKOS term for the text
return this;
}
// disable action dependent on state of object
public String disableUpdateSKOS() {
return getSkoses().isEmpty() ? "No SKOSs to update" : null;
}
// END UPDATE skos
// provide a drop-down
public java.util.Collection<SKOS> choices0RemoveSkos() {
return getSkoses();
}
//END REGION Link Freetext to SKOS list
//region > version (derived property)
@PropertyLayout(hidden=Where.EVERYWHERE)
@ActionLayout(hidden=Where.EVERYWHERE)
public Long getVersionSequence() {
if(!(this instanceof javax.jdo.spi.PersistenceCapable)) {
return null;
}
javax.jdo.spi.PersistenceCapable persistenceCapable = (javax.jdo.spi.PersistenceCapable) this;
final Long version = (Long) JDOHelper.getVersion(persistenceCapable);
return version;}
// hide property (imperatively, based on state of object)
public boolean hideVersionSequence() {
return !(this instanceof javax.jdo.spi.PersistenceCapable);
}
//endregion
//region > id (derived property)
@PropertyLayout(hidden=Where.EVERYWHERE)
@ActionLayout(hidden=Where.EVERYWHERE)
public Long getId() {
if(!(this instanceof javax.jdo.spi.PersistenceCapable)) {
return null;
}
javax.jdo.spi.PersistenceCapable persistenceCapable = (javax.jdo.spi.PersistenceCapable) this;
final Long id = (Long) JDOHelper.getObjectId(persistenceCapable);
return id;
}
// hide property (imperatively, based on state of object)
public boolean hideId() {
return !(this instanceof javax.jdo.spi.PersistenceCapable);
}
//endregion
//region > id (derived property)
@PropertyLayout(hidden=Where.EVERYWHERE)
@ActionLayout(hidden=Where.EVERYWHERE)
public String getIdString() {
if(!(this instanceof javax.jdo.spi.PersistenceCapable)) {
return null;
}
javax.jdo.spi.PersistenceCapable persistenceCapable = (javax.jdo.spi.PersistenceCapable) this;
final String id = (String) JDOHelper.getObjectId(persistenceCapable).toString();
final int indexEnd = id.indexOf("[");
return id.substring(0,indexEnd);
}
// BEGIN REGION SAVE TEXT IN THE RDF GRAPH
// IF SOLAS => CALL ROOT-API TO CREATE ROOT NODE FOR SOLAS
// IF ANNEX => CALL ROOT-API TO CREATE ROOT NODE FOR ANNEX
// IF EU DIR => CALL ROOT-APT TO CREATE ROOT NODE FOR EU DIRECTIVE
// END REGION SAVE TEXT IN THE RDF GRAPH
//region > documentURI (property)
// documentURI contains the URI of the RDF-node storing the text for this chapter-node.
@javax.jdo.annotations.Persistent(defaultFetchGroup="true")
private String documentURI;
@PropertyLayout(hidden=Where.ALL_TABLES)
@MemberOrder(name = "RDF", sequence = "20")
@javax.jdo.annotations.Column(allowsNull="true")
@Property(editing= Editing.DISABLED,editingDisabledReason="Programmatically updated")
public String getDocumentURI() {
return documentURI;
}
@ActionLayout(hidden=Where.EVERYWHERE)
public void setDocumentURI(final String documentURI) {
this.documentURI = documentURI;
}
//endregion
//region > targetShipClassURI (property)
// targetShipClassURI contains the URI of the target ship class for this text in this RDF-node.
@javax.jdo.annotations.Persistent(defaultFetchGroup="true")
private String targetShipClassURI;
@PropertyLayout(hidden=Where.ALL_TABLES)
@MemberOrder(name = "RDF", sequence = "30")
@javax.jdo.annotations.Column(allowsNull="true")
@Property(editing= Editing.DISABLED,editingDisabledReason="Programmatically updated")
public String getTargetShipClassURI() {
return targetShipClassURI;
}
@ActionLayout(hidden=Where.EVERYWHERE)
public void setTargetShipClassURI(final String targetShipClassURI) {
this.targetShipClassURI = targetShipClassURI;
}
//endregion
//region > CREATE RDF node for the FreeTExtSection: (action)
@Action()
@ActionLayout(named = "Make Persistent",position = ActionLayout.Position.PANEL)
@MemberOrder(name="Text", sequence="5")
public FreeText storeFreeText() {
System.out.println("Make Persistent_1");
// Must check if the documentURI has already been stored:
if (getDocumentURI() == null){
System.out.println("DocumentURI not fetched for this Section");
// Must call 192.168.33.10:9000/api/rdf/document/component for this chapter to create a RDF Document for this chapter
DocumentComponentList documentComponentList = new DocumentComponentList();
if (getId() == null) {documentComponentList.setVersion("0");}
else {
documentComponentList.setVersion(getId().toString());
}
// Parent is documentURI of the Chapter:
documentComponentList.setParent(regulationLink.getDocumentURI());
documentComponentList.setComponentType(DocumentComponentType.DOCUMENT);
DocumentComponent documentComponent = new DocumentComponent();
documentComponent.setTitle("SECTION"+" "+getSectionNo());
documentComponent.setShortTitle("SECTION"+" "+getSectionNo());
documentComponent.setText(getPlainRegulationText());
// THIS METHOD is missing:
// documentComponentList.setComponent(documentComponent);
// Need to call the Component API to create the RDF node for the part.
// Will store the value in the documentURI property
IRIList iriList =restClient.CreateDocumentComponentNode(documentComponentList);
// has created the RDF node for only one CHAPTER, that is, only one Node, that is, only one IRI-element:
if (iriList.getIris().size()>0) {
setDocumentURI(iriList.getIris().get(0));
}
else
{setDocumentURI("Could not find URI for RDF");
}
}
else
{
// rootNode is not null, that is, already found.
System.out.println("DocumentURI is already fetched for this = "+getDocumentURI()+".");
}
return this;
}
//endregion
//region > lifecycle callbacks
public void created() {
LOG.debug("lifecycle callback: created: " + this.toString());
}
public void loaded() {
LOG.debug("lifecycle callback: loaded: " + this.toString());
}
public void persisting() {
LOG.debug("lifecycle callback: persisting: " + this.toString());
}
public void persisted() {
LOG.debug("lifecycle callback: persisted: " + this.toString());
}
public void updating() {
LOG.debug("lifecycle callback: updating: " + this.toString());
}
public void updated() {
LOG.debug("lifecycle callback: updated: " + this.toString());
}
public void removing() {
LOG.debug("lifecycle callback: removing: " + this.toString());
}
public void removed() {
LOG.debug("lifecycle callback: removed: " + this.toString());
}
//endregion
//region > events
public static abstract class AbstractActionInteractionEvent extends ActionInteractionEvent<FreeText> {
private static final long serialVersionUID = 1L;
private final String description;
public AbstractActionInteractionEvent(
final String description,
final FreeText source,
final Identifier identifier,
final Object... arguments) {
super(source, identifier, arguments);
this.description = description;
}
public String getEventDescription() {
return description;
}
}
public static class DeletedEvent extends AbstractActionInteractionEvent {
private static final long serialVersionUID = 1L;
public DeletedEvent(
final FreeText source,
final Identifier identifier,
final Object... arguments) {
super("deleted", source, identifier, arguments);
}
}
//endregion
//region > toString, compareTo
@Override
public String toString() {
// return ObjectContracts.toString(this, "description,complete,dueBy,ownedBy");
return ObjectContracts.toString(this, "sectionNo,plainRegulationText, regulationLink, ownedBy");
}
/**
* Required so can store in {@link SortedSet sorted set}s (eg {@link #getDependencies()}).
*/
@Override
public int compareTo(final FreeText other) {
return ObjectContracts.compare(this, other, "sectionNo,plainRegulationText, regulationLink, ownedBy");
}
//endregion
//region > injected services
@javax.inject.Inject
private DomainObjectContainer container;
// @javax.inject.Inject
// private FreeTexts freeTexts;
@javax.inject.Inject
private ShipClassTypes newShipClassTypeCall;
@javax.inject.Inject
private TextItems newTextItemCall;
@javax.inject.Inject
private SubSections newSubSectionCall;
@javax.inject.Inject
private CreationController creationController;
@javax.inject.Inject
private RESTclient restClient;
@SuppressWarnings("deprecation")
Bulk.InteractionContext bulkInteractionContext;
public void injectBulkInteractionContext(@SuppressWarnings("deprecation") Bulk.InteractionContext bulkInteractionContext) {
this.bulkInteractionContext = bulkInteractionContext;
}
@javax.inject.Inject
// private Scratchpad scratchpad;
EventBusService eventBusService;
public void injectEventBusService(EventBusService eventBusService) {
this.eventBusService = eventBusService;
}
@javax.inject.Inject
private WrapperFactory wrapperFactory;
//endregion
}
|
zhxie/Takos
|
src/models/Player.js
|
import Base from './Base';
import { Gear } from './Gear';
import Salmoniod from './Salmoniod';
import { Weapon } from './Weapon';
class Species {
constructor(name, value) {
this.name = name;
this.value = value;
}
static parse = (name) => {
switch (name) {
case 'inklings':
return Species.inklings;
case 'octolings':
return Species.octolings;
default:
throw new RangeError();
}
};
static deserialize = (data) => {
switch (parseInt(data.value)) {
case 0:
return Species.inklings;
case 1:
return Species.octolings;
default:
throw new RangeError();
}
};
}
Species.inklings = new Species('species.inklings', 0);
Species.octolings = new Species('species.octolings', 1);
Object.freeze(Species);
class Style {
constructor(name, value) {
this.name = name;
this.value = value;
}
static parse = (name) => {
switch (name) {
case 'girl':
return Style.girl;
case 'boy':
return Style.boy;
default:
throw new RangeError();
}
};
static deserialize = (data) => {
switch (parseInt(data.value)) {
case 0:
return Style.girl;
case 1:
return Style.boy;
default:
throw new RangeError();
}
};
}
Style.girl = new Style('style.girl', 0);
Style.boy = new Style('style.boy', 1);
Object.freeze(Style);
class PlayerType {
constructor(name, value) {
this.name = name;
this.value = value;
}
}
PlayerType.regularBattle = new PlayerType('player.regular_battle', 0);
PlayerType.rankedBattle = new PlayerType('player.ranked_battle', 1);
PlayerType.salmonRun = new PlayerType('player.salmon_run', 2);
class Player extends Base {
constructor(e, type, id, nickname, species, style, isSelf) {
super(e, null);
this.type = type;
this.id = id;
this.nickname = nickname;
this.species = species;
this.style = style;
this.isSelf = isSelf;
}
}
class Rank {
constructor(name, shortName, value) {
this.name = name;
this.shortName = shortName;
this.value = value;
}
static parse = (data) => {
if (data.name === null) {
return Rank.cMinus;
}
switch (data.name) {
case 'C-':
return Rank.cMinus;
case 'C':
return Rank.c;
case 'C+':
return Rank.cPlus;
case 'B-':
return Rank.bMinus;
case 'B':
return Rank.b;
case 'B+':
return Rank.bPlus;
case 'A-':
return Rank.aMinus;
case 'A':
return Rank.a;
case 'A+':
return Rank.aPlus;
case 'S':
return Rank.s;
case 'S+':
if (data.s_plus_number === null) {
return Rank.sPlus;
}
switch (parseInt(data.s_plus_number)) {
case 0:
return Rank.sPlus0;
case 1:
return Rank.sPlus1;
case 2:
return Rank.sPlus2;
case 3:
return Rank.sPlus3;
case 4:
return Rank.sPlus4;
case 5:
return Rank.sPlus5;
case 6:
return Rank.sPlus6;
case 7:
return Rank.sPlus7;
case 8:
return Rank.sPlus8;
case 9:
return Rank.sPlus9;
default:
throw new RangeError();
}
case 'X':
return Rank.x;
default:
throw new RangeError();
}
};
static deserialize = (data) => {
switch (data.value) {
case 0:
return Rank.cMinus;
case 1:
return Rank.c;
case 2:
return Rank.cPlus;
case 3:
return Rank.bMinus;
case 4:
return Rank.b;
case 5:
return Rank.bPlus;
case 6:
return Rank.aMinus;
case 7:
return Rank.a;
case 8:
return Rank.aPlus;
case 9:
return Rank.s;
case 10:
return Rank.sPlus;
case 11:
return Rank.sPlus0;
case 12:
return Rank.sPlus1;
case 13:
return Rank.sPlus2;
case 14:
return Rank.sPlus3;
case 15:
return Rank.sPlus4;
case 16:
return Rank.sPlus5;
case 17:
return Rank.sPlus6;
case 18:
return Rank.sPlus7;
case 19:
return Rank.sPlus8;
case 20:
return Rank.sPlus9;
case 21:
return Rank.x;
default:
throw new RangeError();
}
};
}
Rank.cMinus = new Rank('rank.c-', 'rank.c-', 0);
Rank.c = new Rank('rank.c', 'rank.c', 1);
Rank.cPlus = new Rank('rank.c+', 'rank.c+', 2);
Rank.bMinus = new Rank('rank.b-', 'rank.b-', 3);
Rank.b = new Rank('rank.b', 'rank.b', 4);
Rank.bPlus = new Rank('rank.b+', 'rank.b+', 5);
Rank.aMinus = new Rank('rank.a-', 'rank.a-', 6);
Rank.a = new Rank('rank.a', 'rank.a', 7);
Rank.aPlus = new Rank('rank.a+', 'rank.a+', 8);
Rank.s = new Rank('rank.s', 'rank.s', 9);
Rank.sPlus = new Rank('rank.s+', 'rank.s+', 10);
Rank.sPlus0 = new Rank('rank.s+0', 'rank.s+', 11);
Rank.sPlus1 = new Rank('rank.s+1', 'rank.s+', 12);
Rank.sPlus2 = new Rank('rank.s+2', 'rank.s+', 13);
Rank.sPlus3 = new Rank('rank.s+3', 'rank.s+', 14);
Rank.sPlus4 = new Rank('rank.s+4', 'rank.s+', 15);
Rank.sPlus5 = new Rank('rank.s+5', 'rank.s+', 16);
Rank.sPlus6 = new Rank('rank.s+6', 'rank.s+', 17);
Rank.sPlus7 = new Rank('rank.s+7', 'rank.s+', 18);
Rank.sPlus8 = new Rank('rank.s+8', 'rank.s+', 19);
Rank.sPlus9 = new Rank('rank.s+9', 'rank.s+', 20);
Rank.x = new Rank('rank.x', 'rank.x', 21);
Object.freeze(Rank);
class BattlePlayer extends Player {
constructor(
e,
type,
id,
nickname,
species,
style,
isSelf,
level,
headgearGear,
clothesGear,
shoesGear,
weapon,
paint,
kill,
assist,
death,
special,
sort
) {
super(e, type, id, nickname, species, style, isSelf);
this.level = level;
this.headgearGear = headgearGear;
this.clothesGear = clothesGear;
this.shoesGear = shoesGear;
this.weapon = weapon;
this.paint = paint;
this.kill = kill;
this.assist = assist;
this.death = death;
this.special = special;
this.sort = sort;
}
get killAndAssist() {
return this.kill + this.assist;
}
get islevelWithStar() {
return this.level > 99;
}
get levelWithStar() {
return this.level - this.star * 100;
}
get star() {
return parseInt(this.level / 100);
}
get isDisconnect() {
return this.paint === 0;
}
static parse = (data, isSelf) => {
try {
const species = Species.parse(data.player.player_type.species);
const style = Style.parse(data.player.player_type.style);
const level = parseInt(data.player.player_rank) + 100 * parseInt(data.player.star_rank);
const headgearGear = Gear.parseHeadgear(data.player.head, data.player.head_skills);
if (headgearGear.error !== null) {
// Handle previous error
return new RegularBattlePlayer(headgearGear.error);
}
const clothesGear = Gear.parseClothes(data.player.clothes, data.player.clothes_skills);
if (clothesGear.error !== null) {
// Handle previous error
return new RegularBattlePlayer(clothesGear.error);
}
const shoesGear = Gear.parseShoes(data.player.shoes, data.player.shoes_skills);
if (shoesGear.error !== null) {
// Handle previous error
return new RegularBattlePlayer(shoesGear.error);
}
const weapon = Weapon.parse(data.player.weapon);
if (weapon.error !== null) {
// Handle previous error
return new RegularBattlePlayer(weapon.error);
}
const paint = parseInt(data.game_paint_point);
const kill = parseInt(data.kill_count);
const assist = parseInt(data.assist_count);
const death = parseInt(data.death_count);
const special = parseInt(data.special_count);
const sort = parseInt(data.sort_score);
if (data.player.udemae === undefined || data.player.udemae === null) {
// Regular battle
return new RegularBattlePlayer(
null,
data.player.principal_id,
data.player.nickname,
species,
style,
isSelf,
level,
headgearGear,
clothesGear,
shoesGear,
weapon,
paint,
kill,
assist,
death,
special,
sort
);
} else {
// Ranked battle
const rank = Rank.parse(data.player.udemae);
return new RankedBattlePlayer(
null,
data.player.principal_id,
data.player.nickname,
species,
style,
isSelf,
level,
rank,
headgearGear,
clothesGear,
shoesGear,
weapon,
paint,
kill,
assist,
death,
special,
sort
);
}
} catch (e) {
console.error(e);
return new BattlePlayer('can_not_parse_player');
}
};
static deserialize = (data) => {
try {
const species = Species.deserialize(data.species);
const style = Style.deserialize(data.style);
const level = parseInt(data.level);
const headgearGear = Gear.deserializeHeadgear(data.headgearGear);
if (headgearGear.error !== null) {
// Handle previous error
return new BattlePlayer(headgearGear.error);
}
const clothesGear = Gear.deserializeClothes(data.clothesGear);
if (clothesGear.error !== null) {
// Handle previous error
return new BattlePlayer(clothesGear.error);
}
const shoesGear = Gear.deserializeShoes(data.shoesGear);
if (shoesGear.error !== null) {
// Handle previous error
return new BattlePlayer(shoesGear.error);
}
const weapon = Weapon.deserialize(data.weapon);
if (weapon.error !== null) {
// Handle previous error
return new BattlePlayer(weapon.error);
}
const paint = parseInt(data.paint);
const kill = parseInt(data.kill);
const assist = parseInt(data.assist);
const death = parseInt(data.death);
const special = parseInt(data.special);
const sort = parseInt(data.sort);
if (data.rank === undefined || data.rank === null) {
// Regular battle
return new RegularBattlePlayer(
null,
data.id,
data.nickname,
species,
style,
data.isSelf,
level,
headgearGear,
clothesGear,
shoesGear,
weapon,
paint,
kill,
assist,
death,
special,
sort
);
} else {
const rank = Rank.deserialize(data.rank);
return new RankedBattlePlayer(
null,
data.id,
data.nickname,
species,
style,
data.isSelf,
level,
rank,
headgearGear,
clothesGear,
shoesGear,
weapon,
paint,
kill,
assist,
death,
special,
sort
);
}
} catch (e) {
console.error(e);
return new BattlePlayer('can_not_deserialize_player');
}
};
}
class RegularBattlePlayer extends BattlePlayer {
constructor(
e,
id,
nickname,
species,
style,
isSelf,
level,
headgearGear,
clothesGear,
shoesGear,
weapon,
paint,
kill,
assist,
death,
special,
sort
) {
super(
e,
PlayerType.regularBattle,
id,
nickname,
species,
style,
isSelf,
level,
headgearGear,
clothesGear,
shoesGear,
weapon,
paint,
kill,
assist,
death,
special,
sort
);
}
}
class RankedBattlePlayer extends BattlePlayer {
constructor(
e,
id,
nickname,
species,
style,
isSelf,
level,
rank,
headgearGear,
clothesGear,
shoesGear,
weapon,
paint,
kill,
assist,
death,
special,
sort
) {
super(
e,
PlayerType.rankedBattle,
id,
nickname,
species,
style,
isSelf,
level,
headgearGear,
clothesGear,
shoesGear,
weapon,
paint,
kill,
assist,
death,
special,
sort
);
this.rank = rank;
}
}
class Grade {
constructor(name, value) {
this.name = name;
this.value = value;
}
static parse = (id) => {
switch (id) {
case 0:
return Grade.intern;
case 1:
return Grade.apprentice;
case 2:
return Grade.partTimer;
case 3:
return Grade.goGetter;
case 4:
return Grade.overachiever;
case 5:
return Grade.professional;
default:
throw new RangeError();
}
};
}
Grade.intern = new Grade('grade.intern', 0);
Grade.apprentice = new Grade('grade.apprentice', 1);
Grade.partTimer = new Grade('grade.part_timer', 2);
Grade.goGetter = new Grade('grade.go_getter', 3);
Grade.overachiever = new Grade('grade.overachiever', 4);
Grade.professional = new Grade('grade.professional', 5);
class JobPlayer extends Player {
constructor(
e,
id,
nickname,
species,
style,
isSelf,
weapons,
specialWeapon,
specialCounts,
bossSalmoniodKills,
goldenEgg,
powerEgg,
help,
death
) {
super(e, PlayerType.salmonRun, id, nickname, species, style, isSelf);
this.weapons = weapons;
this.specialWeapon = specialWeapon;
this.specialCounts = specialCounts;
this.bossSalmoniodKills = bossSalmoniodKills;
this.goldenEgg = goldenEgg;
this.powerEgg = powerEgg;
this.help = help;
this.death = death;
}
get specialRemained() {
let used = 0;
this.specialCounts.forEach((element) => {
used = used + element;
});
return 2 - used;
}
get kill() {
let kill = 0;
this.bossSalmoniodKills.forEach((element) => {
kill = kill + element.kill;
});
return kill;
}
static parse = (data, isSelf) => {
try {
let weapons = [];
data.weapon_list.forEach((element) => {
weapons.push(Weapon.parseSalmonRunMain(element));
});
weapons.forEach((element) => {
if (element.error !== null) {
// Handle previous error
return new JobPlayer(element.error);
}
});
const specialWeapon = Weapon.parseSalmonRunSpecial(data.special);
if (specialWeapon.error !== null) {
// Handle previous error
return new JobPlayer(specialWeapon.error);
}
let specialCounts = [];
data.special_counts.forEach((element) => {
specialCounts.push(parseInt(element));
});
let bossSalmoniodKills = [];
Object.keys(data.boss_kill_counts).forEach((element) => {
let bossSalmoniodKill = {};
try {
bossSalmoniodKill.salmoniod = Salmoniod.parse(parseInt(element));
bossSalmoniodKill.kill = parseInt(data.boss_kill_counts[element].count);
bossSalmoniodKills.push(bossSalmoniodKill);
} catch (e) {
console.error(e);
return new JobPlayer('can_not_parse_player');
}
});
return new JobPlayer(
null,
data.pid,
data.name,
Species.parse(data.player_type.species),
Style.parse(data.player_type.style),
isSelf,
weapons,
specialWeapon,
specialCounts,
bossSalmoniodKills,
parseInt(data.golden_ikura_num),
parseInt(data.ikura_num),
parseInt(data.help_count),
parseInt(data.dead_count)
);
} catch (e) {
console.error(e);
return new JobPlayer('can_not_parse_player');
}
};
static deserialize = (data) => {
try {
let weapons = [];
data.weapons.forEach((element) => {
weapons.push(Weapon.deserializeSalmonRunMain(element));
});
weapons.forEach((element) => {
if (element.error !== null) {
// Handle previous error
return new JobPlayer(element.error);
}
});
const specialWeapon = Weapon.deserializeSalmonRunSpecial(data.specialWeapon);
if (specialWeapon.error !== null) {
// Handle previous error
return new JobPlayer(specialWeapon.error);
}
let specialCounts = [];
data.specialCounts.forEach((element) => {
specialCounts.push(parseInt(element));
});
let bossSalmoniodKills = [];
data.bossSalmoniodKills.forEach((element) => {
let bossSalmoniodKill = {};
try {
bossSalmoniodKill.salmoniod = Salmoniod.parse(parseInt(element.salmoniod.value));
bossSalmoniodKill.kill = parseInt(element.kill);
bossSalmoniodKills.push(bossSalmoniodKill);
} catch (e) {
console.error(e);
return new JobPlayer('can_not_deserialize_player');
}
});
return new JobPlayer(
null,
data.id,
data.nickname,
Species.deserialize(data.species),
Style.deserialize(data.style),
data.isSelf,
weapons,
specialWeapon,
specialCounts,
bossSalmoniodKills,
parseInt(data.goldenEgg),
parseInt(data.powerEgg),
parseInt(data.help),
parseInt(data.death)
);
} catch (e) {
console.error(e);
return new JobPlayer('can_not_deserialize_player');
}
};
}
export {
Species,
Style,
PlayerType,
Player,
Rank,
BattlePlayer,
RegularBattlePlayer,
RankedBattlePlayer,
Grade,
JobPlayer
};
|
subchen/go-stack
|
data/query.go
|
<filename>data/query.go
package data
import (
"fmt"
"strconv"
"strings"
"github.com/subchen/go-stack/conv"
"github.com/subchen/go-stack/scanner/splitattrs"
)
type Query struct {
data interface{}
}
var emptyValue = &conv.Value{nil}
func NewQuery(data interface{}) *Query {
return &Query{data}
}
func (q *Query) Query(expr string) *conv.Value {
if q.data == nil {
return emptyValue
}
if expr == "." {
return &conv.Value{q.data}
}
ctx := q.data
multi := false
paths, err := splitattrs.Split(expr)
if err != nil {
panic(err)
}
for _, path := range paths {
if multi {
matchedCtx := make([]interface{}, 0)
for _, c := range ctx.([]interface{}) {
d, m, err := getAttr(c, path)
if err != nil {
return emptyValue
}
if d != nil {
if m {
matchedCtx = append(matchedCtx, d.([]interface{})...)
} else {
matchedCtx = append(matchedCtx, d)
}
}
}
ctx = matchedCtx
} else {
var err error
ctx, multi, err = getAttr(ctx, path)
if err != nil {
return emptyValue
}
if ctx == nil {
return emptyValue
}
}
}
return &conv.Value{ctx}
}
func getAttr(data interface{}, attr string) (value interface{}, multi bool, err error) {
if len(attr) >= 3 && strings.HasPrefix(attr, "[") && strings.HasSuffix(attr, "]") {
// array
v, ok := data.([]interface{})
if !ok {
panic(fmt.Errorf("%s is not an array, its type is %T", attr, v))
}
if strings.ContainsRune(attr, '=') {
// map[key=value]
kv := strings.SplitN(attr, "=", 2)
matchedList := make([]interface{}, 0)
for _, c := range v {
if cm, ok := c.(map[string]interface{}); ok {
if val, ok := cm[kv[0]]; ok {
if fmt.Sprintf("%v", val) == kv[1] {
matchedList = append(matchedList, cm)
}
}
} else if cm, ok := c.(map[interface{}]interface{}); ok {
if val, ok := cm[kv[0]]; ok {
if fmt.Sprintf("%v", val) == kv[1] {
matchedList = append(matchedList, cm)
}
}
} else {
panic(fmt.Errorf("%s is not an array, its type is %T", attr, c))
}
}
return matchedList, true, nil
} else if strings.ContainsRune(attr, ':') {
// slice[low:high]
low := 0
high := len(v)
var err error
indexes := strings.SplitN(attr, ":", 2)
if indexes[0] != "" {
low, err = strconv.Atoi(indexes[0])
if err != nil {
panic(err)
}
}
if indexes[1] != "" {
high, err = strconv.Atoi(indexes[1])
if err != nil {
panic(err)
}
}
if low < 0 || low >= len(v) {
return nil, true, fmt.Errorf("%s: low index out of range", attr)
}
if high <= 0 {
high = len(v) + high
}
if high < 0 || high > len(v) {
return nil, true, fmt.Errorf("%s: high index out of range", attr)
}
if high <= low {
return nil, true, fmt.Errorf("%s: high index must be large than low index", attr)
}
return v[low:high], true, nil
} else {
// array[i]
index, err := strconv.Atoi(attr[1 : len(attr)-1])
if err != nil {
panic(err)
}
if index < 0 || index >= len(v) {
return nil, false, fmt.Errorf("%s: index out of range", attr)
}
return v[index], false, nil
}
} else {
// map
if v, ok := data.(map[string]interface{}); ok {
if val, ok := v[attr]; ok {
return val, false, nil
}
return nil, false, nil
} else if v, ok := data.(map[interface{}]interface{}); ok {
if val, ok := v[attr]; ok {
return val, false, nil
}
return nil, false, nil
} else {
panic(fmt.Errorf("%s is not an array, its type is %T", attr, v))
}
}
}
|
DariosDjimado/Marvel-Search-Engine
|
src/main/java/fr/tse/fise2/heapoverflow/events/RequestListener.java
|
<reponame>DariosDjimado/Marvel-Search-Engine
package fr.tse.fise2.heapoverflow.events;
import fr.tse.fise2.heapoverflow.interfaces.IRequestListener;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
public class RequestListener {
private final IRequestListener requestListener;
public RequestListener(IRequestListener requestListener) {
this.requestListener = requestListener;
}
public void startLoading(String name) {
this.requestListener.startLoading(name);
}
public void endLoading(String name) {
this.requestListener.endLoading(name);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof RequestListener)) return false;
RequestListener that = (RequestListener) o;
return new EqualsBuilder()
.append(requestListener, that.requestListener)
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder(17, 37)
.append(requestListener)
.toHashCode();
}
}
|
Havoc-OS/androidprebuilts_go_linux-x86
|
src/cmd/go/testdata/src/badc/x.c
|
<filename>src/cmd/go/testdata/src/badc/x.c
// C code!
|
RubenPX/django-orchestra
|
orchestra/contrib/saas/validators.py
|
<reponame>RubenPX/django-orchestra
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from orchestra.utils.apps import isinstalled
def validate_website_saas_directives(app):
def validator(enabled, app=app):
if enabled and isinstalled('orchestra.contrib.websites'):
from orchestra.contrib.websites import settings
if app not in settings.WEBSITES_SAAS_DIRECTIVES:
raise ValidationError(_("Allow custom URL is enabled for '%s', "
"but has no associated WEBSITES_SAAS_DIRECTIVES" % app))
return validator
|
domin1101/ANNHelper
|
src/LightBulbApp/TrainingPlans/Preferences/PredefinedPreferenceGroups/Evolution/ConstantCreationCommandPreferenceGroup.cpp
|
<reponame>domin1101/ANNHelper
// Includes
#include "LightBulbApp/TrainingPlans/Preferences/PredefinedPreferenceGroups/Evolution/ConstantCreationCommandPreferenceGroup.hpp"
#include "LightBulbApp/TrainingPlans/Preferences/IntegerPreference.hpp"
#include "LightBulb/Learning/Evolution/ConstantCreationCommand.hpp"
namespace LightBulb
{
#define PREFERENCE_INDIVIDUAL_COUNT "Individual count"
ConstantCreationCommandPreferenceGroup::ConstantCreationCommandPreferenceGroup(const std::string& name)
:PreferenceGroup(name)
{
addPreference(new IntegerPreference(PREFERENCE_INDIVIDUAL_COUNT, 20, 1, 100));
}
ConstantCreationCommand* ConstantCreationCommandPreferenceGroup::create() const
{
int individualCount = getIntegerPreference(PREFERENCE_INDIVIDUAL_COUNT);
return new ConstantCreationCommand(individualCount);
}
AbstractCloneable* ConstantCreationCommandPreferenceGroup::clone() const
{
return new ConstantCreationCommandPreferenceGroup(*this);
}
}
|
lalyos/kotlin
|
idea/tests/org/jetbrains/jet/plugin/refactoring/rename/RenameInKotlinTest.java
|
/*
* Copyright 2010-2012 JetBrains s.r.o.
*
* 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.jetbrains.jet.plugin.refactoring.rename;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.refactoring.MultiFileTestCase;
import com.intellij.refactoring.rename.RenameProcessor;
import com.intellij.util.Function;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.jet.lang.descriptors.ClassDescriptor;
import org.jetbrains.jet.lang.descriptors.FunctionDescriptor;
import org.jetbrains.jet.lang.psi.JetFile;
import org.jetbrains.jet.lang.resolve.BindingContext;
import org.jetbrains.jet.lang.resolve.BindingContextUtils;
import org.jetbrains.jet.lang.resolve.name.Name;
import org.jetbrains.jet.lang.resolve.scopes.JetScope;
import org.jetbrains.jet.lang.types.TypeProjection;
import org.jetbrains.jet.lang.resolve.name.FqName;
import org.jetbrains.jet.plugin.PluginTestCaseBase;
import org.jetbrains.jet.plugin.project.WholeProjectAnalyzerFacade;
import java.io.File;
import java.util.Collections;
/**
* @author <NAME>
*/
public class RenameInKotlinTest extends MultiFileTestCase {
@Override
protected void setUp() throws Exception {
super.setUp();
refreshPath(getTestDataPath() + getTestRoot());
refreshPath(getTestDataPath() + getTestRoot() + getTestName(true) + File.separator + "before");
refreshPath(getTestDataPath() + getTestRoot() + getTestName(true) + File.separator + "after");
}
public static void refreshPath(String path) {
VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(path);
if (virtualFile != null) {
virtualFile.getChildren();
virtualFile.refresh(false, true);
}
}
public void testRenameKotlinClass() throws Exception {
doTestWithRenameClass(new FqName("testing.rename.First"), "Third");
}
public void testRenameKotlinMethod() throws Exception {
doTestWithRenameMethod(new FqName("testing.rename.C"), "first", "second");
}
private void doTestWithRenameMethod(final FqName qClassName, final String oldMethodName, String newMethodName) throws Exception {
doTestWithRename(new Function<PsiFile, PsiElement>() {
@Override
public PsiElement fun(PsiFile file) {
BindingContext bindingContext = WholeProjectAnalyzerFacade.analyzeProjectWithCacheOnAFile((JetFile) file)
.getBindingContext();
ClassDescriptor classDescriptor = bindingContext.get(BindingContext.FQNAME_TO_CLASS_DESCRIPTOR, qClassName);
assertNotNull(classDescriptor);
final JetScope scope = classDescriptor.getMemberScope(Collections.<TypeProjection>emptyList());
final FunctionDescriptor methodDescriptor = scope.getFunctions(Name.identifier(oldMethodName)).iterator().next();
return BindingContextUtils.callableDescriptorToDeclaration(bindingContext, methodDescriptor);
}
}, newMethodName);
}
private void doTestWithRenameClass(@NonNls final FqName qClassName, @NonNls final String newName) throws Exception {
doTestWithRename(new Function<PsiFile, PsiElement>() {
@Override
public PsiElement fun(PsiFile file) {
BindingContext bindingContext = WholeProjectAnalyzerFacade.analyzeProjectWithCacheOnAFile((JetFile) file)
.getBindingContext();
ClassDescriptor classDescriptor = bindingContext.get(BindingContext.FQNAME_TO_CLASS_DESCRIPTOR, qClassName);
assertNotNull(classDescriptor);
return BindingContextUtils.classDescriptorToDeclaration(bindingContext, classDescriptor);
}
}, newName);
}
private void doTestWithRename(@NonNls final Function<PsiFile, PsiElement> elementToRenameCallback, @NonNls final String newName) throws Exception {
doTest(new PerformAction() {
@Override
public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception {
VirtualFile child = rootDir.findChild(getTestName(false) + ".kt");
if (child == null) {
return;
}
Document document = FileDocumentManager.getInstance().getDocument(child);
if (document == null) {
return;
}
PsiFile file = PsiDocumentManager.getInstance(getProject()).getPsiFile(document);
if (!(file instanceof JetFile)) {
return;
}
PsiElement psiElement = elementToRenameCallback.fun(file);
assertNotNull(psiElement);
new RenameProcessor(myProject, psiElement, newName, true, true).run();
PsiDocumentManager.getInstance(myProject).commitAllDocuments();
FileDocumentManager.getInstance().saveAllDocuments();
VirtualFileManager.getInstance().refresh(false);
}
});
}
@Override
protected String getTestRoot() {
return "/refactoring/rename/";
}
@Override
protected String getTestDataPath() {
return PluginTestCaseBase.getTestDataPathBase();
}
}
|
2637309949/dolphin
|
examples/aisle/types/android_hotfix.auto.go
|
// Code generated by dol build. DO NOT EDIT.
// source: auto.go
package types
import (
"encoding/json"
"github.com/2637309949/dolphin/packages/null"
)
// AndroidHotfix defined
type AndroidHotfix struct {
// AHId defined
AHId null.Int `xorm:"int(11) pk notnull autoincr 'a_h_id'" json:"a_h_id" form:"a_h_id" xml:"a_h_id"`
// AppName defined
AppName null.String `xorm:"varchar(200) 'app_name'" json:"app_name" form:"app_name" xml:"app_name"`
// Applicationid defined
Applicationid null.String `xorm:"varchar(200) 'applicationid'" json:"applicationid" form:"applicationid" xml:"applicationid"`
// VersionName defined
VersionName null.String `xorm:"varchar(200) 'version_name'" json:"version_name" form:"version_name" xml:"version_name"`
// Descriptions defined
Descriptions null.String `xorm:"varchar(500) 'descriptions'" json:"descriptions" form:"descriptions" xml:"descriptions"`
// Creater defined
Creater null.String `xorm:"varchar(36) 'creater'" json:"creater" form:"creater" xml:"creater"`
// CreateDate defined
CreateDate null.Time `xorm:"datetime 'create_date'" json:"create_date" form:"create_date" xml:"create_date"`
// Updater defined
Updater null.String `xorm:"varchar(36) 'updater'" json:"updater" form:"updater" xml:"updater"`
// UpdateDate defined
UpdateDate null.Time `xorm:"datetime 'update_date'" json:"update_date" form:"update_date" xml:"update_date"`
// IsDelete defined
IsDelete null.Int `xorm:"notnull 'is_delete'" json:"is_delete" form:"is_delete" xml:"is_delete"`
}
// TableName table name of defined AndroidHotfix
func (m *AndroidHotfix) TableName() string {
return "android_hotfix"
}
func (r *AndroidHotfix) Marshal() ([]byte, error) {
return json.Marshal(r)
}
func UnmarshalAndroidHotfix(data []byte) (AndroidHotfix, error) {
var r AndroidHotfix
err := json.Unmarshal(data, &r)
return r, err
}
|
Roberto-Mota/CursoemVideo
|
exercicios/ex115.py
|
# Desafio 115 -> Crie um pequeno sistema modularizado que permita cadastrar pessoas pelo seu nome
# e idade em um arquivo de texto simples.
# O sistema só vai ter 2 opções: cadastrar uma nova pessoa e listar todas as pessoas cadastradas
from utilidades import dados
from utilidades import cores
# Menu
while True:
print('-' * 32)
print(f'{"MENU PRINCIPAL":^32}')
print(f'-' * 32)
print('1 - \033[34;1mLista de pessoas cadastradas\033[m\n'
'2 - \033[34;1mCadastrar uma nova pessoa\033[m\n'
'3 - \033[34;1mSair do menu\033[m')
print('-' * 32)
sele = dados.leiaint('Sua opção: ')
while True:
if 1 <= sele <= 3:
if sele == 1: # Ver a lista
print('-' * 32)
print(f'{" LISTA DE CADASTRADOS ":^32}')
print('-' * 32)
with open("teste.txt", 'r') as f:
conteudo = f.read()
print(conteudo)
sair = input('Aperte enter para voltaro ao menu principal.')
break
elif sele == 2: # Cadastrar na lista
print(' ', '-' * 32)
print(f'{" CADASTRO DE USUÁRIOS ":^32}')
print(f' ', '-' * 32)
with open("teste.txt", 'a') as f:
while True:
nome = input('Digite o nome: ')
idade = dados.leiaint('Idade: ')
while True: # Confirmação de cadastro
conf = input('Confirmar cadastro? [S/N]').lower().strip()[0]
if conf not in 'sn':
print('Opção inválida, tente novamente.')
elif conf == 'n':
break
else:
f.write(f'\n{nome} {idade}')
print('Usuário cadastrado com sucesso!')
break
break
f.close()
break
elif sele == 3:
print(' ', '-' * 32)
print(f'{" ENCERRAR PROGRAMA ":^32}')
print(f' ', '-' * 32)
break
print('Blz')
else:
while True:
print('Opcão inválida')
sele = dados.leiaint('Sua opção: ')
if 1 <= sele <= 3:
break
#Ver a lista
#Cadastrar uma nova pessoa
#with open("teste.txt", 'w') as f:
# f.write(f'{nome} {idade}')
#Sair do programa
|
TengChongChong/easy-frame
|
easy-sample/src/main/webapp/static/modular/sample/export/data/list.js
|
<reponame>TengChongChong/easy-frame<filename>easy-sample/src/main/webapp/static/modular/sample/export/data/list.js
//== 数据导出示例
var mExportDataList = function () {
/**
* 初始化列表
*/
var initTable = function () {
var options = {
// 列配置
columns: [
{
field: 'id',
title: '#',
sortable: false, // 禁用此列排序
width: 40,
selector: {class: 'kt-checkbox--solid'},
},
{
field: 'name',
title: '姓名'
},
{
field: 'sex',
title: '性别',
dictType: 'sex'
},
{
field: 'age',
title: '年龄'
},
{
field: 'phone',
title: '手机号码'
},
{
field: 'address',
title: '地址'
},
{
field: 'status',
title: '状态',
dictType: 'commonStatus'
},
{
field: 'editUser',
title: '编辑人'
},
{
field: 'editDate',
title: '编辑时间'
}
]
};
mExportDataList.dataTable = KTTool.initDataTable(options);
};
return {
//== 初始化页面
init: function () {
KTTool.setBaseUrl(basePath + '/auth/sample/export/data/');
initTable();
}
};
}();
/**
* 当前tab激活时是否需要重新加载数据
*
* @return {boolean} true/false
*/
KTTab.needSubmitForm = function () {
return true;
};
//== 初始化
$(document).ready(function () {
mExportDataList.init();
});
|
mantianxing246/angli
|
src/api/order/FinancialAudit/FormalOrderAudit.js
|
<reponame>mantianxing246/angli
import request from '@/utils/request'
// 正式订单查询回显
export function findProductByOrder(orderId) {
return request({
url: 'formal-order-auditing/findFormalOrderByOrderId/' + orderId,
method: 'get'
})
}
|
retrodaredevil/allwpilib
|
hal/src/main/native/sim/jni/RoboRioDataJNI.cpp
|
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2018 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#include <jni.h>
#include "CallbackStore.h"
#include "edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI.h"
#include "mockdata/RoboRioData.h"
extern "C" {
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: registerFPGAButtonCallback
* Signature: (ILjava/lang/Object;Z)I
*/
JNIEXPORT jint JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_registerFPGAButtonCallback
(JNIEnv* env, jclass, jint index, jobject callback, jboolean initialNotify)
{
return sim::AllocateCallback(env, index, callback, initialNotify,
&HALSIM_RegisterRoboRioFPGAButtonCallback);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: cancelFPGAButtonCallback
* Signature: (II)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_cancelFPGAButtonCallback
(JNIEnv* env, jclass, jint index, jint handle)
{
return sim::FreeCallback(env, handle, index,
&HALSIM_CancelRoboRioFPGAButtonCallback);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: getFPGAButton
* Signature: (I)Z
*/
JNIEXPORT jboolean JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_getFPGAButton
(JNIEnv*, jclass, jint index)
{
return HALSIM_GetRoboRioFPGAButton(index);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: setFPGAButton
* Signature: (IZ)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_setFPGAButton
(JNIEnv*, jclass, jint index, jboolean value)
{
HALSIM_SetRoboRioFPGAButton(index, value);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: registerVInVoltageCallback
* Signature: (ILjava/lang/Object;Z)I
*/
JNIEXPORT jint JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_registerVInVoltageCallback
(JNIEnv* env, jclass, jint index, jobject callback, jboolean initialNotify)
{
return sim::AllocateCallback(env, index, callback, initialNotify,
&HALSIM_RegisterRoboRioVInVoltageCallback);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: cancelVInVoltageCallback
* Signature: (II)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_cancelVInVoltageCallback
(JNIEnv* env, jclass, jint index, jint handle)
{
return sim::FreeCallback(env, handle, index,
&HALSIM_CancelRoboRioVInVoltageCallback);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: getVInVoltage
* Signature: (I)D
*/
JNIEXPORT jdouble JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_getVInVoltage
(JNIEnv*, jclass, jint index)
{
return HALSIM_GetRoboRioVInVoltage(index);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: setVInVoltage
* Signature: (ID)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_setVInVoltage
(JNIEnv*, jclass, jint index, jdouble value)
{
HALSIM_SetRoboRioVInVoltage(index, value);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: registerVInCurrentCallback
* Signature: (ILjava/lang/Object;Z)I
*/
JNIEXPORT jint JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_registerVInCurrentCallback
(JNIEnv* env, jclass, jint index, jobject callback, jboolean initialNotify)
{
return sim::AllocateCallback(env, index, callback, initialNotify,
&HALSIM_RegisterRoboRioVInCurrentCallback);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: cancelVInCurrentCallback
* Signature: (II)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_cancelVInCurrentCallback
(JNIEnv* env, jclass, jint index, jint handle)
{
return sim::FreeCallback(env, handle, index,
&HALSIM_CancelRoboRioVInCurrentCallback);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: getVInCurrent
* Signature: (I)D
*/
JNIEXPORT jdouble JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_getVInCurrent
(JNIEnv*, jclass, jint index)
{
return HALSIM_GetRoboRioVInCurrent(index);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: setVInCurrent
* Signature: (ID)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_setVInCurrent
(JNIEnv*, jclass, jint index, jdouble value)
{
HALSIM_SetRoboRioVInCurrent(index, value);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: registerUserVoltage6VCallback
* Signature: (ILjava/lang/Object;Z)I
*/
JNIEXPORT jint JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_registerUserVoltage6VCallback
(JNIEnv* env, jclass, jint index, jobject callback, jboolean initialNotify)
{
return sim::AllocateCallback(env, index, callback, initialNotify,
&HALSIM_RegisterRoboRioUserVoltage6VCallback);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: cancelUserVoltage6VCallback
* Signature: (II)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_cancelUserVoltage6VCallback
(JNIEnv* env, jclass, jint index, jint handle)
{
return sim::FreeCallback(env, handle, index,
&HALSIM_CancelRoboRioUserVoltage6VCallback);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: getUserVoltage6V
* Signature: (I)D
*/
JNIEXPORT jdouble JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_getUserVoltage6V
(JNIEnv*, jclass, jint index)
{
return HALSIM_GetRoboRioUserVoltage6V(index);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: setUserVoltage6V
* Signature: (ID)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_setUserVoltage6V
(JNIEnv*, jclass, jint index, jdouble value)
{
HALSIM_SetRoboRioUserVoltage6V(index, value);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: registerUserCurrent6VCallback
* Signature: (ILjava/lang/Object;Z)I
*/
JNIEXPORT jint JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_registerUserCurrent6VCallback
(JNIEnv* env, jclass, jint index, jobject callback, jboolean initialNotify)
{
return sim::AllocateCallback(env, index, callback, initialNotify,
&HALSIM_RegisterRoboRioUserCurrent6VCallback);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: cancelUserCurrent6VCallback
* Signature: (II)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_cancelUserCurrent6VCallback
(JNIEnv* env, jclass, jint index, jint handle)
{
return sim::FreeCallback(env, handle, index,
&HALSIM_CancelRoboRioUserCurrent6VCallback);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: getUserCurrent6V
* Signature: (I)D
*/
JNIEXPORT jdouble JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_getUserCurrent6V
(JNIEnv*, jclass, jint index)
{
return HALSIM_GetRoboRioUserCurrent6V(index);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: setUserCurrent6V
* Signature: (ID)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_setUserCurrent6V
(JNIEnv*, jclass, jint index, jdouble value)
{
HALSIM_SetRoboRioUserCurrent6V(index, value);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: registerUserActive6VCallback
* Signature: (ILjava/lang/Object;Z)I
*/
JNIEXPORT jint JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_registerUserActive6VCallback
(JNIEnv* env, jclass, jint index, jobject callback, jboolean initialNotify)
{
return sim::AllocateCallback(env, index, callback, initialNotify,
&HALSIM_RegisterRoboRioUserActive6VCallback);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: cancelUserActive6VCallback
* Signature: (II)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_cancelUserActive6VCallback
(JNIEnv* env, jclass, jint index, jint handle)
{
return sim::FreeCallback(env, handle, index,
&HALSIM_CancelRoboRioUserActive6VCallback);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: getUserActive6V
* Signature: (I)Z
*/
JNIEXPORT jboolean JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_getUserActive6V
(JNIEnv*, jclass, jint index)
{
return HALSIM_GetRoboRioUserActive6V(index);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: setUserActive6V
* Signature: (IZ)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_setUserActive6V
(JNIEnv*, jclass, jint index, jboolean value)
{
HALSIM_SetRoboRioUserActive6V(index, value);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: registerUserVoltage5VCallback
* Signature: (ILjava/lang/Object;Z)I
*/
JNIEXPORT jint JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_registerUserVoltage5VCallback
(JNIEnv* env, jclass, jint index, jobject callback, jboolean initialNotify)
{
return sim::AllocateCallback(env, index, callback, initialNotify,
&HALSIM_RegisterRoboRioUserVoltage5VCallback);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: cancelUserVoltage5VCallback
* Signature: (II)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_cancelUserVoltage5VCallback
(JNIEnv* env, jclass, jint index, jint handle)
{
return sim::FreeCallback(env, handle, index,
&HALSIM_CancelRoboRioUserVoltage5VCallback);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: getUserVoltage5V
* Signature: (I)D
*/
JNIEXPORT jdouble JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_getUserVoltage5V
(JNIEnv*, jclass, jint index)
{
return HALSIM_GetRoboRioUserVoltage5V(index);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: setUserVoltage5V
* Signature: (ID)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_setUserVoltage5V
(JNIEnv*, jclass, jint index, jdouble value)
{
HALSIM_SetRoboRioUserVoltage5V(index, value);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: registerUserCurrent5VCallback
* Signature: (ILjava/lang/Object;Z)I
*/
JNIEXPORT jint JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_registerUserCurrent5VCallback
(JNIEnv* env, jclass, jint index, jobject callback, jboolean initialNotify)
{
return sim::AllocateCallback(env, index, callback, initialNotify,
&HALSIM_RegisterRoboRioUserCurrent5VCallback);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: cancelUserCurrent5VCallback
* Signature: (II)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_cancelUserCurrent5VCallback
(JNIEnv* env, jclass, jint index, jint handle)
{
return sim::FreeCallback(env, handle, index,
&HALSIM_CancelRoboRioUserCurrent5VCallback);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: getUserCurrent5V
* Signature: (I)D
*/
JNIEXPORT jdouble JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_getUserCurrent5V
(JNIEnv*, jclass, jint index)
{
return HALSIM_GetRoboRioUserCurrent5V(index);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: setUserCurrent5V
* Signature: (ID)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_setUserCurrent5V
(JNIEnv*, jclass, jint index, jdouble value)
{
HALSIM_SetRoboRioUserCurrent5V(index, value);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: registerUserActive5VCallback
* Signature: (ILjava/lang/Object;Z)I
*/
JNIEXPORT jint JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_registerUserActive5VCallback
(JNIEnv* env, jclass, jint index, jobject callback, jboolean initialNotify)
{
return sim::AllocateCallback(env, index, callback, initialNotify,
&HALSIM_RegisterRoboRioUserActive5VCallback);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: cancelUserActive5VCallback
* Signature: (II)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_cancelUserActive5VCallback
(JNIEnv* env, jclass, jint index, jint handle)
{
return sim::FreeCallback(env, handle, index,
&HALSIM_CancelRoboRioUserActive5VCallback);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: getUserActive5V
* Signature: (I)Z
*/
JNIEXPORT jboolean JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_getUserActive5V
(JNIEnv*, jclass, jint index)
{
return HALSIM_GetRoboRioUserActive5V(index);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: setUserActive5V
* Signature: (IZ)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_setUserActive5V
(JNIEnv*, jclass, jint index, jboolean value)
{
HALSIM_SetRoboRioUserActive5V(index, value);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: registerUserVoltage3V3Callback
* Signature: (ILjava/lang/Object;Z)I
*/
JNIEXPORT jint JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_registerUserVoltage3V3Callback
(JNIEnv* env, jclass, jint index, jobject callback, jboolean initialNotify)
{
return sim::AllocateCallback(env, index, callback, initialNotify,
&HALSIM_RegisterRoboRioUserVoltage3V3Callback);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: cancelUserVoltage3V3Callback
* Signature: (II)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_cancelUserVoltage3V3Callback
(JNIEnv* env, jclass, jint index, jint handle)
{
return sim::FreeCallback(env, handle, index,
&HALSIM_CancelRoboRioUserVoltage3V3Callback);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: getUserVoltage3V3
* Signature: (I)D
*/
JNIEXPORT jdouble JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_getUserVoltage3V3
(JNIEnv*, jclass, jint index)
{
return HALSIM_GetRoboRioUserVoltage3V3(index);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: setUserVoltage3V3
* Signature: (ID)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_setUserVoltage3V3
(JNIEnv*, jclass, jint index, jdouble value)
{
HALSIM_SetRoboRioUserVoltage3V3(index, value);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: registerUserCurrent3V3Callback
* Signature: (ILjava/lang/Object;Z)I
*/
JNIEXPORT jint JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_registerUserCurrent3V3Callback
(JNIEnv* env, jclass, jint index, jobject callback, jboolean initialNotify)
{
return sim::AllocateCallback(env, index, callback, initialNotify,
&HALSIM_RegisterRoboRioUserCurrent3V3Callback);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: cancelUserCurrent3V3Callback
* Signature: (II)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_cancelUserCurrent3V3Callback
(JNIEnv* env, jclass, jint index, jint handle)
{
return sim::FreeCallback(env, handle, index,
&HALSIM_CancelRoboRioUserCurrent3V3Callback);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: getUserCurrent3V3
* Signature: (I)D
*/
JNIEXPORT jdouble JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_getUserCurrent3V3
(JNIEnv*, jclass, jint index)
{
return HALSIM_GetRoboRioUserCurrent3V3(index);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: setUserCurrent3V3
* Signature: (ID)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_setUserCurrent3V3
(JNIEnv*, jclass, jint index, jdouble value)
{
HALSIM_SetRoboRioUserCurrent3V3(index, value);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: registerUserActive3V3Callback
* Signature: (ILjava/lang/Object;Z)I
*/
JNIEXPORT jint JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_registerUserActive3V3Callback
(JNIEnv* env, jclass, jint index, jobject callback, jboolean initialNotify)
{
return sim::AllocateCallback(env, index, callback, initialNotify,
&HALSIM_RegisterRoboRioUserActive3V3Callback);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: cancelUserActive3V3Callback
* Signature: (II)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_cancelUserActive3V3Callback
(JNIEnv* env, jclass, jint index, jint handle)
{
return sim::FreeCallback(env, handle, index,
&HALSIM_CancelRoboRioUserActive3V3Callback);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: getUserActive3V3
* Signature: (I)Z
*/
JNIEXPORT jboolean JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_getUserActive3V3
(JNIEnv*, jclass, jint index)
{
return HALSIM_GetRoboRioUserActive3V3(index);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: setUserActive3V3
* Signature: (IZ)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_setUserActive3V3
(JNIEnv*, jclass, jint index, jboolean value)
{
HALSIM_SetRoboRioUserActive3V3(index, value);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: registerUserFaults6VCallback
* Signature: (ILjava/lang/Object;Z)I
*/
JNIEXPORT jint JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_registerUserFaults6VCallback
(JNIEnv* env, jclass, jint index, jobject callback, jboolean initialNotify)
{
return sim::AllocateCallback(env, index, callback, initialNotify,
&HALSIM_RegisterRoboRioUserFaults6VCallback);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: cancelUserFaults6VCallback
* Signature: (II)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_cancelUserFaults6VCallback
(JNIEnv* env, jclass, jint index, jint handle)
{
return sim::FreeCallback(env, handle, index,
&HALSIM_CancelRoboRioUserFaults6VCallback);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: getUserFaults6V
* Signature: (I)I
*/
JNIEXPORT jint JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_getUserFaults6V
(JNIEnv*, jclass, jint index)
{
return HALSIM_GetRoboRioUserFaults6V(index);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: setUserFaults6V
* Signature: (II)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_setUserFaults6V
(JNIEnv*, jclass, jint index, jint value)
{
HALSIM_SetRoboRioUserFaults6V(index, value);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: registerUserFaults5VCallback
* Signature: (ILjava/lang/Object;Z)I
*/
JNIEXPORT jint JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_registerUserFaults5VCallback
(JNIEnv* env, jclass, jint index, jobject callback, jboolean initialNotify)
{
return sim::AllocateCallback(env, index, callback, initialNotify,
&HALSIM_RegisterRoboRioUserFaults5VCallback);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: cancelUserFaults5VCallback
* Signature: (II)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_cancelUserFaults5VCallback
(JNIEnv* env, jclass, jint index, jint handle)
{
return sim::FreeCallback(env, handle, index,
&HALSIM_CancelRoboRioUserFaults5VCallback);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: getUserFaults5V
* Signature: (I)I
*/
JNIEXPORT jint JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_getUserFaults5V
(JNIEnv*, jclass, jint index)
{
return HALSIM_GetRoboRioUserFaults5V(index);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: setUserFaults5V
* Signature: (II)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_setUserFaults5V
(JNIEnv*, jclass, jint index, jint value)
{
HALSIM_SetRoboRioUserFaults5V(index, value);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: registerUserFaults3V3Callback
* Signature: (ILjava/lang/Object;Z)I
*/
JNIEXPORT jint JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_registerUserFaults3V3Callback
(JNIEnv* env, jclass, jint index, jobject callback, jboolean initialNotify)
{
return sim::AllocateCallback(env, index, callback, initialNotify,
&HALSIM_RegisterRoboRioUserFaults3V3Callback);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: cancelUserFaults3V3Callback
* Signature: (II)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_cancelUserFaults3V3Callback
(JNIEnv* env, jclass, jint index, jint handle)
{
return sim::FreeCallback(env, handle, index,
&HALSIM_CancelRoboRioUserFaults3V3Callback);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: getUserFaults3V3
* Signature: (I)I
*/
JNIEXPORT jint JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_getUserFaults3V3
(JNIEnv*, jclass, jint index)
{
return HALSIM_GetRoboRioUserFaults3V3(index);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: setUserFaults3V3
* Signature: (II)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_setUserFaults3V3
(JNIEnv*, jclass, jint index, jint value)
{
HALSIM_SetRoboRioUserFaults3V3(index, value);
}
/*
* Class: edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI
* Method: resetData
* Signature: (I)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_sim_mockdata_RoboRioDataJNI_resetData
(JNIEnv*, jclass, jint index)
{
HALSIM_ResetRoboRioData(index);
}
} // extern "C"
|
beehive-lab/DFLOW
|
on-board/src/can_module/messages/tpm_module_message.cpp
|
<reponame>beehive-lab/DFLOW<filename>on-board/src/can_module/messages/tpm_module_message.cpp
//Author: <NAME>
#include "tpm_module_message.hpp"
void TPMModuleMessage::set_from_map(std::map<std::string,std::string> value_map)
{
TPMModuleMessage::data.tyre_pressure_front = std::stod(value_map["TyrePressureFront"]);
TPMModuleMessage::data.tyre_pressure_rear = std::stod(value_map["TyrePressureRear"]);
}
|
Xiaoxiong-Liu/gluon-ts
|
test/model/deepvar_hierarchical/test_reconciliation_error.py
|
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license" file accompanying this file. This file is distributed
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied. See the License for the specific language governing
# permissions and limitations under the License.
import mxnet as mx
import numpy as np
import pytest
from gluonts.model.deepvar_hierarchical import (
constraint_mat,
reconciliation_error,
)
TOL = 1e-4
S = np.array(
[
[1, 1, 1, 1],
[1, 1, 0, 0],
[0, 0, 1, 1],
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
],
)
num_bottom_ts = S.shape[1]
A = constraint_mat(S)
@pytest.mark.parametrize(
"bottom_ts",
[
np.random.randint(low=0, high=100, size=num_bottom_ts), # integer data
np.random.randint(
low=1000, high=100000, size=num_bottom_ts
), # large integer data
np.random.poisson(lam=1, size=num_bottom_ts),
np.random.negative_binomial(n=1000, p=0.5, size=num_bottom_ts),
-np.random.negative_binomial(
n=1000, p=0.5, size=num_bottom_ts
), # negative data
np.random.standard_normal(size=num_bottom_ts),
],
)
def test_reconciliation_error(bottom_ts):
all_ts = S @ bottom_ts
assert reconciliation_error(mx.nd.array(A), mx.nd.array(all_ts)) < TOL
|
woshiluo/oi
|
cf/contest/1334/c/c.cpp
|
// Woshiluo<<EMAIL>>
// Started at 2020-04-10 23:17
// Blog: https://blog.woshiluo.com
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
template<class T>
T Min( T a, T b ) { return a < b? a: b; }
template<class T>
T Max( T a, T b ) { return a > b? a: b; }
template<class T>
void chk_Min( T &a, T b ) { if( a > b ) a = b; }
template<class T>
void chk_Max( T &a, T b ) { if( a < b ) a = b; }
const int N = 1e6 + 1e5;
const long long INF = ( 1LL << 60 );
int T;
int n;
long long a[N], b[N], sum[N];
int main() {
#ifdef woshiluo
freopen( "c.in", "r", stdin );
freopen( "c.out", "w", stdout );
#endif
scanf( "%d", &T );
while( T -- ) {
scanf( "%d", &n );
long long ans = INF;
for( int i = 1; i <= n; i ++ ) {
scanf( "%lld%lld", &a[i], &b[i] );
}
for( int i = 1; i <= n; i ++ ) {
a[ i + n ] = a[i]; b[ i + n ] = b[i];
}
int n_2 = 2 * n;
for( int i = 1; i <= n_2; i ++ ) {
sum[i] = sum[ i - 1 ] + Max( 0LL, a[i] - b[ i - 1 ] );
}
for( int i = 1; i <= n; i ++ ) {
long long res = a[i] + sum[ i + n - 1 ] - sum[i];
chk_Min( ans, res );
}
printf( "%lld\n", ans );
}
}
|
SIGBlockchain/project_aurum
|
internal/publickey/publickey_test.go
|
package publickey
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"encoding/hex"
"encoding/pem"
"reflect"
"testing"
"github.com/SIGBlockchain/project_aurum/internal/hashing"
)
func TestNew(t *testing.T) {
private, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
k, ok := private.Public().(*ecdsa.PublicKey)
if !ok {
t.Errorf("Cannot extract a ecdsa public key from private key given")
}
bytes, err := Encode(k)
if err != nil {
t.Errorf("Failed to encode public key inside of private key")
}
expected := AurumPublicKey{
Key: k,
Bytes: bytes,
Hex: hex.EncodeToString(bytes),
Hash: hashing.New(bytes)}
actual, err := New(private)
if err != nil {
t.Errorf("Failed to create new Aurum: %s", err.Error())
}
if !reflect.DeepEqual(actual.Bytes, expected.Bytes) {
t.Errorf("Acutal Bytes does not equal expected Bytes:\nActual: %v\nExpected: %v", actual.Bytes, expected.Bytes)
}
if !reflect.DeepEqual(actual.Hash, expected.Hash) {
t.Errorf("Acutal Hash does not equal expected Hash:\nActual: %v\nExpected: %v", actual.Hash, expected.Hash)
}
if actual.Hex != expected.Hex {
t.Errorf("Acutal Hex does not equal expected Hex:\nActual: %v\nExpected: %v", actual.Hex, expected.Hex)
}
if !reflect.DeepEqual(actual.Key, expected.Key) {
t.Errorf("Acutal Key does not equal expected Key:\nActual: %v\nExpected: %v", actual.Key, expected.Key)
}
}
// test that public keys can be encoded properly
func TestEncoding(t *testing.T) {
private, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
public := private.PublicKey
x509EncodedPub, err := x509.MarshalPKIXPublicKey(nil)
// test that Encoding returns an error for bad input
if err == nil {
t.Errorf("Expected err to not be nil, but it was...")
}
encoded, err := Encode(&public)
// test that Encoding does not receive an error for valid input
if err != nil {
t.Errorf("Received an error for valid input")
}
x509EncodedPub, _ = x509.MarshalPKIXPublicKey(&public)
x509EncodedPub = pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: x509EncodedPub})
// test that Encoding results match
if !reflect.DeepEqual(x509EncodedPub, encoded) {
t.Errorf("Encoding does not match")
}
}
// test that public keys can be decoded properly
func TestDecoding(t *testing.T) {
private, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
public := private.PublicKey
encoded, _ := Encode(&public)
decoded, err := Decode(nil)
// test that Decoding returns an error
if err == nil {
t.Errorf("Expected err to not be nil, but it was...")
}
decoded, err = Decode(encoded)
// test that Decoding does not return an error for valid input
if err != nil {
t.Errorf("Expected err to not be nil, but it was...")
}
localDecoded, _ := pem.Decode(encoded)
x509EncodedPub := localDecoded.Bytes
genericPublicKey, _ := x509.ParsePKIXPublicKey(x509EncodedPub)
// test that decodings match
if !reflect.DeepEqual(genericPublicKey, decoded) {
t.Errorf("Keys do not match after decode")
}
}
// tests for Equals function for public keys
func TestEquals(t *testing.T) {
privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Errorf("Failed to generate private/public key pair")
}
aurumPBKey, err := New(privateKey)
if err != nil {
t.Errorf("Failed to create new Aurum public key")
}
privateKey2, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Errorf("Failed to generate private/public key pair")
}
tests := []struct {
name string
pubKey AurumPublicKey
pubKey2 *ecdsa.PublicKey
want bool
}{
{
"Equals",
aurumPBKey,
&privateKey.PublicKey,
true,
},
{
"Not Equals",
aurumPBKey,
&privateKey2.PublicKey,
false,
},
{
"Not Equals",
aurumPBKey,
nil,
false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if result := tt.pubKey.Equals(tt.pubKey2); result != tt.want {
t.Errorf("Failed to return %v (got %v) for public keys that are: %v", tt.want, result, tt.name)
}
})
}
}
|
kipiberbatov/idec
|
src/algebra/vector_sparse_fscan_raw.c
|
<filename>src/algebra/vector_sparse_fscan_raw.c
#include <errno.h>
#include <stdlib.h>
#include "double.h"
#include "int.h"
#include "vector_sparse_private.h"
static int all_values_in_range(
int a_length, int a_nonzero_max, const int * a_positions)
{
int i;
for (i = 0; i < a_nonzero_max; ++i)
if (a_positions[i] < 0 || a_positions[i] >= a_length)
return 0;
return 1;
}
static int all_values_different(int a_nonzero_max, const int * a_positions)
{
int i, j;
for (i = 0; i < a_nonzero_max - 1; ++i)
for (j = i + 1; j < a_nonzero_max; ++j)
if (a_positions[i] == a_positions[j])
return 0;
return 1;
}
static int vector_sparse_positions_possible(
int a_length, int a_nonzero_max, const int * a_positions)
{
if (!all_values_in_range(a_length, a_nonzero_max, a_positions))
return 0;
if (!all_values_different(a_nonzero_max, a_positions))
return 0;
return 1;
}
vector_sparse * vector_sparse_fscan_raw(FILE * in)
{
vector_sparse * a;
a = (vector_sparse *) malloc(sizeof(vector_sparse));
if (errno)
{
perror("vector_sparse_fscan_raw - cannot allocate memory for a");
goto end;
}
a->length = int_fscan(in);
if (errno)
{
perror("vector_sparse_fscan_raw - cannot scan a->length");
goto a_free;
}
if (a->length <= 0)
{
errno = EINVAL;
perror("vector_sparse_fscan_raw - a->length is nonpositive");
goto a_free;
}
a->nonzero_max = int_fscan(in);
if (errno)
{
perror("vector_sparse_fscan_raw - cannot scan a->nonzero_max");
goto a_free;
}
if (a->nonzero_max <= 0 || a->nonzero_max > a->length)
{
errno = EINVAL;
perror("vector_sparse_fscan_raw - a->nonzero_max is out of domain");
goto a_free;
}
a->positions = int_array_fscan(in, a->nonzero_max, "--raw");
if (errno)
{
perror("vector_sparse_fscan_raw - cannot scan a->positions");
goto a_free;
}
if(!vector_sparse_positions_possible(a->length, a->nonzero_max, a->positions))
{
errno = EINVAL;
perror("vector_sparse_fscan_raw - a->positions is impossible");
goto a_positions_free;
}
a->values = double_array_fscan(in, a->nonzero_max, "--raw");
if (errno)
{
perror("vector_sparse_fscan_raw - cannot scan a->values");
goto a_positions_free;
}
return a;
/* cleaning if an error occurs */
a_positions_free:
free(a->positions);
a_free:
free(a);
end:
return NULL;
}
|
sdgcpae/Hybris_DevOps
|
bin/custom/training/trainingfulfilmentprocess/testsrc/com/hybris/training/fulfilmentprocess/test/beans/QueueServiceImpl.java
|
<filename>bin/custom/training/trainingfulfilmentprocess/testsrc/com/hybris/training/fulfilmentprocess/test/beans/QueueServiceImpl.java
/*
* Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved.
*/
package com.hybris.training.fulfilmentprocess.test.beans;
/**
*
*/
public class QueueServiceImpl implements QueueService
{
/*
* private Map<BusinessProcessModel, BlockingQueue<ActionExecution>> nodeExecutions;
*
* @Override public void init() {
*
* nodeExecutions = Collections.synchronizedMap(LazyMap.decorate( new HashMap<BusinessProcessModel,
* BlockingQueue<ActionExecution>>(), new Factory() {
*
* @Override public Object create() { return new SynchronousQueue<ActionExecution>(); } })); }
*
* @Override public void actionExecuted(final BusinessProcessModel process, final AbstractAction action) throws
* Exception { if (nodeExecutions == null) {
* Logger.getLogger(this.getClass()).error("No nodeExecutions available"); } else { final
* BlockingQueue<ActionExecution> queue = nodeExecutions.get(process); queue.offer(new ActionExecution(process,
* action), 30, TimeUnit.SECONDS); Logger.getLogger(this.getClass()).info("actionExecuted " + action.getClass()); }
*
*
* }
*
* @Override public ActionExecution pollQueue(final BusinessProcessModel process) throws InterruptedException { final
* BlockingQueue<ActionExecution> queue = nodeExecutions.get(process); final ActionExecution exec = queue.poll(30,
* TimeUnit.SECONDS); assertNotNull("No node execution in queue. Timeout?", exec);
*
* Logger.getLogger(this.getClass()).info("pollQueue " + exec.getAction().getClass()); return exec; }
*
* @Override public void destroy() { if (nodeExecutions != null) { for (final BlockingQueue<ActionExecution> queue :
* nodeExecutions.values()) { queue.drainTo(new ArrayList<ActionExecution>()); } nodeExecutions = null; } }
*/
}
|
owynrichen/animalpants
|
FootGame/EnvironmentRepository.h
|
//
// Environment.h
// FootGame
//
// Created by <NAME> on 7/2/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Environment.h"
#import "BaseRepository.h"
@interface EnvironmentRepository : BaseRepository
@property (nonatomic, readonly) NSMutableDictionary *environments;
+(EnvironmentRepository *) sharedRepository;
-(Environment *) getEnvironment: (NSString *) key;
@end
|
sinmetal/angular_study
|
vendor/github.com/favclip/qbg/misc/fixture/c/model.go
|
//go:generate qbg -output model_query.go .
package c
import "time"
// +qbg
type Sample struct {
ID int64 `goon:"id"`
CreatedAt time.Time `datastore:",noindex"`
}
|
lyfls/mallplus
|
mall-portal/src/main/java/com/zscat/mallplus/util/JedisUtil.java
|
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.zscat.mallplus.util;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import javax.annotation.Resource;
public class JedisUtil {
static Logger log = LoggerFactory.getLogger(JedisUtil.class);
@Resource
private static JedisPool jedisPool;
public static Jedis getResource() {
Jedis client = jedisPool.getResource();
return client;
}
public static void returnResource(Jedis resource) {
resource.close();
}
public static void shutdown() {
jedisPool.destroy();
}
public static String hget(String key, String field) {
if (StringUtils.isBlank(key)) {
return "";
} else {
Jedis jedis = getResource();
String var4;
try {
String var3 = jedis.hget(key, field);
return var3;
} catch (Exception var8) {
log.error("Error hget, key:" + key + ", field:" + field, var8);
if (jedis != null && jedis.isConnected()) {
returnResource(jedis);
}
var4 = "";
} finally {
if (null != jedis && jedis.isConnected()) {
returnResource(jedis);
}
}
return var4;
}
}
public static void setex(String key, int seconds, String value) {
if (!StringUtils.isBlank(key)) {
Jedis jedis = getResource();
try {
jedis.setex(key, seconds, value);
return;
} catch (Exception var8) {
log.error("Error setex, key:" + key + ", value:" + value, var8);
if (jedis != null && jedis.isConnected()) {
returnResource(jedis);
}
} finally {
if (null != jedis && jedis.isConnected()) {
returnResource(jedis);
}
}
}
}
public static boolean keyExists(String key) {
if (StringUtils.isBlank(key)) {
return false;
} else {
Jedis jedis = getResource();
boolean var3;
try {
boolean var2 = jedis.exists(key);
return var2;
} catch (Exception var7) {
log.error("Error keyExists, key:" + key, var7);
if (jedis != null && jedis.isConnected()) {
returnResource(jedis);
}
var3 = false;
} finally {
if (null != jedis && jedis.isConnected()) {
returnResource(jedis);
}
}
return var3;
}
}
}
|
razyer/MyJavaDesignPattern
|
src/abstractfactory/NYPizzaIngredientFactory.java
|
package abstractfactory;
public class NYPizzaIngredientFactory implements PizzaIngredientFactory {
@Override
public Dough createDough() {
return new NYDough();
}
@Override
public Sauce createSauce() {
return new NYSauce();
}
}
|
smolnar82/cloudbreak
|
mock-infrastructure/src/generated/com/sequenceiq/mock/swagger/model/ApiActivityStatus.java
|
package com.sequenceiq.mock.swagger.model;
import java.util.Objects;
import io.swagger.annotations.ApiModel;
import com.fasterxml.jackson.annotation.JsonValue;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import javax.validation.constraints.*;
import com.fasterxml.jackson.annotation.JsonCreator;
/**
*
*/
public enum ApiActivityStatus {
UNKNOWN("UNKNOWN"),
SUBMITTED("SUBMITTED"),
STARTED("STARTED"),
SUSPENDED("SUSPENDED"),
FAILED("FAILED"),
KILLED("KILLED"),
SUCCEEDED("SUCCEEDED"),
ASSUMED_SUCCEEDED("ASSUMED_SUCCEEDED");
private String value;
ApiActivityStatus(String value) {
this.value = value;
}
@Override
@JsonValue
public String toString() {
return String.valueOf(value);
}
@JsonCreator
public static ApiActivityStatus fromValue(String text) {
for (ApiActivityStatus b : ApiActivityStatus.values()) {
if (String.valueOf(b.value).equals(text)) {
return b;
}
}
return null;
}
}
|
masud-technope/ACER-Replication-Package-ASE2017
|
corpus/class/ecf/2266.java
|
<reponame>masud-technope/ACER-Replication-Package-ASE2017
/****************************************************************************
* Copyright (c) 2008 Composent, Inc. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Composent, Inc. - initial API and implementation
*****************************************************************************/
package org.eclipse.ecf.tests.remoteservice.generic;
import java.util.Dictionary;
import java.util.Hashtable;
import org.eclipse.ecf.remoteservice.IRemoteService;
import org.eclipse.ecf.remoteservice.IRemoteServiceContainerAdapter;
import org.eclipse.ecf.remoteservice.IRemoteServiceListener;
import org.eclipse.ecf.remoteservice.IRemoteServiceReference;
import org.eclipse.ecf.remoteservice.events.IRemoteServiceEvent;
import org.eclipse.ecf.remoteservice.events.IRemoteServiceRegisteredEvent;
import org.eclipse.ecf.remoteservice.util.tracker.RemoteServiceTracker;
import org.eclipse.ecf.tests.remoteservice.AbstractRemoteServiceTest;
import org.eclipse.ecf.tests.remoteservice.IConcatService;
import org.eclipse.equinox.concurrent.future.IFuture;
import org.eclipse.osgi.util.NLS;
/**
*
*/
public class SSLRemoteServiceTrackerTest extends AbstractRemoteServiceTest {
RemoteServiceTracker remoteServiceTracker;
/*
* (non-Javadoc)
*
* @see org.eclipse.ecf.tests.remoteservice.AbstractRemoteServiceTest#
* getClientContainerName()
*/
protected String getClientContainerName() {
return SSLGeneric.CONSUMER_CONTAINER_TYPE;
}
protected String getServerIdentity() {
return NLS.bind(SSLGeneric.HOST_CONTAINER_ENDPOINT_ID, new Integer(genericServerPort));
}
protected String getServerContainerName() {
return SSLGeneric.HOST_CONTAINER_TYPE;
}
/*
* (non-Javadoc)
*
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception {
super.setUp();
setClientCount(2);
createServerAndClients();
setupRemoteServiceAdapters();
connectClients();
addRemoteServiceListeners();
}
/*
* (non-Javadoc)
*
* @see junit.framework.TestCase#tearDown()
*/
protected void tearDown() throws Exception {
cleanUpServerAndClients();
if (remoteServiceTracker != null) {
remoteServiceTracker.close();
}
super.tearDown();
}
protected IRemoteService getRemoteService(IRemoteServiceContainerAdapter adapter, String clazz, String filter) {
remoteServiceTracker = new RemoteServiceTracker(adapter, null, clazz, null);
assertNotNull(remoteServiceTracker);
remoteServiceTracker.open();
return remoteServiceTracker.getRemoteService();
}
public void testRemoteServiceTracker() throws Exception {
final IRemoteServiceContainerAdapter[] adapters = getRemoteServiceAdapters();
// client [0]/adapter[0] is the service 'server'
// client [1]/adapter[1] is the service target (client)
final Dictionary props = new Hashtable();
// Register
adapters[0].registerRemoteService(new String[] { IConcatService.class.getName() }, createService(), props);
// Give some time for propagation
sleep(3000);
final RemoteServiceTracker st = new RemoteServiceTracker(adapters[1], null, IConcatService.class.getName(), null);
assertNotNull(st);
st.open();
IRemoteService rs = st.getRemoteService();
final IConcatService concatService = (IConcatService) rs.getProxy();
assertNotNull(concatService);
System.out.println("proxy call start");
final String result = concatService.concat("OSGi ", "is cool");
System.out.println("proxy call end. result=" + result);
sleep(3000);
st.close();
sleep(3000);
}
IRemoteService remoteService;
boolean done;
public void testServiceListener() throws Exception {
final IRemoteServiceContainerAdapter[] adapters = getRemoteServiceAdapters();
done = false;
final Object lock = new Object();
adapters[1].addRemoteServiceListener(new IRemoteServiceListener() {
public void handleServiceEvent(IRemoteServiceEvent event) {
if (event instanceof IRemoteServiceRegisteredEvent) {
IRemoteServiceRegisteredEvent e = (IRemoteServiceRegisteredEvent) event;
IRemoteServiceReference ref = e.getReference();
remoteService = adapters[1].getRemoteService(ref);
assertNotNull(remoteService);
synchronized (lock) {
done = true;
lock.notify();
}
}
}
});
// Now register service on server (adapters[0]). This should result in
// notification on client (adapters[1])
// in above handleServiceEvent
adapters[0].registerRemoteService(new String[] { IConcatService.class.getName() }, createService(), customizeProperties(null));
// wait until block above called asynchronously
int count = 0;
synchronized (lock) {
while (!done && count++ < 10) {
try {
lock.wait(1000);
} catch (InterruptedException e) {
fail();
}
}
}
assertTrue(done);
if (remoteService == null)
return;
// We've got the remote service, so we're good to go
assertTrue(remoteService != null);
traceCallStart("callAsynchResult");
final IFuture result = remoteService.callAsync(createRemoteConcat("ECF AsynchResults ", "are cool"));
traceCallEnd("callAsynch");
assertNotNull(result);
Thread.sleep(SLEEPTIME);
}
}
|
Dbevan/SunderingShadows
|
d/atoyatl/tecqumin/mons/tabaxi_explorer.c
|
//Coded by Lujke
#include <std.h>
#include "../tecqumin.h"
#define EYECOLOUR ({"%^BOLD%^%^GREEN%^green%^RESET%^",\
"%^BOLD%^%^YELLOW%^yellow%^RESET%^"})
inherit MOB + "tabaxi";
int eyecolour;
void create()
{
object ob;
::create();
set_name("tabaxi");
set_id(({"tabaxi", "explorer", "tabaxi explorer" "humanoid"}));
set_short("tabaxi explorer");
switch (random(2)){
case 0:
set_gender("male");
break;
case 1:
set_gender("female");
}
set_long( (:TO, "long_desc":) );
set_race("tabaxi");
set_body_type("humanoid");
set_size(2);
set("aggressive",6);
set_class("fighter");
set_mlevel("fighter",45);
set_guild_level("fighter",45);
set_hp(random(500)+200);
set_max_level(45);
set_property("swarm",1);
set_overall_ac(-55);
set_alignment(4);
set_speed(1);
set_property("full attacks",1);
set_property("no random treasure", 1);
eyecolour = random(sizeof(EYECOLOUR));
ob = new(TABAXOBJ + "utility_belt");
ob->move(TO);
force_me("wear belt");
new(TABAXOBJ + "parchment_map")->move(ob);
new(OBJ + "bolas")->move(ob);
set_property("no random treasure", 1);
set_property("not random monster", 1);
}
void reply_func(string msg, object speaker){
string what, how, why;
object env;
env = ETO;
if (!objectp(env)||!objectp(speaker)||!present(speaker, env))
{
return;
}
if (interact("request", msg) && interact("aid", msg) && (interact("village", msg)
|| interact ("veellage", msg)))
{
if (speaker == requester || member_array(speaker->query_name(), commanders)!=-1)
{
return;
}
force_me("say Ahm busy explorin' at the moment. Ah'll help thee veelage when Ah get back");
requester = speaker;
}
if (requester == speaker && interact("yes", msg)|| interact ("yeah", msg) || interact ("yep", msg) || interact ("yah", msg))
{
give_belt(speaker);
}
if (requester == speaker) requester = 0;
if (interact("lost", msg) || interact ("find", msg) || interact("where", msg) || interact ("locat", msg))
{
force_me("say Are jew lost or looking for sumthin? ");
requester = speaker;
}
}
void give_belt(object who){
if (!present("utility belt", TO))
{
force_me("say I have nuthin' to give jew for 'elp at thee moment. Maybee another time?");
return;
}
force_me("say Well, ah can' leave jew strugglin' in thee jongle. Maybee thees will elp jew? Jus' remember thee tabaxi kindly if wee need jor 'elp sumtime");
force_me("give belt to " + who->query_name());
if (present("utility belt", TO) && !present("utility belt", who))
{
force_me("Well, jew can' carry eet jus' now. Ask me again when jew have more space");
}
}
string long_desc(){
string desc;
desc = "%^ORANGE%^This tabaxi is carrying a backpack and a belt equipped"
+" with various utility items. A fedora style hat is propped"
+" rakishly on " + QP + "hat. " + capitalize(QP)
+" brownish red coat has rosetted spots. " + capitalize(QS)
+" is tall and slender, with eyes of "
+ EYECOLOUR[eyecolour] +"%^ORANGE%^. "
+ capitalize(QS) + " has quick, stealthy movements, and "
+ QP +" coat"
+" pattern provides " + QO + " with natural camouflage.";
return desc;
}
|
CheyenneForbes/crate
|
enterprise/users/src/main/java/io/crate/plugin/AuthenticationModule.java
|
<reponame>CheyenneForbes/crate
/*
* This file is part of a module with proprietary Enterprise Features.
*
* Licensed to Crate.io Inc. ("Crate.io") under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* Unauthorized copying of this file, via any medium is strictly prohibited.
*
* To use this file, Crate.io must have given you permission to enable and
* use such Enterprise Features and you must have a valid Enterprise or
* Subscription Agreement with Crate.io. If you enable or use the Enterprise
* Features, you represent and warrant that you have a valid Enterprise or
* Subscription Agreement with Crate.io. Your use of the Enterprise Features
* if governed by the terms and conditions of your Enterprise or Subscription
* Agreement with Crate.io.
*/
package io.crate.plugin;
import io.crate.auth.AlwaysOKAuthentication;
import io.crate.auth.AuthSettings;
import io.crate.auth.Authentication;
import io.crate.auth.HostBasedAuthentication;
import org.elasticsearch.common.inject.AbstractModule;
import org.elasticsearch.common.settings.Settings;
public class AuthenticationModule extends AbstractModule {
private final Settings settings;
public AuthenticationModule(Settings settings) {
this.settings = settings;
}
@Override
protected void configure() {
if (AuthSettings.AUTH_HOST_BASED_ENABLED_SETTING.setting().get(settings)) {
bind(Authentication.class).to(HostBasedAuthentication.class);
} else {
bind(Authentication.class).to(AlwaysOKAuthentication.class);
}
bind(AuthenticationHttpAuthHandlerRegistry.class).asEagerSingleton();
}
}
|
gmlueck/llvm-test-suite
|
SingleSource/Regression/C/gcc-c-torture/execute/pr28865.c
|
struct A { int a; char b[]; };
union B { struct A a; char b[sizeof (struct A) + 31]; };
union B b = { { 1, "123456789012345678901234567890" } };
union B c = { { 2, "123456789012345678901234567890" } };
__attribute__((noinline, noclone)) void
foo (int *x[2])
{
x[0] = &b.a.a;
x[1] = &c.a.a;
}
int
main ()
{
int *x[2];
foo (x);
if (*x[0] != 1 || *x[1] != 2)
__builtin_abort ();
return 0;
}
|
epfml/pax
|
pax/utils/__init__.py
|
<reponame>epfml/pax
from .call_stack import CallStack
|
padorang684/swc
|
crates/swc_ecma_minifier/tests/fixture/projects/underscore/3/input.js
|
_.max = function (obj, iterator, context) {
if (
!iterator &&
_.isArray(obj) &&
obj[0] === +obj[0] &&
obj.length < 65535
) {
return Math.max.apply(Math, obj);
}
if (!iterator && _.isEmpty(obj)) return -Infinity;
var result = { computed: -Infinity, value: -Infinity };
each(obj, function (value, index, list) {
var computed = iterator
? iterator.call(context, value, index, list)
: value;
computed > result.computed &&
(result = { value: value, computed: computed });
});
return result.value;
};
|
MobButcher/Charm
|
src/main/java/svenhjol/charm/module/automatic_recipe_unlock/AutomaticRecipeUnlock.java
|
package svenhjol.charm.module.automatic_recipe_unlock;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerEntityEvents;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.crafting.Recipe;
import net.minecraft.world.item.crafting.RecipeManager;
import svenhjol.charm.Charm;
import svenhjol.charm.annotation.CommonModule;
import svenhjol.charm.loader.CharmModule;
import java.util.Collection;
@CommonModule(mod = Charm.MOD_ID, description = "Unlocks all vanilla recipes.")
public class AutomaticRecipeUnlock extends CharmModule {
@Override
public void runWhenEnabled() {
ServerEntityEvents.ENTITY_LOAD.register(this::handleServerJoin);
}
private void handleServerJoin(Entity entity, ServerLevel level) {
if (!Charm.LOADER.isEnabled(AutomaticRecipeUnlock.class))
return;
if (entity instanceof Player player) {
RecipeManager recipeManager = player.level.getRecipeManager();
Collection<Recipe<?>> allRecipes = recipeManager.getRecipes();
player.awardRecipes(allRecipes);
}
}
}
|
JiiHu/potentiaali
|
src/pages/SubjectsPage.js
|
import React from "react";
import { Physics } from "./subjects/Physics";
import { Geophysics } from "./subjects/Geophysics";
import { Meteorology } from "./subjects/Meteorology";
import { Geology } from "./subjects/Geology";
import { Geography } from "./subjects/Geography";
import { Astronomy } from "./subjects/Astronomy";
import { Chemistry } from "./subjects/Chemistry";
import { Statistics } from "./subjects/Statistics";
import { Mathematics } from "./subjects/Mathematics";
import { ComputerScience } from "./subjects/ComputerScience";
import { Localized } from "fluent-react/compat";
const SubjectsPage = () => {
return (
<>
<section className="app-section">
<h1>
<Localized id="subjects-page-title-text">Aineiden esittely</Localized>
</h1>
<Physics />
<Geophysics />
<Geology />
<Chemistry />
<Geography />
<Mathematics />
<Meteorology />
<ComputerScience />
<Statistics />
<Astronomy />
</section>
</>
);
};
SubjectsPage.propTypes = {};
export default SubjectsPage;
|
omerson-cruz/pollen
|
src/util/abbreviateNumber.test.js
|
import abbreviateNumber from './abbreviateNumber';
describe('abbreviateNumber', () => {
test('returns a string of a number that is less than 1000', () => {
expect(abbreviateNumber(999)).toEqual('999');
});
test('abbreviates 1000 to 1k', () => {
expect(abbreviateNumber(1000)).toEqual('1K');
});
test('abbreviates 1001 to 1k', () => {
expect(abbreviateNumber(1001)).toEqual('1K');
});
test('abbreviates 1234 to 1.2k', () => {
expect(abbreviateNumber(1234)).toEqual('1.2K');
});
test('abbreviates 100000 to 100K', () => {
expect(abbreviateNumber(100000)).toEqual('100K');
});
test('abbreviates 123456789 to 123.5M', () => {
expect(abbreviateNumber(123456789)).toEqual('123.5M');
});
test('returns null if value is null', () => {
expect(abbreviateNumber(null)).toEqual(null);
});
});
|
mapleque/cell
|
client/html/src/pages/components/Contributor.js
|
import React, { Component } from 'react'
import { Tag, Icon } from 'antd'
class Index extends Component {
constructor(props) {
super(props)
this.state = {}
}
render() {
return (
<a href={`https://github.com/${this.props.name}`}>
<Tag>
<Icon type='github'/>
<span style={{ marginLeft: 4 }}>{this.props.name}</span>
</Tag>
</a>
)
}
}
export default Index
|
cschreib/cobalt
|
common-netcom/include/shared_collection.hpp
|
#ifndef SHARED_COLLECTION_HPP
#define SHARED_COLLECTION_HPP
#include <scoped_connection_pool.hpp>
#include <sorted_vector.hpp>
#include "netcom_base.hpp"
using shared_collection_id_t = std::uint16_t;
namespace request {
NETCOM_PACKET(observe_shared_collection) {
shared_collection_id_t id;
struct answer {};
struct failure {};
};
NETCOM_PACKET(get_shared_collection_id) {
std::string name;
struct answer {
shared_collection_id_t id;
};
struct failure {
enum class reason {
no_such_collection
} rsn;
};
};
}
namespace message {
NETCOM_PACKET(leave_shared_collection) {
shared_collection_id_t id;
};
NETCOM_PACKET(shared_collection_add) {
shared_collection_id_t id;
};
NETCOM_PACKET(shared_collection_remove) {
shared_collection_id_t id;
};
NETCOM_PACKET(shared_collection_clear) {
shared_collection_id_t id;
};
}
#ifndef NO_AUTOGEN
#include "autogen/packets/shared_collection.hpp"
#endif
namespace shared_collection_exception {
struct too_many_collections : public netcom_exception::base {
too_many_collections() :
netcom_exception::base("error.netcom.too_many_shared_collections") {}
};
template<typename E>
struct missing_make_collection_delegate : public netcom_exception::base {
missing_make_collection_delegate() :
netcom_exception::base("error.netcom.missing_make_collection_delegate") {}
};
template<typename E>
struct wrong_collection_type : public netcom_exception::base {
wrong_collection_type() :
netcom_exception::base("error.netcom.wrong_collection_type") {}
};
template<typename E>
struct uninitialized_collection : public netcom_exception::base {
uninitialized_collection() :
netcom_exception::base("error.netcom.uninitialized_collection") {}
};
template<typename E>
struct uninitialized_observer : public netcom_exception::base {
uninitialized_observer() :
netcom_exception::base("error.netcom.uninitialized_observer") {}
};
}
class shared_collection_factory;
template<typename ElementTraits>
class shared_collection;
template<typename ElementTraits>
class shared_collection_observer;
namespace netcom_impl {
template<typename T>
struct get_register_packet {
template <typename U> static typename U::register_packet
dummy(typename U::register_packet*);
template <typename U> static ctl::empty_t dummy(...);
using type = decltype(dummy<T>(0));
};
template<typename T>
struct get_register_failed_packet {
template <typename U> static typename U::register_failed_packet
dummy(typename U::register_failed_packet*);
template <typename U> static ctl::empty_t dummy(...);
using type = decltype(dummy<T>(0));
};
template<typename T>
struct shared_collection_traits_proxy {
/// Request to join the collection (optional)
using register_packet = typename get_register_packet<T>::type;
/// Reason for failure to join the collection (optional)
using register_failed_packet = typename get_register_failed_packet<T>::type;
/// Request to send the full collection
using full_packet = typename T::full_packet;
/// Message sent when a new object is added
using add_packet = typename T::add_packet;
/// Message sent when an object is removed
using remove_packet = typename T::remove_packet;
/// Message sent when the collection is cleared
using clear_packet = typename T::clear_packet;
};
class shared_collection_base {
shared_collection_factory& factory_;
protected :
using observe_request = netcom_base::request_t<request::observe_shared_collection>;
using leave_message = netcom_base::message_t<message::leave_shared_collection>;
netcom_base& net_;
ctl::sorted_vector<actor_id_t> clients_;
bool connected_ = false;
virtual void register_and_send_collection_(observe_request& req) const = 0;
virtual void check_valid_() const = 0;
public :
const shared_collection_id_t id;
const std::string name;
shared_collection_base(shared_collection_factory& factory, netcom_base& net,
const std::string& name, shared_collection_id_t id);
virtual ~shared_collection_base();
void destroy();
void connect();
void disconnect();
bool is_connected() const;
void register_client(observe_request& req);
void unregister_client(actor_id_t cid);
};
template<typename ElementTraits>
class shared_collection_impl : public shared_collection_base {
using proxy = shared_collection_traits_proxy<ElementTraits>;
/// Request to join the collection
using register_collection_packet = typename proxy::register_packet;
/// Reason for failure to join the collection
using register_collection_failed_packet = typename proxy::register_failed_packet;
/// Request to send the full collection
using full_collection_packet = typename proxy::full_packet;
/// Message sent when a new object is added
using add_collection_element_packet = typename proxy::add_packet;
/// Message sent when an object is removed
using remove_collection_element_packet = typename proxy::remove_packet;
/// Message sent when the whole collection is cleared
using clear_collection_packet = typename proxy::clear_packet;
void register_and_send_collection_(observe_request& req) const override {
register_collection_packet r;
register_collection_failed_packet rf;
req.packet >> r;
if (register_client.empty() || register_client(r, rf)) {
full_collection_packet p;
make_collection_packet(p);
req.answer_custom(std::move(p));
} else {
req.fail_custom(std::move(rf));
}
}
void check_valid_() const override {
if (make_collection_packet.empty()) {
throw shared_collection_exception::missing_make_collection_delegate<ElementTraits>{};
}
}
public :
shared_collection_impl(shared_collection_factory& factory, netcom_base& net,
const std::string& name, shared_collection_id_t id) :
shared_collection_base(factory, net, name, id) {}
ctl::delegate<bool(const register_collection_packet& reg,
register_collection_failed_packet& failure)> register_client;
ctl::delegate<void(full_collection_packet& req)> make_collection_packet;
template<typename ... Args>
void add_item(Args&& ... args) const {
if (!connected_) return;
auto p = net_.create_custom_message<message::shared_collection_add>(
id, make_packet<add_collection_element_packet>(std::forward<Args>(args)...)
);
for (auto cid : clients_) {
p.to = cid;
net_.send(p);
}
}
template<typename ... Args>
void remove_item(Args&& ... args) const {
if (!connected_) return;
auto p = net_.create_custom_message<message::shared_collection_remove>(
id, make_packet<remove_collection_element_packet>(std::forward<Args>(args)...)
);
for (auto cid : clients_) {
p.to = cid;
net_.send(p);
}
}
void clear() const {
if (!connected_) return;
auto p = net_.create_custom_message<message::shared_collection_remove>(
id, make_packet<clear_collection_packet>()
);
for (auto cid : clients_) {
p.to = cid;
net_.send(p);
}
}
};
class shared_collection_observer_dispatcher_base {
protected :
using add_message = netcom_base::message_t<message::shared_collection_add>;
using remove_message = netcom_base::message_t<message::shared_collection_remove>;
using clear_message = netcom_base::message_t<message::shared_collection_clear>;
netcom_base& net_;
public :
shared_collection_observer_dispatcher_base(netcom_base& net, shared_collection_id_t id) :
net_(net), id(id) {}
virtual ~shared_collection_observer_dispatcher_base() = default;
const shared_collection_id_t id;
virtual void add_item(const add_message& msg) = 0;
virtual void remove_item(const remove_message& msg) = 0;
virtual void clear(const clear_message& msg) = 0;
};
template<typename ElementTraits>
class shared_collection_observer_dispatcher : public shared_collection_observer_dispatcher_base {
using proxy = shared_collection_traits_proxy<ElementTraits>;
/// Message sent when a new object is added
using add_collection_element_packet = typename proxy::add_packet;
/// Message sent when an object is removed
using remove_collection_element_packet = typename proxy::remove_packet;
/// Message sent when an object is removed
using clear_collection_packet = typename proxy::clear_packet;
friend class shared_collection_observer<ElementTraits>;
signal_t<void(const add_collection_element_packet&)> add_signal_;
signal_t<void(const remove_collection_element_packet&)> remove_signal_;
signal_t<void(const clear_collection_packet&)> clear_signal_;
public :
shared_collection_observer_dispatcher(netcom_base& net, shared_collection_id_t id) :
shared_collection_observer_dispatcher_base(net, id) {}
void add_item(const add_message& msg) override {
add_collection_element_packet add;
msg.packet.view() >> add;
add_signal_.dispatch(add);
}
void remove_item(const remove_message& msg) override {
remove_collection_element_packet rem;
msg.packet.view() >> rem;
remove_signal_.dispatch(rem);
}
void clear(const clear_message& msg) override {
clear_collection_packet clr;
msg.packet.view() >> clr;
clear_signal_.dispatch(clr);
}
shared_collection_observer<ElementTraits> create_observer() {
return shared_collection_observer<ElementTraits>(*this, net_);
}
};
}
/// Collection of objects shared over the network.
/** Note that this class does not actually hold any element in memory. It just provides the
interface for clients to "connect" to a collection of elements, i.e. :
- upon "connection", a client is sent the whole content of the collection
- the client is notified each time an element is added or removed from the collection
- the client can "disconnect" at any time from the collection to stop receiving updates
This class only takes care of the "connection" problem. The actual data that gets sent over
the network when the full collection is shared, or when an object is added/removed is set
by the owner of the shared_collection. See add_item(), remove_item() and
make_collection_packet.
The network packets that are sent are configured through the ElementTraits template
argument. It must define:
- full_packet: packet sent by clients to request the full collection
- add_packet: packet sent to clients when a new object is added
- remove_packet: packet sent to clients when an object is removed
This is the server side class. The complementary interface for clients is provided by
shared_collection_observer.
**/
template<typename ElementTraits>
class shared_collection {
using proxy = netcom_impl::shared_collection_traits_proxy<ElementTraits>;
using register_collection_packet = typename proxy::register_packet;
using register_collection_failed_packet = typename proxy::register_failed_packet;
using full_collection_packet = typename proxy::full_packet;
friend class shared_collection_factory;
netcom_impl::shared_collection_impl<ElementTraits>* impl_ = nullptr;
/// Construct a disconnected collection.
/** One has to call connect() in order for this collection to be visible on the network.
In its default state, the collection cannot accept connections of clients.
**/
shared_collection(netcom_impl::shared_collection_impl<ElementTraits>& impl) : impl_(&impl) {}
void check_() const {
if (!impl_) {
throw shared_collection_exception::uninitialized_collection<ElementTraits>{};
}
}
void destroy_() {
if (!impl_) return;
impl_->destroy();
impl_ = nullptr;
}
public :
/// Construct an invalid collection.
/** Collections are created by a shared_collection_factory.
**/
shared_collection() = default;
shared_collection(const shared_collection&) = delete;
shared_collection(shared_collection&& c) noexcept : impl_(c.impl_) {
c.impl_ = nullptr;
}
shared_collection& operator=(const shared_collection&) = delete;
shared_collection& operator=(shared_collection&& c) {
destroy_();
std::swap(impl_, c.impl_);
return *this;
}
~shared_collection() {
destroy_();
}
/// Make this collection visible on the network.
/** The collection can now accept connections of clients.
If the collection was already connected, it is first disconnected then re-connected,
thus all clients are lost.
**/
void connect() {
check_();
impl_->connect();
}
/// Remove this collection from the network.
/**
**/
void disconnect() {
if (!impl_) return;
impl_->disconnect();
}
bool is_connected() const {
if (!impl_) return false;
return impl_->is_connected();
}
shared_collection_id_t id() const {
check_();
return impl_->id;
}
template<typename F>
void make_collection_packet(F&& func) {
static_assert(ctl::argument_count<F>::value == 1,
"make_collection_packet function can only take one argument (collection packet)");
using ArgType = typename std::decay<ctl::function_argument<F>>::type;
static_assert(std::is_same<ArgType, full_collection_packet>::value,
"argument of make_collection_packet function must be a <trait>::full_packet");
check_();
impl_->make_collection_packet = std::forward<F>(func);
}
private :
template<typename F>
void register_client_(F&& func, std::integral_constant<std::size_t,2>) {
using ArgTypes = ctl::function_arguments<F>;
using Arg1 = ctl::type_list_element<0,ArgTypes>;
using Arg2 = ctl::type_list_element<1,ArgTypes>;
static_assert(std::is_same<Arg1, register_collection_packet>::value,
"first argument of register_client function must be a <trait>::register_packet");
static_assert(std::is_same<Arg2, register_collection_failed_packet>::value,
"second argument of register_client function must be a <trait>::register_failed_packet");
impl_->register_client = std::forward<F>(func);
}
template<typename F>
void register_client_(F&& func, std::integral_constant<std::size_t,1>) {
using ArgType = typename std::decay<ctl::function_argument<F>>::type;
static_assert(std::is_empty<register_collection_failed_packet>::value,
"register_client function is missing failure packet in its signature (the failure "
"packet is not empty and thus cannot be ignored)");
static_assert(std::is_same<ArgType, register_collection_packet>::value,
"first argument of register_client function must be a <trait>::register_packet");
impl_->register_client = [func](const register_collection_packet& reg,
register_collection_failed_packet& failure) {
return func(reg);
};
}
public :
template<typename F>
void register_client(F&& func) {
static_assert(ctl::argument_count<F>::value == 1 || ctl::argument_count<F>::value == 2,
"register_client function can only take one or two arguments (input request packet "
"and an optional output failure packet");
check_();
register_client_(std::forward<F>(func), ctl::argument_count<F>{});
}
template<typename ... Args>
void add_item(Args&& ... args) const {
check_();
impl_->add_item(std::forward<Args>(args)...);
}
template<typename ... Args>
void remove_item(Args&& ... args) const {
check_();
impl_->remove_item(std::forward<Args>(args)...);
}
void clear() const {
check_();
impl_->clear();
}
};
template<typename ElementTraits>
class shared_collection_observer {
using proxy = netcom_impl::shared_collection_traits_proxy<ElementTraits>;
using register_collection_packet = typename proxy::register_packet;
using register_collection_failed_packet = typename proxy::register_failed_packet;
using full_collection_packet = typename proxy::full_packet;
using add_collection_element_packet = typename proxy::add_packet;
using remove_collection_element_packet = typename proxy::remove_packet;
using clear_collection_packet = typename proxy::clear_packet;
using observe_answer = netcom_base::request_answer_t<request::observe_shared_collection>;
using dispatcher_t = netcom_impl::shared_collection_observer_dispatcher<ElementTraits>;
friend dispatcher_t;
dispatcher_t* dispatcher_ = nullptr;
netcom_base* net_ = nullptr;
scoped_connection_pool pool_;
actor_id_t aid_;
bool connected_ = false;
explicit shared_collection_observer(dispatcher_t& d, netcom_base& net) :
dispatcher_(&d), net_(&net) {}
public :
shared_collection_observer() = default;
shared_collection_observer(const shared_collection_observer&) = delete;
shared_collection_observer(shared_collection_observer&& o) :
dispatcher_(o.dispatcher_), net_(o.net_), pool_(std::move(o.pool_)), aid_(o.aid_),
connected_(o.connected_) {
o.dispatcher_ = nullptr;
o.net_ = nullptr;
o.connected_ = false;
}
shared_collection_observer& operator=(const shared_collection_observer&) = delete;
shared_collection_observer& operator=(shared_collection_observer&& o) {
disconnect();
dispatcher_ = o.dispatcher_; o.dispatcher_ = nullptr;
net_ = o.net_; o.net_ = nullptr;
pool_ = std::move(o.pool_);
aid_ = o.aid_;
connected_ = o.connected_; o.connected_ = false;
return *this;
}
~shared_collection_observer() noexcept {
disconnect();
}
/// Triggered when the full collection is received.
signal_t<void(const full_collection_packet&)> on_received;
/// Triggered if registration to the collection failed.
signal_t<void(const register_collection_failed_packet&)> on_register_fail;
/// Triggered if the collection does not exist.
signal_t<void()> on_register_unhandled;
/// Triggered when a new item is added to the collection.
signal_t<void(const add_collection_element_packet&)> on_add_item;
/// Triggered when an item is removed from the collection.
signal_t<void(const remove_collection_element_packet&)> on_remove_item;
/// Triggered when the collection is cleared.
signal_t<void(const clear_collection_packet&)> on_clear;
/// Triggered when the collection is disconnected.
signal_t<void()> on_disconnect;
template<typename T = register_collection_packet>
void connect(actor_id_t aid, T&& arg = register_collection_packet()) {
using ArgType = typename std::decay<T>::type;
static_assert(std::is_same<ArgType, register_collection_packet>::value,
"argument of connect() must be a <trait>::register_packet");
if (!net_ || !dispatcher_) {
throw shared_collection_exception::uninitialized_observer<ElementTraits>{};
}
disconnect();
aid_ = aid;
serialized_packet p;
p << make_packet<request::observe_shared_collection>(id());
p << std::forward<T>(arg);
pool_ << net_->send_custom_request<request::observe_shared_collection>(
aid_, std::move(p),
[this](const observe_answer& msg) {
if (msg.failed) {
if (msg.unhandled) {
on_register_unhandled.dispatch();
} else {
register_collection_failed_packet fail;
msg.packet.view() >> fail;
on_register_fail.dispatch(fail);
}
} else {
full_collection_packet ans;
msg.packet.view() >> ans;
pool_ << dispatcher_->add_signal_.connect(
[this](const add_collection_element_packet& p) {
on_add_item.dispatch(p);
}
);
pool_ << dispatcher_->remove_signal_.connect(
[this](const remove_collection_element_packet& p) {
on_remove_item.dispatch(p);
}
);
pool_ << dispatcher_->clear_signal_.connect(
[this](const clear_collection_packet& p) {
on_clear.dispatch(p);
}
);
connected_ = true;
on_received.dispatch(ans);
}
}
);
}
void disconnect() {
if (!connected_) return;
on_disconnect.dispatch();
net_->send_message(aid_, make_packet<message::leave_shared_collection>(id()));
pool_.stop_all();
connected_ = false;
}
bool is_connected() const {
return connected_;
}
shared_collection_id_t id() const {
if (!dispatcher_) return 0;
return dispatcher_->id;
}
};
class shared_collection_factory {
friend class netcom_impl::shared_collection_base;
netcom_base& net_;
using collection_container = ctl::sorted_vector<
std::unique_ptr<netcom_impl::shared_collection_base>,
mem_var_comp(&netcom_impl::shared_collection_base::id)
>;
collection_container collections_;
ctl::unique_id_provider<shared_collection_id_t> id_provider_;
using observer_container = ctl::sorted_vector<
std::unique_ptr<netcom_impl::shared_collection_observer_dispatcher_base>,
mem_var_comp(&netcom_impl::shared_collection_observer_dispatcher_base::id)
>;
observer_container observers_;
scoped_connection_pool pool_;
void destroy_(shared_collection_id_t id);
public :
explicit shared_collection_factory(netcom_base& net);
template<typename T>
shared_collection<T> make_shared_collection(const std::string& name) {
using collection_t = netcom_impl::shared_collection_impl<T>;
shared_collection_id_t id;
if (!id_provider_.make_id(id)) {
throw shared_collection_exception::too_many_collections{};
}
auto p = std::make_unique<collection_t>(*this, net_, name, id);
collection_t* cptr = p.get();
collections_.insert(std::move(p));
return shared_collection<T>(*cptr);
}
template<typename T>
shared_collection_observer<T> make_shared_collection_observer(shared_collection_id_t id) {
using dispatcher_t = netcom_impl::shared_collection_observer_dispatcher<T>;
dispatcher_t* dptr = nullptr;
auto iter = observers_.find(id);
if (iter == observers_.end()) {
auto p = std::make_unique<dispatcher_t>(net_, id);
dptr = p.get();
observers_.insert(std::move(p));
} else {
dptr = dynamic_cast<dispatcher_t*>(iter->get());
if (!dptr) {
throw shared_collection_exception::wrong_collection_type<T>{};
}
}
return dptr->create_observer();
}
void clear();
};
#endif
|
alphagov-mirror/content-audit-tool
|
spec/domain/audits/filter_spec.rb
|
<reponame>alphagov-mirror/content-audit-tool
module Audits
RSpec.describe Filter do
it { is_expected.to respond_to(:after) }
it { is_expected.to respond_to(:allocated_to) }
it { is_expected.to respond_to(:audit_status) }
it { is_expected.to respond_to(:document_type) }
it { is_expected.to respond_to(:organisations) }
it { is_expected.to respond_to(:page) }
it { is_expected.to respond_to(:per_page) }
it { is_expected.to respond_to(:primary_org_only) }
it { is_expected.to respond_to(:sort) }
it { is_expected.to respond_to(:sort_direction) }
it { is_expected.to respond_to(:theme_id) }
it { is_expected.to respond_to(:title) }
it { is_expected.to respond_to(:topics) }
context "initialized with blank organisations" do
subject { described_class.new(organisations: "") }
it { is_expected.to have_attributes(organisations: []) }
end
context "initialized with blank topics" do
subject { described_class.new(topics: "") }
it { is_expected.to have_attributes(topics: []) }
end
describe ".allocated_policy" do
subject { described_class.new(allocated_to: allocated_to) }
context "allocated to no one" do
let(:allocated_to) { "no_one" }
it {
is_expected.to have_attributes(allocated_policy: Policies::Unallocated)
}
end
context "allocated to anyone" do
let(:allocated_to) { "anyone" }
it { is_expected.to have_attributes(allocated_policy: Policies::NoPolicy) }
end
context "allocated to someone" do
let(:allocated_to) { "someone" }
it { is_expected.to have_attributes(allocated_policy: Policies::Allocated) }
end
context "allocated to not available" do
let(:allocated_to) { nil }
it { is_expected.to have_attributes(allocated_policy: Policies::NoPolicy) }
end
end
describe ".audited_policy" do
subject { described_class.new(audit_status: audit_status) }
context "audited" do
let(:audit_status) { :audited }
it {
is_expected.to have_attributes(audited_policy: Policies::Audited)
}
end
context "not audited" do
let(:audit_status) { :non_audited }
it { is_expected.to have_attributes(audited_policy: Policies::NonAudited) }
end
context "audit status not available" do
let(:audit_status) { nil }
it { is_expected.to have_attributes(audited_policy: Policies::NoPolicy) }
end
end
context "with allocated to" do
subject { described_class.new(allocated_to: :double) }
it { is_expected.to have_attributes(allocated_to: "double") }
end
context "with audit status" do
subject { described_class.new(audit_status: "double") }
it { is_expected.to have_attributes(audit_status: :double) }
end
context "with page" do
subject { described_class.new(page: "1") }
it { is_expected.to have_attributes(page: 1) }
end
context "with per page" do
subject { described_class.new(per_page: "10") }
it { is_expected.to have_attributes(per_page: 10) }
end
context "with sort criteria" do
subject { described_class.new(sort: "foo", sort_direction: "asc") }
it { is_expected.to have_attributes(sort_by: "foo_asc") }
end
end
end
|
google-ar/chromium
|
ios/chrome/browser/metrics/ios_chrome_origins_seen_service_factory.cc
|
<gh_stars>100-1000
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ios/chrome/browser/metrics/ios_chrome_origins_seen_service_factory.h"
#include "base/memory/ptr_util.h"
#include "base/memory/singleton.h"
#include "components/keyed_service/ios/browser_state_dependency_manager.h"
#include "components/navigation_metrics/origins_seen_service.h"
#include "ios/chrome/browser/browser_state/browser_state_otr_helper.h"
#include "ios/chrome/browser/browser_state/chrome_browser_state.h"
// static
navigation_metrics::OriginsSeenService*
IOSChromeOriginsSeenServiceFactory::GetForBrowserState(
ios::ChromeBrowserState* browser_state) {
return static_cast<navigation_metrics::OriginsSeenService*>(
GetInstance()->GetServiceForBrowserState(browser_state, true));
}
// static
IOSChromeOriginsSeenServiceFactory*
IOSChromeOriginsSeenServiceFactory::GetInstance() {
return base::Singleton<IOSChromeOriginsSeenServiceFactory>::get();
}
IOSChromeOriginsSeenServiceFactory::IOSChromeOriginsSeenServiceFactory()
: BrowserStateKeyedServiceFactory(
"OriginsSeenService",
BrowserStateDependencyManager::GetInstance()) {}
IOSChromeOriginsSeenServiceFactory::~IOSChromeOriginsSeenServiceFactory() {}
std::unique_ptr<KeyedService>
IOSChromeOriginsSeenServiceFactory::BuildServiceInstanceFor(
web::BrowserState* context) const {
return base::MakeUnique<navigation_metrics::OriginsSeenService>();
}
web::BrowserState* IOSChromeOriginsSeenServiceFactory::GetBrowserStateToUse(
web::BrowserState* context) const {
return GetBrowserStateOwnInstanceInIncognito(context);
}
|
chunkyguy/hideous-engine
|
HideousGameEngine/src/UI/Sprite.cpp
|
<gh_stars>1-10
//
// Sprite.cpp
// HideousGameEngine
//
// Created by Sid on 20/06/13.
// Copyright (c) 2013 whackylabs. All rights reserved.
//
#include <he/UI/Sprite.h>
#include <he/Animation/AnimationLoop.h>
#include <he/Animation/SpriteAnimation.h>
#include <he/Animation/AnimationUtils.h>
#include <he/RenderObject/RenderObject.h>
#include <he/Vertex/TextureVertex.h>
#include <he/Utils/Utils.h>
#include <he/Texture/TextureAtlas.h>
#include <he/Shaders/TextureShader.h>
#include <he/Texture/Texture.h>
#include <he/Vertex/TextureVertex.h>
#include <he/Texture/TextureAtlasRegion.h>
namespace he{
// namespace {
// class SpriteEndAnimationFunctor {
// public:
// SpriteEndAnimationFunctor(Animation::ID ID) :
// id_(ID) {}
//
// void operator()(Animation *anim) {
// if(anim->GetID() == id_){
// //animation->RetainCurrVertex();
// anim->Die();
// }
// }
//
// private:
// Animation::ID id_;
// };
//
//
// void SpriteEndAnimationsWithID(Animation::ID ID){
// g_AnimationLoop->TraverseAnimations(SpriteEndAnimationFunctor(ID));
// }
// }
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: Sprite
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Sprite::Sprite(const SpriteAnimationData *data,
const TextureShader *shader, const TextureAtlas *atlas,
const int repeat_count, AnimationListenable *listener,
const int final_frame, const float fps) :
vertex_(nullptr),
render_object_(),
size_(atlas->GetTextureAtlasRegion(he::FlashFullName(data->GetAnimationName())).sprite_size_)
{
animation_ = static_cast<SpriteAnimation*>(g_AnimationLoop->MoveAnimation(new SpriteAnimation(&vertex_, data, repeat_count, final_frame, fps)));
anim_id_ = animation_->GetID();
if (listener) {
animation_->SetListener(listener);
}
assert(vertex_); // There is some default vertex data.
render_object_ = new RenderObject(vertex_, shader, atlas->GetTexture());
}
Sprite::~Sprite(){
/*
Case 1: The Sprite dies after the SpriteAnimation.
1. Call the SpriteEndAnimationFunctor, would do no harm, as no anim_id_ exists.
X. Before dying the SpriteAnimation must have passed an allocated copy to vertex_.
X. Can safely delete the vertex_ now.
Case 2: The SpriteAnimation dies after Sprite.
X. The SpriteEndAnimationFunctor asks the SpriteAnimation to retain current-vertex.
X. Since 'this' is not NULL yet, so can be used to create an allocated copy for SpriteAnimation::Frame's vertex object.
X. Can safely delete the vertex_ now.
*/
animation::EndAnimationsWithID(EndAnimationFunctor::kAnimationID, anim_id_);
// SpriteEndAnimationsWithID(anim_id_);
// delete vertex_;
// vertex_ = nullptr;
delete render_object_;
}
Animation::ID Sprite::GetID() const {
return anim_id_;
}
void Sprite::Render(const Transform &transform){
render_object_->SetVertexData(vertex_);
render_object_->SetMVP(Transform_GetMVP(&transform));
render_object_->Render();
}
GLKVector2 Sprite::GetSize() const {
return size_;
}
void Sprite::GoToFrameNumber(unsigned int frame_num) {
animation_->GoToFrameNumber(frame_num);
}
unsigned int Sprite::GetCurrentFrameNumber() const {
return animation_->GetCurrentFrameNumber();
}
unsigned int Sprite::GetFrameCount() const {
return animation_->GetFrameCount();
}
void Sprite::StartAnimation() {
animation_->Run();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: Utility
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace sprite {
SpriteAnimationData *Create(const TextureAtlas *texture_atlas,
const std::string ®ion) {
return new SpriteAnimationData(texture_atlas, region);
}
Sprite *Create(const SpriteAnimationData *data,
const TextureShader *shader, const TextureAtlas *texture_atlas,
const int repeat_count, AnimationListenable *listener, const int final_frame, const float fps) {
return new Sprite(data, shader, texture_atlas, repeat_count, listener, final_frame, fps);
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: SpriteView
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
SpriteView::SpriteView(const Transform &transform, Sprite *sprite) :
View(transform),
sprite_(sprite)
{}
void SpriteView::Update(float dt) {
View::Update(dt);
}
void SpriteView::Render() {
sprite_->Render(GetTransform());
}
GLKVector2 SpriteView::GetSize() const {
return sprite_->GetSize();
}
}
///EOF
|
zhengweiye/zwyyf
|
netdisk-service-provider/src/main/java/com/micro/websocket/Message.java
|
<filename>netdisk-service-provider/src/main/java/com/micro/websocket/Message.java
package com.micro.websocket;
import java.io.Serializable;
import lombok.Data;
@Data
public class Message implements Serializable{
private Integer type;//0容量,1通知
private Object data;
private Integer count;
}
|
sushantsahu1987/qr-password-generator
|
app/src/main/java/com/tachyonic/qrpassword/ui/register/RegisterPresenter.java
|
package com.tachyonic.qrpassword.ui.register;
/**
* Created by ssahu on 3/27/2015.
*/
public interface RegisterPresenter {
}
|
ylil93/ydk-go
|
ydk/models/cisco_ios_xe/tunnel_mib/tunnel_mib.go
|
<gh_stars>0
// The MIB module for management of IP Tunnels,
// independent of the specific encapsulation scheme in
// use.
//
// Copyright (C) The Internet Society (2005). This
// version of this MIB module is part of RFC 4087; see
// the RFC itself for full legal notices.
package tunnel_mib
import (
"fmt"
"github.com/CiscoDevNet/ydk-go/ydk"
"github.com/CiscoDevNet/ydk-go/ydk/types"
"github.com/CiscoDevNet/ydk-go/ydk/types/yfilter"
"github.com/CiscoDevNet/ydk-go/ydk/models/cisco_ios_xe"
"reflect"
)
func init() {
ydk.YLogDebug(fmt.Sprintf("Registering top level entities for package tunnel_mib"))
ydk.RegisterEntity("{urn:ietf:params:xml:ns:yang:smiv2:TUNNEL-MIB TUNNEL-MIB}", reflect.TypeOf(TUNNELMIB{}))
ydk.RegisterEntity("TUNNEL-MIB:TUNNEL-MIB", reflect.TypeOf(TUNNELMIB{}))
}
// TUNNELMIB
type TUNNELMIB struct {
parent types.Entity
YFilter yfilter.YFilter
// The (conceptual) table containing information on configured tunnels.
Tunneliftable TUNNELMIB_Tunneliftable
// The (conceptual) table containing information on configured tunnels. This
// table can be used to map a set of tunnel endpoints to the associated
// ifIndex value. It can also be used for row creation. Note that every row
// in the tunnelIfTable with a fixed IPv4 destination address should have a
// corresponding row in the tunnelConfigTable, regardless of whether it was
// created via SNMP. Since this table does not support IPv6, it is deprecated
// in favor of tunnelInetConfigTable.
Tunnelconfigtable TUNNELMIB_Tunnelconfigtable
// The (conceptual) table containing information on configured tunnels. This
// table can be used to map a set of tunnel endpoints to the associated
// ifIndex value. It can also be used for row creation. Note that every row
// in the tunnelIfTable with a fixed destination address should have a
// corresponding row in the tunnelInetConfigTable, regardless of whether it
// was created via SNMP.
Tunnelinetconfigtable TUNNELMIB_Tunnelinetconfigtable
}
func (tUNNELMIB *TUNNELMIB) GetFilter() yfilter.YFilter { return tUNNELMIB.YFilter }
func (tUNNELMIB *TUNNELMIB) SetFilter(yf yfilter.YFilter) { tUNNELMIB.YFilter = yf }
func (tUNNELMIB *TUNNELMIB) GetGoName(yname string) string {
if yname == "tunnelIfTable" { return "Tunneliftable" }
if yname == "tunnelConfigTable" { return "Tunnelconfigtable" }
if yname == "tunnelInetConfigTable" { return "Tunnelinetconfigtable" }
return ""
}
func (tUNNELMIB *TUNNELMIB) GetSegmentPath() string {
return "TUNNEL-MIB:TUNNEL-MIB"
}
func (tUNNELMIB *TUNNELMIB) GetChildByName(childYangName string, segmentPath string) types.Entity {
if childYangName == "tunnelIfTable" {
return &tUNNELMIB.Tunneliftable
}
if childYangName == "tunnelConfigTable" {
return &tUNNELMIB.Tunnelconfigtable
}
if childYangName == "tunnelInetConfigTable" {
return &tUNNELMIB.Tunnelinetconfigtable
}
return nil
}
func (tUNNELMIB *TUNNELMIB) GetChildren() map[string]types.Entity {
children := make(map[string]types.Entity)
children["tunnelIfTable"] = &tUNNELMIB.Tunneliftable
children["tunnelConfigTable"] = &tUNNELMIB.Tunnelconfigtable
children["tunnelInetConfigTable"] = &tUNNELMIB.Tunnelinetconfigtable
return children
}
func (tUNNELMIB *TUNNELMIB) GetLeafs() map[string]interface{} {
leafs := make(map[string]interface{})
return leafs
}
func (tUNNELMIB *TUNNELMIB) GetBundleName() string { return "cisco_ios_xe" }
func (tUNNELMIB *TUNNELMIB) GetYangName() string { return "TUNNEL-MIB" }
func (tUNNELMIB *TUNNELMIB) GetBundleYangModelsLocation() string { return cisco_ios_xe.GetModelsPath() }
func (tUNNELMIB *TUNNELMIB) GetCapabilitiesTable() map[string]string {
return cisco_ios_xe.GetCapabilities() }
func (tUNNELMIB *TUNNELMIB) GetNamespaceTable() map[string]string {
return cisco_ios_xe.GetNamespaces() }
func (tUNNELMIB *TUNNELMIB) SetParent(parent types.Entity) { tUNNELMIB.parent = parent }
func (tUNNELMIB *TUNNELMIB) GetParent() types.Entity { return tUNNELMIB.parent }
func (tUNNELMIB *TUNNELMIB) GetParentYangName() string { return "TUNNEL-MIB" }
// TUNNELMIB_Tunneliftable
// The (conceptual) table containing information on
// configured tunnels.
type TUNNELMIB_Tunneliftable struct {
parent types.Entity
YFilter yfilter.YFilter
// An entry (conceptual row) containing the information on a particular
// configured tunnel. The type is slice of
// TUNNELMIB_Tunneliftable_Tunnelifentry.
Tunnelifentry []TUNNELMIB_Tunneliftable_Tunnelifentry
}
func (tunneliftable *TUNNELMIB_Tunneliftable) GetFilter() yfilter.YFilter { return tunneliftable.YFilter }
func (tunneliftable *TUNNELMIB_Tunneliftable) SetFilter(yf yfilter.YFilter) { tunneliftable.YFilter = yf }
func (tunneliftable *TUNNELMIB_Tunneliftable) GetGoName(yname string) string {
if yname == "tunnelIfEntry" { return "Tunnelifentry" }
return ""
}
func (tunneliftable *TUNNELMIB_Tunneliftable) GetSegmentPath() string {
return "tunnelIfTable"
}
func (tunneliftable *TUNNELMIB_Tunneliftable) GetChildByName(childYangName string, segmentPath string) types.Entity {
if childYangName == "tunnelIfEntry" {
for _, c := range tunneliftable.Tunnelifentry {
if tunneliftable.GetSegmentPath() == segmentPath {
return &c
}
}
child := TUNNELMIB_Tunneliftable_Tunnelifentry{}
tunneliftable.Tunnelifentry = append(tunneliftable.Tunnelifentry, child)
return &tunneliftable.Tunnelifentry[len(tunneliftable.Tunnelifentry)-1]
}
return nil
}
func (tunneliftable *TUNNELMIB_Tunneliftable) GetChildren() map[string]types.Entity {
children := make(map[string]types.Entity)
for i := range tunneliftable.Tunnelifentry {
children[tunneliftable.Tunnelifentry[i].GetSegmentPath()] = &tunneliftable.Tunnelifentry[i]
}
return children
}
func (tunneliftable *TUNNELMIB_Tunneliftable) GetLeafs() map[string]interface{} {
leafs := make(map[string]interface{})
return leafs
}
func (tunneliftable *TUNNELMIB_Tunneliftable) GetBundleName() string { return "cisco_ios_xe" }
func (tunneliftable *TUNNELMIB_Tunneliftable) GetYangName() string { return "tunnelIfTable" }
func (tunneliftable *TUNNELMIB_Tunneliftable) GetBundleYangModelsLocation() string { return cisco_ios_xe.GetModelsPath() }
func (tunneliftable *TUNNELMIB_Tunneliftable) GetCapabilitiesTable() map[string]string {
return cisco_ios_xe.GetCapabilities() }
func (tunneliftable *TUNNELMIB_Tunneliftable) GetNamespaceTable() map[string]string {
return cisco_ios_xe.GetNamespaces() }
func (tunneliftable *TUNNELMIB_Tunneliftable) SetParent(parent types.Entity) { tunneliftable.parent = parent }
func (tunneliftable *TUNNELMIB_Tunneliftable) GetParent() types.Entity { return tunneliftable.parent }
func (tunneliftable *TUNNELMIB_Tunneliftable) GetParentYangName() string { return "TUNNEL-MIB" }
// TUNNELMIB_Tunneliftable_Tunnelifentry
// An entry (conceptual row) containing the information
// on a particular configured tunnel.
type TUNNELMIB_Tunneliftable_Tunnelifentry struct {
parent types.Entity
YFilter yfilter.YFilter
// This attribute is a key. The type is string with range: 1..2147483647.
// Refers to if_mib.IFMIB_Iftable_Ifentry_Ifindex
Ifindex interface{}
// The address of the local endpoint of the tunnel (i.e., the source address
// used in the outer IP header), or 0.0.0.0 if unknown or if the tunnel is
// over IPv6. Since this object does not support IPv6, it is deprecated in
// favor of tunnelIfLocalInetAddress. The type is string with pattern:
// (([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(%[\p{N}\p{L}]+)?.
Tunneliflocaladdress interface{}
// The address of the remote endpoint of the tunnel (i.e., the destination
// address used in the outer IP header), or 0.0.0.0 if unknown, or an IPv6
// address, or the tunnel is not a point-to-point link (e.g., if it is a 6to4
// tunnel). Since this object does not support IPv6, it is deprecated in
// favor of tunnelIfRemoteInetAddress. The type is string with pattern:
// (([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(%[\p{N}\p{L}]+)?.
Tunnelifremoteaddress interface{}
// The encapsulation method used by the tunnel. The type is IANAtunnelType.
Tunnelifencapsmethod interface{}
// The IPv4 TTL or IPv6 Hop Limit to use in the outer IP header. A value of 0
// indicates that the value is copied from the payload's header. The type is
// interface{} with range: 0..255.
Tunnelifhoplimit interface{}
// The method used by the tunnel to secure the outer IP header. The value
// ipsec indicates that IPsec is used between the tunnel endpoints for
// authentication or encryption or both. More specific security-related
// information may be available in a MIB module for the security protocol in
// use. The type is Tunnelifsecurity.
Tunnelifsecurity interface{}
// The method used to set the high 6 bits (the differentiated services
// codepoint) of the IPv4 TOS or IPv6 Traffic Class in the outer IP header. A
// value of -1 indicates that the bits are copied from the payload's header.
// A value of -2 indicates that a traffic conditioner is invoked and more
// information may be available in a traffic conditioner MIB module. A value
// between 0 and 63 inclusive indicates that the bit field is set to the
// indicated value. Note: instead of the name tunnelIfTOS, a better name
// would have been tunnelIfDSCPMethod, but the existing name appeared in RFC
// 2667 and existing objects cannot be renamed. The type is interface{} with
// range: -2..63.
Tunneliftos interface{}
// The method used to set the IPv6 Flow Label value. This object need not be
// present in rows where tunnelIfAddressType indicates the tunnel is not over
// IPv6. A value of -1 indicates that a traffic conditioner is invoked and
// more information may be available in a traffic conditioner MIB. Any other
// value indicates that the Flow Label field is set to the indicated value.
// The type is interface{} with range: -1..100.
Tunnelifflowlabel interface{}
// The type of address in the corresponding tunnelIfLocalInetAddress and
// tunnelIfRemoteInetAddress objects. The type is InetAddressType.
Tunnelifaddresstype interface{}
// The address of the local endpoint of the tunnel (i.e., the source address
// used in the outer IP header). If the address is unknown, the value is
// 0.0.0.0 for IPv4 or :: for IPv6. The type of this object is given by
// tunnelIfAddressType. The type is string with length: 0..255.
Tunneliflocalinetaddress interface{}
// The address of the remote endpoint of the tunnel (i.e., the destination
// address used in the outer IP header). If the address is unknown or the
// tunnel is not a point-to-point link (e.g., if it is a 6to4 tunnel), the
// value is 0.0.0.0 for tunnels over IPv4 or :: for tunnels over IPv6. The
// type of this object is given by tunnelIfAddressType. The type is string
// with length: 0..255.
Tunnelifremoteinetaddress interface{}
// The maximum number of additional encapsulations permitted for packets
// undergoing encapsulation at this node. A value of -1 indicates that no
// limit is present (except as a result of the packet size). The type is
// interface{} with range: -1..255.
Tunnelifencapslimit interface{}
}
func (tunnelifentry *TUNNELMIB_Tunneliftable_Tunnelifentry) GetFilter() yfilter.YFilter { return tunnelifentry.YFilter }
func (tunnelifentry *TUNNELMIB_Tunneliftable_Tunnelifentry) SetFilter(yf yfilter.YFilter) { tunnelifentry.YFilter = yf }
func (tunnelifentry *TUNNELMIB_Tunneliftable_Tunnelifentry) GetGoName(yname string) string {
if yname == "ifIndex" { return "Ifindex" }
if yname == "tunnelIfLocalAddress" { return "Tunneliflocaladdress" }
if yname == "tunnelIfRemoteAddress" { return "Tunnelifremoteaddress" }
if yname == "tunnelIfEncapsMethod" { return "Tunnelifencapsmethod" }
if yname == "tunnelIfHopLimit" { return "Tunnelifhoplimit" }
if yname == "tunnelIfSecurity" { return "Tunnelifsecurity" }
if yname == "tunnelIfTOS" { return "Tunneliftos" }
if yname == "tunnelIfFlowLabel" { return "Tunnelifflowlabel" }
if yname == "tunnelIfAddressType" { return "Tunnelifaddresstype" }
if yname == "tunnelIfLocalInetAddress" { return "Tunneliflocalinetaddress" }
if yname == "tunnelIfRemoteInetAddress" { return "Tunnelifremoteinetaddress" }
if yname == "tunnelIfEncapsLimit" { return "Tunnelifencapslimit" }
return ""
}
func (tunnelifentry *TUNNELMIB_Tunneliftable_Tunnelifentry) GetSegmentPath() string {
return "tunnelIfEntry" + "[ifIndex='" + fmt.Sprintf("%v", tunnelifentry.Ifindex) + "']"
}
func (tunnelifentry *TUNNELMIB_Tunneliftable_Tunnelifentry) GetChildByName(childYangName string, segmentPath string) types.Entity {
return nil
}
func (tunnelifentry *TUNNELMIB_Tunneliftable_Tunnelifentry) GetChildren() map[string]types.Entity {
children := make(map[string]types.Entity)
return children
}
func (tunnelifentry *TUNNELMIB_Tunneliftable_Tunnelifentry) GetLeafs() map[string]interface{} {
leafs := make(map[string]interface{})
leafs["ifIndex"] = tunnelifentry.Ifindex
leafs["tunnelIfLocalAddress"] = tunnelifentry.Tunneliflocaladdress
leafs["tunnelIfRemoteAddress"] = tunnelifentry.Tunnelifremoteaddress
leafs["tunnelIfEncapsMethod"] = tunnelifentry.Tunnelifencapsmethod
leafs["tunnelIfHopLimit"] = tunnelifentry.Tunnelifhoplimit
leafs["tunnelIfSecurity"] = tunnelifentry.Tunnelifsecurity
leafs["tunnelIfTOS"] = tunnelifentry.Tunneliftos
leafs["tunnelIfFlowLabel"] = tunnelifentry.Tunnelifflowlabel
leafs["tunnelIfAddressType"] = tunnelifentry.Tunnelifaddresstype
leafs["tunnelIfLocalInetAddress"] = tunnelifentry.Tunneliflocalinetaddress
leafs["tunnelIfRemoteInetAddress"] = tunnelifentry.Tunnelifremoteinetaddress
leafs["tunnelIfEncapsLimit"] = tunnelifentry.Tunnelifencapslimit
return leafs
}
func (tunnelifentry *TUNNELMIB_Tunneliftable_Tunnelifentry) GetBundleName() string { return "cisco_ios_xe" }
func (tunnelifentry *TUNNELMIB_Tunneliftable_Tunnelifentry) GetYangName() string { return "tunnelIfEntry" }
func (tunnelifentry *TUNNELMIB_Tunneliftable_Tunnelifentry) GetBundleYangModelsLocation() string { return cisco_ios_xe.GetModelsPath() }
func (tunnelifentry *TUNNELMIB_Tunneliftable_Tunnelifentry) GetCapabilitiesTable() map[string]string {
return cisco_ios_xe.GetCapabilities() }
func (tunnelifentry *TUNNELMIB_Tunneliftable_Tunnelifentry) GetNamespaceTable() map[string]string {
return cisco_ios_xe.GetNamespaces() }
func (tunnelifentry *TUNNELMIB_Tunneliftable_Tunnelifentry) SetParent(parent types.Entity) { tunnelifentry.parent = parent }
func (tunnelifentry *TUNNELMIB_Tunneliftable_Tunnelifentry) GetParent() types.Entity { return tunnelifentry.parent }
func (tunnelifentry *TUNNELMIB_Tunneliftable_Tunnelifentry) GetParentYangName() string { return "tunnelIfTable" }
// TUNNELMIB_Tunneliftable_Tunnelifentry_Tunnelifsecurity represents security protocol in use.
type TUNNELMIB_Tunneliftable_Tunnelifentry_Tunnelifsecurity string
const (
TUNNELMIB_Tunneliftable_Tunnelifentry_Tunnelifsecurity_none TUNNELMIB_Tunneliftable_Tunnelifentry_Tunnelifsecurity = "none"
TUNNELMIB_Tunneliftable_Tunnelifentry_Tunnelifsecurity_ipsec TUNNELMIB_Tunneliftable_Tunnelifentry_Tunnelifsecurity = "ipsec"
TUNNELMIB_Tunneliftable_Tunnelifentry_Tunnelifsecurity_other TUNNELMIB_Tunneliftable_Tunnelifentry_Tunnelifsecurity = "other"
)
// TUNNELMIB_Tunnelconfigtable
// The (conceptual) table containing information on
// configured tunnels. This table can be used to map a
// set of tunnel endpoints to the associated ifIndex
// value. It can also be used for row creation. Note
// that every row in the tunnelIfTable with a fixed IPv4
// destination address should have a corresponding row in
// the tunnelConfigTable, regardless of whether it was
// created via SNMP.
//
// Since this table does not support IPv6, it is
// deprecated in favor of tunnelInetConfigTable.
type TUNNELMIB_Tunnelconfigtable struct {
parent types.Entity
YFilter yfilter.YFilter
// An entry (conceptual row) containing the information on a particular
// configured tunnel. Since this entry does not support IPv6, it is
// deprecated in favor of tunnelInetConfigEntry. The type is slice of
// TUNNELMIB_Tunnelconfigtable_Tunnelconfigentry.
Tunnelconfigentry []TUNNELMIB_Tunnelconfigtable_Tunnelconfigentry
}
func (tunnelconfigtable *TUNNELMIB_Tunnelconfigtable) GetFilter() yfilter.YFilter { return tunnelconfigtable.YFilter }
func (tunnelconfigtable *TUNNELMIB_Tunnelconfigtable) SetFilter(yf yfilter.YFilter) { tunnelconfigtable.YFilter = yf }
func (tunnelconfigtable *TUNNELMIB_Tunnelconfigtable) GetGoName(yname string) string {
if yname == "tunnelConfigEntry" { return "Tunnelconfigentry" }
return ""
}
func (tunnelconfigtable *TUNNELMIB_Tunnelconfigtable) GetSegmentPath() string {
return "tunnelConfigTable"
}
func (tunnelconfigtable *TUNNELMIB_Tunnelconfigtable) GetChildByName(childYangName string, segmentPath string) types.Entity {
if childYangName == "tunnelConfigEntry" {
for _, c := range tunnelconfigtable.Tunnelconfigentry {
if tunnelconfigtable.GetSegmentPath() == segmentPath {
return &c
}
}
child := TUNNELMIB_Tunnelconfigtable_Tunnelconfigentry{}
tunnelconfigtable.Tunnelconfigentry = append(tunnelconfigtable.Tunnelconfigentry, child)
return &tunnelconfigtable.Tunnelconfigentry[len(tunnelconfigtable.Tunnelconfigentry)-1]
}
return nil
}
func (tunnelconfigtable *TUNNELMIB_Tunnelconfigtable) GetChildren() map[string]types.Entity {
children := make(map[string]types.Entity)
for i := range tunnelconfigtable.Tunnelconfigentry {
children[tunnelconfigtable.Tunnelconfigentry[i].GetSegmentPath()] = &tunnelconfigtable.Tunnelconfigentry[i]
}
return children
}
func (tunnelconfigtable *TUNNELMIB_Tunnelconfigtable) GetLeafs() map[string]interface{} {
leafs := make(map[string]interface{})
return leafs
}
func (tunnelconfigtable *TUNNELMIB_Tunnelconfigtable) GetBundleName() string { return "cisco_ios_xe" }
func (tunnelconfigtable *TUNNELMIB_Tunnelconfigtable) GetYangName() string { return "tunnelConfigTable" }
func (tunnelconfigtable *TUNNELMIB_Tunnelconfigtable) GetBundleYangModelsLocation() string { return cisco_ios_xe.GetModelsPath() }
func (tunnelconfigtable *TUNNELMIB_Tunnelconfigtable) GetCapabilitiesTable() map[string]string {
return cisco_ios_xe.GetCapabilities() }
func (tunnelconfigtable *TUNNELMIB_Tunnelconfigtable) GetNamespaceTable() map[string]string {
return cisco_ios_xe.GetNamespaces() }
func (tunnelconfigtable *TUNNELMIB_Tunnelconfigtable) SetParent(parent types.Entity) { tunnelconfigtable.parent = parent }
func (tunnelconfigtable *TUNNELMIB_Tunnelconfigtable) GetParent() types.Entity { return tunnelconfigtable.parent }
func (tunnelconfigtable *TUNNELMIB_Tunnelconfigtable) GetParentYangName() string { return "TUNNEL-MIB" }
// TUNNELMIB_Tunnelconfigtable_Tunnelconfigentry
// An entry (conceptual row) containing the information
// on a particular configured tunnel.
//
// Since this entry does not support IPv6, it is
// deprecated in favor of tunnelInetConfigEntry.
type TUNNELMIB_Tunnelconfigtable_Tunnelconfigentry struct {
parent types.Entity
YFilter yfilter.YFilter
// This attribute is a key. The address of the local endpoint of the tunnel,
// or 0.0.0.0 if the device is free to choose any of its addresses at tunnel
// establishment time. Since this object does not support IPv6, it is
// deprecated in favor of tunnelInetConfigLocalAddress. The type is string
// with pattern:
// (([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(%[\p{N}\p{L}]+)?.
Tunnelconfiglocaladdress interface{}
// This attribute is a key. The address of the remote endpoint of the tunnel.
// Since this object does not support IPv6, it is deprecated in favor of
// tunnelInetConfigRemoteAddress. The type is string with pattern:
// (([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(%[\p{N}\p{L}]+)?.
Tunnelconfigremoteaddress interface{}
// This attribute is a key. The encapsulation method used by the tunnel.
// Since this object does not support IPv6, it is deprecated in favor of
// tunnelInetConfigEncapsMethod. The type is IANAtunnelType.
Tunnelconfigencapsmethod interface{}
// This attribute is a key. An identifier used to distinguish between multiple
// tunnels of the same encapsulation method, with the same endpoints. If the
// encapsulation protocol only allows one tunnel per set of endpoint addresses
// (such as for GRE or IP-in-IP), the value of this object is 1. For
// encapsulation methods (such as L2F) which allow multiple parallel tunnels,
// the manager is responsible for choosing any ID which does not conflict with
// an existing row, such as choosing a random number. Since this object does
// not support IPv6, it is deprecated in favor of tunnelInetConfigID. The type
// is interface{} with range: 1..2147483647.
Tunnelconfigid interface{}
// If the value of tunnelConfigStatus for this row is active, then this object
// contains the value of ifIndex corresponding to the tunnel interface. A
// value of 0 is not legal in the active state, and means that the interface
// index has not yet been assigned. Since this object does not support IPv6,
// it is deprecated in favor of tunnelInetConfigIfIndex. The type is
// interface{} with range: 0..2147483647.
Tunnelconfigifindex interface{}
// The status of this row, by which new entries may be created, or old entries
// deleted from this table. The agent need not support setting this object to
// createAndWait or notInService since there are no other writable objects in
// this table, and writable objects in rows of corresponding tables such as
// the tunnelIfTable may be modified while this row is active. To create a
// row in this table for an encapsulation method which does not support
// multiple parallel tunnels with the same endpoints, the management station
// should simply use a tunnelConfigID of 1, and set tunnelConfigStatus to
// createAndGo. For encapsulation methods such as L2F which allow multiple
// parallel tunnels, the management station may select a pseudo-random number
// to use as the tunnelConfigID and set tunnelConfigStatus to createAndGo. In
// the event that this ID is already in use and an inconsistentValue is
// returned in response to the set operation, the management station should
// simply select a new pseudo-random number and retry the operation. Creating
// a row in this table will cause an interface index to be assigned by the
// agent in an implementation-dependent manner, and corresponding rows will be
// instantiated in the ifTable and the tunnelIfTable. The status of this row
// will become active as soon as the agent assigns the interface index,
// regardless of whether the interface is operationally up. Deleting a row in
// this table will likewise delete the corresponding row in the ifTable and in
// the tunnelIfTable. Since this object does not support IPv6, it is
// deprecated in favor of tunnelInetConfigStatus. The type is RowStatus.
Tunnelconfigstatus interface{}
}
func (tunnelconfigentry *TUNNELMIB_Tunnelconfigtable_Tunnelconfigentry) GetFilter() yfilter.YFilter { return tunnelconfigentry.YFilter }
func (tunnelconfigentry *TUNNELMIB_Tunnelconfigtable_Tunnelconfigentry) SetFilter(yf yfilter.YFilter) { tunnelconfigentry.YFilter = yf }
func (tunnelconfigentry *TUNNELMIB_Tunnelconfigtable_Tunnelconfigentry) GetGoName(yname string) string {
if yname == "tunnelConfigLocalAddress" { return "Tunnelconfiglocaladdress" }
if yname == "tunnelConfigRemoteAddress" { return "Tunnelconfigremoteaddress" }
if yname == "tunnelConfigEncapsMethod" { return "Tunnelconfigencapsmethod" }
if yname == "tunnelConfigID" { return "Tunnelconfigid" }
if yname == "tunnelConfigIfIndex" { return "Tunnelconfigifindex" }
if yname == "tunnelConfigStatus" { return "Tunnelconfigstatus" }
return ""
}
func (tunnelconfigentry *TUNNELMIB_Tunnelconfigtable_Tunnelconfigentry) GetSegmentPath() string {
return "tunnelConfigEntry" + "[tunnelConfigLocalAddress='" + fmt.Sprintf("%v", tunnelconfigentry.Tunnelconfiglocaladdress) + "']" + "[tunnelConfigRemoteAddress='" + fmt.Sprintf("%v", tunnelconfigentry.Tunnelconfigremoteaddress) + "']" + "[tunnelConfigEncapsMethod='" + fmt.Sprintf("%v", tunnelconfigentry.Tunnelconfigencapsmethod) + "']" + "[tunnelConfigID='" + fmt.Sprintf("%v", tunnelconfigentry.Tunnelconfigid) + "']"
}
func (tunnelconfigentry *TUNNELMIB_Tunnelconfigtable_Tunnelconfigentry) GetChildByName(childYangName string, segmentPath string) types.Entity {
return nil
}
func (tunnelconfigentry *TUNNELMIB_Tunnelconfigtable_Tunnelconfigentry) GetChildren() map[string]types.Entity {
children := make(map[string]types.Entity)
return children
}
func (tunnelconfigentry *TUNNELMIB_Tunnelconfigtable_Tunnelconfigentry) GetLeafs() map[string]interface{} {
leafs := make(map[string]interface{})
leafs["tunnelConfigLocalAddress"] = tunnelconfigentry.Tunnelconfiglocaladdress
leafs["tunnelConfigRemoteAddress"] = tunnelconfigentry.Tunnelconfigremoteaddress
leafs["tunnelConfigEncapsMethod"] = tunnelconfigentry.Tunnelconfigencapsmethod
leafs["tunnelConfigID"] = tunnelconfigentry.Tunnelconfigid
leafs["tunnelConfigIfIndex"] = tunnelconfigentry.Tunnelconfigifindex
leafs["tunnelConfigStatus"] = tunnelconfigentry.Tunnelconfigstatus
return leafs
}
func (tunnelconfigentry *TUNNELMIB_Tunnelconfigtable_Tunnelconfigentry) GetBundleName() string { return "cisco_ios_xe" }
func (tunnelconfigentry *TUNNELMIB_Tunnelconfigtable_Tunnelconfigentry) GetYangName() string { return "tunnelConfigEntry" }
func (tunnelconfigentry *TUNNELMIB_Tunnelconfigtable_Tunnelconfigentry) GetBundleYangModelsLocation() string { return cisco_ios_xe.GetModelsPath() }
func (tunnelconfigentry *TUNNELMIB_Tunnelconfigtable_Tunnelconfigentry) GetCapabilitiesTable() map[string]string {
return cisco_ios_xe.GetCapabilities() }
func (tunnelconfigentry *TUNNELMIB_Tunnelconfigtable_Tunnelconfigentry) GetNamespaceTable() map[string]string {
return cisco_ios_xe.GetNamespaces() }
func (tunnelconfigentry *TUNNELMIB_Tunnelconfigtable_Tunnelconfigentry) SetParent(parent types.Entity) { tunnelconfigentry.parent = parent }
func (tunnelconfigentry *TUNNELMIB_Tunnelconfigtable_Tunnelconfigentry) GetParent() types.Entity { return tunnelconfigentry.parent }
func (tunnelconfigentry *TUNNELMIB_Tunnelconfigtable_Tunnelconfigentry) GetParentYangName() string { return "tunnelConfigTable" }
// TUNNELMIB_Tunnelinetconfigtable
// The (conceptual) table containing information on
// configured tunnels. This table can be used to map a
// set of tunnel endpoints to the associated ifIndex
// value. It can also be used for row creation. Note
// that every row in the tunnelIfTable with a fixed
// destination address should have a corresponding row in
// the tunnelInetConfigTable, regardless of whether it
// was created via SNMP.
type TUNNELMIB_Tunnelinetconfigtable struct {
parent types.Entity
YFilter yfilter.YFilter
// An entry (conceptual row) containing the information on a particular
// configured tunnel. Note that there is a 128 subid maximum for object OIDs.
// Implementers need to be aware that if the total number of octets in
// tunnelInetConfigLocalAddress and tunnelInetConfigRemoteAddress exceeds 110
// then OIDs of column instances in this table will have more than 128
// sub-identifiers and cannot be accessed using SNMPv1, SNMPv2c, or SNMPv3.
// In practice this is not expected to be a problem since IPv4 and IPv6
// addresses will not cause the limit to be reached, but if other types are
// supported by an agent, care must be taken to ensure that the sum of the
// lengths do not cause the limit to be exceeded. The type is slice of
// TUNNELMIB_Tunnelinetconfigtable_Tunnelinetconfigentry.
Tunnelinetconfigentry []TUNNELMIB_Tunnelinetconfigtable_Tunnelinetconfigentry
}
func (tunnelinetconfigtable *TUNNELMIB_Tunnelinetconfigtable) GetFilter() yfilter.YFilter { return tunnelinetconfigtable.YFilter }
func (tunnelinetconfigtable *TUNNELMIB_Tunnelinetconfigtable) SetFilter(yf yfilter.YFilter) { tunnelinetconfigtable.YFilter = yf }
func (tunnelinetconfigtable *TUNNELMIB_Tunnelinetconfigtable) GetGoName(yname string) string {
if yname == "tunnelInetConfigEntry" { return "Tunnelinetconfigentry" }
return ""
}
func (tunnelinetconfigtable *TUNNELMIB_Tunnelinetconfigtable) GetSegmentPath() string {
return "tunnelInetConfigTable"
}
func (tunnelinetconfigtable *TUNNELMIB_Tunnelinetconfigtable) GetChildByName(childYangName string, segmentPath string) types.Entity {
if childYangName == "tunnelInetConfigEntry" {
for _, c := range tunnelinetconfigtable.Tunnelinetconfigentry {
if tunnelinetconfigtable.GetSegmentPath() == segmentPath {
return &c
}
}
child := TUNNELMIB_Tunnelinetconfigtable_Tunnelinetconfigentry{}
tunnelinetconfigtable.Tunnelinetconfigentry = append(tunnelinetconfigtable.Tunnelinetconfigentry, child)
return &tunnelinetconfigtable.Tunnelinetconfigentry[len(tunnelinetconfigtable.Tunnelinetconfigentry)-1]
}
return nil
}
func (tunnelinetconfigtable *TUNNELMIB_Tunnelinetconfigtable) GetChildren() map[string]types.Entity {
children := make(map[string]types.Entity)
for i := range tunnelinetconfigtable.Tunnelinetconfigentry {
children[tunnelinetconfigtable.Tunnelinetconfigentry[i].GetSegmentPath()] = &tunnelinetconfigtable.Tunnelinetconfigentry[i]
}
return children
}
func (tunnelinetconfigtable *TUNNELMIB_Tunnelinetconfigtable) GetLeafs() map[string]interface{} {
leafs := make(map[string]interface{})
return leafs
}
func (tunnelinetconfigtable *TUNNELMIB_Tunnelinetconfigtable) GetBundleName() string { return "cisco_ios_xe" }
func (tunnelinetconfigtable *TUNNELMIB_Tunnelinetconfigtable) GetYangName() string { return "tunnelInetConfigTable" }
func (tunnelinetconfigtable *TUNNELMIB_Tunnelinetconfigtable) GetBundleYangModelsLocation() string { return cisco_ios_xe.GetModelsPath() }
func (tunnelinetconfigtable *TUNNELMIB_Tunnelinetconfigtable) GetCapabilitiesTable() map[string]string {
return cisco_ios_xe.GetCapabilities() }
func (tunnelinetconfigtable *TUNNELMIB_Tunnelinetconfigtable) GetNamespaceTable() map[string]string {
return cisco_ios_xe.GetNamespaces() }
func (tunnelinetconfigtable *TUNNELMIB_Tunnelinetconfigtable) SetParent(parent types.Entity) { tunnelinetconfigtable.parent = parent }
func (tunnelinetconfigtable *TUNNELMIB_Tunnelinetconfigtable) GetParent() types.Entity { return tunnelinetconfigtable.parent }
func (tunnelinetconfigtable *TUNNELMIB_Tunnelinetconfigtable) GetParentYangName() string { return "TUNNEL-MIB" }
// TUNNELMIB_Tunnelinetconfigtable_Tunnelinetconfigentry
// An entry (conceptual row) containing the information
// on a particular configured tunnel. Note that there is
// a 128 subid maximum for object OIDs. Implementers
// need to be aware that if the total number of octets in
// tunnelInetConfigLocalAddress and
// tunnelInetConfigRemoteAddress exceeds 110 then OIDs of
// column instances in this table will have more than 128
// sub-identifiers and cannot be accessed using SNMPv1,
// SNMPv2c, or SNMPv3. In practice this is not expected
// to be a problem since IPv4 and IPv6 addresses will not
// cause the limit to be reached, but if other types are
// supported by an agent, care must be taken to ensure
// that the sum of the lengths do not cause the limit to
// be exceeded.
type TUNNELMIB_Tunnelinetconfigtable_Tunnelinetconfigentry struct {
parent types.Entity
YFilter yfilter.YFilter
// This attribute is a key. The address type over which the tunnel
// encapsulates packets. The type is InetAddressType.
Tunnelinetconfigaddresstype interface{}
// This attribute is a key. The address of the local endpoint of the tunnel,
// or 0.0.0.0 (for IPv4) or :: (for IPv6) if the device is free to choose any
// of its addresses at tunnel establishment time. The type is string with
// length: 0..255.
Tunnelinetconfiglocaladdress interface{}
// This attribute is a key. The address of the remote endpoint of the tunnel.
// The type is string with length: 0..255.
Tunnelinetconfigremoteaddress interface{}
// This attribute is a key. The encapsulation method used by the tunnel. The
// type is IANAtunnelType.
Tunnelinetconfigencapsmethod interface{}
// This attribute is a key. An identifier used to distinguish between multiple
// tunnels of the same encapsulation method, with the same endpoints. If the
// encapsulation protocol only allows one tunnel per set of endpoint addresses
// (such as for GRE or IP-in-IP), the value of this object is 1. For
// encapsulation methods (such as L2F) which allow multiple parallel tunnels,
// the manager is responsible for choosing any ID which does not conflict
// with an existing row, such as choosing a random number. The type is
// interface{} with range: 1..2147483647.
Tunnelinetconfigid interface{}
// If the value of tunnelInetConfigStatus for this row is active, then this
// object contains the value of ifIndex corresponding to the tunnel interface.
// A value of 0 is not legal in the active state, and means that the interface
// index has not yet been assigned. The type is interface{} with range:
// 0..2147483647.
Tunnelinetconfigifindex interface{}
// The status of this row, by which new entries may be created, or old entries
// deleted from this table. The agent need not support setting this object to
// createAndWait or notInService since there are no other writable objects in
// this table, and writable objects in rows of corresponding tables such as
// the tunnelIfTable may be modified while this row is active. To create a
// row in this table for an encapsulation method which does not support
// multiple parallel tunnels with the same endpoints, the management station
// should simply use a tunnelInetConfigID of 1, and set tunnelInetConfigStatus
// to createAndGo. For encapsulation methods such as L2F which allow multiple
// parallel tunnels, the management station may select a pseudo-random number
// to use as the tunnelInetConfigID and set tunnelInetConfigStatus to
// createAndGo. In the event that this ID is already in use and an
// inconsistentValue is returned in response to the set operation, the
// management station should simply select a new pseudo-random number and
// retry the operation. Creating a row in this table will cause an interface
// index to be assigned by the agent in an implementation-dependent manner,
// and corresponding rows will be instantiated in the ifTable and the
// tunnelIfTable. The status of this row will become active as soon as the
// agent assigns the interface index, regardless of whether the interface is
// operationally up. Deleting a row in this table will likewise delete the
// corresponding row in the ifTable and in the tunnelIfTable. The type is
// RowStatus.
Tunnelinetconfigstatus interface{}
// The storage type of this row. If the row is permanent(4), no objects in
// the row need be writable. The type is StorageType.
Tunnelinetconfigstoragetype interface{}
}
func (tunnelinetconfigentry *TUNNELMIB_Tunnelinetconfigtable_Tunnelinetconfigentry) GetFilter() yfilter.YFilter { return tunnelinetconfigentry.YFilter }
func (tunnelinetconfigentry *TUNNELMIB_Tunnelinetconfigtable_Tunnelinetconfigentry) SetFilter(yf yfilter.YFilter) { tunnelinetconfigentry.YFilter = yf }
func (tunnelinetconfigentry *TUNNELMIB_Tunnelinetconfigtable_Tunnelinetconfigentry) GetGoName(yname string) string {
if yname == "tunnelInetConfigAddressType" { return "Tunnelinetconfigaddresstype" }
if yname == "tunnelInetConfigLocalAddress" { return "Tunnelinetconfiglocaladdress" }
if yname == "tunnelInetConfigRemoteAddress" { return "Tunnelinetconfigremoteaddress" }
if yname == "tunnelInetConfigEncapsMethod" { return "Tunnelinetconfigencapsmethod" }
if yname == "tunnelInetConfigID" { return "Tunnelinetconfigid" }
if yname == "tunnelInetConfigIfIndex" { return "Tunnelinetconfigifindex" }
if yname == "tunnelInetConfigStatus" { return "Tunnelinetconfigstatus" }
if yname == "tunnelInetConfigStorageType" { return "Tunnelinetconfigstoragetype" }
return ""
}
func (tunnelinetconfigentry *TUNNELMIB_Tunnelinetconfigtable_Tunnelinetconfigentry) GetSegmentPath() string {
return "tunnelInetConfigEntry" + "[tunnelInetConfigAddressType='" + fmt.Sprintf("%v", tunnelinetconfigentry.Tunnelinetconfigaddresstype) + "']" + "[tunnelInetConfigLocalAddress='" + fmt.Sprintf("%v", tunnelinetconfigentry.Tunnelinetconfiglocaladdress) + "']" + "[tunnelInetConfigRemoteAddress='" + fmt.Sprintf("%v", tunnelinetconfigentry.Tunnelinetconfigremoteaddress) + "']" + "[tunnelInetConfigEncapsMethod='" + fmt.Sprintf("%v", tunnelinetconfigentry.Tunnelinetconfigencapsmethod) + "']" + "[tunnelInetConfigID='" + fmt.Sprintf("%v", tunnelinetconfigentry.Tunnelinetconfigid) + "']"
}
func (tunnelinetconfigentry *TUNNELMIB_Tunnelinetconfigtable_Tunnelinetconfigentry) GetChildByName(childYangName string, segmentPath string) types.Entity {
return nil
}
func (tunnelinetconfigentry *TUNNELMIB_Tunnelinetconfigtable_Tunnelinetconfigentry) GetChildren() map[string]types.Entity {
children := make(map[string]types.Entity)
return children
}
func (tunnelinetconfigentry *TUNNELMIB_Tunnelinetconfigtable_Tunnelinetconfigentry) GetLeafs() map[string]interface{} {
leafs := make(map[string]interface{})
leafs["tunnelInetConfigAddressType"] = tunnelinetconfigentry.Tunnelinetconfigaddresstype
leafs["tunnelInetConfigLocalAddress"] = tunnelinetconfigentry.Tunnelinetconfiglocaladdress
leafs["tunnelInetConfigRemoteAddress"] = tunnelinetconfigentry.Tunnelinetconfigremoteaddress
leafs["tunnelInetConfigEncapsMethod"] = tunnelinetconfigentry.Tunnelinetconfigencapsmethod
leafs["tunnelInetConfigID"] = tunnelinetconfigentry.Tunnelinetconfigid
leafs["tunnelInetConfigIfIndex"] = tunnelinetconfigentry.Tunnelinetconfigifindex
leafs["tunnelInetConfigStatus"] = tunnelinetconfigentry.Tunnelinetconfigstatus
leafs["tunnelInetConfigStorageType"] = tunnelinetconfigentry.Tunnelinetconfigstoragetype
return leafs
}
func (tunnelinetconfigentry *TUNNELMIB_Tunnelinetconfigtable_Tunnelinetconfigentry) GetBundleName() string { return "cisco_ios_xe" }
func (tunnelinetconfigentry *TUNNELMIB_Tunnelinetconfigtable_Tunnelinetconfigentry) GetYangName() string { return "tunnelInetConfigEntry" }
func (tunnelinetconfigentry *TUNNELMIB_Tunnelinetconfigtable_Tunnelinetconfigentry) GetBundleYangModelsLocation() string { return cisco_ios_xe.GetModelsPath() }
func (tunnelinetconfigentry *TUNNELMIB_Tunnelinetconfigtable_Tunnelinetconfigentry) GetCapabilitiesTable() map[string]string {
return cisco_ios_xe.GetCapabilities() }
func (tunnelinetconfigentry *TUNNELMIB_Tunnelinetconfigtable_Tunnelinetconfigentry) GetNamespaceTable() map[string]string {
return cisco_ios_xe.GetNamespaces() }
func (tunnelinetconfigentry *TUNNELMIB_Tunnelinetconfigtable_Tunnelinetconfigentry) SetParent(parent types.Entity) { tunnelinetconfigentry.parent = parent }
func (tunnelinetconfigentry *TUNNELMIB_Tunnelinetconfigtable_Tunnelinetconfigentry) GetParent() types.Entity { return tunnelinetconfigentry.parent }
func (tunnelinetconfigentry *TUNNELMIB_Tunnelinetconfigtable_Tunnelinetconfigentry) GetParentYangName() string { return "tunnelInetConfigTable" }
|
Trilligy/runelite
|
runescape-client/src/main/java/ClientPreferences.java
|
<reponame>Trilligy/runelite<gh_stars>0
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import net.runelite.mapping.Export;
import net.runelite.mapping.Implements;
import net.runelite.mapping.ObfuscatedGetter;
import net.runelite.mapping.ObfuscatedName;
import net.runelite.mapping.ObfuscatedSignature;
@ObfuscatedName("bl")
@Implements("ClientPreferences")
public class ClientPreferences {
@ObfuscatedName("z")
@ObfuscatedGetter(
intValue = -1035730115
)
@Export("ClientPreferences_optionCount")
static int ClientPreferences_optionCount;
@ObfuscatedName("c")
@ObfuscatedSignature(
signature = "Lhp;"
)
@Export("Widget_spritesArchive")
static AbstractArchive Widget_spritesArchive;
@ObfuscatedName("b")
@ObfuscatedSignature(
signature = "Llp;"
)
static IndexedSprite field1046;
@ObfuscatedName("v")
@Export("roofsHidden")
boolean roofsHidden;
@ObfuscatedName("u")
@Export("titleMusicDisabled")
boolean titleMusicDisabled;
@ObfuscatedName("r")
@ObfuscatedGetter(
intValue = 1970428567
)
@Export("windowMode")
int windowMode;
@ObfuscatedName("p")
@Export("rememberedUsername")
String rememberedUsername;
@ObfuscatedName("q")
@Export("hideUsername")
boolean hideUsername;
@ObfuscatedName("m")
@Export("parameters")
LinkedHashMap parameters;
static {
ClientPreferences_optionCount = 6;
}
ClientPreferences() {
this.windowMode = 1;
this.rememberedUsername = null;
this.hideUsername = false;
this.parameters = new LinkedHashMap();
this.method1847(true);
}
@ObfuscatedSignature(
signature = "(Lkl;)V"
)
ClientPreferences(Buffer var1) {
this.windowMode = 1;
this.rememberedUsername = null;
this.hideUsername = false;
this.parameters = new LinkedHashMap();
if (var1 != null && var1.array != null) {
int var2 = var1.readUnsignedByte();
if (var2 >= 0 && var2 <= ClientPreferences_optionCount) {
if (var1.readUnsignedByte() == 1) {
this.roofsHidden = true;
}
if (var2 > 1) {
this.titleMusicDisabled = var1.readUnsignedByte() == 1;
}
if (var2 > 3) {
this.windowMode = var1.readUnsignedByte();
}
if (var2 > 2) {
int var3 = var1.readUnsignedByte();
for (int var4 = 0; var4 < var3; ++var4) {
int var5 = var1.readInt();
int var6 = var1.readInt();
this.parameters.put(var5, var6);
}
}
if (var2 > 4) {
this.rememberedUsername = var1.readStringCp1252NullTerminatedOrNull();
}
if (var2 > 5) {
this.hideUsername = var1.readBoolean();
}
} else {
this.method1847(true);
}
} else {
this.method1847(true);
}
}
@ObfuscatedName("z")
@ObfuscatedSignature(
signature = "(ZI)V",
garbageValue = "864937253"
)
void method1847(boolean var1) {
}
@ObfuscatedName("n")
@ObfuscatedSignature(
signature = "(I)Lkl;",
garbageValue = "-630561096"
)
@Export("toBuffer")
Buffer toBuffer() {
Buffer var1 = new Buffer(100);
var1.writeByte(ClientPreferences_optionCount);
var1.writeByte(this.roofsHidden ? 1 : 0);
var1.writeByte(this.titleMusicDisabled ? 1 : 0);
var1.writeByte(this.windowMode);
var1.writeByte(this.parameters.size());
Iterator var2 = this.parameters.entrySet().iterator();
while (var2.hasNext()) {
Entry var3 = (Entry)var2.next();
var1.writeInt((Integer)var3.getKey());
var1.writeInt((Integer)var3.getValue());
}
var1.writeStringCp1252NullTerminated(this.rememberedUsername != null ? this.rememberedUsername : "");
var1.writeBoolean(this.hideUsername);
return var1;
}
@ObfuscatedName("r")
@ObfuscatedSignature(
signature = "(B)V",
garbageValue = "-70"
)
static void method1857() {
Players.Players_count = 0;
for (int var0 = 0; var0 < 2048; ++var0) {
Players.field1236[var0] = null;
Players.field1235[var0] = 1;
}
}
@ObfuscatedName("jb")
@ObfuscatedSignature(
signature = "(Lho;IIII)V",
garbageValue = "1173230125"
)
@Export("drawMinimap")
static final void drawMinimap(Widget var0, int var1, int var2, int var3) {
WorldMapID.playPcmPlayers();
SpriteMask var4 = var0.getSpriteMask(false);
if (var4 != null) {
Rasterizer2D.Rasterizer2D_setClip(var1, var2, var4.width + var1, var2 + var4.height);
if (Client.minimapState != 2 && Client.minimapState != 5) {
int var5 = Client.camAngleY & 2047;
int var6 = class223.localPlayer.x / 32 + 48;
int var7 = 464 - class223.localPlayer.y * 682054857 / 32;
ObjectSound.sceneMinimapSprite.drawRotatedMaskedCenteredAround(var1, var2, var4.width, var4.height, var6, var7, var5, 256, var4.xStarts, var4.xWidths);
int var8;
int var9;
int var10;
for (var8 = 0; var8 < Client.mapIconCount; ++var8) {
var9 = Client.mapIconXs[var8] * 4 + 2 - class223.localPlayer.x / 32;
var10 = Client.mapIconYs[var8] * 4 + 2 - class223.localPlayer.y * 682054857 / 32;
class208.drawSpriteOnMinimap(var1, var2, var9, var10, Client.mapIcons[var8], var4);
}
int var11;
int var12;
for (var8 = 0; var8 < 104; ++var8) {
for (var9 = 0; var9 < 104; ++var9) {
NodeDeque var15 = Client.groundItems[WorldMapRectangle.plane][var8][var9];
if (var15 != null) {
var11 = var8 * 4 + 2 - class223.localPlayer.x / 32;
var12 = var9 * 4 + 2 - class223.localPlayer.y * 682054857 / 32;
class208.drawSpriteOnMinimap(var1, var2, var11, var12, class13.mapDotSprites[0], var4);
}
}
}
for (var8 = 0; var8 < Client.npcCount; ++var8) {
NPC var16 = Client.npcs[Client.npcIndices[var8]];
if (var16 != null && var16.isVisible()) {
NPCDefinition var18 = var16.definition;
if (var18 != null && var18.transforms != null) {
var18 = var18.transform();
}
if (var18 != null && var18.drawMapDot && var18.isInteractable) {
var11 = var16.x / 32 - class223.localPlayer.x / 32;
var12 = var16.y * 682054857 / 32 - class223.localPlayer.y * 682054857 / 32;
class208.drawSpriteOnMinimap(var1, var2, var11, var12, class13.mapDotSprites[1], var4);
}
}
}
var8 = Players.Players_count;
int[] var19 = Players.Players_indices;
for (var10 = 0; var10 < var8; ++var10) {
Player var17 = Client.players[var19[var10]];
if (var17 != null && var17.isVisible() && !var17.isHidden && var17 != class223.localPlayer) {
var12 = var17.x / 32 - class223.localPlayer.x / 32;
int var13 = var17.y * 682054857 / 32 - class223.localPlayer.y * 682054857 / 32;
boolean var14 = false;
if (class223.localPlayer.team != 0 && var17.team != 0 && var17.team == class223.localPlayer.team) {
var14 = true;
}
if (var17.isFriend()) {
class208.drawSpriteOnMinimap(var1, var2, var12, var13, class13.mapDotSprites[3], var4);
} else if (var14) {
class208.drawSpriteOnMinimap(var1, var2, var12, var13, class13.mapDotSprites[4], var4);
} else if (var17.isClanMember()) {
class208.drawSpriteOnMinimap(var1, var2, var12, var13, class13.mapDotSprites[5], var4);
} else {
class208.drawSpriteOnMinimap(var1, var2, var12, var13, class13.mapDotSprites[2], var4);
}
}
}
if (Client.hintArrowType != 0 && Client.cycle % 20 < 10) {
if (Client.hintArrowType == 1 && Client.hintArrowNpcIndex >= 0 && Client.hintArrowNpcIndex < Client.npcs.length) {
NPC var20 = Client.npcs[Client.hintArrowNpcIndex];
if (var20 != null) {
var11 = var20.x / 32 - class223.localPlayer.x / 32;
var12 = var20.y * 682054857 / 32 - class223.localPlayer.y * 682054857 / 32;
FloorDecoration.worldToMinimap(var1, var2, var11, var12, GameObject.mapMarkerSprites[1], var4);
}
}
if (Client.hintArrowType == 2) {
var10 = Client.hintArrowX * 4 - class223.baseX * 256 + 2 - class223.localPlayer.x / 32;
var11 = Client.hintArrowY * 4 - class286.baseY * 256 + 2 - class223.localPlayer.y * 682054857 / 32;
FloorDecoration.worldToMinimap(var1, var2, var10, var11, GameObject.mapMarkerSprites[1], var4);
}
if (Client.hintArrowType == 10 && Client.hintArrowPlayerIndex >= 0 && Client.hintArrowPlayerIndex < Client.players.length) {
Player var21 = Client.players[Client.hintArrowPlayerIndex];
if (var21 != null) {
var11 = var21.x / 32 - class223.localPlayer.x / 32;
var12 = var21.y * 682054857 / 32 - class223.localPlayer.y * 682054857 / 32;
FloorDecoration.worldToMinimap(var1, var2, var11, var12, GameObject.mapMarkerSprites[1], var4);
}
}
}
if (Client.destinationX != 0) {
var10 = Client.destinationX * 4 + 2 - class223.localPlayer.x / 32;
var11 = Client.destinationY * 4 + 2 - class223.localPlayer.y * 682054857 / 32;
class208.drawSpriteOnMinimap(var1, var2, var10, var11, GameObject.mapMarkerSprites[0], var4);
}
if (!class223.localPlayer.isHidden) {
Rasterizer2D.Rasterizer2D_fillRectangle(var4.width / 2 + var1 - 1, var4.height / 2 + var2 - 1, 3, 3, 16777215);
}
} else {
Rasterizer2D.Rasterizer2D_fillMaskedRectangle(var1, var2, 0, var4.xStarts, var4.xWidths);
}
Client.field842[var3] = true;
}
}
}
|
SirSkaro/pokeapi-reactor
|
src/main/java/skaro/pokeapi/PokeApiReactorNonCachingConfiguration.java
|
package skaro.pokeapi;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import skaro.pokeapi.client.PokeApiClient;
import skaro.pokeapi.client.PokeApiEntityFactory;
import skaro.pokeapi.client.ReactiveNonCachingPokeApiClient;
@Configuration
@Import(PokeApiReactorBaseConfiguration.class)
public class PokeApiReactorNonCachingConfiguration {
@Bean
public PokeApiClient pokeApiClient(PokeApiEntityFactory entityFactory) {
return new ReactiveNonCachingPokeApiClient(entityFactory);
}
}
|
epion-tropic-test-tool/epion-t3-core
|
src/main/java/com/epion_t3/core/flow/runner/impl/AbstractSimpleIterateFlowRunner.java
|
/* Copyright (c) 2017-2021 <NAME>. */
package com.epion_t3.core.flow.runner.impl;
import com.epion_t3.core.common.bean.ExecuteFlow;
import com.epion_t3.core.common.bean.ExecuteScenario;
import com.epion_t3.core.common.bean.scenario.Flow;
import com.epion_t3.core.common.bean.scenario.HasChildrenFlow;
import com.epion_t3.core.common.context.Context;
import com.epion_t3.core.common.context.ExecuteContext;
import com.epion_t3.core.common.type.FlowStatus;
import com.epion_t3.core.common.type.ScenarioScopeVariables;
import com.epion_t3.core.common.util.ErrorUtils;
import com.epion_t3.core.flow.bean.FlowResult;
import com.epion_t3.core.flow.logging.factory.FlowLoggerFactory;
import com.epion_t3.core.flow.logging.holder.FlowLoggingHolder;
import com.epion_t3.core.flow.runner.IterateTypeFlowRunner;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
/**
* 繰り返しFlowの基底クラス.
*
* @param <FLOW>
*/
@Slf4j
public abstract class AbstractSimpleIterateFlowRunner<FLOW extends HasChildrenFlow>
extends AbstractChildrenExecuteFlowRunner<FLOW> implements IterateTypeFlowRunner {
/**
* {@inheritDoc}
*/
@Override
public FlowResult execute(Context context, ExecuteContext executeContext, ExecuteScenario executeScenario,
FLOW flow) {
// process実行情報を作成
var executeFlow = createExecuteFlow();
executeScenario.getFlows().add(executeFlow);
executeFlow.setFlow(flow);
// Logger生成
var logger = FlowLoggerFactory.getInstance().getFlowLogger(this.getClass());
// Flow実行開始時間を設定
LocalDateTime start = LocalDateTime.now();
executeFlow.setStart(start);
String startTimeKey = flow.getId() + ExecuteScenario.FLOW_START_VARIABLE_SUFFIX;
if (!executeScenario.getScenarioVariables().containsKey(startTimeKey)) {
executeScenario.getScenarioVariables().put(startTimeKey, new ArrayList<>());
}
((List) executeScenario.getScenarioVariables().get(startTimeKey)).add(start);
// 実装側には、ループ継続判定処理のみを実装させるため本クラスで結果の制御が必要
// 生成も本クラスで行う
var flowResult = FlowResult.getDefault();
flowResult.setStatus(FlowStatus.RUNNING);
try {
// Flow開始ログ出力
outputStartFlowLog(context, executeScenario, executeFlow);
// Flowスコープ変数の設定
settingFlowVariables(context, executeContext, executeScenario, executeFlow);
// バインド
bind(context, executeContext, executeScenario, executeFlow, flow);
// ループ対象の解決
var iterateTarget = resolveIterateTarget(context, executeContext, executeScenario, executeFlow, flow,
logger);
// ループ処理
loopProcess(context, executeContext, executeScenario, executeFlow, flow, logger, iterateTarget);
// 正常終了
flowResult.setStatus(FlowStatus.SUCCESS);
} catch (Throwable t) {
// 解析用
log.debug("Error Occurred...", t);
// Flow失敗
flowResult.setStatus(FlowStatus.ERROR);
// 発生したエラーを設定
executeFlow.setError(t);
executeFlow.setStackTrace(ErrorUtils.getInstance().getStacktrace(t));
// エラー処理
onError(context, executeContext, executeScenario, executeFlow, flow, t, logger);
} finally {
// Flow結果を設定
executeFlow.setFlowResult(flowResult);
// 掃除
cleanFlowVariables(context, executeContext, executeScenario, executeFlow);
// シナリオ実行終了時間を設定
LocalDateTime end = LocalDateTime.now();
executeFlow.setEnd(end);
String endTimeKey = flow.getId() + executeScenario.FLOW_END_VARIABLE_SUFFIX;
if (!executeScenario.getScenarioVariables().containsKey(endTimeKey)) {
executeScenario.getScenarioVariables().put(endTimeKey, new ArrayList<>());
}
((List) executeScenario.getScenarioVariables().get(endTimeKey)).add(end);
// 所用時間を設定
executeFlow.setDuration(Duration.between(executeFlow.getStart(), executeFlow.getEnd()));
// プロセスのログを収集
var flowLogs = FlowLoggingHolder.get(executeFlow.getExecuteId().toString());
executeFlow.setFlowLogs(flowLogs);
// プロセスのログは収集し終えたらクリアする(ThreadLocalにて保持)
FlowLoggingHolder.clear(executeFlow.getExecuteId().toString());
// プロセス終了ログ出力
outputEndFlowLog(context, executeScenario, executeFlow);
// エラー処理
onFinally(context, executeContext, executeScenario, executeFlow, flow, logger);
}
return flowResult;
}
/**
* ループ処理対象の反復要素を解決します.
*
* @param context
* @param ExecuteContext
* @param executeScenario
* @param executeFlow
* @param flow
* @param logger
* @return
*/
protected abstract Iterable resolveIterateTarget(Context context, ExecuteContext ExecuteContext,
ExecuteScenario executeScenario, ExecuteFlow executeFlow, FLOW flow, Logger logger);
/**
* ループ処理を行います.
*
* @param context
* @param executeContext
* @param executeScenario
* @param parentExecuteFlow
* @param parentFlow
* @param logger
* @param iterateTarget
*/
private void loopProcess(@NonNull Context context, @NonNull ExecuteContext executeContext,
@NonNull ExecuteScenario executeScenario, @NonNull ExecuteFlow parentExecuteFlow, @NonNull FLOW parentFlow,
@NonNull Logger logger, @NonNull Iterable iterateTarget) {
// 解決したコレクションの数だけ回す
for (var target : iterateTarget) {
// 繰り返し対象オブジェクトを設定(シナリオスコープに設定)
executeScenario.getScenarioVariables().put(ScenarioScopeVariables.CURRENT_ITERATE_TARGET.getName(), target);
// 繰り返し処理
executeChildren(context, executeContext, executeScenario, parentExecuteFlow, parentFlow);
// 繰り返し対象オブジェクトを削除(シナリオスコープに設定)残ってもOK.
executeScenario.getScenarioVariables().remove(ScenarioScopeVariables.CURRENT_ITERATE_TARGET.getName());
if (executeScenario.getFlows()
.stream()
.anyMatch(x -> x.getFlowResult().getStatus() == FlowStatus.FORCE_EXIT)) {
break;
}
}
}
/**
* エラー処理を行う. この処理は、Flowの処理結果が失敗の場合に実行される.
*
* @param context コンテキスト
* @param executeScenario シナリオ実行情報
* @param executeFlow Flow実行情報
* @param flow Flow
* @param t 例外
*/
protected void onError(Context context, ExecuteContext ExecuteContext, ExecuteScenario executeScenario,
ExecuteFlow executeFlow, FLOW flow, Throwable t, Logger logger) {
// 必要に応じてオーバーライド実装すること.
}
/**
* エラー処理を行う. この処理は、子Flowの処理結果が失敗の場合に実行される.
*
* @param context コンテキスト
* @param executeScenario シナリオ実行情報
* @param executeFlow Flow実行情報
* @param flow Flow
* @param t 例外
*/
protected void onChildError(final Context context, final ExecuteContext executeContext,
final ExecuteScenario executeScenario, final ExecuteFlow executeFlow, final FLOW flow,
final ExecuteFlow childExecuteFlow, final Flow childFlow, final Throwable t, final Logger logger) {
// 必要に応じてオーバーライド実装すること.
}
/**
* 終了処理を行う. この処理は、Flowの処理結果が成功・失敗に関わらず実行される.
*
* @param context コンテキスト
* @param executeScenario シナリオ実行情報
* @param executeFlow Flow実行情報
* @param flow Flow
*/
protected void onFinally(final Context context, final ExecuteContext executeContext,
final ExecuteScenario executeScenario, final ExecuteFlow executeFlow, final FLOW flow,
final Logger logger) {
// 必要に応じてオーバーライド実装すること.
}
/**
* 終了処理を行う. この処理は、子Flowの処理結果が成功・失敗に関わらず実行される.
*
* @param context コンテキスト
* @param executeScenario シナリオ実行情報
* @param executeFlow Flow実行情報
* @param flow Flow
*/
protected void onChildFinally(final Context context, final ExecuteContext ExecuteContext,
final ExecuteScenario executeScenario, final ExecuteFlow executeFlow, final FLOW flow,
final ExecuteFlow childExecuteFlow, final Flow childFlow, final Logger logger) {
// 必要に応じてオーバーライド実装すること.
}
}
|
Starorbit723/cms
|
webapps/ROOT/WEB-INF/classes/statics/js/modules/meeting/vtalk_list.js
|
<filename>webapps/ROOT/WEB-INF/classes/statics/js/modules/meeting/vtalk_list.js
var vm = new Vue({
el: '#vtalk_list',
data () {
var validateUrl = (rule, value, callback) => {
var urlReg = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/;
if (value =='') {
callback(new Error('链接不能为空'));
} else if (!urlReg.test(value)) {
callback(new Error('链接格式不正确'));
} else {
callback();
}
}
var validatePriority = (rule, value, callback) => {
var urlReg = /^[0-9]*[1-9][0-9]*$/;
if (value !== '' && value == '-1') {
callback();
} else if (value !== '' && !urlReg.test(value)) {
callback(new Error('权重需改为正整数或-1,-1代表权重最低'));
} else {
callback();
}
}
return {
//展示封面图库
showCoverimgLib:false,
//展示新建或修改
showCreatEditDialog: false,
showCreatEditDialogTitle:'新建内容',
//搜索文章列表提交
timeRange:[], //时间需要特殊处理,并且同步到searchForm
searchForm:{
talkTitle:'',//标题
startTime:'',//开始时间
endTime:'',//结束时间
talkStatus: ['0','1']
},
//表格结果
tableData: [{
talkId:'',//主键
talkTitle:'',//标题
talkImg:'',//头图
talkLabel:'',//标签
talkCrtUserId:'',//创建人编号
talkModUserId:'',//更新人编号
talkCrtTime:'',//创建时间
talkModTime:'',//更新时间
talkStatus:'',//0 上线 1下线 2删除
userName:'',//创建人名称
talkLink:'',//链接
talkReleaseTime:'',//发布时间
talkPriority:'',//权重
talkMLink:'',//M站链接
talkDate:''//自定义发布时间
}],
//分页器相关
pagination1: {
currPage: 1,
totalCount:0,
totalPage:0,
pageSize:10
},
//新建或修改表单项
creatEditForm:{
talkId:'',//主键
talkTitle:'',//标题
talkImg:'',//头图
talkLabel:'',//标签
talkCrtUserId:'',//创建人编号
talkModUserId:'',//更新人编号
talkCrtTime:'',//创建时间
talkModTime:'',//更新时间
talkStatus:'',//0 上线 1下线 2删除
userName:'',//创建人名称
talkLink:'',//链接
talkReleaseTime:'',//发布时间
talkPriority:'',//权重
talkMLink:'',//M站链接
talkDate:''//自定义发布时间
},
creatEditFormRules:{
talkTitle: [
{ required: true, message: '标题不能为空', trigger: 'change' },
{ max: 100, message: '您输入的字数超过100个字', trigger: 'change' }
],
talkImg:[
{ required: true, message: '请选择封面图', trigger: 'change' },
],
talkLink:[
{ required: true, validator: validateUrl, trigger: 'change' }
],
talkMLink:[
{ required: true, validator: validateUrl, trigger: 'change' }
],
talkPriority:[
{ validator: validatePriority, trigger: 'change' }
],
talkDate:[
{ required: true, message: '发布时间不能为空', trigger: 'change' }
]
},
//封面图库相关
searchCoverimgForm:{
picTitle:'',
picType:'0'//0封面图库 1内容图库 2图为图库
},
coverimgTableData:[],
pagination2: {
currPage: 1,
totalCount:0,
totalPage:0,
pageSize:10
},
}
},
watch: {
timeRange (val) {
console.log(val)
if (val) {
this.searchForm.startTime = val[0]
this.searchForm.endTime = val[1]
} else {
this.searchForm.startTime = ''
this.searchForm.endTime = ''
}
console.log(this.searchForm)
}
},
created () {
this.startSearch(0)
},
methods:{
handleCurrentChange (val) {
this.pagination1.currPage = val
this.startSearch()
},
handleCurrentChange2 (val) {
this.pagination2.currPage = val
this.searchCoverImg()
},
//开始搜索
startSearch (type) {
var self = this
var data = JSON.parse(JSON.stringify(self.searchForm))
data.talkTitle = data.talkTitle.toString().trim()
if (type == 0) {
Object.assign(data,{
page: '1',
limit: self.pagination1.pageSize.toString()
})
} else {
Object.assign(data,{
page: self.pagination1.currPage.toString(),
limit: self.pagination1.pageSize.toString()
})
}
$.ajax({
type: "POST",
url: "/talk/list",
contentType: "application/json",
data: JSON.stringify(data),
dataType: "json",
success: function(res){
if(res.code == 200){
self.tableData = res.page.list
for (let i = 0; i < self.tableData.length; i++){
self.tableData[i].talkCrtTime = self.transformTime(parseInt(self.tableData[i].talkCrtTime))
self.tableData[i].talkReleaseTime = self.transformTime(parseInt(self.tableData[i].talkReleaseTime))
}
self.pagination1 = {
currPage: res.page.currPage,
totalCount:res.page.totalCount,
totalPage: res.page.totalPage,
pageSize: res.page.pageSize
}
}else{
mapErrorStatus(res)
vm.error = true;
vm.errorMsg = res.msg;
}
},
error:function(res){
mapErrorStatus(res)
}
});
},
//新建或编辑内容
creatOrEdit (type,item) {
if (type == 'creat') {
this.showCreatEditDialogTitle = '新建内容'
this.showCreatEditDialog = true
} else if (type == 'edit') {
//请求item原始数据,相关时间字段已经转换成标准格式不能提交
this.reqItemOrign(item.talkId)
}
},
//请求单条原始数据
reqItemOrign(id){
var self = this
$.ajax({
type: "POST",
url: '/talk/info/' + id.toString(),
contentType: "application/json",
dataType: "json",
success: function(res){
if(res.code == 200){
self.showCreatEditDialogTitle = '编辑内容'
self.showCreatEditDialog = true
self.creatEditForm = res.dict
}else{
mapErrorStatus(res)
vm.error = true;
vm.errorMsg = res.msg;
}
},
error:function(res){
mapErrorStatus(res)
}
});
},
//新建/编辑Vtalk列表项 type:0 保存, type:1 保存并发布
saveVtalkForm (formName,type){
var self = this
self.$refs[formName].validate((valid) =>{
if (valid) {
//如果保存时权重为'',变成'-1'
if (self.creatEditForm.talkPriority.trim() == '') {
self.creatEditForm.talkPriority = '-1'
}
//去掉标题头尾空格
self.creatEditForm.talkTitle = self.creatEditForm.talkTitle.trim()
if (self.showCreatEditDialogTitle == '新建内容') {
var reqUrl = '/talk/save'
} else if (self.showCreatEditDialogTitle == '编辑内容') {
var reqUrl = '/talk/update'
}
$.ajax({
type: "POST",
url: reqUrl,
contentType: "application/json",
data: JSON.stringify(self.creatEditForm),
dataType: "json",
success: function(res){
if(res.code == 200){
console.log(res)
if (self.showCreatEditDialogTitle == '新建内容') {
if (type == 0 ) {
self.$message.success('保存成功')
self.closeVtalkForm(formName)
self.startSearch()
} else if (type == 1) {
self.creatEditForm.talkId = res.talkId
self.submitVtalk()
}
} else if (self.showCreatEditDialogTitle == '编辑内容') {
if (type == 0 ) {
self.$message.success('保存成功')
self.closeVtalkForm(formName)
self.startSearch()
} else if (type == 1) {
self.submitVtalk()
}
}
}else{
mapErrorStatus(res)
vm.error = true;
vm.errorMsg = res.msg;
}
},
error:function(res){
mapErrorStatus(res)
}
});
}
})
},
//连续提交发布
submitVtalk () {
var self = this
console.log(self.creatEditForm.talkId)
var data = {
talkId: self.creatEditForm.talkId.toString(),
talkReleaseTime: new Date().getTime(),
talkStatus: '0'
}
$.ajax({
type: "POST",
url: "/talk/update",
contentType: "application/json",
data: JSON.stringify(data),
dataType: "json",
success: function(res){
if(res.code == 200){
self.$message.success('发布成功')
self.startSearch()
self.closeVtalkForm('creatEditForm')
}else{
mapErrorStatus(res)
vm.error = true;
vm.errorMsg = res.msg;
}
},
error:function(res){
mapErrorStatus(res)
}
});
},
//关闭并清除表单
closeVtalkForm (formName) {
this.$refs[formName].resetFields()
this.showCreatEditDialog = false,
this.showCreatEditDialogTitle = '新建内容',
this.creatEditForm = {
talkId:'',//主键
talkTitle:'',//标题
talkImg:'',//头图
talkLabel:'',//标签
talkCrtUserId:'',//创建人编号
talkModUserId:'',//更新人编号
talkCrtTime:'',//创建时间
talkModTime:'',//更新时间
talkStatus:'',//0 上线 1下线 2删除
userName:'',//创建人名称
talkLink:'',//链接
talkReleaseTime:'',//发布时间
talkPriority:''//权重
}
},
//删除
deleteThisVtalk (item) {
var self = this
self.$confirm('确实要删除此Vtalk吗?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
var data = {
talkId: item.talkId.toString(),
talkStatus: '2'
}
$.ajax({
type: "POST",
url: "/talk/update",
contentType: "application/json",
data: JSON.stringify(data),
dataType: "json",
success: function(res){
if(res.code == 200){
self.$message.success('删除成功')
self.startSearch()
}else{
mapErrorStatus(res)
vm.error = true;
vm.errorMsg = res.msg;
}
},
error:function(res){
mapErrorStatus(res)
}
});
})
},
//发布上线
onlineThisVtalk (item) {
var self = this
self.$confirm('确实要发布此Vtalk吗?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
var data = {
talkId: item.talkId.toString(),
talkReleaseTime: new Date().getTime(),
talkStatus: '0'
}
$.ajax({
type: "POST",
url: "/talk/update",
contentType: "application/json",
data: JSON.stringify(data),
dataType: "json",
success: function(res){
if(res.code == 200){
self.$message.success('发布成功')
self.startSearch()
}else{
mapErrorStatus(res)
vm.error = true;
vm.errorMsg = res.msg;
}
},
error:function(res){
mapErrorStatus(res)
}
});
})
},
//下线
offlineThisVtalk (item) {
var self = this
self.$confirm('确实要下线此Vtalk吗?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
var data = {
talkId: item.talkId.toString(),
talkStatus: '1'
}
$.ajax({
type: "POST",
url: "/talk/update",
contentType: "application/json",
data: JSON.stringify(data),
dataType: "json",
success: function(res){
if(res.code == 200){
self.$message.success('下线成功')
self.startSearch()
}else{
mapErrorStatus(res)
vm.error = true;
vm.errorMsg = res.msg;
}
},
error:function(res){
mapErrorStatus(res)
}
});
})
},
//打开封面图库弹层
openAddCoverImg () {
this.showCoverimgLib = true
this.searchCoverImg(0)
},
//选择了某一张封面图片
addThisCoverImg (item) {
this.$refs['creatEditForm'].clearValidate();
this.creatEditForm.talkImg = item.picUrl
this.backToEdit()
},
//返回编辑页
backToEdit (){
this.showCoverimgLib = false
this.searchCoverimgForm = {
picTitle:'',
picType:'0'//0封面图库 1内容图库 2图为图库
}
this.coverimgTableData = []
this.pagination2 = {
currPage: 1,
totalCount:0,
totalPage:0,
pageSize:10
}
},
//搜索封面图库
searchCoverImg (type){
var self = this
var data = JSON.parse(JSON.stringify(self.searchCoverimgForm))
data.picTitle = data.picTitle.trim()
if (type == 0) {
Object.assign(data,{
page: '1',
limit: self.pagination2.pageSize.toString()
})
} else {
Object.assign(data,{
page: self.pagination2.currPage.toString(),
limit: self.pagination2.pageSize.toString()
})
}
$.ajax({
type: "POST",
contentType: "application/json",
url: "/picture/list",
data: JSON.stringify(data),
dataType: "json",
success: function(res){
if(res.code == 200){
self.coverimgTableData = res.page.list
self.pagination2 = {
currPage: res.page.currPage,
totalCount:res.page.totalCount,
totalPage:res.page.totalPage,
pageSize:res.page.pageSize
}
}else{
mapErrorStatus(res)
vm.error = true;
vm.errorMsg = res.msg;
}
},
error:function(res){
mapErrorStatus(res)
}
});
},
//跳转至详情
openUrlvTalkPage(item){
if(item.talkStatus == 0){
window.open(item.talkLink, "newwindow")
}
},
//时间格式转换工具
transformTime (timestamp = +new Date()) {
if (timestamp) {
var time = new Date(timestamp);
var y = time.getFullYear();
var M = time.getMonth() + 1;
var d = time.getDate();
var h = time.getHours();
var m = time.getMinutes();
var s = time.getSeconds();
return y + '-' + this.addZero(M) + '-' + this.addZero(d) + ' ' + this.addZero(h) + ':' + this.addZero(m) + ':' + this.addZero(s);
} else {
return '';
}
},
addZero (m) {
return m < 10 ? '0' + m : m;
}
}
})
|
GabrielAmare/Darts
|
venv/Lib/site-packages/tools37/actions/Insert.py
|
from .Action import Action
class Insert(Action):
def __init__(self, obj: list, index: int, item: object):
super().__init__()
self.obj = obj
self.index = index
self.item = item
def do(self) -> None:
self.obj.insert(self.index, self.item)
def undo(self) -> None:
self.obj.pop(self.index)
def redo(self) -> None:
self.obj.insert(self.index, self.item)
|
StarkillerX42/stui
|
TUI/Inst/Guide/GuideStateWdg.py
|
<filename>TUI/Inst/Guide/GuideStateWdg.py
#!/usr/bin/env python
"""Guide status widget
History:
2011-06-13 ROwen Extracted from GuideWdg and expanded to include CCD temperature.
2011-07-12 ROwen Show guide and exposure state in color to indicate severity.
The only "normal" guide state is "on" because all science uses guiding.
2011-11-08 ROwen Show error states in uppercase to make them more visible.
Set state label severity = state severity to make problems more visible.
Bug fix: exposure state was always displayed in normal color.
2012-06-04 ROwen Play sound cues (this should have been done all along).
2015-11-03 ROwen Replace "== None" with "is None" and "!= None" with "is not None" to modernize the code.
"""
import Tkinter
import RO.Alg
import RO.CanvasUtil
import RO.Constants
import RO.DS9
import RO.MathUtil
import RO.OS
import RO.Prefs
import RO.StringUtil
import RO.Wdg
import TUI.Base.Wdg
import TUI.Models
import TUI.PlaySound
class GuideStateWdg(Tkinter.Frame):
def __init__(self,
master,
helpURL = None,
**kargs):
Tkinter.Frame.__init__(self, master, **kargs)
self.gcameraModel = TUI.Models.getModel("gcamera")
self.guiderModel = TUI.Models.getModel("guider")
self.prevGuideSoundFunc = None
gr = RO.Wdg.Gridder(self, sticky="w")
line1Frame = Tkinter.Frame(self)
self.guideStateWdg = RO.Wdg.StrLabel(
master = line1Frame,
# formatFunc = str.capitalize,
anchor = "w",
helpText = "Current state of guiding",
helpURL = helpURL,
)
self.guideStateWdg.pack(side="left")
RO.Wdg.StrLabel(master = line1Frame, text=" ").pack(side="left")
self.simInfoWdg = RO.Wdg.StrLabel(
master = line1Frame,
helpText = "Simulation info (if simulation mode)",
helpURL = helpURL,
)
self.simInfoWdg.pack(side="left")
self.guideStateLabel = RO.Wdg.StrLabel(master = self, text = "Guider")
gr.gridWdg(self.guideStateLabel, line1Frame, colSpan=2)
expStateFrame = Tkinter.Frame(self)
self.expStateWdg = RO.Wdg.StrLabel(
master = expStateFrame,
helpText = "Status of current exposure",
helpURL = helpURL,
anchor="w",
width = 11
)
self.expStateWdg.grid(row=0, column=0)
self.expTimer = RO.Wdg.TimeBar(
master = expStateFrame,
valueFormat = "%3.1f sec",
isHorizontal = True,
autoStop = True,
helpText = "Status of current exposure",
helpURL = helpURL,
)
self.expTimer.grid(row=0, column=1, sticky="ew")
expStateFrame.grid_columnconfigure(1, weight=1)
self.expStateLabel = RO.Wdg.StrLabel(master = self, text = "Exposure")
gr.gridWdg(self.expStateLabel, expStateFrame, sticky="ew")
self.expTimer.grid_remove()
gr.startNewCol()
self.ccdTempWdg = RO.Wdg.FloatLabel(
master = self,
precision = 1,
helpText = "CCD temperature",
helpURL = helpURL,
)
gr.gridWdg("CCD Temp", self.ccdTempWdg, "C", sticky="e")
self.coolerLoadWdg = RO.Wdg.FloatLabel(
master = self,
precision = 0,
helpText = "Load on the CCD cooler",
helpURL = helpURL,
)
gr.gridWdg("Cooler Load", self.coolerLoadWdg, "%", sticky="e")
self.columnconfigure(1, weight=1)
# keyword variable bindings
self.gcameraModel.cooler.addCallback(self._coolerCallback)
self.gcameraModel.exposureState.addCallback(self._exposureStateCallback)
self.gcameraModel.simulating.addCallback(self._simulatingCallback)
self.guiderModel.guideState.addCallback(self._guideStateCallback)
def _coolerCallback(self, keyVar):
"""cooler callback (gcamera keyword)
Float(name="setpoint", help="CCD temperature setpoint", units="degC"),
Float(name="ccdTemp", help="CCD temperature reported by the camera", units="degC"),
Float(name="heatsinkTemp", help="Heatsink temperature reported by the camera", units="degC"),
Float(name="coolerLoad", help="Load on the cooler", units="percent"),
Int(name="fanStatus", help="Fan status. Always 0 with this camera"),
Enum('Off', 'RampingToSetPoint', 'Correcting', 'RampingToAmbient', 'AtAmbient', 'AtMax', 'AtMin', 'AtSetPoint', 'Invalid',
name="coolerStatus",
help="Cooler status. Correcting appears to be the normal state, All others should be considered bad. AtSetPoint does not appear to occur.")),
"""
self.ccdTempWdg.set(keyVar[1], isCurrent=keyVar.isCurrent)
self.coolerLoadWdg.set(keyVar[3], isCurrent=keyVar.isCurrent)
def _exposureStateCallback(self, keyVar):
"""exposureState callback (gcamera keyword)
values are:
- Enum('idle','integrating','reading','done','aborted','failed'),
- Float(help="remaining time for this state (0 if none, short or unknown)", units="sec"),
- Float(help="total time for this state (0 if none, short or unknown)", units="sec")),
"""
expStateStr, remTime, netTime = keyVar[:]
if expStateStr is None:
expStateStr = "?"
lowState = expStateStr.lower()
if lowState in ("?", "aborted"):
severity = RO.Constants.sevWarning
elif lowState == "failed":
expStateStr = expStateStr.upper()
severity = RO.Constants.sevError
else:
severity = RO.Constants.sevNormal
remTime = remTime or 0.0 # change None to 0.0
netTime = netTime or 0.0 # change None to 0.0
self.expStateLabel.setSeverity(severity)
self.expStateWdg.set(expStateStr, isCurrent=keyVar.isCurrent, severity = severity)
if not (keyVar.isGenuine and keyVar.isCurrent):
# data is cached or not current; don't mess with the countdown timer
return
if netTime > 0:
# print "starting a timer; remTime = %r, netTime = %r" % (remTime, netTime)
# handle a countdown timer
# it should be stationary if expStateStr = paused,
# else it should count down
if lowState == "integrating":
# count up exposure
self.expTimer.start(
value = netTime - remTime,
newMax = netTime,
countUp = True,
)
else:
# count down anything else
self.expTimer.start(
value = remTime,
newMax = netTime,
countUp = False,
)
self.expTimer.grid()
else:
# hide countdown timer
self.expTimer.grid_remove()
self.expTimer.clear()
def _guideStateCallback(self, keyVar):
"""Guide state callback
Key("guideState",
Enum("off", "starting", "on", "stopping", "failed", help="state of guider"),
),
"""
guideState = keyVar[0]
# guide summary state is for playing sounds; one of on/off/failed/None
guideSoundFunc = {
"off": TUI.PlaySound.guidingEnds,
"starting": TUI.PlaySound.guidingBegins,
"on": TUI.PlaySound.guidingBegins,
"stopping": TUI.PlaySound.guidingEnds,
"failed": TUI.PlaySound.guidingFailed,
}.get(guideState, None)
doPlaySound = guideSoundFunc is not None \
and self.prevGuideSoundFunc is not None \
and self.prevGuideSoundFunc != guideSoundFunc
self.prevGuideSoundFunc = guideSoundFunc
if doPlaySound:
guideSoundFunc()
if guideState is None:
guideState = "?"
gsLower = guideState.lower()
if gsLower == "on":
severity = RO.Constants.sevNormal
elif gsLower == "failed":
guideState = guideState.upper()
severity = RO.Constants.sevError
else:
severity = RO.Constants.sevWarning
self.guideStateLabel.setSeverity(severity)
self.guideStateWdg.set(guideState, isCurrent=keyVar.isCurrent, severity=severity)
def _simulatingCallback(self, keyVar):
"""Simulating callback (gcamera keyword)
"""
isSim, simDir, seqNum = keyVar[:]
severity = RO.Constants.sevNormal
if isSim:
simStr = "Simulation: # %d from %s" % (seqNum, simDir)
severity = RO.Constants.sevWarning
elif isSim is None:
simStr = "?"
else:
simStr = ""
self.simInfoWdg.set(simStr, isCurrent = keyVar.isCurrent, severity = severity)
if __name__ == "__main__":
from . import GuideTest
#import gc
#gc.set_debug(gc.DEBUG_SAVEALL) # or gc.DEBUG_LEAK to print lots of messages
root = GuideTest.tuiModel.tkRoot
testFrame = GuideStateWdg(root)
testFrame.pack(expand="yes", fill="both")
testFrame.wait_visibility() # must be visible to download images
GuideTest.start()
GuideTest.tuiModel.reactor.run()
|
NCIEVS/nci-report-writer-sparql
|
core/src/main/java/gov/nih/nci/evs/reportwriter/core/util/SPARQLQueryRunner.java
|
<filename>core/src/main/java/gov/nih/nci/evs/reportwriter/core/util/SPARQLQueryRunner.java
import gov.nih.nci.evs.reportwriter.core.util.*;
import java.nio.charset.Charset;
import java.time.Duration;
import java.io.*;
import java.util.*;
import java.net.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
//import gov.nih.nci.evs.restapi.util.*;
/**
*
* Helper class using the RestTemplate to call the SPARQL endpoint using a SPARQL query.
*
*/
public class SPARQLQueryRunner {
private static final Logger log = LoggerFactory.getLogger(SPARQLQueryRunner.class);
private String username;
private String password;
private int readTimeout;
private int connectTimeout;
gov.nih.nci.evs.reportwriter.core.util.JSONUtils jsonUtils = null;
public SPARQLQueryRunner () {}
public SPARQLQueryRunner(String username, String password,int readTimeout, int connectTimeout) {
this.username = username;
this.password = password;
this.readTimeout= readTimeout;
this.connectTimeout = connectTimeout;
this.jsonUtils = new gov.nih.nci.evs.reportwriter.core.util.JSONUtils();
System.out.println("****************** SPARQLQueryRunner instantiated...");
}
public String getPrefixes() {
StringBuffer buf = new StringBuffer();
buf.append("PREFIX :<http://ncicb.nci.nih.gov/xml/owl/EVS/Thesaurus.owl#>").append("\n");
buf.append("PREFIX base:<http://ncicb.nci.nih.gov/xml/owl/EVS/Thesaurus.owl>").append("\n");
buf.append("PREFIX Thesaurus:<http://ncicb.nci.nih.gov/xml/owl/EVS/Thesaurus.owl#>").append("\n");
buf.append("PREFIX xml:<http://www.w3.org/XML/1998/namespace>").append("\n");
buf.append("PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>").append("\n");
buf.append("PREFIX owl:<http://www.w3.org/2002/07/owl#>").append("\n");
buf.append("PREFIX owl2xml:<http://www.w3.org/2006/12/owl2-xml#>").append("\n");
buf.append("PREFIX protege:<http://protege.stanford.edu/plugins/owl/protege#>").append("\n");
buf.append("PREFIX xsd:<http://www.w3.org/2001/XMLSchema#>").append("\n");
buf.append("PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#>").append("\n");
buf.append("PREFIX ncicp:<http://ncicb.nci.nih.gov/xml/owl/EVS/ComplexProperties.xsd#>").append("\n");
buf.append("PREFIX dc:<http://purl.org/dc/elements/1.1/>").append("\n");
return buf.toString();
}
/**
*
* Post a SPARQL query to the SPARQL endpoint and return the results.
*
* @param query SPARQL query.
* @return SPARQL results.
*/
public String runSPARQL(String query, String restURL) {
RestTemplate restTemplate = new RestTemplateBuilder().
rootUri(restURL).
basicAuthentication(username,password).
setReadTimeout(Duration.ofSeconds(readTimeout)).
setConnectTimeout(Duration.ofSeconds(connectTimeout)).
build();
restTemplate.getMessageConverters().add(0,new StringHttpMessageConverter(Charset.forName("UTF-8")));
MultiValueMap <String,String> body = new LinkedMultiValueMap<String,String>();
body.add("query", query);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.setAccept(Arrays.asList(new MediaType("application","sparql-results+json")));
HttpEntity<?> entity = new HttpEntity<Object>(body ,headers);
String results = restTemplate.postForObject(restURL,entity,String.class);
return results;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
public static String replaceAll(String s) {
if (s == null) return null;
StringBuffer buf = new StringBuffer();
for (int i=0; i<s.length(); i++) {
char c = s.charAt(i);
if (c == '+') {
buf.append("%20");
} else{
buf.append(c);
}
}
s = buf.toString();
s = s.replaceAll("%28", "(");
s = s.replaceAll("%29", ")");
return s;
}
public static String encode(String query) {
try {
String retstr = String.format("%s", URLEncoder.encode(query, "UTF-8"));
retstr = replaceAll(retstr);
return retstr;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static String loadQuery(String filename, boolean encode) {
StringBuffer buf = new StringBuffer();
Vector v = readFile(filename);
for (int i=0; i<v.size(); i++) {
String t = (String) v.elementAt(i);
if (!t.startsWith("#")) {
buf.append(t);
if (!encode) {
buf.append("\n");
}
}
}
String query = buf.toString();
if (encode) {
query = encode(query);
}
return query;
}
public static String loadQuery(String filename) {
return loadQuery(filename, true);
}
public static Vector readFile(String filename)
{
Vector v = new Vector();
try {
FileReader a = new FileReader(filename);
BufferedReader br = new BufferedReader(a);
String line;
line = br.readLine();
while(line != null){
v.add(line);
line = br.readLine();
}
br.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return v;
}
public Vector executeQuery(String query, String restURL) {
//System.out.println("\n\nquery: " + query);
//System.out.println("restURL: " + restURL);
String json = runSPARQL(query, restURL);
//System.out.println("json: " + json);
if (json == null) return null;
if (jsonUtils == null) {
System.out.println("jsonUtils == null??? " );
}
Vector w = jsonUtils.parseJSON(json);
if (w == null) return null;
w = jsonUtils.getResponseValues(w);
return w;
}
public Vector run_query(String restURL, String query) {
String queryPrefix = getPrefixes();
String res = runSPARQL(queryPrefix + query, restURL);
Vector v = new gov.nih.nci.evs.reportwriter.core.util.JSONUtils().parseJSON(res);
return new gov.nih.nci.evs.reportwriter.core.util.ParserUtils().getResponseValues(v);
}
}
|
mortezaalizadeh/topicctl
|
cmd/topicctl/subcmd/reset.go
|
<filename>cmd/topicctl/subcmd/reset.go
package subcmd
import (
"context"
"errors"
"fmt"
"github.com/segmentio/topicctl/pkg/apply"
"github.com/segmentio/topicctl/pkg/cli"
"github.com/segmentio/topicctl/pkg/groups"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
var resetOffsetsCmd = &cobra.Command{
Use: "reset-offsets [topic name] [group name]",
Short: "reset consumer group offsets",
Args: cobra.MinimumNArgs(2),
PreRunE: resetOffsetsPreRun,
RunE: resetOffsetsRun,
}
type resetOffsetsCmdConfig struct {
offset int64
partitions []int
shared sharedOptions
}
var resetOffsetsConfig resetOffsetsCmdConfig
func init() {
resetOffsetsCmd.Flags().Int64Var(
&resetOffsetsConfig.offset,
"offset",
-2,
"Offset",
)
resetOffsetsCmd.Flags().IntSliceVar(
&resetOffsetsConfig.partitions,
"partitions",
[]int{},
"Partition (defaults to all)",
)
addSharedFlags(resetOffsetsCmd, &resetOffsetsConfig.shared)
RootCmd.AddCommand(resetOffsetsCmd)
}
func resetOffsetsPreRun(cmd *cobra.Command, args []string) error {
return resetOffsetsConfig.shared.validate()
}
func resetOffsetsRun(cmd *cobra.Command, args []string) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
adminClient, err := replConfig.shared.getAdminClient(ctx, nil, true)
if err != nil {
return err
}
defer adminClient.Close()
topic := args[0]
group := args[1]
topicInfo, err := adminClient.GetTopic(ctx, topic, false)
if err != nil {
return err
}
partitionIDsMap := map[int]struct{}{}
for _, partitionInfo := range topicInfo.Partitions {
partitionIDsMap[partitionInfo.ID] = struct{}{}
}
partitionOffsets := map[int]int64{}
if len(resetOffsetsConfig.partitions) > 0 {
for _, partition := range resetOffsetsConfig.partitions {
if _, ok := partitionIDsMap[partition]; !ok {
return fmt.Errorf("Partition %d not found in topic %s", partition, topic)
}
partitionOffsets[partition] = resetOffsetsConfig.offset
}
} else {
for _, partitionInfo := range topicInfo.Partitions {
partitionOffsets[partitionInfo.ID] = resetOffsetsConfig.offset
}
}
log.Infof(
"This will reset the offsets for the following partitions in topic %s for group %s:\n%s",
topic,
group,
groups.FormatPartitionOffsets(partitionOffsets),
)
log.Info(
"Please ensure that all other consumers are stopped, otherwise the reset might be overridden.",
)
ok, _ := apply.Confirm("OK to continue?", false)
if !ok {
return errors.New("Stopping because of user response")
}
cliRunner := cli.NewCLIRunner(adminClient, log.Infof, !noSpinner)
return cliRunner.ResetOffsets(
ctx,
topic,
group,
partitionOffsets,
)
}
|
stauntonknight/algorithm
|
gcj/4284486/a/a.cc
|
<filename>gcj/4284486/a/a.cc
#include <iostream>
using namespace std;
int getNum(long long i, int target) {
if (i <= 1) return 0;
long long numDig = (1ll << target) - 1;
if (i == numDig / 2 + 1) {
return 0;
} else if (i <= numDig / 2) {
return getNum(i, target - 1);
} else {
return 1 - (getNum(numDig - i + 1, target - 1));
}
return -1;
}
int main() {
int N;
cin >> N;
for (int i = 0 ; i < N ;i++) {
long long K;
cin >> K;
int target = 0;
while ((1ll<<target) <= K) {
target++;
}
cout << "Case #" << i + 1 << ": " << getNum(K, target) << endl;
}
return 0;
}
|
tas9n/OpenSiv3D
|
Siv3D/src/Siv3D-Platform/macOS/Siv3D/AudioFormat/MP3/MP3Decoder.cpp
|
//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2022 <NAME>
// Copyright (c) 2016-2022 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# include <Siv3D/AudioFormat/MP3Decoder.hpp>
# include <Siv3D/FileSystem.hpp>
# include <Siv3D/EngineLog.hpp>
# include <Siv3D/AudioCodec/CAudioCodec.hpp>
# include <Siv3D/Common/Siv3DEngine.hpp>
namespace s3d
{
StringView MP3Decoder::name() const
{
return U"MP3"_sv;
}
bool MP3Decoder::isHeader(const uint8(&bytes)[48]) const
{
static constexpr uint8 MPEG1_SIGN[] = { 0xFF, 0xFB };
static constexpr uint8 MP3_SIGN[] = { 0x49, 0x44, 0x33 };
return (std::memcmp(bytes, MPEG1_SIGN, sizeof(MPEG1_SIGN)) == 0)
|| (std::memcmp(bytes, MP3_SIGN, sizeof(MP3_SIGN)) == 0);
}
const Array<String>& MP3Decoder::possibleExtensions() const
{
static const Array<String> extensions = { U"mp3" };
return extensions;
}
AudioFormat MP3Decoder::audioFormat() const noexcept
{
return AudioFormat::MP3;
}
Wave MP3Decoder::decode(const FilePathView path) const
{
if (auto p = dynamic_cast<CAudioCodec*>(SIV3D_ENGINE(AudioCodec)))
{
return p->decode(path, AudioFormat::MP3);
}
return{};
}
Wave MP3Decoder::decode(IReader& reader, const FilePathView path) const
{
if (path)
{
return decode(path);
}
else
{
const FilePath tmpPath = FileSystem::UniqueFilePath();
Blob blob{ reader };
if (not blob.save(tmpPath))
{
return{};
}
const Wave result = decode(tmpPath);
FileSystem::Remove(tmpPath);
return result;
}
}
}
|
jkomoros/boardgame
|
boardgame-util/cmd_db_version.go
|
<reponame>jkomoros/boardgame
package main
import (
"fmt"
"strconv"
"github.com/bobziuchkovski/writ"
)
type dbVersion struct {
baseSubCommand
}
func (d *dbVersion) Name() string {
return "version"
}
func (d *dbVersion) Description() string {
return "Print what version of the migrations have been applied to db so far and quit"
}
func (d *dbVersion) Run(p writ.Path, positonal []string) {
parent := d.Parent().(*db)
m := parent.GetMigrate(false)
version, _, err := m.Version()
if err != nil {
d.Base().errAndQuit("Couldn't get version: " + err.Error())
}
fmt.Println("Version: " + strconv.Itoa(int(version)))
}
|
Redchards/AutoMark
|
tests/cadrage/CadrageTest.java
|
<gh_stars>0
import com.auto.mark.annotation.MarkedTest;
import static org.junit.Assert.assertEquals;
import up5.cadrage.Cadrage;
/**
* Unit test for Cadrage
*/
public class CadrageTest
{
@MarkedTest(value = 3.0)
public static void cadrerAGaucheTest( ) {
assertEquals("azertxxxxx",new Cadrage('x').cadrerAGauche("azert",10));
}
@MarkedTest(value = 2.0)
public static void cadrerADroiteTest( ) {
assertEquals("xxxxxazert",new Cadrage('x').cadrerADroite("azert",10));
}
@MarkedTest(value = 1.5)
public static void cadrerADroiteTronque( ) {
assertEquals("aze",new Cadrage('x').cadrerADroite("azert",3));
}
@MarkedTest(value = 1.5)
public static void cadrerAGaucheTronque( ) {
assertEquals("aze",new Cadrage('x').cadrerAGauche("azert",3));
}
}
|
yurinogueira/EterniaServer
|
src/main/java/br/com/eterniaserver/eterniaserver/modules/Constants.java
|
<filename>src/main/java/br/com/eterniaserver/eterniaserver/modules/Constants.java
package br.com.eterniaserver.eterniaserver.modules;
import java.io.File;
public class Constants {
public static final String DATA_LAYER_FOLDER_PATH = "plugins" + File.separator + "EterniaServer";
public static final String MAIN_CONFIG_FILE_PATH = DATA_LAYER_FOLDER_PATH + File.separator + "config";
public static final String DATA_MODULE_FOLDER_PATH = DATA_LAYER_FOLDER_PATH + File.separator + "modules";
public static final String CORE_CONFIG_FILE_PATH = DATA_MODULE_FOLDER_PATH + File.separator + "core.yml";
public static final String CORE_COMMAND_FILE_PATH = DATA_MODULE_FOLDER_PATH + File.separator + "core-cmd.yml";
public static final String SPAWNER_MODULE_FOLDER_PATH = DATA_MODULE_FOLDER_PATH + File.separator + "spawner";
public static final String SPAWNER_CONFIG_FILE_PATH = SPAWNER_MODULE_FOLDER_PATH + File.separator + "spawner.yml";
public static final String SPAWNER_COMMAND_FILE_PATH = SPAWNER_MODULE_FOLDER_PATH + File.separator + "spawner-cmd.yml";
public static final String SPAWNER_MESSAGE_FILE_PATH = SPAWNER_MODULE_FOLDER_PATH + File.separator + "spawner-msg.yml";
public static final String EXPERIENCE_MODULE_FOLDER_PATH = DATA_MODULE_FOLDER_PATH + File.separator + "experience";
public static final String EXPERIENCE_CONFIG_FILE_PATH = EXPERIENCE_MODULE_FOLDER_PATH + File.separator + "experience.yml";
public static final String EXPERIENCE_COMMAND_FILE_PATH = EXPERIENCE_MODULE_FOLDER_PATH + File.separator + "experience-cmd.yml";
public static final String EXPERIENCE_MESSAGE_FILE_PATH = EXPERIENCE_MODULE_FOLDER_PATH + File.separator + "experience-msg.yml";
public static final String ELEVATOR_MODULE_FOLDER_PATH = DATA_MODULE_FOLDER_PATH + File.separator + "elevator";
public static final String ELEVATOR_CONFIG_FILE_PATH = ELEVATOR_MODULE_FOLDER_PATH + File.separator + "elevator.yml";
public static final String REWARDS_MODULE_FOLDER_PATH = DATA_MODULE_FOLDER_PATH + File.separator + "rewards";
public static final String REWARDS_CONFIG_FILE_PATH = REWARDS_MODULE_FOLDER_PATH + File.separator + "rewards.yml";
public static final String REWARDS_COMMAND_FILE_PATH = REWARDS_MODULE_FOLDER_PATH + File.separator + "rewards-cmd.yml";
public static final String REWARDS_MESSAGE_FILE_PATH = REWARDS_MODULE_FOLDER_PATH + File.separator + "rewards-msg.yml";
public static final String GLOW_MODULE_FOLDER_PATH = DATA_MODULE_FOLDER_PATH + File.separator + "glow";
public static final String GLOW_CONFIG_FILE_PATH = GLOW_MODULE_FOLDER_PATH + File.separator + "glow.yml";
public static final String GLOW_COMMAND_FILE_PATH = GLOW_MODULE_FOLDER_PATH + File.separator + "glow-cmd.yml";
public static final String GLOW_MESSAGE_FILE_PATH = GLOW_MODULE_FOLDER_PATH + File.separator + "glow-msg.yml";
public static final String PAPI_MODULE_FOLDER_PATH = DATA_MODULE_FOLDER_PATH + File.separator + "papi";
public static final String PAPI_CONFIG_FILE_PATH = GLOW_MODULE_FOLDER_PATH + File.separator + "papi.yml";
public static final String CASH_MODULE_FOLDER_PATH = DATA_MODULE_FOLDER_PATH + File.separator + "cash";
public static final String CASH_CONFIG_FILE_PATH = CASH_MODULE_FOLDER_PATH + File.separator + "cash.yml";
public static final String CASH_COMMAND_FILE_PATH = CASH_MODULE_FOLDER_PATH + File.separator + "cash-cmd.yml";
public static final String CASH_MESSAGE_FILE_PATH = CASH_MODULE_FOLDER_PATH + File.separator + "cash-msg.yml";
}
|
barboras7/drools
|
kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/parser/feel11/FEELParserTest.java
|
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.dmn.feel.parser.feel11;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.antlr.v4.runtime.tree.ParseTree;
import org.junit.Test;
import org.kie.dmn.feel.lang.Type;
import org.kie.dmn.feel.lang.ast.BaseNode;
import org.kie.dmn.feel.lang.ast.BetweenNode;
import org.kie.dmn.feel.lang.ast.BooleanNode;
import org.kie.dmn.feel.lang.ast.ContextEntryNode;
import org.kie.dmn.feel.lang.ast.ContextNode;
import org.kie.dmn.feel.lang.ast.FilterExpressionNode;
import org.kie.dmn.feel.lang.ast.ForExpressionNode;
import org.kie.dmn.feel.lang.ast.FunctionDefNode;
import org.kie.dmn.feel.lang.ast.FunctionInvocationNode;
import org.kie.dmn.feel.lang.ast.IfExpressionNode;
import org.kie.dmn.feel.lang.ast.InNode;
import org.kie.dmn.feel.lang.ast.InfixOpNode;
import org.kie.dmn.feel.lang.ast.InstanceOfNode;
import org.kie.dmn.feel.lang.ast.IterationContextNode;
import org.kie.dmn.feel.lang.ast.ListNode;
import org.kie.dmn.feel.lang.ast.NameDefNode;
import org.kie.dmn.feel.lang.ast.NameRefNode;
import org.kie.dmn.feel.lang.ast.NamedParameterNode;
import org.kie.dmn.feel.lang.ast.NullNode;
import org.kie.dmn.feel.lang.ast.NumberNode;
import org.kie.dmn.feel.lang.ast.PathExpressionNode;
import org.kie.dmn.feel.lang.ast.QualifiedNameNode;
import org.kie.dmn.feel.lang.ast.QuantifiedExpressionNode;
import org.kie.dmn.feel.lang.ast.RangeNode;
import org.kie.dmn.feel.lang.ast.SignedUnaryNode;
import org.kie.dmn.feel.lang.ast.StringNode;
import org.kie.dmn.feel.lang.ast.TypeNode;
import org.kie.dmn.feel.lang.ast.UnaryTestNode;
import org.kie.dmn.feel.lang.impl.MapBackedType;
import org.kie.dmn.feel.lang.types.BuiltInType;
import org.kie.dmn.feel.util.Msg;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.Matchers.empty;
import static org.junit.Assert.assertThat;
import static org.kie.dmn.feel.util.DynamicTypeUtils.entry;
import static org.kie.dmn.feel.util.DynamicTypeUtils.mapOf;
public class FEELParserTest {
@Test
public void testIntegerLiteral() {
String inputExpression = "10";
BaseNode number = parse( inputExpression );
assertThat( number, is( instanceOf( NumberNode.class ) ) );
assertThat( number.getResultType(), is( BuiltInType.NUMBER ) );
assertLocation( inputExpression, number );
}
@Test
public void testNegativeIntegerLiteral() {
String inputExpression = "-10";
BaseNode number = parse( inputExpression );
assertThat( number, is( instanceOf( SignedUnaryNode.class ) ) );
assertThat( number.getResultType(), is( BuiltInType.NUMBER ) );
assertLocation( inputExpression, number );
SignedUnaryNode sun = (SignedUnaryNode) number;
assertThat( sun.getSign(), is( SignedUnaryNode.Sign.NEGATIVE ) );
assertThat( sun.getExpression(), is( instanceOf( NumberNode.class ) ) );
assertThat( sun.getExpression().getText(), is( "10" ) );
}
@Test
public void testPositiveIntegerLiteral() {
String inputExpression = "+10";
BaseNode number = parse( inputExpression );
assertThat( number, is( instanceOf( SignedUnaryNode.class ) ) );
assertThat( number.getResultType(), is( BuiltInType.NUMBER ) );
assertLocation( inputExpression, number );
SignedUnaryNode sun = (SignedUnaryNode) number;
assertThat( sun.getSign(), is( SignedUnaryNode.Sign.POSITIVE ) );
assertThat( sun.getExpression(), is( instanceOf( NumberNode.class ) ) );
assertThat( sun.getExpression().getText(), is( "10" ) );
}
@Test
public void testFloatLiteral() {
String inputExpression = "10.5";
BaseNode number = parse( inputExpression );
assertThat( number, is( instanceOf( NumberNode.class ) ) );
assertThat( number.getResultType(), is( BuiltInType.NUMBER ) );
assertLocation( inputExpression, number );
}
@Test
public void testNegativeFloatLiteral() {
String inputExpression = "-10.5";
BaseNode number = parse( inputExpression );
assertThat( number, is( instanceOf( SignedUnaryNode.class ) ) );
assertThat( number.getResultType(), is( BuiltInType.NUMBER ) );
assertLocation( inputExpression, number );
SignedUnaryNode sun = (SignedUnaryNode) number;
assertThat( sun.getSign(), is( SignedUnaryNode.Sign.NEGATIVE ) );
assertThat( sun.getExpression(), is( instanceOf( NumberNode.class ) ) );
assertThat( sun.getExpression().getText(), is( "10.5" ) );
}
@Test
public void testPositiveFloatLiteral() {
String inputExpression = "+10.5";
BaseNode number = parse( inputExpression );
assertThat( number, is( instanceOf( SignedUnaryNode.class ) ) );
assertThat( number.getResultType(), is( BuiltInType.NUMBER ) );
assertLocation( inputExpression, number );
SignedUnaryNode sun = (SignedUnaryNode) number;
assertThat( sun.getSign(), is( SignedUnaryNode.Sign.POSITIVE ) );
assertThat( sun.getExpression(), is( instanceOf( NumberNode.class ) ) );
assertThat( sun.getExpression().getText(), is( "10.5" ) );
}
@Test
public void testBooleanTrueLiteral() {
String inputExpression = "true";
BaseNode bool = parse( inputExpression );
assertThat( bool, is( instanceOf( BooleanNode.class ) ) );
assertThat( bool.getResultType(), is( BuiltInType.BOOLEAN ) );
assertLocation( inputExpression, bool );
}
@Test
public void testBooleanFalseLiteral() {
String inputExpression = "false";
BaseNode bool = parse( inputExpression );
assertThat( bool, is( instanceOf( BooleanNode.class ) ) );
assertThat( bool.getResultType(), is( BuiltInType.BOOLEAN ) );
assertLocation( inputExpression, bool );
}
@Test
public void testNullLiteral() {
String inputExpression = "null";
BaseNode nullLit = parse( inputExpression );
assertThat( nullLit, is( instanceOf( NullNode.class ) ) );
assertThat( nullLit.getResultType(), is( BuiltInType.UNKNOWN ) );
assertLocation( inputExpression, nullLit );
}
@Test
public void testStringLiteral() {
String inputExpression = "\"some string\"";
BaseNode stringLit = parse( inputExpression );
assertThat( stringLit, is( instanceOf( StringNode.class ) ) );
assertThat( stringLit.getResultType(), is( BuiltInType.STRING ) );
assertLocation( inputExpression, stringLit );
}
@Test
public void testNameReference() {
String inputExpression = "someSimpleName";
BaseNode nameRef = parse( inputExpression, mapOf( entry("someSimpleName", BuiltInType.STRING) ) );
assertThat( nameRef, is( instanceOf( NameRefNode.class ) ) );
assertThat( nameRef.getResultType(), is( BuiltInType.STRING ) );
assertLocation( inputExpression, nameRef );
}
@Test
public void testQualifiedName() {
String inputExpression = "My Person.Full Name";
MapBackedType personType = new MapBackedType("Person", mapOf( entry("Full Name", BuiltInType.STRING), entry("Age", BuiltInType.NUMBER) ) );
BaseNode qualRef = parse( inputExpression, mapOf( entry("My Person", personType) ) );
assertThat( qualRef, is( instanceOf( QualifiedNameNode.class ) ) );
assertThat( qualRef.getResultType(), is( BuiltInType.STRING ) );
List<NameRefNode> parts = ((QualifiedNameNode) qualRef).getParts();
// `My Person` ...
assertThat( parts.get(0), is( instanceOf( NameRefNode.class ) ) );
assertThat( parts.get(0).getResultType(), is( personType ) );
// ... `.Full Name`
assertThat( parts.get(1), is( instanceOf( NameRefNode.class ) ) );
assertThat( parts.get(1).getResultType(), is( BuiltInType.STRING ) );
assertLocation( inputExpression, qualRef );
}
@Test
public void testParensWithLiteral() {
String inputExpression = "(10.5 )";
BaseNode number = parse( inputExpression );
assertThat( number, is( instanceOf( NumberNode.class ) ) );
assertThat( number.getResultType(), is( BuiltInType.NUMBER ) );
assertThat( number.getText(), is( "10.5" ) );
}
@Test
public void testLogicalNegation() {
String inputExpression = "not ( true )";
BaseNode neg = parse( inputExpression );
assertThat( neg, is( instanceOf( FunctionInvocationNode.class ) ) );
assertThat( neg.getResultType(), is( BuiltInType.BOOLEAN ) );
assertThat( neg.getText(), is( "not ( true )" ) );
FunctionInvocationNode not = (FunctionInvocationNode) neg;
assertThat( not.getParams().getElements().get( 0 ), is( instanceOf( BooleanNode.class ) ) );
assertThat( not.getParams().getElements().get( 0 ).getResultType(), is( BuiltInType.BOOLEAN ) );
assertThat( not.getParams().getElements().get( 0 ).getText(), is( "true" ) );
}
@Test
public void testMultiplication() {
String inputExpression = "10 * x";
BaseNode infix = parse( inputExpression, mapOf(entry("x", BuiltInType.NUMBER)) );
assertThat( infix, is( instanceOf( InfixOpNode.class ) ) );
assertThat( infix.getResultType(), is( BuiltInType.NUMBER ) );
assertThat( infix.getText(), is( inputExpression ) );
InfixOpNode mult = (InfixOpNode) infix;
assertThat( mult.getLeft(), is( instanceOf( NumberNode.class ) ) );
assertThat( mult.getLeft().getText(), is( "10" ) );
assertThat( mult.getOperator(), is( InfixOpNode.InfixOperator.MULT ) );
assertThat( mult.getRight(), is( instanceOf( NameRefNode.class ) ) );
assertThat( mult.getRight().getText(), is( "x" ) );
}
@Test
public void testDivision() {
String inputExpression = "y / 5 * ( x )";
BaseNode infix = parse( inputExpression, mapOf(entry("x", BuiltInType.NUMBER), entry("y", BuiltInType.NUMBER)) );
assertThat( infix, is( instanceOf( InfixOpNode.class ) ) );
assertThat( infix.getResultType(), is( BuiltInType.NUMBER ) );
assertThat( infix.getText(), is( inputExpression ) );
InfixOpNode mult = (InfixOpNode) infix;
assertThat( mult.getLeft(), is( instanceOf( InfixOpNode.class ) ) );
assertThat( mult.getLeft().getText(), is( "y / 5" ) );
InfixOpNode div = (InfixOpNode) mult.getLeft();
assertThat( div.getLeft(), is( instanceOf( NameRefNode.class ) ) );
assertThat( div.getLeft().getText(), is( "y" ) );
assertThat( div.getOperator(), is( InfixOpNode.InfixOperator.DIV ) );
assertThat( div.getRight(), is( instanceOf( NumberNode.class ) ) );
assertThat( div.getRight().getText(), is( "5" ) );
assertThat( mult.getOperator(), is( InfixOpNode.InfixOperator.MULT ) );
assertThat( mult.getRight(), is( instanceOf( NameRefNode.class ) ) );
assertThat( mult.getRight().getText(), is( "x" ) );
}
@Test
public void testPower1() {
String inputExpression = "y * 5 ** 3";
BaseNode infix = parse( inputExpression, mapOf(entry("y", BuiltInType.NUMBER)) );
assertThat( infix, is( instanceOf( InfixOpNode.class ) ) );
assertThat( infix.getResultType(), is( BuiltInType.NUMBER ) );
assertThat( infix.getText(), is( inputExpression ) );
InfixOpNode mult = (InfixOpNode) infix;
assertThat( mult.getLeft(), is( instanceOf( NameRefNode.class ) ) );
assertThat( mult.getLeft().getText(), is( "y" ) );
assertThat( mult.getOperator(), is( InfixOpNode.InfixOperator.MULT ) );
assertThat( mult.getRight(), is( instanceOf( InfixOpNode.class ) ) );
assertThat( mult.getRight().getText(), is( "5 ** 3" ) );
InfixOpNode exp = (InfixOpNode) mult.getRight();
assertThat( exp.getLeft(), is( instanceOf( NumberNode.class ) ) );
assertThat( exp.getLeft().getText(), is( "5" ) );
assertThat( exp.getOperator(), is( InfixOpNode.InfixOperator.POW ) );
assertThat( exp.getRight(), is( instanceOf( NumberNode.class ) ) );
assertThat( exp.getRight().getText(), is( "3" ) );
}
@Test
public void testPower2() {
String inputExpression = "(y * 5) ** 3";
BaseNode infix = parse( inputExpression, mapOf(entry("y", BuiltInType.NUMBER)) );
assertThat( infix, is( instanceOf( InfixOpNode.class ) ) );
assertThat( infix.getResultType(), is( BuiltInType.NUMBER ) );
assertThat( infix.getText(), is( inputExpression ) );
InfixOpNode exp = (InfixOpNode) infix;
assertThat( exp.getLeft(), is( instanceOf( InfixOpNode.class ) ) );
assertThat( exp.getLeft().getText(), is( "y * 5" ) );
assertThat( exp.getOperator(), is( InfixOpNode.InfixOperator.POW ) );
assertThat( exp.getRight(), is( instanceOf( NumberNode.class ) ) );
assertThat( exp.getRight().getText(), is( "3" ) );
InfixOpNode mult = (InfixOpNode) exp.getLeft();
assertThat( mult.getLeft(), is( instanceOf( NameRefNode.class ) ) );
assertThat( mult.getLeft().getText(), is( "y" ) );
assertThat( mult.getOperator(), is( InfixOpNode.InfixOperator.MULT ) );
assertThat( mult.getRight(), is( instanceOf( NumberNode.class ) ) );
assertThat( mult.getRight().getText(), is( "5" ) );
}
@Test
public void testPower3() {
String inputExpression = "y ** 5 * 3";
BaseNode infix = parse( inputExpression, mapOf(entry("y", BuiltInType.NUMBER)) );
assertThat( infix, is( instanceOf( InfixOpNode.class ) ) );
assertThat( infix.getResultType(), is( BuiltInType.NUMBER ) );
assertThat( infix.getText(), is( inputExpression ) );
InfixOpNode mult = (InfixOpNode) infix;
assertThat( mult.getLeft(), is( instanceOf( InfixOpNode.class ) ) );
assertThat( mult.getLeft().getText(), is( "y ** 5" ) );
assertThat( mult.getOperator(), is( InfixOpNode.InfixOperator.MULT ) );
assertThat( mult.getRight(), is( instanceOf( NumberNode.class ) ) );
assertThat( mult.getRight().getText(), is( "3" ) );
InfixOpNode exp = (InfixOpNode) mult.getLeft();
assertThat( exp.getLeft(), is( instanceOf( NameRefNode.class ) ) );
assertThat( exp.getLeft().getText(), is( "y" ) );
assertThat( exp.getOperator(), is( InfixOpNode.InfixOperator.POW ) );
assertThat( exp.getRight(), is( instanceOf( NumberNode.class ) ) );
assertThat( exp.getRight().getText(), is( "5" ) );
}
@Test
public void testPower4() {
String inputExpression = "y ** ( 5 * 3 )";
BaseNode infix = parse( inputExpression, mapOf(entry("y", BuiltInType.NUMBER)) );
assertThat( infix, is( instanceOf( InfixOpNode.class ) ) );
assertThat( infix.getResultType(), is( BuiltInType.NUMBER ) );
assertThat( infix.getText(), is( inputExpression ) );
InfixOpNode exp = (InfixOpNode) infix;
assertThat( exp.getLeft(), is( instanceOf( NameRefNode.class ) ) );
assertThat( exp.getLeft().getText(), is( "y" ) );
assertThat( exp.getOperator(), is( InfixOpNode.InfixOperator.POW ) );
assertThat( exp.getRight(), is( instanceOf( InfixOpNode.class ) ) );
assertThat( exp.getRight().getText(), is( "5 * 3" ) );
InfixOpNode mult = (InfixOpNode) exp.getRight();
assertThat( mult.getLeft(), is( instanceOf( NumberNode.class ) ) );
assertThat( mult.getLeft().getText(), is( "5" ) );
assertThat( mult.getOperator(), is( InfixOpNode.InfixOperator.MULT ) );
assertThat( mult.getRight(), is( instanceOf( NumberNode.class ) ) );
assertThat( mult.getRight().getText(), is( "3" ) );
}
@Test
public void testAdd1() {
String inputExpression = "y + 5 * 3";
BaseNode infix = parse( inputExpression, mapOf(entry("y", BuiltInType.NUMBER)) );
assertThat( infix, is( instanceOf( InfixOpNode.class ) ) );
assertThat( infix.getResultType(), is( BuiltInType.NUMBER ) );
assertThat( infix.getText(), is( inputExpression ) );
InfixOpNode add = (InfixOpNode) infix;
assertThat( add.getLeft(), is( instanceOf( NameRefNode.class ) ) );
assertThat( add.getLeft().getText(), is( "y" ) );
assertThat( add.getOperator(), is( InfixOpNode.InfixOperator.ADD ) );
assertThat( add.getRight(), is( instanceOf( InfixOpNode.class ) ) );
assertThat( add.getRight().getText(), is( "5 * 3" ) );
InfixOpNode mult = (InfixOpNode) add.getRight();
assertThat( mult.getLeft(), is( instanceOf( NumberNode.class ) ) );
assertThat( mult.getLeft().getText(), is( "5" ) );
assertThat( mult.getOperator(), is( InfixOpNode.InfixOperator.MULT ) );
assertThat( mult.getRight(), is( instanceOf( NumberNode.class ) ) );
assertThat( mult.getRight().getText(), is( "3" ) );
}
@Test
public void testSub1() {
String inputExpression = "(y - 5) ** 3";
BaseNode infix = parse( inputExpression, mapOf(entry("y", BuiltInType.NUMBER)) );
assertThat( infix, is( instanceOf( InfixOpNode.class ) ) );
assertThat( infix.getResultType(), is( BuiltInType.NUMBER ) );
assertThat( infix.getText(), is( inputExpression ) );
InfixOpNode sub = (InfixOpNode) infix;
assertThat( sub.getLeft(), is( instanceOf( InfixOpNode.class ) ) );
assertThat( sub.getLeft().getText(), is( "y - 5" ) );
assertThat( sub.getOperator(), is( InfixOpNode.InfixOperator.POW ) );
assertThat( sub.getRight(), is( instanceOf( NumberNode.class ) ) );
assertThat( sub.getRight().getText(), is( "3" ) );
InfixOpNode mult = (InfixOpNode) sub.getLeft();
assertThat( mult.getLeft(), is( instanceOf( NameRefNode.class ) ) );
assertThat( mult.getLeft().getText(), is( "y" ) );
assertThat( mult.getOperator(), is( InfixOpNode.InfixOperator.SUB ) );
assertThat( mult.getRight(), is( instanceOf( NumberNode.class ) ) );
assertThat( mult.getRight().getText(), is( "5" ) );
}
@Test
public void testBetween() {
String inputExpression = "x between 10+y and 3**z";
BaseNode between = parse( inputExpression );
assertThat( between, is( instanceOf( BetweenNode.class ) ) );
assertThat( between.getResultType(), is( BuiltInType.BOOLEAN ) );
assertThat( between.getText(), is( inputExpression ) );
BetweenNode btw = (BetweenNode) between;
assertThat( btw.getValue(), is( instanceOf( NameRefNode.class ) ) );
assertThat( btw.getValue().getText(), is( "x" ) );
assertThat( btw.getStart(), is( instanceOf( InfixOpNode.class ) ) );
assertThat( btw.getStart().getText(), is( "10+y" ) );
assertThat( btw.getEnd(), is( instanceOf( InfixOpNode.class ) ) );
assertThat( btw.getEnd().getText(), is( "3**z" ) );
}
@Test
public void testInValueList() {
// TODO review this test might be wrong as list is not homogeneous
String inputExpression = "x / 4 in ( 10+y, true, 80, someVar )";
BaseNode inNode = parse( inputExpression );
assertThat( inNode, is( instanceOf( InNode.class ) ) );
assertThat( inNode.getResultType(), is( BuiltInType.BOOLEAN ) );
assertThat( inNode.getText(), is( inputExpression ) );
InNode in = (InNode) inNode;
assertThat( in.getValue(), is( instanceOf( InfixOpNode.class ) ) );
assertThat( in.getValue().getText(), is( "x / 4" ) );
assertThat( in.getExprs(), is( instanceOf( ListNode.class ) ) );
assertThat( in.getExprs().getText(), is( "10+y, true, 80, someVar" ) );
ListNode list = (ListNode) in.getExprs();
assertThat( list.getElements().get( 0 ), is( instanceOf( InfixOpNode.class ) ) );
assertThat( list.getElements().get( 1 ), is( instanceOf( BooleanNode.class ) ) );
assertThat( list.getElements().get( 2 ), is( instanceOf( NumberNode.class ) ) );
assertThat( list.getElements().get( 3 ), is( instanceOf( NameRefNode.class ) ) );
}
@Test
public void testInUnaryTestList() {
String inputExpression = "x ** y in ( <=1000, >t, null, (2000..z[, ]z..2000], [(10+5)..(a*b)) )";
BaseNode inNode = parse( inputExpression );
assertThat( inNode, is( instanceOf( InNode.class ) ) );
assertThat( inNode.getResultType(), is( BuiltInType.BOOLEAN ) );
assertThat( inNode.getText(), is( inputExpression ) );
InNode in = (InNode) inNode;
assertThat( in.getValue(), is( instanceOf( InfixOpNode.class ) ) );
assertThat( in.getValue().getText(), is( "x ** y" ) );
assertThat( in.getExprs(), is( instanceOf( ListNode.class ) ) );
assertThat( in.getExprs().getText(), is( "<=1000, >t, null, (2000..z[, ]z..2000], [(10+5)..(a*b))" ) );
ListNode list = (ListNode) in.getExprs();
assertThat( list.getElements().get( 0 ), is( instanceOf( UnaryTestNode.class ) ) );
assertThat( list.getElements().get( 0 ).getText(), is( "<=1000" ) );
assertThat( list.getElements().get( 1 ), is( instanceOf( UnaryTestNode.class ) ) );
assertThat( list.getElements().get( 1 ).getText(), is( ">t" ) );
assertThat( list.getElements().get( 2 ), is( instanceOf( NullNode.class ) ) );
assertThat( list.getElements().get( 2 ).getText(), is( "null" ) );
assertThat( list.getElements().get( 3 ), is( instanceOf( RangeNode.class ) ) );
RangeNode interval = (RangeNode) list.getElements().get( 3 );
assertThat( interval.getText(), is( "(2000..z[") );
assertThat( interval.getLowerBound(), is( RangeNode.IntervalBoundary.OPEN ) );
assertThat( interval.getUpperBound(), is( RangeNode.IntervalBoundary.OPEN ) );
assertThat( interval.getStart(), is( instanceOf( NumberNode.class ) ) );
assertThat( interval.getEnd(), is( instanceOf( NameRefNode.class ) ) );
assertThat( list.getElements().get( 4 ), is( instanceOf( RangeNode.class ) ) );
interval = (RangeNode) list.getElements().get( 4 );
assertThat( interval.getText(), is( "]z..2000]") );
assertThat( interval.getLowerBound(), is( RangeNode.IntervalBoundary.OPEN ) );
assertThat( interval.getUpperBound(), is( RangeNode.IntervalBoundary.CLOSED ) );
assertThat( interval.getStart(), is( instanceOf( NameRefNode.class ) ) );
assertThat( interval.getEnd(), is( instanceOf( NumberNode.class ) ) );
assertThat( list.getElements().get( 5 ), is( instanceOf( RangeNode.class ) ) );
interval = (RangeNode) list.getElements().get( 5 );
assertThat( interval.getText(), is( "[(10+5)..(a*b))") );
assertThat( interval.getLowerBound(), is( RangeNode.IntervalBoundary.CLOSED ) );
assertThat( interval.getUpperBound(), is( RangeNode.IntervalBoundary.OPEN ) );
assertThat( interval.getStart(), is( instanceOf( InfixOpNode.class ) ) );
assertThat( interval.getEnd(), is( instanceOf( InfixOpNode.class ) ) );
}
@Test
public void testInUnaryTest() {
String inputExpression = "x - y in [(10+5)..(a*b))";
BaseNode inNode = parse( inputExpression );
assertThat( inNode, is( instanceOf( InNode.class ) ) );
assertThat( inNode.getResultType(), is( BuiltInType.BOOLEAN ) );
assertThat( inNode.getText(), is( inputExpression ) );
InNode in = (InNode) inNode;
assertThat( in.getValue(), is( instanceOf( InfixOpNode.class ) ) );
assertThat( in.getValue().getText(), is( "x - y" ) );
assertThat( in.getExprs(), is( instanceOf( RangeNode.class ) ) );
assertThat( in.getExprs().getText(), is( "[(10+5)..(a*b))" ) );
}
@Test
public void testComparisonInFixOp() {
String inputExpression = "foo >= bar * 10";
BaseNode infix = parse( inputExpression );
assertThat( infix, is( instanceOf( InfixOpNode.class ) ) );
assertThat( infix.getResultType(), is( BuiltInType.BOOLEAN ) );
assertThat( infix.getText(), is( inputExpression ) );
InfixOpNode in = (InfixOpNode) infix;
assertThat( in.getLeft(), is( instanceOf( NameRefNode.class ) ) );
assertThat( in.getLeft().getText(), is( "foo" ) );
assertThat( in.getRight(), is( instanceOf( InfixOpNode.class ) ) );
assertThat( in.getRight().getText(), is( "bar * 10" ) );
}
@Test
public void testConditionalLogicalOp() {
String inputExpression = "foo < 10 and bar = \"x\" or baz";
BaseNode infix = parse( inputExpression );
assertThat( infix, is( instanceOf( InfixOpNode.class ) ) );
assertThat( infix.getResultType(), is( BuiltInType.BOOLEAN ) );
assertThat( infix.getText(), is( inputExpression ) );
InfixOpNode or = (InfixOpNode) infix;
assertThat( or.getLeft(), is( instanceOf( InfixOpNode.class ) ) );
assertThat( or.getLeft().getText(), is( "foo < 10 and bar = \"x\"" ) );
assertThat( or.getOperator(), is( InfixOpNode.InfixOperator.OR ) );
assertThat( or.getRight(), is( instanceOf( NameRefNode.class ) ) );
assertThat( or.getRight().getText(), is( "baz" ) );
InfixOpNode and = (InfixOpNode) or.getLeft();
assertThat( and.getLeft(), is( instanceOf( InfixOpNode.class ) ) );
assertThat( and.getLeft().getText(), is( "foo < 10" ) );
assertThat( and.getOperator(), is( InfixOpNode.InfixOperator.AND ) );
assertThat( and.getRight(), is( instanceOf( InfixOpNode.class ) ) );
assertThat( and.getRight().getText(), is( "bar = \"x\"" ) );
}
@Test
public void testEmptyList() {
String inputExpression = "[]";
BaseNode list = parse( inputExpression );
assertThat( list, is( instanceOf( ListNode.class ) ) );
assertThat( list.getResultType(), is( BuiltInType.LIST ) );
assertThat( list.getText(), is( inputExpression ) );
ListNode ln = (ListNode) list;
assertThat( ln.getElements(), is( empty() ));
}
@Test
public void testExpressionList() {
// TODO review this test is potentially wrong as the list is not homogeneous
String inputExpression = "[ 10, foo * bar, true ]";
BaseNode list = parse( inputExpression );
assertThat( list, is( instanceOf( ListNode.class ) ) );
assertThat( list.getResultType(), is( BuiltInType.LIST ) );
assertThat( list.getText(), is( "10, foo * bar, true" ) );
ListNode ln = (ListNode) list;
assertThat( ln.getElements().size(), is( 3 ) );
assertThat( ln.getElements().get( 0 ), is( instanceOf( NumberNode.class ) ) );
assertThat( ln.getElements().get( 1 ), is( instanceOf( InfixOpNode.class ) ) );
assertThat( ln.getElements().get( 2 ), is( instanceOf( BooleanNode.class ) ) );
}
@Test
public void testEmptyContext() {
String inputExpression = "{}";
BaseNode context = parse( inputExpression );
assertThat( context, is( instanceOf( ContextNode.class ) ) );
assertThat( context.getText(), is( inputExpression ) );
ContextNode ctx = (ContextNode) context;
assertThat( ctx.getEntries(), is( empty() ));
}
@Test
public void testContextWithMultipleEntries() {
String inputExpression = "{ \"a string key\" : 10,"
+ " a non-string key : foo+bar,"
+ " a key.with + /' odd chars : [10..50] }";
BaseNode ctxbase = parse( inputExpression, mapOf(entry("foo", BuiltInType.NUMBER), entry("bar", BuiltInType.NUMBER)) );
assertThat( ctxbase, is( instanceOf( ContextNode.class ) ) );
assertThat( ctxbase.getText(), is( inputExpression ) );
ContextNode ctx = (ContextNode) ctxbase;
assertThat( ctx.getEntries().size(), is( 3 ) );
ContextEntryNode entry = ctx.getEntries().get( 0 );
assertThat( entry.getName(), is( instanceOf( NameDefNode.class ) ) );
NameDefNode name = (NameDefNode) entry.getName();
assertThat( name.getName(), is( notNullValue() ) );
assertThat( name.getName(), is("\"a string key\"") );
assertThat( entry.getValue(), is( instanceOf( NumberNode.class ) ) );
assertThat( entry.getResultType(), is( BuiltInType.NUMBER ) );
assertThat( entry.getValue().getText(), is("10") );
entry = ctx.getEntries().get( 1 );
assertThat( entry.getName(), is( instanceOf( NameDefNode.class ) ) );
name = (NameDefNode) entry.getName();
assertThat( name.getParts(), is( notNullValue() ) );
assertThat( name.getParts().size(), is( 5 ) );
assertThat( entry.getName().getText(), is("a non-string key") );
assertThat( entry.getValue(), is( instanceOf( InfixOpNode.class ) ) );
assertThat( entry.getResultType(), is( BuiltInType.NUMBER ) );
assertThat( entry.getValue().getText(), is( "foo+bar" ) );
entry = ctx.getEntries().get( 2 );
assertThat( entry.getName(), is( instanceOf( NameDefNode.class ) ) );
name = (NameDefNode) entry.getName();
assertThat( name.getParts(), is( notNullValue() ) );
assertThat( name.getParts().size(), is( 9 ) );
assertThat( entry.getName().getText(), is("a key.with + /' odd chars") );
assertThat( entry.getValue(), is( instanceOf( RangeNode.class ) ) );
assertThat( entry.getResultType(), is( BuiltInType.RANGE ) );
assertThat( entry.getValue().getText(), is( "[10..50]" ) );
}
@Test
public void testNestedContexts() {
String inputExpression = "{ a value : 10,"
+ " an applicant : { "
+ " first name : \"Edson\", "
+ " last + name : \"Tirelli\", "
+ " full name : first name + last + name, "
+ " address : {"
+ " street : \"55 broadway st\","
+ " city : \"New York\" "
+ " }, "
+ " xxx: last + name"
+ " } "
+ "}";
BaseNode ctxbase = parse( inputExpression );
assertThat( ctxbase, is( instanceOf( ContextNode.class ) ) );
assertThat( ctxbase.getText(), is( inputExpression ) );
ContextNode ctx = (ContextNode) ctxbase;
assertThat( ctx.getEntries().size(), is( 2 ) );
ContextEntryNode entry = ctx.getEntries().get( 0 );
assertThat( entry.getName(), is( instanceOf( NameDefNode.class ) ) );
NameDefNode name = (NameDefNode) entry.getName();
assertThat( name.getText(), is("a value") );
assertThat( entry.getValue(), is( instanceOf( NumberNode.class ) ) );
assertThat( entry.getResultType(), is( BuiltInType.NUMBER ) );
assertThat( entry.getValue().getText(), is("10") );
entry = ctx.getEntries().get( 1 );
assertThat( entry.getName(), is( instanceOf( NameDefNode.class ) ) );
name = (NameDefNode) entry.getName();
assertThat( name.getText(), is( "an applicant" ) );
assertThat( entry.getValue(), is( instanceOf( ContextNode.class ) ) );
ContextNode applicant = (ContextNode) entry.getValue();
assertThat( applicant.getEntries().size(), is( 5 ) );
assertThat( applicant.getEntries().get( 0 ).getName().getText(), is("first name") );
assertThat( applicant.getEntries().get( 0 ).getResultType(), is( BuiltInType.STRING ) );
assertThat( applicant.getEntries().get( 1 ).getName().getText(), is("last + name") );
assertThat( applicant.getEntries().get( 1 ).getResultType(), is( BuiltInType.STRING ) );
assertThat( applicant.getEntries().get( 2 ).getName().getText(), is("full name") );
assertThat( applicant.getEntries().get( 2 ).getResultType(), is( BuiltInType.STRING ) );
assertThat( applicant.getEntries().get( 3 ).getName().getText(), is("address") );
assertThat( applicant.getEntries().get( 3 ).getValue(), is( instanceOf( ContextNode.class ) ) );
ContextNode address = (ContextNode) applicant.getEntries().get( 3 ).getValue();
assertThat( address.getEntries().size(), is( 2 ) );
assertThat( address.getEntries().get( 0 ).getName().getText(), is("street") );
assertThat( address.getEntries().get( 0 ).getResultType(), is( BuiltInType.STRING ) );
assertThat( address.getEntries().get( 1 ).getName().getText(), is("city") );
assertThat( address.getEntries().get( 0 ).getResultType(), is( BuiltInType.STRING ) );
}
@Test
public void testNestedContexts2() {
String inputExpression = "{ an applicant : { "
+ " home address : {"
+ " street name: \"broadway st\","
+ " city : \"New York\" "
+ " } "
+ " },\n "
+ " street : an applicant.home address.street name \n"
+ "}";
BaseNode ctxbase = parse( inputExpression );
assertThat( ctxbase, is( instanceOf( ContextNode.class ) ) );
assertThat( ctxbase.getText(), is( inputExpression ) );
ContextNode ctx = (ContextNode) ctxbase;
assertThat( ctx.getEntries().size(), is( 2 ) );
ContextEntryNode entry = ctx.getEntries().get( 1 );
assertThat( entry.getName(), is( instanceOf( NameDefNode.class ) ) );
assertThat( entry.getResultType(), is( BuiltInType.STRING ) );
NameDefNode name = (NameDefNode) entry.getName();
assertThat( name.getText(), is("street") );
assertThat( entry.getValue(), is( instanceOf( QualifiedNameNode.class ) ) );
QualifiedNameNode qnn = (QualifiedNameNode) entry.getValue();
assertThat( qnn.getParts().get( 0 ).getText(), is("an applicant") );
assertThat( qnn.getParts().get( 1 ).getText(), is("home address") );
assertThat( qnn.getParts().get( 2 ).getText(), is("street name") );
}
@Test
public void testFunctionDefinition() {
String inputExpression = "{ is minor : function( person's age ) person's age < 21 }";
BaseNode ctxbase = parse( inputExpression );
assertThat( ctxbase, is( instanceOf( ContextNode.class ) ) );
assertThat( ctxbase.getText(), is( inputExpression ) );
ContextNode ctx = (ContextNode) ctxbase;
assertThat( ctx.getEntries().size(), is( 1 ) );
ContextEntryNode entry = ctx.getEntries().get( 0 );
assertThat( entry.getName(), is( instanceOf( NameDefNode.class ) ) );
NameDefNode name = (NameDefNode) entry.getName();
assertThat( name.getText(), is("is minor") );
assertThat( entry.getValue(), is( instanceOf( FunctionDefNode.class ) ) );
assertThat( entry.getValue().getText(), is("function( person's age ) person's age < 21") );
FunctionDefNode isMinorFunc = (FunctionDefNode) entry.getValue();
assertThat( isMinorFunc.getFormalParameters().size(), is( 1 ) );
assertThat( isMinorFunc.getFormalParameters().get( 0 ).getText(), is( "person's age" ) );
assertThat( isMinorFunc.isExternal(), is( false ) );
assertThat( isMinorFunc.getBody(), is( instanceOf( InfixOpNode.class ) ) );
}
@Test
public void testExternalFunctionDefinition() {
String inputExpression = "{ trigonometric cosine : function( angle ) external {"
+ " java : {"
+ " class : \"java.lang.Math\","
+ " method signature : \"cos(double)\""
+ " }"
+ "}}";
BaseNode ctxbase = parse( inputExpression );
assertThat( ctxbase, is( instanceOf( ContextNode.class ) ) );
assertThat( ctxbase.getText(), is( inputExpression ) );
ContextNode ctx = (ContextNode) ctxbase;
assertThat( ctx.getEntries().size(), is( 1 ) );
ContextEntryNode entry = ctx.getEntries().get( 0 );
assertThat( entry.getName(), is( instanceOf( NameDefNode.class ) ) );
NameDefNode name = (NameDefNode) entry.getName();
assertThat( name.getText(), is("trigonometric cosine") );
assertThat( entry.getValue(), is( instanceOf( FunctionDefNode.class ) ) );
assertThat( entry.getValue().getText(), is("function( angle ) external {"
+ " java : {"
+ " class : \"java.lang.Math\","
+ " method signature : \"cos(double)\""
+ " }"
+ "}" ) );
FunctionDefNode cos = (FunctionDefNode) entry.getValue();
assertThat( cos.getFormalParameters().size(), is( 1 ) );
assertThat( cos.getFormalParameters().get( 0 ).getText(), is( "angle" ) );
assertThat( cos.isExternal(), is( true ) );
assertThat( cos.getBody(), is( instanceOf( ContextNode.class ) ) );
ContextNode body = (ContextNode) cos.getBody();
assertThat( body.getEntries().size(), is( 1 ) );
ContextEntryNode java = body.getEntries().get( 0 );
assertThat( java.getName().getText(), is( "java" ) );
assertThat( java.getValue(), is( instanceOf( ContextNode.class ) ) );
ContextNode def = (ContextNode) java.getValue();
assertThat( def.getEntries().size(), is( 2 ) );
assertThat( def.getEntries().get( 0 ).getName().getText(), is( "class" ) );
assertThat( def.getEntries().get( 0 ).getValue(), is( instanceOf( StringNode.class ) ) );
assertThat( def.getEntries().get( 0 ).getValue().getText(), is( "\"java.lang.Math\"" ) );
assertThat( def.getEntries().get( 1 ).getName().getText(), is( "method signature" ) );
assertThat( def.getEntries().get( 1 ).getValue(), is( instanceOf( StringNode.class ) ) );
assertThat( def.getEntries().get( 1 ).getValue().getText(), is( "\"cos(double)\"" ) );
}
@Test
public void testForExpression() {
String inputExpression = "for item in order.items return item.price * item.quantity";
BaseNode forbase = parse( inputExpression );
assertThat( forbase, is( instanceOf( ForExpressionNode.class ) ) );
assertThat( forbase.getText(), is( inputExpression ) );
assertThat( forbase.getResultType(), is( BuiltInType.LIST ) );
ForExpressionNode forExpr = (ForExpressionNode) forbase;
assertThat( forExpr.getIterationContexts().size(), is( 1 ) );
assertThat( forExpr.getExpression(), is( instanceOf( InfixOpNode.class ) ) );
assertThat( forExpr.getExpression().getText(), is( "item.price * item.quantity" ) );
IterationContextNode ic = forExpr.getIterationContexts().get( 0 );
assertThat( ic.getName().getText(), is("item") );
assertThat( ic.getExpression(), is( instanceOf( QualifiedNameNode.class ) ) );
assertThat( ic.getExpression().getText(), is("order.items") );
}
@Test
public void testIfExpression() {
String inputExpression = "if applicant.age < 18 then \"declined\" else \"accepted\"";
BaseNode ifBase = parse( inputExpression );
assertThat( ifBase, is( instanceOf( IfExpressionNode.class ) ) );
assertThat( ifBase.getText(), is( inputExpression ) );
assertThat( ifBase.getResultType(), is( BuiltInType.STRING ) );
IfExpressionNode ifExpr = (IfExpressionNode) ifBase;
assertThat( ifExpr.getCondition().getText(), is( "applicant.age < 18" ) );
assertThat( ifExpr.getThenExpression().getText(), is( "\"declined\"" ) );
assertThat( ifExpr.getElseExpression().getText(), is( "\"accepted\"" ) );
}
@Test
public void testQuantifiedExpressionSome() {
String inputExpression = "some item in order.items satisfies item.price > 100";
BaseNode someBase = parse( inputExpression );
assertThat( someBase, is( instanceOf( QuantifiedExpressionNode.class ) ) );
assertThat( someBase.getText(), is( inputExpression ) );
assertThat( someBase.getResultType(), is( BuiltInType.BOOLEAN ) );
QuantifiedExpressionNode someExpr = (QuantifiedExpressionNode) someBase;
assertThat( someExpr.getQuantifier(), is( QuantifiedExpressionNode.Quantifier.SOME ) );
assertThat( someExpr.getIterationContexts().size(), is( 1 ) );
assertThat( someExpr.getIterationContexts().get( 0 ).getText(), is( "item in order.items" ) );
assertThat( someExpr.getExpression().getText(), is( "item.price > 100" ) );
}
@Test
public void testQuantifiedExpressionEvery() {
String inputExpression = "every item in order.items satisfies item.price > 100";
BaseNode everyBase = parse( inputExpression );
assertThat( everyBase, is( instanceOf( QuantifiedExpressionNode.class ) ) );
assertThat( everyBase.getText(), is( inputExpression ) );
assertThat( everyBase.getResultType(), is( BuiltInType.BOOLEAN ) );
QuantifiedExpressionNode everyExpr = (QuantifiedExpressionNode) everyBase;
assertThat( everyExpr.getQuantifier(), is( QuantifiedExpressionNode.Quantifier.EVERY ) );
assertThat( everyExpr.getIterationContexts().size(), is( 1 ) );
assertThat( everyExpr.getIterationContexts().get( 0 ).getText(), is( "item in order.items" ) );
assertThat( everyExpr.getExpression().getText(), is( "item.price > 100" ) );
}
@Test
public void testInstanceOfExpression() {
String inputExpression = "\"foo\" instance of string";
BaseNode instanceOfBase = parse( inputExpression );
assertThat( instanceOfBase, is( instanceOf( InstanceOfNode.class ) ) );
assertThat( instanceOfBase.getText(), is( inputExpression ) );
assertThat( instanceOfBase.getResultType(), is( BuiltInType.BOOLEAN ) );
InstanceOfNode ioExpr = (InstanceOfNode) instanceOfBase;
assertThat( ioExpr.getExpression(), is( instanceOf( StringNode.class ) ) );
assertThat( ioExpr.getExpression().getText(), is( "\"foo\"" ) );
assertThat( ioExpr.getType(), is( instanceOf( TypeNode.class ) ) );
assertThat( ioExpr.getType().getText(), is( "string" ) );
}
@Test
public void testInstanceOfExpressionAnd() {
String inputExpression = "\"foo\" instance of string and 10 instance of number";
BaseNode andExpr = parse( inputExpression );
assertThat( andExpr, is( instanceOf( InfixOpNode.class ) ) );
assertThat( andExpr.getText(), is( inputExpression ) );
assertThat( andExpr.getResultType(), is( BuiltInType.BOOLEAN ) );
InfixOpNode and = (InfixOpNode) andExpr;
assertThat( and.getOperator(), is( InfixOpNode.InfixOperator.AND ) );
assertThat( and.getLeft(), is( instanceOf( InstanceOfNode.class ) ) );
assertThat( and.getRight(), is( instanceOf( InstanceOfNode.class ) ) );
assertThat( and.getLeft().getText(), is( "\"foo\" instance of string" ) );
assertThat( and.getRight().getText(), is( "10 instance of number" ) );
assertThat( and.getLeft().getResultType(), is( BuiltInType.BOOLEAN ) );
assertThat( and.getRight().getResultType(), is( BuiltInType.BOOLEAN ) );
InstanceOfNode ioExpr = (InstanceOfNode) and.getLeft();
assertThat( ioExpr.getExpression(), is( instanceOf( StringNode.class ) ) );
assertThat( ioExpr.getExpression().getText(), is( "\"foo\"" ) );
assertThat( ioExpr.getType(), is( instanceOf( TypeNode.class ) ) );
assertThat( ioExpr.getType().getText(), is( "string" ) );
ioExpr = (InstanceOfNode) and.getRight();
assertThat( ioExpr.getExpression(), is( instanceOf( NumberNode.class ) ) );
assertThat( ioExpr.getExpression().getText(), is( "10" ) );
assertThat( ioExpr.getType(), is( instanceOf( TypeNode.class ) ) );
assertThat( ioExpr.getType().getText(), is( "number" ) );
}
@Test
public void testInstanceOfExpressionFunction() {
String inputExpression = "duration instance of function";
BaseNode instanceOfBase = parse( inputExpression );
assertThat( instanceOfBase, is( instanceOf( InstanceOfNode.class ) ) );
assertThat( instanceOfBase.getText(), is( inputExpression ) );
assertThat( instanceOfBase.getResultType(), is( BuiltInType.BOOLEAN ) );
InstanceOfNode ioExpr = (InstanceOfNode) instanceOfBase;
assertThat( ioExpr.getExpression(), is( instanceOf( NameRefNode.class ) ) );
assertThat( ioExpr.getExpression().getText(), is( "duration" ) );
assertThat( ioExpr.getType(), is( instanceOf( TypeNode.class ) ) );
assertThat( ioExpr.getType().getText(), is( "function" ) );
}
@Test
public void testPathExpression() {
String inputExpression = "[ 10, 15 ].size";
BaseNode pathBase = parse( inputExpression );
assertThat( pathBase, is( instanceOf( PathExpressionNode.class ) ) );
assertThat( pathBase.getText(), is( inputExpression ) );
PathExpressionNode pathExpr = (PathExpressionNode) pathBase;
assertThat( pathExpr.getExpression(), is( instanceOf( ListNode.class ) ) );
assertThat( pathExpr.getExpression().getText(), is( "10, 15" ) );
assertThat( pathExpr.getName(), is( instanceOf( NameRefNode.class ) ) );
assertThat( pathExpr.getName().getText(), is( "size" ) );
}
@Test
public void testFilterExpression() {
String inputExpression = "[ {x:1, y:2}, {x:2, y:3} ][ x=1 ]";
BaseNode filterBase = parse( inputExpression );
assertThat( filterBase, is( instanceOf( FilterExpressionNode.class ) ) );
assertThat( filterBase.getText(), is( inputExpression ) );
FilterExpressionNode filter = (FilterExpressionNode) filterBase;
assertThat( filter.getExpression(), is( instanceOf( ListNode.class ) ) );
assertThat( filter.getExpression().getText(), is( "{x:1, y:2}, {x:2, y:3}" ) );
assertThat( filter.getFilter(), is( instanceOf( InfixOpNode.class ) ) );
assertThat( filter.getFilter().getText(), is( "x=1" ) );
}
@Test
public void testFunctionInvocationNamedParams() {
String inputExpression = "my.test.Function( named parameter 1 : x+10, named parameter 2 : \"foo\" )";
BaseNode functionBase = parse( inputExpression );
assertThat( functionBase, is( instanceOf( FunctionInvocationNode.class ) ) );
assertThat( functionBase.getText(), is( inputExpression ) );
FunctionInvocationNode function = (FunctionInvocationNode) functionBase;
assertThat( function.getName(), is( instanceOf( QualifiedNameNode.class ) ) );
assertThat( function.getName().getText(), is( "my.test.Function" ) );
assertThat( function.getParams(), is( instanceOf( ListNode.class ) ) );
assertThat( function.getParams().getElements().size(), is( 2 ) );
assertThat( function.getParams().getElements().get( 0 ), is( instanceOf( NamedParameterNode.class ) ) );
assertThat( function.getParams().getElements().get( 1 ), is( instanceOf( NamedParameterNode.class ) ) );
NamedParameterNode named = (NamedParameterNode) function.getParams().getElements().get( 0 );
assertThat( named.getText(), is( "named parameter 1 : x+10" ) );
assertThat( named.getName().getText(), is( "named parameter 1" ) );
assertThat( named.getExpression(), is( instanceOf( InfixOpNode.class ) ) );
assertThat( named.getExpression().getText(), is( "x+10" ) );
named = (NamedParameterNode) function.getParams().getElements().get( 1 );
assertThat( named.getText(), is( "named parameter 2 : \"foo\"" ) );
assertThat( named.getName().getText(), is( "named parameter 2" ) );
assertThat( named.getExpression(), is( instanceOf( StringNode.class ) ) );
assertThat( named.getExpression().getText(), is( "\"foo\"" ) );
}
@Test
public void testFunctionInvocationPositionalParams() {
String inputExpression = "my.test.Function( x+10, \"foo\" )";
BaseNode functionBase = parse( inputExpression );
assertThat( functionBase, is( instanceOf( FunctionInvocationNode.class ) ) );
assertThat( functionBase.getText(), is( inputExpression ) );
FunctionInvocationNode function = (FunctionInvocationNode) functionBase;
assertThat( function.getName(), is( instanceOf( QualifiedNameNode.class ) ) );
assertThat( function.getName().getText(), is( "my.test.Function" ) );
assertThat( function.getParams(), is( instanceOf( ListNode.class ) ) );
assertThat( function.getParams().getElements().size(), is( 2 ) );
assertThat( function.getParams().getElements().get( 0 ), is( instanceOf( InfixOpNode.class ) ) );
assertThat( function.getParams().getElements().get( 1 ), is( instanceOf( StringNode.class ) ) );
}
@Test
public void testFunctionInvocationWithKeyword() {
String inputExpression = "date and time( \"2016-07-29T19:47:53\" )";
BaseNode functionBase = parse( inputExpression );
assertThat( functionBase, is( instanceOf( FunctionInvocationNode.class ) ) );
assertThat( functionBase.getText(), is( inputExpression ) );
FunctionInvocationNode function = (FunctionInvocationNode) functionBase;
assertThat( function.getName(), is( instanceOf( NameRefNode.class ) ) );
assertThat( function.getName().getText(), is( "date and time" ) );
assertThat( function.getParams(), is( instanceOf( ListNode.class ) ) );
assertThat( function.getParams().getElements().size(), is( 1 ) );
assertThat( function.getParams().getElements().get( 0 ), is( instanceOf( StringNode.class ) ) );
}
@Test
public void testFunctionInvocationWithExpressionParameters() {
String inputExpression = "date and time( date(\"2016-07-29\"), time(\"19:47:53\") )";
BaseNode functionBase = parse( inputExpression );
assertThat( functionBase, is( instanceOf( FunctionInvocationNode.class ) ) );
assertThat( functionBase.getText(), is( inputExpression ) );
FunctionInvocationNode function = (FunctionInvocationNode) functionBase;
assertThat( function.getName(), is( instanceOf( NameRefNode.class ) ) );
assertThat( function.getName().getText(), is( "date and time" ) );
assertThat( function.getParams(), is( instanceOf( ListNode.class ) ) );
assertThat( function.getParams().getElements().size(), is( 2 ) );
assertThat( function.getParams().getElements().get( 0 ), is( instanceOf( FunctionInvocationNode.class ) ) );
assertThat( function.getParams().getElements().get( 1 ), is( instanceOf( FunctionInvocationNode.class ) ) );
}
@Test
public void testFunctionInvocationEmptyParams() {
String inputExpression = "my.test.Function()";
BaseNode functionBase = parse( inputExpression );
assertThat( functionBase, is( instanceOf( FunctionInvocationNode.class ) ) );
assertThat( functionBase.getText(), is( inputExpression ) );
FunctionInvocationNode function = (FunctionInvocationNode) functionBase;
assertThat( function.getName(), is( instanceOf( QualifiedNameNode.class ) ) );
assertThat( function.getName().getText(), is( "my.test.Function" ) );
assertThat( function.getParams(), is( instanceOf( ListNode.class ) ) );
assertThat( function.getParams().getElements(), is( empty() ) );
}
@Test
public void testFunctionDecisionTableInvocation() {
String inputExpression = "decision table( "
+ " outputs: \"Applicant Risk Rating\","
+ " input expression list: [\"Applicant Age\", \"Medical History\"],"
+ " rule list: ["
+ " [ >60 , \"good\" , \"Medium\" ],"
+ " [ >60 , \"bad\" , \"High\" ],"
+ " [ [25..60] , - , \"Medium\" ],"
+ " [ <25 , \"good\" , \"Low\" ],"
+ " [ <25 , \"bad\" , \"Medium\" ] ],"
+ " hit policy: \"Unique\" )";
// need to call parse passing in the input variables
BaseNode functionBase = parse( inputExpression );
assertThat( functionBase, is( instanceOf( FunctionInvocationNode.class ) ) );
assertThat( functionBase.getText(), is( inputExpression ) );
FunctionInvocationNode function = (FunctionInvocationNode) functionBase;
assertThat( function.getName(), is( instanceOf( NameRefNode.class ) ) );
assertThat( function.getName().getText(), is( "decision table" ) );
assertThat( function.getParams(), is( instanceOf( ListNode.class ) ) );
assertThat( function.getParams().getElements().size(), is( 4 ) );
assertThat( function.getParams().getElements().get( 0 ), is( instanceOf( NamedParameterNode.class ) ) );
assertThat( function.getParams().getElements().get( 1 ), is( instanceOf( NamedParameterNode.class ) ) );
assertThat( function.getParams().getElements().get( 2 ), is( instanceOf( NamedParameterNode.class ) ) );
assertThat( function.getParams().getElements().get( 3 ), is( instanceOf( NamedParameterNode.class ) ) );
NamedParameterNode named = (NamedParameterNode) function.getParams().getElements().get( 0 );
assertThat( named.getText(), is( "outputs: \"Applicant Risk Rating\"" ) );
assertThat( named.getName().getText(), is( "outputs" ) );
assertThat( named.getExpression(), is( instanceOf( StringNode.class ) ) );
assertThat( named.getExpression().getText(), is( "\"Applicant Risk Rating\"" ) );
named = (NamedParameterNode) function.getParams().getElements().get( 1 );
assertThat( named.getName().getText(), is( "input expression list" ) );
assertThat( named.getExpression(), is( instanceOf( ListNode.class ) ) );
ListNode list = (ListNode) named.getExpression();
assertThat( list.getElements().size(), is( 2 ) );
assertThat( list.getElements().get( 0 ), is( instanceOf( StringNode.class ) ) );
assertThat( list.getElements().get( 0 ).getText(), is( "\"Applicant Age\"" ) );
assertThat( list.getElements().get( 1 ), is( instanceOf( StringNode.class ) ) );
assertThat( list.getElements().get( 1 ).getText(), is( "\"Medical History\"" ) );
named = (NamedParameterNode) function.getParams().getElements().get( 2 );
assertThat( named.getName().getText(), is( "rule list" ) );
assertThat( named.getExpression(), is( instanceOf( ListNode.class ) ) );
list = (ListNode) named.getExpression();
assertThat( list.getElements().size(), is( 5 ) );
assertThat( list.getElements().get( 0 ), is( instanceOf( ListNode.class ) ) );
ListNode rule = (ListNode) list.getElements().get( 0 );
assertThat( rule.getElements().size(), is( 3 ) );
assertThat( rule.getElements().get( 0 ), is( instanceOf( UnaryTestNode.class ) ) );
assertThat( rule.getElements().get( 0 ).getText(), is( ">60" ) );
assertThat( rule.getElements().get( 1 ), is( instanceOf( StringNode.class ) ) );
assertThat( rule.getElements().get( 1 ).getText(), is( "\"good\"" ) );
assertThat( rule.getElements().get( 2 ), is( instanceOf( StringNode.class ) ) );
assertThat( rule.getElements().get( 2 ).getText(), is( "\"Medium\"" ) );
named = (NamedParameterNode) function.getParams().getElements().get( 3 );
assertThat( named.getName().getText(), is( "hit policy" ) );
assertThat( named.getExpression(), is( instanceOf( StringNode.class ) ) );
assertThat( named.getExpression().getText(), is( "\"Unique\"" ) );
}
@Test
public void testContextPathExpression() {
String inputExpression = "{ x : \"foo\" }.x";
BaseNode pathBase = parse( inputExpression );
assertThat( pathBase, is( instanceOf( PathExpressionNode.class ) ) );
assertThat( pathBase.getText(), is( inputExpression ) );
assertThat( pathBase.getResultType(), is( BuiltInType.STRING ) );
PathExpressionNode pathExpr = (PathExpressionNode) pathBase;
assertThat( pathExpr.getExpression(), is( instanceOf( ContextNode.class ) ) );
assertThat( pathExpr.getExpression().getText(), is( "{ x : \"foo\" }" ) );
assertThat( pathExpr.getName(), is( instanceOf( NameRefNode.class ) ) );
assertThat( pathExpr.getName().getText(), is( "x" ) );
}
@Test
public void testContextPathExpression2() {
String inputExpression = "{ x : { y : \"foo\" } }.x.y";
BaseNode pathBase = parse( inputExpression );
assertThat( pathBase, is( instanceOf( PathExpressionNode.class ) ) );
assertThat( pathBase.getText(), is( inputExpression ) );
assertThat( pathBase.getResultType(), is( BuiltInType.STRING ) );
PathExpressionNode pathExpr = (PathExpressionNode) pathBase;
assertThat( pathExpr.getExpression(), is( instanceOf( ContextNode.class ) ) );
assertThat( pathExpr.getExpression().getText(), is( "{ x : { y : \"foo\" } }" ) );
assertThat( pathExpr.getName(), is( instanceOf( QualifiedNameNode.class ) ) );
assertThat( pathExpr.getName().getText(), is( "x.y" ) );
}
@Test
public void testContextPathExpression3() {
String inputExpression = "{ first name : \"bob\" }.first name";
BaseNode pathBase = parse( inputExpression );
assertThat( pathBase, is( instanceOf( PathExpressionNode.class ) ) );
assertThat( pathBase.getText(), is( inputExpression ) );
assertThat( pathBase.getResultType(), is( BuiltInType.STRING ) );
PathExpressionNode pathExpr = (PathExpressionNode) pathBase;
assertThat( pathExpr.getExpression(), is( instanceOf( ContextNode.class ) ) );
assertThat( pathExpr.getExpression().getText(), is( "{ first name : \"bob\" }" ) );
assertThat( pathExpr.getName(), is( instanceOf( NameRefNode.class ) ) );
assertThat( pathExpr.getName().getText(), is( "first name" ) );
}
@Test
public void testVariableName() {
String var = "valid variable name";
assertThat( FEELParser.isVariableNameValid( var ), is( true ) );
}
@Test
public void testVariableNameWithValidCharacters() {
String var = "?_873./-'+*valid";
assertThat( FEELParser.isVariableNameValid( var ), is( true ) );
}
@Test
public void testVariableNameWithInvalidCharacterPercent() {
String var = "?_873./-'%+*valid";
assertThat( FEELParser.isVariableNameValid( var ), is( false ) );
assertThat( FEELParser.checkVariableName( var ).get( 0 ).getMessage(), is( Msg.createMessage(Msg.INVALID_VARIABLE_NAME, "character", "%") ) );
}
@Test
public void testVariableNameInvalidStartCharacter() {
String var = "5variable can't start with a number";
assertThat( FEELParser.isVariableNameValid( var ), is( false ) );
assertThat( FEELParser.checkVariableName( var ).get( 0 ).getMessage(), is( Msg.createMessage(Msg.INVALID_VARIABLE_NAME_START, "character", "5") ) );
}
@Test
public void testVariableNameCantContainKeywordIn() {
String var = "variable can't contain 'in' keyword";
assertThat( FEELParser.isVariableNameValid( var ), is( false ) );
assertThat( FEELParser.checkVariableName( var ).get( 0 ).getMessage(), is( Msg.createMessage(Msg.INVALID_VARIABLE_NAME, "keyword", "in") ) );
}
@Test
public void testVariableNameCantStartWithKeyword() {
String var = "for keyword is an invalid start for a variable name";
assertThat( FEELParser.isVariableNameValid( var ), is( false ) );
assertThat( FEELParser.checkVariableName( var ).get( 0 ).getMessage(), is( Msg.createMessage(Msg.INVALID_VARIABLE_NAME_START, "keyword", "for") ) );
}
private void assertLocation(String inputExpression, BaseNode number) {
assertThat( number.getText(), is( inputExpression ) );
assertThat( number.getStartChar(), is( 0 ) );
assertThat( number.getStartLine(), is( 1 ) );
assertThat( number.getStartColumn(), is( 0 ) );
assertThat( number.getEndChar(), is( inputExpression.length() - 1 ) );
assertThat( number.getEndLine(), is( 1 ) );
assertThat( number.getEndColumn(), is( inputExpression.length() ) );
}
private BaseNode parse(String input) {
return parse( input, Collections.emptyMap() );
}
private BaseNode parse(String input, Map<String, Type> inputTypes) {
FEEL_1_1Parser parser = FEELParser.parse(null, input, inputTypes, Collections.emptyMap(), Collections.emptyList(), Collections.emptyList());
ParseTree tree = parser.expression();
ASTBuilderVisitor v = new ASTBuilderVisitor(inputTypes);
BaseNode expr = v.visit( tree );
return expr;
}
}
|
mostafa-arshadi/aiotdlib
|
aiotdlib/api/types/message_position.py
|
# =============================================================================== #
# #
# This file has been generated automatically!! Do not change this manually! #
# #
# =============================================================================== #
from __future__ import annotations
from pydantic import Field
from ..base_object import BaseObject
class MessagePosition(BaseObject):
"""
Contains information about a message in a specific position
:param position: 0-based message position in the full list of suitable messages
:type position: :class:`int`
:param message_id: Message identifier
:type message_id: :class:`int`
:param date: Point in time (Unix timestamp) when the message was sent
:type date: :class:`int`
"""
ID: str = Field("messagePosition", alias="@type")
position: int
message_id: int
date: int
@staticmethod
def read(q: dict) -> MessagePosition:
return MessagePosition.construct(**q)
|
dangkiet000/LoNhiet
|
MyLib/inc/Fls.h
|
<reponame>dangkiet000/LoNhiet
/*******************************************************************************
* @file DataFlash.h
* @version V1.00
* $Revision: 1 $
* $Date: 31/12/2016 11:47p $
* @brief Data Flash driver source file
*
* @note
* Copyright (C) 2016 DangKiet Technology Corp. All rights reserved.
******************************************************************************/
#ifndef __FLS_H__
#define __FLS_H__
/*******************************************************************************
** Include **
*******************************************************************************/
#include "NUC200Series.h"
#include "Fls_Cfg.h"
#ifdef __cplusplus
extern "C"
{
#endif
/*******************************************************************************
** Type definitions **
******************************************************************************/
extern const Fls_DataConfigType Fls_GaaConfig[];
/*----------------------------------------------------------------------------*/
/* ISPCON constant definitions */
/*----------------------------------------------------------------------------*/
/*!< ISPCON setting to select to boot from LDROM */
#define FMC_ISPCON_BS_LDROM 0x2
/*!< ISPCON setting to select to boot from APROM */
#define FMC_ISPCON_BS_APROM 0x0
/*----------------------------------------------------------------------------*/
/* ISPCMD constant definitions */
/*----------------------------------------------------------------------------*/
#define FMC_ISPCMD_READ 0x00 /*!< ISP Command: Read Flash */
#define FMC_ISPCMD_PROGRAM 0x21 /*!< ISP Command: Program Flash */
#define FMC_ISPCMD_PAGE_ERASE 0x22 /*!< ISP Command: Page Erase Flash */
#define FMC_ISPCMD_VECMAP 0x2e /*!< ISP Command: Set VECMAP */
#define FMC_ISPCMD_READ_UID 0x04 /*!< ISP Command: Read Unique ID */
#define FMC_ISPCMD_READ_CID 0x0B /*!< ISP Command: Read Company ID */
#define FMC_ISPCMD_READ_DID 0x0C /*!< ISP Command: Read Device ID */
/*@}*/ /* end of group FMC_EXPORTED_CONSTANTS */
/** @addtogroup FMC_EXPORTED_FUNCTIONS FMC Exported Functions
@{
*/
/*----------------------------------------------------------------------------*/
/* FMC Macro Definitions */
/*----------------------------------------------------------------------------*/
/**
* @brief Enable ISP Function
*
* @param None
*
* @return None
*
* @details This function will set ISPEN bit of ISPCON control register to
* enable ISP function.
*
*/
#define FMC_ENABLE_ISP() (FMC->ISPCON |= FMC_ISPCON_ISPEN_Msk)
/**
* @brief Disable ISP Function
*
* @param None
*
* @return None
*
* @details This function will clear ISPEN bit of ISPCON control register to
* disable ISP function.
*
*/
#define FMC_DISABLE_ISP() (FMC->ISPCON &= ~FMC_ISPCON_ISPEN_Msk)
/**
* @brief Get ISP fail flag
*
* @param None
*
* @retval 0 Previous ISP command execution result is successful
* @retval 1 Previous ISP command execution result is fail
*
* @details ISPFF flag of ISPCON is used to indicate ISP command success or
* fail.
* This function will return the ISPFF flag to identify ISP command
* OK or fail.
*
*/
#define FMC_GET_FAIL_FLAG() ((FMC->ISPCON & FMC_ISPCON_ISPFF_Msk) ? 1 : 0)
#define FLS_GET_PAGE_ADDR(PageNumber) (DATA_FLS_START_ADDR + \
(PageNumber*FMC_FLASH_PAGE_SIZE))
/*******************************************************************************
** Internal Functions **
*******************************************************************************/
extern void FMC_Open(void);
extern void FMC_Close(void);
Std_ReturnType FMC_Erase(uint32_t u32addr);
uint32_t FMC_Read(uint32_t u32addr);
void FMC_Write(uint32_t u32addr, uint32_t u32data);
/*******************************************************************************
** API Functions **
*******************************************************************************/
void Fls_Init(const Fls_DataConfigType *Configset);
void Fls_DeInit(void);
extern Std_ReturnType Fls_Write(Fls_DataIdType FlsId,
const Fls_DataType *SourceAddressPtr);
extern Std_ReturnType Fls_Read(Fls_DataIdType FlsId, \
Fls_DataType* TargetAddressPtr);
#ifdef __cplusplus
}
#endif
#endif /* __FLS_H__ */
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.