text:
E2.p = E2.plugins["toggle_modulator"] = function(core, node)
{
	this.desc = 'For every continous sequence of \'true\' values sent to the \'trigger\' input slot the emitted value will switch from true to false and visa versa. The initial value is true.';

	this.input_slots = [
		{ name: 'trigger', dt: core.datatypes.BOOL, desc: 'Every time true is sent one or more times in a row, the emitted value will switch between true and false, starting with true.', def: false }
	];

	this.output_slots = [
		{ name: 'bool', dt: core.datatypes.BOOL, desc: 'The current state.', def: true }
	];

	this.state = { value: true };
};

E2.p.prototype.update_input = function(slot, data)
{
	if(data)
	{
		this.triggered = true;
		this.state.value = !this.state.value;
	}
};

E2.p.prototype.update_state = function()
{
	if(!this.triggered)
		this.updated = false;

	this.triggered = false;
};

E2.p.prototype.update_output = function(slot)
{
	return this.state.value;
};

E2.p.prototype.state_changed = function(ui)
{
	if(!ui)
	{
		this.state.value = true;
		this.triggered = true;
	}
};

redpajama_set_name: RedPajamaGithub


text:
class ZenApi::Owner < ZenApi::User
  include ZenApi::Resource

  tag 'owner'
  element :name, String

  validates :name, :presence => true

end


text:
'use strict';

/**
 * Module dependencies
 */
var cajaturnosPolicy = require('../policies/cajaturnos.server.policy'),
  cajaturnos = require('../controllers/cajaturnos.server.controller');

module.exports = function(app) {
  // Cierreturnos Routes
  app.route('/api/cajaturnos').all(cajaturnosPolicy.isAllowed)
    .get(cajaturnos.list)
    .post(cajaturnos.create);

  app.route('/api/cajaturnos/:cajaturnoId').all(cajaturnosPolicy.isAllowed)
    .get(cajaturnos.read)
    .put(cajaturnos.update)
    .delete(cajaturnos.delete);

  app.route('/api/getMulFilter')
    .post(cajaturnos.getMulFilter);

  // Finish by binding the Cierreturno middleware
  app.param('cajaturnoId', cajaturnos.cajaturnoByID);
};


text:
<?php
/**
 * Created by PhpStorm.
 * User: fernandobritofl
 * Date: 4/22/15
 * Time: 10:34 PM
 */

namespace Laralib\L5scaffold\Makes;

use Illuminate\Filesystem\Filesystem;
use Laralib\L5scaffold\Commands\ScaffoldMakeCommand;
use Laralib\L5scaffold\Migrations\SchemaParser;
use Laralib\L5scaffold\Migrations\SyntaxBuilder;

class MakeMigration {
    use MakerTrait;

    protected $scaffoldCommandObj;

    public function __construct(ScaffoldMakeCommand $scaffoldCommand, Filesystem $files)
    {
        $this->files = $files;
        $this->scaffoldCommandObj = $scaffoldCommand;

        $this->start();
    }

    protected function start(){
        // Cria o nome do arquivo do migration // create_tweets_table
        $name = 'create_'.str_plural(strtolower( $this->scaffoldCommandObj->argument('name') )).'_table';

        // Verifica se o arquivo existe com o mesmo o nome
        if ($this->files->exists($path = $this->getPath($name)))
        {
            return $this->scaffoldCommandObj->error($this->type.' already exists!');
        }

        // Cria a pasta caso nao exista
        $this->makeDirectory($path);

        // Grava o arquivo
        $this->files->put($path, $this->compileMigrationStub());

        $this->scaffoldCommandObj->info('Migration created successfully');
    }

    /**
     * Get the path to where we should store the migration.
     *
     * @param  string $name
     * @return string
     */
    protected function getPath($name)
    {
        return './database/migrations/'.date('Y_m_d_His').'_'.$name.'.php';
    }

    /**
     * Compile the migration stub.
     *
     * @return string
     */
    protected function compileMigrationStub()
    {
        $stub = $this->files->get(__DIR__.'/../stubs/migration.stub');

        $this->replaceClassName($stub)
            ->replaceSchema($stub)
            ->replaceTableName($stub);

        return $stub;
    }

    /**
     * Replace the class name in the stub.
     *
     * @param  string $stub
     * @return $this
     */
    protected function replaceClassName(&$stub)
    {
        $className = ucwords(camel_case('Create'.str_plural($this->scaffoldCommandObj->argument('name')).'Table'));
        $stub = str_replace('{{class}}', $className, $stub);

        return $this;
    }

    /**
     * Replace the table name in the stub.
     *
     * @param  string $stub
     * @return $this
     */
    protected function replaceTableName(&$stub)
    {
        $table = $this->scaffoldCommandObj->getMeta()['table'];
        $stub = str_replace('{{table}}', $table, $stub);

        return $this;
    }

    /**
     * Replace the schema for the stub.
     *
     * @param  string $stub
     * @param string $type
     * @return $this
     */
    protected function replaceSchema(&$stub, $type='migration')
    {
        if ($schema = $this->scaffoldCommandObj->option('schema')) {
            $schema = (new SchemaParser)->parse($schema);
        }

        if($type == 'migration'){
            // Create migration fields
            $schema = (new SyntaxBuilder)->create($schema, $this->scaffoldCommandObj->getMeta());
            $stub = str_replace(['{{schema_up}}', '{{schema_down}}'], $schema, $stub);

        } else if($type='controller'){
            // Create controllers fields
            $schema = (new SyntaxBuilder)->create($schema, $this->scaffoldCommandObj->getMeta(), 'controller');
            $stub = str_replace('{{model_fields}}', $schema, $stub);

        } else {}

        return $this;
    }

}


text:
#include <aws/ssm-sap/model/ApplicationCredential.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace SsmSap
{
namespace Model
{

ApplicationCredential::ApplicationCredential() :
    m_databaseNameHasBeenSet(false),
    m_credentialType(CredentialType::NOT_SET),
    m_credentialTypeHasBeenSet(false),
    m_secretIdHasBeenSet(false)
{
}

ApplicationCredential::ApplicationCredential(JsonView jsonValue) :
    m_databaseNameHasBeenSet(false),
    m_credentialType(CredentialType::NOT_SET),
    m_credentialTypeHasBeenSet(false),
    m_secretIdHasBeenSet(false)
{
  *this = jsonValue;
}

ApplicationCredential& ApplicationCredential::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("DatabaseName"))
  {
    m_databaseName = jsonValue.GetString("DatabaseName");

    m_databaseNameHasBeenSet = true;
  }

  if(jsonValue.ValueExists("CredentialType"))
  {
    m_credentialType = CredentialTypeMapper::GetCredentialTypeForName(jsonValue.GetString("CredentialType"));

    m_credentialTypeHasBeenSet = true;
  }

  if(jsonValue.ValueExists("SecretId"))
  {
    m_secretId = jsonValue.GetString("SecretId");

    m_secretIdHasBeenSet = true;
  }

  return *this;
}

JsonValue ApplicationCredential::Jsonize() const
{
  JsonValue payload;

  if(m_databaseNameHasBeenSet)
  {
   payload.WithString("DatabaseName", m_databaseName);

  }

  if(m_credentialTypeHasBeenSet)
  {
   payload.WithString("CredentialType", CredentialTypeMapper::GetNameForCredentialType(m_credentialType));
  }

  if(m_secretIdHasBeenSet)
  {
   payload.WithString("SecretId", m_secretId);

  }

  return payload;
}

} // namespace Model
} // namespace SsmSap
} // namespace Aws


text:
//
//  CollectViewController.m
//  ViewLuoYang
//
//  Created by scjy on 16/3/19.
//  Copyright © 2016年 秦俊珍. All rights reserved.
//

#import "CollectViewController.h"
//#import "CollectTableViewCell.h"
#import "DataBaseManger.h"
#import "CollectResultViewController.h"
#import <MJRefresh/MJRefresh.h>
@interface CollectViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    NSInteger _pageCount;
}
@property (nonatomic, assign) BOOL isRefresh;
@property (nonatomic, strong) UITableView *tableView;
//@property (nonatomic, strong) UIButton *button;//清除收藏按钮

@end

@implementation CollectViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self showBarButtonWithImage:@"back_arrow"];
    self.title = @"我的收藏";

    DataBaseManger *manager=[DataBaseManger shareInstance];
    [manager openDataBase];

    self.urlArray=[manager selectAllUrl];

    [self.view addSubview:self.tableView];
//    [self.view addSubview:self.button];

    //下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //添加数据
        [self.tableView.mj_header beginRefreshing];
        _pageCount = 1;
        self.isRefresh = YES;
        [self.urlArray removeAllObjects];
        self.urlArray = [manager selectAllUrl];
        [self.tableView.mj_header endRefreshing];
    }];

    [self.view addSubview:self.tableView];

}

#pragma mark ------------ UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return self.urlArray.count;

}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    self.tabBarController.tabBar.hidden = NO;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    self.tabBarController.tabBar.hidden = YES;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *cellIndentifiter = @"cellIndentifiter";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifiter];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIndentifiter];

    }
    Collect *collect = self.urlArray[indexPath.row];
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:collect.image] placeholderImage:nil];
    cell.detailTextLabel.text = collect.url;
    cell.detailTextLabel.textColor = barColor;
    cell.detailTextLabel.font = [UIFont systemFontOfSize:15.0f];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    return cell;
}

#pragma mark ------------- UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    CollectResultViewController *collectResultVC = [[CollectResultViewController alloc] init];
    if (self.urlArray.count > 0) {
        Collect *collect = self.urlArray[indexPath.row];
        collectResultVC.url = collect.url;
    }

    [self.navigationController pushViewController:collectResultVC animated:YES];

}

#pragma mark --------------- lazt Loading
- (UITableView *)tableView{
    if (_tableView == nil) {
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight - 64)];
        self.tableView.separatorColor = [UIColor clearColor];
        self.tableView.rowHeight = 140;
        self.tableView.delegate = self;
        self.tableView.dataSource = self;

    }
    return _tableView;
}

- (NSMutableArray *)urlArray{
    if (_urlArray == nil) {
        self.urlArray = [NSMutableArray new];
    }
    return _urlArray;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
#include <linux/kernel.h>
#include <linux/audit.h>
#include <linux/kthread.h>
#include <linux/mutex.h>
#include <linux/fs.h>
#include <linux/namei.h>
#include <linux/netlink.h>
#include <linux/sched.h>
#include <linux/inotify.h>
#include <linux/security.h>
#include "audit.h"

/*
 * Reference counting:
 *
 * audit_parent: lifetime is from audit_init_parent() to receipt of an IN_IGNORED
 * 	event.  Each audit_watch holds a reference to its associated parent.
 *
 * audit_watch: if added to lists, lifetime is from audit_init_watch() to
 * 	audit_remove_watch().  Additionally, an audit_watch may exist
 * 	temporarily to assist in searching existing filter data.  Each
 * 	audit_krule holds a reference to its associated watch.
 */

struct audit_watch {
	atomic_t		count;	/* reference count */
	dev_t			dev;	/* associated superblock device */
	char			*path;	/* insertion path */
	unsigned long		ino;	/* associated inode number */
	struct audit_parent	*parent; /* associated parent */
	struct list_head	wlist;	/* entry in parent->watches list */
	struct list_head	rules;	/* associated rules */
};

struct audit_parent {
	struct list_head	ilist;	/* entry in inotify registration list */
	struct list_head	watches; /* associated watches */
	struct inotify_watch	wdata;	/* inotify watch data */
	unsigned		flags;	/* status flags */
};

/* Inotify handle. */
struct inotify_handle *audit_ih;

/*
 * audit_parent status flags:
 *
 * AUDIT_PARENT_INVALID - set anytime rules/watches are auto-removed due to
 * a filesystem event to ensure we're adding audit watches to a valid parent.
 * Technically not needed for IN_DELETE_SELF or IN_UNMOUNT events, as we cannot
 * receive them while we have nameidata, but must be used for IN_MOVE_SELF which
 * we can receive while holding nameidata.
 */
#define AUDIT_PARENT_INVALID	0x001

/* Inotify events we care about. */
#define AUDIT_IN_WATCH IN_MOVE|IN_CREATE|IN_DELETE|IN_DELETE_SELF|IN_MOVE_SELF

static void audit_free_parent(struct inotify_watch *i_watch)
{
	struct audit_parent *parent;

	parent = container_of(i_watch, struct audit_parent, wdata);
	WARN_ON(!list_empty(&parent->watches));
	kfree(parent);
}

void audit_get_watch(struct audit_watch *watch)
{
	atomic_inc(&watch->count);
}

void audit_put_watch(struct audit_watch *watch)
{
	if (atomic_dec_and_test(&watch->count)) {
		WARN_ON(watch->parent);
		WARN_ON(!list_empty(&watch->rules));
		kfree(watch->path);
		kfree(watch);
	}
}

void audit_remove_watch(struct audit_watch *watch)
{
	list_del(&watch->wlist);
	put_inotify_watch(&watch->parent->wdata);
	watch->parent = NULL;
	audit_put_watch(watch); /* match initial get */
}

char *audit_watch_path(struct audit_watch *watch)
{
	return watch->path;
}

struct list_head *audit_watch_rules(struct audit_watch *watch)
{
	return &watch->rules;
}

unsigned long audit_watch_inode(struct audit_watch *watch)
{
	return watch->ino;
}

dev_t audit_watch_dev(struct audit_watch *watch)
{
	return watch->dev;
}

/* Initialize a parent watch entry. */
static struct audit_parent *audit_init_parent(struct nameidata *ndp)
{
	struct audit_parent *parent;
	s32 wd;

	parent = kzalloc(sizeof(*parent), GFP_KERNEL);
	if (unlikely(!parent))
		return ERR_PTR(-ENOMEM);

	INIT_LIST_HEAD(&parent->watches);
	parent->flags = 0;

	inotify_init_watch(&parent->wdata);
	/* grab a ref so inotify watch hangs around until we take audit_filter_mutex */
	get_inotify_watch(&parent->wdata);
	wd = inotify_add_watch(audit_ih, &parent->wdata,
			       ndp->path.dentry->d_inode, AUDIT_IN_WATCH);
	if (wd < 0) {
		audit_free_parent(&parent->wdata);
		return ERR_PTR(wd);
	}

	return parent;
}

/* Initialize a watch entry. */
static struct audit_watch *audit_init_watch(char *path)
{
	struct audit_watch *watch;

	watch = kzalloc(sizeof(*watch), GFP_KERNEL);
	if (unlikely(!watch))
		return ERR_PTR(-ENOMEM);

	INIT_LIST_HEAD(&watch->rules);
	atomic_set(&watch->count, 1);
	watch->path = path;
	watch->dev = (dev_t)-1;
	watch->ino = (unsigned long)-1;

	return watch;
}

/* Translate a watch string to kernel respresentation. */
int audit_to_watch(struct audit_krule *krule, char *path, int len, u32 op)
{
	struct audit_watch *watch;

	if (!audit_ih)
		return -EOPNOTSUPP;

	if (path[0] != '/' || path[len-1] == '/' ||
	    krule->listnr != AUDIT_FILTER_EXIT ||
	    op != Audit_equal ||
	    krule->inode_f || krule->watch || krule->tree)
		return -EINVAL;

	watch = audit_init_watch(path);
	if (IS_ERR(watch))
		return PTR_ERR(watch);

	audit_get_watch(watch);
	krule->watch = watch;

	return 0;
}

/* Duplicate the given audit watch.  The new watch's rules list is initialized
 * to an empty list and wlist is undefined. */
static struct audit_watch *audit_dupe_watch(struct audit_watch *old)
{
	char *path;
	struct audit_watch *new;

	path = kstrdup(old->path, GFP_KERNEL);
	if (unlikely(!path))
		return ERR_PTR(-ENOMEM);

	new = audit_init_watch(path);
	if (IS_ERR(new)) {
		kfree(path);
		goto out;
	}

	new->dev = old->dev;
	new->ino = old->ino;
	get_inotify_watch(&old->parent->wdata);
	new->parent = old->parent;

out:
	return new;
}

static void audit_watch_log_rule_change(struct audit_krule *r, struct audit_watch *w, char *op)
{
	if (audit_enabled) {
		struct audit_buffer *ab;
		ab = audit_log_start(NULL, GFP_NOFS, AUDIT_CONFIG_CHANGE);
		audit_log_format(ab, "auid=%u ses=%u op=",
				 audit_get_loginuid(current),
				 audit_get_sessionid(current));
		audit_log_string(ab, op);
		audit_log_format(ab, " path=");
		audit_log_untrustedstring(ab, w->path);
		audit_log_key(ab, r->filterkey);
		audit_log_format(ab, " list=%d res=1", r->listnr);
		audit_log_end(ab);
	}
}

/* Update inode info in audit rules based on filesystem event. */
static void audit_update_watch(struct audit_parent *parent,
			       const char *dname, dev_t dev,
			       unsigned long ino, unsigned invalidating)
{
	struct audit_watch *owatch, *nwatch, *nextw;
	struct audit_krule *r, *nextr;
	struct audit_entry *oentry, *nentry;

	mutex_lock(&audit_filter_mutex);
	list_for_each_entry_safe(owatch, nextw, &parent->watches, wlist) {
		if (audit_compare_dname_path(dname, owatch->path, NULL))
			continue;

		/* If the update involves invalidating rules, do the inode-based
		 * filtering now, so we don't omit records. */
		if (invalidating && current->audit_context)
			audit_filter_inodes(current, current->audit_context);

		nwatch = audit_dupe_watch(owatch);
		if (IS_ERR(nwatch)) {
			mutex_unlock(&audit_filter_mutex);
			audit_panic("error updating watch, skipping");
			return;
		}
		nwatch->dev = dev;
		nwatch->ino = ino;

		list_for_each_entry_safe(r, nextr, &owatch->rules, rlist) {

			oentry = container_of(r, struct audit_entry, rule);
			list_del(&oentry->rule.rlist);
			list_del_rcu(&oentry->list);

			nentry = audit_dupe_rule(&oentry->rule, nwatch);
			if (IS_ERR(nentry)) {
				list_del(&oentry->rule.list);
				audit_panic("error updating watch, removing");
			} else {
				int h = audit_hash_ino((u32)ino);
				list_add(&nentry->rule.rlist, &nwatch->rules);
				list_add_rcu(&nentry->list, &audit_inode_hash[h]);
				list_replace(&oentry->rule.list,
					     &nentry->rule.list);
			}

			audit_watch_log_rule_change(r, owatch, "updated rules");

			call_rcu(&oentry->rcu, audit_free_rule_rcu);
		}

		audit_remove_watch(owatch);
		goto add_watch_to_parent; /* event applies to a single watch */
	}
	mutex_unlock(&audit_filter_mutex);
	return;

add_watch_to_parent:
	list_add(&nwatch->wlist, &parent->watches);
	mutex_unlock(&audit_filter_mutex);
	return;
}

/* Remove all watches & rules associated with a parent that is going away. */
static void audit_remove_parent_watches(struct audit_parent *parent)
{
	struct audit_watch *w, *nextw;
	struct audit_krule *r, *nextr;
	struct audit_entry *e;

	mutex_lock(&audit_filter_mutex);
	parent->flags |= AUDIT_PARENT_INVALID;
	list_for_each_entry_safe(w, nextw, &parent->watches, wlist) {
		list_for_each_entry_safe(r, nextr, &w->rules, rlist) {
			e = container_of(r, struct audit_entry, rule);
			audit_watch_log_rule_change(r, w, "remove rule");
			list_del(&r->rlist);
			list_del(&r->list);
			list_del_rcu(&e->list);
			call_rcu(&e->rcu, audit_free_rule_rcu);
		}
		audit_remove_watch(w);
	}
	mutex_unlock(&audit_filter_mutex);
}

/* Unregister inotify watches for parents on in_list.
 * Generates an IN_IGNORED event. */
void audit_inotify_unregister(struct list_head *in_list)
{
	struct audit_parent *p, *n;

	list_for_each_entry_safe(p, n, in_list, ilist) {
		list_del(&p->ilist);
		inotify_rm_watch(audit_ih, &p->wdata);
		/* the unpin matching the pin in audit_do_del_rule() */
		unpin_inotify_watch(&p->wdata);
	}
}

/* Get path information necessary for adding watches. */
static int audit_get_nd(char *path, struct nameidata **ndp, struct nameidata **ndw)
{
	struct nameidata *ndparent, *ndwatch;
	int err;

	ndparent = kmalloc(sizeof(*ndparent), GFP_KERNEL);
	if (unlikely(!ndparent))
		return -ENOMEM;

	ndwatch = kmalloc(sizeof(*ndwatch), GFP_KERNEL);
	if (unlikely(!ndwatch)) {
		kfree(ndparent);
		return -ENOMEM;
	}

	err = path_lookup(path, LOOKUP_PARENT, ndparent);
	if (err) {
		kfree(ndparent);
		kfree(ndwatch);
		return err;
	}

	err = path_lookup(path, 0, ndwatch);
	if (err) {
		kfree(ndwatch);
		ndwatch = NULL;
	}

	*ndp = ndparent;
	*ndw = ndwatch;

	return 0;
}

/* Release resources used for watch path information. */
static void audit_put_nd(struct nameidata *ndp, struct nameidata *ndw)
{
	if (ndp) {
		path_put(&ndp->path);
		kfree(ndp);
	}
	if (ndw) {
		path_put(&ndw->path);
		kfree(ndw);
	}
}

/* Associate the given rule with an existing parent inotify_watch.
 * Caller must hold audit_filter_mutex. */
static void audit_add_to_parent(struct audit_krule *krule,
				struct audit_parent *parent)
{
	struct audit_watch *w, *watch = krule->watch;
	int watch_found = 0;

	list_for_each_entry(w, &parent->watches, wlist) {
		if (strcmp(watch->path, w->path))
			continue;

		watch_found = 1;

		/* put krule's and initial refs to temporary watch */
		audit_put_watch(watch);
		audit_put_watch(watch);

		audit_get_watch(w);
		krule->watch = watch = w;
		break;
	}

	if (!watch_found) {
		get_inotify_watch(&parent->wdata);
		watch->parent = parent;

		list_add(&watch->wlist, &parent->watches);
	}
	list_add(&krule->rlist, &watch->rules);
}

/* Find a matching watch entry, or add this one.
 * Caller must hold audit_filter_mutex. */
int audit_add_watch(struct audit_krule *krule)
{
	struct audit_watch *watch = krule->watch;
	struct inotify_watch *i_watch;
	struct audit_parent *parent;
	struct nameidata *ndp = NULL, *ndw = NULL;
	int ret = 0;

	mutex_unlock(&audit_filter_mutex);

	/* Avoid calling path_lookup under audit_filter_mutex. */
	ret = audit_get_nd(watch->path, &ndp, &ndw);
	if (ret) {
		/* caller expects mutex locked */
		mutex_lock(&audit_filter_mutex);
		goto error;
	}

	/* update watch filter fields */
	if (ndw) {
		watch->dev = ndw->path.dentry->d_inode->i_sb->s_dev;
		watch->ino = ndw->path.dentry->d_inode->i_ino;
	}

	/* The audit_filter_mutex must not be held during inotify calls because
	 * we hold it during inotify event callback processing.  If an existing
	 * inotify watch is found, inotify_find_watch() grabs a reference before
	 * returning.
	 */
	if (inotify_find_watch(audit_ih, ndp->path.dentry->d_inode,
			       &i_watch) < 0) {
		parent = audit_init_parent(ndp);
		if (IS_ERR(parent)) {
			/* caller expects mutex locked */
			mutex_lock(&audit_filter_mutex);
			ret = PTR_ERR(parent);
			goto error;
		}
	} else
		parent = container_of(i_watch, struct audit_parent, wdata);

	mutex_lock(&audit_filter_mutex);

	/* parent was moved before we took audit_filter_mutex */
	if (parent->flags & AUDIT_PARENT_INVALID)
		ret = -ENOENT;
	else
		audit_add_to_parent(krule, parent);

	/* match get in audit_init_parent or inotify_find_watch */
	put_inotify_watch(&parent->wdata);

error:
	audit_put_nd(ndp, ndw);		/* NULL args OK */
	return ret;

}

void audit_remove_watch_rule(struct audit_krule *krule, struct list_head *list)
{
	struct audit_watch *watch = krule->watch;
	struct audit_parent *parent = watch->parent;

	list_del(&krule->rlist);

	if (list_empty(&watch->rules)) {
		audit_remove_watch(watch);

		if (list_empty(&parent->watches)) {
			/* Put parent on the inotify un-registration
			 * list.  Grab a reference before releasing
			 * audit_filter_mutex, to be released in
			 * audit_inotify_unregister().
			 * If filesystem is going away, just leave
			 * the sucker alone, eviction will take
			 * care of it. */
			if (pin_inotify_watch(&parent->wdata))
				list_add(&parent->ilist, list);
		}
	}
}

/* Update watch data in audit rules based on inotify events. */
static void audit_handle_ievent(struct inotify_watch *i_watch, u32 wd, u32 mask,
			 u32 cookie, const char *dname, struct inode *inode)
{
	struct audit_parent *parent;

	parent = container_of(i_watch, struct audit_parent, wdata);

	if (mask & (IN_CREATE|IN_MOVED_TO) && inode)
		audit_update_watch(parent, dname, inode->i_sb->s_dev,
				   inode->i_ino, 0);
	else if (mask & (IN_DELETE|IN_MOVED_FROM))
		audit_update_watch(parent, dname, (dev_t)-1, (unsigned long)-1, 1);
	/* inotify automatically removes the watch and sends IN_IGNORED */
	else if (mask & (IN_DELETE_SELF|IN_UNMOUNT))
		audit_remove_parent_watches(parent);
	/* inotify does not remove the watch, so remove it manually */
	else if(mask & IN_MOVE_SELF) {
		audit_remove_parent_watches(parent);
		inotify_remove_watch_locked(audit_ih, i_watch);
	} else if (mask & IN_IGNORED)
		put_inotify_watch(i_watch);
}

static const struct inotify_operations audit_inotify_ops = {
	.handle_event   = audit_handle_ievent,
	.destroy_watch  = audit_free_parent,
};

static int __init audit_watch_init(void)
{
	audit_ih = inotify_init(&audit_inotify_ops);
	if (IS_ERR(audit_ih))
		audit_panic("cannot initialize inotify handle");
	return 0;
}
subsys_initcall(audit_watch_init);


text:
require "log"
require "ril"
module(..., package.seeall)

local ID, FILE = 1, '/RecDir/rec001'
local recording
local stoping
local duration
local recordCallback

--- record.getdata 读取录音数据
-- @param offset 偏移位置
-- @param len 长度
-- @return data 录音数据
-- @usage data = record.getdata(0, 1024)
function getdata(offset, len)
    local f = io.open(FILE, "rb")
    if not f then log.error('record.getdata', 'open failed') return "" end
    if not f:seek("set", offset) then log.error('record.getdata', 'seek failed') f:close() return "" end
    local data = f:read(len)
    f:close()
    log.info("record.getdata", data and data:len() or 0)
    return data or ""
end

--- record.getsize 读取录音文件总长度,录音时长
-- @return filesize 录音文件大小
-- @return duration 录音时长
-- @usage filesize, duration = record.getsize()
function getsize()
    return io.filesize(FILE), duration and (duration-1)/1000+1 or 0
end

--- record.delete 删除录音
-- @usage record.delete()
function delete()
    os.remove(FILE)
end

--- record.exists 判断是否存在录音
-- @return result true - 有录音 false - 无录音
-- @usage result = record.exists()
function exists()
    return io.exists(FILE)
end

--- record.isBusy 是否正在处理录音
-- @return result true - 正在处理 false - 空闲
-- @usage result = record.isBusy()
function isBusy()
    return recording or stoping
end

--- record.start 开始录音
-- @param seconds 录音时长,单位:秒
-- @param cb 录音结果回调
-- @return result true - 开始录音 其他 - 失败
-- @usage result = record.start()
function start(seconds, cb)
    if recording or stoping or seconds <= 0 or seconds > 50 then
        log.error('record.start', recording, stoping, seconds)
        return
    end
    delete()
    duration = seconds * 1000
    ril.request("AT+AUDREC=0,0,1," .. ID .. "," .. duration)
    recording = true
    recordCallback = cb
    return true
end

--- record.stop 停止录音
-- @usage record.stop()
function stop()
    if not recording or stoping then return end
    ril.request("AT+AUDREC=0,0,0," .. ID .. "," .. duration)
    stoping = true
end

ril.regurc("+AUDREC", function(data)
    local action, size = data:match("(%d),(%d+)")
    if action and size then
        size = tonumber(size)
        if action == "1" then
            local result = size > 0 and recording
            if not result then os.remove(FILE) size = 0 end
            duration = size
            if recordCallback then recordCallback(result, size) recordCallback = nil end
            recording = false
            stoping = false
        end
    end
end)
ril.regrsp("+AUDREC", function(cmd, success)
    local action = cmd:match("AUDREC=%d,%d,(%d)")
    if action == "1" then
        if not success then
            if recordCallback then
                recordCallback(false, 0)
                recordCallback = nil
            end
            recording = false
        end
    elseif action == '0' then
        if stoping and not success then stoping = false end -- 失败直接结束,成功则等到+AUDREC上报才判定停止录音成功
    end
end)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FindFreeRoom.ExchangeConnector;
using FindFreeRoom.ExchangeConnector.Base;
using NUnit.Framework;

namespace ExchangeConnector.Tests
{
	[TestFixture]
	public class SmartSearchTests
	{
		private readonly Location _center = new Location { Geometry = new Geometry(0, 0, 0) };
		private TimeInterval _availableNow;
		private TimeInterval _availableVerySoon;
		private TimeInterval _availableLater;
		private TimeInterval _availableForShortPeriod;

		[SetUp]
		public void SetUp()
		{
			_availableNow = new TimeInterval(DateTime.Now, DateTime.Now.AddHours(1));
			_availableVerySoon = new TimeInterval(DateTime.Now.AddMinutes(3), DateTime.Now.AddHours(1));
			_availableLater = new TimeInterval(DateTime.Now.AddHours(2), DateTime.Now.AddHours(4));
			_availableForShortPeriod = new TimeInterval(DateTime.Now, DateTime.Now.AddMinutes(13));
		}

		[Test]
		public void DistanceComparerTest()
		{
			var room1 = new RoomAvailabilityInfo(_availableNow, new RoomInfo
			{
				Location = new Location
				{
					Geometry = new Geometry(1, 1, 0)
				}
			});
			var room2 = new RoomAvailabilityInfo(_availableNow, new RoomInfo
			{
				Location = new Location
				{
					Geometry = new Geometry(2, 2, 0)
				}
			});
			var comparer = new SmartRoomComparer(_center);
			Assert.That(comparer.Compare(room1, room2), Is.LessThan(0));
			Assert.That(comparer.Compare(room2, room1), Is.GreaterThan(0));

			Assert.That(new SmartSearch(_center).Sort(new[] { room1, room2 }), Is.EqualTo(new[] { room1, room2 }));
		}

		[Test]
		public void NegligibleTimeComparerTest()
		{
			var room1 = new RoomAvailabilityInfo(_availableVerySoon, new RoomInfo
			{
				Location = new Location
				{
					Geometry = new Geometry(1, 1, 0)
				}
			});
			var room2 = new RoomAvailabilityInfo(_availableNow, new RoomInfo
			{
				Location = new Location
				{
					Geometry = new Geometry(2, 2, 0)
				}
			});
			var comparer = new SmartRoomComparer(_center);
			Assert.That(comparer.Compare(room1, room2), Is.LessThan(0));
			Assert.That(comparer.Compare(room2, room1), Is.GreaterThan(0));

			Assert.That(new SmartSearch(_center).Sort(new[] { room1, room2 }), Is.EqualTo(new[] { room1, room2 }));
		}

		[Test]
		public void NonNegligibleTimeComparerTest()
		{
			var room1 = new RoomAvailabilityInfo(_availableLater, new RoomInfo
			{
				Location = new Location
				{
					Geometry = new Geometry(1, 1, 0)
				}
			});
			var room2 = new RoomAvailabilityInfo(_availableNow, new RoomInfo
			{
				Location = new Location
				{
					Geometry = new Geometry(2, 2, 0)
				}
			});
			var comparer = new SmartRoomComparer(_center);
			Assert.That(comparer.Compare(room1, room2), Is.GreaterThan(0));
			Assert.That(comparer.Compare(room2, room1), Is.LessThan(0));

			Assert.That(new SmartSearch(_center).Sort(new[] { room1, room2 }), Is.EqualTo(new[] { room2, room1 }));
		}

		[Test]
		public void SmallWindowComparerTest()
		{
			var room1 = new RoomAvailabilityInfo(_availableForShortPeriod, new RoomInfo
			{
				Location = new Location
				{
					Geometry = new Geometry(1, 1, 0)
				}
			});
			var room2 = new RoomAvailabilityInfo(_availableNow, new RoomInfo
			{
				Location = new Location
				{
					Geometry = new Geometry(2, 2, 0)
				}
			});
			var comparer = new SmartRoomComparer(_center);
			Assert.That(comparer.Compare(room1, room2), Is.GreaterThan(0));
			Assert.That(comparer.Compare(room2, room1), Is.LessThan(0));

			Assert.That(new SmartSearch(_center).Sort(new[] { room1, room2 }), Is.EqualTo(new[] { room2, room1 }));
		}
	}
}


text:
import type { CSSProperties, FC } from 'react'
import { useDrop } from 'react-dnd'

import { ItemTypes } from './ItemTypes'

const style: CSSProperties = {
  border: '1px solid gray',
  height: '15rem',
  width: '15rem',
  padding: '2rem',
  textAlign: 'center',
}

export const TargetBox: FC = () => {
  const [{ isActive }, drop] = useDrop(() => ({
    accept: ItemTypes.BOX,
    collect: (monitor) => ({
      isActive: monitor.canDrop() && monitor.isOver(),
    }),
  }))
  return (
    <div ref={drop} style={style}>
      {isActive ? 'Release to drop' : 'Drag item here'}
    </div>
  )
}


text:
package com.moemao.tgks.cgms.download.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.moemao.tgks.cgms.cardorder.entity.CardOrderEvt;
import com.moemao.tgks.cgms.cardorder.service.CardOrderService;
import com.moemao.tgks.cgms.kssma.entity.KssmaEvt;
import com.moemao.tgks.cgms.kssma.service.KssmaService;
import com.moemao.tgks.cgms.lovelive.entity.LoveLiveEvt;
import com.moemao.tgks.cgms.lovelive.service.LoveLiveService;
import com.moemao.tgks.cgms.tool.CgmsConstant;
import com.moemao.tgks.common.core.action.TGKSAction;
import com.moemao.tgks.common.tool.CommonUtil;

public class DownloadAction extends TGKSAction
{

    /**
     * @Fields serialVersionUID
     */
    private static final long serialVersionUID = 8166293537310971647L;

    private CardOrderService cgms_cardOrderService;

    private KssmaService cgms_kssmaService;

    private LoveLiveService cgms_loveLiveService;

    private static final String basePath = "/upload/cgms";

    private String cardIds;

    private String cardType;

    /**
     * @throws IOException
     *
     * @Title: downloadCardZip
     * @Description: CGMS下载cardOrder选中的卡图包
     * @return
     * @return String 返回类型
     * @throws
     */
    public String downloadCardZip() throws IOException
    {
        String cardOrderId = this.getRequest().getParameter("id");

        CardOrderEvt cardOrder = cgms_cardOrderService.queryCardOrderById(cardOrderId);

        if (CommonUtil.isEmpty(cardOrder))
        {
            return ERROR;
        }

        List<File> fileList = new ArrayList<File>();

        if (CgmsConstant.CARDORDER_TYPE_1.equals(cardOrder.getType()))
        {
            List<LoveLiveEvt> list = cgms_loveLiveService.queryLoveLiveByCardId(CommonUtil.stringToList(cardOrder.getCardId()));

            for (LoveLiveEvt ll : list)
            {
                File file = new File(ServletActionContext.getServletContext().getRealPath(basePath) + ll.getImageUrl().split(".." + basePath)[1]);

                if (file.exists())
                {
                    fileList.add(file);
                }
            }
        }
        else if (CgmsConstant.CARDORDER_TYPE_2.equals(cardOrder.getType()))
        {
            List<KssmaEvt> list = cgms_kssmaService.queryKssmaByCardId(CommonUtil.stringToList(cardOrder.getCardId()));

            for (KssmaEvt ma : list)
            {
                File file = new File(ServletActionContext.getServletContext().getRealPath(basePath) + ma.getImageUrl().split(".." + basePath)[1]);

                if (file.exists())
                {
                    fileList.add(file);
                }
            }
        }

        if (CommonUtil.isEmpty(fileList))
        {
            return ERROR;
        }

        HttpServletResponse response = ServletActionContext.getResponse();

        OutputStream os = response.getOutputStream();

        //清空输出流
        response.reset();

        //设定输出文件头
        response.setHeader("Content-disposition ","attachment; filename=" + cardOrderId + ".zip");
        response.setContentType("application/zip");

        ZipOutputStream zos = new ZipOutputStream(os);

        // 文件进行打包处理
        zipFiles(fileList, "", zos);

        zos.close();
        os.close();

        return SUCCESS;
    }

    /**
     * @throws IOException
     *
     * @Title: downloadCardZipByIds
     * @Description: 通过cardOrder的ids来下载图片包
     * @return
     * @return String 返回类型
     * @throws
     */
    public String downloadCardZipByIds() throws IOException
    {
        if (CommonUtil.isEmpty(cardIds))
        {
            return ERROR;
        }

        List<File> fileList = new ArrayList<File>();

        if (CgmsConstant.CARDORDER_TYPE_1.equals(cardType))
        {
            List<LoveLiveEvt> list = cgms_loveLiveService.queryLoveLiveByCardId(CommonUtil.stringToList(cardIds));

            for (LoveLiveEvt ll : list)
            {
                File file = new File(ServletActionContext.getServletContext().getRealPath(basePath) + ll.getImageUrl().split(".." + basePath)[1]);

                if (file.exists())
                {
                    fileList.add(file);
                }
            }
        }
        else if (CgmsConstant.CARDORDER_TYPE_2.equals(cardType))
        {
            List<KssmaEvt> list = cgms_kssmaService.queryKssmaByCardId(CommonUtil.stringToList(cardIds));

            for (KssmaEvt ma : list)
            {
                File file = new File(ServletActionContext.getServletContext().getRealPath(basePath) + ma.getImageUrl().split(".." + basePath)[1]);

                if (file.exists())
                {
                    fileList.add(file);
                }
            }
        }

        if (CommonUtil.isEmpty(fileList))
        {
            return ERROR;
        }

        HttpServletResponse response = ServletActionContext.getResponse();

        OutputStream os = response.getOutputStream();

        //清空输出流
        response.reset();

        //设定输出文件头
        response.setHeader("Content-disposition ","attachment; filename=card.zip");
        response.setContentType("application/zip");

        ZipOutputStream zos = new ZipOutputStream(os);

        // 文件进行打包处理
        zipFiles(fileList, "", zos);

        zos.close();
        os.close();

        return SUCCESS;
    }

    /**
     *
     * @Title: zipFiles
     * @Description: 将文件打包成一个zip
     * @param fileList
     * @param baseName
     * @param zos
     * @throws IOException
     * @return void 返回类型
     * @throws
     */
    private void zipFiles(List<File> fileList, String baseName, ZipOutputStream zos) throws IOException, FileNotFoundException
    {
        for (File file : fileList)
        {
            zos.putNextEntry(new ZipEntry(baseName + file.getName()));
            FileInputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int r = 0;
            while (-1 != (r = fis.read(buffer)))
            {
                zos.write(buffer, 0, r);
            }
            fis.close();
        }
    }

    public CardOrderService getCgms_cardOrderService()
    {
        return cgms_cardOrderService;
    }

    public void setCgms_cardOrderService(CardOrderService cgms_cardOrderService)
    {
        this.cgms_cardOrderService = cgms_cardOrderService;
    }

    public KssmaService getCgms_kssmaService()
    {
        return cgms_kssmaService;
    }

    public void setCgms_kssmaService(KssmaService cgms_kssmaService)
    {
        this.cgms_kssmaService = cgms_kssmaService;
    }

    public LoveLiveService getCgms_loveLiveService()
    {
        return cgms_loveLiveService;
    }

    public void setCgms_loveLiveService(LoveLiveService cgms_loveLiveService)
    {
        this.cgms_loveLiveService = cgms_loveLiveService;
    }

    public String getCardIds()
    {
        return cardIds;
    }

    public void setCardIds(String cardIds)
    {
        this.cardIds = cardIds;
    }

    public String getCardType()
    {
        return cardType;
    }

    public void setCardType(String cardType)
    {
        this.cardType = cardType;
    }
}


text:
extern crate flatbuffers;
use std::mem;
use std::cmp::Ordering;
use self::flatbuffers::{EndianScalar, Follow};
use super::*;
pub enum OpenTypeNameRecordOffset {}
#[derive(Copy, Clone, PartialEq)]

pub struct OpenTypeNameRecord<'a> {
  pub _tab: flatbuffers::Table<'a>,
}

impl<'a> flatbuffers::Follow<'a> for OpenTypeNameRecord<'a> {
  type Inner = OpenTypeNameRecord<'a>;
  #[inline]
  fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
    Self { _tab: flatbuffers::Table { buf, loc } }
  }
}

impl<'a> OpenTypeNameRecord<'a> {
  pub const VT_NAMEID: flatbuffers::VOffsetT = 4;
  pub const VT_PLATFORMID: flatbuffers::VOffsetT = 6;
  pub const VT_ENCODINGID: flatbuffers::VOffsetT = 8;
  pub const VT_LANGUAGEID: flatbuffers::VOffsetT = 10;
  pub const VT_STRING: flatbuffers::VOffsetT = 12;

  #[inline]
  pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
    OpenTypeNameRecord { _tab: table }
  }
  #[allow(unused_mut)]
  pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
    _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
    args: &'args OpenTypeNameRecordArgs<'args>
  ) -> flatbuffers::WIPOffset<OpenTypeNameRecord<'bldr>> {
    let mut builder = OpenTypeNameRecordBuilder::new(_fbb);
    if let Some(x) = args.string { builder.add_string(x); }
    builder.add_languageID(args.languageID);
    builder.add_encodingID(args.encodingID);
    builder.add_platformID(args.platformID);
    builder.add_nameID(args.nameID);
    builder.finish()
  }

  #[inline]
  pub fn nameID(&self) -> u16 {
    self._tab.get::<u16>(OpenTypeNameRecord::VT_NAMEID, Some(0)).unwrap()
  }
  #[inline]
  pub fn platformID(&self) -> u16 {
    self._tab.get::<u16>(OpenTypeNameRecord::VT_PLATFORMID, Some(0)).unwrap()
  }
  #[inline]
  pub fn encodingID(&self) -> u16 {
    self._tab.get::<u16>(OpenTypeNameRecord::VT_ENCODINGID, Some(0)).unwrap()
  }
  #[inline]
  pub fn languageID(&self) -> u16 {
    self._tab.get::<u16>(OpenTypeNameRecord::VT_LANGUAGEID, Some(0)).unwrap()
  }
  #[inline]
  pub fn string(&self) -> Option<&'a str> {
    self._tab.get::<flatbuffers::ForwardsUOffset<&str>>(OpenTypeNameRecord::VT_STRING, None)
  }
}

impl flatbuffers::Verifiable for OpenTypeNameRecord<'_> {
  #[inline]
  fn run_verifier(
    v: &mut flatbuffers::Verifier, pos: usize
  ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
    use self::flatbuffers::Verifiable;
    v.visit_table(pos)?
     .visit_field::<u16>("nameID", Self::VT_NAMEID, false)?
     .visit_field::<u16>("platformID", Self::VT_PLATFORMID, false)?
     .visit_field::<u16>("encodingID", Self::VT_ENCODINGID, false)?
     .visit_field::<u16>("languageID", Self::VT_LANGUAGEID, false)?
     .visit_field::<flatbuffers::ForwardsUOffset<&str>>("string", Self::VT_STRING, false)?
     .finish();
    Ok(())
  }
}
pub struct OpenTypeNameRecordArgs<'a> {
    pub nameID: u16,
    pub platformID: u16,
    pub encodingID: u16,
    pub languageID: u16,
    pub string: Option<flatbuffers::WIPOffset<&'a str>>,
}
impl<'a> Default for OpenTypeNameRecordArgs<'a> {
  #[inline]
  fn default() -> Self {
    OpenTypeNameRecordArgs {
      nameID: 0,
      platformID: 0,
      encodingID: 0,
      languageID: 0,
      string: None,
    }
  }
}
pub struct OpenTypeNameRecordBuilder<'a: 'b, 'b> {
  fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
  start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> OpenTypeNameRecordBuilder<'a, 'b> {
  #[inline]
  pub fn add_nameID(&mut self, nameID: u16) {
    self.fbb_.push_slot::<u16>(OpenTypeNameRecord::VT_NAMEID, nameID, 0);
  }
  #[inline]
  pub fn add_platformID(&mut self, platformID: u16) {
    self.fbb_.push_slot::<u16>(OpenTypeNameRecord::VT_PLATFORMID, platformID, 0);
  }
  #[inline]
  pub fn add_encodingID(&mut self, encodingID: u16) {
    self.fbb_.push_slot::<u16>(OpenTypeNameRecord::VT_ENCODINGID, encodingID, 0);
  }
  #[inline]
  pub fn add_languageID(&mut self, languageID: u16) {
    self.fbb_.push_slot::<u16>(OpenTypeNameRecord::VT_LANGUAGEID, languageID, 0);
  }
  #[inline]
  pub fn add_string(&mut self, string: flatbuffers::WIPOffset<&'b  str>) {
    self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(OpenTypeNameRecord::VT_STRING, string);
  }
  #[inline]
  pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> OpenTypeNameRecordBuilder<'a, 'b> {
    let start = _fbb.start_table();
    OpenTypeNameRecordBuilder {
      fbb_: _fbb,
      start_: start,
    }
  }
  #[inline]
  pub fn finish(self) -> flatbuffers::WIPOffset<OpenTypeNameRecord<'a>> {
    let o = self.fbb_.end_table(self.start_);
    flatbuffers::WIPOffset::new(o.value())
  }
}

impl std::fmt::Debug for OpenTypeNameRecord<'_> {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    let mut ds = f.debug_struct("OpenTypeNameRecord");
      ds.field("nameID", &self.nameID());
      ds.field("platformID", &self.platformID());
      ds.field("encodingID", &self.encodingID());
      ds.field("languageID", &self.languageID());
      ds.field("string", &self.string());
      ds.finish()
  }
}


text:
@component('mail::message')
# {{ $title }}

@foreach ($packages as $package => $report)
## {{ $package }} — {{ $report['version'] }}

@component('mail::table')
| @lang('laravel-security-checker::messages.title') | @lang('laravel-security-checker::messages.cve') | @lang('laravel-security-checker::messages.information') |
| :---- | :-- | :---------- |
@foreach($report['advisories'] as $key => $information)
| {{ $information['title'] }} | {{ $information['cve'] or '' }} | [@lang('laravel-security-checker::messages.view')]({{ $information['link'] }})
@endforeach
@endcomponent
@endforeach

@if (count($packages) === 0)
{{ __('laravel-security-checker::messages.body_no_vulnerabilities') }}
@endif

@endcomponent


text:
import { Directive, EventEmitter, Input, Output } from '@angular/core';
import { Country } from './country';

export type SortColumn = keyof Country | '';
export type SortDirection = 'asc' | 'desc' | '';
const rotate: { [key: string]: SortDirection } = { asc: 'desc', desc: '', '': 'asc' };

export interface SortEvent {
	column: SortColumn;
	direction: SortDirection;
}

@Directive({
	selector: 'th[sortable]',
	standalone: true,
	host: {
		'[class.asc]': 'direction === "asc"',
		'[class.desc]': 'direction === "desc"',
		'(click)': 'rotate()',
	},
})
export class NgbdSortableHeader {
	@Input() sortable: SortColumn = '';
	@Input() direction: SortDirection = '';
	@Output() sort = new EventEmitter<SortEvent>();

	rotate() {
		this.direction = rotate[this.direction];
		this.sort.emit({ column: this.sortable, direction: this.direction });
	}
}


text: google-site-verification: google224b592a6676987f.html


text:
function recommendationSort(team1, team2) {
    if (team1.placesLeft !== 0 && team2.placesLeft === 0) {
        return -1;
    }

    if (team1.placesLeft === 0 && team2.placesLeft !== 0) {
        return 1;
    }

    if (team1.missingSkillsMatch.number > team2.missingSkillsMatch.number) {
        return -1;
    }

    if (team1.missingSkillsMatch.number < team2.missingSkillsMatch.number) {
        return 1;
    }

    if (team1.skillsMatch.number > team2.skillsMatch.number) {
        return -1;
    }

    if (team1.skillsMatch.number < team2.skillsMatch.number) {
        return 1;
    }

    if (team1.placesLeft > team2.placesLeft) {
        return -1;
    }

    if (team1.placesLeft < team2.placesLeft) {
        return 1;
    }

    return 0;
}

angular.module("teamform-user-app", ["firebase", "ngMaterial", "ngMessages"])
.controller("UserCtrl", function($scope, $firebaseObject, $firebaseArray) {
    initializeFirebase();

    $scope.user = null;

    var userRef = null;
    $scope.userObj = null;

    var skillsRef = null;
    $scope.skills = null;

    var eventTeamRef = null;
    $scope.eventTeamObj = null;

    // observe the auth state change
    firebase.auth().onAuthStateChanged(function(user) {
        if (user) {
            // User is signed in.
            console.log(user);

            // refresh the scope
            $scope.$apply(function() {
                $scope.user = user;

                // get the user object from the database
                userRef = firebase.database().ref().child("users").child(user.uid);
                $scope.userObj = $firebaseObject(userRef);

                skillsRef = userRef.child("skills");
                $scope.skills = $firebaseArray(skillsRef);

                $scope.userObj.$loaded().then(function() {
                    // get the events object from the database after the user object is loaded
                    eventTeamRef = firebase.database().ref().child("events");
                    $scope.eventTeamObj = $firebaseObject(eventTeamRef);
                    $scope.eventTeamObj.$loaded().then(function() {
                        console.log($scope.eventTeamObj);
                        $scope.recommend();
                    });
                });

                // change the title in the navigation to the name of the signed in user
                $(".mdl-layout>.mdl-layout__header>.mdl-layout__header-row>.mdl-layout__title").html($scope.user.displayName);
            });
        } else {
            // No user is signed in.
            console.log('no user is signed in');

            // refresh the scope
            $scope.$apply(function() {
                $scope.user = null;

                userRef = null;
                $scope.userObj = null;

                skillsRef = null;
                $scope.skills = null;

                eventTeamRef = null;
                $scope.eventTeamObj = null;

                // change the title in the navigation to "User"
                $(".mdl-layout>.mdl-layout__header>.mdl-layout__header-row>.mdl-layout__title").html("User");
            });
        }
    });

    $scope.skillInput = null;

    // add skill function
    $scope.addSkill = function() {
        // return if no user is signed in
        if (!$scope.user) {
            return;
        }

        // return if the skill input is invalid
        if (!$scope.skillInput) {
            return;
        }

        var skillsArray = $firebaseArray(skillsRef);
        skillsArray.$loaded().then(function(skills) {
            var skill = {};
            skill[skills.length.toString()] = $scope.skillInput;

            // add the skill to the user's profile
            skillsRef.update(skill);

            // add the skill to the member object of all the events that the user joined
            for (var i in $scope.userObj.events) {
                var eventRef = firebase.database().ref().child("events").child(i).child("member").child($scope.user.uid).child("skills");
                eventRef.update(skill);
            }

            $scope.skillInput = null;
            $("#skillInput").blur();
        });
    };

    /* recommendations */
    $scope.recommendations = [];

    // filter the events to events that the user joined
    $scope.filterEvents = function(eventTeamObj, userObj) {
        var eventTeam = {};

        angular.forEach(eventTeamObj, function(eventValue, eventKey) {
            var c = eventKey.charAt(0);
            if (c !== "_" && c !== "$" && c !== ".") {
                if (userObj.events[eventKey] !== undefined) {
                    eventTeam[eventKey] = eventValue;
                }
            }
        });

        return eventTeam;
    };

    // construct the recommendations array object
    $scope.constructRecommendations = function(eventTeamObj, userObj) {
        var recommendations = [];

        angular.forEach(eventTeamObj, function(eventValue, eventKey) {
            var recommendation = {
                eventName: eventKey,
                teams: []
            };

            angular.forEach(eventValue.team, function(teamValue, teamKey) {
                recommendation.teams.push({
                    teamName: teamKey,
                    placesLeft: teamValue.size - teamValue.currentTeamSize,
                    skillsMatch: isMatched(teamValue.skills, userObj.skills),
                    missingSkillsMatch: missingSkillsMatched(teamValue.skills, teamValue.teamSkills, userObj.skills),
                    skills: teamValue.skills,
                    teamSkills: teamValue.teamSkills
                });
            });

            recommendations.push(recommendation);
        });

        return recommendations;
    };

    /*
     * Provide recommendations
     *
     * 1. separate the teams into 2 sets (teams with places left, teams without places left)
     * 2. sort each set by the number of missing skills match
     * 3. sort each set by the number of skills match
     * 4. sort each set by the number of places left
     *
     * @param recommendations recommendations object
     */
    $scope.provideRecommendations = function(recommendations) {
        angular.forEach(recommendations, function(recommendation, index, recommendationsArray) {
            recommendationsArray[index].teams = recommendation.teams.sort(recommendationSort);
        });
    };

    // limit the number of recommendations for each event
    $scope.limitRecommendations = function(recommendations, limit) {
        angular.forEach(recommendations, function(recommendation, index, recommendationsArray) {
            if (recommendation.teams.length > limit) {
                recommendationsArray[index].teams = recommendation.teams.slice(0, limit);
            }
        });
    };

    $scope.recommend = function() {
        $scope.recommendations = [];

        var eventsFiltered = $scope.filterEvents($scope.eventTeamObj, $scope.userObj);

        $scope.recommendations = $scope.constructRecommendations(eventsFiltered, $scope.userObj);

        $scope.provideRecommendations($scope.recommendations);

        $scope.limitRecommendations($scope.recommendations, 5);
        console.log($scope.recommendations);
    };

    // request team function
    $scope.requestTeam = function(eventName, teamName) {
        var eventMemberTeamRef = firebase.database().ref().child("events").child(eventName).child("member").child($scope.user.uid).child("selection");
        var userEventRef = firebase.database().ref().child("users").child($scope.user.uid).child("events").child(eventName).child("selection");
        var eventMemberTeamArray = $firebaseArray(eventMemberTeamRef);

        eventMemberTeamArray.$loaded().then(function(selections) {
            var requests = [];

            // add the selections stored in the database
            selections.forEach(function(selection) {
                requests.push(selection.$value);
            });

            // add the request team if it was not in the database
            if (!requests.includes(teamName)) {
                requests.push(teamName);
            }

            // update the record in the event
            eventMemberTeamRef.set(requests);
            // update the record in the user's profile
            userEventRef.set(requests);

            // refresh the recommendations
            $scope.recommend();
        });
    };
})
.config(function($mdThemingProvider) {
    $mdThemingProvider.theme('default')
    .primaryPalette('orange')
    .accentPalette('indigo');
});
var member_ready = function(){

	$('#member_page_controller').hide();
	$('#text_event_name').text("Error: Invalid event name ");
	var eventName = getURLParameter("q");
	if (eventName != null && eventName != '' ) {
		$('#text_event_name').text("Event name: " + eventName);
		$('#member_page_controller').show();
	}

}

$(document).ready(member_ready);

angular.module('teamform-member-app', ['firebase'])
.controller('MemberCtrl', ['$scope', '$firebaseObject', '$firebaseArray', function($scope, $firebaseObject, $firebaseArray) {

	// TODO: implementation of MemberCtrl

	// Call Firebase initialization code defined in site.js
	initalizeFirebase();

	$scope.userID = "";
	$scope.userName = "";
	$scope.teams = {};

	$scope.loadFunc = function() {
		var userID = $scope.userID;
		if ( userID !== '' ) {

			var refPath = getURLParameter("q") + "/member/" + userID;
			retrieveOnceFirebase(firebase, refPath, function(data) {

				if ( data.child("name").val() != null )
				{
					$scope.userName = data.child("name").val();
				}
				else
				{
					$scope.userName = "";
				}

				if (data.child("selection").val() != null )
				{
					$scope.selection = data.child("selection").val();
				}
				else
				{
					$scope.selection = [];
				}
				$scope.$apply();
			});
		}
	}

	$scope.saveFunc = function() {

		var userID = $.trim( $scope.userID );
		var userName = $.trim( $scope.userName );

		if ( userID !== '' && userName !== '' ) {

			var newData = {
				'name': userName,
				'selection': $scope.selection
			};

			var refPath = getURLParameter("q") + "/member/" + userID;
			var ref = firebase.database().ref(refPath);

			ref.set(newData, function(){
				// complete call back
				//alert("data pushed...");

				// Finally, go back to the front-end
				window.location.href= "index.html";
			});
		}
	}

	$scope.refreshTeams = function() {
		var refPath = getURLParameter("q") + "/team";
		var ref = firebase.database().ref(refPath);

		// Link and sync a firebase object
		$scope.selection = [];
		$scope.toggleSelection = function (item) {
			var idx = $scope.selection.indexOf(item);
			if (idx > -1) {
				$scope.selection.splice(idx, 1);
			}
			else {
				$scope.selection.push(item);
			}
		}

		$scope.teams = $firebaseArray(ref);
		$scope.teams.$loaded()
			.then( function(data) {

			})
			.catch(function(error) {
				// Database connection error handling...
				//console.error("Error:", error);
			});

	}

	$scope.refreshTeams(); // call to refresh teams...

}]);


text:
package com.yahoo.gondola.cli;

import com.yahoo.gondola.*;
import com.yahoo.gondola.core.CoreMember;
import com.yahoo.gondola.impl.NastyNetwork;
import com.yahoo.gondola.impl.NastyStorage;

import org.apache.log4j.PropertyConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

/**
 * The type Gondola command. TODO: will eventually be command line tool for users to quickly bring up a gondola shard in
 * their environment and do some quick performance tests. They would 1. create a config file and 2. start this command
 * on the different hosts. Right now this is just a quick and dirty test command to test the prototype.
 */
public class GondolaCommand {

    final static Logger logger = LoggerFactory.getLogger(GondolaCommand.class);

    Shard shard;
    Config config;
    Gondola gondola;

    AtomicLong waitTime = new AtomicLong();
    AtomicLong requests = new AtomicLong();

    // Parameters
    boolean serverMode = false;
    int port = 1099;
    String hostId;
    String shardId;
    int delay = 1000;
    File configFile = new File("conf/gondola-sample.conf");

    int maxWorkers = 1024;
    int numWorkers = 0;
    BlockingQueue<Socket> socketQueue = new ArrayBlockingQueue<>(maxWorkers);
    AtomicInteger availableWorkers = new AtomicInteger();

    // Config variables
    int maxCommandSize;
    boolean tracing;

    CoreMember.Latency latency = new CoreMember.Latency();

    public static void main(String[] args) throws Exception {
        PropertyConfigurator.configure("conf/log4j.properties");
        new GondolaCommand(args);
    }

    public void printUsage() {
        // Stop is implemented in the shell script
        System.out.println(
            "Usage: gondola.sh -hostid <host-id> -shardid <shard-id> [-port <port>] [-workers <num>] [start|stop]");
        if (config != null) {
            System.out.println("    Available host ids: " + config.getHostIds());
        }
        System.exit(1);
    }

    public GondolaCommand(String[] args) throws Exception {
        if (args.length == 0) {
            printUsage();
        }

        for (int i = 0; i < args.length; i++) {
            if (args[i].equals("start")) {
                serverMode = true;
            }
            if (args[i].equals("-port")) {
                if (args.length == i - 1) {
                    printUsage();
                }
                port = Integer.parseInt(args[++i]);
            }
            if (args[i].equals("-hostid")) {
                if (args.length == i - 1) {
                    printUsage();
                }
                hostId = args[++i];
            }
            if (args[i].equals("-shardid")) {
                if (args.length == i - 1) {
                    printUsage();
                }
                shardId = args[++i];
            }
            if (args[i].equals("-workers")) {
                if (args.length == i - 1) {
                    printUsage();
                }
                numWorkers = Integer.parseInt(args[++i]);
            }
            if (args[i].equals("-delay")) {
                if (args.length == i - 1) {
                    printUsage();
                }
                delay = Integer.parseInt(args[++i]);
            }
            if (args[i].equals("-config")) {
                if (args.length == i - 1) {
                    printUsage();
                }
                configFile = new File(args[++i]);
            }
        }
        config = new Config(configFile);
        if (hostId == null || shardId == null) {
            printUsage();
        }

        maxCommandSize = config.getInt("raft.command_max_size");
        tracing = config.getBoolean("tracing.cli.command");

        // Initialize the gondola system
        try {
            gondola = new Gondola(config, hostId);
            gondola.start();
            shard = gondola.getShard(shardId);
        } catch (Exception e) {
            logger.error("Could not initialize gondola", e);
            System.exit(1);
        }

        if (serverMode) {
            System.out.println("Server-mode");
            new Acceptor().start();
        } else {
            // Temporary test mode
            Map<Integer, Integer> values = new HashMap<>();
            // Create writer threads
            for (int i = 0; i < numWorkers; i++) {
                values.put(i, 0);
                new Writer(hostId, i).start();
            }

            // Create reader
            //new Reader().start();
            // Print out some RPS stats
            while (true) {
                long start = requests.get();
                Thread.sleep(5000);
                double avgLatency = 1.0 * waitTime.get() / requests.get();
                if (shard.getLocalMember().isLeader()) {
                    logger.info(String.format("commits: %.2f/s  latency: %.2f ms (%.2fms)",
                                              (requests.get() - start) / 5.0, avgLatency, latency.get()));
                }
                waitTime.set(0);
                requests.set(0);
            }
        }

    }

    // Background thread to get committed commands from gondola
    class Reader extends Thread {

        public Reader() {
            setName("CommandReader-");
        }

        @Override
        public void run() {
            byte[] buffer = new byte[maxCommandSize];

            int index = 0;
            try {
                index = Math.max(1, shard.getLastSavedIndex());
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }

            int start = index;
            Command command = null;
            long startTs = System.currentTimeMillis();
            while (true) {
                try {
                    command = shard.getCommittedCommand(index, 5000);
                    System.arraycopy(command.getBuffer(), 0, buffer, 0, command.getSize());
                    command.release();
                    index++;
                } catch (TimeoutException e) {
                    logger.info(e.getMessage());
                } catch (Exception e) {
                    e.printStackTrace();
                }

                long now = System.currentTimeMillis();
                if (now - startTs > 5000) {
                    logger.info(String.format("reads: %.2f/s", (index - start) / 5.0));
                    start = index;
                    startTs = now;
                }
            }
        }
    }

    static AtomicInteger ccounter = new AtomicInteger();

    class Writer extends Thread {

        int id;

        Writer(String hostId, int id) {
            setName("worker-" + hostId + "-" + id);
            this.id = id;
        }

        public void run() {
            int value = 0;
            byte[] buffer = new byte[128];
            ByteBuffer bbuffer = ByteBuffer.wrap(buffer);
            long wait = 0;
            int count = 0;

            while (true) {
                try {
                    if (shard.getLocalMember().isLeader()) {
                        Command command = shard.checkoutCommand();
                        bbuffer.clear();
                        bbuffer.putInt(id);
                        bbuffer.putInt(value);

                        long start = System.currentTimeMillis();
                        int c = ccounter.incrementAndGet();
                        latency.head(c);
                        command.commit(buffer, 0, 128);
                        latency.tail(c);
                        waitTime.addAndGet(System.currentTimeMillis() - start);
                        requests.incrementAndGet();

                        value++;
                        command.release();
                        if (delay > 0) {
                            Thread.sleep(delay);
                        }
                    } else {
                        Thread.sleep(1000);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * **************************** server mode **************************
     */

    class Acceptor extends Thread {

        public Acceptor() {
            setName("RemoteInterfaceAcceptor-" + gondola.getHostId());
            new RemoteInterface().start();
        }

        public void run() {
            while (true) {
                logger.info("Listening " + hostId + " " + port);
                try (ServerSocket listener = new ServerSocket(port)) {
                    while (true) {
                        Socket socket = listener.accept();
                        socket.setTcpNoDelay(true);
                        if (tracing) {
                            logger.info("[{}] GondolaCommand socket accept from {} ({})", hostId,
                                        socket.getInetAddress());
                        }

                        // Create more remote interface threads if needed
                        if (availableWorkers.get() <= socketQueue.size() && numWorkers < maxWorkers) {
                            if (tracing) {
                                logger.info(
                                    "[{}] Creating remote interface worker: avail workers={} socketQ={} numWorkers={}",
                                    hostId, availableWorkers.get(), socketQueue, numWorkers);
                            }
                            new RemoteInterface().start();
                            numWorkers++;
                        }
                        socketQueue.put(socket);
                    }
                } catch (BindException e) {
                    logger.error(e.getMessage(), e);
                    Runtime.getRuntime().halt(0);
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);

                    // Small delay to avoid a spin loop
                    try {
                        Thread.sleep(1000);
                    } catch (Exception e2) {
                        logger.error(e2.getMessage(), e2);
                    }
                }
            }
        }
    }

    class RemoteInterface extends Thread {

        Socket socket;

        public RemoteInterface() {
            setName("RemoteInterfaceWorker-" + gondola.getHostId());
        }

        public void run() {
            while (true) {
                try {
                    availableWorkers.incrementAndGet();
                    socket = socketQueue.take();
                    availableWorkers.decrementAndGet();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
                try (
                    InputStream in = socket.getInputStream();
                    OutputStream out = socket.getOutputStream();
                    BufferedReader rd = new BufferedReader(new InputStreamReader(in));
                    BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(out));
                ) {
                    try {
                        String line;
                        while ((line = rd.readLine()) != null) {
                            if (line.length() == 0) {
                                continue;
                            }
                            String result = processCommand(line);
                            wr.write(result + "\n");
                            wr.flush();
                            if (line.startsWith("q")) {
                                Runtime.getRuntime().halt(0);
                            }
                        }
                    } catch (NotLeaderException e) {
                        wr.write(String.format("ERROR: Not leader - leader is %s", e.getLeaderAddress()));
                    } catch (Exception e) {
                        wr.write("ERROR: Unhandled exception: " + e.getMessage() + "\n");
                        logger.error(e.getMessage(), e);
                    }
                } catch (Exception e) {
                    logger.error("GondolaCommand connection closed", e);
                }
            }
        }

        String processCommand(String line) throws Exception {
            String[] args = line.split(" ");
            if (args.length == 0) {
                return "ERROR: No command";
            }
            switch (args[0]) {
                case "c":
                    // commit a command
                    if (args.length < 2) {
                        return "ERROR: c <command>";
                    }
                    Command command = shard.checkoutCommand();
                    try {
                        byte[] buffer = line.substring(2).getBytes("UTF-8");
                        if (buffer.length > command.getCapacity()) {
                            String msg = String.format("ERROR command too long. size=%d, max=%d",
                                                       buffer.length, command.getCapacity());
                            logger.error(msg);
                            return msg;
                        }
                        command.commit(buffer, 0, buffer.length);
                    } finally {
                        command.release();
                    }
                    return String.format("SUCCESS: index %d", command.getIndex());
                case "F":
                    Role role = shard.getLocalRole();
                    if (shard.getLocalRole() == Role.LEADER) {
                        logger.info("This member is already a leader");
                    } else {
                        logger.info("Forcing {} to be a leader...", role);
                        int timeout = -1;
                        if (args.length >= 2) {
                            timeout = Integer.parseInt(args[1]);
                        }
                        shard.forceLeader(timeout);
                    }
                    return "SUCCESS: This member is now " + shard.getLocalRole();
                case "m":
                    // return the current role
                    return String.format("SUCCESS: %s", shard.getLocalRole());
                case "g":
                    // get command by index
                    if (args.length < 2) {
                        return "ERROR: g <index> <timeout>";
                    }
                    int index = Integer.parseInt(args[1]);
                    int timeout = args.length > 2 ? Integer.parseInt(args[2]) : -1;
                    command = shard.getCommittedCommand(index, timeout);
                    try {
                        return String.format("SUCCESS: %s", command.getString());
                    } finally {
                        command.release();
                    }
                case "s":
                    // Status
                    LogEntry le = gondola.getStorage().getLastLogEntry(shard.getLocalMember().getMemberId());
                    int savedIndex = 0;
                    if (le != null) {
                        savedIndex = le.index;
                        le.release();
                    }
                    return String.format("SUCCESS: Mode=%s, commitIndex=%d, savedIndex=%d",
                                         shard.getLocalRole(), shard.getLastSavedIndex(), savedIndex);
                case "n":
                    if (args.length < 2) {
                        return "ERROR: n <on|off>";
                    }
                    // Enable/disable nasty mode
                    if (gondola.getStorage() instanceof NastyStorage) {
                        NastyStorage ns = (NastyStorage) gondola.getStorage();
                        ns.enable(args[1].equals("on"));
                        logger.info("Nasty storage " + ns.isEnabled());
                    }
                    if (gondola.getNetwork() instanceof NastyNetwork) {
                        NastyNetwork nn = (NastyNetwork) gondola.getNetwork();
                        nn.enable(args[1].equals("on"));
                        logger.info("Nasty network " + nn.isEnabled());
                    }
                    return "SUCCESS: Nasty mode " + args[1];
                case "q":
                    // Exit immediately
                    le = gondola.getStorage().getLastLogEntry(shard.getLocalMember().getMemberId());
                    if (le != null) {
                        logger.info("lastTerm={}, lastIndex={}", le.term, le.index);
                    }
                    logger.info("Exiting");
                    return "SUCCESS: exiting";
                default:
                    String msg = String.format("ERROR: Invalid command: %s", line);
                    logger.error(msg);
                    return msg;
            }
        }
    }
}


text:
package basementbobs.queencitybuschaser.utils;

import android.content.Context;
import android.util.TypedValue;

public class BitmapUtils {

	public static int convertDpToPixel(float dp, Context context) {
		return (int) (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources().getDisplayMetrics()));
	}

	public static int addAlpha(int colour, int alpha) {
		return ((alpha & 0xFF) << 24) + colour;
	}

}


text:
/**
*
* ChartArea for MainDash
*
*/

import React from 'react';
import styles from './styles.css';
import ProductBarPlot from '../ProductBarPlot';
class Chart1Area extends React.Component { // eslint-disable-line react/prefer-stateless-function
  render() {

  	// This is where you can change the dimensions of the chart
  	// let chartWidth =  '500',
  	// 	chartHeight = '300' //aspect ratio is 0.7

  	// let margins = {top: 20,
  	// 			   left: 50,
  	// 			   right: 50,
  	// 			   bottom: 50}
    let params = { data: this.props.mainDashboardData1,
                   xName: 'productname',
                   yName: 'units',
                   grouping: 'isfresh',
                   colorScheme: d3.schemeCategory10,
                   legendPosition: 'left',
                   height: window.innerHeight - 250,
                   width: window.innerWidth - 200,
                   chartWidth: window.innerWidth,
				   chartHeight: window.innerHeight,
				   margins: {top: 20,
				             left: 50,
                             right: 50,
                             bottom: 50}
				   };

  	// Translation for grouping element
  	let translate = `translate(${params.margins.left}, ${params.margins.top})`;

    return (
      <div className={styles.chart1Area}>
      	<svg height={params.chartHeight} width={params.chartWidth}>
          <ProductBarPlot {...params}/>
      	</svg>

      </div>
    );
  }
}

export default Chart1Area;


text:
using FluentValidation.Attributes;
using Bivi.BackOffice.Web.ViewModels.Validators.GestionContenu;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bivi.BackOffice.Web.ViewModels.Pages.GestionContenu
{
    [Validator(typeof(ContenuViewModelValidator))]
    public class ContenuViewModel
    {
        public long ID { get; set; }
        public long? TypeContenuID { get; set; }
        public string Texte { get; set; }
         public string Accroche { get; set; }
        public string Titre { get; set; }
        public string UrlDestination { get; set; }
        public string NumeroChapitre { get; set; }

        public long? Option { get; set; }
        public string CodeFonctionnel { get; set; }
        public bool AffichagePopup { get; set; }
        public long? CleModificationLot { get; set; }
        public long? OptionSupplementaire { get; set; }
        public long? ContenuIDDup { get; set; }
        public long? BlocIdDup { get; set; }
        public int? Ordre { get; set; }
        public bool Indicateur1 { get; set; }
        public bool Indicateur2 { get; set; }

        public long? BlocIDContenu { get; set; }
        public long? BlocIDDocument { get; set; }
        public string BlocIDContenuLibelle { get; set; }
    }
}


text:
<?php

/**
 * Abstract Rule entity resource model
 *
 * @author Magento Core Team <core@magentocommerce.com>
 */
namespace Magento\Rule\Model\Resource;

abstract class AbstractResource extends \Magento\Framework\Model\Resource\Db\AbstractDb
{
    /**
     * Store associated with rule entities information map
     *
     * Example:
     * array(
     *    'entity_type1' => array(
     *        'associations_table' => 'table_name',
     *        'rule_id_field'      => 'rule_id',
     *        'entity_id_field'    => 'entity_id'
     *    ),
     *    'entity_type2' => array(
     *        'associations_table' => 'table_name',
     *        'rule_id_field'      => 'rule_id',
     *        'entity_id_field'    => 'entity_id'
     *    )
     *    ....
     * )
     *
     * @var array
     */
    protected $_associatedEntitiesMap = [];

    /**
     * Prepare rule's active "from" and "to" dates
     *
     * @param \Magento\Framework\Model\AbstractModel $object
     * @return $this
     */
    public function _beforeSave(\Magento\Framework\Model\AbstractModel $object)
    {
        $fromDate = $object->getFromDate();
        if ($fromDate instanceof \Zend_Date) {
            $object->setFromDate($fromDate->toString(\Magento\Framework\Stdlib\DateTime::DATETIME_INTERNAL_FORMAT));
        } elseif (!is_string($fromDate) || empty($fromDate)) {
            $object->setFromDate(null);
        }

        $toDate = $object->getToDate();
        if ($toDate instanceof \Zend_Date) {
            $object->setToDate($toDate->toString(\Magento\Framework\Stdlib\DateTime::DATETIME_INTERNAL_FORMAT));
        } elseif (!is_string($toDate) || empty($toDate)) {
            $object->setToDate(null);
        }

        parent::_beforeSave($object);
        return $this;
    }

    /**
     * Bind specified rules to entities
     *
     * @param int[]|int|string $ruleIds
     * @param int[]|int|string $entityIds
     * @param string $entityType
     * @return $this
     * @throws \Exception
     */
    public function bindRuleToEntity($ruleIds, $entityIds, $entityType)
    {
        $this->_getWriteAdapter()->beginTransaction();

        try {
            $this->_multiplyBunchInsert($ruleIds, $entityIds, $entityType);
        } catch (\Exception $e) {
            $this->_getWriteAdapter()->rollback();
            throw $e;
        }

        $this->_getWriteAdapter()->commit();

        return $this;
    }

    /**
     * Multiply rule ids by entity ids and insert
     *
     * @param int|[] $ruleIds
     * @param int|[] $entityIds
     * @param string $entityType
     * @return $this
     */
    protected function _multiplyBunchInsert($ruleIds, $entityIds, $entityType)
    {
        if (empty($ruleIds) || empty($entityIds)) {
            return $this;
        }
        if (!is_array($ruleIds)) {
            $ruleIds = [(int)$ruleIds];
        }
        if (!is_array($entityIds)) {
            $entityIds = [(int)$entityIds];
        }
        $data = [];
        $count = 0;
        $entityInfo = $this->_getAssociatedEntityInfo($entityType);
        foreach ($ruleIds as $ruleId) {
            foreach ($entityIds as $entityId) {
                $data[] = [
                    $entityInfo['entity_id_field'] => $entityId,
                    $entityInfo['rule_id_field'] => $ruleId,
                ];
                $count++;
                if ($count % 1000 == 0) {
                    $this->_getWriteAdapter()->insertOnDuplicate(
                        $this->getTable($entityInfo['associations_table']),
                        $data,
                        [$entityInfo['rule_id_field']]
                    );
                    $data = [];
                }
            }
        }
        if (!empty($data)) {
            $this->_getWriteAdapter()->insertOnDuplicate(
                $this->getTable($entityInfo['associations_table']),
                $data,
                [$entityInfo['rule_id_field']]
            );
        }

        $this->_getWriteAdapter()->delete(
            $this->getTable($entityInfo['associations_table']),
            $this->_getWriteAdapter()->quoteInto(
                $entityInfo['rule_id_field'] . ' IN (?) AND ',
                $ruleIds
            ) . $this->_getWriteAdapter()->quoteInto(
                $entityInfo['entity_id_field'] . ' NOT IN (?)',
                $entityIds
            )
        );
        return $this;
    }

    /**
     * Unbind specified rules from entities
     *
     * @param int[]|int|string $ruleIds
     * @param int[]|int|string $entityIds
     * @param string $entityType
     * @return $this
     */
    public function unbindRuleFromEntity($ruleIds, $entityIds, $entityType)
    {
        $writeAdapter = $this->_getWriteAdapter();
        $entityInfo = $this->_getAssociatedEntityInfo($entityType);

        if (!is_array($entityIds)) {
            $entityIds = [(int)$entityIds];
        }
        if (!is_array($ruleIds)) {
            $ruleIds = [(int)$ruleIds];
        }

        $where = [];
        if (!empty($ruleIds)) {
            $where[] = $writeAdapter->quoteInto($entityInfo['rule_id_field'] . ' IN (?)', $ruleIds);
        }
        if (!empty($entityIds)) {
            $where[] = $writeAdapter->quoteInto($entityInfo['entity_id_field'] . ' IN (?)', $entityIds);
        }

        $writeAdapter->delete($this->getTable($entityInfo['associations_table']), implode(' AND ', $where));

        return $this;
    }

    /**
     * Retrieve rule's associated entity Ids by entity type
     *
     * @param int $ruleId
     * @param string $entityType
     * @return array
     */
    public function getAssociatedEntityIds($ruleId, $entityType)
    {
        $entityInfo = $this->_getAssociatedEntityInfo($entityType);

        $select = $this->_getReadAdapter()->select()->from(
            $this->getTable($entityInfo['associations_table']),
            [$entityInfo['entity_id_field']]
        )->where(
            $entityInfo['rule_id_field'] . ' = ?',
            $ruleId
        );

        return $this->_getReadAdapter()->fetchCol($select);
    }

    /**
     * Retrieve website ids of specified rule
     *
     * @param int $ruleId
     * @return array
     */
    public function getWebsiteIds($ruleId)
    {
        return $this->getAssociatedEntityIds($ruleId, 'website');
    }

    /**
     * Retrieve customer group ids of specified rule
     *
     * @param int $ruleId
     * @return array
     */
    public function getCustomerGroupIds($ruleId)
    {
        return $this->getAssociatedEntityIds($ruleId, 'customer_group');
    }

    /**
     * Retrieve correspondent entity information (associations table name, columns names)
     * of rule's associated entity by specified entity type
     *
     * @param string $entityType
     * @return array
     * @throws \Magento\Framework\Model\Exception
     */
    protected function _getAssociatedEntityInfo($entityType)
    {
        if (isset($this->_associatedEntitiesMap[$entityType])) {
            return $this->_associatedEntitiesMap[$entityType];
        }

        throw new \Magento\Framework\Model\Exception(
            __('There is no information about associated entity type "%1".', $entityType),
            0
        );
    }
}


text:
<?php
namespace Mevdschee\PhpCrudApi\Tests;

require_once(__DIR__ . '/../api.php');

class Api
{
    /**
     * Database configuration array
     *
     * @var array
     */
    protected $config;

    /**
     * @var Mevdschee\PhpCrudApi\Tests\BaseTest
     */
    protected $test;

    /**
     * @var \PHP_CRUD_API
     */
    protected $api;

    public function __construct($test)
    {
        $this->test = $test;
        $this->config = $test::$config;
        $this->config['dbengine'] = $test->getEngineName();
    }

    private function action($method, $url, $data='')
    {
        $url = parse_url($url);
        $query = isset($url['query'])?$url['query']:'';
        parse_str($query, $get);

        $this->api = new \PHP_CRUD_API(array(
            'dbengine'=>$this->config['dbengine'],
            'hostname'=>$this->config['hostname'],
            'username'=>$this->config['username'],
            'password'=>$this->config['password'],
            'database'=>$this->config['database'],
            // callbacks
            'table_authorizer'=>function ($action, $database, $table) {
                return true;
            },
            'column_authorizer'=>function ($action, $database, $table, $column) {
                return !($column=='password'&&$action=='list');
            },
            'record_filter'=>function ($action, $database, $table) {
                return ($table=='posts')?array('id,neq,13'):false;
            },
            'tenancy_function'=>function ($action, $database, $table, $column) {
                return ($table=='users'&&$column=='id')?1:null;
            },
            'input_sanitizer'=>function ($action, $database, $table, $column, $type, $value) {
                return is_string($value)?strip_tags($value):$value;
            },
            'input_validator'=>function ($action, $database, $table, $column, $type, $value, $context) {
                return ($column=='category_id' && !is_numeric($value))?'must be numeric':true;
            },
            'before'=>function (&$action, &$database, &$table, &$id, &$input) {
                if ($table=='products') {
                    if ($action=='create') {
                        $input->created_at = '2013-12-11 10:09:08';
                    } elseif ($action=='delete') {
                        $action='update';
                        $input = (object)array('deleted_at' => '2013-12-11 11:10:09');
                    }
                }
            },
            'after'=>function ($action, $database, $table, $id, $input, $output) {
                file_put_contents('log.txt', var_export(array($action,$database,$table,$id,$input,$output), true), FILE_APPEND);
            },
            // for tests
            'method'=>$method,
            'request'=>$url['path'],
            'post'=>$data,
            'get'=>$get,
        ));
        return $this;
    }

    public function get($url)
    {
        return $this->action('GET', $url);
    }

    public function post($url, $data)
    {
        return $this->action('POST', $url, $data);
    }

    public function put($url, $data)
    {
        return $this->action('PUT', $url, $data);
    }

    public function delete($url)
    {
        return $this->action('DELETE', $url);
    }

    public function options($url)
    {
        return $this->action('OPTIONS', $url);
    }

    public function patch($url, $data)
    {
        return $this->action('PATCH', $url, $data);
    }

    public function expectAny()
    {
        ob_start();
        $this->api->executeCommand();
        ob_end_clean();
        return $this;
    }

    public function expect($output, $error=false)
    {
        $exception = false;
        ob_start();
        try {
            $this->api->executeCommand();
        } catch (\Exception $e) {
            $exception = $e->getMessage();
        }
        $data = ob_get_contents();
        ob_end_clean();
        if ($exception) {
            $this->test->assertEquals($error, $exception);
        } else {
            $this->test->assertEquals($output, $data);
        }
        return $this;
    }
}