code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30
values | license stringclasses 15
values | size int64 3 1.01M |
|---|---|---|---|---|---|
#include "../../../../../../src/reports/processor/style/color.h"
| arnost00/quickbox | libqf/libqfqmlwidgets/include/qf/qmlwidgets/reports/processor/style/color.h | C | gpl-2.0 | 65 |
@CHARSET "UTF-8";
div.ose-action-edit {
background-image: url("../../../../templates/bluestork/images/menu/icon-16-edit.png");
display: inline-block;
height: 16px;
width: 16px;
float:left;
margin-right:5px
}
div.ose-action-validate {
background-image: url("../../../../templates/bluestork/images/menu/icon-16-links.png");
display: inline-block;
height: 16px;
width: 16px;
float:left;
margin-right:5px
}
div.ose-action-edit-date {
background-image: url("../../../../templates/bluestork/images/menu/icon-16-calendar.png");
display: inline-block;
height: 16px;
width: 16px;
float:left;
margin-right:5px
}
div.ose-action-delete {
background-image: url("../../../../templates/bluestork/images/menu/icon-16-deny.png");
display: inline-block;
height: 16px;
width: 16px;
float:left;
margin-right:5px
}
div.btntips {
height: 16px;
float:left;
margin-right:10px
} | Jasonudoo/platform | administrator/components/com_osemsc/assets/css/extra.css | CSS | gpl-2.0 | 954 |
/*
* linux/fs/super.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* super.c contains code to handle: - mount structures
* - super-block tables
* - filesystem drivers list
* - mount system call
* - umount system call
* - ustat system call
*
* GK 2/5/95 - Changed to support mounting the root fs via NFS
*
* Added kerneld support: Jacques Gelinas and Bjorn Ekwall
* Added change_root: Werner Almesberger & Hans Lermen, Feb '96
* Added options to /proc/mounts:
* Torbjörn Lindh (torbjorn.lindh@gopta.se), April 14, 1996.
* Added devfs support: Richard Gooch <rgooch@atnf.csiro.au>, 13-JAN-1998
* Heavily rewritten for 'one fs - one tree' dcache architecture. AV, Mar 2000
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/acct.h>
#include <linux/blkdev.h>
#include <linux/mount.h>
#include <linux/security.h>
#include <linux/writeback.h> /* for the emergency remount stuff */
#include <linux/idr.h>
#include <linux/mutex.h>
#include <linux/backing-dev.h>
#include <linux/rculist_bl.h>
#include <linux/cleancache.h>
#include <linux/lockdep.h>
#include "internal.h"
LIST_HEAD(super_blocks);
DEFINE_SPINLOCK(sb_lock);
static struct lock_class_key sb_writers_key[SB_FREEZE_LEVELS-1];
static int init_sb_writers(struct super_block *s, int level, char *lockname)
{
struct sb_writers_level *sl = &s->s_writers[level-1];
int err;
err = percpu_counter_init(&sl->counter, 0);
if (err < 0)
return err;
init_waitqueue_head(&sl->wait);
lockdep_init_map(&sl->lock_map, lockname, &sb_writers_key[level-1], 0);
return 0;
}
static void destroy_sb_writers(struct super_block *s, int level)
{
percpu_counter_destroy(&s->s_writers[level-1].counter);
}
/**
* alloc_super - create new superblock
* @type: filesystem type superblock should belong to
*
* Allocates and initializes a new &struct super_block. alloc_super()
* returns a pointer new superblock or %NULL if allocation had failed.
*/
static struct super_block *alloc_super(struct file_system_type *type)
{
struct super_block *s = kzalloc(sizeof(struct super_block), GFP_USER);
static const struct super_operations default_op;
if (s) {
if (security_sb_alloc(s)) {
/*
* We cannot call security_sb_free() without
* security_sb_alloc() succeeding. So bail out manually
*/
kfree(s);
s = NULL;
goto out;
}
#ifdef CONFIG_SMP
s->s_files = alloc_percpu(struct list_head);
if (!s->s_files)
goto err_out;
else {
int i;
for_each_possible_cpu(i)
INIT_LIST_HEAD(per_cpu_ptr(s->s_files, i));
}
#else
INIT_LIST_HEAD(&s->s_files);
#endif
if (init_sb_writers(s, SB_FREEZE_WRITE, "sb_writers_write"))
goto err_out;
if (init_sb_writers(s, SB_FREEZE_TRANS, "sb_writers_trans"))
goto err_out;
s->s_bdi = &default_backing_dev_info;
INIT_LIST_HEAD(&s->s_instances);
INIT_HLIST_BL_HEAD(&s->s_anon);
INIT_LIST_HEAD(&s->s_inodes);
INIT_LIST_HEAD(&s->s_dentry_lru);
init_rwsem(&s->s_umount);
mutex_init(&s->s_lock);
lockdep_set_class(&s->s_umount, &type->s_umount_key);
/*
* The locking rules for s_lock are up to the
* filesystem. For example ext3fs has different
* lock ordering than usbfs:
*/
lockdep_set_class(&s->s_lock, &type->s_lock_key);
/*
* sget() can have s_umount recursion.
*
* When it cannot find a suitable sb, it allocates a new
* one (this one), and tries again to find a suitable old
* one.
*
* In case that succeeds, it will acquire the s_umount
* lock of the old one. Since these are clearly distrinct
* locks, and this object isn't exposed yet, there's no
* risk of deadlocks.
*
* Annotate this by putting this lock in a different
* subclass.
*/
down_write_nested(&s->s_umount, SINGLE_DEPTH_NESTING);
s->s_count = 1;
atomic_set(&s->s_active, 1);
mutex_init(&s->s_vfs_rename_mutex);
lockdep_set_class(&s->s_vfs_rename_mutex, &type->s_vfs_rename_key);
mutex_init(&s->s_dquot.dqio_mutex);
mutex_init(&s->s_dquot.dqonoff_mutex);
init_rwsem(&s->s_dquot.dqptr_sem);
init_waitqueue_head(&s->s_wait_unfrozen);
s->s_maxbytes = MAX_NON_LFS;
s->s_op = &default_op;
s->s_time_gran = 1000000000;
s->cleancache_poolid = -1;
}
out:
return s;
err_out:
security_sb_free(s);
#ifdef CONFIG_SMP
if (s->s_files)
free_percpu(s->s_files);
#endif
destroy_sb_writers(s, SB_FREEZE_WRITE);
destroy_sb_writers(s, SB_FREEZE_TRANS);
kfree(s);
s = NULL;
goto out;
}
/**
* destroy_super - frees a superblock
* @s: superblock to free
*
* Frees a superblock.
*/
static inline void destroy_super(struct super_block *s)
{
#ifdef CONFIG_SMP
free_percpu(s->s_files);
#endif
security_sb_free(s);
kfree(s->s_subtype);
kfree(s->s_options);
kfree(s);
}
/* Superblock refcounting */
/*
* Drop a superblock's refcount. The caller must hold sb_lock.
*/
void __put_super(struct super_block *sb)
{
if (!--sb->s_count) {
list_del_init(&sb->s_list);
destroy_super(sb);
}
}
/**
* put_super - drop a temporary reference to superblock
* @sb: superblock in question
*
* Drops a temporary reference, frees superblock if there's no
* references left.
*/
void put_super(struct super_block *sb)
{
spin_lock(&sb_lock);
__put_super(sb);
spin_unlock(&sb_lock);
}
/**
* deactivate_locked_super - drop an active reference to superblock
* @s: superblock to deactivate
*
* Drops an active reference to superblock, converting it into a temprory
* one if there is no other active references left. In that case we
* tell fs driver to shut it down and drop the temporary reference we
* had just acquired.
*
* Caller holds exclusive lock on superblock; that lock is released.
*/
void deactivate_locked_super(struct super_block *s)
{
struct file_system_type *fs = s->s_type;
if (atomic_dec_and_test(&s->s_active)) {
cleancache_flush_fs(s);
fs->kill_sb(s);
/*
* We need to call rcu_barrier so all the delayed rcu free
* inodes are flushed before we release the fs module.
*/
rcu_barrier();
put_filesystem(fs);
put_super(s);
} else {
up_write(&s->s_umount);
}
}
EXPORT_SYMBOL(deactivate_locked_super);
/**
* deactivate_super - drop an active reference to superblock
* @s: superblock to deactivate
*
* Variant of deactivate_locked_super(), except that superblock is *not*
* locked by caller. If we are going to drop the final active reference,
* lock will be acquired prior to that.
*/
void deactivate_super(struct super_block *s)
{
if (!atomic_add_unless(&s->s_active, -1, 1)) {
down_write(&s->s_umount);
deactivate_locked_super(s);
}
}
EXPORT_SYMBOL(deactivate_super);
/**
* grab_super - acquire an active reference
* @s: reference we are trying to make active
*
* Tries to acquire an active reference. grab_super() is used when we
* had just found a superblock in super_blocks or fs_type->fs_supers
* and want to turn it into a full-blown active reference. grab_super()
* is called with sb_lock held and drops it. Returns 1 in case of
* success, 0 if we had failed (superblock contents was already dead or
* dying when grab_super() had been called).
*/
static int grab_super(struct super_block *s) __releases(sb_lock)
{
if (atomic_inc_not_zero(&s->s_active)) {
spin_unlock(&sb_lock);
return 1;
}
/* it's going away */
s->s_count++;
spin_unlock(&sb_lock);
/* wait for it to die */
down_write(&s->s_umount);
up_write(&s->s_umount);
put_super(s);
return 0;
}
/*
* grab_super_passive - acquire a passive reference
* @s: reference we are trying to grab
*
* Tries to acquire a passive reference. This is used in places where we
* cannot take an active reference but we need to ensure that the
* superblock does not go away while we are working on it. It returns
* false if a reference was not gained, and returns true with the s_umount
* lock held in read mode if a reference is gained. On successful return,
* the caller must drop the s_umount lock and the passive reference when
* done.
*/
bool grab_super_passive(struct super_block *sb)
{
spin_lock(&sb_lock);
if (list_empty(&sb->s_instances)) {
spin_unlock(&sb_lock);
return false;
}
sb->s_count++;
spin_unlock(&sb_lock);
if (down_read_trylock(&sb->s_umount)) {
if (sb->s_root)
return true;
up_read(&sb->s_umount);
}
put_super(sb);
return false;
}
/*
* Superblock locking. We really ought to get rid of these two.
*/
void lock_super(struct super_block * sb)
{
mutex_lock(&sb->s_lock);
}
void unlock_super(struct super_block * sb)
{
mutex_unlock(&sb->s_lock);
}
EXPORT_SYMBOL(lock_super);
EXPORT_SYMBOL(unlock_super);
/**
* generic_shutdown_super - common helper for ->kill_sb()
* @sb: superblock to kill
*
* generic_shutdown_super() does all fs-independent work on superblock
* shutdown. Typical ->kill_sb() should pick all fs-specific objects
* that need destruction out of superblock, call generic_shutdown_super()
* and release aforementioned objects. Note: dentries and inodes _are_
* taken care of and do not need specific handling.
*
* Upon calling this function, the filesystem may no longer alter or
* rearrange the set of dentries belonging to this super_block, nor may it
* change the attachments of dentries to inodes.
*/
void generic_shutdown_super(struct super_block *sb)
{
const struct super_operations *sop = sb->s_op;
if (sb->s_root) {
shrink_dcache_for_umount(sb);
sync_filesystem(sb);
get_fs_excl();
sb->s_flags &= ~MS_ACTIVE;
fsnotify_unmount_inodes(&sb->s_inodes);
evict_inodes(sb);
if (sop->put_super)
sop->put_super(sb);
if (!list_empty(&sb->s_inodes)) {
printk("VFS: Busy inodes after unmount of %s. "
"Self-destruct in 5 seconds. Have a nice day...\n",
sb->s_id);
}
put_fs_excl();
}
spin_lock(&sb_lock);
/* should be initialized for __put_super_and_need_restart() */
list_del_init(&sb->s_instances);
spin_unlock(&sb_lock);
up_write(&sb->s_umount);
}
EXPORT_SYMBOL(generic_shutdown_super);
/**
* sget - find or create a superblock
* @type: filesystem type superblock should belong to
* @test: comparison callback
* @set: setup callback
* @data: argument to each of them
*/
struct super_block *sget(struct file_system_type *type,
int (*test)(struct super_block *,void *),
int (*set)(struct super_block *,void *),
void *data)
{
struct super_block *s = NULL;
struct super_block *old;
int err;
retry:
spin_lock(&sb_lock);
if (test) {
list_for_each_entry(old, &type->fs_supers, s_instances) {
if (!test(old, data))
continue;
if (!grab_super(old))
goto retry;
if (s) {
up_write(&s->s_umount);
destroy_super(s);
s = NULL;
}
down_write(&old->s_umount);
if (unlikely(!(old->s_flags & MS_BORN))) {
deactivate_locked_super(old);
goto retry;
}
return old;
}
}
if (!s) {
spin_unlock(&sb_lock);
s = alloc_super(type);
if (!s)
return ERR_PTR(-ENOMEM);
goto retry;
}
err = set(s, data);
if (err) {
spin_unlock(&sb_lock);
up_write(&s->s_umount);
destroy_super(s);
return ERR_PTR(err);
}
s->s_type = type;
strlcpy(s->s_id, type->name, sizeof(s->s_id));
list_add_tail(&s->s_list, &super_blocks);
list_add(&s->s_instances, &type->fs_supers);
spin_unlock(&sb_lock);
get_filesystem(type);
return s;
}
EXPORT_SYMBOL(sget);
void drop_super(struct super_block *sb)
{
up_read(&sb->s_umount);
put_super(sb);
}
EXPORT_SYMBOL(drop_super);
/**
* sync_supers - helper for periodic superblock writeback
*
* Call the write_super method if present on all dirty superblocks in
* the system. This is for the periodic writeback used by most older
* filesystems. For data integrity superblock writeback use
* sync_filesystems() instead.
*
* Note: check the dirty flag before waiting, so we don't
* hold up the sync while mounting a device. (The newly
* mounted device won't need syncing.)
*/
void sync_supers(void)
{
struct super_block *sb, *p = NULL;
spin_lock(&sb_lock);
list_for_each_entry(sb, &super_blocks, s_list) {
if (list_empty(&sb->s_instances))
continue;
if (sb->s_op->write_super && sb->s_dirt) {
sb->s_count++;
spin_unlock(&sb_lock);
down_read(&sb->s_umount);
if (sb->s_root && sb->s_dirt)
sb->s_op->write_super(sb);
up_read(&sb->s_umount);
spin_lock(&sb_lock);
if (p)
__put_super(p);
p = sb;
}
}
if (p)
__put_super(p);
spin_unlock(&sb_lock);
}
/**
* iterate_supers - call function for all active superblocks
* @f: function to call
* @arg: argument to pass to it
*
* Scans the superblock list and calls given function, passing it
* locked superblock and given argument.
*/
void iterate_supers(void (*f)(struct super_block *, void *), void *arg)
{
struct super_block *sb, *p = NULL;
spin_lock(&sb_lock);
list_for_each_entry(sb, &super_blocks, s_list) {
if (list_empty(&sb->s_instances))
continue;
sb->s_count++;
spin_unlock(&sb_lock);
down_read(&sb->s_umount);
if (sb->s_root)
f(sb, arg);
up_read(&sb->s_umount);
spin_lock(&sb_lock);
if (p)
__put_super(p);
p = sb;
}
if (p)
__put_super(p);
spin_unlock(&sb_lock);
}
/**
* get_super - get the superblock of a device
* @bdev: device to get the superblock for
*
* Scans the superblock list and finds the superblock of the file system
* mounted on the device given. %NULL is returned if no match is found.
*/
struct super_block *get_super(struct block_device *bdev)
{
struct super_block *sb;
if (!bdev)
return NULL;
spin_lock(&sb_lock);
rescan:
list_for_each_entry(sb, &super_blocks, s_list) {
if (list_empty(&sb->s_instances))
continue;
if (sb->s_bdev == bdev) {
sb->s_count++;
spin_unlock(&sb_lock);
down_read(&sb->s_umount);
/* still alive? */
if (sb->s_root)
return sb;
up_read(&sb->s_umount);
/* nope, got unmounted */
spin_lock(&sb_lock);
__put_super(sb);
goto rescan;
}
}
spin_unlock(&sb_lock);
return NULL;
}
EXPORT_SYMBOL(get_super);
/**
* get_active_super - get an active reference to the superblock of a device
* @bdev: device to get the superblock for
*
* Scans the superblock list and finds the superblock of the file system
* mounted on the device given. Returns the superblock with an active
* reference or %NULL if none was found.
*/
struct super_block *get_active_super(struct block_device *bdev)
{
struct super_block *sb;
if (!bdev)
return NULL;
restart:
spin_lock(&sb_lock);
list_for_each_entry(sb, &super_blocks, s_list) {
if (list_empty(&sb->s_instances))
continue;
if (sb->s_bdev == bdev) {
if (grab_super(sb)) /* drops sb_lock */
return sb;
else
goto restart;
}
}
spin_unlock(&sb_lock);
return NULL;
}
struct super_block *user_get_super(dev_t dev)
{
struct super_block *sb;
spin_lock(&sb_lock);
rescan:
list_for_each_entry(sb, &super_blocks, s_list) {
if (list_empty(&sb->s_instances))
continue;
if (sb->s_dev == dev) {
sb->s_count++;
spin_unlock(&sb_lock);
down_read(&sb->s_umount);
/* still alive? */
if (sb->s_root)
return sb;
up_read(&sb->s_umount);
/* nope, got unmounted */
spin_lock(&sb_lock);
__put_super(sb);
goto rescan;
}
}
spin_unlock(&sb_lock);
return NULL;
}
/**
* do_remount_sb - asks filesystem to change mount options.
* @sb: superblock in question
* @flags: numeric part of options
* @data: the rest of options
* @force: whether or not to force the change
*
* Alters the mount options of a mounted file system.
*/
int do_remount_sb(struct super_block *sb, int flags, void *data, int force)
{
int retval;
int remount_ro;
if (sb->s_frozen != SB_UNFROZEN)
return -EBUSY;
#ifdef CONFIG_BLOCK
if (!(flags & MS_RDONLY) && bdev_read_only(sb->s_bdev))
return -EACCES;
#endif
if (flags & MS_RDONLY)
acct_auto_close(sb);
shrink_dcache_sb(sb);
sync_filesystem(sb);
remount_ro = (flags & MS_RDONLY) && !(sb->s_flags & MS_RDONLY);
/* If we are remounting RDONLY and current sb is read/write,
make sure there are no rw files opened */
if (remount_ro) {
if (force)
mark_files_ro(sb);
else if (!fs_may_remount_ro(sb))
return -EBUSY;
}
if (sb->s_op->remount_fs) {
retval = sb->s_op->remount_fs(sb, &flags, data);
if (retval)
return retval;
}
sb->s_flags = (sb->s_flags & ~MS_RMT_MASK) | (flags & MS_RMT_MASK);
/*
* Some filesystems modify their metadata via some other path than the
* bdev buffer cache (eg. use a private mapping, or directories in
* pagecache, etc). Also file data modifications go via their own
* mappings. So If we try to mount readonly then copy the filesystem
* from bdev, we could get stale data, so invalidate it to give a best
* effort at coherency.
*/
if (remount_ro && sb->s_bdev)
invalidate_bdev(sb->s_bdev);
return 0;
}
static void do_emergency_remount(struct work_struct *work)
{
struct super_block *sb, *p = NULL;
spin_lock(&sb_lock);
list_for_each_entry(sb, &super_blocks, s_list) {
if (list_empty(&sb->s_instances))
continue;
sb->s_count++;
spin_unlock(&sb_lock);
down_write(&sb->s_umount);
if (sb->s_root && sb->s_bdev && !(sb->s_flags & MS_RDONLY)) {
/*
* What lock protects sb->s_flags??
*/
do_remount_sb(sb, MS_RDONLY, NULL, 1);
}
up_write(&sb->s_umount);
spin_lock(&sb_lock);
if (p)
__put_super(p);
p = sb;
}
if (p)
__put_super(p);
spin_unlock(&sb_lock);
kfree(work);
printk("Emergency Remount complete\n");
}
void emergency_remount(void)
{
struct work_struct *work;
work = kmalloc(sizeof(*work), GFP_ATOMIC);
if (work) {
INIT_WORK(work, do_emergency_remount);
schedule_work(work);
}
}
/*
* Unnamed block devices are dummy devices used by virtual
* filesystems which don't use real block-devices. -- jrs
*/
static DEFINE_IDA(unnamed_dev_ida);
static DEFINE_SPINLOCK(unnamed_dev_lock);/* protects the above */
static int unnamed_dev_start = 0; /* don't bother trying below it */
int set_anon_super(struct super_block *s, void *data)
{
int dev;
int error;
retry:
if (ida_pre_get(&unnamed_dev_ida, GFP_ATOMIC) == 0)
return -ENOMEM;
spin_lock(&unnamed_dev_lock);
error = ida_get_new_above(&unnamed_dev_ida, unnamed_dev_start, &dev);
if (!error)
unnamed_dev_start = dev + 1;
spin_unlock(&unnamed_dev_lock);
if (error == -EAGAIN)
/* We raced and lost with another CPU. */
goto retry;
else if (error)
return -EAGAIN;
if ((dev & MAX_ID_MASK) == (1 << MINORBITS)) {
spin_lock(&unnamed_dev_lock);
ida_remove(&unnamed_dev_ida, dev);
if (unnamed_dev_start > dev)
unnamed_dev_start = dev;
spin_unlock(&unnamed_dev_lock);
return -EMFILE;
}
s->s_dev = MKDEV(0, dev & MINORMASK);
s->s_bdi = &noop_backing_dev_info;
return 0;
}
EXPORT_SYMBOL(set_anon_super);
void kill_anon_super(struct super_block *sb)
{
int slot = MINOR(sb->s_dev);
generic_shutdown_super(sb);
spin_lock(&unnamed_dev_lock);
ida_remove(&unnamed_dev_ida, slot);
if (slot < unnamed_dev_start)
unnamed_dev_start = slot;
spin_unlock(&unnamed_dev_lock);
}
EXPORT_SYMBOL(kill_anon_super);
void kill_litter_super(struct super_block *sb)
{
if (sb->s_root)
d_genocide(sb->s_root);
kill_anon_super(sb);
}
EXPORT_SYMBOL(kill_litter_super);
static int ns_test_super(struct super_block *sb, void *data)
{
return sb->s_fs_info == data;
}
static int ns_set_super(struct super_block *sb, void *data)
{
sb->s_fs_info = data;
return set_anon_super(sb, NULL);
}
struct dentry *mount_ns(struct file_system_type *fs_type, int flags,
void *data, int (*fill_super)(struct super_block *, void *, int))
{
struct super_block *sb;
sb = sget(fs_type, ns_test_super, ns_set_super, data);
if (IS_ERR(sb))
return ERR_CAST(sb);
if (!sb->s_root) {
int err;
sb->s_flags = flags;
err = fill_super(sb, data, flags & MS_SILENT ? 1 : 0);
if (err) {
deactivate_locked_super(sb);
return ERR_PTR(err);
}
sb->s_flags |= MS_ACTIVE;
}
return dget(sb->s_root);
}
EXPORT_SYMBOL(mount_ns);
#ifdef CONFIG_BLOCK
static int set_bdev_super(struct super_block *s, void *data)
{
s->s_bdev = data;
s->s_dev = s->s_bdev->bd_dev;
/*
* We set the bdi here to the queue backing, file systems can
* overwrite this in ->fill_super()
*/
s->s_bdi = &bdev_get_queue(s->s_bdev)->backing_dev_info;
return 0;
}
static int test_bdev_super(struct super_block *s, void *data)
{
return (void *)s->s_bdev == data;
}
struct dentry *mount_bdev(struct file_system_type *fs_type,
int flags, const char *dev_name, void *data,
int (*fill_super)(struct super_block *, void *, int))
{
struct block_device *bdev;
struct super_block *s;
fmode_t mode = FMODE_READ | FMODE_EXCL;
int error = 0;
if (!(flags & MS_RDONLY))
mode |= FMODE_WRITE;
bdev = blkdev_get_by_path(dev_name, mode, fs_type);
if (IS_ERR(bdev))
return ERR_CAST(bdev);
/*
* once the super is inserted into the list by sget, s_umount
* will protect the lockfs code from trying to start a snapshot
* while we are mounting
*/
mutex_lock(&bdev->bd_fsfreeze_mutex);
if (bdev->bd_fsfreeze_count > 0) {
mutex_unlock(&bdev->bd_fsfreeze_mutex);
error = -EBUSY;
goto error_bdev;
}
s = sget(fs_type, test_bdev_super, set_bdev_super, bdev);
mutex_unlock(&bdev->bd_fsfreeze_mutex);
if (IS_ERR(s))
goto error_s;
if (s->s_root) {
if ((flags ^ s->s_flags) & MS_RDONLY) {
deactivate_locked_super(s);
error = -EBUSY;
goto error_bdev;
}
/*
* s_umount nests inside bd_mutex during
* __invalidate_device(). blkdev_put() acquires
* bd_mutex and can't be called under s_umount. Drop
* s_umount temporarily. This is safe as we're
* holding an active reference.
*/
up_write(&s->s_umount);
blkdev_put(bdev, mode);
down_write(&s->s_umount);
} else {
char b[BDEVNAME_SIZE];
s->s_flags = flags;
s->s_mode = mode;
strlcpy(s->s_id, bdevname(bdev, b), sizeof(s->s_id));
sb_set_blocksize(s, block_size(bdev));
error = fill_super(s, data, flags & MS_SILENT ? 1 : 0);
if (error) {
deactivate_locked_super(s);
goto error;
}
s->s_flags |= MS_ACTIVE;
bdev->bd_super = s;
}
return dget(s->s_root);
error_s:
error = PTR_ERR(s);
error_bdev:
blkdev_put(bdev, mode);
error:
return ERR_PTR(error);
}
EXPORT_SYMBOL(mount_bdev);
void kill_block_super(struct super_block *sb)
{
struct block_device *bdev = sb->s_bdev;
fmode_t mode = sb->s_mode;
bdev->bd_super = NULL;
generic_shutdown_super(sb);
sync_blockdev(bdev);
WARN_ON_ONCE(!(mode & FMODE_EXCL));
blkdev_put(bdev, mode | FMODE_EXCL);
}
EXPORT_SYMBOL(kill_block_super);
#endif
struct dentry *mount_nodev(struct file_system_type *fs_type,
int flags, void *data,
int (*fill_super)(struct super_block *, void *, int))
{
int error;
struct super_block *s = sget(fs_type, NULL, set_anon_super, NULL);
if (IS_ERR(s))
return ERR_CAST(s);
s->s_flags = flags;
error = fill_super(s, data, flags & MS_SILENT ? 1 : 0);
if (error) {
deactivate_locked_super(s);
return ERR_PTR(error);
}
s->s_flags |= MS_ACTIVE;
return dget(s->s_root);
}
EXPORT_SYMBOL(mount_nodev);
static int compare_single(struct super_block *s, void *p)
{
return 1;
}
struct dentry *mount_single(struct file_system_type *fs_type,
int flags, void *data,
int (*fill_super)(struct super_block *, void *, int))
{
struct super_block *s;
int error;
s = sget(fs_type, compare_single, set_anon_super, NULL);
if (IS_ERR(s))
return ERR_CAST(s);
if (!s->s_root) {
s->s_flags = flags;
error = fill_super(s, data, flags & MS_SILENT ? 1 : 0);
if (error) {
deactivate_locked_super(s);
return ERR_PTR(error);
}
s->s_flags |= MS_ACTIVE;
} else {
do_remount_sb(s, flags, data, 0);
}
return dget(s->s_root);
}
EXPORT_SYMBOL(mount_single);
struct dentry *
mount_fs(struct file_system_type *type, int flags, const char *name, void *data)
{
struct dentry *root;
struct super_block *sb;
char *secdata = NULL;
int error = -ENOMEM;
if (data && !(type->fs_flags & FS_BINARY_MOUNTDATA)) {
secdata = alloc_secdata();
if (!secdata)
goto out;
error = security_sb_copy_data(data, secdata);
if (error)
goto out_free_secdata;
}
root = type->mount(type, flags, name, data);
if (IS_ERR(root)) {
error = PTR_ERR(root);
goto out_free_secdata;
}
sb = root->d_sb;
BUG_ON(!sb);
WARN_ON(!sb->s_bdi);
WARN_ON(sb->s_bdi == &default_backing_dev_info);
sb->s_flags |= MS_BORN;
error = security_sb_kern_mount(sb, flags, secdata);
if (error)
goto out_sb;
/*
* filesystems should never set s_maxbytes larger than MAX_LFS_FILESIZE
* but s_maxbytes was an unsigned long long for many releases. Throw
* this warning for a little while to try and catch filesystems that
* violate this rule.
*/
WARN((sb->s_maxbytes < 0), "%s set sb->s_maxbytes to "
"negative value (%lld)\n", type->name, sb->s_maxbytes);
up_write(&sb->s_umount);
free_secdata(secdata);
return root;
out_sb:
dput(root);
deactivate_locked_super(sb);
out_free_secdata:
free_secdata(secdata);
out:
return ERR_PTR(error);
}
/**
* sb_end_write - drop write access to a superblock
* @sb: the super we wrote to
* @level: the lowest level of freezing which we blocked
*
* Decrement number of writers to the filesystem preventing freezing of
* given level. Wake up possible waiters wanting to freeze the filesystem.
*/
void sb_end_write(struct super_block *sb, int level)
{
struct sb_writers_level *sl = &sb->s_writers[level-1];
percpu_counter_dec(&sl->counter);
/*
* Make sure s_writers are updated before we wake up waiters in
* freeze_super().
*/
smp_mb();
if (waitqueue_active(&sl->wait))
wake_up(&sl->wait);
rwsem_release(&sl->lock_map, 1, _RET_IP_);
}
EXPORT_SYMBOL(sb_end_write);
/**
* sb_start_write - get write access to a superblock
* @sb: the super we write to
* @level: the lowest level of freezing which we block
*
* When a process wants to write data to a filesystem (i.e. dirty a page), it
* should embed the operation in a sb_start_write() - sb_end_write() pair to
* get exclusion against filesystem freezing. This function increments number
* of writers preventing freezing of given level to proceed. If the file
* system is already frozen it waits until it is thawed.
*
* The lock orderding constraints of sb_start_write() for level SB_FREEZE_WRITE
* are following:
* mmap_sem (page-fault)
* -> s_writers (block_page_mkwrite or equivalent)
*
* i_mutex (do_truncate, __generic_file_aio_write)
* -> s_writers
*
* s_umount (freeze_super)
* -> s_writers
*
* For level SB_FREEZE_TRANS lock constraints are rather file system dependent,
* in most cases equivalent to constraints for starting a fs transaction.
*/
void sb_start_write(struct super_block *sb, int level)
{
retry:
rwsem_acquire_read(&sb->s_writers[level-1].lock_map, 0, 0, _RET_IP_);
vfs_check_frozen(sb, level);
percpu_counter_inc(&sb->s_writers[level-1].counter);
/*
* Make sure s_writers are updated before we check s_frozen.
* freeze_super() first sets s_frozen and then checks s_writers.
*/
smp_mb();
if (sb->s_frozen >= level) {
sb_end_write(sb, level);
goto retry;
}
}
EXPORT_SYMBOL(sb_start_write);
/**
* sb_dup_write - get write access to a superblock without blocking
* @sb: the super we write to
* @level: the lowest level of freezing which we block
*
* This function is like sb_start_write() only that it does not check s_frozen
* in the superblock. The caller can call this function only when it already
* holds write access to the superblock at this level (i.e., called
* sb_start_write(sb, level) previously).
*/
void sb_dup_write(struct super_block *sb, int level)
{
/*
* Trick lockdep into acquiring read lock again without complaining
* about lock recursion
*/
rwsem_acquire_read(&sb->s_writers[level-1].lock_map, 0, 1, _RET_IP_);
percpu_counter_inc(&sb->s_writers[level-1].counter);
}
EXPORT_SYMBOL(sb_dup_write);
/**
* sb_wait_write - wait until all writers at given level finish
* @sb: the super for which we wait
* @level: the level at which we wait for writers
*
* This function waits until there are no writers at given level. Caller
* of this function should make sure there can be no new writers at required
* level before calling this function. Otherwise this function can livelock.
*/
void sb_wait_write(struct super_block *sb, int level)
{
s64 writers;
struct sb_writers_level *sl = &sb->s_writers[level-1];
do {
DEFINE_WAIT(wait);
/*
* We use a barrier in prepare_to_wait() to separate setting
* of s_frozen and checking of s_writers
*/
prepare_to_wait(&sl->wait, &wait, TASK_UNINTERRUPTIBLE);
writers = percpu_counter_sum(&sl->counter);
if (writers)
schedule();
finish_wait(&sl->wait, &wait);
} while (writers);
}
EXPORT_SYMBOL(sb_wait_write);
/*
* Freeze superblock to given level, wait for writers at given level
* to finish.
*/
static void sb_freeze_to_level(struct super_block *sb, int level)
{
sb->s_frozen = level;
/*
* We just cycle-through lockdep here so that it does not complain
* about returning with lock to userspace
*/
rwsem_acquire(&sb->s_writers[level-1].lock_map, 0, 0, _THIS_IP_);
rwsem_release(&sb->s_writers[level-1].lock_map, 1, _THIS_IP_);
/*
* Now wait for writers to finish. As s_frozen is already set to
* 'level' we are guaranteed there are no new writers at given level.
*/
sb_wait_write(sb, level);
}
/**
* freeze_super - lock the filesystem and force it into a consistent state
* @sb: the super to lock
*
* Syncs the super to make sure the filesystem is consistent and calls the fs's
* freeze_fs. Subsequent calls to this without first thawing the fs will return
* -EBUSY.
*/
int freeze_super(struct super_block *sb)
{
int ret;
atomic_inc(&sb->s_active);
down_write(&sb->s_umount);
if (sb->s_frozen) {
deactivate_locked_super(sb);
return -EBUSY;
}
if (sb->s_flags & MS_RDONLY) {
sb->s_frozen = SB_FREEZE_TRANS;
smp_wmb();
up_write(&sb->s_umount);
return 0;
}
sb_freeze_to_level(sb, SB_FREEZE_WRITE);
sync_filesystem(sb);
sb_freeze_to_level(sb, SB_FREEZE_TRANS);
sync_blockdev(sb->s_bdev);
if (sb->s_op->freeze_fs) {
ret = sb->s_op->freeze_fs(sb);
if (ret) {
printk(KERN_ERR
"VFS:Filesystem freeze failed\n");
sb->s_frozen = SB_UNFROZEN;
deactivate_locked_super(sb);
return ret;
}
}
up_write(&sb->s_umount);
return 0;
}
EXPORT_SYMBOL(freeze_super);
/**
* thaw_super -- unlock filesystem
* @sb: the super to thaw
*
* Unlocks the filesystem and marks it writeable again after freeze_super().
*/
int thaw_super(struct super_block *sb)
{
int error;
down_write(&sb->s_umount);
if (sb->s_frozen == SB_UNFROZEN) {
up_write(&sb->s_umount);
return -EINVAL;
}
if (sb->s_flags & MS_RDONLY)
goto out;
if (sb->s_op->unfreeze_fs) {
error = sb->s_op->unfreeze_fs(sb);
if (error) {
printk(KERN_ERR
"VFS:Filesystem thaw failed\n");
sb->s_frozen = SB_FREEZE_TRANS;
up_write(&sb->s_umount);
return error;
}
}
out:
sb->s_frozen = SB_UNFROZEN;
smp_wmb();
wake_up(&sb->s_wait_unfrozen);
deactivate_locked_super(sb);
return 0;
}
EXPORT_SYMBOL(thaw_super);
| shankarathi07/linux_samsung_ics | fs/super.c | C | gpl-2.0 | 31,275 |
#include "cmdq_platform.h"
#include "cmdq_core.h"
#include "cmdq_reg.h"
#include <linux/vmalloc.h>
#include <mach/mt_clkmgr.h>
#include <linux/seq_file.h>
#include "smi_debug.h"
#include "m4u.h"
#define MMSYS_CONFIG_BASE cmdq_dev_get_module_base_VA_MMSYS_CONFIG()
typedef struct RegDef {
int offset;
const char *name;
} RegDef;
const bool cmdq_core_support_sync_non_suspendable(void)
{
return true;
}
const bool cmdq_core_support_wait_and_receive_event_in_same_tick(void)
{
return true;
}
const uint32_t cmdq_core_get_subsys_LSB_in_argA(void)
{
return 16;
}
int32_t cmdq_subsys_from_phys_addr(uint32_t physAddr)
{
const int32_t msb = (physAddr & 0x0FFFF0000) >> 16;
#undef DECLARE_CMDQ_SUBSYS
#define DECLARE_CMDQ_SUBSYS(addr, id, grp, base) case addr: return id;
switch (msb) {
#include "cmdq_subsys.h"
}
CMDQ_ERR("unrecognized subsys, msb=0x%04x, physAddr:0x%08x\n", msb, physAddr);
return -1;
#undef DECLARE_CMDQ_SUBSYS
}
void cmdq_core_fix_command_desc_scenario_for_user_space_request(cmdqCommandStruct *pCommand)
{
if ((CMDQ_SCENARIO_USER_DISP_COLOR == pCommand->scenario) || (CMDQ_SCENARIO_USER_MDP == pCommand->scenario)) {
CMDQ_VERBOSE("user space request, scenario:%d\n", pCommand->scenario);
} else {
CMDQ_VERBOSE("[WARNING]fix user space request to CMDQ_SCENARIO_USER_SPACE\n");
pCommand->scenario = CMDQ_SCENARIO_USER_SPACE;
}
}
bool cmdq_core_is_request_from_user_space(const CMDQ_SCENARIO_ENUM scenario)
{
switch (scenario) {
case CMDQ_SCENARIO_USER_DISP_COLOR:
case CMDQ_SCENARIO_USER_MDP:
case CMDQ_SCENARIO_USER_SPACE: /* phased out */
return true;
default:
return false;
}
return false;
}
bool cmdq_core_is_disp_scenario(const CMDQ_SCENARIO_ENUM scenario)
{
switch (scenario) {
case CMDQ_SCENARIO_PRIMARY_DISP:
case CMDQ_SCENARIO_PRIMARY_MEMOUT:
case CMDQ_SCENARIO_PRIMARY_ALL:
case CMDQ_SCENARIO_SUB_DISP:
case CMDQ_SCENARIO_SUB_MEMOUT:
case CMDQ_SCENARIO_SUB_ALL:
case CMDQ_SCENARIO_MHL_DISP:
case CMDQ_SCENARIO_RDMA0_DISP:
case CMDQ_SCENARIO_RDMA0_COLOR0_DISP:
case CMDQ_SCENARIO_RDMA1_DISP:
case CMDQ_SCENARIO_TRIGGER_LOOP:
case CMDQ_SCENARIO_DISP_ESD_CHECK:
case CMDQ_SCENARIO_DISP_SCREEN_CAPTURE:
case CMDQ_SCENARIO_DISP_MIRROR_MODE:
/* color path */
case CMDQ_SCENARIO_DISP_COLOR:
case CMDQ_SCENARIO_USER_DISP_COLOR:
/* secure path */
case CMDQ_SCENARIO_DISP_PRIMARY_DISABLE_SECURE_PATH:
case CMDQ_SCENARIO_DISP_SUB_DISABLE_SECURE_PATH:
return true;
default:
return false;
}
/* freely dispatch */
return false;
}
bool cmdq_core_should_enable_prefetch(CMDQ_SCENARIO_ENUM scenario)
{
switch (scenario) {
case CMDQ_SCENARIO_PRIMARY_DISP:
case CMDQ_SCENARIO_PRIMARY_ALL:
case CMDQ_SCENARIO_DEBUG_PREFETCH: /* HACK: force debug into 0/1 thread */
/* any path that connects to Primary DISP HW */
/* should enable prefetch. */
/* MEMOUT scenarios does not. */
/* Also, since thread 0/1 shares one prefetch buffer, */
/* we allow only PRIMARY path to use prefetch. */
return true;
default:
return false;
}
return false;
}
bool cmdq_core_should_profile(CMDQ_SCENARIO_ENUM scenario)
{
#ifdef CMDQ_GPR_SUPPORT
switch (scenario) {
default:
return false;
}
return false;
#else
/* note command profile method depends on GPR */
CMDQ_ERR("func:%s failed since CMDQ dosen't support GPR\n", __func__);
return false;
#endif
}
const bool cmdq_core_is_a_secure_thread(const int32_t thread)
{
#ifdef CMDQ_SECURE_PATH_SUPPORT
if ((CMDQ_MIN_SECURE_THREAD_ID <= thread) &&
(CMDQ_MIN_SECURE_THREAD_ID + CMDQ_MAX_SECURE_THREAD_COUNT > thread)){
return true;
}
#endif
return false;
}
const bool cmdq_core_is_valid_notify_thread_for_secure_path(const int32_t thread)
{
#ifdef CMDQ_SECURE_PATH_SUPPORT
return (15 == thread) ? (true) : (false);
#else
return false;
#endif
}
int cmdq_core_get_thread_index_from_scenario_and_secure_data(CMDQ_SCENARIO_ENUM scenario, const bool secure)
{
#ifdef CMDQ_SECURE_PATH_SUPPORT
if (!secure && CMDQ_SCENARIO_SECURE_NOTIFY_LOOP == scenario) {
return 15;
}
#endif
if (!secure) {
return cmdq_core_disp_thread_index_from_scenario(scenario);
}
/* dispatch secure thread according to scenario */
switch (scenario) {
case CMDQ_SCENARIO_DISP_PRIMARY_DISABLE_SECURE_PATH:
case CMDQ_SCENARIO_PRIMARY_DISP:
case CMDQ_SCENARIO_PRIMARY_ALL:
case CMDQ_SCENARIO_RDMA0_DISP:
case CMDQ_SCENARIO_DEBUG_PREFETCH:
/* CMDQ_MIN_SECURE_THREAD_ID */
return 12;
case CMDQ_SCENARIO_DISP_SUB_DISABLE_SECURE_PATH:
case CMDQ_SCENARIO_SUB_DISP:
case CMDQ_SCENARIO_SUB_ALL:
case CMDQ_SCENARIO_MHL_DISP:
/* because mirror mode and sub disp never use at the same time in secure path, */
/* dispatch to same HW thread */
case CMDQ_SCENARIO_DISP_MIRROR_MODE:
case CMDQ_SCENARIO_DISP_COLOR:
case CMDQ_SCENARIO_PRIMARY_MEMOUT:
return 13;
case CMDQ_SCENARIO_USER_MDP:
case CMDQ_SCENARIO_USER_SPACE:
case CMDQ_SCENARIO_DEBUG:
/* because there is one input engine for MDP, reserve one secure thread is enough */
return 14;
default:
CMDQ_ERR("no dedicated secure thread for senario:%d\n", scenario);
return CMDQ_INVALID_THREAD;
}
}
int cmdq_core_disp_thread_index_from_scenario(CMDQ_SCENARIO_ENUM scenario)
{
if (cmdq_core_should_enable_prefetch(scenario)) {
return 0;
}
switch (scenario) {
case CMDQ_SCENARIO_PRIMARY_DISP:
case CMDQ_SCENARIO_PRIMARY_ALL:
case CMDQ_SCENARIO_RDMA0_DISP:
case CMDQ_SCENARIO_RDMA0_COLOR0_DISP:
case CMDQ_SCENARIO_DEBUG_PREFETCH: /* HACK: force debug into 0/1 thread */
/* primary config: thread 0 */
return 0;
case CMDQ_SCENARIO_SUB_DISP:
case CMDQ_SCENARIO_SUB_ALL:
case CMDQ_SCENARIO_MHL_DISP:
case CMDQ_SCENARIO_SUB_MEMOUT:
case CMDQ_SCENARIO_RDMA1_DISP:
/* when HW thread 0 enables pre-fetch, any thread 1 operation will let HW thread 0's behavior abnormally */
/* forbid thread 1 */
return 5;
case CMDQ_SCENARIO_DISP_ESD_CHECK:
return 2;
case CMDQ_SCENARIO_DISP_SCREEN_CAPTURE:
case CMDQ_SCENARIO_DISP_MIRROR_MODE:
return 3;
case CMDQ_SCENARIO_DISP_COLOR:
case CMDQ_SCENARIO_USER_DISP_COLOR:
case CMDQ_SCENARIO_PRIMARY_MEMOUT:
return 4;
default:
/* freely dispatch */
return CMDQ_INVALID_THREAD;
}
/* freely dispatch */
return CMDQ_INVALID_THREAD;
}
CMDQ_HW_THREAD_PRIORITY_ENUM cmdq_core_priority_from_scenario(CMDQ_SCENARIO_ENUM scenario)
{
switch (scenario) {
case CMDQ_SCENARIO_PRIMARY_DISP:
case CMDQ_SCENARIO_PRIMARY_ALL:
case CMDQ_SCENARIO_SUB_MEMOUT:
case CMDQ_SCENARIO_SUB_DISP:
case CMDQ_SCENARIO_SUB_ALL:
case CMDQ_SCENARIO_RDMA1_DISP:
case CMDQ_SCENARIO_MHL_DISP:
case CMDQ_SCENARIO_RDMA0_DISP:
case CMDQ_SCENARIO_RDMA0_COLOR0_DISP:
case CMDQ_SCENARIO_DISP_MIRROR_MODE:
case CMDQ_SCENARIO_PRIMARY_MEMOUT:
/* color path */
case CMDQ_SCENARIO_DISP_COLOR:
case CMDQ_SCENARIO_USER_DISP_COLOR:
/* secure path **/
case CMDQ_SCENARIO_DISP_PRIMARY_DISABLE_SECURE_PATH:
case CMDQ_SCENARIO_DISP_SUB_DISABLE_SECURE_PATH:
/* currently, a prefetch thread is always in high priority. */
return CMDQ_THR_PRIO_DISPLAY_CONFIG;
/* HACK: force debug into 0/1 thread */
case CMDQ_SCENARIO_DEBUG_PREFETCH:
return CMDQ_THR_PRIO_DISPLAY_CONFIG;
case CMDQ_SCENARIO_DISP_ESD_CHECK:
case CMDQ_SCENARIO_DISP_SCREEN_CAPTURE:
return CMDQ_THR_PRIO_DISPLAY_ESD;
default:
/* other cases need exta logic, see below. */
break;
}
if (cmdq_platform_is_loop_scenario(scenario, true)) {
return CMDQ_THR_PRIO_DISPLAY_TRIGGER;
} else {
return CMDQ_THR_PRIO_NORMAL;
}
}
bool cmdq_platform_force_loop_irq_from_scenario(CMDQ_SCENARIO_ENUM scenario)
{
#ifdef CMDQ_SECURE_PATH_SUPPORT
if (CMDQ_SCENARIO_SECURE_NOTIFY_LOOP == scenario) {
/* For secure notify loop, we need IRQ to update secure task */
return true;
}
#endif
return false;
}
bool cmdq_platform_is_loop_scenario(CMDQ_SCENARIO_ENUM scenario, bool displayOnly)
{
#ifdef CMDQ_SECURE_PATH_SUPPORT
if (!displayOnly && CMDQ_SCENARIO_SECURE_NOTIFY_LOOP == scenario) {
return true;
}
#endif
if (CMDQ_SCENARIO_TRIGGER_LOOP == scenario) {
return true;
}
return false;
}
void cmdq_core_get_reg_id_from_hwflag(uint64_t hwflag, CMDQ_DATA_REGISTER_ENUM *valueRegId,
CMDQ_DATA_REGISTER_ENUM *destRegId,
CMDQ_EVENT_ENUM *regAccessToken)
{
*regAccessToken = CMDQ_SYNC_TOKEN_INVALID;
if (hwflag & (1LL << CMDQ_ENG_JPEG_ENC)) {
*valueRegId = CMDQ_DATA_REG_JPEG;
*destRegId = CMDQ_DATA_REG_JPEG_DST;
*regAccessToken = CMDQ_SYNC_TOKEN_GPR_SET_0;
} else if (hwflag & (1LL << CMDQ_ENG_MDP_TDSHP0)) {
*valueRegId = CMDQ_DATA_REG_2D_SHARPNESS_0;
*destRegId = CMDQ_DATA_REG_2D_SHARPNESS_0_DST;
*regAccessToken = CMDQ_SYNC_TOKEN_GPR_SET_1;
} else if (hwflag & (1LL << CMDQ_ENG_DISP_COLOR0)) {
*valueRegId = CMDQ_DATA_REG_PQ_COLOR;
*destRegId = CMDQ_DATA_REG_PQ_COLOR_DST;
*regAccessToken = CMDQ_SYNC_TOKEN_GPR_SET_3;
} else {
/* assume others are debug cases */
*valueRegId = CMDQ_DATA_REG_DEBUG;
*destRegId = CMDQ_DATA_REG_DEBUG_DST;
*regAccessToken = CMDQ_SYNC_TOKEN_GPR_SET_4;
}
return;
}
const char *cmdq_core_module_from_event_id(CMDQ_EVENT_ENUM event, uint32_t instA, uint32_t instB)
{
const char *module = "CMDQ";
switch (event) {
case CMDQ_EVENT_DISP_RDMA0_SOF:
case CMDQ_EVENT_DISP_RDMA1_SOF:
case CMDQ_EVENT_DISP_RDMA0_EOF:
case CMDQ_EVENT_DISP_RDMA1_EOF:
case CMDQ_EVENT_DISP_RDMA0_UNDERRUN:
case CMDQ_EVENT_DISP_RDMA1_UNDERRUN:
module = "DISP_RDMA";
break;
case CMDQ_EVENT_DISP_WDMA0_SOF:
case CMDQ_EVENT_DISP_WDMA1_SOF:
case CMDQ_EVENT_DISP_WDMA0_EOF:
case CMDQ_EVENT_DISP_WDMA1_EOF:
module = "DISP_WDMA";
break;
case CMDQ_EVENT_DISP_OVL0_SOF:
case CMDQ_EVENT_DISP_OVL1_SOF:
case CMDQ_EVENT_DISP_OVL0_EOF:
case CMDQ_EVENT_DISP_OVL1_EOF:
module = "DISP_OVL";
break;
case CMDQ_EVENT_DSI_TE:
case CMDQ_EVENT_DISP_COLOR_SOF...CMDQ_EVENT_DISP_PWM0_SOF:
case CMDQ_EVENT_DISP_COLOR_EOF...CMDQ_EVENT_DISP_DPI0_EOF:
case CMDQ_EVENT_MUTEX0_STREAM_EOF...CMDQ_EVENT_MUTEX4_STREAM_EOF:
case CMDQ_SYNC_TOKEN_CONFIG_DIRTY:
case CMDQ_SYNC_TOKEN_STREAM_EOF:
module = "DISP";
break;
case CMDQ_EVENT_UFOD_RAMA0_L0_SOF...CMDQ_EVENT_UFOD_RAMA1_L3_SOF:
case CMDQ_EVENT_UFOD_RAMA0_L0_EOF...CMDQ_EVENT_UFOD_RAMA1_L3_EOF:
module = "DISP_UFOD";
break;
case CMDQ_EVENT_MDP_RDMA0_SOF...CMDQ_EVENT_MDP_WROT_SOF:
case CMDQ_EVENT_MDP_RDMA0_EOF...CMDQ_EVENT_MDP_WROT_READ_EOF:
case CMDQ_EVENT_MUTEX5_STREAM_EOF...CMDQ_EVENT_MUTEX9_STREAM_EOF:
module = "MDP";
break;
case CMDQ_EVENT_ISP_PASS2_2_EOF...CMDQ_EVENT_ISP_PASS1_0_EOF:
case CMDQ_EVENT_ISP_CAMSV_2_PASS1_DONE...CMDQ_EVENT_ISP_SENINF_CAM0_FULL:
module = "ISP";
break;
case CMDQ_EVENT_JPEG_ENC_EOF:
case CMDQ_EVENT_JPEG_DEC_EOF:
module = "JPGE";
break;
case CMDQ_EVENT_VENC_EOF:
case CMDQ_EVENT_VENC_MB_DONE:
case CMDQ_EVENT_VENC_128BYTE_CNT_DONE:
module = "VENC";
break;
default:
module = "CMDQ";
break;
}
return module;
}
const char *cmdq_core_parse_module_from_reg_addr(uint32_t reg_addr)
{
const uint32_t addr_base_and_page = (reg_addr & 0xFFFFF000);
const uint32_t addr_base_shifted = (reg_addr & 0xFFFF0000) >> 16;
const char *module = "CMDQ";
/* for well-known base, we check them with 12-bit mask */
/* defined in mt_reg_base.h */
/* TODO: comfirm with SS if IO_VIRT_TO_PHYS workable when enable device tree? */
#define DECLARE_REG_RANGE(base, name) case base: return #name;
switch (addr_base_and_page) {
DECLARE_REG_RANGE(0x14001000, MDP); /* MDP_RDMA */
DECLARE_REG_RANGE(0x14002000, MDP); /* MDP_RSZ0 */
DECLARE_REG_RANGE(0x14003000, MDP); /* MDP_RSZ1 */
DECLARE_REG_RANGE(0x14004000, MDP); /* MDP_WDMA */
DECLARE_REG_RANGE(0x14005000, MDP); /* MDP_WROT */
DECLARE_REG_RANGE(0x14006000, MDP); /* MDP_TDSHP */
DECLARE_REG_RANGE(0x1400C000, COLOR); /* DISP_COLOR */
DECLARE_REG_RANGE(0x1400D000, CCORR); /* DISP_CCORR */
DECLARE_REG_RANGE(0x14007000, OVL0); /* DISP_OVL0 */
DECLARE_REG_RANGE(0x14008000, OVL1); /* DISP_OVL1 */
DECLARE_REG_RANGE(0x1400E000, AAL); /* DISP_AAL */
DECLARE_REG_RANGE(0x1400F000, AAL); /* DISP_GAMMA */
DECLARE_REG_RANGE(0x17002FFF, VENC); /* VENC */
DECLARE_REG_RANGE(0x17003FFF, JPGENC); /* JPGENC */
DECLARE_REG_RANGE(0x17004FFF, JPGDEC); /* JPGDEC */
}
#undef DECLARE_REG_RANGE
/* for other register address we rely on GCE subsys to group them with */
/* 16-bit mask. */
#undef DECLARE_CMDQ_SUBSYS
#define DECLARE_CMDQ_SUBSYS(msb, id, grp, base) case msb: return #grp;
switch (addr_base_shifted) {
#include "cmdq_subsys.h"
}
#undef DECLARE_CMDQ_SUBSYS
return module;
}
const int32_t cmdq_core_can_module_entry_suspend(EngineStruct *engineList)
{
int32_t status = 0;
int i;
CMDQ_ENG_ENUM e = 0;
CMDQ_ENG_ENUM mdpEngines[] = {
CMDQ_ENG_ISP_IMGI,
CMDQ_ENG_MDP_RDMA0,
CMDQ_ENG_MDP_RSZ0,
CMDQ_ENG_MDP_RSZ1,
CMDQ_ENG_MDP_TDSHP0,
CMDQ_ENG_MDP_WROT0,
CMDQ_ENG_MDP_WDMA
};
for (i = 0; i < (sizeof(mdpEngines) / sizeof(CMDQ_ENG_ENUM)); ++i) {
e = mdpEngines[i];
if (0 != engineList[e].userCount) {
CMDQ_ERR("suspend but engine %d has userCount %d, owner=%d\n",
e, engineList[e].userCount, engineList[e].currOwner);
status = -EBUSY;
}
}
return status;
}
ssize_t cmdq_core_print_status_clock(char *buf)
{
int32_t length = 0;
char *pBuffer = buf;
#ifdef CMDQ_PWR_AWARE
/* MT_CG_DISP0_MUTEX_32K is removed in this platform */
pBuffer += sprintf(pBuffer, "MT_CG_INFRA_GCE: %d\n", clock_is_on(MT_CG_INFRA_GCE));
#endif
length = pBuffer - buf;
return length;
}
void cmdq_core_print_status_seq_clock(struct seq_file *m)
{
#ifdef CMDQ_PWR_AWARE
/* MT_CG_DISP0_MUTEX_32K is removed in this platform */
seq_printf(m, "MT_CG_INFRA_GCE: %d\n", clock_is_on(MT_CG_INFRA_GCE));
#endif
}
void cmdq_core_enable_common_clock_locked_impl(bool enable)
{
#ifdef CMDQ_PWR_AWARE
if (enable) {
CMDQ_VERBOSE("[CLOCK] Enable SMI & LARB0 Clock\n");
enable_clock(MT_CG_DISP0_SMI_COMMON, "CMDQ_MDP");
//enable_clock(MT_CG_DISP0_SMI_LARB0, "CMDQ_MDP");
m4u_larb0_enable("CMDQ_MDP");
#if 0
/* MT_CG_DISP0_MUTEX_32K is removed in this platform */
CMDQ_LOG("[CLOCK] enable MT_CG_DISP0_MUTEX_32K\n");
enable_clock(MT_CG_DISP0_MUTEX_32K, "CMDQ_MDP");
#endif
} else {
CMDQ_VERBOSE("[CLOCK] Disable SMI & LARB0 Clock\n");
/* disable, reverse the sequence */
//disable_clock(MT_CG_DISP0_SMI_LARB0, "CMDQ_MDP");
m4u_larb0_disable("CMDQ_MDP");
disable_clock(MT_CG_DISP0_SMI_COMMON, "CMDQ_MDP");
#if 0
/* MT_CG_DISP0_MUTEX_32K is removed in this platform */
CMDQ_LOG("[CLOCK] disable MT_CG_DISP0_MUTEX_32K\n");
disable_clock(MT_CG_DISP0_MUTEX_32K, "CMDQ_MDP");
#endif
}
#endif /* CMDQ_PWR_AWARE */
}
void cmdq_core_enable_gce_clock_locked_impl(bool enable)
{
#ifdef CMDQ_PWR_AWARE
if (enable) {
CMDQ_VERBOSE("[CLOCK] Enable CMDQ(GCE) Clock\n");
cmdq_core_enable_cmdq_clock_locked_impl(enable, CMDQ_DRIVER_DEVICE_NAME);
} else {
CMDQ_VERBOSE("[CLOCK] Disable CMDQ(GCE) Clock\n");
cmdq_core_enable_cmdq_clock_locked_impl(enable, CMDQ_DRIVER_DEVICE_NAME);
}
#endif /* CMDQ_PWR_AWARE */
}
void cmdq_core_enable_cmdq_clock_locked_impl(bool enable, char *deviceName)
{
#ifdef CMDQ_PWR_AWARE
if (enable) {
enable_clock(MT_CG_INFRA_GCE, deviceName);
} else {
disable_clock(MT_CG_INFRA_GCE, deviceName);
}
#endif /* CMDQ_PWR_AWARE */
}
const char* cmdq_core_parse_error_module_by_hwflag_impl(struct TaskStruct *pTask)
{
const char *module = NULL;
const uint32_t ISP_ONLY[2] = {
((1LL << CMDQ_ENG_ISP_IMGI) | (1LL << CMDQ_ENG_ISP_IMG2O)),
((1LL << CMDQ_ENG_ISP_IMGI) | (1LL << CMDQ_ENG_ISP_IMG2O) | (1LL << CMDQ_ENG_ISP_IMGO))};
/* common part for both normal and secure path */
/* for JPEG scenario, use HW flag is sufficient */
if (pTask->engineFlag & (1LL << CMDQ_ENG_JPEG_ENC)) {
module = "JPGENC";
} else if (pTask->engineFlag & (1LL << CMDQ_ENG_JPEG_DEC)) {
module = "JPGDEC";
} else if ((ISP_ONLY[0] == pTask->engineFlag) || (ISP_ONLY[1] == pTask->engineFlag)) {
module = "ISP_ONLY";
} else if (cmdq_core_is_disp_scenario(pTask->scenario)) {
module = "DISP";
}
/* for secure path, use HW flag is sufficient */
do {
if (NULL != module) {
break;
}
if (false == pTask->secData.isSecure) {
/* normal path, need parse current running instruciton for more detail */
break;
}
else if (CMDQ_ENG_MDP_GROUP_FLAG(pTask->engineFlag)) {
module = "MDP";
break;
}
module = "CMDQ";
} while(0);
/* other case, we need to analysis instruction for more detail */
return module;
}
void cmdq_core_dump_mmsys_config(void)
{
int i = 0;
uint32_t value = 0;
const static struct RegDef configRegisters[] = {
{0x01c, "ISP_MOUT_EN"},
{0x020, "MDP_RDMA_MOUT_EN"},
{0x024, "MDP_PRZ0_MOUT_EN"},
{0x028, "MDP_PRZ1_MOUT_EN"},
{0x02C, "MDP_TDSHP_MOUT_EN"},
{0x030, "DISP_OVL0_MOUT_EN"},
{0x034, "DISP_OVL1_MOUT_EN"},
{0x038, "DISP_DITHER_MOUT_EN"},
{0x03C, "DISP_UFOE_MOUT_EN"},
/* {0x040, "MMSYS_MOUT_RST"}, */
{0x044, "MDP_PRZ0_SEL_IN"},
{0x048, "MDP_PRZ1_SEL_IN"},
{0x04C, "MDP_TDSHP_SEL_IN"},
{0x050, "MDP_WDMA_SEL_IN"},
{0x054, "MDP_WROT_SEL_IN"},
{0x058, "DISP_COLOR_SEL_IN"},
{0x05C, "DISP_WDMA_SEL_IN"},
{0x060, "DISP_UFOE_SEL_IN"},
{0x064, "DSI0_SEL_IN"},
{0x068, "DPI0_SEL_IN"},
{0x06C, "DISP_RDMA0_SOUT_SEL_IN"},
{0x070, "DISP_RDMA1_SOUT_SEL_IN"},
{0x0F0, "MMSYS_MISC"},
/* ACK and REQ related */
{0x8a0, "DISP_DL_VALID_0"},
{0x8a4, "DISP_DL_VALID_1"},
{0x8a8, "DISP_DL_READY_0"},
{0x8ac, "DISP_DL_READY_1"},
{0x8b0, "MDP_DL_VALID_0"},
{0x8b4, "MDP_DL_READY_0"}
};
for (i = 0; i < sizeof(configRegisters) / sizeof(configRegisters[0]); ++i) {
value = CMDQ_REG_GET16(MMSYS_CONFIG_BASE + configRegisters[i].offset);
CMDQ_ERR("%s: 0x%08x\n", configRegisters[i].name, value);
}
return;
}
void cmdq_core_dump_clock_gating(void)
{
uint32_t value[3] = { 0 };
value[0] = CMDQ_REG_GET32(MMSYS_CONFIG_BASE + 0x100);
value[1] = CMDQ_REG_GET32(MMSYS_CONFIG_BASE + 0x110);
/* value[2] = CMDQ_REG_GET32(MMSYS_CONFIG_BASE + 0x890); */
CMDQ_ERR("MMSYS_CG_CON0(deprecated): 0x%08x, MMSYS_CG_CON1: 0x%08x\n", value[0], value[1]);
/* CMDQ_ERR("MMSYS_DUMMY_REG: 0x%08x\n", value[2]); */
#ifndef CONFIG_MTK_FPGA
CMDQ_ERR("ISPSys clock state %d\n", subsys_is_on(SYS_ISP));
CMDQ_ERR("DisSys clock state %d\n", subsys_is_on(SYS_DIS));
CMDQ_ERR("VDESys clock state %d\n", subsys_is_on(SYS_VDE));
#endif
}
int cmdq_core_dump_smi(const int showSmiDump)
{
#if 0
int isSMIHang = 0;
#ifndef CONFIG_MTK_FPGA
isSMIHang = smi_debug_bus_hanging_detect(
SMI_DBG_DISPSYS | SMI_DBG_VDEC | SMI_DBG_IMGSYS | SMI_DBG_VENC | SMI_DBG_MJC,
showSmiDump);
isSMIHang = smi_debug_bus_hanging_detect_ext(
SMI_DBG_DISPSYS | SMI_DBG_VDEC | SMI_DBG_IMGSYS | SMI_DBG_VENC | SMI_DBG_MJC,
showSmiDump, 1);
CMDQ_ERR("SMI Hang? = %d\n", isSMIHang);
#endif
return isSMIHang;
#else
CMDQ_LOG("[WARNING]not enable SMI dump now\n");
return 0;
#endif
}
void cmdq_core_dump_secure_metadata(cmdqSecDataStruct *pSecData)
{
uint32_t i = 0;
cmdqSecAddrMetadataStruct *pAddr = NULL;
if (NULL == pSecData) {
return;
}
pAddr = (cmdqSecAddrMetadataStruct *)(CMDQ_U32_PTR(pSecData->addrMetadatas));
CMDQ_LOG("========= pSecData: %p dump =========\n", pSecData);
CMDQ_LOG("count:%d(%d), enginesNeedDAPC:0x%llx, enginesPortSecurity:0x%llx\n",
pSecData->addrMetadataCount, pSecData->addrMetadataMaxCount,
pSecData->enginesNeedDAPC, pSecData->enginesNeedPortSecurity);
if (NULL == pAddr) {
return;
}
for (i = 0; i < pSecData->addrMetadataCount; i++) {
CMDQ_LOG("idx:%d, type:%d, baseHandle:%x, offset:%d, size:%d, port:%d\n",
i, pAddr[i].type, pAddr[i].baseHandle, pAddr[i].offset, pAddr[i].size, pAddr[i].port);
}
}
uint64_t cmdq_rec_flag_from_scenario(CMDQ_SCENARIO_ENUM scn)
{
uint64_t flag = 0;
switch (scn) {
case CMDQ_SCENARIO_JPEG_DEC:
flag = (1LL << CMDQ_ENG_JPEG_DEC);
break;
case CMDQ_SCENARIO_PRIMARY_DISP:
flag = (1LL << CMDQ_ENG_DISP_OVL0) |
(1LL << CMDQ_ENG_DISP_COLOR0) |
(1LL << CMDQ_ENG_DISP_AAL) |
(1LL << CMDQ_ENG_DISP_GAMMA) |
(1LL << CMDQ_ENG_DISP_RDMA0) |
(1LL << CMDQ_ENG_DISP_UFOE) | (1LL << CMDQ_ENG_DISP_DSI0_CMD);
break;
case CMDQ_SCENARIO_PRIMARY_MEMOUT:
flag = 0LL;
break;
case CMDQ_SCENARIO_PRIMARY_ALL:
flag = ((1LL << CMDQ_ENG_DISP_OVL0) |
(1LL << CMDQ_ENG_DISP_WDMA0) |
(1LL << CMDQ_ENG_DISP_COLOR0) |
(1LL << CMDQ_ENG_DISP_AAL) |
(1LL << CMDQ_ENG_DISP_GAMMA) |
(1LL << CMDQ_ENG_DISP_RDMA0) |
(1LL << CMDQ_ENG_DISP_UFOE) | (1LL << CMDQ_ENG_DISP_DSI0_CMD));
break;
case CMDQ_SCENARIO_SUB_DISP:
flag = ((1LL << CMDQ_ENG_DISP_OVL1) |
(1LL << CMDQ_ENG_DISP_RDMA1) | (1LL << CMDQ_ENG_DISP_DPI));
break;
case CMDQ_SCENARIO_SUB_MEMOUT:
flag = ((1LL << CMDQ_ENG_DISP_OVL1) | (1LL << CMDQ_ENG_DISP_WDMA1));
break;
case CMDQ_SCENARIO_SUB_ALL:
flag = ((1LL << CMDQ_ENG_DISP_OVL1) |
(1LL << CMDQ_ENG_DISP_WDMA1) |
(1LL << CMDQ_ENG_DISP_RDMA1) | (1LL << CMDQ_ENG_DISP_DPI));
break;
case CMDQ_SCENARIO_RDMA0_DISP:
flag = ((1LL << CMDQ_ENG_DISP_RDMA0) | (1LL << CMDQ_ENG_DISP_DSI0_CMD));
break;
case CMDQ_SCENARIO_RDMA0_COLOR0_DISP:
flag = ((1LL << CMDQ_ENG_DISP_RDMA0) |
(1LL << CMDQ_ENG_DISP_COLOR0) |
(1LL << CMDQ_ENG_DISP_AAL) |
(1LL << CMDQ_ENG_DISP_GAMMA) |
(1LL << CMDQ_ENG_DISP_UFOE) | (1LL << CMDQ_ENG_DISP_DSI0_CMD));
break;
case CMDQ_SCENARIO_MHL_DISP:
case CMDQ_SCENARIO_RDMA1_DISP:
flag = ((1LL << CMDQ_ENG_DISP_RDMA1) | (1LL << CMDQ_ENG_DISP_DPI));
break;
case CMDQ_SCENARIO_TRIGGER_LOOP:
/* Trigger loop does not related to any HW by itself. */
flag = 0LL;
break;
case CMDQ_SCENARIO_USER_SPACE:
/* user space case, engine flag is passed seprately */
flag = 0LL;
break;
case CMDQ_SCENARIO_DEBUG:
case CMDQ_SCENARIO_DEBUG_PREFETCH:
flag = 0LL;
break;
case CMDQ_SCENARIO_DISP_ESD_CHECK:
case CMDQ_SCENARIO_DISP_SCREEN_CAPTURE:
/* ESD check uses separate thread (not config, not trigger) */
flag = 0LL;
break;
case CMDQ_SCENARIO_DISP_COLOR:
case CMDQ_SCENARIO_USER_DISP_COLOR:
/* color path */
flag = 0LL;
break;
case CMDQ_SCENARIO_DISP_MIRROR_MODE:
flag = 0LL;
break;
case CMDQ_SCENARIO_DISP_PRIMARY_DISABLE_SECURE_PATH:
case CMDQ_SCENARIO_DISP_SUB_DISABLE_SECURE_PATH:
/* secure path */
flag = 0LL;
break;
case CMDQ_SCENARIO_SECURE_NOTIFY_LOOP:
flag = 0LL;
break;
default:
CMDQ_ERR("Unknown scenario type %d\n", scn);
flag = 0LL;
break;
}
return flag;
}
void cmdq_core_gpr_dump(void)
{
int i = 0;
long offset = 0;
uint32_t value = 0;
CMDQ_LOG("========= GPR dump ========= \n");
for (i = 0; i < 16; i++) {
offset = CMDQ_GPR_R32(i);
value = CMDQ_REG_GET32(offset);
CMDQ_LOG("[GPR %2d]+0x%lx = 0x%08x\n", i, offset, value);
}
CMDQ_LOG("========= GPR dump ========= \n");
return;
}
void cmdq_test_setup(void)
{
/* unconditionally set CMDQ_SYNC_TOKEN_CONFIG_ALLOW and mutex STREAM_DONE */
/* so that DISPSYS scenarios may pass check. */
cmdqCoreSetEvent(CMDQ_SYNC_TOKEN_STREAM_EOF);
cmdqCoreSetEvent(CMDQ_EVENT_MUTEX0_STREAM_EOF);
cmdqCoreSetEvent(CMDQ_EVENT_MUTEX1_STREAM_EOF);
cmdqCoreSetEvent(CMDQ_EVENT_MUTEX2_STREAM_EOF);
cmdqCoreSetEvent(CMDQ_EVENT_MUTEX3_STREAM_EOF);
}
void cmdq_test_cleanup(void)
{
return; /* do nothing */
}
| DKingCN/android_kernel_jiayu_s3_h560 | drivers/misc/mediatek/cmdq/mt6752/cmdq_platform.c | C | gpl-2.0 | 23,146 |
/* Copyright (c) 2008-2013, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/err.h>
#include <linux/platform_device.h>
#include <linux/sched.h>
#include <linux/ratelimit.h>
#include <linux/workqueue.h>
#include <linux/pm_runtime.h>
#include <linux/diagchar.h>
#include <linux/delay.h>
#include <linux/reboot.h>
#include <linux/of.h>
#include <linux/kmemleak.h>
#ifdef CONFIG_DIAG_OVER_USB
#include <mach/usbdiag.h>
#endif
#include <mach/msm_smd.h>
#include <mach/socinfo.h>
#include <mach/restart.h>
#include "diagmem.h"
#include "diagchar.h"
#include "diagfwd.h"
#include "diagfwd_cntl.h"
#include "diagfwd_hsic.h"
#include "diagchar_hdlc.h"
#ifdef CONFIG_DIAG_SDIO_PIPE
#include "diagfwd_sdio.h"
#endif
#include "diag_dci.h"
#include "diag_masks.h"
#include "diagfwd_bridge.h"
#define MODE_CMD 41
#define RESET_ID 2
int diag_debug_buf_idx;
unsigned char diag_debug_buf[1024];
static unsigned int buf_tbl_size = 8; /*Number of entries in table of buffers */
struct diag_master_table entry;
struct diag_send_desc_type send = { NULL, NULL, DIAG_STATE_START, 0 };
struct diag_hdlc_dest_type enc = { NULL, NULL, 0 };
int wrap_enabled;
uint16_t wrap_count;
void encode_rsp_and_send(int buf_length)
{
struct diag_smd_info *data = &(driver->smd_data[MODEM_DATA]);
send.state = DIAG_STATE_START;
send.pkt = driver->apps_rsp_buf;
send.last = (void *)(driver->apps_rsp_buf + buf_length);
send.terminate = 1;
if (!data->in_busy_1) {
enc.dest = data->buf_in_1;
enc.dest_last = (void *)(data->buf_in_1 + APPS_BUF_SIZE - 1);
diag_hdlc_encode(&send, &enc);
data->write_ptr_1->buf = data->buf_in_1;
data->write_ptr_1->length = (int)(enc.dest -
(void *)(data->buf_in_1));
data->in_busy_1 = 1;
diag_device_write(data->buf_in_1, data->peripheral,
data->write_ptr_1);
memset(driver->apps_rsp_buf, '\0', APPS_BUF_SIZE);
}
}
/* Determine if this device uses a device tree */
#ifdef CONFIG_OF
static int has_device_tree(void)
{
struct device_node *node;
node = of_find_node_by_path("/");
if (node) {
of_node_put(node);
return 1;
}
return 0;
}
#else
static int has_device_tree(void)
{
return 0;
}
#endif
int chk_config_get_id(void)
{
/* For all Fusion targets, Modem will always be present */
if (machine_is_msm8x60_fusion() || machine_is_msm8x60_fusn_ffa())
return 0;
if (driver->use_device_tree) {
if (machine_is_msm8974())
return MSM8974_TOOLS_ID;
else
return 0;
} else {
switch (socinfo_get_msm_cpu()) {
case MSM_CPU_8X60:
return APQ8060_TOOLS_ID;
case MSM_CPU_8960:
case MSM_CPU_8960AB:
return AO8960_TOOLS_ID;
case MSM_CPU_8064:
case MSM_CPU_8064AB:
case MSM_CPU_8064AA:
return APQ8064_TOOLS_ID;
case MSM_CPU_8930:
case MSM_CPU_8930AA:
case MSM_CPU_8930AB:
return MSM8930_TOOLS_ID;
case MSM_CPU_8974:
return MSM8974_TOOLS_ID;
case MSM_CPU_8625:
return MSM8625_TOOLS_ID;
default:
return 0;
}
}
}
/*
* This will return TRUE for targets which support apps only mode and hence SSR.
* This applies to 8960 and newer targets.
*/
int chk_apps_only(void)
{
if (driver->use_device_tree)
return 1;
switch (socinfo_get_msm_cpu()) {
case MSM_CPU_8960:
case MSM_CPU_8960AB:
case MSM_CPU_8064:
case MSM_CPU_8064AB:
case MSM_CPU_8064AA:
case MSM_CPU_8930:
case MSM_CPU_8930AA:
case MSM_CPU_8930AB:
case MSM_CPU_8627:
case MSM_CPU_9615:
case MSM_CPU_8974:
return 1;
default:
return 0;
}
}
/*
* This will return TRUE for targets which support apps as master.
* Thus, SW DLOAD and Mode Reset are supported on apps processor.
* This applies to 8960 and newer targets.
*/
int chk_apps_master(void)
{
if (driver->use_device_tree)
return 1;
else if (soc_class_is_msm8960() || soc_class_is_msm8930() ||
soc_class_is_apq8064() || cpu_is_msm9615())
return 1;
else
return 0;
}
int chk_polling_response(void)
{
if (!(driver->polling_reg_flag) && chk_apps_master())
/*
* If the apps processor is master and no other processor
* has registered to respond for polling
*/
return 1;
else if (!(driver->smd_data[MODEM_DATA].ch) &&
!(chk_apps_master()))
/*
* If the apps processor is not the master and the modem
* is not up
*/
return 1;
else
return 0;
}
/*
* This function should be called if you feel that the logging process may
* need to be woken up. For instance, if the logging mode is MEMORY_DEVICE MODE
* and while trying to read data from a SMD data channel there are no buffers
* available to read the data into, then this function should be called to
* determine if the logging process needs to be woken up.
*/
void chk_logging_wakeup(void)
{
int i;
/* Find the index of the logging process */
for (i = 0; i < driver->num_clients; i++)
if (driver->client_map[i].pid ==
driver->logging_process_id)
break;
if (i < driver->num_clients) {
/* At very high logging rates a race condition can
* occur where the buffers containing the data from
* an smd channel are all in use, but the data_ready
* flag is cleared. In this case, the buffers never
* have their data read/logged. Detect and remedy this
* situation.
*/
if ((driver->data_ready[i] & USER_SPACE_DATA_TYPE) == 0) {
driver->data_ready[i] |= USER_SPACE_DATA_TYPE;
pr_debug("diag: Force wakeup of logging process\n");
wake_up_interruptible(&driver->wait_q);
}
}
}
/* Process the data read from the smd data channel */
int diag_process_smd_read_data(struct diag_smd_info *smd_info, void *buf,
int total_recd)
{
struct diag_request *write_ptr_modem = NULL;
int *in_busy_ptr = 0;
if (smd_info->buf_in_1 == buf) {
write_ptr_modem = smd_info->write_ptr_1;
in_busy_ptr = &smd_info->in_busy_1;
} else if (smd_info->buf_in_2 == buf) {
write_ptr_modem = smd_info->write_ptr_2;
in_busy_ptr = &smd_info->in_busy_2;
} else {
pr_err("diag: In %s, no match for in_busy_1\n", __func__);
}
if (write_ptr_modem) {
write_ptr_modem->length = total_recd;
*in_busy_ptr = 1;
diag_device_write(buf, smd_info->peripheral, write_ptr_modem);
}
return 0;
}
void diag_smd_send_req(struct diag_smd_info *smd_info)
{
void *buf = NULL, *temp_buf = NULL;
int total_recd = 0, r = 0, pkt_len;
int loop_count = 0;
int notify = 0;
if (!smd_info) {
pr_err("diag: In %s, no smd info. Not able to read.\n",
__func__);
return;
}
if (!smd_info->in_busy_1)
buf = smd_info->buf_in_1;
else if ((smd_info->type == SMD_DATA_TYPE) && !smd_info->in_busy_2)
buf = smd_info->buf_in_2;
if (smd_info->ch && buf) {
temp_buf = buf;
pkt_len = smd_cur_packet_size(smd_info->ch);
while (pkt_len && (pkt_len != total_recd)) {
loop_count++;
r = smd_read_avail(smd_info->ch);
pr_debug("diag: In %s, received pkt %d %d\n",
__func__, r, total_recd);
if (!r) {
/* Nothing to read from SMD */
wait_event(driver->smd_wait_q,
((smd_info->ch == 0) ||
smd_read_avail(smd_info->ch)));
/* If the smd channel is open */
if (smd_info->ch) {
pr_debug("diag: In %s, return from wait_event\n",
__func__);
continue;
} else {
pr_debug("diag: In %s, return from wait_event ch closed\n",
__func__);
return;
}
}
total_recd += r;
if (total_recd > IN_BUF_SIZE) {
if (total_recd < MAX_IN_BUF_SIZE) {
pr_err("diag: In %s, SMD sending in packets up to %d bytes\n",
__func__, total_recd);
buf = krealloc(buf, total_recd,
GFP_KERNEL);
} else {
pr_err("diag: In %s, SMD sending in packets more than %d bytes\n",
__func__, MAX_IN_BUF_SIZE);
return;
}
}
if (pkt_len < r) {
pr_err("diag: In %s, SMD sending incorrect pkt\n",
__func__);
return;
}
if (pkt_len > r) {
pr_err("diag: In %s, SMD sending partial pkt %d %d %d %d %d %d\n",
__func__, pkt_len, r, total_recd, loop_count,
smd_info->peripheral, smd_info->type);
}
/* keep reading for complete packet */
smd_read(smd_info->ch, temp_buf, r);
temp_buf += r;
}
if (total_recd > 0) {
if (!buf) {
pr_err("diag: Out of diagmem for Modem\n");
} else if (smd_info->process_smd_read_data) {
notify = smd_info->process_smd_read_data(
smd_info, buf, total_recd);
/* Poll SMD channels to check for data */
if (notify)
diag_smd_notify(smd_info,
SMD_EVENT_DATA);
}
}
} else if (smd_info->ch && !buf &&
(driver->logging_mode == MEMORY_DEVICE_MODE)) {
chk_logging_wakeup();
}
}
void diag_read_smd_work_fn(struct work_struct *work)
{
struct diag_smd_info *smd_info = container_of(work,
struct diag_smd_info,
diag_read_smd_work);
diag_smd_send_req(smd_info);
}
int diag_device_write(void *buf, int data_type, struct diag_request *write_ptr)
{
int i, err = 0, index;
index = 0;
if (driver->logging_mode == MEMORY_DEVICE_MODE) {
if (data_type == APPS_DATA) {
for (i = 0; i < driver->poolsize_write_struct; i++)
if (driver->buf_tbl[i].length == 0) {
driver->buf_tbl[i].buf = buf;
driver->buf_tbl[i].length =
driver->used;
#ifdef DIAG_DEBUG
pr_debug("diag: ENQUEUE buf ptr"
" and length is %x , %d\n",
(unsigned int)(driver->buf_
tbl[i].buf), driver->buf_tbl[i].length);
#endif
break;
}
}
#ifdef CONFIG_DIAGFWD_BRIDGE_CODE
else if (data_type == HSIC_DATA || data_type == HSIC_2_DATA) {
unsigned long flags;
int foundIndex = -1;
index = data_type - HSIC_DATA;
spin_lock_irqsave(&diag_hsic[index].hsic_spinlock,
flags);
for (i = 0; i < diag_hsic[index].poolsize_hsic_write;
i++) {
if (diag_hsic[index].hsic_buf_tbl[i].length
== 0) {
diag_hsic[index].hsic_buf_tbl[i].buf
= buf;
diag_hsic[index].hsic_buf_tbl[i].length
= diag_bridge[index].write_len;
diag_hsic[index].
num_hsic_buf_tbl_entries++;
foundIndex = i;
break;
}
}
spin_unlock_irqrestore(&diag_hsic[index].hsic_spinlock,
flags);
if (foundIndex == -1)
err = -1;
else
pr_debug("diag: ENQUEUE HSIC buf ptr and length is %x , %d, ch %d\n",
(unsigned int)buf,
diag_bridge[index].write_len, index);
}
#endif
for (i = 0; i < driver->num_clients; i++)
if (driver->client_map[i].pid ==
driver->logging_process_id)
break;
if (i < driver->num_clients) {
driver->data_ready[i] |= USER_SPACE_DATA_TYPE;
pr_debug("diag: wake up logging process\n");
wake_up_interruptible(&driver->wait_q);
} else
return -EINVAL;
} else if (driver->logging_mode == NO_LOGGING_MODE) {
if ((data_type >= 0) && (data_type < NUM_SMD_DATA_CHANNELS)) {
driver->smd_data[data_type].in_busy_1 = 0;
driver->smd_data[data_type].in_busy_2 = 0;
queue_work(driver->diag_wq,
&(driver->smd_data[data_type].
diag_read_smd_work));
}
#ifdef CONFIG_DIAG_SDIO_PIPE
else if (data_type == SDIO_DATA) {
driver->in_busy_sdio = 0;
queue_work(driver->diag_sdio_wq,
&(driver->diag_read_sdio_work));
}
#endif
#ifdef CONFIG_DIAGFWD_BRIDGE_CODE
else if (data_type == HSIC_DATA || data_type == HSIC_2_DATA) {
index = data_type - HSIC_DATA;
if (diag_hsic[index].hsic_ch)
queue_work(diag_bridge[index].wq,
&(diag_hsic[index].
diag_read_hsic_work));
}
#endif
err = -1;
}
#ifdef CONFIG_DIAG_OVER_USB
else if (driver->logging_mode == USB_MODE) {
if (data_type == APPS_DATA) {
driver->write_ptr_svc = (struct diag_request *)
(diagmem_alloc(driver, sizeof(struct diag_request),
POOL_TYPE_WRITE_STRUCT));
if (driver->write_ptr_svc) {
driver->write_ptr_svc->length = driver->used;
driver->write_ptr_svc->buf = buf;
err = usb_diag_write(driver->legacy_ch,
driver->write_ptr_svc);
} else
err = -1;
} else if ((data_type >= 0) &&
(data_type < NUM_SMD_DATA_CHANNELS)) {
write_ptr->buf = buf;
#ifdef DIAG_DEBUG
printk(KERN_INFO "writing data to USB,"
"pkt length %d\n", write_ptr->length);
print_hex_dump(KERN_DEBUG, "Written Packet Data to"
" USB: ", 16, 1, DUMP_PREFIX_ADDRESS,
buf, write_ptr->length, 1);
#endif /* DIAG DEBUG */
err = usb_diag_write(driver->legacy_ch, write_ptr);
}
#ifdef CONFIG_DIAG_SDIO_PIPE
else if (data_type == SDIO_DATA) {
if (machine_is_msm8x60_fusion() ||
machine_is_msm8x60_fusn_ffa()) {
write_ptr->buf = buf;
err = usb_diag_write(driver->mdm_ch, write_ptr);
} else
pr_err("diag: Incorrect sdio data "
"while USB write\n");
}
#endif
#ifdef CONFIG_DIAGFWD_BRIDGE_CODE
else if (data_type == HSIC_DATA || data_type == HSIC_2_DATA) {
index = data_type - HSIC_DATA;
if (diag_hsic[index].hsic_device_enabled) {
struct diag_request *write_ptr_mdm;
write_ptr_mdm = (struct diag_request *)
diagmem_alloc(driver,
sizeof(struct diag_request),
index +
POOL_TYPE_HSIC_WRITE);
if (write_ptr_mdm) {
write_ptr_mdm->buf = buf;
write_ptr_mdm->length =
diag_bridge[index].write_len;
write_ptr_mdm->context = (void *)index;
err = usb_diag_write(
diag_bridge[index].ch, write_ptr_mdm);
/* Return to the pool immediately */
if (err) {
diagmem_free(driver,
write_ptr_mdm,
index +
POOL_TYPE_HSIC_WRITE);
pr_err_ratelimited("diag: HSIC write failure, err: %d, ch %d\n",
err, index);
}
} else {
pr_err("diag: allocate write fail\n");
err = -1;
}
} else {
pr_err("diag: Incorrect HSIC data "
"while USB write\n");
err = -1;
}
} else if (data_type == SMUX_DATA) {
write_ptr->buf = buf;
write_ptr->context = (void *)SMUX;
pr_debug("diag: writing SMUX data\n");
err = usb_diag_write(diag_bridge[SMUX].ch,
write_ptr);
}
#endif
APPEND_DEBUG('d');
}
#endif /* DIAG OVER USB */
return err;
}
static void diag_update_pkt_buffer(unsigned char *buf)
{
unsigned char *ptr = driver->pkt_buf;
unsigned char *temp = buf;
mutex_lock(&driver->diagchar_mutex);
if (CHK_OVERFLOW(ptr, ptr, ptr + PKT_SIZE, driver->pkt_length))
memcpy(ptr, temp , driver->pkt_length);
else
printk(KERN_CRIT " Not enough buffer space for PKT_RESP\n");
mutex_unlock(&driver->diagchar_mutex);
}
void diag_update_userspace_clients(unsigned int type)
{
int i;
mutex_lock(&driver->diagchar_mutex);
for (i = 0; i < driver->num_clients; i++)
if (driver->client_map[i].pid != 0)
driver->data_ready[i] |= type;
wake_up_interruptible(&driver->wait_q);
mutex_unlock(&driver->diagchar_mutex);
}
void diag_update_sleeping_process(int process_id, int data_type)
{
int i;
mutex_lock(&driver->diagchar_mutex);
for (i = 0; i < driver->num_clients; i++)
if (driver->client_map[i].pid == process_id) {
driver->data_ready[i] |= data_type;
break;
}
wake_up_interruptible(&driver->wait_q);
mutex_unlock(&driver->diagchar_mutex);
}
static int diag_check_mode_reset(unsigned char *buf)
{
int is_mode_reset = 0;
if (chk_apps_master() && (int)(*(char *)buf) == MODE_CMD)
if ((int)(*(char *)(buf+1)) == RESET_ID)
is_mode_reset = 1;
return is_mode_reset;
}
void diag_send_data(struct diag_master_table entry, unsigned char *buf,
int len, int type)
{
driver->pkt_length = len;
if (entry.process_id != NON_APPS_PROC && type != MODEM_DATA) {
diag_update_pkt_buffer(buf);
diag_update_sleeping_process(entry.process_id, PKT_TYPE);
} else {
if (len > 0) {
if ((entry.client_id >= 0) &&
(entry.client_id < NUM_SMD_DATA_CHANNELS)) {
int index = entry.client_id;
if (driver->smd_data[index].ch) {
if ((index == MODEM_DATA) &&
diag_check_mode_reset(buf)) {
return;
}
smd_write(driver->smd_data[index].ch,
buf, len);
} else {
pr_err("diag: In %s, smd channel %d not open\n",
__func__, index);
}
} else {
pr_alert("diag: In %s, incorrect channel: %d",
__func__, entry.client_id);
}
}
}
}
static int diag_process_apps_pkt(unsigned char *buf, int len)
{
uint16_t subsys_cmd_code;
int subsys_id, ssid_first, ssid_last, ssid_range;
int packet_type = 1, i, cmd_code;
unsigned char *temp = buf;
int data_type;
int mask_ret;
#if defined(CONFIG_DIAG_OVER_USB)
unsigned char *ptr;
#endif
/* Check if the command is a supported mask command */
mask_ret = diag_process_apps_masks(buf, len);
if (mask_ret <= 0)
return mask_ret;
/* Check for registered clients and forward packet to apropriate proc */
cmd_code = (int)(*(char *)buf);
temp++;
subsys_id = (int)(*(char *)temp);
temp++;
subsys_cmd_code = *(uint16_t *)temp;
temp += 2;
data_type = APPS_DATA;
/* Dont send any command other than mode reset */
if (chk_apps_master() && cmd_code == MODE_CMD) {
if (subsys_id != RESET_ID)
data_type = MODEM_DATA;
}
pr_debug("diag: %d %d %d", cmd_code, subsys_id, subsys_cmd_code);
for (i = 0; i < diag_max_reg; i++) {
entry = driver->table[i];
if (entry.process_id != NO_PROCESS) {
if (entry.cmd_code == cmd_code && entry.subsys_id ==
subsys_id && entry.cmd_code_lo <=
subsys_cmd_code &&
entry.cmd_code_hi >= subsys_cmd_code) {
diag_send_data(entry, buf, len, data_type);
packet_type = 0;
} else if (entry.cmd_code == 255
&& cmd_code == 75) {
if (entry.subsys_id ==
subsys_id &&
entry.cmd_code_lo <=
subsys_cmd_code &&
entry.cmd_code_hi >=
subsys_cmd_code) {
diag_send_data(entry, buf, len,
data_type);
packet_type = 0;
}
} else if (entry.cmd_code == 255 &&
entry.subsys_id == 255) {
if (entry.cmd_code_lo <=
cmd_code &&
entry.
cmd_code_hi >= cmd_code) {
diag_send_data(entry, buf, len,
data_type);
packet_type = 0;
}
}
}
}
#if defined(CONFIG_DIAG_OVER_USB)
/* Check for the command/respond msg for the maximum packet length */
if ((*buf == 0x4b) && (*(buf+1) == 0x12) &&
(*(uint16_t *)(buf+2) == 0x0055)) {
for (i = 0; i < 4; i++)
*(driver->apps_rsp_buf+i) = *(buf+i);
*(uint32_t *)(driver->apps_rsp_buf+4) = PKT_SIZE;
encode_rsp_and_send(7);
return 0;
}
/* Check for Apps Only & get event mask request */
else if (!(driver->smd_data[MODEM_DATA].ch) && chk_apps_only() &&
*buf == 0x81) {
driver->apps_rsp_buf[0] = 0x81;
driver->apps_rsp_buf[1] = 0x0;
*(uint16_t *)(driver->apps_rsp_buf + 2) = 0x0;
*(uint16_t *)(driver->apps_rsp_buf + 4) = EVENT_LAST_ID + 1;
for (i = 0; i < EVENT_LAST_ID/8 + 1; i++)
*(unsigned char *)(driver->apps_rsp_buf + 6 + i) = 0x0;
encode_rsp_and_send(6 + EVENT_LAST_ID/8);
return 0;
}
/* Get log ID range & Check for Apps Only */
else if (!(driver->smd_data[MODEM_DATA].ch) && chk_apps_only()
&& (*buf == 0x73) && *(int *)(buf+4) == 1) {
driver->apps_rsp_buf[0] = 0x73;
*(int *)(driver->apps_rsp_buf + 4) = 0x1; /* operation ID */
*(int *)(driver->apps_rsp_buf + 8) = 0x0; /* success code */
*(int *)(driver->apps_rsp_buf + 12) = LOG_GET_ITEM_NUM(LOG_0);
*(int *)(driver->apps_rsp_buf + 16) = LOG_GET_ITEM_NUM(LOG_1);
*(int *)(driver->apps_rsp_buf + 20) = LOG_GET_ITEM_NUM(LOG_2);
*(int *)(driver->apps_rsp_buf + 24) = LOG_GET_ITEM_NUM(LOG_3);
*(int *)(driver->apps_rsp_buf + 28) = LOG_GET_ITEM_NUM(LOG_4);
*(int *)(driver->apps_rsp_buf + 32) = LOG_GET_ITEM_NUM(LOG_5);
*(int *)(driver->apps_rsp_buf + 36) = LOG_GET_ITEM_NUM(LOG_6);
*(int *)(driver->apps_rsp_buf + 40) = LOG_GET_ITEM_NUM(LOG_7);
*(int *)(driver->apps_rsp_buf + 44) = LOG_GET_ITEM_NUM(LOG_8);
*(int *)(driver->apps_rsp_buf + 48) = LOG_GET_ITEM_NUM(LOG_9);
*(int *)(driver->apps_rsp_buf + 52) = LOG_GET_ITEM_NUM(LOG_10);
*(int *)(driver->apps_rsp_buf + 56) = LOG_GET_ITEM_NUM(LOG_11);
*(int *)(driver->apps_rsp_buf + 60) = LOG_GET_ITEM_NUM(LOG_12);
*(int *)(driver->apps_rsp_buf + 64) = LOG_GET_ITEM_NUM(LOG_13);
*(int *)(driver->apps_rsp_buf + 68) = LOG_GET_ITEM_NUM(LOG_14);
*(int *)(driver->apps_rsp_buf + 72) = LOG_GET_ITEM_NUM(LOG_15);
encode_rsp_and_send(75);
return 0;
}
/* Respond to Get SSID Range request message */
else if (!(driver->smd_data[MODEM_DATA].ch) && chk_apps_only()
&& (*buf == 0x7d) && (*(buf+1) == 0x1)) {
driver->apps_rsp_buf[0] = 0x7d;
driver->apps_rsp_buf[1] = 0x1;
driver->apps_rsp_buf[2] = 0x1;
driver->apps_rsp_buf[3] = 0x0;
/* -1 to un-account for OEM SSID range */
*(int *)(driver->apps_rsp_buf + 4) = MSG_MASK_TBL_CNT - 1;
*(uint16_t *)(driver->apps_rsp_buf + 8) = MSG_SSID_0;
*(uint16_t *)(driver->apps_rsp_buf + 10) = MSG_SSID_0_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 12) = MSG_SSID_1;
*(uint16_t *)(driver->apps_rsp_buf + 14) = MSG_SSID_1_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 16) = MSG_SSID_2;
*(uint16_t *)(driver->apps_rsp_buf + 18) = MSG_SSID_2_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 20) = MSG_SSID_3;
*(uint16_t *)(driver->apps_rsp_buf + 22) = MSG_SSID_3_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 24) = MSG_SSID_4;
*(uint16_t *)(driver->apps_rsp_buf + 26) = MSG_SSID_4_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 28) = MSG_SSID_5;
*(uint16_t *)(driver->apps_rsp_buf + 30) = MSG_SSID_5_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 32) = MSG_SSID_6;
*(uint16_t *)(driver->apps_rsp_buf + 34) = MSG_SSID_6_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 36) = MSG_SSID_7;
*(uint16_t *)(driver->apps_rsp_buf + 38) = MSG_SSID_7_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 40) = MSG_SSID_8;
*(uint16_t *)(driver->apps_rsp_buf + 42) = MSG_SSID_8_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 44) = MSG_SSID_9;
*(uint16_t *)(driver->apps_rsp_buf + 46) = MSG_SSID_9_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 48) = MSG_SSID_10;
*(uint16_t *)(driver->apps_rsp_buf + 50) = MSG_SSID_10_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 52) = MSG_SSID_11;
*(uint16_t *)(driver->apps_rsp_buf + 54) = MSG_SSID_11_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 56) = MSG_SSID_12;
*(uint16_t *)(driver->apps_rsp_buf + 58) = MSG_SSID_12_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 60) = MSG_SSID_13;
*(uint16_t *)(driver->apps_rsp_buf + 62) = MSG_SSID_13_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 64) = MSG_SSID_14;
*(uint16_t *)(driver->apps_rsp_buf + 66) = MSG_SSID_14_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 68) = MSG_SSID_15;
*(uint16_t *)(driver->apps_rsp_buf + 70) = MSG_SSID_15_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 72) = MSG_SSID_16;
*(uint16_t *)(driver->apps_rsp_buf + 74) = MSG_SSID_16_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 76) = MSG_SSID_17;
*(uint16_t *)(driver->apps_rsp_buf + 78) = MSG_SSID_17_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 80) = MSG_SSID_18;
*(uint16_t *)(driver->apps_rsp_buf + 82) = MSG_SSID_18_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 84) = MSG_SSID_19;
*(uint16_t *)(driver->apps_rsp_buf + 86) = MSG_SSID_19_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 88) = MSG_SSID_20;
*(uint16_t *)(driver->apps_rsp_buf + 90) = MSG_SSID_20_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 92) = MSG_SSID_21;
*(uint16_t *)(driver->apps_rsp_buf + 94) = MSG_SSID_21_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 96) = MSG_SSID_22;
*(uint16_t *)(driver->apps_rsp_buf + 98) = MSG_SSID_22_LAST;
encode_rsp_and_send(99);
return 0;
}
/* Check for Apps Only Respond to Get Subsys Build mask */
else if (!(driver->smd_data[MODEM_DATA].ch) && chk_apps_only()
&& (*buf == 0x7d) && (*(buf+1) == 0x2)) {
ssid_first = *(uint16_t *)(buf + 2);
ssid_last = *(uint16_t *)(buf + 4);
ssid_range = 4 * (ssid_last - ssid_first + 1);
/* frame response */
driver->apps_rsp_buf[0] = 0x7d;
driver->apps_rsp_buf[1] = 0x2;
*(uint16_t *)(driver->apps_rsp_buf + 2) = ssid_first;
*(uint16_t *)(driver->apps_rsp_buf + 4) = ssid_last;
driver->apps_rsp_buf[6] = 0x1;
driver->apps_rsp_buf[7] = 0x0;
ptr = driver->apps_rsp_buf + 8;
/* bld time masks */
switch (ssid_first) {
case MSG_SSID_0:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_0[i/4];
break;
case MSG_SSID_1:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_1[i/4];
break;
case MSG_SSID_2:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_2[i/4];
break;
case MSG_SSID_3:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_3[i/4];
break;
case MSG_SSID_4:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_4[i/4];
break;
case MSG_SSID_5:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_5[i/4];
break;
case MSG_SSID_6:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_6[i/4];
break;
case MSG_SSID_7:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_7[i/4];
break;
case MSG_SSID_8:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_8[i/4];
break;
case MSG_SSID_9:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_9[i/4];
break;
case MSG_SSID_10:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_10[i/4];
break;
case MSG_SSID_11:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_11[i/4];
break;
case MSG_SSID_12:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_12[i/4];
break;
case MSG_SSID_13:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_13[i/4];
break;
case MSG_SSID_14:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_14[i/4];
break;
case MSG_SSID_15:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_15[i/4];
break;
case MSG_SSID_16:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_16[i/4];
break;
case MSG_SSID_17:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_17[i/4];
break;
case MSG_SSID_18:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_18[i/4];
break;
case MSG_SSID_19:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_19[i/4];
break;
case MSG_SSID_20:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_20[i/4];
break;
case MSG_SSID_21:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_21[i/4];
break;
case MSG_SSID_22:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_22[i/4];
break;
}
encode_rsp_and_send(8 + ssid_range - 1);
return 0;
}
/* Check for download command */
else if ((cpu_is_msm8x60() || chk_apps_master()) && (*buf == 0x3A)) {
/* send response back */
driver->apps_rsp_buf[0] = *buf;
encode_rsp_and_send(0);
msleep(5000);
/* call download API */
msm_set_restart_mode(RESTART_DLOAD);
printk(KERN_CRIT "diag: download mode set, Rebooting SoC..\n");
kernel_restart(NULL);
/* Not required, represents that command isnt sent to modem */
return 0;
}
/* Check for polling for Apps only DIAG */
else if ((*buf == 0x4b) && (*(buf+1) == 0x32) &&
(*(buf+2) == 0x03)) {
/* If no one has registered for polling */
if (chk_polling_response()) {
/* Respond to polling for Apps only DIAG */
for (i = 0; i < 3; i++)
driver->apps_rsp_buf[i] = *(buf+i);
for (i = 0; i < 13; i++)
driver->apps_rsp_buf[i+3] = 0;
encode_rsp_and_send(15);
return 0;
}
}
/* Return the Delayed Response Wrap Status */
else if ((*buf == 0x4b) && (*(buf+1) == 0x32) &&
(*(buf+2) == 0x04) && (*(buf+3) == 0x0)) {
memcpy(driver->apps_rsp_buf, buf, 4);
driver->apps_rsp_buf[4] = wrap_enabled;
encode_rsp_and_send(4);
return 0;
}
/* Wrap the Delayed Rsp ID */
else if ((*buf == 0x4b) && (*(buf+1) == 0x32) &&
(*(buf+2) == 0x05) && (*(buf+3) == 0x0)) {
wrap_enabled = true;
memcpy(driver->apps_rsp_buf, buf, 4);
driver->apps_rsp_buf[4] = wrap_count;
encode_rsp_and_send(5);
return 0;
}
/* Check for ID for NO MODEM present */
else if (chk_polling_response()) {
/* respond to 0x0 command */
if (*buf == 0x00) {
for (i = 0; i < 55; i++)
driver->apps_rsp_buf[i] = 0;
encode_rsp_and_send(54);
return 0;
}
/* respond to 0x7c command */
else if (*buf == 0x7c) {
driver->apps_rsp_buf[0] = 0x7c;
for (i = 1; i < 8; i++)
driver->apps_rsp_buf[i] = 0;
/* Tools ID for APQ 8060 */
*(int *)(driver->apps_rsp_buf + 8) =
chk_config_get_id();
*(unsigned char *)(driver->apps_rsp_buf + 12) = '\0';
*(unsigned char *)(driver->apps_rsp_buf + 13) = '\0';
encode_rsp_and_send(13);
return 0;
}
}
#endif
return packet_type;
}
#ifdef CONFIG_DIAG_OVER_USB
void diag_send_error_rsp(int index)
{
int i;
if (index > 490) {
pr_err("diag: error response too huge, aborting\n");
return;
}
driver->apps_rsp_buf[0] = 0x13; /* error code 13 */
for (i = 0; i < index; i++)
driver->apps_rsp_buf[i+1] = *(driver->hdlc_buf+i);
encode_rsp_and_send(index - 3);
}
#else
static inline void diag_send_error_rsp(int index) {}
#endif
void diag_process_hdlc(void *data, unsigned len)
{
struct diag_hdlc_decode_type hdlc;
int ret, type = 0;
pr_debug("diag: HDLC decode fn, len of data %d\n", len);
hdlc.dest_ptr = driver->hdlc_buf;
hdlc.dest_size = USB_MAX_OUT_BUF;
hdlc.src_ptr = data;
hdlc.src_size = len;
hdlc.src_idx = 0;
hdlc.dest_idx = 0;
hdlc.escaping = 0;
ret = diag_hdlc_decode(&hdlc);
if (hdlc.dest_idx < 3) {
pr_err("diag: Integer underflow in hdlc processing\n");
return;
}
if (ret) {
type = diag_process_apps_pkt(driver->hdlc_buf,
hdlc.dest_idx - 3);
if (type < 0)
return;
} else if (driver->debug_flag) {
printk(KERN_ERR "Packet dropped due to bad HDLC coding/CRC"
" errors or partial packet received, packet"
" length = %d\n", len);
print_hex_dump(KERN_DEBUG, "Dropped Packet Data: ", 16, 1,
DUMP_PREFIX_ADDRESS, data, len, 1);
driver->debug_flag = 0;
}
/* send error responses from APPS for Central Routing */
if (type == 1 && chk_apps_only()) {
diag_send_error_rsp(hdlc.dest_idx);
type = 0;
}
/* implies this packet is NOT meant for apps */
if (!(driver->smd_data[MODEM_DATA].ch) && type == 1) {
if (chk_apps_only()) {
diag_send_error_rsp(hdlc.dest_idx);
} else { /* APQ 8060, Let Q6 respond */
if (driver->smd_data[LPASS_DATA].ch)
smd_write(driver->smd_data[LPASS_DATA].ch,
driver->hdlc_buf,
hdlc.dest_idx - 3);
}
type = 0;
}
#ifdef DIAG_DEBUG
pr_debug("diag: hdlc.dest_idx = %d", hdlc.dest_idx);
for (i = 0; i < hdlc.dest_idx; i++)
printk(KERN_DEBUG "\t%x", *(((unsigned char *)
driver->hdlc_buf)+i));
#endif /* DIAG DEBUG */
/* ignore 2 bytes for CRC, one for 7E and send */
if ((driver->smd_data[MODEM_DATA].ch) && (ret) && (type) &&
(hdlc.dest_idx > 3)) {
APPEND_DEBUG('g');
smd_write(driver->smd_data[MODEM_DATA].ch,
driver->hdlc_buf, hdlc.dest_idx - 3);
APPEND_DEBUG('h');
#ifdef DIAG_DEBUG
printk(KERN_INFO "writing data to SMD, pkt length %d\n", len);
print_hex_dump(KERN_DEBUG, "Written Packet Data to SMD: ", 16,
1, DUMP_PREFIX_ADDRESS, data, len, 1);
#endif /* DIAG DEBUG */
}
}
#ifdef CONFIG_DIAG_OVER_USB
/* 2+1 for modem ; 2 for LPASS ; 1 for WCNSS */
#define N_LEGACY_WRITE (driver->poolsize + 6)
#define N_LEGACY_READ 1
int diagfwd_connect(void)
{
int err;
int i;
printk(KERN_DEBUG "diag: USB connected\n");
err = usb_diag_alloc_req(driver->legacy_ch, N_LEGACY_WRITE,
N_LEGACY_READ);
if (err)
printk(KERN_ERR "diag: unable to alloc USB req on legacy ch");
driver->usb_connected = 1;
for (i = 0; i < NUM_SMD_DATA_CHANNELS; i++) {
driver->smd_data[i].in_busy_1 = 0;
driver->smd_data[i].in_busy_2 = 0;
/* Poll SMD data channels to check for data */
queue_work(driver->diag_wq,
&(driver->smd_data[i].diag_read_smd_work));
/* Poll SMD CNTL channels to check for data */
diag_smd_notify(&(driver->smd_cntl[i]), SMD_EVENT_DATA);
}
/* Poll USB channel to check for data*/
queue_work(driver->diag_wq, &(driver->diag_read_work));
#ifdef CONFIG_DIAG_SDIO_PIPE
if (machine_is_msm8x60_fusion() || machine_is_msm8x60_fusn_ffa()) {
if (driver->mdm_ch && !IS_ERR(driver->mdm_ch))
diagfwd_connect_sdio();
else
printk(KERN_INFO "diag: No USB MDM ch");
}
#endif
return 0;
}
int diagfwd_disconnect(void)
{
int i;
printk(KERN_DEBUG "diag: USB disconnected\n");
driver->usb_connected = 0;
driver->debug_flag = 1;
usb_diag_free_req(driver->legacy_ch);
if (driver->logging_mode == USB_MODE) {
for (i = 0; i < NUM_SMD_DATA_CHANNELS; i++) {
driver->smd_data[i].in_busy_1 = 1;
driver->smd_data[i].in_busy_2 = 1;
}
}
#ifdef CONFIG_DIAG_SDIO_PIPE
if (machine_is_msm8x60_fusion() || machine_is_msm8x60_fusn_ffa())
if (driver->mdm_ch && !IS_ERR(driver->mdm_ch))
diagfwd_disconnect_sdio();
#endif
/* TBD - notify and flow control SMD */
return 0;
}
int diagfwd_write_complete(struct diag_request *diag_write_ptr)
{
unsigned char *buf = diag_write_ptr->buf;
int found_it = 0;
int i;
/* Determine if the write complete is for data from modem/apps/q6 */
/* Need a context variable here instead */
for (i = 0; i < NUM_SMD_DATA_CHANNELS; i++) {
struct diag_smd_info *data = &(driver->smd_data[i]);
if (buf == (void *)data->buf_in_1) {
data->in_busy_1 = 0;
queue_work(driver->diag_wq,
&(data->diag_read_smd_work));
found_it = 1;
break;
} else if (buf == (void *)data->buf_in_2) {
data->in_busy_2 = 0;
queue_work(driver->diag_wq,
&(data->diag_read_smd_work));
found_it = 1;
break;
}
}
#ifdef CONFIG_DIAG_SDIO_PIPE
if (!found_it) {
if (buf == (void *)driver->buf_in_sdio) {
if (machine_is_msm8x60_fusion() ||
machine_is_msm8x60_fusn_ffa())
diagfwd_write_complete_sdio();
else
pr_err("diag: Incorrect buffer pointer while WRITE");
found_it = 1;
}
}
#endif
if (!found_it) {
diagmem_free(driver, (unsigned char *)buf,
POOL_TYPE_HDLC);
diagmem_free(driver, (unsigned char *)diag_write_ptr,
POOL_TYPE_WRITE_STRUCT);
}
return 0;
}
int diagfwd_read_complete(struct diag_request *diag_read_ptr)
{
int status = diag_read_ptr->status;
unsigned char *buf = diag_read_ptr->buf;
/* Determine if the read complete is for data on legacy/mdm ch */
if (buf == (void *)driver->usb_buf_out) {
driver->read_len_legacy = diag_read_ptr->actual;
APPEND_DEBUG('s');
#ifdef DIAG_DEBUG
printk(KERN_INFO "read data from USB, pkt length %d",
diag_read_ptr->actual);
print_hex_dump(KERN_DEBUG, "Read Packet Data from USB: ", 16, 1,
DUMP_PREFIX_ADDRESS, diag_read_ptr->buf,
diag_read_ptr->actual, 1);
#endif /* DIAG DEBUG */
if (driver->logging_mode == USB_MODE) {
if (status != -ECONNRESET && status != -ESHUTDOWN)
queue_work(driver->diag_wq,
&(driver->diag_proc_hdlc_work));
else
queue_work(driver->diag_wq,
&(driver->diag_read_work));
}
}
#ifdef CONFIG_DIAG_SDIO_PIPE
else if (buf == (void *)driver->usb_buf_mdm_out) {
if (machine_is_msm8x60_fusion() ||
machine_is_msm8x60_fusn_ffa()) {
driver->read_len_mdm = diag_read_ptr->actual;
diagfwd_read_complete_sdio();
} else
pr_err("diag: Incorrect buffer pointer while READ");
}
#endif
else
printk(KERN_ERR "diag: Unknown buffer ptr from USB");
return 0;
}
void diag_read_work_fn(struct work_struct *work)
{
APPEND_DEBUG('d');
driver->usb_read_ptr->buf = driver->usb_buf_out;
driver->usb_read_ptr->length = USB_MAX_OUT_BUF;
usb_diag_read(driver->legacy_ch, driver->usb_read_ptr);
APPEND_DEBUG('e');
}
void diag_process_hdlc_fn(struct work_struct *work)
{
APPEND_DEBUG('D');
diag_process_hdlc(driver->usb_buf_out, driver->read_len_legacy);
diag_read_work_fn(work);
APPEND_DEBUG('E');
}
void diag_usb_legacy_notifier(void *priv, unsigned event,
struct diag_request *d_req)
{
switch (event) {
case USB_DIAG_CONNECT:
diagfwd_connect();
break;
case USB_DIAG_DISCONNECT:
diagfwd_disconnect();
break;
case USB_DIAG_READ_DONE:
diagfwd_read_complete(d_req);
break;
case USB_DIAG_WRITE_DONE:
diagfwd_write_complete(d_req);
break;
default:
printk(KERN_ERR "Unknown event from USB diag\n");
break;
}
}
#endif /* DIAG OVER USB */
void diag_smd_notify(void *ctxt, unsigned event)
{
struct diag_smd_info *smd_info = (struct diag_smd_info *)ctxt;
if (!smd_info)
return;
if (event == SMD_EVENT_CLOSE) {
smd_info->ch = 0;
wake_up(&driver->smd_wait_q);
if (smd_info->type == SMD_DATA_TYPE) {
smd_info->notify_context = event;
queue_work(driver->diag_cntl_wq,
&(smd_info->diag_notify_update_smd_work));
} else if (smd_info->type == SMD_DCI_TYPE) {
/* Notify the clients of the close */
diag_dci_notify_client(smd_info->peripheral_mask,
DIAG_STATUS_CLOSED);
}
return;
} else if (event == SMD_EVENT_OPEN) {
if (smd_info->ch_save)
smd_info->ch = smd_info->ch_save;
if (smd_info->type == SMD_CNTL_TYPE) {
smd_info->notify_context = event;
queue_work(driver->diag_cntl_wq,
&(smd_info->diag_notify_update_smd_work));
} else if (smd_info->type == SMD_DCI_TYPE) {
smd_info->notify_context = event;
queue_work(driver->diag_dci_wq,
&(smd_info->diag_notify_update_smd_work));
/* Notify the clients of the open */
diag_dci_notify_client(smd_info->peripheral_mask,
DIAG_STATUS_OPEN);
}
}
wake_up(&driver->smd_wait_q);
if (smd_info->type == SMD_DCI_TYPE)
queue_work(driver->diag_dci_wq,
&(smd_info->diag_read_smd_work));
else
queue_work(driver->diag_wq, &(smd_info->diag_read_smd_work));
}
static int diag_smd_probe(struct platform_device *pdev)
{
int r = 0;
int index = -1;
if (pdev->id == SMD_APPS_MODEM) {
index = MODEM_DATA;
r = smd_open("DIAG", &driver->smd_data[index].ch,
&driver->smd_data[index],
diag_smd_notify);
driver->smd_data[index].ch_save =
driver->smd_data[index].ch;
}
#if defined(CONFIG_MSM_N_WAY_SMD)
if (pdev->id == SMD_APPS_QDSP) {
index = LPASS_DATA;
r = smd_named_open_on_edge("DIAG", SMD_APPS_QDSP,
&driver->smd_data[index].ch,
&driver->smd_data[index],
diag_smd_notify);
driver->smd_data[index].ch_save =
driver->smd_data[index].ch;
}
#endif
if (pdev->id == SMD_APPS_WCNSS) {
index = WCNSS_DATA;
r = smd_named_open_on_edge("APPS_RIVA_DATA",
SMD_APPS_WCNSS,
&driver->smd_data[index].ch,
&driver->smd_data[index],
diag_smd_notify);
driver->smd_data[index].ch_save =
driver->smd_data[index].ch;
}
pm_runtime_set_active(&pdev->dev);
pm_runtime_enable(&pdev->dev);
pr_debug("diag: open SMD port, Id = %d, r = %d\n", pdev->id, r);
return 0;
}
static int diag_smd_runtime_suspend(struct device *dev)
{
dev_dbg(dev, "pm_runtime: suspending...\n");
return 0;
}
static int diag_smd_runtime_resume(struct device *dev)
{
dev_dbg(dev, "pm_runtime: resuming...\n");
return 0;
}
static const struct dev_pm_ops diag_smd_dev_pm_ops = {
.runtime_suspend = diag_smd_runtime_suspend,
.runtime_resume = diag_smd_runtime_resume,
};
static struct platform_driver msm_smd_ch1_driver = {
.probe = diag_smd_probe,
.driver = {
.name = "DIAG",
.owner = THIS_MODULE,
.pm = &diag_smd_dev_pm_ops,
},
};
static struct platform_driver diag_smd_lite_driver = {
.probe = diag_smd_probe,
.driver = {
.name = "APPS_RIVA_DATA",
.owner = THIS_MODULE,
.pm = &diag_smd_dev_pm_ops,
},
};
void diag_smd_destructor(struct diag_smd_info *smd_info)
{
if (smd_info->ch)
smd_close(smd_info->ch);
smd_info->ch = 0;
smd_info->ch_save = 0;
kfree(smd_info->buf_in_1);
kfree(smd_info->buf_in_2);
kfree(smd_info->write_ptr_1);
kfree(smd_info->write_ptr_2);
}
int diag_smd_constructor(struct diag_smd_info *smd_info, int peripheral,
int type)
{
smd_info->peripheral = peripheral;
smd_info->type = type;
switch (peripheral) {
case MODEM_DATA:
smd_info->peripheral_mask = DIAG_CON_MPSS;
break;
case LPASS_DATA:
smd_info->peripheral_mask = DIAG_CON_LPASS;
break;
case WCNSS_DATA:
smd_info->peripheral_mask = DIAG_CON_WCNSS;
break;
default:
pr_err("diag: In %s, unknown peripheral, peripheral: %d\n",
__func__, peripheral);
goto err;
}
smd_info->ch = 0;
smd_info->ch_save = 0;
if (smd_info->buf_in_1 == NULL) {
smd_info->buf_in_1 = kzalloc(IN_BUF_SIZE, GFP_KERNEL);
if (smd_info->buf_in_1 == NULL)
goto err;
kmemleak_not_leak(smd_info->buf_in_1);
}
if (smd_info->write_ptr_1 == NULL) {
smd_info->write_ptr_1 = kzalloc(sizeof(struct diag_request),
GFP_KERNEL);
if (smd_info->write_ptr_1 == NULL)
goto err;
kmemleak_not_leak(smd_info->write_ptr_1);
}
/* The smd data type needs two buffers */
if (smd_info->type == SMD_DATA_TYPE) {
if (smd_info->buf_in_2 == NULL) {
smd_info->buf_in_2 = kzalloc(IN_BUF_SIZE, GFP_KERNEL);
if (smd_info->buf_in_2 == NULL)
goto err;
kmemleak_not_leak(smd_info->buf_in_2);
}
if (smd_info->write_ptr_2 == NULL) {
smd_info->write_ptr_2 =
kzalloc(sizeof(struct diag_request),
GFP_KERNEL);
if (smd_info->write_ptr_2 == NULL)
goto err;
kmemleak_not_leak(smd_info->write_ptr_2);
}
}
INIT_WORK(&(smd_info->diag_read_smd_work), diag_read_smd_work_fn);
/*
* The update function assigned to the diag_notify_update_smd_work
* work_struct is meant to be used for updating that is not to
* be done in the context of the smd notify function. The
* notify_context variable can be used for passing additional
* information to the update function.
*/
smd_info->notify_context = 0;
if (type == SMD_DATA_TYPE)
INIT_WORK(&(smd_info->diag_notify_update_smd_work),
diag_clean_reg_fn);
else if (type == SMD_CNTL_TYPE)
INIT_WORK(&(smd_info->diag_notify_update_smd_work),
diag_mask_update_fn);
else if (type == SMD_DCI_TYPE)
INIT_WORK(&(smd_info->diag_notify_update_smd_work),
diag_update_smd_dci_work_fn);
else {
pr_err("diag: In %s, unknown type, type: %d\n", __func__, type);
goto err;
}
/*
* Set function ptr for function to call to process the data that
* was just read from the smd channel
*/
if (type == SMD_DATA_TYPE)
smd_info->process_smd_read_data = diag_process_smd_read_data;
else if (type == SMD_CNTL_TYPE)
smd_info->process_smd_read_data =
diag_process_smd_cntl_read_data;
else if (type == SMD_DCI_TYPE)
smd_info->process_smd_read_data =
diag_process_smd_dci_read_data;
else {
pr_err("diag: In %s, unknown type, type: %d\n", __func__, type);
goto err;
}
return 1;
err:
kfree(smd_info->buf_in_1);
kfree(smd_info->buf_in_2);
kfree(smd_info->write_ptr_1);
kfree(smd_info->write_ptr_2);
return 0;
}
void diagfwd_init(void)
{
int success;
int i;
wrap_enabled = 0;
wrap_count = 0;
diag_debug_buf_idx = 0;
driver->read_len_legacy = 0;
driver->use_device_tree = has_device_tree();
mutex_init(&driver->diag_cntl_mutex);
success = diag_smd_constructor(&driver->smd_data[MODEM_DATA],
MODEM_DATA, SMD_DATA_TYPE);
if (!success)
goto err;
success = diag_smd_constructor(&driver->smd_data[LPASS_DATA],
LPASS_DATA, SMD_DATA_TYPE);
if (!success)
goto err;
success = diag_smd_constructor(&driver->smd_data[WCNSS_DATA],
WCNSS_DATA, SMD_DATA_TYPE);
if (!success)
goto err;
if (driver->usb_buf_out == NULL &&
(driver->usb_buf_out = kzalloc(USB_MAX_OUT_BUF,
GFP_KERNEL)) == NULL)
goto err;
kmemleak_not_leak(driver->usb_buf_out);
if (driver->hdlc_buf == NULL
&& (driver->hdlc_buf = kzalloc(HDLC_MAX, GFP_KERNEL)) == NULL)
goto err;
kmemleak_not_leak(driver->hdlc_buf);
if (driver->user_space_data == NULL)
driver->user_space_data = kzalloc(USER_SPACE_DATA, GFP_KERNEL);
if (driver->user_space_data == NULL)
goto err;
kmemleak_not_leak(driver->user_space_data);
if (driver->client_map == NULL &&
(driver->client_map = kzalloc
((driver->num_clients) * sizeof(struct diag_client_map),
GFP_KERNEL)) == NULL)
goto err;
kmemleak_not_leak(driver->client_map);
if (driver->buf_tbl == NULL)
driver->buf_tbl = kzalloc(buf_tbl_size *
sizeof(struct diag_write_device), GFP_KERNEL);
if (driver->buf_tbl == NULL)
goto err;
kmemleak_not_leak(driver->buf_tbl);
if (driver->data_ready == NULL &&
(driver->data_ready = kzalloc(driver->num_clients * sizeof(int)
, GFP_KERNEL)) == NULL)
goto err;
kmemleak_not_leak(driver->data_ready);
if (driver->table == NULL &&
(driver->table = kzalloc(diag_max_reg*
sizeof(struct diag_master_table),
GFP_KERNEL)) == NULL)
goto err;
kmemleak_not_leak(driver->table);
if (driver->usb_read_ptr == NULL) {
driver->usb_read_ptr = kzalloc(
sizeof(struct diag_request), GFP_KERNEL);
if (driver->usb_read_ptr == NULL)
goto err;
kmemleak_not_leak(driver->usb_read_ptr);
}
if (driver->pkt_buf == NULL &&
(driver->pkt_buf = kzalloc(PKT_SIZE,
GFP_KERNEL)) == NULL)
goto err;
kmemleak_not_leak(driver->pkt_buf);
if (driver->apps_rsp_buf == NULL) {
driver->apps_rsp_buf = kzalloc(APPS_BUF_SIZE, GFP_KERNEL);
if (driver->apps_rsp_buf == NULL)
goto err;
kmemleak_not_leak(driver->apps_rsp_buf);
}
driver->diag_wq = create_singlethread_workqueue("diag_wq");
#ifdef CONFIG_DIAG_OVER_USB
INIT_WORK(&(driver->diag_proc_hdlc_work), diag_process_hdlc_fn);
INIT_WORK(&(driver->diag_read_work), diag_read_work_fn);
driver->legacy_ch = usb_diag_open(DIAG_LEGACY, driver,
diag_usb_legacy_notifier);
if (IS_ERR(driver->legacy_ch)) {
printk(KERN_ERR "Unable to open USB diag legacy channel\n");
goto err;
}
#endif
platform_driver_register(&msm_smd_ch1_driver);
platform_driver_register(&diag_smd_lite_driver);
return;
err:
pr_err("diag: Could not initialize diag buffers");
for (i = 0; i < NUM_SMD_DATA_CHANNELS; i++)
diag_smd_destructor(&driver->smd_data[i]);
kfree(driver->buf_msg_mask_update);
kfree(driver->buf_log_mask_update);
kfree(driver->buf_event_mask_update);
kfree(driver->usb_buf_out);
kfree(driver->hdlc_buf);
kfree(driver->client_map);
kfree(driver->buf_tbl);
kfree(driver->data_ready);
kfree(driver->table);
kfree(driver->pkt_buf);
kfree(driver->usb_read_ptr);
kfree(driver->apps_rsp_buf);
kfree(driver->user_space_data);
if (driver->diag_wq)
destroy_workqueue(driver->diag_wq);
}
void diagfwd_exit(void)
{
int i;
for (i = 0; i < NUM_SMD_DATA_CHANNELS; i++)
diag_smd_destructor(&driver->smd_data[i]);
#ifdef CONFIG_DIAG_OVER_USB
if (driver->usb_connected)
usb_diag_free_req(driver->legacy_ch);
usb_diag_close(driver->legacy_ch);
#endif
platform_driver_unregister(&msm_smd_ch1_driver);
platform_driver_unregister(&msm_diag_dci_driver);
platform_driver_unregister(&diag_smd_lite_driver);
kfree(driver->buf_msg_mask_update);
kfree(driver->buf_log_mask_update);
kfree(driver->buf_event_mask_update);
kfree(driver->usb_buf_out);
kfree(driver->hdlc_buf);
kfree(driver->client_map);
kfree(driver->buf_tbl);
kfree(driver->data_ready);
kfree(driver->table);
kfree(driver->pkt_buf);
kfree(driver->usb_read_ptr);
kfree(driver->apps_rsp_buf);
kfree(driver->user_space_data);
destroy_workqueue(driver->diag_wq);
}
| paul-xxx/kernel_sony_fuji-3.7 | drivers/char/diag/diagfwd.c | C | gpl-2.0 | 47,466 |
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2002-2006 Donald N. Allingham
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
#-------------------------------------------------------------------------
#
# Standard Python modules
#
#-------------------------------------------------------------------------
from ....const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
#-------------------------------------------------------------------------
#
# GRAMPS modules
#
#-------------------------------------------------------------------------
from .. import HasGrampsId
#-------------------------------------------------------------------------
#
# HasIdOf
#
#-------------------------------------------------------------------------
class HasIdOf(HasGrampsId):
"""Rule that checks for a person with a specific GRAMPS ID"""
name = _('Person with <Id>')
description = _("Matches person with a specified Gramps ID")
| pmghalvorsen/gramps_branch | gramps/gen/filters/rules/person/_hasidof.py | Python | gpl-2.0 | 1,631 |
/*
* Copyright (c) 1998-2012 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Resin Open Source is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.quercus.expr;
import java.io.IOException;
import java.util.ArrayList;
import com.caucho.quercus.Location;
import com.caucho.quercus.env.Env;
import com.caucho.quercus.env.MethodIntern;
import com.caucho.quercus.env.NullValue;
import com.caucho.quercus.env.StringValue;
import com.caucho.quercus.env.QuercusClass;
import com.caucho.quercus.env.Value;
import com.caucho.quercus.env.Var;
import com.caucho.quercus.parser.QuercusParser;
import com.caucho.util.L10N;
/**
* Represents a PHP static field reference.
*/
public class ClassVirtualFieldExpr extends AbstractVarExpr {
private static final L10N L = new L10N(ClassVirtualFieldExpr.class);
protected final StringValue _varName;
public ClassVirtualFieldExpr(String varName)
{
_varName = MethodIntern.intern(varName);
}
//
// function call creation
//
/**
* Creates a function call expression
*/
@Override
public Expr createCall(QuercusParser parser,
Location location,
ArrayList<Expr> args)
throws IOException
{
ExprFactory factory = parser.getExprFactory();
Expr var = parser.createVar(_varName.toString());
return factory.createClassVirtualMethodCall(location, var, args);
}
/**
* Evaluates the expression.
*
* @param env the calling environment.
*
* @return the expression value.
*/
@Override
public Value eval(Env env)
{
Value qThis = env.getThis();
QuercusClass qClass = qThis != null ? qThis.getQuercusClass() : null;
if (qClass == null) {
env.error(L.l("No calling class found for '{0}'", this));
return NullValue.NULL;
}
return qClass.getStaticFieldValue(env, _varName);
}
/**
* Evaluates the expression.
*
* @param env the calling environment.
*
* @return the expression value.
*/
@Override
public Var evalVar(Env env)
{
Value qThis = env.getThis();
QuercusClass qClass = qThis != null ? qThis.getQuercusClass() : null;
if (qClass == null) {
env.error(L.l("No calling class found for '{0}'", this));
return NullValue.NULL.toVar();
}
return qClass.getStaticFieldVar(env, _varName);
}
/**
* Evaluates the expression.
*
* @param env the calling environment.
*
* @return the expression value.
*/
@Override
public Value evalAssignRef(Env env, Value value)
{
Value qThis = env.getThis();
QuercusClass qClass = qThis != null ? qThis.getQuercusClass() : null;
if (qClass == null) {
env.error(L.l("No calling class found for '{0}'", this));
return NullValue.NULL.toVar();
}
return qClass.setStaticFieldRef(env, _varName, value);
}
/**
* Evaluates the expression.
*
* @param env the calling environment.
*
* @return the expression value.
*/
public void evalUnset(Env env)
{
env.error(getLocation(),
L.l("{0}::${1}: Cannot unset static variables.",
env.getCallingClass().getName(), _varName));
}
public String toString()
{
return "static::$" + _varName;
}
}
| dwango/quercus | src/main/java/com/caucho/quercus/expr/ClassVirtualFieldExpr.java | Java | gpl-2.0 | 4,206 |
#include "punchestableview.h"
#include <qf/core/log.h>
#include <QDrag>
#include <QDragEnterEvent>
#include <QMimeData>
#include <QPainter>
#include <QPixmap>
PunchesTableView::PunchesTableView(QWidget *parent)
: Super(parent)
{
setDropIndicatorShown(false);
}
bool PunchesTableView::edit(const QModelIndex &index, QAbstractItemView::EditTrigger trigger, QEvent *event)
{
Q_UNUSED(event)
if(trigger == QAbstractItemView::EditTrigger::DoubleClicked
|| trigger == QAbstractItemView::EditTrigger::EditKeyPressed) {
qf::core::utils::TableRow row = tableRow(index.row());
int class_id = row.value("classes.id").toInt();
int code = row.value("punches.code").toInt();
qfDebug() << "codeClassActivated:" << class_id << code;
emit codeClassActivated(class_id, code);
}
return false;
}
/*
void PunchesTableView::mousePressEvent(QMouseEvent *event)
{
qfInfo() << Q_FUNC_INFO;
QModelIndex ix = indexAt(event->pos());
if (!ix.isValid())
return;
qf::core::utils::TableRow row = tableRow(ix.row());
QString class_name = row.value(QStringLiteral("classes.name")).toString();
int code = row.value(QStringLiteral("punches.code")).toInt();
QByteArray item_data;
QDataStream data_stream(&item_data, QIODevice::WriteOnly);
data_stream << ix.row() << ix.column();
QMimeData *mime_data = new QMimeData;
mime_data->setData("application/x-quickevent", item_data);
QDrag *drag = new QDrag(this);
drag->setMimeData(mime_data);
//drag->setPixmap(pixmap);
//drag->setHotSpot(event->pos() - child->pos());
QPixmap px{QSize{10, 10}};
QPainter painter;
QFont f = font();
QFontMetrics fm(f, &px);
QString s = QString("%1 - %2").arg(class_name).arg(code);
QRect bounding_rect = fm.boundingRect(s);
static constexpr int inset = 5;
bounding_rect.adjust(-inset, -inset, inset, inset);
px = QPixmap{bounding_rect.size()};
painter.begin(&px);
painter.setFont(f);
//painter.setPen(Qt::black);
//painter.setBrush(Qt::black);
painter.fillRect(px.rect(), QColor("khaki"));
painter.drawRect(QRect(QPoint(), bounding_rect.size() - QSize(1, 1)));
painter.drawText(QPoint{inset, inset + fm.ascent()}, s);
painter.end();
drag->setPixmap(px);
if (drag->exec(Qt::CopyAction | Qt::MoveAction, Qt::CopyAction) == Qt::MoveAction) {
//child->close();
} else {
//child->show();
//child->setPixmap(pixmap);
}
}
void PunchesTableView::dragEnterEvent(QDragEnterEvent *event)
{
if (event->mimeData()->hasFormat("application/x-quickevent")) {
if (event->source() == this) {
event->setDropAction(Qt::MoveAction);
event->accept();
} else {
event->acceptProposedAction();
}
} else {
event->ignore();
}
}
void PunchesTableView::dragMoveEvent(QDragMoveEvent *event)
{
if (event->mimeData()->hasFormat("application/x-quickevent")) {
if (event->source() == this) {
event->setDropAction(Qt::MoveAction);
event->accept();
} else {
event->acceptProposedAction();
}
} else {
event->ignore();
}
}
*/
| arnost00/quickbox | quickevent/app/quickevent/plugins/Speaker/src/punchestableview.cpp | C++ | gpl-2.0 | 2,945 |
// prng.cpp or pseudo-random number generator (prng)
// Generates some pseudo-random numbers.
#include <iostream>
#include <iomanip>
using std::cout; // iostream
using std::endl;
using std::setw; // iomanip
// function generates random number
unsigned pseudoRNG() {
static unsigned seed = 5493; // some (any) initial starting seed; initialized only once!
// Take the current seed and generate new value from it
// Due to larg numbers used to generate numbers is difficult to
// predict next value from previous one.
// Static keyword has program scope and is terminated at the end of
// program. Seed value is stored every time in memory using previous
// value.
seed = (3852591 * seed + 5180347);
// return value between 0 and 65535
return (seed % 65535);
}
int main()
{
// generate 100 random numbers - print in separate fields
for (int i = 1; i <= 100; i++) {
cout << setw(8) << pseudoRNG();
// new line every fifth number
if (i % 5 == 0)
cout << endl;
}
return 0;
}
| Grayninja/General | Programming/C++/5.Control_Flow/5.9-random-number-generation/prng.cpp | C++ | gpl-2.0 | 1,000 |
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class System
{
function System()
{
if (!isset($this->CI))
{
$this->CI =& get_instance();
}
$this->settings_table = 'settings';
$this->template_table = 'templates';
$this->languages_table = 'languages';
$this->CI->config->set_item('language', $this->get_default_language());
$this->get_site_info();
}
function get_default_template()
{
$this->CI->db->select('path');
$this->CI->db->where('is_default', '1');
$query = $this->CI->db->get($this->template_table, 1);
if ($query->num_rows() == 1)
{
$row = $query->row_array();
}
return $row['path'];
}
function get_default_language()
{
$this->CI->db->select('language');
$this->CI->db->where('is_default', '1');
$query = $this->CI->db->get($this->languages_table, 1);
if ($query->num_rows() == 1)
{
$row = $query->row_array();
}
return $row['language'];
}
function get_site_info()
{
$this->CI->db->select('blog_title, blog_description, meta_keywords, allow_registrations, enable_rss, enable_atom, links_per_box, months_per_archive');
$this->CI->db->where('id', '1');
$query = $this->CI->db->get($this->settings_table, 1);
if ($query->num_rows() == 1)
{
$result = $query->row_array();
foreach ($result as $key => $value)
{
$this->settings[$key] = $value;
}
}
}
function check_site_status()
{
$this->CI->db->select('enabled, offline_reason');
$this->CI->db->where('id', '1');
$query = $this->CI->db->get($this->settings_table, 1);
if ($query->num_rows() == 1)
{
$result = $query->row_array();
if ($result['enabled'] == 0)
{
echo lang('site_disabled') . "<br />";
echo lang('reason') . " <strong>" . $result['offline_reason'] . "</strong>";
die();
}
}
}
function load($page, $data = null, $admin = false)
{
$data['page'] = $page;
if ($admin == true)
{
$this->CI->load->view('admin/layout/container', $data);
}
else
{
$template = $this->get_default_template();
$this->CI->load->view('templates/' . $template . '/layout/container', $data);
}
}
function load_normal($page, $data = null)
{
$template = $this->get_default_template();
$this->CI->load->view('templates/' . $template . '/layout/pages/' . $page, $data);
}
}
/* End of file System.php */
/* Location: ./application/libraries/System.php */ | JasonBaier/Open-Blog | application/libraries/System.php | PHP | gpl-3.0 | 2,540 |
import string
import socket
import base64
import sys
class message:
def __init__(self, name="generate" ):
if name == "generate":
self.name=socket.gethostname()
else:
self.name=name
self.type="gc"
self.decoded=""
def set ( self, content=" " ):
base64content = base64.b64encode ( content )
self.decoded="piratebox;"+ self.type + ";01;" + self.name + ";" + base64content
def get ( self ):
# TODO Split decoded part
message_parts = string.split ( self.decoded , ";" )
if message_parts[0] != "piratebox":
return None
b64_content_part = message_parts[4]
content = base64.b64decode ( b64_content_part )
return content
def get_sendername (self):
return self.name
def get_message ( self ):
return self.decoded
def set_message ( self , decoded):
self.decoded = decoded
class shoutbox_message(message):
def __init__(self, name="generate" ):
message.__init__( self , name)
self.type="sb"
| LibraryBox-Dev/LibraryBox-core | piratebox_origin/piratebox/piratebox/python_lib/messages.py | Python | gpl-3.0 | 1,109 |
\documentclass{article}
\begin{filecontents}{mybib.bib}
\begin{document}
here is some text
more text
here
\end{document}
\end{filecontents}
\begin{filecontents}{another.bib}
\begin{document}
some more text
more text
here
\end{document}
\end{filecontents}
\begin{document}
\begin{myotherenvironment}
some text goes here
some text goes here
some text goes here
some text goes here
\end{myotherenvironment}
\end{document}
| cmhughes/latexindent.pl | test-cases/filecontents/filecontents1.tex | TeX | gpl-3.0 | 454 |
using System;
using Server;
using Server.Items;
namespace Server.Mobiles
{
public class Kurlem : BaseCreature
{
[Constructable]
public Kurlem()
: base( AIType.AI_Melee, FightMode.Aggressor, 22, 1, 0.2, 1.0 )
{
Name = "Kurlem";
Title = "the Caretaker";
Race = Race.Gargoyle;
Blessed = true;
Hue = 0x86DF;
HairItemID = 0x4258;
HairHue = 0x31C;
AddItem( new GargishLeatherArms() );
AddItem( new GargishFancyRobe( 0x3B3 ) );
}
public override bool CanTeach { get { return false; } }
public Kurlem( Serial serial )
: base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
/*int version = */
reader.ReadInt();
}
}
} | greeduomacro/xrunuo | Scripts/Distro/Mobiles/Townfolk/Holy City/Kurlem.cs | C# | gpl-3.0 | 917 |
package instance
import (
"encoding/json"
)
// ID is the identifier for an instance.
type ID string
// Description contains details about an instance.
type Description struct {
ID ID
LogicalID *LogicalID
Tags map[string]string
}
// LogicalID is the logical identifier to associate with an instance.
type LogicalID string
// Attachment is an identifier for a resource to attach to an instance.
type Attachment struct {
// ID is the unique identifier for the attachment.
ID string
// Type is the kind of attachment. This allows multiple attachments of different types, with the supported
// types defined by the plugin.
Type string
}
// Spec is a specification of an instance to be provisioned
type Spec struct {
// Properties is the opaque instance plugin configuration.
Properties *json.RawMessage
// Tags are metadata that describes an instance.
Tags map[string]string
// Init is the boot script to execute when the instance is created.
Init string
// LogicalID is the logical identifier assigned to this instance, which may be absent.
LogicalID *LogicalID
// Attachments are instructions for external entities that should be attached to the instance.
Attachments []Attachment
}
| anarcher/infrakit.gcp | vendor/github.com/docker/infrakit/pkg/spi/instance/types.go | GO | gpl-3.0 | 1,223 |
#ifndef _XmDataF_h
#define _XmDataF_h
#include <Xm/Xm.h>
#include <Xm/TextF.h>
#include <Xm/Ext.h>
#if defined(__cplusplus)
extern "C" {
#endif
typedef struct _XmDataFieldClassRec *XmDataFieldWidgetClass;
typedef struct _XmDataFieldRec *XmDataFieldWidget;
/* Function Name: XmCreateDataField
* Description: Creation Routine for UIL and ADA.
* Arguments: parent - the parent widget.
* name - the name of the widget.
* args, num_args - the number and list of args.
* Returns: The Widget created.
*/
Widget XmCreateDataField(
#ifndef _NO_PROTO
Widget, String, ArgList, Cardinal
#endif
);
/*
* Variable argument list functions
*/
extern Widget XmVaCreateDataField(
Widget parent,
char *name,
...);
extern Widget XmVaCreateManagedDataField(
Widget parent,
char *name,
...);
Boolean _XmDataFieldReplaceText(
#ifndef _NO_PROTO
XmDataFieldWidget, XEvent*, XmTextPosition, XmTextPosition, char*, int, Boolean
#endif
);
void XmDataFieldSetString(
#ifndef _NO_PROTO
Widget, char*
#endif
);
extern char * XmDataFieldGetString(
#ifndef _NO_PROTO
Widget
#endif
);
extern wchar_t * XmDataFieldGetStringWcs(
#ifndef _NO_PROTO
Widget
#endif
);
void _XmDataFieldSetClipRect(
#ifndef _NO_PROTO
XmDataFieldWidget
#endif
);
void _XmDataFieldDrawInsertionPoint(
#ifndef _NO_PROTO
XmDataFieldWidget, Boolean
#endif
);
void XmDataFieldSetHighlight(
#ifndef _NO_PROTO
Widget, XmTextPosition, XmTextPosition, XmHighlightMode
#endif
);
void XmDataFieldSetAddMode(
#ifndef _NO_PROTO
Widget, Boolean
#endif
);
char * XmDataFieldGetSelection(
#ifndef _NO_PROTO
Widget
#endif
);
void XmDataFieldSetSelection(
#ifndef _NO_PROTO
Widget, XmTextPosition, XmTextPosition, Time
#endif
);
void _XmDataFieldSetSel2(
#ifndef _NO_PROTO
Widget, XmTextPosition, XmTextPosition, Boolean, Time
#endif
);
Boolean XmDataFieldGetSelectionPosition(
#ifndef _NO_PROTO
Widget, XmTextPosition *, XmTextPosition *
#endif
);
XmTextPosition XmDataFieldXYToPos(
#ifndef _NO_PROTO
Widget, Position, Position
#endif
);
void XmDataFieldShowPosition(
#ifndef _NO_PROTO
Widget, XmTextPosition
#endif
);
Boolean XmDataFieldCut(
#ifndef _NO_PROTO
Widget, Time
#endif
);
Boolean XmDataFieldCopy(
#ifndef _NO_PROTO
Widget, Time
#endif
);
Boolean XmDataFieldPaste(
#ifndef _NO_PROTO
Widget
#endif
);
void XmDataFieldSetEditable(
#ifndef _NO_PROTO
Widget, Boolean
#endif
);
void XmDataFieldSetInsertionPosition(
#ifndef _NO_PROTO
Widget, XmTextPosition
#endif
);
extern WidgetClass xmDataFieldWidgetClass;
typedef struct _XmDataFieldCallbackStruct {
Widget w; /* The XmDataField */
String text; /* Proposed string */
Boolean accept; /* Accept return value, for validation */
} XmDataFieldCallbackStruct;
#if defined(__cplusplus)
} /* extern "C" */
#endif
#endif /* _XmDataF_h */
| CPFDSoftware-Tony/gmv | utils/OpenMotif/openMotif-2.3.3/lib/Xm/DataF.h | C | gpl-3.0 | 2,978 |
#ifndef OFP_VERSION_H
#define OFP_VERSION_H 1
#include <openflow/openflow-common.h>
#include "util.h"
#include "openvswitch/ofp-util.h"
#define OFP_VERSION_LONG_OPTIONS \
{"version", no_argument, NULL, 'V'}, \
{"protocols", required_argument, NULL, 'O'}
#define OFP_VERSION_OPTION_HANDLERS \
case 'V': \
ovs_print_version(OFP10_VERSION, OFP13_VERSION); \
exit(EXIT_SUCCESS); \
\
case 'O': \
set_allowed_ofp_versions(optarg); \
break;
uint32_t get_allowed_ofp_versions(void);
void set_allowed_ofp_versions(const char *string);
void mask_allowed_ofp_versions(uint32_t);
void add_allowed_ofp_versions(uint32_t);
void ofp_version_usage(void);
#endif
| ejschiller/FLEX | ovs/lib/ofp-version-opt.h | C | gpl-3.0 | 1,018 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright © 2014 René Samselnig
#
# This file is part of Database Navigator.
#
# Database Navigator is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Database Navigator is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Database Navigator. If not, see <http://www.gnu.org/licenses/>.
#
import sys
import re
import codecs
from collections import Counter
filename = sys.argv[1]
with codecs.open(filename, encoding='utf-8') as f:
text = f.read()
m = re.findall(r'^#{2,3} .*$', text, re.MULTILINE)
def title(s):
return re.sub(r'#+ ', '', s)
def fragment(s):
return '#' + re.sub(r'[^a-z-]', '', re.sub(r'#+ ', '', s).replace(' ', '-').lower())
def depth(s):
return len(re.match(r'(#*)', s).group(0))
c = Counter()
toc = []
for header in m:
t = title(header)
f = fragment(header)
d = depth(header)
if c[f] > 0:
toc.append('{}- [{}]({}-{})'.format('\t'*(d-2), t, f, c[f]))
else:
toc.append('{}- [{}]({})'.format('\t'*(d-2), t, f))
c[f] += 1
with codecs.open(filename, 'w', encoding='utf-8') as f:
f.write(text.replace('[TOC]', '\n'.join(toc)))
| resamsel/dbmanagr | scripts/toc.py | Python | gpl-3.0 | 1,614 |
# -*- coding: utf-8 -*-
"""
pygments.plugin
~~~~~~~~~~~~~~~
Pygments setuptools plugin interface. The methods defined
here also work if setuptools isn't installed but they just
return nothing.
lexer plugins::
[pygments.lexers]
yourlexer = yourmodule:YourLexer
formatter plugins::
[pygments.formatters]
yourformatter = yourformatter:YourFormatter
/.ext = yourformatter:YourFormatter
As you can see, you can define extensions for the formatter
with a leading slash.
syntax plugins::
[pygments.styles]
yourstyle = yourstyle:YourStyle
filter plugin::
[pygments.filter]
yourfilter = yourfilter:YourFilter
:copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from __future__ import unicode_literals
try:
import pkg_resources
except ImportError:
pkg_resources = None
LEXER_ENTRY_POINT = 'pygments.lexers'
FORMATTER_ENTRY_POINT = 'pygments.formatters'
STYLE_ENTRY_POINT = 'pygments.styles'
FILTER_ENTRY_POINT = 'pygments.filters'
def find_plugin_lexers():
if pkg_resources is None:
return
for entrypoint in pkg_resources.iter_entry_points(LEXER_ENTRY_POINT):
yield entrypoint.load()
def find_plugin_formatters():
if pkg_resources is None:
return
for entrypoint in pkg_resources.iter_entry_points(FORMATTER_ENTRY_POINT):
yield entrypoint.name, entrypoint.load()
def find_plugin_styles():
if pkg_resources is None:
return
for entrypoint in pkg_resources.iter_entry_points(STYLE_ENTRY_POINT):
yield entrypoint.name, entrypoint.load()
def find_plugin_filters():
if pkg_resources is None:
return
for entrypoint in pkg_resources.iter_entry_points(FILTER_ENTRY_POINT):
yield entrypoint.name, entrypoint.load()
| davy39/eric | ThirdParty/Pygments/pygments/plugin.py | Python | gpl-3.0 | 1,903 |
/*QMainWindow, QMenuBar, QToolBar, QPushButton {
background-color: #000000;
color: #ffffff;
}
QDockWidget::title, QDockWidget::float-button, QDockWidget::close-button {
background-color: #999999;
color: #ffffff;
}*/
/****************************************************/
/* http://tech-artists.org/forum/showthread.php?2359-Release-Qt-dark-orange-stylesheet */
QToolTip
{
border: 1px solid black;
background-color: %ACCENT3%;
/*padding: 2px;*/
/*border-radius: 3px;*/
opacity: 100;
color: black;
}
QWidget
{
color: #c0c0c0;
background-color: #323232;
}
QWidget:item:hover
{
background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 %ACCENT3%, stop: 1 %ACCENT4%);
color: #000000;
}
QWidget:item:selected
{
background-color: %ACCENT2%; /*QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 %ACCENT3%, stop: 1 %ACCENT2%);*/
}
QDockWidget {
border: 5px solid black;
}
/* MENUS */
/***********************************************/
QMenuBar::item
{
background: transparent;
}
QMenuBar::item:selected
{
background: transparent;
border: 1px solid %ACCENT%;
}
QMenuBar::item:pressed
{
background: #444;
border: 1px solid #000;
background-color: QLinearGradient(
x1:0, y1:0,
x2:0, y2:1,
stop:1 #212121,
stop:0.4 #343434/*,
stop:0.2 #343434,
stop:0.1 %ACCENT%*/
);
margin-bottom:-1px;
padding-bottom:1px;
}
QMenu
{
border: 1px solid #000;
}
QMenu::item
{
padding: 2px 20px 2px 20px;
}
QMenu::item:selected
{
color: #000000;
}
QWidget:disabled
{
color: #808080;
/*background-color: #606060;*/
}
QAbstractItemView
{
background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #4d4d4d, stop: 0.1 #646464, stop: 1 #5d5d5d);
}
QWidget:focus
{
/*border: 2px solid QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 %ACCENT3%, stop: 1 %ACCENT2%);*/
}
QLineEdit
{
background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #4d4d4d, stop: 0 #646464, stop: 1 #5d5d5d);
padding: 1px;
border-style: solid;
border: 1px solid #1e1e1e;
border-radius: 5;
}
/* CONTROLS */
/***********************************************/
QPushButton
{
/*color: #b1b1b1;*/
background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #565656, stop: 0.1 #525252, stop: 0.5 #4e4e4e, stop: 0.9 #4a4a4a, stop: 1 #464646);
border-width: 1px;
border-color: #1e1e1e;
border-style: solid;
/*border-radius: 6;*/
/*font-size: 12px;*/
/*padding: 5px;*/
/*padding-left: 5px;
padding-right: 5px;*/
}
QPushButton:pressed
{
background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #2d2d2d, stop: 0.1 #2b2b2b, stop: 0.5 #292929, stop: 0.9 #282828, stop: 1 #252525);
}
QPushButton:checked
{
background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #2d2d2d, stop: 0.1 #2b2b2b, stop: 0.5 #292929, stop: 0.9 #282828, stop: 1 #252525);
}
QComboBox
{
selection-background-color: %ACCENT%;
background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #565656, stop: 0.1 #525252, stop: 0.5 #4e4e4e, stop: 0.9 #4a4a4a, stop: 1 #464646);
border-style: solid;
border: 1px solid #1e1e1e;
/*border-radius: 5;*/
}
QComboBox:hover,QPushButton:hover
{
border: 1px solid QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 %ACCENT3%, stop: 1 %ACCENT2%);
}
QComboBox:on
{
padding-top: 3px;
padding-left: 4px;
background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #2d2d2d, stop: 0.1 #2b2b2b, stop: 0.5 #292929, stop: 0.9 #282828, stop: 1 #252525);
selection-background-color: %ACCENT%;
}
QComboBox QAbstractItemView
{
border: 1px solid darkgray;
selection-background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 %ACCENT3%, stop: 1 %ACCENT2%);
selection-color: #000000;
}
QComboBox::drop-down
{
subcontrol-origin: padding;
subcontrol-position: top right;
width: 15px;
border-left-width: 0px;
border-left-color: darkgray;
border-left-style: solid;
/*border-top-right-radius: 3px;
border-bottom-right-radius: 3px;*/
}
QComboBox::down-arrow
{
image: url(:/icons/down_arrow.png);
}
QGroupBox:focus
{
border: 1px solid QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 %ACCENT3%, stop: 1 %ACCENT2%);
}
QTextEdit:focus
{
border: 1px solid QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 %ACCENT3%, stop: 1 %ACCENT2%);
}
/* SCROLL BAR */
/***********************************************/
QScrollBar:horizontal {
border: 1px solid #222222;
background: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0.0 #121212, stop: 0.2 #282828, stop: 1 #484848);
height: 20px;
margin: 0px 16px 0 16px;
}
QScrollBar::handle:horizontal
{
background: QLinearGradient( x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 %ACCENT3%, stop: 0.5 %ACCENT2%, stop: 1 %ACCENT3%);
min-height: 20px;
border-radius: 2px;
}
QScrollBar::add-line:horizontal {
border: 1px solid #1b1b19;
border-radius: 2px;
background: QLinearGradient( x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 %ACCENT3%, stop: 1 %ACCENT2%);
width: 14px;
subcontrol-position: right;
subcontrol-origin: margin;
}
QScrollBar::sub-line:horizontal {
border: 1px solid #1b1b19;
border-radius: 2px;
background: QLinearGradient( x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 %ACCENT3%, stop: 1 %ACCENT2%);
width: 14px;
subcontrol-position: left;
subcontrol-origin: margin;
}
/*
QScrollBar::right-arrow:horizontal, QScrollBar::left-arrow:horizontal
{
border: 1px solid black;
width: 10px;
height: 10px;
background: white;
}*/
QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal
{
background: none;
}
QScrollBar:vertical
{
background: QLinearGradient( x1: 0, y1: 0, x2: 1, y2: 0, stop: 0.0 #121212, stop: 0.2 #282828, stop: 1 #484848);
width: 20px;
margin: 16px 0 16px 0;
border: 1px solid #222222;
}
QScrollBar::handle:vertical
{
background: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 %ACCENT3%, stop: 0.5 %ACCENT2%, stop: 1 %ACCENT3%);
min-height: 20px;
border-radius: 2px;
}
QScrollBar::add-line:vertical
{
border: 1px solid #1b1b19;
border-radius: 2px;
background: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 %ACCENT3%, stop: 1 %ACCENT2%);
height: 14px;
subcontrol-position: bottom;
subcontrol-origin: margin;
}
QScrollBar::sub-line:vertical
{
border: 1px solid #1b1b19;
border-radius: 2px;
background: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 %ACCENT2%, stop: 1 %ACCENT3%);
height: 14px;
subcontrol-position: top;
subcontrol-origin: margin;
}
QScrollBar::add-line:vertical:hover,
QScrollBar::sub-line:vertical:hover,
QScrollBar::add-line:horizontal:hover,
QScrollBar::sub-line:horizontal:hover
{
background-color: #909090;
}
QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical
{
image: url(':/icons/up.png');
}
QScrollBar::down-arrow:vertical, QScrollBar::down-arrow:vertical
{
image: url(':/icons/down.png');
}
QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical
{
background: none;
}
/* TEXT */
/***********************************************/
QTextEdit
{
background-color: #242424;
font-family: "Courier New";
}
QPlainTextEdit
{
background-color: #242424;
font-family: "Courier New";
}
QHeaderView::section
{
background-color: QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:0 #616161, stop: 0.5 #505050, stop: 0.6 #434343, stop:1 #656565);
color: #b1b1b1;
padding-left: 4px;
border: 1px solid #6c6c6c;
}
QCheckBox:disabled
{
color: #414141;
}
/* DOCK WIDGET */
/***********************************************/
QDockWidget::title
{
text-align: center;
spacing: 3px; /* spacing between items in the tool bar */
border-color: #343434;
/*background-color: QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:0 #323232, stop: 0.5 #242424, stop:1 #323232);*/
}
QDockWidget::close-button, QDockWidget::float-button
{
/*text-align: center;*/
/*spacing: 10px;*/
background-color: #707070;
}
QDockWidget::close-button:hover, QDockWidget::float-button:hover
{
/*background: #242424;*/
background-color: #b1b1b1;
border: none;
}
/*
QDockWidget::close-button:pressed, QDockWidget::float-button:pressed
{
padding: 1px -1px -1px 1px;
}
*/
QMainWindow::separator
{
background-color: QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:0 #161616, stop: 0.5 #151515, stop: 0.6 #212121, stop:1 #343434);
color: white;
padding-left: 4px;
border: 1px solid #4c4c4c;
spacing: 3px; /* spacing between items in the tool bar */
}
QMainWindow::separator:hover
{
background-color: QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:0 %ACCENT2%, stop:0.5 %ACCENT4% stop:1 %ACCENT3%);
color: white;
padding-left: 4px;
border: 1px solid #6c6c6c;
spacing: 3px; /* spacing between items in the tool bar */
}
QToolBar
{
border-color: #323232;
}
QToolBar::handle
{
spacing: 3px; /* spacing between items in the tool bar */
background: url(':/icons/handle.png');
}
QToolButton:hover
{
background-color: #202020;
}
QMenu::separator
{
height: 2px;
background-color: QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:0 #161616, stop: 0.5 #151515, stop: 0.6 #212121, stop:1 #343434);
color: white;
padding-left: 4px;
margin-left: 10px;
margin-right: 5px;
}
QProgressBar
{
border: 2px solid grey;
/*border-radius: 5px;*/
text-align: center;
}
QProgressBar::chunk
{
background-color: %ACCENT2%;
width: 2.15px;
margin: 0.5px;
}
QTabBar::tab {
color: #b1b1b1;
border: 1px solid #444;
border-bottom-style: none;
background-color: #323232;
padding-left: 10px;
padding-right: 10px;
padding-top: 3px;
padding-bottom: 2px;
margin-right: -1px;
}
QTabWidget::pane {
border: 1px solid #444;
top: 1px;
}
QTabBar::tab:last
{
margin-right: 0; /* the last selected tab has nothing to overlap with on the right */
border-top-right-radius: 3px;
}
QTabBar::tab:first:!selected
{
margin-left: 0px; /* the last selected tab has nothing to overlap with on the right */
border-top-left-radius: 3px;
}
QTabBar::tab:!selected
{
color: #b1b1b1;
border-bottom-style: solid;
margin-top: 3px;
background-color: QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:1 #212121, stop:.4 #343434);
}
QTabBar::tab:selected
{
border-top-left-radius: 3px;
border-top-right-radius: 3px;
margin-bottom: 0px;
}
QTabBar::tab:!selected:hover
{
/*border-top: 2px solid %ACCENT%;
padding-bottom: 3px;*/
border-top-left-radius: 3px;
border-top-right-radius: 3px;
background-color: QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:1 #212121, stop:0.4 #343434, stop:0.2 #343434, stop:0.1 %ACCENT%);
}
QRadioButton::indicator:checked, QRadioButton::indicator:unchecked{
color: #b1b1b1;
background-color: #323232;
border: 1px solid #b1b1b1;
border-radius: 6px;
}
QRadioButton::indicator:checked
{
background-color: qradialgradient(
cx: 0.5, cy: 0.5,
fx: 0.5, fy: 0.5,
radius: 1.0,
stop: 0.25 %ACCENT%,
stop: 0.3 #323232
);
}
QCheckBox::indicator{
color: #b1b1b1;
background-color: #323232;
border: 1px solid #b1b1b1;
width: 9px;
height: 9px;
}
QRadioButton::indicator
{
border-radius: 6px;
}
QRadioButton::indicator:hover, QCheckBox::indicator:hover
{
border: 1px solid %ACCENT%;
}
QCheckBox::indicator:checked
{
image:url(:/icons/checkbox.png);
}
QCheckBox::indicator:disabled, QRadioButton::indicator:disabled
{
border: 1px solid #444;
}
/****************************************************/
QStatusBar::item
{
border: none;
}
QTreeView {
background-color: #000000;
/*color: #b1b1b1;*/
}
QTreeView::item {
/*color: #b1b1b1;*/
}
QTreeView::item:hover {
background-color: #7a7a7a;
color: #000000;
}
QTreeView::item:selected {
background-color: #b1b1b1;
color: #000000;
}
| DavidTingley/ephys-processing-pipeline | installation/klustaviewa-0.3.0/klustaviewa/gui/styles.css | CSS | gpl-3.0 | 12,907 |
/* YUI 3.9.0pr1 (build 202) Copyright 2013 Yahoo! Inc. http://yuilibrary.com/license/ */
YUI.add("lang/dial",function(e){e.Intl.add("dial","",{label:"My label",resetStr:"Reset",tooltipHandle:"Drag to set value"})},"3.9.0pr1");
| rochestb/Adventurly | node_modules/grunt-contrib-yuidoc/node_modules/yuidocjs/node_modules/yui/dial/lang/dial.js | JavaScript | gpl-3.0 | 227 |
package com.amaze.filemanager.filesystem;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.provider.DocumentFile;
import com.amaze.filemanager.exceptions.RootNotPermittedException;
import com.amaze.filemanager.utils.DataUtils;
import com.amaze.filemanager.utils.cloud.CloudUtil;
import com.amaze.filemanager.utils.Logger;
import com.amaze.filemanager.utils.MainActivityHelper;
import com.amaze.filemanager.utils.OTGUtil;
import com.amaze.filemanager.utils.OpenMode;
import com.amaze.filemanager.utils.RootUtils;
import com.cloudrail.si.interfaces.CloudStorage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
/**
* Created by arpitkh996 on 13-01-2016, modified by Emmanuel Messulam<emmanuelbendavid@gmail.com>
*/
public class Operations {
// reserved characters by OS, shall not be allowed in file names
private static final String FOREWARD_SLASH = "/";
private static final String BACKWARD_SLASH = "\\";
private static final String COLON = ":";
private static final String ASTERISK = "*";
private static final String QUESTION_MARK = "?";
private static final String QUOTE = "\"";
private static final String GREATER_THAN = ">";
private static final String LESS_THAN = "<";
private static final String FAT = "FAT";
private DataUtils dataUtils = DataUtils.getInstance();
public interface ErrorCallBack {
/**
* Callback fired when file being created in process already exists
*
* @param file
*/
void exists(HFile file);
/**
* Callback fired when creating new file/directory and required storage access framework permission
* to access SD Card is not available
*
* @param file
*/
void launchSAF(HFile file);
/**
* Callback fired when renaming file and required storage access framework permission to access
* SD Card is not available
*
* @param file
* @param file1
*/
void launchSAF(HFile file, HFile file1);
/**
* Callback fired when we're done processing the operation
*
* @param hFile
* @param b defines whether operation was successful
*/
void done(HFile hFile, boolean b);
/**
* Callback fired when an invalid file name is found.
*
* @param file
*/
void invalidName(HFile file);
}
public static void mkdir(@NonNull final HFile file, final Context context, final boolean rootMode,
@NonNull final ErrorCallBack errorCallBack) {
new AsyncTask<Void, Void, Void>() {
private DataUtils dataUtils = DataUtils.getInstance();
@Override
protected Void doInBackground(Void... params) {
// checking whether filename is valid or a recursive call possible
if (MainActivityHelper.isNewDirectoryRecursive(file) ||
!Operations.isFileNameValid(file.getName(context))) {
errorCallBack.invalidName(file);
return null;
}
if (file.exists()) {
errorCallBack.exists(file);
return null;
}
if (file.isSmb()) {
try {
file.getSmbFile(2000).mkdirs();
} catch (SmbException e) {
Logger.log(e, file.getPath(), context);
errorCallBack.done(file, false);
return null;
}
errorCallBack.done(file, file.exists());
return null;
} else if (file.isOtgFile()) {
// first check whether new directory already exists
DocumentFile directoryToCreate = OTGUtil.getDocumentFile(file.getPath(), context, false);
if (directoryToCreate != null) errorCallBack.exists(file);
DocumentFile parentDirectory = OTGUtil.getDocumentFile(file.getParent(), context, false);
if (parentDirectory.isDirectory()) {
parentDirectory.createDirectory(file.getName(context));
errorCallBack.done(file, true);
} else errorCallBack.done(file, false);
return null;
} else if (file.isDropBoxFile()) {
CloudStorage cloudStorageDropbox = dataUtils.getAccount(OpenMode.DROPBOX);
try {
cloudStorageDropbox.createFolder(CloudUtil.stripPath(OpenMode.DROPBOX, file.getPath()));
errorCallBack.done(file, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(file, false);
}
} else if (file.isBoxFile()) {
CloudStorage cloudStorageBox = dataUtils.getAccount(OpenMode.BOX);
try {
cloudStorageBox.createFolder(CloudUtil.stripPath(OpenMode.BOX, file.getPath()));
errorCallBack.done(file, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(file, false);
}
} else if (file.isOneDriveFile()) {
CloudStorage cloudStorageOneDrive = dataUtils.getAccount(OpenMode.ONEDRIVE);
try {
cloudStorageOneDrive.createFolder(CloudUtil.stripPath(OpenMode.ONEDRIVE, file.getPath()));
errorCallBack.done(file, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(file, false);
}
} else if (file.isGoogleDriveFile()) {
CloudStorage cloudStorageGdrive = dataUtils.getAccount(OpenMode.GDRIVE);
try {
cloudStorageGdrive.createFolder(CloudUtil.stripPath(OpenMode.GDRIVE, file.getPath()));
errorCallBack.done(file, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(file, false);
}
} else {
if (file.isLocal() || file.isRoot()) {
int mode = checkFolder(new File(file.getParent()), context);
if (mode == 2) {
errorCallBack.launchSAF(file);
return null;
}
if (mode == 1 || mode == 0)
FileUtil.mkdir(file.getFile(), context);
if (!file.exists() && rootMode) {
file.setMode(OpenMode.ROOT);
if (file.exists()) errorCallBack.exists(file);
try {
RootUtils.mkDir(file.getParent(context), file.getName(context));
} catch (RootNotPermittedException e) {
Logger.log(e, file.getPath(), context);
}
errorCallBack.done(file, file.exists());
return null;
}
errorCallBack.done(file, file.exists());
return null;
}
errorCallBack.done(file, file.exists());
}
return null;
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
public static void mkfile(@NonNull final HFile file, final Context context, final boolean rootMode,
@NonNull final ErrorCallBack errorCallBack) {
new AsyncTask<Void, Void, Void>() {
private DataUtils dataUtils = DataUtils.getInstance();
@Override
protected Void doInBackground(Void... params) {
// check whether filename is valid or not
if (!Operations.isFileNameValid(file.getName(context))) {
errorCallBack.invalidName(file);
return null;
}
if (file.exists()) {
errorCallBack.exists(file);
return null;
}
if (file.isSmb()) {
try {
file.getSmbFile(2000).createNewFile();
} catch (SmbException e) {
Logger.log(e, file.getPath(), context);
errorCallBack.done(file, false);
return null;
}
errorCallBack.done(file, file.exists());
return null;
} else if (file.isDropBoxFile()) {
CloudStorage cloudStorageDropbox = dataUtils.getAccount(OpenMode.DROPBOX);
try {
byte[] tempBytes = new byte[0];
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(tempBytes);
cloudStorageDropbox.upload(CloudUtil.stripPath(OpenMode.DROPBOX, file.getPath()),
byteArrayInputStream, 0l, true);
errorCallBack.done(file, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(file, false);
}
} else if (file.isBoxFile()) {
CloudStorage cloudStorageBox = dataUtils.getAccount(OpenMode.BOX);
try {
byte[] tempBytes = new byte[0];
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(tempBytes);
cloudStorageBox.upload(CloudUtil.stripPath(OpenMode.BOX, file.getPath()),
byteArrayInputStream, 0l, true);
errorCallBack.done(file, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(file, false);
}
} else if (file.isOneDriveFile()) {
CloudStorage cloudStorageOneDrive = dataUtils.getAccount(OpenMode.ONEDRIVE);
try {
byte[] tempBytes = new byte[0];
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(tempBytes);
cloudStorageOneDrive.upload(CloudUtil.stripPath(OpenMode.ONEDRIVE, file.getPath()),
byteArrayInputStream, 0l, true);
errorCallBack.done(file, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(file, false);
}
} else if (file.isGoogleDriveFile()) {
CloudStorage cloudStorageGdrive = dataUtils.getAccount(OpenMode.GDRIVE);
try {
byte[] tempBytes = new byte[0];
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(tempBytes);
cloudStorageGdrive.upload(CloudUtil.stripPath(OpenMode.GDRIVE, file.getPath()),
byteArrayInputStream, 0l, true);
errorCallBack.done(file, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(file, false);
}
} else if (file.isOtgFile()) {
// first check whether new file already exists
DocumentFile fileToCreate = OTGUtil.getDocumentFile(file.getPath(), context, false);
if (fileToCreate != null) errorCallBack.exists(file);
DocumentFile parentDirectory = OTGUtil.getDocumentFile(file.getParent(), context, false);
if (parentDirectory.isDirectory()) {
parentDirectory.createFile(file.getName(context).substring(file.getName().lastIndexOf(".")),
file.getName(context));
errorCallBack.done(file, true);
} else errorCallBack.done(file, false);
return null;
} else {
if (file.isLocal() || file.isRoot()) {
int mode = checkFolder(new File(file.getParent()), context);
if (mode == 2) {
errorCallBack.launchSAF(file);
return null;
}
if (mode == 1 || mode == 0)
try {
FileUtil.mkfile(file.getFile(), context);
} catch (IOException e) {
}
if (!file.exists() && rootMode) {
file.setMode(OpenMode.ROOT);
if (file.exists()) errorCallBack.exists(file);
try {
RootUtils.mkFile(file.getPath());
} catch (RootNotPermittedException e) {
Logger.log(e, file.getPath(), context);
}
errorCallBack.done(file, file.exists());
return null;
}
errorCallBack.done(file, file.exists());
return null;
}
errorCallBack.done(file, file.exists());
}
return null;
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
public static void rename(final HFile oldFile, final HFile newFile, final boolean rootMode,
final Context context, final ErrorCallBack errorCallBack) {
new AsyncTask<Void, Void, Void>() {
private DataUtils dataUtils = DataUtils.getInstance();
@Override
protected Void doInBackground(Void... params) {
// check whether file names for new file are valid or recursion occurs
if (MainActivityHelper.isNewDirectoryRecursive(newFile) ||
!Operations.isFileNameValid(newFile.getName(context))) {
errorCallBack.invalidName(newFile);
return null;
}
if (newFile.exists()) {
errorCallBack.exists(newFile);
return null;
}
if (oldFile.isSmb()) {
try {
SmbFile smbFile = new SmbFile(oldFile.getPath());
SmbFile smbFile1 = new SmbFile(newFile.getPath());
if (smbFile1.exists()) {
errorCallBack.exists(newFile);
return null;
}
smbFile.renameTo(smbFile1);
if (!smbFile.exists() && smbFile1.exists())
errorCallBack.done(newFile, true);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (SmbException e) {
e.printStackTrace();
}
return null;
} else if (oldFile.isDropBoxFile()) {
CloudStorage cloudStorageDropbox = dataUtils.getAccount(OpenMode.DROPBOX);
try {
cloudStorageDropbox.move(CloudUtil.stripPath(OpenMode.DROPBOX, oldFile.getPath()),
CloudUtil.stripPath(OpenMode.DROPBOX, newFile.getPath()));
errorCallBack.done(newFile, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(newFile, false);
}
} else if (oldFile.isBoxFile()) {
CloudStorage cloudStorageBox = dataUtils.getAccount(OpenMode.BOX);
try {
cloudStorageBox.move(CloudUtil.stripPath(OpenMode.BOX, oldFile.getPath()),
CloudUtil.stripPath(OpenMode.BOX, newFile.getPath()));
errorCallBack.done(newFile, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(newFile, false);
}
} else if (oldFile.isOneDriveFile()) {
CloudStorage cloudStorageOneDrive = dataUtils.getAccount(OpenMode.ONEDRIVE);
try {
cloudStorageOneDrive.move(CloudUtil.stripPath(OpenMode.ONEDRIVE, oldFile.getPath()),
CloudUtil.stripPath(OpenMode.ONEDRIVE, newFile.getPath()));
errorCallBack.done(newFile, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(newFile, false);
}
} else if (oldFile.isGoogleDriveFile()) {
CloudStorage cloudStorageGdrive = dataUtils.getAccount(OpenMode.GDRIVE);
try {
cloudStorageGdrive.move(CloudUtil.stripPath(OpenMode.GDRIVE, oldFile.getPath()),
CloudUtil.stripPath(OpenMode.GDRIVE, newFile.getPath()));
errorCallBack.done(newFile, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(newFile, false);
}
} else if (oldFile.isOtgFile()) {
DocumentFile oldDocumentFile = OTGUtil.getDocumentFile(oldFile.getPath(), context, false);
DocumentFile newDocumentFile = OTGUtil.getDocumentFile(newFile.getPath(), context, false);
if (newDocumentFile != null) {
errorCallBack.exists(newFile);
return null;
}
errorCallBack.done(newFile, oldDocumentFile.renameTo(newFile.getName(context)));
return null;
} else {
File file = new File(oldFile.getPath());
File file1 = new File(newFile.getPath());
switch (oldFile.getMode()) {
case FILE:
int mode = checkFolder(file.getParentFile(), context);
if (mode == 2) {
errorCallBack.launchSAF(oldFile, newFile);
} else if (mode == 1 || mode == 0) {
try {
FileUtil.renameFolder(file, file1, context);
} catch (RootNotPermittedException e) {
e.printStackTrace();
}
boolean a = !file.exists() && file1.exists();
if (!a && rootMode) {
try {
RootUtils.rename(file.getPath(), file1.getPath());
} catch (Exception e) {
Logger.log(e, oldFile.getPath() + "\n" + newFile.getPath(), context);
}
oldFile.setMode(OpenMode.ROOT);
newFile.setMode(OpenMode.ROOT);
a = !file.exists() && file1.exists();
}
errorCallBack.done(newFile, a);
return null;
}
break;
case ROOT:
try {
RootUtils.rename(file.getPath(), file1.getPath());
} catch (Exception e) {
Logger.log(e, oldFile.getPath() + "\n" + newFile.getPath(), context);
}
newFile.setMode(OpenMode.ROOT);
errorCallBack.done(newFile, true);
break;
}
}
return null;
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private static int checkFolder(final File folder, Context context) {
boolean lol = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
if (lol) {
boolean ext = FileUtil.isOnExtSdCard(folder, context);
if (ext) {
if (!folder.exists() || !folder.isDirectory()) {
return 0;
}
// On Android 5, trigger storage access framework.
if (!FileUtil.isWritableNormalOrSaf(folder, context)) {
return 2;
}
return 1;
}
} else if (Build.VERSION.SDK_INT == 19) {
// Assume that Kitkat workaround works
if (FileUtil.isOnExtSdCard(folder, context)) return 1;
}
// file not on external sd card
if (FileUtil.isWritable(new File(folder, "DummyFile"))) {
return 1;
} else {
return 0;
}
}
/**
* Well, we wouldn't want to copy when the target is inside the source
* otherwise it'll end into a loop
*
* @param sourceFile
* @param targetFile
* @return true when copy loop is possible
*/
public static boolean isCopyLoopPossible(BaseFile sourceFile, HFile targetFile) {
return targetFile.getPath().contains(sourceFile.getPath());
}
/**
* Validates file name
* special reserved characters shall not be allowed in the file names on FAT filesystems
*
* @param fileName the filename, not the full path!
* @return boolean if the file name is valid or invalid
*/
public static boolean isFileNameValid(String fileName) {
//String fileName = builder.substring(builder.lastIndexOf("/")+1, builder.length());
// TODO: check file name validation only for FAT filesystems
return !(fileName.contains(ASTERISK) || fileName.contains(BACKWARD_SLASH) ||
fileName.contains(COLON) || fileName.contains(FOREWARD_SLASH) ||
fileName.contains(GREATER_THAN) || fileName.contains(LESS_THAN) ||
fileName.contains(QUESTION_MARK) || fileName.contains(QUOTE));
}
private static boolean isFileSystemFAT(String mountPoint) {
String[] args = new String[]{"/bin/bash", "-c", "df -DO_NOT_REPLACE | awk '{print $1,$2,$NF}' | grep \"^"
+ mountPoint + "\""};
try {
Process proc = new ProcessBuilder(args).start();
OutputStream outputStream = proc.getOutputStream();
String buffer = null;
outputStream.write(buffer.getBytes());
return buffer != null && buffer.contains(FAT);
} catch (IOException e) {
e.printStackTrace();
// process interrupted, returning true, as a word of cation
return true;
}
}
}
| martincz/AmazeFileManager | src/main/java/com/amaze/filemanager/filesystem/Operations.java | Java | gpl-3.0 | 24,347 |
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#include "qmljstoolsplugin.h"
#include "qmljsmodelmanager.h"
#include "qmljsfunctionfilter.h"
#include "qmljslocatordata.h"
#include "qmljscodestylesettingspage.h"
#include "qmljstoolsconstants.h"
#include "qmljstoolssettings.h"
#include "qmljsbundleprovider.h"
#include <coreplugin/icontext.h>
#include <coreplugin/icore.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <QMenu>
using namespace Core;
namespace QmlJSTools {
namespace Internal {
enum { debug = 0 };
class QmlJSToolsPluginPrivate : public QObject
{
public:
QmlJSToolsPluginPrivate();
QmlJSToolsSettings settings;
ModelManager modelManager;
QAction resetCodeModelAction{QmlJSToolsPlugin::tr("Reset Code Model"), nullptr};
LocatorData locatorData;
FunctionFilter functionFilter{&locatorData};
QmlJSCodeStyleSettingsPage codeStyleSettingsPage;
BasicBundleProvider basicBundleProvider;
};
QmlJSToolsPlugin::~QmlJSToolsPlugin()
{
delete d;
}
bool QmlJSToolsPlugin::initialize(const QStringList &arguments, QString *error)
{
Q_UNUSED(arguments)
Q_UNUSED(error)
d = new QmlJSToolsPluginPrivate;
return true;
}
QmlJSToolsPluginPrivate::QmlJSToolsPluginPrivate()
{
// Core::VcsManager *vcsManager = Core::VcsManager::instance();
// Core::DocumentManager *documentManager = Core::DocumentManager::instance();
// connect(vcsManager, &Core::VcsManager::repositoryChanged,
// &d->modelManager, &ModelManager::updateModifiedSourceFiles);
// connect(documentManager, &DocumentManager::filesChangedInternally,
// &d->modelManager, &ModelManager::updateSourceFiles);
// Menus
ActionContainer *mtools = ActionManager::actionContainer(Core::Constants::M_TOOLS);
ActionContainer *mqmljstools = ActionManager::createMenu(Constants::M_TOOLS_QMLJS);
QMenu *menu = mqmljstools->menu();
menu->setTitle(QmlJSToolsPlugin::tr("&QML/JS"));
menu->setEnabled(true);
mtools->addMenu(mqmljstools);
// Update context in global context
Command *cmd = ActionManager::registerAction(
&resetCodeModelAction, Constants::RESET_CODEMODEL);
connect(&resetCodeModelAction, &QAction::triggered,
&modelManager, &ModelManager::resetCodeModel);
mqmljstools->addAction(cmd);
// Watch task progress
connect(ProgressManager::instance(), &ProgressManager::taskStarted, this,
[this](Core::Id type) {
if (type == QmlJS::Constants::TASK_INDEX)
resetCodeModelAction.setEnabled(false);
});
connect(ProgressManager::instance(), &ProgressManager::allTasksFinished,
[this](Core::Id type) {
if (type == QmlJS::Constants::TASK_INDEX)
resetCodeModelAction.setEnabled(true);
});
}
void QmlJSToolsPlugin::extensionsInitialized()
{
d->modelManager.delayedInitialization();
}
} // Internal
} // QmlJSTools
| sailfish-sdk/sailfish-qtcreator | src/plugins/qmljstools/qmljstoolsplugin.cpp | C++ | gpl-3.0 | 4,284 |
/*
* DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-cen-xr-w32-bld/build/netwerk/base/public/nsPISocketTransportService.idl
*/
#ifndef __gen_nsPISocketTransportService_h__
#define __gen_nsPISocketTransportService_h__
#ifndef __gen_nsISocketTransportService_h__
#include "nsISocketTransportService.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
/* starting interface: nsPISocketTransportService */
#define NS_PISOCKETTRANSPORTSERVICE_IID_STR "83123036-81c0-47cb-8d9c-bd85d29a1b3f"
#define NS_PISOCKETTRANSPORTSERVICE_IID \
{0x83123036, 0x81c0, 0x47cb, \
{ 0x8d, 0x9c, 0xbd, 0x85, 0xd2, 0x9a, 0x1b, 0x3f }}
/**
* This is a private interface used by the internals of the networking library.
* It will never be frozen. Do not use it in external code.
*/
class NS_NO_VTABLE NS_SCRIPTABLE nsPISocketTransportService : public nsISocketTransportService {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_PISOCKETTRANSPORTSERVICE_IID)
/**
* init/shutdown routines.
*/
/* void init (); */
NS_SCRIPTABLE NS_IMETHOD Init(void) = 0;
/* void shutdown (); */
NS_SCRIPTABLE NS_IMETHOD Shutdown(void) = 0;
/**
* controls whether or not the socket transport service should poke
* the autodialer on connection failure.
*/
/* attribute boolean autodialEnabled; */
NS_SCRIPTABLE NS_IMETHOD GetAutodialEnabled(PRBool *aAutodialEnabled) = 0;
NS_SCRIPTABLE NS_IMETHOD SetAutodialEnabled(PRBool aAutodialEnabled) = 0;
/**
* controls the TCP sender window clamp
*/
/* readonly attribute long sendBufferSize; */
NS_SCRIPTABLE NS_IMETHOD GetSendBufferSize(PRInt32 *aSendBufferSize) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsPISocketTransportService, NS_PISOCKETTRANSPORTSERVICE_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSPISOCKETTRANSPORTSERVICE \
NS_SCRIPTABLE NS_IMETHOD Init(void); \
NS_SCRIPTABLE NS_IMETHOD Shutdown(void); \
NS_SCRIPTABLE NS_IMETHOD GetAutodialEnabled(PRBool *aAutodialEnabled); \
NS_SCRIPTABLE NS_IMETHOD SetAutodialEnabled(PRBool aAutodialEnabled); \
NS_SCRIPTABLE NS_IMETHOD GetSendBufferSize(PRInt32 *aSendBufferSize);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSPISOCKETTRANSPORTSERVICE(_to) \
NS_SCRIPTABLE NS_IMETHOD Init(void) { return _to Init(); } \
NS_SCRIPTABLE NS_IMETHOD Shutdown(void) { return _to Shutdown(); } \
NS_SCRIPTABLE NS_IMETHOD GetAutodialEnabled(PRBool *aAutodialEnabled) { return _to GetAutodialEnabled(aAutodialEnabled); } \
NS_SCRIPTABLE NS_IMETHOD SetAutodialEnabled(PRBool aAutodialEnabled) { return _to SetAutodialEnabled(aAutodialEnabled); } \
NS_SCRIPTABLE NS_IMETHOD GetSendBufferSize(PRInt32 *aSendBufferSize) { return _to GetSendBufferSize(aSendBufferSize); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSPISOCKETTRANSPORTSERVICE(_to) \
NS_SCRIPTABLE NS_IMETHOD Init(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->Init(); } \
NS_SCRIPTABLE NS_IMETHOD Shutdown(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->Shutdown(); } \
NS_SCRIPTABLE NS_IMETHOD GetAutodialEnabled(PRBool *aAutodialEnabled) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetAutodialEnabled(aAutodialEnabled); } \
NS_SCRIPTABLE NS_IMETHOD SetAutodialEnabled(PRBool aAutodialEnabled) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetAutodialEnabled(aAutodialEnabled); } \
NS_SCRIPTABLE NS_IMETHOD GetSendBufferSize(PRInt32 *aSendBufferSize) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetSendBufferSize(aSendBufferSize); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class _MYCLASS_ : public nsPISocketTransportService
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSPISOCKETTRANSPORTSERVICE
_MYCLASS_();
private:
~_MYCLASS_();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(_MYCLASS_, nsPISocketTransportService)
_MYCLASS_::_MYCLASS_()
{
/* member initializers and constructor code */
}
_MYCLASS_::~_MYCLASS_()
{
/* destructor code */
}
/* void init (); */
NS_IMETHODIMP _MYCLASS_::Init()
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void shutdown (); */
NS_IMETHODIMP _MYCLASS_::Shutdown()
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* attribute boolean autodialEnabled; */
NS_IMETHODIMP _MYCLASS_::GetAutodialEnabled(PRBool *aAutodialEnabled)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP _MYCLASS_::SetAutodialEnabled(PRBool aAutodialEnabled)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute long sendBufferSize; */
NS_IMETHODIMP _MYCLASS_::GetSendBufferSize(PRInt32 *aSendBufferSize)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsPISocketTransportService_h__ */
| DragonZX/fdm | Gecko.SDK/2.0/include/nsPISocketTransportService.h | C | gpl-3.0 | 5,168 |
<div class="container profile">
<div class="row">
<div class="col-sm-10">
<div class="panel panel-default">
<div class="panel-body">
<h1>Adding new Value is the best</h1>
<legend>Contribution:</legend>
<div class="form-group">
<label class="control-label"><i class="ion-clipboard"></i> title</label>
<input type="text" id="title" class="form-control" ng-model="model.title" required/>
</div>
<div class="form-group">
<label class="control-label"><i class="ion-clipboard"></i> content</label>
<textarea class="form-control" id="title" ng-model="model.file" required rows="5"></textarea>
</div>
<legend>Contributers:</legend>
<div ng-repeat="contributer in model.contributers" >
<div class="row well-lg contributer-cell">
<div class = 'col-sm-2'>
<img class="img-rounded" ng-src="{{contributer.img}}" alt="" HEIGHT = 50 WIDTH=50>
</div>
<div class = 'col-sm-3'>
<select ng-model = "contributer.contributer_id" ng-options="user.id as user.name for user in contributer.usersList"
ng-change="contributer.img = updateContributer(contributer.contributer_id,$index)" data-placeholder="Choose Contributer">
</select>
</div>
<div class = 'col-sm-3'>
<input style="width: 200px;" type="range" min="0" max="100" step="1"
ng-disabled ="contributer.contributer_id == '0'" ng-model="contributer.contribution1" ng-change="changeContribution()">
</input>
</div>
<div class = 'col-sm-2'>
<input size = "5" type="text" disabled = "disabled" id="contributer_percentage" ng-model="contributer.contributer_percentage">
</input> %
</div>
<div class = 'col-sm-2'>
<button type="submit" class="btn btn-default" aria-label="Left Align" ng-click='removeCollaboratorItem($index)'>
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
</button>
</div>
</div>
</div>
<button type="submit" class="btn btn-default" aria-label="Left Align" ng-click='addCollaborator()'>
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span> Add Collaborator
</button>
<div align="center" ><button type="submit" class="btn btn-warning submit-button"
ng-disabled="!model.title || !model.file || buttonDisabled" ng-click="onSubmit()">Submit</button>
</div>
</div>
</div>
</div>
</div>
</div> | Backfeed/Backfeed-Protocol-Service | static/partials/createContribution.html | HTML | gpl-3.0 | 2,609 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Strings for component 'theme_overlay', language 'es', branch 'MOODLE_22_STABLE'
*
* @package theme_overlay
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$string['configtitle'] = 'Ajustes Overlay';
$string['customcss'] = 'CSS personalizado';
$string['customcssdesc'] = 'Cualquier CSS que introduzca aquí será agregado a todas las páginas, permitiéndole personalizar con facilidad este tema.';
$string['footertext'] = 'Texto del pie de página';
$string['footertextdesc'] = 'Ajustar una nota o texto a pie de página.';
$string['headercolor'] = 'Color de la cabecera';
$string['headercolordesc'] = 'Color de fondo de la cabecera.';
$string['linkcolor'] = 'Color de los enlaces';
$string['linkcolordesc'] = 'Esta opción ajusta el color de los enlaces en el tema';
$string['pluginname'] = 'Overlay';
$string['region-side-post'] = 'Derecha';
$string['region-side-pre'] = 'Izquierda';
| danielbonetto/twig_MVC | lang/es/theme_overlay.php | PHP | gpl-3.0 | 1,725 |
package org.ovirt.engine.core.bll.scheduling.commands;
import java.util.HashMap;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.common.scheduling.ClusterPolicy;
import org.ovirt.engine.core.common.scheduling.parameters.ClusterPolicyCRUDParameters;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.utils.MockConfigRule;
public class ClusterPolicyCRUDCommandTest {
@Rule
public MockConfigRule mockConfigRule =
new MockConfigRule((MockConfigRule.mockConfig(ConfigValues.EnableVdsLoadBalancing, false)),
(MockConfigRule.mockConfig(ConfigValues.EnableVdsHaReservation, false)));
@Test
public void testCheckAddEditValidations() {
Guid clusterPolicyId = new Guid("e754440b-76a6-4099-8235-4565ab4b5521");
ClusterPolicy clusterPolicy = new ClusterPolicy();
clusterPolicy.setId(clusterPolicyId);
ClusterPolicyCRUDCommand command =
new ClusterPolicyCRUDCommand(new ClusterPolicyCRUDParameters(clusterPolicyId,
clusterPolicy)) {
@Override
protected void executeCommand() {
}
};
Assert.assertTrue(command.checkAddEditValidations());
}
@Test
public void testCheckAddEditValidationsFailOnParameters() {
Guid clusterPolicyId = new Guid("e754440b-76a6-4099-8235-4565ab4b5521");
ClusterPolicy clusterPolicy = new ClusterPolicy();
clusterPolicy.setId(clusterPolicyId);
HashMap<String, String> parameterMap = new HashMap<String, String>();
parameterMap.put("fail?", "sure, fail!");
clusterPolicy.setParameterMap(parameterMap);
ClusterPolicyCRUDCommand command =
new ClusterPolicyCRUDCommand(new ClusterPolicyCRUDParameters(clusterPolicyId,
clusterPolicy)) {
@Override
protected void executeCommand() {
}
};
Assert.assertFalse(command.checkAddEditValidations());
}
}
| jtux270/translate | ovirt/backend/manager/modules/bll/src/test/java/org/ovirt/engine/core/bll/scheduling/commands/ClusterPolicyCRUDCommandTest.java | Java | gpl-3.0 | 2,187 |
/*
Copyright (C) 2014-2019 de4dot@gmail.com
This file is part of dnSpy
dnSpy is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
dnSpy is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with dnSpy. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.Linq;
using dnSpy.Contracts.Images;
using dnSpy.Contracts.Menus;
using dnSpy.Contracts.ToolWindows;
using dnSpy.Contracts.ToolWindows.App;
namespace dnSpy.MainApp {
sealed class ToolWindowGroupContext {
public readonly IDsToolWindowService DsToolWindowService;
public readonly IToolWindowGroupService ToolWindowGroupService;
public readonly IToolWindowGroup ToolWindowGroup;
public ToolWindowGroupContext(IDsToolWindowService toolWindowService, IToolWindowGroup toolWindowGroup) {
DsToolWindowService = toolWindowService;
ToolWindowGroupService = toolWindowGroup.ToolWindowGroupService;
ToolWindowGroup = toolWindowGroup;
}
}
abstract class CtxMenuToolWindowGroupCommand : MenuItemBase<ToolWindowGroupContext> {
protected sealed override object CachedContextKey => ContextKey;
static readonly object ContextKey = new object();
protected sealed override ToolWindowGroupContext? CreateContext(IMenuItemContext context) => CreateContextInternal(context);
readonly IDsToolWindowService toolWindowService;
protected CtxMenuToolWindowGroupCommand(IDsToolWindowService toolWindowService) => this.toolWindowService = toolWindowService;
protected ToolWindowGroupContext? CreateContextInternal(IMenuItemContext context) {
if (context.CreatorObject.Guid != new Guid(MenuConstants.GUIDOBJ_TOOLWINDOW_TABCONTROL_GUID))
return null;
var twg = context.Find<IToolWindowGroup>();
if (twg is null || !toolWindowService.Owns(twg))
return null;
return new ToolWindowGroupContext(toolWindowService, twg);
}
}
[ExportMenuItem(Header = "res:HideToolWindowCommand", InputGestureText = "res:ShortCutKeyShiftEsc", Icon = DsImagesAttribute.TableViewNameOnly, Group = MenuConstants.GROUP_CTX_TOOLWINS_CLOSE, Order = 10)]
sealed class HideTWCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
HideTWCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroup.CloseActiveTabCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroup.CloseActiveTab();
}
[ExportMenuItem(Header = "res:HideAllToolWindowsCommand", Icon = DsImagesAttribute.CloseDocumentGroup, Group = MenuConstants.GROUP_CTX_TOOLWINS_CLOSE, Order = 20)]
sealed class CloseAllTabsTWCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
CloseAllTabsTWCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.CloseAllTabsCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.CloseAllTabs();
}
static class CmdConstants {
public const string MOVE_CONTENT_GUID = "D54D52CB-A6FC-408C-9A52-EA0D53AEEC3A";
public const string GROUP_MOVE_CONTENT = "0,92C51A9F-DE4B-4D7F-B1DC-AAA482936B5C";
public const string MOVE_GROUP_GUID = "047ECD64-82EF-4774-9C0A-330A61989432";
public const string GROUP_MOVE_GROUP = "0,174B60EE-279F-4DA4-9F07-44FFD03E4421";
}
[ExportMenuItem(Header = "res:MoveToolWindowCommand", Guid = CmdConstants.MOVE_CONTENT_GUID, Group = MenuConstants.GROUP_CTX_TOOLWINS_CLOSE, Order = 30)]
sealed class MoveTWCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveTWCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override void Execute(ToolWindowGroupContext context) => Debug.Fail("Shouldn't be here");
}
[ExportMenuItem(Header = "res:MoveToolWindowGroupCommand", Guid = CmdConstants.MOVE_GROUP_GUID, Group = MenuConstants.GROUP_CTX_TOOLWINS_CLOSE, Order = 40)]
sealed class MoveGroupTWCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveGroupTWCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroup.TabContents.Count() > 1;
public override void Execute(ToolWindowGroupContext context) => Debug.Fail("Shouldn't be here");
}
[ExportMenuItem(OwnerGuid = CmdConstants.MOVE_CONTENT_GUID, Header = "res:MoveTopCommand", Icon = DsImagesAttribute.ToolstripPanelTop, Group = CmdConstants.GROUP_MOVE_CONTENT, Order = 0)]
sealed class MoveTWTopCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveTWTopCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsEnabled(ToolWindowGroupContext context) => context.DsToolWindowService.CanMove(context.ToolWindowGroup.ActiveTabContent, AppToolWindowLocation.Top);
public override void Execute(ToolWindowGroupContext context) => context.DsToolWindowService.Move(context.ToolWindowGroup.ActiveTabContent, AppToolWindowLocation.Top);
}
[ExportMenuItem(OwnerGuid = CmdConstants.MOVE_CONTENT_GUID, Header = "res:MoveLeftCommand", Icon = DsImagesAttribute.ToolstripPanelLeft, Group = CmdConstants.GROUP_MOVE_CONTENT, Order = 10)]
sealed class MoveTWLeftCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveTWLeftCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsEnabled(ToolWindowGroupContext context) => context.DsToolWindowService.CanMove(context.ToolWindowGroup.ActiveTabContent, AppToolWindowLocation.Left);
public override void Execute(ToolWindowGroupContext context) => context.DsToolWindowService.Move(context.ToolWindowGroup.ActiveTabContent, AppToolWindowLocation.Left);
}
[ExportMenuItem(OwnerGuid = CmdConstants.MOVE_CONTENT_GUID, Header = "res:MoveRightCommand", Icon = DsImagesAttribute.ToolstripPanelRight, Group = CmdConstants.GROUP_MOVE_CONTENT, Order = 20)]
sealed class MoveTWRightCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveTWRightCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsEnabled(ToolWindowGroupContext context) => context.DsToolWindowService.CanMove(context.ToolWindowGroup.ActiveTabContent, AppToolWindowLocation.Right);
public override void Execute(ToolWindowGroupContext context) => context.DsToolWindowService.Move(context.ToolWindowGroup.ActiveTabContent, AppToolWindowLocation.Right);
}
[ExportMenuItem(OwnerGuid = CmdConstants.MOVE_CONTENT_GUID, Header = "res:MoveBottomCommand", Icon = DsImagesAttribute.ToolstripPanelBottom, Group = CmdConstants.GROUP_MOVE_CONTENT, Order = 30)]
sealed class MoveTWBottomCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveTWBottomCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsEnabled(ToolWindowGroupContext context) => context.DsToolWindowService.CanMove(context.ToolWindowGroup.ActiveTabContent, AppToolWindowLocation.Bottom);
public override void Execute(ToolWindowGroupContext context) => context.DsToolWindowService.Move(context.ToolWindowGroup.ActiveTabContent, AppToolWindowLocation.Bottom);
}
[ExportMenuItem(OwnerGuid = CmdConstants.MOVE_GROUP_GUID, Header = "res:MoveTopCommand", Icon = DsImagesAttribute.ToolstripPanelTop, Group = CmdConstants.GROUP_MOVE_GROUP, Order = 0)]
sealed class MoveGroupTWTopCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveGroupTWTopCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsEnabled(ToolWindowGroupContext context) => context.DsToolWindowService.CanMove(context.ToolWindowGroup, AppToolWindowLocation.Top);
public override void Execute(ToolWindowGroupContext context) => context.DsToolWindowService.Move(context.ToolWindowGroup, AppToolWindowLocation.Top);
}
[ExportMenuItem(OwnerGuid = CmdConstants.MOVE_GROUP_GUID, Header = "res:MoveLeftCommand", Icon = DsImagesAttribute.ToolstripPanelLeft, Group = CmdConstants.GROUP_MOVE_GROUP, Order = 10)]
sealed class MoveGroupTWLeftCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveGroupTWLeftCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsEnabled(ToolWindowGroupContext context) => context.DsToolWindowService.CanMove(context.ToolWindowGroup, AppToolWindowLocation.Left);
public override void Execute(ToolWindowGroupContext context) => context.DsToolWindowService.Move(context.ToolWindowGroup, AppToolWindowLocation.Left);
}
[ExportMenuItem(OwnerGuid = CmdConstants.MOVE_GROUP_GUID, Header = "res:MoveRightCommand", Icon = DsImagesAttribute.ToolstripPanelRight, Group = CmdConstants.GROUP_MOVE_GROUP, Order = 20)]
sealed class MoveGroupTWRightCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveGroupTWRightCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsEnabled(ToolWindowGroupContext context) => context.DsToolWindowService.CanMove(context.ToolWindowGroup, AppToolWindowLocation.Right);
public override void Execute(ToolWindowGroupContext context) => context.DsToolWindowService.Move(context.ToolWindowGroup, AppToolWindowLocation.Right);
}
[ExportMenuItem(OwnerGuid = CmdConstants.MOVE_GROUP_GUID, Header = "res:MoveBottomCommand", Icon = DsImagesAttribute.ToolstripPanelBottom, Group = CmdConstants.GROUP_MOVE_GROUP, Order = 30)]
sealed class MoveGroupTWBottomCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveGroupTWBottomCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsEnabled(ToolWindowGroupContext context) => context.DsToolWindowService.CanMove(context.ToolWindowGroup, AppToolWindowLocation.Bottom);
public override void Execute(ToolWindowGroupContext context) => context.DsToolWindowService.Move(context.ToolWindowGroup, AppToolWindowLocation.Bottom);
}
[ExportMenuItem(Header = "res:NewHorizontalTabGroupCommand", Icon = DsImagesAttribute.SplitScreenHorizontally, Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPS, Order = 0)]
sealed class NewHorizontalTabGroupCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
NewHorizontalTabGroupCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.NewHorizontalTabGroupCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.NewHorizontalTabGroup();
}
[ExportMenuItem(Header = "res:NewVerticalTabGroupCommand", Icon = DsImagesAttribute.SplitScreenVertically, Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPS, Order = 10)]
sealed class NewVerticalTabGroupCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
NewVerticalTabGroupCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.NewVerticalTabGroupCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.NewVerticalTabGroup();
}
[ExportMenuItem(Header = "res:MoveToNextTabGroupCommand", Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPS, Order = 20)]
sealed class MoveToNextTabGroupCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveToNextTabGroupCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.MoveToNextTabGroupCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.MoveToNextTabGroup();
}
[ExportMenuItem(Header = "res:MoveAllTabsToNextTabGroupCommand", Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPS, Order = 30)]
sealed class MoveAllToNextTabGroupCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveAllToNextTabGroupCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.MoveAllToNextTabGroupCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.MoveAllToNextTabGroup();
}
[ExportMenuItem(Header = "res:MoveToPreviousTabGroupCommand", Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPS, Order = 40)]
sealed class MoveToPreviousTabGroupCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveToPreviousTabGroupCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.MoveToPreviousTabGroupCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.MoveToPreviousTabGroup();
}
[ExportMenuItem(Header = "res:MoveAllToPreviousTabGroupCommand", Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPS, Order = 50)]
sealed class MoveAllToPreviousTabGroupCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveAllToPreviousTabGroupCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.MoveAllToPreviousTabGroupCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.MoveAllToPreviousTabGroup();
}
[ExportMenuItem(Header = "res:CloseTabGroupCommand", Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPSCLOSE, Order = 0)]
sealed class CloseTabGroupCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
CloseTabGroupCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.CloseTabGroupCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.CloseTabGroup();
}
[ExportMenuItem(Header = "res:CloseAllTabGroupsButThisCommand", Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPSCLOSE, Order = 10)]
sealed class CloseAllTabGroupsButThisCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
CloseAllTabGroupsButThisCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.CloseAllTabGroupsButThisCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.CloseAllTabGroupsButThis();
}
[ExportMenuItem(Header = "res:MoveTabGroupAfterNextTabGroupCommand", Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPSCLOSE, Order = 20)]
sealed class MoveTabGroupAfterNextTabGroupCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveTabGroupAfterNextTabGroupCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.MoveTabGroupAfterNextTabGroupCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.MoveTabGroupAfterNextTabGroup();
}
[ExportMenuItem(Header = "res:MoveTabGroupBeforePreviousTabGroupCommand", Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPSCLOSE, Order = 30)]
sealed class MoveTabGroupBeforePreviousTabGroupCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveTabGroupBeforePreviousTabGroupCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.MoveTabGroupBeforePreviousTabGroupCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.MoveTabGroupBeforePreviousTabGroup();
}
[ExportMenuItem(Header = "res:MergeAllTabGroupsCommand", Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPSCLOSE, Order = 40)]
sealed class MergeAllTabGroupsCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MergeAllTabGroupsCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.MergeAllTabGroupsCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.MergeAllTabGroups();
}
[ExportMenuItem(Header = "res:UseVerticalTabGroupsCommand", Icon = DsImagesAttribute.SplitScreenVertically, Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPSVERT, Order = 0)]
sealed class UseVerticalTabGroupsCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
UseVerticalTabGroupsCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.UseVerticalTabGroupsCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.UseVerticalTabGroups();
}
[ExportMenuItem(Header = "res:UseHorizontalTabGroupsCommand", Icon = DsImagesAttribute.SplitScreenHorizontally, Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPSVERT, Order = 10)]
sealed class UseHorizontalTabGroupsCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
UseHorizontalTabGroupsCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.UseHorizontalTabGroupsCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.UseHorizontalTabGroups();
}
}
| manojdjoshi/dnSpy | dnSpy/dnSpy/MainApp/DsToolWindowServiceCommands.cs | C# | gpl-3.0 | 19,003 |
'use strict';
/**
* Types of events
* @readonly
* @enum {number}
*/
var EventTypes = {
// Channel Events
/**
* A channel got connected
* @type {EventType}
*/
CONNECT: "connect",
/**
* A channel got disconnected
*/
DISCONNECT: "disconnect",
/**
* A channel got reconnected
*/
RECONNECT: "reconnect",
/**
* A channel is attempting to reconnect
*/
RECONNECTATTEMPT: "reconnect_attempt",
/**
* chatMode
*/
CHATMODE: "chatMode",
/**
* A list of current users in a channel
*/
CHANNELUSERS: "channelUsers",
/**
* A server message
*/
SERVERMESSAGE: "srvMsg",
/**
* A user message
*/
USERMESSAGE: "userMsg",
/**
* A /me message
*/
MEMESSAGE: "meMsg",
/**
* A /me message
*/
WHISPER: "whisper",
/**
* A global message
*/
GLOBALMESSAGE: "globalMsg",
/**
* An instruction/request to clear chat history
*/
CLEARCHAT: "clearChat",
/**
* A request for built-in command help
*/
COMMANDHELP: "commandHelp",
/**
* Whether or not mod tools should be visible
*/
MODTOOLSVISIBLE: "modToolsVisible",
/**
* A list of current mods in a channel
*/
MODLIST: "modList",
/**
* The color of the bot's name in chat
*/
COLOR: "color",
/**
* The online state of a stream
*/
ONLINESTATE: "onlineState",
/**
* A list of users included in a raffle
*/
RAFFLEUSERS: "raffleUsers",
/**
* The winner of a raffle
*/
WONRAFFLE: "wonRaffle",
/**
* runPoll
*/
RUNPOLL: "runPoll",
/**
* showPoll
*/
SHOWPOLL: "showPoll",
/**
* pollVotes
*/
POLLVOTES: "pollVotes",
/**
* voteResponse
*/
VOTERESPONSE: "voteResponse",
/**
* finishPoll
*/
FINISHPOLL: "finishPoll",
/**
* gameMode
*/
GAMEMODE: "gameMode",
/**
* adultMode
*/
ADULTMODE: "adultMode",
/**
* commissionsAvailable
*/
COMMISSIONSAVAILABLE: "commissionsAvailable",
/**
* clearUser
*/
CLEARUSER: "clearUser",
/**
* removeMsg
*/
REMOVEMESSAGE: "removeMsg",
/**
* A PTVAdmin? warning that a channel has adult content but is not in adult mode.
*/
WARNADULT: "warnAdult",
/**
* A PTVAdmin? warning that a channel has gaming content but is not in gaming mode.
*/
WARNGAMING: "warnGaming",
/**
* A PTVAdmin? warning that a channel has movie content.
*/
WARNMOVIES: "warnMovies",
/**
* The multistream status of a channel
*/
MULTISTATUS: "multiStatus",
/**
* Emitted after replaying chat history
*/
ENDHISTORY: "endHistory",
/**
* A list of people being ignored
*/
IGNORES: "ignores",
// Bot Events
/**
* The bot threw an exception
*/
EXCEPTION: "exception",
/**
* A bot command
*/
CHATCOMMAND: "chatCommand",
/**
* A console command
*/
CONSOLECOMMAND: "consoleCommand",
/**
* A command needs completing
*/
COMMANDCOMPLETION: "commandCompletion",
/**
* A plugin was loaded
*/
PLUGINLOADED: "pluginLoaded",
/**
* A plugin was started
*/
PLUGINSTARTED: "pluginStarted",
/**
* A plugin was loaded
*/
PLUGINUNLOADED: "pluginUnloaded",
/**
* A plugin was started
*/
PLUGINSTOPPED: "pluginStopped",
/**
* Used to query plugins if they want to add a cli option/flag
*/
CLIOPTIONS: "CLIOptions"
};
module.exports = EventTypes; | Tschrock/FezBot | modules/eventtypes.js | JavaScript | gpl-3.0 | 3,753 |
// Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Ethcore basic typenames.
use util::hash::H2048;
/// Type for a 2048-bit log-bloom, as used by our blocks.
pub type LogBloom = H2048;
/// Constant 2048-bit datum for 0. Often used as a default.
pub static ZERO_LOGBLOOM: LogBloom = H2048([0x00; 256]);
#[cfg_attr(feature="dev", allow(enum_variant_names))]
/// Semantic boolean for when a seal/signature is included.
pub enum Seal {
/// The seal/signature is included.
With,
/// The seal/signature is not included.
Without,
}
| immartian/musicoin | ethcore/src/basic_types.rs | Rust | gpl-3.0 | 1,197 |
/****************************************************************************/
/// @file GUIColorScheme.h
/// @author Michael Behrisch
/// @author Daniel Krajzewicz
/// @date Mon, 20.07.2009
/// @version $Id: GUIColorScheme.h 14425 2013-08-16 20:11:47Z behrisch $
///
//
/****************************************************************************/
// SUMO, Simulation of Urban MObility; see http://sumo-sim.org/
// Copyright (C) 2001-2013 DLR (http://www.dlr.de/) and contributors
/****************************************************************************/
//
// This file is part of SUMO.
// SUMO is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
/****************************************************************************/
#ifndef GUIColorScheme_h
#define GUIColorScheme_h
// ===========================================================================
// included modules
// ===========================================================================
#ifdef _MSC_VER
#include <windows_config.h>
#else
#include <config.h>
#endif
#include <cassert>
#include <vector>
#include <utils/common/RGBColor.h>
#include <utils/iodevices/OutputDevice.h>
// ===========================================================================
// class definitions
// ===========================================================================
/**
* @class GUIColorScheme
* @brief
*/
class GUIColorScheme {
public:
/// Constructor
GUIColorScheme(const std::string& name, const RGBColor& baseColor,
const std::string& colName = "", const bool isFixed = false)
: myName(name), myIsInterpolated(!isFixed), myIsFixed(isFixed) {
addColor(baseColor, 0, colName);
}
void setThreshold(const size_t pos, const SUMOReal threshold) {
myThresholds[pos] = threshold;
}
void setColor(const size_t pos, const RGBColor& color) {
myColors[pos] = color;
}
bool setColor(const std::string& name, const RGBColor& color) {
std::vector<std::string>::iterator nameIt = myNames.begin();
std::vector<RGBColor>::iterator colIt = myColors.begin();
for (; nameIt != myNames.end(); ++nameIt, ++colIt) {
if (*nameIt == name) {
(*colIt) = color;
return true;
}
}
return false;
}
unsigned int addColor(const RGBColor& color, const SUMOReal threshold, const std::string& name = "") {
std::vector<RGBColor>::iterator colIt = myColors.begin();
std::vector<SUMOReal>::iterator threshIt = myThresholds.begin();
std::vector<std::string>::iterator nameIt = myNames.begin();
unsigned int pos = 0;
while (threshIt != myThresholds.end() && (*threshIt) < threshold) {
++threshIt;
++colIt;
++nameIt;
pos++;
}
myColors.insert(colIt, color);
myThresholds.insert(threshIt, threshold);
myNames.insert(nameIt, name);
return pos;
}
void removeColor(const size_t pos) {
assert(pos < myColors.size());
myColors.erase(myColors.begin() + pos);
myThresholds.erase(myThresholds.begin() + pos);
myNames.erase(myNames.begin() + pos);
}
void clear() {
myColors.clear();
myThresholds.clear();
myNames.clear();
}
const RGBColor getColor(const SUMOReal value) const {
if (myColors.size() == 1 || value < myThresholds.front()) {
return myColors.front();
}
std::vector<RGBColor>::const_iterator colIt = myColors.begin() + 1;
std::vector<SUMOReal>::const_iterator threshIt = myThresholds.begin() + 1;
while (threshIt != myThresholds.end() && (*threshIt) <= value) {
++threshIt;
++colIt;
}
if (threshIt == myThresholds.end()) {
return myColors.back();
}
if (!myIsInterpolated) {
return *(colIt - 1);
}
SUMOReal lowVal = *(threshIt - 1);
return RGBColor::interpolate(*(colIt - 1), *colIt, (value - lowVal) / ((*threshIt) - lowVal));
}
void setInterpolated(const bool interpolate, SUMOReal interpolationStart = 0.f) {
myIsInterpolated = interpolate;
if (interpolate) {
myThresholds[0] = interpolationStart;
}
}
const std::string& getName() const {
return myName;
}
const std::vector<RGBColor>& getColors() const {
return myColors;
}
const std::vector<SUMOReal>& getThresholds() const {
return myThresholds;
}
bool isInterpolated() const {
return myIsInterpolated;
}
const std::vector<std::string>& getNames() const {
return myNames;
}
bool isFixed() const {
return myIsFixed;
}
bool allowsNegativeValues() const {
return myAllowNegativeValues;
}
void setAllowsNegativeValues(bool value) {
myAllowNegativeValues = value;
}
void save(OutputDevice& dev) const {
dev << " <colorScheme name=\"" << myName;
if (!myIsFixed) {
dev << "\" interpolated=\"" << myIsInterpolated;
}
dev << "\">\n";
std::vector<RGBColor>::const_iterator colIt = myColors.begin();
std::vector<SUMOReal>::const_iterator threshIt = myThresholds.begin();
std::vector<std::string>::const_iterator nameIt = myNames.begin();
while (threshIt != myThresholds.end()) {
dev << " <entry color=\"" << (*colIt);
if (!myIsFixed) {
dev << "\" threshold=\"" << (*threshIt);
}
if ((*nameIt) != "") {
dev << "\" name=\"" << (*nameIt);
}
dev << "\"/>\n";
++threshIt;
++colIt;
++nameIt;
}
dev << " </colorScheme>\n";
}
bool operator==(const GUIColorScheme& c) const {
return myName == c.myName && myColors == c.myColors && myThresholds == c.myThresholds && myIsInterpolated == c.myIsInterpolated;
}
private:
std::string myName;
std::vector<RGBColor> myColors;
std::vector<SUMOReal> myThresholds;
bool myIsInterpolated;
std::vector<std::string> myNames;
bool myIsFixed;
bool myAllowNegativeValues;
};
#endif
/****************************************************************************/
| cathyyul/sumo | src/utils/gui/settings/GUIColorScheme.h | C | gpl-3.0 | 6,638 |
namespace Allors.Repository
{
using System;
using Attributes;
#region Allors
[Id("d0f9fc0d-a3c5-46cc-ab00-4c724995fc14")]
#endregion
public partial class FaceToFaceCommunication : CommunicationEvent, Versioned
{
#region inherited properties
public CommunicationEventState PreviousCommunicationEventState { get; set; }
public CommunicationEventState LastCommunicationEventState { get; set; }
public CommunicationEventState CommunicationEventState { get; set; }
public ObjectState[] PreviousObjectStates { get; set; }
public ObjectState[] LastObjectStates { get; set; }
public ObjectState[] ObjectStates { get; set; }
public SecurityToken OwnerSecurityToken { get; set; }
public AccessControl OwnerAccessControl { get; set; }
public DateTime ScheduledStart { get; set; }
public Party[] ToParties { get; set; }
public ContactMechanism[] ContactMechanisms { get; set; }
public Party[] InvolvedParties { get; set; }
public DateTime InitialScheduledStart { get; set; }
public CommunicationEventPurpose[] EventPurposes { get; set; }
public DateTime ScheduledEnd { get; set; }
public DateTime ActualEnd { get; set; }
public WorkEffort[] WorkEfforts { get; set; }
public string Description { get; set; }
public DateTime InitialScheduledEnd { get; set; }
public Party[] FromParties { get; set; }
public string Subject { get; set; }
public Media[] Documents { get; set; }
public Case Case { get; set; }
public Priority Priority { get; set; }
public Person Owner { get; set; }
public string Note { get; set; }
public DateTime ActualStart { get; set; }
public bool SendNotification { get; set; }
public bool SendReminder { get; set; }
public DateTime RemindAt { get; set; }
public Permission[] DeniedPermissions { get; set; }
public SecurityToken[] SecurityTokens { get; set; }
public string Comment { get; set; }
public LocalisedText[] LocalisedComments { get; set; }
public Guid UniqueId { get; set; }
public User CreatedBy { get; set; }
public User LastModifiedBy { get; set; }
public DateTime CreationDate { get; set; }
public DateTime LastModifiedDate { get; set; }
#endregion
#region Allors
[Id("52b8614b-799e-4aea-a012-ea8dbc23f8dd")]
[AssociationId("ac424847-d426-4614-99a2-37c70841c454")]
[RoleId("bcf4a8df-8b57-4b3c-a6e5-f9b56c71a13b")]
#endregion
[Multiplicity(Multiplicity.ManyToMany)]
[Indexed]
[Workspace]
public Party[] Participants { get; set; }
#region Allors
[Id("95ae979f-d549-4ea1-87f0-46aa55e4b14a")]
[AssociationId("d34e4203-0bd2-4fe4-a2ef-9f9f52b49cf9")]
[RoleId("9f67b296-953d-4e04-b94d-6ffece87ceef")]
#endregion
[Size(256)]
[Workspace]
public string Location { get; set; }
#region Versioning
#region Allors
[Id("4339C173-EEAA-4B11-8E54-D96C98B2AF01")]
[AssociationId("41DDA0ED-160D-41B7-A347-CD167A957555")]
[RoleId("DE4BD7DC-B219-4CE6-9F03-4E7F4681BFEC")]
[Indexed]
#endregion
[Multiplicity(Multiplicity.OneToOne)]
[Workspace]
public FaceToFaceCommunicationVersion CurrentVersion { get; set; }
#region Allors
[Id("B97DEBD2-482A-47A7-A7A2-FBC3FD20E7B4")]
[AssociationId("428849DB-9000-4107-A68E-27FA4828344E")]
[RoleId("4F9C3CE5-3418-484C-A770-48D2EDEB6E6A")]
[Indexed]
#endregion
[Multiplicity(Multiplicity.OneToMany)]
[Workspace]
public FaceToFaceCommunicationVersion[] AllVersions { get; set; }
#endregion
#region inherited methods
public void OnBuild(){}
public void OnPostBuild(){}
public void OnPreDerive(){}
public void OnDerive(){}
public void OnPostDerive(){}
public void Cancel(){}
public void Close(){}
public void Reopen(){}
public void Delete(){}
#endregion
}
} | Allors/allors | Domains/Apps/Repository/Domain/Export/Apps/FaceToFaceCommunication.cs | C# | gpl-3.0 | 4,297 |
package com.xxl.job.admin.core.route.strategy;
import com.xxl.job.admin.core.route.ExecutorRouter;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.biz.model.TriggerParam;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* 单个JOB对应的每个执行器,使用频率最低的优先被选举
* a(*)、LFU(Least Frequently Used):最不经常使用,频率/次数
* b、LRU(Least Recently Used):最近最久未使用,时间
*
* Created by xuxueli on 17/3/10.
*/
public class ExecutorRouteLFU extends ExecutorRouter {
private static ConcurrentMap<Integer, HashMap<String, Integer>> jobLfuMap = new ConcurrentHashMap<Integer, HashMap<String, Integer>>();
private static long CACHE_VALID_TIME = 0;
public String route(int jobId, List<String> addressList) {
// cache clear
if (System.currentTimeMillis() > CACHE_VALID_TIME) {
jobLfuMap.clear();
CACHE_VALID_TIME = System.currentTimeMillis() + 1000*60*60*24;
}
// lfu item init
HashMap<String, Integer> lfuItemMap = jobLfuMap.get(jobId); // Key排序可以用TreeMap+构造入参Compare;Value排序暂时只能通过ArrayList;
if (lfuItemMap == null) {
lfuItemMap = new HashMap<String, Integer>();
jobLfuMap.putIfAbsent(jobId, lfuItemMap); // 避免重复覆盖
}
// put new
for (String address: addressList) {
if (!lfuItemMap.containsKey(address) || lfuItemMap.get(address) >1000000 ) {
lfuItemMap.put(address, new Random().nextInt(addressList.size())); // 初始化时主动Random一次,缓解首次压力
}
}
// remove old
List<String> delKeys = new ArrayList<>();
for (String existKey: lfuItemMap.keySet()) {
if (!addressList.contains(existKey)) {
delKeys.add(existKey);
}
}
if (delKeys.size() > 0) {
for (String delKey: delKeys) {
lfuItemMap.remove(delKey);
}
}
// load least userd count address
List<Map.Entry<String, Integer>> lfuItemList = new ArrayList<Map.Entry<String, Integer>>(lfuItemMap.entrySet());
Collections.sort(lfuItemList, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
Map.Entry<String, Integer> addressItem = lfuItemList.get(0);
String minAddress = addressItem.getKey();
addressItem.setValue(addressItem.getValue() + 1);
return addressItem.getKey();
}
@Override
public ReturnT<String> route(TriggerParam triggerParam, List<String> addressList) {
String address = route(triggerParam.getJobId(), addressList);
return new ReturnT<String>(address);
}
}
| xuxueli/xxl-job | xxl-job-admin/src/main/java/com/xxl/job/admin/core/route/strategy/ExecutorRouteLFU.java | Java | gpl-3.0 | 3,053 |
package com.bioxx.tfc2.gui;
import java.awt.Rectangle;
import java.util.Collection;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.inventory.GuiContainerCreative;
import net.minecraft.client.gui.inventory.GuiInventory;
import net.minecraft.client.renderer.InventoryEffectRenderer;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Slot;
import net.minecraft.stats.AchievementList;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
import com.bioxx.tfc2.Core;
import com.bioxx.tfc2.Reference;
import com.bioxx.tfc2.core.PlayerInventory;
public class GuiInventoryTFC extends InventoryEffectRenderer
{
private float xSizeLow;
private float ySizeLow;
private boolean hasEffect;
protected static final ResourceLocation UPPER_TEXTURE = new ResourceLocation(Reference.ModID+":textures/gui/inventory.png");
protected static final ResourceLocation UPPER_TEXTURE_2X2 = new ResourceLocation(Reference.ModID+":textures/gui/gui_inventory2x2.png");
protected static final ResourceLocation EFFECTS_TEXTURE = new ResourceLocation(Reference.ModID+":textures/gui/inv_effects.png");
protected EntityPlayer player;
protected Slot activeSlot;
public GuiInventoryTFC(EntityPlayer player)
{
super(player.inventoryContainer);
this.allowUserInput = true;
player.addStat(AchievementList.OPEN_INVENTORY, 1);
xSize = 176;
ySize = 102 + PlayerInventory.invYSize;
this.player = player;
}
@Override
protected void drawGuiContainerBackgroundLayer(float par1, int par2, int par3)
{
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
if(player.getEntityData().hasKey("craftingTable"))
Core.bindTexture(UPPER_TEXTURE);
else
Core.bindTexture(UPPER_TEXTURE_2X2);
int k = this.guiLeft;
int l = this.guiTop;
this.drawTexturedModalRect(k, l, 0, 0, this.xSize, 102);
//Draw the player avatar
GuiInventory.drawEntityOnScreen(k + 51, l + 75, 30, k + 51 - this.xSizeLow, l + 75 - 50 - this.ySizeLow, this.mc.player);
PlayerInventory.drawInventory(this, width, height, ySize - PlayerInventory.invYSize);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
}
@Override
protected void drawGuiContainerForegroundLayer(int par1, int par2)
{
//this.fontRenderer.drawString(I18n.format("container.crafting", new Object[0]), 86, 7, 4210752);
}
@Override
/**
* Called from the main game loop to update the screen.
*/
public void updateScreen()
{
if (this.mc.playerController.isInCreativeMode())
this.mc.displayGuiScreen(new GuiContainerCreative(player));
}
@Override
public void initGui()
{
super.buttonList.clear();
if (this.mc.playerController.isInCreativeMode())
{
this.mc.displayGuiScreen(new GuiContainerCreative(this.mc.player));
}
else
super.initGui();
if (!this.mc.player.getActivePotionEffects().isEmpty())
{
//this.guiLeft = 160 + (this.width - this.xSize - 200) / 2;
this.guiLeft = (this.width - this.xSize) / 2;
this.hasEffect = true;
}
buttonList.clear();
buttonList.add(new GuiInventoryButton(0, new Rectangle(guiLeft+176, guiTop + 3, 25, 20),
new Rectangle(0, 103, 25, 20), Core.translate("gui.Inventory.Inventory"), new Rectangle(1,223,32,32)));
buttonList.add(new GuiInventoryButton(1, new Rectangle(guiLeft+176, guiTop + 22, 25, 20),
new Rectangle(0, 103, 25, 20), Core.translate("gui.Inventory.Skills"), new Rectangle(100,223,32,32)));
buttonList.add(new GuiInventoryButton(2, new Rectangle(guiLeft+176, guiTop + 41, 25, 20),
new Rectangle(0, 103, 25, 20), Core.translate("gui.Calendar.Calendar"), new Rectangle(34,223,32,32)));
buttonList.add(new GuiInventoryButton(3, new Rectangle(guiLeft+176, guiTop + 60, 25, 20),
new Rectangle(0, 103, 25, 20), Core.translate("gui.Inventory.Health"), new Rectangle(67,223,32,32)));
}
@Override
protected void actionPerformed(GuiButton guibutton)
{
//Removed during port
if (guibutton.id == 1)
Minecraft.getMinecraft().displayGuiScreen(new GuiSkills(player));
/*else if (guibutton.id == 2)
Minecraft.getMinecraft().displayGuiScreen(new GuiCalendar(player));*/
else if (guibutton.id == 3)
Minecraft.getMinecraft().displayGuiScreen(new GuiHealth(player));
}
@Override
public void drawScreen(int par1, int par2, float par3)
{
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
super.drawScreen(par1, par2, par3);
this.xSizeLow = par1;
this.ySizeLow = par2;
if(hasEffect)
displayDebuffEffects();
//removed during port
/*for (int j1 = 0; j1 < this.inventorySlots.inventorySlots.size(); ++j1)
{
Slot slot = (Slot)this.inventorySlots.inventorySlots.get(j1);
if (this.isMouseOverSlot(slot, par1, par2) && slot.func_111238_b())
this.activeSlot = slot;
}*/
}
protected boolean isMouseOverSlot(Slot par1Slot, int par2, int par3)
{
return this.isPointInRegion(par1Slot.xPos, par1Slot.yPos, 16, 16, par2, par3);
}
/**
* Displays debuff/potion effects that are currently being applied to the player
*/
private void displayDebuffEffects()
{
int var1 = this.guiLeft - 124;
int var2 = this.guiTop;
Collection var4 = this.mc.player.getActivePotionEffects();
//Remvoed during port
/*if (!var4.isEmpty())
{
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glDisable(GL11.GL_LIGHTING);
int var6 = 33;
if (var4.size() > 5)
var6 = 132 / (var4.size() - 1);
for (Iterator var7 = this.mc.player.getActivePotionEffects().iterator(); var7.hasNext(); var2 += var6)
{
PotionEffect var8 = (PotionEffect)var7.next();
Potion var9 = Potion.potionTypes[var8.getPotionID()] instanceof TFCPotion ?
((TFCPotion) Potion.potionTypes[var8.getPotionID()]) :
Potion.potionTypes[var8.getPotionID()];
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
TFC_Core.bindTexture(EFFECTS_TEXTURE);
this.drawTexturedModalRect(var1, var2, 0, 166, 140, 32);
if (var9.hasStatusIcon())
{
int var10 = var9.getStatusIconIndex();
this.drawTexturedModalRect(var1 + 6, var2 + 7, 0 + var10 % 8 * 18, 198 + var10 / 8 * 18, 18, 18);
}
String var12 = Core.translate(var9.getName());
if (var8.getAmplifier() == 1)
var12 = var12 + " II";
else if (var8.getAmplifier() == 2)
var12 = var12 + " III";
else if (var8.getAmplifier() == 3)
var12 = var12 + " IV";
this.fontRenderer.drawStringWithShadow(var12, var1 + 10 + 18, var2 + 6, 16777215);
String var11 = Potion.getDurationString(var8);
this.fontRenderer.drawStringWithShadow(var11, var1 + 10 + 18, var2 + 6 + 10, 8355711);
}
}*/
}
private long spamTimer;
@Override
protected boolean checkHotbarKeys(int keycode)
{
/*if(this.activeSlot != null && this.activeSlot.slotNumber == 0 && this.activeSlot.getHasStack() &&
this.activeSlot.getStack().getItem() instanceof IFood)
return false;*/
return super.checkHotbarKeys(keycode);
}
private int getEmptyCraftSlot()
{
if(this.inventorySlots.getSlot(4).getStack() == null)
return 4;
if(this.inventorySlots.getSlot(1).getStack() == null)
return 1;
if(this.inventorySlots.getSlot(2).getStack() == null)
return 2;
if(this.inventorySlots.getSlot(3).getStack() == null)
return 3;
if(player.getEntityData().hasKey("craftingTable"))
{
if(this.inventorySlots.getSlot(45).getStack() == null)
return 45;
if(this.inventorySlots.getSlot(46).getStack() == null)
return 46;
if(this.inventorySlots.getSlot(47).getStack() == null)
return 47;
if(this.inventorySlots.getSlot(48).getStack() == null)
return 48;
if(this.inventorySlots.getSlot(49).getStack() == null)
return 49;
}
return -1;
}
}
| CHeuberger/TFC2 | src/Common/com/bioxx/tfc2/gui/GuiInventoryTFC.java | Java | gpl-3.0 | 7,667 |
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_show_tab.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: pgritsen <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/08/05 19:31:02 by pgritsen #+# #+# */
/* Updated: 2017/08/05 19:31:04 by pgritsen ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_stock_par.h"
void ft_putchar(char c);
void ft_putstr(char *str)
{
int it;
it = 0;
while (str[it] != 0)
ft_putchar(str[it++]);
}
void ft_putnbr(int nb)
{
long int mult;
long int nb_t;
mult = 1;
nb_t = nb;
if (nb_t < 0)
{
ft_putchar('-');
nb_t *= -1;
}
if (nb_t == 0)
ft_putchar('0');
while (nb_t / mult != 0)
mult *= 10;
while (mult > 1)
{
mult /= 10;
if (mult == 0)
ft_putchar(nb_t + 48);
else
ft_putchar(nb_t / mult + 48);
nb_t %= mult;
}
}
void ft_show_tab(struct s_stock_par *par)
{
int it;
int argv_it;
it = 0;
while (par[it].str)
{
ft_putstr(par[it].copy);
ft_putchar('\n');
ft_putnbr(par[it].size_param);
ft_putchar('\n');
argv_it = 0;
while (par[it].tab[argv_it])
{
ft_putstr(par[it].tab[argv_it]);
ft_putchar('\n');
argv_it++;
}
it++;
}
}
| CoZZmOnAvT/42-Piscine-C | d08/tmp/ex06/ft_show_tab.c | C | gpl-3.0 | 1,733 |
<?php
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=127.0.0.1;dbname=manga_ranobe_storage_app',
'username' => 'travis',
'password' => '',
'charset' => 'utf8',
]; | gunmetal313/MangaRanobeStorageApp | helper_scripts/travis/db_mysql.php | PHP | gpl-3.0 | 198 |
// Copyright 2008 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef V8_V8_DEBUG_H_
#define V8_V8_DEBUG_H_
#include "v8.h"
#ifdef _WIN32
typedef int int32_t;
typedef unsigned int uint32_t;
typedef unsigned short uint16_t; // NOLINT
typedef long long int64_t; // NOLINT
// Setup for Windows DLL export/import. See v8.h in this directory for
// information on how to build/use V8 as a DLL.
#if defined(BUILDING_V8_SHARED) && defined(USING_V8_SHARED)
#error both BUILDING_V8_SHARED and USING_V8_SHARED are set - please check the\
build configuration to ensure that at most one of these is set
#endif
#ifdef BUILDING_V8_SHARED
#define EXPORT __declspec(dllexport)
#elif USING_V8_SHARED
#define EXPORT __declspec(dllimport)
#else
#define EXPORT
#endif
#else // _WIN32
// Setup for Linux shared library export. See v8.h in this directory for
// information on how to build/use V8 as shared library.
#if defined(__GNUC__) && (__GNUC__ >= 4) && defined(V8_SHARED)
#define EXPORT __attribute__ ((visibility("default")))
#else // defined(__GNUC__) && (__GNUC__ >= 4)
#define EXPORT
#endif // defined(__GNUC__) && (__GNUC__ >= 4)
#endif // _WIN32
/**
* Debugger support for the V8 JavaScript engine.
*/
namespace v8 {
// Debug events which can occur in the V8 JavaScript engine.
enum DebugEvent {
Break = 1,
Exception = 2,
NewFunction = 3,
BeforeCompile = 4,
AfterCompile = 5,
ScriptCollected = 6,
BreakForCommand = 7
};
class EXPORT Debug {
public:
/**
* A client object passed to the v8 debugger whose ownership will be taken by
* it. v8 is always responsible for deleting the object.
*/
class ClientData {
public:
virtual ~ClientData() {}
};
/**
* A message object passed to the debug message handler.
*/
class Message {
public:
/**
* Check type of message.
*/
virtual bool IsEvent() const = 0;
virtual bool IsResponse() const = 0;
virtual DebugEvent GetEvent() const = 0;
/**
* Indicate whether this is a response to a continue command which will
* start the VM running after this is processed.
*/
virtual bool WillStartRunning() const = 0;
/**
* Access to execution state and event data. Don't store these cross
* callbacks as their content becomes invalid. These objects are from the
* debugger event that started the debug message loop.
*/
virtual Handle<Object> GetExecutionState() const = 0;
virtual Handle<Object> GetEventData() const = 0;
/**
* Get the debugger protocol JSON.
*/
virtual Handle<String> GetJSON() const = 0;
/**
* Get the context active when the debug event happened. Note this is not
* the current active context as the JavaScript part of the debugger is
* running in it's own context which is entered at this point.
*/
virtual Handle<Context> GetEventContext() const = 0;
/**
* Client data passed with the corresponding request if any. This is the
* client_data data value passed into Debug::SendCommand along with the
* request that led to the message or NULL if the message is an event. The
* debugger takes ownership of the data and will delete it even if there is
* no message handler.
*/
virtual ClientData* GetClientData() const = 0;
virtual ~Message() {}
};
/**
* An event details object passed to the debug event listener.
*/
class EventDetails {
public:
/**
* Event type.
*/
virtual DebugEvent GetEvent() const = 0;
/**
* Access to execution state and event data of the debug event. Don't store
* these cross callbacks as their content becomes invalid.
*/
virtual Handle<Object> GetExecutionState() const = 0;
virtual Handle<Object> GetEventData() const = 0;
/**
* Get the context active when the debug event happened. Note this is not
* the current active context as the JavaScript part of the debugger is
* running in it's own context which is entered at this point.
*/
virtual Handle<Context> GetEventContext() const = 0;
/**
* Client data passed with the corresponding callbak whet it was registered.
*/
virtual Handle<Value> GetCallbackData() const = 0;
/**
* Client data passed to DebugBreakForCommand function. The
* debugger takes ownership of the data and will delete it even if
* there is no message handler.
*/
virtual ClientData* GetClientData() const = 0;
virtual ~EventDetails() {}
};
/**
* Debug event callback function.
*
* \param event the type of the debug event that triggered the callback
* (enum DebugEvent)
* \param exec_state execution state (JavaScript object)
* \param event_data event specific data (JavaScript object)
* \param data value passed by the user to SetDebugEventListener
*/
typedef void (*EventCallback)(DebugEvent event,
Handle<Object> exec_state,
Handle<Object> event_data,
Handle<Value> data);
/**
* Debug event callback function.
*
* \param event_details object providing information about the debug event
*
* A EventCallback2 does not take possession of the event data,
* and must not rely on the data persisting after the handler returns.
*/
typedef void (*EventCallback2)(const EventDetails& event_details);
/**
* Debug message callback function.
*
* \param message the debug message handler message object
* \param length length of the message
* \param client_data the data value passed when registering the message handler
* A MessageHandler does not take possession of the message string,
* and must not rely on the data persisting after the handler returns.
*
* This message handler is deprecated. Use MessageHandler2 instead.
*/
typedef void (*MessageHandler)(const uint16_t* message, int length,
ClientData* client_data);
/**
* Debug message callback function.
*
* \param message the debug message handler message object
* A MessageHandler does not take possession of the message data,
* and must not rely on the data persisting after the handler returns.
*/
typedef void (*MessageHandler2)(const Message& message);
/**
* Debug host dispatch callback function.
*/
typedef void (*HostDispatchHandler)();
/**
* Callback function for the host to ensure debug messages are processed.
*/
typedef void (*DebugMessageDispatchHandler)();
// Set a C debug event listener.
static bool SetDebugEventListener(EventCallback that,
Handle<Value> data = Handle<Value>());
static bool SetDebugEventListener2(EventCallback2 that,
Handle<Value> data = Handle<Value>());
// Set a JavaScript debug event listener.
static bool SetDebugEventListener(v8::Handle<v8::Object> that,
Handle<Value> data = Handle<Value>());
// Schedule a debugger break to happen when JavaScript code is run.
static void DebugBreak();
// Remove scheduled debugger break if it has not happened yet.
static void CancelDebugBreak();
// Break execution of JavaScript (this method can be invoked from a
// non-VM thread) for further client command execution on a VM
// thread. Client data is then passed in EventDetails to
// EventCallback at the moment when the VM actually stops.
static void DebugBreakForCommand(ClientData* data = NULL);
// Message based interface. The message protocol is JSON. NOTE the message
// handler thread is not supported any more parameter must be false.
static void SetMessageHandler(MessageHandler handler,
bool message_handler_thread = false);
static void SetMessageHandler2(MessageHandler2 handler);
static void SendCommand(const uint16_t* command, int length,
ClientData* client_data = NULL);
// Dispatch interface.
static void SetHostDispatchHandler(HostDispatchHandler handler,
int period = 100);
/**
* Register a callback function to be called when a debug message has been
* received and is ready to be processed. For the debug messages to be
* processed V8 needs to be entered, and in certain embedding scenarios this
* callback can be used to make sure V8 is entered for the debug message to
* be processed. Note that debug messages will only be processed if there is
* a V8 break. This can happen automatically by using the option
* --debugger-auto-break.
* \param provide_locker requires that V8 acquires v8::Locker for you before
* calling handler
*/
static void SetDebugMessageDispatchHandler(
DebugMessageDispatchHandler handler, bool provide_locker = false);
/**
* Run a JavaScript function in the debugger.
* \param fun the function to call
* \param data passed as second argument to the function
* With this call the debugger is entered and the function specified is called
* with the execution state as the first argument. This makes it possible to
* get access to information otherwise not available during normal JavaScript
* execution e.g. details on stack frames. Receiver of the function call will
* be the debugger context global object, however this is a subject to change.
* The following example show a JavaScript function which when passed to
* v8::Debug::Call will return the current line of JavaScript execution.
*
* \code
* function frame_source_line(exec_state) {
* return exec_state.frame(0).sourceLine();
* }
* \endcode
*/
static Local<Value> Call(v8::Handle<v8::Function> fun,
Handle<Value> data = Handle<Value>());
/**
* Returns a mirror object for the given object.
*/
static Local<Value> GetMirror(v8::Handle<v8::Value> obj);
/**
* Enable the V8 builtin debug agent. The debugger agent will listen on the
* supplied TCP/IP port for remote debugger connection.
* \param name the name of the embedding application
* \param port the TCP/IP port to listen on
* \param wait_for_connection whether V8 should pause on a first statement
* allowing remote debugger to connect before anything interesting happened
*/
static bool EnableAgent(const char* name, int port,
bool wait_for_connection = false);
/**
* Makes V8 process all pending debug messages.
*
* From V8 point of view all debug messages come asynchronously (e.g. from
* remote debugger) but they all must be handled synchronously: V8 cannot
* do 2 things at one time so normal script execution must be interrupted
* for a while.
*
* Generally when message arrives V8 may be in one of 3 states:
* 1. V8 is running script; V8 will automatically interrupt and process all
* pending messages (however auto_break flag should be enabled);
* 2. V8 is suspended on debug breakpoint; in this state V8 is dedicated
* to reading and processing debug messages;
* 3. V8 is not running at all or has called some long-working C++ function;
* by default it means that processing of all debug message will be deferred
* until V8 gets control again; however, embedding application may improve
* this by manually calling this method.
*
* It makes sense to call this method whenever a new debug message arrived and
* V8 is not already running. Method v8::Debug::SetDebugMessageDispatchHandler
* should help with the former condition.
*
* Technically this method in many senses is equivalent to executing empty
* script:
* 1. It does nothing except for processing all pending debug messages.
* 2. It should be invoked with the same precautions and from the same context
* as V8 script would be invoked from, because:
* a. with "evaluate" command it can do whatever normal script can do,
* including all native calls;
* b. no other thread should call V8 while this method is running
* (v8::Locker may be used here).
*
* "Evaluate" debug command behavior currently is not specified in scope
* of this method.
*/
static void ProcessDebugMessages();
/**
* Debugger is running in it's own context which is entered while debugger
* messages are being dispatched. This is an explicit getter for this
* debugger context. Note that the content of the debugger context is subject
* to change.
*/
static Local<Context> GetDebugContext();
};
} // namespace v8
#undef EXPORT
#endif // V8_V8_DEBUG_H_
| toshiroyamada/Max-v8 | lib/v8/v8-debug.h | C | gpl-3.0 | 14,194 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* FUEL CMS
* http://www.getfuelcms.com
*
* An open source Content Management System based on the
* Codeigniter framework (http://codeigniter.com)
*
* @package FUEL CMS
* @author David McReynolds @ Daylight Studio
* @copyright Copyright (c) 2015, Run for Daylight LLC.
* @license http://docs.getfuelcms.com/general/license
* @link http://www.getfuelcms.com
*/
// ------------------------------------------------------------------------
/**
* An alternative to the CI Validation class
*
* This class is used in MY_Model and the Form class. Does not require
* post data and is a little more generic then the CI Validation class.
* The <a href="[user_guide_url]helpers/validator_helper">validator_helper</a>
* that contains many helpful rule functions is automatically loaded.
*
* @package FUEL CMS
* @subpackage Libraries
* @category Libraries
* @author David McReynolds @ Daylight Studio
* @link http://docs.getfuelcms.com/libraries/validator
*/
class Validator {
public $field_error_delimiter = "\n"; // delimiter for rendering multiple errors for a field
public $stack_field_errors = FALSE; // stack multiple field errors if any or just replace with the newest
public $register_to_global_errors = TRUE; // will add to the globals error array
public $load_helpers = TRUE; // will automatically load the validator helpers
protected $_fields = array(); // fields to validate
protected $_errors = array(); // errors after running validation
// --------------------------------------------------------------------
/**
* Constructor
*
* Accepts an associative array as input, containing preferences (optional)
*
* @access public
* @param array config preferences
* @return void
*/
public function __construct ($params = array()) {
if (!defined('GLOBAL_ERRORS'))
{
define('GLOBAL_ERRORS', '__ERRORS__');
}
if (!isset($GLOBALS[GLOBAL_ERRORS])) $GLOBALS[GLOBAL_ERRORS] = array();
if (function_exists('get_instance') && $this->load_helpers)
{
$CI =& get_instance();
$CI->load->helper('validator');
}
if (count($params) > 0)
{
$this->initialize($params);
}
}
// --------------------------------------------------------------------
/**
* Initialize preferences
*
* @access public
* @param array
* @return void
*/
public function initialize($params = array())
{
$this->reset();
$this->set_params($params);
}
// --------------------------------------------------------------------
/**
* Set object parameters
*
* @access public
* @param array
* @return void
*/
function set_params($params)
{
if (is_array($params) AND count($params) > 0)
{
foreach ($params as $key => $val)
{
if (isset($this->$key))
{
$this->$key = $val;
}
}
}
}
// --------------------------------------------------------------------
/**
* Add processing rule (function) to an input variable.
* The <a href="[user_guide_url]helpers/validator_helper">validator_helper</a> contains many helpful rule functions you can use
*
* @access public
* @param string key in processing array to assign to rule. Often times its the same name as the field input
* @param string error message
* @param string function for processing
* @param mixed function arguments with the first usually being the posted value. If multiple arguments need to be passed, then you can use an array.
* @return void
*/
public function add_rule($field, $func, $msg, $params = array())
{
if (empty($fields[$field])) $fields[$field] = array();
settype($params, 'array');
// if params are emtpy then we will look in the $_POST
if (empty($params))
{
if (!empty($_POST[$field])) $params = $_POST[$field];
if (empty($params[$field]) AND !empty($_FILES[$field])) $params = $_FILES[$field];
}
$rule = new Validator_Rule($func, $msg, $params);
$this->_fields[$field][] = $rule;
}
// --------------------------------------------------------------------
/**
* Removes rule from validation
*
* @access public
* @param string field to remove
* @param string key for rule (can have more then one rule for a field) (optional)
* @return void
*/
public function remove_rule($field, $func = NULL)
{
if (!empty($func))
{
if (!isset($this->_fields[$field]))
{
return;
}
foreach($this->_fields[$field] as $key => $rule)
{
if ($rule->func == $func)
{
unset($this->_fields[$field][$key]);
}
}
}
else
{
// remove all rules
unset($this->_fields[$field]);
}
}
// --------------------------------------------------------------------
/**
* Runs through validation
*
* @access public
* @param array assoc array of values to validate (optional)
* @param boolean exit on first error? (optional)
* @param boolean reset validation errors (optional)
* @return boolean
*/
public function validate($values = array(), $stop_on_first = FALSE, $reset = TRUE)
{
// reset errors to start with a fresh validation
if ($reset) $this->_errors = array();
//if (empty($values)) $values = $_POST;
if (empty($values))
{
$values = array_keys($this->_fields);
}
else if (!array_key_exists(0, $values)) // detect if it is an associative array and if so just use keys
{
$values = array_keys($values);
}
foreach($values as $key)
{
if (!empty($this->_fields[$key]))
{
$rules = $this->_fields[$key];
foreach($rules as $key2 => $val2)
{
$ok = $val2->run();
if (!$ok)
{
$this->catch_error($val2->get_message(), $key);
if (!empty($stop_on_first)) return FALSE;
}
}
}
}
return $this->is_valid();
}
// --------------------------------------------------------------------
/**
* Checks to see if it validates
*
* @access public
* @return boolean
*/
public function is_valid()
{
return (count($this->_errors) <= 0);
}
// --------------------------------------------------------------------
/**
* Catches error into the global array
*
* @access public
* @param string msg error message
* @param mixed key to identify error message
* @return string key of variable input
*/
public function catch_error($msg, $key = NULL)
{
if (empty($key)) $key = count($this->_errors);
if ($this->stack_field_errors)
{
$this->_errors[$key] = (!empty($this->_errors[$key])) ? $this->_errors[$key] = $this->_errors[$key].$this->field_error_delimiter.$msg : $msg;
}
else
{
$this->_errors[$key] = $msg;
}
if ($this->register_to_global_errors)
{
$GLOBALS[GLOBAL_ERRORS][$key] = $this->_errors[$key];
}
return $key;
}
// --------------------------------------------------------------------
/**
* Catches multiple errors
*
* @access public
* @param array of error messages
* @param key of error message if a single message
* @return string key of variable input
*/
public function catch_errors($errors, $key = NULL)
{
if (is_array($errors))
{
foreach($errors as $key => $val)
{
if (is_int($key))
{
$this->catch_error($val);
}
else
{
$this->catch_error($val, $key);
}
}
}
else
{
return $this->catch_error($errors, $key);
}
}
// --------------------------------------------------------------------
/**
* Retrieve errors
*
* @access public
* @return assoc array of errors and messages
*/
public function get_errors()
{
return $this->_errors;
}
// --------------------------------------------------------------------
/**
* Retrieves a single error
*
* @access public
* @param mixed key to error message
* @return string error message
*/
public function get_error($key)
{
if (!empty($this->_errors[$key]))
{
return $this->_errors[$key];
}
else
{
return NULL;
}
}
// --------------------------------------------------------------------
/**
* Retrieves the last error message
*
* @access public
* @return string error message
*/
public function get_last_error()
{
if (!empty($this->_errors))
{
return end($this->_errors);
}
else
{
return NULL;
}
}
// --------------------------------------------------------------------
/**
* Returns the fields with rules
* @access public
* @return array
*/
public function fields()
{
return $this->_fields;
}
// --------------------------------------------------------------------
/**
* Same as reset
*
* @access public
* @return void
*/
public function clear()
{
$this->reset();
}
// --------------------------------------------------------------------
/**
* Resets rules and errors
* @access public
* @return void
*/
public function reset($remove_fields = TRUE)
{
$this->_errors = array();
if ($remove_fields)
{
$this->_fields = array();
}
}
}
// ------------------------------------------------------------------------
/**
* Validation rule object
*
* @package FUEL CMS
* @subpackage Libraries
* @category Libraries
* @author David McReynolds @ Daylight Studio
* @autodoc FALSE
*/
class Validator_Rule {
public $func; // function to execute that will return TRUE/FALSE
public $msg; // message to be display on error
public $args; // arguments to pass to the function
/**
* Validator rule constructor
*
* @param string function to execute that will return TRUE/FALSE
* @param string message to be display on error
* @param mixed arguments to pass to the function
*/
public function __construct($func, $msg, $args)
{
$this->func = $func;
$this->msg = $msg;
if (!is_array($args))
{
$this->args[] = $args;
}
else if (empty($args))
{ // create first argument
$this->args[] = '';
}
else
{
$this->args = $args;
}
}
/**
* Runs the rules function
*
* @access public
* @return boolean (should return TRUE/FALSE but it depends on the function of course)
*/
public function run()
{
return call_user_func_array($this->func, $this->args);
}
/**
* Retrieve errors
*
* @access public
* @return string error message
*/
public function get_message()
{
return $this->msg;
}
}
/* End of file Validator.php */
/* Location: ./modules/fuel/libraries/Validator.php */ | scotton34/sample | fuel/modules/fuel/libraries/Validator.php | PHP | gpl-3.0 | 10,348 |
/*
* GPXParser.java
*
* Copyright (c) 2012, AlternativeVision. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.alternativevision.gpx;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.alternativevision.gpx.beans.GPX;
import org.alternativevision.gpx.beans.Route;
import org.alternativevision.gpx.beans.Track;
import org.alternativevision.gpx.beans.Waypoint;
import org.alternativevision.gpx.extensions.IExtensionParser;
import org.alternativevision.gpx.types.FixType;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* <p>This class defines methods for parsing and writing gpx files.</p>
* <br>
* Usage for parsing a gpx file into a {@link GPX} object:<br>
* <code>
* GPXParser p = new GPXParser();<br>
* FileInputStream in = new FileInputStream("inFile.gpx");<br>
* GPX gpx = p.parseGPX(in);<br>
* </code>
* <br>
* Usage for writing a {@link GPX} object to a file:<br>
* <code>
* GPXParser p = new GPXParser();<br>
* FileOutputStream out = new FileOutputStream("outFile.gpx");<br>
* p.writeGPX(gpx, out);<br>
* out.close();<br>
* </code>
*/
public class GPXParser {
private ArrayList<IExtensionParser> extensionParsers = new ArrayList<IExtensionParser>();
private Logger logger = Logger.getLogger(this.getClass().getName());
private DocumentBuilderFactory docFactory= DocumentBuilderFactory.newInstance();
private TransformerFactory tFactory = TransformerFactory.newInstance();
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss");
private SimpleDateFormat sdfZ = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss'Z'");
/**
* Adds a new extension parser to be used when parsing a gpx steam
*
* @param parser an instance of a {@link IExtensionParser} implementation
*/
public void addExtensionParser(IExtensionParser parser) {
extensionParsers.add(parser);
}
/**
* Removes an extension parser previously added
*
* @param parser an instance of a {@link IExtensionParser} implementation
*/
public void removeExtensionParser(IExtensionParser parser) {
extensionParsers.remove(parser);
}
public GPX parseGPX(File gpxFile) throws IOException, ParserConfigurationException, SAXException, IOException {
InputStream in = FileUtils.openInputStream(gpxFile);
GPX gpx = parseGPX(in);
in.close();
return gpx;
}
/**
* Parses a stream containing GPX data
*
* @param in the input stream
* @return {@link GPX} object containing parsed data, or null if no gpx data was found in the seream
* @throws ParserConfigurationException
* @throws SAXException
* @throws IOException
*/
public GPX parseGPX(InputStream in) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilder builder = docFactory.newDocumentBuilder();
Document doc = builder.parse(in);
Node firstChild = doc.getFirstChild();
if( firstChild != null && GPXConstants.GPX_NODE.equals(firstChild.getNodeName())) {
GPX gpx = new GPX();
NamedNodeMap attrs = firstChild.getAttributes();
for(int idx = 0; idx < attrs.getLength(); idx++) {
Node attr = attrs.item(idx);
if(GPXConstants.VERSION_ATTR.equals(attr.getNodeName())) {
gpx.setVersion(attr.getNodeValue());
} else if(GPXConstants.CREATOR_ATTR.equals(attr.getNodeName())) {
gpx.setCreator(attr.getNodeValue());
}
}
NodeList nodes = firstChild.getChildNodes();
if(logger.isDebugEnabled())logger.debug("Found " +nodes.getLength()+ " child nodes. Start parsing ...");
for(int idx = 0; idx < nodes.getLength(); idx++) {
Node currentNode = nodes.item(idx);
if(GPXConstants.WPT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("Found waypoint node. Start parsing...");
Waypoint w = parseWaypoint(currentNode);
if(w!= null) {
logger.info("Add waypoint to gpx data. [waypointName="+ w.getName() + "]");
gpx.addWaypoint(w);
}
} else if(GPXConstants.TRK_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("Found track node. Start parsing...");
Track trk = parseTrack(currentNode);
if(trk!= null) {
logger.info("Add track to gpx data. [trackName="+ trk.getName() + "]");
gpx.addTrack(trk);
}
} else if(GPXConstants.EXTENSIONS_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("Found extensions node. Start parsing...");
Iterator<IExtensionParser> it = extensionParsers.iterator();
while(it.hasNext()) {
IExtensionParser parser = it.next();
Object data = parser.parseGPXExtension(currentNode);
gpx.addExtensionData(parser.getId(), data);
}
} else if(GPXConstants.RTE_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("Found route node. Start parsing...");
Route rte = parseRoute(currentNode);
if(rte!= null) {
logger.info("Add route to gpx data. [routeName="+ rte.getName() + "]");
gpx.addRoute(rte);
}
}
}
//TODO: parse route node
return gpx;
} else {
logger.error("FATAL!! - Root node is not gpx.");
}
return null;
}
/**
* Parses a wpt node into a Waypoint object
*
* @param node
* @return Waypoint object with info from the received node
*/
private Waypoint parseWaypoint(Node node) {
if(node == null) {
logger.error("null node received");
return null;
}
Waypoint w = new Waypoint();
NamedNodeMap attrs = node.getAttributes();
//check for lat attribute
Node latNode = attrs.getNamedItem(GPXConstants.LAT_ATTR);
if(latNode != null) {
Double latVal = null;
try {
latVal = Double.parseDouble(latNode.getNodeValue());
} catch(NumberFormatException ex) {
logger.error("bad lat value in waypoint data: " + latNode.getNodeValue());
}
w.setLatitude(latVal);
} else {
logger.warn("no lat value in waypoint data.");
}
//check for lon attribute
Node lonNode = attrs.getNamedItem(GPXConstants.LON_ATTR);
if(lonNode != null) {
Double lonVal = null;
try {
lonVal = Double.parseDouble(lonNode.getNodeValue());
} catch(NumberFormatException ex) {
logger.error("bad lon value in waypoint data: " + lonNode.getNodeValue());
}
w.setLongitude(lonVal);
} else {
logger.warn("no lon value in waypoint data.");
}
NodeList childNodes = node.getChildNodes();
if(childNodes != null) {
for(int idx = 0; idx < childNodes.getLength(); idx++) {
Node currentNode = childNodes.item(idx);
if(GPXConstants.ELE_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found ele node in waypoint data");
w.setElevation(getNodeValueAsDouble(currentNode));
} else if(GPXConstants.TIME_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found time node in waypoint data");
w.setTime(getNodeValueAsDate(currentNode));
} else if(GPXConstants.NAME_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found name node in waypoint data");
w.setName(getNodeValueAsString(currentNode));
} else if(GPXConstants.CMT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found cmt node in waypoint data");
w.setComment(getNodeValueAsString(currentNode));
} else if(GPXConstants.DESC_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found desc node in waypoint data");
w.setDescription(getNodeValueAsString(currentNode));
} else if(GPXConstants.SRC_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found src node in waypoint data");
w.setSrc(getNodeValueAsString(currentNode));
} else if(GPXConstants.MAGVAR_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found magvar node in waypoint data");
w.setMagneticDeclination(getNodeValueAsDouble(currentNode));
} else if(GPXConstants.GEOIDHEIGHT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found geoidheight node in waypoint data");
w.setGeoidHeight(getNodeValueAsDouble(currentNode));
} else if(GPXConstants.LINK_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found link node in waypoint data");
//TODO: parse link
//w.setGeoidHeight(getNodeValueAsDouble(currentNode));
} else if(GPXConstants.SYM_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found sym node in waypoint data");
w.setSym(getNodeValueAsString(currentNode));
} else if(GPXConstants.FIX_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found fix node in waypoint data");
w.setFix(getNodeValueAsFixType(currentNode));
} else if(GPXConstants.TYPE_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found type node in waypoint data");
w.setType(getNodeValueAsString(currentNode));
} else if(GPXConstants.SAT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found sat node in waypoint data");
w.setSat(getNodeValueAsInteger(currentNode));
} else if(GPXConstants.HDOP_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found hdop node in waypoint data");
w.setHdop(getNodeValueAsDouble(currentNode));
} else if(GPXConstants.VDOP_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found vdop node in waypoint data");
w.setVdop(getNodeValueAsDouble(currentNode));
} else if(GPXConstants.PDOP_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found pdop node in waypoint data");
w.setPdop(getNodeValueAsDouble(currentNode));
} else if(GPXConstants.AGEOFGPSDATA_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found ageofgpsdata node in waypoint data");
w.setAgeOfGPSData(getNodeValueAsDouble(currentNode));
} else if(GPXConstants.DGPSID_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found dgpsid node in waypoint data");
w.setDgpsid(getNodeValueAsInteger(currentNode));
} else if(GPXConstants.EXTENSIONS_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found extensions node in waypoint data");
Iterator<IExtensionParser> it = extensionParsers.iterator();
while(it.hasNext()) {
IExtensionParser parser = it.next();
Object data = parser.parseWaypointExtension(currentNode);
w.addExtensionData(parser.getId(), data);
}
}
}
} else {
if(logger.isDebugEnabled())logger.debug("no child nodes found in waypoint");
}
return w;
}
private Track parseTrack(Node node) {
if(node == null) {
logger.error("null node received");
return null;
}
Track trk = new Track();
NodeList nodes = node.getChildNodes();
if(nodes != null) {
for(int idx = 0; idx < nodes.getLength(); idx++) {
Node currentNode = nodes.item(idx);
if(GPXConstants.NAME_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node name found");
trk.setName(getNodeValueAsString(currentNode));
} else if(GPXConstants.CMT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node cmt found");
trk.setComment(getNodeValueAsString(currentNode));
} else if(GPXConstants.DESC_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node desc found");
trk.setDescription(getNodeValueAsString(currentNode));
} else if(GPXConstants.SRC_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node src found");
trk.setSrc(getNodeValueAsString(currentNode));
} else if(GPXConstants.LINK_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node link found");
//TODO: parse link
//trk.setLink(getNodeValueAsLink(currentNode));
} else if(GPXConstants.NUMBER_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node number found");
trk.setNumber(getNodeValueAsInteger(currentNode));
} else if(GPXConstants.TYPE_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node type found");
trk.setType(getNodeValueAsString(currentNode));
} else if(GPXConstants.TRKSEG_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node trkseg found");
trk.setTrackPoints(parseTrackSeg(currentNode));
} else if(GPXConstants.EXTENSIONS_NODE.equals(currentNode.getNodeName())) {
Iterator<IExtensionParser> it = extensionParsers.iterator();
while(it.hasNext()) {
if(logger.isDebugEnabled())logger.debug("node extensions found");
while(it.hasNext()) {
IExtensionParser parser = it.next();
Object data = parser.parseTrackExtension(currentNode);
trk.addExtensionData(parser.getId(), data);
}
}
}
}
}
return trk;
}
private Route parseRoute(Node node) {
if(node == null) {
logger.error("null node received");
return null;
}
Route rte = new Route();
NodeList nodes = node.getChildNodes();
if(nodes != null) {
for(int idx = 0; idx < nodes.getLength(); idx++) {
Node currentNode = nodes.item(idx);
if(GPXConstants.NAME_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node name found");
rte.setName(getNodeValueAsString(currentNode));
} else if(GPXConstants.CMT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node cmt found");
rte.setComment(getNodeValueAsString(currentNode));
} else if(GPXConstants.DESC_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node desc found");
rte.setDescription(getNodeValueAsString(currentNode));
} else if(GPXConstants.SRC_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node src found");
rte.setSrc(getNodeValueAsString(currentNode));
} else if(GPXConstants.LINK_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node link found");
//TODO: parse link
//rte.setLink(getNodeValueAsLink(currentNode));
} else if(GPXConstants.NUMBER_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node number found");
rte.setNumber(getNodeValueAsInteger(currentNode));
} else if(GPXConstants.TYPE_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node type found");
rte.setType(getNodeValueAsString(currentNode));
} else if(GPXConstants.RTEPT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node rtept found");
Waypoint wp = parseWaypoint(currentNode);
if(wp!=null) {
rte.addRoutePoint(wp);
}
} else if(GPXConstants.EXTENSIONS_NODE.equals(currentNode.getNodeName())) {
Iterator<IExtensionParser> it = extensionParsers.iterator();
while(it.hasNext()) {
if(logger.isDebugEnabled())logger.debug("node extensions found");
while(it.hasNext()) {
IExtensionParser parser = it.next();
Object data = parser.parseRouteExtension(currentNode);
rte.addExtensionData(parser.getId(), data);
}
}
}
}
}
return rte;
}
private ArrayList<Waypoint> parseTrackSeg(Node node) {
if(node == null) {
logger.error("null node received");
return null;
}
ArrayList<Waypoint> trkpts = new ArrayList<Waypoint>();
NodeList nodes = node.getChildNodes();
if(nodes != null) {
for(int idx = 0; idx < nodes.getLength(); idx++) {
Node currentNode = nodes.item(idx);
if(GPXConstants.TRKPT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node name found");
Waypoint wp = parseWaypoint(currentNode);
if(wp!=null) {
trkpts.add(wp);
}
} else if(GPXConstants.EXTENSIONS_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node extensions found");
/*
Iterator<IExtensionParser> it = extensionParsers.iterator();
while(it.hasNext()) {
IExtensionParser parser = it.next();
Object data = parser.parseWaypointExtension(currentNode);
//.addExtensionData(parser.getId(), data);
}
*/
}
}
}
return trkpts;
}
private Double getNodeValueAsDouble(Node node) {
Double val = null;
try {
val = Double.parseDouble(node.getFirstChild().getNodeValue());
} catch (Exception ex) {
logger.error("error parsing Double value form node. val=" + node.getNodeValue(), ex);
}
return val;
}
private Date getNodeValueAsDate(Node node) {
//2012-02-25T09:28:45Z
Date val = null;
try {
val = sdf.parse(node.getFirstChild().getNodeValue());
} catch (Exception ex) {
logger.error("error parsing Date value form node. val=" + node.getNodeName(), ex);
}
return val;
}
private String getNodeValueAsString(Node node) {
String val = null;
try {
val = node.getFirstChild().getNodeValue();
} catch (Exception ex) {
logger.error("error getting String value form node. val=" + node.getNodeName(), ex);
}
return val;
}
private FixType getNodeValueAsFixType(Node node) {
FixType val = null;
try {
val = FixType.returnType(node.getFirstChild().getNodeValue());
} catch (Exception ex) {
logger.error("error getting FixType value form node. val=" + node.getNodeName(), ex);
}
return val;
}
private Integer getNodeValueAsInteger(Node node) {
Integer val = null;
try {
val = Integer.parseInt(node.getFirstChild().getNodeValue());
} catch (Exception ex) {
logger.error("error parsing Integer value form node. val=" + node.getNodeValue(), ex);
}
return val;
}
public void writeGPX(GPX gpx, File gpxFile) throws IOException, ParserConfigurationException, TransformerException {
OutputStream out = FileUtils.openOutputStream(gpxFile);
writeGPX(gpx,out);
out.flush();
out.close();
}
public void writeGPX(GPX gpx, OutputStream out) throws ParserConfigurationException, TransformerException {
DocumentBuilder builder = docFactory.newDocumentBuilder();
Document doc = builder.newDocument();
Node gpxNode = doc.createElement(GPXConstants.GPX_NODE);
addBasicGPXInfoToNode(gpx, gpxNode, doc);
if(gpx.getWaypoints() != null) {
Iterator<Waypoint> itW = gpx.getWaypoints().iterator();
while(itW.hasNext()) {
addWaypointToGPXNode(itW.next(), gpxNode, doc);
}
Iterator<Track> itT = gpx.getTracks().iterator();
while(itT.hasNext()) {
addTrackToGPXNode(itT.next(), gpxNode, doc);
}
Iterator<Route> itR = gpx.getRoutes().iterator();
while(itR.hasNext()) {
addRouteToGPXNode(itR.next(), gpxNode, doc);
}
}
doc.appendChild(gpxNode);
// Use a Transformer for output
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(out);
transformer.transform(source, result);
}
private void addWaypointToGPXNode(Waypoint wpt, Node gpxNode, Document doc) {
addGenericWaypointToGPXNode(GPXConstants.WPT_NODE, wpt, gpxNode, doc);
}
private void addGenericWaypointToGPXNode(String tagName,Waypoint wpt, Node gpxNode, Document doc) {
Node wptNode = doc.createElement(tagName);
NamedNodeMap attrs = wptNode.getAttributes();
if(wpt.getLatitude() != null) {
Node latNode = doc.createAttribute(GPXConstants.LAT_ATTR);
latNode.setNodeValue(wpt.getLatitude().toString());
attrs.setNamedItem(latNode);
}
if(wpt.getLongitude() != null) {
Node longNode = doc.createAttribute(GPXConstants.LON_ATTR);
longNode.setNodeValue(wpt.getLongitude().toString());
attrs.setNamedItem(longNode);
}
if(wpt.getElevation() != null) {
Node node = doc.createElement(GPXConstants.ELE_NODE);
node.appendChild(doc.createTextNode(wpt.getElevation().toString()));
wptNode.appendChild(node);
}
if(wpt.getTime() != null) {
Node node = doc.createElement(GPXConstants.TIME_NODE);
node.appendChild(doc.createTextNode(sdfZ.format(wpt.getTime())));
wptNode.appendChild(node);
}
if(wpt.getMagneticDeclination() != null) {
Node node = doc.createElement(GPXConstants.MAGVAR_NODE);
node.appendChild(doc.createTextNode(wpt.getMagneticDeclination().toString()));
wptNode.appendChild(node);
}
if(wpt.getGeoidHeight() != null) {
Node node = doc.createElement(GPXConstants.GEOIDHEIGHT_NODE);
node.appendChild(doc.createTextNode(wpt.getGeoidHeight().toString()));
wptNode.appendChild(node);
}
if(wpt.getName() != null) {
Node node = doc.createElement(GPXConstants.NAME_NODE);
node.appendChild(doc.createTextNode(wpt.getName()));
wptNode.appendChild(node);
}
if(wpt.getComment() != null) {
Node node = doc.createElement(GPXConstants.CMT_NODE);
node.appendChild(doc.createTextNode(wpt.getComment()));
wptNode.appendChild(node);
}
if(wpt.getDescription() != null) {
Node node = doc.createElement(GPXConstants.DESC_NODE);
node.appendChild(doc.createTextNode(wpt.getDescription()));
wptNode.appendChild(node);
}
if(wpt.getSrc() != null) {
Node node = doc.createElement(GPXConstants.SRC_NODE);
node.appendChild(doc.createTextNode(wpt.getSrc()));
wptNode.appendChild(node);
}
//TODO: write link node
if(wpt.getSym() != null) {
Node node = doc.createElement(GPXConstants.SYM_NODE);
node.appendChild(doc.createTextNode(wpt.getSym()));
wptNode.appendChild(node);
}
if(wpt.getType() != null) {
Node node = doc.createElement(GPXConstants.TYPE_NODE);
node.appendChild(doc.createTextNode(wpt.getType()));
wptNode.appendChild(node);
}
if(wpt.getFix() != null) {
Node node = doc.createElement(GPXConstants.FIX_NODE);
node.appendChild(doc.createTextNode(wpt.getFix().toString()));
wptNode.appendChild(node);
}
if(wpt.getSat() != null) {
Node node = doc.createElement(GPXConstants.SAT_NODE);
node.appendChild(doc.createTextNode(wpt.getSat().toString()));
wptNode.appendChild(node);
}
if(wpt.getHdop() != null) {
Node node = doc.createElement(GPXConstants.HDOP_NODE);
node.appendChild(doc.createTextNode(wpt.getHdop().toString()));
wptNode.appendChild(node);
}
if(wpt.getVdop() != null) {
Node node = doc.createElement(GPXConstants.VDOP_NODE);
node.appendChild(doc.createTextNode(wpt.getVdop().toString()));
wptNode.appendChild(node);
}
if(wpt.getPdop() != null) {
Node node = doc.createElement(GPXConstants.PDOP_NODE);
node.appendChild(doc.createTextNode(wpt.getPdop().toString()));
wptNode.appendChild(node);
}
if(wpt.getAgeOfGPSData() != null) {
Node node = doc.createElement(GPXConstants.AGEOFGPSDATA_NODE);
node.appendChild(doc.createTextNode(wpt.getAgeOfGPSData().toString()));
wptNode.appendChild(node);
}
if(wpt.getDgpsid() != null) {
Node node = doc.createElement(GPXConstants.DGPSID_NODE);
node.appendChild(doc.createTextNode(wpt.getDgpsid().toString()));
wptNode.appendChild(node);
}
if(wpt.getExtensionsParsed() > 0) {
Node node = doc.createElement(GPXConstants.EXTENSIONS_NODE);
Iterator<IExtensionParser> it = extensionParsers.iterator();
while(it.hasNext()) {
it.next().writeWaypointExtensionData(node, wpt, doc);
}
wptNode.appendChild(node);
}
gpxNode.appendChild(wptNode);
}
private void addTrackToGPXNode(Track trk, Node gpxNode, Document doc) {
Node trkNode = doc.createElement(GPXConstants.TRK_NODE);
if(trk.getName() != null) {
Node node = doc.createElement(GPXConstants.NAME_NODE);
node.appendChild(doc.createTextNode(trk.getName()));
trkNode.appendChild(node);
}
if(trk.getComment() != null) {
Node node = doc.createElement(GPXConstants.CMT_NODE);
node.appendChild(doc.createTextNode(trk.getComment()));
trkNode.appendChild(node);
}
if(trk.getDescription() != null) {
Node node = doc.createElement(GPXConstants.DESC_NODE);
node.appendChild(doc.createTextNode(trk.getDescription()));
trkNode.appendChild(node);
}
if(trk.getSrc() != null) {
Node node = doc.createElement(GPXConstants.SRC_NODE);
node.appendChild(doc.createTextNode(trk.getSrc()));
trkNode.appendChild(node);
}
//TODO: write link
if(trk.getNumber() != null) {
Node node = doc.createElement(GPXConstants.NUMBER_NODE);
node.appendChild(doc.createTextNode(trk.getNumber().toString()));
trkNode.appendChild(node);
}
if(trk.getType() != null) {
Node node = doc.createElement(GPXConstants.TYPE_NODE);
node.appendChild(doc.createTextNode(trk.getType()));
trkNode.appendChild(node);
}
if(trk.getExtensionsParsed() > 0) {
Node node = doc.createElement(GPXConstants.EXTENSIONS_NODE);
Iterator<IExtensionParser> it = extensionParsers.iterator();
while(it.hasNext()) {
it.next().writeTrackExtensionData(node, trk, doc);
}
trkNode.appendChild(node);
}
if(trk.getTrackPoints() != null) {
Node trksegNode = doc.createElement(GPXConstants.TRKSEG_NODE);
Iterator<Waypoint> it = trk.getTrackPoints().iterator();
while(it.hasNext()) {
addGenericWaypointToGPXNode(GPXConstants.TRKPT_NODE, it.next(), trksegNode, doc);
}
trkNode.appendChild(trksegNode);
}
gpxNode.appendChild(trkNode);
}
private void addRouteToGPXNode(Route rte, Node gpxNode, Document doc) {
Node trkNode = doc.createElement(GPXConstants.TRK_NODE);
if(rte.getName() != null) {
Node node = doc.createElement(GPXConstants.NAME_NODE);
node.appendChild(doc.createTextNode(rte.getName()));
trkNode.appendChild(node);
}
if(rte.getComment() != null) {
Node node = doc.createElement(GPXConstants.CMT_NODE);
node.appendChild(doc.createTextNode(rte.getComment()));
trkNode.appendChild(node);
}
if(rte.getDescription() != null) {
Node node = doc.createElement(GPXConstants.DESC_NODE);
node.appendChild(doc.createTextNode(rte.getDescription()));
trkNode.appendChild(node);
}
if(rte.getSrc() != null) {
Node node = doc.createElement(GPXConstants.SRC_NODE);
node.appendChild(doc.createTextNode(rte.getSrc()));
trkNode.appendChild(node);
}
//TODO: write link
if(rte.getNumber() != null) {
Node node = doc.createElement(GPXConstants.NUMBER_NODE);
node.appendChild(doc.createTextNode(rte.getNumber().toString()));
trkNode.appendChild(node);
}
if(rte.getType() != null) {
Node node = doc.createElement(GPXConstants.TYPE_NODE);
node.appendChild(doc.createTextNode(rte.getType()));
trkNode.appendChild(node);
}
if(rte.getExtensionsParsed() > 0) {
Node node = doc.createElement(GPXConstants.EXTENSIONS_NODE);
Iterator<IExtensionParser> it = extensionParsers.iterator();
while(it.hasNext()) {
it.next().writeRouteExtensionData(node, rte, doc);
}
trkNode.appendChild(node);
}
if(rte.getRoutePoints() != null) {
Iterator<Waypoint> it = rte.getRoutePoints().iterator();
while(it.hasNext()) {
addGenericWaypointToGPXNode(GPXConstants.RTEPT_NODE, it.next(), trkNode, doc);
}
}
gpxNode.appendChild(trkNode);
}
private void addBasicGPXInfoToNode(GPX gpx, Node gpxNode, Document doc) {
NamedNodeMap attrs = gpxNode.getAttributes();
if(gpx.getVersion() != null) {
Node verNode = doc.createAttribute(GPXConstants.VERSION_ATTR);
verNode.setNodeValue(gpx.getVersion());
attrs.setNamedItem(verNode);
}
if(gpx.getCreator() != null) {
Node creatorNode = doc.createAttribute(GPXConstants.CREATOR_ATTR);
creatorNode.setNodeValue(gpx.getCreator());
attrs.setNamedItem(creatorNode);
}
if(gpx.getExtensionsParsed() > 0) {
Node node = doc.createElement(GPXConstants.EXTENSIONS_NODE);
Iterator<IExtensionParser> it = extensionParsers.iterator();
while(it.hasNext()) {
it.next().writeGPXExtensionData(node, gpx, doc);
}
gpxNode.appendChild(node);
}
}
} | RBerliner/freeboard-server | src/main/java/org/alternativevision/gpx/GPXParser.java | Java | gpl-3.0 | 30,515 |
! RUN: %S/test_folding.sh %s %t %f18
! Test folding of array constructors with constant implied DO bounds;
! their indices are constant expressions and can be used as such.
module m1
integer, parameter :: kinds(*) = [1, 2, 4, 8]
integer(kind=8), parameter :: clipping(*) = [integer(kind=8) :: &
(int(z'100010101', kind=kinds(j)), j=1,4)]
integer(kind=8), parameter :: expected(*) = [ &
int(z'01',8), int(z'0101',8), int(z'00010101',8), int(z'100010101',8)]
logical, parameter :: test_clipping = all(clipping == expected)
end module
| sabel83/metashell | 3rd/templight/flang/test/Evaluate/folding13.f90 | FORTRAN | gpl-3.0 | 548 |
// ************************************************************************** //
//
// BornAgain: simulate and fit scattering at grazing incidence
//
//! @file Core/StandardSamples/SizeDistributionModelsBuilder.h
//! @brief Defines various sample builder classes to test DA, LMA, SSCA approximations
//!
//! @homepage http://www.bornagainproject.org
//! @license GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2018
//! @authors Scientific Computing Group at MLZ (see CITATION, AUTHORS)
//
// ************************************************************************** //
#ifndef SIZEDISTRIBUTIONMODELSBUILDER_H
#define SIZEDISTRIBUTIONMODELSBUILDER_H
#include "IMultiLayerBuilder.h"
//! Creates the sample demonstrating size distribution model in decoupling approximation.
//! Equivalent of Examples/python/simulation/ex03_InterferenceFunctions/ApproximationDA.py
//! @ingroup standard_samples
class BA_CORE_API_ SizeDistributionDAModelBuilder : public IMultiLayerBuilder
{
public:
SizeDistributionDAModelBuilder(){}
MultiLayer* buildSample() const;
};
//! Creates the sample demonstrating size distribution model in local monodisperse approximation.
//! Equivalent of Examples/python/simulation/ex03_InterferenceFunctions/ApproximationLMA.py
//! @ingroup standard_samples
class BA_CORE_API_ SizeDistributionLMAModelBuilder : public IMultiLayerBuilder
{
public:
SizeDistributionLMAModelBuilder(){}
MultiLayer* buildSample() const;
};
//! Creates the sample demonstrating size distribution model in size space coupling approximation.
//! Equivalent of Examples/python/simulation/ex03_InterferenceFunctions/ApproximationSSCA.py
//! @ingroup standard_samples
class BA_CORE_API_ SizeDistributionSSCAModelBuilder : public IMultiLayerBuilder
{
public:
SizeDistributionSSCAModelBuilder(){}
MultiLayer* buildSample() const;
};
//! Builds sample: size spacing correlation approximation (IsGISAXS example #15).
//! @ingroup standard_samples
class BA_CORE_API_ CylindersInSSCABuilder : public IMultiLayerBuilder
{
public:
CylindersInSSCABuilder(){}
MultiLayer* buildSample() const;
};
#endif // SIZEDISTRIBUTIONMODELSBUILDER_H
| waltervh/BornAgain | Core/StandardSamples/SizeDistributionModelsBuilder.h | C | gpl-3.0 | 2,226 |
<?php
/**
* This file is part of OXID eShop Community Edition.
*
* OXID eShop Community Edition is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OXID eShop Community Edition is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OXID eShop Community Edition. If not, see <http://www.gnu.org/licenses/>.
*
* @link http://www.oxid-esales.com
* @package core
* @copyright (C) OXID eSales AG 2003-2012
* @version OXID eShop CE
* @version SVN: $Id: oxvoucherserie.php 47273 2012-07-12 12:47:43Z linas.kukulskis $
*/
/**
* Voucher serie manager.
* Manages list of available Vouchers (fetches, deletes, etc.).
*
* @package model
*/
class oxVoucherSerie extends oxBase
{
/**
* User groups array (default null).
* @var object
*/
protected $_oGroups = null;
/**
* @var string name of current class
*/
protected $_sClassName = 'oxvoucherserie';
/**
* Class constructor, initiates parent constructor (parent::oxBase()).
*/
public function __construct()
{
parent::__construct();
$this->init('oxvoucherseries');
}
/**
* Override delete function so we can delete user group and article or category relations first.
*
* @param string $sOxId object ID (default null)
*
* @return null
*/
public function delete( $sOxId = null )
{
if ( !$sOxId ) {
$sOxId = $this->getId();
}
$this->unsetDiscountRelations();
$this->unsetUserGroups();
$this->deleteVoucherList();
return parent::delete( $sOxId );
}
/**
* Collects and returns user group list.
*
* @return object
*/
public function setUserGroups()
{
if ( $this->_oGroups === null ) {
$this->_oGroups = oxNew( 'oxlist' );
$this->_oGroups->init( 'oxgroups' );
$sViewName = getViewName( "oxgroups" );
$sSelect = "select gr.* from {$sViewName} as gr, oxobject2group as o2g where
o2g.oxobjectid = ". oxDb::getDb()->quote( $this->getId() ) ." and gr.oxid = o2g.oxgroupsid ";
$this->_oGroups->selectString( $sSelect );
}
return $this->_oGroups;
}
/**
* Removes user groups relations.
*
* @return null
*/
public function unsetUserGroups()
{
$oDb = oxDb::getDb();
$sDelete = 'delete from oxobject2group where oxobjectid = ' . $oDb->quote( $this->getId() );
$oDb->execute( $sDelete );
}
/**
* Removes product or dategory relations.
*
* @return null
*/
public function unsetDiscountRelations()
{
$oDb = oxDb::getDb();
$sDelete = 'delete from oxobject2discount where oxobject2discount.oxdiscountid = ' . $oDb->quote( $this->getId() );
$oDb->execute( $sDelete );
}
/**
* Returns array of a vouchers assigned to this serie.
*
* @return array
*/
public function getVoucherList()
{
$oVoucherList = oxNew( 'oxvoucherlist' );
$sSelect = 'select * from oxvouchers where oxvoucherserieid = ' . oxDb::getDb()->quote( $this->getId() );
$oVoucherList->selectString( $sSelect );
return $oVoucherList;
}
/**
* Deletes assigned voucher list.
*
* @return null
*/
public function deleteVoucherList()
{
$oDb = oxDb::getDb();
$sDelete = 'delete from oxvouchers where oxvoucherserieid = ' . $oDb->quote( $this->getId() );
$oDb->execute( $sDelete );
}
/**
* Returns array of vouchers counts.
*
* @return array
*/
public function countVouchers()
{
$aStatus = array();
$oDb = oxDb::getDb();
$sQuery = 'select count(*) as total from oxvouchers where oxvoucherserieid = ' .$oDb->quote( $this->getId() );
$aStatus['total'] = $oDb->getOne( $sQuery );
$sQuery = 'select count(*) as used from oxvouchers where oxvoucherserieid = ' . $oDb->quote( $this->getId() ) . ' and ((oxorderid is not NULL and oxorderid != "") or (oxdateused is not NULL and oxdateused != 0))';
$aStatus['used'] = $oDb->getOne( $sQuery );
$aStatus['available'] = $aStatus['total'] - $aStatus['used'];
return $aStatus;
}
}
| jadzgauskas/oxidce | application/models/oxvoucherserie.php | PHP | gpl-3.0 | 4,795 |
var translations = {
'es': {
'One moment while we<br>log you in':
'Espera un momento mientras<br>iniciamos tu sesión',
'You are now connected to the network':
'Ahora estás conectado a la red',
'Account signups/purchases are disabled in preview mode':
'La inscripciones de cuenta/compras están desactivadas en el modo de vista previa.',
'Notice':
'Aviso',
'Day':
'Día',
'Days':
'Días',
'Hour':
'Hora',
'Hours':
'Horas',
'Minutes':
'Minutos',
'Continue':
'Continuar',
'Thank You for Trying TWC WiFi':
'Gracias por probar TWC WiFi',
'Please purchase a TWC Access Pass to continue using WiFi':
'Adquiere un Pase de acceso (Access Pass) de TWC para continuar usando la red WiFi',
'Your TWC Access Pass has expired. Please select a new Access Pass Now.':
'Tu Access Pass (Pase de acceso) de TWC ha vencido. Selecciona un nuevo Access Pass (Pase de acceso) ahora.',
'Your account information has been pre-populated into the form. If you wish to change any information, you may edit the form before completing the order.':
'El formulario ha sido llenado con la información de tu cuenta. Si deseas modificar algún dato, puedes editar el formulario antes de completar la solicitud.',
'Your Password':
'Tu contraseña',
'Proceed to Login':
'Proceder con el inicio de sesión',
'Payment portal is not available at this moment':
'',
'Redirecting to Payment portal...':
'',
'Could not log you into the network':
'No se pudo iniciar sesión en la red'
}
}
function translate(text, language) {
if (language == 'en')
return text;
if (!translations[language])
return text;
if (!translations[language][text])
return text;
return translations[language][text] || text;
}
| kbeflo/evilportals | archive/optimumwifi/assets/js/xlate.js | JavaScript | gpl-3.0 | 2,089 |
package it.ninjatech.kvo.async.job;
import it.ninjatech.kvo.model.ImageProvider;
import it.ninjatech.kvo.util.Logger;
import java.awt.Dimension;
import java.awt.Image;
import java.util.EnumSet;
public class CacheRemoteImageAsyncJob extends AbstractImageLoaderAsyncJob {
private static final long serialVersionUID = -8459315395025635686L;
private final String path;
private final String type;
private final Dimension size;
private Image image;
public CacheRemoteImageAsyncJob(String id, ImageProvider provider, String path, Dimension size, String type) {
super(id, EnumSet.of(LoadType.Cache, LoadType.Remote), provider);
this.path = path;
this.size = size;
this.type = type;
}
@Override
protected void execute() {
try {
Logger.log("-> executing cache-remote image %s\n", this.id);
this.image = getImage(null, null, this.id, this.path, this.size, this.type);
}
catch (Exception e) {
this.exception = e;
}
}
public Image getImage() {
return this.image;
}
}
| vincenzomazzeo/kodi-video-organizer | src/main/java/it/ninjatech/kvo/async/job/CacheRemoteImageAsyncJob.java | Java | gpl-3.0 | 1,058 |
-----------------------------------
--
-- Zone: Bhaflau_Remnants
--
-----------------------------------
require("scripts/globals/settings");
package.loaded["scripts/zones/Bhaflau_Remnants/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Bhaflau_Remnants/TextIDs");
-----------------------------------
function onInitialize(zone)
end;
function onZoneIn(player,prevZone)
local cs = -1;
return cs;
end;
function onRegionEnter(player,region)
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
end;
| waterlgndx/darkstar | scripts/zones/Bhaflau_Remnants/Zone.lua | Lua | gpl-3.0 | 581 |
#ifdef TI83P
# include <ti83pdefs.h>
# include <ti83p.h>
void YName() __naked
{
__asm
push af
push hl
push iy
ld iy,#flags___dw
BCALL(_YName___db)
pop iy
pop hl
pop af
ret
__endasm;
}
#endif
| catastropher/tisdcc-deadproject | lib/old/YName.c | C | gpl-3.0 | 193 |
/*
* UFTP - UDP based FTP with multicast
*
* Copyright (C) 2001-2013 Dennis A. Bush, Jr. bush@tcnj.edu
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this program, or any covered work, by linking or
* combining it with the OpenSSL project's OpenSSL library (or a
* modified version of that library), containing parts covered by the
* terms of the OpenSSL or SSLeay licenses, the copyright holder
* grants you additional permission to convey the resulting work.
* Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of OpenSSL used as well
* as that of the covered work.
*/
#ifndef _CLIENT_FILEINFO_H
#define _CLIENT_FILEINFO_H
void handle_fileinfo(struct group_list_t *group, const unsigned char *message,
unsigned meslen, struct timeval rxtime);
void send_fileinfo_ack(struct group_list_t *group, int restart);
#endif // _CLIENT_FILEINFO_H
| No9/uftp | deps/uftp-4.7/client_fileinfo.h | C | gpl-3.0 | 1,645 |
/******************************************************************************/
/* */
/* X r d C m s L o g i n . c c */
/* */
/* (c) 2007 by the Board of Trustees of the Leland Stanford, Jr., University */
/* All Rights Reserved */
/* Produced by Andrew Hanushevsky for Stanford University under contract */
/* DE-AC02-76-SFO0515 with the Department of Energy */
/* */
/* This file is part of the XRootD software suite. */
/* */
/* XRootD is free software: you can redistribute it and/or modify it under */
/* the terms of the GNU Lesser General Public License as published by the */
/* Free Software Foundation, either version 3 of the License, or (at your */
/* option) any later version. */
/* */
/* XRootD is distributed in the hope that it will be useful, but WITHOUT */
/* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or */
/* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public */
/* License for more details. */
/* */
/* You should have received a copy of the GNU Lesser General Public License */
/* along with XRootD in a file called COPYING.LESSER (LGPL license) and file */
/* COPYING (GPL license). If not, see <http://www.gnu.org/licenses/>. */
/* */
/* The copyright holder's institutional names and contributor's names may not */
/* be used to endorse or promote products derived from this software without */
/* specific prior written permission of the institution or contributor. */
/******************************************************************************/
#include <netinet/in.h>
#include "XProtocol/YProtocol.hh"
#include "Xrd/XrdLink.hh"
#include "XrdCms/XrdCmsLogin.hh"
#include "XrdCms/XrdCmsParser.hh"
#include "XrdCms/XrdCmsTalk.hh"
#include "XrdCms/XrdCmsSecurity.hh"
#include "XrdCms/XrdCmsTrace.hh"
#include "XrdOuc/XrdOucPup.hh"
#include "XrdSys/XrdSysError.hh"
#include "XrdSys/XrdSysPthread.hh"
using namespace XrdCms;
/******************************************************************************/
/* Public: A d m i t */
/******************************************************************************/
int XrdCmsLogin::Admit(XrdLink *Link, CmsLoginData &Data)
{
CmsRRHdr myHdr;
CmsLoginData myData;
const char *eText, *Token;
int myDlen, Toksz;
// Get complete request
//
if ((eText = XrdCmsTalk::Attend(Link, myHdr, myBuff, myBlen, myDlen)))
return Emsg(Link, eText, 0);
// If we need to do authentication, do so now
//
if ((Token = XrdCmsSecurity::getToken(Toksz, Link->Host()))
&& !XrdCmsSecurity::Authenticate(Link, Token, Toksz)) return 0;
// Fiddle with the login data structures
//
Data.SID = Data.Paths = 0;
memset(&myData, 0, sizeof(myData));
myData.Mode = Data.Mode;
myData.HoldTime = Data.HoldTime;
myData.Version = Data.Version = kYR_Version;
// Decode the data pointers ans grab the login data
//
if (!Parser.Parse(&Data, myBuff, myBuff+myDlen))
return Emsg(Link, "invalid login data", 0);
// Do authentication now, if needed
//
if ((Token = XrdCmsSecurity::getToken(Toksz, Link->Host())))
if (!XrdCmsSecurity::Authenticate(Link, Token, Toksz)) return 0;
// Send off login reply
//
return (sendData(Link, myData) ? 0 : 1);
}
/******************************************************************************/
/* Private: E m s g */
/******************************************************************************/
int XrdCmsLogin::Emsg(XrdLink *Link, const char *msg, int ecode)
{
Say.Emsg("Login", Link->Name(), "login failed;", msg);
return ecode;
}
/******************************************************************************/
/* Public: L o g i n */
/******************************************************************************/
int XrdCmsLogin::Login(XrdLink *Link, CmsLoginData &Data, int timeout)
{
CmsRRHdr LIHdr;
char WorkBuff[4096], *hList, *wP = WorkBuff;
int n, dataLen;
// Send the data
//
if (sendData(Link, Data)) return kYR_EINVAL;
// Get the response.
//
if ((n = Link->RecvAll((char *)&LIHdr, sizeof(LIHdr), timeout)) < 0)
return Emsg(Link, (n == -ETIMEDOUT ? "timed out" : "rejected"));
// Receive and decode the response. We apparently have protocol version 2.
//
if ((dataLen = static_cast<int>(ntohs(LIHdr.datalen))))
{if (dataLen > (int)sizeof(WorkBuff))
return Emsg(Link, "login reply too long");
if (Link->RecvAll(WorkBuff, dataLen, timeout) < 0)
return Emsg(Link, "login receive error");
}
// Check if we are being asked to identify ourselves
//
if (LIHdr.rrCode == kYR_xauth)
{if (!XrdCmsSecurity::Identify(Link, LIHdr, WorkBuff, sizeof(WorkBuff)))
return kYR_EINVAL;
dataLen = static_cast<int>(ntohs(LIHdr.datalen));
if (dataLen > (int)sizeof(WorkBuff))
return Emsg(Link, "login reply too long");
}
// The response can also be a login redirect (i.e., a try request).
//
if (!(Data.Mode & CmsLoginData::kYR_director)
&& LIHdr.rrCode == kYR_try)
{if (!XrdOucPup::Unpack(&wP, wP+dataLen, &hList, n))
return Emsg(Link, "malformed try host data");
Data.Paths = (kXR_char *)strdup(n ? hList : "");
return kYR_redirect;
}
// Process error reply
//
if (LIHdr.rrCode == kYR_error)
return (dataLen < (int)sizeof(kXR_unt32)+8
? Emsg(Link, "invalid error reply")
: Emsg(Link, WorkBuff+sizeof(kXR_unt32)));
// Process normal reply
//
if (LIHdr.rrCode != kYR_login
|| !Parser.Parse(&Data, WorkBuff, WorkBuff+dataLen))
return Emsg(Link, "invalid login response");
return 0;
}
/******************************************************************************/
/* Private: s e n d D a t a */
/******************************************************************************/
int XrdCmsLogin::sendData(XrdLink *Link, CmsLoginData &Data)
{
static const int xNum = 16;
int iovcnt;
char Work[xNum*12];
struct iovec Liov[xNum];
CmsRRHdr Resp={0, kYR_login, 0, 0};
// Pack the response (ignore the auth token for now)
//
if (!(iovcnt=Parser.Pack(kYR_login,&Liov[1],&Liov[xNum],(char *)&Data,Work)))
return Emsg(Link, "too much login reply data");
// Complete I/O vector
//
Resp.datalen = Data.Size;
Liov[0].iov_base = (char *)&Resp;
Liov[0].iov_len = sizeof(Resp);
// Send off the data
//
Link->Send(Liov, iovcnt+1);
// Return success
//
return 0;
}
| bbockelm/xrootd_old_git | src/XrdCms/XrdCmsLogin.cc | C++ | gpl-3.0 | 7,499 |
/* RetroArch - A frontend for libretro.
* Copyright (C) 2010-2014 - Hans-Kristian Arntzen
*
* RetroArch is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Found-
* ation, either version 3 of the License, or (at your option) any later version.
*
* RetroArch is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with RetroArch.
* If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __RARCH_POSIX_STRING_H
#define __RARCH_POSIX_STRING_H
#ifdef _WIN32
#include "../msvc/msvc_compat.h"
#ifdef __cplusplus
extern "C" {
#endif
#undef strcasecmp
#undef strdup
#undef isblank
#undef strtok_r
#define strcasecmp(a, b) rarch_strcasecmp__(a, b)
#define strdup(orig) rarch_strdup__(orig)
#define isblank(c) rarch_isblank__(c)
#define strtok_r(str, delim, saveptr) rarch_strtok_r__(str, delim, saveptr)
int strcasecmp(const char *a, const char *b);
char *strdup(const char *orig);
int isblank(int c);
char *strtok_r(char *str, const char *delim, char **saveptr);
#ifdef __cplusplus
}
#endif
#endif
#endif
| AampApps/RetroArch | compat/posix_string.h | C | gpl-3.0 | 1,368 |
//
// Author : Toru Shiozaki
// Date : May 2009
//
#define NGRID 12
#define MAXT 64
#define NBOX 32
#define NBOXL 0
#define T_INFTY 11
#include <sstream>
#include <iostream>
#include <iomanip>
#include <vector>
#include "mpreal.h"
#include <map>
#include <cmath>
#include <string>
#include <cassert>
#include <fstream>
#include "gmp_macros.h"
#include <boost/lexical_cast.hpp>
#include "../erirootlist.h"
extern "C" {
void dsyev_(const char*, const char*, const int*, double*, const int*, double*, double*, const int*, int*);
}
using namespace boost;
using namespace std;
using namespace mpfr;
using namespace bagel;
void rysroot_gmp(const vector<mpfr::mpreal>& ta, vector<mpfr::mpreal>& dx, vector<mpfr::mpreal>& dw, const int nrank, const int nbatch) ;
vector<mpreal> chebft(int n) {
mpfr::mpreal::set_default_prec(GMPPREC);
vector<mpreal> out(n);
const mpreal half = "0.5";
for (int k = 0; k != n; ++k) {
const mpreal y = mpfr::cos(GMPPI * (k + half) / n);
out[k] = y;
}
return out;
}
vector<vector<double>> get_C(const mpreal tbase, const mpreal stride, int rank, const bool asymp) {
mpfr::mpreal::set_default_prec(GMPPREC);
const int n = NGRID;
const mpreal zero = "0.0";
const mpreal half = "0.5";
const mpreal one = "1.0";
vector<mpreal> cheb = chebft(n);
const mpreal Tmin = tbase;
const mpreal Tmax = Tmin + stride;
const mpreal Tp = half * (Tmin + Tmax);
vector<mpreal> Tpoints(n);
for (int i = 0; i != n; ++i) {
Tpoints[i] = stride*half*cheb[i] + Tp;
}
#ifdef DAWSON
vector<mpreal> tt_infty(1); tt_infty[0] = Tmax;
vector<mpreal> dx_infty(rank);
vector<mpreal> dw_infty(rank);
if (asymp) rysroot_gmp(tt_infty, dx_infty, dw_infty, rank, 1);
#endif
vector<map<mpreal, mpreal>> table_reserve(n);
#pragma omp parallel for
for (int i = 0; i < n; ++i) {
vector<mpreal> ttt(1); ttt[0] = Tpoints[i];
vector<mpreal> dx(rank);
vector<mpreal> dw(rank);
rysroot_gmp(ttt, dx, dw, rank, 1);
// sort dx and dw using dx
#ifdef DAWSON
if (asymp) {
for (int j = 0; j != rank; ++j) {
table_reserve[i].insert(make_pair(-(1.0 - dx[j])*ttt[0]/((1.0 - dx_infty[j])*tt_infty[0]), dw[j]*ttt[0]/(dw_infty[j]*tt_infty[0])));
}
} else {
for (int j = 0; j != rank; ++j)
table_reserve[i].insert(make_pair(dx[j], dw[j]));
}
#else
for (int j = 0; j != rank; ++j)
table_reserve[i].insert(make_pair(dx[j], dw[j]));
#endif
}
vector<vector<double>> c;
for (int ii = 0; ii != rank; ++ii) {
vector<double> tc(n);
vector<double> tc2(n);
vector<mpreal> cdx, cdw;
for (int j = 0; j != n; ++j) {
auto iter = table_reserve[j].begin();
for (int i = 0; i != ii; ++i) ++iter;
cdx.push_back(iter->first);
cdw.push_back(iter->second);
}
const mpreal two = "2.0";
const mpreal half = "0.5";
const mpreal fac = two / n;
const mpreal pi = GMPPI;
for (int j = 0; j != n; ++j) {
mpreal sum = "0.0";
mpreal sum2 = "0.0";
for (int k = 0; k != n; ++k) {
sum += cdx[k] * mpfr::cos(pi * j * (k + half) / n);
sum2 += cdw[k] * mpfr::cos(pi * j * (k + half) / n);
}
tc[j] = (sum * fac).toDouble();
tc2[j] = (sum2 * fac).toDouble();
}
if (tc[n-1] > 1.0e-10 || tc2[n-1] > 1.0e-10) {
cout << " caution: cheb not converged " << ii << " " << setprecision(10) << fixed << Tmin.toDouble() << " " << Tmax.toDouble() << endl;
for (int i = 0; i != n; ++i) {
cout << setw(20) << Tpoints[i].toDouble() << setw(20) << tc[i] << setw(20) << tc2[i] << endl;
}
}
c.push_back(tc);
c.push_back(tc2);
}
return c;
}
bool test(const int nrank, const double tin) {
mpfr::mpreal::set_default_prec(GMPPREC);
const static int nsize = 1;
vector<mpreal> tt(nsize, tin);
vector<mpreal> rr(nsize*nrank);
vector<mpreal> ww(nsize*nrank);
rysroot_gmp(tt, rr, ww, nrank, nsize);
map<mpreal,mpreal> gmp;
for (int i = 0; i != nsize*nrank; ++i)
gmp.insert(make_pair(rr[i], ww[i]));
double dt[nsize] = {tt[0].toDouble()};
double dr[nsize*nrank];
double dw[nsize*nrank];
eriroot__.root(nrank, dt, dr, dw, nsize);
cout << setprecision(10) << scientific << endl;
auto iter = gmp.begin();
for (int i = 0; i != nrank*nsize; ++i, ++iter) {
cout << setw(20) << dr[i] << setw(20) << iter->first << setw(20) << fabs(dr[i] - (iter->first).toDouble()) << endl;
cout << setw(20) << dw[i] << setw(20) << iter->second << setw(20) << fabs(dw[i] - (iter->second).toDouble()) << endl;
}
iter = gmp.begin();
for (int i = 0; i != nrank; ++i, ++iter) {
if (!(fabs(dr[i] - (iter->first).toDouble()))) cout << dt[0] << endl;
//assert(fabs(dr[i] - (iter->first).toDouble()) < 1.0e-13);
//assert(fabs(dw[i] - (iter->second).toDouble()) < 1.0e-13);
}
cout << "test passed: rank" << setw(3) << nrank << endl;
cout << "----------" << endl;
}
#include <boost/lexical_cast.hpp>
int main(int argc, char** argv) {
const mpreal T_ASYM = static_cast<mpreal>(MAXT + (NBOXL)*(NBOXL + 1.0)*(2.0*NBOXL + 1.0)/6.0);
mpfr::mpreal::set_default_prec(GMPPREC);
mpfr::mpreal pi = GMPPI;
if (argc > 1) {
cout << "--- TEST---" << endl;
const string toggle = argv[1];
if (toggle == "t") {
#if 0
if (argc <= 3) assert(false);
const string low = argv[2];
const string high = argv[3];
for (int i = 0; i < 700; ++i) {
for (int n = lexical_cast<int>(low); n <= lexical_cast<int>(high); ++n) test(n, i*0.1+1.0e-10);
}
#else
test(6,1.10033333333333);
test(6,1.11133333333333);
test(6,1.12233333333333);
test(6,1.13233333333333);
test(6,1.14333333333333);
test(6,1.14333333333333e1);
test(6,0.645e2);
test(6,0.675e2);
test(6,0.805e2);
test(6,0.912e2);
test(6,1.14333333333333e2);
test(6,1.285e2);
test(6,128.000000000000);
test(6,1.31e2);
test(6,1.38e2);
test(6,2.43e2);
test(6,256.000000000000);
test(6,1.14333333333333e3);
test(6,8e3);
test(6,8192.000000000000);
test(6,1.14333333333333e4);
test(6,1.14333333333333e5);
test(6,1.14333333333333e6);
#endif
return 0;
}
}
vector<double> nbox_(52);
for (int nroot=1; nroot!=52; ++nroot) {
nbox_[nroot] = NBOX;
}
for (int nroot=1; nroot!=52; ++nroot) { // this is the outer most loop.
if (argc > 2) {
const string toggle = argv[1];
if (toggle == "-r") {
const string target = argv[2];
if (nroot != lexical_cast<int>(target)) continue;
}
}
vector<double> aroot;
vector<double> aweight;
#ifndef DAWSON
#ifndef SPIN2
#ifndef BREIT
// first obtain asymptotics
const int n=nroot*2;
double a[10000] = {0.0};
double b[100];
double c[500];
for (int i=0; i!= n; ++i) {
a[i+i*n] = 0.0;
if (i > 0) {
const double ia = static_cast<double>(i);
a[(i-1)+i*n] = std::sqrt(ia*0.5);
a[i+(i-1)*n] = std::sqrt(ia*0.5);
}
}
int nn = n*5;
int info = 0;
dsyev_("v", "U", &n, a, &n, b, c, &nn, &info);
for (int j = 0; j != nroot; ++j) {
aroot.push_back(b[nroot+j]*b[nroot+j]);
aweight.push_back(a[(nroot+j)*(nroot*2)]*a[(nroot+j)*(nroot*2)]*(sqrt(pi)).toDouble());
}
#else
const mpreal t = 1000;
const mpreal s = 2000;
vector<mpreal> dx(nroot*2);
vector<mpreal> dw(nroot*2);
vector<mpreal> tt(1, t); tt.push_back(s);
rysroot_gmp(tt, dx, dw, nroot, 2);
for (int j = 0; j != nroot; ++j) {
assert(fabs(dx[j]*t - dx[j+nroot]*s) < 1.0e-16);
assert(fabs(dw[j]*t*sqrt(t) - dw[j+nroot]*s*sqrt(s)) < 1.0e-16);
aroot.push_back((dx[j]*t).toDouble());
aweight.push_back((dw[j]*t*sqrt(t)).toDouble());
}
#endif
#else
const mpreal t = 1000;
const mpreal s = 2000;
vector<mpreal> dx(nroot*2);
vector<mpreal> dw(nroot*2);
vector<mpreal> tt(1, t); tt.push_back(s);
rysroot_gmp(tt, dx, dw, nroot, 2);
for (int j = 0; j != nroot; ++j) {
assert(fabs(dx[j]*t - dx[j+nroot]*s) < 1.0e-16);
assert(fabs(dw[j]*t*t*sqrt(t) - dw[j+nroot]*s*s*sqrt(s)) < 1.0e-16);
aroot.push_back((dx[j]*t).toDouble());
aweight.push_back((dw[j]*t*t*sqrt(t)).toDouble());
}
#endif
#else
mpreal infty;
if (T_INFTY < MAXT) {
assert (NBOXL == 0);
const int nbox0 = static_cast<int>(log(MAXT)/log(2.0));
infty = pow(2, nbox0 + T_INFTY);
} else {
infty = static_cast<mpreal>(T_INFTY);
}
vector<mpreal> tt_infty(1); tt_infty[0] = infty;
vector<mpreal> dx_infty(nroot);
vector<mpreal> dw_infty(nroot);
rysroot_gmp(tt_infty, dx_infty, dw_infty, nroot, 1);
for (int j = 0; j != nroot; ++j) {
aroot.push_back(((1.0 - dx_infty[j])*tt_infty[0]).toDouble());
aweight.push_back((dw_infty[j]*tt_infty[0]).toDouble());
}
#endif
const int ndeg = NGRID;
const int nbox = nbox_[nroot];
#ifndef DAWSON
const int jend = nbox;
#else
int jend;
if (MAXT < T_INFTY) {
jend = NBOX + NBOXL + 1;
} else {
jend = NBOX + T_INFTY;
}
#endif
const double stride = static_cast<double>(MAXT)/nbox;
const mpreal mstride = static_cast<mpreal>(MAXT)/nbox;
ofstream ofs;
#ifndef SPIN2
#ifndef BREIT
#ifndef DAWSON
const string func = "eriroot";
#else
const string func = "r2root";
#endif
#else
const string func = "breitroot";
#endif
#else
const string func = "spin2root";
#endif
string filename = "_" + func + "_" + lexical_cast<string>(nroot) + ".cc";
ofs.open(filename.c_str());
ofs << "\
//\n\
// BAGEL - Brilliantly Advanced General Electronic Structure Library\n\
// Filename: " + filename + "\n\
// Copyright (C) 2013 Toru Shiozaki\n\
//\n\
// Author: Toru Shiozaki <shiozaki@northwestern.edu>\n\
// Maintainer: Shiozaki group\n\
//\n\
// This file is part of the BAGEL package.\n\
//\n\
// This program is free software: you can redistribute it and/or modify\n\
// it under the terms of the GNU General Public License as published by\n\
// the Free Software Foundation, either version 3 of the License, or\n\
// (at your option) any later version.\n\
//\n\
// This program is distributed in the hope that it will be useful,\n\
// but WITHOUT ANY WARRANTY; without even the implied warranty of\n\
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\
// GNU General Public License for more details.\n\
//\n\
// You should have received a copy of the GNU General Public License\n\
// along with this program. If not, see <http://www.gnu.org/licenses/>.\n\
//\n\
\n\
#include <algorithm> \n\
#include <cassert>" << endl;
#ifdef BREIT
ofs << "#include <src/integral/rys/breitrootlist.h>\n\
\n\
using namespace std;\n\
using namespace bagel;\n\
\n\
void BreitRootList::" << func << nroot << "(const double* ta, double* rr, double* ww, const int n) {\n" << endl;
#else
#ifdef DAWSON
ofs << "#include <src/integral/rys/r2rootlist.h>\n\
\n\
using namespace std;\n\
using namespace bagel;\n\
\n\
void R2RootList::" << func << nroot << "(const double* ta, double* rr, double* ww, const int n) {\n" << endl;
#else
#ifdef SPIN2
ofs << "#include <src/integral/rys/spin2rootlist.h>\n\
\n\
using namespace std;\n\
using namespace bagel;\n\
\n\
void Spin2RootList::" << func << nroot << "(const double* ta, double* rr, double* ww, const int n) {\n" << endl;
#else
ofs << "#include <src/integral/rys/erirootlist.h>\n\
\n\
using namespace std;\n\
using namespace bagel;\n\
\n\
void ERIRootList::" << func << nroot << "(const double* ta, double* rr, double* ww, const int n) {\n" << endl;
#endif
#endif
#endif
ofs << "\
constexpr double ax["<<nroot<<"] = {";
for (int j=0; j!= nroot; ++j) {
ofs << scientific << setprecision(15) << setw(20) << aroot[j];
if (j != nroot-1) ofs << ",";
if (j%7 == 4) ofs << endl << " ";
}
ofs << "};" << endl;
ofs << "\
constexpr double aw["<<nroot<<"] = {";
for (int j=0; j!= nroot; ++j) {
ofs << scientific << setprecision(15) << setw(20) << aweight[j];
if (j != nroot-1) ofs << ",";
if (j%7 == 4) ofs << endl << " ";
}
ofs << "};" << endl;
////////////////////////////////////////
// now creates data
////////////////////////////////////////
stringstream listx, listw;
string indent(" ");
int nblock = 0;
int index = 0;
double tiny = 1.0e-100;
int xcnt = 0;
int wcnt = 0;
#ifdef DAWSON
const int ibox0 = static_cast<int>(log(MAXT)/log(2.0));
#endif
for (int j=0; j != jend; ++j) {
#ifndef DAWSON
vector<vector<double>> c_all = get_C(j*mstride, mstride, nroot, false);
#else
vector<vector<double>> c_all;
if (j < NBOX) {
c_all = get_C(j*mstride, mstride, nroot, false);
} else {
if (MAXT < T_INFTY) {
if (j >= NBOX && j < jend-1) { // NBOXL between MAXT and T_ASYM
const int ibox = j - NBOX;
const mpreal mstart = static_cast<mpreal> (MAXT + ibox*(ibox + 1.0)*(2.0*ibox + 1.0)/6.0);
const mpreal mstrideL = static_cast<mpreal> (ibox + 1.0)*(ibox + 1.0);
c_all = get_C(mstart, mstrideL, nroot, false);
} else {
const mpreal mstart = static_cast<mpreal> (T_ASYM);
const mpreal mstrideL = static_cast<mpreal> (infty - T_ASYM);
c_all = get_C(mstart, mstrideL, nroot, true);
}
} else {
assert(NBOXL == 0);
const int ibox = j - NBOX;
const mpreal mstart = static_cast<mpreal>(pow(2.0, ibox0 + ibox));
const mpreal mstrideL = static_cast<mpreal>(pow(2.0, ibox0 + ibox));
c_all = get_C(mstart, mstrideL, nroot, true);
}
}
#endif
for (int i = 0; i != nroot; ++i, ++index) {
const int ii = 2 * i;
const vector<double> x = c_all[ii];
const vector<double> w = c_all[ii + 1];
for (auto iter = x.begin(); iter != x.end(); ++iter) {
listx << indent << scientific << setprecision(15) << ((*iter > 0.0 || fabs(*iter) < tiny) ? " " : "") << setw(20) <<
(fabs(*iter) < tiny ? 0.0 : *iter);
if (iter + 1 != x.end() || j+1 != jend || i+1 != nroot || MAXT >= T_INFTY) listx << ",";
if (xcnt++ % 7 == 4) listx << "\n";
}
for (auto iter = w.begin(); iter != w.end(); ++iter) {
listw << indent << scientific << setprecision(15) << ((*iter > 0.0 || fabs(*iter) < tiny) ? " " : "") << setw(20) <<
(fabs(*iter) < tiny ? 0.0 : *iter);
if (iter + 1 != w.end() || j+1 != jend || i+1 != nroot || MAXT >= T_INFTY) listw << ",";
if (wcnt++ % 7 == 4) listw << "\n";
}
}
}
#ifdef DAWSON
if (MAXT >= T_INFTY) {
for (int ibox = 0; ibox != T_INFTY; ++ibox) {
vector<mpreal> tt_infty(1); tt_infty[0] = static_cast<mpreal>(pow(2.0, ibox + ibox0 + 1));
vector<mpreal> dx_infty(nroot);
vector<mpreal> dw_infty(nroot);
rysroot_gmp(tt_infty, dx_infty, dw_infty, nroot, 1);
for (auto iter = dx_infty.begin(); iter != dx_infty.end(); ++iter) {
listx << indent << scientific << setprecision(15) << ((*iter > 0.0 || fabs(*iter) < tiny) ? " " : "") << setw(20) <<
(fabs(*iter) < tiny ? 0.0 : *iter);
if (iter + 1 != dx_infty.end() || ibox + 1 != T_INFTY) listx << ",";
if (xcnt++ % 7 == 4) listx << "\n";
}
for (auto iter = dw_infty.begin(); iter != dw_infty.end(); ++iter) {
listw << indent << scientific << setprecision(15) << ((*iter > 0.0 || fabs(*iter) < tiny) ? " " : "") << setw(20) <<
(fabs(*iter) < tiny ? 0.0 : *iter);
if (iter + 1 != dw_infty.end() || ibox + 1 != T_INFTY) listw << ",";
if (wcnt++ % 7 == 4) listw << "\n";
}
}
}
#endif
#ifndef SPIN2
#ifndef BREIT
string tafactor = "t";
#else
string tafactor = "t*t*t";
#endif
#else
string tafactor = "t*t*t*t*t";
#endif
int nbox2 = 0;
#ifndef DAWSON
const int nbox1 = nbox;
#else
int nbox1;
if (MAXT < T_INFTY) {
nbox1 = nbox + NBOXL + 1;
} else {
nbox1 = nbox + T_INFTY;
nbox2 = T_INFTY;
}
#endif
ofs << "\
constexpr double x[" << nroot*nbox1*ndeg + nroot*nbox2 <<"] = {";
ofs << listx.str() << "\
};" << endl;
ofs << "\
constexpr double w[" << nroot*nbox1*ndeg + nroot*nbox2 <<"] = {";
ofs << listw.str() << "\
};" << endl;
ofs << "\
int offset = -" << nroot << ";\n";
#ifdef DAWSON
ofs << "\
const int ibox0 = static_cast<int>(log(" << MAXT << ".0) / log(2.0)); \n";
#endif
ofs << "\
for (int i = 1; i <= n; ++i) {\n\
double t = ta[i-1];\n\
offset += " << nroot << ";\n\
if (std::isnan(t)) {\n\
fill_n(rr+offset, " << nroot << ", 0.5);\n\
fill_n(ww+offset, " << nroot << ", 0.0);\n";
#ifndef DAWSON
ofs << "\
} else if (t >= " << MAXT << ".0) {\n\
t = 1.0/sqrt(t);\n\
for (int r = 0; r != " << nroot << "; ++r) {\n\
rr[offset+r] = ax[r]*t*t;\n\
ww[offset+r] = aw[r]*" + tafactor + ";\n\
}\n\
} else {\n\
assert(t >= 0);\n\
int it = static_cast<int>(t*" << setw(20) << setprecision(15) << fixed << 1.0/stride<< ");\n\
t = (t-it*" << stride << "-" << setw(20) << setprecision(15) << fixed << stride/2.0 << ") *" << setw(20) << setprecision(15) << fixed << 2.0/stride << ";\n\
\n";
#else
ofs << "\
} else if (t >= " << infty << ".0) {\n\
for (int r = 0; r != " << nroot << "; ++r) {\n\
ww[offset+r] = aw[" << nroot << "-r-1] / t;\n\
rr[offset+r] = 1.0 - ax[" << nroot << "-r-1] / t;\n\
}\n\
} else {\n\
assert(t >= 0);\n";
if (MAXT < T_INFTY) {
ofs << "\
vector<double> rr_infty(" << nroot << "); \n\
vector<double> ww_infty(" << nroot << "); \n";
for (int j = 0; j != nroot; ++j) {
ofs << "\
ww_infty[" << j << "] = " << setw(20) << setprecision(15) << fixed << dw_infty[j] << "; \n\
rr_infty[" << j << "] = " << setw(20) << setprecision(15) << fixed << dx_infty[j] << "; \n";
}
}
ofs << "\
int it; \n\
double bigT = 0.0; \n";
if (NBOXL != 0) {
ofs << "\
if (" << MAXT << ".0 <= t && t < " << T_ASYM << ".0) { \n\
int ka = static_cast<int>((pow((t - " << MAXT << ".0)*6.0, 1.0/3.0) - pow(0.25, 1.0/3.0))/pow(2.0, 1.0/3.0)); \n\
int kb = static_cast<int>((pow((t - " << MAXT << ".0)*6.0, 1.0/3.0) - pow(6.0, 1.0/3.0))/pow(2.0, 1.0/3.0)); \n\
assert(kb + 1 == ka || kb == ka); \n\
it = " << NBOX << " + ka; \n\
double a = " << MAXT << ".0 + ka * (ka + 1) * (2*ka + 1)/6.0; \n\
double b = " << MAXT << ".0 + (ka + 1) * (ka + 2) * (2*ka + 3)/6.0; \n\
t = (t - (a+b)/2) * 2/(a-b);\n\
} else if (t >= " << T_ASYM << ".0 && t < " << infty << ".0) { \n";
} else {
ofs << "\
if (t >= " << T_ASYM << ".0 && t < " << infty << ".0) { \n";
}
ofs << "\
bigT = t; \n";
if (MAXT < T_INFTY) {
ofs << "\
it = static_cast<int>(" << NBOX + NBOXL << ");\n\
t = (t - (" << T_ASYM << ".0 + " << infty << ".0)/2) * 2/(" << infty << ".0 - " << T_ASYM << ".0);\n";
} else {
ofs << "\
it = static_cast<int>(log(bigT) / log(2.0) + " << NBOX << " - ibox0);\n\
t = (t - 1.5 * pow(2.0, it + ibox0 - " << NBOX << "))* 2/pow(2.0, it + ibox0 - " << NBOX << ");\n\
cout << \" new t = \" << t << endl; \n";
}
ofs << "\
} else { \n\
it = static_cast<int>(t*" << setw(20) << setprecision(15) << fixed << 1.0/stride<< ");\n\
t = (t - it *" << stride << "-" << setw(20) << setprecision(15) << fixed << stride/2.0 << ") *" << setw(20) << setprecision(15) << fixed << 2.0/stride << ";\n\
} \n";
#endif
ofs << "\
const double t2 = t * 2.0;\n\
for (int j=1; j <=" << nroot << "; ++j) {\n\
const int boxof = it*" << ndeg*nroot << "+" << ndeg << "*(j-1);\n";
assert((ndeg/2)*2 == ndeg);
for (int i=ndeg; i!=0; --i) {
if (i==ndeg) {
ofs << "\
double d = x[boxof+" << i-1 << "];\n\
double e = w[boxof+" << i-1 << "];\n";
} else if (i==ndeg-1) {
ofs << "\
double f = t2*d + x[boxof+" << i-1 << "];\n\
double g = t2*e + w[boxof+" << i-1 << "];\n";
} else if (i != 1 && ((i/2)*2 == i)) { // odd
ofs << "\
d = t2*f - d + x[boxof+" << i-1 << "];\n\
e = t2*g - e + w[boxof+" << i-1 << "];\n";
} else if (i != 1) { // even
ofs << "\
f = t2*d - f + x[boxof+" << i-1 << "];\n\
g = t2*e - g + w[boxof+" << i-1 << "];\n";
} else {
ofs << "\
rr[offset+j-1] = t*d - f + x[boxof+" << i-1 << "]*0.5;\n\
ww[offset+j-1] = t*e - g + w[boxof+" << i-1 << "]*0.5;\n";
#ifdef DAWSON
if (MAXT < T_INFTY) {
ofs << "\
if (" << T_ASYM << ".0 <= bigT && bigT < " << infty << ".0) { \n\
ww[offset+j-1] = ww[offset+j-1] * ww_infty[" << nroot << "-j] * " << infty << ".0 / bigT;\n\
rr[offset+j-1] = 1.0 + rr[offset+j-1] * (1.0 - rr_infty[" << nroot << "-j]) * " << infty << ".0 /bigT; \n\
}\n";
} else {
ofs << "\
if (" << MAXT << ".0 <= bigT && bigT < " << infty << ".0) {\n\
const int iref = " << (NBOX + T_INFTY) * nroot * NGRID << " + (it - " << NBOX << ") * " << nroot << " + " << nroot << " - j;\n\
double rr_infty = x[iref];\n\
double ww_infty = w[iref];\n\
double Tref = pow(2.0, it + ibox0 + 1 - " << NBOX << ");\n\
ww[offset+j-1] = ww[offset+j-1] * ww_infty * Tref / bigT;\n\
rr[offset+j-1] = 1.0 + rr[offset+j-1] * (1.0 - rr_infty) * Tref /bigT;\n\
}\n";
}
#endif
}
}
ofs << "\
}\n\
}\n\
}\n\
}";
ofs.close();
}
return 0;
}
| nubakery/bagel | src/integral/rys/interpolate/main.cc | C++ | gpl-3.0 | 22,012 |
/// \file container.h
/// \brief simple array in STL style, level-based array
/// \author LNM RWTH Aachen: Joerg Grande, Volker Reichelt; SC RWTH Aachen: Oliver Fortmeier
/*
* This file is part of DROPS.
*
* DROPS is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* DROPS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with DROPS. If not, see <http://www.gnu.org/licenses/>.
*
*
* Copyright 2009 LNM/SC RWTH Aachen, Germany
*/
#ifndef DROPS_CONTAINER_H
#define DROPS_CONTAINER_H
#include <vector>
#include <list>
#include <cmath>
#include <iostream>
#include <valarray>
#include "misc/utils.h"
namespace DROPS
{
//**************************************************************************
// Class: DMatrixCL *
// Purpose: dynamical storage for 2D data *
// Remarks: just the bare minimum *
//**************************************************************************
template <typename T>
class DMatrixCL
{
private:
size_t Rows_, Cols_;
T* Array_;
public:
DMatrixCL(size_t row, size_t col) : Rows_(row), Cols_(col), Array_(new T[row*col]) {}
~DMatrixCL() { delete[] Array_; }
T& operator() (size_t row, size_t col) {
Assert(row<Rows_ && col<Cols_, DROPSErrCL("DMatrixCL::operator(): Invalide index"), DebugNumericC);
return Array_[col*Rows_+row];
}
T operator() (size_t row, size_t col) const {
Assert(row<Rows_ && col<Cols_, DROPSErrCL("DMatrixCL::operator() const: Invalide index"), DebugNumericC);
return Array_[col*Rows_+row];
}
T* GetCol (size_t col) {
Assert(col<Cols_, DROPSErrCL("DMatrixCL::GetCol: Invalide index"), DebugNumericC);
return Array_+col*Rows_;
}
};
template <class T, Uint _Size>
class SArrayCL;
template <class T, Uint _Size>
class SBufferCL;
template <Uint _Size>
class SVectorCL;
template <Uint _Rows, Uint _Cols>
class SMatrixCL;
template <class T, Uint _Size>
inline bool
operator==(const SArrayCL<T, _Size>&, const SArrayCL<T, _Size>&);
template <class T, Uint _Size>
inline bool
operator<(const SArrayCL<T, _Size>&, const SArrayCL<T, _Size>&);
template <class T, Uint _Size>
inline bool
operator==(const SBufferCL<T, _Size>&, const SBufferCL<T, _Size>&);
/// Stores 2D coordinates
typedef SVectorCL<2> Point2DCL;
/// Stores 3D coordinates
typedef SVectorCL<3> Point3DCL;
/// Stores barycentric coordinates
typedef SVectorCL<4> BaryCoordCL;
enum InitStateT { Uninitialized, Initialized };
//**************************************************************************
// Class: SArrayCL *
// Purpose: an array that remembers its size *
// Remarks: All functions are inline, should be as fast as a "bare" array *
//**************************************************************************
template <class T, Uint _Size>
class SArrayCL
{
private:
T Array[_Size];
public:
typedef T* iterator;
typedef const T* const_iterator;
typedef T& reference;
typedef const T& const_reference;
typedef T value_type;
// SArrayCL() {}
explicit SArrayCL(T val= T()) { std::fill_n(Array+0, _Size, val); }
/*uninitialized memory; mainly for faster SVectorCL-math*/
explicit SArrayCL(InitStateT) {}
template<class In> explicit SArrayCL(In start) { std::copy(start, start+_Size, Array+0); }
template<class In> SArrayCL(In start, In end) { std::copy(start, end, Array+0); }
// Default copy-ctor, assignment operator, dtor
iterator begin () { return static_cast<T*>(Array); }
const_iterator begin () const { return static_cast<const T*>(Array); }
iterator end () { return Array+_Size; }
const_iterator end () const { return Array+_Size; }
reference operator[](Uint i) { Assert(i<_Size, DROPSErrCL("SArrayCL::operator[]: wrong index"), DebugContainerC);
return Array[i]; }
value_type operator[](Uint i) const { Assert(i<_Size, DROPSErrCL("SArrayCL::operator[]: wrong index"), DebugContainerC);
return Array[i]; }
Uint size () const { return _Size; }
friend bool operator==<>(const SArrayCL&, const SArrayCL&); // Component-wise equality
friend bool operator< <>(const SArrayCL&, const SArrayCL&); // lexicographic ordering
};
template <class T, Uint _Size>
inline bool
operator==(const SArrayCL<T, _Size>& a0, const SArrayCL<T, _Size>& a1)
{
for (Uint i=0; i<_Size; ++i)
if (a0[i] != a1[i]) return false;
return true;
}
template <class T, Uint _Size>
inline bool
operator<(const SArrayCL<T, _Size>& a0, const SArrayCL<T, _Size>& a1)
{
for (Uint i=0; i<_Size; ++i)
if (a0[i] < a1[i]) return true;
else if ( a0[i] > a1[i]) return false;
return false;
}
template <class T, Uint _Size>
inline const T*
Addr(const SArrayCL<T, _Size>& a)
{
return a.begin();
}
template <class T, Uint _Size>
inline T*
Addr(SArrayCL<T, _Size>& a)
{
return a.begin();
}
//**************************************************************************
// Class: SBufferCL *
// Purpose: A buffer or ring-buffer of fixed size with wrap-around indices*
//**************************************************************************
template <class T, Uint _Size>
class SBufferCL
{
private:
T Array[_Size];
int Front;
public:
typedef T& reference;
typedef const T& const_reference;
typedef T value_type;
// SBufferCL() {}
explicit SBufferCL(T val= T()) { std::fill_n(Array+0, _Size, val); Front= 0; }
template<class In> explicit SBufferCL(In start) { std::copy(start, start+_Size, Array+0); Front= 0; }
template<class In> SBufferCL(In start, In end) { std::copy(start, end, Array+0); Front= 0; }
SBufferCL(const SBufferCL& b) {
std::copy( b.Array+0, b.Array+_Size, Array+0);
Front= b.Front; }
SBufferCL& operator=(const SBufferCL& b) {
if (&b!=this) {
std::copy( b.Array+0, b.Array+_Size, Array+0);
Front= b.Front; }
return *this; }
// Default dtor
reference operator[](int i) {
if (i<0) i+= _Size;
else if (i >= static_cast<int>( _Size)) i-=_Size;
Assert( (i>=0 && i<static_cast<int>( _Size)), DROPSErrCL("SBufferCL::operator[]: wrong index"), DebugContainerC);
return Array[(i+Front < static_cast<int>( _Size)) ? i+Front : i+Front-_Size]; }
value_type operator[](int i) const {
if (i<0) i+= _Size;
else if (i >= static_cast<int>( _Size)) i-=_Size;
Assert( (i>=0 && i<_Size), DROPSErrCL("SBufferCL::operator[]: wrong index"), DebugContainerC);
return Array[(i+Front < static_cast<int>( _Size)) ? i+Front : i+Front-_Size]; }
Uint size() const { return _Size; }
// first entry is overwritten.
void push_back(const T& t) {
Array[Front]= t;
if (++Front == static_cast<int>( _Size)) Front-= _Size; }
// for positive i, front element moves to the end.
void rotate (int i= 1) {
Assert(i<static_cast<int>( _Size), DROPSErrCL("SBufferCL::rotate: wrong index"), DebugContainerC);
Front+= i;
if (Front >= static_cast<int>( _Size)) Front-= _Size;
else if (Front < 0) Front+= _Size; }
friend bool operator==<>(const SBufferCL&, const SBufferCL&);
};
template <class T, Uint _Size>
inline bool
operator==(const SBufferCL<T, _Size>& a0, const SBufferCL<T, _Size>& a1)
{
if (a0.Front != a1.Front) return false;
for (Uint i=0; i<_Size; ++i)
if (a0.Array[i] != a1.Array[i]) return false;
return true;
}
//**************************************************************************
// Class: SVectorCL *
// Purpose: primitive vector class with templates for short vectors *
// Remarks: Many optimizations are possible. *
//**************************************************************************
template <Uint _Size>
class SVectorCL : public SArrayCL<double,_Size>
{
public:
typedef SArrayCL<double,_Size> base_type;
SVectorCL() {}
explicit SVectorCL(InitStateT i) : base_type( i) {}
explicit SVectorCL(double val) : base_type( val) {}
template<class In> explicit SVectorCL(In start) : base_type( start) {}
template<class In> SVectorCL(In start, In end) : base_type( start,end) {}
SVectorCL& operator+=(const SVectorCL&);
SVectorCL& operator-=(const SVectorCL&);
SVectorCL& operator*=(double);
SVectorCL& operator/=(double);
// komponentenweise Operatoren
SVectorCL& operator*=(const SVectorCL&);
SVectorCL& operator/=(const SVectorCL&);
double norm_sq() const;
double norm() const { return std::sqrt(norm_sq()); }
};
template <Uint _Size>
SVectorCL<_Size>&
SVectorCL<_Size>::operator+=(const SVectorCL& v)
{
for (Uint i=0; i!=_Size; ++i) (*this)[i]+= v[i];
return *this;
}
template <Uint _Size>
SVectorCL<_Size>&
SVectorCL<_Size>::operator-=(const SVectorCL<_Size>& v)
{
for (Uint i=0; i!=_Size; ++i) (*this)[i]-= v[i];
return *this;
}
template <Uint _Size>
SVectorCL<_Size>&
SVectorCL<_Size>::operator*=(const SVectorCL<_Size>& v)
{
for (Uint i=0; i!=_Size; ++i) (*this)[i]*= v[i];
return *this;
}
template <Uint _Size>
SVectorCL<_Size>&
SVectorCL<_Size>::operator/=(const SVectorCL<_Size>& v)
{
for (Uint i=0; i!=_Size; ++i) (*this)[i]/= v[i];
return *this;
}
template <Uint _Size>
SVectorCL<_Size>&
SVectorCL<_Size>::operator*=(double s)
{
for (Uint i=0; i!=_Size; ++i) (*this)[i]*= s;
return *this;
}
template <Uint _Size>
SVectorCL<_Size>&
SVectorCL<_Size>::operator/=(double s)
{
for (Uint i=0; i!=_Size; ++i) (*this)[i]/= s;
return *this;
}
template <Uint _Size>
double SVectorCL<_Size>::norm_sq() const
{
double x = 0.0;
for (Uint i=0; i<_Size; ++i) x += (*this)[i]*(*this)[i];
return x;
}
template <Uint _Size>
SVectorCL<_Size> BaryCenter(const SVectorCL<_Size>& v1, const SVectorCL<_Size>& v2)
{
SVectorCL<_Size> tempv( Uninitialized);
for (Uint i=0; i<_Size; ++i) tempv[i] = .5 * (v1[i] + v2[i]);
return tempv;
}
template <Uint _Size>
SVectorCL<_Size> ConvexComb (double a,
const SVectorCL<_Size>& v1,
const SVectorCL<_Size>& v2)
{
SVectorCL<_Size> tempv( Uninitialized);
for (Uint i=0; i<_Size; ++i) tempv[i] = (1.0-a)*v1[i] + a*v2[i];
return tempv;
}
template <Uint _Size>
SVectorCL<_Size> operator+(const SVectorCL<_Size>& v1,
const SVectorCL<_Size>& v2)
{
SVectorCL<_Size> tempv( Uninitialized);
for (Uint i=0; i<_Size; ++i) tempv[i]= v1[i] + v2[i];
return tempv;
}
template <Uint _Size>
SVectorCL<_Size> operator-(const SVectorCL<_Size>& v1,
const SVectorCL<_Size>& v2)
{
SVectorCL<_Size> tempv( Uninitialized);
for (Uint i=0; i<_Size; ++i) tempv[i]= v1[i] - v2[i];
return tempv;
}
template <Uint _Size>
SVectorCL<_Size> operator-(const SVectorCL<_Size>& v1)
{
SVectorCL<_Size> tempv( Uninitialized);
for (Uint i=0; i<_Size; ++i) tempv[i]= -v1[i];
return tempv;
}
template <Uint _Size>
SVectorCL<_Size> operator*(double d, const SVectorCL<_Size>& v)
{
SVectorCL<_Size> tempv( Uninitialized);
for (Uint i=0; i<_Size; ++i) tempv[i]= d * v[i];
return tempv;
}
template <Uint _Size>
SVectorCL<_Size> operator*(const SVectorCL<_Size>& v, double d)
{
return d*v;
}
template <Uint _Size>
double inner_prod(const SVectorCL<_Size>& v1, const SVectorCL<_Size>& v2)
{
double ret= 0.0;
for (Uint i= 0; i <_Size; ++i) ret+= v1[i]*v2[i];
return ret;
}
inline double
inner_prod(const SVectorCL<3u>& v1, const SVectorCL<3u>& v2)
{
return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2];
}
template <Uint _Size>
SVectorCL<_Size> operator/(const SVectorCL<_Size>& v, double d)
{
SVectorCL<_Size> tempv( Uninitialized);
for (Uint i=0; i<_Size; ++i) tempv[i]= v[i]/d;
return tempv;
}
template <Uint _Size>
SVectorCL<_Size> operator*(const SVectorCL<_Size>& v1,
const SVectorCL<_Size>& v2)
{
SVectorCL<_Size> tempv( Uninitialized);
for (Uint i=0; i<_Size; ++i) tempv[i]= v1[i] * v2[i];
return tempv;
}
template <Uint _Size>
SVectorCL<_Size> operator/(const SVectorCL<_Size>& v1,
const SVectorCL<_Size>& v2)
{
SVectorCL<_Size> tempv( Uninitialized);
for (Uint i=0; i<_Size; ++i) tempv[i]= v1[i] / v2[i];
return tempv;
}
template <Uint _Size>
bool operator<(const SVectorCL<_Size>& v1,
const SVectorCL<_Size>& v2)
{
for (Uint i=0; i<_Size; ++i) if(!( v1[i] < v2[i]) ) return false;
return true;
}
template <Uint _Size>
SVectorCL<_Size> sqrt(const SVectorCL<_Size>& v)
{
SVectorCL<_Size> tempv( Uninitialized);
for (Uint i=0; i<_Size; ++i) tempv[i]= std::sqrt(v[i]);
return tempv;
}
template <Uint _Size>
SVectorCL<_Size> fabs(const SVectorCL<_Size>& v)
{
SVectorCL<_Size> tempv( Uninitialized);
for (Uint i=0; i<_Size; ++i) tempv[i]= std::fabs(v[i]);
return tempv;
}
template <Uint _Size>
std::ostream& operator<<(std::ostream& os, const SVectorCL<_Size>& v)
{
// os << v.size() << " ";
for (Uint i=0; i<v.size(); ++i)
os << v[i] << ' ';
return os;
}
inline void
cross_product(Point3DCL& res, const Point3DCL& v0, const Point3DCL& v1)
// res= v0 x v1
{
res[0]= v0[1]*v1[2] - v0[2]*v1[1];
res[1]= v0[2]*v1[0] - v0[0]*v1[2];
res[2]= v0[0]*v1[1] - v0[1]*v1[0];
}
// std_basis<n>(0)==Null, std_basis<n>(i)[j]==Delta_i-1_j
template <Uint _Size>
inline SVectorCL<_Size> std_basis(Uint i)
{
SVectorCL<_Size> ret(0.);
if (i>0) ret[i-1]= 1.;
return ret;
}
inline BaryCoordCL
MakeBaryCoord(double a, double b, double c, double d)
{
BaryCoordCL ret( Uninitialized);
ret[0]= a; ret[1]= b; ret[2]= c; ret[3]= d;
return ret;
}
inline Point3DCL
MakePoint3D(double a, double b, double c)
{
Point3DCL ret( Uninitialized);
ret[0]= a; ret[1]= b; ret[2]= c;
return ret;
}
inline Point2DCL
MakePoint2D(double a, double b)
{
Point2DCL ret( Uninitialized);
ret[0]= a; ret[1]= b;
return ret;
}
template<class T>
SArrayCL<T, 2>
MakeSArray(T a, T b)
{
SArrayCL<T, 2> ret( Uninitialized);
ret[0]= a; ret[1]= b;
return ret;
}
template<class T>
SArrayCL<T, 3>
MakeSArray(T a, T b, T c)
{
SArrayCL<T, 3> ret( Uninitialized);
ret[0]= a; ret[1]= b; ret[2]= c;
return ret;
}
template<class T>
SArrayCL<T, 4>
MakeSArray(T a, T b, T c, T d)
{
SArrayCL<T, 4> ret( Uninitialized);
ret[0]= a; ret[1]= b; ret[2]= c; ret[3]= d;
return ret;
}
template <class T, Uint _Size>
std::ostream& operator<<(std::ostream& os, const SArrayCL<T,_Size>& a)
{
// os << v.size() << " ";
for (Uint i=0; i<a.size(); ++i)
os << a[i] << ' ';
return os;
}
template <Uint _Rows, Uint _Cols>
class SMatrixCL : public SVectorCL<_Rows*_Cols>
{
public:
typedef SVectorCL<_Rows*_Cols> _vec_base;
SMatrixCL() {}
explicit SMatrixCL(InitStateT i) : _vec_base( i) {}
explicit SMatrixCL(double val) : _vec_base( val) {}
template<class In> explicit SMatrixCL(In start) : _vec_base( start) {}
template<class In> SMatrixCL(In start, In end) : _vec_base( start,end) {}
// Schreib- & Lesezugriff
double& operator() (int row, int col) { return (*this)[row*_Cols+col]; }// Matrix(i,j)
double operator() (int row, int col) const { return (*this)[row*_Cols+col]; }
SVectorCL<_Rows> col( int) const;
void col( int, const SVectorCL<_Rows>&);
// Zuweisung & Co.
SMatrixCL& operator+=(const SMatrixCL&); // Matrix=Matrix+Matrix'
SMatrixCL& operator-=(const SMatrixCL&); // Matrix=Matrix-Matrix'
SMatrixCL& operator*=(double s); // Matrix = c * Matrix
SMatrixCL& operator/=(double s); // Matrix = Matrix'/c
// Dimensionen feststellen
Uint num_rows() const { return _Rows; } // Zeilenzahl
Uint num_cols() const { return _Cols; } // Spaltenzahl
};
template<Uint _Rows, Uint _Cols>
SVectorCL<_Rows>
SMatrixCL<_Rows, _Cols>::col (int c) const
{
SVectorCL<_Rows> ret( Uninitialized);
for (Uint i= 0; i != _Rows; ++i, c+= _Cols)
ret[i]= (*this)[c];
return ret;
}
template<Uint _Rows, Uint _Cols>
void
SMatrixCL<_Rows,_Cols>::col (int c, const SVectorCL<_Rows>& v)
{
for (Uint i= 0; i != _Rows; ++i)
(*this)( i, c)= v[i];
}
template<Uint _Rows, Uint _Cols>
SMatrixCL<_Rows, _Cols>&
SMatrixCL<_Rows, _Cols>::operator+=(const SMatrixCL<_Rows, _Cols>& m)
{
*static_cast<_vec_base*>(this)+= *static_cast<const _vec_base*>(&m);
return *this;
}
template<Uint _Rows, Uint _Cols>
SMatrixCL<_Rows, _Cols>&
SMatrixCL<_Rows, _Cols>::operator-=(const SMatrixCL<_Rows, _Cols>& m)
{
*static_cast<_vec_base*>(this)-= *static_cast<const _vec_base*>(&m);
return *this;
}
template<Uint _Rows, Uint _Cols>
SMatrixCL<_Rows, _Cols>&
SMatrixCL<_Rows, _Cols>::operator*=(double d)
{
*static_cast<_vec_base*>(this)*= d;
return *this;
}
template<Uint _Rows, Uint _Cols>
SMatrixCL<_Rows, _Cols>&
SMatrixCL<_Rows, _Cols>::operator/=(double d)
{
*static_cast<_vec_base*>(this)/= d;
return *this;
}
template<Uint _Rows, Uint _Cols>
SMatrixCL<_Rows, _Cols>
operator+(const SMatrixCL<_Rows, _Cols>& m1, const SMatrixCL<_Rows, _Cols>& m2)
{
SMatrixCL<_Rows, _Cols> ret( Uninitialized);
*static_cast<typename SMatrixCL<_Rows, _Cols>::_vec_base*>(&ret)
= *static_cast<const typename SMatrixCL<_Rows, _Cols>::_vec_base*>(&m1)
+*static_cast<const typename SMatrixCL<_Rows, _Cols>::_vec_base*>(&m2);
return ret;
}
template<Uint _Rows, Uint _Cols>
SMatrixCL<_Rows, _Cols>
operator-(const SMatrixCL<_Rows, _Cols>& m1, const SMatrixCL<_Rows, _Cols>& m2)
{
SMatrixCL<_Rows, _Cols> ret( Uninitialized);
*static_cast<typename SMatrixCL<_Rows, _Cols>::_vec_base*>(&ret)
= *static_cast<const typename SMatrixCL<_Rows, _Cols>::_vec_base*>(&m1)
-*static_cast<const typename SMatrixCL<_Rows, _Cols>::_vec_base*>(&m2);
return ret;
}
template<Uint _Rows, Uint _Cols>
SMatrixCL<_Rows, _Cols>
operator-(const SMatrixCL<_Rows, _Cols>& m)
{
SMatrixCL<_Rows, _Cols> ret( Uninitialized);
*static_cast<typename SMatrixCL<_Rows, _Cols>::_vec_base*>(&ret)
= -*static_cast<const typename SMatrixCL<_Rows, _Cols>::_vec_base*>(&m);
return ret;
}
template<Uint _Rows, Uint _Cols>
SMatrixCL<_Rows, _Cols>
operator*(double d, const SMatrixCL<_Rows, _Cols>& m)
{
SMatrixCL<_Rows, _Cols> ret( Uninitialized);
*static_cast<typename SMatrixCL<_Rows, _Cols>::_vec_base*>(&ret)
= d**static_cast<const typename SMatrixCL<_Rows, _Cols>::_vec_base*>(&m);
return ret;
}
template<Uint _Rows, Uint _Cols>
SMatrixCL<_Rows, _Cols>
operator*(const SMatrixCL<_Rows, _Cols>& m, double d)
{
SMatrixCL<_Rows, _Cols> ret( Uninitialized);
*static_cast<typename SMatrixCL<_Rows, _Cols>::_vec_base*>(&ret)
= *static_cast<const typename SMatrixCL<_Rows, _Cols>::_vec_base*>(&m)*d;
return ret;
}
template<Uint _Rows, Uint _Cols>
SMatrixCL<_Rows, _Cols>
operator/(const SMatrixCL<_Rows, _Cols>& m, double d)
{
SMatrixCL<_Rows, _Cols> ret( Uninitialized);
*static_cast<typename SMatrixCL<_Rows, _Cols>::_vec_base*>(&ret)
= *static_cast<const typename SMatrixCL<_Rows, _Cols>::_vec_base*>(&m)/d;
return ret;
}
template<Uint _RowsL, Uint _ColsR, Uint _Dim>
SMatrixCL<_RowsL, _ColsR>
operator*(const SMatrixCL<_RowsL, _Dim>& m1, const SMatrixCL<_Dim, _ColsR>& m2)
{
SMatrixCL<_RowsL, _ColsR> ret(0.0);
for (Uint row=0; row!=_RowsL; ++row)
for (Uint col=0; col!=_ColsR; ++col)
for (Uint i=0; i!=_Dim; ++i)
ret(row, col)+= m1(row, i)*m2(i, col);
return ret;
}
template<Uint _Rows, Uint _Cols>
SMatrixCL<_Cols, _Cols>
GramMatrix(const SMatrixCL<_Rows, _Cols>& m)
/// Computes m^T*m
{
SMatrixCL<_Cols, _Cols> ret( 0.0);
for (Uint row= 0; row != _Cols; ++row) {
for (Uint col= 0; col < row; ++col) {
for (Uint i= 0; i != _Rows; ++i)
ret( row, col)+= m( i, row)*m( i, col);
ret( col, row)= ret( row, col);
}
for (Uint i= 0; i != _Rows; ++i)
ret( row, row)+= std::pow( m( i, row), 2);
}
return ret;
}
template<Uint _Rows, Uint _Cols>
SVectorCL<_Cols>
transp_mul(const SMatrixCL<_Rows, _Cols>& m, const SVectorCL<_Rows>& v)
{
SVectorCL<_Cols> ret(0.0);
for (Uint col=0; col!=_Cols; ++col)
for (Uint i=0; i!=_Rows; ++i)
ret[col]+= m( i, col)*v[i];
return ret;
}
template<Uint _Rows, Uint _Cols>
SVectorCL<_Rows>
operator*(const SMatrixCL<_Rows, _Cols>& m, const SVectorCL<_Cols>& v)
{
SVectorCL<_Rows> ret(0.0);
for (Uint row=0; row!=_Rows; ++row)
for (Uint i=0; i!=_Cols; ++i)
ret[row]+= m(row, i)*v[i];
return ret;
}
inline SVectorCL<3>
operator*(const SMatrixCL<3, 3>& m, const SVectorCL<3>& v)
{
SVectorCL<3> ret( Uninitialized);
const double* const a= m.begin();
ret[0]= a[0]*v[0] + a[1]*v[1] + a[2]*v[2];
ret[1]= a[3]*v[0] + a[4]*v[1] + a[5]*v[2];
ret[2]= a[6]*v[0] + a[7]*v[1] + a[8]*v[2];
return ret;
}
template <Uint _Rows, Uint _Cols>
std::ostream& operator << (std::ostream& os, const SMatrixCL<_Rows, _Cols>& m)
{
const Uint M = m.num_rows();
const Uint N = m.num_cols();
os << M << ' ' << N << '\n' ;
for (Uint row=0; row<M; ++row)
{
os << " ";
for (Uint col=0; col<N; ++col)
os << m(row, col) << ' ';
os << '\n';
}
return os;
}
template <Uint _Rows>
inline SMatrixCL<_Rows,_Rows>
outer_product (const SVectorCL<_Rows>& a, const SVectorCL<_Rows>& b)
{
SMatrixCL<_Rows,_Rows> ret( Uninitialized);
for (Uint i= 0; i < _Rows; ++i)
for (Uint j= 0; j < _Rows; ++j)
ret(i, j)= a[i]*b[j];
return ret;
}
template <Uint _Rows>
inline double
frobenius_norm_sq (const SMatrixCL<_Rows, _Rows>& a)
{
double ret = 0;
for (Uint i= 0; i < _Rows*_Rows; ++i)
ret += a[i]*a[i];
return ret;
}
template <Uint _Rows>
inline double
trace (const SMatrixCL<_Rows, _Rows>& a)
{
double ret= 0.;
for (Uint i= 0; i < _Rows; ++i)
ret+= a( i, i);
return ret;
}
template <Uint _Rows>
inline SMatrixCL<_Rows,_Rows>&
assign_transpose (SMatrixCL<_Rows, _Rows>& out, const SMatrixCL<_Rows,_Rows>& in)
{
for (Uint i= 0; i < _Rows; ++i) {
for (Uint j= 0; j < i; ++j) {
out( i, j)= in( j, i);
out( j, i)= in( i, j);
}
out( i, i)= in( i, i);
}
return out;
}
/// \brief \f$full_local+= (scalar_local^T) \mathop{kroneckerproduct} Id_{3\times 3}\f$
///
/// This is the operation that distributes a scalar-valued operator over the block-diagonal of a vector-valued operator.
inline void
add_transpose_kronecker_id (SMatrixCL<3,3> full_local[10][10], const double scalar_local[10][10])
{
for(int i= 0; i < 10; ++i)
for(int j= 0; j < 10; ++j)
for (int k= 0; k < 3; ++k)
full_local[i][j]( k, k)+= scalar_local[j][i];
}
///\brief A small diagonal matrix. It is needed as distinct type for SparseMatBuilderCL for block diagonal sparse matrices.
template <Uint _Rows>
class SDiagMatrixCL : public SVectorCL<_Rows>
{
public:
typedef SVectorCL<_Rows> _vec_base;
SDiagMatrixCL() {}
explicit SDiagMatrixCL(InitStateT i) : _vec_base( i) {}
explicit SDiagMatrixCL(double val) : _vec_base( val) {}
template<class In> explicit SDiagMatrixCL(In start) : _vec_base( start) {}
template<class In> SDiagMatrixCL(In start, In end) : _vec_base( start,end) {}
// Schreib- & Lesezugriff
double& operator() (int row) { return (*this)[row]; }// Matrix(i,i)
double operator() (int row) const { return (*this)[row]; }
// Zuweisung & Co.
SDiagMatrixCL& operator+=(const SDiagMatrixCL&); // Matrix=Matrix+Matrix'
SDiagMatrixCL& operator-=(const SDiagMatrixCL&); // Matrix=Matrix-Matrix'
SDiagMatrixCL& operator*=(double s); // Matrix = c * Matrix
SDiagMatrixCL& operator/=(double s); // Matrix = Matrix'/c
// Dimensionen feststellen
Uint num_rows() const { return _Rows; } // Zeilenzahl
Uint num_cols() const { return _Rows; } // Spaltenzahl
};
template<Uint _Rows>
SDiagMatrixCL<_Rows>&
SDiagMatrixCL<_Rows>::operator+=(const SDiagMatrixCL<_Rows>& m)
{
*static_cast<_vec_base*>(this)+= *static_cast<const _vec_base*>(&m);
return *this;
}
template<Uint _Rows>
SDiagMatrixCL<_Rows>&
SDiagMatrixCL<_Rows>::operator-=(const SDiagMatrixCL<_Rows>& m)
{
*static_cast<_vec_base*>(this)-= *static_cast<const _vec_base*>(&m);
return *this;
}
template<Uint _Rows>
SDiagMatrixCL<_Rows>&
SDiagMatrixCL<_Rows>::operator*=(double d)
{
*static_cast<_vec_base*>(this)*= d;
return *this;
}
template<Uint _Rows>
SDiagMatrixCL<_Rows>&
SDiagMatrixCL<_Rows>::operator/=(double d)
{
*static_cast<_vec_base*>(this)/= d;
return *this;
}
/// \brief A QR-factored, rectangular matrix, A=QR.
///
/// This allows for fast application of A^{-1} and A.
/// A can have more rows than columns. In this case, the least-squares-solution is computed.
template <Uint Rows_, Uint Cols_= Rows_>
class QRDecompCL
{
private:
SMatrixCL<Rows_,Cols_> a_;
double d_[Cols_]; ///< The diagonal of R
double beta_[Cols_]; ///< The reflections are R_j= I + beta_j*a_[j:Rows_-1][j]
public:
QRDecompCL () : a_( Uninitialized) {}
template <class MatT>
QRDecompCL (MatT m)
: a_( m) { prepare_solve (); }
SMatrixCL<Rows_,Cols_>& GetMatrix () { return a_; }
const SMatrixCL<Rows_,Cols_>& GetMatrix () const { return a_; }
void prepare_solve (); ///< Computes the factorization.
///@{ Call only after prepare_solve; solves are inplace. For least-squares, the first Cols_ entries are the least squares solution, the remaining components of b are the residual-vector.
void Solve (SVectorCL<Rows_>& b) const;
void Solve (size_t n, SVectorCL<Rows_>* b) const;
template <template<class> class SVecCont>
void Solve (SVecCont<SVectorCL<Rows_> >& b) const;
template <Uint Size>
void Solve (SArrayCL<SVectorCL<Rows_>, Size>& b) const;
double Determinant_R () const; ///< Computes the determinant of R (stable). For Rows_ > Cols_, the determinant of the upper Cols_ x Cols_ block of R is returned.
///@}
///@{ Serialize and Deserialize a QR decomposition
void Serialize(double*) const;
void Deserialize(const double*);
///@}
};
template <Uint Rows_, Uint Cols_>
double
QRDecompCL<Rows_, Cols_>::Determinant_R () const
{
double tmp= 1.0;
for(Uint i= 0; i < Cols_; ++i)
tmp *= d_[i];
return tmp;
}
template <Uint Rows_, Uint Cols_>
void
QRDecompCL<Rows_, Cols_>::prepare_solve ()
{
// inplace Householder
double sigma, sp;
for (Uint j= 0; j < Cols_; ++j) {
sigma = 0.;
for(Uint i= j; i < Rows_; ++i)
sigma+= std::pow( a_(i, j), 2);
if(sigma == 0.)
throw DROPSErrCL( "QRDecompCL::prepare_solve: rank-deficient matrix\n");
d_[j]= (a_(j, j) < 0 ? 1. : -1.) * std::sqrt( sigma);
beta_[j]= 1./(d_[j]*a_(j, j) - sigma);
a_(j, j)-= d_[j];
for(Uint k= j + 1; k < Cols_; ++k) { // Apply reflection in column j
sp= 0.;
for(Uint i= j; i < Rows_; ++i)
sp+= a_(i, j) * a_(i, k);
sp*= beta_[j];
for(Uint i= j; i < Rows_; ++i)
a_(i, k)+= a_(i, j)*sp;
}
}
}
template <Uint Rows_, Uint Cols_>
void
QRDecompCL<Rows_, Cols_>::Solve (size_t n, SVectorCL<Rows_>* b) const
{
for (Uint i= 0; i < n; ++i)
Solve( b[i]);
}
template <Uint Rows_, Uint Cols_>
void
QRDecompCL<Rows_, Cols_>::Solve (SVectorCL<Rows_>& b) const
{
double sp;
for(Uint j= 0; j < Cols_; ++j) { // Apply reflection in column j
sp= 0.;
for(Uint i= j; i < Rows_; ++i)
sp+= a_(i, j) * b[i];
sp*= beta_[j];
for(Uint i= j; i < Rows_; ++i)
b[i]+= a_(i, j)*sp;
}
for (Uint i= Cols_ - 1; i < Cols_; --i) { // backsolve
for (Uint j= i + 1; j < Cols_; ++j)
b[i]-= a_(i, j)*b[j];
b[i]/= d_[i];
}
}
template <Uint Rows_, Uint Cols_>
template <template<class> class SVecCont>
void
QRDecompCL<Rows_, Cols_>::Solve (SVecCont<SVectorCL<Rows_> >& b) const
{
for (Uint i= 0; i < b.size(); ++i)
Solve( b[i]);
}
template <Uint Rows_, Uint Cols_>
template <Uint Size>
void
QRDecompCL<Rows_, Cols_>::Solve (SArrayCL<SVectorCL<Rows_>, Size>& b) const
{
for (Uint i= 0; i < Size; ++i)
Solve( b[i]);
}
/** Put the values of a_, d_ and beta_ in buffer. Note that buffer must be of size
(Rows_+2)*Cols_
*/
template <Uint Rows_, Uint Cols_>
void QRDecompCL<Rows_, Cols_>::Serialize(double* buffer) const
{
std::copy( a_.begin(), a_.end(), buffer);
std::copy( d_, d_+Cols_, buffer+a_.size());
std::copy( beta_, beta_+Cols_, buffer+a_.size()+Cols_);
}
template <Uint Rows_, Uint Cols_>
void QRDecompCL<Rows_, Cols_>::Deserialize( const double* buffer)
{
std::copy( buffer, buffer+a_.size(), a_.begin());
std::copy( buffer+a_.size(), buffer+a_.size()+Cols_, d_);
std::copy(buffer+a_.size()+Cols_, buffer+a_.size()+Cols_+Cols_, beta_);
}
//**************************************************************************
// Class: GlobalListCL *
// Purpose: A list that is subdivided in levels. For modifications, it can *
// efficiently be split into std::lists per level and then merged *
// after modifications. *
// Remarks: Negative level-indices count backwards from end(). *
//**************************************************************************
template <class T>
class GlobalListCL
{
public:
typedef std::list<T> Cont;
typedef std::list<T> LevelCont;
typedef typename Cont::iterator iterator;
typedef typename Cont::const_iterator const_iterator;
typedef typename LevelCont::iterator LevelIterator;
typedef typename LevelCont::const_iterator const_LevelIterator;
private:
Cont Data_;
std::vector<iterator> LevelStarts_;
std::vector<const_iterator> const_LevelStarts_;
std::vector<LevelCont*> LevelViews_;
bool modifiable_;
int
StdLevel (int lvl) const { return lvl >= 0 ? lvl : lvl + GetNumLevel(); }
public:
GlobalListCL (bool modifiable= true) : modifiable_( modifiable) {}
// standard dtor
Uint GetNumLevel () const {
return modifiable_ ? LevelViews_.size()
: (LevelStarts_.size() > 0 ? LevelStarts_.size()-1 : 0);
}
bool IsEmpty () const
{ return modifiable_ ? LevelViews_.empty() : LevelStarts_.empty(); }
bool IsLevelEmpty (Uint Level) const {
return modifiable_ ? LevelViews_[Level]->empty()
: LevelStarts_[Level] == LevelStarts_[1+Level];
}
// Only useful, if modifiable_ == false, otherwise 0.
Uint size () const { return Data_.size(); }
// If modifiable_==true, Data_ is empty, thus these accessors are useless.
iterator begin () { return Data_.begin(); }
iterator end () { return Data_.end(); }
const_iterator begin () const { return Data_.begin(); }
const_iterator end () const { return Data_.end(); }
iterator level_begin (int lvl)
{ return !modifiable_ ? LevelStarts_[StdLevel( lvl)] : LevelViews_[StdLevel( lvl)]->begin(); }
iterator level_end (int lvl)
{ return !modifiable_ ? LevelStarts_[StdLevel( lvl) + 1] : LevelViews_[StdLevel( lvl)]->end(); }
const_iterator level_begin (int lvl) const
{ return !modifiable_ ? const_LevelStarts_[StdLevel( lvl)] : LevelViews_[StdLevel( lvl)]->begin(); }
const_iterator level_end (int lvl) const
{ return !modifiable_ ? const_LevelStarts_[StdLevel( lvl) + 1] : LevelViews_[StdLevel( lvl)]->end(); }
// Split Data_ into level-wise lists in LevelViews_ or merge LevelViews_ into Data_.
void PrepareModify();
void FinalizeModify();
void AppendLevel();
void RemoveLastLevel();
LevelCont& // Only usable, if modifiable_ == true
operator[] (int lvl) {
Assert( modifiable_, DROPSErrCL("GlobalListCL::operator[]: "
"Data not modifiable."), DebugContainerC );
return *LevelViews_[StdLevel( lvl)];
}
};
template <class T>
void // Split Data_ into level-wise lists in LevelViews_.
GlobalListCL<T>::PrepareModify()
{
Assert( !modifiable_, DROPSErrCL("GlobalListCL::PrepareModify:"
"Data is already modifiable."), DebugContainerC );
Assert( LevelViews_.empty(), DROPSErrCL("GlobalListCL::PrepareModify:"
"Inconsistent LevelViews_."), DebugContainerC );
LevelViews_.resize( GetNumLevel());
for (Uint lvl= 0, numlvl= GetNumLevel(); lvl < numlvl; ++lvl) {
LevelViews_[lvl]= new LevelCont();
LevelViews_[lvl]->splice( LevelViews_[lvl]->end(), Data_,
level_begin( lvl), level_begin( lvl+1));
}
LevelStarts_.clear();
const_LevelStarts_.clear();
Assert( Data_.empty(), DROPSErrCL("GlobalListCL::PrepareModify: "
"Did not move all Data."), DebugContainerC );
modifiable_= true;
}
template <class T>
void // Merge LevelViews_ into Data_.
GlobalListCL<T>::FinalizeModify()
{
Assert( modifiable_,
DROPSErrCL("GlobalListCL::FinalizeModify: Data is not modifiable."),
DebugContainerC );
Assert( LevelStarts_.empty(),
DROPSErrCL("GlobalListCL::FinalizeModify: Inconsistent LevelStarts_."),
DebugContainerC );
Assert( Data_.empty(), DROPSErrCL("GlobalListCL::FinalizeModify:"
"Inconsistent Data_."), DebugContainerC );
modifiable_= false;
if (LevelViews_.empty()) return;
LevelStarts_.resize( LevelViews_.size() + 1);
LevelStarts_[LevelViews_.size()]= Data_.end();
const_LevelStarts_.resize( LevelViews_.size() + 1);
const_LevelStarts_[LevelViews_.size()]= Data_.end();
for (Uint lvl= LevelViews_.size(); lvl > 0; --lvl) {
Data_.splice( Data_.begin(), *LevelViews_[lvl-1]);
LevelStarts_[lvl-1]= Data_.begin();
const_LevelStarts_[lvl-1]= Data_.begin();
Assert( LevelViews_[lvl-1]->empty(),
DROPSErrCL("GlobalListCL::FinalizeModify: Did not move all Data."),
DebugContainerC );
delete LevelViews_[lvl-1];
}
LevelViews_.clear();
}
template <class T>
void
GlobalListCL<T>::AppendLevel()
{
Assert( modifiable_, DROPSErrCL("GlobalListCL::AppendLevel: "
"Data not modifiable."), DebugContainerC );
LevelViews_.push_back( new LevelCont());
}
template <class T>
void
GlobalListCL<T>::RemoveLastLevel()
{
Assert( modifiable_, DROPSErrCL("GlobalListCL::RemoveLast: "
"Data not modifiable."), DebugContainerC );
Assert( LevelViews_.size() > 0, DROPSErrCL("GlobalListCL: RemoveLastLevel: "
"There are no levels to be removed."), DebugContainerC);
Assert( LevelViews_.back()->empty(), DROPSErrCL("GlobalListCL: RemoveLastLevel: "
"Last level not empty"), DebugContainerC);
delete LevelViews_.back();
LevelViews_.pop_back();
}
//**************************************************************************
// Class: MLDataCL *
//**************************************************************************
template <class T>
class MLDataCL : public std::list<T>
{
public:
explicit MLDataCL ()
: std::list<T>() {}
explicit MLDataCL (size_t n, const T& val= T())
: std::list<T>( n, val) {}
T& GetFinest() { return this->back(); }
T& GetCoarsest() { return this->front(); }
T* GetFinestPtr() { return &this->back(); }
T* GetCoarsestPtr() { return &this->front(); }
const T& GetFinest() const { return this->back(); }
const T& GetCoarsest() const { return this->front(); }
const T* GetFinestPtr() const { return &this->back(); }
const T* GetCoarsestPtr() const { return &this->front(); }
typename MLDataCL::iterator GetFinestIter() { return --this->end(); }
typename MLDataCL::const_iterator GetFinestIter() const { return --this->end(); }
typename MLDataCL::iterator GetCoarsestIter() { return this->begin(); }
typename MLDataCL::const_iterator GetCoarsestIter() const { return this->begin(); }
};
///\brief Designates the part of the domain, usually on tetras at the interface, one is interested in.
enum TetraSignEnum { AllTetraC, NegTetraC, PosTetraC };
} // end of namespace DROPS
#endif
| athrpf/drops | misc/container.h | C | gpl-3.0 | 38,510 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>The transformDistance purpose</title>
</head>
<body><div class="manualnavbar" style="text-align: center;">
<div class="prev" style="text-align: left; float: left;"><a href="cairomatrix.scale.html">CairoMatrix::scale</a></div>
<div class="next" style="text-align: right; float: right;"><a href="cairomatrix.transformpoint.html">CairoMatrix::transformPoint</a></div>
<div class="up"><a href="class.cairomatrix.html">CairoMatrix</a></div>
<div class="home"><a href="index.html">PHP Manual</a></div>
</div><hr /><div id="cairomatrix.transformdistance" class="refentry">
<div class="refnamediv">
<h1 class="refname">CairoMatrix::transformDistance</h1>
<p class="verinfo">(PECL cairo >= 0.1.0)</p><p class="refpurpose"><span class="refname">CairoMatrix::transformDistance</span> — <span class="dc-title">The transformDistance purpose</span></p>
</div>
<div class="refsect1 description" id="refsect1-cairomatrix.transformdistance-description">
<h3 class="title">Description</h3>
<div class="methodsynopsis dc-description">
<span class="modifier">public</span> <span class="type">array</span> <span class="methodname"><strong>CairoMatrix::transformDistance</strong></span>
( <span class="methodparam"><span class="type">string</span> <code class="parameter">$dx</code></span>
, <span class="methodparam"><span class="type">string</span> <code class="parameter">$dy</code></span>
)</div>
<p class="para rdfs-comment">
The method description goes here.
</p>
<div class="warning"><strong class="warning">Warning</strong><p class="simpara">This function is
currently not documented; only its argument list is available.
</p></div>
</div>
<div class="refsect1 parameters" id="refsect1-cairomatrix.transformdistance-parameters">
<h3 class="title">Parameters</h3>
<p class="para">
<dl>
<dt>
<code class="parameter">dx</code></dt>
<dd>
<p class="para">
Description...
</p>
</dd>
<dt>
<code class="parameter">dy</code></dt>
<dd>
<p class="para">
Description...
</p>
</dd>
</dl>
</p>
</div>
<div class="refsect1 returnvalues" id="refsect1-cairomatrix.transformdistance-returnvalues">
<h3 class="title">Return Values</h3>
<p class="para">
Description...
</p>
</div>
<div class="refsect1 examples" id="refsect1-cairomatrix.transformdistance-examples">
<h3 class="title">Examples</h3>
<p class="para">
<div class="example" id="example-3249">
<p><strong>Example #1 <span class="methodname"><strong>CairoMatrix::transformDistance()</strong></span> example</strong></p>
<div class="example-contents">
<div class="phpcode"><code><span style="color: #000000">
<span style="color: #0000BB"><?php<br /></span><span style="color: #FF8000">/* ... */<br /></span><span style="color: #0000BB">?></span>
</span>
</code></div>
</div>
<div class="example-contents"><p>The above example will output
something similar to:</p></div>
<div class="example-contents screen">
<div class="cdata"><pre>
...
</pre></div>
</div>
</div>
</p>
</div>
<div class="refsect1 seealso" id="refsect1-cairomatrix.transformdistance-seealso">
<h3 class="title">See Also</h3>
<p class="para">
<ul class="simplelist">
<li class="member"><span class="methodname"><strong>Classname::Method()</strong></span></li>
</ul>
</p>
</div>
</div><hr /><div class="manualnavbar" style="text-align: center;">
<div class="prev" style="text-align: left; float: left;"><a href="cairomatrix.scale.html">CairoMatrix::scale</a></div>
<div class="next" style="text-align: right; float: right;"><a href="cairomatrix.transformpoint.html">CairoMatrix::transformPoint</a></div>
<div class="up"><a href="class.cairomatrix.html">CairoMatrix</a></div>
<div class="home"><a href="index.html">PHP Manual</a></div>
</div></body></html>
| P3PO/the-phpjs-local-docs-collection | php/5.5/cairomatrix.transformdistance.html | HTML | gpl-3.0 | 4,105 |
// Copyright CERN and copyright holders of ALICE O2. This software is
// distributed under the terms of the GNU General Public License v3 (GPL
// Version 3), copied verbatim in the file "COPYING".
//
// See http://alice-o2.web.cern.ch/license for full licensing information.
//
// In applying this license CERN does not waive the privileges and immunities
// granted to it by virtue of its status as an Intergovernmental Organization
// or submit itself to any jurisdiction.
/********************************************************************************
* Copyright (C) 2014 GSI Helmholtzzentrum fuer Schwerionenforschung GmbH *
* *
* This software is distributed under the terms of the *
* GNU Lesser General Public Licence version 3 (LGPL) version 3, *
* copied verbatim in the file "LICENSE" *
********************************************************************************/
#ifdef __CLING__
#pragma link off all globals;
#pragma link off all classes;
#pragma link off all functions;
#pragma link C++ class o2::parameters::GRPObject + ;
#endif
| AllaMaevskaya/AliceO2 | DataFormats/Parameters/src/ParametersDataLinkDef.h | C | gpl-3.0 | 1,224 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Configuration;
using System.Security.Cryptography;
using System.Xml;
using Nesoft.Utility.DataAccess.Database.Config;
using Nesoft.Utility.DataAccess.Database;
using System.Data;
namespace Nesoft.Utility.DataAccess.RealTime
{
internal static class ConfigHelper
{
private static XmlNode[] GetChildrenNodes(XmlNode node, string nodeName)
{
return GetChildrenNodes(node, delegate(XmlNode child)
{
return child.Name == nodeName;
});
}
private static XmlNode[] GetChildrenNodes(XmlNode node, Predicate<XmlNode> match)
{
if (node == null || node.ChildNodes == null || node.ChildNodes.Count <= 0)
{
return new XmlNode[0];
}
List<XmlNode> nodeList = new List<XmlNode>(node.ChildNodes.Count);
foreach (XmlNode child in node.ChildNodes)
{
if (match(child))
{
nodeList.Add(child);
}
}
return nodeList.ToArray();
}
private static string GetNodeAttribute(XmlNode node, string attributeName)
{
if (node.Attributes == null
|| node.Attributes[attributeName] == null
|| node.Attributes[attributeName].Value == null
|| node.Attributes[attributeName].Value.Trim() == string.Empty)
{
return string.Empty;
}
return node.Attributes[attributeName].Value.Trim();
}
private static string GetConfigPath()
{
string path = ConfigurationManager.AppSettings["RealTimeConfigFilePath"];
if (path == null || path.Trim().Length <= 0)
{
return Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "Configuration/RealTime.config");
}
string p = Path.GetPathRoot(path);
if (p == null || p.Trim().Length <= 0) // 说明是相对路径
{
path = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, path);
}
return path;
}
//internal static List<RealTimeExtensionConfig> GetExtensionConfig()
//{
// List<RealTimeExtensionConfig> list = new List<RealTimeExtensionConfig>();
// string path = GetConfigPath();
// if (!File.Exists(path))
// {
// return list;
// }
// XmlDocument x = new XmlDocument();
// x.Load(path);
// XmlNode node = x.SelectSingleNode(@"//extensions");
// if (node == null || node.ChildNodes == null || node.ChildNodes.Count <= 0)
// {
// return list;
// }
// XmlNode[] eventList = GetChildrenNodes(node, "data");
// foreach (XmlNode ev in eventList)
// {
// string name = GetNodeAttribute(ev, "name");
// string dataType = GetNodeAttribute(ev, "type");
// string extensionType = GetNodeAttribute(ev, "extensionType");
// RealTimeExtensionConfig config = new RealTimeExtensionConfig();
// config.Name = name;
// config.DataType = dataType;
// config.ExtensionType = extensionType;
// list.Add(config);
// }
// return list;
//}
//internal static RealTimeExtensionConfig GetExtensionConfig(string dataName)
//{
// var list = GetExtensionConfig();
// if (list != null)
// {
// return list.FirstOrDefault(p => p.Name.Trim().ToUpper() == dataName.Trim().ToUpper());
// }
// return null;
//}
internal static List<RealTimeMethod> GetRealTimeConfig()
{
List<RealTimeMethod> list = new List<RealTimeMethod>();
string path = GetConfigPath();
if (!File.Exists(path))
{
return list;
}
XmlDocument x = new XmlDocument();
x.Load(path);
XmlNode node = x.SelectSingleNode(@"//realTime");
if (node == null || node.ChildNodes == null || node.ChildNodes.Count <= 0)
{
return list;
}
XmlNode[] eventList = GetChildrenNodes(node, "query");
foreach (XmlNode ev in eventList)
{
string dataType = GetNodeAttribute(ev, "dataType");
string queryName = GetNodeAttribute(ev, "name");
//string tableName = GetNodeAttribute(ev, "tableName");
//string primaryField = GetNodeAttribute(ev, "primaryField");
RealTimeMethod query = new RealTimeMethod
{
Name = queryName,
DataType = dataType,
//TableName = tableName,
//PrimaryField = primaryField,
FilterFields = new List<FilterField>(),
ReturnFields = new List<ReturnField>()
};
list.Add(query);
XmlNode filterFieldsNode = ev.SelectSingleNode("filterFields");
XmlNode[] filterFields = GetChildrenNodes(filterFieldsNode,"field");
foreach (XmlNode no in filterFields)
{
string name = GetNodeAttribute(no, "name");
string valuePath = GetNodeAttribute(no, "valuePath");
string relationType = GetNodeAttribute(no, "relationType");
string operatorType = GetNodeAttribute(no, "operatorType");
string dbType = GetNodeAttribute(no, "dbType");
FilterField filed = new FilterField
{
Name = name,
ValuePath = valuePath,
OperatorType = operatorType,
RelationType = relationType,
DBType = dbType
};
query.FilterFields.Add(filed);
}
XmlNode returnFieldsNode = ev.SelectSingleNode("returnFields");
XmlNode[] returnFields = GetChildrenNodes(returnFieldsNode, "field");
foreach (XmlNode no in returnFields)
{
string name = GetNodeAttribute(no, "name");
string valuePath = GetNodeAttribute(no, "valuePath");
string dbType = GetNodeAttribute(no, "dbType");
ReturnField filed = new ReturnField
{
Name = name,
ValuePath = valuePath,
DBType = dbType
};
query.ReturnFields.Add(filed);
}
}
return list;
}
internal static RealTimeMethod GetRealTimeConfig(string name)
{
var list = GetRealTimeConfig();
if (list != null)
{
return list.FirstOrDefault(p => p.Name.Trim().ToUpper() == name.Trim().ToUpper());
}
return null;
}
internal static IRealTimePersister GetDefaultPersiter()
{
return PersisteFactory.GetInstance();
}
}
public static class RealTimeHelper
{
private static string loadDataSql = @"
SELECT
#XmlFields#
FROM EcommerceRealtime.dbo.RealTimeData r WITH(NOLOCK)
#StrWhere#
UNION ALL
#InputSql#";
private static string loadPagingDataSql = @"
SELECT @TotalCount = COUNT(1)
FROM (
SELECT
#XmlFields#
FROM EcommerceRealtime.dbo.RealTimeData r WITH(NOLOCK)
#StrWhere#
UNION ALL
#InputSql#
) result
SELECT
#Columns#
FROM(
SELECT TOP (@EndNumber)
ROW_NUMBER() OVER(ORDER BY #SortColumnName#) AS RowNumber,
#Columns#
FROM
(
SELECT
#XmlFields#
FROM EcommerceRealtime.dbo.RealTimeData r WITH(NOLOCK)
#StrWhere#
UNION ALL
#InputSql#
) unionResult ) result
WHERE RowNumber > @StartNumber
";
// private static string excludeDataSql = @"NOT EXISTS(
// SELECT TOP 1 1
// FROM #TableName# t WITH(NOLOCK)
// WHERE r.Key = t.#PrimaryKey#)";
/// <summary>
/// 获取属性数据类型
/// </summary>
/// <param name="pro"></param>
/// <param name="property"></param>
/// <param name="propertyNameIgnoreCase"></param>
/// <param name="skipNotExistProperty"></param>
/// <returns></returns>
//private static Type GetPropertyType(object pro, string property, bool propertyNameIgnoreCase, bool skipNotExistProperty)
//{
// Type type = null;
// string[] pNames = property.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
// //object val = DataMapper.ConvertIfEnum(reader[i], typeof(T), pNames, propertyNameIgnoreCase, skipNotExistProperty);
// int index = 0;
// foreach (string propertyName in pNames)
// {
// if (!Invoker.ExistPropertySet(pro.GetType(), propertyName, propertyNameIgnoreCase))
// {
// if (!skipNotExistProperty)
// {
// throw new ApplicationException("There is no public instance property that can be set '" + propertyName + "' in type '" + pro.GetType().FullName + "'");
// }
// break;
// }
// // 根据property的值(不区分大小写)找到在pro对象的类型中的属性的名称
// string realName = Invoker.GetPropertyNameIgnoreCase(pro.GetType(), propertyName);
// if (realName == null || (realName != propertyName && !propertyNameIgnoreCase))
// // realName == null 说明pro对象的类型中不存在名为property变量值的属性
// // realName != propertyName 说明存在属性,但属性名与输入的值的大小写不一致
// {
// if (!skipNotExistProperty)
// {
// throw new ApplicationException("There is no public instance property that can be set '" + propertyName + "' in type '" + pro.GetType().FullName + "'");
// }
// break;
// }
// if (index == pNames.Length - 1)
// {
// type = Invoker.GetPropertyType(pro.GetType(), realName);
// }
// else
// {
// object tmp = null;
// if (Invoker.ExistPropertyGet(pro.GetType(), realName))
// {
// tmp = Invoker.PropertyGet(pro, realName);
// }
// if (tmp == null)
// {
// type = Invoker.GetPropertyType(pro.GetType(), realName, false, false);
// }
// pro = tmp;
// }
// index++;
// }
// return type;
//}
//private static string GetDBTypeStr(Type type)
//{
// if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
// {
// type = type.GetGenericArguments()[0];
// }
// TypeCode code = Type.GetTypeCode(type);
// switch (code)
// {
// case TypeCode.Boolean:
// return "bit";
// case TypeCode.Int16:
// return "smallint";
// case TypeCode.Int32:
// return "int";
// case TypeCode.Int64:
// return "bigint";
// case TypeCode.String:
// case TypeCode.Char:
// return "nvarchar(max)";
// case TypeCode.Decimal:
// return "decimal(19,6)";
// case TypeCode.Double:
// return "double(19,6)";
// case TypeCode.DateTime:
// return "datetime";
// default:
// return "nvarchar(max)";
// }
//}
//private static System.Data.DbType GetDbType(Type type)
//{
// if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
// {
// type = type.GetGenericArguments()[0];
// }
// TypeCode code = Type.GetTypeCode(type);
// switch (code)
// {
// case TypeCode.Boolean:
// return DbType.Boolean;
// case TypeCode.Int16:
// return DbType.Int16;
// case TypeCode.Int32:
// return DbType.Int32;
// case TypeCode.Int64:
// return DbType.Int64;
// case TypeCode.String:
// return DbType.String;
// case TypeCode.Char:
// return DbType.AnsiStringFixedLength;
// case TypeCode.Decimal:
// return DbType.Decimal;
// case TypeCode.Double:
// return DbType.Double;
// case TypeCode.DateTime:
// return DbType.DateTime;
// default:
// return DbType.String;
// }
//}
/// <summary>
/// 根据配置文件中的Sql数据类型获取DbType
/// </summary>
/// <param name="sqlTypeString"></param>
/// <returns></returns>
private static DbType GetDbType(string sqlTypeString)
{
sqlTypeString = sqlTypeString.Trim();
if (sqlTypeString.Contains("("))
{
sqlTypeString = sqlTypeString.Substring(0, sqlTypeString.IndexOf("("));
}
switch (sqlTypeString)
{
case "bigint":
return DbType.Int64;
case "binary":
return DbType.Binary;
case "bit":
return DbType.Boolean;
case "char":
return DbType.AnsiStringFixedLength;
case "date":
return DbType.Date;
case "datetime":
return DbType.DateTime;
case "datetime2":
return DbType.DateTime2;
case "datetimeoffset":
return DbType.DateTimeOffset;
case "decimal":
return DbType.Decimal;
case "filestream":
return DbType.Binary;
case "float":
return DbType.Double;
case "image":
return DbType.Binary;
case "int":
return DbType.Int32;
case "money":
return DbType.Decimal;
case "nchar":
return DbType.StringFixedLength;
case "ntext":
return DbType.String;
case "numeric":
return DbType.Decimal;
case "nvarchar":
return DbType.String;
case "real":
return DbType.Single;
case "rowversion":
return DbType.Binary;
case "smalldatetime":
return DbType.DateTime;
case "smallint":
return DbType.Int16;
case "smallmoney":
return DbType.Decimal;
case "sql_variant":
return DbType.Object;
case "text":
return DbType.String;
case "time":
return DbType.Time;
case "timestamp":
return DbType.Binary;
case "tinyint":
return DbType.Byte;
case "uniqueidentifier":
return DbType.Guid;
case "varbinary":
return DbType.Binary;
case "varchar":
return DbType.AnsiString;
case "xml":
return DbType.Xml;
default:
throw new ArgumentException("Invalid sql dbtype.");
}
}
private static T GetEnum<T>(string name) where T : struct
{
T result = default(T);
bool flag = Enum.TryParse<T>(name, out result);
if (flag)
{
return result;
}
throw new ArgumentException("Invalid value of enum {0}", typeof(T).Name);
}
private static void BuilCondition<Q>(Q filter, string dataType, List<FilterField> filterFields, DynamicQuerySqlBuilder sqlBuilder)
{
sqlBuilder.ConditionConstructor.AddCondition(QueryConditionRelationType.AND, "r.BusinessDataType", DbType.String, "@BusinessDataType", QueryConditionOperatorType.Equal, dataType);
List<string> changeTypes = new List<string>() { "A", "U" };
sqlBuilder.ConditionConstructor.AddInCondition(QueryConditionRelationType.AND, "r.ChangeType", DbType.String, changeTypes);
int index = 0;
filterFields.ForEach(p =>
{
object parameterValue = Invoker.PropertyGet(filter, p.Name);
string[] pNames = p.ValuePath.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
string path = string.Format("(//{0}/text())[1]", pNames.Join("/"));
DbType dbType = GetDbType(p.DBType);
string field = string.Format("r.BusinessData.value('{0}','{1}')", path, p.DBType);
QueryConditionOperatorType operatorType = GetEnum<QueryConditionOperatorType>(p.OperatorType);
QueryConditionRelationType relationType = GetEnum<QueryConditionRelationType>(p.RelationType);
sqlBuilder.ConditionConstructor.AddCondition(relationType,
field, dbType, "@Parameter" + index.ToString(), operatorType, parameterValue);
index++;
});
}
private static void BuildColumns(List<ReturnField> returnFields, out string xmlFields, out List<string> columns)
{
StringBuilder fields = new StringBuilder();
var cols = new List<string>();
returnFields.ForEach(p =>
{
cols.Add(string.Format("[{0}]", p.Name));
string[] pNames = p.ValuePath.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
string path = string.Format("(//{0}/text())[1]", pNames.Join("/"));
fields.AppendFormat("r.BusinessData.value('{0}','{1}') AS [{2}],", path, p.DBType, p.Name);
});
fields.Remove(fields.Length - 1, 1);
xmlFields = fields.ToString();
columns = cols;
}
public static void Persiste<T>(RealTimeData<T> data) where T : class
{
ConfigHelper.GetDefaultPersiter().Persiste<T>(data);
}
public static object LoadData(int key)
{
return null;
}
public static T LoadData<T>(int key) where T : class, new()
{
//查询RealTime表中的数据
return default(T);
}
/// <summary>
/// 查询数据不分页
/// </summary>
/// <typeparam name="Q"></typeparam>
/// <typeparam name="T"></typeparam>
/// <param name="command"></param>
/// <param name="filter"></param>
/// <returns></returns>
public static List<T> QueryData<Q, T>(CustomDataCommand command, Q filter, string configName) where T : class, new()
{
var config = ConfigHelper.GetRealTimeConfig(configName);
string xmlFields;
List<string> columns;
BuildColumns(config.ReturnFields, out xmlFields, out columns);
var cmd = DataCommandManager.CreateCustomDataCommandFromSql(loadDataSql, command.DatabaseAliasName);
using (DynamicQuerySqlBuilder sqlBuilder = new DynamicQuerySqlBuilder(cmd, "SysNo desc"))
{
BuilCondition<Q>(filter, config.DataType, config.FilterFields, sqlBuilder);
cmd.CommandText = sqlBuilder.BuildQuerySql();
cmd.CommandText = cmd.CommandText.Replace("#XmlFields#", xmlFields.ToString());
cmd.CommandText = cmd.CommandText.Replace("#InputSql#", command.CommandText);
var list = cmd.ExecuteEntityList<T>();
return list;
}
}
/// <summary>
/// 查询数据并分页
/// </summary>
/// <typeparam name="Q"></typeparam>
/// <typeparam name="T"></typeparam>
/// <param name="command"></param>
/// <param name="filter"></param>
/// <param name="needRealTime"></param>
/// <param name="pageIndex"></param>
/// <param name="pageSize"></param>
/// <param name="sortField"></param>
/// <param name="totalCount"></param>
/// <returns></returns>
public static List<T> QueryData<Q, T>(CustomDataCommand command, Q filter, string configName,
PagingInfoEntity pagingInfo, out int totalCount) where T : class, new()
{
pagingInfo.SortField = "[SOMaster.SOSysNo]";
if (string.IsNullOrEmpty(pagingInfo.SortField))
{
throw new ApplicationException("You must specified one sort field at least.");
}
var config = ConfigHelper.GetRealTimeConfig(configName);
string xmlFields;
List<string> columns;
BuildColumns(config.ReturnFields, out xmlFields, out columns);
var cmd = DataCommandManager.CreateCustomDataCommandFromSql(loadPagingDataSql, command.DatabaseAliasName);
using (DynamicQuerySqlBuilder sqlBuilder = new DynamicQuerySqlBuilder(cmd, pagingInfo, pagingInfo.SortField))
{
BuilCondition<Q>(filter, config.DataType, config.FilterFields, sqlBuilder);
cmd.CommandText = sqlBuilder.BuildQuerySql();
//把传入的参数添加到组合后的DataCommand中
//command.DbParameterList.ForEach(p =>
//{
// var param = cmd.DbParameterList.FirstOrDefault(k => k.ParameterName.Trim().ToUpper() == p.ParameterName.Trim().ToUpper());
// if (param == null)
// {
// cmd.AddInputParameter(p.ParameterName, p.DbType, p.Value);
// }
//});
cmd.CommandText = cmd.CommandText.Replace("#Columns#", columns.Join(","));
cmd.CommandText = cmd.CommandText.Replace("#XmlFields#", xmlFields.ToString());
cmd.CommandText = cmd.CommandText.Replace("#InputSql#", command.CommandText);
var list = cmd.ExecuteEntityList<T>();
totalCount = Convert.ToInt32(cmd.GetParameterValue("@TotalCount"));
return list;
}
}
}
} | ZeroOne71/ql | 03_SellerPortal/ECommerce.Utility.DataAccess/RealTime/RealTimeHelper.cs | C# | gpl-3.0 | 24,097 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="robots" content="index, follow, all" />
<title>Symfony\Bridge\Doctrine\Form\ChoiceList\EntityChoiceList | </title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css">
</head>
<body id="class">
<div class="header">
<ul>
<li><a href="../../../../../classes.html">Classes</a></li>
<li><a href="../../../../../namespaces.html">Namespaces</a></li>
<li><a href="../../../../../interfaces.html">Interfaces</a></li>
<li><a href="../../../../../traits.html">Traits</a></li>
<li><a href="../../../../../doc-index.html">Index</a></li>
</ul>
<div id="title"></div>
<div class="type">Class</div>
<h1><a href="../ChoiceList.html">Symfony\Bridge\Doctrine\Form\ChoiceList</a>\EntityChoiceList</h1>
</div>
<div class="content">
<p> class
<strong>EntityChoiceList</strong> extends <a href="../../../../Component/Form/Extension/Core/ChoiceList/ObjectChoiceList.html"><abbr title="Symfony\Component\Form\Extension\Core\ChoiceList\ObjectChoiceList">ObjectChoiceList</abbr></a></p>
<div class="description">
<p>A choice list presenting a list of Doctrine entities as choices</p>
<p>
</p>
</div>
<h2>Methods</h2>
<table>
<tr>
<td class="type">
</td>
<td class="last">
<a href="EntityChoiceList.html#method___construct">__construct</a>(<abbr title="Doctrine\Common\Persistence\ObjectManager">ObjectManager</abbr> $manager, string $class, string $labelPath = null, <a href="EntityLoaderInterface.html"><abbr title="Symfony\Bridge\Doctrine\Form\ChoiceList\EntityLoaderInterface">EntityLoaderInterface</abbr></a> $entityLoader = null, array|<a href="http://php.net/Traversable"><abbr title="Traversable">Traversable</abbr></a>|null $entities = null, array $preferredEntities = array(), string $groupPath = null, <a href="../../../../Component/PropertyAccess/PropertyAccessorInterface.html"><abbr title="Symfony\Component\PropertyAccess\PropertyAccessorInterface">PropertyAccessorInterface</abbr></a> $propertyAccessor = null)
<p>Creates a new entity choice list.</p>
</td>
<td></td>
</tr>
<tr>
<td class="type">
array
</td>
<td class="last">
<a href="EntityChoiceList.html#method_getChoices">getChoices</a>()
<p>Returns the list of entities</p>
</td>
<td></td>
</tr>
<tr>
<td class="type">
array
</td>
<td class="last">
<a href="EntityChoiceList.html#method_getValues">getValues</a>()
<p>Returns the values for the entities</p>
</td>
<td></td>
</tr>
<tr>
<td class="type">
array
</td>
<td class="last">
<a href="EntityChoiceList.html#method_getPreferredViews">getPreferredViews</a>()
<p>Returns the choice views of the preferred choices as nested array with the choice groups as top-level keys.</p>
</td>
<td></td>
</tr>
<tr>
<td class="type">
array
</td>
<td class="last">
<a href="EntityChoiceList.html#method_getRemainingViews">getRemainingViews</a>()
<p>Returns the choice views of the choices that are not preferred as nested array with the choice groups as top-level keys.</p>
</td>
<td></td>
</tr>
<tr>
<td class="type">
array
</td>
<td class="last">
<a href="EntityChoiceList.html#method_getChoicesForValues">getChoicesForValues</a>(array $values)
<p>Returns the entities corresponding to the given values.</p>
</td>
<td></td>
</tr>
<tr>
<td class="type">
array
</td>
<td class="last">
<a href="EntityChoiceList.html#method_getValuesForChoices">getValuesForChoices</a>(array $entities)
<p>Returns the values corresponding to the given entities.</p>
</td>
<td></td>
</tr>
<tr>
<td class="type">
array
</td>
<td class="last">
<a href="EntityChoiceList.html#method_getIndicesForChoices">getIndicesForChoices</a>(array $entities)
<p>Returns the indices corresponding to the given entities.</p>
</td>
<td></td>
</tr>
<tr>
<td class="type">
array
</td>
<td class="last">
<a href="EntityChoiceList.html#method_getIndicesForValues">getIndicesForValues</a>(array $values)
<p>Returns the entities corresponding to the given values.</p>
</td>
<td></td>
</tr>
</table>
<h2>Details</h2>
<h3 id="method___construct">
<div class="location">at line 101</div>
<code> public
<strong>__construct</strong>(<abbr title="Doctrine\Common\Persistence\ObjectManager">ObjectManager</abbr> $manager, string $class, string $labelPath = null, <a href="EntityLoaderInterface.html"><abbr title="Symfony\Bridge\Doctrine\Form\ChoiceList\EntityLoaderInterface">EntityLoaderInterface</abbr></a> $entityLoader = null, array|<a href="http://php.net/Traversable"><abbr title="Traversable">Traversable</abbr></a>|null $entities = null, array $preferredEntities = array(), string $groupPath = null, <a href="../../../../Component/PropertyAccess/PropertyAccessorInterface.html"><abbr title="Symfony\Component\PropertyAccess\PropertyAccessorInterface">PropertyAccessorInterface</abbr></a> $propertyAccessor = null)</code>
</h3>
<div class="details">
<p>Creates a new entity choice list.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td><abbr title="Doctrine\Common\Persistence\ObjectManager">ObjectManager</abbr></td>
<td>$manager</td>
<td>An EntityManager instance</td>
</tr>
<tr>
<td>string</td>
<td>$class</td>
<td>The class name</td>
</tr>
<tr>
<td>string</td>
<td>$labelPath</td>
<td>The property path used for the label</td>
</tr>
<tr>
<td><a href="EntityLoaderInterface.html"><abbr title="Symfony\Bridge\Doctrine\Form\ChoiceList\EntityLoaderInterface">EntityLoaderInterface</abbr></a></td>
<td>$entityLoader</td>
<td>An optional query builder</td>
</tr>
<tr>
<td>array|<a href="http://php.net/Traversable"><abbr title="Traversable">Traversable</abbr></a>|null</td>
<td>$entities</td>
<td>An array of choices or null to lazy load</td>
</tr>
<tr>
<td>array</td>
<td>$preferredEntities</td>
<td>An array of preferred choices</td>
</tr>
<tr>
<td>string</td>
<td>$groupPath</td>
<td>A property path pointing to the property used to group the choices. Only allowed if the choices are given as flat array.</td>
</tr>
<tr>
<td><a href="../../../../Component/PropertyAccess/PropertyAccessorInterface.html"><abbr title="Symfony\Component\PropertyAccess\PropertyAccessorInterface">PropertyAccessorInterface</abbr></a></td>
<td>$propertyAccessor</td>
<td>The reflection graph for reading property paths.</td>
</tr>
</table>
</div>
</div>
<h3 id="method_getChoices">
<div class="location">at line 137</div>
<code> public array
<strong>getChoices</strong>()</code>
</h3>
<div class="details">
<p>Returns the list of entities</p>
<p>
</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td>array</td>
<td>The choices with their indices as keys</td>
</tr>
</table>
<h4>See also</h4>
<table>
<tr>
<td>Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface</td>
<td></td>
</tr>
</table>
</div>
</div>
<h3 id="method_getValues">
<div class="location">at line 153</div>
<code> public array
<strong>getValues</strong>()</code>
</h3>
<div class="details">
<p>Returns the values for the entities</p>
<p>
</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td>array</td>
<td>The values with the corresponding choice indices as keys</td>
</tr>
</table>
<h4>See also</h4>
<table>
<tr>
<td>Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface</td>
<td></td>
</tr>
</table>
</div>
</div>
<h3 id="method_getPreferredViews">
<div class="location">at line 170</div>
<code> public array
<strong>getPreferredViews</strong>()</code>
</h3>
<div class="details">
<p>Returns the choice views of the preferred choices as nested array with the choice groups as top-level keys.</p>
<p>
</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td>array</td>
<td>A nested array containing the views with the corresponding choice indices as keys on the lowest levels and the choice group names in the keys of the higher levels</td>
</tr>
</table>
<h4>See also</h4>
<table>
<tr>
<td>Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface</td>
<td></td>
</tr>
</table>
</div>
</div>
<h3 id="method_getRemainingViews">
<div class="location">at line 187</div>
<code> public array
<strong>getRemainingViews</strong>()</code>
</h3>
<div class="details">
<p>Returns the choice views of the choices that are not preferred as nested array with the choice groups as top-level keys.</p>
<p>
</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td>array</td>
<td>A nested array containing the views with the corresponding choice indices as keys on the lowest levels and the choice group names in the keys of the higher levels</td>
</tr>
</table>
<h4>See also</h4>
<table>
<tr>
<td>Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface</td>
<td></td>
</tr>
</table>
</div>
</div>
<h3 id="method_getChoicesForValues">
<div class="location">at line 205</div>
<code> public array
<strong>getChoicesForValues</strong>(array $values)</code>
</h3>
<div class="details">
<p>Returns the entities corresponding to the given values.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>array</td>
<td>$values</td>
<td>An array of choice values. Not existing values in this array are ignored</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>array</td>
<td>An array of choices with ascending, 0-based numeric keys</td>
</tr>
</table>
<h4>See also</h4>
<table>
<tr>
<td>Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface</td>
<td></td>
</tr>
</table>
</div>
</div>
<h3 id="method_getValuesForChoices">
<div class="location">at line 258</div>
<code> public array
<strong>getValuesForChoices</strong>(array $entities)</code>
</h3>
<div class="details">
<p>Returns the values corresponding to the given entities.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>array</td>
<td>$entities</td>
<td>
</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>array</td>
<td>An array of choice values with ascending, 0-based numeric keys</td>
</tr>
</table>
<h4>See also</h4>
<table>
<tr>
<td>Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface</td>
<td></td>
</tr>
</table>
</div>
</div>
<h3 id="method_getIndicesForChoices">
<div class="location">at line 300</div>
<code> public array
<strong>getIndicesForChoices</strong>(array $entities)</code>
</h3>
<div class="details">
<p>Returns the indices corresponding to the given entities.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>array</td>
<td>$entities</td>
<td>
</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>array</td>
<td>An array of indices with ascending, 0-based numeric keys</td>
</tr>
</table>
<h4>See also</h4>
<table>
<tr>
<td>Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface</td>
<td></td>
</tr>
</table>
</div>
</div>
<h3 id="method_getIndicesForValues">
<div class="location">at line 342</div>
<code> public array
<strong>getIndicesForValues</strong>(array $values)</code>
</h3>
<div class="details">
<p>Returns the entities corresponding to the given values.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>array</td>
<td>$values</td>
<td>An array of choice values. Not existing values in this array are ignored</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>array</td>
<td>An array of indices with ascending, 0-based numeric keys</td>
</tr>
</table>
<h4>See also</h4>
<table>
<tr>
<td>Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div id="footer">
Generated by <a href="http://sami.sensiolabs.org/" target="_top">Sami, the API Documentation Generator</a>.
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-89393-6']);
_gaq.push(['_setDomainName', '.symfony.com']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</body>
</html>
| rafaelgou/the-phpjs-local-docs-collection | symfony2/api/2.5/Symfony/Bridge/Doctrine/Form/ChoiceList/EntityChoiceList.html | HTML | gpl-3.0 | 18,471 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!--Converted with LaTeX2HTML 2008 (1.71)
original version by: Nikos Drakos, CBLU, University of Leeds
* revised and updated by: Marcus Hennecke, Ross Moore, Herb Swan
* with significant contributions from:
Jens Lippmann, Marek Rouchal, Martin Wilck and others -->
<HTML>
<HEAD>
<TITLE>Conclusion</TITLE>
<META NAME="description" CONTENT="Conclusion">
<META NAME="keywords" CONTENT="document">
<META NAME="resource-type" CONTENT="document">
<META NAME="distribution" CONTENT="global">
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf-8">
<META NAME="Generator" CONTENT="LaTeX2HTML v2008">
<META HTTP-EQUIV="Content-Style-Type" CONTENT="text/css">
<LINK REL="STYLESHEET" HREF="document.css">
<LINK REL="previous" HREF="node12.html">
<LINK REL="up" HREF="node2.html">
<LINK REL="next" HREF="node14.html">
</HEAD>
<BODY >
<DIV CLASS="navigation"><!--Navigation Panel-->
<A NAME="tex2html168"
HREF="node14.html">
<IMG WIDTH="37" HEIGHT="24" ALIGN="BOTTOM" BORDER="0" ALT="next"
SRC="/usr/share/latex2html/icons/next.png"></A>
<A NAME="tex2html166"
HREF="node2.html">
<IMG WIDTH="26" HEIGHT="24" ALIGN="BOTTOM" BORDER="0" ALT="up"
SRC="/usr/share/latex2html/icons/up.png"></A>
<A NAME="tex2html162"
HREF="node12.html">
<IMG WIDTH="63" HEIGHT="24" ALIGN="BOTTOM" BORDER="0" ALT="previous"
SRC="/usr/share/latex2html/icons/prev.png"></A>
<BR>
<B> Next:</B> <A NAME="tex2html169"
HREF="node14.html">ReqHunter</A>
<B> Up:</B> <A NAME="tex2html167"
HREF="node2.html">Review of the available</A>
<B> Previous:</B> <A NAME="tex2html163"
HREF="node12.html">REMA</A>
<BR>
<BR></DIV>
<!--End of Navigation Panel-->
<H2><A NAME="SECTION000211000000000000000">
Conclusion</A>
</H2>
<P>
<BR><HR>
<ADDRESS>
Nicolas James
2011-07-19
</ADDRESS>
</BODY>
</HTML>
| artebin/ReqHunter | documentation/html/node13.html | HTML | gpl-3.0 | 1,850 |
/**
* The MIT License
* Copyright (c) 2012 Graylog, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.graylog2.plugin;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.graylog2.plugin.streams.Stream;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class MessageTest {
private Message message;
private DateTime originalTimestamp;
@Before
public void setUp() {
originalTimestamp = Tools.iso8601();
message = new Message("foo", "bar", originalTimestamp);
}
@Test
public void testAddFieldDoesOnlyAcceptAlphanumericKeys() throws Exception {
Message m = new Message("foo", "bar", Tools.iso8601());
m.addField("some_thing", "bar");
assertEquals("bar", m.getField("some_thing"));
m = new Message("foo", "bar", Tools.iso8601());
m.addField("some-thing", "bar");
assertEquals("bar", m.getField("some-thing"));
m = new Message("foo", "bar", Tools.iso8601());
m.addField("somethin$g", "bar");
assertNull(m.getField("somethin$g"));
m = new Message("foo", "bar", Tools.iso8601());
m.addField("someäthing", "bar");
assertNull(m.getField("someäthing"));
}
@Test
public void testAddFieldTrimsValue() throws Exception {
Message m = new Message("foo", "bar", Tools.iso8601());
m.addField("something", " bar ");
assertEquals("bar", m.getField("something"));
m.addField("something2", " bar");
assertEquals("bar", m.getField("something2"));
m.addField("something3", "bar ");
assertEquals("bar", m.getField("something3"));
}
@Test
public void testAddFieldWorksWithIntegers() throws Exception {
Message m = new Message("foo", "bar", Tools.iso8601());
m.addField("something", 3);
assertEquals(3, m.getField("something"));
}
@Test
public void testAddFields() throws Exception {
final Map<String, Object> map = Maps.newHashMap();
map.put("field1", "Foo");
map.put("field2", 1);
message.addFields(map);
assertEquals("Foo", message.getField("field1"));
assertEquals(1, message.getField("field2"));
}
@Test
public void testAddStringFields() throws Exception {
final Map<String, String> map = Maps.newHashMap();
map.put("field1", "Foo");
map.put("field2", "Bar");
message.addStringFields(map);
assertEquals("Foo", message.getField("field1"));
assertEquals("Bar", message.getField("field2"));
}
@Test
public void testAddLongFields() throws Exception {
final Map<String, Long> map = Maps.newHashMap();
map.put("field1", 10L);
map.put("field2", 230L);
message.addLongFields(map);
assertEquals(10L, message.getField("field1"));
assertEquals(230L, message.getField("field2"));
}
@Test
public void testAddDoubleFields() throws Exception {
final Map<String, Double> map = Maps.newHashMap();
map.put("field1", 10.0d);
map.put("field2", 230.2d);
message.addDoubleFields(map);
assertEquals(10.0d, message.getField("field1"));
assertEquals(230.2d, message.getField("field2"));
}
@Test
public void testRemoveField() throws Exception {
message.addField("foo", "bar");
message.removeField("foo");
assertNull(message.getField("foo"));
}
@Test
public void testRemoveFieldNotDeletingReservedFields() throws Exception {
message.removeField("message");
message.removeField("source");
message.removeField("timestamp");
assertNotNull(message.getField("message"));
assertNotNull(message.getField("source"));
assertNotNull(message.getField("timestamp"));
}
@Test
public void testGetFieldAs() throws Exception {
message.addField("fields", Lists.newArrayList("hello"));
assertEquals(Lists.newArrayList("hello"), message.getFieldAs(List.class, "fields"));
}
@Test(expected = ClassCastException.class)
public void testGetFieldAsWithIncompatibleCast() throws Exception {
message.addField("fields", Lists.newArrayList("hello"));
message.getFieldAs(Map.class, "fields");
}
@Test
public void testSetAndGetStreams() throws Exception {
final Stream stream1 = mock(Stream.class);
final Stream stream2 = mock(Stream.class);
message.setStreams(Lists.newArrayList(stream1, stream2));
assertEquals(Lists.newArrayList(stream1, stream2), message.getStreams());
}
@Test
public void testGetStreamIds() throws Exception {
message.addField("streams", Lists.newArrayList("stream-id"));
assertEquals(Lists.newArrayList("stream-id"), message.getStreamIds());
}
@Test
public void testGetAndSetFilterOut() throws Exception {
assertFalse(message.getFilterOut());
message.setFilterOut(true);
assertTrue(message.getFilterOut());
message.setFilterOut(false);
assertFalse(message.getFilterOut());
}
@Test
public void testGetId() throws Exception {
final Pattern pattern = Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}");
assertTrue(pattern.matcher(message.getId()).matches());
}
@Test
public void testGetTimestamp() {
try {
final DateTime timestamp = message.getTimestamp();
assertNotNull(timestamp);
assertEquals(originalTimestamp.getZone(), timestamp.getZone());
} catch (ClassCastException e) {
fail("timestamp wasn't a DateTime " + e.getMessage());
}
}
@Test
public void testTimestampAsDate() {
final DateTime dateTime = new DateTime(2015, 9, 8, 0, 0, DateTimeZone.UTC);
message.addField(Message.FIELD_TIMESTAMP,
dateTime.toDate());
final Map<String, Object> elasticSearchObject = message.toElasticSearchObject();
final Object esTimestampFormatted = elasticSearchObject.get(Message.FIELD_TIMESTAMP);
assertEquals("Setting message timestamp as java.util.Date results in correct format for elasticsearch",
Tools.buildElasticSearchTimeFormat(dateTime), esTimestampFormatted);
}
@Test
public void testGetMessage() throws Exception {
assertEquals("foo", message.getMessage());
}
@Test
public void testGetSource() throws Exception {
assertEquals("bar", message.getSource());
}
@Test
public void testValidKeys() throws Exception {
assertTrue(Message.validKey("foo123"));
assertTrue(Message.validKey("foo-bar123"));
assertTrue(Message.validKey("foo_bar123"));
assertTrue(Message.validKey("foo.bar123"));
assertTrue(Message.validKey("123"));
assertTrue(Message.validKey(""));
assertFalse(Message.validKey("foo bar"));
assertFalse(Message.validKey("foo+bar"));
assertFalse(Message.validKey("foo$bar"));
assertFalse(Message.validKey(" "));
}
@Test
public void testToElasticSearchObject() throws Exception {
message.addField("field1", "wat");
message.addField("field2", "that");
final Map<String, Object> object = message.toElasticSearchObject();
assertEquals("foo", object.get("message"));
assertEquals("bar", object.get("source"));
assertEquals("wat", object.get("field1"));
assertEquals("that", object.get("field2"));
assertEquals(Tools.buildElasticSearchTimeFormat((DateTime) message.getField("timestamp")), object.get("timestamp"));
assertEquals(Collections.EMPTY_LIST, object.get("streams"));
}
@Test
public void testToElasticSearchObjectWithoutDateTimeTimestamp() throws Exception {
message.addField("timestamp", "time!");
final Map<String, Object> object = message.toElasticSearchObject();
assertEquals("time!", object.get("timestamp"));
}
@Test
public void testToElasticSearchObjectWithStreams() throws Exception {
final Stream stream = mock(Stream.class);
when(stream.getId()).thenReturn("stream-id");
message.setStreams(Lists.newArrayList(stream));
final Map<String, Object> object = message.toElasticSearchObject();
assertEquals(Lists.newArrayList("stream-id"), object.get("streams"));
}
@Test
public void testIsComplete() throws Exception {
Message message = new Message("message", "source", Tools.iso8601());
assertTrue(message.isComplete());
message = new Message("message", "", Tools.iso8601());
assertTrue(message.isComplete());
message = new Message("message", null, Tools.iso8601());
assertTrue(message.isComplete());
message = new Message("", "source", Tools.iso8601());
assertFalse(message.isComplete());
message = new Message(null, "source", Tools.iso8601());
assertFalse(message.isComplete());
}
@Test
public void testGetValidationErrorsWithEmptyMessage() throws Exception {
final Message message = new Message("", "source", Tools.iso8601());
assertEquals("message is empty, ", message.getValidationErrors());
}
@Test
public void testGetValidationErrorsWithNullMessage() throws Exception {
final Message message = new Message(null, "source", Tools.iso8601());
assertEquals("message is missing, ", message.getValidationErrors());
}
@Test
public void testGetFields() throws Exception {
final Map<String, Object> fields = message.getFields();
assertEquals(message.getId(), fields.get("_id"));
assertEquals(message.getMessage(), fields.get("message"));
assertEquals(message.getSource(), fields.get("source"));
assertEquals(message.getField("timestamp"), fields.get("timestamp"));
}
@Test(expected = UnsupportedOperationException.class)
public void testGetFieldsReturnsImmutableMap() throws Exception {
final Map<String, Object> fields = message.getFields();
fields.put("foo", "bar");
}
@Test
public void testGetFieldNames() throws Exception {
assertTrue("Missing fields in set!", Sets.symmetricDifference(message.getFieldNames(), Sets.newHashSet("_id", "timestamp", "source", "message")).isEmpty());
message.addField("testfield", "testvalue");
assertTrue("Missing fields in set!", Sets.symmetricDifference(message.getFieldNames(), Sets.newHashSet("_id", "timestamp", "source", "message", "testfield")).isEmpty());
}
@Test(expected = UnsupportedOperationException.class)
public void testGetFieldNamesReturnsUnmodifiableSet() throws Exception {
final Set<String> fieldNames = message.getFieldNames();
fieldNames.remove("_id");
}
@Test
public void testHasField() throws Exception {
assertFalse(message.hasField("__foo__"));
message.addField("__foo__", "bar");
assertTrue(message.hasField("__foo__"));
}
}
| berkeleydave/graylog2-server | graylog2-plugin-interfaces/src/test/java/org/graylog2/plugin/MessageTest.java | Java | gpl-3.0 | 12,940 |
<?php
/**
* LICENSE: The MIT License (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* https://github.com/azure/azure-storage-php/LICENSE
*
* 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.
*
* PHP version 5
*
* @category Microsoft
* @package MicrosoftAzure\Storage\Table\Models
* @author Azure Storage PHP SDK <dmsh@microsoft.com>
* @copyright 2016 Microsoft Corporation
* @license https://github.com/azure/azure-storage-php/LICENSE
* @link https://github.com/azure/azure-storage-php
*/
namespace MicrosoftAzure\Storage\Table\Models;
use MicrosoftAzure\Storage\Common\Internal\Validate;
use MicrosoftAzure\Storage\Common\Internal\Resources;
use MicrosoftAzure\Storage\Common\Internal\Utilities;
/**
* Represents one batch operation
*
* @category Microsoft
* @package MicrosoftAzure\Storage\Table\Models
* @author Azure Storage PHP SDK <dmsh@microsoft.com>
* @copyright 2016 Microsoft Corporation
* @license https://github.com/azure/azure-storage-php/LICENSE
* @version Release: 0.10.1
* @link https://github.com/azure/azure-storage-php
*/
class BatchOperation
{
/**
* @var string
*/
private $_type;
/**
* @var array
*/
private $_params;
/**
* Sets operation type.
*
* @param string $type The operation type. Must be valid type.
*
* @return none
*/
public function setType($type)
{
Validate::isTrue(
BatchOperationType::isValid($type),
Resources::INVALID_BO_TYPE_MSG
);
$this->_type = $type;
}
/**
* Gets operation type.
*
* @return string
*/
public function getType()
{
return $this->_type;
}
/**
* Adds or sets parameter for the operation.
*
* @param string $name The param name. Must be valid name.
* @param mix $value The param value.
*
* @return none
*/
public function addParameter($name, $value)
{
Validate::isTrue(
BatchOperationParameterName::isValid($name),
Resources::INVALID_BO_PN_MSG
);
$this->_params[$name] = $value;
}
/**
* Gets parameter value and if the name doesn't exist, return null.
*
* @param string $name The parameter name.
*
* @return mix
*/
public function getParameter($name)
{
return Utilities::tryGetValue($this->_params, $name);
}
}
| segej87/ecomapper | DataEntry/server_side/ecomapper-backend/vendor/microsoft/azure-storage/src/Table/Models/BatchOperation.php | PHP | gpl-3.0 | 2,844 |
var
assert = require('assert'),
path = require('path'),
exec = require('child_process').exec,
tmp = require('../lib/tmp');
// make sure that we do not test spam the global tmp
tmp.TMP_DIR = './tmp';
function _spawnTestWithError(testFile, params, cb) {
_spawnTest(true, testFile, params, cb);
}
function _spawnTestWithoutError(testFile, params, cb) {
_spawnTest(false, testFile, params, cb);
}
function _spawnTest(passError, testFile, params, cb) {
var
node_path = process.argv[0],
command = [ node_path, path.join(__dirname, testFile) ].concat(params).join(' ');
exec(command, function _execDone(err, stdout, stderr) {
if (passError) {
if (err) {
return cb(err);
} else if (stderr.length > 0) {
return cb(stderr.toString());
}
}
return cb(null, stdout.toString());
});
}
function _testStat(stat, mode) {
assert.equal(stat.uid, process.getuid(), 'should have the same UID');
assert.equal(stat.gid, process.getgid(), 'should have the same GUID');
assert.equal(stat.mode, mode);
}
function _testPrefix(prefix) {
return function _testPrefixGenerated(err, name) {
assert.equal(path.basename(name).slice(0, prefix.length), prefix, 'should have the provided prefix');
};
}
function _testPrefixSync(prefix) {
return function _testPrefixGeneratedSync(result) {
if (result instanceof Error) {
throw result;
}
_testPrefix(prefix)(null, result.name, result.fd);
};
}
function _testPostfix(postfix) {
return function _testPostfixGenerated(err, name) {
assert.equal(name.slice(name.length - postfix.length, name.length), postfix, 'should have the provided postfix');
};
}
function _testPostfixSync(postfix) {
return function _testPostfixGeneratedSync(result) {
if (result instanceof Error) {
throw result;
}
_testPostfix(postfix)(null, result.name, result.fd);
};
}
function _testKeep(type, keep, cb) {
_spawnTestWithError('keep.js', [ type, keep ], cb);
}
function _testKeepSync(type, keep, cb) {
_spawnTestWithError('keep-sync.js', [ type, keep ], cb);
}
function _testGraceful(type, graceful, cb) {
_spawnTestWithoutError('graceful.js', [ type, graceful ], cb);
}
function _testGracefulSync(type, graceful, cb) {
_spawnTestWithoutError('graceful-sync.js', [ type, graceful ], cb);
}
function _assertName(err, name) {
assert.isString(name);
assert.isNotZero(name.length, 'an empty string is not a valid name');
}
function _assertNameSync(result) {
if (result instanceof Error) {
throw result;
}
var name = typeof(result) == 'string' ? result : result.name;
_assertName(null, name);
}
function _testName(expected){
return function _testNameGenerated(err, name) {
assert.equal(expected, name, 'should have the provided name');
};
}
function _testNameSync(expected){
return function _testNameGeneratedSync(result) {
if (result instanceof Error) {
throw result;
}
_testName(expected)(null, result.name, result.fd);
};
}
function _testUnsafeCleanup(unsafe, cb) {
_spawnTestWithoutError('unsafe.js', [ 'dir', unsafe ], cb);
}
function _testIssue62(cb) {
_spawnTestWithoutError('issue62.js', [], cb);
}
function _testUnsafeCleanupSync(unsafe, cb) {
_spawnTestWithoutError('unsafe-sync.js', [ 'dir', unsafe ], cb);
}
function _testIssue62Sync(cb) {
_spawnTestWithoutError('issue62-sync.js', [], cb);
}
module.exports.testStat = _testStat;
module.exports.testPrefix = _testPrefix;
module.exports.testPrefixSync = _testPrefixSync;
module.exports.testPostfix = _testPostfix;
module.exports.testPostfixSync = _testPostfixSync;
module.exports.testKeep = _testKeep;
module.exports.testKeepSync = _testKeepSync;
module.exports.testGraceful = _testGraceful;
module.exports.testGracefulSync = _testGracefulSync;
module.exports.assertName = _assertName;
module.exports.assertNameSync = _assertNameSync;
module.exports.testName = _testName;
module.exports.testNameSync = _testNameSync;
module.exports.testUnsafeCleanup = _testUnsafeCleanup;
module.exports.testIssue62 = _testIssue62;
module.exports.testUnsafeCleanupSync = _testUnsafeCleanupSync;
module.exports.testIssue62Sync = _testIssue62Sync;
| klhdy/im-indepartment | packORGAN/client/sealtalk-desktop-ent-src/node_modules/tmp/test/base.js | JavaScript | gpl-3.0 | 4,348 |
// Copyright Aaron Smith 2009
//
// This file is part of Gity.
//
// Gity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Gity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Gity. If not, see <http://www.gnu.org/licenses/>.
#import <Cocoa/Cocoa.h>
#import <GDKit/GDKit.h>
#import "GTBaseGitTask.h"
#import "GTGitCommitLoadInfo.h"
#import "GittyDocument.h"
#import "GTCallback.h"
#import "GTGitCommit.h"
@interface GTOpLoadHistory : GTBaseGitTask {
BOOL detatchedHead;
GTGitCommitLoadInfo * loadInfo;
//GTCallback * callback;
NSMutableArray * commits;
}
//- (id) initWithGD:(GittyDocument *) _gd andLoadInfo:(GTGitCommitLoadInfo *) _loadInfo andCallback:(GTCallback *) _callback;
- (id) initWithGD:(GittyDocument *) _gd andLoadInfo:(GTGitCommitLoadInfo *) _loadInfo;
//- (void) readSTDOUTC;
//- (void) readSTDOUTCPP;
@end
| gngrwzrd/gity | src/GTOpLoadHistory.h | C | gpl-3.0 | 1,296 |
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><head><!--
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
This file is generated from xml source: DO NOT EDIT
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
-->
<title>mod_negotiation - Apache HTTP Server</title>
<link href="../../style/css/manual.css" rel="stylesheet" media="all" type="text/css" title="Main stylesheet" />
<link href="../../style/css/manual-loose-100pc.css" rel="alternate stylesheet" media="all" type="text/css" title="No Sidebar - Default font size" />
<link href="../../style/css/manual-print.css" rel="stylesheet" media="print" type="text/css" /><link rel="stylesheet" type="text/css" href="../../style/css/prettify.css" />
<script src="../../style/scripts/prettify.js" type="text/javascript">
</script>
<link href="../../images/favicon.ico" rel="shortcut icon" /></head>
<body>
<div id="page-header">
<p class="menu"><a href="../mod/index.html">Modules</a> | <a href="../mod/directives.html">Directives</a> | <a href="http://wiki.apache.org/httpd/FAQ">FAQ</a> | <a href="../glossary.html">Glossary</a> | <a href="../sitemap.html">Sitemap</a></p>
<p class="apache">Apache HTTP Server Version 2.4</p>
<img alt="" src="../../images/feather.gif" /></div>
<div class="up"><a href="./index.html"><img title="<-" alt="<-" src="../../images/left.gif" /></a></div>
<div id="path">
<a href="http://www.apache.org/">Apache</a> > <a href="http://httpd.apache.org/">HTTP Server</a> > <a href="http://httpd.apache.org/docs/">Documentation</a> > <a href="../index.html">Version 2.4</a> > <a href="./index.html">Modules</a></div>
<div id="page-content">
<div id="preamble"><h1>Apache Module mod_negotiation</h1>
<div class="toplang">
<p><span>Available Languages: </span><a href="../../en/mod/mod_negotiation.html" title="English"> en </a> |
<a href="../../fr/mod/mod_negotiation.html" hreflang="fr" rel="alternate" title="Français"> fr </a> |
<a href="../../ja/mod/mod_negotiation.html" hreflang="ja" rel="alternate" title="Japanese"> ja </a></p>
</div>
<table class="module"><tr><th><a href="module-dict.html#Description">Description:</a></th><td>Provides for <a href="../content-negotiation.html">content negotiation</a></td></tr>
<tr><th><a href="module-dict.html#Status">Status:</a></th><td>Base</td></tr>
<tr><th><a href="module-dict.html#ModuleIdentifier">Module Identifier:</a></th><td>negotiation_module</td></tr>
<tr><th><a href="module-dict.html#SourceFile">Source File:</a></th><td>mod_negotiation.c</td></tr></table>
<h3>Summary</h3>
<p>Content negotiation, or more accurately content selection, is
the selection of the document that best matches the clients
capabilities, from one of several available documents. There
are two implementations of this.</p>
<ul>
<li>A type map (a file with the handler
<code>type-map</code>) which explicitly lists the files
containing the variants.</li>
<li>A Multiviews search (enabled by the <code>Multiviews</code>
<code class="directive"><a href="../mod/core.html#options">Options</a></code>), where the server does
an implicit filename pattern match, and choose from amongst the
results.</li>
</ul>
</div>
<div id="quickview"><h3 class="directives">Directives</h3>
<ul id="toc">
<li><img alt="" src="../../images/down.gif" /> <a href="#cachenegotiateddocs">CacheNegotiatedDocs</a></li>
<li><img alt="" src="../../images/down.gif" /> <a href="#forcelanguagepriority">ForceLanguagePriority</a></li>
<li><img alt="" src="../../images/down.gif" /> <a href="#languagepriority">LanguagePriority</a></li>
</ul>
<h3>Topics</h3>
<ul id="topics">
<li><img alt="" src="../../images/down.gif" /> <a href="#typemaps">Type maps</a></li>
<li><img alt="" src="../../images/down.gif" /> <a href="#multiviews">Multiviews</a></li>
</ul><h3>See also</h3>
<ul class="seealso">
<li><code class="directive"><a href="../mod/core.html#options">Options</a></code></li>
<li><code class="module"><a href="../mod/mod_mime.html">mod_mime</a></code></li>
<li><a href="../content-negotiation.html">Content
Negotiation</a></li>
<li><a href="../env.html">Environment Variables</a></li>
</ul><ul class="seealso"><li><a href="#comments_section">Comments</a></li></ul></div>
<div class="top"><a href="#page-header"><img alt="top" src="../../images/up.gif" /></a></div>
<div class="section">
<h2><a name="typemaps" id="typemaps">Type maps</a></h2>
<p>A type map has a format similar to RFC822 mail headers. It
contains document descriptions separated by blank lines, with
lines beginning with a hash character ('#') treated as
comments. A document description consists of several header
records; records may be continued on multiple lines if the
continuation lines start with spaces. The leading space will be
deleted and the lines concatenated. A header record consists of
a keyword name, which always ends in a colon, followed by a
value. Whitespace is allowed between the header name and value,
and between the tokens of value. The headers allowed are: </p>
<dl>
<dt><code>Content-Encoding:</code></dt>
<dd>The encoding of the file. Apache only recognizes
encodings that are defined by an <code class="directive"><a href="../mod/mod_mime.html#addencoding">AddEncoding</a></code> directive.
This normally includes the encodings <code>x-compress</code>
for compress'd files, and <code>x-gzip</code> for gzip'd
files. The <code>x-</code> prefix is ignored for encoding
comparisons.</dd>
<dt><code>Content-Language:</code></dt>
<dd>The language(s) of the variant, as an Internet standard
language tag (<a href="http://www.ietf.org/rfc/rfc1766.txt">RFC 1766</a>). An example is <code>en</code>,
meaning English. If the variant contains more than one
language, they are separated by a comma.</dd>
<dt><code>Content-Length:</code></dt>
<dd>The length of the file, in bytes. If this header is not
present, then the actual length of the file is used.</dd>
<dt><code>Content-Type:</code></dt>
<dd>
The <a class="glossarylink" href="../glossary.html#mime-type" title="see glossary">MIME media type</a> of
the document, with optional parameters. Parameters are
separated from the media type and from one another by a
semi-colon, with a syntax of <code>name=value</code>. Common
parameters include:
<dl>
<dt><code>level</code></dt>
<dd>an integer specifying the version of the media type.
For <code>text/html</code> this defaults to 2, otherwise
0.</dd>
<dt><code>qs</code></dt>
<dd>a floating-point number with a value in the range 0[.000]
to 1[.000], indicating the relative 'quality' of this variant
compared to the other available variants, independent of
the client's capabilities. For example, a jpeg file is
usually of higher source quality than an ascii file if it
is attempting to represent a photograph. However, if the
resource being represented is ascii art, then an ascii
file would have a higher source quality than a jpeg file.
All <code>qs</code> values are therefore specific to a given
resource.</dd>
</dl>
<div class="example"><h3>Example</h3><p><code>
Content-Type: image/jpeg; qs=0.8
</code></p></div>
</dd>
<dt><code>URI:</code></dt>
<dd>uri of the file containing the variant (of the given
media type, encoded with the given content encoding). These
are interpreted as URLs relative to the map file; they must
be on the same server, and they must refer to files to
which the client would be granted access if they were to be
requested directly.</dd>
<dt><code>Body:</code></dt>
<dd>The actual content of the resource may
be included in the type-map file using the Body header. This
header must contain a string that designates a delimiter for
the body content. Then all following lines in the type map
file will be considered part of the resource body until the
delimiter string is found.
<div class="example"><h3>Example:</h3><p><code>
Body:----xyz----<br />
<html><br />
<body><br />
<p>Content of the page.</p><br />
</body><br />
</html><br />
----xyz----
</code></p></div>
</dd>
</dl>
<p>Consider, for example, a resource called
<code>document.html</code> which is available in English, French,
and German. The files for each of these are called
<code>document.html.en</code>, <code>document.html.fr</code>, and
<code>document.html.de</code>, respectively. The type map file will
be called <code>document.html.var</code>, and will contain the
following:</p>
<div class="example"><p><code>
URI: document.html<br />
<br />
Content-language: en<br />
Content-type: text/html<br />
URI: document.html.en<br />
<br />
Content-language: fr<br />
Content-type: text/html<br />
URI: document.html.fr<br />
<br />
Content-language: de<br />
Content-type: text/html<br />
URI: document.html.de<br />
<br />
</code></p></div>
<p>All four of these files should be placed in the same directory,
and the <code>.var</code> file should be associated with the
<code>type-map</code> handler with an <code class="directive"><a href="../mod/mod_mime.html#addhandler">AddHandler</a></code> directive:</p>
<pre class="prettyprint lang-config">
AddHandler type-map .var
</pre>
<p>A request for <code>document.html.var</code> in this directory will
result in choosing the variant which most closely matches the language preference
specified in the user's <code>Accept-Language</code> request
header.</p>
<p>If <code>Multiviews</code> is enabled, and <code class="directive"><a href="../mod/mod_mime.html#multiviewsmatch">MultiviewsMatch</a></code> is set to "handlers" or "any", a request to
<code>document.html</code> will discover <code>document.html.var</code> and
continue negotiating with the explicit type map.</p>
<p>Other configuration directives, such as <code class="directive"><a href="../mod/mod_alias.html#alias">Alias</a></code> can be used to map <code>document.html</code> to
<code>document.html.var</code>.</p>
</div><div class="top"><a href="#page-header"><img alt="top" src="../../images/up.gif" /></a></div>
<div class="section">
<h2><a name="multiviews" id="multiviews">Multiviews</a></h2>
<p>A Multiviews search is enabled by the <code>Multiviews</code>
<code class="directive"><a href="../mod/core.html#options">Options</a></code>. If the server receives a
request for <code>/some/dir/foo</code> and
<code>/some/dir/foo</code> does <em>not</em> exist, then the
server reads the directory looking for all files named
<code>foo.*</code>, and effectively fakes up a type map which
names all those files, assigning them the same media types and
content-encodings it would have if the client had asked for one
of them by name. It then chooses the best match to the client's
requirements, and returns that document.</p>
<p>The <code class="directive"><a href="../mod/mod_mime.html#multiviewsmatch">MultiviewsMatch</a></code>
directive configures whether Apache will consider files
that do not have content negotiation meta-information assigned
to them when choosing files.</p>
</div>
<div class="top"><a href="#page-header"><img alt="top" src="../../images/up.gif" /></a></div>
<div class="directive-section"><h2><a name="CacheNegotiatedDocs" id="CacheNegotiatedDocs">CacheNegotiatedDocs</a> <a name="cachenegotiateddocs" id="cachenegotiateddocs">Directive</a></h2>
<table class="directive">
<tr><th><a href="directive-dict.html#Description">Description:</a></th><td>Allows content-negotiated documents to be
cached by proxy servers</td></tr>
<tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>CacheNegotiatedDocs On|Off</code></td></tr>
<tr><th><a href="directive-dict.html#Default">Default:</a></th><td><code>CacheNegotiatedDocs Off</code></td></tr>
<tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config, virtual host</td></tr>
<tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Base</td></tr>
<tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_negotiation</td></tr>
</table>
<p>If set, this directive allows content-negotiated documents
to be cached by proxy servers. This could mean that clients
behind those proxys could retrieve versions of the documents
that are not the best match for their abilities, but it will
make caching more efficient.</p>
<p>This directive only applies to requests which come from
HTTP/1.0 browsers. HTTP/1.1 provides much better control over
the caching of negotiated documents, and this directive has no
effect in responses to HTTP/1.1 requests.</p>
</div>
<div class="top"><a href="#page-header"><img alt="top" src="../../images/up.gif" /></a></div>
<div class="directive-section"><h2><a name="ForceLanguagePriority" id="ForceLanguagePriority">ForceLanguagePriority</a> <a name="forcelanguagepriority" id="forcelanguagepriority">Directive</a></h2>
<table class="directive">
<tr><th><a href="directive-dict.html#Description">Description:</a></th><td>Action to take if a single acceptable document is not
found</td></tr>
<tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>ForceLanguagePriority None|Prefer|Fallback [Prefer|Fallback]</code></td></tr>
<tr><th><a href="directive-dict.html#Default">Default:</a></th><td><code>ForceLanguagePriority Prefer</code></td></tr>
<tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config, virtual host, directory, .htaccess</td></tr>
<tr><th><a href="directive-dict.html#Override">Override:</a></th><td>FileInfo</td></tr>
<tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Base</td></tr>
<tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_negotiation</td></tr>
</table>
<p>The <code class="directive">ForceLanguagePriority</code> directive uses
the given <code class="directive"><a href="#languagepriority">LanguagePriority</a></code> to satisfy
negotiation where the server could otherwise not return a single
matching document.</p>
<p><code>ForceLanguagePriority Prefer</code> uses
<code>LanguagePriority</code> to serve a one valid result, rather
than returning an HTTP result 300 (MULTIPLE CHOICES) when there
are several equally valid choices. If the directives below were
given, and the user's <code>Accept-Language</code> header assigned
<code>en</code> and <code>de</code> each as quality <code>.500</code>
(equally acceptable) then the first matching variant, <code>en</code>,
will be served.</p>
<pre class="prettyprint lang-config">
LanguagePriority en fr de
ForceLanguagePriority Prefer
</pre>
<p><code>ForceLanguagePriority Fallback</code> uses
<code class="directive"><a href="#languagepriority">LanguagePriority</a></code> to
serve a valid result, rather than returning an HTTP result 406
(NOT ACCEPTABLE). If the directives below were given, and the user's
<code>Accept-Language</code> only permitted an <code>es</code>
language response, but such a variant isn't found, then the first
variant from the <code class="directive"><a href="#languagepriority">LanguagePriority</a></code> list below will be served.</p>
<pre class="prettyprint lang-config">
LanguagePriority en fr de
ForceLanguagePriority Fallback
</pre>
<p>Both options, <code>Prefer</code> and <code>Fallback</code>, may be
specified, so either the first matching variant from <code class="directive"><a href="#languagepriority">LanguagePriority</a></code> will be served if
more than one variant is acceptable, or first available document will
be served if none of the variants matched the client's acceptable list
of languages.</p>
<h3>See also</h3>
<ul>
<li><code class="directive"><a href="../mod/mod_mime.html#addlanguage">AddLanguage</a></code></li>
</ul>
</div>
<div class="top"><a href="#page-header"><img alt="top" src="../../images/up.gif" /></a></div>
<div class="directive-section"><h2><a name="LanguagePriority" id="LanguagePriority">LanguagePriority</a> <a name="languagepriority" id="languagepriority">Directive</a></h2>
<table class="directive">
<tr><th><a href="directive-dict.html#Description">Description:</a></th><td>The precendence of language variants for cases where
the client does not express a preference</td></tr>
<tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>LanguagePriority <var>MIME-lang</var> [<var>MIME-lang</var>]
...</code></td></tr>
<tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config, virtual host, directory, .htaccess</td></tr>
<tr><th><a href="directive-dict.html#Override">Override:</a></th><td>FileInfo</td></tr>
<tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Base</td></tr>
<tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_negotiation</td></tr>
</table>
<p>The <code class="directive">LanguagePriority</code> sets the precedence
of language variants for the case where the client does not
express a preference, when handling a Multiviews request. The list
of <var>MIME-lang</var> are in order of decreasing preference.</p>
<pre class="prettyprint lang-config">
LanguagePriority en fr de
</pre>
<p>For a request for <code>foo.html</code>, where
<code>foo.html.fr</code> and <code>foo.html.de</code> both
existed, but the browser did not express a language preference,
then <code>foo.html.fr</code> would be returned.</p>
<p>Note that this directive only has an effect if a 'best'
language cannot be determined by any other means or the <code class="directive"><a href="#forcelanguagepriority">ForceLanguagePriority</a></code> directive
is not <code>None</code>. In general, the client determines the
language preference, not the server.</p>
<h3>See also</h3>
<ul>
<li><code class="directive"><a href="../mod/mod_mime.html#addlanguage">AddLanguage</a></code></li>
</ul>
</div>
</div>
<div class="bottomlang">
<p><span>Available Languages: </span><a href="../../en/mod/mod_negotiation.html" title="English"> en </a> |
<a href="../../fr/mod/mod_negotiation.html" hreflang="fr" rel="alternate" title="Français"> fr </a> |
<a href="../../ja/mod/mod_negotiation.html" hreflang="ja" rel="alternate" title="Japanese"> ja </a></p>
</div><div class="top"><a href="#page-header"><img src="../../images/up.gif" alt="top" /></a></div><div class="section"><h2><a id="comments_section" name="comments_section">Comments</a></h2><div class="warning"><strong>Notice:</strong><br />This is not a Q&A section. Comments placed here should be pointed towards suggestions on improving the documentation or server, and may be removed again by our moderators if they are either implemented or considered invalid/off-topic. Questions on how to manage the Apache HTTP Server should be directed at either our IRC channel, #httpd, on Freenode, or sent to our <a href="http://httpd.apache.org/lists.html">mailing lists</a>.</div>
<script type="text/javascript"><!--//--><![CDATA[//><!--
var comments_shortname = 'httpd';
var comments_identifier = 'http://httpd.apache.org/docs/2.4/mod/mod_negotiation.html';
(function(w, d) {
if (w.location.hostname.toLowerCase() == "httpd.apache.org") {
d.write('<div id="comments_thread"><\/div>');
var s = d.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = 'https://comments.apache.org/show_comments.lua?site=' + comments_shortname + '&page=' + comments_identifier;
(d.getElementsByTagName('head')[0] || d.getElementsByTagName('body')[0]).appendChild(s);
}
else {
d.write('<div id="comments_thread">Comments are disabled for this page at the moment.<\/div>');
}
})(window, document);
//--><!]]></script></div><div id="footer">
<p class="apache">Copyright 2013 The Apache Software Foundation.<br />Licensed under the <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache License, Version 2.0</a>.</p>
<p class="menu"><a href="../mod/index.html">Modules</a> | <a href="../mod/directives.html">Directives</a> | <a href="http://wiki.apache.org/httpd/FAQ">FAQ</a> | <a href="../glossary.html">Glossary</a> | <a href="../sitemap.html">Sitemap</a></p></div><script type="text/javascript"><!--//--><![CDATA[//><!--
if (typeof(prettyPrint) !== 'undefined') {
prettyPrint();
}
//--><!]]></script>
</body></html> | rafaelgou/the-phpjs-local-docs-collection | apache/2.4.7/en/mod/mod_negotiation.html | HTML | gpl-3.0 | 21,280 |
var searchData=
[
['gestionnaire_2ehpp',['Gestionnaire.hpp',['../Gestionnaire_8hpp.html',1,'']]],
['gestionnairemutex',['GestionnaireMutex',['../classGestionnaireMutex.html',1,'GestionnaireMutex'],['../classGestionnaireMutex.html#a16e149bb5c836f1ea2e7d6758422aca9',1,'GestionnaireMutex::GestionnaireMutex()']]],
['gestionnairemutex_2ecpp',['GestionnaireMutex.cpp',['../GestionnaireMutex_8cpp.html',1,'']]],
['gestionnairemutex_2ehpp',['GestionnaireMutex.hpp',['../GestionnaireMutex_8hpp.html',1,'']]],
['gestionnairepartie',['GestionnairePartie',['../classGestionnairePartie.html',1,'GestionnairePartie'],['../classGestionnairePartie.html#a83bcbead120fcdae027d9a3a6a7af83c',1,'GestionnairePartie::GestionnairePartie()']]],
['gestionnairepartie_2ecpp',['GestionnairePartie.cpp',['../GestionnairePartie_8cpp.html',1,'']]],
['gestionnairepartie_2ehpp',['GestionnairePartie.hpp',['../GestionnairePartie_8hpp.html',1,'']]],
['gestionnairerequete_2ecpp',['GestionnaireRequete.cpp',['../GestionnaireRequete_8cpp.html',1,'']]],
['gestionnairerequete_2ehpp',['GestionnaireRequete.hpp',['../GestionnaireRequete_8hpp.html',1,'']]],
['gestionnairesalon',['GestionnaireSalon',['../classGestionnaireSalon.html',1,'GestionnaireSalon'],['../classGestionnaireSalon.html#ae606439b050c0065db4a833a15d52f8b',1,'GestionnaireSalon::GestionnaireSalon()']]],
['gestionnairesalon_2ecpp',['GestionnaireSalon.cpp',['../GestionnaireSalon_8cpp.html',1,'']]],
['gestionnairesalon_2ehpp',['GestionnaireSalon.hpp',['../GestionnaireSalon_8hpp.html',1,'']]],
['gestionnairesocket',['GestionnaireSocket',['../classGestionnaireSocket.html',1,'GestionnaireSocket'],['../classGestionnaireSocket.html#aea6b223b8d0af0ec2688940a887fe17b',1,'GestionnaireSocket::GestionnaireSocket()']]],
['gestionnairesocket_2ecpp',['GestionnaireSocket.cpp',['../GestionnaireSocket_8cpp.html',1,'']]],
['gestionnairesocket_2ehpp',['GestionnaireSocket.hpp',['../GestionnaireSocket_8hpp.html',1,'']]],
['getdata',['getData',['../classDataPartieEnTete.html#aae81e6ebc709a0d6462c9a49afac6e6f',1,'DataPartieEnTete']]],
['gethote',['getHote',['../classSalon.html#a488ec3d4aea47aae26f7e33040d6db46',1,'Salon']]],
['getintervalletemporisation',['getIntervalleTemporisation',['../classMachineEtat.html#a05ba8f109b96a4c3eee40cc82da296e3',1,'MachineEtat']]],
['getlisteetat',['getListeEtat',['../classMachineEtat.html#abac1333e441143ac59f360ed3d950374',1,'MachineEtat']]],
['getmutex',['getMutex',['../classGestionnaireMutex.html#a4cd9287c0fc861296ead18746dbed30b',1,'GestionnaireMutex']]],
['getniveaumemoiretampon',['getNiveauMemoireTampon',['../classMachineEtat.html#a557ea7c575b72b0f2558c6ab9a1f121f',1,'MachineEtat']]],
['getnomjoueur',['getNomJoueur',['../classJoueur.html#a76413c6f6291c98784e3cb864db1311b',1,'Joueur']]],
['getnumeroclient',['getNumeroClient',['../classSocketTcp.html#a330cde24a46b5b945300402cd8f2495f',1,'SocketTcp']]],
['getnumerojoueur',['getNumeroJoueur',['../classJoueur.html#a28138f8a7705e6deea7802118072d1fe',1,'Joueur']]],
['getnumerosalon',['getNumeroSalon',['../classSalon.html#ab52889c156173dacca77b4a0188f742f',1,'Salon']]],
['getparam',['getParam',['../classConfiguration.html#a3d4b63d76baaad5a598402d9d0b2295e',1,'Configuration']]],
['getsocket',['getSocket',['../classGestionnaireSocket.html#ae54adc24a32a0e5db1bafff3564ebf8d',1,'GestionnaireSocket']]],
['getsockettcp',['getSocketTcp',['../classJoueur.html#a5971cb1e7bf96db7144e92e0d95de5bb',1,'Joueur']]],
['gettaillelistesocket',['getTailleListeSocket',['../classGestionnaireSocket.html#a95ee63ccc58d90538664af94559f66b7',1,'GestionnaireSocket']]],
['getvaleurlisteetat',['getValeurListeEtat',['../classMachineEtat.html#a63e8ed788501c5a22db4db813bd15d5e',1,'MachineEtat']]]
];
| Aredhele/FreakyMonsters | serveur/doc/html/search/all_5.js | JavaScript | gpl-3.0 | 3,760 |
#!/bin/sh
if [ $# -lt 4 ]; then
cat <<EOF
Usage: test_smbclient_basic.sh SERVER SERVER_IP DOMAIN USERNAME PASSWORD
EOF
exit 1;
fi
SERVER="$1"
SERVER_IP="$2"
USERNAME="$3"
PASSWORD="$4"
TARGET_ENV="$5"
shift 5
ADDARGS="$@"
incdir=`dirname $0`/../../../testprogs/blackbox
. $incdir/subunit.sh
. $incdir/common_test_fns.inc
samba_bindir="$BINDIR"
samba_vlp="$samba_bindir/vlp"
samba_smbspool="$samba_bindir/smbspool"
samba_argv_wrapper="$samba_bindir/smbspool_argv_wrapper"
samba_smbtorture3="$samba_bindir/smbtorture3"
samba_smbspool_krb5="$samba_bindir/smbspool_krb5_wrapper"
test_smbspool_noargs()
{
cmd='$1 2>&1'
eval echo "$cmd"
out=$(eval $cmd)
ret=$?
if [ $ret != 0 ]; then
echo "$out"
echo "failed to execute $1"
fi
echo "$out" | grep 'network smb "Unknown" "Windows Printer via SAMBA"'
ret=$?
if [ $ret != 0 ] ; then
echo "$out"
return 1
fi
}
test_smbspool_authinforequired_none()
{
cmd='$samba_smbspool_krb5 smb://$SERVER_IP/print4 200 $USERNAME "Testprint" 1 "options" $SRCDIR/testdata/printing/example.ps 2>&1'
AUTH_INFO_REQUIRED="none"
export AUTH_INFO_REQUIRED
eval echo "$cmd"
out=$(eval $cmd)
ret=$?
unset AUTH_INFO_REQUIRED
if [ $ret != 0 ]; then
echo "$out"
echo "failed to execute $smbspool_krb5"
return 1
fi
return 0
}
test_smbspool_authinforequired_unknown()
{
cmd='$samba_smbspool_krb5 smb://$SERVER_IP/print4 200 $USERNAME "Testprint" 1 "options" $SRCDIR/testdata/printing/example.ps 2>&1'
# smbspool_krb5_wrapper must ignore AUTH_INFO_REQUIRED unknown to him and pass the task to smbspool
# smbspool must fail with NT_STATUS_ACCESS_DENIED (22)
# "jjf4wgmsbc0" is just a random string
AUTH_INFO_REQUIRED="jjf4wgmsbc0"
export AUTH_INFO_REQUIRED
eval echo "$cmd"
out=$(eval $cmd)
ret=$?
unset AUTH_INFO_REQUIRED
case "$ret" in
2 ) return 0 ;;
* )
echo "ret=$ret"
echo "$out"
echo "failed to test $smbspool_krb5 against unknown value of AUTH_INFO_REQUIRED"
return 1
;;
esac
}
#
# The test enviornment uses 'vlp' (virtual lp) as the printing backend.
#
# When using the vlp backend the print job is only written to the database.
# The job needs to removed manually using 'vlp lprm' command!
#
# This calls the 'vlp' command to check if the print job has been successfully
# added to the database and also makes sure the temorary print file has been
# created.
#
# The function removes the print job from the vlp database if successful.
#
test_vlp_verify()
{
tdbfile="$PREFIX_ABS/$TARGET_ENV/lockdir/vlp.tdb"
if [ ! -w $tdbfile ]; then
echo "vlp tdbfile $tdbfile doesn't exist or is not writeable!"
return 1
fi
cmd='$samba_vlp tdbfile=$tdbfile lpq print1 2>&1'
eval echo "$cmd"
out=$(eval $cmd)
ret=$?
if [ $ret != 0 ]; then
echo "failed to get print queue with $samba_vlp"
echo "$out"
fi
jobid=$(echo "$out" | awk '/[0-9]+/ { print $1 };')
if [ -z "$jobid" ] || [ $jobid -lt 100 || [ $jobid -gt 2000 ]; then
echo "Invalid jobid: $jobid"
echo "$out"
return 1
fi
file=$(echo "$out" | awk '/[0-9]+/ { print $6 };')
if [ ! -r $PREFIX_ABS/$TARGET_ENV/share/$file ]; then
echo "$file doesn't exist"
echo "$out"
return 1
fi
$samba_vlp "tdbfile=$tdbfile" lprm print1 $jobid
ret=$?
if [ $ret != 0 ] ; then
echo "Failed to remove jobid $jobid from $tdbfile"
return 1
fi
}
test_delete_on_close()
{
tdbfile="$PREFIX_ABS/$TARGET_ENV/lockdir/vlp.tdb"
if [ ! -w $tdbfile ]; then
echo "vlp tdbfile $tdbfile doesn't exist or is not writeable!"
return 1
fi
cmd='$samba_vlp tdbfile=$tdbfile lpq print1 2>&1'
eval echo "$cmd"
out=$(eval $cmd)
ret=$?
if [ $ret != 0 ]; then
echo "failed to lpq jobs on print1 with $samba_vlp"
echo "$out"
return 1
fi
num_jobs=$(echo "$out" | wc -l)
#
# Now run the test DELETE-PRINT from smbtorture3
#
cmd='$samba_smbtorture3 //$SERVER_IP/print1 -U$USERNAME%$PASSWORD DELETE-PRINT 2>&1'
eval echo "$cmd"
out_t=$(eval $cmd)
ret=$?
if [ $ret != 0 ]; then
echo "failed to run DELETE-PRINT on print1"
echo "$out_t"
return 1
fi
cmd='$samba_vlp tdbfile=$tdbfile lpq print1 2>&1'
eval echo "$cmd"
out1=$(eval $cmd)
ret=$?
if [ $ret != 0 ]; then
echo "(2) failed to lpq jobs on print1 with $samba_vlp"
echo "$out1"
return 1
fi
num_jobs1=$(echo "$out1" | wc -l)
#
# Number of jobs should not change. Job
# should not have made it to backend.
#
if [ "$num_jobs1" -ne "$num_jobs" ]; then
echo "delete-on-close fail $num_jobs1 -ne $num_jobs"
echo "$out"
echo "$out_t"
echo "$out1"
return 1
fi
return 0
}
testit "smbspool no args" \
test_smbspool_noargs $samba_smbspool || \
failed=$(expr $failed + 1)
testit "smbspool_krb5_wrapper no args" \
test_smbspool_noargs $samba_smbspool_krb5 || \
failed=$(expr $failed + 1)
testit "smbspool_krb5_wrapper AuthInfoRequired=none" \
test_smbspool_authinforequired_none || \
failed=$(expr $failed + 1)
testit "smbspool_krb5_wrapper AuthInfoRequired=(sth unknown)" \
test_smbspool_authinforequired_unknown || \
failed=$(expr $failed + 1)
testit "smbspool print example.ps" \
$samba_smbspool smb://$USERNAME:$PASSWORD@$SERVER_IP/print1 200 $USERNAME "Testprint" 1 "options" $SRCDIR/testdata/printing/example.ps || \
failed=$(expr $failed + 1)
testit "vlp verify example.ps" \
test_vlp_verify \
|| failed=$(expr $failed + 1)
testit "smbspool print example.ps via stdin" \
$samba_smbspool smb://$USERNAME:$PASSWORD@$SERVER_IP/print1 200 $USERNAME "Testprint" 1 "options" < $SRCDIR/testdata/printing/example.ps || \
failed=$(expr $failed + 1)
testit "vlp verify example.ps" \
test_vlp_verify \
|| failed=$(expr $failed + 1)
DEVICE_URI="smb://$USERNAME:$PASSWORD@$SERVER_IP/print1"
export DEVICE_URI
testit "smbspool print DEVICE_URI example.ps" \
$samba_smbspool 200 $USERNAME "Testprint" 1 "options" $SRCDIR/testdata/printing/example.ps || \
failed=$(expr $failed + 1)
unset DEVICE_URI
testit "vlp verify example.ps" \
test_vlp_verify \
|| failed=$(expr $failed + 1)
DEVICE_URI="smb://$USERNAME:$PASSWORD@$SERVER_IP/print1"
export DEVICE_URI
testit "smbspool print DEVICE_URI example.ps via stdin" \
$samba_smbspool 200 $USERNAME "Testprint" 1 "options" < $SRCDIR/testdata/printing/example.ps || \
failed=$(expr $failed + 1)
unset DEVICE_URI
testit "vlp verify example.ps" \
test_vlp_verify \
|| failed=$(expr $failed + 1)
DEVICE_URI="smb://$USERNAME:$PASSWORD@$SERVER_IP/print1"
export DEVICE_URI
testit "smbspool print sanitized Device URI in argv0 example.ps" \
$smbspool_argv_wrapper $samba_smbspool smb://$SERVER_IP/print1 200 $USERNAME "Testprint" 1 "options" $SRCDIR/testdata/printing/example.ps || \
failed=$(expr $failed + 1)
unset DEVICE_URI
testit "vlp verify example.ps" \
test_vlp_verify \
|| failed=$(expr $failed + 1)
DEVICE_URI="smb://$USERNAME:$PASSWORD@$SERVER_IP/print1"
export DEVICE_URI
testit "smbspool print sanitized Device URI in argv0 example.ps via stdin" \
$smbspool_argv_wrapper $samba_smbspool smb://$SERVER_IP/print1 200 $USERNAME "Testprint" 1 "options" < $SRCDIR/testdata/printing/example.ps || \
failed=$(expr $failed + 1)
unset DEVICE_URI
testit "vlp verify example.ps" \
test_vlp_verify \
|| failed=$(expr $failed + 1)
AUTH_INFO_REQUIRED="username,password"
export AUTH_INFO_REQUIRED
testit "smbspool_krb5(username,password) print example.ps" \
$samba_smbspool_krb5 smb://$USERNAME:$PASSWORD@$SERVER_IP/print1 200 $USERNAME "Testprint" 1 "options" $SRCDIR/testdata/printing/example.ps || \
failed=$(expr $failed + 1)
testit "vlp verify example.ps" \
test_vlp_verify || \
failed=$(expr $failed + 1)
unset AUTH_INFO_REQUIRED
testit "delete on close" \
test_delete_on_close \
|| failed=$(expr $failed + 1)
exit $failed
| kernevil/samba | source3/script/tests/test_smbspool.sh | Shell | gpl-3.0 | 7,656 |
#! /bin/sh
# A simple utility script which reads the SBD configuration file and loops
# through all SBD block devices, clearing message slots for all nodes. This
# effectively unfences any nodes.
SBD_CONFIG="/etc/sysconfig/sbd"
# Read the SBD config file and loop over all devices
while read -r device; do
while read -r sbd_list; do
node="$(echo ${sbd_list} | awk '{print $2}')"
echo "Clearing message slots for node '${node}'" \
"on device '${device}'..."
sbd -d ${device} message ${node} clear
done <<< "$(sbd -d ${device} list)"
done <<< "$(cat ${SBD_CONFIG} | grep SBD_DEVICE | cut -d= -f2 | \
tr -d '"' | tr ';' '\n')"
| astersmith/esos | scripts/sbd_unfence.sh | Shell | gpl-3.0 | 676 |
/*
*\class PASER_Neighbor_Table
*@brief Class represents an entry in the neighbor table
*
*\authors Eugen.Paul | Mohamad.Sbeiti \@paser.info
*
*\copyright (C) 2012 Communication Networks Institute (CNI - Prof. Dr.-Ing. Christian Wietfeld)
* at Technische Universitaet Dortmund, Germany
* http://www.kn.e-technik.tu-dortmund.de/
*
*
* This program is free software; you can redistribute it
* and/or modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later
* version.
* For further information see file COPYING
* in the top level directory
********************************************************************************
* This work is part of the secure wireless mesh networks framework, which is currently under development by CNI
********************************************************************************/
#include "Configuration.h"
#ifdef OPENSSL_IS_LINKED
#include <openssl/x509.h>
#include "PASER_Neighbor_Entry.h"
PASER_Neighbor_Entry::~PASER_Neighbor_Entry() {
if (root) {
free(root);
}
root = NULL;
if (Cert) {
X509_free((X509*) Cert);
}
Cert = NULL;
}
void PASER_Neighbor_Entry::setValidTimer(PASER_Timer_Message *_validTimer) {
validTimer = _validTimer;
}
#endif
| ngocthienle/SG_OMNeTpp | inetmanet-2.0/src/networklayer/manetrouting/PASER/paser_tables/PASER_Neighbor_Entry.cc | C++ | gpl-3.0 | 1,505 |
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
**Table of contents**
- [symbol-tree](#symbol-tree)
- [Example](#example)
- [Testing](#testing)
- [API Documentation](#api-documentation)
- [symbol-tree](#symbol-tree-1)
- [SymbolTree ⏏](#symboltree-%E2%8F%8F)
- [new SymbolTree([description])](#new-symboltreedescription)
- [symbolTree.initialize(object) ⇒ <code>Object</code>](#symboltreeinitializeobject-%E2%87%92-codeobjectcode)
- [symbolTree.hasChildren(object) ⇒ <code>Boolean</code>](#symboltreehaschildrenobject-%E2%87%92-codebooleancode)
- [symbolTree.firstChild(object) ⇒ <code>Object</code>](#symboltreefirstchildobject-%E2%87%92-codeobjectcode)
- [symbolTree.lastChild(object) ⇒ <code>Object</code>](#symboltreelastchildobject-%E2%87%92-codeobjectcode)
- [symbolTree.previousSibling(object) ⇒ <code>Object</code>](#symboltreeprevioussiblingobject-%E2%87%92-codeobjectcode)
- [symbolTree.nextSibling(object) ⇒ <code>Object</code>](#symboltreenextsiblingobject-%E2%87%92-codeobjectcode)
- [symbolTree.parent(object) ⇒ <code>Object</code>](#symboltreeparentobject-%E2%87%92-codeobjectcode)
- [symbolTree.lastInclusiveDescendant(object) ⇒ <code>Object</code>](#symboltreelastinclusivedescendantobject-%E2%87%92-codeobjectcode)
- [symbolTree.preceding(object, [options]) ⇒ <code>Object</code>](#symboltreeprecedingobject-options-%E2%87%92-codeobjectcode)
- [symbolTree.following(object, [options]) ⇒ <code>Object</code>](#symboltreefollowingobject-options-%E2%87%92-codeobjectcode)
- [symbolTree.childrenToArray(parent, [options]) ⇒ <code>Array.<Object></code>](#symboltreechildrentoarrayparent-options-%E2%87%92-codearrayltobjectgtcode)
- [symbolTree.ancestorsToArray(object, [options]) ⇒ <code>Array.<Object></code>](#symboltreeancestorstoarrayobject-options-%E2%87%92-codearrayltobjectgtcode)
- [symbolTree.treeToArray(root, [options]) ⇒ <code>Array.<Object></code>](#symboltreetreetoarrayroot-options-%E2%87%92-codearrayltobjectgtcode)
- [symbolTree.childrenIterator(parent, [options]) ⇒ <code>Object</code>](#symboltreechildreniteratorparent-options-%E2%87%92-codeobjectcode)
- [symbolTree.previousSiblingsIterator(object) ⇒ <code>Object</code>](#symboltreeprevioussiblingsiteratorobject-%E2%87%92-codeobjectcode)
- [symbolTree.nextSiblingsIterator(object) ⇒ <code>Object</code>](#symboltreenextsiblingsiteratorobject-%E2%87%92-codeobjectcode)
- [symbolTree.ancestorsIterator(object) ⇒ <code>Object</code>](#symboltreeancestorsiteratorobject-%E2%87%92-codeobjectcode)
- [symbolTree.treeIterator(root, options) ⇒ <code>Object</code>](#symboltreetreeiteratorroot-options-%E2%87%92-codeobjectcode)
- [symbolTree.index(child) ⇒ <code>Number</code>](#symboltreeindexchild-%E2%87%92-codenumbercode)
- [symbolTree.childrenCount(parent) ⇒ <code>Number</code>](#symboltreechildrencountparent-%E2%87%92-codenumbercode)
- [symbolTree.compareTreePosition(left, right) ⇒ <code>Number</code>](#symboltreecomparetreepositionleft-right-%E2%87%92-codenumbercode)
- [symbolTree.remove(removeObject) ⇒ <code>Object</code>](#symboltreeremoveremoveobject-%E2%87%92-codeobjectcode)
- [symbolTree.insertBefore(referenceObject, newObject) ⇒ <code>Object</code>](#symboltreeinsertbeforereferenceobject-newobject-%E2%87%92-codeobjectcode)
- [symbolTree.insertAfter(referenceObject, newObject) ⇒ <code>Object</code>](#symboltreeinsertafterreferenceobject-newobject-%E2%87%92-codeobjectcode)
- [symbolTree.prependChild(referenceObject, newObject) ⇒ <code>Object</code>](#symboltreeprependchildreferenceobject-newobject-%E2%87%92-codeobjectcode)
- [symbolTree.appendChild(referenceObject, newObject) ⇒ <code>Object</code>](#symboltreeappendchildreferenceobject-newobject-%E2%87%92-codeobjectcode)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
symbol-tree
===========
[](https://travis-ci.org/jsdom/js-symbol-tree) [](https://coveralls.io/github/jsdom/js-symbol-tree?branch=master)
Turn any collection of objects into its own efficient tree or linked list using `Symbol`.
This library has been designed to provide an efficient backing data structure for DOM trees. You can also use this library as an efficient linked list. Any meta data is stored on your objects directly, which ensures any kind of insertion or deletion is performed in constant time. Because an ES6 `Symbol` is used, the meta data does not interfere with your object in any way.
Node.js 4+, io.js and modern browsers are supported.
Example
-------
A linked list:
```javascript
const SymbolTree = require('symbol-tree');
const tree = new SymbolTree();
let a = {foo: 'bar'}; // or `new Whatever()`
let b = {foo: 'baz'};
let c = {foo: 'qux'};
tree.insertBefore(b, a); // insert a before b
tree.insertAfter(b, c); // insert c after b
console.log(tree.nextSibling(a) === b);
console.log(tree.nextSibling(b) === c);
console.log(tree.previousSibling(c) === b);
tree.remove(b);
console.log(tree.nextSibling(a) === c);
```
A tree:
```javascript
const SymbolTree = require('symbol-tree');
const tree = new SymbolTree();
let parent = {};
let a = {};
let b = {};
let c = {};
tree.prependChild(parent, a); // insert a as the first child
tree.appendChild(parent,c ); // insert c as the last child
tree.insertAfter(a, b); // insert b after a, it now has the same parent as a
console.log(tree.firstChild(parent) === a);
console.log(tree.nextSibling(tree.firstChild(parent)) === b);
console.log(tree.lastChild(parent) === c);
let grandparent = {};
tree.prependChild(grandparent, parent);
console.log(tree.firstChild(tree.firstChild(grandparent)) === a);
```
Testing
-------
Make sure you install the dependencies first:
npm install
You can now run the unit tests by executing:
npm test
The line and branch coverage should be 100%.
API Documentation
-----------------
<a name="module_symbol-tree"></a>
## symbol-tree
**Author:** Joris van der Wel <joris@jorisvanderwel.com>
* [symbol-tree](#module_symbol-tree)
* [SymbolTree](#exp_module_symbol-tree--SymbolTree) ⏏
* [new SymbolTree([description])](#new_module_symbol-tree--SymbolTree_new)
* [.initialize(object)](#module_symbol-tree--SymbolTree+initialize) ⇒ <code>Object</code>
* [.hasChildren(object)](#module_symbol-tree--SymbolTree+hasChildren) ⇒ <code>Boolean</code>
* [.firstChild(object)](#module_symbol-tree--SymbolTree+firstChild) ⇒ <code>Object</code>
* [.lastChild(object)](#module_symbol-tree--SymbolTree+lastChild) ⇒ <code>Object</code>
* [.previousSibling(object)](#module_symbol-tree--SymbolTree+previousSibling) ⇒ <code>Object</code>
* [.nextSibling(object)](#module_symbol-tree--SymbolTree+nextSibling) ⇒ <code>Object</code>
* [.parent(object)](#module_symbol-tree--SymbolTree+parent) ⇒ <code>Object</code>
* [.lastInclusiveDescendant(object)](#module_symbol-tree--SymbolTree+lastInclusiveDescendant) ⇒ <code>Object</code>
* [.preceding(object, [options])](#module_symbol-tree--SymbolTree+preceding) ⇒ <code>Object</code>
* [.following(object, [options])](#module_symbol-tree--SymbolTree+following) ⇒ <code>Object</code>
* [.childrenToArray(parent, [options])](#module_symbol-tree--SymbolTree+childrenToArray) ⇒ <code>Array.<Object></code>
* [.ancestorsToArray(object, [options])](#module_symbol-tree--SymbolTree+ancestorsToArray) ⇒ <code>Array.<Object></code>
* [.treeToArray(root, [options])](#module_symbol-tree--SymbolTree+treeToArray) ⇒ <code>Array.<Object></code>
* [.childrenIterator(parent, [options])](#module_symbol-tree--SymbolTree+childrenIterator) ⇒ <code>Object</code>
* [.previousSiblingsIterator(object)](#module_symbol-tree--SymbolTree+previousSiblingsIterator) ⇒ <code>Object</code>
* [.nextSiblingsIterator(object)](#module_symbol-tree--SymbolTree+nextSiblingsIterator) ⇒ <code>Object</code>
* [.ancestorsIterator(object)](#module_symbol-tree--SymbolTree+ancestorsIterator) ⇒ <code>Object</code>
* [.treeIterator(root, options)](#module_symbol-tree--SymbolTree+treeIterator) ⇒ <code>Object</code>
* [.index(child)](#module_symbol-tree--SymbolTree+index) ⇒ <code>Number</code>
* [.childrenCount(parent)](#module_symbol-tree--SymbolTree+childrenCount) ⇒ <code>Number</code>
* [.compareTreePosition(left, right)](#module_symbol-tree--SymbolTree+compareTreePosition) ⇒ <code>Number</code>
* [.remove(removeObject)](#module_symbol-tree--SymbolTree+remove) ⇒ <code>Object</code>
* [.insertBefore(referenceObject, newObject)](#module_symbol-tree--SymbolTree+insertBefore) ⇒ <code>Object</code>
* [.insertAfter(referenceObject, newObject)](#module_symbol-tree--SymbolTree+insertAfter) ⇒ <code>Object</code>
* [.prependChild(referenceObject, newObject)](#module_symbol-tree--SymbolTree+prependChild) ⇒ <code>Object</code>
* [.appendChild(referenceObject, newObject)](#module_symbol-tree--SymbolTree+appendChild) ⇒ <code>Object</code>
<a name="exp_module_symbol-tree--SymbolTree"></a>
### SymbolTree ⏏
**Kind**: Exported class
<a name="new_module_symbol-tree--SymbolTree_new"></a>
#### new SymbolTree([description])
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [description] | <code>string</code> | <code>"'SymbolTree data'"</code> | Description used for the Symbol |
<a name="module_symbol-tree--SymbolTree+initialize"></a>
#### symbolTree.initialize(object) ⇒ <code>Object</code>
You can use this function to (optionally) initialize an object right after its creation,
to take advantage of V8's fast properties. Also useful if you would like to
freeze your object.
`O(1)`
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
**Returns**: <code>Object</code> - object
| Param | Type |
| --- | --- |
| object | <code>Object</code> |
<a name="module_symbol-tree--SymbolTree+hasChildren"></a>
#### symbolTree.hasChildren(object) ⇒ <code>Boolean</code>
Returns `true` if the object has any children. Otherwise it returns `false`.
* `O(1)`
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
| Param | Type |
| --- | --- |
| object | <code>Object</code> |
<a name="module_symbol-tree--SymbolTree+firstChild"></a>
#### symbolTree.firstChild(object) ⇒ <code>Object</code>
Returns the first child of the given object.
* `O(1)`
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
| Param | Type |
| --- | --- |
| object | <code>Object</code> |
<a name="module_symbol-tree--SymbolTree+lastChild"></a>
#### symbolTree.lastChild(object) ⇒ <code>Object</code>
Returns the last child of the given object.
* `O(1)`
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
| Param | Type |
| --- | --- |
| object | <code>Object</code> |
<a name="module_symbol-tree--SymbolTree+previousSibling"></a>
#### symbolTree.previousSibling(object) ⇒ <code>Object</code>
Returns the previous sibling of the given object.
* `O(1)`
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
| Param | Type |
| --- | --- |
| object | <code>Object</code> |
<a name="module_symbol-tree--SymbolTree+nextSibling"></a>
#### symbolTree.nextSibling(object) ⇒ <code>Object</code>
Returns the next sibling of the given object.
* `O(1)`
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
| Param | Type |
| --- | --- |
| object | <code>Object</code> |
<a name="module_symbol-tree--SymbolTree+parent"></a>
#### symbolTree.parent(object) ⇒ <code>Object</code>
Return the parent of the given object.
* `O(1)`
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
| Param | Type |
| --- | --- |
| object | <code>Object</code> |
<a name="module_symbol-tree--SymbolTree+lastInclusiveDescendant"></a>
#### symbolTree.lastInclusiveDescendant(object) ⇒ <code>Object</code>
Find the inclusive descendant that is last in tree order of the given object.
* `O(n)` (worst case) where `n` is the depth of the subtree of `object`
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
| Param | Type |
| --- | --- |
| object | <code>Object</code> |
<a name="module_symbol-tree--SymbolTree+preceding"></a>
#### symbolTree.preceding(object, [options]) ⇒ <code>Object</code>
Find the preceding object (A) of the given object (B).
An object A is preceding an object B if A and B are in the same tree
and A comes before B in tree order.
* `O(n)` (worst case)
* `O(1)` (amortized when walking the entire tree)
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
| Param | Type | Description |
| --- | --- | --- |
| object | <code>Object</code> | |
| [options] | <code>Object</code> | |
| [options.root] | <code>Object</code> | If set, `root` must be an inclusive ancestor of the return value (or else null is returned). This check _assumes_ that `root` is also an inclusive ancestor of the given `object` |
<a name="module_symbol-tree--SymbolTree+following"></a>
#### symbolTree.following(object, [options]) ⇒ <code>Object</code>
Find the following object (A) of the given object (B).
An object A is following an object B if A and B are in the same tree
and A comes after B in tree order.
* `O(n)` (worst case) where `n` is the amount of objects in the entire tree
* `O(1)` (amortized when walking the entire tree)
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| object | <code>Object</code> | | |
| [options] | <code>Object</code> | | |
| [options.root] | <code>Object</code> | | If set, `root` must be an inclusive ancestor of the return value (or else null is returned). This check _assumes_ that `root` is also an inclusive ancestor of the given `object` |
| [options.skipChildren] | <code>Boolean</code> | <code>false</code> | If set, ignore the children of `object` |
<a name="module_symbol-tree--SymbolTree+childrenToArray"></a>
#### symbolTree.childrenToArray(parent, [options]) ⇒ <code>Array.<Object></code>
Append all children of the given object to an array.
* `O(n)` where `n` is the amount of children of the given `parent`
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| parent | <code>Object</code> | | |
| [options] | <code>Object</code> | | |
| [options.array] | <code>Array.<Object></code> | <code>[]</code> | |
| [options.filter] | <code>function</code> | | Function to test each object before it is added to the array. Invoked with arguments (object). Should return `true` if an object is to be included. |
| [options.thisArg] | <code>\*</code> | | Value to use as `this` when executing `filter`. |
<a name="module_symbol-tree--SymbolTree+ancestorsToArray"></a>
#### symbolTree.ancestorsToArray(object, [options]) ⇒ <code>Array.<Object></code>
Append all inclusive ancestors of the given object to an array.
* `O(n)` where `n` is the amount of ancestors of the given `object`
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| object | <code>Object</code> | | |
| [options] | <code>Object</code> | | |
| [options.array] | <code>Array.<Object></code> | <code>[]</code> | |
| [options.filter] | <code>function</code> | | Function to test each object before it is added to the array. Invoked with arguments (object). Should return `true` if an object is to be included. |
| [options.thisArg] | <code>\*</code> | | Value to use as `this` when executing `filter`. |
<a name="module_symbol-tree--SymbolTree+treeToArray"></a>
#### symbolTree.treeToArray(root, [options]) ⇒ <code>Array.<Object></code>
Append all descendants of the given object to an array (in tree order).
* `O(n)` where `n` is the amount of objects in the sub-tree of the given `object`
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| root | <code>Object</code> | | |
| [options] | <code>Object</code> | | |
| [options.array] | <code>Array.<Object></code> | <code>[]</code> | |
| [options.filter] | <code>function</code> | | Function to test each object before it is added to the array. Invoked with arguments (object). Should return `true` if an object is to be included. |
| [options.thisArg] | <code>\*</code> | | Value to use as `this` when executing `filter`. |
<a name="module_symbol-tree--SymbolTree+childrenIterator"></a>
#### symbolTree.childrenIterator(parent, [options]) ⇒ <code>Object</code>
Iterate over all children of the given object
* `O(1)` for a single iteration
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
**Returns**: <code>Object</code> - An iterable iterator (ES6)
| Param | Type | Default |
| --- | --- | --- |
| parent | <code>Object</code> | |
| [options] | <code>Object</code> | |
| [options.reverse] | <code>Boolean</code> | <code>false</code> |
<a name="module_symbol-tree--SymbolTree+previousSiblingsIterator"></a>
#### symbolTree.previousSiblingsIterator(object) ⇒ <code>Object</code>
Iterate over all the previous siblings of the given object. (in reverse tree order)
* `O(1)` for a single iteration
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
**Returns**: <code>Object</code> - An iterable iterator (ES6)
| Param | Type |
| --- | --- |
| object | <code>Object</code> |
<a name="module_symbol-tree--SymbolTree+nextSiblingsIterator"></a>
#### symbolTree.nextSiblingsIterator(object) ⇒ <code>Object</code>
Iterate over all the next siblings of the given object. (in tree order)
* `O(1)` for a single iteration
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
**Returns**: <code>Object</code> - An iterable iterator (ES6)
| Param | Type |
| --- | --- |
| object | <code>Object</code> |
<a name="module_symbol-tree--SymbolTree+ancestorsIterator"></a>
#### symbolTree.ancestorsIterator(object) ⇒ <code>Object</code>
Iterate over all inclusive ancestors of the given object
* `O(1)` for a single iteration
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
**Returns**: <code>Object</code> - An iterable iterator (ES6)
| Param | Type |
| --- | --- |
| object | <code>Object</code> |
<a name="module_symbol-tree--SymbolTree+treeIterator"></a>
#### symbolTree.treeIterator(root, options) ⇒ <code>Object</code>
Iterate over all descendants of the given object (in tree order).
Where `n` is the amount of objects in the sub-tree of the given `root`:
* `O(n)` (worst case for a single iteration)
* `O(n)` (amortized, when completing the iterator)
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
**Returns**: <code>Object</code> - An iterable iterator (ES6)
| Param | Type | Default |
| --- | --- | --- |
| root | <code>Object</code> | |
| options | <code>Object</code> | |
| [options.reverse] | <code>Boolean</code> | <code>false</code> |
<a name="module_symbol-tree--SymbolTree+index"></a>
#### symbolTree.index(child) ⇒ <code>Number</code>
Find the index of the given object (the number of preceding siblings).
* `O(n)` where `n` is the amount of preceding siblings
* `O(1)` (amortized, if the tree is not modified)
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
**Returns**: <code>Number</code> - The number of preceding siblings, or -1 if the object has no parent
| Param | Type |
| --- | --- |
| child | <code>Object</code> |
<a name="module_symbol-tree--SymbolTree+childrenCount"></a>
#### symbolTree.childrenCount(parent) ⇒ <code>Number</code>
Calculate the number of children.
* `O(n)` where `n` is the amount of children
* `O(1)` (amortized, if the tree is not modified)
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
| Param | Type |
| --- | --- |
| parent | <code>Object</code> |
<a name="module_symbol-tree--SymbolTree+compareTreePosition"></a>
#### symbolTree.compareTreePosition(left, right) ⇒ <code>Number</code>
Compare the position of an object relative to another object. A bit set is returned:
<ul>
<li>DISCONNECTED : 1</li>
<li>PRECEDING : 2</li>
<li>FOLLOWING : 4</li>
<li>CONTAINS : 8</li>
<li>CONTAINED_BY : 16</li>
</ul>
The semantics are the same as compareDocumentPosition in DOM, with the exception that
DISCONNECTED never occurs with any other bit.
where `n` and `m` are the amount of ancestors of `left` and `right`;
where `o` is the amount of children of the lowest common ancestor of `left` and `right`:
* `O(n + m + o)` (worst case)
* `O(n + m)` (amortized, if the tree is not modified)
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
| Param | Type |
| --- | --- |
| left | <code>Object</code> |
| right | <code>Object</code> |
<a name="module_symbol-tree--SymbolTree+remove"></a>
#### symbolTree.remove(removeObject) ⇒ <code>Object</code>
Remove the object from this tree.
Has no effect if already removed.
* `O(1)`
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
**Returns**: <code>Object</code> - removeObject
| Param | Type |
| --- | --- |
| removeObject | <code>Object</code> |
<a name="module_symbol-tree--SymbolTree+insertBefore"></a>
#### symbolTree.insertBefore(referenceObject, newObject) ⇒ <code>Object</code>
Insert the given object before the reference object.
`newObject` is now the previous sibling of `referenceObject`.
* `O(1)`
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
**Returns**: <code>Object</code> - newObject
**Throws**:
- <code>Error</code> If the newObject is already present in this SymbolTree
| Param | Type |
| --- | --- |
| referenceObject | <code>Object</code> |
| newObject | <code>Object</code> |
<a name="module_symbol-tree--SymbolTree+insertAfter"></a>
#### symbolTree.insertAfter(referenceObject, newObject) ⇒ <code>Object</code>
Insert the given object after the reference object.
`newObject` is now the next sibling of `referenceObject`.
* `O(1)`
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
**Returns**: <code>Object</code> - newObject
**Throws**:
- <code>Error</code> If the newObject is already present in this SymbolTree
| Param | Type |
| --- | --- |
| referenceObject | <code>Object</code> |
| newObject | <code>Object</code> |
<a name="module_symbol-tree--SymbolTree+prependChild"></a>
#### symbolTree.prependChild(referenceObject, newObject) ⇒ <code>Object</code>
Insert the given object as the first child of the given reference object.
`newObject` is now the first child of `referenceObject`.
* `O(1)`
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
**Returns**: <code>Object</code> - newObject
**Throws**:
- <code>Error</code> If the newObject is already present in this SymbolTree
| Param | Type |
| --- | --- |
| referenceObject | <code>Object</code> |
| newObject | <code>Object</code> |
<a name="module_symbol-tree--SymbolTree+appendChild"></a>
#### symbolTree.appendChild(referenceObject, newObject) ⇒ <code>Object</code>
Insert the given object as the last child of the given reference object.
`newObject` is now the last child of `referenceObject`.
* `O(1)`
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
**Returns**: <code>Object</code> - newObject
**Throws**:
- <code>Error</code> If the newObject is already present in this SymbolTree
| Param | Type |
| --- | --- |
| referenceObject | <code>Object</code> |
| newObject | <code>Object</code> |
| hhkaos/awesome-arcgis | node_modules/symbol-tree/README.md | Markdown | gpl-3.0 | 24,982 |
/**
* This file is part of Hercules.
* http://herc.ws - http://github.com/HerculesWS/Hercules
*
* Copyright (C) 2012-2015 Hercules Dev Team
* Copyright (C) Athena Dev Teams
*
* Hercules is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#define HERCULES_CORE
#include "conf.h"
#include "common/showmsg.h" // ShowError
#include "common/strlib.h" // safestrncpy
#include "common/utils.h" // exists
#include <libconfig/libconfig.h>
/* interface source */
struct libconfig_interface libconfig_s;
struct libconfig_interface *libconfig;
/**
* Initializes 'config' and loads a configuration file.
*
* Shows error and destroys 'config' in case of failure.
* It is the caller's care to destroy 'config' in case of success.
*
* @param config The config file to initialize.
* @param config_filename The file to read.
*
* @retval CONFIG_TRUE in case of success.
* @retval CONFIG_FALSE in case of failure.
*/
int config_load_file(struct config_t *config, const char *config_filename)
{
libconfig->init(config);
if (!exists(config_filename)) {
ShowError("Unable to load '%s' - File not found\n", config_filename);
return CONFIG_FALSE;
}
if (libconfig->read_file_src(config, config_filename) != CONFIG_TRUE) {
ShowError("%s:%d - %s\n", config_error_file(config),
config_error_line(config), config_error_text(config));
libconfig->destroy(config);
return CONFIG_FALSE;
}
return CONFIG_TRUE;
}
//
// Functions to copy settings from libconfig/contrib
//
void config_setting_copy_simple(struct config_setting_t *parent, const struct config_setting_t *src)
{
if (config_setting_is_aggregate(src)) {
libconfig->setting_copy_aggregate(parent, src);
} else {
struct config_setting_t *set;
if( libconfig->setting_get_member(parent, config_setting_name(src)) != NULL )
return;
if ((set = libconfig->setting_add(parent, config_setting_name(src), config_setting_type(src))) == NULL)
return;
if (CONFIG_TYPE_INT == config_setting_type(src)) {
libconfig->setting_set_int(set, libconfig->setting_get_int(src));
libconfig->setting_set_format(set, src->format);
} else if (CONFIG_TYPE_INT64 == config_setting_type(src)) {
libconfig->setting_set_int64(set, libconfig->setting_get_int64(src));
libconfig->setting_set_format(set, src->format);
} else if (CONFIG_TYPE_FLOAT == config_setting_type(src)) {
libconfig->setting_set_float(set, libconfig->setting_get_float(src));
} else if (CONFIG_TYPE_STRING == config_setting_type(src)) {
libconfig->setting_set_string(set, libconfig->setting_get_string(src));
} else if (CONFIG_TYPE_BOOL == config_setting_type(src)) {
libconfig->setting_set_bool(set, libconfig->setting_get_bool(src));
}
}
}
void config_setting_copy_elem(struct config_setting_t *parent, const struct config_setting_t *src)
{
struct config_setting_t *set = NULL;
if (config_setting_is_aggregate(src))
libconfig->setting_copy_aggregate(parent, src);
else if (CONFIG_TYPE_INT == config_setting_type(src)) {
set = libconfig->setting_set_int_elem(parent, -1, libconfig->setting_get_int(src));
libconfig->setting_set_format(set, src->format);
} else if (CONFIG_TYPE_INT64 == config_setting_type(src)) {
set = libconfig->setting_set_int64_elem(parent, -1, libconfig->setting_get_int64(src));
libconfig->setting_set_format(set, src->format);
} else if (CONFIG_TYPE_FLOAT == config_setting_type(src)) {
libconfig->setting_set_float_elem(parent, -1, libconfig->setting_get_float(src));
} else if (CONFIG_TYPE_STRING == config_setting_type(src)) {
libconfig->setting_set_string_elem(parent, -1, libconfig->setting_get_string(src));
} else if (CONFIG_TYPE_BOOL == config_setting_type(src)) {
libconfig->setting_set_bool_elem(parent, -1, libconfig->setting_get_bool(src));
}
}
void config_setting_copy_aggregate(struct config_setting_t *parent, const struct config_setting_t *src)
{
struct config_setting_t *newAgg;
int i, n;
if( libconfig->setting_get_member(parent, config_setting_name(src)) != NULL )
return;
newAgg = libconfig->setting_add(parent, config_setting_name(src), config_setting_type(src));
if (newAgg == NULL)
return;
n = config_setting_length(src);
for (i = 0; i < n; i++) {
if (config_setting_is_group(src)) {
libconfig->setting_copy_simple(newAgg, libconfig->setting_get_elem(src, i));
} else {
libconfig->setting_copy_elem(newAgg, libconfig->setting_get_elem(src, i));
}
}
}
int config_setting_copy(struct config_setting_t *parent, const struct config_setting_t *src)
{
if (!config_setting_is_group(parent) && !config_setting_is_list(parent))
return CONFIG_FALSE;
if (config_setting_is_aggregate(src)) {
libconfig->setting_copy_aggregate(parent, src);
} else {
libconfig->setting_copy_simple(parent, src);
}
return CONFIG_TRUE;
}
/**
* Converts the value of a setting that is type CONFIG_TYPE_BOOL to bool.
*
* @param setting The setting to read.
*
* @return The converted value.
* @retval false in case of failure.
*/
bool config_setting_get_bool_real(const struct config_setting_t *setting)
{
if (setting == NULL || setting->type != CONFIG_TYPE_BOOL)
return false;
return setting->value.ival ? true : false;
}
/**
* Same as config_setting_lookup_bool, but uses bool instead of int.
*
* @param[in] setting The setting to read.
* @param[in] name The setting name to lookup.
* @param[out] value The output value.
*
* @retval CONFIG_TRUE in case of success.
* @retval CONFIG_FALSE in case of failure.
*/
int config_setting_lookup_bool_real(const struct config_setting_t *setting, const char *name, bool *value)
{
struct config_setting_t *member = config_setting_get_member(setting, name);
if (!member)
return CONFIG_FALSE;
if (config_setting_type(member) != CONFIG_TYPE_BOOL)
return CONFIG_FALSE;
*value = config_setting_get_bool_real(member);
return CONFIG_TRUE;
}
/**
* Converts and returns a configuration that is CONFIG_TYPE_INT to unsigned int (uint32).
*
* @param setting The setting to read.
*
* @return The converted value.
* @retval 0 in case of failure.
*/
uint32 config_setting_get_uint32(const struct config_setting_t *setting)
{
if (setting == NULL || setting->type != CONFIG_TYPE_INT)
return 0;
if (setting->value.ival < 0)
return 0;
return (uint32)setting->value.ival;
}
/**
* Looks up a configuration entry of type CONFIG_TYPE_INT and reads it as uint32.
*
* @param[in] setting The setting to read.
* @param[in] name The setting name to lookup.
* @param[out] value The output value.
*
* @retval CONFIG_TRUE in case of success.
* @retval CONFIG_FALSE in case of failure.
*/
int config_setting_lookup_uint32(const struct config_setting_t *setting, const char *name, uint32 *value)
{
struct config_setting_t *member = config_setting_get_member(setting, name);
if (!member)
return CONFIG_FALSE;
if (config_setting_type(member) != CONFIG_TYPE_INT)
return CONFIG_FALSE;
*value = config_setting_get_uint32(member);
return CONFIG_TRUE;
}
/**
* Converts and returns a configuration that is CONFIG_TYPE_INT to uint16
*
* @param setting The setting to read.
*
* @return The converted value.
* @retval 0 in case of failure.
*/
uint16 config_setting_get_uint16(const struct config_setting_t *setting)
{
if (setting == NULL || setting->type != CONFIG_TYPE_INT)
return 0;
if (setting->value.ival > UINT16_MAX)
return UINT16_MAX;
if (setting->value.ival < UINT16_MIN)
return UINT16_MIN;
return (uint16)setting->value.ival;
}
/**
* Looks up a configuration entry of type CONFIG_TYPE_INT and reads it as uint16.
*
* @param[in] setting The setting to read.
* @param[in] name The setting name to lookup.
* @param[out] value The output value.
*
* @retval CONFIG_TRUE in case of success.
* @retval CONFIG_FALSE in case of failure.
*/
int config_setting_lookup_uint16(const struct config_setting_t *setting, const char *name, uint16 *value)
{
struct config_setting_t *member = config_setting_get_member(setting, name);
if (!member)
return CONFIG_FALSE;
if (config_setting_type(member) != CONFIG_TYPE_INT)
return CONFIG_FALSE;
*value = config_setting_get_uint16(member);
return CONFIG_TRUE;
}
/**
* Converts and returns a configuration that is CONFIG_TYPE_INT to int16
*
* @param setting The setting to read.
*
* @return The converted value.
* @retval 0 in case of failure.
*/
int16 config_setting_get_int16(const struct config_setting_t *setting)
{
if (setting == NULL || setting->type != CONFIG_TYPE_INT)
return 0;
if (setting->value.ival > INT16_MAX)
return INT16_MAX;
if (setting->value.ival < INT16_MIN)
return INT16_MIN;
return (int16)setting->value.ival;
}
/**
* Looks up a configuration entry of type CONFIG_TYPE_INT and reads it as int16.
*
* @param[in] setting The setting to read.
* @param[in] name The setting name to lookup.
* @param[out] value The output value.
*
* @retval CONFIG_TRUE in case of success.
* @retval CONFIG_FALSE in case of failure.
*/
int config_setting_lookup_int16(const struct config_setting_t *setting, const char *name, int16 *value)
{
struct config_setting_t *member = config_setting_get_member(setting, name);
if (!member)
return CONFIG_FALSE;
if (config_setting_type(member) != CONFIG_TYPE_INT)
return CONFIG_FALSE;
*value = config_setting_get_int16(member);
return CONFIG_TRUE;
}
/**
* Looks up a configuration entry of type CONFIG_TYPE_STRING inside a struct config_setting_t and copies it into a (non-const) char buffer.
*
* @param[in] setting The setting to read.
* @param[in] name The setting name to lookup.
* @param[out] out The output buffer.
* @param[in] out_size The size of the output buffer.
*
* @retval CONFIG_TRUE in case of success.
* @retval CONFIG_FALSE in case of failure.
*/
int config_setting_lookup_mutable_string(const struct config_setting_t *setting, const char *name, char *out, size_t out_size)
{
const char *str = NULL;
if (libconfig->setting_lookup_string(setting, name, &str) == CONFIG_TRUE) {
safestrncpy(out, str, out_size);
return CONFIG_TRUE;
}
return CONFIG_FALSE;
}
/**
* Looks up a configuration entry of type CONFIG_TYPE_STRING inside a struct config_t and copies it into a (non-const) char buffer.
*
* @param[in] config The configuration to read.
* @param[in] name The setting name to lookup.
* @param[out] out The output buffer.
* @param[in] out_size The size of the output buffer.
*
* @retval CONFIG_TRUE in case of success.
* @retval CONFIG_FALSE in case of failure.
*/
int config_lookup_mutable_string(const struct config_t *config, const char *name, char *out, size_t out_size)
{
const char *str = NULL;
if (libconfig->lookup_string(config, name, &str) == CONFIG_TRUE) {
safestrncpy(out, str, out_size);
return CONFIG_TRUE;
}
return CONFIG_FALSE;
}
void libconfig_defaults(void) {
libconfig = &libconfig_s;
libconfig->read = config_read;
libconfig->write = config_write;
/* */
libconfig->set_options = config_set_options;
libconfig->get_options = config_get_options;
/* */
libconfig->read_string = config_read_string;
libconfig->read_file_src = config_read_file;
libconfig->write_file = config_write_file;
/* */
libconfig->set_destructor = config_set_destructor;
libconfig->set_include_dir = config_set_include_dir;
/* */
libconfig->init = config_init;
libconfig->destroy = config_destroy;
/* */
libconfig->setting_get_int = config_setting_get_int;
libconfig->setting_get_int64 = config_setting_get_int64;
libconfig->setting_get_float = config_setting_get_float;
libconfig->setting_get_bool = config_setting_get_bool;
libconfig->setting_get_string = config_setting_get_string;
/* */
libconfig->setting_lookup = config_setting_lookup;
libconfig->setting_lookup_int = config_setting_lookup_int;
libconfig->setting_lookup_int64 = config_setting_lookup_int64;
libconfig->setting_lookup_float = config_setting_lookup_float;
libconfig->setting_lookup_bool = config_setting_lookup_bool;
libconfig->setting_lookup_string = config_setting_lookup_string;
/* */
libconfig->setting_set_int = config_setting_set_int;
libconfig->setting_set_int64 = config_setting_set_int64;
libconfig->setting_set_float = config_setting_set_float;
libconfig->setting_set_bool = config_setting_set_bool;
libconfig->setting_set_string = config_setting_set_string;
/* */
libconfig->setting_set_format = config_setting_set_format;
libconfig->setting_get_format = config_setting_get_format;
/* */
libconfig->setting_get_int_elem = config_setting_get_int_elem;
libconfig->setting_get_int64_elem = config_setting_get_int64_elem;
libconfig->setting_get_float_elem = config_setting_get_float_elem;
libconfig->setting_get_bool_elem = config_setting_get_bool_elem;
libconfig->setting_get_string_elem = config_setting_get_string_elem;
/* */
libconfig->setting_set_int_elem = config_setting_set_int_elem;
libconfig->setting_set_int64_elem = config_setting_set_int64_elem;
libconfig->setting_set_float_elem = config_setting_set_float_elem;
libconfig->setting_set_bool_elem = config_setting_set_bool_elem;
libconfig->setting_set_string_elem = config_setting_set_string_elem;
/* */
libconfig->setting_index = config_setting_index;
libconfig->setting_length = config_setting_length;
/* */
libconfig->setting_get_elem = config_setting_get_elem;
libconfig->setting_get_member = config_setting_get_member;
/* */
libconfig->setting_add = config_setting_add;
libconfig->setting_remove = config_setting_remove;
libconfig->setting_remove_elem = config_setting_remove_elem;
/* */
libconfig->setting_set_hook = config_setting_set_hook;
/* */
libconfig->lookup = config_lookup;
/* */
libconfig->lookup_int = config_lookup_int;
libconfig->lookup_int64 = config_lookup_int64;
libconfig->lookup_float = config_lookup_float;
libconfig->lookup_bool = config_lookup_bool;
libconfig->lookup_string = config_lookup_string;
/* those are custom and are from src/common/conf.c */
libconfig->load_file = config_load_file;
libconfig->setting_copy_simple = config_setting_copy_simple;
libconfig->setting_copy_elem = config_setting_copy_elem;
libconfig->setting_copy_aggregate = config_setting_copy_aggregate;
libconfig->setting_copy = config_setting_copy;
/* Functions to get different types */
libconfig->setting_get_bool_real = config_setting_get_bool_real;
libconfig->setting_get_uint32 = config_setting_get_uint32;
libconfig->setting_get_uint16 = config_setting_get_uint16;
libconfig->setting_get_int16 = config_setting_get_int16;
/* Functions to lookup different types */
libconfig->setting_lookup_int16 = config_setting_lookup_int16;
libconfig->setting_lookup_bool_real = config_setting_lookup_bool_real;
libconfig->setting_lookup_uint32 = config_setting_lookup_uint32;
libconfig->setting_lookup_uint16 = config_setting_lookup_uint16;
libconfig->setting_lookup_mutable_string = config_setting_lookup_mutable_string;
libconfig->lookup_mutable_string = config_lookup_mutable_string;
}
| dor003/Herc | src/common/conf.c | C | gpl-3.0 | 15,602 |
<?php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\PageCache\Test\Unit\Model;
use Magento\PageCache\Model\Config;
class ConfigTest extends \PHPUnit_Framework_TestCase
{
/**
* @var \Magento\PageCache\Model\Config
*/
protected $_model;
/**
* @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\Config\ScopeConfigInterface
*/
protected $_coreConfigMock;
/**
* @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\Cache\StateInterface
*/
protected $_cacheState;
/**
* @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Module\Dir\Reader
*/
protected $moduleReader;
/**
* setUp all mocks and data function
*/
protected function setUp()
{
$readFactoryMock = $this->getMock('Magento\Framework\Filesystem\Directory\ReadFactory', [], [], '', false);
$this->_coreConfigMock = $this->getMock('Magento\Framework\App\Config\ScopeConfigInterface');
$this->_cacheState = $this->getMockForAbstractClass('Magento\Framework\App\Cache\StateInterface');
$modulesDirectoryMock = $this->getMock(
'Magento\Framework\Filesystem\Directory\Write',
[],
[],
'',
false
);
$readFactoryMock->expects(
$this->any()
)->method(
'create'
)->will(
$this->returnValue($modulesDirectoryMock)
);
$modulesDirectoryMock->expects(
$this->any()
)->method(
'readFile'
)->will(
$this->returnValue(file_get_contents(__DIR__ . '/_files/test.vcl'))
);
$this->_coreConfigMock->expects(
$this->any()
)->method(
'getValue'
)->will(
$this->returnValueMap(
[
[
\Magento\PageCache\Model\Config::XML_VARNISH_PAGECACHE_BACKEND_HOST,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE,
null,
'example.com',
],
[
\Magento\PageCache\Model\Config::XML_VARNISH_PAGECACHE_BACKEND_PORT,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE,
null,
'8080'
],
[
\Magento\PageCache\Model\Config::XML_VARNISH_PAGECACHE_ACCESS_LIST,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE,
null,
'127.0.0.1, 192.168.0.1,127.0.0.2'
],
[
\Magento\PageCache\Model\Config::XML_VARNISH_PAGECACHE_DESIGN_THEME_REGEX,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE,
null,
serialize([['regexp' => '(?i)pattern', 'value' => 'value_for_pattern']])
],
]
)
);
$this->moduleReader = $this->getMock('Magento\Framework\Module\Dir\Reader', [], [], '', false);
$this->_model = new \Magento\PageCache\Model\Config(
$readFactoryMock,
$this->_coreConfigMock,
$this->_cacheState,
$this->moduleReader
);
}
/**
* test for getVcl method
*/
public function testGetVcl()
{
$this->moduleReader->expects($this->once())
->method('getModuleDir')
->willReturn('/magento/app/code/Magento/PageCache');
$test = $this->_model->getVclFile(Config::VARNISH_3_CONFIGURATION_PATH);
$this->assertEquals(file_get_contents(__DIR__ . '/_files/result.vcl'), $test);
}
public function testGetTll()
{
$this->_coreConfigMock->expects($this->once())->method('getValue')->with(Config::XML_PAGECACHE_TTL);
$this->_model->getTtl();
}
/**
* Whether a cache type is enabled
*/
public function testIsEnabled()
{
$this->_cacheState->expects($this->at(0))
->method('isEnabled')
->with(\Magento\PageCache\Model\Cache\Type::TYPE_IDENTIFIER)
->will($this->returnValue(true));
$this->_cacheState->expects($this->at(1))
->method('isEnabled')
->with(\Magento\PageCache\Model\Cache\Type::TYPE_IDENTIFIER)
->will($this->returnValue(false));
$this->assertTrue($this->_model->isEnabled());
$this->assertFalse($this->_model->isEnabled());
}
}
| rajmahesh/magento2-master | vendor/magento/module-page-cache/Test/Unit/Model/ConfigTest.php | PHP | gpl-3.0 | 4,719 |
#ifndef _INTERNAL_H
#define _INTERNAL_H
#include "pluginmain.h"
//menu identifiers
#define MENU_ANALYSIS 0
//functions
void internalInit(PLUG_INITSTRUCT* initStruct);
void internalStop();
void internalSetup();
#endif // _TEST_H
| x64dbg/StaticAnalysis | src/internal.h | C | gpl-3.0 | 233 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_151) on Tue Jan 16 16:58:40 CET 2018 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Interface org.openbase.bco.dal.lib.layer.service.stream.StreamService (BCO DAL 1.5-SNAPSHOT API)</title>
<meta name="date" content="2018-01-16">
<link rel="stylesheet" type="text/css" href="../../../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Interface org.openbase.bco.dal.lib.layer.service.stream.StreamService (BCO DAL 1.5-SNAPSHOT API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../../../org/openbase/bco/dal/lib/layer/service/stream/StreamService.html" title="interface in org.openbase.bco.dal.lib.layer.service.stream">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../../../index.html?org/openbase/bco/dal/lib/layer/service/stream/class-use/StreamService.html" target="_top">Frames</a></li>
<li><a href="StreamService.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Interface org.openbase.bco.dal.lib.layer.service.stream.StreamService" class="title">Uses of Interface<br>org.openbase.bco.dal.lib.layer.service.stream.StreamService</h2>
</div>
<div class="classUseContainer">No usage of org.openbase.bco.dal.lib.layer.service.stream.StreamService</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../../../org/openbase/bco/dal/lib/layer/service/stream/StreamService.html" title="interface in org.openbase.bco.dal.lib.layer.service.stream">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../../../index.html?org/openbase/bco/dal/lib/layer/service/stream/class-use/StreamService.html" target="_top">Frames</a></li>
<li><a href="StreamService.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2014–2018 <a href="https://github.com/openbase">openbase.org</a>. All rights reserved.</small></p>
</body>
</html>
| DivineCooperation/bco.dal | docs/apidocs/org/openbase/bco/dal/lib/layer/service/stream/class-use/StreamService.html | HTML | gpl-3.0 | 5,099 |
<a href="http://wikipedia.org">Wikipedia</a> | vidageek/games | games/html/src/main/resources/html/wikipedia.html | HTML | gpl-3.0 | 44 |
/*
dev: Mickeymouse, Moutarde and Nepta
manager: Word
Copyright © 2011
You should have received a copy of the
GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#include "bullet.h"
/**
* \fn Bullet* createBullet(Tower *tower)
* \brief create a new bullet
* a new bullet which doesn't have
* \param tower the tower the bullet belong to
*/
Bullet* createBullet(Tower *tower){
Bullet *bullet = malloc(sizeof (Bullet));
bullet->type = tower->type->typeBul;
bullet->position = searchEnemy(tower);
return bullet;
}
/**
* \fn void drawBullet(Bullet *bullet)
* \brief draw a bullet
*
* \param bullet a bullet to draw
*/
void drawBullet(Bullet *bullet){
SDL_Rect position;
position.x = 280; //=xx
position.y = 280; //=yy
blitToViewport(_viewport, bullet->type->image, NULL, &position);
}
/**
* \fn void animateBullet(Bullet *bullet)
* \brief move the bullet to an enemy and draw it
* Depreciated, recode your own function!
* \param bullet the bullet to animate
*/
void animateBullet(Bullet *bullet){
/* if(!(bullet->position->xx == bullet->position->x && bullet->position->yy == bullet->position->y)){*/
drawBullet(bullet);
/* }*/
}
| ycaihua/Tower-Defense-1 | src/tower/bullet.c | C | gpl-3.0 | 1,216 |
<?php
/**
* Nooku Platform - http://www.nooku.org/platform
*
* @copyright Copyright (C) 2007 - 2014 Johan Janssens and Timble CVBA. (http://www.timble.net)
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link https://github.com/nooku/nooku-platform for the canonical source repository
*/
namespace Nooku\Library;
/**
* Event Mixin
*
* Class can be used as a mixin in classes that want to implement a an event publisher and allow adding and removing
* event listeners and subscribers.
*
* @author Johan Janssens <http://github.com/johanjanssens>
* @package Nooku\Library\Event
*/
class EventMixin extends ObjectMixinAbstract implements EventMixinInterface
{
/**
* Event publisher object
*
* @var EventPublisherInterface
*/
private $__event_publisher;
/**
* List of event subscribers
*
* Associative array of event subscribers, where key holds the subscriber identifier string
* and the value is an identifier object.
*
* @var array
*/
private $__event_subscribers = array();
/**
* Object constructor
*
* @param ObjectConfig $config An optional ObjectConfig object with configuration options
* @throws \InvalidArgumentException
*/
public function __construct(ObjectConfig $config)
{
parent::__construct($config);
if (is_null($config->event_publisher)) {
throw new \InvalidArgumentException('event_publisher [EventPublisherInterface] config option is required');
}
//Set the event dispatcher
$this->__event_publisher = $config->event_publisher;
//Add the event listeners
foreach ($config->event_listeners as $event => $listener) {
$this->addEventListener($event, $listener);
}
//Add the event subscribers
$subscribers = (array) ObjectConfig::unbox($config->event_subscribers);
foreach ($subscribers as $key => $value)
{
if (is_numeric($key)) {
$this->addEventSubscriber($value);
} else {
$this->addEventSubscriber($key, $value);
}
}
}
/**
* Initializes the options for the object
*
* Called from {@link __construct()} as a first step of object instantiation.
*
* @param ObjectConfig $config An optional ObjectConfig object with configuration options
* @return void
*/
protected function _initialize(ObjectConfig $config)
{
$config->append(array(
'event_publisher' => 'event.publisher',
'event_subscribers' => array(),
'event_listeners' => array(),
));
parent::_initialize($config);
}
/**
* Publish an event by calling all listeners that have registered to receive it.
*
* @param string|EventInterface $event The event name or a KEventInterface object
* @param array|\Traversable|EventInterface $attributes An associative array, an object implementing the
* EventInterface or a Traversable object
* @param mixed $target The event target
* @throws \InvalidArgumentException If the event is not a string or does not implement the KEventInterface
* @return null|EventInterface Returns the event object. If the chain is not enabled will return NULL.
*/
public function publishEvent($event, $attributes = array(), $target = null)
{
return $this->getEventPublisher()->publishEvent($event, $attributes, $target);
}
/**
* Get the event publisher
*
* @throws \UnexpectedValueException
* @return EventPublisherInterface
*/
public function getEventPublisher()
{
if(!$this->__event_publisher instanceof EventPublisherInterface)
{
$this->__event_publisher = $this->getObject($this->__event_publisher);
if(!$this->__event_publisher instanceof EventPublisherInterface)
{
throw new \UnexpectedValueException(
'EventPublisher: '.get_class($this->__event_publisher).' does not implement KEventPublisherInterface'
);
}
}
return $this->__event_publisher;
}
/**
* Set the event publisher
*
* @param EventPublisherInterface $publisher An event publisher object
* @return ObjectInterface The mixer
*/
public function setEventPublisher(EventPublisherInterface $publisher)
{
$this->__event_publisher = $publisher;
return $this->getMixer();
}
/**
* Add an event listener
*
* @param string|EventInterface $event The event name or a KEventInterface object
* @param callable $listener The listener
* @param integer $priority The event priority, usually between 1 (high priority) and 5 (lowest),
* default is 3 (normal)
* @throws \InvalidArgumentException If the listener is not a callable
* @throws \InvalidArgumentException If the event is not a string or does not implement the KEventInterface
* @return ObjectInterface The mixer
*/
public function addEventListener($event, $listener, $priority = EventInterface::PRIORITY_NORMAL)
{
$this->getEventPublisher()->addListener($event, $listener, $priority);
return $this->getMixer();
}
/**
* Remove an event listener
*
* @param string|EventInterface $event The event name or a KEventInterface object
* @param callable $listener The listener
* @throws \InvalidArgumentException If the listener is not a callable
* @throws \InvalidArgumentException If the event is not a string or does not implement the KEventInterface
* @return ObjectInterface The mixer
*/
public function removeEventListener($event, $listener)
{
$this->getEventPublisher()->removeListener($event, $listener);
return $this->getMixer();
}
/**
* Add an event subscriber
*
* @param mixed $subscriber An object that implements ObjectInterface, ObjectIdentifier object
* or valid identifier string
* @param array $config An optional associative array of configuration options
* @return ObjectInterface The mixer
*/
public function addEventSubscriber($subscriber, $config = array())
{
if (!($subscriber instanceof EventSubscriberInterface)) {
$subscriber = $this->getEventSubscriber($subscriber, $config);
}
$subscriber->subscribe($this->getEventPublisher());
return $this;
}
/**
* Remove an event subscriber
*
* @param EventSubscriberInterface $subscriber An event subscriber
* @return ObjectInterface The mixer
*/
public function removeEventSubscriber(EventSubscriberInterface $subscriber)
{
$subscriber->unsubscribe($this->getEventPublisher());
return $this->getMixer();
}
/**
* Get a event subscriber by identifier
*
* The subscriber will be created if does not exist yet, otherwise the existing subscriber will be returned.
*
* @param mixed $subscriber An object that implements ObjectInterface, ObjectIdentifier object
* or valid identifier string
* @param array $config An optional associative array of configuration settings
* @throws \UnexpectedValueException If the subscriber is not implementing the EventSubscriberInterface
* @return EventSubscriberInterface
*/
public function getEventSubscriber($subscriber, $config = array())
{
if (!($subscriber instanceof ObjectIdentifier))
{
//Create the complete identifier if a partial identifier was passed
if (is_string($subscriber) && strpos($subscriber, '.') === false)
{
$identifier = $this->getIdentifier()->toArray();
$identifier['path'] = array('event', 'subscriber');
$identifier['name'] = $subscriber;
$identifier = $this->getIdentifier($identifier);
}
else $identifier = $this->getIdentifier($subscriber);
}
else $identifier = $subscriber;
if (!isset($this->__event_subscribers[(string)$identifier]))
{
$subscriber = $this->getObject($identifier, $config);
//Check the event subscriber interface
if (!($subscriber instanceof EventSubscriberInterface))
{
throw new \UnexpectedValueException(
"Event Subscriber $identifier does not implement KEventSubscriberInterface"
);
}
}
else $subscriber = $this->__event_subscribers[(string)$identifier];
return $subscriber;
}
/**
* Gets the event subscribers
*
* @return array An array of event subscribers
*/
public function getEventSubscribers()
{
return array_values($this->__event_subscribers);
}
} | babsgosgens/nooku-ember-example-theme | library/event/mixin.php | PHP | gpl-3.0 | 9,285 |
require 'nokogiri'
require 'digest'
class XMLReader
# uses nokogiri to extract all system information from scenario.xml
# This includes module filters, which are module objects that contain filters for selecting
# from the actual modules that are available
# @return [Array] Array containing Systems objects
def self.parse_doc(file_path, schema, type)
doc = nil
begin
doc = Nokogiri::XML(File.read(file_path))
rescue
Print.err "Failed to read #{type} configuration file (#{file_path})"
exit
end
validate_xml(doc, file_path, schema, type)
# remove xml namespaces for ease of processing
doc.remove_namespaces!
end
def self.validate_xml(doc, file_path, schema, type)
# validate XML against schema
begin
xsd = Nokogiri::XML::Schema(File.open(schema))
xsd.validate(doc).each do |error|
Print.err "Error in scenario configuration file (#{scenario_file}):"
Print.err " #{error.line}: #{error.message}"
exit
end
rescue Exception => e
Print.err "Failed to validate #{type} xml file (#{file_path}): against schema (#{schema})"
Print.err e.message
exit
end
end
def self.read_attributes(node)
attributes = {}
node.xpath('@*').each do |attr|
attributes["#{attr.name}"] = [attr.text] unless attr.text.nil? || attr.text == ''
end
attributes
end
end | cliffe/SecGen | lib/readers/xml_reader.rb | Ruby | gpl-3.0 | 1,407 |
<?php
// Heading
$_['heading_title'] = 'Blog Viewed Report';
// Text
$_['text_success'] = 'Success: You have modified the blog viewed report!';
// Column
$_['column_article_name'] = 'Article Name';
$_['column_author_name'] = 'Author Name';
$_['column_viewed'] = 'Viewed';
$_['column_percent'] = 'Percent';
// Entry
$_['entry_date_start'] = 'Date Start:';
$_['entry_date_end'] = 'Date End:';
?> | dhananjaypingale2112/vc_fitness | upload/aplogin/language/english/simple_blog/report.php | PHP | gpl-3.0 | 415 |
//
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
#import "OWSViewController.h"
@class TSThread;
NS_ASSUME_NONNULL_BEGIN
@protocol SelectThreadViewControllerDelegate <NSObject>
- (void)threadWasSelected:(TSThread *)thread;
- (BOOL)canSelectBlockedContact;
- (nullable UIView *)createHeaderWithSearchBar:(UISearchBar *)searchBar;
@end
#pragma mark -
// A base class for views used to pick a single signal user, either by
// entering a phone number or picking from your contacts.
@interface SelectThreadViewController : OWSViewController
@property (nonatomic, weak) id<SelectThreadViewControllerDelegate> delegate;
@end
NS_ASSUME_NONNULL_END
| jaropawlak/Signal-iOS | Signal/src/ViewControllers/SelectThreadViewController.h | C | gpl-3.0 | 675 |
<?php
namespace App\itnovum\openITCOCKPIT\Core\AngularJS;
class PdfAssets {
/**
* @return array
*/
static public function getCssFiles() {
return [
'/node_modules/bootstrap/dist/css/bootstrap.css',
'/smartadmin4/dist/css/vendors.bundle.css',
'/smartadmin4/dist/css/app.bundle.css',
'/node_modules/@fortawesome/fontawesome-free/css/all.css',
'/css/openitcockpit-colors.css',
'/css/openitcockpit-utils.css',
'/css/openitcockpit.css',
'/css/openitcockpit-pdf.css',
];
}
}
| trevrobwhite/openITCOCKPIT | src/itnovum/openITCOCKPIT/Core/AngularJS/PdfAssets.php | PHP | gpl-3.0 | 608 |
#!/usr/bin/perl
package Koha::Reporting::Report::Grouping::DateLastLoaned;
use Modern::Perl;
use Moose;
use Data::Dumper;
use C4::Context;
extends 'Koha::Reporting::Report::Grouping::Abstract';
sub BUILD {
my $self = shift;
$self->setName('datelastborrowed');
$self->setAlias('Date last borrowed');
$self->setDescription('Date last borrowed');
$self->setDimension('item');
$self->setField('datelastborrowed');
}
1;
| KohaSuomi/kohasuomi | Koha/Reporting/Report/Grouping/DateLastLoaned.pm | Perl | gpl-3.0 | 443 |
using LeagueSharp.Common;
using SharpDX;
using EloBuddy;
using LeagueSharp.Common;
namespace e.Motion_Katarina
{
public class Dagger
{
private static readonly int DELAY = 0;
private static readonly int MAXACTIVETIME = 4000;
private bool Destructable;
private Vector3 Position;
private int Time;
public Dagger(Vector3 position)
{
Time = Utils.TickCount + DELAY;
this.Position = position;
}
//Object Pooling Pseudo-Constructor
public void Recreate(Vector3 position)
{
Destructable = false;
Time = Utils.TickCount + DELAY;
this.Position = position;
}
public Vector3 GetPosition()
{
return Position;
}
public bool IsDead()
{
return Destructable;
}
public void MarkDead()
{
Destructable = true;
}
public bool IsActive()
{
return Utils.TickCount >= Time;
}
public void CheckForUpdate()
{
if(Time + MAXACTIVETIME <= Utils.TickCount)
{
Destructable = true;
return;
}
}
}
}
| saophaisau/port | Core/Champion Ports/Katarina/e.Motion Katarina/Dagger.cs | C# | gpl-3.0 | 1,294 |
package org.obiba.mica.search.aggregations;
import org.obiba.mica.micaConfig.service.helper.AggregationMetaDataProvider;
import org.obiba.mica.micaConfig.service.helper.PopulationIdAggregationMetaDataHelper;
import org.springframework.stereotype.Component;
import javax.inject.Inject;
import java.util.Map;
@Component
public class PopulationAggregationMetaDataProvider implements AggregationMetaDataProvider {
private static final String AGGREGATION_NAME = "populationId";
private final PopulationIdAggregationMetaDataHelper helper;
@Inject
public PopulationAggregationMetaDataProvider(PopulationIdAggregationMetaDataHelper helper) {
this.helper = helper;
}
@Override
public MetaData getMetadata(String aggregation, String termKey, String locale) {
Map<String, LocalizedMetaData> dataMap = helper.getPopulations();
return AGGREGATION_NAME.equals(aggregation) && dataMap.containsKey(termKey) ?
MetaData.newBuilder()
.title(dataMap.get(termKey).getTitle().get(locale))
.description(dataMap.get(termKey).getDescription().get(locale))
.className(dataMap.get(termKey).getClassName())
.build() : null;
}
@Override
public boolean containsAggregation(String aggregation) {
return AGGREGATION_NAME.equals(aggregation);
}
@Override
public void refresh() {
}
}
| obiba/mica2 | mica-search/src/main/java/org/obiba/mica/search/aggregations/PopulationAggregationMetaDataProvider.java | Java | gpl-3.0 | 1,342 |
<p style="text-align:justify">word0<strong> short term debt securities</strong> word1 word2 word3 <strong>december 21, 2010.</strong></p><p><br /></p> | ernestbuffington/PHP-Nuke-Titanium | includes/wysiwyg/ckeditor/tests/plugins/pastefromword/generated/_fixtures/Tickets/6751disappearing_spaces_example2/expected.html | HTML | gpl-3.0 | 150 |
/**
* This file is part of d:swarm graph extension.
*
* d:swarm graph extension is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* d:swarm graph extension is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with d:swarm graph extension. If not, see <http://www.gnu.org/licenses/>.
*/
package org.dswarm.graph.delta.match.model.util;
import java.util.Collection;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import org.dswarm.graph.delta.match.model.CSEntity;
import org.dswarm.graph.delta.match.model.ValueEntity;
/**
* @author tgaengler
*/
public final class CSEntityUtil {
public static Optional<? extends Collection<ValueEntity>> getValueEntities(final Optional<? extends Collection<CSEntity>> csEntities) {
if (!csEntities.isPresent() || csEntities.get().isEmpty()) {
return Optional.empty();
}
final Set<ValueEntity> valueEntities = new HashSet<>();
for (final CSEntity csEntity : csEntities.get()) {
valueEntities.addAll(csEntity.getValueEntities());
}
return Optional.of(valueEntities);
}
}
| zazi/dswarm-graph-neo4j | src/main/java/org/dswarm/graph/delta/match/model/util/CSEntityUtil.java | Java | gpl-3.0 | 1,515 |
#region License
// Copyright (c) 2013, ClearCanvas Inc.
// All rights reserved.
// http://www.ClearCanvas.ca
//
// This file is part of the ClearCanvas RIS/PACS open source project.
//
// The ClearCanvas RIS/PACS open source project is free software: you can
// redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// The ClearCanvas RIS/PACS open source project is distributed in the hope that it
// will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// the ClearCanvas RIS/PACS open source project. If not, see
// <http://www.gnu.org/licenses/>.
#endregion
// This file is auto-generated by the Macro.Model.SqlServer.CodeGenerator project.
namespace Macro.ImageServer.Model.EntityBrokers
{
using Macro.ImageServer.Enterprise;
public interface IServerRuleApplyTimeEnumBroker: IEnumBroker<ServerRuleApplyTimeEnum>
{ }
}
| 151706061/MacroMedicalSystem | ImageServer/Model/EntityBrokers/IServerRuleApplyTimeEnumBroker.gen.cs | C# | gpl-3.0 | 1,219 |
#region License
// Copyright (c) 2013, ClearCanvas Inc.
// All rights reserved.
// http://www.ClearCanvas.ca
//
// This file is part of the ClearCanvas RIS/PACS open source project.
//
// The ClearCanvas RIS/PACS open source project is free software: you can
// redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// The ClearCanvas RIS/PACS open source project is distributed in the hope that it
// will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// the ClearCanvas RIS/PACS open source project. If not, see
// <http://www.gnu.org/licenses/>.
#endregion
using System;
namespace Macro.ImageServer.Common.Exceptions
{
/// <summary>
/// Represents an exception thrown when the study state is invalid for the operation.
/// </summary>
public class InvalidStudyStateOperationException : System.Exception
{
public InvalidStudyStateOperationException(string message):base(message)
{
}
}
}
| 151706061/MacroMedicalSystem | ImageServer/Common/Exceptions/InvalidStudyStateOperationException.cs | C# | gpl-3.0 | 1,334 |
function assign(taskID, assignedTo)
{
$('.assign').width(150);
$('.assign').height(40);
$('.assign').load(createLink('user', 'ajaxGetUser', 'taskID=' + taskID + '&assignedTo=' + assignedTo));
}
function setComment()
{
$('#comment').toggle();
}
| isleon/zentao | module/task/js/view.js | JavaScript | gpl-3.0 | 252 |
(function() {
'use strict';
angular
.module('editor.database', [])
.config(function($indexedDBProvider) {
$indexedDBProvider
.connection('otus-studio')
.upgradeDatabase(1, function(event, db, tx) {
var store = db.createObjectStore('survey_template', { keyPath: 'template_oid'});
store.createIndex('contributor_idx', 'contributor', { unique: false });
});
});
}());
| ccem-dev/otus-studio | source/app/editor/database/editor-database-module.js | JavaScript | gpl-3.0 | 499 |
/* Image.js
*
* copyright (c) 2010-2017, Christian Mayer and the CometVisu contributers.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
/**
*
*/
qx.Class.define('cv.parser.widgets.Image', {
type: "static",
/*
******************************************************
STATICS
******************************************************
*/
statics: {
/**
* Parses the widgets XML configuration and extracts the given information
* to a simple key/value map.
*
* @param xml {Element} XML-Element
* @param path {String} internal path of the widget
* @param flavour {String} Flavour of the widget
* @param pageType {String} Page type (2d, 3d, ...)
*/
parse: function (xml, path, flavour, pageType) {
var data = cv.parser.WidgetParser.parseElement(this, xml, path, flavour, pageType, this.getAttributeToPropertyMappings());
cv.parser.WidgetParser.parseRefresh(xml, path);
return data;
},
getAttributeToPropertyMappings: function () {
return {
'width' : { "default": "100%" },
'height' : {},
'src' : {},
'widthfit' : { target: 'widthFit', transform: function(value) {
return value === "true";
}}
};
}
},
defer: function(statics) {
// register the parser
cv.parser.WidgetParser.addHandler("image", statics);
}
});
| joltcoke/CometVisu | source/class/cv/parser/widgets/Image.js | JavaScript | gpl-3.0 | 2,083 |
/* devanagari */
@font-face {
font-family: 'Hind';
font-style: normal;
font-weight: 400;
src: local('Hind'), local('Hind-Regular'), url(https://fonts.gstatic.com/s/hind/v6/Vb88BBmXXgbpZxolKzz6dw.woff2) format('woff2');
unicode-range: U+02BC, U+0900-097F, U+1CD0-1CF6, U+1CF8-1CF9, U+200B-200D, U+20A8, U+20B9, U+25CC, U+A830-A839, U+A8E0-A8FB;
}
/* latin-ext */
@font-face {
font-family: 'Hind';
font-style: normal;
font-weight: 400;
src: local('Hind'), local('Hind-Regular'), url(https://fonts.gstatic.com/s/hind/v6/eND698DA6CUFWomaRdrTiw.woff2) format('woff2');
unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Hind';
font-style: normal;
font-weight: 400;
src: local('Hind'), local('Hind-Regular'), url(https://fonts.gstatic.com/s/hind/v6/xLdg5JI0N_C2fvyu9XVzXg.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
}
/* devanagari */
@font-face {
font-family: 'Hind';
font-style: normal;
font-weight: 500;
src: local('Hind Medium'), local('Hind-Medium'), url(https://fonts.gstatic.com/s/hind/v6/bWPw4Za2XndpOjggSNN5JPY6323mHUZFJMgTvxaG2iE.woff2) format('woff2');
unicode-range: U+02BC, U+0900-097F, U+1CD0-1CF6, U+1CF8-1CF9, U+200B-200D, U+20A8, U+20B9, U+25CC, U+A830-A839, U+A8E0-A8FB;
}
/* latin-ext */
@font-face {
font-family: 'Hind';
font-style: normal;
font-weight: 500;
src: local('Hind Medium'), local('Hind-Medium'), url(https://fonts.gstatic.com/s/hind/v6/TCDCvLw6ewp4kJ2WSI4MT_Y6323mHUZFJMgTvxaG2iE.woff2) format('woff2');
unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Hind';
font-style: normal;
font-weight: 500;
src: local('Hind Medium'), local('Hind-Medium'), url(https://fonts.gstatic.com/s/hind/v6/_JiDQLq4JWzs7prWhNNmuA.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
}
/* devanagari */
@font-face {
font-family: 'Hind';
font-style: normal;
font-weight: 700;
src: local('Hind Bold'), local('Hind-Bold'), url(https://fonts.gstatic.com/s/hind/v6/AFoPIhbuX_gBhSszntNC0_Y6323mHUZFJMgTvxaG2iE.woff2) format('woff2');
unicode-range: U+02BC, U+0900-097F, U+1CD0-1CF6, U+1CF8-1CF9, U+200B-200D, U+20A8, U+20B9, U+25CC, U+A830-A839, U+A8E0-A8FB;
}
/* latin-ext */
@font-face {
font-family: 'Hind';
font-style: normal;
font-weight: 700;
src: local('Hind Bold'), local('Hind-Bold'), url(https://fonts.gstatic.com/s/hind/v6/503ks6dbq2nVdfUL61JyAfY6323mHUZFJMgTvxaG2iE.woff2) format('woff2');
unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Hind';
font-style: normal;
font-weight: 700;
src: local('Hind Bold'), local('Hind-Bold'), url(https://fonts.gstatic.com/s/hind/v6/PQuIEfcr_wdF_zOSNjqWKQ.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
}
/* latin */
@font-face {
font-family: 'Montserrat';
font-style: normal;
font-weight: 400;
src: local('Montserrat-Regular'), url(https://fonts.gstatic.com/s/montserrat/v7/zhcz-_WihjSQC0oHJ9TCYPk_vArhqVIZ0nv9q090hN8.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
}
/* latin */
@font-face {
font-family: 'Montserrat';
font-style: normal;
font-weight: 700;
src: local('Montserrat-Bold'), url(https://fonts.gstatic.com/s/montserrat/v7/IQHow_FEYlDC4Gzy_m8fcoWiMMZ7xLd792ULpGE4W_Y.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
}
/* cyrillic-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans'), local('OpenSans'), url(https://fonts.gstatic.com/s/opensans/v13/K88pR3goAWT7BTt32Z01mxJtnKITppOI_IvcXXDNrsc.woff2) format('woff2');
unicode-range: U+0460-052F, U+20B4, U+2DE0-2DFF, U+A640-A69F;
}
/* cyrillic */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans'), local('OpenSans'), url(https://fonts.gstatic.com/s/opensans/v13/RjgO7rYTmqiVp7vzi-Q5URJtnKITppOI_IvcXXDNrsc.woff2) format('woff2');
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* greek-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans'), local('OpenSans'), url(https://fonts.gstatic.com/s/opensans/v13/LWCjsQkB6EMdfHrEVqA1KRJtnKITppOI_IvcXXDNrsc.woff2) format('woff2');
unicode-range: U+1F00-1FFF;
}
/* greek */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans'), local('OpenSans'), url(https://fonts.gstatic.com/s/opensans/v13/xozscpT2726on7jbcb_pAhJtnKITppOI_IvcXXDNrsc.woff2) format('woff2');
unicode-range: U+0370-03FF;
}
/* vietnamese */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans'), local('OpenSans'), url(https://fonts.gstatic.com/s/opensans/v13/59ZRklaO5bWGqF5A9baEERJtnKITppOI_IvcXXDNrsc.woff2) format('woff2');
unicode-range: U+0102-0103, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans'), local('OpenSans'), url(https://fonts.gstatic.com/s/opensans/v13/u-WUoqrET9fUeobQW7jkRRJtnKITppOI_IvcXXDNrsc.woff2) format('woff2');
unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans'), local('OpenSans'), url(https://fonts.gstatic.com/s/opensans/v13/cJZKeOuBrn4kERxqtaUH3VtXRa8TVwTICgirnJhmVJw.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
}
/* cyrillic-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
src: local('Open Sans Bold'), local('OpenSans-Bold'), url(https://fonts.gstatic.com/s/opensans/v13/k3k702ZOKiLJc3WVjuplzK-j2U0lmluP9RWlSytm3ho.woff2) format('woff2');
unicode-range: U+0460-052F, U+20B4, U+2DE0-2DFF, U+A640-A69F;
}
/* cyrillic */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
src: local('Open Sans Bold'), local('OpenSans-Bold'), url(https://fonts.gstatic.com/s/opensans/v13/k3k702ZOKiLJc3WVjuplzJX5f-9o1vgP2EXwfjgl7AY.woff2) format('woff2');
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* greek-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
src: local('Open Sans Bold'), local('OpenSans-Bold'), url(https://fonts.gstatic.com/s/opensans/v13/k3k702ZOKiLJc3WVjuplzBWV49_lSm1NYrwo-zkhivY.woff2) format('woff2');
unicode-range: U+1F00-1FFF;
}
/* greek */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
src: local('Open Sans Bold'), local('OpenSans-Bold'), url(https://fonts.gstatic.com/s/opensans/v13/k3k702ZOKiLJc3WVjuplzKaRobkAwv3vxw3jMhVENGA.woff2) format('woff2');
unicode-range: U+0370-03FF;
}
/* vietnamese */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
src: local('Open Sans Bold'), local('OpenSans-Bold'), url(https://fonts.gstatic.com/s/opensans/v13/k3k702ZOKiLJc3WVjuplzP8zf_FOSsgRmwsS7Aa9k2w.woff2) format('woff2');
unicode-range: U+0102-0103, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
src: local('Open Sans Bold'), local('OpenSans-Bold'), url(https://fonts.gstatic.com/s/opensans/v13/k3k702ZOKiLJc3WVjuplzD0LW-43aMEzIO6XUTLjad8.woff2) format('woff2');
unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
src: local('Open Sans Bold'), local('OpenSans-Bold'), url(https://fonts.gstatic.com/s/opensans/v13/k3k702ZOKiLJc3WVjuplzOgdm0LZdjqr5-oayXSOefg.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
}
| e-spres-oh/acuma.in | web/assets/styles/googlefonts.css | CSS | gpl-3.0 | 8,686 |
<?php
echo("Discovery protocols:");
global $link_exists;
$community = $device['community'];
if ($device['os'] == "ironware")
{
echo(" Brocade FDP: ");
$fdp_array = snmpwalk_cache_twopart_oid($device, "snFdpCacheEntry", array(), "FOUNDRY-SN-SWITCH-GROUP-MIB");
if ($fdp_array)
{
unset($fdp_links);
foreach (array_keys($fdp_array) as $key)
{
$interface = dbFetchRow("SELECT * FROM `ports` WHERE `device_id` = ? AND `ifIndex` = ?",array($device['device_id'],$key));
$fdp_if_array = $fdp_array[$key];
foreach (array_keys($fdp_if_array) as $entry_key)
{
$fdp = $fdp_if_array[$entry_key];
$remote_device_id = dbFetchCell("SELECT `device_id` FROM `devices` WHERE `sysName` = ? OR `hostname` = ?",array($fdp['snFdpCacheDeviceId'], $fdp['snFdpCacheDeviceId']));
if (!$remote_device_id)
{
$remote_device_id = discover_new_device($fdp['snFdpCacheDeviceId']);
if ($remote_device_id)
{
$int = ifNameDescr($interface);
log_event("Device autodiscovered through FDP on " . $device['hostname'] . " (port " . $int['label'] . ")", $remote_device_id, 'interface', $int['port_id']);
}
}
if ($remote_device_id)
{
$if = $fdp['snFdpCacheDevicePort'];
$remote_port_id = dbFetchCell("SELECT port_id FROM `ports` WHERE (`ifDescr` = ? OR `ifName = ?) AND `device_id` = ?",array($if,$if,$remote_device_id));
} else { $remote_port_id = "0"; }
discover_link($interface['port_id'], $fdp['snFdpCacheVendorId'], $remote_port_id, $fdp['snFdpCacheDeviceId'], $fdp['snFdpCacheDevicePort'], $fdp['snFdpCachePlatform'], $fdp['snFdpCacheVersion']);
}
}
}
}
echo(" CISCO-CDP-MIB: ");
unset($cdp_array);
$cdp_array = snmpwalk_cache_twopart_oid($device, "cdpCache", array(), "CISCO-CDP-MIB");
if ($cdp_array)
{
unset($cdp_links);
foreach (array_keys($cdp_array) as $key)
{
$interface = dbFetchRow("SELECT * FROM `ports` WHERE device_id = ? AND `ifIndex` = ?", array($device['device_id'], $key));
$cdp_if_array = $cdp_array[$key];
foreach (array_keys($cdp_if_array) as $entry_key)
{
$cdp = $cdp_if_array[$entry_key];
if (is_valid_hostname($cdp['cdpCacheDeviceId']))
{
$remote_device_id = dbFetchCell("SELECT `device_id` FROM `devices` WHERE `sysName` = ? OR `hostname` = ?", array($cdp['cdpCacheDeviceId'], $cdp['cdpCacheDeviceId']));
if (!$remote_device_id)
{
$remote_device_id = discover_new_device($cdp['cdpCacheDeviceId']);
if ($remote_device_id)
{
$int = ifNameDescr($interface);
log_event("Device autodiscovered through CDP on " . $device['hostname'] . " (port " . $int['label'] . ")", $remote_device_id, 'interface', $int['port_id']);
}
}
if ($remote_device_id)
{
$if = $cdp['cdpCacheDevicePort'];
$remote_port_id = dbFetchCell("SELECT port_id FROM `ports` WHERE (`ifDescr` = ? OR `ifName` = ?) AND `device_id` = ?", array($if, $if, $remote_device_id));
} else { $remote_port_id = "0"; }
if ($interface['port_id'] && $cdp['cdpCacheDeviceId'] && $cdp['cdpCacheDevicePort'])
{
discover_link($interface['port_id'], 'cdp', $remote_port_id, $cdp['cdpCacheDeviceId'], $cdp['cdpCacheDevicePort'], $cdp['cdpCachePlatform'], $cdp['cdpCacheVersion']);
}
}
else
{
echo("X");
}
}
}
}
echo(" LLDP-MIB: ");
unset($lldp_array);
$lldp_array = snmpwalk_cache_threepart_oid($device, "lldpRemoteSystemsData", array(), "LLDP-MIB");
$dot1d_array = snmpwalk_cache_oid($device, "dot1dBasePortIfIndex", array(), "BRIDGE-MIB");
if ($lldp_array)
{
$lldp_links = "";
foreach (array_keys($lldp_array) as $key)
{
$lldp_if_array = $lldp_array[$key];
foreach (array_keys($lldp_if_array) as $entry_key)
{
if (is_numeric($dot1d_array[$entry_key]['dot1dBasePortIfIndex']))
{
$ifIndex = $dot1d_array[$entry_key]['dot1dBasePortIfIndex'];
} else {
$ifIndex = $entry_key;
}
$interface = dbFetchRow("SELECT * FROM `ports` WHERE `device_id` = ? AND `ifIndex` = ?",array($device['device_id'],$ifIndex));
$lldp_instance = $lldp_if_array[$entry_key];
foreach (array_keys($lldp_instance) as $entry_instance)
{
$lldp = $lldp_instance[$entry_instance];
$remote_device_id = dbFetchCell("SELECT `device_id` FROM `devices` WHERE `sysName` = ? OR `hostname` = ?",array($lldp['lldpRemSysName'], $lldp['lldpRemSysName']));
if (!$remote_device_id && is_valid_hostname($lldp['lldpRemSysName']))
{
$remote_device_id = discover_new_device($lldp['lldpRemSysName']);
if ($remote_device_id)
{
$int = ifNameDescr($interface);
log_event("Device autodiscovered through LLDP on " . $device['hostname'] . " (port " . $int['label'] . ")", $remote_device_id, 'interface', $int['port_id']);
}
}
if ($remote_device_id)
{
$if = $lldp['lldpRemPortDesc']; $id = $lldp['lldpRemPortId'];
$remote_port_id = dbFetchCell("SELECT `port_id` FROM `ports` WHERE (`ifDescr` = ? OR `ifName` = ? OR `ifDescr` = ? OR `ifName` = ?) AND `device_id` = ?",array($if,$if,$id,$id,$remote_device_id));
} else {
$remote_port_id = "0";
}
if (is_numeric($interface['port_id']) && isset($lldp['lldpRemSysName']) && isset($lldp['lldpRemPortId']))
{
discover_link($interface['port_id'], 'lldp', $remote_port_id, $lldp['lldpRemSysName'], $lldp['lldpRemPortId'], NULL, $lldp['lldpRemSysDesc']);
}
}
}
}
}
if ($debug) { print_r($link_exists); }
$sql = "SELECT * FROM `links` AS L, `ports` AS I WHERE L.local_port_id = I.port_id AND I.device_id = '".$device['device_id']."'";
foreach (dbFetchRows($sql) as $test)
{
$local_port_id = $test['local_port_id'];
$remote_hostname = $test['remote_hostname'];
$remote_port = $test['remote_port'];
if ($debug) { echo("$local_port_id -> $remote_hostname -> $remote_port \n"); }
if (!$link_exists[$local_port_id][$remote_hostname][$remote_port])
{
echo("-");
$rows = dbDelete('links', '`id` = ?', array($test['id']));
if ($debug) { echo("$rows deleted "); }
}
}
unset($link_exists);
echo("\n");
?>
| wojons/librenms | includes/discovery/discovery-protocols.inc.php | PHP | gpl-3.0 | 6,429 |
/****************************************************************\
* *
* Library for HSP sets (high-scoring segment pairs) *
* *
* Guy St.C. Slater.. mailto:guy@ebi.ac.uk *
* Copyright (C) 2000-2008. All Rights Reserved. *
* *
* This source code is distributed under the terms of the *
* GNU General Public License, version 3. See the file COPYING *
* or http://www.gnu.org/licenses/gpl.txt for details *
* *
* If you use this code, please keep this notice intact. *
* *
\****************************************************************/
#include <string.h> /* For strlen() */
#include <ctype.h> /* For tolower() */
#include <stdlib.h> /* For qsort() */
#include "hspset.h"
HSPset_ArgumentSet *HSPset_ArgumentSet_create(Argument *arg){
register ArgumentSet *as;
static HSPset_ArgumentSet has = {0};
if(arg){
as = ArgumentSet_create("HSP creation options");
ArgumentSet_add_option(as, '\0', "hspfilter", NULL,
"Aggressive HSP filtering level", "0",
Argument_parse_int, &has.filter_threshold);
ArgumentSet_add_option(as, '\0', "useworddropoff", NULL,
"Use word neighbourhood dropoff", "TRUE",
Argument_parse_boolean, &has.use_wordhood_dropoff);
ArgumentSet_add_option(as, '\0', "seedrepeat", NULL,
"Seeds per diagonal required for HSP seeding", "1",
Argument_parse_int, &has.seed_repeat);
/**/
ArgumentSet_add_option(as, 0, "dnawordlen", "bp",
"Wordlength for DNA words", "12",
Argument_parse_int, &has.dna_wordlen);
ArgumentSet_add_option(as, 0, "proteinwordlen", "aa",
"Wordlength for protein words", "6",
Argument_parse_int, &has.protein_wordlen);
ArgumentSet_add_option(as, 0, "codonwordlen", "bp",
"Wordlength for codon words", "12",
Argument_parse_int, &has.codon_wordlen);
/**/
ArgumentSet_add_option(as, 0, "dnahspdropoff", "score",
"DNA HSP dropoff score", "30",
Argument_parse_int, &has.dna_hsp_dropoff);
ArgumentSet_add_option(as, 0, "proteinhspdropoff", "score",
"Protein HSP dropoff score", "20",
Argument_parse_int, &has.protein_hsp_dropoff);
ArgumentSet_add_option(as, 0, "codonhspdropoff", "score",
"Codon HSP dropoff score", "40",
Argument_parse_int, &has.codon_hsp_dropoff);
/**/
ArgumentSet_add_option(as, 0, "dnahspthreshold", "score",
"DNA HSP threshold score", "75",
Argument_parse_int, &has.dna_hsp_threshold);
ArgumentSet_add_option(as, 0, "proteinhspthreshold", "score",
"Protein HSP threshold score", "30",
Argument_parse_int, &has.protein_hsp_threshold);
ArgumentSet_add_option(as, 0, "codonhspthreshold", "score",
"Codon HSP threshold score", "50",
Argument_parse_int, &has.codon_hsp_threshold);
/**/
ArgumentSet_add_option(as, 0, "dnawordlimit", "score",
"Score limit for dna word neighbourhood", "0",
Argument_parse_int, &has.dna_wordlimit);
ArgumentSet_add_option(as, 0, "proteinwordlimit", "score",
"Score limit for protein word neighbourhood", "4",
Argument_parse_int, &has.protein_wordlimit);
ArgumentSet_add_option(as, 0, "codonwordlimit", "score",
"Score limit for codon word neighbourhood", "4",
Argument_parse_int, &has.codon_wordlimit);
/**/
ArgumentSet_add_option(as, '\0', "geneseed", "threshold",
"Geneseed Threshold", "0",
Argument_parse_int, &has.geneseed_threshold);
ArgumentSet_add_option(as, '\0', "geneseedrepeat", "number",
"Seeds per diagonal required for geneseed HSP seeding", "3",
Argument_parse_int, &has.geneseed_repeat);
/**/
Argument_absorb_ArgumentSet(arg, as);
}
return &has;
}
/**/
static gboolean HSP_check_positions(HSPset *hsp_set,
gint query_pos, gint target_pos){
g_assert(query_pos >= 0);
g_assert(target_pos >= 0);
g_assert(query_pos < hsp_set->query->len);
g_assert(target_pos < hsp_set->target->len);
return TRUE;
}
static gboolean HSP_check(HSP *hsp){
g_assert(hsp);
g_assert(hsp->hsp_set);
g_assert(hsp->length);
g_assert(HSP_query_end(hsp) <= hsp->hsp_set->query->len);
g_assert(HSP_target_end(hsp) <= hsp->hsp_set->target->len);
return TRUE;
}
void HSP_Param_set_wordlen(HSP_Param *hsp_param, gint wordlen){
if(wordlen <= 0)
g_error("Wordlength must be greater than zero");
hsp_param->wordlen = wordlen;
hsp_param->seedlen = hsp_param->wordlen
/ hsp_param->match->query->advance;
return;
}
/**/
void HSP_Param_set_dna_hsp_threshold(HSP_Param *hsp_param,
gint dna_hsp_threshold){
if(hsp_param->match->type == Match_Type_DNA2DNA)
hsp_param->threshold = dna_hsp_threshold;
return;
}
void HSP_Param_set_protein_hsp_threshold(HSP_Param *hsp_param,
gint protein_hsp_threshold){
if((hsp_param->match->type == Match_Type_PROTEIN2PROTEIN)
|| (hsp_param->match->type == Match_Type_PROTEIN2DNA)
|| (hsp_param->match->type == Match_Type_DNA2PROTEIN))
hsp_param->threshold = protein_hsp_threshold;
return;
}
void HSP_Param_set_codon_hsp_threshold(HSP_Param *hsp_param,
gint codon_hsp_threshold){
if(hsp_param->match->type == Match_Type_CODON2CODON)
hsp_param->threshold = codon_hsp_threshold;
return;
}
/**/
void HSP_Param_set_dna_hsp_dropoff(HSP_Param *hsp_param,
gint dna_hsp_dropoff){
if(hsp_param->match->type == Match_Type_DNA2DNA)
hsp_param->dropoff = dna_hsp_dropoff;
return;
}
void HSP_Param_set_protein_hsp_dropoff(HSP_Param *hsp_param,
gint protein_hsp_dropoff){
if((hsp_param->match->type == Match_Type_PROTEIN2PROTEIN)
|| (hsp_param->match->type == Match_Type_PROTEIN2DNA)
|| (hsp_param->match->type == Match_Type_DNA2PROTEIN))
hsp_param->dropoff = protein_hsp_dropoff;
return;
}
void HSP_Param_set_codon_hsp_dropoff(HSP_Param *hsp_param,
gint codon_hsp_dropoff){
if(hsp_param->match->type == Match_Type_CODON2CODON)
hsp_param->dropoff = codon_hsp_dropoff;
return;
}
/**/
void HSP_Param_set_hsp_threshold(HSP_Param *hsp_param,
gint hsp_threshold){
hsp_param->threshold = hsp_threshold;
return;
}
void HSP_Param_set_seed_repeat(HSP_Param *hsp_param,
gint seed_repeat){
hsp_param->seed_repeat = seed_repeat;
return;
}
HSP_Param *HSP_Param_create(Match *match, gboolean use_horizon){
register HSP_Param *hsp_param = g_new(HSP_Param, 1);
register WordHood_Alphabet *wha = NULL;
register Submat *submat;
hsp_param->ref_count = 1;
hsp_param->has = HSPset_ArgumentSet_create(NULL);
hsp_param->match = match;
hsp_param->seed_repeat = hsp_param->has->seed_repeat;
switch(match->type){
case Match_Type_DNA2DNA:
hsp_param->dropoff = hsp_param->has->dna_hsp_dropoff;
hsp_param->threshold = hsp_param->has->dna_hsp_threshold;
HSP_Param_set_wordlen(hsp_param, hsp_param->has->dna_wordlen);
hsp_param->wordlimit = hsp_param->has->dna_wordlimit;
break;
case Match_Type_PROTEIN2PROTEIN: /*fallthrough*/
case Match_Type_PROTEIN2DNA: /*fallthrough*/
case Match_Type_DNA2PROTEIN:
hsp_param->dropoff = hsp_param->has->protein_hsp_dropoff;
hsp_param->threshold
= hsp_param->has->protein_hsp_threshold;
HSP_Param_set_wordlen(hsp_param, hsp_param->has->protein_wordlen);
hsp_param->wordlimit = hsp_param->has->protein_wordlimit;
break;
case Match_Type_CODON2CODON:
hsp_param->dropoff = hsp_param->has->codon_hsp_dropoff;
hsp_param->threshold = hsp_param->has->codon_hsp_threshold;
HSP_Param_set_wordlen(hsp_param, hsp_param->has->codon_wordlen);
hsp_param->wordlimit = hsp_param->has->codon_wordlimit;
g_assert(!(hsp_param->wordlen % 3));
break;
default:
g_error("Bad Match_Type [%d]", match->type);
break;
}
hsp_param->use_horizon = use_horizon;
if(hsp_param->has->use_wordhood_dropoff && (!hsp_param->wordlimit)){
hsp_param->wordhood = NULL;
} else {
submat = (match->type == Match_Type_DNA2DNA)
? match->mas->dna_submat
: match->mas->protein_submat;
wha = WordHood_Alphabet_create_from_Submat(
(gchar*)match->comparison_alphabet->member,
(gchar*)match->comparison_alphabet->member, submat, FALSE);
g_assert(wha);
hsp_param->wordhood = WordHood_create(wha, hsp_param->wordlimit,
hsp_param->has->use_wordhood_dropoff);
WordHood_Alphabet_destroy(wha);
}
return hsp_param;
}
void HSP_Param_destroy(HSP_Param *hsp_param){
g_assert(hsp_param);
if(--hsp_param->ref_count)
return;
if(hsp_param->wordhood)
WordHood_destroy(hsp_param->wordhood);
g_free(hsp_param);
return;
}
HSP_Param *HSP_Param_share(HSP_Param *hsp_param){
g_assert(hsp_param);
hsp_param->ref_count++;
return hsp_param;
}
HSP_Param *HSP_Param_swap(HSP_Param *hsp_param){
g_assert(hsp_param);
return HSP_Param_create(Match_swap(hsp_param->match),
hsp_param->use_horizon);
}
static RecycleBin *global_hsp_recycle_bin = NULL;
HSPset *HSPset_create(Sequence *query, Sequence *target,
HSP_Param *hsp_param){
register HSPset *hsp_set = g_new(HSPset, 1);
g_assert(query);
g_assert(target);
hsp_set->ref_count = 1;
hsp_set->query = Sequence_share(query);
hsp_set->target = Sequence_share(target);
hsp_set->param = HSP_Param_share(hsp_param);
/**/
if(global_hsp_recycle_bin){
hsp_set->hsp_recycle = RecycleBin_share(global_hsp_recycle_bin);
} else {
global_hsp_recycle_bin = RecycleBin_create("HSP", sizeof(HSP), 64);
hsp_set->hsp_recycle = global_hsp_recycle_bin;
}
if(hsp_param->use_horizon){
hsp_set->horizon = (gint****)Matrix4d_create(
1 + ((hsp_param->seed_repeat > 1)?1:0),
query->len,
hsp_param->match->query->advance,
hsp_param->match->target->advance,
sizeof(gint));
} else {
hsp_set->horizon = NULL;
}
hsp_set->hsp_list = g_ptr_array_new();
hsp_set->is_finalised = FALSE;
hsp_set->param->has = HSPset_ArgumentSet_create(NULL);
if(hsp_set->param->has->filter_threshold){
hsp_set->filter = g_new0(PQueue*, query->len);
hsp_set->pqueue_set = PQueueSet_create();
} else {
hsp_set->filter = NULL;
hsp_set->pqueue_set = NULL;
}
hsp_set->is_empty = TRUE;
return hsp_set;
}
/**/
HSPset *HSPset_share(HSPset *hsp_set){
g_assert(hsp_set);
hsp_set->ref_count++;
return hsp_set;
}
void HSPset_destroy(HSPset *hsp_set){
register gint i;
register HSP *hsp;
g_assert(hsp_set);
if(--hsp_set->ref_count)
return;
HSP_Param_destroy(hsp_set->param);
if(hsp_set->filter)
g_free(hsp_set->filter);
if(hsp_set->pqueue_set)
PQueueSet_destroy(hsp_set->pqueue_set);
Sequence_destroy(hsp_set->query);
Sequence_destroy(hsp_set->target);
for(i = 0; i < hsp_set->hsp_list->len; i++){
hsp = hsp_set->hsp_list->pdata[i];
HSP_destroy(hsp);
}
g_ptr_array_free(hsp_set->hsp_list, TRUE);
if(hsp_set->hsp_recycle->ref_count == 1) /* last active hsp_set */
global_hsp_recycle_bin = NULL;
RecycleBin_destroy(hsp_set->hsp_recycle);
if(hsp_set->horizon)
g_free(hsp_set->horizon);
g_free(hsp_set);
return;
}
void HSPset_swap(HSPset *hsp_set, HSP_Param *hsp_param){
register Sequence *query;
register gint i, query_start;
register HSP *hsp;
g_assert(hsp_set->ref_count == 1);
/* Swap query and target */
query = hsp_set->query;
hsp_set->query = hsp_set->target;
hsp_set->target = query;
/* Switch parameters */
HSP_Param_destroy(hsp_set->param);
hsp_set->param = HSP_Param_share(hsp_param);
/* Swap HSPs coordinates */
for(i = 0; i < hsp_set->hsp_list->len; i++){
hsp = hsp_set->hsp_list->pdata[i];
query_start = hsp->query_start;
hsp->query_start = hsp->target_start;
hsp->target_start = query_start;
}
return;
}
void HSPset_revcomp(HSPset *hsp_set){
register Sequence *rc_query = Sequence_revcomp(hsp_set->query),
*rc_target = Sequence_revcomp(hsp_set->target);
register gint i;
register HSP *hsp;
g_assert(hsp_set);
g_assert(hsp_set->is_finalised);
g_assert(hsp_set->ref_count == 1);
/**/
Sequence_destroy(hsp_set->query);
Sequence_destroy(hsp_set->target);
hsp_set->query = rc_query;
hsp_set->target = rc_target;
for(i = 0; i < hsp_set->hsp_list->len; i++){
hsp = hsp_set->hsp_list->pdata[i];
hsp->query_start = hsp_set->query->len - HSP_query_end(hsp);
hsp->target_start = hsp_set->target->len - HSP_target_end(hsp);
}
return;
}
static gint HSP_find_cobs(HSP *hsp){
register gint i, query_pos = hsp->query_start,
target_pos = hsp->target_start;
register Match_Score score = 0;
/* Find the HSP centre offset by score */
for(i = 0; i < hsp->length; i++){
g_assert(HSP_check_positions(hsp->hsp_set,
query_pos, target_pos));
score += HSP_get_score(hsp, query_pos, target_pos);
if(score >= (hsp->score>>1))
break;
query_pos += HSP_query_advance(hsp);
target_pos += HSP_target_advance(hsp);
}
return i;
}
/**/
static void HSP_print_info(HSP *hsp){
g_print("HSP info (%p)\n"
" query_start = [%d]\n"
" target_start = [%d]\n"
" length = [%d]\n"
" score = [%d]\n"
" cobs = [%d]\n",
(gpointer)hsp,
hsp->query_start,
hsp->target_start,
hsp->length,
hsp->score,
hsp->cobs);
return;
}
typedef struct {
HSP *hsp; /* not freed */
gint padding;
gint max_advance;
gint query_display_pad;
gint target_display_pad;
GString *top;
GString *mid;
GString *low;
} HSP_Display;
static HSP_Display *HSP_Display_create(HSP *hsp, gint padding){
register HSP_Display *hd = g_new(HSP_Display, 1);
register gint approx_length;
hd->hsp = hsp;
hd->padding = padding;
hd->max_advance = MAX(HSP_query_advance(hsp),
HSP_target_advance(hsp));
hd->query_display_pad = (hd->max_advance
-HSP_query_advance(hsp))>>1;
hd->target_display_pad = (hd->max_advance
-HSP_target_advance(hsp))>>1;
approx_length = hd->max_advance * (hsp->length + 2);
hd->top = g_string_sized_new(approx_length);
hd->mid = g_string_sized_new(approx_length);
hd->low = g_string_sized_new(approx_length);
return hd;
}
static void HSP_Display_destroy(HSP_Display *hd){
g_assert(hd);
g_string_free(hd->top, TRUE);
g_string_free(hd->mid, TRUE);
g_string_free(hd->low, TRUE);
g_free(hd);
return;
}
static void HSP_Display_add(HSP_Display *hd,
gchar *top, gchar *mid, gchar *low){
g_assert(hd);
g_assert(top);
g_assert(mid);
g_assert(low);
g_string_append(hd->top, top);
g_string_append(hd->mid, mid);
g_string_append(hd->low, low);
g_assert(hd->top->len == hd->mid->len);
g_assert(hd->mid->len == hd->low->len);
return;
}
static gchar HSP_Display_get_ruler_char(HSP_Display *hd, gint pos,
gint advance){
register gint stop;
register gint pad_length = 3;
stop = hd->padding * hd->max_advance;
if(pos >= stop){
if(pos < (stop+pad_length)){
return '#';
}
stop = ((hd->padding+hd->hsp->length) * hd->max_advance)
+ pad_length;
if(pos >= stop){
if(pos < (stop+pad_length)){
return '#';
}
pos -= pad_length;
}
pos -= pad_length;
}
if((pos/advance) & 1)
return '=';
return '-';
}
static void HSP_Display_print_ruler(HSP_Display *hd, gint width,
gint pos, gboolean is_query){
register gint i, adv;
if(is_query){
if(HSP_target_advance(hd->hsp) == 1)
return; /* opposite padding */
adv = HSP_target_advance(hd->hsp);
} else { /* Is target */
if(HSP_query_advance(hd->hsp) == 1)
return; /* opposite padding */
adv = HSP_query_advance(hd->hsp);
}
g_print(" ruler:[");
for(i = 0; i < width; i++)
g_print("%c", HSP_Display_get_ruler_char(hd, pos+i, adv));
g_print("]\n");
return;
}
static void HSP_Display_print(HSP_Display *hd){
register gint pos, pause, width = 50;
g_assert(hd);
g_assert(hd->top->len == hd->mid->len);
g_assert(hd->mid->len == hd->low->len);
for(pos = 0, pause = hd->top->len-width; pos < pause; pos += width){
HSP_Display_print_ruler(hd, width, pos, TRUE);
g_print(" query:[%.*s]\n [%.*s]\ntarget:[%.*s]\n",
width, hd->top->str+pos,
width, hd->mid->str+pos,
width, hd->low->str+pos);
HSP_Display_print_ruler(hd, width, pos, FALSE);
g_print("\n");
}
HSP_Display_print_ruler(hd, hd->top->len-pos, pos, TRUE);
g_print(" query:[%.*s]\n [%.*s]\ntarget:[%.*s]\n",
hd->top->len-pos, hd->top->str+pos,
hd->mid->len-pos, hd->mid->str+pos,
hd->low->len-pos, hd->low->str+pos);
HSP_Display_print_ruler(hd, hd->top->len-pos, pos, FALSE);
g_print("\n");
return;
}
static void HSP_Display_insert(HSP_Display *hd, gint position){
register gint query_pos, target_pos;
register gboolean is_padding,
query_valid = TRUE, target_valid = TRUE;
register Match *match = hd->hsp->hsp_set->param->match;
gchar query_str[4] = {0},
target_str[4] = {0},
equiv_str[4] = {0};
g_assert(hd);
query_pos = hd->hsp->query_start
+ (HSP_query_advance(hd->hsp) * position);
target_pos = hd->hsp->target_start
+ (HSP_target_advance(hd->hsp) * position);
/* If outside HSP, then is_padding */
is_padding = ((position < 0) || (position >= hd->hsp->length));
/* If outside seqs, then invalid */
query_valid = ( (query_pos >= 0)
&&((query_pos+HSP_query_advance(hd->hsp))
<= hd->hsp->hsp_set->query->len));
target_valid = ((target_pos >= 0)
&&((target_pos+HSP_target_advance(hd->hsp))
<= hd->hsp->hsp_set->target->len));
/* Get equiv string */
if(query_valid && target_valid){
g_assert(HSP_check_positions(hd->hsp->hsp_set,
query_pos, target_pos));
HSP_get_display(hd->hsp, query_pos, target_pos, equiv_str);
} else {
strncpy(equiv_str, "###", hd->max_advance);
equiv_str[hd->max_advance] = '\0';
}
/* Get query string */
if(query_valid){
Match_Strand_get_raw(match->query, hd->hsp->hsp_set->query,
query_pos, query_str);
if((match->query->advance == 1) && (hd->max_advance == 3)){
query_str[1] = query_str[0];
query_str[0] = query_str[2] = ' ';
query_str[3] = '\0';
}
} else {
strncpy(query_str, "###", hd->max_advance);
query_str[hd->max_advance] = '\0';
}
/* Get target string */
if(target_valid){
Match_Strand_get_raw(match->target, hd->hsp->hsp_set->target,
target_pos, target_str);
if((match->target->advance == 1) && (hd->max_advance == 3)){
target_str[1] = target_str[0];
target_str[0] = target_str[2] = ' ';
target_str[3] = '\0';
}
} else {
strncpy(target_str, "###", hd->max_advance);
target_str[hd->max_advance] = '\0';
}
/* Make lower case for padding */
if(is_padding){
g_strdown(query_str);
g_strdown(target_str);
} else {
g_strup(query_str);
g_strup(target_str);
}
HSP_Display_add(hd, query_str, equiv_str, target_str);
return;
}
static void HSP_print_alignment(HSP *hsp){
register HSP_Display *hd = HSP_Display_create(hsp, 10);
register gint i;
for(i = 0; i < hd->padding; i++) /* Pre-padding */
HSP_Display_insert(hd, i-hd->padding);
/* Use pad_length == 3 */
HSP_Display_add(hd, " < ", " < ", " < "); /* Start divider */
for(i = 0; i < hsp->length; i++) /* The HSP itself */
HSP_Display_insert(hd, i);
HSP_Display_add(hd, " > ", " > ", " > "); /* End divider */
for(i = 0; i < hd->padding; i++) /* Post-padding */
HSP_Display_insert(hd, hsp->length+i);
HSP_Display_print(hd);
HSP_Display_destroy(hd);
return;
}
/*
* HSP display style:
*
* =-=-=- =-=-=-=-=-=-=-=-=- =-=-=-
* nnnnnn < ACGACGCCCACGATCGAT > nnn###
* ||| < |||:::||| |||||| > |||
* ### x < A R N D C Q > x ###
* ===--- ===---===---===--- ===---
*/
static void HSP_print_sugar(HSP *hsp){
g_print("sugar: %s %d %d %c %s %d %d %c %d\n",
hsp->hsp_set->query->id,
hsp->query_start,
hsp->length*HSP_query_advance(hsp),
Sequence_get_strand_as_char(hsp->hsp_set->query),
hsp->hsp_set->target->id,
hsp->target_start,
hsp->length*HSP_target_advance(hsp),
Sequence_get_strand_as_char(hsp->hsp_set->target),
hsp->score);
return;
}
/* Sugar output format:
* sugar: <query_id> <query_start> <query_length> <query_strand>
* <target_id> <target_start> <target_start> <target_strand>
* <score>
*/
void HSP_print(HSP *hsp, gchar *name){
g_print("draw_hsp(%d, %d, %d, %d, %d, %d, \"%s\")\n",
hsp->query_start,
hsp->target_start,
hsp->length,
hsp->cobs,
HSP_query_advance(hsp),
HSP_target_advance(hsp),
name);
HSP_print_info(hsp);
HSP_print_alignment(hsp);
HSP_print_sugar(hsp);
return;
}
void HSPset_print(HSPset *hsp_set){
register gint i;
register gchar *name;
g_print("HSPset [%p] contains [%d] hsps\n",
(gpointer)hsp_set, hsp_set->hsp_list->len);
g_print("Comparison of [%s] and [%s]\n",
hsp_set->query->id, hsp_set->target->id);
for(i = 0; i < hsp_set->hsp_list->len; i++){
name = g_strdup_printf("hsp [%d]", i+1);
HSP_print(hsp_set->hsp_list->pdata[i], name);
g_free(name);
}
return;
}
/**/
static void HSP_init(HSP *nh){
register gint i;
register gint query_pos, target_pos;
g_assert(HSP_check(nh));
/* Initial hsp score */
query_pos = nh->query_start;
target_pos = nh->target_start;
nh->score = 0;
for(i = 0; i < nh->length; i++){
g_assert(HSP_check_positions(nh->hsp_set,
query_pos, target_pos));
nh->score += HSP_get_score(nh, query_pos, target_pos);
query_pos += HSP_query_advance(nh);
target_pos += HSP_target_advance(nh);
}
if(nh->score < 0){
HSP_print(nh, "Bad HSP seed");
g_error("Initial HSP score [%d] less than zero", nh->score);
}
g_assert(HSP_check(nh));
return;
}
static void HSP_extend(HSP *nh, gboolean forbid_masked){
register Match_Score score, maxscore;
register gint query_pos, target_pos;
register gint extend, maxext;
g_assert(HSP_check(nh));
/* extend left */
maxscore = score = nh->score;
query_pos = nh->query_start-HSP_query_advance(nh);
target_pos = nh->target_start-HSP_target_advance(nh);
for(extend = 1, maxext = 0;
((query_pos >= 0) && (target_pos >= 0));
extend++){
g_assert(HSP_check_positions(nh->hsp_set,
query_pos, target_pos));
if((forbid_masked)
&& (HSP_query_masked(nh, query_pos)
|| HSP_target_masked(nh, target_pos)))
break;
score += HSP_get_score(nh, query_pos, target_pos);
if(maxscore <= score){
maxscore = score;
maxext = extend;
} else {
if(score < 0) /* See note below */
break;
if((maxscore-score) >= nh->hsp_set->param->dropoff)
break;
}
query_pos -= HSP_query_advance(nh);
target_pos -= HSP_target_advance(nh);
}
query_pos = HSP_query_end(nh);
target_pos = HSP_target_end(nh);
nh->query_start -= (maxext * HSP_query_advance(nh));
nh->target_start -= (maxext * HSP_target_advance(nh));
nh->length += maxext;
score = maxscore;
/* extend right */
for(extend = 1, maxext = 0;
( ((query_pos+HSP_query_advance(nh))
<= nh->hsp_set->query->len)
&& ((target_pos+HSP_target_advance(nh))
<= nh->hsp_set->target->len) );
extend++){
g_assert(HSP_check_positions(nh->hsp_set,
query_pos, target_pos));
if((forbid_masked)
&& (HSP_query_masked(nh, query_pos)
|| HSP_target_masked(nh, target_pos)))
break;
score += HSP_get_score(nh, query_pos, target_pos);
if(maxscore <= score){
maxscore = score;
maxext = extend;
} else {
if(score < 0) /* See note below */
break;
if((maxscore-score) >= nh->hsp_set->param->dropoff)
break;
}
query_pos += HSP_query_advance(nh);
target_pos += HSP_target_advance(nh);
}
nh->score = maxscore;
nh->length += maxext;
g_assert(HSP_check(nh));
return;
}
/* The score cannot be allowed to drop below zero in the HSP,
* as this can result in overlapping HSPs in some circurmstances.
*/
static HSP *HSP_create(HSP *nh){
register HSP *hsp = RecycleBin_alloc(nh->hsp_set->hsp_recycle);
hsp->hsp_set = nh->hsp_set;
hsp->query_start = nh->query_start;
hsp->target_start = nh->target_start;
hsp->length = nh->length;
hsp->score = nh->score;
hsp->cobs = nh->cobs; /* Value can be set by HSPset_finalise(); */
return hsp;
}
void HSP_destroy(HSP *hsp){
register HSPset *hsp_set = hsp->hsp_set;
RecycleBin_recycle(hsp_set->hsp_recycle, hsp);
return;
}
static void HSP_trim_ends(HSP *hsp){
register gint i;
register gint query_pos, target_pos;
/* Trim left to first good match */
g_assert(HSP_check(hsp));
for(i = 0; i < hsp->length; i++){
if(HSP_get_score(hsp, hsp->query_start, hsp->target_start) > 0)
break;
hsp->query_start += HSP_query_advance(hsp);
hsp->target_start += HSP_target_advance(hsp);
}
hsp->length -= i;
/**/
g_assert(HSP_check(hsp));
query_pos = HSP_query_end(hsp) - HSP_query_advance(hsp);
target_pos = HSP_target_end(hsp) - HSP_target_advance(hsp);
/* Trim right to last good match */
while(hsp->length > 0){
g_assert(HSP_check_positions(hsp->hsp_set,
query_pos, target_pos));
if(HSP_get_score(hsp, query_pos, target_pos) > 0)
break;
hsp->length--;
query_pos -= HSP_query_advance(hsp);
target_pos -= HSP_target_advance(hsp);
}
g_assert(HSP_check(hsp));
return;
}
/* This is to remove any unmatching ends from the HSP seed.
*/
static gboolean HSP_PQueue_comp_func(gpointer low, gpointer high,
gpointer user_data){
register HSP *hsp_low = (HSP*)low, *hsp_high = (HSP*)high;
return hsp_low->score - hsp_high->score;
}
static void HSP_store(HSP *nascent_hsp){
register HSPset *hsp_set = nascent_hsp->hsp_set;
register PQueue *pq;
register HSP *hsp = NULL;
g_assert(nascent_hsp);
if(nascent_hsp->score < hsp_set->param->threshold)
return;
if(hsp_set->param->has->filter_threshold){ /* If have filter */
/* Get cobs value */
nascent_hsp->cobs = HSP_find_cobs(nascent_hsp);
pq = hsp_set->filter[HSP_query_cobs(nascent_hsp)];
if(pq){ /* Put in PQueue if better than worst */
if(PQueue_total(pq)
< hsp_set->param->has->filter_threshold){
hsp = HSP_create(nascent_hsp);
PQueue_push(pq, hsp);
} else {
g_assert(PQueue_total(pq));
hsp = PQueue_top(pq);
if(hsp->score < nascent_hsp->score){
hsp = PQueue_pop(pq);
HSP_destroy(hsp);
hsp = HSP_create(nascent_hsp);
PQueue_push(pq, hsp);
}
}
} else {
pq = PQueue_create(hsp_set->pqueue_set,
HSP_PQueue_comp_func, NULL);
hsp_set->filter[HSP_query_cobs(nascent_hsp)] = pq;
hsp = HSP_create(nascent_hsp);
PQueue_push(pq, hsp);
hsp_set->is_empty = FALSE;
}
} else {
hsp = HSP_create(nascent_hsp);
g_ptr_array_add(hsp_set->hsp_list, hsp);
hsp_set->is_empty = FALSE;
}
return;
}
/* FIXME: optimisation: could store HSPs as a list up until
* filter_threshold, then convert to a PQueue
*/
void HSPset_seed_hsp(HSPset *hsp_set,
guint query_start, guint target_start){
register gint diag_pos
= ((target_start * hsp_set->param->match->query->advance)
-(query_start * hsp_set->param->match->target->advance));
register gint query_frame = query_start
% hsp_set->param->match->query->advance,
target_frame = target_start
% hsp_set->param->match->target->advance;
register gint section_pos = (diag_pos + hsp_set->query->len)
% hsp_set->query->len;
HSP nascent_hsp;
g_assert(!hsp_set->is_finalised);
/**/
g_assert(section_pos >= 0);
g_assert(section_pos < hsp_set->query->len);
/* Check whether we have seen this HSP already */
if(target_start < hsp_set->horizon[0]
[section_pos]
[query_frame]
[target_frame])
return;
if(hsp_set->param->seed_repeat > 1){
if(++hsp_set->horizon[1][section_pos][query_frame][target_frame]
< hsp_set->param->seed_repeat)
return;
hsp_set->horizon[1][section_pos][query_frame][target_frame] = 0;
}
/* Nascent HSP building: */
nascent_hsp.hsp_set = hsp_set;
nascent_hsp.query_start = query_start;
nascent_hsp.target_start = target_start;
nascent_hsp.length = hsp_set->param->seedlen;
nascent_hsp.cobs = 0;
g_assert(HSP_check(&nascent_hsp));
HSP_trim_ends(&nascent_hsp);
/* Score is irrelevant before HSP_init() */
HSP_init(&nascent_hsp);
/* Try to make above threshold HSP using masking */
if(hsp_set->param->match->query->mask_func
|| hsp_set->param->match->target->mask_func){
HSP_extend(&nascent_hsp, TRUE);
if(nascent_hsp.score < hsp_set->param->threshold){
hsp_set->horizon[0][section_pos][query_frame][target_frame]
= HSP_target_end(&nascent_hsp);
return;
}
}
/* Extend the HSP again ignoring masking */
HSP_extend(&nascent_hsp, FALSE);
HSP_store(&nascent_hsp);
hsp_set->horizon[0][section_pos][query_frame][target_frame]
= HSP_target_end(&nascent_hsp);
return;
}
void HSPset_add_known_hsp(HSPset *hsp_set,
guint query_start, guint target_start,
guint length){
HSP nascent_hsp;
nascent_hsp.hsp_set = hsp_set;
nascent_hsp.query_start = query_start;
nascent_hsp.target_start = target_start;
nascent_hsp.length = length;
nascent_hsp.cobs = 0;
/* Score is irrelevant before HSP_init() */
HSP_init(&nascent_hsp);
HSP_store(&nascent_hsp);
return;
}
static void HSPset_seed_hsp_sorted(HSPset *hsp_set,
guint query_start, guint target_start,
gint ***horizon){
HSP nascent_hsp;
register gint diag_pos
= ((target_start * hsp_set->param->match->query->advance)
-(query_start * hsp_set->param->match->target->advance));
register gint query_frame = query_start
% hsp_set->param->match->query->advance,
target_frame = target_start
% hsp_set->param->match->target->advance;
register gint section_pos = (diag_pos + hsp_set->query->len)
% hsp_set->query->len;
g_assert(!hsp_set->is_finalised);
g_assert(!hsp_set->horizon);
g_assert(section_pos >= 0);
g_assert(section_pos < hsp_set->query->len);
/**/
if(horizon[1][query_frame][target_frame] != section_pos){
horizon[1][query_frame][target_frame] = section_pos;
horizon[0][query_frame][target_frame] = 0;
horizon[2][query_frame][target_frame] = 0;
}
if(++horizon[2][query_frame][target_frame] < hsp_set->param->seed_repeat)
return;
horizon[2][query_frame][target_frame] = 0;
/* Check whether we have seen this HSP already */
if(target_start < horizon[0][query_frame][target_frame])
return;
/**/
/* Nascent HSP building: */
nascent_hsp.hsp_set = hsp_set;
nascent_hsp.query_start = query_start;
nascent_hsp.target_start = target_start;
nascent_hsp.length = hsp_set->param->seedlen;
nascent_hsp.cobs = 0;
g_assert(HSP_check(&nascent_hsp));
HSP_trim_ends(&nascent_hsp);
/* Score is irrelevant before HSP_init() */
HSP_init(&nascent_hsp);
/* Try to make above threshold HSP using masking */
if(hsp_set->param->match->query->mask_func
|| hsp_set->param->match->target->mask_func){
HSP_extend(&nascent_hsp, TRUE);
if(nascent_hsp.score < hsp_set->param->threshold){
horizon[0][query_frame][target_frame]
= HSP_target_end(&nascent_hsp);
return;
}
}
/* Extend the HSP again ignoring masking */
HSP_extend(&nascent_hsp, FALSE);
HSP_store(&nascent_hsp);
/**/
horizon[0][query_frame][target_frame] = HSP_target_end(&nascent_hsp);
return;
}
/* horizon[0] = diag
* horizon[1] = target_end
* horizon[2] = repeat_count
*/
/* Need to use the global to pass q,t advance to qsort compare func */
static HSPset *HSPset_seed_compare_hsp_set = NULL;
static int HSPset_seed_compare(const void *a, const void *b){
register guint *seed_a = (guint*)a,
*seed_b = (guint*)b;
register gint diag_a, diag_b;
register HSPset *hsp_set = HSPset_seed_compare_hsp_set;
g_assert(hsp_set);
diag_a = ((seed_a[1] * hsp_set->param->match->query->advance)
- (seed_a[0] * hsp_set->param->match->target->advance)),
diag_b = ((seed_b[1] * hsp_set->param->match->query->advance)
- (seed_b[0] * hsp_set->param->match->target->advance));
if(diag_a == diag_b)
return seed_a[0] - seed_b[0];
return diag_a - diag_b;
}
void HSPset_seed_all_hsps(HSPset *hsp_set,
guint *seed_list, guint seed_list_len){
register gint i;
register gint ***horizon;
register gint qpos, tpos;
if(seed_list_len > 1){
HSPset_seed_compare_hsp_set = hsp_set;
qsort(seed_list, seed_list_len, sizeof(guint) << 1,
HSPset_seed_compare);
HSPset_seed_compare_hsp_set = NULL;
}
if(seed_list_len){
horizon = (gint***)Matrix3d_create(3,
hsp_set->param->match->query->advance,
hsp_set->param->match->target->advance,
sizeof(gint));
for(i = 0; i < seed_list_len; i++){
HSPset_seed_hsp_sorted(hsp_set,
seed_list[(i << 1)],
seed_list[(i << 1) + 1],
horizon);
qpos = seed_list[(i << 1)];
tpos = seed_list[(i << 1) + 1];
}
g_free(horizon);
}
HSPset_finalise(hsp_set);
return;
}
/**/
HSPset *HSPset_finalise(HSPset *hsp_set){
register gint i;
register HSP *hsp;
register PQueue *pq;
g_assert(!hsp_set->is_finalised);
hsp_set->is_finalised = TRUE;
if(hsp_set->param->has->filter_threshold && (!hsp_set->is_empty)){
/* Get HSPs from each PQueue */
for(i = 0; i < hsp_set->query->len; i++){
pq = hsp_set->filter[i];
if(pq){
while(PQueue_total(pq)){
hsp = PQueue_pop(pq);
g_ptr_array_add(hsp_set->hsp_list, hsp);
}
}
}
}
/* Set cobs for each HSP */
if(!hsp_set->param->has->filter_threshold){
for(i = 0; i < hsp_set->hsp_list->len; i++){
hsp = hsp_set->hsp_list->pdata[i];
hsp->cobs = HSP_find_cobs(hsp);
}
}
hsp_set->is_finalised = TRUE;
return hsp_set;
}
/**/
static int HSPset_sort_by_diag_then_query_start(const void *a,
const void *b){
register HSP **hsp_a = (HSP**)a, **hsp_b = (HSP**)b;
register gint diag_a = HSP_diagonal(*hsp_a),
diag_b = HSP_diagonal(*hsp_b);
if(diag_a == diag_b)
return (*hsp_a)->query_start - (*hsp_b)->query_start;
return diag_a - diag_b;
}
static Match_Score HSP_score_overlap(HSP *left, HSP *right){
register Match_Score score = 0;
register gint query_pos, target_pos;
g_assert(left->hsp_set == right->hsp_set);
g_assert(HSP_diagonal(left) == HSP_diagonal(right));
query_pos = HSP_query_end(left) - HSP_query_advance(left);
target_pos = HSP_target_end(left) - HSP_target_advance(left);
while(query_pos >= right->query_start){
score += HSP_get_score(left, query_pos, target_pos);
query_pos -= HSP_query_advance(left);
target_pos -= HSP_target_advance(left);
}
query_pos = right->query_start;
target_pos = right->target_start;
while(query_pos < (HSP_query_end(left)- HSP_query_advance(right))){
score += HSP_get_score(right, query_pos, target_pos);
query_pos += HSP_query_advance(right);
target_pos += HSP_target_advance(right);
}
return score;
}
/* Returns score for overlapping region of HSPs on same diagonal */
void HSPset_filter_ungapped(HSPset *hsp_set){
register GPtrArray *new_hsp_list;
register HSP *curr_hsp, *prev_hsp;
register gboolean del_prev, del_curr;
register gint i;
register Match_Score score;
/* Filter strongly overlapping HSPs on same diagonal
* but different frames (happens with 3:3 HSPs only)
*/
if((hsp_set->hsp_list->len > 1)
&& (hsp_set->param->match->query->advance == 3)
&& (hsp_set->param->match->target->advance == 3)){
/* FIXME: should not sort when using all-at-once HSPset */
qsort(hsp_set->hsp_list->pdata, hsp_set->hsp_list->len,
sizeof(gpointer), HSPset_sort_by_diag_then_query_start);
prev_hsp = hsp_set->hsp_list->pdata[0];
del_prev = FALSE;
del_curr = FALSE;
new_hsp_list = g_ptr_array_new();
for(i = 1; i < hsp_set->hsp_list->len; i++){
curr_hsp = hsp_set->hsp_list->pdata[i];
del_curr = FALSE;
if((HSP_diagonal(prev_hsp) == HSP_diagonal(curr_hsp))
&& (HSP_query_end(prev_hsp) > curr_hsp->query_start)){
score = HSP_score_overlap(prev_hsp, curr_hsp);
if((score << 1) > (curr_hsp->score + prev_hsp->score)){
/* FIXME: use codon_usage scores here instead */
if(prev_hsp->score < curr_hsp->score){
del_prev = TRUE;
} else {
del_curr = TRUE;
}
}
}
if(del_prev)
HSP_destroy(prev_hsp);
else
g_ptr_array_add(new_hsp_list, prev_hsp);
prev_hsp = curr_hsp;
del_prev = del_curr;
}
if(del_prev)
HSP_destroy(prev_hsp);
else
g_ptr_array_add(new_hsp_list, prev_hsp);
g_ptr_array_free(hsp_set->hsp_list, TRUE);
hsp_set->hsp_list = new_hsp_list;
}
return;
}
/**/
#define HSPset_SList_PAGE_BIT_WIDTH 10
#define HSPset_SList_PAGE_SIZE (1 << HSPset_SList_PAGE_BIT_WIDTH)
RecycleBin *HSPset_SList_RecycleBin_create(void){
return RecycleBin_create("HSPset_Slist", sizeof(HSPset_SList_Node),
4096);
}
HSPset_SList_Node *HSPset_SList_append(RecycleBin *recycle_bin,
HSPset_SList_Node *next,
gint query_pos, gint target_pos){
register HSPset_SList_Node *node = RecycleBin_alloc(recycle_bin);
node->next = next;
node->query_pos = query_pos;
node->target_pos = target_pos;
return node;
}
#if 0
typedef struct {
gint page_alloc;
gint page_total;
HSPset_SList_Node **diag_page_list;
gint ****horizon;
gint *page_used;
gint page_used_total;
} HSPset_SeedData;
static HSPset_SeedData *HSPset_SeedData_create(HSP_Param *hsp_param,
gint target_len){
register HSPset_SeedData *seed_data = g_new(HSPset_SeedData, 1);
seed_data->page_total = (target_len
>> HSPset_SList_PAGE_BIT_WIDTH) + 1;
seed_data->page_alloc = seed_data->page_total;
seed_data->diag_page_list = g_new0(HSPset_SList_Node*, seed_data->page_total);
seed_data->page_used = g_new(gint, seed_data->page_total);
seed_data->horizon = (gint****)Matrix4d_create(
2 + ((hsp_param->seed_repeat > 1)?1:0),
HSPset_SList_PAGE_SIZE,
hsp_param->match->query->advance,
hsp_param->match->target->advance,
sizeof(gint));
seed_data->page_used_total = 0;
return seed_data;
}
static void HSPset_SeedData_destroy(HSPset_SeedData *seed_data){
g_free(seed_data->diag_page_list);
g_free(seed_data->page_used);
g_free(seed_data->horizon);
g_free(seed_data);
return;
}
static void HSPset_SeedData_set_target_len(HSPset_SeedData *seed_data,
HSPset *hsp_set){
register gint new_page_total = (hsp_set->target->len
>> HSPset_SList_PAGE_BIT_WIDTH) + 1;
register gint i, a, b, c, d;
seed_data->page_total = new_page_total;
if(seed_data->page_alloc < new_page_total){
seed_data->page_alloc = seed_data->page_total;
g_free(seed_data->diag_page_list);
seed_data->diag_page_list = g_new(HSPset_SList_Node*,
seed_data->page_total);
g_free(seed_data->page_used);
seed_data->page_used = g_new(gint, seed_data->page_total);
}
/* Clear diag_page_list */
for(i = 0; i < seed_data->page_total; i++)
seed_data->diag_page_list[i] = 0;
/* Clear horizon */
for(a = 2 + ((hsp_set->param->seed_repeat > 1)?1:0); a >= 0; a--)
for(b = HSPset_SList_PAGE_SIZE; b >= 0; b--)
for(c = hsp_set->param->match->query->advance; c >= 0; c--)
for(d = hsp_set->param->match->target->advance; d >= 0; d--)
seed_data->horizon[a][b][c][d] = 0;
seed_data->page_used_total = 0;
return;
}
#endif /* 0 */
void HSPset_seed_all_qy_sorted(HSPset *hsp_set, HSPset_SList_Node *seed_list){
register gint page_total = (hsp_set->target->len
>> HSPset_SList_PAGE_BIT_WIDTH) + 1;
register HSPset_SList_Node **diag_page_list
= g_new0(HSPset_SList_Node*, page_total);
register gint *page_used = g_new(gint, page_total);
register gint ****horizon = (gint****)Matrix4d_create(
2 + ((hsp_set->param->seed_repeat > 1)?1:0),
HSPset_SList_PAGE_SIZE,
hsp_set->param->match->query->advance,
hsp_set->param->match->target->advance,
sizeof(gint));
/*
register HSPset_SeedData *seed_data = HSPset_SeedData_create(hsp_set->param,
hsp_set->target->len);
*/
register gint i, page, diag_pos, query_frame, target_frame,
section_pos, page_pos;
register HSPset_SList_Node *seed;
register gint page_used_total = 0;
HSP nascent_hsp;
/* g_message("[%s] with [%d]", __FUNCTION__, hsp_set->target->len); */
/* HSPset_SeedData_set_target_len(seed_data, hsp_set); */
/* Bin on diagonal into pages */
while(seed_list){
seed = seed_list;
seed_list = seed_list->next;
/**/
diag_pos = (seed->target_pos
* hsp_set->param->match->query->advance)
- (seed->query_pos
* hsp_set->param->match->target->advance);
section_pos = ((diag_pos + hsp_set->target->len)
% hsp_set->target->len);
page = (section_pos >> HSPset_SList_PAGE_BIT_WIDTH);
g_assert(section_pos >= 0);
g_assert(section_pos < hsp_set->target->len);
g_assert(page >= 0);
g_assert(page < page_total);
/**/
if(!diag_page_list[page])
page_used[page_used_total++] = page;
seed->next = diag_page_list[page];
diag_page_list[page] = seed;
}
/* Seed each page using page horizon */
for(i = 0; i < page_used_total; i++){
page = page_used[i];
for(seed = diag_page_list[page]; seed; seed = seed->next){
g_assert((!seed->next)
|| (seed->query_pos <= seed->next->query_pos));
diag_pos = (seed->target_pos
* hsp_set->param->match->query->advance)
- (seed->query_pos
* hsp_set->param->match->target->advance);
query_frame = seed->query_pos
% hsp_set->param->match->query->advance;
target_frame = seed->target_pos
% hsp_set->param->match->target->advance;
section_pos = ((diag_pos + hsp_set->target->len)
% hsp_set->target->len);
page_pos = section_pos
- (page << HSPset_SList_PAGE_BIT_WIDTH);
g_assert(page_pos >= 0);
g_assert(page_pos < HSPset_SList_PAGE_SIZE);
/* Clear if page has changed */
if(horizon[1][page_pos][query_frame][target_frame] != page){
horizon[0][page_pos][query_frame][target_frame] = 0;
horizon[1][page_pos][query_frame][target_frame] = page;
if(hsp_set->param->seed_repeat > 1)
horizon[2][page_pos][query_frame][target_frame] = 0;
}
if(seed->query_pos < horizon[0][page_pos][query_frame][target_frame])
continue;
if(hsp_set->param->seed_repeat > 1){
if(++horizon[2][page_pos][query_frame][target_frame]
< hsp_set->param->seed_repeat){
continue;
}
horizon[2][page_pos][query_frame][target_frame] = 0;
}
/* Nascent HSP building: */
nascent_hsp.hsp_set = hsp_set;
nascent_hsp.query_start = seed->query_pos;
nascent_hsp.target_start = seed->target_pos;
nascent_hsp.length = hsp_set->param->seedlen;
nascent_hsp.cobs = 0;
g_assert(HSP_check(&nascent_hsp));
HSP_trim_ends(&nascent_hsp);
/* Score is irrelevant before HSP_init() */
HSP_init(&nascent_hsp);
/* Try to make above threshold HSP using masking */
if(hsp_set->param->match->query->mask_func
|| hsp_set->param->match->target->mask_func){
HSP_extend(&nascent_hsp, TRUE);
if(nascent_hsp.score < hsp_set->param->threshold){
horizon[0][page_pos][query_frame][target_frame]
= HSP_query_end(&nascent_hsp);
continue;
}
}
/* Extend the HSP again ignoring masking */
HSP_extend(&nascent_hsp, FALSE);
HSP_store(&nascent_hsp);
/**/
horizon[0][page_pos][query_frame][target_frame]
= HSP_query_end(&nascent_hsp);
}
}
g_free(diag_page_list);
g_free(page_used);
g_free(horizon);
HSPset_finalise(hsp_set);
/* HSPset_SeedData_destroy(seed_data); */
return;
}
/* horizon[horizon][mailbox][seed_repeat]
* [page_size][qadv][tadv]
*/
/**/
| hotdogee/exonerate-gff3 | src/comparison/hspset.c | C | gpl-3.0 | 51,355 |
/*
Copyright 2014 Red Hat, Inc. and/or its affiliates.
This file is part of lightblue.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.redhat.lightblue.hystrix.ldap;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.unboundid.ldap.sdk.LDAPConnection;
public abstract class AbstractLdapHystrixCommand<T> extends HystrixCommand<T>{
public static final String GROUPKEY = "ldap";
private final LDAPConnection connection;
public LDAPConnection getConnection(){
return connection;
}
public AbstractLdapHystrixCommand(LDAPConnection connection, String commandKey){
super(HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(GROUPKEY)).
andCommandKey(HystrixCommandKey.Factory.asKey(GROUPKEY + ":" + commandKey)));
this.connection = connection;
}
}
| dcrissman/lightblue-ldap | lightblue-ldap-hystrix/src/main/java/com/redhat/lightblue/hystrix/ldap/AbstractLdapHystrixCommand.java | Java | gpl-3.0 | 1,527 |
#include "intfile.hh"
dcmplx Pf8(const double x[], double es[], double esx[], double em[], double lambda, double lrs[], double bi) {
double x0=x[0];
double x1=x[1];
double x2=x[2];
dcmplx y[149];
dcmplx FOUT;
dcmplx MYI(0.,1.);
y[1]=1./bi;
y[2]=em[0];
y[3]=x0*x0;
y[4]=em[3];
y[5]=em[1];
y[6]=em[2];
y[7]=esx[0];
y[8]=y[1]*y[5];
y[9]=-(y[1]*y[7]);
y[10]=-x1;
y[11]=1.+y[10];
y[12]=x0*y[1]*y[2];
y[13]=y[1]*y[2]*y[3];
y[14]=2.*x2*y[1]*y[2]*y[3];
y[15]=y[1]*y[3]*y[5];
y[16]=x0*y[1]*y[6];
y[17]=x0*y[1]*y[4];
y[18]=2.*x1*y[1]*y[3]*y[4];
y[19]=-(y[1]*y[3]*y[7]);
y[20]=y[12]+y[13]+y[14]+y[15]+y[16]+y[17]+y[18]+y[19];
y[21]=-x0;
y[22]=1.+y[21];
y[23]=x2*x2;
y[24]=x1*x1;
y[25]=lrs[0];
y[26]=x2*y[1]*y[2];
y[27]=2.*x0*x1*y[1]*y[5];
y[28]=x1*y[1]*y[6];
y[29]=x1*y[1]*y[4];
y[30]=2.*x0*y[1]*y[4]*y[24];
y[31]=x1*x2*y[1]*y[2];
y[32]=2.*x0*x1*x2*y[1]*y[2];
y[33]=y[1]*y[2]*y[23];
y[34]=2.*x0*x1*y[1]*y[2]*y[23];
y[35]=x1*y[1]*y[5];
y[36]=x2*y[1]*y[5];
y[37]=2.*x0*x1*x2*y[1]*y[5];
y[38]=x1*x2*y[1]*y[6];
y[39]=y[1]*y[4]*y[24];
y[40]=x1*x2*y[1]*y[4];
y[41]=2.*x0*x2*y[1]*y[4]*y[24];
y[42]=-(x1*y[1]*y[7]);
y[43]=-(x2*y[1]*y[7]);
y[44]=-2.*x0*x1*x2*y[1]*y[7];
y[45]=y[8]+y[26]+y[27]+y[28]+y[29]+y[30]+y[31]+y[32]+y[33]+y[34]+y[35]+y[36]\
+y[37]+y[38]+y[39]+y[40]+y[41]+y[42]+y[43]+y[44];
y[46]=lrs[1];
y[47]=-x2;
y[48]=1.+y[47];
y[49]=y[1]*y[2];
y[50]=x1*y[1]*y[2];
y[51]=2.*x0*x1*y[1]*y[2];
y[52]=2.*x2*y[1]*y[2];
y[53]=4.*x0*x1*x2*y[1]*y[2];
y[54]=-2.*x0*x1*y[1]*y[7];
y[55]=y[8]+y[9]+y[27]+y[28]+y[29]+y[30]+y[49]+y[50]+y[51]+y[52]+y[53]+y[54];
y[56]=lambda*lambda;
y[57]=2.*x0*x2*y[1]*y[2];
y[58]=2.*x0*y[1]*y[2]*y[23];
y[59]=2.*x0*y[1]*y[5];
y[60]=2.*x0*x2*y[1]*y[5];
y[61]=y[1]*y[6];
y[62]=x2*y[1]*y[6];
y[63]=y[1]*y[4];
y[64]=2.*x1*y[1]*y[4];
y[65]=4.*x0*x1*y[1]*y[4];
y[66]=x2*y[1]*y[4];
y[67]=4.*x0*x1*x2*y[1]*y[4];
y[68]=-2.*x0*x2*y[1]*y[7];
y[69]=y[8]+y[9]+y[26]+y[57]+y[58]+y[59]+y[60]+y[61]+y[62]+y[63]+y[64]+y[65]+\
y[66]+y[67]+y[68];
y[70]=x0*x2*y[1]*y[2];
y[71]=x2*y[1]*y[2]*y[3];
y[72]=y[1]*y[2]*y[3]*y[23];
y[73]=x0*y[1]*y[5];
y[74]=x2*y[1]*y[3]*y[5];
y[75]=x0*x2*y[1]*y[6];
y[76]=2.*x0*x1*y[1]*y[4];
y[77]=x0*x2*y[1]*y[4];
y[78]=2.*x1*x2*y[1]*y[3]*y[4];
y[79]=-(x0*y[1]*y[7]);
y[80]=-(x2*y[1]*y[3]*y[7]);
y[81]=y[15]+y[16]+y[17]+y[18]+y[61]+y[70]+y[71]+y[72]+y[73]+y[74]+y[75]+y[76\
]+y[77]+y[78]+y[79]+y[80];
y[82]=lrs[2];
y[83]=2.*x1*x2*y[1]*y[2];
y[84]=2.*x1*y[1]*y[2]*y[23];
y[85]=2.*x1*y[1]*y[5];
y[86]=2.*x1*x2*y[1]*y[5];
y[87]=2.*y[1]*y[4]*y[24];
y[88]=2.*x2*y[1]*y[4]*y[24];
y[89]=-2.*x1*x2*y[1]*y[7];
y[90]=y[83]+y[84]+y[85]+y[86]+y[87]+y[88]+y[89];
y[91]=-(lambda*MYI*x0*y[22]*y[25]*y[90]);
y[92]=-(lambda*MYI*y[22]*y[25]*y[45]);
y[93]=lambda*MYI*x0*y[25]*y[45];
y[94]=1.+y[91]+y[92]+y[93];
y[95]=2.*x0*y[1]*y[4];
y[96]=2.*y[1]*y[3]*y[4];
y[97]=2.*x2*y[1]*y[3]*y[4];
y[98]=y[95]+y[96]+y[97];
y[99]=-(lambda*MYI*x1*y[11]*y[46]*y[98]);
y[100]=-(lambda*MYI*y[11]*y[46]*y[81]);
y[101]=lambda*MYI*x1*y[46]*y[81];
y[102]=1.+y[99]+y[100]+y[101];
y[103]=x0*x1*y[1]*y[2];
y[104]=x1*y[1]*y[2]*y[3];
y[105]=2.*x1*x2*y[1]*y[2]*y[3];
y[106]=x1*y[1]*y[3]*y[5];
y[107]=x0*x1*y[1]*y[6];
y[108]=x0*x1*y[1]*y[4];
y[109]=y[1]*y[3]*y[4]*y[24];
y[110]=-(x1*y[1]*y[3]*y[7]);
y[111]=y[12]+y[57]+y[61]+y[73]+y[79]+y[103]+y[104]+y[105]+y[106]+y[107]+y[10\
8]+y[109]+y[110];
y[112]=-(lambda*MYI*x1*y[11]*y[46]*y[81]);
y[113]=x1+y[112];
y[114]=-(lambda*MYI*x0*y[22]*y[25]*y[45]);
y[115]=x0+y[114];
y[116]=-(lambda*MYI*x2*y[48]*y[82]*y[111]);
y[117]=x2+y[116];
y[118]=pow(bi,-2);
y[119]=x0*x1*y[11]*y[22]*y[25]*y[46]*y[55]*y[56]*y[69];
y[120]=-(lambda*MYI*x1*y[11]*y[20]*y[46]*y[94]);
y[121]=y[119]+y[120];
y[122]=lambda*MYI*x2*y[20]*y[48]*y[82]*y[121];
y[123]=-(x0*x1*y[11]*y[20]*y[22]*y[25]*y[46]*y[56]*y[69]);
y[124]=lambda*MYI*x0*y[22]*y[25]*y[55]*y[102];
y[125]=y[123]+y[124];
y[126]=-(lambda*MYI*x2*y[48]*y[55]*y[82]*y[125]);
y[127]=pow(y[69],2);
y[128]=x0*x1*y[11]*y[22]*y[25]*y[46]*y[56]*y[127];
y[129]=y[94]*y[102];
y[130]=y[128]+y[129];
y[131]=2.*x0*y[1]*y[2];
y[132]=2.*x1*y[1]*y[2]*y[3];
y[133]=y[131]+y[132];
y[134]=-(lambda*MYI*x2*y[48]*y[82]*y[133]);
y[135]=-(lambda*MYI*y[48]*y[82]*y[111]);
y[136]=lambda*MYI*x2*y[82]*y[111];
y[137]=1.+y[134]+y[135]+y[136];
y[138]=y[130]*y[137];
y[139]=y[122]+y[126]+y[138];
y[140]=y[1]*y[113];
y[141]=y[1]*y[113]*y[115];
y[142]=y[1]*y[117];
y[143]=y[1]*y[113]*y[115]*y[117];
y[144]=y[1]+y[140]+y[141]+y[142]+y[143];
y[145]=pow(y[144],-2);
y[146]=pow(y[115],2);
y[147]=pow(y[113],2);
y[148]=pow(y[117],2);
FOUT=myLog(bi)*y[118]*y[139]*y[145]+myLog(x0)*y[118]*y[139]*y[145]+myLog(1.+\
y[92])*y[118]*y[139]*y[145]+3.*myLog(y[144])*y[118]*y[139]*y[145]-2.*myLog(\
y[61]+y[1]*y[6]*y[113]+y[1]*y[5]*y[115]+y[1]*y[4]*y[113]*y[115]+y[1]*y[5]*y\
[113]*y[115]+y[1]*y[6]*y[113]*y[115]-y[1]*y[7]*y[113]*y[115]+y[1]*y[6]*y[11\
7]+y[1]*y[2]*y[115]*y[117]+y[1]*y[5]*y[115]*y[117]-y[1]*y[7]*y[115]*y[117]+\
y[1]*y[2]*y[113]*y[115]*y[117]+y[1]*y[4]*y[113]*y[115]*y[117]+y[1]*y[6]*y[1\
13]*y[115]*y[117]+y[1]*y[5]*y[113]*y[146]+y[1]*y[2]*y[113]*y[117]*y[146]+y[\
1]*y[5]*y[113]*y[117]*y[146]-y[1]*y[7]*y[113]*y[117]*y[146]+y[1]*y[4]*y[115\
]*y[147]+y[1]*y[4]*y[146]*y[147]+y[1]*y[4]*y[117]*y[146]*y[147]+y[1]*y[2]*y\
[115]*y[148]+y[1]*y[2]*y[113]*y[146]*y[148])*y[118]*y[139]*y[145];
return (FOUT);
}
| HEPcodes/FeynHiggs | extse/OasatPdep.app/SecDec3/loop/T1234m1234/together/epstothe1/f8.cc | C++ | gpl-3.0 | 5,226 |
/*
* Syncany, www.syncany.org
* Copyright (C) 2011 Philipp C. Heckel <philipp.heckel@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.stacksync.desktop.watch.local;
import java.io.File;
import org.apache.log4j.Logger;
import com.stacksync.desktop.Environment;
import com.stacksync.desktop.Environment.OperatingSystem;
import com.stacksync.desktop.config.Config;
import com.stacksync.desktop.config.Folder;
import com.stacksync.desktop.config.profile.Profile;
import com.stacksync.desktop.index.Indexer;
import com.stacksync.desktop.util.FileUtil;
/**
*
* @author oubou68, pheckel
*/
public abstract class LocalWatcher {
protected final Logger logger = Logger.getLogger(LocalWatcher.class.getName());
protected static final Environment env = Environment.getInstance();
protected static LocalWatcher instance;
protected Config config;
protected Indexer indexer;
public LocalWatcher() {
initDependencies();
logger.info("Creating watcher ...");
}
private void initDependencies() {
config = Config.getInstance();
indexer = Indexer.getInstance();
}
public void queueCheckFile(Folder root, File file) {
// Exclude ".ignore*" files from everything
if (FileUtil.checkIgnoreFile(root, file)) {
logger.debug("Watcher: Ignoring file "+file.getAbsolutePath());
return;
}
// File vanished!
if (!file.exists()) {
logger.warn("Watcher: File "+file+" vanished. IGNORING.");
return;
}
// Add to queue
logger.info("Watcher: Checking new/modified file "+file);
indexer.queueChecked(root, file);
}
public void queueMoveFile(Folder fromRoot, File fromFile, Folder toRoot, File toFile) {
// Exclude ".ignore*" files from everything
if (FileUtil.checkIgnoreFile(fromRoot, fromFile) || FileUtil.checkIgnoreFile(toRoot, toFile)) {
logger.info("Watcher: Ignoring file "+fromFile.getAbsolutePath());
return;
}
// File vanished!
if (!toFile.exists()) {
logger.warn("Watcher: File "+toFile+" vanished. IGNORING.");
return;
}
// Add to queue
logger.info("Watcher: Moving file "+fromFile+" TO "+toFile+"");
indexer.queueMoved(fromRoot, fromFile, toRoot, toFile);
}
public void queueDeleteFile(Folder root, File file) {
// Exclude ".ignore*" files from everything
if (FileUtil.checkIgnoreFile(root, file)) {
logger.info("Watcher: Ignoring file "+file.getAbsolutePath());
return;
}
// Add to queue
logger.info("Watcher: Deleted file "+file+"");
indexer.queueDeleted(root, file);
}
public static synchronized LocalWatcher getInstance() {
if (instance != null) {
return instance;
}
if (env.getOperatingSystem() == OperatingSystem.Linux
|| env.getOperatingSystem() == OperatingSystem.Windows
|| env.getOperatingSystem() == OperatingSystem.Mac) {
instance = new CommonLocalWatcher();
return instance;
}
throw new RuntimeException("Your operating system is currently not supported: " + System.getProperty("os.name"));
}
public abstract void start();
public abstract void stop();
public abstract void watch(Profile profile);
public abstract void unwatch(Profile profile);
}
| pviotti/stacksync-desktop | src/com/stacksync/desktop/watch/local/LocalWatcher.java | Java | gpl-3.0 | 4,196 |
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2017 - ROLI Ltd.
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 5 End-User License
Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
27th April 2017).
End User License Agreement: www.juce.com/juce-5-licence
Privacy Policy: www.juce.com/juce-5-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
class ScrollBar::ScrollbarButton : public Button
{
public:
ScrollbarButton (int direc, ScrollBar& s)
: Button (String()), direction (direc), owner (s)
{
setWantsKeyboardFocus (false);
}
void paintButton (Graphics& g, bool over, bool down) override
{
getLookAndFeel().drawScrollbarButton (g, owner, getWidth(), getHeight(),
direction, owner.isVertical(), over, down);
}
void clicked() override
{
owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
}
int direction;
private:
ScrollBar& owner;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ScrollbarButton)
};
//==============================================================================
ScrollBar::ScrollBar (const bool shouldBeVertical)
: totalRange (0.0, 1.0),
visibleRange (0.0, 0.1),
singleStepSize (0.1),
thumbAreaStart (0),
thumbAreaSize (0),
thumbStart (0),
thumbSize (0),
initialDelayInMillisecs (100),
repeatDelayInMillisecs (50),
minimumDelayInMillisecs (10),
vertical (shouldBeVertical),
isDraggingThumb (false),
autohides (true)
{
setRepaintsOnMouseActivity (true);
setFocusContainer (true);
}
ScrollBar::~ScrollBar()
{
upButton = nullptr;
downButton = nullptr;
}
//==============================================================================
void ScrollBar::setRangeLimits (Range<double> newRangeLimit, NotificationType notification)
{
if (totalRange != newRangeLimit)
{
totalRange = newRangeLimit;
setCurrentRange (visibleRange, notification);
updateThumbPosition();
}
}
void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum, NotificationType notification)
{
jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
setRangeLimits (Range<double> (newMinimum, newMaximum), notification);
}
bool ScrollBar::setCurrentRange (Range<double> newRange, const NotificationType notification)
{
const Range<double> constrainedRange (totalRange.constrainRange (newRange));
if (visibleRange != constrainedRange)
{
visibleRange = constrainedRange;
updateThumbPosition();
if (notification != dontSendNotification)
triggerAsyncUpdate();
if (notification == sendNotificationSync)
handleUpdateNowIfNeeded();
return true;
}
return false;
}
void ScrollBar::setCurrentRange (const double newStart, const double newSize, NotificationType notification)
{
setCurrentRange (Range<double> (newStart, newStart + newSize), notification);
}
void ScrollBar::setCurrentRangeStart (const double newStart, NotificationType notification)
{
setCurrentRange (visibleRange.movedToStartAt (newStart), notification);
}
void ScrollBar::setSingleStepSize (const double newSingleStepSize) noexcept
{
singleStepSize = newSingleStepSize;
}
bool ScrollBar::moveScrollbarInSteps (const int howManySteps, NotificationType notification)
{
return setCurrentRange (visibleRange + howManySteps * singleStepSize, notification);
}
bool ScrollBar::moveScrollbarInPages (const int howManyPages, NotificationType notification)
{
return setCurrentRange (visibleRange + howManyPages * visibleRange.getLength(), notification);
}
bool ScrollBar::scrollToTop (NotificationType notification)
{
return setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()), notification);
}
bool ScrollBar::scrollToBottom (NotificationType notification)
{
return setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()), notification);
}
void ScrollBar::setButtonRepeatSpeed (const int newInitialDelay,
const int newRepeatDelay,
const int newMinimumDelay)
{
initialDelayInMillisecs = newInitialDelay;
repeatDelayInMillisecs = newRepeatDelay;
minimumDelayInMillisecs = newMinimumDelay;
if (upButton != nullptr)
{
upButton ->setRepeatSpeed (newInitialDelay, newRepeatDelay, newMinimumDelay);
downButton->setRepeatSpeed (newInitialDelay, newRepeatDelay, newMinimumDelay);
}
}
//==============================================================================
void ScrollBar::addListener (Listener* const listener)
{
listeners.add (listener);
}
void ScrollBar::removeListener (Listener* const listener)
{
listeners.remove (listener);
}
void ScrollBar::handleAsyncUpdate()
{
double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
listeners.call (&ScrollBar::Listener::scrollBarMoved, this, start);
}
//==============================================================================
void ScrollBar::updateThumbPosition()
{
const int minimumScrollBarThumbSize = getLookAndFeel().getMinimumScrollbarThumbSize (*this);
int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
: thumbAreaSize);
if (newThumbSize < minimumScrollBarThumbSize)
newThumbSize = jmin (minimumScrollBarThumbSize, thumbAreaSize - 1);
if (newThumbSize > thumbAreaSize)
newThumbSize = thumbAreaSize;
int newThumbStart = thumbAreaStart;
if (totalRange.getLength() > visibleRange.getLength())
newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
/ (totalRange.getLength() - visibleRange.getLength()));
setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength()
&& visibleRange.getLength() > 0.0));
if (thumbStart != newThumbStart || thumbSize != newThumbSize)
{
const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
if (vertical)
repaint (0, repaintStart, getWidth(), repaintSize);
else
repaint (repaintStart, 0, repaintSize, getHeight());
thumbStart = newThumbStart;
thumbSize = newThumbSize;
}
}
void ScrollBar::setOrientation (const bool shouldBeVertical)
{
if (vertical != shouldBeVertical)
{
vertical = shouldBeVertical;
if (upButton != nullptr)
{
upButton->direction = vertical ? 0 : 3;
downButton->direction = vertical ? 2 : 1;
}
updateThumbPosition();
}
}
void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
{
autohides = shouldHideWhenFullRange;
updateThumbPosition();
}
bool ScrollBar::autoHides() const noexcept
{
return autohides;
}
//==============================================================================
void ScrollBar::paint (Graphics& g)
{
if (thumbAreaSize > 0)
{
LookAndFeel& lf = getLookAndFeel();
const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
? thumbSize : 0;
if (vertical)
lf.drawScrollbar (g, *this, 0, thumbAreaStart, getWidth(), thumbAreaSize,
vertical, thumbStart, thumb, isMouseOver(), isMouseButtonDown());
else
lf.drawScrollbar (g, *this, thumbAreaStart, 0, thumbAreaSize, getHeight(),
vertical, thumbStart, thumb, isMouseOver(), isMouseButtonDown());
}
}
void ScrollBar::lookAndFeelChanged()
{
setComponentEffect (getLookAndFeel().getScrollbarEffect());
if (isVisible())
resized();
}
void ScrollBar::resized()
{
const int length = vertical ? getHeight() : getWidth();
LookAndFeel& lf = getLookAndFeel();
const bool buttonsVisible = lf.areScrollbarButtonsVisible();
int buttonSize = 0;
if (buttonsVisible)
{
if (upButton == nullptr)
{
addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
}
buttonSize = jmin (lf.getScrollbarButtonSize (*this), length / 2);
}
else
{
upButton = nullptr;
downButton = nullptr;
}
if (length < 32 + lf.getMinimumScrollbarThumbSize (*this))
{
thumbAreaStart = length / 2;
thumbAreaSize = 0;
}
else
{
thumbAreaStart = buttonSize;
thumbAreaSize = length - 2 * buttonSize;
}
if (upButton != nullptr)
{
Rectangle<int> r (getLocalBounds());
if (vertical)
{
upButton->setBounds (r.removeFromTop (buttonSize));
downButton->setBounds (r.removeFromBottom (buttonSize));
}
else
{
upButton->setBounds (r.removeFromLeft (buttonSize));
downButton->setBounds (r.removeFromRight (buttonSize));
}
}
updateThumbPosition();
}
void ScrollBar::parentHierarchyChanged()
{
lookAndFeelChanged();
}
void ScrollBar::mouseDown (const MouseEvent& e)
{
isDraggingThumb = false;
lastMousePos = vertical ? e.y : e.x;
dragStartMousePos = lastMousePos;
dragStartRange = visibleRange.getStart();
if (dragStartMousePos < thumbStart)
{
moveScrollbarInPages (-1);
startTimer (400);
}
else if (dragStartMousePos >= thumbStart + thumbSize)
{
moveScrollbarInPages (1);
startTimer (400);
}
else
{
isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
&& (thumbAreaSize > thumbSize);
}
}
void ScrollBar::mouseDrag (const MouseEvent& e)
{
const int mousePos = vertical ? e.y : e.x;
if (isDraggingThumb && lastMousePos != mousePos && thumbAreaSize > thumbSize)
{
const int deltaPixels = mousePos - dragStartMousePos;
setCurrentRangeStart (dragStartRange
+ deltaPixels * (totalRange.getLength() - visibleRange.getLength())
/ (thumbAreaSize - thumbSize));
}
lastMousePos = mousePos;
}
void ScrollBar::mouseUp (const MouseEvent&)
{
isDraggingThumb = false;
stopTimer();
repaint();
}
void ScrollBar::mouseWheelMove (const MouseEvent&, const MouseWheelDetails& wheel)
{
float increment = 10.0f * (vertical ? wheel.deltaY : wheel.deltaX);
if (increment < 0)
increment = jmin (increment, -1.0f);
else if (increment > 0)
increment = jmax (increment, 1.0f);
setCurrentRange (visibleRange - singleStepSize * increment);
}
void ScrollBar::timerCallback()
{
if (isMouseButtonDown())
{
startTimer (40);
if (lastMousePos < thumbStart)
setCurrentRange (visibleRange - visibleRange.getLength());
else if (lastMousePos > thumbStart + thumbSize)
setCurrentRangeStart (visibleRange.getEnd());
}
else
{
stopTimer();
}
}
bool ScrollBar::keyPressed (const KeyPress& key)
{
if (isVisible())
{
if (key == KeyPress::upKey || key == KeyPress::leftKey) return moveScrollbarInSteps (-1);
if (key == KeyPress::downKey || key == KeyPress::rightKey) return moveScrollbarInSteps (1);
if (key == KeyPress::pageUpKey) return moveScrollbarInPages (-1);
if (key == KeyPress::pageDownKey) return moveScrollbarInPages (1);
if (key == KeyPress::homeKey) return scrollToTop();
if (key == KeyPress::endKey) return scrollToBottom();
}
return false;
}
| gbevin/HEELP | JuceLibraryCode/modules/juce_gui_basics/layout/juce_ScrollBar.cpp | C++ | gpl-3.0 | 12,905 |
<?php
/*
**************************************************************************************************************************
** CORAL Resources Module v. 1.2
**
** Copyright (c) 2010 University of Notre Dame
**
** This file is part of CORAL.
**
** CORAL is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
**
** CORAL is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License along with CORAL. If not, see <http://www.gnu.org/licenses/>.
**
**************************************************************************************************************************
*/
class Resource extends DatabaseObject {
protected function defineRelationships() {}
protected function defineIsbnOrIssn() {}
protected function overridePrimaryKeyName() {}
//returns resource objects by title
public function getResourceByTitle($title){
$query = "SELECT *
FROM Resource
WHERE UPPER(titleText) = '" . str_replace("'", "''", strtoupper($title)) . "'
ORDER BY 1";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['resourceID'])){
$object = new Resource(new NamedArguments(array('primaryKey' => $result['resourceID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new Resource(new NamedArguments(array('primaryKey' => $row['resourceID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns resource objects by title
public function getResourceByIsbnOrISSN($isbnOrISSN){
$query = "SELECT DISTINCT(resourceID)
FROM IsbnOrIssn";
$i = 0;
if (!is_array($isbnOrISSN)) {
$value = $isbnOrISSN;
$isbnOrISSN = array($value);
}
foreach ($isbnOrISSN as $value) {
$query .= ($i == 0) ? " WHERE " : " OR ";
$query .= "isbnOrIssn = '" . $this->db->escapeString($value) . "'";
$i++;
}
$query .= " ORDER BY 1";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['resourceID'])){
$object = new Resource(new NamedArguments(array('primaryKey' => $result['resourceID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new Resource(new NamedArguments(array('primaryKey' => $row['resourceID'])));
array_push($objects, $object);
}
}
return $objects;
}
public function getIsbnOrIssn() {
$query = "SELECT *
FROM IsbnOrIssn
WHERE resourceID = '" . $this->resourceID . "'
ORDER BY 1";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['isbnOrIssnID'])){
$object = new IsbnOrIssn(new NamedArguments(array('primaryKey' => $result['isbnOrIssnID'])));
array_push($objects, $object);
} else {
foreach ($result as $row) {
$object = new IsbnOrIssn(new NamedArguments(array('primaryKey' => $row['isbnOrIssnID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns array of parent resource objects
public function getParentResources(){
return $this->getRelatedResources('resourceID');
}
//returns array of child resource objects
public function getChildResources(){
return $this->getRelatedResources('relatedResourceID');
}
// return array of related resource objects
private function getRelatedResources($key) {
$query = "SELECT *
FROM ResourceRelationship
WHERE $key = '" . $this->resourceID . "'
AND relationshipTypeID = '1'
ORDER BY 1";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result[$key])){
$object = new ResourceRelationship(new NamedArguments(array('primaryKey' => $result['resourceRelationshipID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new ResourceRelationship(new NamedArguments(array('primaryKey' => $row['resourceRelationshipID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns array of purchase site objects
public function getResourcePurchaseSites(){
$query = "SELECT PurchaseSite.* FROM PurchaseSite, ResourcePurchaseSiteLink RPSL where RPSL.purchaseSiteID = PurchaseSite.purchaseSiteID AND resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['purchaseSiteID'])){
$object = new PurchaseSite(new NamedArguments(array('primaryKey' => $result['purchaseSiteID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new PurchaseSite(new NamedArguments(array('primaryKey' => $row['purchaseSiteID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns array of ResourcePayment objects
public function getResourcePayments(){
$query = "SELECT * FROM ResourcePayment WHERE resourceID = '" . $this->resourceID . "' ORDER BY year DESC, fundName, subscriptionStartDate DESC";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['resourcePaymentID'])){
$object = new ResourcePayment(new NamedArguments(array('primaryKey' => $result['resourcePaymentID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new ResourcePayment(new NamedArguments(array('primaryKey' => $row['resourcePaymentID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns array of associated licenses
public function getLicenseArray(){
$config = new Configuration;
//if the lic module is installed get the lic name from lic database
if ($config->settings->licensingModule == 'Y'){
$dbName = $config->settings->licensingDatabaseName;
$resourceLicenseArray = array();
$query = "SELECT * FROM ResourceLicenseLink WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['licenseID'])){
$licArray = array();
//first, get the license name
$query = "SELECT shortName FROM " . $dbName . ".License WHERE licenseID = " . $result['licenseID'];
if ($licResult = $this->db->query($query)){
while ($licRow = $licResult->fetch_assoc()){
$licArray['license'] = $licRow['shortName'];
$licArray['licenseID'] = $result['licenseID'];
}
}
array_push($resourceLicenseArray, $licArray);
}else{
foreach ($result as $row) {
$licArray = array();
//first, get the license name
$query = "SELECT shortName FROM " . $dbName . ".License WHERE licenseID = " . $row['licenseID'];
if ($licResult = $this->db->query($query)){
while ($licRow = $licResult->fetch_assoc()){
$licArray['license'] = $licRow['shortName'];
$licArray['licenseID'] = $row['licenseID'];
}
}
array_push($resourceLicenseArray, $licArray);
}
}
return $resourceLicenseArray;
}
}
//returns array of resource license status objects
public function getResourceLicenseStatuses(){
$query = "SELECT * FROM ResourceLicenseStatus WHERE resourceID = '" . $this->resourceID . "' ORDER BY licenseStatusChangeDate desc;";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['resourceLicenseStatusID'])){
$object = new ResourceLicenseStatus(new NamedArguments(array('primaryKey' => $result['resourceLicenseStatusID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new ResourceLicenseStatus(new NamedArguments(array('primaryKey' => $row['resourceLicenseStatusID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns LicenseStatusID of the most recent resource license status
public function getCurrentResourceLicenseStatus(){
$query = "SELECT licenseStatusID FROM ResourceLicenseStatus RLS WHERE resourceID = '" . $this->resourceID . "' AND licenseStatusChangeDate = (SELECT MAX(licenseStatusChangeDate) FROM ResourceLicenseStatus WHERE ResourceLicenseStatus.resourceID = '" . $this->resourceID . "') LIMIT 0,1;";
$result = $this->db->processQuery($query, 'assoc');
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['licenseStatusID'])){
return $result['licenseStatusID'];
}
}
//returns array of authorized site objects
public function getResourceAuthorizedSites(){
$query = "SELECT AuthorizedSite.* FROM AuthorizedSite, ResourceAuthorizedSiteLink RPSL where RPSL.authorizedSiteID = AuthorizedSite.authorizedSiteID AND resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['authorizedSiteID'])){
$object = new AuthorizedSite(new NamedArguments(array('primaryKey' => $result['authorizedSiteID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new AuthorizedSite(new NamedArguments(array('primaryKey' => $row['authorizedSiteID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns array of administering site objects
public function getResourceAdministeringSites(){
$query = "SELECT AdministeringSite.* FROM AdministeringSite, ResourceAdministeringSiteLink RPSL where RPSL.administeringSiteID = AdministeringSite.administeringSiteID AND resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['administeringSiteID'])){
$object = new AdministeringSite(new NamedArguments(array('primaryKey' => $result['administeringSiteID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new AdministeringSite(new NamedArguments(array('primaryKey' => $row['administeringSiteID'])));
array_push($objects, $object);
}
}
return $objects;
}
//deletes all parent resources associated with this resource
public function removeParentResources(){
$query = "DELETE FROM ResourceRelationship WHERE resourceID = '" . $this->resourceID . "'";
return $this->db->processQuery($query);
}
//returns array of alias objects
public function getAliases(){
$query = "SELECT * FROM Alias WHERE resourceID = '" . $this->resourceID . "' order by shortName";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['aliasID'])){
$object = new Alias(new NamedArguments(array('primaryKey' => $result['aliasID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new Alias(new NamedArguments(array('primaryKey' => $row['aliasID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns array of contact objects
public function getUnarchivedContacts($moduleFilter=false){
$config = new Configuration;
$resultArray = array();
$contactsArray = array();
if (!$moduleFilter || $moduleFilter == 'resources') {
//get resource specific contacts first
$query = "SELECT C.*, GROUP_CONCAT(CR.shortName SEPARATOR '<br /> ') contactRoles
FROM Contact C, ContactRole CR, ContactRoleProfile CRP
WHERE (archiveDate = '0000-00-00' OR archiveDate is null)
AND C.contactID = CRP.contactID
AND CRP.contactRoleID = CR.contactRoleID
AND resourceID = '" . $this->resourceID . "'
GROUP BY C.contactID
ORDER BY C.name";
$result = $this->db->processQuery($query, 'assoc');
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['contactID'])){
foreach (array_keys($result) as $attributeName) {
$resultArray[$attributeName] = $result[$attributeName];
}
array_push($contactsArray, $resultArray);
}else{
foreach ($result as $row) {
$resultArray = array();
foreach (array_keys($row) as $attributeName) {
$resultArray[$attributeName] = $row[$attributeName];
}
array_push($contactsArray, $resultArray);
}
}
}
//if the org module is installed also get the org contacts from org database
if ($config->settings->organizationsModule == 'Y' && (!$moduleFilter || $moduleFilter == 'organizations')) {
$dbName = $config->settings->organizationsDatabaseName;
$query = "SELECT distinct OC.*, O.name organizationName, GROUP_CONCAT(DISTINCT CR.shortName SEPARATOR '<br /> ') contactRoles
FROM " . $dbName . ".Contact OC, " . $dbName . ".ContactRole CR, " . $dbName . ".ContactRoleProfile CRP, " . $dbName . ".Organization O, Resource R, ResourceOrganizationLink ROL
WHERE (OC.archiveDate = '0000-00-00' OR OC.archiveDate is null)
AND R.resourceID = ROL.resourceID
AND ROL.organizationID = OC.organizationID
AND CRP.contactID = OC.contactID
AND CRP.contactRoleID = CR.contactRoleID
AND O.organizationID = OC.organizationID
AND R.resourceID = '" . $this->resourceID . "'
GROUP BY OC.contactID, O.name
ORDER BY OC.name";
$result = $this->db->processQuery($query, 'assoc');
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['contactID'])){
foreach (array_keys($result) as $attributeName) {
$resultArray[$attributeName] = $result[$attributeName];
}
array_push($contactsArray, $resultArray);
}else{
foreach ($result as $row) {
$resultArray = array();
foreach (array_keys($row) as $attributeName) {
$resultArray[$attributeName] = $row[$attributeName];
}
array_push($contactsArray, $resultArray);
}
}
}
return $contactsArray;
}
//returns array of contact objects
public function getArchivedContacts(){
$config = new Configuration;
$contactsArray = array();
//get resource specific contacts
$query = "SELECT C.*, GROUP_CONCAT(CR.shortName SEPARATOR '<br /> ') contactRoles
FROM Contact C, ContactRole CR, ContactRoleProfile CRP
WHERE (archiveDate != '0000-00-00' && archiveDate != '')
AND C.contactID = CRP.contactID
AND CRP.contactRoleID = CR.contactRoleID
AND resourceID = '" . $this->resourceID . "'
GROUP BY C.contactID
ORDER BY C.name";
$result = $this->db->processQuery($query, 'assoc');
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['contactID'])){
foreach (array_keys($result) as $attributeName) {
$resultArray[$attributeName] = $result[$attributeName];
}
array_push($contactsArray, $resultArray);
}else{
foreach ($result as $row) {
$resultArray = array();
foreach (array_keys($row) as $attributeName) {
$resultArray[$attributeName] = $row[$attributeName];
}
array_push($contactsArray, $resultArray);
}
}
//if the org module is installed also get the org contacts from org database
if ($config->settings->organizationsModule == 'Y'){
$dbName = $config->settings->organizationsDatabaseName;
$query = "SELECT DISTINCT OC.*, O.name organizationName, GROUP_CONCAT(DISTINCT CR.shortName SEPARATOR '<br /> ') contactRoles
FROM " . $dbName . ".Contact OC, " . $dbName . ".ContactRole CR, " . $dbName . ".ContactRoleProfile CRP, " . $dbName . ".Organization O, Resource R, ResourceOrganizationLink ROL
WHERE (OC.archiveDate != '0000-00-00' && OC.archiveDate is not null)
AND R.resourceID = ROL.resourceID
AND ROL.organizationID = OC.organizationID
AND CRP.contactID = OC.contactID
AND CRP.contactRoleID = CR.contactRoleID
AND O.organizationID = OC.organizationID
AND R.resourceID = '" . $this->resourceID . "'
GROUP BY OC.contactID, O.name
ORDER BY OC.name";
$result = $this->db->processQuery($query, 'assoc');
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['contactID'])){
foreach (array_keys($result) as $attributeName) {
$resultArray[$attributeName] = $result[$attributeName];
}
array_push($contactsArray, $resultArray);
}else{
foreach ($result as $row) {
$resultArray = array();
foreach (array_keys($row) as $attributeName) {
$resultArray[$attributeName] = $row[$attributeName];
}
array_push($contactsArray, $resultArray);
}
}
}
return $contactsArray;
}
//returns array of contact objects
public function getCreatorsArray(){
$creatorsArray = array();
$resultArray = array();
//get resource specific creators
$query = "SELECT distinct loginID, firstName, lastName
FROM Resource R, User U
WHERE U.loginID = R.createLoginID
ORDER BY lastName, firstName, loginID";
$result = $this->db->processQuery($query, 'assoc');
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['loginID'])){
foreach (array_keys($result) as $attributeName) {
$resultArray[$attributeName] = $result[$attributeName];
}
array_push($creatorsArray, $resultArray);
}else{
foreach ($result as $row) {
$resultArray = array();
foreach (array_keys($row) as $attributeName) {
$resultArray[$attributeName] = $row[$attributeName];
}
array_push($creatorsArray, $resultArray);
}
}
return $creatorsArray;
}
//returns array of external login records
public function getExternalLoginArray(){
$config = new Configuration;
$elArray = array();
//get resource specific accounts first
$query = "SELECT EL.*, ELT.shortName externalLoginType
FROM ExternalLogin EL, ExternalLoginType ELT
WHERE EL.externalLoginTypeID = ELT.externalLoginTypeID
AND resourceID = '" . $this->resourceID . "'
ORDER BY ELT.shortName;";
$result = $this->db->processQuery($query, 'assoc');
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['externalLoginID'])){
foreach (array_keys($result) as $attributeName) {
$resultArray[$attributeName] = $result[$attributeName];
}
array_push($elArray, $resultArray);
}else{
foreach ($result as $row) {
$resultArray = array();
foreach (array_keys($row) as $attributeName) {
$resultArray[$attributeName] = $row[$attributeName];
}
array_push($elArray, $resultArray);
}
}
//if the org module is installed also get the external logins from org database
if ($config->settings->organizationsModule == 'Y'){
$dbName = $config->settings->organizationsDatabaseName;
$query = "SELECT DISTINCT EL.*, ELT.shortName externalLoginType, O.name organizationName
FROM " . $dbName . ".ExternalLogin EL, " . $dbName . ".ExternalLoginType ELT, " . $dbName . ".Organization O,
Resource R, ResourceOrganizationLink ROL
WHERE EL.externalLoginTypeID = ELT.externalLoginTypeID
AND R.resourceID = ROL.resourceID
AND ROL.organizationID = EL.organizationID
AND O.organizationID = EL.organizationID
AND R.resourceID = '" . $this->resourceID . "'
ORDER BY ELT.shortName;";
$result = $this->db->processQuery($query, 'assoc');
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['externalLoginID'])){
foreach (array_keys($result) as $attributeName) {
$resultArray[$attributeName] = $result[$attributeName];
}
array_push($elArray, $resultArray);
}else{
foreach ($result as $row) {
$resultArray = array();
foreach (array_keys($row) as $attributeName) {
$resultArray[$attributeName] = $row[$attributeName];
}
array_push($elArray, $resultArray);
}
}
}
return $elArray;
}
//returns array of notes objects
public function getNotes($tabName = NULL){
if ($tabName){
$query = "SELECT * FROM ResourceNote RN
WHERE resourceID = '" . $this->resourceID . "'
AND UPPER(tabName) = UPPER('" . $tabName . "')
ORDER BY updateDate desc";
}else{
$query = "SELECT RN.*
FROM ResourceNote RN
LEFT JOIN NoteType NT ON NT.noteTypeID = RN.noteTypeID
WHERE resourceID = '" . $this->resourceID . "'
ORDER BY updateDate desc, NT.shortName";
}
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['resourceNoteID'])){
$object = new ResourceNote(new NamedArguments(array('primaryKey' => $result['resourceNoteID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new ResourceNote(new NamedArguments(array('primaryKey' => $row['resourceNoteID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns array of the initial note object
public function getInitialNote(){
$noteType = new NoteType();
$query = "SELECT * FROM ResourceNote RN
WHERE resourceID = '" . $this->resourceID . "'
AND noteTypeID = " . $noteType->getInitialNoteTypeID . "
ORDER BY noteTypeID desc LIMIT 0,1";
$result = $this->db->processQuery($query, 'assoc');
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['resourceNoteID'])){
$resourceNote = new ResourceNote(new NamedArguments(array('primaryKey' => $result['resourceNoteID'])));
return $resourceNote;
} else{
$resourceNote = new ResourceNote();
return $resourceNote;
}
}
public function getIssues($archivedOnly=false){
$query = "SELECT i.*
FROM Issue i
LEFT JOIN IssueRelationship ir ON ir.issueID=i.issueID
WHERE ir.entityID={$this->resourceID} AND ir.entityTypeID=2";
if ($archivedOnly) {
$query .= " AND i.dateClosed IS NOT NULL";
} else {
$query .= " AND i.dateClosed IS NULL";
}
$query .= " ORDER BY i.dateCreated DESC";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['issueID'])){
$object = new Issue(new NamedArguments(array('primaryKey' => $result['issueID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new Issue(new NamedArguments(array('primaryKey' => $row['issueID'])));
array_push($objects, $object);
}
}
return $objects;
}
public function getDowntime($archivedOnly=false){
$query = "SELECT d.*
FROM Downtime d
WHERE d.entityID={$this->resourceID} AND d.entityTypeID=2";
if ($archivedOnly) {
$query .= " AND d.endDate < CURDATE()";
} else {
$query .= " AND (d.endDate >= CURDATE() OR d.endDate IS NULL)";
}
$query .= " ORDER BY d.dateCreated DESC";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['downtimeID'])){
$object = new Downtime(new NamedArguments(array('primaryKey' => $result['downtimeID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new Downtime(new NamedArguments(array('primaryKey' => $row['downtimeID'])));
array_push($objects, $object);
}
}
return $objects;
}
public function getExportableIssues($archivedOnly=false){
if ($this->db->config->settings->organizationsModule == 'Y' && $this->db->config->settings->organizationsDatabaseName) {
$contactsDB = $this->db->config->settings->organizationsDatabaseName;
} else {
$contactsDB = $this->db->config->database->name;
}
$query = "SELECT i.*,(SELECT GROUP_CONCAT(CONCAT(sc.name,' - ',sc.emailAddress) SEPARATOR ', ')
FROM IssueContact sic
LEFT JOIN `{$contactsDB}`.Contact sc ON sc.contactID=sic.contactID
WHERE sic.issueID=i.issueID) AS `contacts`,
(SELECT GROUP_CONCAT(se.titleText SEPARATOR ', ')
FROM IssueRelationship sir
LEFT JOIN Resource se ON (se.resourceID=sir.entityID AND sir.entityTypeID=2)
WHERE sir.issueID=i.issueID) AS `appliesto`,
(SELECT GROUP_CONCAT(sie.email SEPARATOR ', ')
FROM IssueEmail sie
WHERE sie.issueID=i.issueID) AS `CCs`
FROM Issue i
LEFT JOIN IssueRelationship ir ON ir.issueID=i.issueID
WHERE ir.entityID={$this->resourceID} AND ir.entityTypeID=2";
if ($archivedOnly) {
$query .= " AND i.dateClosed IS NOT NULL";
} else {
$query .= " AND i.dateClosed IS NULL";
}
$query .= " ORDER BY i.dateCreated DESC";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['issueID'])){
return array($result);
}else{
return $result;
}
}
public function getExportableDowntimes($archivedOnly=false){
$query = "SELECT d.*
FROM Downtime d
WHERE d.entityID={$this->resourceID} AND d.entityTypeID=2";
if ($archivedOnly) {
$query .= " AND d.endDate < CURDATE()";
} else {
$query .= " AND d.endDate >= CURDATE()";
}
$query .= " ORDER BY d.dateCreated DESC";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['downtimeID'])){
return array($result);
}else{
return $result;
}
}
//returns array of attachments objects
public function getAttachments(){
$query = "SELECT * FROM Attachment A, AttachmentType AT
WHERE AT.attachmentTypeID = A.attachmentTypeID
AND resourceID = '" . $this->resourceID . "'
ORDER BY AT.shortName";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['attachmentID'])){
$object = new Attachment(new NamedArguments(array('primaryKey' => $result['attachmentID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new Attachment(new NamedArguments(array('primaryKey' => $row['attachmentID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns array of contact objects
public function getContacts(){
$query = "SELECT * FROM Contact
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['contactID'])){
$object = new Contact(new NamedArguments(array('primaryKey' => $result['contactID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new Contact(new NamedArguments(array('primaryKey' => $row['contactID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns array of externalLogin objects
public function getExternalLogins(){
$query = "SELECT * FROM ExternalLogin
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['externalLoginID'])){
$object = new ExternalLogin(new NamedArguments(array('primaryKey' => $result['externalLoginID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new ExternalLogin(new NamedArguments(array('primaryKey' => $row['externalLoginID'])));
array_push($objects, $object);
}
}
return $objects;
}
public static function setSearch($search) {
$config = new Configuration;
if ($config->settings->defaultsort) {
$orderBy = $config->settings->defaultsort;
} else {
$orderBy = "R.createDate DESC, TRIM(LEADING 'THE ' FROM UPPER(R.titleText)) asc";
}
$defaultSearchParameters = array(
"orderBy" => $orderBy,
"page" => 1,
"recordsPerPage" => 25,
);
foreach ($defaultSearchParameters as $key => $value) {
if (!$search[$key]) {
$search[$key] = $value;
}
}
foreach ($search as $key => $value) {
$search[$key] = trim($value);
}
$_SESSION['resourceSearch'] = $search;
}
public static function resetSearch() {
Resource::setSearch(array());
}
public static function getSearch() {
if (!isset($_SESSION['resourceSearch'])) {
Resource::resetSearch();
}
return $_SESSION['resourceSearch'];
}
public static function getSearchDetails() {
// A successful mysqli_connect must be run before mysqli_real_escape_string will function. Instantiating a resource model will set up the connection
$resource = new Resource();
$search = Resource::getSearch();
$whereAdd = array();
$searchDisplay = array();
$config = new Configuration();
//if name is passed in also search alias, organizations and organization aliases
if ($search['name']) {
$nameQueryString = $resource->db->escapeString(strtoupper($search['name']));
$nameQueryString = preg_replace("/ +/", "%", $nameQueryString);
$nameQueryString = "'%" . $nameQueryString . "%'";
if ($config->settings->organizationsModule == 'Y'){
$dbName = $config->settings->organizationsDatabaseName;
$whereAdd[] = "((UPPER(R.titleText) LIKE " . $nameQueryString . ") OR (UPPER(A.shortName) LIKE " . $nameQueryString . ") OR (UPPER(O.name) LIKE " . $nameQueryString . ") OR (UPPER(OA.name) LIKE " . $nameQueryString . ") OR (UPPER(RP.titleText) LIKE " . $nameQueryString . ") OR (UPPER(RC.titleText) LIKE " . $nameQueryString . ") OR (UPPER(R.recordSetIdentifier) LIKE " . $nameQueryString . "))";
}else{
$whereAdd[] = "((UPPER(R.titleText) LIKE " . $nameQueryString . ") OR (UPPER(A.shortName) LIKE " . $nameQueryString . ") OR (UPPER(O.shortName) LIKE " . $nameQueryString . ") OR (UPPER(RP.titleText) LIKE " . $nameQueryString . ") OR (UPPER(RC.titleText) LIKE " . $nameQueryString . ") OR (UPPER(R.recordSetIdentifier) LIKE " . $nameQueryString . "))";
}
$searchDisplay[] = "Name contains: " . $search['name'];
}
//get where statements together (and escape single quotes)
if ($search['resourceID']) {
$whereAdd[] = "R.resourceID = '" . $resource->db->escapeString($search['resourceID']) . "'";
$searchDisplay[] = "Resource ID: " . $search['resourceID'];
}
if ($search['resourceISBNOrISSN']) {
$resourceISBNOrISSN = $resource->db->escapeString(str_replace("-","",$search['resourceISBNOrISSN']));
$whereAdd[] = "REPLACE(I.isbnOrIssn,'-','') = '" . $resourceISBNOrISSN . "'";
$searchDisplay[] = "ISSN/ISBN: " . $search['resourceISBNOrISSN'];
}
if ($search['fund']) {
$fund = $resource->db->escapeString(str_replace("-","",$search['fund']));
$whereAdd[] = "REPLACE(RPAY.fundName,'-','') = '" . $fund . "'";
$searchDisplay[] = "Fund: " . $search['fund'];
}
if ($search['stepName']) {
$status = new Status();
$completedStatusID = $status->getIDFromName('complete');
$whereAdd[] = "(R.statusID != $completedStatusID AND RS.stepName = '" . $resource->db->escapeString($search['stepName']) . "' AND RS.stepStartDate IS NOT NULL AND RS.stepEndDate IS NULL)";
$searchDisplay[] = "Routing Step: " . $search['stepName'];
}
if ($search['parent'] != null) {
$parentadd = "(" . $search['parent'] . ".relationshipTypeID = 1";
$parentadd .= ")";
$whereAdd[] = $parentadd;
}
if ($search['statusID']) {
$whereAdd[] = "R.statusID = '" . $resource->db->escapeString($search['statusID']) . "'";
$status = new Status(new NamedArguments(array('primaryKey' => $search['statusID'])));
$searchDisplay[] = "Status: " . $status->shortName;
}
if ($search['creatorLoginID']) {
$whereAdd[] = "R.createLoginID = '" . $resource->db->escapeString($search['creatorLoginID']) . "'";
$createUser = new User(new NamedArguments(array('primaryKey' => $search['creatorLoginID'])));
if ($createUser->firstName){
$name = $createUser->lastName . ", " . $createUser->firstName;
}else{
$name = $createUser->loginID;
}
$searchDisplay[] = "Creator: " . $name;
}
if ($search['resourceFormatID']) {
$whereAdd[] = "R.resourceFormatID = '" . $resource->db->escapeString($search['resourceFormatID']) . "'";
$resourceFormat = new ResourceFormat(new NamedArguments(array('primaryKey' => $search['resourceFormatID'])));
$searchDisplay[] = "Resource Format: " . $resourceFormat->shortName;
}
if ($search['acquisitionTypeID']) {
$whereAdd[] = "R.acquisitionTypeID = '" . $resource->db->escapeString($search['acquisitionTypeID']) . "'";
$acquisitionType = new AcquisitionType(new NamedArguments(array('primaryKey' => $search['acquisitionTypeID'])));
$searchDisplay[] = "Acquisition Type: " . $acquisitionType->shortName;
}
if ($search['resourceNote']) {
$whereAdd[] = "UPPER(RN.noteText) LIKE UPPER('%" . $resource->db->escapeString($search['resourceNote']) . "%')";
$searchDisplay[] = "Note contains: " . $search['resourceNote'];
}
if ($search['createDateStart']) {
$whereAdd[] = "R.createDate >= STR_TO_DATE('" . $resource->db->escapeString($search['createDateStart']) . "','%m/%d/%Y')";
if (!$search['createDateEnd']) {
$searchDisplay[] = "Created on or after: " . $search['createDateStart'];
} else {
$searchDisplay[] = "Created between: " . $search['createDateStart'] . " and " . $search['createDateEnd'];
}
}
if ($search['createDateEnd']) {
$whereAdd[] = "R.createDate <= STR_TO_DATE('" . $resource->db->escapeString($search['createDateEnd']) . "','%m/%d/%Y')";
if (!$search['createDateStart']) {
$searchDisplay[] = "Created on or before: " . $search['createDateEnd'];
}
}
if ($search['startWith']) {
$whereAdd[] = "TRIM(LEADING 'THE ' FROM UPPER(R.titleText)) LIKE UPPER('" . $resource->db->escapeString($search['startWith']) . "%')";
$searchDisplay[] = "Starts with: " . $search['startWith'];
}
//the following are not-required fields with dropdowns and have "none" as an option
if ($search['resourceTypeID'] == 'none'){
$whereAdd[] = "((R.resourceTypeID IS NULL) OR (R.resourceTypeID = '0'))";
$searchDisplay[] = "Resource Type: none";
}else if ($search['resourceTypeID']){
$whereAdd[] = "R.resourceTypeID = '" . $resource->db->escapeString($search['resourceTypeID']) . "'";
$resourceType = new ResourceType(new NamedArguments(array('primaryKey' => $search['resourceTypeID'])));
$searchDisplay[] = "Resource Type: " . $resourceType->shortName;
}
if ($search['generalSubjectID'] == 'none'){
$whereAdd[] = "((GDLINK.generalSubjectID IS NULL) OR (GDLINK.generalSubjectID = '0'))";
$searchDisplay[] = "Resource Type: none";
}else if ($search['generalSubjectID']){
$whereAdd[] = "GDLINK.generalSubjectID = '" . $resource->db->escapeString($search['generalSubjectID']) . "'";
$generalSubject = new GeneralSubject(new NamedArguments(array('primaryKey' => $search['generalSubjectID'])));
$searchDisplay[] = "General Subject: " . $generalSubject->shortName;
}
if ($search['detailedSubjectID'] == 'none'){
$whereAdd[] = "((GDLINK.detailedSubjectID IS NULL) OR (GDLINK.detailedSubjectID = '0') OR (GDLINK.detailedSubjectID = '-1'))";
$searchDisplay[] = "Resource Type: none";
}else if ($search['detailedSubjectID']){
$whereAdd[] = "GDLINK.detailedSubjectID = '" . $resource->db->escapeString($search['detailedSubjectID']) . "'";
$detailedSubject = new DetailedSubject(new NamedArguments(array('primaryKey' => $search['detailedSubjectID'])));
$searchDisplay[] = "Detailed Subject: " . $detailedSubject->shortName;
}
if ($search['noteTypeID'] == 'none'){
$whereAdd[] = "(RN.noteTypeID IS NULL) AND (RN.noteText IS NOT NULL)";
$searchDisplay[] = "Note Type: none";
}else if ($search['noteTypeID']){
$whereAdd[] = "RN.noteTypeID = '" . $resource->db->escapeString($search['noteTypeID']) . "'";
$noteType = new NoteType(new NamedArguments(array('primaryKey' => $search['noteTypeID'])));
$searchDisplay[] = "Note Type: " . $noteType->shortName;
}
if ($search['purchaseSiteID'] == 'none'){
$whereAdd[] = "RPSL.purchaseSiteID IS NULL";
$searchDisplay[] = "Purchase Site: none";
}else if ($search['purchaseSiteID']){
$whereAdd[] = "RPSL.purchaseSiteID = '" . $resource->db->escapeString($search['purchaseSiteID']) . "'";
$purchaseSite = new PurchaseSite(new NamedArguments(array('primaryKey' => $search['purchaseSiteID'])));
$searchDisplay[] = "Purchase Site: " . $purchaseSite->shortName;
}
if ($search['authorizedSiteID'] == 'none'){
$whereAdd[] = "RAUSL.authorizedSiteID IS NULL";
$searchDisplay[] = "Authorized Site: none";
}else if ($search['authorizedSiteID']){
$whereAdd[] = "RAUSL.authorizedSiteID = '" . $resource->db->escapeString($search['authorizedSiteID']) . "'";
$authorizedSite = new AuthorizedSite(new NamedArguments(array('primaryKey' => $search['authorizedSiteID'])));
$searchDisplay[] = "Authorized Site: " . $authorizedSite->shortName;
}
if ($search['administeringSiteID'] == 'none'){
$whereAdd[] = "RADSL.administeringSiteID IS NULL";
$searchDisplay[] = "Administering Site: none";
}else if ($search['administeringSiteID']){
$whereAdd[] = "RADSL.administeringSiteID = '" . $resource->db->escapeString($search['administeringSiteID']) . "'";
$administeringSite = new AdministeringSite(new NamedArguments(array('primaryKey' => $search['administeringSiteID'])));
$searchDisplay[] = "Administering Site: " . $administeringSite->shortName;
}
if ($search['authenticationTypeID'] == 'none'){
$whereAdd[] = "R.authenticationTypeID IS NULL";
$searchDisplay[] = "Authentication Type: none";
}else if ($search['authenticationTypeID']){
$whereAdd[] = "R.authenticationTypeID = '" . $resource->db->escapeString($search['authenticationTypeID']) . "'";
$authenticationType = new AuthenticationType(new NamedArguments(array('primaryKey' => $search['authenticationTypeID'])));
$searchDisplay[] = "Authentication Type: " . $authenticationType->shortName;
}
if ($search['catalogingStatusID'] == 'none') {
$whereAdd[] = "(R.catalogingStatusID IS NULL)";
$searchDisplay[] = "Cataloging Status: none";
} else if ($search['catalogingStatusID']) {
$whereAdd[] = "R.catalogingStatusID = '" . $resource->db->escapeString($search['catalogingStatusID']) . "'";
$catalogingStatus = new CatalogingStatus(new NamedArguments(array('primaryKey' => $search['catalogingStatusID'])));
$searchDisplay[] = "Cataloging Status: " . $catalogingStatus->shortName;
}
$orderBy = $search['orderBy'];
$page = $search['page'];
$recordsPerPage = $search['recordsPerPage'];
return array("where" => $whereAdd, "page" => $page, "order" => $orderBy, "perPage" => $recordsPerPage, "display" => $searchDisplay);
}
public function searchQuery($whereAdd, $orderBy = '', $limit = '', $count = false) {
$config = new Configuration();
$status = new Status();
if ($config->settings->organizationsModule == 'Y'){
$dbName = $config->settings->organizationsDatabaseName;
$orgJoinAdd = "LEFT JOIN " . $dbName . ".Organization O ON O.organizationID = ROL.organizationID
LEFT JOIN " . $dbName . ".Alias OA ON OA.organizationID = ROL.organizationID";
}else{
$orgJoinAdd = "LEFT JOIN Organization O ON O.organizationID = ROL.organizationID";
}
$savedStatusID = intval($status->getIDFromName('saved'));
//also add to not retrieve saved records
$whereAdd[] = "R.statusID != " . $savedStatusID;
if (count($whereAdd) > 0){
$whereStatement = " WHERE " . implode(" AND ", $whereAdd);
}else{
$whereStatement = "";
}
if ($count) {
$select = "SELECT COUNT(DISTINCT R.resourceID) count";
$groupBy = "";
} else {
$select = "SELECT R.resourceID, R.titleText, AT.shortName acquisitionType, R.createLoginID, CU.firstName, CU.lastName, R.createDate, S.shortName status,
GROUP_CONCAT(DISTINCT A.shortName, I.isbnOrIssn ORDER BY A.shortName DESC SEPARATOR '<br />') aliases";
$groupBy = "GROUP BY R.resourceID";
}
$referenced_tables = array();
$table_matches = array();
// Build a list of tables that are referenced by the select and where statements in order to limit the number of joins performed in the search.
preg_match_all("/[A-Z]+(?=[.][A-Z]+)/i", $select, $table_matches);
$referenced_tables = array_unique($table_matches[0]);
preg_match_all("/[A-Z]+(?=[.][A-Z]+)/i", $whereStatement, $table_matches);
$referenced_tables = array_unique(array_merge($referenced_tables, $table_matches[0]));
// These join statements will only be included in the query if the alias is referenced by the select and/or where.
$conditional_joins = explode("\n", "LEFT JOIN ResourceFormat RF ON R.resourceFormatID = RF.resourceFormatID
LEFT JOIN ResourceType RT ON R.resourceTypeID = RT.resourceTypeID
LEFT JOIN AcquisitionType AT ON R.acquisitionTypeID = AT.acquisitionTypeID
LEFT JOIN Status S ON R.statusID = S.statusID
LEFT JOIN User CU ON R.createLoginID = CU.loginID
LEFT JOIN ResourcePurchaseSiteLink RPSL ON R.resourceID = RPSL.resourceID
LEFT JOIN ResourceAuthorizedSiteLink RAUSL ON R.resourceID = RAUSL.resourceID
LEFT JOIN ResourceAdministeringSiteLink RADSL ON R.resourceID = RADSL.resourceID
LEFT JOIN ResourcePayment RPAY ON R.resourceID = RPAY.resourceID
LEFT JOIN ResourceNote RN ON R.resourceID = RN.resourceID
LEFT JOIN ResourceStep RS ON R.resourceID = RS.resourceID
LEFT JOIN IsbnOrIssn I ON R.resourceID = I.resourceID
");
$additional_joins = array();
foreach($conditional_joins as $join) {
$match = array();
preg_match("/[A-Z]+(?= ON )/i", $join, $match);
$table_name = $match[0];
if (in_array($table_name, $referenced_tables)) {
$additional_joins[] = $join;
}
}
$query = $select . "
FROM Resource R
LEFT JOIN Alias A ON R.resourceID = A.resourceID
LEFT JOIN ResourceOrganizationLink ROL ON R.resourceID = ROL.resourceID
" . $orgJoinAdd . "
LEFT JOIN ResourceRelationship RRC ON RRC.relatedResourceID = R.resourceID
LEFT JOIN ResourceRelationship RRP ON RRP.resourceID = R.resourceID
LEFT JOIN ResourceSubject RSUB ON R.resourceID = RSUB.resourceID
LEFT JOIN Resource RC ON RC.resourceID = RRC.resourceID
LEFT JOIN Resource RP ON RP.resourceID = RRP.relatedResourceID
LEFT JOIN GeneralDetailSubjectLink GDLINK ON RSUB.generalDetailSubjectLinkID = GDLINK.generalDetailSubjectLinkID
" . implode("\n", $additional_joins) . "
" . $whereStatement . "
" . $groupBy;
if ($orderBy) {
$query .= "\nORDER BY " . $orderBy;
}
if ($limit) {
$query .= "\nLIMIT " . $limit;
}
return $query;
}
//returns array based on search
public function search($whereAdd, $orderBy, $limit){
$query = $this->searchQuery($whereAdd, $orderBy, $limit, false);
$result = $this->db->processQuery($query, 'assoc');
$searchArray = array();
$resultArray = array();
//need to do this since it could be that there's only one result and this is how the dbservice returns result
if (isset($result['resourceID'])){
foreach (array_keys($result) as $attributeName) {
$resultArray[$attributeName] = $result[$attributeName];
}
array_push($searchArray, $resultArray);
}else{
foreach ($result as $row) {
$resultArray = array();
foreach (array_keys($row) as $attributeName) {
$resultArray[$attributeName] = $row[$attributeName];
}
array_push($searchArray, $resultArray);
}
}
return $searchArray;
}
public function searchCount($whereAdd) {
$query = $this->searchQuery($whereAdd, '', '', true);
$result = $this->db->processQuery($query, 'assoc');
//echo $query;
return $result['count'];
}
//used for A-Z on search (index)
public function getAlphabeticalList(){
$alphArray = array();
$result = $this->db->query("SELECT DISTINCT UPPER(SUBSTR(TRIM(LEADING 'The ' FROM titleText),1,1)) letter, COUNT(SUBSTR(TRIM(LEADING 'The ' FROM titleText),1,1)) letter_count
FROM Resource R
GROUP BY SUBSTR(TRIM(LEADING 'The ' FROM titleText),1,1)
ORDER BY 1;");
while ($row = $result->fetch_assoc()){
$alphArray[$row['letter']] = $row['letter_count'];
}
return $alphArray;
}
//returns array based on search for excel output (export.php)
public function export($whereAdd, $orderBy){
$config = new Configuration();
if ($config->settings->organizationsModule == 'Y'){
$dbName = $config->settings->organizationsDatabaseName;
$orgJoinAdd = "LEFT JOIN " . $dbName . ".Organization O ON O.organizationID = ROL.organizationID
LEFT JOIN " . $dbName . ".Alias OA ON OA.organizationID = ROL.organizationID";
$orgSelectAdd = "GROUP_CONCAT(DISTINCT O.name ORDER BY O.name DESC SEPARATOR '; ') organizationNames";
}else{
$orgJoinAdd = "LEFT JOIN Organization O ON O.organizationID = ROL.organizationID";
$orgSelectAdd = "GROUP_CONCAT(DISTINCT O.shortName ORDER BY O.shortName DESC SEPARATOR '; ') organizationNames";
}
$licSelectAdd = '';
$licJoinAdd = '';
if ($config->settings->licensingModule == 'Y'){
$dbName = $config->settings->licensingDatabaseName;
$licJoinAdd = " LEFT JOIN ResourceLicenseLink RLL ON RLL.resourceID = R.resourceID
LEFT JOIN " . $dbName . ".License L ON RLL.licenseID = L.licenseID
LEFT JOIN ResourceLicenseStatus RLS ON RLS.resourceID = R.resourceID
LEFT JOIN LicenseStatus LS ON LS.licenseStatusID = RLS.licenseStatusID";
$licSelectAdd = "GROUP_CONCAT(DISTINCT L.shortName ORDER BY L.shortName DESC SEPARATOR '; ') licenseNames,
GROUP_CONCAT(DISTINCT LS.shortName, ': ', DATE_FORMAT(RLS.licenseStatusChangeDate, '%m/%d/%Y') ORDER BY RLS.licenseStatusChangeDate DESC SEPARATOR '; ') licenseStatuses, ";
}
$status = new Status();
//also add to not retrieve saved records
$savedStatusID = intval($status->getIDFromName('saved'));
$whereAdd[] = "R.statusID != " . $savedStatusID;
if (count($whereAdd) > 0){
$whereStatement = " WHERE " . implode(" AND ", $whereAdd);
}else{
$whereStatement = "";
}
//now actually execute query
$query = "SELECT R.resourceID, R.titleText, AT.shortName acquisitionType, CONCAT_WS(' ', CU.firstName, CU.lastName) createName,
R.createDate createDate, CONCAT_WS(' ', UU.firstName, UU.lastName) updateName,
R.updateDate updateDate, S.shortName status,
RT.shortName resourceType, RF.shortName resourceFormat, R.orderNumber, R.systemNumber, R.resourceURL, R.resourceAltURL,
R.currentStartDate, R.currentEndDate, R.subscriptionAlertEnabledInd, AUT.shortName authenticationType,
AM.shortName accessMethod, SL.shortName storageLocation, UL.shortName userLimit, R.authenticationUserName,
R.authenticationPassword, R.coverageText, CT.shortName catalogingType, CS.shortName catalogingStatus, R.recordSetIdentifier, R.bibSourceURL,
R.numberRecordsAvailable, R.numberRecordsLoaded, R.hasOclcHoldings, I.isbnOrIssn,
" . $orgSelectAdd . ",
" . $licSelectAdd . "
GROUP_CONCAT(DISTINCT A.shortName ORDER BY A.shortName DESC SEPARATOR '; ') aliases,
GROUP_CONCAT(DISTINCT PS.shortName ORDER BY PS.shortName DESC SEPARATOR '; ') purchasingSites,
GROUP_CONCAT(DISTINCT AUS.shortName ORDER BY AUS.shortName DESC SEPARATOR '; ') authorizedSites,
GROUP_CONCAT(DISTINCT ADS.shortName ORDER BY ADS.shortName DESC SEPARATOR '; ') administeringSites,
GROUP_CONCAT(DISTINCT RP.titleText ORDER BY RP.titleText DESC SEPARATOR '; ') parentResources,
GROUP_CONCAT(DISTINCT RC.titleText ORDER BY RC.titleText DESC SEPARATOR '; ') childResources,
GROUP_CONCAT(DISTINCT RPAY.fundName, ': ', ROUND(COALESCE(RPAY.paymentAmount, 0) / 100, 2), ' ', RPAY.currencyCode, ' ', OT.shortName ORDER BY RPAY.paymentAmount ASC SEPARATOR '; ') payments
FROM Resource R
LEFT JOIN Alias A ON R.resourceID = A.resourceID
LEFT JOIN ResourceOrganizationLink ROL ON R.resourceID = ROL.resourceID
" . $orgJoinAdd . "
LEFT JOIN ResourceRelationship RRC ON RRC.relatedResourceID = R.resourceID
LEFT JOIN ResourceRelationship RRP ON RRP.resourceID = R.resourceID
LEFT JOIN Resource RC ON RC.resourceID = RRC.resourceID
LEFT JOIN ResourceSubject RSUB ON R.resourceID = RSUB.resourceID
LEFT JOIN Resource RP ON RP.resourceID = RRP.relatedResourceID
LEFT JOIN GeneralDetailSubjectLink GDLINK ON RSUB.generalDetailSubjectLinkID = GDLINK.generalDetailSubjectLinkID
LEFT JOIN ResourceFormat RF ON R.resourceFormatID = RF.resourceFormatID
LEFT JOIN ResourceType RT ON R.resourceTypeID = RT.resourceTypeID
LEFT JOIN AcquisitionType AT ON R.acquisitionTypeID = AT.acquisitionTypeID
LEFT JOIN ResourceStep RS ON R.resourceID = RS.resourceID
LEFT JOIN ResourcePayment RPAY ON R.resourceID = RPAY.resourceID
LEFT JOIN OrderType OT ON RPAY.orderTypeID = OT.orderTypeID
LEFT JOIN Status S ON R.statusID = S.statusID
LEFT JOIN ResourceNote RN ON R.resourceID = RN.resourceID
LEFT JOIN NoteType NT ON RN.noteTypeID = NT.noteTypeID
LEFT JOIN User CU ON R.createLoginID = CU.loginID
LEFT JOIN User UU ON R.updateLoginID = UU.loginID
LEFT JOIN CatalogingStatus CS ON R.catalogingStatusID = CS.catalogingStatusID
LEFT JOIN CatalogingType CT ON R.catalogingTypeID = CT.catalogingTypeID
LEFT JOIN ResourcePurchaseSiteLink RPSL ON R.resourceID = RPSL.resourceID
LEFT JOIN PurchaseSite PS ON RPSL.purchaseSiteID = PS.purchaseSiteID
LEFT JOIN ResourceAuthorizedSiteLink RAUSL ON R.resourceID = RAUSL.resourceID
LEFT JOIN AuthorizedSite AUS ON RAUSL.authorizedSiteID = AUS.authorizedSiteID
LEFT JOIN ResourceAdministeringSiteLink RADSL ON R.resourceID = RADSL.resourceID
LEFT JOIN AdministeringSite ADS ON RADSL.administeringSiteID = ADS.administeringSiteID
LEFT JOIN AuthenticationType AUT ON AUT.authenticationTypeID = R.authenticationTypeID
LEFT JOIN AccessMethod AM ON AM.accessMethodID = R.accessMethodID
LEFT JOIN StorageLocation SL ON SL.storageLocationID = R.storageLocationID
LEFT JOIN UserLimit UL ON UL.userLimitID = R.userLimitID
LEFT JOIN IsbnOrIssn I ON I.resourceID = R.resourceID
" . $licJoinAdd . "
" . $whereStatement . "
GROUP BY R.resourceID
ORDER BY " . $orderBy;
$result = $this->db->processQuery(stripslashes($query), 'assoc');
$searchArray = array();
$resultArray = array();
//need to do this since it could be that there's only one result and this is how the dbservice returns result
if (isset($result['resourceID'])){
foreach (array_keys($result) as $attributeName) {
$resultArray[$attributeName] = $result[$attributeName];
}
array_push($searchArray, $resultArray);
}else{
foreach ($result as $row) {
$resultArray = array();
foreach (array_keys($row) as $attributeName) {
$resultArray[$attributeName] = $row[$attributeName];
}
array_push($searchArray, $resultArray);
}
}
return $searchArray;
}
//search used index page drop down
public function getOrganizationList(){
$config = new Configuration;
$orgArray = array();
//if the org module is installed get the org names from org database
if ($config->settings->organizationsModule == 'Y'){
$dbName = $config->settings->organizationsDatabaseName;
$query = "SELECT name, organizationID FROM " . $dbName . ".Organization ORDER BY 1;";
//otherwise get the orgs from this database
}else{
$query = "SELECT shortName name, organizationID FROM Organization ORDER BY 1;";
}
$result = $this->db->processQuery($query, 'assoc');
$resultArray = array();
//need to do this since it could be that there's only one result and this is how the dbservice returns result
if (isset($result['organizationID'])){
foreach (array_keys($result) as $attributeName) {
$resultArray[$attributeName] = $result[$attributeName];
}
array_push($orgArray, $resultArray);
}else{
foreach ($result as $row) {
$resultArray = array();
foreach (array_keys($row) as $attributeName) {
$resultArray[$attributeName] = $row[$attributeName];
}
array_push($orgArray, $resultArray);
}
}
return $orgArray;
}
//gets an array of organizations set up for this resource (organizationID, organization, organizationRole)
public function getOrganizationArray(){
$config = new Configuration;
//if the org module is installed get the org name from org database
if ($config->settings->organizationsModule == 'Y'){
$dbName = $config->settings->organizationsDatabaseName;
$resourceOrgArray = array();
$query = "SELECT * FROM ResourceOrganizationLink WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['organizationID'])){
$orgArray = array();
//first, get the organization name
$query = "SELECT name FROM " . $dbName . ".Organization WHERE organizationID = " . $result['organizationID'];
if ($orgResult = $this->db->query($query)){
while ($orgRow = $orgResult->fetch_assoc()){
$orgArray['organization'] = $orgRow['name'];
$orgArray['organizationID'] = $result['organizationID'];
}
}
//then, get the role name
$query = "SELECT * FROM " . $dbName . ".OrganizationRole WHERE organizationRoleID = " . $result['organizationRoleID'];
if ($orgResult = $this->db->query($query)){
while ($orgRow = $orgResult->fetch_assoc()){
$orgArray['organizationRoleID'] = $orgRow['organizationRoleID'];
$orgArray['organizationRole'] = $orgRow['shortName'];
}
}
array_push($resourceOrgArray, $orgArray);
}else{
foreach ($result as $row) {
$orgArray = array();
//first, get the organization name
$query = "SELECT name FROM " . $dbName . ".Organization WHERE organizationID = " . $row['organizationID'];
if ($orgResult = $this->db->query($query)){
while ($orgRow = $orgResult->fetch_assoc()){
$orgArray['organization'] = $orgRow['name'];
$orgArray['organizationID'] = $row['organizationID'];
}
}
//then, get the role name
$query = "SELECT * FROM " . $dbName . ".OrganizationRole WHERE organizationRoleID = " . $row['organizationRoleID'];
if ($orgResult = $this->db->query($query)){
while ($orgRow = $orgResult->fetch_assoc()){
$orgArray['organizationRoleID'] = $orgRow['organizationRoleID'];
$orgArray['organizationRole'] = $orgRow['shortName'];
}
}
array_push($resourceOrgArray, $orgArray);
}
}
//otherwise if the org module is not installed get the org name from this database
}else{
$resourceOrgArray = array();
$query = "SELECT * FROM ResourceOrganizationLink WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['organizationID'])){
$orgArray = array();
//first, get the organization name
$query = "SELECT shortName FROM Organization WHERE organizationID = " . $result['organizationID'];
if ($orgResult = $this->db->query($query)){
while ($orgRow = $orgResult->fetch_assoc()){
$orgArray['organization'] = $orgRow['shortName'];
$orgArray['organizationID'] = $result['organizationID'];
}
}
//then, get the role name
$query = "SELECT * FROM OrganizationRole WHERE organizationRoleID = " . $result['organizationRoleID'];
if ($orgResult = $this->db->query($query)){
while ($orgRow = $orgResult->fetch_assoc()){
$orgArray['organizationRoleID'] = $orgRow['organizationRoleID'];
$orgArray['organizationRole'] = $orgRow['shortName'];
}
}
array_push($resourceOrgArray, $orgArray);
}else{
foreach ($result as $row) {
$orgArray = array();
//first, get the organization name
$query = "SELECT shortName FROM Organization WHERE organizationID = " . $row['organizationID'];
if ($orgResult = $this->db->query($query)){
while ($orgRow = $orgResult->fetch_assoc()){
$orgArray['organization'] = $orgRow['shortName'];
$orgArray['organizationID'] = $row['organizationID'];
}
}
//then, get the role name
$query = "SELECT * FROM OrganizationRole WHERE organizationRoleID = " . $row['organizationRoleID'];
if ($orgResult = $this->db->query($query)){
while ($orgRow = $orgResult->fetch_assoc()){
$orgArray['organizationRoleID'] = $orgRow['organizationRoleID'];
$orgArray['organizationRole'] = $orgRow['shortName'];
}
}
array_push($resourceOrgArray, $orgArray);
}
}
}
return $resourceOrgArray;
}
public function getSiblingResourcesArray($organizationID) {
$query = "SELECT DISTINCT r.resourceID, r.titleText FROM ResourceOrganizationLink rol
LEFT JOIN Resource r ON r.resourceID=rol.resourceID
WHERE rol.organizationID=".$organizationID." AND r.archiveDate IS NULL
ORDER BY r.titleText";
$result = $this->db->processQuery($query, 'assoc');
if($result["resourceID"]) {
return array($result);
}
return $result;
}
//gets an array of distinct organizations set up for this resource (organizationID, organization)
public function getDistinctOrganizationArray(){
$config = new Configuration;
//if the org module is installed get the org name from org database
if ($config->settings->organizationsModule == 'Y'){
$dbName = $config->settings->organizationsDatabaseName;
$resourceOrgArray = array();
$query = "SELECT DISTINCT organizationID FROM ResourceOrganizationLink WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['organizationID'])){
$orgArray = array();
//first, get the organization name
$query = "SELECT name FROM " . $dbName . ".Organization WHERE organizationID = " . $result['organizationID'];
if ($orgResult = $this->db->query($query)){
while ($orgRow = $orgResult->fetch_assoc()){
$orgArray['organization'] = $orgRow['name'];
$orgArray['organizationID'] = $result['organizationID'];
}
}
array_push($resourceOrgArray, $orgArray);
}else{
foreach ($result as $row) {
$orgArray = array();
//first, get the organization name
$query = "SELECT DISTINCT name FROM " . $dbName . ".Organization WHERE organizationID = " . $row['organizationID'];
if ($orgResult = $this->db->query($query)){
while ($orgRow = $orgResult->fetch_assoc()){
$orgArray['organization'] = $orgRow['name'];
$orgArray['organizationID'] = $row['organizationID'];
}
}
array_push($resourceOrgArray, $orgArray);
}
}
//otherwise if the org module is not installed get the org name from this database
}else{
$resourceOrgArray = array();
$query = "SELECT DISTINCT organizationID FROM ResourceOrganizationLink WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['organizationID'])){
$orgArray = array();
//first, get the organization name
$query = "SELECT DISTINCT shortName FROM Organization WHERE organizationID = " . $result['organizationID'];
if ($orgResult = $this->db->query($query)){
while ($orgRow = $orgResult->fetch_assoc()){
$orgArray['organization'] = $orgRow['shortName'];
$orgArray['organizationID'] = $result['organizationID'];
}
}
array_push($resourceOrgArray, $orgArray);
}else{
foreach ($result as $row) {
$orgArray = array();
//first, get the organization name
$query = "SELECT DISTINCT shortName FROM Organization WHERE organizationID = " . $row['organizationID'];
if ($orgResult = $this->db->query($query)){
while ($orgRow = $orgResult->fetch_assoc()){
$orgArray['organization'] = $orgRow['shortName'];
$orgArray['organizationID'] = $row['organizationID'];
}
}
array_push($resourceOrgArray, $orgArray);
}
}
}
return $resourceOrgArray;
}
public function hasCatalogingInformation() {
return ($this->recordSetIdentifier || $this->recordSetIdentifier || $this->bibSourceURL || $this->catalogingTypeID || $this->catalogingStatusID || $this->numberRecordsAvailable || $this->numberRecordsLoaded || $this->hasOclcHoldings);
}
//removes this resource and its children
public function removeResourceAndChildren(){
// for each children
foreach ($this->getChildResources() as $instance) {
$removeChild = true;
$child = new Resource(new NamedArguments(array('primaryKey' => $instance->resourceID)));
// get parents of this children
$parents = $child->getParentResources();
// If the child ressource belongs to another parent than the one we're removing
foreach ($parents as $pinstance) {
$parentResourceObj = new Resource(new NamedArguments(array('primaryKey' => $pinstance->relatedResourceID)));
if ($parentResourceObj->resourceID != $this->resourceID) {
// We do not delete this child.
$removeChild = false;
}
}
if ($removeChild == true) {
$child->removeResource();
}
}
// Finally, we remove the parent
$this->removeResource();
}
//removes this resource
public function removeResource(){
//delete data from child linked tables
$this->removeResourceRelationships();
$this->removePurchaseSites();
$this->removeAuthorizedSites();
$this->removeAdministeringSites();
$this->removeResourceLicenses();
$this->removeResourceLicenseStatuses();
$this->removeResourceOrganizations();
$this->removeResourcePayments();
$this->removeAllSubjects();
$this->removeAllIsbnOrIssn();
$instance = new Contact();
foreach ($this->getContacts() as $instance) {
$instance->removeContactRoles();
$instance->delete();
}
$instance = new ExternalLogin();
foreach ($this->getExternalLogins() as $instance) {
$instance->delete();
}
$instance = new ResourceNote();
foreach ($this->getNotes() as $instance) {
$instance->delete();
}
$instance = new Attachment();
foreach ($this->getAttachments() as $instance) {
$instance->delete();
}
$instance = new Alias();
foreach ($this->getAliases() as $instance) {
$instance->delete();
}
$this->delete();
}
//removes resource hierarchy records
public function removeResourceRelationships(){
$query = "DELETE
FROM ResourceRelationship
WHERE resourceID = '" . $this->resourceID . "' OR relatedResourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query);
}
//removes resource purchase sites
public function removePurchaseSites(){
$query = "DELETE
FROM ResourcePurchaseSiteLink
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query);
}
//removes resource authorized sites
public function removeAuthorizedSites(){
$query = "DELETE
FROM ResourceAuthorizedSiteLink
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query);
}
//removes resource administering sites
public function removeAdministeringSites(){
$query = "DELETE
FROM ResourceAdministeringSiteLink
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query);
}
//removes payment records
public function removeResourcePayments(){
$query = "DELETE
FROM ResourcePayment
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query);
}
//removes resource licenses
public function removeResourceLicenses(){
$query = "DELETE
FROM ResourceLicenseLink
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query);
}
//removes resource license statuses
public function removeResourceLicenseStatuses(){
$query = "DELETE
FROM ResourceLicenseStatus
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query);
}
//removes resource organizations
public function removeResourceOrganizations(){
$query = "DELETE
FROM ResourceOrganizationLink
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query);
}
//removes resource note records
public function removeResourceNotes(){
$query = "DELETE
FROM ResourceNote
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query);
}
//removes resource steps
public function removeResourceSteps(){
$query = "DELETE
FROM ResourceStep
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query);
}
//search used for the resource autocomplete
public function resourceAutocomplete($q){
$resourceArray = array();
$result = $this->db->query("SELECT titleText, resourceID
FROM Resource
WHERE upper(titleText) like upper('%" . $q . "%')
ORDER BY 1;");
while ($row = $result->fetch_assoc()){
$resourceArray[] = $row['titleText'] . "|" . $row['resourceID'];
}
return $resourceArray;
}
//search used for the organization autocomplete
public function organizationAutocomplete($q){
$config = new Configuration;
$organizationArray = array();
//if the org module is installed get the org name from org database
if ($config->settings->organizationsModule == 'Y'){
$dbName = $config->settings->organizationsDatabaseName;
$result = $this->db->query("SELECT CONCAT(A.name, ' (', O.name, ')') shortName, O.organizationID
FROM " . $dbName . ".Alias A, " . $dbName . ".Organization O
WHERE A.organizationID=O.organizationID
AND upper(A.name) like upper('%" . $q . "%')
UNION
SELECT name shortName, organizationID
FROM " . $dbName . ".Organization
WHERE upper(name) like upper('%" . $q . "%')
ORDER BY 1;");
}else{
$result = $this->db->query("SELECT organizationID, shortName
FROM Organization O
WHERE upper(O.shortName) like upper('%" . $q . "%')
ORDER BY shortName;");
}
while ($row = $result->fetch_assoc()){
$organizationArray[] = $row['shortName'] . "|" . $row['organizationID'];
}
return $organizationArray;
}
//search used for the license autocomplete
public function licenseAutocomplete($q){
$config = new Configuration;
$licenseArray = array();
//if the org module is installed get the org name from org database
if ($config->settings->licensingModule == 'Y'){
$dbName = $config->settings->licensingDatabaseName;
$result = $this->db->query("SELECT shortName, licenseID
FROM " . $dbName . ".License
WHERE upper(shortName) like upper('%" . $q . "%')
ORDER BY 1;");
}
while ($row = $result->fetch_assoc()){
$licenseArray[] = $row['shortName'] . "|" . $row['licenseID'];
}
return $licenseArray;
}
///////////////////////////////////////////////////////////////////////////////////
//
// Workflow functions follow
//
///////////////////////////////////////////////////////////////////////////////////
//returns array of ResourceStep objects for this Resource
public function getResourceSteps(){
$query = "SELECT * FROM ResourceStep
WHERE resourceID = '" . $this->resourceID . "'
ORDER BY displayOrderSequence, stepID";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['resourceStepID'])){
$object = new ResourceStep(new NamedArguments(array('primaryKey' => $result['resourceStepID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new ResourceStep(new NamedArguments(array('primaryKey' => $row['resourceStepID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns current step location in the workflow for this resource
//used to display the group on the tabs
public function getCurrentStepGroup(){
$query = "SELECT groupName FROM ResourceStep RS, UserGroup UG
WHERE resourceID = '" . $this->resourceID . "'
ORDER BY stepID";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['resourceStepID'])){
}
}
//returns first steps (object) in the workflow for this resource
public function getFirstSteps(){
$query = "SELECT * FROM ResourceStep
WHERE resourceID = '" . $this->resourceID . "'
AND (priorStepID is null OR priorStepID = '0')
ORDER BY stepID";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['resourceStepID'])){
$object = new ResourceStep(new NamedArguments(array('primaryKey' => $result['resourceStepID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new ResourceStep(new NamedArguments(array('primaryKey' => $row['resourceStepID'])));
array_push($objects, $object);
}
}
return $objects;
}
//enters resource into new workflow
public function enterNewWorkflow(){
$config = new Configuration();
//remove any current workflow steps
$this->removeResourceSteps();
//make sure this resource is marked in progress in case it was archived
$status = new Status();
$this->statusID = $status->getIDFromName('progress');
$this->save();
//Determine the workflow this resource belongs to
$workflowObj = new Workflow();
$workflowID = $workflowObj->getWorkflowID($this->resourceTypeID, $this->resourceFormatID, $this->acquisitionTypeID);
if ($workflowID){
$workflow = new Workflow(new NamedArguments(array('primaryKey' => $workflowID)));
//Copy all of the step attributes for this workflow to a new resource step
foreach ($workflow->getSteps() as $step){
$resourceStep = new ResourceStep();
$resourceStep->resourceStepID = '';
$resourceStep->resourceID = $this->resourceID;
$resourceStep->stepID = $step->stepID;
$resourceStep->priorStepID = $step->priorStepID;
$resourceStep->stepName = $step->stepName;
$resourceStep->userGroupID = $step->userGroupID;
$resourceStep->displayOrderSequence = $step->displayOrderSequence;
$resourceStep->save();
}
//Start the first step
//this handles updating the db and sending notifications for approval groups
foreach ($this->getFirstSteps() as $resourceStep){
$resourceStep->startStep();
}
}
//send an email notification to the feedback email address and the creator
$cUser = new User(new NamedArguments(array('primaryKey' => $this->createLoginID)));
$acquisitionType = new AcquisitionType(new NamedArguments(array('primaryKey' => $this->acquisitionTypeID)));
if ($cUser->firstName){
$creator = $cUser->firstName . " " . $cUser->lastName;
}else if ($this->createLoginID){ //for some reason user isn't set up or their firstname/last name don't exist
$creator = $this->createLoginID;
}else{
$creator = "(unknown user)";
}
if (($config->settings->feedbackEmailAddress) || ($cUser->emailAddress)){
$email = new Email();
$util = new Utility();
$email->message = $util->createMessageFromTemplate('NewResourceMain', $this->resourceID, $this->titleText, '', '', $creator);
if ($cUser->emailAddress){
$emailTo[] = $cUser->emailAddress;
}
if ($config->settings->feedbackEmailAddress != ''){
$emailTo[] = $config->settings->feedbackEmailAddress;
}
$email->to = implode(",", $emailTo);
if ($acquisitionType->shortName){
$email->subject = "CORAL Alert: New " . $acquisitionType->shortName . " Resource Added: " . $this->titleText;
}else{
$email->subject = "CORAL Alert: New Resource Added: " . $this->titleText;
}
$email->send();
}
}
//completes a workflow (changes status to complete and sends notifications to creator and "master email")
public function completeWorkflow(){
$config = new Configuration();
$util = new Utility();
$status = new Status();
$statusID = $status->getIDFromName('complete');
if ($statusID){
$this->statusID = $statusID;
$this->save();
}
//send notification to creator and master email address
$cUser = new User(new NamedArguments(array('primaryKey' => $this->createLoginID)));
//formulate emil to be sent
$email = new Email();
$email->message = $util->createMessageFromTemplate('CompleteResource', $this->resourceID, $this->titleText, '', $this->systemNumber, '');
if ($cUser->emailAddress){
$emailTo[] = $cUser->emailAddress;
}
if ($config->settings->feedbackEmailAddress != ''){
$emailTo[] = $config->settings->feedbackEmailAddress;
}
$email->to = implode(",", $emailTo);
$email->subject = "CORAL Alert: Workflow completion for " . $this->titleText;
$email->send();
}
//returns array of subject objects
public function getGeneralDetailSubjectLinkID(){
$query = "SELECT
GDL.generalDetailSubjectLinkID
FROM
Resource R
INNER JOIN ResourceSubject RSUB ON (R.resourceID = RSUB.resourceID)
INNER JOIN GeneralDetailSubjectLink GDL ON (RSUB.generalDetailSubjectLinkID = GDL.generalDetailSubjectLinkID)
LEFT OUTER JOIN GeneralSubject GS ON (GDL.generalSubjectID = GS.generalSubjectID)
LEFT OUTER JOIN DetailedSubject DS ON (GDL.detailedSubjectID = DS.detailedSubjectID)
WHERE
R.resourceID = '" . $this->resourceID . "'
ORDER BY
GS.shortName,
DS.shortName";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['generalDetailSubjectLinkID'])){
$object = new GeneralDetailSubjectLink(new NamedArguments(array('primaryKey' => $result['generalDetailSubjectLinkID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new GeneralDetailSubjectLink(new NamedArguments(array('primaryKey' => $row['generalDetailSubjectLinkID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns array of subject objects
public function getDetailedSubjects($resourceID, $generalSubjectID){
$query = "SELECT
RSUB.resourceID,
GDL.detailedSubjectID,
DetailedSubject.shortName,
GDL.generalSubjectID
FROM
ResourceSubject RSUB
INNER JOIN GeneralDetailSubjectLink GDL ON (RSUB.GeneralDetailSubjectLinkID = GDL.GeneralDetailSubjectLinkID)
INNER JOIN DetailedSubject ON (GDL.detailedSubjectID = DetailedSubject.detailedSubjectID)
WHERE
RSUB.resourceID = " . $resourceID . " AND GDL.generalSubjectID = " . $generalSubjectID . " ORDER BY DetailedSubject.shortName";
//echo $query . "<br>";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['detailedSubjectID'])){
$object = new DetailedSubject(new NamedArguments(array('primaryKey' => $result['detailedSubjectID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new DetailedSubject(new NamedArguments(array('primaryKey' => $row['detailedSubjectID'])));
array_push($objects, $object);
}
}
return $objects;
}
//removes all resource subjects
public function removeAllSubjects(){
$query = "DELETE
FROM ResourceSubject
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query);
}
public function removeAllIsbnOrIssn() {
$query = "DELETE
FROM IsbnOrIssn
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query);
}
public function setIsbnOrIssn($isbnorissns) {
$this->removeAllIsbnOrIssn();
foreach ($isbnorissns as $isbnorissn) {
if (trim($isbnorissn) != '') {
$isbnOrIssn = new IsbnOrIssn();
$isbnOrIssn->resourceID = $this->resourceID;
$isbnOrIssn->isbnOrIssn = $isbnorissn;
$isbnOrIssn->save();
}
}
}
}
?>
| TAMULib/CORAL-Resources | admin/classes/domain/Resource.php | PHP | gpl-3.0 | 79,589 |
<roundcube:include file="includes/layout.html" />
<div class="content frame-content">
<roundcube:object name="dialogcontent" />
</div>
<roundcube:include file="includes/footer.html" />
| dhoffend/roundcubemail | skins/elastic/templates/dialog.html | HTML | gpl-3.0 | 188 |
/*
* Meran - MERAN UNLP is a ILS (Integrated Library System) wich provides Catalog,
* Circulation and User's Management. It's written in Perl, and uses Apache2
* Web-Server, MySQL database and Sphinx 2 indexing.
* Copyright (C) 2009-2013 Grupo de desarrollo de Meran CeSPI-UNLP
*
* This file is part of Meran.
*
* Meran is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Meran is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Meran. If not, see <http://www.gnu.org/licenses/>.
*/
define([],function(){
'use strict'
/**
* Implements unique() using the browser's sort().
*
* @param a
* The array to sort and strip of duplicate values.
* Warning: this array will be modified in-place.
* @param compFn
* A custom comparison function that accepts two values a and
* b from the given array and returns -1, 0, 1 depending on
* whether a < b, a == b, a > b respectively.
*
* If no compFn is provided, the algorithm will use the
* browsers default sort behaviour and loose comparison to
* detect duplicates.
* @return
* The given array.
*/
function sortUnique(a, compFn){
var i;
if (compFn) {
a.sort(compFn);
for (i = 1; i < a.length; i++) {
if (0 === compFn(a[i], a[i - 1])) {
a.splice(i--, 1);
}
}
} else {
a.sort();
for (i = 1; i < a.length; i++) {
// Use loosely typed comparsion if no compFn is given
// to avoid sortUnique( [6, "6", 6] ) => [6, "6", 6]
if (a[i] == a[i - 1]) {
a.splice(i--, 1);
}
}
}
return a;
}
/**
* Shallow comparison of two arrays.
*
* @param a, b
* The arrays to compare.
* @param equalFn
* A custom comparison function that accepts two values a and
* b from the given arrays and returns true or false for
* equal and not equal respectively.
*
* If no equalFn is provided, the algorithm will use the strict
* equals operator.
* @return
* True if all items in a and b are equal, false if not.
*/
function equal(a, b, equalFn) {
var i = 0, len = a.length;
if (len !== b.length) {
return false;
}
if (equalFn) {
for (; i < len; i++) {
if (!equalFn(a[i], b[i])) {
return false;
}
}
} else {
for (; i < len; i++) {
if (a[i] !== b[i]) {
return false;
}
}
}
return true;
}
/**
* ECMAScript map replacement
* See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map
* And http://es5.github.com/#x15.4.4.19
* It's not exactly according to standard, but it does exactly what one expects.
*/
function map(a, fn) {
var i, len, result = [];
for (i = 0, len = a.length; i < len; i++) {
result.push(fn(a[i]));
}
return result;
}
function mapNative(a, fn) {
// Call map directly on the object instead of going through
// Array.prototype.map. This avoids the problem that we may get
// passed an array-like object (NodeList) which may cause an
// error if the implementation of Array.prototype.map can only
// deal with arrays (Array.prototype.map may be native or
// provided by a javscript framework).
return a.map(fn);
}
return {
sortUnique: sortUnique,
equal: equal,
map: Array.prototype.map ? mapNative : map
};
});
| Desarrollo-CeSPI/meran | includes/aloha/util/arrays.js | JavaScript | gpl-3.0 | 3,812 |
echo off
rem Parameters
set postgresbindir=C:\Program Files (x86)\PostgreSQL\9.5\bin
set postgresport=5433
set postgresusername=postgres
rem List all sql files in the dir
dir *.sql
rem Prompt user to give filename to restore
set /p filename="SQL filename to restore? "
call "%postgresbindir%\psql.exe" --host localhost --port %postgresport% --username "%postgresusername%" -f %filename% | Raphcal/sigmah | scripts/cli/restore_SigmahCentral_dumpFile.bat | Batchfile | gpl-3.0 | 391 |
import logging
from borgmatic.borg.flags import make_flags, make_flags_from_arguments
from borgmatic.execute import execute_command
logger = logging.getLogger(__name__)
# A hack to convince Borg to exclude archives ending in ".checkpoint". This assumes that a
# non-checkpoint archive name ends in a digit (e.g. from a timestamp).
BORG_EXCLUDE_CHECKPOINTS_GLOB = '*[0123456789]'
def resolve_archive_name(repository, archive, storage_config, local_path='borg', remote_path=None):
'''
Given a local or remote repository path, an archive name, a storage config dict, a local Borg
path, and a remote Borg path, simply return the archive name. But if the archive name is
"latest", then instead introspect the repository for the latest successful (non-checkpoint)
archive, and return its name.
Raise ValueError if "latest" is given but there are no archives in the repository.
'''
if archive != "latest":
return archive
lock_wait = storage_config.get('lock_wait', None)
full_command = (
(local_path, 'list')
+ (('--info',) if logger.getEffectiveLevel() == logging.INFO else ())
+ (('--debug', '--show-rc') if logger.isEnabledFor(logging.DEBUG) else ())
+ make_flags('remote-path', remote_path)
+ make_flags('lock-wait', lock_wait)
+ make_flags('glob-archives', BORG_EXCLUDE_CHECKPOINTS_GLOB)
+ make_flags('last', 1)
+ ('--short', repository)
)
output = execute_command(full_command, output_log_level=None, borg_local_path=local_path)
try:
latest_archive = output.strip().splitlines()[-1]
except IndexError:
raise ValueError('No archives found in the repository')
logger.debug('{}: Latest archive is {}'.format(repository, latest_archive))
return latest_archive
def list_archives(repository, storage_config, list_arguments, local_path='borg', remote_path=None):
'''
Given a local or remote repository path, a storage config dict, and the arguments to the list
action, display the output of listing Borg archives in the repository or return JSON output. Or,
if an archive name is given, listing the files in that archive.
'''
lock_wait = storage_config.get('lock_wait', None)
if list_arguments.successful:
list_arguments.glob_archives = BORG_EXCLUDE_CHECKPOINTS_GLOB
full_command = (
(local_path, 'list')
+ (
('--info',)
if logger.getEffectiveLevel() == logging.INFO and not list_arguments.json
else ()
)
+ (
('--debug', '--show-rc')
if logger.isEnabledFor(logging.DEBUG) and not list_arguments.json
else ()
)
+ make_flags('remote-path', remote_path)
+ make_flags('lock-wait', lock_wait)
+ make_flags_from_arguments(
list_arguments, excludes=('repository', 'archive', 'paths', 'successful')
)
+ (
'::'.join((repository, list_arguments.archive))
if list_arguments.archive
else repository,
)
+ (tuple(list_arguments.paths) if list_arguments.paths else ())
)
return execute_command(
full_command,
output_log_level=None if list_arguments.json else logging.WARNING,
borg_local_path=local_path,
)
| witten/borgmatic | borgmatic/borg/list.py | Python | gpl-3.0 | 3,343 |
// Copyright 2017 Jon Skeet. All rights reserved. Use of this source code is governed by the Apache License 2.0, as found in the LICENSE.txt file.
using System;
namespace NullConditional
{
class LoggingDemo
{
static void Main()
{
int x = 10;
Logger logger = new Logger();
logger.Debug?.Log($"Debug log entry");
logger.Info?.Log($"Info at {DateTime.UtcNow}; x={x}");
}
}
}
| krazymirk/cs7 | CS7/CS7/NullConditional/LoggingDemo.cs | C# | gpl-3.0 | 460 |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AssociationContains.cs" company="Allors bvba">
// Copyright 2002-2017 Allors bvba.
//
// Dual Licensed under
// a) the Lesser General Public Licence v3 (LGPL)
// b) the Allors License
//
// The LGPL License is included in the file lgpl.txt.
// The Allors License is an addendum to your contract.
//
// Allors Platform is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// For more information visit http://www.allors.com/legal
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Allors.Adapters.Object.SqlClient
{
using Allors.Meta;
using Adapters;
internal sealed class AssociationContains : Predicate
{
private readonly IObject allorsObject;
private readonly IAssociationType association;
internal AssociationContains(ExtentFiltered extent, IAssociationType association, IObject allorsObject)
{
extent.CheckAssociation(association);
PredicateAssertions.AssertAssociationContains(association, allorsObject);
this.association = association;
this.allorsObject = allorsObject;
}
internal override bool BuildWhere(ExtentStatement statement, string alias)
{
var schema = statement.Mapping;
if ((this.association.IsMany && this.association.RoleType.IsMany) || !this.association.RelationType.ExistExclusiveClasses)
{
statement.Append("\n");
statement.Append("EXISTS(\n");
statement.Append("SELECT " + alias + "." + Mapping.ColumnNameForObject + "\n");
statement.Append("FROM " + schema.TableNameForRelationByRelationType[this.association.RelationType] + "\n");
statement.Append("WHERE " + Mapping.ColumnNameForAssociation + "=" + this.allorsObject.Strategy.ObjectId + "\n");
statement.Append("AND " + Mapping.ColumnNameForRole + "=" + alias + "." + Mapping.ColumnNameForObject + "\n");
statement.Append(")");
}
else
{
statement.Append(" " + this.association.SingularFullName + "_A." + Mapping.ColumnNameForObject + " = " + this.allorsObject.Strategy.ObjectId);
}
return this.Include;
}
internal override void Setup(ExtentStatement statement)
{
statement.UseAssociation(this.association);
}
}
} | Allors/allors | Platform/Database/Adapters/Allors.Adapters.Object.SqlClient/Predicates/AssociationContains.cs | C# | gpl-3.0 | 2,811 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.