text:
#include <linux/acpi.h>
#include <linux/export.h>
#include <linux/kernel.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/property.h>
#include <linux/etherdevice.h>
#include <linux/phy.h>

/**
 * device_add_property_set - Add a collection of properties to a device object.
 * @dev: Device to add properties to.
 * @pset: Collection of properties to add.
 *
 * Associate a collection of device properties represented by @pset with @dev
 * as its secondary firmware node.
 */
void device_add_property_set(struct device *dev, struct property_set *pset)
{
	if (!pset)
		return;

	pset->fwnode.type = FWNODE_PDATA;
	set_secondary_fwnode(dev, &pset->fwnode);
}
EXPORT_SYMBOL_GPL(device_add_property_set);

static inline bool is_pset(struct fwnode_handle *fwnode)
{
	return fwnode && fwnode->type == FWNODE_PDATA;
}

static inline struct property_set *to_pset(struct fwnode_handle *fwnode)
{
	return is_pset(fwnode) ?
		container_of(fwnode, struct property_set, fwnode) : NULL;
}

static struct property_entry *pset_prop_get(struct property_set *pset,
					    const char *name)
{
	struct property_entry *prop;

	if (!pset || !pset->properties)
		return NULL;

	for (prop = pset->properties; prop->name; prop++)
		if (!strcmp(name, prop->name))
			return prop;

	return NULL;
}

static int pset_prop_read_array(struct property_set *pset, const char *name,
				enum dev_prop_type type, void *val, size_t nval)
{
	struct property_entry *prop;
	unsigned int item_size;

	prop = pset_prop_get(pset, name);
	if (!prop)
		return -ENODATA;

	if (prop->type != type)
		return -EPROTO;

	if (!val)
		return prop->nval;

	if (prop->nval < nval)
		return -EOVERFLOW;

	switch (type) {
	case DEV_PROP_U8:
		item_size = sizeof(u8);
		break;
	case DEV_PROP_U16:
		item_size = sizeof(u16);
		break;
	case DEV_PROP_U32:
		item_size = sizeof(u32);
		break;
	case DEV_PROP_U64:
		item_size = sizeof(u64);
		break;
	case DEV_PROP_STRING:
		item_size = sizeof(const char *);
		break;
	default:
		return -EINVAL;
	}
	memcpy(val, prop->value.raw_data, nval * item_size);
	return 0;
}

static inline struct fwnode_handle *dev_fwnode(struct device *dev)
{
	return IS_ENABLED(CONFIG_OF) && dev->of_node ?
		&dev->of_node->fwnode : dev->fwnode;
}

/**
 * device_property_present - check if a property of a device is present
 * @dev: Device whose property is being checked
 * @propname: Name of the property
 *
 * Check if property @propname is present in the device firmware description.
 */
bool device_property_present(struct device *dev, const char *propname)
{
	return fwnode_property_present(dev_fwnode(dev), propname);
}
EXPORT_SYMBOL_GPL(device_property_present);

/**
 * fwnode_property_present - check if a property of a firmware node is present
 * @fwnode: Firmware node whose property to check
 * @propname: Name of the property
 */
bool fwnode_property_present(struct fwnode_handle *fwnode, const char *propname)
{
	if (is_of_node(fwnode))
		return of_property_read_bool(to_of_node(fwnode), propname);
	else if (is_acpi_node(fwnode))
		return !acpi_node_prop_get(fwnode, propname, NULL);

	return !!pset_prop_get(to_pset(fwnode), propname);
}
EXPORT_SYMBOL_GPL(fwnode_property_present);

/**
 * device_property_read_u8_array - return a u8 array property of a device
 * @dev: Device to get the property of
 * @propname: Name of the property
 * @val: The values are stored here or %NULL to return the number of values
 * @nval: Size of the @val array
 *
 * Function reads an array of u8 properties with @propname from the device
 * firmware description and stores them to @val if found.
 *
 * Return: number of values if @val was %NULL,
 *         %0 if the property was found (success),
 *	   %-EINVAL if given arguments are not valid,
 *	   %-ENODATA if the property does not have a value,
 *	   %-EPROTO if the property is not an array of numbers,
 *	   %-EOVERFLOW if the size of the property is not as expected.
 *	   %-ENXIO if no suitable firmware interface is present.
 */
int device_property_read_u8_array(struct device *dev, const char *propname,
				  u8 *val, size_t nval)
{
	return fwnode_property_read_u8_array(dev_fwnode(dev), propname, val, nval);
}
EXPORT_SYMBOL_GPL(device_property_read_u8_array);

/**
 * device_property_read_u16_array - return a u16 array property of a device
 * @dev: Device to get the property of
 * @propname: Name of the property
 * @val: The values are stored here or %NULL to return the number of values
 * @nval: Size of the @val array
 *
 * Function reads an array of u16 properties with @propname from the device
 * firmware description and stores them to @val if found.
 *
 * Return: number of values if @val was %NULL,
 *         %0 if the property was found (success),
 *	   %-EINVAL if given arguments are not valid,
 *	   %-ENODATA if the property does not have a value,
 *	   %-EPROTO if the property is not an array of numbers,
 *	   %-EOVERFLOW if the size of the property is not as expected.
 *	   %-ENXIO if no suitable firmware interface is present.
 */
int device_property_read_u16_array(struct device *dev, const char *propname,
				   u16 *val, size_t nval)
{
	return fwnode_property_read_u16_array(dev_fwnode(dev), propname, val, nval);
}
EXPORT_SYMBOL_GPL(device_property_read_u16_array);

/**
 * device_property_read_u32_array - return a u32 array property of a device
 * @dev: Device to get the property of
 * @propname: Name of the property
 * @val: The values are stored here or %NULL to return the number of values
 * @nval: Size of the @val array
 *
 * Function reads an array of u32 properties with @propname from the device
 * firmware description and stores them to @val if found.
 *
 * Return: number of values if @val was %NULL,
 *         %0 if the property was found (success),
 *	   %-EINVAL if given arguments are not valid,
 *	   %-ENODATA if the property does not have a value,
 *	   %-EPROTO if the property is not an array of numbers,
 *	   %-EOVERFLOW if the size of the property is not as expected.
 *	   %-ENXIO if no suitable firmware interface is present.
 */
int device_property_read_u32_array(struct device *dev, const char *propname,
				   u32 *val, size_t nval)
{
	return fwnode_property_read_u32_array(dev_fwnode(dev), propname, val, nval);
}
EXPORT_SYMBOL_GPL(device_property_read_u32_array);

/**
 * device_property_read_u64_array - return a u64 array property of a device
 * @dev: Device to get the property of
 * @propname: Name of the property
 * @val: The values are stored here or %NULL to return the number of values
 * @nval: Size of the @val array
 *
 * Function reads an array of u64 properties with @propname from the device
 * firmware description and stores them to @val if found.
 *
 * Return: number of values if @val was %NULL,
 *         %0 if the property was found (success),
 *	   %-EINVAL if given arguments are not valid,
 *	   %-ENODATA if the property does not have a value,
 *	   %-EPROTO if the property is not an array of numbers,
 *	   %-EOVERFLOW if the size of the property is not as expected.
 *	   %-ENXIO if no suitable firmware interface is present.
 */
int device_property_read_u64_array(struct device *dev, const char *propname,
				   u64 *val, size_t nval)
{
	return fwnode_property_read_u64_array(dev_fwnode(dev), propname, val, nval);
}
EXPORT_SYMBOL_GPL(device_property_read_u64_array);

/**
 * device_property_read_string_array - return a string array property of device
 * @dev: Device to get the property of
 * @propname: Name of the property
 * @val: The values are stored here or %NULL to return the number of values
 * @nval: Size of the @val array
 *
 * Function reads an array of string properties with @propname from the device
 * firmware description and stores them to @val if found.
 *
 * Return: number of values if @val was %NULL,
 *         %0 if the property was found (success),
 *	   %-EINVAL if given arguments are not valid,
 *	   %-ENODATA if the property does not have a value,
 *	   %-EPROTO or %-EILSEQ if the property is not an array of strings,
 *	   %-EOVERFLOW if the size of the property is not as expected.
 *	   %-ENXIO if no suitable firmware interface is present.
 */
int device_property_read_string_array(struct device *dev, const char *propname,
				      const char **val, size_t nval)
{
	return fwnode_property_read_string_array(dev_fwnode(dev), propname, val, nval);
}
EXPORT_SYMBOL_GPL(device_property_read_string_array);

/**
 * device_property_read_string - return a string property of a device
 * @dev: Device to get the property of
 * @propname: Name of the property
 * @val: The value is stored here
 *
 * Function reads property @propname from the device firmware description and
 * stores the value into @val if found. The value is checked to be a string.
 *
 * Return: %0 if the property was found (success),
 *	   %-EINVAL if given arguments are not valid,
 *	   %-ENODATA if the property does not have a value,
 *	   %-EPROTO or %-EILSEQ if the property type is not a string.
 *	   %-ENXIO if no suitable firmware interface is present.
 */
int device_property_read_string(struct device *dev, const char *propname,
				const char **val)
{
	return fwnode_property_read_string(dev_fwnode(dev), propname, val);
}
EXPORT_SYMBOL_GPL(device_property_read_string);

/**
 * device_property_match_string - find a string in an array and return index
 * @dev: Device to get the property of
 * @propname: Name of the property holding the array
 * @string: String to look for
 *
 * Find a given string in a string array and if it is found return the
 * index back.
 *
 * Return: %0 if the property was found (success),
 *	   %-EINVAL if given arguments are not valid,
 *	   %-ENODATA if the property does not have a value,
 *	   %-EPROTO if the property is not an array of strings,
 *	   %-ENXIO if no suitable firmware interface is present.
 */
int device_property_match_string(struct device *dev, const char *propname,
				 const char *string)
{
	return fwnode_property_match_string(dev_fwnode(dev), propname, string);
}
EXPORT_SYMBOL_GPL(device_property_match_string);

#define OF_DEV_PROP_READ_ARRAY(node, propname, type, val, nval) \
	(val) ? of_property_read_##type##_array((node), (propname), (val), (nval)) \
	      : of_property_count_elems_of_size((node), (propname), sizeof(type))

#define FWNODE_PROP_READ_ARRAY(_fwnode_, _propname_, _type_, _proptype_, _val_, _nval_) \
({ \
	int _ret_; \
	if (is_of_node(_fwnode_)) \
		_ret_ = OF_DEV_PROP_READ_ARRAY(to_of_node(_fwnode_), _propname_, \
					       _type_, _val_, _nval_); \
	else if (is_acpi_node(_fwnode_)) \
		_ret_ = acpi_node_prop_read(_fwnode_, _propname_, _proptype_, \
					    _val_, _nval_); \
	else if (is_pset(_fwnode_)) \
		_ret_ = pset_prop_read_array(to_pset(_fwnode_), _propname_, \
					     _proptype_, _val_, _nval_); \
	else \
		_ret_ = -ENXIO; \
	_ret_; \
})

/**
 * fwnode_property_read_u8_array - return a u8 array property of firmware node
 * @fwnode: Firmware node to get the property of
 * @propname: Name of the property
 * @val: The values are stored here or %NULL to return the number of values
 * @nval: Size of the @val array
 *
 * Read an array of u8 properties with @propname from @fwnode and stores them to
 * @val if found.
 *
 * Return: number of values if @val was %NULL,
 *         %0 if the property was found (success),
 *	   %-EINVAL if given arguments are not valid,
 *	   %-ENODATA if the property does not have a value,
 *	   %-EPROTO if the property is not an array of numbers,
 *	   %-EOVERFLOW if the size of the property is not as expected,
 *	   %-ENXIO if no suitable firmware interface is present.
 */
int fwnode_property_read_u8_array(struct fwnode_handle *fwnode,
				  const char *propname, u8 *val, size_t nval)
{
	return FWNODE_PROP_READ_ARRAY(fwnode, propname, u8, DEV_PROP_U8,
				      val, nval);
}
EXPORT_SYMBOL_GPL(fwnode_property_read_u8_array);

/**
 * fwnode_property_read_u16_array - return a u16 array property of firmware node
 * @fwnode: Firmware node to get the property of
 * @propname: Name of the property
 * @val: The values are stored here or %NULL to return the number of values
 * @nval: Size of the @val array
 *
 * Read an array of u16 properties with @propname from @fwnode and store them to
 * @val if found.
 *
 * Return: number of values if @val was %NULL,
 *         %0 if the property was found (success),
 *	   %-EINVAL if given arguments are not valid,
 *	   %-ENODATA if the property does not have a value,
 *	   %-EPROTO if the property is not an array of numbers,
 *	   %-EOVERFLOW if the size of the property is not as expected,
 *	   %-ENXIO if no suitable firmware interface is present.
 */
int fwnode_property_read_u16_array(struct fwnode_handle *fwnode,
				   const char *propname, u16 *val, size_t nval)
{
	return FWNODE_PROP_READ_ARRAY(fwnode, propname, u16, DEV_PROP_U16,
				      val, nval);
}
EXPORT_SYMBOL_GPL(fwnode_property_read_u16_array);

/**
 * fwnode_property_read_u32_array - return a u32 array property of firmware node
 * @fwnode: Firmware node to get the property of
 * @propname: Name of the property
 * @val: The values are stored here or %NULL to return the number of values
 * @nval: Size of the @val array
 *
 * Read an array of u32 properties with @propname from @fwnode store them to
 * @val if found.
 *
 * Return: number of values if @val was %NULL,
 *         %0 if the property was found (success),
 *	   %-EINVAL if given arguments are not valid,
 *	   %-ENODATA if the property does not have a value,
 *	   %-EPROTO if the property is not an array of numbers,
 *	   %-EOVERFLOW if the size of the property is not as expected,
 *	   %-ENXIO if no suitable firmware interface is present.
 */
int fwnode_property_read_u32_array(struct fwnode_handle *fwnode,
				   const char *propname, u32 *val, size_t nval)
{
	return FWNODE_PROP_READ_ARRAY(fwnode, propname, u32, DEV_PROP_U32,
				      val, nval);
}
EXPORT_SYMBOL_GPL(fwnode_property_read_u32_array);

/**
 * fwnode_property_read_u64_array - return a u64 array property firmware node
 * @fwnode: Firmware node to get the property of
 * @propname: Name of the property
 * @val: The values are stored here or %NULL to return the number of values
 * @nval: Size of the @val array
 *
 * Read an array of u64 properties with @propname from @fwnode and store them to
 * @val if found.
 *
 * Return: number of values if @val was %NULL,
 *         %0 if the property was found (success),
 *	   %-EINVAL if given arguments are not valid,
 *	   %-ENODATA if the property does not have a value,
 *	   %-EPROTO if the property is not an array of numbers,
 *	   %-EOVERFLOW if the size of the property is not as expected,
 *	   %-ENXIO if no suitable firmware interface is present.
 */
int fwnode_property_read_u64_array(struct fwnode_handle *fwnode,
				   const char *propname, u64 *val, size_t nval)
{
	return FWNODE_PROP_READ_ARRAY(fwnode, propname, u64, DEV_PROP_U64,
				      val, nval);
}
EXPORT_SYMBOL_GPL(fwnode_property_read_u64_array);

/**
 * fwnode_property_read_string_array - return string array property of a node
 * @fwnode: Firmware node to get the property of
 * @propname: Name of the property
 * @val: The values are stored here or %NULL to return the number of values
 * @nval: Size of the @val array
 *
 * Read an string list property @propname from the given firmware node and store
 * them to @val if found.
 *
 * Return: number of values if @val was %NULL,
 *         %0 if the property was found (success),
 *	   %-EINVAL if given arguments are not valid,
 *	   %-ENODATA if the property does not have a value,
 *	   %-EPROTO if the property is not an array of strings,
 *	   %-EOVERFLOW if the size of the property is not as expected,
 *	   %-ENXIO if no suitable firmware interface is present.
 */
int fwnode_property_read_string_array(struct fwnode_handle *fwnode,
				      const char *propname, const char **val,
				      size_t nval)
{
	if (is_of_node(fwnode))
		return val ?
			of_property_read_string_array(to_of_node(fwnode),
						      propname, val, nval) :
			of_property_count_strings(to_of_node(fwnode), propname);
	else if (is_acpi_node(fwnode))
		return acpi_node_prop_read(fwnode, propname, DEV_PROP_STRING,
					   val, nval);
	else if (is_pset(fwnode))
		return pset_prop_read_array(to_pset(fwnode), propname,
					    DEV_PROP_STRING, val, nval);
	return -ENXIO;
}
EXPORT_SYMBOL_GPL(fwnode_property_read_string_array);

/**
 * fwnode_property_read_string - return a string property of a firmware node
 * @fwnode: Firmware node to get the property of
 * @propname: Name of the property
 * @val: The value is stored here
 *
 * Read property @propname from the given firmware node and store the value into
 * @val if found.  The value is checked to be a string.
 *
 * Return: %0 if the property was found (success),
 *	   %-EINVAL if given arguments are not valid,
 *	   %-ENODATA if the property does not have a value,
 *	   %-EPROTO or %-EILSEQ if the property is not a string,
 *	   %-ENXIO if no suitable firmware interface is present.
 */
int fwnode_property_read_string(struct fwnode_handle *fwnode,
				const char *propname, const char **val)
{
	if (is_of_node(fwnode))
		return of_property_read_string(to_of_node(fwnode), propname, val);
	else if (is_acpi_node(fwnode))
		return acpi_node_prop_read(fwnode, propname, DEV_PROP_STRING,
					   val, 1);

	return pset_prop_read_array(to_pset(fwnode), propname,
				    DEV_PROP_STRING, val, 1);
}
EXPORT_SYMBOL_GPL(fwnode_property_read_string);

/**
 * fwnode_property_match_string - find a string in an array and return index
 * @fwnode: Firmware node to get the property of
 * @propname: Name of the property holding the array
 * @string: String to look for
 *
 * Find a given string in a string array and if it is found return the
 * index back.
 *
 * Return: %0 if the property was found (success),
 *	   %-EINVAL if given arguments are not valid,
 *	   %-ENODATA if the property does not have a value,
 *	   %-EPROTO if the property is not an array of strings,
 *	   %-ENXIO if no suitable firmware interface is present.
 */
int fwnode_property_match_string(struct fwnode_handle *fwnode,
	const char *propname, const char *string)
{
	const char **values;
	int nval, ret, i;

	nval = fwnode_property_read_string_array(fwnode, propname, NULL, 0);
	if (nval < 0)
		return nval;

	values = kcalloc(nval, sizeof(*values), GFP_KERNEL);
	if (!values)
		return -ENOMEM;

	ret = fwnode_property_read_string_array(fwnode, propname, values, nval);
	if (ret < 0)
		goto out;

	ret = -ENODATA;
	for (i = 0; i < nval; i++) {
		if (!strcmp(values[i], string)) {
			ret = i;
			break;
		}
	}
out:
	kfree(values);
	return ret;
}
EXPORT_SYMBOL_GPL(fwnode_property_match_string);

/**
 * device_get_next_child_node - Return the next child node handle for a device
 * @dev: Device to find the next child node for.
 * @child: Handle to one of the device's child nodes or a null handle.
 */
struct fwnode_handle *device_get_next_child_node(struct device *dev,
						 struct fwnode_handle *child)
{
	if (IS_ENABLED(CONFIG_OF) && dev->of_node) {
		struct device_node *node;

		node = of_get_next_available_child(dev->of_node, to_of_node(child));
		if (node)
			return &node->fwnode;
	} else if (IS_ENABLED(CONFIG_ACPI)) {
		return acpi_get_next_subnode(dev, child);
	}
	return NULL;
}
EXPORT_SYMBOL_GPL(device_get_next_child_node);

/**
 * fwnode_handle_put - Drop reference to a device node
 * @fwnode: Pointer to the device node to drop the reference to.
 *
 * This has to be used when terminating device_for_each_child_node() iteration
 * with break or return to prevent stale device node references from being left
 * behind.
 */
void fwnode_handle_put(struct fwnode_handle *fwnode)
{
	if (is_of_node(fwnode))
		of_node_put(to_of_node(fwnode));
}
EXPORT_SYMBOL_GPL(fwnode_handle_put);

/**
 * device_get_child_node_count - return the number of child nodes for device
 * @dev: Device to cound the child nodes for
 */
unsigned int device_get_child_node_count(struct device *dev)
{
	struct fwnode_handle *child;
	unsigned int count = 0;

	device_for_each_child_node(dev, child)
		count++;

	return count;
}
EXPORT_SYMBOL_GPL(device_get_child_node_count);

bool device_dma_supported(struct device *dev)
{
	/* For DT, this is always supported.
	 * For ACPI, this depends on CCA, which
	 * is determined by the acpi_dma_supported().
	 */
	if (IS_ENABLED(CONFIG_OF) && dev->of_node)
		return true;

	return acpi_dma_supported(ACPI_COMPANION(dev));
}
EXPORT_SYMBOL_GPL(device_dma_supported);

enum dev_dma_attr device_get_dma_attr(struct device *dev)
{
	enum dev_dma_attr attr = DEV_DMA_NOT_SUPPORTED;

	if (IS_ENABLED(CONFIG_OF) && dev->of_node) {
		if (of_dma_is_coherent(dev->of_node))
			attr = DEV_DMA_COHERENT;
		else
			attr = DEV_DMA_NON_COHERENT;
	} else
		attr = acpi_get_dma_attr(ACPI_COMPANION(dev));

	return attr;
}
EXPORT_SYMBOL_GPL(device_get_dma_attr);

/**
 * device_get_phy_mode - Get phy mode for given device
 * @dev:	Pointer to the given device
 *
 * The function gets phy interface string from property 'phy-mode' or
 * 'phy-connection-type', and return its index in phy_modes table, or errno in
 * error case.
 */
int device_get_phy_mode(struct device *dev)
{
	const char *pm;
	int err, i;

	err = device_property_read_string(dev, "phy-mode", &pm);
	if (err < 0)
		err = device_property_read_string(dev,
						  "phy-connection-type", &pm);
	if (err < 0)
		return err;

	for (i = 0; i < PHY_INTERFACE_MODE_MAX; i++)
		if (!strcasecmp(pm, phy_modes(i)))
			return i;

	return -ENODEV;
}
EXPORT_SYMBOL_GPL(device_get_phy_mode);

static void *device_get_mac_addr(struct device *dev,
				 const char *name, char *addr,
				 int alen)
{
	int ret = device_property_read_u8_array(dev, name, addr, alen);

	if (ret == 0 && alen == ETH_ALEN && is_valid_ether_addr(addr))
		return addr;
	return NULL;
}

/**
 * device_get_mac_address - Get the MAC for a given device
 * @dev:	Pointer to the device
 * @addr:	Address of buffer to store the MAC in
 * @alen:	Length of the buffer pointed to by addr, should be ETH_ALEN
 *
 * Search the firmware node for the best MAC address to use.  'mac-address' is
 * checked first, because that is supposed to contain to "most recent" MAC
 * address. If that isn't set, then 'local-mac-address' is checked next,
 * because that is the default address.  If that isn't set, then the obsolete
 * 'address' is checked, just in case we're using an old device tree.
 *
 * Note that the 'address' property is supposed to contain a virtual address of
 * the register set, but some DTS files have redefined that property to be the
 * MAC address.
 *
 * All-zero MAC addresses are rejected, because those could be properties that
 * exist in the firmware tables, but were not updated by the firmware.  For
 * example, the DTS could define 'mac-address' and 'local-mac-address', with
 * zero MAC addresses.  Some older U-Boots only initialized 'local-mac-address'.
 * In this case, the real MAC is in 'local-mac-address', and 'mac-address'
 * exists but is all zeros.
*/
void *device_get_mac_address(struct device *dev, char *addr, int alen)
{
	char *res;

	res = device_get_mac_addr(dev, "mac-address", addr, alen);
	if (res)
		return res;

	res = device_get_mac_addr(dev, "local-mac-address", addr, alen);
	if (res)
		return res;

	return device_get_mac_addr(dev, "address", addr, alen);
}
EXPORT_SYMBOL(device_get_mac_address);


text:
package graphedit.command;

import graphedit.app.ApplicationMode;
import graphedit.app.MainFrame;
import graphedit.model.components.GraphElement;
import graphedit.model.diagram.GraphEditModel;
import graphedit.model.elements.ClassElement;
import graphedit.model.elements.PersistentClassElement;
import graphedit.model.elements.UIClassElement;
import graphedit.model.enums.ClassStereotypeUI;
import graphedit.view.ElementPainter;
import graphedit.view.GraphEditView;
import kroki.profil.VisibleElement;
import kroki.profil.panel.VisibleClass;

public class AddElementCommand extends Command {

	private GraphElement component;
	private ElementPainter elementPainter;
	private GraphEditModel model;
	private ClassElement element;

	public AddElementCommand(GraphEditView view, GraphElement component,
			ElementPainter elementPainter) {
		this.model = view.getModel();
		this.view = view;
		this.component = component;
		this.elementPainter = elementPainter;

		if (component instanceof graphedit.model.components.Class){
			if (MainFrame.getInstance().getAppMode() != ApplicationMode.PERSISTENT)
				element = new UIClassElement(component, ClassStereotypeUI.STANDARD_PANEL);
			else
				element = new PersistentClassElement(component);
		}
		element.setElement(component);
		this.component.setRepresentedElement(element);

	}

	@Override
	public void execute() {

		if (element.getUmlType() instanceof VisibleElement){
			model.getParentPackage().getUmlPackage().addOwnedType(element.getUmlType());

			element.getUmlType().setUmlPackage(model.getParentPackage().getUmlPackage());
			if (element instanceof UIClassElement)
				model.getParentPackage().getClassElementsByVisibleClassesMap().put((VisibleClass)element.getUmlType(), (UIClassElement) element);
		}
		model.addDiagramElement(component);
		view.addElementPainter(elementPainter);
	}

	@Override
	public void undo() {
		model.getParentPackage().getUmlPackage().removeOwnedType(element.getUmlType());
		model.removeDiagramElement(component);
		view.removeElementPainter(component);
		view.getSelectionModel().removeAllSelectedElements();

		if (element instanceof UIClassElement)
			model.getParentPackage().getClassElementsByVisibleClassesMap().remove((VisibleClass)element.getUmlType());
	}

}

redpajama_set_name: RedPajamaGithub


text:
function resolved (value) {
  return new FidelityPromise(function (resolve, reject) {
    resolve(value);
  });
}

function rejected (reason) {
  return new FidelityPromise(function (resolve, reject) {
    reject(reason);
  });
}

describe("Promises/A+ Tests", function () {
    require("promises-aplus-tests").mocha({
        resolved: resolved,
        rejected: rejected,
        deferred: FidelityPromise.deferred
    });
});


text:
class RegistrationController < ApplicationController

  def activate
    $hostfull=request.protocol + request.host_with_port

    @user=User.find_by_activation_code(params[:activation_code]) unless params[:activation_code].nil?
    if @user.nil?

      flash[:notice] = "Your account has already been activated"
      redirect_to :action=>:index, :controller=>:site
    else
      #     if request.post?
      @user.delete_activation_code
      flash[:notice] = "Account successfully activated for #{@user.name}"
      redirect_to :action=>:index, :controller=>:site
      #     else
      #        render :action => :password_is_reset
      #     end

    end
  end

  def testinventory
    @product_detail = ProductDetail.find(params[:id])
    $hostfull=request.protocol + request.host_with_port

    UserNotifier.inventory_alert(@product_detail, $hostfull).deliver
    redirect_back_or_default(request.referer)

  end

  def lostwithemail
    @user = User.find_by_name(params[:name])
    $hostfull=request.protocol + request.host_with_port
    if @user
      if @user.activation_code

        @user.resend_activation_code

        UserNotifier.lostwithemail(@user, $hostfull).deliver

        flash[:notice] = "Activation code re-sent to #{@user.name}"
      else
        flash[:notice] = "#{@user.name} has already been activated."
      end
    else
      flash[:notice] = "#{params[:user][:name]} does not exist in system"
    end
    redirect_back_or_default(request.referer)
  end

  def lost
    $hostfull=request.protocol + request.host_with_port

    if request.post?
      @user = User.find_by_name(params[:user][:name])
      if @user
        if @user.activation_code
          @user.resend_activation_code
          flash[:notice] = "Activation code re-sent to #{@user.name}"
        else
          flash[:notice] = "#{@user.name} has already been activated."
        end
      else
        flash[:notice] = "#{params[:user][:name]} does not exist in system"
      end
      redirect_back_or_default('/')
    end
  end

  def forgot
    #  @hostfull =
    $hostfull=request.protocol + request.host_with_port
    @hostfull=$hostfull
    if request.post?
      @user = User.find_by_name(params[:user][:name])
      if @user
        @user.create_reset_code
        UserNotifier.reset_notification(@user, $hostfull).deliver
        #         UserNotifier.reset_notification2(@user, @hostfull)
        flash[:notice] = "Reset code sent to #{@user.name}"
      else
        flash[:notice] = "#{params[:user][:name]} does not exist in system"
      end
      redirect_back_or_default('/')
    end
  end

  def reset
    @user = User.find_by_password_reset_code(params[:reset_code]) unless params[:reset_code].empty?
    #    @user = User.find_by_password_reset_code(params[:reset_code])
    if @user.nil?
      flash[:notice] ="You already reset your password."
      redirect_to :action=>:forgot
    else
      if request.post?
        if @user.update_attributes(:password => params[:user][:password], :password_confirmation => params[:user][:password_confirmation])
          #self.current_user = @user
          @user.delete_reset_code
          flash[:notice] = "Password reset successfully for #{@user.name}"
          redirect_to :controller=>:admin, :action=>:login
        else
          render :action => :reset
        end
      end
    end
  end

  def notify_winner
    @user = User.find_by_name(params[:user])

    $hostfull=request.protocol + request.host_with_port
    user=params[:user]
    UserNotifier.deliver_winner_notification(@user,"", $hostfull)
    flash[:notice] = "Winner Notification sent to #{@user.name}"
    redirect_back_or_default('/')
  end

  def password_is_reset

  end

  def register_customer
    session[:main_search_status] = false
    @user = User.new
    @role_name="Customer"
    @new_uri = params[:new_uri] || ""
    puts 'New URI:' + @new_uri
    #     redirect_back_or_default('/')
    session[:original_uri] = @new_uri if not @new_uri==nil
  end

  def register_voter
    @user = User.new
    @role_name="Participant"
    #session[:original_uri] = "/registration/register_voter"

  end

  def register_shop
    @user = User.new
    @role_name="Shop Owner"
    #session[:original_uri] = "/registration/register_shop"

  end

  def register_artist
    @user = User.new
    @role_name="Artist"
    #session[:original_uri] = "/registration/register_artist"

  end

  #  Will perform registration for the new user.  It will
  #  automatically set the role give then invisible field on
  #  the entry form.  Each type of user uses this to register.

  def registration
    session[:main_search_status] = false

    puts"registration"
    uri =  session[:original_uri]
    $hostfull=request.protocol + request.host_with_port

    puts uri
    #first check if user exists.
    @user = User.find_by_name(params[:user][:name])
    @regtype=params[:register][:regtype]||""
    if not @user then
      if request.post? and params[:user]
        @user = User.create(params[:user])
        @role_name = params[:register][:role]
        @role = Role.find_by_name(@role_name)
        @user.roles << @role

        @user_attribute = UserAttribute.create(params[:user_attribute])
        puts(@user_attribute)
        @user.user_attribute = @user_attribute

        if @user.save
          @user.create_activation_code
          flash[:notice] = @role_name +" account created."
          session[:user_id] = @user.id
          session[:original_uri] = nil
          redirect_to(uri || { :controller=>"admin", :action => "index"  })
          #redirect_to({ :controller=>"admin", :action => "index"  })
          UserNotifier.signup_notification(@user, $hostfull).deliver

          # redirect_to(:action=> :login,  :name=>@user.name, :password=>@user.password)
          #     redirect_to("/admin/")
          # redirect_to(uri)
        else
          flash[:notice] = @user.errors.full_messages.join("<br>")
          redirect_to("/registration/"+@regtype)
          #redirect_to(uri)
        end
      end

    else
      flash[:notice] = "User already Exists, please try again."
      redirect_to("/registration/"+@regtype)
    end

    #    redirect_to("/admin/")
  end
  #def login
  #    @junk="this is a test"
  #
  #end

  # Had to add this to allow user to either login or do a quick register.  Have kept login in admin for maintanance reasons
  def login
    session[:main_search_status] = false

    logger.debug  "in login 1*****************"
    session[:user_id] = nil
    if request.post?
      user = User.authenticate(params[:name], params[:password])
      if user
        session[:user_id] = user.id
        uri = session[:original_uri]
        session[:original_uri] = nil
        redirect_to(uri || { :controller=>"admin", :action => "index"  })
      else
        flash.now[:notice] = "Invalid user/password combination"
      end
    end
  end

  private

  # def login (username, password)
  #        @junk="this is a test 2"
  #
  #    session[:main_search_status] = false
  #    logger.debug  "in login 2*****************"
  #
  #    session[:user_id] = nil
  #    if request.post?
  #      user = User.authenticate(username, password)
  #      if user
  #        session[:user_id] = user.id
  #        uri = session[:original_uri]
  #        session[:original_uri] = nil
  #        redirect_to(uri || {:controller=>"admin", :action => "index" })
  #      else
  #        flash.now[:notice] = "Invalid user/password combination"
  #      end
  #    end
  #  end

  protected

  def authorize
    #  session[:original_uri] = request.request_uri

  end

  def authenticate
  end
end


text:
package com.asakusafw.utils.java.model.syntax;

/**
 * An interface which represents {@code default} labels in switch statements.
 * This element only can appear in the body of {@link SwitchStatement}.
 *

 *
 Specified In:

 *
 {@code [JLS3:14.11] The switch Statement (SwitchLabel)}

 *

 *

 * @see SwitchStatement
 */
public interface SwitchDefaultLabel
        extends SwitchLabel {

    // properties
}


text:
import {remote} from 'electron';

import {
  VAULT_LIST_REQUEST,
  VAULT_LIST_SUCCESS,
  VAULT_LIST_FAILURE,
} from '../../../../contracts/enums/action_types';

const glacier = remote.getGlobal('glacier');

export default function listVaults() {
  return (dispatch, getState) => {

    dispatch({type: VAULT_LIST_REQUEST});

    return glacier.listVaults()
      .then((vaults) => {
        dispatch({type: VAULT_LIST_SUCCESS, payload: vaults});
        return vaults;
      })
      .catch((error) => {
        dispatch({type: VAULT_LIST_FAILURE});
      });

  };

}


text:
```js
const lunr = require('lunr');
const ItemsJS = require('itemsjs');

const data = [{
  id: 1,
  title: 'Moby Dick',
  text: 'Call me Ishmael. Some years ago...',
  category: 'fiction'
},
{
  id: 2,
  title: 'Zen and the Art of Motorcycle Maintenance',
  text: 'I can see by my watch...',
  category: 'fiction'
},
{
  id: 3,
  title: 'Neuromancer',
  text: 'The sky above the port was...',
  category: 'fiction'
},
{
  id: 4,
  title: 'Zen and the Art of Archery',
  text: 'At first sight it must seem...',
  category: 'non-fiction'
}];

// configuration for itemsjs faceted search
const configuration = {
  native_search_enabled: false,
  custom_id_field: 'id', // 'id' is a default one but we can also use 'uuid' and other if necessary
  aggregations: {
    category: {
      title: 'Categories',
      size: 10,
      conjunction: true
    }
  }
}

// indexing lunr with data
const idx = lunr(function () {
  this.ref('id');
  this.field('title');
  this.field('text');
  this.field('category');

  data.forEach(v => {
    this.add(v);
  });
});

// indexing data into itemsjs
const itemsjs = ItemsJS(data, configuration);

// searching
const search_result = idx.search('sky');
console.log(search_result);

const result = itemsjs.search({
  per_page: 3,
  // important! providing ids from full text search
  ids: search_result.map(v => v.ref),
  filters: {
    category: ['fiction'],
  }
});

console.log(result);
//console.log(result.data.items);
//console.log(result.data.aggregations.category);
```


text:
*This document is early work in progress*

Gitblog applies filters -- a sorted list of callables -- to different objects. For instance post body, comments, etc.

Plugins which alter the content of a gitblog hooks itself into one or more filter chains.

See the [akismet](../plugins/akismet.php) and [markdown](../plugins/markdown.php) plugins for examples and look at [lib/GBFilter.php](../lib/GBFilter.php) for details and to see what filters exists and can be hooked into.


text:
package com.netpet.spools.spring.aop.jdk;

/**
 * Created by woncz on 2017/11/8.
 */
public class Business implements IBusiness, IBusiness2 {
    @Override
    public boolean doSomeThing() {
        System.out.println("执行业务逻辑");
        return true;
    }

    @Override
    public void doSomeThing2() {
        System.out.println("执行业务逻辑2");
    }
}


text:
<?php namespace MaartenStaa\PHPTA\Processors\Smells;

use PhpParser\Node\Expr\Exit_;

/**
 * @coversDefaultClass \MaartenStaa\PHPTA\Processors\Smells\ExitStatementUsage
 */
class ExitStatementUsageTest extends SmellTest
{
    /**
     * @covers ::addError
     */
    public function testAddError()
    {
        $smell = new ExitStatementUsage;

        $fileMock = $this->getMockBuilder('MaartenStaa\PHPTA\Processors\File')
            ->setMethods(array('addError'))
            ->disableOriginalConstructor()
            ->getMock();

        $fileMock->expects($this->once())
            ->method('addError')
            ->with(
                'You have an exit statement on line 23, which will prevent you from ' .
                'testing this function fully and/or correctly.'
            );

        $node = new Exit_(
            null,
            array('startLine' => 23)
        );

        $smell->addError($node, $fileMock);
    }

    /**
     * @covers  ::process
     * @covers  ::getTargetNodeType
     * @covers  ::nodeSmells
     * @covers  ::smellCount
     * @depends testAddError
     */
    public function testNoMatch()
    {
        $smell = new ExitStatementUsage;

        $fileMock = $this->getMockBuilder('MaartenStaa\PHPTA\Processors\File')
            ->setMethods(array('addError'))
            ->disableOriginalConstructor()
            ->getMock();

        $fileMock->expects($this->never())
            ->method('addError');

        $node = $this->createFunctionNode(
            '$this->foo->bar("baz");'
        );

        $this->assertEquals(
            0,
            $smell->process(
                $node,
                $fileMock
            )
        );
    }

    /**
     * @covers  ::process
     * @covers  ::getTargetNodeType
     * @covers  ::nodeSmells
     * @covers  ::smellCount
     * @depends testAddError
     */
    public function testOneMatch()
    {
        $smell = new ExitStatementUsage;

        $fileMock = $this->getMockBuilder('MaartenStaa\PHPTA\Processors\File')
            ->setMethods(array('addError'))
            ->disableOriginalConstructor()
            ->getMock();

        $fileMock->expects($this->once())
            ->method('addError');

        $node = $this->createFunctionNode(
            'exit;'
        );

        $this->assertEquals(
            1,
            $smell->process(
                $node,
                $fileMock
            )
        );
    }

    /**
     * @covers  ::process
     * @covers  ::getTargetNodeType
     * @covers  ::nodeSmells
     * @covers  ::smellCount
     * @depends testAddError
     */
    public function testOneMatchDie()
    {
        $smell = new ExitStatementUsage;

        $fileMock = $this->getMockBuilder('MaartenStaa\PHPTA\Processors\File')
            ->setMethods(array('addError'))
            ->disableOriginalConstructor()
            ->getMock();

        $fileMock->expects($this->once())
            ->method('addError');

        $node = $this->createFunctionNode(
            'die();'
        );

        $this->assertEquals(
            1,
            $smell->process(
                $node,
                $fileMock
            )
        );
    }

    /**
     * @covers  ::process
     * @covers  ::getTargetNodeType
     * @covers  ::nodeSmells
     * @covers  ::smellCount
     * @depends testAddError
     */
    public function testMultipleMatches()
    {
        $smell = new ExitStatementUsage;

        $fileMock = $this->getMockBuilder('MaartenStaa\PHPTA\Processors\File')
            ->setMethods(array('addError'))
            ->disableOriginalConstructor()
            ->getMock();

        $fileMock->expects($this->exactly(2))
            ->method('addError');

        $node = $this->createFunctionNode(
            '$a ? exit("a") : exit("b")'
        );

        $this->assertEquals(
            2,
            $smell->process(
                $node,
                $fileMock
            )
        );
    }
}


text:
package uk.gov.nationalarchives.droid.gui.treemodel;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;

import uk.gov.nationalarchives.droid.core.interfaces.ResourceType;
import uk.gov.nationalarchives.droid.profile.ProfileResourceNode;

/**
 *
 * @author rflitcroft
 *
 * @param <T> the source comparable
 */
public abstract class DirectoryComparableObject<T extends Comparable<T>> implements DirectoryComparable<T> {

    // The data value
    private T source;

    // The resource node the value is associated with.
    private ProfileResourceNode node;

    /**
     *
     * @param source the source object
     * @param node the tree node from which we can compare various properties for sorting.
     */
    public DirectoryComparableObject(T source, ProfileResourceNode node) {
        this.source = source;
        this.node = node;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int compareTo(DirectoryComparable<T> o) {
        return nullSafeCompareTo(o);
    }

    private int nullSafeCompareTo(DirectoryComparable<T> o) {
        int compare;

        if (source == null && o == null) {
            compare = 0;
        } else if (source == null) {
            compare = -1;
        } else if (o == null || o.getSource() == null) {
            compare = 1;
        } else {
            compare = sourceCompareTo(o);
        }

        return compare;
    }

    /**
     *
     * @param o The object to compare.
     * @return int the result of the source object comparison
     */
    protected int sourceCompareTo(DirectoryComparable<T> o) {
        return source.compareTo(o.getSource());
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String toString() {
        return source == null ? "" : source.toString();
    }

    /**
     * {@inheritDoc}
     * @see uk.gov.nationalarchives.droid.gui.treemodel.DirectoryComparable#getSource()
     */
    @Override
    public T getSource() {
        return source;
    }

    @Override
    public int getFilterStatus() {
        return node.getFilterStatus();
    }

    /**
     *
     * @return whether the object has a file extension mismatch.
     */
    public boolean getExtensionMismatch() {
        return node.getExtensionMismatch();
    }

    /**
     * {@inheritDoc}
     */
    //@Override
    //public Boolean isFile() {
    //    return file;
    //}
    @Override
    public ResourceType getResourceType() {
        return node.getMetaData().getResourceType();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int hashCode() {
        return new HashCodeBuilder().append(source).toHashCode();
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }

        DirectoryComparableObject<T> other = (DirectoryComparableObject<T>) obj;
        return new EqualsBuilder().append(source, other.source).isEquals();
    }

}


text:
var common     = require('../../common');
var connection = common.createConnection();
var assert     = require('assert');

common.useTestDb(connection);

var table = 'zerofill_results_test';
connection.query([
  'CREATE TEMPORARY TABLE `' + table + '` (',
  '`id` int(11) unsigned NOT NULL AUTO_INCREMENT,',
  '`num` int(5) UNSIGNED ZEROFILL,',
  'PRIMARY KEY (`id`)',
  ') ENGINE=InnoDB DEFAULT CHARSET=utf8'
].join('\n'));

var test_numbers = [ "00000", "00001", "00012", "00123", "01234", "12345", null ];
var results = {};

for (var i = 0; i < test_numbers.length; i++) {
  connection.query('INSERT INTO ' + table + ' SET ?', {
    id: (i + 1),
    num: (test_numbers[i] !== null ? parseInt(test_numbers[i], 10) : null)
  }, function (err, _result) {
    if (err) throw err;
  });
}
connection.query('SELECT * FROM ' + table, function (err, _results) {
  if (err) throw err;

  results = _results;
});
connection.end();

process.on('exit', function() {
  assert.strictEqual(results.length, test_numbers.length);
  for (var i = 0; i < results.length; i++) {
    assert.strictEqual(test_numbers[results[i].id - 1], (results[i].num !== null ? "" + results[i].num : null));
  }
});


text:
package org.glob3.mobile.generated;
//
//  ITileVisitor.hpp
//  G3MiOSSDK
//
//  Created by Vidal on 1/22/13.
//
//

public interface ITileVisitor
{
  void dispose();

  void visitTile(java.util.ArrayList<Layer> layers, Tile tile);
}


text:
namespace HyperbolicModels
{
	using R3.Core;
	using R3.Geometry;
	using R3.Math;
	using System.Collections.Generic;
	using System.IO;
	using System.Linq;
	using Math = System.Math;

	public static class S3_Hopf
	{

		public static void Experiment()
		{
			TilingConfig config = new TilingConfig( 4, 3 );
			Tiling tiling = new Tiling();
			tiling.Generate( config );

			HashSet<H3.Cell.Edge> completed = new HashSet<H3.Cell.Edge>( new H3.Cell.EdgeEqualityComparer() );

			string fileName = "hopf.pov";
			using( StreamWriter sw = File.CreateText( fileName ) )
			{
				Tile[] tiles = tiling.Tiles.ToArray();
				//foreach( Tile t in tiling.Tiles )
				foreach( Tile t in new Tile[] { tiles[0] } )
				{
					foreach( Segment seg in t.Boundary.Segments )
					{
						H3.Cell.Edge e = new H3.Cell.Edge( seg.P1, seg.P2 );
						if( completed.Contains( e ) )
							continue;

						HopfLink( sw,
							Sterographic.PlaneToSphereSafe( e.Start ),
							Sterographic.PlaneToSphereSafe( e.End ), anti: false );
						completed.Add( e );
					}
				}
			}
		}

		/// <summary>
		/// Hopf Link between two points on S^2.
		/// </summary>
		public static void HopfLink( StreamWriter sw, Vector3D s2_1, Vector3D s2_2, bool anti )
		{
			Vector3D[] circlePoints;
			string circleString;
			circlePoints = OneHopfCircleProjected( s2_1, anti );
			circleString = PovRay.EdgeSphereSweep( circlePoints, SizeFunc );
			sw.WriteLine( circleString );
			circlePoints = OneHopfCircleProjected( s2_2, anti );
			circleString = PovRay.EdgeSphereSweep( circlePoints, SizeFunc );
			sw.WriteLine( circleString );

			Mesh mesh = new Mesh();
			Vector3D[] interpolated = S3.GeodesicPoints( s2_1, s2_2 );
			for( int i = 0; i < interpolated.Length - 1; i++ )
			{
				Vector3D v1 = interpolated[i];
				Vector3D v2 = interpolated[i + 1];
				Vector3D[] p1 = OneHopfCircleProjected( v1, anti );
				Vector3D[] p2 = OneHopfCircleProjected( v2, anti );

				for( int j = 0; j < p1.Length-1; j++ )
				{
					Mesh.Triangle t1 = new Mesh.Triangle( p1[j], p1[j + 1], p2[j] );
					Mesh.Triangle t2 = new Mesh.Triangle( p2[j], p1[j + 1], p2[j + 1] );
					mesh.Triangles.Add( t1 );
					mesh.Triangles.Add( t2 );
				}
			}

			PovRay.WriteMesh( sw, mesh, append: true );
		}

		private static Vector3D[] OneHopfCircleProjected( Vector3D s2Point, bool anti )
		{
			Vector3D[] circlePoints = S3.OneHopfCircle( s2Point, anti );
			for( int i = 0; i < circlePoints.Length; i++ )
				circlePoints[i] = Sterographic.S3toR3( circlePoints[i] );
			return circlePoints;
		}

		private static Sphere SizeFunc( Vector3D v )
		{
			Vector3D c;
			double r;
			H3Models.Ball.DupinCyclideSphere( v, .04 / 2, Geometry.Spherical, out c, out r );
			return new Sphere() { Center = c, Radius = r };
		}
	}
}


text:
layout: default
permalink: /opportunities

#title: "Next generation subsurface imaging software"

---

### PhD studentships
We are currently looking for PhD students to join our highly multidisciplinary team to work in research areas such as:
* Domain specific languages
* Code generation and compiler technologies
* High performance computing
* PDE-constrained optimisation
* Machine learning
* Seismic imaging and non-destructive testing

Imperial College London offers a number of competitive scholarships you can apply for. Use this [search tool](http://www.imperial.ac.uk/study/pg/fees-and-funding/scholarships/scholarships-search-tool/) to find a scholarship that fits your background. Potential scholarships you can find through the search tool include:
* Earth science and engineering departmental scholarships (Janet Watson, STFC, EPSRC) 2018, deadline 8th January 2018
* NERC Grantham DTP, deadline 8th of January 2018
* NERC Oil & Gas, deadline TBA
* President's PhD Scholarship round 2, deadline 19th of January
* CSC Scholarships, deadline 31st of January

Example project:
* [Redundancy, retiming and data flow in compiling finite-difference applications for many core architectures](http://www.imperial.ac.uk/media/imperial-college/faculty-of-engineering/earth-science-and-engineering/phd-opportunities/PhD-proposal---OPESCI.pdf)

If you have any questions then either email g.gorman at imperial.ac.uk or reach out to us on our slack channel.


text:
package com.ts.timeseries.util;

public final class Preconditions {

    private Preconditions() {
        throw new AssertionError();
    }

    public static void checkArgument(boolean b, String message) {
        if (!b)
        {
            throw new IllegalArgumentException(message);
        }
    }

    public static void checkNotNull(Object instance, String message) {
        if (instance == null)
        {
            throw new NullPointerException(message);
        }
    }
}


text:
window.onload = () => {
  const FILES_APP_ORIGIN =
      'chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj';
  let messageSource;

  const content = document.querySelector('#content');

  window.addEventListener('message', event => {
    if (event.origin !== FILES_APP_ORIGIN) {
      console.error('Unknown origin: ' + event.origin);
      return;
    }

    messageSource = event.source;
    switch (event.data.type) {
      case 'html':
        content.textContent = '';
        contentChanged(null);
        fetch(event.data.src)
            .then((response) => {
              return response.text();
            })
            .then((text) => {
              content.textContent = text;
              contentChanged(text);
            });
        break;
      case 'audio':
      case 'video':
        content.onloadeddata = (e) => contentChanged(e.target.src);
        content.src = event.data.src;
        break;
      case 'image':
        content.remove();
        content.src = '';

        const image = new Image();
        image.onload = (e) => {
          contentChanged(e.target.src);
          document.body.appendChild(content);
          content.src = e.target.src;
        };

        image.onerror = (e) => {
          contentDecodeFailed();
        };

        image.src = event.data.src;
        break;
      default:
        content.onload = (e) => contentChanged(e.target.src);
        content.src = event.data.src;
        break;
    }
  });

  document.addEventListener('contextmenu', e => {
    e.preventDefault();
    return false;
  });

  document.addEventListener('click', e => {
    sendMessage((e.target === content) ? 'tap-inside' : 'tap-outside');
  });

  function contentChanged(src) {
    sendMessage(src ? 'webview-loaded' : 'webview-cleared');
  }

  function contentDecodeFailed() {
    sendMessage('content-decode-failed');
  }

  function sendMessage(message) {
    if (messageSource) {
      messageSource.postMessage(message, FILES_APP_ORIGIN);
    }
  }

  // TODO(oka): This is a workaround to fix FOUC problem, where sometimes
  // immature view with smaller window size than outer window is rendered for a
  // moment. Remove this after the root cause is fixed. http://crbug.com/640525
  window.addEventListener('resize', () => {
    // Remove hidden attribute on event of resize to avoid FOUC. The window's
    // initial size is 100 x 100 and it's fit into the outer window size after a
    // moment. Due to Files App's window size constraint, resized window must be
    // larger than 100 x 100. So this event is always invoked.
    content.removeAttribute('hidden');
  });
  // Fallback for the case of webview bug is fixed and above code is not
  // executed.
  setTimeout(() => {
    content.removeAttribute('hidden');
  }, 500);
};


text:
package com.itheima.mobileguard.receivers;

import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;

import com.itheima.mobileguard.services.UpdateWidgetService;

/**
 * ÌØÊâµÄ¹ã²¥½ÓÊÜÕß
 * @author Administrator
 * 1.дһ¸öÀà ¼Ì³ÐAppWidgetProvider
 *
 */
public class MyWidget extends AppWidgetProvider {
	@Override
	public void onEnabled(Context context) {
		//¿ªÆô·þÎñ ¶¨ÆڵĸüÐÂwidget
		Intent i = new Intent(context,UpdateWidgetService.class);
		context.startService(i);
		super.onEnabled(context);
	}

	@Override
	public void onDisabled(Context context) {
		//Í£Ö¹·þÎñ ²»ÔÙÈ¥¸üÐÂwidget
		Intent i = new Intent(context,UpdateWidgetService.class);
		context.stopService(i);
		super.onDisabled(context);
	}
}


text:
// Copyright 2016 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.devtools.build.lib.rules.java.proto;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.devtools.build.lib.analysis.configuredtargets.RuleConfiguredTarget.Mode.TARGET;
import static com.google.devtools.build.lib.cmdline.Label.parseAbsoluteUnchecked;
import static com.google.devtools.build.lib.packages.Attribute.ConfigurationTransition.HOST;
import static com.google.devtools.build.lib.packages.Attribute.attr;
import static com.google.devtools.build.lib.packages.BuildType.LABEL;
import static com.google.devtools.build.lib.rules.java.proto.JplCcLinkParams.createCcLinkParamsStore;
import static com.google.devtools.build.lib.rules.java.proto.StrictDepsUtils.createNonStrictCompilationArgsProvider;

import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.analysis.ConfiguredAspect;
import com.google.devtools.build.lib.analysis.ConfiguredAspectFactory;
import com.google.devtools.build.lib.analysis.ConfiguredTarget;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.TransitiveInfoCollection;
import com.google.devtools.build.lib.analysis.TransitiveInfoProviderMap;
import com.google.devtools.build.lib.analysis.TransitiveInfoProviderMapBuilder;
import com.google.devtools.build.lib.analysis.WrappingProvider;
import com.google.devtools.build.lib.analysis.config.BuildConfiguration.StrictDepsMode;
import com.google.devtools.build.lib.analysis.configuredtargets.RuleConfiguredTarget;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.collect.nestedset.Order;
import com.google.devtools.build.lib.packages.AspectDefinition;
import com.google.devtools.build.lib.packages.AspectParameters;
import com.google.devtools.build.lib.packages.Attribute;
import com.google.devtools.build.lib.packages.Attribute.LateBoundDefault;
import com.google.devtools.build.lib.packages.NativeAspectClass;
import com.google.devtools.build.lib.rules.java.JavaCompilationArgsProvider;
import com.google.devtools.build.lib.rules.java.JavaCompilationHelper;
import com.google.devtools.build.lib.rules.java.JavaConfiguration;
import com.google.devtools.build.lib.rules.java.JavaHelper;
import com.google.devtools.build.lib.rules.java.JavaInfo;
import com.google.devtools.build.lib.rules.java.JavaLibraryHelper;
import com.google.devtools.build.lib.rules.java.JavaRuleOutputJarsProvider;
import com.google.devtools.build.lib.rules.java.JavaSemantics;
import com.google.devtools.build.lib.rules.java.JavaSkylarkApiProvider;
import com.google.devtools.build.lib.rules.java.JavaSourceJarsProvider;
import com.google.devtools.build.lib.rules.proto.ProtoCompileActionBuilder;
import com.google.devtools.build.lib.rules.proto.ProtoCompileActionBuilder.ToolchainInvocation;
import com.google.devtools.build.lib.rules.proto.ProtoConfiguration;
import com.google.devtools.build.lib.rules.proto.ProtoLangToolchainProvider;
import com.google.devtools.build.lib.rules.proto.ProtoSourceFileBlacklist;
import com.google.devtools.build.lib.rules.proto.ProtoSourcesProvider;
import com.google.devtools.build.lib.rules.proto.ProtoSupportDataProvider;
import com.google.devtools.build.lib.rules.proto.SupportData;
import javax.annotation.Nullable;

/** An Aspect which JavaProtoLibrary injects to build Java SPEED protos. */
public class JavaProtoAspect extends NativeAspectClass implements ConfiguredAspectFactory {

  private static final String SPEED_PROTO_TOOLCHAIN_ATTR = ":aspect_java_proto_toolchain";
  private final LateBoundDefault<?, Label> hostJdkAttribute;

  private static LateBoundDefault<?, Label> getSpeedProtoToolchainLabel(String defaultValue) {
    return LateBoundDefault.fromTargetConfiguration(
        ProtoConfiguration.class,
        Label.parseAbsoluteUnchecked(defaultValue),
        (rule, attributes, protoConfig) -> protoConfig.protoToolchainForJava());
  }

  private final JavaSemantics javaSemantics;

  @Nullable private final String jacocoLabel;
  private final RpcSupport rpcSupport;
  private final String defaultSpeedProtoToolchainLabel;

  protected JavaProtoAspect(
      JavaSemantics javaSemantics,
      @Nullable String jacocoLabel,
      RpcSupport rpcSupport,
      String defaultSpeedProtoToolchainLabel,
      LateBoundDefault<?, Label> hostJdkAttribute) {
    this.javaSemantics = javaSemantics;
    this.jacocoLabel = jacocoLabel;
    this.rpcSupport = rpcSupport;
    this.defaultSpeedProtoToolchainLabel = defaultSpeedProtoToolchainLabel;
    this.hostJdkAttribute = hostJdkAttribute;
  }

  @Override
  public ConfiguredAspect create(
      ConfiguredTarget base, RuleContext ruleContext, AspectParameters parameters)
      throws InterruptedException {
    ConfiguredAspect.Builder aspect = new ConfiguredAspect.Builder(this, parameters, ruleContext);

    if (!rpcSupport.checkAttributes(ruleContext, parameters)) {
      return aspect.build();
    }

    // Get SupportData, which is provided by the proto_library rule we attach to.
    SupportData supportData =
        checkNotNull(base.getProvider(ProtoSupportDataProvider.class)).getSupportData();

    Impl impl = new Impl(ruleContext, supportData, javaSemantics, rpcSupport);
    if (impl.shouldGenerateCode() && ActionReuser.reuseExistingActions(base, ruleContext, aspect)) {
      return aspect.build();
    }
    impl.addProviders(aspect);
    return aspect.build();
  }

  @Override
  public AspectDefinition getDefinition(AspectParameters aspectParameters) {
    AspectDefinition.Builder result =
        new AspectDefinition.Builder(this)
            .propagateAlongAttribute("deps")
            .requiresConfigurationFragments(JavaConfiguration.class, ProtoConfiguration.class)
            .requireProviders(ProtoSourcesProvider.class)
            .advertiseProvider(JavaProtoLibraryAspectProvider.class)
            .advertiseProvider(ImmutableList.of(JavaSkylarkApiProvider.PROTO_NAME))
            .add(
                attr(SPEED_PROTO_TOOLCHAIN_ATTR, LABEL)
                    // TODO(carmi): reinstate mandatoryNativeProviders(ProtoLangToolchainProvider)
                    // once it's in a Bazel release.
                    .legacyAllowAnyFileType()
                    .value(getSpeedProtoToolchainLabel(defaultSpeedProtoToolchainLabel)))
            .add(attr(":host_jdk", LABEL).cfg(HOST).value(hostJdkAttribute))
            .add(
                attr(":java_toolchain", LABEL)
                    .useOutputLicenses()
                    .allowedRuleClasses("java_toolchain")
                    .value(JavaSemantics.JAVA_TOOLCHAIN));

    rpcSupport.mutateAspectDefinition(result, aspectParameters);

    Attribute.Builder<Label> jacocoAttr = attr("$jacoco_instrumentation", LABEL).cfg(HOST);

    if (jacocoLabel != null) {
      jacocoAttr.value(parseAbsoluteUnchecked(jacocoLabel));
    }
    return result.add(jacocoAttr).build();
  }

  private static class Impl {

    private final RuleContext ruleContext;
    private final SupportData supportData;

    private final RpcSupport rpcSupport;
    private final JavaSemantics javaSemantics;

    /**
     * Compilation-args from all dependencies, merged together. This is typically the input to a
     * Java compilation action.
     */
    private final JavaCompilationArgsProvider dependencyCompilationArgs;

    private final Iterable<JavaProtoLibraryAspectProvider> javaProtoLibraryAspectProviders;

    Impl(
        final RuleContext ruleContext,
        final SupportData supportData,
        JavaSemantics javaSemantics,
        RpcSupport rpcSupport) {
      this.ruleContext = ruleContext;
      this.supportData = supportData;
      this.javaSemantics = javaSemantics;
      this.rpcSupport = rpcSupport;
      this.javaProtoLibraryAspectProviders =
          ruleContext.getPrerequisites(
              "deps", RuleConfiguredTarget.Mode.TARGET, JavaProtoLibraryAspectProvider.class);

      dependencyCompilationArgs =
          JavaCompilationArgsProvider.merge(
              WrappingProvider.Helper.unwrapProviders(
                  javaProtoLibraryAspectProviders, JavaCompilationArgsProvider.class));
    }

    void addProviders(ConfiguredAspect.Builder aspect) {
      // Represents the result of compiling the code generated for this proto, including all of its
      // dependencies.
      JavaCompilationArgsProvider generatedCompilationArgsProvider;

      // The jars that this proto and its dependencies produce. Used to roll-up jars up to the
      // java_proto_library, to be put into filesToBuild.
      NestedSetBuilder<Artifact> transitiveOutputJars = NestedSetBuilder.stableOrder();
      for (JavaProtoLibraryAspectProvider provider : javaProtoLibraryAspectProviders) {
        transitiveOutputJars.addTransitive(provider.getJars());
      }

      TransitiveInfoProviderMapBuilder javaProvidersBuilder =
          new TransitiveInfoProviderMapBuilder();

      if (shouldGenerateCode()) {
        Artifact sourceJar = getSourceJarArtifact();
        createProtoCompileAction(sourceJar);
        Artifact outputJar = getOutputJarArtifact();

        generatedCompilationArgsProvider = createJavaCompileAction(sourceJar, outputJar);

        NestedSet<Artifact> javaSourceJars =
            NestedSetBuilder.<Artifact>stableOrder().add(sourceJar).build();
        transitiveOutputJars.add(outputJar);

        Artifact compileTimeJar =
            getOnlyElement(
                generatedCompilationArgsProvider.getJavaCompilationArgs().getCompileTimeJars());
        // TODO(carmi): Expose to native rules
        JavaRuleOutputJarsProvider ruleOutputJarsProvider =
            JavaRuleOutputJarsProvider.builder()
                .addOutputJar(outputJar, compileTimeJar, ImmutableList.of(sourceJar))
                .build();
        JavaSourceJarsProvider sourceJarsProvider =
            JavaSourceJarsProvider.create(
                NestedSetBuilder.<Artifact>emptySet(Order.STABLE_ORDER), javaSourceJars);

        javaProvidersBuilder.add(ruleOutputJarsProvider).add(sourceJarsProvider);
      } else {
        // No sources - this proto_library is an alias library, which exports its dependencies.
        // Simply propagate the compilation-args from its dependencies.
        generatedCompilationArgsProvider = dependencyCompilationArgs;
        javaProvidersBuilder.add(JavaRuleOutputJarsProvider.EMPTY);
      }

      javaProvidersBuilder.add(generatedCompilationArgsProvider);
      javaProvidersBuilder.add(createCcLinkParamsStore(ruleContext, getProtoRuntimeDeps()));
      TransitiveInfoProviderMap javaProviders = javaProvidersBuilder.build();
      aspect
          .addSkylarkTransitiveInfo(
              JavaSkylarkApiProvider.PROTO_NAME.getLegacyId(),
              JavaSkylarkApiProvider.fromProviderMap(javaProviders))
          .addProvider(
              new JavaProtoLibraryAspectProvider(
                  javaProviders,
                  transitiveOutputJars.build(),
                  createNonStrictCompilationArgsProvider(
                      javaProtoLibraryAspectProviders,
                      generatedCompilationArgsProvider.getJavaCompilationArgs(),
                      getProtoRuntimeDeps())));
    }

    /**
     * Decides whether code should be generated for the .proto files in the currently-processed
     * proto_library.
     */
    private boolean shouldGenerateCode() {
      if (!supportData.hasProtoSources()) {
        return false;
      }

      final ProtoSourceFileBlacklist protoBlackList;
      NestedSetBuilder<Artifact> blacklistedProtos = NestedSetBuilder.stableOrder();
      blacklistedProtos.addTransitive(getProtoToolchainProvider().blacklistedProtos());
      blacklistedProtos.addTransitive(rpcSupport.getBlacklist(ruleContext));

      protoBlackList = new ProtoSourceFileBlacklist(ruleContext, blacklistedProtos.build());

      return protoBlackList.checkSrcs(supportData.getDirectProtoSources(), "java_proto_library");
    }

    private void createProtoCompileAction(Artifact sourceJar) {
      ImmutableList.Builder<ToolchainInvocation> invocations = ImmutableList.builder();
      invocations.add(
          new ToolchainInvocation(
              "java", checkNotNull(getProtoToolchainProvider()), sourceJar.getExecPathString()));
      invocations.addAll(rpcSupport.getToolchainInvocation(ruleContext, sourceJar));
      ProtoCompileActionBuilder.registerActions(
          ruleContext,
          invocations.build(),
          supportData.getDirectProtoSources(),
          supportData.getTransitiveImports(),
          supportData.getProtosInDirectDeps(),
          ruleContext.getLabel(),
          ImmutableList.of(sourceJar),
          "Java (Immutable)",
          rpcSupport.allowServices(ruleContext));
    }

    private JavaCompilationArgsProvider createJavaCompileAction(
        Artifact sourceJar, Artifact outputJar) {
      JavaLibraryHelper helper =
          new JavaLibraryHelper(ruleContext)
              .setOutput(outputJar)
              .addSourceJars(sourceJar)
              .setJavacOpts(ProtoJavacOpts.constructJavacOpts(ruleContext));
      helper.addDep(dependencyCompilationArgs).setCompilationStrictDepsMode(StrictDepsMode.OFF);
      for (TransitiveInfoCollection t : getProtoRuntimeDeps()) {
        JavaCompilationArgsProvider provider =
            JavaInfo.getProvider(JavaCompilationArgsProvider.class, t);
        if (provider != null) {
          helper.addDep(provider);
        }
      }

      return helper.buildCompilationArgsProvider(
          helper.build(
              javaSemantics,
              JavaCompilationHelper.getJavaToolchainProvider(ruleContext),
              JavaHelper.getHostJavabaseInputs(ruleContext),
              JavaCompilationHelper.getInstrumentationJars(ruleContext),
              JavaRuleOutputJarsProvider.builder()),
          true /* isReportedAsStrict */);
    }

    private ImmutableList<TransitiveInfoCollection> getProtoRuntimeDeps() {
      ImmutableList.Builder<TransitiveInfoCollection> result = ImmutableList.builder();
      TransitiveInfoCollection runtime = getProtoToolchainProvider().runtime();
      if (runtime != null) {
        result.add(runtime);
      }
      result.addAll(rpcSupport.getRuntimes(ruleContext));
      return result.build();
    }

    private ProtoLangToolchainProvider getProtoToolchainProvider() {
      return ruleContext.getPrerequisite(
          SPEED_PROTO_TOOLCHAIN_ATTR, TARGET, ProtoLangToolchainProvider.class);
    }

    private Artifact getSourceJarArtifact() {
      return ruleContext.getGenfilesArtifact(ruleContext.getLabel().getName() + "-speed-src.jar");
    }

    private Artifact getOutputJarArtifact() {
      return ruleContext.getBinArtifact("lib" + ruleContext.getLabel().getName() + "-speed.jar");
    }
  }
}


text:
"""
flask_swag
==========

Flask extension that extracts swagger spec from flask app & provides
Swagger UI.

"""
import os
import urllib.parse

from flask import Flask, Blueprint, current_app, jsonify, \
    send_from_directory, url_for, request, redirect

from . import core
from .extractor import Extractor, MarkExtractor
from .globals import SWAGGER_UI_DIR
from .mark import Mark
from .version import VERSION

__version__ = VERSION

class Swag(object):
    """
    Flask extension class for flask_swag.

    This is plain flask extension. So, you can use it like ::

        swag = Swag(app)

    and also ::

        swag = Swag(app)

        # Init later
        swag.init_app(app)

    The extension requires following configurations.

        *   SWAG_TITLE

            Title for swagger info.

        *   SWAG_API_VERSION

            API version info.

    Or you can provide `core.Info` instead of them.

    To customize URL for swagger, use following configurations.

        *   SWAG_BLUEPRINT_NAME

            Default is ``'swag'``

        *   SWAG_URL_PREFIX

            Default is ``'/swagger'``

        *   SWAG_JSON_URL

            Default is ``'/swagger.json'``

        *   SWAG_UI_PREFIX

            Default is ``'/ui'``

    And you can use another version of swagger-ui using configuration.

        *   SWAG_UI_ROOT

    """
    def __init__(self, app: Flask=None, extractor: Extractor=None,
                 mark: Mark=None, *args, **kwargs):
        """
        :param app: app to be initialized
        :param extractor: extractor instance, default is
                          :class:`.extractor.MarkExtractor`
        :param extractor: marker instance, default is
                          :class:`.mark.Mark`
        :param \*args: args to be passed to :meth:`init_app`
        :param \*\*kwargs: kwargs to be passed to :meth:`init_app`

        """
        self.app = app
        self.extractor = extractor or MarkExtractor()
        self.mark = mark or Mark()
        if app is not None:
            self.init_app(app, *args, **kwargs)

    def init_app(self, app, swagger_info=None, swagger_fields=None):
        """Init flask app for Flask-Swag."""
        # Default values for configurations
        app.config.setdefault('SWAG_UI_ROOT', SWAGGER_UI_DIR)
        app.config.setdefault('SWAG_BLUEPRINT_NAME', 'swag')
        app.config.setdefault('SWAG_URL_PREFIX', '/swagger')
        app.config.setdefault('SWAG_JSON_URL', '/swagger.json')
        app.config.setdefault('SWAG_UI_PREFIX', '/ui')

        # Add generator too app
        def generate_swagger():
            return self.generate_swagger(app, swagger_info, swagger_fields)
        app.generate_swagger = generate_swagger

        self.register_blueprint(app)

    def generate_swagger(self, app: Flask=current_app, swagger_info=None,
                         swagger_fields=None, swag_blueprint='swag',
                         extractor_kwargs=None):
        """
        Generate swagger spec from `app`.

        :param app: the flask app.

        :param swagger_info: `info` field in swagger root object.

        :param swagger_fields: extra fields in swagger root object.

        :param swag_blueprint: the name of Flask-Swag blueprint

        :extractor_kwargs: kwargs to be passed to extractor's
                           :meth:`extract_paths`

        """
        # Normalize args
        swagger_fields = swagger_fields or {}
        swagger_info = swagger_info or core.Info(
            title=app.config['SWAG_TITLE'],
            version=app.config['SWAG_API_VERSION'],
        )
        # Extract info from current request
        parsed = urllib.parse.urlparse(request.host_url)
        schemes = [parsed.scheme]
        host = parsed.netloc

        # Extract paths from app
        ex_kwargs = {
            'exclude_blueprint': swag_blueprint,
        }
        ex_kwargs.update(extractor_kwargs or {})
        paths = self.extractor.extract_paths(app, **ex_kwargs)

        # Build kwargs for core.Swagger
        kwargs = {
            'info': swagger_info,
            'host': host,
            'schemes': schemes,
            'version': "2.0",
            'paths': paths,
        }

        # Update with swagger_fields
        kwargs.update(swagger_fields)
        return core.dump(core.Swagger(**kwargs))

    def inject_swagger_url(self, html, url):
        """
        Change default swagger URL by injecting javascript code into html.
        """
        js = """
              $(function() {{
                window.swaggerUi.updateSwaggerUi({{
                    url: '{url}',
                    apiKey: ''
                }});
            }});
        """.format(url=url)
        tag = ''.format(
            js=js
        )
        components = html.rsplit('', 1)
        if len(components) == 1:
            html, = components
            components = html.rsplit('', 1)
            if len(components) == 1:
                html = html + tag
            else:
                first, rest = components
                html = first + tag + '' + rest
        else:
            first, rest = components
            html = first + tag + '' + rest
        return html

    def make_blueprint(self, blueprint_name, swagger_ui_root, json_url,
                       ui_prefix) -> Blueprint:
        """
        Create a new Swagger UI related blueprint.

        :param blueprint_name: name of the blueprint. default is `'swag'`
        :param swagger_ui_root: root path for swagger-ui.
        :param json_url: swagger spec json URL.
        :param ui_prefix: prefix URL for swagger-ui

        """
        blueprint = Blueprint(blueprint_name, __name__)

        @blueprint.route(json_url)
        def swagger_json():
            swagger = current_app.generate_swagger()
            return jsonify(swagger)

        @blueprint.route('{}/<path:path>'.format(ui_prefix))
        def swagger_ui(path):
            return send_from_directory(swagger_ui_root, path,
                                       cache_timeout=3600)

        @blueprint.route('{}/'.format(ui_prefix))
        def swagger_ui_index():
            with open(os.path.join(swagger_ui_root, 'index.html')) as f:
                html = f.read()
            # Inject javascript code
            url = url_for('{}.swagger_json'.format(blueprint_name))
            html = self.inject_swagger_url(html, url)
            return html, 200

        @blueprint.route(ui_prefix)
        def swagger_ui_prefix():
            return redirect('{}.swagger_ui_index'.format(blueprint_name))

        return blueprint

    def register_blueprint(self, app: Flask) \
            -> Blueprint:
        """
        Register Swagger UI related blueprint.

        :param blueprint_name: name of the blueprint. default is `'swag'`
        :param prefix: URL prefix of the blueprint.
        :returns: created blueprint

        """
        prefix = app.config['SWAG_URL_PREFIX']
        blueprint_name = app.config['SWAG_BLUEPRINT_NAME']
        swagger_ui_root = app.config['SWAG_UI_ROOT']
        json_url = app.config['SWAG_JSON_URL']
        ui_prefix = app.config['SWAG_UI_PREFIX']

        blueprint = self.make_blueprint(blueprint_name, swagger_ui_root,
                                        json_url, ui_prefix)
        app.register_blueprint(blueprint, url_prefix=prefix)

        return blueprint


text:
import pouch from 'services/pouch'
import getModels from 'models'

let db = null
let models = null

const thunkMiddleware = ({ dispatch, getState }) => next => action => {
  if (typeof action !== 'function') return next(action)

  let nextDb = pouch.getDb()
  if (nextDb !== db) {
    db = nextDb
    models = db ? getModels(db) : null
  }
  return action(dispatch, { models, getState })
}

export default thunkMiddleware


text:
define("ghost/controllers/settings",
  ["exports"],
  function(__exports__) {
    "use strict";
    var SettingsController = Ember.Controller.extend({
        showGeneral: Ember.computed('session.user.name', function () {
            return this.get('session.user.isAuthor') || this.get('session.user.isEditor') ? false : true;
        }),
        showUsers: Ember.computed('session.user.name', function () {
            return this.get('session.user.isAuthor') ? false : true;
        }),
        showTags: Ember.computed('session.user.name', 'config.tagsUI', function () {
            return this.get('session.user.isAuthor') || !this.get('config.tagsUI') ? false : true;
        }),

        showCodeInjection: Ember.computed('session.user.name', 'config.codeInjectionUI', function () {
            return this.get('session.user.isAuthor') || this.get('session.user.isEditor') || !this.get('config.codeInjectionUI') ? false : true;
        }),

        showLabs: Ember.computed('session.user.name', function () {
            return this.get('session.user.isAuthor')  || this.get('session.user.isEditor') ? false : true;
        }),

        showAbout: Ember.computed('session.user.name', function () {
            return this.get('session.user.isAuthor') ? false : true;
        })
    });

    __exports__["default"] = SettingsController;
  });


text:
use ColorButton;
use Widget;
use ffi;
use gdk;
use glib::object::IsA;
use glib::object::Downcast;
use glib::translate::*;
use std::mem;

pub trait ColorButtonExtManual {
    fn new_with_color(color: &gdk::Color) -> ColorButton;

    fn get_color(&self) -> gdk::Color;

    fn set_color(&self, color: &gdk::Color);
}

impl<O: IsA<ColorButton>> ColorButtonExtManual for O {
    fn new_with_color(color: &gdk::Color) -> ColorButton {
        assert_initialized_main_thread!();
        unsafe {
            Widget::from_glib_none(ffi::gtk_color_button_new_with_color(color)).downcast_unchecked()
        }
    }

    fn get_color(&self) -> gdk::Color {
        unsafe {
            let mut color = mem::uninitialized();
            ffi::gtk_color_button_get_color(self.to_glib_none().0, &mut color);
            color
        }
    }

    fn set_color(&self, color: &gdk::Color) {
        unsafe { ffi::gtk_color_button_set_color(self.to_glib_none().0, color) }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Posadasia esteriformis Cantón

### Remarks
null


text:
import {getTestBed} from '@angular/core/testing';
import {BrowserDynamicTestingModule, platformBrowserDynamicTesting} from '@angular/platform-browser-dynamic/testing';

const platform = platformBrowserDynamicTesting();
getTestBed()
    .initTestEnvironment(BrowserDynamicTestingModule, platform);


text:
using System.IO;
using Stratageme15.Core.JavascriptCodeDom.Statements;

namespace Stratageme15.Core.Compiler.DefaultNodeCompilers.Statements
{
    public class CallStatementNodeCompiler : StatementNodeCompilerBase<CallStatement>
    {
        protected override void CompileStatement(TextWriter output, CallStatement node)
        {
            CompileChild(output,node.CallExpression);
        }
    }
}


text:
package com.tc.websocket;

import org.eclipse.core.runtime.Plugin;
import org.eclipse.osgi.framework.console.CommandProvider;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;

// TODO: Auto-generated Javadoc
/**
 * The Class Activator.
 * Activator for the OSGi environment.
 * Starts and Stops the xockets.io server.
 */
public class Activator extends Plugin {

	/** The plugin id. */
	public static Bundle bundle;

	/** The version. */
	public static String VERSION;

	/** The command line reg. */
	@SuppressWarnings("unused")
	private ServiceRegistration commandLineReg;

	/* (non-Javadoc)
	 * @see org.eclipse.core.runtime.Plugin#start(org.osgi.framework.BundleContext)
	 */
	@Override
	public void start(final BundleContext context) {
		bundle=context.getBundle();
		commandLineReg=context.registerService(CommandProvider.class.getName(), new CommandLine(), null);
		StartAndStop.getInstance().start();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.core.runtime.Plugin#stop(org.osgi.framework.BundleContext)
	 */
	@Override
	public void stop(final BundleContext context) {
		StartAndStop.getInstance().stop();
	}

}


text:
title: Configuring
description: Detailed information on the documentation scaffold configuration process.
lunr: true
nav_sort: 1
nav_groups:
  - primary
tags:
  - config
  - configuring
collection: gettingstarted
order: 2
---
Configuring your new documentation project is as simple as altering the configuration files in the `config` folder.

Make sure that your `config/config.js` variable `webRoot` matches the root folder of where the documentation will be hosted. For example: if you plan on hosting the documentation at `https://you.github.io/your-documentation`, the `webRoot` should be `/your-documentation/`.

If you would like to use a logo of a different aspect ratio than the example logo `144x40px` you might have to adjust the margins in `style/layout/_nav.scss`.


text:
<?php

namespace ApiPlatform\Core\Bridge\Doctrine\Orm\Extension;

use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use Doctrine\ORM\QueryBuilder;

/**
 * Interface of Doctrine ORM query extensions for collection queries.
 *
 * @author Samuel ROZE <samuel.roze@gmail.com>
 * @author Kévin Dunglas <dunglas@gmail.com>
 */
interface QueryCollectionExtensionInterface
{
    /**
     * @param QueryBuilder                $queryBuilder
     * @param QueryNameGeneratorInterface $queryNameGenerator
     * @param string                      $resourceClass
     * @param string|null                 $operationName
     */
    public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, string $operationName = null);
}


text:
<?php
/**
 * Show a form to the user so he can fill his email
 * It then send the postcard by email
 *
 * @author     P. Henelle for Cubitux
 * @license    BSD License (https://github.com/phenelle/RPi_Photoboth/blob/master/LICENSE)
 * @version    1.0
 */

  require_once('config.php');

  $lng = $_REQUEST['lng'];
  $photo1 = $_REQUEST['photo1'];
  $photo2 = $_REQUEST['photo2'];
  $photo3 = $_REQUEST['photo3'];
?>
<!DOCTYPE html>

  <meta charset="UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Cubitux PhotoBooth</title>
  <meta http-equiv="Cache-Control" content="no-cache" />
  <meta http-equiv="Pragma" content="no-cache" />
  <meta http-equiv="Expires" content="0" />
  <link rel="stylesheet" type="text/css" href="fonts/poppins.css" />
  <link rel="stylesheet" type="text/css" href="stylesheets/styles.css" />

  <?php if (VIRTUAL_KEYBOARD): ?>

    <link href="jquery-ui-1.12.1.custom/jquery-ui.min.css" />
    <link href="css/virtual_keyboard.css" />
    <link href="keyboard/Keyboard-master/css/keyboard.css" rel="stylesheet">

  <?php endif; ?>

         <form action="sendmail_form.php">
            <input type="hidden" name="lng" value="<?php echo $lng ?>">
            <input type="hidden" name="photo1" value="<?php echo $photo1 ?>">
            <input type="hidden" name="photo2" value="<?php echo $photo2 ?>">
            <input type="hidden" name="photo3" value="<?php echo $photo3 ?>">
            <input id="email-input" class="keyboard-init-focus" type="email" name="email" placeholder="<?php echo ($lng == "fr") ? 'Ecrivez votre courriel' : "Type your email" ?>" />

<button type="reset" onclick="backHome()"><?php echo ($lng == "fr") ? "Annuler" : "Cancel" ?></button>

<button type="submit"><?php echo ($lng == "fr") ? "Envoyer" : "Sent" ?></button>

         </form>


text:
def show_toolbar(self):
    return True


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                "http://www.w3.org/TR/REC-html40/loose.dtd">

  <title>Description of intersectLinePlane</title>
  <meta name="keywords" content="intersectLinePlane">
  <meta name="description" content="INTERSECTLINEPLANE return intersection between a plane and a line">
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <meta name="generator" content="m2html © 2003 Guillaume Flandin">
  <meta name="robots" content="index, follow">
  <link type="text/css" rel="stylesheet" href="../../m2html.css">

Home >  imael > geom3d > intersectLinePlane.m

intersectLinePlane

PURPOSE

INTERSECTLINEPLANE return intersection between a plane and a line

SYNOPSIS

function point = intersectLinePlane(line, plane)

DESCRIPTION

INTERSECTLINEPLANE return intersection between a plane and a line

   PT = intersectLinePlane(LINE, PLANE)
   Returns the intersection point of the given line and the given plane.
   PLANE : [x0 y0 z0 dx1 dy1 dz1 dx2 dy2 dz2]
   LINE :  [x0 y0 z0 dx dy dz]
   PT :    [xi yi zi]
   If LINE and PLANE are parallel, return [NaN NaN NaN].
   If LINE (or PLANE) is a matrix with 6 (or 9) columns and N rows, result
   is an array of points with N rows and 3 columns.

   See also:
   lines3d, planes3d, points3d, intersectEdgePlane

   ---------
   author : David Legland
   INRA - TPV URPOI - BIA IMASTE
   created the 17/02/2005.

CROSS-REFERENCE INFORMATION

This function calls:

This function is called by:

clipConvexPolygon3dHP	CLIPCONVEXPOLYGON3DHP clip a convex 3D polygon with Half-space

clipLine3d	CLIPLINE3D clip a line with a box and return an edge

drawPlane3d	DRAWPLANE3D draw a plane clipped in the current window

drawSphericalTriangle	DRAWSPHERICALTRIANGLE draw a triangle on a sphere

projPointOnPlane	PROJPOINTONPLANE return the projection of a point on a plane

<address>Generated on Fri 05-Feb-2010 11:20:41 by m2html © 2003</address>


text:
log_level = Logger.const_get Errbit::Config.log_level.upcase

Mongoid.logger.level = log_level
Mongo::Logger.level = log_level

Mongoid.configure do |config|
  uri = if Errbit::Config.mongo_url == 'mongodb://localhost'
          "mongodb://localhost/errbit_#{Rails.env}"
        else
          Errbit::Config.mongo_url
        end

  config.load_configuration(
    clients: {
      default: {
        uri: uri
      }
    },
    options: {
      use_activesupport_time_zone: true
    }
  )
end


text:
package org.qi4j.entitystore.hazelcast.assembly;

import org.qi4j.api.common.Visibility;
import org.qi4j.bootstrap.Assembler;
import org.qi4j.bootstrap.AssemblyException;
import org.qi4j.bootstrap.ModuleAssembly;
import org.qi4j.entitystore.hazelcast.HazelcastConfiguration;
import org.qi4j.entitystore.hazelcast.HazelcastEntityStoreService;
import org.qi4j.spi.uuid.UuidIdentityGeneratorService;

public class HazelcastEntityStoreAssembler
    implements Assembler
{

    private final Visibility visibility;
    private ModuleAssembly config;
    private Visibility configVisibility;

    public HazelcastEntityStoreAssembler()
    {
        this( Visibility.application );
    }

    public HazelcastEntityStoreAssembler( Visibility visibility )
    {
        this.visibility = visibility;
    }

    public HazelcastEntityStoreAssembler withConfigIn( ModuleAssembly config, Visibility configVisibility )
    {
        this.config = config;
        this.configVisibility = configVisibility;
        return this;
    }

    @Override
    public void assemble( ModuleAssembly module )
        throws AssemblyException
    {
        module.services( HazelcastEntityStoreService.class ).visibleIn( visibility ).instantiateOnStartup();
        module.services( UuidIdentityGeneratorService.class ).visibleIn( visibility );
        if( config != null )
        {
            config.entities( HazelcastConfiguration.class ).visibleIn( configVisibility );
        }
    }
}


text:
import React from "react";
import PropTypes from "prop-types";
import { css } from "emotion";
import ThemeContext from "@hig/theme-context";
import stylesheet from "./stylesheet";

/**
 * @typedef {Object} BannerActionProps
 * @property {any} children
 * @property {Function} stylesheet
 */

/**
 * @param {BannerActionProps} props
 * @returns {JSX.Element}
 */
export default function BannerAction({
  children,
  stylesheet: customStylesheet,
}) {
  return (
    <ThemeContext.Consumer>
      {({ resolvedRoles }) => (
        <div
          className={css(
            stylesheet({ stylesheet: customStylesheet }, resolvedRoles)
          )}
        >
          {children}
        </div>
      )}
    </ThemeContext.Consumer>
  );
}

BannerAction.propTypes = {
  children: PropTypes.node,
  stylesheet: PropTypes.func,
};


text:
#pragma once

#include "il2cpp-config.h"

#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif

#include <stdint.h>
#include <assert.h>
#include <exception>

// Mono.Security.Protocol.Tls.CertificateValidationCallback2
struct CertificateValidationCallback2_t1582269749;
// System.Object
struct Il2CppObject;
// Mono.Security.Protocol.Tls.ValidationResult
struct ValidationResult_t2397874734;
// Mono.Security.X509.X509CertificateCollection
struct X509CertificateCollection_t3336811651;
// System.IAsyncResult
struct IAsyncResult_t537683269;
// System.AsyncCallback
struct AsyncCallback_t1363551830;

#include "codegen/il2cpp-codegen.h"
#include "mscorlib_System_Object837106420.h"
#include "mscorlib_System_IntPtr676692020.h"
#include "Mono_Security_Mono_Security_X509_X509CertificateCo3336811650.h"
#include "mscorlib_System_AsyncCallback1363551830.h"

// System.Void Mono.Security.Protocol.Tls.CertificateValidationCallback2::.ctor(System.Object,System.IntPtr)
extern "C"  void CertificateValidationCallback2__ctor_m1854682743 (CertificateValidationCallback2_t1582269749 * __this, Il2CppObject * ___object, IntPtr_t ___method, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// Mono.Security.Protocol.Tls.ValidationResult Mono.Security.Protocol.Tls.CertificateValidationCallback2::Invoke(Mono.Security.X509.X509CertificateCollection)
extern "C"  ValidationResult_t2397874734 * CertificateValidationCallback2_Invoke_m4228010672 (CertificateValidationCallback2_t1582269749 * __this, X509CertificateCollection_t3336811651 * ___collection, const MethodInfo* method) IL2CPP_METHOD_ATTR;
extern "C" ValidationResult_t2397874734 * pinvoke_delegate_wrapper_CertificateValidationCallback2_t1582269749(Il2CppObject* delegate, X509CertificateCollection_t3336811651 * ___collection);
// System.IAsyncResult Mono.Security.Protocol.Tls.CertificateValidationCallback2::BeginInvoke(Mono.Security.X509.X509CertificateCollection,System.AsyncCallback,System.Object)
extern "C"  Il2CppObject * CertificateValidationCallback2_BeginInvoke_m1231864174 (CertificateValidationCallback2_t1582269749 * __this, X509CertificateCollection_t3336811651 * ___collection, AsyncCallback_t1363551830 * ___callback, Il2CppObject * ___object, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// Mono.Security.Protocol.Tls.ValidationResult Mono.Security.Protocol.Tls.CertificateValidationCallback2::EndInvoke(System.IAsyncResult)
extern "C"  ValidationResult_t2397874734 * CertificateValidationCallback2_EndInvoke_m2684174416 (CertificateValidationCallback2_t1582269749 * __this, Il2CppObject * ___result, const MethodInfo* method) IL2CPP_METHOD_ATTR;