text:
#include <linux/fs.h>
#include <linux/module.h>
#include <linux/mm.h>
#include <linux/pagemap.h>
#include <linux/statfs.h>
#include <linux/slab.h>
#include <linux/seq_file.h>
#include <linux/mount.h>
#include <linux/namei.h>
#include "hostfs.h"
#include "init.h"
#include "kern.h"

struct hostfs_inode_info {
	int fd;
	fmode_t mode;
	struct inode vfs_inode;
};

static inline struct hostfs_inode_info *HOSTFS_I(struct inode *inode)
{
	return list_entry(inode, struct hostfs_inode_info, vfs_inode);
}

#define FILE_HOSTFS_I(file) HOSTFS_I((file)->f_path.dentry->d_inode)

static int hostfs_d_delete(const struct dentry *dentry)
{
	return 1;
}

static const struct dentry_operations hostfs_dentry_ops = {
	.d_delete		= hostfs_d_delete,
};

/* Changed in hostfs_args before the kernel starts running */
static char *root_ino = "";
static int append = 0;

#define HOSTFS_SUPER_MAGIC 0x00c0ffee

static const struct inode_operations hostfs_iops;
static const struct inode_operations hostfs_dir_iops;
static const struct inode_operations hostfs_link_iops;

#ifndef MODULE
static int __init hostfs_args(char *options, int *add)
{
	char *ptr;

	ptr = strchr(options, ',');
	if (ptr != NULL)
		*ptr++ = '\0';
	if (*options != '\0')
		root_ino = options;

	options = ptr;
	while (options) {
		ptr = strchr(options, ',');
		if (ptr != NULL)
			*ptr++ = '\0';
		if (*options != '\0') {
			if (!strcmp(options, "append"))
				append = 1;
			else printf("hostfs_args - unsupported option - %s\n",
				    options);
		}
		options = ptr;
	}
	return 0;
}

__uml_setup("hostfs=", hostfs_args,
"hostfs=<root dir>,<flags>,...\n"
"    This is used to set hostfs parameters.  The root directory argument\n"
"    is used to confine all hostfs mounts to within the specified directory\n"
"    tree on the host.  If this isn't specified, then a user inside UML can\n"
"    mount anything on the host that's accessible to the user that's running\n"
"    it.\n"
"    The only flag currently supported is 'append', which specifies that all\n"
"    files opened by hostfs will be opened in append mode.\n\n"
);
#endif

static char *__dentry_name(struct dentry *dentry, char *name)
{
	char *p = dentry_path_raw(dentry, name, PATH_MAX);
	char *root;
	size_t len;

	root = dentry->d_sb->s_fs_info;
	len = strlen(root);
	if (IS_ERR(p)) {
		__putname(name);
		return NULL;
	}
	strlcpy(name, root, PATH_MAX);
	if (len > p - name) {
		__putname(name);
		return NULL;
	}
	if (p > name + len) {
		char *s = name + len;
		while ((*s++ = *p++) != '\0')
			;
	}
	return name;
}

static char *dentry_name(struct dentry *dentry)
{
	char *name = __getname();
	if (!name)
		return NULL;

	return __dentry_name(dentry, name); /* will unlock */
}

static char *inode_name(struct inode *ino)
{
	struct dentry *dentry;
	char *name;

	dentry = d_find_alias(ino);
	if (!dentry)
		return NULL;

	name = dentry_name(dentry);

	dput(dentry);

	return name;
}

static char *follow_link(char *link)
{
	int len, n;
	char *name, *resolved, *end;

	len = 64;
	while (1) {
		n = -ENOMEM;
		name = kmalloc(len, GFP_KERNEL);
		if (name == NULL)
			goto out;

		n = hostfs_do_readlink(link, name, len);
		if (n < len)
			break;
		len *= 2;
		kfree(name);
	}
	if (n < 0)
		goto out_free;

	if (*name == '/')
		return name;

	end = strrchr(link, '/');
	if (end == NULL)
		return name;

	*(end + 1) = '\0';
	len = strlen(link) + strlen(name) + 1;

	resolved = kmalloc(len, GFP_KERNEL);
	if (resolved == NULL) {
		n = -ENOMEM;
		goto out_free;
	}

	sprintf(resolved, "%s%s", link, name);
	kfree(name);
	kfree(link);
	return resolved;

 out_free:
	kfree(name);
 out:
	return ERR_PTR(n);
}

static struct inode *hostfs_iget(struct super_block *sb)
{
	struct inode *inode = new_inode(sb);
	if (!inode)
		return ERR_PTR(-ENOMEM);
	return inode;
}

int hostfs_statfs(struct dentry *dentry, struct kstatfs *sf)
{
	/*
	 * do_statfs uses struct statfs64 internally, but the linux kernel
	 * struct statfs still has 32-bit versions for most of these fields,
	 * so we convert them here
	 */
	int err;
	long long f_blocks;
	long long f_bfree;
	long long f_bavail;
	long long f_files;
	long long f_ffree;

	err = do_statfs(dentry->d_sb->s_fs_info,
			&sf->f_bsize, &f_blocks, &f_bfree, &f_bavail, &f_files,
			&f_ffree, &sf->f_fsid, sizeof(sf->f_fsid),
			&sf->f_namelen);
	if (err)
		return err;
	sf->f_blocks = f_blocks;
	sf->f_bfree = f_bfree;
	sf->f_bavail = f_bavail;
	sf->f_files = f_files;
	sf->f_ffree = f_ffree;
	sf->f_type = HOSTFS_SUPER_MAGIC;
	return 0;
}

static struct inode *hostfs_alloc_inode(struct super_block *sb)
{
	struct hostfs_inode_info *hi;

	hi = kzalloc(sizeof(*hi), GFP_KERNEL);
	if (hi == NULL)
		return NULL;
	hi->fd = -1;
	inode_init_once(&hi->vfs_inode);
	return &hi->vfs_inode;
}

static void hostfs_evict_inode(struct inode *inode)
{
	truncate_inode_pages(&inode->i_data, 0);
	end_writeback(inode);
	if (HOSTFS_I(inode)->fd != -1) {
		close_file(&HOSTFS_I(inode)->fd);
		HOSTFS_I(inode)->fd = -1;
	}
}

static void hostfs_i_callback(struct rcu_head *head)
{
	struct inode *inode = container_of(head, struct inode, i_rcu);
	kfree(HOSTFS_I(inode));
}

static void hostfs_destroy_inode(struct inode *inode)
{
	call_rcu(&inode->i_rcu, hostfs_i_callback);
}

static int hostfs_show_options(struct seq_file *seq, struct dentry *root)
{
	const char *root_path = root->d_sb->s_fs_info;
	size_t offset = strlen(root_ino) + 1;

	if (strlen(root_path) > offset)
		seq_printf(seq, ",%s", root_path + offset);

	return 0;
}

static const struct super_operations hostfs_sbops = {
	.alloc_inode	= hostfs_alloc_inode,
	.destroy_inode	= hostfs_destroy_inode,
	.evict_inode	= hostfs_evict_inode,
	.statfs		= hostfs_statfs,
	.show_options	= hostfs_show_options,
};

int hostfs_readdir(struct file *file, void *ent, filldir_t filldir)
{
	void *dir;
	char *name;
	unsigned long long next, ino;
	int error, len;
	unsigned int type;

	name = dentry_name(file->f_path.dentry);
	if (name == NULL)
		return -ENOMEM;
	dir = open_dir(name, &error);
	__putname(name);
	if (dir == NULL)
		return -error;
	next = file->f_pos;
	while ((name = read_dir(dir, &next, &ino, &len, &type)) != NULL) {
		error = (*filldir)(ent, name, len, file->f_pos,
				   ino, type);
		if (error) break;
		file->f_pos = next;
	}
	close_dir(dir);
	return 0;
}

int hostfs_file_open(struct inode *ino, struct file *file)
{
	static DEFINE_MUTEX(open_mutex);
	char *name;
	fmode_t mode = 0;
	int err;
	int r = 0, w = 0, fd;

	mode = file->f_mode & (FMODE_READ | FMODE_WRITE);
	if ((mode & HOSTFS_I(ino)->mode) == mode)
		return 0;

	mode |= HOSTFS_I(ino)->mode;

retry:
	if (mode & FMODE_READ)
		r = 1;
	if (mode & FMODE_WRITE)
		w = 1;
	if (w)
		r = 1;

	name = dentry_name(file->f_path.dentry);
	if (name == NULL)
		return -ENOMEM;

	fd = open_file(name, r, w, append);
	__putname(name);
	if (fd < 0)
		return fd;

	mutex_lock(&open_mutex);
	/* somebody else had handled it first? */
	if ((mode & HOSTFS_I(ino)->mode) == mode) {
		mutex_unlock(&open_mutex);
		return 0;
	}
	if ((mode | HOSTFS_I(ino)->mode) != mode) {
		mode |= HOSTFS_I(ino)->mode;
		mutex_unlock(&open_mutex);
		close_file(&fd);
		goto retry;
	}
	if (HOSTFS_I(ino)->fd == -1) {
		HOSTFS_I(ino)->fd = fd;
	} else {
		err = replace_file(fd, HOSTFS_I(ino)->fd);
		close_file(&fd);
		if (err < 0) {
			mutex_unlock(&open_mutex);
			return err;
		}
	}
	HOSTFS_I(ino)->mode = mode;
	mutex_unlock(&open_mutex);

	return 0;
}

int hostfs_fsync(struct file *file, loff_t start, loff_t end, int datasync)
{
	struct inode *inode = file->f_mapping->host;
	int ret;

	ret = filemap_write_and_wait_range(inode->i_mapping, start, end);
	if (ret)
		return ret;

	mutex_lock(&inode->i_mutex);
	ret = fsync_file(HOSTFS_I(inode)->fd, datasync);
	mutex_unlock(&inode->i_mutex);

	return ret;
}

static const struct file_operations hostfs_file_fops = {
	.llseek		= generic_file_llseek,
	.read		= do_sync_read,
	.splice_read	= generic_file_splice_read,
	.aio_read	= generic_file_aio_read,
	.aio_write	= generic_file_aio_write,
	.write		= do_sync_write,
	.mmap		= generic_file_mmap,
	.open		= hostfs_file_open,
	.release	= NULL,
	.fsync		= hostfs_fsync,
};

static const struct file_operations hostfs_dir_fops = {
	.llseek		= generic_file_llseek,
	.readdir	= hostfs_readdir,
	.read		= generic_read_dir,
};

int hostfs_writepage(struct page *page, struct writeback_control *wbc)
{
	struct address_space *mapping = page->mapping;
	struct inode *inode = mapping->host;
	char *buffer;
	unsigned long long base;
	int count = PAGE_CACHE_SIZE;
	int end_index = inode->i_size >> PAGE_CACHE_SHIFT;
	int err;

	if (page->index >= end_index)
		count = inode->i_size & (PAGE_CACHE_SIZE-1);

	buffer = kmap(page);
	base = ((unsigned long long) page->index) << PAGE_CACHE_SHIFT;

	err = write_file(HOSTFS_I(inode)->fd, &base, buffer, count);
	if (err != count) {
		ClearPageUptodate(page);
		goto out;
	}

	if (base > inode->i_size)
		inode->i_size = base;

	if (PageError(page))
		ClearPageError(page);
	err = 0;

 out:
	kunmap(page);

	unlock_page(page);
	return err;
}

int hostfs_readpage(struct file *file, struct page *page)
{
	char *buffer;
	long long start;
	int err = 0;

	start = (long long) page->index << PAGE_CACHE_SHIFT;
	buffer = kmap(page);
	err = read_file(FILE_HOSTFS_I(file)->fd, &start, buffer,
			PAGE_CACHE_SIZE);
	if (err < 0)
		goto out;

	memset(&buffer[err], 0, PAGE_CACHE_SIZE - err);

	flush_dcache_page(page);
	SetPageUptodate(page);
	if (PageError(page)) ClearPageError(page);
	err = 0;
 out:
	kunmap(page);
	unlock_page(page);
	return err;
}

int hostfs_write_begin(struct file *file, struct address_space *mapping,
			loff_t pos, unsigned len, unsigned flags,
			struct page **pagep, void **fsdata)
{
	pgoff_t index = pos >> PAGE_CACHE_SHIFT;

	*pagep = grab_cache_page_write_begin(mapping, index, flags);
	if (!*pagep)
		return -ENOMEM;
	return 0;
}

int hostfs_write_end(struct file *file, struct address_space *mapping,
			loff_t pos, unsigned len, unsigned copied,
			struct page *page, void *fsdata)
{
	struct inode *inode = mapping->host;
	void *buffer;
	unsigned from = pos & (PAGE_CACHE_SIZE - 1);
	int err;

	buffer = kmap(page);
	err = write_file(FILE_HOSTFS_I(file)->fd, &pos, buffer + from, copied);
	kunmap(page);

	if (!PageUptodate(page) && err == PAGE_CACHE_SIZE)
		SetPageUptodate(page);

	/*
	 * If err > 0, write_file has added err to pos, so we are comparing
	 * i_size against the last byte written.
	 */
	if (err > 0 && (pos > inode->i_size))
		inode->i_size = pos;
	unlock_page(page);
	page_cache_release(page);

	return err;
}

static const struct address_space_operations hostfs_aops = {
	.writepage 	= hostfs_writepage,
	.readpage	= hostfs_readpage,
	.set_page_dirty = __set_page_dirty_nobuffers,
	.write_begin	= hostfs_write_begin,
	.write_end	= hostfs_write_end,
};

static int read_name(struct inode *ino, char *name)
{
	dev_t rdev;
	struct hostfs_stat st;
	int err = stat_file(name, &st, -1);
	if (err)
		return err;

	/* Reencode maj and min with the kernel encoding.*/
	rdev = MKDEV(st.maj, st.min);

	switch (st.mode & S_IFMT) {
	case S_IFLNK:
		ino->i_op = &hostfs_link_iops;
		break;
	case S_IFDIR:
		ino->i_op = &hostfs_dir_iops;
		ino->i_fop = &hostfs_dir_fops;
		break;
	case S_IFCHR:
	case S_IFBLK:
	case S_IFIFO:
	case S_IFSOCK:
		init_special_inode(ino, st.mode & S_IFMT, rdev);
		ino->i_op = &hostfs_iops;
		break;

	default:
		ino->i_op = &hostfs_iops;
		ino->i_fop = &hostfs_file_fops;
		ino->i_mapping->a_ops = &hostfs_aops;
	}

	ino->i_ino = st.ino;
	ino->i_mode = st.mode;
	set_nlink(ino, st.nlink);
	ino->i_uid = st.uid;
	ino->i_gid = st.gid;
	ino->i_atime = st.atime;
	ino->i_mtime = st.mtime;
	ino->i_ctime = st.ctime;
	ino->i_size = st.size;
	ino->i_blocks = st.blocks;
	return 0;
}

int hostfs_create(struct inode *dir, struct dentry *dentry, umode_t mode,
		  struct nameidata *nd)
{
	struct inode *inode;
	char *name;
	int error, fd;

	inode = hostfs_iget(dir->i_sb);
	if (IS_ERR(inode)) {
		error = PTR_ERR(inode);
		goto out;
	}

	error = -ENOMEM;
	name = dentry_name(dentry);
	if (name == NULL)
		goto out_put;

	fd = file_create(name,
			 mode & S_IRUSR, mode & S_IWUSR, mode & S_IXUSR,
			 mode & S_IRGRP, mode & S_IWGRP, mode & S_IXGRP,
			 mode & S_IROTH, mode & S_IWOTH, mode & S_IXOTH);
	if (fd < 0)
		error = fd;
	else
		error = read_name(inode, name);

	__putname(name);
	if (error)
		goto out_put;

	HOSTFS_I(inode)->fd = fd;
	HOSTFS_I(inode)->mode = FMODE_READ | FMODE_WRITE;
	d_instantiate(dentry, inode);
	return 0;

 out_put:
	iput(inode);
 out:
	return error;
}

struct dentry *hostfs_lookup(struct inode *ino, struct dentry *dentry,
			     struct nameidata *nd)
{
	struct inode *inode;
	char *name;
	int err;

	inode = hostfs_iget(ino->i_sb);
	if (IS_ERR(inode)) {
		err = PTR_ERR(inode);
		goto out;
	}

	err = -ENOMEM;
	name = dentry_name(dentry);
	if (name == NULL)
		goto out_put;

	err = read_name(inode, name);

	__putname(name);
	if (err == -ENOENT) {
		iput(inode);
		inode = NULL;
	}
	else if (err)
		goto out_put;

	d_add(dentry, inode);
	return NULL;

 out_put:
	iput(inode);
 out:
	return ERR_PTR(err);
}

int hostfs_link(struct dentry *to, struct inode *ino, struct dentry *from)
{
	char *from_name, *to_name;
	int err;

	if ((from_name = dentry_name(from)) == NULL)
		return -ENOMEM;
	to_name = dentry_name(to);
	if (to_name == NULL) {
		__putname(from_name);
		return -ENOMEM;
	}
	err = link_file(to_name, from_name);
	__putname(from_name);
	__putname(to_name);
	return err;
}

int hostfs_unlink(struct inode *ino, struct dentry *dentry)
{
	char *file;
	int err;

	if (append)
		return -EPERM;

	if ((file = dentry_name(dentry)) == NULL)
		return -ENOMEM;

	err = unlink_file(file);
	__putname(file);
	return err;
}

int hostfs_symlink(struct inode *ino, struct dentry *dentry, const char *to)
{
	char *file;
	int err;

	if ((file = dentry_name(dentry)) == NULL)
		return -ENOMEM;
	err = make_symlink(file, to);
	__putname(file);
	return err;
}

int hostfs_mkdir(struct inode *ino, struct dentry *dentry, umode_t mode)
{
	char *file;
	int err;

	if ((file = dentry_name(dentry)) == NULL)
		return -ENOMEM;
	err = do_mkdir(file, mode);
	__putname(file);
	return err;
}

int hostfs_rmdir(struct inode *ino, struct dentry *dentry)
{
	char *file;
	int err;

	if ((file = dentry_name(dentry)) == NULL)
		return -ENOMEM;
	err = do_rmdir(file);
	__putname(file);
	return err;
}

static int hostfs_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
{
	struct inode *inode;
	char *name;
	int err;

	inode = hostfs_iget(dir->i_sb);
	if (IS_ERR(inode)) {
		err = PTR_ERR(inode);
		goto out;
	}

	err = -ENOMEM;
	name = dentry_name(dentry);
	if (name == NULL)
		goto out_put;

	init_special_inode(inode, mode, dev);
	err = do_mknod(name, mode, MAJOR(dev), MINOR(dev));
	if (!err)
		goto out_free;

	err = read_name(inode, name);
	__putname(name);
	if (err)
		goto out_put;
	if (err)
		goto out_put;

	d_instantiate(dentry, inode);
	return 0;

 out_free:
	__putname(name);
 out_put:
	iput(inode);
 out:
	return err;
}

int hostfs_rename(struct inode *from_ino, struct dentry *from,
		  struct inode *to_ino, struct dentry *to)
{
	char *from_name, *to_name;
	int err;

	if ((from_name = dentry_name(from)) == NULL)
		return -ENOMEM;
	if ((to_name = dentry_name(to)) == NULL) {
		__putname(from_name);
		return -ENOMEM;
	}
	err = rename_file(from_name, to_name);
	__putname(from_name);
	__putname(to_name);
	return err;
}

int hostfs_permission(struct inode *ino, int desired)
{
	char *name;
	int r = 0, w = 0, x = 0, err;

	if (desired & MAY_NOT_BLOCK)
		return -ECHILD;

	if (desired & MAY_READ) r = 1;
	if (desired & MAY_WRITE) w = 1;
	if (desired & MAY_EXEC) x = 1;
	name = inode_name(ino);
	if (name == NULL)
		return -ENOMEM;

	if (S_ISCHR(ino->i_mode) || S_ISBLK(ino->i_mode) ||
	    S_ISFIFO(ino->i_mode) || S_ISSOCK(ino->i_mode))
		err = 0;
	else
		err = access_file(name, r, w, x);
	__putname(name);
	if (!err)
		err = generic_permission(ino, desired);
	return err;
}

int hostfs_setattr(struct dentry *dentry, struct iattr *attr)
{
	struct inode *inode = dentry->d_inode;
	struct hostfs_iattr attrs;
	char *name;
	int err;

	int fd = HOSTFS_I(inode)->fd;

	err = inode_change_ok(inode, attr);
	if (err)
		return err;

	if (append)
		attr->ia_valid &= ~ATTR_SIZE;

	attrs.ia_valid = 0;
	if (attr->ia_valid & ATTR_MODE) {
		attrs.ia_valid |= HOSTFS_ATTR_MODE;
		attrs.ia_mode = attr->ia_mode;
	}
	if (attr->ia_valid & ATTR_UID) {
		attrs.ia_valid |= HOSTFS_ATTR_UID;
		attrs.ia_uid = attr->ia_uid;
	}
	if (attr->ia_valid & ATTR_GID) {
		attrs.ia_valid |= HOSTFS_ATTR_GID;
		attrs.ia_gid = attr->ia_gid;
	}
	if (attr->ia_valid & ATTR_SIZE) {
		attrs.ia_valid |= HOSTFS_ATTR_SIZE;
		attrs.ia_size = attr->ia_size;
	}
	if (attr->ia_valid & ATTR_ATIME) {
		attrs.ia_valid |= HOSTFS_ATTR_ATIME;
		attrs.ia_atime = attr->ia_atime;
	}
	if (attr->ia_valid & ATTR_MTIME) {
		attrs.ia_valid |= HOSTFS_ATTR_MTIME;
		attrs.ia_mtime = attr->ia_mtime;
	}
	if (attr->ia_valid & ATTR_CTIME) {
		attrs.ia_valid |= HOSTFS_ATTR_CTIME;
		attrs.ia_ctime = attr->ia_ctime;
	}
	if (attr->ia_valid & ATTR_ATIME_SET) {
		attrs.ia_valid |= HOSTFS_ATTR_ATIME_SET;
	}
	if (attr->ia_valid & ATTR_MTIME_SET) {
		attrs.ia_valid |= HOSTFS_ATTR_MTIME_SET;
	}
	name = dentry_name(dentry);
	if (name == NULL)
		return -ENOMEM;
	err = set_attr(name, &attrs, fd);
	__putname(name);
	if (err)
		return err;

	if ((attr->ia_valid & ATTR_SIZE) &&
	    attr->ia_size != i_size_read(inode)) {
		int error;

		error = vmtruncate(inode, attr->ia_size);
		if (err)
			return err;
	}

	setattr_copy(inode, attr);
	mark_inode_dirty(inode);
	return 0;
}

static const struct inode_operations hostfs_iops = {
	.create		= hostfs_create,
	.link		= hostfs_link,
	.unlink		= hostfs_unlink,
	.symlink	= hostfs_symlink,
	.mkdir		= hostfs_mkdir,
	.rmdir		= hostfs_rmdir,
	.mknod		= hostfs_mknod,
	.rename		= hostfs_rename,
	.permission	= hostfs_permission,
	.setattr	= hostfs_setattr,
};

static const struct inode_operations hostfs_dir_iops = {
	.create		= hostfs_create,
	.lookup		= hostfs_lookup,
	.link		= hostfs_link,
	.unlink		= hostfs_unlink,
	.symlink	= hostfs_symlink,
	.mkdir		= hostfs_mkdir,
	.rmdir		= hostfs_rmdir,
	.mknod		= hostfs_mknod,
	.rename		= hostfs_rename,
	.permission	= hostfs_permission,
	.setattr	= hostfs_setattr,
};

static void *hostfs_follow_link(struct dentry *dentry, struct nameidata *nd)
{
	char *link = __getname();
	if (link) {
		char *path = dentry_name(dentry);
		int err = -ENOMEM;
		if (path) {
			err = hostfs_do_readlink(path, link, PATH_MAX);
			if (err == PATH_MAX)
				err = -E2BIG;
			__putname(path);
		}
		if (err < 0) {
			__putname(link);
			link = ERR_PTR(err);
		}
	} else {
		link = ERR_PTR(-ENOMEM);
	}

	nd_set_link(nd, link);
	return NULL;
}

static void hostfs_put_link(struct dentry *dentry, struct nameidata *nd, void *cookie)
{
	char *s = nd_get_link(nd);
	if (!IS_ERR(s))
		__putname(s);
}

static const struct inode_operations hostfs_link_iops = {
	.readlink	= generic_readlink,
	.follow_link	= hostfs_follow_link,
	.put_link	= hostfs_put_link,
};

static int hostfs_fill_sb_common(struct super_block *sb, void *d, int silent)
{
	struct inode *root_inode;
	char *host_root_path, *req_root = d;
	int err;

	sb->s_blocksize = 1024;
	sb->s_blocksize_bits = 10;
	sb->s_magic = HOSTFS_SUPER_MAGIC;
	sb->s_op = &hostfs_sbops;
	sb->s_d_op = &hostfs_dentry_ops;
	sb->s_maxbytes = MAX_LFS_FILESIZE;

	/* NULL is printed as <NULL> by sprintf: avoid that. */
	if (req_root == NULL)
		req_root = "";

	err = -ENOMEM;
	sb->s_fs_info = host_root_path =
		kmalloc(strlen(root_ino) + strlen(req_root) + 2, GFP_KERNEL);
	if (host_root_path == NULL)
		goto out;

	sprintf(host_root_path, "%s/%s", root_ino, req_root);

	root_inode = new_inode(sb);
	if (!root_inode)
		goto out;

	err = read_name(root_inode, host_root_path);
	if (err)
		goto out_put;

	if (S_ISLNK(root_inode->i_mode)) {
		char *name = follow_link(host_root_path);
		if (IS_ERR(name))
			err = PTR_ERR(name);
		else
			err = read_name(root_inode, name);
		kfree(name);
		if (err)
			goto out_put;
	}

	err = -ENOMEM;
	sb->s_root = d_make_root(root_inode);
	if (sb->s_root == NULL)
		goto out;

	return 0;

out_put:
	iput(root_inode);
out:
	return err;
}

static struct dentry *hostfs_read_sb(struct file_system_type *type,
			  int flags, const char *dev_name,
			  void *data)
{
	return mount_nodev(type, flags, data, hostfs_fill_sb_common);
}

static void hostfs_kill_sb(struct super_block *s)
{
	kill_anon_super(s);
	kfree(s->s_fs_info);
}

static struct file_system_type hostfs_type = {
	.owner 		= THIS_MODULE,
	.name 		= "hostfs",
	.mount	 	= hostfs_read_sb,
	.kill_sb	= hostfs_kill_sb,
	.fs_flags 	= 0,
};

static int __init init_hostfs(void)
{
	return register_filesystem(&hostfs_type);
}

static void __exit exit_hostfs(void)
{
	unregister_filesystem(&hostfs_type);
}

module_init(init_hostfs)
module_exit(exit_hostfs)
MODULE_LICENSE("GPL");


text:
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.provider;

import android.app.SearchManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;

import androidx.annotation.VisibleForTesting;

/**
 * This class provides access to user data stored in Chrome, such as bookmarks, most visited pages,
 * etc. It is used to support android.provider.Browser.
 */
public class ChromeBrowserProviderImpl extends ChromeBrowserProvider.Impl {
    private static final String TAG = "ChromeBrowserProvider";

    /**
     * A projection of {@link #SEARCHES_URI} that contains {@link SearchColumns#ID},
     * {@link SearchColumns#SEARCH}, and {@link SearchColumns#DATE}.
     */
    @VisibleForTesting
    public static final String[] SEARCHES_PROJECTION = new String[] {
            // if you change column order you must also change indices below
            SearchColumns.ID, // 0
            SearchColumns.SEARCH, // 1
            SearchColumns.DATE, // 2
    };

    // Defines Chrome's API authority, so it can be run and tested
    // independently.
    private static final String API_AUTHORITY_SUFFIX = ".browser";

    private static final String BROWSER_CONTRACT_API_AUTHORITY =
            "com.google.android.apps.chrome.browser-contract";

    // These values are taken from android.provider.BrowserContract.java since
    // that class is hidden from the SDK.
    private static final String BROWSER_CONTRACT_AUTHORITY = "com.android.browser";
    private static final String BROWSER_CONTRACT_HISTORY_CONTENT_TYPE =
            "vnd.android.cursor.dir/browser-history";
    private static final String BROWSER_CONTRACT_HISTORY_CONTENT_ITEM_TYPE =
            "vnd.android.cursor.item/browser-history";
    private static final String BROWSER_CONTRACT_BOOKMARK_CONTENT_TYPE =
            "vnd.android.cursor.dir/bookmark";
    private static final String BROWSER_CONTRACT_BOOKMARK_CONTENT_ITEM_TYPE =
            "vnd.android.cursor.item/bookmark";
    private static final String BROWSER_CONTRACT_SEARCH_CONTENT_TYPE =
            "vnd.android.cursor.dir/searches";
    private static final String BROWSER_CONTRACT_SEARCH_CONTENT_ITEM_TYPE =
            "vnd.android.cursor.item/searches";

    // This Authority is for internal interface. It's concatenated with
    // Context.getPackageName() so that we can install different channels
    // SxS and have different authorities.
    private static final String AUTHORITY_SUFFIX = ".ChromeBrowserProvider";
    private static final String BOOKMARKS_PATH = "bookmarks";
    private static final String SEARCHES_PATH = "searches";
    private static final String HISTORY_PATH = "history";
    private static final String COMBINED_PATH = "combined";

    private static final int URI_MATCH_BOOKMARKS = 0;
    private static final int URI_MATCH_BOOKMARKS_ID = 1;
    private static final int URL_MATCH_API_BOOKMARK = 2;
    private static final int URL_MATCH_API_BOOKMARK_ID = 3;
    private static final int URL_MATCH_API_SEARCHES = 4;
    private static final int URL_MATCH_API_SEARCHES_ID = 5;
    private static final int URL_MATCH_API_HISTORY_CONTENT = 6;
    private static final int URL_MATCH_API_HISTORY_CONTENT_ID = 7;
    private static final int URL_MATCH_API_BOOKMARK_CONTENT = 8;
    private static final int URL_MATCH_API_BOOKMARK_CONTENT_ID = 9;
    private static final int URL_MATCH_BOOKMARK_SUGGESTIONS_ID = 10;
    private static final int URL_MATCH_BOOKMARK_HISTORY_SUGGESTIONS_ID = 11;

    private static final String[] BOOKMARK_DEFAULT_PROJECTION =
            new String[] {BookmarkColumns.ID, BookmarkColumns.URL, BookmarkColumns.VISITS,
                    BookmarkColumns.DATE, BookmarkColumns.BOOKMARK, BookmarkColumns.TITLE,
                    BookmarkColumns.FAVICON, BookmarkColumns.CREATED};

    private final Object mInitializeUriMatcherLock = new Object();
    private UriMatcher mUriMatcher;

    private void ensureUriMatcherInitialized() {
        synchronized (mInitializeUriMatcherLock) {
            if (mUriMatcher != null) return;

            mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
            // The internal URIs
            String authority = getContext().getPackageName() + AUTHORITY_SUFFIX;
            mUriMatcher.addURI(authority, BOOKMARKS_PATH, URI_MATCH_BOOKMARKS);
            mUriMatcher.addURI(authority, BOOKMARKS_PATH + "/#", URI_MATCH_BOOKMARKS_ID);
            // The internal authority for public APIs
            String apiAuthority = getContext().getPackageName() + API_AUTHORITY_SUFFIX;
            mUriMatcher.addURI(apiAuthority, BOOKMARKS_PATH, URL_MATCH_API_BOOKMARK);
            mUriMatcher.addURI(apiAuthority, BOOKMARKS_PATH + "/#", URL_MATCH_API_BOOKMARK_ID);
            mUriMatcher.addURI(apiAuthority, SEARCHES_PATH, URL_MATCH_API_SEARCHES);
            mUriMatcher.addURI(apiAuthority, SEARCHES_PATH + "/#", URL_MATCH_API_SEARCHES_ID);
            mUriMatcher.addURI(apiAuthority, HISTORY_PATH, URL_MATCH_API_HISTORY_CONTENT);
            mUriMatcher.addURI(apiAuthority, HISTORY_PATH + "/#", URL_MATCH_API_HISTORY_CONTENT_ID);
            mUriMatcher.addURI(apiAuthority, COMBINED_PATH, URL_MATCH_API_BOOKMARK);
            mUriMatcher.addURI(apiAuthority, COMBINED_PATH + "/#", URL_MATCH_API_BOOKMARK_ID);
            // The internal authority for BrowserContracts
            mUriMatcher.addURI(
                    BROWSER_CONTRACT_API_AUTHORITY, HISTORY_PATH, URL_MATCH_API_HISTORY_CONTENT);
            mUriMatcher.addURI(BROWSER_CONTRACT_API_AUTHORITY, HISTORY_PATH + "/#",
                    URL_MATCH_API_HISTORY_CONTENT_ID);
            mUriMatcher.addURI(
                    BROWSER_CONTRACT_API_AUTHORITY, COMBINED_PATH, URL_MATCH_API_BOOKMARK);
            mUriMatcher.addURI(BROWSER_CONTRACT_API_AUTHORITY, COMBINED_PATH + "/#",
                    URL_MATCH_API_BOOKMARK_ID);
            mUriMatcher.addURI(
                    BROWSER_CONTRACT_API_AUTHORITY, SEARCHES_PATH, URL_MATCH_API_SEARCHES);
            mUriMatcher.addURI(BROWSER_CONTRACT_API_AUTHORITY, SEARCHES_PATH + "/#",
                    URL_MATCH_API_SEARCHES_ID);
            mUriMatcher.addURI(
                    BROWSER_CONTRACT_API_AUTHORITY, BOOKMARKS_PATH, URL_MATCH_API_BOOKMARK_CONTENT);
            mUriMatcher.addURI(BROWSER_CONTRACT_API_AUTHORITY, BOOKMARKS_PATH + "/#",
                    URL_MATCH_API_BOOKMARK_CONTENT_ID);
            // Added the Android Framework URIs, so the provider can easily switched
            // by adding 'browser' and 'com.android.browser' in manifest.
            // The Android's BrowserContract
            mUriMatcher.addURI(
                    BROWSER_CONTRACT_AUTHORITY, HISTORY_PATH, URL_MATCH_API_HISTORY_CONTENT);
            mUriMatcher.addURI(BROWSER_CONTRACT_AUTHORITY, HISTORY_PATH + "/#",
                    URL_MATCH_API_HISTORY_CONTENT_ID);
            mUriMatcher.addURI(BROWSER_CONTRACT_AUTHORITY, "combined", URL_MATCH_API_BOOKMARK);
            mUriMatcher.addURI(BROWSER_CONTRACT_AUTHORITY, "combined/#", URL_MATCH_API_BOOKMARK_ID);
            mUriMatcher.addURI(BROWSER_CONTRACT_AUTHORITY, SEARCHES_PATH, URL_MATCH_API_SEARCHES);
            mUriMatcher.addURI(
                    BROWSER_CONTRACT_AUTHORITY, SEARCHES_PATH + "/#", URL_MATCH_API_SEARCHES_ID);
            mUriMatcher.addURI(
                    BROWSER_CONTRACT_AUTHORITY, BOOKMARKS_PATH, URL_MATCH_API_BOOKMARK_CONTENT);
            mUriMatcher.addURI(BROWSER_CONTRACT_AUTHORITY, BOOKMARKS_PATH + "/#",
                    URL_MATCH_API_BOOKMARK_CONTENT_ID);
            // For supporting android.provider.browser.BookmarkColumns and
            // SearchColumns
            mUriMatcher.addURI("browser", BOOKMARKS_PATH, URL_MATCH_API_BOOKMARK);
            mUriMatcher.addURI("browser", BOOKMARKS_PATH + "/#", URL_MATCH_API_BOOKMARK_ID);
            mUriMatcher.addURI("browser", SEARCHES_PATH, URL_MATCH_API_SEARCHES);
            mUriMatcher.addURI("browser", SEARCHES_PATH + "/#", URL_MATCH_API_SEARCHES_ID);

            mUriMatcher.addURI(apiAuthority,
                    BOOKMARKS_PATH + "/" + SearchManager.SUGGEST_URI_PATH_QUERY,
                    URL_MATCH_BOOKMARK_SUGGESTIONS_ID);
            mUriMatcher.addURI(apiAuthority, SearchManager.SUGGEST_URI_PATH_QUERY,
                    URL_MATCH_BOOKMARK_HISTORY_SUGGESTIONS_ID);
        }
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
            String sortOrder) {
        return new MatrixCursor(BOOKMARK_DEFAULT_PROJECTION, 0);
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        return null;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        return 0;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        return 0;
    }

    @VisibleForTesting
    public static String getApiAuthority(Context context) {
        return context.getPackageName() + API_AUTHORITY_SUFFIX;
    }

    @VisibleForTesting
    public static Uri getBookmarksApiUri(Context context) {
        return buildContentUri(getApiAuthority(context), BOOKMARKS_PATH);
    }

    @VisibleForTesting
    public static Uri getSearchesApiUri(Context context) {
        return buildContentUri(getApiAuthority(context), SEARCHES_PATH);
    }

    @Override
    public String getType(Uri uri) {
        // Keep returning non-null values just in case, to avoid breaking old apps.
        ensureUriMatcherInitialized();
        int match = mUriMatcher.match(uri);
        switch (match) {
            case URI_MATCH_BOOKMARKS:
            case URL_MATCH_API_BOOKMARK:
                return BROWSER_CONTRACT_BOOKMARK_CONTENT_TYPE;
            case URI_MATCH_BOOKMARKS_ID:
            case URL_MATCH_API_BOOKMARK_ID:
                return BROWSER_CONTRACT_BOOKMARK_CONTENT_ITEM_TYPE;
            case URL_MATCH_API_SEARCHES:
                return BROWSER_CONTRACT_SEARCH_CONTENT_TYPE;
            case URL_MATCH_API_SEARCHES_ID:
                return BROWSER_CONTRACT_SEARCH_CONTENT_ITEM_TYPE;
            case URL_MATCH_API_HISTORY_CONTENT:
                return BROWSER_CONTRACT_HISTORY_CONTENT_TYPE;
            case URL_MATCH_API_HISTORY_CONTENT_ID:
                return BROWSER_CONTRACT_HISTORY_CONTENT_ITEM_TYPE;
            default:
                throw new IllegalArgumentException(TAG + ": getType - unknown URL " + uri);
        }
    }

    private static Uri buildContentUri(String authority, String path) {
        return Uri.parse("content://" + authority + "/" + path);
    }
}

redpajama_set_name: RedPajamaGithub


text:
/* global define */

define([
    'underscore',
    'backbone',
    'views/clock'
], function (_, Backbone, ClockView) {
    'use strict';

    var ActivityView = Backbone.View.extend({

        el: '#current-activity',

        template: _.template($('#activity-template').html()),

        initialize: function () {
            this.createClock();
            this.render();
        },

        events: {
            'click .btn': 'complete'
        },

        render: function () {
            this.$el.html(this.template({
                task: this.model.get('task')
            }));
            this.$el.prepend(this.clock.el);
            return this;
        },

        createClock: function () {
            this.clock = new ClockView({
                model: this.model.clock
            });
        },

        complete: function () {
            var self = this;
            this.model.set('duration', Date.now() - this.model.get('start'));
            this.model.set('complete', true);
            setTimeout(function () {
                self.remove();
            }, 800);
        },

        remove: function () {
            this.clock.model.pause();
            this.clock.remove();
            this.stopListening();
            this.$el.empty();
            return this;
        }

    });

    return ActivityView;
});


text:
require_relative 'geometry/unit.rb'
require_relative 'geometry/side.rb'
require_relative 'geometry/rectangle.rb'


text:
/**
 *     This code was auto-generated by a Codezu.
 *
 *     Changes to this file may cause incorrect behavior and will be lost if
 *     the code is regenerated.
 */
package com.mozu.api.urls.commerce.orders;

import com.mozu.api.MozuUrl;
import com.mozu.api.utils.UrlFormatter;
import org.joda.time.DateTime;

public class ShipmentUrl
{

	/**
	 * Get Resource Url for GetShipment
	 * @param orderId Unique identifier of the order.
	 * @param responseFields Use this field to include those fields which are not included by default.
	 * @param shipmentId Unique identifier of the shipment to retrieve.
	 * @return   String Resource Url
	 */
	public static MozuUrl getShipmentUrl(String orderId, String responseFields, String shipmentId)
	{
		UrlFormatter formatter = new UrlFormatter("/api/commerce/orders/{orderId}/shipments/{shipmentId}?responseFields={responseFields}");
		formatter.formatUrl("orderId", orderId);
		formatter.formatUrl("responseFields", responseFields);
		formatter.formatUrl("shipmentId", shipmentId);
		return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
	}

	/**
	 * Get Resource Url for GetAvailableShipmentMethods
	 * @param draft If true, retrieve the draft version of the order, which might include uncommitted changes to the order or its components.
	 * @param orderId Unique identifier of the order.
	 * @return   String Resource Url
	 */
	public static MozuUrl getAvailableShipmentMethodsUrl(Boolean draft, String orderId)
	{
		UrlFormatter formatter = new UrlFormatter("/api/commerce/orders/{orderId}/shipments/methods?draft={draft}");
		formatter.formatUrl("draft", draft);
		formatter.formatUrl("orderId", orderId);
		return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
	}

	/**
	 * Get Resource Url for CreatePackageShipments
	 * @param orderId Unique identifier of the order.
	 * @return   String Resource Url
	 */
	public static MozuUrl createPackageShipmentsUrl(String orderId)
	{
		UrlFormatter formatter = new UrlFormatter("/api/commerce/orders/{orderId}/shipments");
		formatter.formatUrl("orderId", orderId);
		return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
	}

	/**
	 * Get Resource Url for DeleteShipment
	 * @param orderId Unique identifier of the order.
	 * @param shipmentId Unique identifier of the shipment to retrieve.
	 * @return   String Resource Url
	 */
	public static MozuUrl deleteShipmentUrl(String orderId, String shipmentId)
	{
		UrlFormatter formatter = new UrlFormatter("/api/commerce/orders/{orderId}/shipments/{shipmentId}");
		formatter.formatUrl("orderId", orderId);
		formatter.formatUrl("shipmentId", shipmentId);
		return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center">
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher"
        android:contentDescription="@string/app_name"/>
    <TextView
        android:id="@+id/tv_content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip"
        android:textSize="20sp"/>

</LinearLayout>


text:
<?php

defined("_VALID_ACCESS") || die('Direct access forbidden');

class Tests_RecordBrowserInstall extends ModuleInstall{
	public function install(){
        Utils_CommonDataCommon::new_array('Tests/RecordBrowser/Test_Commondata', array('Test0','Test1', 'Test2', 'Test3', 'Test4'));
		Utils_CommonDataCommon::new_array('Tests/RecordBrowser/Test_Permissions', array('none','partial view','full view','partial edit','full edit','delete'));

		$tr = new Tests_RecordBrowser_Recordset();
		$tr->install();

		//$ra = new RBO_RecordsetAccessor('tests_record_set');
		//$records = array();
		//$in = -1;
		//records for RB tests (full permission)
		$record = $tr->new_record($this->prepare_data(5,false,false));
		$this->update_record($record,$this->prepare_data(5,true,false));
		$record = $tr->new_record($this->prepare_data(5,false,true));
		$this->update_record($record,$this->prepare_data(5,true,true));
		//records for permissions tests
		for ($j=0;$j<5;$j++){
			$record = $tr->new_record($this->prepare_data($j,false,true));
			$this->update_record($record,$this->prepare_data($j,true,true));
		}
		//setting permissions
		$this->prepare_permissions();
		return true;
	}

	public function uninstall() {
		$test_recordset = new Tests_RecordBrowser_Recordset();
		$test_recordset->uninstall();
		return true;
	}

	public function requires($v) {
		return array(	array('name'=>Utils_RecordBrowserInstall::module_name(),'version'=>0));
	}

	function create_sample_tasks(){

	}

	function prepare_data($permission = 0,$is_altered = false,$are_nonrequired_filled = false){
		$ra_task = new RBO_RecordsetAccessor('task');
		$tasks_number = 2;
		$tasks = array_keys($ra_task->get_records(array(),array(),array(),$tasks_number));
		while (count($tasks)<$tasks_number){
			$t = $ra_task->new_record(array('title'=>'Sample task '.(count($tasks)+1),'status'=>0,'priority'=>0,'permission'=>0,'employees'=>array(1)));
			$tasks[] = $t->id;
		}
		$data_required = array(
				'text_required' => 'Sample text required',
				'long_text_required' => 'Permission:'.$permission.' Not required fields full:'.$are_nonrequired_filled.' Altered:false',
				'integer_required' => 123,
				'float_required' => 123.45,
				'checkbox' => 0,
				'date_required' => date('Y-m-d'),
				'timestamp_required' => date('Y-m-d H:i:s'),
				'time_required' => date('Y-m-d 12:23:45'),
				'currency_required' => Utils_CurrencyFieldCommon::format_default(100,1),
				'select_required' => $tasks[0],
				'select_commondata_required' => 2,
				'multiselect_required' => array($tasks[0]),
				'multiselect_commondata_required' => array(0,1,2),
				'permission' => $permission
			);
		$data_other = array(
				'text' => 'Sample text',
				'long_text' => 'A sample of long text',
				'integer' => 1234,
				'float' => 123.4567,
				'checkbox' => 1,
				'date' => date('Y-m-d',strtotime('+2 days')),
				'timestamp' => date('Y-m-d H:i:s',strtotime('-3 days')),
				'time' => date('Y-m-d 12:24:46'),
				'currency' => Utils_CurrencyFieldCommon::format_default(200,1),
				'select' => $tasks[1],
				'select_commondata' => 1,
				'multiselect' => array($tasks[0]),
				'multiselect_commondata' => array(0,1,2)
			);
		$data_required_altered = array(
				'text_required' => 'Sample text required altered',
				'long_text_required' => 'Permission:'.$permission.' Not required fields full:'.$are_nonrequired_filled.' Altered:true',
				'integer_required' => 111111,
				'float_required' => 11111.1111,
				'checkbox' => 1,
				'date_required' => date('Y-m-d',strtotime('+2 days')),
				'timestamp_required' => date('Y-m-d H:i:s',strtotime('-3 days')),
				'time_required' => date('Y-m-d 12:26:47'),
				'currency_required' => Utils_CurrencyFieldCommon::format_default(10,1),
				'select_required' => $tasks[0],
				'select_commondata_required' => 3,
				'multiselect_required' => array($tasks[0],$tasks[1]),
				'multiselect_commondata_required' => array(1,2,3),
				'permission' => $permission
			);
		$data_other_altered = array(
				'text' => 'Sample text altered',
				'long_text' => 'A sample of long altered text',
				'integer' => 1234,
				'float' => 123.4567,
				'checkbox' => 0,
				'date' => date('Y-m-d'),
				'timestamp' => date('Y-m-d H:i:s'),
				'time' => date('Y-m-d 12:27:47'),
				'currency' => Utils_CurrencyFieldCommon::format_default(20,1),
				'select' => $tasks[0],
				'select_commondata' => 3,
				'multiselect' => array($tasks[0],$tasks[1]),
				'multiselect_commondata' => array(1,2,3)
			);
		if ($is_altered){
			$data1 = $data_required_altered;
			$data2 = $data_other_altered;
		} else {
			$data1 = $data_required;
			$data2 = $data_other;
		}
		if ($are_nonrequired_filled) return $data1+$data2; else return $data1;
	}

	function update_record($object,$data){
		foreach ($data as $f=>$v)
			$object->$f = $v;
		$object->save();
	}

	function prepare_permissions(){
		$fields = array('autonumber','text_required','text','long_text_required','long_text','integer_required','integer','float_required','float','checkbox','calculated','currency_required','currency','date_required','date','timestamp_required','timestamp','time_required','time','select_required','select','select_commondata_required','select_commondata','multiselect_required','multiselect','multiselect_commondata_required','multiselect_commondata');
		//view
		Utils_RecordBrowserCommon::add_access('tests_record_set','view','ADMIN',array('permission'=>1),$fields);
		Utils_RecordBrowserCommon::add_access('tests_record_set','view','ADMIN',array('>permission'=>1));
		//edit
		Utils_RecordBrowserCommon::add_access('tests_record_set','edit','ADMIN',array('permission'=>3),$fields);
		Utils_RecordBrowserCommon::add_access('tests_record_set','edit','ADMIN',array('>permission'=>3));
		//delete
		Utils_RecordBrowserCommon::add_access('tests_record_set','delete','ADMIN',array('permission'=>5));
		Utils_RecordBrowserCommon::add_access('tests_record_set','add','ADMIN');
	}

}
?>


text:
def lista_digitos(n):
    return list(map(lambda x: int(x), str(n)))

print(lista_digitos(123))


text:
UpRaise.EmployeeView = Ember.View.extend(Ember.TargetActionSupport, {
	tagName: 'tr',
	content:null,
	actions: {
		saveRow: function() {
			var model = this.get('controller').get('model');

			var control = this.$();

			if(model.get('name') == '') {
					control.addClass('has-error');
			}
			else {
				this.triggerAction({
			    	action:'saveRow',
			    	target: this.get('controller')
	    		});
			}
	    }
	},
	adjustedIndex: function() {
	    return this.get('_parentView.contentIndex') + 1;
	}.property('_parentView.contentIndex')
});


text:
{{!-- This is the base layout for corporate blogs pages (EP, Blog). --}}

<!doctype html>

    <meta charset="utf-8" />
    <meta http-equiv="x-ua-compatible" content="ie=edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>{{ title }}</title>
    <meta name="abstract" content="{{ abstract }}" />
    <meta name="keywords" content="{{ keywords }}" />
    <meta name="twitter:card" content="summary" />
    <meta name="twitter:site" content="@FreddieMac" />
    <meta property="og:title" content="{{ title }}" />
    <meta name="twitter:title" content="{{ title }}"/>
    <meta name="Description" content="{{ description }}" />
    <meta property="og:description" content="{{ description }}" />
    <meta name="twitter:description" content="{{ description }}" />
    <meta property="og:locale" content="en_US">
    <meta property="og:type" content="website" />
    <meta property="og:image" content="{{ image }}" />
    <meta name="twitter:image" content="{{ image }}" />
    <meta property="og:url" content="{{ url }}" />
    <meta name="theme-color" content="#88BD45">
    <link rel="shortcut icon" type="image/png" href="/images/favicon.png" />
    <link rel="icon" type="image/png" href="/images/favicon.png" />
    <link rel="stylesheet" href="/ss/app_corp.css" />
    <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700,900" rel="stylesheet" />

FreddieMac.com

    {{> ribbon}}
    {{> nav-corp-primary}}
    {{> nav-corp-secondary}}

    {{> body}}
    {{> footer-corp}}
    {{> footer-js-corp}}


text:
#include "config.h"

#include <stdio.h>

#include "libvarnish.h"
#include "vcs_version.h"

const char *VCS_version =
    PACKAGE_TARNAME "-" PACKAGE_VERSION " revision " VCS_Version;

void
VCS_Message(const char *progname)
{
	fprintf(stderr, "%s (%s)\n", progname, VCS_version);
	fprintf(stderr, "Copyright (c) 2006 Verdens Gang AS\n");
	fprintf(stderr, "Copyright (c) 2006-2011 Varnish Software AS\n");
}


text:
/*
 * @test
 * @bug 4886011
 * @summary Test that QueryExp.toString() is reversible
 * @author Eamonn McManus
 * @run clean QueryExpStringTest
 * @run build QueryExpStringTest
 * @run main QueryExpStringTest
 */

import java.util.*;
import javax.management.*;

public class QueryExpStringTest {

    private static final ValueExp
        attr = Query.attr("attr"),
        qattr = Query.attr("className", "attr"),
        aa = Query.attr("A"),
        bb = Query.attr("B"),
        cc = Query.attr("C"),
        dd = Query.attr("D"),
        zero = Query.value(0),
        classattr = Query.classattr(),
        simpleString = Query.value("simpleString"),
        complexString = Query.value("a'b\\'\""),
        intValue = Query.value(12345678),
        integerValue = Query.value(new Integer(12345678)),
        longValue = Query.value(12345678L),
        floatValue = Query.value(2.5f),
        doubleValue = Query.value(2.5d),
        booleanValue = Query.value(true),
        plusValue = Query.plus(intValue, integerValue),
        timesValue = Query.times(doubleValue, floatValue),
        minusValue = Query.minus(floatValue, doubleValue),
        divValue = Query.div(doubleValue, floatValue);

    private static final QueryExp
        gt = Query.gt(intValue, floatValue),
        geq = Query.geq(intValue, floatValue),
        leq = Query.leq(intValue, floatValue),
        lt = Query.lt(intValue, floatValue),
        eq = Query.eq(intValue, floatValue),
        between = Query.between(intValue, floatValue, doubleValue),
        match = Query.match((AttributeValueExp) attr,
                            (StringValueExp) simpleString),
        initial = Query.initialSubString((AttributeValueExp) attr,
                                         (StringValueExp) simpleString),
        initialStar = Query.initialSubString((AttributeValueExp) attr,
                                             Query.value("*")),
        initialPercent = Query.initialSubString((AttributeValueExp) attr,
                                                Query.value("%")),
        any = Query.anySubString((AttributeValueExp) attr,
                                 (StringValueExp) simpleString),
        anyStar = Query.anySubString((AttributeValueExp) attr,
                                     Query.value("*")),
        anyPercent = Query.anySubString((AttributeValueExp) attr,
                                        Query.value("%")),
        ffinal = Query.finalSubString((AttributeValueExp) attr,
                                      (StringValueExp) simpleString),
        finalMagic = Query.finalSubString((AttributeValueExp) attr,
                                          Query.value("?*[\\")),
        in = Query.in(intValue, new ValueExp[] {intValue, floatValue}),
        and = Query.and(gt, lt),
        or = Query.or(gt, lt),
        not = Query.not(gt),
        aPlusB_PlusC = Query.gt(Query.plus(Query.plus(aa, bb), cc), zero),
        aPlus_BPlusC = Query.gt(Query.plus(aa, Query.plus(bb, cc)), zero);

    // Commented-out tests below require change to implementation

    private static final Object tests[] = {
        attr, "attr",
//      qattr, "className.attr",
// Preceding form now appears as className#attr, an incompatible change
// which we don't mind much because nobody uses the two-arg Query.attr.
        classattr, "Class",
        simpleString, "'simpleString'",
        complexString, "'a''b\\\''\"'",
        intValue, "12345678",
        integerValue, "12345678",
        longValue, "12345678",
        floatValue, "2.5",
        doubleValue, "2.5",
        booleanValue, "true",
        plusValue, "12345678 + 12345678",
        timesValue, "2.5 * 2.5",
        minusValue, "2.5 - 2.5",
        divValue, "2.5 / 2.5",
        gt, "(12345678) > (2.5)",
        geq, "(12345678) >= (2.5)",
        leq, "(12345678) <= (2.5)",
        lt, "(12345678) < (2.5)",
        eq, "(12345678) = (2.5)",
        between, "(12345678) between (2.5) and (2.5)",
        match, "attr like 'simpleString'",
        initial, "attr like 'simpleString*'",
        initialStar, "attr like '\\**'",
        initialPercent, "attr like '%*'",
        any, "attr like '*simpleString*'",
        anyStar, "attr like '*\\**'",
        anyPercent, "attr like '*%*'",
        ffinal, "attr like '*simpleString'",
        finalMagic, "attr like '*\\?\\*\\[\\\\'",
        in, "12345678 in (12345678, 2.5)",
        and, "((12345678) > (2.5)) and ((12345678) < (2.5))",
        or, "((12345678) > (2.5)) or ((12345678) < (2.5))",
        not, "not ((12345678) > (2.5))",
        aPlusB_PlusC, "(A + B + C) > (0)",
//        aPlus_BPlusC, "(A + (B + C)) > (0)",
    };

    public static void main(String[] args) throws Exception {
        System.out.println("Testing QueryExp.toString()");

        boolean ok = true;

        for (int i = 0; i < tests.length; i += 2) {
            String testString = tests[i].toString();
            String expected = (String) tests[i + 1];
            if (expected.equals(testString))
                System.out.println("OK: " + expected);
            else {
                System.err.println("Expected: {" + expected + "}; got: {" +
                                   testString + "}");
                ok = false;
            }

            try {
                Object parsed;
                String[] expectedref = new String[] {expected};
                if (tests[i] instanceof ValueExp)
                    parsed = parseExp(expectedref);
                else
                    parsed = parseQuery(expectedref);
                if (expectedref[0].length() > 0)
                    throw new Exception("Junk after parse: " + expectedref[0]);
                String parsedString = parsed.toString();
                if (parsedString.equals(expected))
                    System.out.println("OK: parsed " + parsedString);
                else {
                    System.err.println("Parse differs: expected: {" +
                                       expected + "}; got: {" +
                                       parsedString + "}");
                    ok = false;
                }
            } catch (Exception e) {
                System.err.println("Parse got exception: {" + expected +
                                   "}: " + e);
                ok = false;
            }
        }

        if (ok)
            System.out.println("Test passed");
        else {
            System.out.println("TEST FAILED");
            System.exit(1);
        }
    }

    private static QueryExp parseQuery(String[] ss) throws Exception {
        if (skip(ss, "("))
            return parseQueryAfterParen(ss);

        if (skip(ss, "not (")) {
            QueryExp not = parseQuery(ss);
            if (!skip(ss, ")"))
                throw new Exception("Expected ) after not (...");
            return Query.not(not);
        }

        ValueExp exp = parseExp(ss);

        if (skip(ss, " like ")) {
            ValueExp pat = parseExp(ss);
            if (!(exp instanceof AttributeValueExp &&
                  pat instanceof StringValueExp)) {
                throw new Exception("Expected types `attr like string': " +
                                    exp + " like " + pat);
            }
            StringValueExp spat = (StringValueExp) pat;
            return Query.match((AttributeValueExp) exp, spat);
        }

        if (skip(ss, " in (")) {
            List values = new ArrayList();
            if (!skip(ss, ")")) {
                do {
                    values.add(parseExp(ss));
                } while (skip(ss, ", "));
                if (!skip(ss, ")"))
                    throw new Exception("Expected ) after in (...");
            }
            return Query.in(exp, (ValueExp[]) values.toArray(new ValueExp[0]));
        }

        throw new Exception("Expected in or like after expression");
    }

    private static QueryExp parseQueryAfterParen(String[] ss)
            throws Exception {
        /* This is very ugly.  We might have "(q1) and (q2)" here, or
           we might have "(e1) < (e2)".  Since the syntax for a query
           (q1) is not the same as for an expression (e1), but can
           begin with one, we try to parse the query, and if we get an
           exception we then try to parse an expression.  It's a hacky
           kind of look-ahead.  */
        String start = ss[0];
        try {
            QueryExp lhs = parseQuery(ss);
            QueryExp result;

            if (skip(ss, ") and ("))
                result = Query.and(lhs, parseQuery(ss));
            else if (skip(ss, ") or ("))
                result = Query.or(lhs, parseQuery(ss));
            else
                throw new Exception("Expected `) and/or ('");
            if (!skip(ss, ")"))
                throw new Exception("Expected `)' after subquery");
            return result;
        } catch (Exception e) {
            ss[0] = start;
            ValueExp lhs = parseExp(ss);
            if (!skip(ss, ") "))
                throw new Exception("Expected `) ' after subexpression: " + ss[0]);
            String op = scanWord(ss);
            if (!skip(ss, " ("))
                throw new Exception("Expected ` (' after `" + op + "'");
            ValueExp rhs = parseExp(ss);
            if (!skip(ss, ")"))
                throw new Exception("Expected `)' after subexpression");
            if (op.equals("="))
                return Query.eq(lhs, rhs);
            if (op.equals("<"))
                return Query.lt(lhs, rhs);
            if (op.equals(">"))
                return Query.gt(lhs, rhs);
            if (op.equals("<="))
                return Query.leq(lhs, rhs);
            if (op.equals(">="))
                return Query.geq(lhs, rhs);
            if (!op.equals("between"))
                throw new Exception("Unknown operator `" + op + "'");
            if (!skip(ss, " and ("))
                throw new Exception("Expected ` and (' after between");
            ValueExp high = parseExp(ss);
            if (!skip(ss, ")"))
                throw new Exception("Expected `)' after subexpression");
            return Query.between(lhs, rhs, high);
        }
    }

    private static ValueExp parseExp(String[] ss) throws Exception {
        ValueExp lhs = parsePrimary(ss);

        while (true) {
        /* Look ahead to see if we have an arithmetic operator. */
        String back = ss[0];
        if (!skip(ss, " "))
                return lhs;
        if (ss[0].equals("") || "+-*/".indexOf(ss[0].charAt(0)) < 0) {
            ss[0] = back;
                return lhs;
        }

        final String op = scanWord(ss);
        if (op.length() != 1)
            throw new Exception("Expected arithmetic operator after space");
        if ("+-*/".indexOf(op) < 0)
            throw new Exception("Unknown arithmetic operator: " + op);
        if (!skip(ss, " "))
            throw new Exception("Expected space after arithmetic operator");
            ValueExp rhs = parsePrimary(ss);
        switch (op.charAt(0)) {
            case '+': lhs = Query.plus(lhs, rhs); break;
            case '-': lhs = Query.minus(lhs, rhs); break;
            case '*': lhs = Query.times(lhs, rhs); break;
            case '/': lhs = Query.div(lhs, rhs); break;
        default: throw new Exception("Can't happen: " + op.charAt(0));
        }
    }
    }

    private static ValueExp parsePrimary(String[] ss) throws Exception {
        String s = ss[0];

        if (s.length() == 0)
            throw new Exception("Empty string found, expression expected");

        char first = s.charAt(0);

        if (first == ' ')
            throw new Exception("Space found, expression expected");

        if (first == '-' || Character.isDigit(first))
            return parseNumberExp(ss);

        if (first == '\'')
            return parseString(ss);

        if (matchWord(ss, "true"))
            return Query.value(true);

        if (matchWord(ss, "false"))
            return Query.value(false);

        if (matchWord(ss, "Class"))
            return Query.classattr();

        String word = scanWord(ss);
        int lastDot = word.lastIndexOf('.');
        if (lastDot < 0)
            return Query.attr(word);
        else
            return Query.attr(word.substring(0, lastDot),
                              word.substring(lastDot + 1));
    }

    private static String scanWord(String[] ss) throws Exception {
        String s = ss[0];
        int space = s.indexOf(' ');
        int rpar = s.indexOf(')');
        if (space < 0 && rpar < 0) {
            ss[0] = "";
            return s;
        }
        int stop;
        if (space >= 0 && rpar >= 0)  // string has both space and ), stop at first
            stop = Math.min(space, rpar);
        else                          // string has only one, stop at it
            stop = Math.max(space, rpar);
        String word = s.substring(0, stop);
        ss[0] = s.substring(stop);
        return word;
    }

    private static boolean matchWord(String[] ss, String word)
            throws Exception {
        String s = ss[0];
        if (s.startsWith(word)) {
            int len = word.length();
            if (s.length() == len || s.charAt(len) == ' '
                || s.charAt(len) == ')') {
                ss[0] = s.substring(len);
                return true;
            }
        }
        return false;
    }

    private static ValueExp parseNumberExp(String[] ss) throws Exception {
        String s = ss[0];
        int len = s.length();
        boolean isFloat = false;
        int i;
        for (i = 0; i < len; i++) {
            char c = s.charAt(i);
            if (Character.isDigit(c) || c == '-' || c == '+')
                continue;
            if (c == '.' || c == 'e' || c == 'E') {
                isFloat = true;
                continue;
            }
            break;
        }
        ss[0] = s.substring(i);
        s = s.substring(0, i);
        if (isFloat)
            return Query.value(Double.parseDouble(s));
        else
            return Query.value(Long.parseLong(s));
    }

    private static ValueExp parseString(String[] ss) throws Exception {
        if (!skip(ss, "'"))
            throw new Exception("Expected ' at start of string");
        String s = ss[0];
        int len = s.length();
        StringBuffer buf = new StringBuffer();
        int i;
        for (i = 0; i < len; i++) {
            char c = s.charAt(i);
            if (c == '\'') {
                ++i;
                if (i >= len || s.charAt(i) != '\'') {
                    ss[0] = s.substring(i);
                return Query.value(buf.toString());
            }
            }
            buf.append(c);
        }
        throw new Exception("No closing ' at end of string");
    }

    private static boolean skip(String[] ss, String skip) {
        if (ss[0].startsWith(skip)) {
            ss[0] = ss[0].substring(skip.length());
            return true;
        } else
            return false;
    }
}


text:
'use strict';

// Sigfoxdevices controller
angular.module('sigfoxdevices').controller('SigfoxdevicesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Sigfoxdevices',
	function($scope, $stateParams, $location, Authentication, Sigfoxdevices) {
		$scope.authentication = Authentication;

		// Create new Sigfoxdevice
		$scope.create = function() {
			// Create new Sigfoxdevice object
			var sigfoxdevice = new Sigfoxdevices ({
				name: this.name
			});

			// Redirect after save
			sigfoxdevice.$save(function(response) {
				$location.path('sigfoxdevices/' + response._id);

				// Clear form fields
				$scope.name = '';
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Remove existing Sigfoxdevice
		$scope.remove = function(sigfoxdevice) {
			if ( sigfoxdevice ) {
				sigfoxdevice.$remove();

				for (var i in $scope.sigfoxdevices) {
					if ($scope.sigfoxdevices [i] === sigfoxdevice) {
						$scope.sigfoxdevices.splice(i, 1);
					}
				}
			} else {
				$scope.sigfoxdevice.$remove(function() {
					$location.path('sigfoxdevices');
				});
			}
		};

		// Update existing Sigfoxdevice
		$scope.update = function() {
			var sigfoxdevice = $scope.sigfoxdevice;

			sigfoxdevice.$update(function() {
				$location.path('sigfoxdevices/' + sigfoxdevice._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of Sigfoxdevices
		$scope.find = function() {
			$scope.sigfoxdevices = Sigfoxdevices.query();
		};

		// Find existing Sigfoxdevice
		$scope.findOne = function() {
			$scope.sigfoxdevice = Sigfoxdevices.get({
				sigfoxdeviceId: $stateParams.sigfoxdeviceId
			});
		};
	}
]);


text:
package iso20022

type PriceValueType8Code string


text:
package org.apache.http.auth;

import org.apache.http.ProtocolException;
import org.apache.http.annotation.Immutable;

/**
 * Signals a failure in authentication process
 *
 *
 * @since 4.0
 */
@Immutable
public class AuthenticationException extends ProtocolException {

    private static final long serialVersionUID = -6794031905674764776L;

    /**
     * Creates a new AuthenticationException with a {@code null} detail message.
     */
    public AuthenticationException() {
        super();
    }

    /**
     * Creates a new AuthenticationException with the specified message.
     *
     * @param message the exception detail message
     */
    public AuthenticationException(final String message) {
        super(message);
    }

    /**
     * Creates a new AuthenticationException with the specified detail message and cause.
     *
     * @param message the exception detail message
     * @param cause the {@code Throwable} that caused this exception, or {@code null}
     * if the cause is unavailable, unknown, or not a {@code Throwable}
     */
    public AuthenticationException(final String message, final Throwable cause) {
        super(message, cause);
    }

}


text:
FOUNDATION_EXPORT double Pods_FLCommonLibrary_TestsVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_FLCommonLibrary_TestsVersionString[];


text:
$.components.register("toolbar", {
  mode: "init",
  init: function(context) {
    if (!$.fn.toolbar) return;

    var defaults = $.components.getDefaults("toolbar");

    $('[data-plugin="toolbar"]', context).each(function() {
      var $this = $(this);
      var content = $this.data("toolbar");

      var options = $.extend(true, {}, defaults);

      if (content) {
        options.content = content;
      }

      $this.toolbar(options);
    });
  }
});


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
    <title>React</title>
    <link href="assets/css/ionic.css" rel="stylesheet" type="text/css">
    <link href="assets/css/keypoint.css" rel="stylesheet" type="text/css">
    <link href="assets/css/prettify.css" rel="stylesheet" type="text/css">
    <link href="assets/css/slides.css" rel="stylesheet" type="text/css">

Introduction to React

@dothanhlam

About

Lam Do

Ho Chi Minh City, Vietnam

@dothanhlam

http://dothanhlam.wordpress.com

https://github.com/dothanhlam

What is React ?

A library for creating user interfaces

Renders UI and responds to events

Plays the role "V(iew)" in MVC

Fundamentals

Everything is a Component

Build component, not template

not a framework, neither an architecture

Re-render everything on every update

Fast virtual DOM

Build component, not template

Combine DOM generation and display logic

Transform data into interface components

Data can come from anywhere

First glance

        <xmp class="prettyprint small">var HelloWorld = React.createClass({
    render: function() {
        return
            (
{'Hello, ' + this.props.name}
);
    }
});
React.renderComponent(<Hello name="Raw Oyster" />, document.body);
        </xmp>

JSX

Optional HTML-like markup

Declarative description of the UI inlined in JS code

Combines ease-of-use of templates with power of JavaScript

Preprocessor translates to plain JavaScript:

On the fly (suitable during development)

Offline using the React CLI

JSX - a glance

        <xmp class="prettyprint" style="margin-top:2rem;">var Header = React.createClass({
    render: function () {
            return (
Employee Directory
);
    }
    // other
    React.DOM.h1({}, 'Employee Directory');
});</xmp>

Traditional Performance Best Practices

Avoid expensive DOM operations

Minimize access to the DOM

Update elements offline before reinserting into the DOM

Avoid tweaking layouts in JavaScript

Re-render everything on every update

Create lightweight description of component UI

Diff it with the old one

Compute minimal set of changes to apply to the DOM

Batch execute all updates

Still confusing?

React builds a new virtual DOM subtree

We just saw the term Virtual DOM

Virtual DOM

It's pure JavaScript, in-memory representation of the DOM

render() fires whenever something changes

React modifies the real DOM to match

Fast, fast and fast

How about actual DOM ?

this.getDOMNode();

We just say virtual DOM fast

DOM is slow

Computes minimal DOM operations

Batched reads and writes for optimal DOM performance

Usually faster than manual DOM operations

Automatic top-level event delegation

Provides hooks for custom update logic

Virtual DOM Benefits

Clean
Clear, descriptive programming model

Fast
Optimized DOM updates and less reflows

... more, and more

Run on NodeJS

Java ... via Nashorn JavaScript Engine

Optimizations base on application structure

Testability for free

SVG, VML and ... canvas support

Web worker ?

Hold for 5 minutes ...

The Lifecycle

Initialization

Props change

States change

Component unmount

diving deeper

Initialization

getDefaultProps

getInitialState

componentWillMount

render

componentDidMount

Props change

componentWillReceiveProps

shouldComponentUpdate

componentWillUpdate

render

componentDidUpdate

State change

shouldComponentUpdate

componentWillUpdate

render

componentDidUpdate

Unmount

componentWillUnmount

Show me the code ...

Creating a Component

        <xmp class="prettyprint">var Header = React.createClass({
    render: function () {
        return (

Employee Directory

        );
    }
});</xmp>

Composition

        <xmp class="prettyprint">var HomePage = React.createClass({
    render: function () {
        return (

            <SearchBar />
            <EmployeeList />

        );
    }
});</xmp>

Data Flow

Parent-to-Child

Properties passed by the parent are available in this.props in the child

Properties are immutable

Data Flow

Parent

        <xmp class="prettyprint">var HomePage = React.createClass({
    render: function () {
        return (

            <SearchBar/>
            <EmployeeList/>

        );
    }
});</xmp>

Data Flow

Child

        <xmp class="prettyprint">var Header = React.createClass({
    render: function () {
        return (

{this.props.title}

        );
    }
});</xmp>

Inverse Data Flow

Child-to-Parent

Pass event handler has a property

Inverse Data Flow

Parent

        <xmp class="prettyprint small">var HomePage = React.createClass({
    searchHandler:function(key) {
        alert('Search key: ' + key);
    },
    render: function () {
        return (

            <SearchBar searchHandler={this.searchHandler}/>
                <EmployeeList/>

        );
    }
});</xmp>

Inverse Data Flow

Child

        <xmp class="prettyprint small">var SearchBar = React.createClass({
    keyChange: function(event) {
    var searchKey = event.target.value;
        this.props.searchHandler(searchKey);
    },
    render: function () {
        return (
        <input type="search" onChange={this.keyChange}/>
        );
    }
});</xmp>

State

Parent

        <xmp class="prettyprint small">var HomePage = React.createClass({
    getInitialState: function() {
        return {employees: []}
    },
    searchHandler: function(key) {
        this.props.service.findByName(key).then(function(result) {
            this.setState({searchKey: key, employees: result});
        }.bind(this));
    },
    render: function () {
        return (

            <SearchBar searchHandler={this.searchHandler}/>
                <EmployeeList employees={this.state.employees}/>

        );
    }
});</xmp>

State

Child

        <xmp class="prettyprint small">var EmployeeList = React.createClass({
    render: function () {
        var items = this.props.employees.map(function (employee) {
        return (
        <EmployeeListItem
                key={employee.id} employee={employee}/>
            );
        });
        return (
{items}
);
    }
});</xmp>

The key attribute is used to uniquely identify an instance of a component (useful in the diff process)

State

Nested Child

        <xmp class="prettyprint small">var EmployeeListItem = React.createClass({
        render: function () {
            return (

                    {this.props.employee.firstName}
                    {this.props.employee.lastName}

            );
        }
    });</xmp>

Resources

React Tutorial

Rethinking best practices

Secrets of the Virtual DOM

Thinking in React

Trader Desktop

Beer Explorer

Employee Directory

Credit

This slide is just a folk by @ccoenraets

I made the modification with providing more specific information

Thank You!

Keypoint


text:
package io.datarouter.client.mysql.test.client.insert.generated;

import io.datarouter.model.key.primary.PrimaryKey;

public interface PutOpGeneratedTestBeanKey<PK extends PutOpGeneratedTestBeanKey<PK>> extends PrimaryKey<PK>{

	Long getId();

}


text:
<?xml version="1.0" ?>
<xmcda:XMCDA xmlns:xmcda="http://www.decision-deck.org/2013/XMCDA-3.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.decision-deck.org/2013/XMCDA-3.0.0 http://www.decision-deck.org/xmcda/_downloads/XMCDA-3.0.0.xsd">

    <alternativesAssignments>
        <alternativeAssignment>
            <alternativeID>a1</alternativeID>
            <categoriesInterval>
                <lowerBound>
                    <categoryID>C3</categoryID>
                </lowerBound>
                <upperBound>
                    <categoryID>C3</categoryID>
                </upperBound>
            </categoriesInterval>
        </alternativeAssignment>
        <alternativeAssignment>
            <alternativeID>a2</alternativeID>
            <categoriesInterval>
                <lowerBound>
                    <categoryID>C1</categoryID>
                </lowerBound>
                <upperBound>
                    <categoryID>C2</categoryID>
                </upperBound>
            </categoriesInterval>
        </alternativeAssignment>
        <alternativeAssignment>
            <alternativeID>a3</alternativeID>
            <categoriesInterval>
                <lowerBound>
                    <categoryID>C1</categoryID>
                </lowerBound>
                <upperBound>
                    <categoryID>C4</categoryID>
                </upperBound>
            </categoriesInterval>
        </alternativeAssignment>
    </alternativesAssignments>
</xmcda:XMCDA>


text:
function locator(value: string, fromIndex: number) {
  return value.indexOf("$", fromIndex);
}

const ESCAPED_INLINE_MATH = /^\\\$/;
const INLINE_MATH = /^\$((?:\\\$|[^$])+)\$/;
const INLINE_MATH_DOUBLE = /^\$\$((?:\\\$|[^$])+)\$\$/;

// eslint-disable-next-line no-unused-vars
export function inlinePlugin(this: any, opts: object) {
  function inlineTokenizer(eat: any, value: string, silent: boolean) {
    let isDouble = true;
    let match = INLINE_MATH_DOUBLE.exec(value);
    if (!match) {
      match = INLINE_MATH.exec(value);
      isDouble = false;
    }
    const escaped = ESCAPED_INLINE_MATH.exec(value);

    if (escaped) {
      /* istanbul ignore if - never used (yet) */
      if (silent) {
        return true;
      }
      return eat(escaped[0])({
        type: "text",
        value: "$"
      });
    }

    if (value.slice(-2) === "\\$") {
      return eat(value)({
        type: "text",
        value: value.slice(0, -2) + "$"
      });
    }

    if (match) {
      /* istanbul ignore if - never used (yet) */
      if (silent) {
        return true;
      }

      const endingDollarInBackticks =
        match[0].includes("`") && value.slice(match[0].length).includes("`");
      if (endingDollarInBackticks) {
        const toEat = value.slice(0, value.indexOf("`"));
        return eat(toEat)({
          type: "text",
          value: toEat
        });
      }

      const trimmedContent = match[1].trim();

      if (isDouble) {
        return eat(match[0])({
          type: "math",
          value: trimmedContent,
          data: {
            hName: "div",
            hProperties: {
              className: "math"
            },
            hChildren: [
              {
                type: "text",
                value: trimmedContent
              }
            ]
          }
        });
      }

      return eat(match[0])({
        type: "inlineMath",
        value: trimmedContent,
        data: {
          hName: "span",
          hProperties: {
            className: "inlineMath"
          },
          hChildren: [
            {
              type: "text",
              value: trimmedContent
            }
          ]
        }
      });
    }
  }
  inlineTokenizer.locator = locator;

  const Parser = this.Parser;

  // Inject inlineTokenizer
  const inlineTokenizers = Parser.prototype.inlineTokenizers;
  const inlineMethods = Parser.prototype.inlineMethods;
  inlineTokenizers.math = inlineTokenizer;
  inlineMethods.splice(inlineMethods.indexOf("text"), 0, "math");

  const Compiler = this.Compiler;

  // Stringify for math inline
  if (Compiler != null) {
    const visitors = Compiler.prototype.visitors;
    visitors.inlineMath = function(node: any) {
      return "$" + node.value + "$";
    };
  }
}

export default inlinePlugin;


text:
<?php

namespace Tkcns\Model;

/**
 * Class Client
 *
 * @package Tkcns\Model
 */
class Client implements ModelInterface
{
    use ModelTrait,
        IdTrait;

    /**
     * @var string
     */
    protected $clientName;

    /**
     * @var string
     */
    protected $clientUid;

    /**
     * @var int
     */
    protected $miReport;

    /**
     * @return string
     */
    public function getClientName()
    {
        return $this->clientName;
    }

    /**
     * @param string $clientName
     * @return $this
     */
    public function setClientName($clientName)
    {
        $this->clientName = $clientName;
        return $this;
    }

    /**
     * @return string
     */
    public function getClientUid()
    {
        return $this->clientUid;
    }

    /**
     * @param string $clientUid
     * @return $this
     */
    public function setClientUid($clientUid)
    {
        $this->clientUid = $clientUid;
        return $this;
    }

    /**
     * @return int
     */
    public function getMiReport()
    {
        return $this->miReport;
    }

    /**
     * @param int $miReport
     * @return $this
     */
    public function setMiReport($miReport)
    {
        $this->miReport = $miReport;
        return $this;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<CustomFieldTranslation xmlns="http://soap.sforce.com/2006/04/metadata">
    <name>Term__c</name>
    <relationshipLabel>Kurssitarjonnat</relationshipLabel>
    <label>Jakso</label>
</CustomFieldTranslation>


text:
export default {
  header: {
    id: 'menu.title',
    defaultMessage: 'MENU',
  },
};


text:
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'lib'))
import base58
import hashlib
import re
from decimal import Decimal
import simplejson
import binascii
from misc import printdbg, epoch2str
import time

def is_valid_dash_address(address, network='mainnet'):
    raise RuntimeWarning('This method should not be used with sibcoin')
    # Only public key addresses are allowed
    # A valid address is a RIPEMD-160 hash which contains 20 bytes
    # Prior to base58 encoding 1 version byte is prepended and
    # 4 checksum bytes are appended so the total number of
    # base58 encoded bytes should be 25.  This means the number of characters
    # in the encoding should be about 34 ( 25 * log2( 256 ) / log2( 58 ) ).
    dash_version = 140 if network == 'testnet' else 76

    # Check length (This is important because the base58 library has problems
    # with long addresses (which are invalid anyway).
    if ((len(address) < 26) or (len(address) > 35)):
        return False

    address_version = None

    try:
        decoded = base58.b58decode_chk(address)
        address_version = ord(decoded[0:1])
    except:
        # rescue from exception, not a valid Dash address
        return False

    if (address_version != dash_version):
        return False

    return True

def is_valid_sibcoin_address(address, network='mainnet'):
    # Only public key addresses are allowed
    # A valid address is a RIPEMD-160 hash which contains 20 bytes
    # Prior to base58 encoding 1 version byte is prepended and
    # 4 checksum bytes are appended so the total number of
    # base58 encoded bytes should be 25.  This means the number of characters
    # in the encoding should be about 34 ( 25 * log2( 256 ) / log2( 58 ) ).
    dash_version = 125 if network == 'testnet' else 63

    # Check length (This is important because the base58 library has problems
    # with long addresses (which are invalid anyway).
    if ((len(address) < 26) or (len(address) > 35)):
        return False

    address_version = None

    try:
        decoded = base58.b58decode_chk(address)
        address_version = ord(decoded[0:1])
    except:
        # rescue from exception, not a valid Dash address
        return False

    if (address_version != dash_version):
        return False

    return True

def is_valid_address(address, network='mainnet'):
    return is_valid_sibcoin_address(address, network)

def hashit(data):
    return int(hashlib.sha256(data.encode('utf-8')).hexdigest(), 16)

# returns the masternode VIN of the elected winner
def elect_mn(**kwargs):
    current_block_hash = kwargs['block_hash']
    mn_list = kwargs['mnlist']

    # filter only enabled MNs
    enabled = [mn for mn in mn_list if mn.status == 'ENABLED']

    block_hash_hash = hashit(current_block_hash)

    candidates = []
    for mn in enabled:
        mn_vin_hash = hashit(mn.vin)
        diff = mn_vin_hash - block_hash_hash
        absdiff = abs(diff)
        candidates.append({'vin': mn.vin, 'diff': absdiff})

    candidates.sort(key=lambda k: k['diff'])

    try:
        winner = candidates[0]['vin']
    except:
        winner = None

    return winner

def parse_masternode_status_vin(status_vin_string):
    status_vin_string_regex = re.compile(r'CTxIn\(COutPoint\(([0-9a-zA-Z]+),\s*(\d+)\),')

    m = status_vin_string_regex.match(status_vin_string)

    # To Support additional format of string return from masternode status rpc.
    if m is None:
        status_output_string_regex = re.compile(r'([0-9a-zA-Z]+)-(\d+)')
        m = status_output_string_regex.match(status_vin_string)

    txid = m.group(1)
    index = m.group(2)

    vin = txid + '-' + index
    if (txid == '0000000000000000000000000000000000000000000000000000000000000000'):
        vin = None

    return vin

def create_superblock(proposals, event_block_height, budget_max, sb_epoch_time):
    from models import Superblock, GovernanceObject, Proposal
    from constants import SUPERBLOCK_FUDGE_WINDOW
    import copy

    # don't create an empty superblock
    if (len(proposals) == 0):
        printdbg("No proposals, cannot create an empty superblock.")
        return None

    budget_allocated = Decimal(0)
    fudge = SUPERBLOCK_FUDGE_WINDOW  # fudge-factor to allow for slightly incorrect estimates

    payments_list = []

    for proposal in proposals:
        fmt_string = "name: %s, rank: %4d, hash: %s, amount: %s <= %s"

        # skip proposals that are too expensive...
        if (budget_allocated + proposal.payment_amount) > budget_max:
            printdbg(
                fmt_string % (
                    proposal.name,
                    proposal.rank,
                    proposal.object_hash,
                    proposal.payment_amount,
                    "skipped (blows the budget)",
                )
            )
            continue

        # skip proposals if the SB isn't within the Proposal time window...
        window_start = proposal.start_epoch - fudge
        window_end = proposal.end_epoch + fudge

        printdbg("\twindow_start: %s" % epoch2str(window_start))
        printdbg("\twindow_end: %s" % epoch2str(window_end))
        printdbg("\tsb_epoch_time: %s" % epoch2str(sb_epoch_time))

        if (sb_epoch_time < window_start or sb_epoch_time > window_end):
            printdbg(
                fmt_string % (
                    proposal.name,
                    proposal.rank,
                    proposal.object_hash,
                    proposal.payment_amount,
                    "skipped (SB time is outside of Proposal window)",
                )
            )
            continue

        printdbg(
            fmt_string % (
                proposal.name,
                proposal.rank,
                proposal.object_hash,
                proposal.payment_amount,
                "adding",
            )
        )

        payment = {
            'address': proposal.payment_address,
            'amount': "{0:.8f}".format(proposal.payment_amount),
            'proposal': "{}".format(proposal.object_hash)
        }

        temp_payments_list = copy.deepcopy(payments_list)
        temp_payments_list.append(payment)

        # calculate size of proposed Superblock
        sb_temp = Superblock(
            event_block_height=event_block_height,
            payment_addresses='|'.join([pd['address'] for pd in temp_payments_list]),
            payment_amounts='|'.join([pd['amount'] for pd in temp_payments_list]),
            proposal_hashes='|'.join([pd['proposal'] for pd in temp_payments_list])
        )
        proposed_sb_size = len(sb_temp.serialise())

        # add proposal and keep track of total budget allocation
        budget_allocated += proposal.payment_amount
        payments_list.append(payment)

    # don't create an empty superblock
    if not payments_list:
        printdbg("No proposals made the cut!")
        return None

    # 'payments' now contains all the proposals for inclusion in the
    # Superblock, but needs to be sorted by proposal hash descending
    payments_list.sort(key=lambda k: k['proposal'], reverse=True)

    sb = Superblock(
        event_block_height=event_block_height,
        payment_addresses='|'.join([pd['address'] for pd in payments_list]),
        payment_amounts='|'.join([pd['amount'] for pd in payments_list]),
        proposal_hashes='|'.join([pd['proposal'] for pd in payments_list]),
    )
    printdbg("generated superblock: %s" % sb.__dict__)

    return sb

# convenience
def deserialise(hexdata):
    json = binascii.unhexlify(hexdata)
    obj = simplejson.loads(json, use_decimal=True)
    return obj

def serialise(dikt):
    json = simplejson.dumps(dikt, sort_keys=True, use_decimal=True)
    hexdata = binascii.hexlify(json.encode('utf-8')).decode('utf-8')
    return hexdata

def did_we_vote(output):
    from bitcoinrpc.authproxy import JSONRPCException

    # sentinel
    voted = False
    err_msg = ''

    try:
        detail = output.get('detail').get('sibcoin.conf')
        result = detail.get('result')
        if 'errorMessage' in detail:
            err_msg = detail.get('errorMessage')
    except JSONRPCException as e:
        result = 'failed'
        err_msg = e.message

    # success, failed
    printdbg("result  = [%s]" % result)
    if err_msg:
        printdbg("err_msg = [%s]" % err_msg)

    voted = False
    if result == 'success':
        voted = True

    # in case we spin up a new instance or server, but have already voted
    # on the network and network has recorded those votes
    m_old = re.match(r'^time between votes is too soon', err_msg)
    m_new = re.search(r'Masternode voting too often', err_msg, re.M)

    if result == 'failed' and (m_old or m_new):
        printdbg("DEBUG: Voting too often, need to sync w/network")
        voted = False

    return voted

def parse_raw_votes(raw_votes):
    votes = []
    for v in list(raw_votes.values()):
        (outpoint, ntime, outcome, signal) = v.split(':')
        signal = signal.lower()
        outcome = outcome.lower()

        mn_collateral_outpoint = parse_masternode_status_vin(outpoint)
        v = {
            'mn_collateral_outpoint': mn_collateral_outpoint,
            'signal': signal,
            'outcome': outcome,
            'ntime': ntime,
        }
        votes.append(v)

    return votes

def blocks_to_seconds(blocks):
    """
    Return the estimated number of seconds which will transpire for a given
    number of blocks.
    """
    return blocks * 2.62 * 60


text:
/*****************************************************************************\
 *                        ANALYSIS PERFORMANCE TOOLS                         *
 *                                   Extrae                                  *
 *              Instrumentation package for parallel applications            *
 *****************************************************************************
 *     ___     This library is free software; you can redistribute it and/or *
 *    /  __         modify it under the terms of the GNU LGPL as published   *
 *   /  /  _____    by the Free Software Foundation; either version 2.1      *
 *  /  /  /     \   of the License, or (at your option) any later version.   *
 * (  (  ( B S C )                                                           *
 *  \  \  \_____/   This library is distributed in 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 LGPL 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          *
 * The GNU LEsser General Public License is contained in the file COPYING.   *
 *                                 ---------                                 *
 *   Barcelona Supercomputing Center - Centro Nacional de Supercomputacion   *
\*****************************************************************************/

/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\
 | @file: $HeadURL: https://svn.bsc.es/repos/ptools/extrae/branches/2.5/tests/overhead/extrae_get_caller1.c $
 | @last_commit: $Date: 2013-07-17 18:39:08 +0200 (mié, 17 jul 2013) $
 | @version:     $Revision: 1942 $
\* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
#include <stdio.h>
#include <time.h>

#include "extrae_user_events.h"

extern void * get_caller (int);

int main(int argc, char **argv)
{
	unsigned long long t1, t2;
	struct timespec start, stop;
	int n = 1000000, i;
	Extrae_init();
	clock_gettime (CLOCK_MONOTONIC, &start);
	for (i = 0; i < n; i++)
		get_caller (2);
	clock_gettime (CLOCK_MONOTONIC, &stop);
	t1 = start.tv_nsec;
	t1 += start.tv_sec * 1000000000;
	t2 = stop.tv_nsec;
	t2 += stop.tv_sec * 1000000000;
	printf ("RESULT : Extrae_eventandcounters() %Lu ns\n", (t2 - t1) / n);
	Extrae_fini();
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
	"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

		<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
		<link rel="stylesheet" href="css/master.css" type="text/css" />
		<title>Job Listing - Pro Job Seeker</title>

Pro Job Seeker

Industry leaders since 2006. The best companies use our system to find the best and brightest professionals.

					  Post a Job, 90 days for only 400€

						Programming Jobs
						Latest post about 20 hours ago

							New

							San Francisco
							Ruby on Rails developer in
							Rails Jungle S.L.
							Nov 6

							New

							Berlin
							.Net Developer in
							Netologies Inc
							Nov 4

							New

							NY City
							Front-end expert (jQuery) in
							RatCo Solutions
							Nov 1

								Barcelona
								LAMP Programmer in
								Freesoft S.A
								Oct 15

							Chicago
							Spark Framework Expert in
							tuxprog.com
							Oct 9

« Back to all Jobs

© 2011 Job Listing Company International


text:
package org.apache.geronimo.st.v11.ui.sections;

import java.util.List;

import javax.xml.bind.JAXBElement;

import org.apache.geronimo.j2ee.deployment.DependenciesType;
import org.apache.geronimo.j2ee.deployment.DependencyType;
import org.apache.geronimo.j2ee.deployment.EnvironmentType;
import org.apache.geronimo.st.ui.CommonMessages;
import org.apache.geronimo.st.ui.sections.AbstractTableSection;
import org.apache.geronimo.st.v11.ui.Activator;
import org.apache.geronimo.st.v11.ui.wizards.DependencyWizard;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.IContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.forms.widgets.FormToolkit;

/**
 * @version $Rev$ $Date$
 */
public class DependencySection extends AbstractTableSection {

    boolean isServerEnvironment;
    protected EnvironmentType environment;

    public DependencySection(JAXBElement plan, EnvironmentType environment, Composite parent, FormToolkit toolkit, int style) {
        this(plan, environment, parent, toolkit, style, true);
    }

    public DependencySection(JAXBElement plan, EnvironmentType environment, Composite parent, FormToolkit toolkit, int style, boolean isServerEnvironment) {
        super(plan, parent, toolkit, style);
        this.environment = environment;
        this.isServerEnvironment = isServerEnvironment;
        this.COLUMN_NAMES = new String[] {
                CommonMessages.groupId, CommonMessages.artifactId, CommonMessages.version, CommonMessages.artifactType
        };
        createClient();
        getSection().setExpanded(false);
    }

    public String getTitle() {
        if (isServerEnvironment) {
            return CommonMessages.editorSectionDependenciesTitle;
        } else {
            return CommonMessages.editorSectionClientDependenciesTitle;
        }
    }

    public String getDescription() {
        if (isServerEnvironment) {
            return CommonMessages.editorSectionDependenciesDescription;
        } else {
            return CommonMessages.editorSectionClientDependenciesDescription;
        }
    }

    public List getObjectContainer() {
        return getDependencies().getDependency();
    }

    private DependenciesType getDependencies() {
        if (environment == null) {
            environment = new EnvironmentType();
        }
        if (environment.getDependencies() == null) {
            environment.setDependencies(new DependenciesType());
        }
        return environment.getDependencies();
    }

    @Override
    public Wizard getWizard() {
        return new DependencyWizard(this);
    }

    public ImageDescriptor getImageDescriptor() {
        return Activator.imageDescriptorFromPlugin("org.eclipse.jdt.ui", "icons/full/obj16/jar_obj.gif");
    }

    public Class getTableEntryObjectType() {
        return DependencyType.class;
    }

    public Object getInput() {
        return getDependencies();
    }

    @Override
    public IContentProvider getContentProvider() {
        return new ContentProvider() {
            @Override
            public Object[] getElements(Object inputElement) {
                if (!DependenciesType.class.isInstance(inputElement)) {
                    return new String[] { "" };
                }
                return ((DependenciesType) inputElement).getDependency().toArray();
            }
        };
    }

    @Override
    public ITableLabelProvider getLabelProvider() {
        return new LabelProvider() {
            @Override
            public String getColumnText(Object element, int columnIndex) {
                if (DependencyType.class.isInstance(element)) {
                	DependencyType dependency = (DependencyType) element;
                    switch (columnIndex) {
                    case 0:
                        return dependency.getGroupId();
                    case 1:
                        return dependency.getArtifactId();
                    case 2:
                        return dependency.getVersion();
                    case 3:
                        return dependency.getType();
                    }
                }
                return "";
            }
        };
    }
}