text:
require.paths.unshift(__dirname);
var xml2js = require("xml2js");
var parse = require("url").parse;
var helpers = require("helpers");
var handlers = require("handlers");
var nClass = require("nTunes-class");
var nCommand = require("nTunes-command");
var querystring = require("querystring");
var applescript = require("applescript");
var nSpecifier = require("nTunes-specifier");
require.paths.shift();

// Before doing anything, the "iTunes.sdef" file must be read and
// parsed. The SDEF file dynamically builds the 'nTunes' API once
// the file has been parsed into memory.
var parser = new xml2js.Parser();
parser.on('end', function(result) {
  // With the parsed XML result, we need to format the object into
  // nClass and nCommand instances.
  var iTunesSuite = result.suite[1];
  nCommand.processCommands(iTunesSuite.command);
  nClass.processClasses(iTunesSuite['class']);
  nSpecifier.setNClass(nClass);

  // Add the custom nTunes class handlers from "handlers.js"
  handlers(nClass);

  parser = null;
});
// Read the file synchronously, since the 'xml2js' parseString function is
// also synchronous. This is wanted behavior in this case though, since it's
// only the inital parsing of the classes, and we want them to be immediately
// available for extending by the user of the module.
parser.parseString(require("fs").readFileSync(__dirname + '/iTunes.sdef'));

// Patch "node-applescript"'s UndefinedParser to look for Specifiers
// in the result, and convert them to URIs for the API to use.
var oldUndefinedParser = applescript.Parsers.UndefinedParser;
var suffix = ' of application "iTunes"';
applescript.Parsers.UndefinedParser = function() {
  var result = oldUndefinedParser.apply(this, arguments);
  if (result.substring(result.length-suffix.length) == suffix) {
    result = nSpecifier.specifierFromApplescript(result);
  }
  return result;
}

// The 'nTunes' function is directly returned from the "nTunes" module. When
// it is called, it returns a connect layer that is the nTunes API. It usually
// goes at the bottom of your connect stack. See "bin/nTunes" for an example.
function nTunes() {
  function nTunesLayer(req, res, next) {
    var self = nTunesLayer;
    req.parsedUrl = res.parsedUrl = parse(req.url, true);

    // Each "/" in the request URI represents selecting a resource, narrowing
    // down the previous selection, or possibly calling a command.
    req.parsedUrl.request = req.parsedUrl.pathname.split("/").slice(1);

    // First check for the case of a "command", since it's only valid with a
    // single token in the URI, and a POST method request.
    if (req.method == "POST" && req.parsedUrl.request.length == 1 && nCommand.REGEXP.test(req.parsedUrl.request[0])) {
      var body = "";
      req.setEncoding("utf8");
      req.on("data", function(chunk) {
        body += chunk;
      });
      req.on("end", function() {
        req.body = querystring.parse(querystring.unescape(body));
        self.doNTunesCommand(req.parsedUrl.request[0], req.body, res);
      });

    } else {
      // If it's not a command, then maybe it's a class/property lookup.
      // Attempt to resolve the url into a 'specifier'.
      var resolvedSpecifier;
      try {
        resolvedSpecifier = new nSpecifier(req.parsedUrl.pathname);
      } catch (e) {
        // If 'new nSpecifier' throws an error, then the user requested
        // an invalid specifier. nTunes should report it to the next layer.
        return next(e);
      }

      // If this request is for a custom handler, then invoke the
      // custom callback.
      if (resolvedSpecifier.handler) {
        resolvedSpecifier.handler(req, res, self);

      } else {
        var as = resolvedSpecifier.vars;

        if (req.method == "POST") {
          req.body = "";
          req.setEncoding("utf8");
          req.on("data", function(chunk) { req.body += chunk; });
          req.on("end", function() {
            if (req.body.length > self.defaultValue.length+1 && req.body.substring(0, self.defaultValue.length) == self.defaultValue) {
              req.body = querystring.parse(req.body);
            } else {
              req.body = new String(req.body);
              req.body[self.defaultValue] = String(req.body);
            }
            var value = querystring.unescape(req.body[self.defaultValue]);
            as += "set " + resolvedSpecifier.finalVar + " to " + value + "\n";
            as += "get " + resolvedSpecifier.finalVar;
            self.doAppleScriptThenResponse(as, res);
          });

        } else if (req.method == "GET") {
          as += 'get ' + resolvedSpecifier.finalVar;
          self.doAppleScriptThenResponse(as, res);
        }
      }
    }
  }
  // Make the layer inherit everything that the normal 'nTunes' module has.
  // This way, you have the option of either modifying your layer instance,
  // or modifying the module itself globally.
  nTunesLayer.__proto__ = nTunes;
  return nTunesLayer;
}

// The value used in POST request when there is an unnamed parameter.
nTunes.defaultValue = "value";

nTunes.doNTunesCommand = function(command, params, res) {
  var ncommand = nCommand.getCommand(command);
  var asStr = command + ' ';
  var self = this;

  ncommand.parameters.forEach(function(parameter) {
    var userDidSupplyParam = parameter.name in params;
    if (!userDidSupplyParam && !parameter.optional) {
      // Return error, user did not supply required param
      var e = new Error("Required parameter \"" + parameter.name + "\" was not found.");
      self.sendNTunesResponse(res, 500, null, {
        error: e
      });
    }
    if (userDidSupplyParam) {
      if (parameter.name != "value") {
        asStr += parameter.name + " ";
      }
      if (parameter.type == "specifier") {
        var specifier = new nSpecifier(params[parameter.name]);
        asStr = specifier.vars + asStr + specifier.finalVar;
      } else if (parameter.type == "boolean") {
        asStr += String(params[parameter.name]).toLowerCase() == "true" ? "yes" : "no";
      }
      asStr += " ";
    }
  });
  self.doAppleScriptThenResponse(asStr, res);
}

// Performs the passed AppleScript code against the "iTunes" application,
// then sends the response from AppleScript to the HTTP client, ending
// the request.
nTunes.doAppleScriptThenResponse = function(as, res) {
  var self = this;
  as = 'tell application "iTunes"\n' + as + "\nend tell";
  applescript.execString(as, function(err, rtn) {
    if (err) {
      self.sendNTunesResponse(res, 500, null, {
        error: err
      });
    } else {
      self.sendNTunesResponse(res, 200, null, rtn);
    }
  });
}

// Called whenever the nTunes API is ready to send a response to the client.
// It's a single shared function so that we can do last minute things like
// convert the data to a different transfer format if the client requested.
//   i.e. checks for ?format=xml to convert to XML
nTunes.sendNTunesResponse = function(res, code, headers, body) {
  var format = res.parsedUrl.query && res.parsedUrl.query.format ? res.parsedUrl.query.format : 'json';

  headers = headers || {};
  if (Buffer.isBuffer(body)) {
    // Manually set the 'Content-Length' if the body is a Buffer.
    format = "buffer";
    headers['Content-Length'] = body.length;
  } else if (res.parsedUrl.query && res.parsedUrl.query.unique && Array.isArray(body)) {
    // Handle the 'unique' query parameter.
    body = helpers.arrayUniqDeep(body);
  }

  // TODO: Implement body conversion to XML, JSONP
  if (format == 'json') {
    body = JSON.stringify(body);
  } else if (format == 'txt') {
    body = String(body);
  } else if (format == 'buffer') {
    // Don't need to do anything...
  } else {
    throw new Error("Unsupported format!");
  }

  // Ensure there's a 'Content-Type' and 'Content-Length'
  var encoding = undefined;
  if (!headers['Content-Type']) {
    headers['Content-Type'] = helpers.mime(format);
  }
  if (!headers['Content-Length']) {
    encoding = 'utf8';
    headers['Content-Length'] = Buffer.byteLength(body, "utf8");
  }

  // Finally flush the response
  res.writeHead(code, headers);
  res.end(body, encoding);
}

// The 'CLASSES' property contains all the 'nClass' instances parsed from the
// iTunes.sdef file. It is exported to the nTunes module so that the end user
// can add additional handlers to classes as needed.
nTunes.CLASSES = nClass;

module.exports = nTunes;


text:
#ifndef __APPARMOR_H
#define __APPARMOR_H

#include <linux/slab.h>
#include <linux/fs.h>

#include "match.h"

/* Provide our own test for whether a write lock is held for asserts
 * this is because on none SMP systems write_can_lock will always
 * resolve to true, which is what you want for code making decisions
 * based on it, but wrong for asserts checking that the lock is held
 */
#ifdef CONFIG_SMP
#define write_is_locked(X) !write_can_lock(X)
#else
#define write_is_locked(X) (1)
#endif /* CONFIG_SMP */

/*
 * Class of mediation types in the AppArmor policy db
 */
#define AA_CLASS_ENTRY		0
#define AA_CLASS_UNKNOWN	1
#define AA_CLASS_FILE		2
#define AA_CLASS_CAP		3
#define AA_CLASS_NET		4
#define AA_CLASS_RLIMITS	5
#define AA_CLASS_DOMAIN		6
#define AA_CLASS_MOUNT		7
#define AA_CLASS_PTRACE		9
#define AA_CLASS_SIGNAL		10
#define AA_CLASS_LABEL		16

#define AA_CLASS_LAST		AA_CLASS_LABEL

/* Control parameters settable through module/boot flags */
extern enum audit_mode aa_g_audit;
extern bool aa_g_audit_header;
extern bool aa_g_debug;
extern bool aa_g_lock_policy;
extern bool aa_g_logsyscall;
extern bool aa_g_paranoid_load;
extern unsigned int aa_g_path_max;
extern bool aa_g_unconfined_init;

/*
 * DEBUG remains global (no per profile flag) since it is mostly used in sysctl
 * which is not related to profile accesses.
 */

#define AA_DEBUG(fmt, args...)						\
	do {								\
		if (aa_g_debug && printk_ratelimit())			\
			printk(KERN_DEBUG "AppArmor: " fmt, ##args);	\
	} while (0)

#define AA_WARN(X) WARN((X), "APPARMOR WARN %s: %s\n", __FUNCTION__, #X)

#define AA_BUG(X, args...) AA_BUG_FMT((X), "" args )
#define AA_BUG_FMT(X, fmt, args...)					\
	WARN((X), "AppArmor WARN %s: (" #X "): " fmt, __FUNCTION__ , ##args )

#define AA_ERROR(fmt, args...)						\
	do {								\
		if (printk_ratelimit())					\
			printk(KERN_ERR "AppArmor: " fmt, ##args);	\
	} while (0)

/* Flag indicating whether initialization completed */
extern int apparmor_initialized __initdata;

/* fn's in lib */
char *aa_split_fqname(char *args, char **ns_name);
char *aa_splitn_fqname(char *fqname, size_t n, char **ns_name, size_t *ns_len);
void aa_info_message(const char *str);
void *__aa_kvmalloc(size_t size, gfp_t flags);

static inline void *kvmalloc(size_t size)
{
	return __aa_kvmalloc(size, 0);
}

static inline void *kvzalloc(size_t size)
{
	return __aa_kvmalloc(size, __GFP_ZERO);
}

/* returns 0 if kref not incremented */
static inline int kref_get_not0(struct kref *kref)
{
	return atomic_inc_not_zero(&kref->refcount);
}

/**
 * aa_strneq - compare null terminated @str to a non null terminated substring
 * @str: a null terminated string
 * @sub: a substring, not necessarily null terminated
 * @len: length of @sub to compare
 *
 * The @str string must be full consumed for this to be considered a match
 */
static inline bool aa_strneq(const char *str, const char *sub, int len)
{
	return !strncmp(str, sub, len) && !str[len];
}

/**
 * aa_dfa_null_transition - step to next state after null character
 * @dfa: the dfa to match against
 * @start: the state of the dfa to start matching in
 *
 * aa_dfa_null_transition transitions to the next state after a null
 * character which is not used in standard matching and is only
 * used to separate pairs.
 */
static inline unsigned int aa_dfa_null_transition(struct aa_dfa *dfa,
						  unsigned int start)
{
	/* the null transition only needs the string's null terminator byte */
	return aa_dfa_next(dfa, start, 0);
}

static inline bool path_mediated_fs(struct inode *inode)
{
	return !(inode->i_sb->s_flags & MS_NOUSER);
}

struct counted_str {
	struct kref count;
	char name[];
};

#define str_to_counted(str) \
	((struct counted_str *)(str - offsetof(struct counted_str,name)))

#define __counted	/* atm just a notation */

void aa_str_kref(struct kref *kref);
char *aa_str_alloc(int size, gfp_t gfp);

static inline __counted char *aa_get_str(__counted char *str)
{
	if (str)
		kref_get(&(str_to_counted(str)->count));

	return str;
}

static inline void aa_put_str(__counted char *str)
{
	if (str)
		kref_put(&str_to_counted(str)->count, aa_str_kref);
}

const char *aa_imode_name(umode_t mode);

#endif /* __APPARMOR_H */

redpajama_set_name: RedPajamaGithub


text:
/**
 * @source https://www.404it.no/en/blog/javascript_random_password_generator
 */

// Public: Constructor
var RandomPassword = function () {
	this.chrLower="abcdefghjkmnpqrst";
	this.chrUpper="ABCDEFGHJKMNPQRST";
	this.chrNumbers="23456789";
	this.chrSymbols="!#%&?+*_.,:;";

	this.maxLength=255;
	this.minLength=4;
}

/*
	Public: Create password

	length (optional): Password length. If value is not within minLength/maxLength (defined in constructor), length will be adjusted automatically.

	characters (optional): The characters the password will be composed of. Must contain at least one of the following:
		this.chrLower
		this.chrUpper
		this.chrNumbers
		this.chrSymbols
	Use + to combine. You can add your own sets of characters. If not at least one of the constructor defined sets of characters is found, default set of characters will be used.
*/
RandomPassword.prototype.create = function(length, characters) {
	let _length=this.adjustLengthWithinLimits(length);
	let _characters=this.secureCharacterCombination(characters);

	return this.shufflePassword(this.assemblePassword(_characters, _length));
};

// Private: Adjusts password length to be within limits.
RandomPassword.prototype.adjustLengthWithinLimits = function(length) {
	if(!length || length<this.minLength)
		return this.minLength;
	else if(length>this.maxLength)
		return this.maxLength;
	else
		return length;
};

// Private: Make sure characters password is build of contains meaningful set of characters.
RandomPassword.prototype.secureCharacterCombination = function(characters) {
	let defaultCharacters=this.chrLower+this.chrUpper+this.chrNumbers;

	if(!characters || this.trim(characters)=="")
		return defaultCharacters;
	else if(!this.containsAtLeast(characters, [this.chrLower, this.chrUpper, this.chrNumbers, this.chrSymbols]))
		return defaultCharacters;
	else
		return characters;

};

// Private: Assemble password using a string of characters the password will consist of.
RandomPassword.prototype.assemblePassword = function(characters, length) {
	let randMax=this.chrNumbers.length;
	let randMin=randMax-4;
	let index=this.random(0, characters.length-1);
	let password="";

	for(let i=0; i<length; i++) {
		let jump=this.random(randMin, randMax);
		index=((index+jump)>(characters.length-1)?this.random(0, characters.length-1):index+jump);
		password+=characters[index];
	}

	return password;
};

// Private: Shuffle password.
RandomPassword.prototype.shufflePassword = function(password) {
	return password.split('').sort(function(){return 0.5-Math.random()}).join('');
};

// Private: Checks if string contains at least one string in an array
RandomPassword.prototype.containsAtLeast = function(string, strings) {
	for(let i=0; i<strings.length; i++) {
		if(string.indexOf(strings[i])!=-1)
			return true;
	}
	return false;
};

// Private: Returns a random number between min and max.
RandomPassword.prototype.random = function(min, max) {
	return Math.floor((Math.random() * max) + min);
};

// Private: Trims a string (required for compatibility with IE9 or older)
RandomPassword.prototype.trim = function(s) {
	if(typeof String.prototype.trim !== 'function')
		return s.replace(/^\s+|\s+$/g, '');
	else
		return s.trim();
};


text:
import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'admin-component',
    templateUrl: 'admin-component.html',
})

export class AdminComponent implements OnInit {
    url : String = API_URL;
    constructor() {

    }

    ngOnInit(): void {

    }
}


text:
package com.sweetmanor.demo.gui.swing.basic;

import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;

import com.sweetmanor.common.Const;
import com.sweetmanor.utils.FrameUtil;

/**
 * 交互对话框示例:使用JOptionPane实现各种对话框
 *
 * @version 1.0 2014-08-26
 * @author ijlhjj
 */
public class JOptionPaneDemo1 {
	JFrame frame = new JFrame("交互对话框示例");

	// 定义6个面板,分别用于定义对话框的几种选项
	private ButtonPanel messagePanel;// 消息内容面板
	private ButtonPanel messageTypePanel;// 消息类型面板
	private ButtonPanel msgPanel;// 消息对话框面板
	private ButtonPanel confirmPanel;// 确认对话框面板
	private ButtonPanel optionsPanel;// 选项对话框面板
	private ButtonPanel inputPanel;// 输入对话框面板

	private String msgStr = "消息区内容";// 消息内容:字符串
	private Icon msgIcon = new ImageIcon(Const.classPath + "images/swing/heart.png");// 消息内容:图标
	private Object msgObj = new Date();// 消息内容:普遍对象
	private Component msgButton = new JButton("组件消息");// 消息内容:组件对象

	public void init() {
		Box box = new Box(BoxLayout.Y_AXIS);
		frame.add(box);

		// 顶部区域
		JPanel top = new JPanel();
		top.setBorder(new TitledBorder(new EtchedBorder(), "对话框的通用选项", TitledBorder.CENTER, TitledBorder.TOP));
		top.setLayout(new GridLayout(1, 2));
		box.add(top);

		messageTypePanel = new ButtonPanel("选择消息的类型", new String[] { "ERROR_MESSAGE", "INFORMATION_MESSAGE",
				"WARNING_MESSAGE", "QUESTION_MESSAGE", "PLAIN_MESSAGE" });// 创建消息类型面板
		top.add(messageTypePanel);
		messagePanel = new ButtonPanel("选择消息内容的类型", new String[] { "字符串信息", "图标消息", "组件消息", "普通对象消息", "Object[]消息" });// 创建消息内容面板
		top.add(messagePanel);

		// 底部区域
		JPanel bottom = new JPanel();
		bottom.setBorder(new TitledBorder(new EtchedBorder(), "弹出不同的对话框", TitledBorder.CENTER, TitledBorder.TOP));
		bottom.setLayout(new GridLayout(1, 4));
		box.add(bottom);

		ShowAction btListener = new ShowAction();// 按钮监听器

		// 组建消息对话框面板
		JButton btMessage = new JButton("消息对话框");
		btMessage.addActionListener(btListener);
		msgPanel = new ButtonPanel("消息对话框", null);
		msgPanel.add(btMessage);
		bottom.add(msgPanel);

		// 组建确认对话框面板
		JButton btConfrim = new JButton("确认对话框");
		btConfrim.addActionListener(new ShowAction());
		confirmPanel = new ButtonPanel("确认对话框",
				new String[] { "DEFAULT_OPTION", "YES_NO_OPTION", "YES_NO_CANCEL_OPTION", "OK_CANCEL_OPTION" });// 包含四个选项
		confirmPanel.add(btConfrim);
		bottom.add(confirmPanel);

		// 组建输入对话框面板
		JButton btInput = new JButton("输入对话框");
		btInput.addActionListener(new ShowAction());
		inputPanel = new ButtonPanel("输入对话框", new String[] { "单行文本框", "下拉列表选择框" });// 包含两个选项
		inputPanel.add(btInput);
		bottom.add(inputPanel);

		// 组建选项对话框面板
		JButton btOption = new JButton("选项对话框");
		btOption.addActionListener(new ShowAction());
		optionsPanel = new ButtonPanel("选项对话框", new String[] { "字符串选项", "图标选项", "对象选项" });// 包含三个选项
		optionsPanel.add(btOption);
		bottom.add(optionsPanel);

		frame.pack();
		FrameUtil.center(frame);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}

	/**
	 * 返回确认对话框的按钮选项
	 */
	private int getOptionType() {
		if ("DEFAULT_OPTION".equals(confirmPanel.getSelection())) {
			return JOptionPane.DEFAULT_OPTION;// 默认选项将只返回"确定"按钮
		} else if ("YES_NO_OPTION".equals(confirmPanel.getSelection())) {
			return JOptionPane.YES_NO_OPTION;
		} else if ("YES_NO_CANCEL_OPTION".equals(confirmPanel.getSelection())) {
			return JOptionPane.YES_NO_CANCEL_OPTION;
		} else {
			return JOptionPane.OK_CANCEL_OPTION;
		}
	}

	/**
	 * 返回消息内容
	 */
	private Object getMessage() {
		if ("字符串信息".equals(messagePanel.getSelection())) {
			return msgStr;
		} else if ("图标消息".equals(messagePanel.getSelection())) {
			return msgIcon;
		} else if ("组件消息".equals(messagePanel.getSelection())) {
			return msgButton;
		} else if ("普通对象消息".equals(messagePanel.getSelection())) {
			return msgObj;
		} else {
			return new Object[] { msgStr, msgIcon, msgButton, msgObj };
		}
	}

	/**
	 * 返回消息的类型(决定图标区的图标)
	 */
	private int getDialogType() {
		if ("ERROR_MESSAGE".equals(messageTypePanel.getSelection())) {
			return JOptionPane.ERROR_MESSAGE;
		} else if ("INFORMATION_MESSAGE".equals(messageTypePanel.getSelection())) {
			return JOptionPane.INFORMATION_MESSAGE;
		} else if ("WARNING_MESSAGE".equals(messageTypePanel.getSelection())) {
			return JOptionPane.WARNING_MESSAGE;
		} else if ("QUESTION_MESSAGE".equals(messageTypePanel.getSelection())) {
			return JOptionPane.QUESTION_MESSAGE;
		} else {
			return JOptionPane.PLAIN_MESSAGE;
		}
	}

	/**
	 * 返回选项对话框的选项
	 */
	private Object[] getOptions() {
		if ("字符串选项".equals(optionsPanel.getSelection())) {
			return new String[] { "a", "b", "c", "d" };
		} else if ("图标选项".equals(optionsPanel.getSelection())) {
			return new Icon[] { new ImageIcon(Const.classPath + "images/swing/1.gif"),
					new ImageIcon(Const.classPath + "images/swing/2.gif"),
					new ImageIcon(Const.classPath + "images/swing/3.gif"),
					new ImageIcon(Const.classPath + "images/swing/4.gif") };
		} else {
			return new Object[] { new Date(), new Date(), new Date() };
		}
	}

	public static void main(String[] args) {
		new JOptionPaneDemo1().init();
	}

	// 按钮监听器:该监听器其实是本示例的重点,将单独提取到JOptionPaneDemo2中进行简单使用示例
	class ShowAction implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent e) {
			if ("确认对话框".equals(e.getActionCommand())) {
				JOptionPane.showConfirmDialog(frame, getMessage(), "确认对话框", getOptionType(), getDialogType());
			} else if ("输入对话框".equals(e.getActionCommand())) {
				if ("单行文本框".equals(inputPanel.getSelection())) {
					JOptionPane.showInputDialog(frame, getMessage(), "输入对话框", getDialogType());
				} else {
					JOptionPane.showInputDialog(frame, getMessage(), "输入对话框", getDialogType(), null,
							new String[] { "轻量级JavaEE企业应用开发", "Struts2权威指南" }, "Struts2权威指南");
				}
			} else if ("消息对话框".equals(e.getActionCommand())) {
				JOptionPane.showMessageDialog(frame, getMessage(), "消息对话框", getDialogType());
			} else if ("选项对话框".equals(e.getActionCommand())) {
				JOptionPane.showOptionDialog(frame, getMessage(), "选项对话框", getOptionType(), getDialogType(), null,
						getOptions(), "b");
			}
		}
	}

	// 可指定标题的自定义单选按钮组组件
	class ButtonPanel extends JPanel {
		private static final long serialVersionUID = 1L;
		private ButtonGroup btGroup = new ButtonGroup();// 单选按钮组

		public ButtonPanel(String title, String[] options) {
			setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), title));
			setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
			for (int i = 0; options != null && i < options.length; i++) {
				JRadioButton rbItem = new JRadioButton(options[i]);
				add(rbItem);
				btGroup.add(rbItem);
				// 疑问:单独使用时不需要指定ActionCommand属性,但此处不加此语句返回值不正确,原因未知。
				rbItem.setActionCommand(options[i]);
				rbItem.setSelected(i == 0);
			}
		}

		public String getSelection() {
			return btGroup.getSelection().getActionCommand();
		}
	}

}


text:
import log from "../../../log";
import assert from "../../../utils/assert";
import {
  be2toi,
  be3toi,
  be4toi,
  be8toi,
  concat,
  itobe4,
  itobe8,
} from "../../../utils/byte_parsing";
import {
  hexToBytes,
  readNullTerminatedString,
} from "../../../utils/string_parsing";
import { MAX_32_BIT_INT } from "./constants";
import { createBox } from "./create_box";
import { getPlayReadyKIDFromPrivateData } from "./drm";
import {
  getBoxContent,
  getBoxOffsets,
  getChildBox,
} from "./get_box";
import {
  getEMSG,
  getMDIA,
  getTRAF,
  getTRAFs,
} from "./read";

/** Information related to a PSSH box. */
export interface IISOBMFFPSSHInfo {
  /** Corresponding DRM's system ID, as an hexadecimal string. */
  systemId : string;
  /** Additional data contained in the PSSH Box. */
  privateData : Uint8Array;
}

/**
 * Inband event data when the data was contained inside an ISOBMFF box.
 * The value and their name corresponds to the same one than in the
 * corresponding ISOBMFF specification.
 */
export interface IEMSG {
  schemeIdUri: string;
  value: string;
  timescale: number;
  presentationTimeDelta: number;
  eventDuration: number;
  id: number;
  messageData: Uint8Array;
}

/** Segment information from a parsed sidx. */
export interface ISidxSegment {
  /** This segment start time, timescaled. */
  time : number;
  /** This segment difference between its end and start time, timescaled. */
  duration : number;
  /** Dividing `time` or `duration` with this value allows to obtain seconds. */
  timescale : number;
  /**
   * Start and ending bytes (included) for the segment in the whole ISOBMFF
   * buffer.
   */
  range : [number, number];
}

/**
 * Parse the sidx part (segment index) of an ISOBMFF buffer and construct a
 * corresponding Array of available segments.
 *
 * Returns `null` if not found.
 * @param {Uint8Array} buf
 * @param {Number} sidxOffsetInWholeSegment
 * @returns {Object|null} {Array.<Object>} - Information about each subsegment.
 */
function getSegmentsFromSidx(
  buf : Uint8Array,
  sidxOffsetInWholeSegment : number
) : ISidxSegment[]|null {
  const sidxOffsets = getBoxOffsets(buf, 0x73696478 /* "sidx" */);
  if (sidxOffsets === null) {
    return null;
  }
  let offset = sidxOffsetInWholeSegment;
  const boxSize = sidxOffsets[2] - sidxOffsets[0];
  let cursor = sidxOffsets[1];

  /* version(8) */
  /* flags(24) */
  /* reference_ID(32); */
  /* timescale(32); */
  const version = buf[cursor]; cursor += 4 + 4;
  const timescale = be4toi(buf, cursor); cursor += 4;

  /* earliest_presentation_time(32 / 64) */
  /* first_offset(32 / 64) */
  let time;
  if (version === 0) {
    time    = be4toi(buf, cursor);           cursor += 4;
    offset += be4toi(buf, cursor) + boxSize; cursor += 4;
  }
  else if (version === 1) {
    time    = be8toi(buf, cursor);           cursor += 8;
    offset += be8toi(buf, cursor) + boxSize; cursor += 8;
  }
  else {
    return null;
  }

  const segments : ISidxSegment[] = [];

  /* reserved(16) */
  /* reference_count(16) */
  cursor += 2;
  let count = be2toi(buf, cursor);
  cursor += 2;
  while (--count >= 0) {
    /* reference_type(1) */
    /* reference_size(31) */
    /* segment_duration(32) */
    /* sap..(32) */
    const refChunk = be4toi(buf, cursor);
    cursor += 4;
    const refType = (refChunk & 0x80000000) >>> 31;
    const refSize = (refChunk & 0x7FFFFFFF);

    // when set to 1 indicates that the reference is to a sidx, else to media
    if (refType === 1) {
      throw new Error("sidx with reference_type `1` not yet implemented");
    }

    const duration = be4toi(buf, cursor);
    cursor += 4;

    // let sapChunk = be4toi(buf, cursor + 8);
    cursor += 4;

    // TODO(pierre): handle sap
    // let startsWithSap = (sapChunk & 0x80000000) >>> 31;
    // let sapType = (sapChunk & 0x70000000) >>> 28;
    // let sapDelta = sapChunk & 0x0FFFFFFF;

    segments.push({ time,
                    duration,
                    timescale,
                    range: [offset, offset + refSize - 1] });

    time += duration;
    offset += refSize;
  }

  return segments;
}

/**
 * Parse track Fragment Decode Time to get a precize initial time for this
 * segment (in the media timescale).
 *
 * Stops at the first tfdt encountered from the beginning of the file.
 * Returns this time.
 * `undefined` if not found.
 * @param {Uint8Array} buffer
 * @returns {Number | undefined}
 */
function getTrackFragmentDecodeTime(buffer : Uint8Array) : number | undefined {
  const traf = getTRAF(buffer);
  if (traf === null) {
    return undefined;
  }
  const tfdt = getBoxContent(traf, 0x74666474 /* tfdt */);
  if (tfdt === null) {
    return undefined;
  }
  const version = tfdt[0];
  return version === 1 ? be8toi(tfdt, 4) :
         version === 0 ? be4toi(tfdt, 4) :
                         undefined;
}

/**
 * Returns the "default sample duration" which is the default value for duration
 * of samples found in a "traf" ISOBMFF box.
 *
 * Returns `undefined` if no "default sample duration" has been found.
 * @param {Uint8Array} traf
 * @returns {number|undefined}
 */
function getDefaultDurationFromTFHDInTRAF(traf : Uint8Array) : number | undefined {
  const tfhd = getBoxContent(traf, 0x74666864 /* tfhd */);
  if (tfhd === null) {
    return undefined;
  }

  let cursor = /* version */ 1;

  const flags = be3toi(tfhd, cursor); cursor += 3;
  const hasBaseDataOffset = (flags & 0x000001) > 0;
  const hasSampleDescriptionIndex = (flags & 0x000002) > 0;
  const hasDefaultSampleDuration = (flags & 0x000008) > 0;

  if (!hasDefaultSampleDuration) {
    return undefined;
  }
  cursor += 4;

  if (hasBaseDataOffset) {
    cursor += 8;
  }

  if (hasSampleDescriptionIndex) {
    cursor += 4;
  }

  const defaultDuration = be4toi(tfhd, cursor);
  return defaultDuration;
}

/**
 * Calculate segment duration approximation by additioning the duration from
 * every samples in a trun ISOBMFF box.
 *
 * Returns `undefined` if we could not parse the duration.
 * @param {Uint8Array} buffer
 * @returns {number | undefined}
 */
function getDurationFromTrun(buffer : Uint8Array) : number | undefined {
  const trafs = getTRAFs(buffer);
  if (trafs.length === 0) {
    return undefined;
  }

  let completeDuration : number = 0;
  for (const traf of trafs) {
    const trun = getBoxContent(traf, 0x7472756E /* trun */);
    if (trun === null) {
      return undefined;
    }
    let cursor = 0;
    const version = trun[cursor]; cursor += 1;
    if (version > 1) {
      return undefined;
    }

    const flags = be3toi(trun, cursor); cursor += 3;
    const hasSampleDuration = (flags & 0x000100) > 0;

    let defaultDuration : number | undefined = 0;
    if (!hasSampleDuration) {
      defaultDuration = getDefaultDurationFromTFHDInTRAF(traf);
      if (defaultDuration === undefined) {
        return undefined;
      }
    }

    const hasDataOffset = (flags & 0x000001) > 0;
    const hasFirstSampleFlags = (flags & 0x000004) > 0;
    const hasSampleSize = (flags & 0x000200) > 0;
    const hasSampleFlags = (flags & 0x000400) > 0;
    const hasSampleCompositionOffset = (flags & 0x000800) > 0;

    const sampleCounts = be4toi(trun, cursor); cursor += 4;

    if (hasDataOffset) {
      cursor += 4;
    }
    if (hasFirstSampleFlags) {
      cursor += 4;
    }

    let i = sampleCounts;
    let duration = 0;
    while (i-- > 0) {
      if (hasSampleDuration) {
        duration += be4toi(trun, cursor);
        cursor += 4;
      } else {
        duration += defaultDuration;
      }
      if (hasSampleSize) {
        cursor += 4;
      }
      if (hasSampleFlags) {
        cursor += 4;
      }
      if (hasSampleCompositionOffset) {
        cursor += 4;
      }
    }

    completeDuration += duration;
  }
  return completeDuration;
}

/**
 * Get timescale information from a movie header box. Found in init segments.
 * `undefined` if not found or not parsed.
 *
 * This timescale is the default timescale used for segments.
 * @param {Uint8Array} buffer
 * @returns {Number | undefined}
 */
function getMDHDTimescale(buffer : Uint8Array) : number | undefined {
  const mdia = getMDIA(buffer);
  if (mdia === null) {
    return undefined;
  }

  const mdhd = getBoxContent(mdia, 0x6D646864  /* "mdhd" */);
  if (mdhd === null) {
    return undefined;
  }

  let cursor = 0;
  const version = mdhd[cursor]; cursor += 4;
  return version === 1 ? be4toi(mdhd, cursor + 16) :
         version === 0 ? be4toi(mdhd, cursor + 8) :
                         undefined;
}

/**
 * Creates a PSSH box with the given systemId and data.
 * @param {Array.<Object>} psshInfo
 * @returns {Uint8Array}
 */
function createPssh({ systemId, privateData } : IISOBMFFPSSHInfo) : Uint8Array {
  const _systemId = systemId.replace(/-/g, "");

  assert(_systemId.length === 32);
  return createBox("pssh", concat(4, // 4 initial zeroed bytes
                                  hexToBytes(_systemId),
                                  itobe4(privateData.length),
                                  privateData));
}

/**
 * Update ISOBMFF given to add a "pssh" box in the "moov" box for every content
 * protection in the psshList array given.
 * @param {Uint8Array} buf - the ISOBMFF file
 * @param {Array.<Object>} psshList
 * @returns {Uint8Array} - The new ISOBMFF generated.
 */
function patchPssh(buf : Uint8Array, psshList : IISOBMFFPSSHInfo[]) : Uint8Array {
  if (psshList == null || psshList.length === 0) {
    return buf;
  }

  const moovOffsets = getBoxOffsets(buf, 0x6D6F6F76 /* = "moov" */);
  if (moovOffsets === null) {
    return buf;
  }

  const moov = buf.subarray(moovOffsets[0], moovOffsets[2]);
  const moovArr = [moov];
  for (let i = 0; i < psshList.length; i++) {
    moovArr.push(createPssh(psshList[i]));
  }
  const newmoov = updateBoxLength(concat(...moovArr));

  return concat(buf.subarray(0, moovOffsets[0]),
                newmoov,
                buf.subarray(moovOffsets[2]));
}

/**
 * Returns a new version of the given box with the size updated
 * so it reflects its actual size.
 *
 * You can use this function after modifying a ISOBMFF box so its size is
 * updated.
 *
 * /!\ Please consider that this function might mutate the given Uint8Array
 * in place or might create a new one, depending on the current conditions.
 * @param {Uint8Array} buf - The ISOBMFF box
 * @returns {Uint8Array}
 */
function updateBoxLength(buf : Uint8Array) : Uint8Array {
  const newLen = buf.length;
  if (newLen < 4) {
    throw new Error("Cannot update box length: box too short");
  }
  const oldSize = be4toi(buf, 0);
  if (oldSize === 0) {
    if (newLen > MAX_32_BIT_INT) {
      const newBox = new Uint8Array(newLen + 8);
      newBox.set(itobe4(1), 0);
      newBox.set(buf.subarray(4, 8), 4);
      newBox.set(itobe8(newLen + 8), 8);
      newBox.set(buf.subarray(8, newLen), 16);
      return newBox;
    } else {
      buf.set(itobe4(newLen), 0);
      return buf;
    }
  } else if (oldSize === 1) {
    if (newLen < 16) {
      throw new Error("Cannot update box length: box too short");
    }
    buf.set(itobe8(newLen), 8);
    return buf;
  } else if (newLen <= MAX_32_BIT_INT) {
    buf.set(itobe4(newLen), 0);
    return buf;
  } else {
    const newBox = new Uint8Array(newLen + 8);
    newBox.set(itobe4(1), 0);
    newBox.set(buf.subarray(4, 8), 4);
    newBox.set(itobe8(newLen + 8), 8);
    newBox.set(buf.subarray(8, newLen), 16);
    return newBox;
  }
}

/**
 * Parse EMSG boxes from ISOBMFF data.
 * @param {Uint8Array} buffer
 * @returns {Array.<Object> | undefined}
 */
function parseEmsgBoxes(buffer: Uint8Array) : IEMSG[] | undefined {
  const emsgs: IEMSG[] = [];
  let offset = 0;
  while (offset < buffer.length) {
    const emsg = getEMSG(buffer, offset);
    if (emsg === null) {
      break;
    }

    const length = emsg.length;
    offset += length;

    const version = emsg[0];
    if (version !== 0) {
      log.warn("ISOBMFF: EMSG version " + version.toString() + " not supported.");
    } else {
      let position = 4; // skip version + flags

      const { end: schemeIdEnd, string: schemeIdUri } =
        readNullTerminatedString(emsg, position);
      position = schemeIdEnd; // skip schemeIdUri

      const { end: valueEnd, string: value } = readNullTerminatedString(emsg, position);
      position = valueEnd; // skip value

      const timescale = be4toi(emsg, position);
      position += 4; // skip timescale

      const presentationTimeDelta = be4toi(emsg, position);
      position += 4; // skip presentationTimeDelta

      const eventDuration = be4toi(emsg, position);
      position += 4; // skip eventDuration

      const id = be4toi(emsg, position);
      position += 4; // skip id

      const messageData = emsg.subarray(position, length);

      const emsgData = { schemeIdUri,
                         value,
                         timescale,
                         presentationTimeDelta,
                         eventDuration,
                         id,
                         messageData };
      emsgs.push(emsgData);
    }
  }
  if (emsgs.length === 0) {
    return undefined;
  }
  return emsgs;
}

/**
 * @param {Uint8Array} segment
 * @returns {Uint8Array|null}
 */
function getKeyIdFromInitSegment(
  segment: Uint8Array
): Uint8Array | null {
  const stsd = getChildBox(segment, [ 0x6D6F6F76 /* moov */,
                                      0x7472616B /* trak */,
                                      0x6D646961 /* mdia */,
                                      0x6D696E66 /* minf */,
                                      0x7374626C /* stbl */,
                                      0x73747364 /* stsd */ ]);
  if (stsd === null) {
    return null;
  }
  const stsdSubBoxes = stsd.subarray(8);
  let encBox = getBoxContent(stsdSubBoxes, 0x656E6376 /* encv */);
  let encContentOffset = 0;
  if (encBox === null) {
    encContentOffset = 8 + // sample entry header
      8 + // reserved
      2 + // channelcount
      2 + // samplesize
      2 + // predefined
      2 + // reserved
      4; // samplerate
    encBox = getBoxContent(stsdSubBoxes, 0x656E6361 /* enca */);
  } else {
    encContentOffset = 8 + // sample entry header
      2 + 2 + 12 + // predefined + reserved + predefined
      2 + 2 + // width + height
      4 + 4 + // horizresolution + vertresolution
      4 + // reserved
      2 + // frame_count
      32 +
      2 + // depth
      2; // pre-defined;
  }
  if (encBox === null) {
    // There's no encryption data here
    return null;
  }
  const tenc = getChildBox(encBox.subarray(encContentOffset),
                           [ 0x73696e66 /* sinf */,
                             0x73636869 /* schi */,
                             0x74656e63 /* tenc */ ]);
  if (tenc === null || tenc.byteLength < 24) {
    return null;
  }
  return tenc.subarray(8, 24);
}

export {
  getKeyIdFromInitSegment,
  getMDHDTimescale,
  getPlayReadyKIDFromPrivateData,
  getTrackFragmentDecodeTime,
  getDurationFromTrun,
  getSegmentsFromSidx,
  patchPssh,
  updateBoxLength,
  parseEmsgBoxes,
};


text:
<?php
require_once 'tutorial_example_03.php';

$manager = new ezcTranslationManager( $backend );
$manager->addFilter( ezcTranslationBorkFilter::getInstance() );
$search = $manager->getContext( 'nl_NL', 'search' );
$params = array( 'search_string' => 'appelmoes', 'matches' => 4 );
echo $search->getTranslation( "Search for '%search_string' returned %matches matches.", $params ), "\n";

$manager = new ezcTranslationManager( $backend );
$manager->addFilter( ezcTranslationLeetFilter::getInstance() );
$search = $manager->getContext( 'nl_NL', 'search' );
$params = array( 'search_string' => 'appelmoes', 'matches' => 4 );
echo $search->getTranslation( "Search for '%search_string' returned %matches matches.", $params ), "\n";
?>


text:
import { RealTimeEvent } from '../realtimeFacade'

import { Comment } from '../../entities/comment'
import { Requester } from '../requester'

export const commentCreated = (requester: Requester, comment: Comment, cardId: number): RealTimeEvent => (
    {
        type: 'create-comment',
        about: {
            object: 'card',
            id: cardId
        },
        payload: {
            comment,
            requester: requester.getUID()
        }
    }
)

export const commentUpdated = (requester: Requester, comment: Comment, cardId: number): RealTimeEvent => (
    {
        type: 'update-comment',
        about: {
            object: 'card',
            id: cardId
        },
        payload: {
            comment,
            requester: requester.getUID()
        }
    }
)

export const commentDeleted = (requester: Requester, comment: Comment, cardId: number): RealTimeEvent => (
    {
        type: 'delete-comment',
        about: {
            object: 'card',
            id: cardId
        },
        payload: {
            comment,
            requester: requester.getUID()
        }
    }
)


text:
package ee.pri.bcup.common.message.server.game;

import ee.pri.bcup.common.message.server.ServerMessage;

public class ServerGameObserveSuccessfulMessage extends ServerMessage {}


text:
```java
listen1被不断执行
打印很多
Failed to submit a listener notification task. Event loop shut down?
最后自动关闭
```


text:
"use strict";
describe('Unit : Controller - WidgetWeatherCtrl', function () {

// load the controller's module

  var WidgetWeatherCtrl, $timeout, $q, scope, Buildfire, DataStore, TAG_NAMES, STATUS_CODE, ViewStack, $rootScope, uvoInfo, Modals;

  beforeEach(module('skinIndexPluginWidget'));

  beforeEach(inject(function ($controller, _$timeout_, _$q_, _Buildfire_, _DataStore_, _TAG_NAMES_, _STATUS_CODE_, _ViewStack_, _$rootScope_, _Modals_) {

    ViewStack = jasmine.createSpyObj('ViewStack', ['pop', 'push']);
    DataStore = jasmine.createSpyObj('DataStore', ['get', 'save']);
    scope = _$rootScope_.$new();
    $timeout : _$timeout_;
    $q = _$q_;
    uvoInfo = {};
    Buildfire :_Buildfire_;
    Modals:_Modals_;
    ViewStack:ViewStack;
    WidgetWeatherCtrl = $controller('WidgetWeatherCtrl', {

      TAG_NAMES: _TAG_NAMES_,
      DB: _DataStore_,
      $scope: scope,
      ViewStack: ViewStack,
      Buildfire: {
        datastore: {
          onUpdate: function () {

          }
        },
        spinner: {
          show: function () {

          },
          hide: function () {
          }
        },
        uvoInfo: {
          data: {
            design: {}
          }
        }
      }
    });
  }));

  describe('Units: units should be Defined', function () {
    beforeEach(function () {

    });
    it('it should pass if ContentHome is defined', function () {
      DataStore.get.and.callFake(function () {
        var deferred = $q.defer();
        deferred.resolve(deferred.promise);
        return deferred.promise;
      });

      expect(WidgetWeatherCtrl).toBeDefined();
      scope.$digest();
    });

    it(' WidgetWeatherCtrl.resetLocation should be called', function () {
      ViewStack.push({template: {}});
      WidgetWeatherCtrl.resetLocation();

    });

    it(' WidgetWeatherCtrl.error should be called', function () {

      WidgetWeatherCtrl.error({});

    });

    it(' WidgetWeatherCtrl.getWeatherData should be called', function () {
      WidgetWeatherCtrl.data = {
        widget: {
          location_coordinates: [12121, 12212]
        },
        settings: {
          apiKey: '1212121'
        }
      };

      WidgetWeatherCtrl.getWeatherData();
      WidgetWeatherCtrl.errorWeather();
      WidgetWeatherCtrl.successWeather({data: {data: {}}});
    });
  });

});


text:
use darling::{ast::Fields, FromDeriveInput, FromField, FromMeta};
use proc_macro::TokenStream;
use proc_macro2::{Ident, Span};
use quote::{quote, ToTokens};
use syn::{spanned::Spanned, Data, DataStruct, DeriveInput, Generics};

use std::collections::HashSet;

use crate::find_meta_attrs;

#[derive(Debug)]
struct BinaryValueStruct {
    ident: Ident,
    attrs: BinaryValueAttrs,
}

impl FromDeriveInput for BinaryValueStruct {
    fn from_derive_input(input: &DeriveInput) -> darling::Result<Self> {
        let attrs = find_meta_attrs("binary_value", &input.attrs)
            .map(|meta| BinaryValueAttrs::from_nested_meta(&meta))
            .unwrap_or_else(|| Ok(BinaryValueAttrs::default()))?;

        Ok(Self {
            ident: input.ident.clone(),
            attrs,
        })
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Codec {
    Protobuf,
    Bincode,
}

impl Default for Codec {
    fn default() -> Self {
        Codec::Protobuf
    }
}

impl FromMeta for Codec {
    fn from_string(value: &str) -> darling::Result<Self> {
        match value {
            "protobuf" => Ok(Codec::Protobuf),
            "bincode" => Ok(Codec::Bincode),
            _ => {
                let msg = format!(
                    "Unknown codec ({}). Use one of `protobuf` or `bincode`",
                    value
                );
                Err(darling::Error::custom(msg))
            }
        }
    }
}

#[derive(Debug, Default, FromMeta)]
struct BinaryValueAttrs {
    #[darling(default)]
    codec: Codec,
}

#[derive(Debug, FromDeriveInput)]
struct ObjectHashStruct {
    ident: Ident,
}

impl ObjectHashStruct {
    pub fn implement_object_hash(&self) -> impl ToTokens {
        let name = &self.ident;

        quote! {
            impl exonum_merkledb::ObjectHash for #name {
                fn object_hash(&self) -> exonum_merkledb::_reexports::Hash {
                    let bytes = exonum_merkledb::BinaryValue::to_bytes(self);
                    exonum_merkledb::_reexports::hash(&bytes)
                }
            }
        }
    }
}

impl BinaryValueStruct {
    fn implement_binary_value_from_pb(&self) -> proc_macro2::TokenStream {
        let name = &self.ident;

        quote! {
            impl exonum_merkledb::BinaryValue for #name {
                fn to_bytes(&self) -> Vec<u8> {
                    use protobuf::Message as _;
                    // This trait assumes that we work with trusted data so we can unwrap here.
                    exonum_proto::ProtobufConvert::to_pb(self).write_to_bytes().expect(
                        concat!("Failed to serialize `BinaryValue` for ", stringify!(#name))
                    )
                }

                fn from_bytes(
                    value: std::borrow::Cow<[u8]>,
                ) -> std::result::Result<Self, exonum_merkledb::_reexports::Error> {
                    use protobuf::Message as _;

                    let mut block = <Self as exonum_proto::ProtobufConvert>::ProtoStruct::new();
                    block.merge_from_bytes(value.as_ref())?;
                    exonum_proto::ProtobufConvert::from_pb(block)
                }
            }
        }
    }

    fn implement_binary_value_from_bincode(&self) -> proc_macro2::TokenStream {
        let name = &self.ident;

        quote! {
            impl exonum_merkledb::BinaryValue for #name {
                fn to_bytes(&self) -> std::vec::Vec<u8> {
                    bincode::serialize(self).expect(
                        concat!("Failed to serialize `BinaryValue` for ", stringify!(#name))
                    )
                }

                fn from_bytes(
                    value: std::borrow::Cow<[u8]>,
                ) -> std::result::Result<Self, exonum_merkledb::_reexports::Error> {
                    bincode::deserialize(value.as_ref()).map_err(From::from)
                }
            }
        }
    }

    fn implement_binary_value(&self) -> impl ToTokens {
        match self.attrs.codec {
            Codec::Protobuf => self.implement_binary_value_from_pb(),
            Codec::Bincode => self.implement_binary_value_from_bincode(),
        }
    }
}

impl ToTokens for BinaryValueStruct {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        let mod_name = Ident::new(
            &format!("binary_value_impl_{}", self.ident),
            Span::call_site(),
        );

        let binary_value = self.implement_binary_value();
        let expanded = quote! {
            mod #mod_name {
                use super::*;
                #binary_value
            }
        };

        tokens.extend(expanded);
    }
}

impl ToTokens for ObjectHashStruct {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        let object_hash = self.implement_object_hash();
        let expanded = quote! { #object_hash };

        tokens.extend(expanded);
    }
}

pub fn impl_binary_value(input: TokenStream) -> TokenStream {
    let input: DeriveInput = syn::parse(input).unwrap();

    let db_object = BinaryValueStruct::from_derive_input(&input)
        .unwrap_or_else(|e| panic!("BinaryValue: {}", e));
    let tokens = quote! { #db_object };
    tokens.into()
}

pub fn impl_object_hash(input: TokenStream) -> TokenStream {
    let input: DeriveInput = syn::parse(input).unwrap();

    let db_object =
        ObjectHashStruct::from_derive_input(&input).unwrap_or_else(|e| panic!("ObjectHash: {}", e));
    let tokens = quote! { #db_object };
    tokens.into()
}

/// Checks that an ASCII character is allowed in the `IndexAddress` component.
pub fn is_allowed_component_char(c: u8) -> bool {
    matches!(c, b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z' | b'-' | b'_')
}

fn validate_address_component(name: &str) -> Result<(), String> {
    if name.is_empty() {
        return Err("Name shouldn't be empty".to_owned());
    }
    if !name
        .as_bytes()
        .iter()
        .copied()
        .all(is_allowed_component_char)
    {
        return Err(format!(
            "Name `{}` contains invalid chars (allowed: `A-Z`, `a-z`, `0-9`, `_` and `-`)",
            name
        ));
    }
    Ok(())
}

#[derive(Debug)]
struct FromAccess {
    ident: Ident,
    access_ident: Ident,
    fields: Vec<AccessField>,
    generics: Generics,
    attrs: FromAccessAttrs,
}

#[derive(Debug, Default, FromMeta)]
struct FromAccessAttrs {
    #[darling(default)]
    transparent: bool,
}

#[derive(Debug, Default, FromMeta)]
struct FromAccessFieldAttrs {
    #[darling(default)]
    rename: Option<String>,
    #[darling(default)]
    flatten: bool,
}

impl FromAccess {
    fn extract_access_ident(generics: &syn::Generics) -> darling::Result<&Ident> {
        use syn::{TraitBound, TypeParamBound};

        for type_param in generics.type_params() {
            if type_param
                .attrs
                .iter()
                .any(|attr| attr.path.is_ident("from_access"))
            {
                return Ok(&type_param.ident);
            }
        }

        for type_param in generics.type_params() {
            for bound in type_param.bounds.iter() {
                if let TypeParamBound::Trait(TraitBound { path, .. }) = bound {
                    if path.is_ident("Access") {
                        return Ok(&type_param.ident);
                    }
                }
            }
        }

        // No type params with the overt attribute or `T: Access` constraint.
        let mut params = generics.type_params();
        let type_param = params.next().ok_or_else(|| {
            darling::Error::custom("`FromAccess` struct should be generic over `Access` type")
        })?;
        if params.next().is_some() {
            let msg = "Cannot find type param implementing `Access` trait. \
                       You may mark it explicitly with `#[from_access]`";
            let e = darling::Error::custom(msg);
            Err(e)
        } else {
            // If there is a single type param, we hope it's the correct one.
            Ok(&type_param.ident)
        }
    }
}

impl FromDeriveInput for FromAccess {
    fn from_derive_input(input: &syn::DeriveInput) -> darling::Result<Self> {
        let attrs = find_meta_attrs("from_access", &input.attrs)
            .map(|meta| FromAccessAttrs::from_nested_meta(&meta))
            .unwrap_or_else(|| Ok(FromAccessAttrs::default()))?;

        match &input.data {
            Data::Struct(DataStruct { fields, .. }) => {
                let this = Self {
                    ident: input.ident.clone(),
                    access_ident: Self::extract_access_ident(&input.generics)?.clone(),
                    generics: input.generics.clone(),
                    fields: Fields::try_from(fields)?.fields,
                    attrs,
                };

                if this.attrs.transparent {
                    if this.fields.len() != 1 {
                        let e = darling::Error::custom(
                            "Transparent struct must contain a single field",
                        );
                        return Err(e);
                    }
                } else {
                    let mut field_names = HashSet::new();

                    for field in &this.fields {
                        if let Some(ref name) = field.name_suffix {
                            validate_address_component(name).map_err(|msg| {
                                darling::Error::custom(msg).with_span(&field.span)
                            })?;
                            if !field_names.insert(name) {
                                let e = "Duplicate field name";
                                return Err(darling::Error::custom(e).with_span(&field.span));
                            }
                        } else if !field.flatten {
                            let msg = if this.fields.len() == 1 {
                                "Unnamed fields necessitate #[from_access(rename = ...)]. \
                                 To use a wrapper, add #[from_access(transparent)] to the struct"
                            } else {
                                "Unnamed fields necessitate #[from_access(rename = ...)]"
                            };
                            let e = darling::Error::custom(msg).with_span(&field.span);
                            return Err(e);
                        }
                    }
                }
                Ok(this)
            }
            _ => Err(darling::Error::unsupported_shape(
                "`FromAccess` can be only implemented for structs",
            )),
        }
    }
}

#[derive(Debug)]
struct AccessField {
    span: Span,
    ident: Option<Ident>,
    name_suffix: Option<String>,
    flatten: bool,
}

impl FromField for AccessField {
    fn from_field(field: &syn::Field) -> darling::Result<Self> {
        let ident = field.ident.clone();

        let attrs = find_meta_attrs("from_access", &field.attrs)
            .map(|meta| FromAccessFieldAttrs::from_nested_meta(&meta))
            .unwrap_or_else(|| Ok(FromAccessFieldAttrs::default()))?;

        let name_suffix = attrs
            .rename
            .or_else(|| ident.as_ref().map(ToString::to_string));
        Ok(Self {
            ident,
            name_suffix,
            span: field.span(),
            flatten: attrs.flatten,
        })
    }
}

impl AccessField {
    fn ident(&self, field_index: usize) -> impl ToTokens {
        if let Some(ref ident) = self.ident {
            quote!(#ident)
        } else {
            let field_index = syn::Index::from(field_index);
            quote!(#field_index)
        }
    }

    fn constructor(&self, field_index: usize) -> impl ToTokens {
        let from_access = quote!(exonum_merkledb::access::FromAccess);
        let ident = self.ident(field_index);
        if self.flatten {
            quote!(#ident: #from_access::from_access(access.clone(), addr.clone())?)
        } else {
            let name = self.name_suffix.as_ref().unwrap();
            quote!(#ident: #from_access::from_access(access.clone(), addr.clone().append_name(#name))?)
        }
    }

    fn root_constructor(&self, field_index: usize) -> impl ToTokens {
        let from_access = quote!(exonum_merkledb::access::FromAccess);
        let ident = self.ident(field_index);
        if self.flatten {
            quote!(#ident: #from_access::from_root(access.clone())?)
        } else {
            let name = &self.name_suffix;
            quote!(#ident: #from_access::from_access(access.clone(), #name.into())?)
        }
    }
}

impl FromAccess {
    fn access_fn(&self) -> impl ToTokens {
        let fn_impl = if self.attrs.transparent {
            let from_access = quote!(exonum_merkledb::access::FromAccess);
            let ident = self.fields[0].ident(0);
            quote!(Ok(Self { #ident: #from_access::from_access(access, addr)? }))
        } else {
            let field_constructors = self
                .fields
                .iter()
                .enumerate()
                .map(|(i, field)| field.constructor(i));
            quote!(Ok(Self { #(#field_constructors,)* }))
        };

        let access_ident = &self.access_ident;
        quote! {
            fn from_access(
                access: #access_ident,
                addr: exonum_merkledb::IndexAddress,
            ) -> Result<Self, exonum_merkledb::access::AccessError> {
                #fn_impl
            }
        }
    }

    fn root_fn(&self) -> impl ToTokens {
        let fn_impl = if self.attrs.transparent {
            let from_access = quote!(exonum_merkledb::access::FromAccess);
            let ident = self.fields[0].ident(0);
            quote!(Ok(Self { #ident: #from_access::from_root(access)? }))
        } else {
            let field_constructors = self
                .fields
                .iter()
                .enumerate()
                .map(|(i, field)| field.root_constructor(i));
            quote!(Ok(Self { #(#field_constructors,)* }))
        };

        let access_ident = &self.access_ident;
        quote! {
            fn from_root(
                access: #access_ident,
            ) -> Result<Self, exonum_merkledb::access::AccessError> {
                #fn_impl
            }
        }
    }
}

impl ToTokens for FromAccess {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        let name = &self.ident;
        let tr = quote!(exonum_merkledb::access::FromAccess);
        let access_ident = &self.access_ident;
        let (impl_generics, ty_generics, where_clause) = self.generics.split_for_impl();

        let from_access_fn = self.access_fn();
        let from_root_fn = self.root_fn();

        let expanded = quote! {
            impl #impl_generics #tr<#access_ident> for #name #ty_generics #where_clause {
                #from_access_fn
                #from_root_fn
            }
        };
        tokens.extend(expanded);
    }
}

pub fn impl_from_access(input: TokenStream) -> TokenStream {
    let input: DeriveInput = syn::parse(input).unwrap();
    let from_access = match FromAccess::from_derive_input(&input) {
        Ok(access) => access,
        Err(e) => return e.write_errors().into(),
    };
    let tokens = quote!(#from_access);
    tokens.into()
}


text:
A place where we can discuss and work with audio precision.

2016-01-15 - Generated the following file: https://archive.org/details/72MinuteAudioFileWithTonesAt7SecondIntervals
This is a 72 minute FLAC file generated by Matlab at 44.1kHz/16bit with a tone exactly every 7 seconds.


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SimpleCrm.Facade;
using SimpleCrm.DTO;
using SimpleCrm.Utils;
using SimpleCrm.Model;
using SimpleCrm.InsuranceForm;

namespace SimpleCrm.CustomerForm
{
    public partial class CustomerPickListForm : SimpleCrm.BaseForm
    {
        public CustomerSearchResultDto CustomerDto { get; set; }

        public CustomerPickListForm()
        {
            InitializeComponent();
        }

        private void CustomerMainForm_Load(object sender, EventArgs e)
        {
            InitForm();
        }

        private void InitForm()
        {
            ComboBoxUtil.BindLov(LovType.CustomerClass, cmbCustomerClass);
            ComboBoxUtil.BindLov(LovType.CustomerSource, cmbCustomerSource);
            ComboBoxUtil.BindLov(LovType.IntentPhase, cmbIntentPhase);
            ComboBoxUtil.BindLov(LovType.CustomerStatus, cmbCustomerStatus);

            ComboBoxUtil.BindLov(LovType.CustomerClass, colCustomerClass);
            ComboBoxUtil.BindLov(LovType.CustomerSource, colCustomerSource);
            ComboBoxUtil.BindLov(LovType.IntentPhase, colIntentPhase);
            ComboBoxUtil.BindLov(LovType.CustomerStatus, colStatus);

            ComboBoxUtil.BindEnumType(typeof(GenderType), colGender);
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                SearchData();
            }
            catch (Exception ex)
            {
                ExceptionHelper.HandleException(ex);
            }
        }

        private void SearchData()
        {
            CustomerSearchParamDto param = new CustomerSearchParamDto();
            dataBindingParam.MapToObject(param);

            BaseSearchResultDto<CustomerSearchResultDto> searchResult = AppFacade.Facade.SearchCustomer(param);
            if (searchResult.Results != null)
            {
                grdResult.DataSource = searchResult.Results;
            }
        }

        private void grdResult_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            CustomerSearchResultDto dto = grdResult.Rows[e.RowIndex].DataBoundItem as CustomerSearchResultDto;
            if (dto != null)
            {
                this.CustomerDto = dto;
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                this.Close();
            }
        }
    }
}


text:
package com.navercorp.pinpoint.collector.cluster;

import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.navercorp.pinpoint.collector.receiver.tcp.AgentHandshakePropertyType;
import com.navercorp.pinpoint.rpc.Future;
import com.navercorp.pinpoint.rpc.server.PinpointServer;
import com.navercorp.pinpoint.rpc.util.AssertUtils;
import com.navercorp.pinpoint.rpc.util.MapUtils;

/**
 * @author koo.taejin
 */
public class PinpointServerClusterPoint implements TargetClusterPoint {

    private final PinpointServer pinpointServer;

    private final String applicationName;
    private final String agentId;
    private final long startTimeStamp;

    private final String version;

    public PinpointServerClusterPoint(PinpointServer pinpointServer) {
        AssertUtils.assertNotNull(pinpointServer, "pinpointServer may not be null.");
        this.pinpointServer = pinpointServer;

        Map<Object, Object> properties = pinpointServer.getChannelProperties();
        this.version = MapUtils.getString(properties, AgentHandshakePropertyType.VERSION.getName());
        AssertUtils.assertTrue(!StringUtils.isBlank(version), "Version may not be null or empty.");

        this.applicationName = MapUtils.getString(properties, AgentHandshakePropertyType.APPLICATION_NAME.getName());
        AssertUtils.assertTrue(!StringUtils.isBlank(applicationName), "ApplicationName may not be null or empty.");

        this.agentId = MapUtils.getString(properties, AgentHandshakePropertyType.AGENT_ID.getName());
        AssertUtils.assertTrue(!StringUtils.isBlank(agentId), "AgentId may not be null or empty.");

        this.startTimeStamp = MapUtils.getLong(properties, AgentHandshakePropertyType.START_TIMESTAMP.getName());
        AssertUtils.assertTrue(startTimeStamp > 0, "StartTimeStamp is must greater than zero.");
    }

    @Override
    public void send(byte[] payload) {
        pinpointServer.send(payload);
    }

    @Override
    public Future request(byte[] payload) {
        return pinpointServer.request(payload);
    }

    @Override
    public String getApplicationName() {
        return applicationName;
    }

    @Override
    public String getAgentId() {
        return agentId;
    }

    public long getStartTimeStamp() {
        return startTimeStamp;
    }

    @Override
    public String gerVersion() {
        return version;
    }

    public PinpointServer getPinpointServer() {
        return pinpointServer;
    }

    @Override
    public String toString() {
        StringBuilder log = new StringBuilder(32);
        log.append(this.getClass().getSimpleName());
        log.append("(");
        log.append(applicationName);
        log.append("/");
        log.append(agentId);
        log.append("/");
        log.append(startTimeStamp);
        log.append(")");
        log.append(", version:");
        log.append(version);
        log.append(", pinpointServer:");
        log.append(pinpointServer);

        return log.toString();
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 17;

        result = prime * result + ((applicationName == null) ? 0 : applicationName.hashCode());
        result = prime * result + ((agentId == null) ? 0 : agentId.hashCode());
        result = prime * result + (int) (startTimeStamp ^ (startTimeStamp >>> 32));
        result = prime * result + ((version == null) ? 0 : version.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if (!(obj instanceof PinpointServerClusterPoint)) {
            return false;
        }

        if (this.getPinpointServer() == ((PinpointServerClusterPoint) obj).getPinpointServer()) {
            return true;
        }

        return false;
    }

}


text:
export type Color = number[];
export function asArray(color: Color | string): Color;
export function asString(color: Color | string): string;
export function normalize(color: Color): Color;
export function toString(color: Color): string;


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
 Copyright (C) 2008 ZXing authors

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:keepScreenOn="true" >

    <SurfaceView
        android:id="@+id/preview_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <com.github.barcodeeye.scan.ui.ViewfinderView
        android:id="@+id/viewfinder_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <TextView android:id="@+id/status_view"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_gravity="bottom|center_horizontal"
          android:background="@color/transparent"
          android:text="@string/msg_default_status"
          android:textColor="@color/status_text"/>

</RelativeLayout>


text:
	<?php $this->load->view('messages/sidebar'); ?>

Inbox

						<?php
						if($messages):
						foreach($messages as $message): ?>

								<?php if($message->important == "Yes"): ?>
									<a href="<?php echo base_url('Messages/markUnimportant/' . $message->id); ?>">
								<?php else: ?>
									<a href="<?php echo base_url('Messages/markImportant/' . $message->id); ?>">
								<?php endif; ?>
								<a href="<?php echo base_url('Messages/show/' . $message->id); ?>">From: <?php echo $message->from_user; ?>
								<?php $truncated = (strlen($message->description) > 40) ? substr($message->description, 0, 40) . '...' : $message->description; ?>
								<?php echo $message->subject; ?> - <?php echo strip_tags($truncated); ?>

								<?php echo date('F j, Y, g:i a', strtotime($message->created_on)); ?>

									<?php if($message->message_read == 'Yes'): ?>
										<?php echo $message->message_read; ?>
									<?php elseif($message->message_read == 'No'): ?>
										<?php echo $message->message_read; ?>
									<?php else: ?>
										Something is wrong...
									<?php endif; ?>

						<?php
							endforeach;
						else:
						?>

								No Messages

						<?php endif; ?>


text:
""" Module defining annotations.

This module contains two classes:

    1. :class:`~pypet.annotations.Annotations`

        Container class for annotations. There are no restrictions regarding what is considered
        to be an annotation. In principle, this can be any python object. However,
        if using the standard :class:`~pypet.storageservice.HDF5StorageService`,
        these annotations are stored as hdf5 node attributes.
        Accordingly, annotations should be rather small since reading
        and writing these attributes to disk is slow.

    2. :class:`~pypet.annotations.WithAnnotations`

        Abstract class to subclass from. Instances that subclass `WithAnnotations`
        have the `v_annotations` property which is an instance of the `Annotations` class
        to handle annotations. They also acquire some functions to put annotations directly
        into the `v_annotations` object like `f_set_annotations`.

"""

__author__ = 'Robert Meyer'

from pypet.pypetlogging import HasLogger
from pypet.slots import HasSlots

class Annotations(HasSlots):
    """ Simple container class for annotations.

    Every tree node (*leaves* and *group* nodes) can be annotated.
    In case you use the standard :class:`~pypet.storageservice.HDF5StorageService`,
    these annotations are stored in the attributes of the hdf5 nodes in the hdf5 file,
    you might wanna take a look at pytables attributes_.

    Annotations should be small (short strings or basic python data types) since their storage
    and retrieval is quite slow!

    .. _attributes: http://pytables.github.io/usersguide/libref/declarative_classes.html#the-attributeset-class

    """
    __slots__ = ('_dict_',)

    def __init__(self):
        self._dict_ = None

    @property
    def _dict(self):
        if self._dict_ is None:
            self._dict_ = {}
        return self._dict_

    def __iter__(self):
        return self._dict.__iter__()

    def __getitem__(self, item):
        """Equivalent to calling f_get()"""
        return self.f_get(item)

    def __setitem__(self, key, value):
        """Almost equivalent to calling __setattr__.

        Treats integer values as `f_get`.

        """
        self.f_set(**{key: value})

    def __delitem__(self, key):
        self.f_remove(key)

    def f_to_dict(self, copy=True):
        """Returns annotations as dictionary.

        :param copy: Whether to return a shallow copy or the real thing (aka _dict).

        """
        if copy:
            return self._dict.copy()
        else:
            return self._dict

    def f_is_empty(self):
        """Checks if annotations are empty"""
        return len(self._dict) == 0

    def f_empty(self):
        """Removes all annotations from RAM """
        self._dict_ = None

    def __setattr__(self, key, value):
        if key.startswith('_'):
            # We set a private attribute
            super(Annotations, self).__setattr__(key, value)
        else:
            self.f_set_single(key, value)

    def __getattr__(self, item):
        return self.f_get(item)

    def __delattr__(self, item):
        self.f_remove(item)

    def _translate_key(self, key):
        if isinstance(key, int):
            if key == 0:
                key = 'annotation'
            else:
                key = 'annotation_%d' % key
        return key

    def f_get(self, *args):
        """Returns annotations

        If len(args)>1, then returns a list of annotations.

        `f_get(X)` with *X* integer will return the annotation with name `annotation_X`.

        If the annotation contains only a single entry you can call `f_get()` without arguments.
        If you call `f_get()` and the annotation contains more than one element a ValueError is
        thrown.

        """

        if len(args) == 0:
            if len(self._dict) == 1:
                return self._dict[list(self._dict.keys())[0]]
            elif len(self._dict) > 1:
                raise ValueError('Your annotation contains more than one entry: '
                                 '`%s` Please use >>f_get<< with one of these.' %
                                 (str(list(self._dict.keys()))))
            else:
                raise AttributeError('Your annotation is empty, cannot access data.')

        result_list = []
        for name in args:
            name = self._translate_key(name)
            try:
                result_list.append(self._dict[name])
            except KeyError:
                raise AttributeError('Your annotation does not contain %s.' % name)

        if len(args) == 1:
            return result_list[0]
        else:
            return tuple(result_list)

    def f_set(self, *args, **kwargs):
        """Sets annotations

        Items in args are added as `annotation` and `annotation_X` where
        'X' is the position in args for following arguments.

        """
        for idx, arg in enumerate(args):
            valstr = self._translate_key(idx)
            self.f_set_single(valstr, arg)

        for key, arg in kwargs.items():
            self.f_set_single(key, arg)

    def f_remove(self, key):
        """Removes `key` from annotations"""
        key = self._translate_key(key)
        try:
            del self._dict[key]
        except KeyError:
            raise AttributeError('Your annotations do not contain %s' % key)

    def f_set_single(self, name, data):
        """ Sets a single annotation. """
        self._dict[name] = data

    def f_ann_to_str(self):
        """Returns all annotations lexicographically sorted as a concatenated string."""
        resstr = ''
        for key in sorted(self._dict.keys()):
            resstr += '%s=%s; ' % (key, str(self._dict[key]))
        return resstr[:-2]

    def __str__(self):
        return self.f_ann_to_str()

class WithAnnotations(HasLogger):

    __slots__ = ('_annotations',)

    def __init__(self):
        self._annotations = Annotations()  # The annotation object to handle annotations

    @property
    def v_annotations(self):
        """ Annotation feature of a trajectory node.

        Store some short additional information about your nodes here.
        If you use the standard HDF5 storage service, they will be stored as hdf5 node
        attributes_.

        .. _attributes: http://pytables.github.io/usersguide/libref/declarative_classes.html#the-attributeset-class

        """
        return self._annotations

    def f_set_annotations(self, *args, **kwargs):
        """Sets annotations

        Equivalent to calling `v_annotations.f_set(*args,**kwargs)`

        """
        self._annotations.f_set(*args, **kwargs)

    def f_get_annotations(self, *args):
        """Returns annotations

        Equivalent to `v_annotations.f_get(*args)`

        """
        return self._annotations.f_get(*args)

    def f_ann_to_str(self):
        """Returns annotations as string

        Equivalent to `v_annotations.f_ann_to_str()`

        """
        return self._annotations.f_ann_to_str()


text:
import webpack from 'webpack';
import path from 'path';
import HtmlWebpackPlugin from 'html-webpack-plugin';

const GLOBALS = {
  'process.env.NODE_ENV': JSON.stringify('development'),
  __DEV__: true
};

export default {
  debug: true,
  devtool: 'cheap-module-eval-source-map', // more info:https://webpack.github.io/docs/build-performance.html#sourcemaps and https://webpack.github.io/docs/configuration.html#devtool
  noInfo: true, // set to false to see a list of every file being bundled.
  entry: [
    'webpack-hot-middleware/client?reload=true',
    './src/index'
  ],
  target: 'web', // necessary per https://webpack.github.io/docs/testing.html#compile-and-test
  output: {
    path: `${__dirname}/dist`, // Note: Physical files are only output by the production build task `npm run build`.
    publicPath: 'http://localhost:5001/', // Use absolute paths to avoid the way that URLs are resolved by Chrome when they're parsed from a dynamically loaded CSS blob. Note: Only necessary in Dev.
    filename: 'bundle.js'
  },
  plugins: [
    new webpack.DefinePlugin(GLOBALS), // Tells React to build in prod mode. https://facebook.github.io/react/downloads.html
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    new HtmlWebpackPlugin({     // Create HTML file that includes references to bundled CSS and JS.
      template: 'src/index.ejs',
      inject: true
    })
  ],
  module: {
    loaders: [
      {test: /\.js$/, include: path.join(__dirname, 'src'), loaders: ['babel']},
      {test: /\.eot(\?v=\d+.\d+.\d+)?$/, loader: 'file'},
      {test: /\.(woff|woff2)$/, loader: 'file-loader?prefix=font/&limit=5000'},
      {test: /\.ttf(\?v=\d+.\d+.\d+)?$/, loader: 'file-loader?limit=10000&mimetype=application/octet-stream'},
      {test: /\.svg(\?v=\d+.\d+.\d+)?$/, loader: 'file-loader?limit=10000&mimetype=image/svg+xml'},
      {test: /\.(jpe?g|png|gif)$/i, loaders: ['file']},
      {test: /\.ico$/, loader: 'file-loader?name=[name].[ext]'},
      {test: /(\.css|\.less)$/, loaders: ['style', 'css?sourceMap', 'less?sourceMap']}
    ]
  }
};


text:
Modularity is at the core of **http4k**. The API is very unopinionated and designed to allow the user to use as much
or as little of it as desired.

Minimal usage requires the `http4k-core` module, which has ZERO external dependencies. Other modules only bring in the
minimum of dependencies in order to work. For instance, the Jetty Server backend `http4k-server-jetty` only brings in
the `jetty-server` and `jetty-servlet` modules.


text:
Ui.LBox.extend('KJing.VideoPlayer', {
	media: undefined,
	scroll: undefined,
	playButton: undefined,
	mediaBar: undefined,
	controlsVisible: true,

	constructor: function(config) {
		this.addEvents('statechange', 'end', 'timeupdate', 'transform');

		this.scroll = new Ui.ScrollingArea({ maxScale: 4 });
		this.connect(this.scroll, 'scroll', function(s)  {
			this.fireEvent('transform', this, this.getContentTransform());
		});
		this.append(this.scroll);

		this.media = new Ui.Video();
		this.scroll.setContent(this.media);

		this.connect(this.media, 'statechange', this.onMediaStateChange);
		this.connect(this.media, 'timeupdate', this.onMediaTimeUpdate);
		this.connect(this.media, 'ended', this.onMediaEnd);

		var pressable = new Ui.Pressable({ verticalAlign: 'center', horizontalAlign: 'center' });
		this.connect(pressable, 'press', this.onPlayButtonPress);
		this.playButton = new KJing.PlayButton({ mode: 'play', width: 80, height: 80 });
		pressable.setContent(this.playButton);
		this.append(pressable);

		this.mediaBar = new KJing.MediaPlayBar({ media: this.media, verticalAlign: 'bottom' });
		this.append(this.mediaBar);
	},

	getIsDown: function() {
		return this.scroll.getIsDown();
	},

	getIsInertia: function() {
		return this.scroll.getIsInertia();
	},

	getContentTransform: function() {
		return {
			x: -this.scroll.getRelativeOffsetX(),
			y: -this.scroll.getRelativeOffsetY(),
			scale: this.scroll.getScale()
		};
	},

	setContentTransform: function(transform) {
		this.scroll.setScale(transform.scale);
		this.scroll.setOffset(-transform.x, -transform.y, false);
	},

	setSrc: function(src) {
		this.media.setSrc(src);
	},

	setPoster: function(poster) {
		this.media.setPoster(poster);
	},

	pause: function() {
		this.media.pause();
	},

	play: function() {
		this.media.play();
	},

	getState: function() {
		return this.media.getState();
	},

	getDuration: function() {
		return this.media.getDuration();
	},

	getCurrentTime: function() {
		return this.media.getCurrentTime();
	},

	setCurrentTime: function(time) {
		this.media.setCurrentTime(time);
	},

	getVolume: function() {
		this.media.getVolume();
	},

	setVolume: function(volume) {
		this.media.setVolume(volume);
	},

	getIsControlsVisible: function() {
		return this.controlsVisible;
	},

	showControls: function() {
		this.controlsVisible = true;
		this.playButton.show();
		this.mediaBar.show();
	},

	hideControls: function() {
		this.controlsVisible = false;
		this.playButton.hide();
		this.mediaBar.hide();
	},

	onMediaEnd: function(media) {
		this.fireEvent('end', this);
	},

	onMediaTimeUpdate: function(media) {
		this.fireEvent('timeupdate', this, media.getCurrentTime(), media.getDuration());
	},

	onMediaStateChange: function(media, state) {
		//console.log(this+'.onMediaStateChange state: '+state);

		if(state == 'playing') {
			this.hideControls();
			this.playButton.setMode('pause');
		}
		else if((state == 'paused') || (state == 'initial')) {
			this.showControls();
			this.playButton.setMode('play');
		}
		else if(state == 'buffering') {
			this.showControls();
			this.playButton.setMode('load');
		}
		this.fireEvent('statechange', this, state);
	},

	onPlayButtonPress: function() {
		var state = this.media.getState();
		//console.log('onPlayButtonPress state: '+state);
		if(state === 'playing')
			this.media.pause();
		else if(state === 'paused')
			this.media.play();
		else if(state === 'buffering')
			this.media.pause();
		else if(state === 'initial')
			this.media.play();
	}
});


text:
<?php

namespace Application\Migrations;

use Doctrine\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
class Version20170330130308 extends AbstractMigration
{
    /**
     * @param Schema $schema
     */
    public function up(Schema $schema)
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf('mysql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('DROP TABLE odp_huurder_afsluitingen');
        $this->addSql('DROP TABLE odp_huurovereenkomst_afsluitingen');
        $this->addSql('DROP TABLE odp_verhuurder_afsluiting');
        $this->addSql('ALTER TABLE odp_huurovereenkomsten CHANGE afsluitdatum einddatum DATE DEFAULT NULL');
        $this->addSql('ALTER TABLE odp_huurovereenkomsten ADD afsluitdatum DATE DEFAULT NULL');
    }

    /**
     * @param Schema $schema
     */
    public function down(Schema $schema)
    {
        $this->throwIrreversibleMigrationException();
    }
}


text:
package com.business.domain.repository;

import com.business.domain.Purchase;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

/**
 * Created by billb on 2015-04-15.
 */
@RepositoryRestResource(path = "purchaserest")
public interface PurchaseRepository extends PagingAndSortingRepository<Purchase, String>, JpaSpecificationExecutor {

    Page<Purchase> findByUsername(@Param("username") String name, Pageable pageable);

    Page<Purchase> findByFlag(@Param("flag") int flag, Pageable pageable);

    Page<Purchase> findByFlagGreaterThan(@Param("flag") int flag, Pageable pageable);

    Page<Purchase> findAll(Specification spec, Pageable pageable);

}


text:
package ram

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// UpdateRole invokes the ram.UpdateRole API synchronously
// api document: https://help.aliyun.com/api/ram/updaterole.html
func (client *Client) UpdateRole(request *UpdateRoleRequest) (response *UpdateRoleResponse, err error) {
	response = CreateUpdateRoleResponse()
	err = client.DoAction(request, response)
	return
}

// UpdateRoleWithChan invokes the ram.UpdateRole API asynchronously
// api document: https://help.aliyun.com/api/ram/updaterole.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) UpdateRoleWithChan(request *UpdateRoleRequest) (<-chan *UpdateRoleResponse, <-chan error) {
	responseChan := make(chan *UpdateRoleResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.UpdateRole(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// UpdateRoleWithCallback invokes the ram.UpdateRole API asynchronously
// api document: https://help.aliyun.com/api/ram/updaterole.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) UpdateRoleWithCallback(request *UpdateRoleRequest, callback func(response *UpdateRoleResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *UpdateRoleResponse
		var err error
		defer close(result)
		response, err = client.UpdateRole(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// UpdateRoleRequest is the request struct for api UpdateRole
type UpdateRoleRequest struct {
	*requests.RpcRequest
	NewAssumeRolePolicyDocument string           `position:"Query" name:"NewAssumeRolePolicyDocument"`
	RoleName                    string           `position:"Query" name:"RoleName"`
	NewMaxSessionDuration       requests.Integer `position:"Query" name:"NewMaxSessionDuration"`
}

// UpdateRoleResponse is the response struct for api UpdateRole
type UpdateRoleResponse struct {
	*responses.BaseResponse
	RequestId string           `json:"RequestId" xml:"RequestId"`
	Role      RoleInUpdateRole `json:"Role" xml:"Role"`
}

// CreateUpdateRoleRequest creates a request to invoke UpdateRole API
func CreateUpdateRoleRequest() (request *UpdateRoleRequest) {
	request = &UpdateRoleRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("Ram", "2015-05-01", "UpdateRole", "Ram", "openAPI")
	return
}

// CreateUpdateRoleResponse creates a response to parse from UpdateRole response
func CreateUpdateRoleResponse() (response *UpdateRoleResponse) {
	response = &UpdateRoleResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
/*
 * SerialComms.h
 *
 *  Created on:   July 20, 2014
 *      Author:   Alon Yaari
 *      BASED ON:
 *          arduino-serial-lib -- simple library for reading/writing serial ports
 *          2006-2013, Tod E. Kurt, http://todbot.com/blog/
 *
 */

#ifndef SERIALCOMMS_H_
#define SERIALCOMMS_H_

#include <stdint.h>   // Standard types
#include <deque>
#include "MOOS/libMOOS/MOOSLib.h"

#define BUF_SIZE 1024
#define TIMEOUT  30000      // 30 seconds (in ms)

class SerialComms {

public:
                SerialComms(std::string port, int baud, std::string& errMsg);
    virtual     ~SerialComms() {};
    bool        Run();
    static bool dispatch(void* param);

    void        Set_Delims(char beg, char end, std::string ignore);
    bool        IsListening() { return bGoodSerialComms; };
    std::string GetNextSentence();
    bool        WriteToSerialPort(std::string str);
    bool        SerialLoop();
    bool        IsGoodSerialComms() { return bGoodSerialComms; };
    int         DataAvailable();
    int         serialport_flush();

private:
    bool        serialport_init(const char* serialport, int baud, std::string& errMsg);
    int         serialport_close();
    int         serialport_writebyte(uint8_t b, std::string& errMsg);
    int         serialport_write(const char* str, std::string& errMsg);
    bool        SerialIncoming(std::string& errMsg);
    void        AddToProcessingQueue(std::string& str);
    std::string GetLastErrorMsg();

    CMOOSThread serialThread;

    char        m_char_beg;
    char        m_char_end;
    std::string m_ignore;
    bool        bGoodSerialComms;
    int         fd;
    bool        bQuit;
    std::string lastErrorMsg;
    std::deque<std::string>   inLines;
    char        buf[BUF_SIZE];
    std::string strBuf;
};

#endif

//


text:
using System.Configuration;
using System.Diagnostics.CodeAnalysis;
using ProviderModel.Configuration;

namespace Cachengue.Configuration
{
    /// <summary>
    /// Caching configuration section handler
    /// </summary>
    public class CachingSectionHandler : ProviderSectionHandler, ICacheSettings
    {
        /// <summary>
        /// The name of the caching section
        /// </summary>
        [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "NAME", Justification = "Supported by conventions")]
        [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Supported by conventions")]
        [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SECTION", Justification = "Supported by conventions")]
        public const string SECTION_NAME = "cinchcast.framework.caching";

        private static CachingSectionHandler _section;

        /// <summary>
        /// Gets the default absolute expiration minutes.
        /// </summary>
        /// <value>
        /// The default absolute expiration minutes.
        /// </value>
        [ConfigurationProperty("defaultAbsoluteExpirationSeconds", DefaultValue = 1800)]
        public int DefaultAbsoluteExpirationSeconds
        {
            get { return (int)base["defaultAbsoluteExpirationSeconds"]; }
        }

        /// <summary>
        /// Gets a value indicating whether caching is enabled is enabled.
        /// </summary>
        /// <value>
        ///   <c>true</c> if enabled; otherwise, <c>false</c>.
        /// </value>
        [ConfigurationProperty("enabled", DefaultValue = true)]
        public bool Enabled
        {
            get { return (bool)base["enabled"]; }
        }

        /// <summary>
        /// Gets the max fail attempts before disabling the cache.
        /// </summary>
        /// <value>
        /// The max fail attempts.
        /// </value>
        [ConfigurationProperty("maxFailAttempts", DefaultValue = 10)]
        public int MaxFailAttempts
        {
            get { return (int)base["maxFailAttempts"]; }
        }

        /// <summary>
        /// Gets the max retry attempts at connecting to the cache provider
        /// </summary>
        /// <value>
        /// The max retry attempts.
        /// </value>
        [ConfigurationProperty("maxRetryAttempts", DefaultValue = 100)]
        public int MaxRetryAttempts
        {
            get { return (int)base["maxRetryAttempts"]; }
        }

        /// <summary>
        /// Gets a value indicating whether [enable logging].
        /// </summary>
        /// <value>
        ///   <c>true</c> if [enable logging]; otherwise, <c>false</c>.
        /// </value>
        [ConfigurationProperty("verboseLogging", DefaultValue = false)]
        public bool VerboseLogging
        {
            get { return (bool)base["verboseLogging"]; }
        }

        /// <summary>
        /// Gets the serializer.
        /// </summary>
        /// <value>
        /// The serializer.
        /// </value>
        [ConfigurationProperty("serializer", DefaultValue = "json")]
        public string Serializer
        {
            get { return (string)base["serializer"]; }
        }

        /// <summary>
        /// Gets the statistics.
        /// </summary>
        /// <value>
        /// The statistics.
        /// </value>
        [ConfigurationProperty("statistics")]
        public CacheStatisticsElement Statistics
        {
            get { return (CacheStatisticsElement)base["statistics"]; }
        }

        /// <summary>
        /// Gets the section.
        /// </summary>
        /// <value>
        /// The section.
        /// </value>
        internal static CachingSectionHandler Section
        {
            get
            {
                if (_section == null)
                {
                    _section = ConfigurationManager.GetSection(SECTION_NAME) as CachingSectionHandler;
                }

                return _section;
            }
        }
    }
}


text:
#pragma once

#include "src/analyzer/analyzer_object_interface.h"
#include "src/bash/domain/detail/scripts_interface.h"
#include "src/bash/analyzer/detail/daily_user_statistics_creator_interface.h"
#include "src/bash/database/detail/database_functions_interface.h"
#include "src/database/detail/general_database_functions_interface.h"
#include "detail/system_interface.h"
#include "detail/network_trainer/network_trainer_interface.h"
#include "detail/classificator/classificator_interface.h"

#include <slas/type/date.h>

#include <memory>

namespace bash
{

namespace analyzer
{

class BashAnalyzerObject;
typedef std::shared_ptr<BashAnalyzerObject> BashAnalyzerObjectPtr;

class BashAnalyzerObject : public ::analyzer::AnalyzerObjectInterface {
 public:
  virtual ~BashAnalyzerObject() = default;

  static BashAnalyzerObjectPtr Create(::bash::database::detail::DatabaseFunctionsInterfacePtr database_functions,
                                      ::database::detail::GeneralDatabaseFunctionsInterfacePtr general_database_functions,
                                      ::bash::domain::detail::ScriptsInterfacePtr scripts_interface,
                                      const std::string &neural_network_data_directory);

  static BashAnalyzerObjectPtr Create(::bash::database::detail::DatabaseFunctionsInterfacePtr database_functions,
                                      ::database::detail::GeneralDatabaseFunctionsInterfacePtr general_database_functions,
                                      ::bash::domain::detail::ScriptsInterfacePtr scripts_interface,
                                      detail::SystemInterfacePtr system_interface,
                                      const std::string &neural_network_data_directory);

  void Analyze() override;

 private:
  BashAnalyzerObject(detail::DailyUserStatisticsCreatorInterfacePtr daily_user_statistics_creator,
                     detail::network_trainer::NetworkTrainerInterfacePtr network_trainer,
                     detail::classificator::ClassificatorInterfacePtr classificator,
                     ::bash::domain::detail::ScriptsInterfacePtr scripts_interface,
                     detail::SystemInterfacePtr system_interface);

  ::type::Date GetCurrentDate() const;

  detail::DailyUserStatisticsCreatorInterfacePtr daily_user_statistics_creator_;
  detail::network_trainer::NetworkTrainerInterfacePtr network_trainer_;
  detail::classificator::ClassificatorInterfacePtr classificator_;
  ::bash::domain::detail::ScriptsInterfacePtr scripts_interface_;
  detail::SystemInterfacePtr system_interface_;
};

}

}


text:
import myfunc1
print myfunc1.function(10.0)


text:
package com.amazonaws.services.snowball.model;

import javax.annotation.Generated;

/**
 * <p>
 * The specified resource can't be found. Check the information you provided in your last request, and try again.
 * </p>
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class InvalidResourceException extends com.amazonaws.services.snowball.model.AmazonSnowballException {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new InvalidResourceException with the specified error message.
     *
     * @param message
     *        Describes the error encountered.
     */
    public InvalidResourceException(String message) {
        super(message);
    }

}