text:
package org.andengine.opengl.texture;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;

import org.andengine.opengl.texture.bitmap.AssetBitmapTexture;
import org.andengine.opengl.texture.bitmap.BitmapTexture;
import org.andengine.opengl.texture.bitmap.BitmapTextureFormat;
import org.andengine.opengl.util.GLState;
import org.andengine.util.adt.io.in.IInputStreamOpener;
import org.andengine.util.debug.Debug;

import android.content.res.AssetManager;

/**
 * (c) 2010 Nicolas Gramlich
 * (c) 2011 Zynga Inc.
 *
 * @author Nicolas Gramlich
 * @since 17:48:46 - 08.03.2010
 */
public class TextureManager {
	// ===========================================================
	// Constants
	// ===========================================================

	// ===========================================================
	// Fields
	// ===========================================================

	private final HashSet<ITexture> mTexturesManaged = new HashSet<ITexture>();
	private final HashMap<String, ITexture> mTexturesMapped = new HashMap<String, ITexture>();

	private final ArrayList<ITexture> mTexturesLoaded = new ArrayList<ITexture>();

	private final ArrayList<ITexture> mTexturesToBeLoaded = new ArrayList<ITexture>();
	private final ArrayList<ITexture> mTexturesToBeUnloaded = new ArrayList<ITexture>();

	private TextureWarmUpVertexBufferObject mTextureWarmUpVertexBufferObject;

	private int mTextureMemoryUsed;

	// ===========================================================
	// Constructors
	// ===========================================================

	// ===========================================================
	// Getter & Setter
	// ===========================================================

	public int getTextureMemoryUsed() {
		return this.mTextureMemoryUsed;
	}

	public int getTexturesLoadedCount() {
		return this.mTexturesLoaded.size();
	}

	// ===========================================================
	// Methods for/from SuperClass/Interfaces
	// ===========================================================

	// ===========================================================
	// Methods
	// ===========================================================

	public synchronized void onCreate() {
		this.mTextureWarmUpVertexBufferObject = new TextureWarmUpVertexBufferObject();
	}

	public synchronized void onReload() {
		final HashSet<ITexture> managedTextures = this.mTexturesManaged;
		if (!managedTextures.isEmpty()) {
			for (final ITexture texture : managedTextures) { // TODO Can the use of the iterator be avoided somehow?
				texture.setNotLoadedToHardware();
			}
		}

		if (!this.mTexturesLoaded.isEmpty()) {
			this.mTexturesToBeLoaded.addAll(this.mTexturesLoaded); // TODO Check if addAll uses iterator internally!
			this.mTexturesLoaded.clear();
		}

		if (!this.mTexturesToBeUnloaded.isEmpty()) {
			this.mTexturesManaged.removeAll(this.mTexturesToBeUnloaded); // TODO Check if removeAll uses iterator internally!
			this.mTexturesToBeUnloaded.clear();
		}

		this.mTextureWarmUpVertexBufferObject.setNotLoadedToHardware();

		this.mTextureMemoryUsed = 0;
	}

	public synchronized void onDestroy() {
		final HashSet<ITexture> managedTextures = this.mTexturesManaged;
		for (final ITexture texture : managedTextures) { // TODO Can the use of the iterator be avoided somehow?
			texture.setNotLoadedToHardware();
		}

		this.mTexturesToBeLoaded.clear();
		this.mTexturesLoaded.clear();
		this.mTexturesManaged.clear();
		this.mTexturesMapped.clear();

		this.mTextureWarmUpVertexBufferObject.dispose();
		this.mTextureWarmUpVertexBufferObject = null;

		this.mTextureMemoryUsed = 0;
	}

	public synchronized boolean hasMappedTexture(final String pID) {
		if (pID == null) {
			throw new IllegalArgumentException("pID must not be null!");
		}
		return this.mTexturesMapped.containsKey(pID);
	}

	public synchronized ITexture getMappedTexture(final String pID) {
		if (pID == null) {
			throw new IllegalArgumentException("pID must not be null!");
		}
		return this.mTexturesMapped.get(pID);
	}

	public synchronized void addMappedTexture(final String pID, final ITexture pTexture) throws IllegalArgumentException {
		if (pID == null) {
			throw new IllegalArgumentException("pID must not be null!");
		} else if (pTexture == null) {
			throw new IllegalArgumentException("pTexture must not be null!");
		} else if (this.mTexturesMapped.containsKey(pID)) {
			throw new IllegalArgumentException("Collision for pID: '" + pID + "'.");
		}
		this.mTexturesMapped.put(pID, pTexture);
	}

	public synchronized ITexture removedMappedTexture(final String pID) {
		if (pID == null) {
			throw new IllegalArgumentException("pID must not be null!");
		}
		return this.mTexturesMapped.remove(pID);
	}

	/**
	 * @param pTexture the {@link org.andengine.opengl.texture.ITexture} to be loaded before the very next frame is drawn (Or prevent it from being unloaded then).
	 * @return true when the {@link org.andengine.opengl.texture.ITexture} was previously not managed by this {@link org.andengine.opengl.texture.TextureManager}, false if it was already managed.
	 */
	public synchronized boolean loadTexture(final ITexture pTexture) {
		if (pTexture == null) {
			throw new IllegalArgumentException("pTexture must not be null!");
		}

		if (this.mTexturesManaged.contains(pTexture)) {
			/* Just make sure it doesn't get deleted. */
			this.mTexturesToBeUnloaded.remove(pTexture);
			return false;
		} else {
			this.mTexturesManaged.add(pTexture);
			this.mTexturesToBeLoaded.add(pTexture);
			return true;
		}
	}

	/**
	 * Must be called from the GL-{@link Thread}.
	 *
	 * @param pGLState
	 * @param pTexture the {@link org.andengine.opengl.texture.ITexture} to be loaded right now, if it is not loaded.
	 * @return true when the {@link org.andengine.opengl.texture.ITexture} was previously not managed by this {@link org.andengine.opengl.texture.TextureManager}, false if it was already managed.
	 */
	public synchronized boolean loadTexture(final GLState pGLState, final ITexture pTexture) throws IOException {
		if (pTexture == null) {
			throw new IllegalArgumentException("pTexture must not be null!");
		}

		if (!pTexture.isLoadedToHardware()) {
			pTexture.loadToHardware(pGLState);
		} else if (pTexture.isUpdateOnHardwareNeeded()) {
			pTexture.reloadToHardware(pGLState);
		}

		if (this.mTexturesManaged.contains(pTexture)) {
			/* Just make sure it doesn't get deleted. */
			this.mTexturesToBeUnloaded.remove(pTexture);
			return false;
		} else {
			this.mTexturesManaged.add(pTexture);
			this.mTexturesLoaded.add(pTexture);
			return true;
		}
	}

	/**
	 * @param pTexture the {@link org.andengine.opengl.texture.ITexture} to be unloaded before the very next frame is drawn (Or prevent it from being loaded then).
	 * @return true when the {@link org.andengine.opengl.texture.ITexture} was already managed by this {@link org.andengine.opengl.texture.TextureManager}, false if it was not managed.
	 */
	public synchronized boolean unloadTexture(final ITexture pTexture) {
		if (pTexture == null) {
			throw new IllegalArgumentException("pTexture must not be null!");
		}

		if (this.mTexturesManaged.contains(pTexture)) {
			/* If the Texture is loaded, unload it.
			 * If the Texture is about to be loaded, stop it from being loaded. */
			if (this.mTexturesLoaded.contains(pTexture)) {
				this.mTexturesToBeUnloaded.add(pTexture);
			} else if (this.mTexturesToBeLoaded.remove(pTexture)) {
				this.mTexturesManaged.remove(pTexture);
			}
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Must be called from the GL-{@link Thread}.
	 *
	 * @param pGLState
	 * @param pTexture the {@link org.andengine.opengl.texture.ITexture} to be unloaded right now, if it is loaded.
	 * @return true when the {@link org.andengine.opengl.texture.ITexture} was already managed by this {@link org.andengine.opengl.texture.TextureManager}, false if it was not managed.
	 */
	public synchronized boolean unloadTexture(final GLState pGLState, final ITexture pTexture) {
		if (pTexture == null) {
			throw new IllegalArgumentException("pTexture must not be null!");
		} else if (pTexture.isLoadedToHardware()) {
			pTexture.unloadFromHardware(pGLState);
		}

		if (this.mTexturesManaged.contains(pTexture)) {
			/* Just make sure it doesn't get loaded. */
			this.mTexturesLoaded.remove(pTexture);
			this.mTexturesToBeLoaded.remove(pTexture);

			return true;
		} else {
			return false;
		}
	}

	public synchronized void updateTextures(final GLState pGLState) {
		final HashSet<ITexture> texturesManaged = this.mTexturesManaged;
		final ArrayList<ITexture> texturesLoaded = this.mTexturesLoaded;
		final ArrayList<ITexture> texturesToBeLoaded = this.mTexturesToBeLoaded;
		final ArrayList<ITexture> texturesToBeUnloaded = this.mTexturesToBeUnloaded;

		/* First reCreate Textures that need to be updated. */
		for (int i = texturesLoaded.size() - 1; i >= 0; i--) {
			final ITexture textureToBeReloaded = texturesLoaded.get(i);
			if (textureToBeReloaded.isUpdateOnHardwareNeeded()) {
				try {
					textureToBeReloaded.reloadToHardware(pGLState);
				} catch (final IOException e) {
					Debug.e(e);
				}
			}
		}

		/* Then load pending Textures. */
		final int texturesToBeLoadedCount = texturesToBeLoaded.size();

		if (texturesToBeLoadedCount > 0) {
			for (int i = texturesToBeLoadedCount - 1; i >= 0; i--) {
				final ITexture textureToBeLoaded = texturesToBeLoaded.remove(i);
				if (!textureToBeLoaded.isLoadedToHardware()) {
					try {
						textureToBeLoaded.loadToHardware(pGLState);

						this.mTextureMemoryUsed += textureToBeLoaded.getTextureMemorySize();

						/* Execute the warm-up to ensure the texture data is actually moved to the GPU. */
						this.mTextureWarmUpVertexBufferObject.warmup(pGLState, textureToBeLoaded);
					} catch (final IOException e) {
						Debug.e(e);
					}
				}
				texturesLoaded.add(textureToBeLoaded);
			}
		}

		/* Then unload pending Textures. */
		final int texturesToBeUnloadedCount = texturesToBeUnloaded.size();

		if (texturesToBeUnloadedCount > 0) {
			for (int i = texturesToBeUnloadedCount - 1; i >= 0; i--) {
				final ITexture textureToBeUnloaded = texturesToBeUnloaded.remove(i);
				if (textureToBeUnloaded.isLoadedToHardware()) {
					textureToBeUnloaded.unloadFromHardware(pGLState);

					this.mTextureMemoryUsed -= textureToBeUnloaded.getTextureMemorySize();
				}
				texturesLoaded.remove(textureToBeUnloaded);
				texturesManaged.remove(textureToBeUnloaded);
			}
		}

		/* Finally invoke the GC if anything has changed. */
		if ((texturesToBeLoadedCount > 0) || (texturesToBeUnloadedCount > 0)) {
			System.gc();
		}
	}

	public synchronized ITexture getTexture(final String pID, final AssetManager pAssetManager, final String pAssetPath) throws IOException {
		return this.getTexture(pID, pAssetManager, pAssetPath, TextureOptions.DEFAULT);
	}

	public synchronized ITexture getTexture(final String pID, final AssetManager pAssetManager, final String pAssetPath, final TextureOptions pTextureOptions) throws IOException {
		if (this.hasMappedTexture(pID)) {
			return this.getMappedTexture(pID);
		} else {
			final ITexture texture = new AssetBitmapTexture(this, pAssetManager, pAssetPath, pTextureOptions);
			this.loadTexture(texture);
			this.addMappedTexture(pID, texture);

			return texture;
		}
	}

	public synchronized ITexture getTexture(final String pID, final IInputStreamOpener pInputStreamOpener) throws IOException {
		return this.getTexture(pID, pInputStreamOpener, TextureOptions.DEFAULT);
	}

	public synchronized ITexture getTexture(final String pID, final IInputStreamOpener pInputStreamOpener, final TextureOptions pTextureOptions) throws IOException {
		return this.getTexture(pID, pInputStreamOpener, BitmapTextureFormat.RGBA_8888, pTextureOptions);
	}

	public synchronized ITexture getTexture(final String pID, final IInputStreamOpener pInputStreamOpener, final BitmapTextureFormat pBitmapTextureFormat, final TextureOptions pTextureOptions) throws IOException {
		return this.getTexture(pID, pInputStreamOpener, pBitmapTextureFormat, pTextureOptions, true);
	}

	public synchronized ITexture getTexture(final String pID, final IInputStreamOpener pInputStreamOpener, final BitmapTextureFormat pBitmapTextureFormat, final TextureOptions pTextureOptions, final boolean pLoadToHardware) throws IOException {
		if (this.hasMappedTexture(pID)) {
			return this.getMappedTexture(pID);
		} else {
			final ITexture texture = new BitmapTexture(this, pInputStreamOpener, pBitmapTextureFormat, pTextureOptions);
			if (pLoadToHardware) {
				this.loadTexture(texture);
			}
			this.addMappedTexture(pID, texture);

			return texture;
		}
	}

	// ===========================================================
	// Inner and Anonymous Classes
	// ===========================================================
}


text:
using Bridge.Html5;
using System;

namespace Bridge.ChartJS
{
    [ObjectLiteral]
    [External]
    public class LegendConfig
    {
        /// <summary>
        /// Is the legend displayed, default is true
        /// </summary>
        public bool Display = true;
        /// <summary>
        /// Position of the legend.
        /// </summary>
        public Position Position = Position.Top;
        /// <summary>
        /// Marks that this box should take the full width of the canvas (pushing down other boxes)
        /// </summary>
        public bool FullWidth = true;
        /// <summary>
        /// Legend will show datasets in reverse order
        /// </summary>
        public bool Reverse = false;
        /// <summary>
        /// A callback that is called when a 'click' event is registered on top of a label item
        /// </summary>
        public Action<Event, object> OnClick;
        /// <summary>
        /// A callback that is called when a 'mousemove' event is registered on top of a label item
        /// </summary>
        public Action<Event, object> OnHover;
        /// <summary>
        /// label configuration of legend
        /// </summary>
        public LegendLabelConfig Labels;

    }
}

redpajama_set_name: RedPajamaGithub


text:
from flocker.node.agents.blockdevice import (
    VolumeException, AlreadyAttachedVolume,
    UnknownVolume, UnattachedVolume,
    IBlockDeviceAPI, BlockDeviceVolume
)

from eliot import Message, Logger
from twisted.python.filepath import FilePath
from zope.interface import implementer
import os
import socket
import requests

_logger = Logger()

class NedgeConfig(object):
    def __init__(self, cluster_id, tenant_id, bucket_id, chunk_sz):
        self._cluster_id = cluster_id
        self._tenant_id = tenant_id
        self._bucket_id = bucket_id
        self._chunk_sz = chunk_sz
	self.cdnbd_url = 'http://127.0.0.1:8080/nbd'
	self.adttnbd_url = 'http://127.0.0.1:8080/nbd/register'

    def get_chunk_sz(self):
        return self._chunk_sz

    def get_clust_id_str(self):
        return str(self._cluster_id)

    def get_tenant_id_str(self):
        return str(self._tenant_id)

    def get_bucket_id_str(self):
        return str(self._bucket_id)

    def get_objpath_str(self, idx):
        return self.get_clust_id_str() + '/' + \
               self.get_tenant_id_str() + '/' + \
               self.get_bucket_id_str() + '/' + str(idx)

@implementer(IBlockDeviceAPI)
class NedgeBlockDeviceAPI(object):

    def __init__(self, nedge_conf, compute_instance_id=socket.gethostname(),
                 allocation_unit=4096):
        self._config = nedge_conf
        self._node_id = compute_instance_id
        self._chunk_sz = allocation_unit
        self._objs_list = {}
        self._reqdata = {}

    def _get_vol(self, blockdevice_id):
        try:
            vol = self._objs_list[str(blockdevice_id)]
            if vol is not None:
                return vol
            else:
                raise UnknownVolume(blockdevice_id)
        except:
            raise UnknownVolume(blockdevice_id)

    def compute_instance_id(self):
        return self._node_id

    def allocation_unit(self):
        return self._chunk_sz

    def create_volume(self, dataset_id, size):
        volume = BlockDeviceVolume(size=size, attached_to=None,
                                 dataset_id=dataset_id,
                                 blockdevice_id=u"nedge-{0}".format(dataset_id))
        obj_idx = len(self._objs_list)
        self._reqdata.clear();
        self._reqdata['number'] = obj_idx
        self._reqdata['volSizeMB'] = size >> 20
        self._reqdata['blockSize'] = 512
        self._reqdata['chunkSize'] = self._chunk_sz
        self._reqdata['objectPath'] = self._config.get_objpath_str(obj_idx)

        resp = requests.post(self._config.cdnbd_url, self._reqdata)
        if resp.status_code > 199 and resp.status_code < 300:
            self._objs_list[str(volume.blockdevice_id)] = volume
        else:
            volume = None

        return volume

    def destroy_volume(self, blockdevice_id):
        try:
            volume = self._get_vol(blockdevice_id)
            obj_idx = self._objs_list.values().index(volume)
            self._objs_list.pop(str(blockdevice_id), None)

            self._reqdata.clear();
            self._reqdata['number'] = obj_idx
            self._reqdata['objectPath'] = self._config.get_objpath_str(obj_idx)
            resp = requests.delete(self._config.cdnbd_url, data=self._reqdata)
            if resp.status_code != requests.codes.ok:
                Message.new(resp.text).write(_logger)
        except:
            raise

    def destroy_volume_folder(self):
        #Do nothing for now
        return

    def attach_volume(self, blockdevice_id, attach_to):
        try:
            volume = self._get_vol(blockdevice_id)
            if volume.attached_to is None:
                obj_idx = self._objs_list.values().index(volume)
                self._reqdata.clear();
                self._reqdata['number'] = obj_idx
                self._reqdata['objectPath'] = self._config.get_objpath_str(obj_idx)

                resp = requests.post(self._config.adttnbd_url, self._reqdata)
                if resp.status_code == 204:
                    att_vol = volume.set(attached_to=unicode(attach_to))
                    self._objs_list[str(blockdevice_id)] = att_vol
                else:
                    att_vol = None
                return att_vol
            else:
                raise AlreadyAttachedVolume(blockdevice_id)
        except:
            raise

    def resize_volume(self, blockdevice_id, size):
        #Do nothing for now
        return

    def detach_volume(self, blockdevice_id):
        try:
            volume = self._get_vol(blockdevice_id)
            if volume.attached_to is not None:
                obj_idx = self._objs_list.values().index(volume)
                self._reqdata.clear();
                self._reqdata['number'] = obj_idx
                self._reqdata['objectPath'] = self._config.get_objpath_str(obj_idx)

                resp = requests.delete(self._config.adttnbd_url, data=self._reqdata)
                if resp.status_code == requests.codes.ok:
                    dtt_vol = volume.set(attached_to=None)
                    self._objs_list[str(blockdevice_id)] = dtt_vol
            else:
                Message.new(Info='Volume' + blockdevice_id + 'not attached').write(_logger)
                raise UnattachedVolume(blockdevice_id)
        except:
            raise

    def list_volumes(self):
        return self._objs_list.values()

    def get_device_path(self, blockdevice_id):
        try:
            volume = self._get_vol(blockdevice_id)
            if volume.attached_to is not None:
                return FilePath('/dev/nbd' + \
                                str(self._objs_list.values().index(volume)))
            else:
                Message.new(Info='Volume' + blockdevice_id + 'not attached').write(_logger)
                raise UnattachedVolume(blockdevice_id)
        except:
            raise

def get_nedge_block_api(conf):
    return NedgeBlockDeviceAPI(conf,
                compute_instance_id=unicode(socket.gethostname()),
                allocation_unit=conf.get_chunk_sz())


text:
<resources>
    <string name="app_name">Huffman Keyboard</string>

    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="huffman_keyboard_settings">Huffman Keybaord Settings</string>
    <string name="huffman_keyboard_name">Huffman Keyboard</string>
</resources>


text:
namespace clover {
namespace physics {

//
// Tightly coupled utility functions
//

template <typename T>
void createB2Joint(b2JointDef& def, T*& joint){
	ensure(!joint);
	joint= static_cast<T*>(global::g_env.physMgr->getWorld().getB2World().CreateJoint(&def));
}

template <typename T>
void destroyB2Joint(T*& joint){
	ensure(joint);
	global::g_env.physMgr->getWorld().getB2World().DestroyJoint(joint);
	joint= nullptr;
}

/// @note Current b2Bodies of joints can be different than new bodies in recreation
/// @todo Handle frequencies etc. when mass of attached body changes

template <typename Joint, typename Def>
void recreateB2Joint_basic(Def& def, Joint*& joint, b2Body* b1, b2Body* b2){
	ensure(b1 && b2);

	b2Vec2 new_anchor1= b1->GetLocalPoint(joint->GetAnchorA());
	b2Vec2 new_anchor2= b2->GetLocalPoint(joint->GetAnchorB());

	destroyB2Joint(joint);
	def.bodyA= b1;
	def.bodyB= b2;
	def.localAnchorA= new_anchor1;
	def.localAnchorB= new_anchor2;
	createB2Joint(def, joint);
}

template <typename Joint, typename Def>
void recreateB2Joint_refAngle(Def& def, Joint*& joint, b2Body* b1, b2Body* b2){
	ensure(b1 && b2);

	b2Vec2 new_anchor1= b1->GetLocalPoint(joint->GetAnchorA());
	b2Vec2 new_anchor2= b2->GetLocalPoint(joint->GetAnchorB());
	/// @todo Test with limits
	real64 new_ref_angle= b2->GetAngle() - b1->GetAngle();

	destroyB2Joint(joint);
	def.bodyA= b1;
	def.bodyB= b2;
	def.localAnchorA= new_anchor1;
	def.localAnchorB= new_anchor2;
	def.referenceAngle= new_ref_angle;
	createB2Joint(def, joint);
}

void recreateB2Joint(b2DistanceJointDef& def, b2DistanceJoint*& joint,
		b2Body* b1, b2Body* b2){
	recreateB2Joint_basic(def, joint, b1, b2);
}

void recreateB2Joint(b2FrictionJointDef& def, b2FrictionJoint*& joint,
		b2Body* b1, b2Body* b2){
	recreateB2Joint_basic(def, joint, b1, b2);
}

void recreateB2Joint(b2MouseJointDef& def, b2MouseJoint*& joint,
		b2Body* b1, b2Body* b2){
	ensure(b1);
	ensure(b2 == nullptr);

	b2Vec2 anchor= joint->GetAnchorB();
	b2Vec2 target= def.target;

	destroyB2Joint(joint);
	def.target= anchor; // Target (anchor) is in the right spot on object
	def.bodyB= b1;
	createB2Joint(def, joint);

	// Change target back to where it was before recreation (anchor remains)
	def.target= target;
	joint->SetTarget(target);
}

void recreateB2Joint(b2PrismaticJointDef& def, b2PrismaticJoint*& joint,
		b2Body* b1, b2Body* b2){
	recreateB2Joint_refAngle(def, joint, b1, b2);
}

void recreateB2Joint(b2RevoluteJointDef& def, b2RevoluteJoint*& joint,
		b2Body* b1, b2Body* b2){
	recreateB2Joint_refAngle(def, joint, b1, b2);
}

void recreateB2Joint(b2RopeJointDef& def, b2RopeJoint*& joint,
		b2Body* b1, b2Body* b2){
	recreateB2Joint_basic(def, joint, b1, b2);
}

void recreateB2Joint(b2WeldJointDef& def, b2WeldJoint*& joint,
		b2Body* b1, b2Body* b2){
	recreateB2Joint_refAngle(def, joint, b1, b2);
}

void recreateB2Joint(b2WheelJointDef& def, b2WheelJoint*& joint,
		b2Body* b1, b2Body* b2){
	recreateB2Joint_basic(def, joint, b1, b2);
}

//
// B2Joint
//

template <typename DefType, typename JointType>
void B2Joint<DefType, JointType>::detach(){
	Joint::detach();

	if (joint)
		destroyB2Joint();
}

template <typename DefType, typename JointType>
WorldVec B2Joint<DefType, JointType>::getAnchor(SizeType i) const {
	ensure(joint);
	if (i == 0)
		return fromB2(joint->GetAnchorA());
	if (i == 1)
		return fromB2(joint->GetAnchorB());
	release_ensure(0);
	std::abort();
}

template <typename DefType, typename JointType>
void B2Joint<DefType, JointType>::recreate(){
	ensure(isAttached());
	ensure(joint);

	physics::recreateB2Joint(def, joint, getB2Body(0), getB2Body(1));
}

template <typename DefType, typename JointType>
void B2Joint<DefType, JointType>::createB2Joint(){
	physics::createB2Joint(def, joint);
}

template <typename DefType, typename JointType>
void B2Joint<DefType, JointType>::destroyB2Joint(){
	physics::destroyB2Joint(joint);
}

template <typename DefType, typename JointType>
b2Body* B2Joint<DefType, JointType>::getB2Body(SizeType i) const {
	if (i < getObjectCount())
		return static_cast<RigidObject&>(getObject(i)).getB2Body();
	else
		return nullptr;
}

template class B2Joint<b2DistanceJointDef, b2DistanceJoint>;
template class B2Joint<b2FrictionJointDef, b2FrictionJoint>;
//template class B2Joint<b2GearJointDef, b2GearJoint>;
template class B2Joint<b2MouseJointDef, b2MouseJoint>;
template class B2Joint<b2PrismaticJointDef, b2PrismaticJoint>;
//template class B2Joint<b2PulleyJointDef, b2PulleyJoint>;
template class B2Joint<b2RevoluteJointDef, b2RevoluteJoint>;
template class B2Joint<b2RopeJointDef, b2RopeJoint>;
template class B2Joint<b2WeldJointDef, b2WeldJoint>;
template class B2Joint<b2WheelJointDef, b2WheelJoint>;

} // physics
} // clover


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>com.webside.ip2region (webside 0.0.1-SNAPSHOT API)</title>
<meta name="date" content="2017-07-13">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

com.webside.ip2region

类

DataBlock

DbConfig

DbSearcher

HeaderBlock

IndexBlock

Util

异常错误

DbMakerConfigException


text:
<?xml version="1.0" encoding="UTF-8" ?>

<routes xmlns="http://symfony.com/schema/routing"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd">

    <route id="sonata_customer_addresses" path="/address">
        <default key="_controller">SonataCustomerBundle:Customer:addresses</default>
    </route>

    <route id="sonata_customer_address_add" path="/address/add">
        <default key="_controller">SonataCustomerBundle:Customer:addAddress</default>
    </route>

    <route id="sonata_customer_address_delete" path="/address/delete/{id}">
        <default key="_controller">SonataCustomerBundle:Customer:deleteAddress</default>
    </route>

    <route id="sonata_customer_address_setcurrent" path="/address/current/{id}">
        <default key="_controller">SonataCustomerBundle:Customer:setCurrentAddress</default>
    </route>

    <route id="sonata_customer_address_edit" path="/address/edit/{id}">
        <default key="_controller">SonataCustomerBundle:Customer:editAddress</default>
    </route>

    <route id="sonata_customer_address_update" path="/address/update">
        <default key="_controller">SonataCustomerBundle:Customer:updateAddress</default>
    </route>

</routes>


text:
cask "steermouse" do
  version "5.4.5"
  sha256 "a2ad5821b923673ca5ee6ac27c0ee543127b3ec9c61dfd053f820246aa47417f"

  url "https://plentycom.jp/ctrl/files_sm/SteerMouse#{version}.dmg"
  appcast "https://plentycom.jp/en/steermouse/download.php"
  name "SteerMouse"
  homepage "https://plentycom.jp/en/steermouse/"

  prefpane "SteerMouse.prefPane"

  zap trash: "~/Library/Application Support/SteerMouse & CursorSense/Device.smsetting",
      rmdir: [
        "~/Library/Application Support/SteerMouse & CursorSense/Device Definitions/",
        "~/Library/Application Support/SteerMouse & CursorSense/",
      ]
end


text:
package app.core.commands;

import app.domains.models.User;
import app.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;

public class DeleteUserCommand extends Command {

    @Autowired
    private UserService userService;

    protected DeleteUserCommand(String[] data) {
        super(data);
    }

    /**
     *  DeleteUser <username>
     *  Delete User by username (only mark him as inactive)
     */
    @Override
    public String Execute() {

        String username = this.getData()[1];
        User user = userService.findUserByUsername(username);

        if (user == null) {
            throw new UnsupportedOperationException("User with that username was not found");
        }

        user.setDeleted(true);
        return "User " + username + " was deleted from the database";
    }
}


text:
using content::BrowserThread;
using testing::_;
using webkit::forms::FormData;
using webkit::forms::FormField;
using WebKit::WebAutofillClient;

namespace {

// A constant value to use as the Autofill query ID.
const int kQueryId = 5;

// A constant value to use as an Autofill profile ID.
const int kAutofillProfileId = 1;

class MockAutofillExternalDelegate : public TestAutofillExternalDelegate {
 public:
  MockAutofillExternalDelegate(TabContents* tab_contents,
                               AutofillManager* autofill_manger)
      : TestAutofillExternalDelegate(tab_contents, autofill_manger) {}
  ~MockAutofillExternalDelegate() {}

  MOCK_METHOD4(ApplyAutofillSuggestions, void(
      const std::vector<string16>& autofill_values,
      const std::vector<string16>& autofill_labels,
      const std::vector<string16>& autofill_icons,
      const std::vector<int>& autofill_unique_ids));

  MOCK_METHOD4(OnQueryPlatformSpecific,
               void(int query_id,
                    const webkit::forms::FormData& form,
                    const webkit::forms::FormField& field,
                    const gfx::Rect& bounds));

  MOCK_METHOD0(ClearPreviewedForm, void());

  MOCK_METHOD0(HideAutofillPopup, void());

 private:
  virtual void HideAutofillPopupInternal() {};
};

class MockAutofillManager : public AutofillManager {
 public:
  explicit MockAutofillManager(TabContents* tab_contents)
      // Force to use the constructor designated for unit test, but we don't
      // really need personal_data in this test so we pass a NULL pointer.
      : AutofillManager(tab_contents, NULL) {}

  MOCK_METHOD4(OnFillAutofillFormData,
               void(int query_id,
                    const webkit::forms::FormData& form,
                    const webkit::forms::FormField& field,
                    int unique_id));

 protected:
  virtual ~MockAutofillManager() {}
};

}  // namespace

class AutofillExternalDelegateUnitTest : public TabContentsTestHarness {
 public:
  AutofillExternalDelegateUnitTest()
      : ui_thread_(BrowserThread::UI, &message_loop_) {}
  virtual ~AutofillExternalDelegateUnitTest() {}

  virtual void SetUp() OVERRIDE {
    TabContentsTestHarness::SetUp();
    autofill_manager_ = new MockAutofillManager(tab_contents());
    external_delegate_.reset(new MockAutofillExternalDelegate(
        tab_contents(),
        autofill_manager_));
  }

 protected:
  // Set up the expectation for a platform specific OnQuery call and then
  // execute it with the given QueryId.
  void IssueOnQuery(int query_id) {
    const FormData form;
    FormField field;
    field.is_focusable = true;
    field.should_autocomplete = true;
    const gfx::Rect bounds;

    EXPECT_CALL(*external_delegate_,
                OnQueryPlatformSpecific(query_id, form, field, bounds));

    // This should call OnQueryPlatform specific.
    external_delegate_->OnQuery(query_id, form, field, bounds, false);
  }

  scoped_refptr<MockAutofillManager> autofill_manager_;
  scoped_ptr<MockAutofillExternalDelegate> external_delegate_;

 private:
  content::TestBrowserThread ui_thread_;

  DISALLOW_COPY_AND_ASSIGN(AutofillExternalDelegateUnitTest);
};

// Test that our external delegate called the virtual methods at the right time.
TEST_F(AutofillExternalDelegateUnitTest, TestExternalDelegateVirtualCalls) {
  IssueOnQuery(kQueryId);

  // The enums must be cast to ints to prevent compile errors on linux_rel.
  EXPECT_CALL(*external_delegate_,
              ApplyAutofillSuggestions(_, _, _, testing::ElementsAre(
                  kAutofillProfileId,
                  static_cast<int>(WebAutofillClient::MenuItemIDSeparator),
                  static_cast<int>(
                      WebAutofillClient::MenuItemIDAutofillOptions))));

  // This should call ApplyAutofillSuggestions.
  std::vector<string16> autofill_item;
  autofill_item.push_back(string16());
  std::vector<int> autofill_ids;
  autofill_ids.push_back(kAutofillProfileId);
  external_delegate_->OnSuggestionsReturned(kQueryId,
                                            autofill_item,
                                            autofill_item,
                                            autofill_item,
                                            autofill_ids);

  EXPECT_CALL(*external_delegate_, HideAutofillPopup());

  // Called by DidAutofillSuggestions, add expectation to remove warning.
  EXPECT_CALL(*autofill_manager_, OnFillAutofillFormData(_, _, _, _));

  // This should trigger a call to hide the popup since
  // we've selected an option.
  external_delegate_->DidAcceptAutofillSuggestions(autofill_item[0],
                                                   autofill_ids[0], 0);
}

// Test that data list elements for a node will appear in the Autofill popup.
TEST_F(AutofillExternalDelegateUnitTest, ExternalDelegateDataList) {
  IssueOnQuery(kQueryId);

  std::vector<string16> data_list_items;
  data_list_items.push_back(string16());
  std::vector<int> data_list_ids;
  data_list_ids.push_back(WebAutofillClient::MenuItemIDDataListEntry);

  external_delegate_->SetCurrentDataListValues(data_list_items,
                                               data_list_items,
                                               data_list_items,
                                               data_list_ids);

  // The enums must be cast to ints to prevent compile errors on linux_rel.
  EXPECT_CALL(*external_delegate_,
              ApplyAutofillSuggestions(
                  _, _, _, testing::ElementsAre(
                      static_cast<int>(
                          WebAutofillClient::MenuItemIDDataListEntry),
                      static_cast<int>(WebAutofillClient::MenuItemIDSeparator),
                      kAutofillProfileId,
                      static_cast<int>(WebAutofillClient::MenuItemIDSeparator),
                      static_cast<int>(
                          WebAutofillClient::MenuItemIDAutofillOptions))));

  // This should call ApplyAutofillSuggestions.
  std::vector<string16> autofill_item;
  autofill_item.push_back(string16());
  std::vector<int> autofill_ids;
  autofill_ids.push_back(kAutofillProfileId);
  external_delegate_->OnSuggestionsReturned(kQueryId,
                                            autofill_item,
                                            autofill_item,
                                            autofill_item,
                                            autofill_ids);

  // Try calling OnSuggestionsReturned with no Autofill values and ensure
  // the datalist items are still shown.
  // The enum must be cast to an int to prevent compile errors on linux_rel.
  EXPECT_CALL(*external_delegate_,
              ApplyAutofillSuggestions(
                  _, _, _, testing::ElementsAre(
                      static_cast<int>(
                          WebAutofillClient::MenuItemIDDataListEntry))));

  autofill_item = std::vector<string16>();
  autofill_ids = std::vector<int>();
  external_delegate_->OnSuggestionsReturned(kQueryId,
                                            autofill_item,
                                            autofill_item,
                                            autofill_item,
                                            autofill_ids);
}

// Test that the Autofill delegate doesn't try and fill a form with a
// negative unique id.
TEST_F(AutofillExternalDelegateUnitTest, ExternalDelegateInvalidUniqueId) {
  // Ensure it doesn't try to preview the negative id.
  EXPECT_CALL(*autofill_manager_, OnFillAutofillFormData(_, _, _, _)).Times(0);
  EXPECT_CALL(*external_delegate_, ClearPreviewedForm()).Times(1);
  external_delegate_->SelectAutofillSuggestionAtIndex(-1);

  // Ensure it doesn't try to fill the form in with the negative id.
  EXPECT_CALL(*autofill_manager_, OnFillAutofillFormData(_, _, _, _)).Times(0);
  external_delegate_->DidAcceptAutofillSuggestions(string16(), -1, 0);
}

// Test that the ClearPreview IPC is only sent the form was being previewed
// (i.e. it isn't autofilling a password).
TEST_F(AutofillExternalDelegateUnitTest, ExternalDelegateClearPreviewedForm) {
  // Called by SelectAutofillSuggestionAtIndex, add expectation to remove
  // warning.
  EXPECT_CALL(*autofill_manager_, OnFillAutofillFormData(_, _, _, _));

  // Ensure selecting a new password entries or Autofill entries will
  // cause any previews to get cleared.
  EXPECT_CALL(*external_delegate_, ClearPreviewedForm()).Times(1);
  external_delegate_->SelectAutofillSuggestionAtIndex(
      WebAutofillClient::MenuItemIDPasswordEntry);

  EXPECT_CALL(*external_delegate_, ClearPreviewedForm()).Times(1);
  external_delegate_->SelectAutofillSuggestionAtIndex(1);
}

// Test that the popup is hidden once we are done editing the autofill field.
TEST_F(AutofillExternalDelegateUnitTest,
       ExternalDelegateHidePopupAfterEditing) {
  EXPECT_CALL(*external_delegate_, HideAutofillPopup());

  external_delegate_->DidEndTextFieldEditing();
}


text:
require 'net/https'
require 'open-uri'
require 'mechanize'
require 'generator'

module SAIC
  class Job
    BASE_URI = "https://cp-its-rmprd.saic.com/main/careerportal/"
    SEARCH_URI = BASE_URI + "Job_List.cfm?/28HV6028GX72HHJCPALDDGY64A3PF1WVIXHJRL8BQZYJHT7RZ2HT2AX5LD30TSXQ1TLI3QEJQRW0VH8ZEGDPRKZVQAIZ18I9IFAKJE8ZWORN"

    def self.all
      parse(SEARCH_URI)
    end

    def self.parse(uri)
      agent = Mechanize.new
      agent.verify_callback = true
      page = agent.get(SEARCH_URI)

      page_links = page.search(".Rmax_RegularText td a")
      current_page_link = page_links.search(".Rmax_LinkBold").first
      current_page_number = current_page_link.text.to_i
      last_page_link = page_links[-2] # last entry is blank
      last_page_number = last_page_link.text.to_i

      page_links.pop # remove last item it's just an arrow
      Generator.new do |yielder|
        parse_jobs(page) do |job|
          yielder.yield job
        end
        page_links.each_with_index do |page_link, idx|
          next if idx == 0 # skip first page, we're already on it
          page = agent.get(BASE_URI + page_link['href'])
          parse_jobs(page) do |job|
            yielder.yield job
          end
        end
      end
    end

    def self.parse_jobs(page)
      odd_job_rows  = page.search(".Rmax_JobListRow1")
      even_job_rows = page.search(".Rmax_JobListRow0")
      job_rows = odd_job_rows + even_job_rows

      job_rows.each do |job_row|
        tds = job_row.search("td")
        job = SAIC::Job.new
        job.title = strip_whitespace tds[0].text
        job.location = strip_whitespace tds[1].text
        split_location = job.location.split(", ")
        job.city = split_location[0]
        job.state = split_location[1]
        job.country = split_location[2]
        job.posted_date = Date.parse tds[2].text
        job.url = BASE_URI + tds[0].at("a")['href']
        yield job
      end
    end

    def self.strip_whitespace(text)
      text.strip.gsub(/^[\302\240|\s]*|[\302\240|\s]*$/, '')
    end

    attr_accessor :title, :location, :city, :state, :country, :posted_date, :url

    def id
      keep_trying do
        doc.at("table.Rmax_RegularText").search("tr")[5].search("td")[1].text
      end
    end

    def description
      keep_trying do
        SAIC::Job.strip_whitespace doc.at("table.Rmax_RegularText").search("tr")[11].search("td")[1].text
      end
    end

    private
    def doc
      @doc ||= begin
                 uri              = URI.parse(url)
                 http             = Net::HTTP.new(uri.host, uri.port)
                 http.use_ssl     = true
                 http.verify_mode = OpenSSL::SSL::VERIFY_NONE
                 response         = http.start do |conn|
                   conn.get("#{uri.path}?#{uri.query}")
                 end
                 Nokogiri::HTML(response.body)
               end
    end

    def keep_trying(max_attempts = 5)
      attempts = 0
      yield
    rescue NoMethodError
      sleep 0.25
      @doc = nil
      attempts += 1
      retry unless attempts > max_attempts
    end
  end
end


text:
@javax.xml.bind.annotation.XmlSchema(namespace = "urn:federated:bus:1.0", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package org.jboss.bus.config.model;


text:
namespace Torshia.Models.Tasks
{
    public class TaskViewModel
    {
        public int TaskId { get; set; }

        public string Title { get; set; }

        public int Level { get; set; }
    }
}


text:
<?php

namespace Smeagol\Model;

use Zend\Db\TableGateway\TableGateway;
// Class Select
use Zend\Db\Sql\Select;

class MenuTable {

    protected $tableGateway;

    public function __construct(TableGateway $tableGateway) {
        $this->tableGateway = $tableGateway;
    }

    public function fetchAll() {
        $resultSet = $this->tableGateway->select();
        return $resultSet;
    }

    public function getMenu($id) {
        $id = (int) $id;
        $rowset = $this->tableGateway->select(array('id' => $id));
        $row = $rowset->current();
        if (!$row) {
            throw new \Exception("Could not find row $id");
        }
        return $row;
    }

    /**
     * Método que genera el array Zend\Navigation a partir de la tabla menu en base a un id base de menú .
     *
     * @param int $parent_id id de menú a partir de donde se extraerá el arbol
     * @param string $path Cadena con ruta de los índices del array multidimensional hasta llegar al page a insertar
     * @param array $menuTree array multidimensional con la estructura de un array de Zend\Navigation
     * @param bolean $include_itself boleano que indica si se incluye o no el id buscado en menuTree
     * @return array
     */
    public function getNavigationArray($parent_id = 0, $path = "", $menuTree = array(), $include_itself = false) {

        $parent_id = (int) $parent_id;
        if ($include_itself) {
            $resultSet = $this->tableGateway->select(function (Select $select, $parent_id) {
                $select->columns(array('id', 'name', 'label', 'parent_id', 'url', 'node_id'));
                $select->where->equalTo('id', $parent_id);
            });
            $menu = $resultSet->current();
            if (!empty($menu)) {
                $page = array('id' => $parent_id, 'label' => $menu->label);
                if (!empty($menu->route)) {
                    $page['route'] = $menu->route;
                }
                $menuTree[] = $page;
            }
        }

        $adapter = $this->tableGateway->getAdapter();

        $sql = new \Zend\Db\Sql\SQL($adapter);

        $select = $sql->select();
        $select->from(array('m' => 'menu'));
        $select->columns(array(
                    'id',
                    'name',
                    'label',
                    'parent_id',
                    'urlmenu' => 'url',
                    'node_id'
                ))
                ->join(array('n' => 'node'), 'node_id=n.id', array('urlnode' => 'url'), 'left')
        ->where->equalTo('m.parent_id', $parent_id);
        $select->order("order_id");
        $statement = $sql->prepareStatementForSqlObject($select);
        $resultSet = $statement->execute();

        foreach ($resultSet as $menu) {
            $route = "home";
            $module = "application";
            $controller = "";
            $action = "";
            $resource = "mvc:application.index.index";

            if (empty($menu['node_id'])) {
                if ($menu['urlmenu'] != '/') {
                    $m = explode("/", $menu['urlmenu']);
                    $route = $m[0];
                    $module = $m[0];
                    if (!empty($m[1])) {
                        $controller = $m[1];
                    } else {
                        $controller = "index";
                    }
                    if (!empty($m2)) {
                        $action = $m[2];
                    } else {
                        $action = "index";
                    }
                    $resource = "mvc:$module.$controller.$action";
                }
            } else {
                $route = "node";
                $module = "application";
            }

            $page = array('id' => $menu['id'],
                'label' => $menu['label'],
                'route' => $route,
                'module' => $module);

            if (!empty($controller)) {
                $page['controller'] = $controller;
                if (!empty($action)) {
                    $page['action'] = $action;
                }
            } else {
                if ($route != "home") {
                    $resource = "mvc:application.index.node";
                }
                $page['params'] = array('id' => $menu['id'], 'link' => "/" . $menu['urlnode']);
            }

            if (!empty($resource)) {
                $page['resource'] = $resource;
            }

            if (empty($path)) {
                $menuTree[] = $page;
                end($menuTree);
                $last_key = key($menuTree) . ":";
            } else {
                $pt = explode(":", $path);
                $temp = & $menuTree;
                foreach ($pt as $p) {
                    if (!empty($p)) {
                        $temp = &$temp[$p];
                    }
                }
                $temp["pages"]["menu" . $menu['id']] = $page;
                end($temp["pages"]);
                $last_key = "pages:" . key($temp["pages"]) . ":";
                unset($temp);
            }
            $menuTree = $this->getNavigationArray($menu['id'], $path . $last_key, $menuTree);
        }
        return $menuTree;
    }
}


text:
    char buf[512]; \
    lmqtt_tx_buffer_t state; \
    lmqtt_store_t store; \
    lmqtt_io_result_t res; \
    size_t bytes_written; \
    lmqtt_store_value_t value; \
    lmqtt_store_entry_t entries[ENTRY_COUNT]; \
    memset(buf, 0xcc, sizeof(buf)); \
    memset(&state, 0, sizeof(state)); \
    memset(&store, 0, sizeof(store)); \
    memset(&value, 0, sizeof(value)); \
    memset(entries, 0, sizeof(entries)); \
    state.store = &store; \
    store.get_time = &test_time_get; \
    store.entries = entries; \
    store.capacity = ENTRY_COUNT

int test_on_publish(void *data, lmqtt_publish_t *publish)
{
    *((void **) data) = publish;
    return 1;
}

int test_on_publish_fail(void *data, lmqtt_publish_t *publish)
{
    return 0;
}

START_TEST(should_encode_connect)
{
    char *expected_buffer;
    int i;
    lmqtt_connect_t connect;

    PREPARE;
    memset(&connect, 0, sizeof(connect));

    connect.keep_alive = 0x102;
    connect.client_id.buf = "a";
    connect.client_id.len = 1;
    connect.will_topic.buf = "b";
    connect.will_topic.len = 1;
    connect.will_message.buf = "c";
    connect.will_message.len = 1;
    connect.user_name.buf = "d";
    connect.user_name.len = 1;
    connect.password.buf = "e";
    connect.password.len = 1;

    value.value = &connect;
    lmqtt_store_append(&store, LMQTT_KIND_CONNECT, &value);

    res = lmqtt_tx_buffer_encode(&state, (unsigned char *) buf, sizeof(buf),
        &bytes_written);

    ck_assert_int_eq(LMQTT_IO_SUCCESS, res);
    ck_assert_int_eq(27, bytes_written);

    expected_buffer = "\x10\x19\x00\x04" "MQTT\x04\xc4\x01\x02\x00\x01"
        "a\x00\x01" "b\x00\x01" "c\x00\x01" "d\x00\x01" "e";

    for (i = 0; i < 27; i++)
        ck_assert_int_eq(expected_buffer[i], buf[i]);
}
END_TEST

START_TEST(should_encode_subscribe_to_one_topic)
{
    char *expected_buffer;
    int i;
    lmqtt_subscribe_t subscribe;
    lmqtt_subscription_t subscription;

    PREPARE;
    memset(&subscribe, 0, sizeof(subscribe));
    memset(&subscription, 0, sizeof(subscription));

    subscribe.count = 1;
    subscribe.subscriptions = &subscription;

    subscription.requested_qos = LMQTT_QOS_2;
    subscription.topic.buf = "test";
    subscription.topic.len = 4;

    value.packet_id = 0x0a0b;
    value.value = &subscribe;
    lmqtt_store_append(&store, LMQTT_KIND_SUBSCRIBE, &value);

    res = lmqtt_tx_buffer_encode(&state, (unsigned char *) buf, sizeof(buf),
        &bytes_written);

    ck_assert_int_eq(LMQTT_IO_SUCCESS, res);
    ck_assert_int_eq(11, bytes_written);

    expected_buffer = "\x82\x09\x0a\x0b\x00\x04" "test\x02";
    for (i = 0; i < 11; i++)
        ck_assert_int_eq(expected_buffer[i], buf[i]);
}
END_TEST

START_TEST(should_encode_subscribe_to_multiple_topics)
{
    lmqtt_subscribe_t subscribe;
    lmqtt_subscription_t subscriptions[2];
    char topic_1[127];
    char topic_2[129];

    PREPARE;
    memset(&subscribe, 0, sizeof(subscribe));
    memset(&subscriptions, 0, sizeof(subscriptions));
    memset(topic_1, 'x', sizeof(topic_1));
    memset(topic_2, 'y', sizeof(topic_2));

    subscribe.count = 2;
    subscribe.subscriptions = subscriptions;

    subscriptions[0].requested_qos = LMQTT_QOS_0;
    subscriptions[0].topic.buf = topic_1;
    subscriptions[0].topic.len = sizeof(topic_1);

    subscriptions[1].requested_qos = LMQTT_QOS_1;
    subscriptions[1].topic.buf = topic_2;
    subscriptions[1].topic.len = sizeof(topic_2);

    value.packet_id = 0x0c0d;
    value.value = &subscribe;
    lmqtt_store_append(&store, LMQTT_KIND_SUBSCRIBE, &value);

    res = lmqtt_tx_buffer_encode(&state, (unsigned char *) buf, sizeof(buf),
        &bytes_written);

    ck_assert_int_eq(LMQTT_IO_SUCCESS, res);
    ck_assert_int_eq(267, bytes_written);

    ck_assert_int_eq('\x82', buf[0]);
    ck_assert_int_eq('\x88', buf[1]);
    ck_assert_int_eq('\x02', buf[2]);
    ck_assert_int_eq('\x0c', buf[3]);
    ck_assert_int_eq('\x0d', buf[4]);

    ck_assert_int_eq('\x00', buf[5]);
    ck_assert_int_eq('\x7f', buf[6]);
    ck_assert_int_eq('x',    buf[7]);
    ck_assert_int_eq('\x00', buf[134]);

    ck_assert_int_eq('\x00', buf[135]);
    ck_assert_int_eq('\x81', buf[136]);
    ck_assert_int_eq('y',    buf[137]);
    ck_assert_int_eq('\x01', buf[266]);
}
END_TEST

START_TEST(should_encode_unsubscribe_to_multiple_topics)
{
    lmqtt_subscribe_t subscribe;
    lmqtt_subscription_t subscriptions[2];
    char topic_1[127];
    char topic_2[129];

    PREPARE;
    memset(&subscribe, 0, sizeof(subscribe));
    memset(&subscriptions, 0, sizeof(subscriptions));
    memset(topic_1, 'x', sizeof(topic_1));
    memset(topic_2, 'y', sizeof(topic_2));

    subscribe.count = 2;
    subscribe.subscriptions = subscriptions;

    subscriptions[0].topic.buf = topic_1;
    subscriptions[0].topic.len = sizeof(topic_1);

    subscriptions[1].topic.buf = topic_2;
    subscriptions[1].topic.len = sizeof(topic_2);

    value.packet_id = 0x0c0d;
    value.value = &subscribe;
    lmqtt_store_append(&store, LMQTT_KIND_UNSUBSCRIBE, &value);

    res = lmqtt_tx_buffer_encode(&state, (unsigned char *) buf, sizeof(buf),
        &bytes_written);

    ck_assert_int_eq(LMQTT_IO_SUCCESS, res);
    ck_assert_int_eq(265, bytes_written);

    ck_assert_int_eq('\xa2', buf[0]);
    ck_assert_int_eq('\x86', buf[1]);
    ck_assert_int_eq('\x02', buf[2]);
    ck_assert_int_eq('\x0c', buf[3]);
    ck_assert_int_eq('\x0d', buf[4]);

    ck_assert_int_eq('\x00', buf[5]);
    ck_assert_int_eq('\x7f', buf[6]);
    ck_assert_int_eq('x',    buf[7]);
    ck_assert_int_eq('x',    buf[133]);

    ck_assert_int_eq('\x00', buf[134]);
    ck_assert_int_eq('\x81', buf[135]);
    ck_assert_int_eq('y',    buf[136]);
    ck_assert_int_eq('y',    buf[264]);
}
END_TEST

START_TEST(should_encode_publish_with_qos_0)
{
    lmqtt_publish_t publish;
    int kind;
    void *data = NULL;
    lmqtt_store_value_t value_out;

    PREPARE;
    memset(&publish, 0, sizeof(publish));
    publish.topic.buf = "topic";
    publish.topic.len = strlen(publish.topic.buf);
    publish.payload.buf = "payload";
    publish.payload.len = strlen(publish.payload.buf);

    value.value = &publish;
    value.callback = (lmqtt_store_entry_callback_t) &test_on_publish;
    value.callback_data = &data;
    lmqtt_store_append(&store, LMQTT_KIND_PUBLISH_0, &value);

    res = lmqtt_tx_buffer_encode(&state, (unsigned char *) buf, sizeof(buf),
        &bytes_written);

    ck_assert_int_eq(LMQTT_IO_SUCCESS, res);
    ck_assert_int_eq(16, bytes_written);

    ck_assert_uint_eq(0x30, buf[0]);
    ck_assert_uint_eq(0x0e, buf[1]);
    ck_assert_uint_eq(0x00, buf[2]);
    ck_assert_uint_eq(0x05, buf[3]);
    ck_assert_uint_eq('t',  buf[4]);
    ck_assert_uint_eq('c',  buf[8]);
    ck_assert_uint_eq('p',  buf[9]);
    ck_assert_uint_eq('d',  buf[15]);

    ck_assert_int_eq(0, lmqtt_store_shift(&store, &kind, &value_out));
    ck_assert_ptr_eq(NULL, value_out.value);
    ck_assert_ptr_eq(&publish, data);
}
END_TEST

START_TEST(should_handle_publish_callback_failure_with_qos_0)
{
    lmqtt_publish_t publish;
    lmqtt_error_t error;
    int os_error = 0;

    PREPARE;
    memset(&publish, 0, sizeof(publish));
    publish.topic.buf = "topic";
    publish.topic.len = strlen(publish.topic.buf);

    value.value = &publish;
    value.callback = (lmqtt_store_entry_callback_t) &test_on_publish_fail;
    lmqtt_store_append(&store, LMQTT_KIND_PUBLISH_0, &value);

    res = lmqtt_tx_buffer_encode(&state, (unsigned char *) buf, sizeof(buf),
        &bytes_written);
    ck_assert_int_eq(LMQTT_IO_ERROR, res);

    error = lmqtt_tx_buffer_get_error(&state, &os_error);
    ck_assert_int_eq(LMQTT_ERROR_CALLBACK_PUBLISH, error);
}
END_TEST

START_TEST(should_encode_publish_with_qos_1)
{
    lmqtt_publish_t publish;
    int kind;
    void *data = NULL;
    lmqtt_store_value_t value_out;

    PREPARE;
    memset(&publish, 0, sizeof(publish));
    publish.retain = 1;
    publish.internal.encode_count++;
    publish.qos = LMQTT_QOS_1;
    publish.topic.buf = "topic";
    publish.topic.len = strlen(publish.topic.buf);
    publish.payload.buf = "payload";
    publish.payload.len = strlen(publish.payload.buf);

    value.packet_id = 0x0708;
    value.value = &publish;
    value.callback = (lmqtt_store_entry_callback_t) &test_on_publish;
    value.callback_data = &data;
    lmqtt_store_append(&store, LMQTT_KIND_PUBLISH_1, &value);

    res = lmqtt_tx_buffer_encode(&state, (unsigned char *) buf, sizeof(buf),
        &bytes_written);

    ck_assert_int_eq(LMQTT_IO_SUCCESS, res);
    ck_assert_int_eq(18, bytes_written);

    ck_assert_uint_eq(0x3b, buf[0]);
    ck_assert_uint_eq(0x10, buf[1]);
    ck_assert_uint_eq(0x00, buf[2]);
    ck_assert_uint_eq(0x05, buf[3]);
    ck_assert_uint_eq('t',  buf[4]);
    ck_assert_uint_eq('c',  buf[8]);
    ck_assert_uint_eq(0x07, buf[9]);
    ck_assert_uint_eq(0x08, buf[10]);
    ck_assert_uint_eq('p',  buf[11]);
    ck_assert_uint_eq('d',  buf[17]);

    ck_assert_int_eq(1, lmqtt_store_shift(&store, &kind, &value_out));
    ck_assert_ptr_eq(&publish, value_out.value);
    ck_assert_ptr_eq(NULL, data);
}
END_TEST

START_TEST(should_increment_publish_encode_count_after_encode)
{
    lmqtt_publish_t publish;

    PREPARE;
    memset(&publish, 0, sizeof(publish));
    publish.qos = LMQTT_QOS_1;
    publish.topic.buf = "topic";
    publish.topic.len = strlen(publish.topic.buf);
    publish.payload.buf = "payload";
    publish.payload.len = strlen(publish.payload.buf);

    value.packet_id = 0x0708;
    value.value = &publish;
    lmqtt_store_append(&store, LMQTT_KIND_PUBLISH_1, &value);
    res = lmqtt_tx_buffer_encode(&state, (unsigned char *) buf, sizeof(buf),
        &bytes_written);
    ck_assert_int_eq(LMQTT_IO_SUCCESS, res);
    ck_assert_uint_eq(0x32, buf[0]);

    value.packet_id = 0x0708;
    value.value = &publish;
    lmqtt_store_append(&store, LMQTT_KIND_PUBLISH_1, &value);
    res = lmqtt_tx_buffer_encode(&state, (unsigned char *) buf, sizeof(buf),
        &bytes_written);
    ck_assert_int_eq(LMQTT_IO_SUCCESS, res);
    ck_assert_uint_eq(0x3a, buf[0]);
}
END_TEST

START_TEST(should_encode_puback)
{
    int kind;

    PREPARE;

    value.packet_id = 0x0102;
    lmqtt_store_append(&store, LMQTT_KIND_PUBACK, &value);

    res = lmqtt_tx_buffer_encode(&state, (unsigned char *) buf, sizeof(buf),
        &bytes_written);

    ck_assert_int_eq(LMQTT_IO_SUCCESS, res);
    ck_assert_int_eq(4, bytes_written);

    ck_assert_uint_eq(0x40, buf[0]);
    ck_assert_uint_eq(0x02, buf[1]);
    ck_assert_uint_eq(0x01, buf[2]);
    ck_assert_uint_eq(0x02, buf[3]);

    ck_assert_int_eq(0, lmqtt_store_shift(&store, &kind, &value));
}
END_TEST

START_TEST(should_encode_pubrec)
{
    int kind;

    PREPARE;

    value.packet_id = 0x0102;
    lmqtt_store_append(&store, LMQTT_KIND_PUBREC, &value);

    res = lmqtt_tx_buffer_encode(&state, (unsigned char *) buf, sizeof(buf),
        &bytes_written);

    ck_assert_int_eq(LMQTT_IO_SUCCESS, res);
    ck_assert_int_eq(4, bytes_written);

    ck_assert_uint_eq(0x50, buf[0]);
    ck_assert_uint_eq(0x02, buf[1]);
    ck_assert_uint_eq(0x01, buf[2]);
    ck_assert_uint_eq(0x02, buf[3]);

    ck_assert_int_eq(0, lmqtt_store_shift(&store, &kind, &value));
}
END_TEST

START_TEST(should_encode_pubrel)
{
    lmqtt_publish_t publish;

    PREPARE;
    memset(&publish, 0, sizeof(publish));
    publish.topic.buf = "topic";
    publish.topic.len = strlen(publish.topic.buf);

    value.packet_id = 0x0102;
    value.value = &publish;
    lmqtt_store_append(&store, LMQTT_KIND_PUBREL, &value);

    res = lmqtt_tx_buffer_encode(&state, (unsigned char *) buf, sizeof(buf),
        &bytes_written);

    ck_assert_int_eq(LMQTT_IO_SUCCESS, res);
    ck_assert_int_eq(4, bytes_written);

    ck_assert_uint_eq(0x62, buf[0]);
    ck_assert_uint_eq(0x02, buf[1]);
    ck_assert_uint_eq(0x01, buf[2]);
    ck_assert_uint_eq(0x02, buf[3]);
}
END_TEST

START_TEST(should_encode_pubcomp)
{
    int kind;

    PREPARE;

    value.packet_id = 0x0102;
    lmqtt_store_append(&store, LMQTT_KIND_PUBCOMP, &value);

    res = lmqtt_tx_buffer_encode(&state, (unsigned char *) buf, sizeof(buf),
        &bytes_written);

    ck_assert_int_eq(LMQTT_IO_SUCCESS, res);
    ck_assert_int_eq(4, bytes_written);

    ck_assert_uint_eq(0x70, buf[0]);
    ck_assert_uint_eq(0x02, buf[1]);
    ck_assert_uint_eq(0x01, buf[2]);
    ck_assert_uint_eq(0x02, buf[3]);

    ck_assert_int_eq(0, lmqtt_store_shift(&store, &kind, &value));
}
END_TEST

START_TEST(should_encode_pingreq)
{
    PREPARE;

    lmqtt_store_append(&store, LMQTT_KIND_PINGREQ, NULL);

    res = lmqtt_tx_buffer_encode(&state, (unsigned char *) buf, sizeof(buf),
        &bytes_written);

    ck_assert_int_eq(LMQTT_IO_SUCCESS, res);
    ck_assert_int_eq(2, bytes_written);

    ck_assert_int_eq('\xc0', buf[0]);
    ck_assert_int_eq('\x00', buf[1]);
}
END_TEST

START_TEST(should_encode_disconnect)
{
    PREPARE;

    lmqtt_store_append(&store, LMQTT_KIND_DISCONNECT, NULL);

    res = lmqtt_tx_buffer_encode(&state, (unsigned char *) buf, sizeof(buf),
        &bytes_written);

    ck_assert_int_eq(LMQTT_IO_SUCCESS, res);
    ck_assert_int_eq(2, bytes_written);

    ck_assert_int_eq('\xe0', buf[0]);
    ck_assert_int_eq('\x00', buf[1]);
}
END_TEST

START_TCASE("Tx buffer finders")
{
    ADD_TEST(should_encode_connect);
    ADD_TEST(should_encode_subscribe_to_one_topic);
    ADD_TEST(should_encode_subscribe_to_multiple_topics);
    ADD_TEST(should_encode_unsubscribe_to_multiple_topics);
    ADD_TEST(should_encode_publish_with_qos_0);
    ADD_TEST(should_handle_publish_callback_failure_with_qos_0);
    ADD_TEST(should_encode_publish_with_qos_1);
    ADD_TEST(should_increment_publish_encode_count_after_encode);
    ADD_TEST(should_encode_puback);
    ADD_TEST(should_encode_pubrec);
    ADD_TEST(should_encode_pubrel);
    ADD_TEST(should_encode_pubcomp);
    ADD_TEST(should_encode_pingreq);
    ADD_TEST(should_encode_disconnect);
}
END_TCASE


text:
namespace sponge {
namespace net {

// The default DatagramChannelConfig implementation.
class DefaultDatagramChannelConfig
        : public DefaultChannelConfig, public DatagramChannelConfig {
  public:
    DefaultDatagramChannelConfig(const DatagramSocket &socket)
            : kSocket_(socket), predictor_factory_(kDefaultPredictorFactory_) {}

    bool SetOption(const std::string &key, void* value);
    bool IsBroadcast();
    void SetBroadcast(bool broadcast);
    std::string GetInterface();
    void SetInterface(const std::string &interface_address);
    bool IsLoopbackModeDisabled();
    void SetLoopbackModeDisabled(bool loopback_mode_disabled);
    std::string GetNetworkInterface();
    void SetNetworkInterface(const std::string &network_interface);
    bool IsReuseAddress();
    void SetReuseAddress(bool reuse_address);
    int  GetReceiveBufferSize();
    void SetReceiveBufferSize(int receive_buffer_size);
    int  GetSendBufferSize();
    void SetSendBufferSize(int send_buffer_size);
    int  GetTimeToLive();
    void SetTimeToLove(int ttl);
    int  GetTrafficClass();
    void SetTrafficClass(int traffic_class);
    ReceiveBufferSizePredictor GetReceiveBufferSizePredictor();
    void SetReceiveBufferSizePredictor(
        const ReceiveBufferSizePredictor &predictor);

    inline ReceiveBufferSizePredictorFactory
    GetReceiveBufferSizePredictorFactory() {
        return predictor_factory_;
    }

    void SetReceiveBufferSizePredictorFactory(
        const ReceiveBufferSizePredictorFactory &predictor_factory);

  private:
    static const ReceiveBufferSizePredictorFactory kDefaultPredictorFactory_;
    const DatagramSocket kSocket_;
    volatile ReceiveBufferSizePredictor predictor_;
    volatile ReceiveBufferSizePredictorFactory predictor_factory_;
}

} } // namespace sponge::net

#endif // SPONGE_NET_CHANNEL_SOCKET_DEFAULT_DATAGRAM_CHANNEL_CONFIG_H_


text:
extern crate anon_trait_static_method_lib;
use anon_trait_static_method_lib::Foo;

pub fn main() {
    let x = Foo::new();
    println!("{}", x.x);
}


text:
package org.apache.accumulo.server.util;

import java.util.ArrayList;
import java.util.Map.Entry;
import java.util.TreeSet;

import org.apache.accumulo.core.client.Connector;
import org.apache.accumulo.core.client.Scanner;
import org.apache.accumulo.core.client.impl.ClientContext;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.metadata.MetadataTable;
import org.apache.accumulo.core.metadata.RootTable;
import org.apache.accumulo.core.metadata.schema.MetadataSchema;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.accumulo.core.tabletserver.log.LogEntry;
import org.apache.accumulo.server.AccumuloServerContext;
import org.apache.accumulo.server.client.HdfsZooInstance;
import org.apache.accumulo.server.conf.ServerConfigurationFactory;
import org.apache.accumulo.server.fs.VolumeManager.FileType;
import org.apache.hadoop.fs.Path;

/**
 *
 */
public class ListVolumesUsed {

  public static void main(String[] args) throws Exception {
    listVolumes(new AccumuloServerContext(new ServerConfigurationFactory(HdfsZooInstance.getInstance())));
  }

  private static String getTableURI(String rootTabletDir) {
    Path ret = FileType.TABLE.getVolume(new Path(rootTabletDir));
    if (ret == null)
      return "RELATIVE";
    return ret.toString();
  }

  private static String getLogURI(String logEntry) {
    Path ret = FileType.WAL.getVolume(new Path(logEntry));
    if (ret == null)
      return "RELATIVE";
    return ret.toString();
  }

  private static void getLogURIs(TreeSet<String> volumes, LogEntry logEntry) {
    volumes.add(getLogURI(logEntry.filename));
    for (String logSet : logEntry.logSet) {
      volumes.add(getLogURI(logSet));
    }
  }

  private static void listZookeeper() throws Exception {
    System.out.println("Listing volumes referenced in zookeeper");
    TreeSet<String> volumes = new TreeSet<>();

    volumes.add(getTableURI(MetadataTableUtil.getRootTabletDir()));
    ArrayList<LogEntry> result = new ArrayList<>();
    MetadataTableUtil.getRootLogEntries(result);
    for (LogEntry logEntry : result) {
      getLogURIs(volumes, logEntry);
    }

    for (String volume : volumes)
      System.out.println("\tVolume : " + volume);

  }

  private static void listTable(String name, Connector conn) throws Exception {

    System.out.println("Listing volumes referenced in " + name + " tablets section");

    Scanner scanner = conn.createScanner(name, Authorizations.EMPTY);

    scanner.setRange(MetadataSchema.TabletsSection.getRange());
    scanner.fetchColumnFamily(MetadataSchema.TabletsSection.DataFileColumnFamily.NAME);
    scanner.fetchColumnFamily(MetadataSchema.TabletsSection.LogColumnFamily.NAME);
    MetadataSchema.TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.fetch(scanner);

    TreeSet<String> volumes = new TreeSet<>();

    for (Entry<Key,Value> entry : scanner) {
      if (entry.getKey().getColumnFamily().equals(MetadataSchema.TabletsSection.DataFileColumnFamily.NAME)) {
        volumes.add(getTableURI(entry.getKey().getColumnQualifier().toString()));
      } else if (entry.getKey().getColumnFamily().equals(MetadataSchema.TabletsSection.LogColumnFamily.NAME)) {
        LogEntry le = LogEntry.fromKeyValue(entry.getKey(), entry.getValue());
        getLogURIs(volumes, le);
      } else if (MetadataSchema.TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.hasColumns(entry.getKey())) {
        volumes.add(getTableURI(entry.getValue().toString()));
      }
    }

    for (String volume : volumes)
      System.out.println("\tVolume : " + volume);

    volumes.clear();

    scanner.clearColumns();
    scanner.setRange(MetadataSchema.DeletesSection.getRange());

    for (Entry<Key,Value> entry : scanner) {
      String delPath = entry.getKey().getRow().toString().substring(MetadataSchema.DeletesSection.getRowPrefix().length());
      volumes.add(getTableURI(delPath));
    }

    System.out.println("Listing volumes referenced in " + name + " deletes section (volume replacement occurrs at deletion time)");

    for (String volume : volumes)
      System.out.println("\tVolume : " + volume);
  }

  public static void listVolumes(ClientContext context) throws Exception {
    Connector conn = context.getConnector();
    listZookeeper();
    System.out.println();
    listTable(RootTable.NAME, conn);
    System.out.println();
    listTable(MetadataTable.NAME, conn);
  }

}


text:
<?php

class BWGControllerOptions_bwg {
  ////////////////////////////////////////////////////////////////////////////////////////
  // Events                                                                             //
  ////////////////////////////////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////////////////////////////////
  // Constants                                                                          //
  ////////////////////////////////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////////////////////////////////
  // Variables                                                                          //
  ////////////////////////////////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////////////////////////////////
  // Constructor & Destructor                                                           //
  ////////////////////////////////////////////////////////////////////////////////////////
  public function __construct() {
  }
  ////////////////////////////////////////////////////////////////////////////////////////
  // Public Methods                                                                     //
  ////////////////////////////////////////////////////////////////////////////////////////
  public function execute() {
    $task = ((isset($_POST['task'])) ? esc_html(stripslashes($_POST['task'])) : '');
    $id = ((isset($_POST['current_id'])) ? esc_html(stripslashes($_POST['current_id'])) : 0);

    if($task != ''){
      if(!WDWLibrary::verify_nonce('options_bwg')){
        die('Sorry, your nonce did not verify.');
      }
    }

    if (method_exists($this, $task)) {
      $this->$task($id);
    }
    else {
      $this->display();
    }
  }

  public function display() {
    require_once WD_BWG_DIR . "/admin/models/BWGModelOptions_bwg.php";
    $model = new BWGModelOptions_bwg();

    require_once WD_BWG_DIR . "/admin/views/BWGViewOptions_bwg.php";
    $view = new BWGViewOptions_bwg($model);
    $view->display();
  }

  public function reset() {
    require_once WD_BWG_DIR . "/admin/models/BWGModelOptions_bwg.php";
    $model = new BWGModelOptions_bwg();

    require_once WD_BWG_DIR . "/admin/views/BWGViewOptions_bwg.php";
    $view = new BWGViewOptions_bwg($model);
    echo WDWLibrary::message('Changes must be saved.', 'error');
    $view->display(true);
  }

  public function save() {
    $this->save_db();
    $this->display();
  }

  public function save_db() {
    global $wpdb;
    $id = 1;
    if (isset($_POST['old_images_directory'])) {
      $old_images_directory = esc_html(stripslashes($_POST['old_images_directory']));
    }
    if (isset($_POST['images_directory'])) {
      $images_directory = esc_html(stripslashes($_POST['images_directory']));
      if (!is_dir(ABSPATH . $images_directory)) {
        echo WDWLibrary::message('Uploads directory doesn\'t exist. Old value is restored.', 'error');
        if ($old_images_directory) {
          $images_directory = $old_images_directory;
        }
        else {
          $upload_dir = wp_upload_dir();
          if (!is_dir($upload_dir['basedir'] . '/photo-gallery')) {
            mkdir($upload_dir['basedir'] . '/photo-gallery', 0777);
          }
          $images_directory = str_replace(ABSPATH, '', $upload_dir['basedir']);
        }
      }
    }
    else {
      $upload_dir = wp_upload_dir();
      if (!is_dir($upload_dir['basedir'] . '/photo-gallery')) {
        mkdir($upload_dir['basedir'] . '/photo-gallery', 0777);
      }
      $images_directory = str_replace(ABSPATH, '', $upload_dir['basedir']);
    }
    $resize_image = (isset($_POST['resize_image']) ? esc_html(stripslashes($_POST['resize_image'])) : 1);

    $masonry = (isset($_POST['masonry']) ? esc_html(stripslashes($_POST['masonry'])) : 'vertical');
    $mosaic = (isset($_POST['mosaic']) ? esc_html(stripslashes($_POST['mosaic'])) : 'vertical');
    $resizable_mosaic = (isset($_POST['resizable_mosaic']) ? esc_html(stripslashes($_POST['resizable_mosaic'])) : 0);
    $mosaic_total_width = (isset($_POST['mosaic_total_width']) ? esc_html(stripslashes($_POST['mosaic_total_width'])) : 100);

    $image_column_number = (isset($_POST['image_column_number']) ? esc_html(stripslashes($_POST['image_column_number'])) : 5);
    $images_per_page = (isset($_POST['images_per_page']) ? esc_html(stripslashes($_POST['images_per_page'])) : 30);
    $thumb_width = (isset($_POST['thumb_width']) ? esc_html(stripslashes($_POST['thumb_width'])) : 120);
    $thumb_height = (isset($_POST['thumb_height']) ? esc_html(stripslashes($_POST['thumb_height'])) : 90);
    $upload_thumb_width = (isset($_POST['upload_thumb_width']) ? esc_html(stripslashes($_POST['upload_thumb_width'])) : 300);
    $upload_thumb_height = (isset($_POST['upload_thumb_height']) ? esc_html(stripslashes($_POST['upload_thumb_height'])) : 300);
	  $upload_img_width = (isset($_POST['upload_img_width']) ? esc_html(stripslashes($_POST['upload_img_width'])) : 1200);
    $upload_img_height = (isset($_POST['upload_img_height']) ? esc_html(stripslashes($_POST['upload_img_height'])) : 1200);
    $image_enable_page = (isset($_POST['image_enable_page']) ? esc_html(stripslashes($_POST['image_enable_page'])) : 1);
    $image_title_show_hover = (isset($_POST['image_title_show_hover']) ? esc_html(stripslashes($_POST['image_title_show_hover'])) : 'none');
    $album_column_number = (isset($_POST['album_column_number']) ? esc_html(stripslashes($_POST['album_column_number'])) : 5);
    $albums_per_page = (isset($_POST['albums_per_page']) ? esc_html(stripslashes($_POST['albums_per_page'])) : 30);
    $album_title_show_hover = (isset($_POST['album_title_show_hover']) ? esc_html(stripslashes($_POST['album_title_show_hover'])) : 'hover');
    $album_thumb_width = (isset($_POST['album_thumb_width']) ? esc_html(stripslashes($_POST['album_thumb_width'])) : 120);
    $album_thumb_height = (isset($_POST['album_thumb_height']) ? esc_html(stripslashes($_POST['album_thumb_height'])) : 90);
    $album_enable_page = (isset($_POST['album_enable_page']) ? esc_html(stripslashes($_POST['album_enable_page'])) : 1);
    $extended_album_height = (isset($_POST['extended_album_height']) ? esc_html(stripslashes($_POST['extended_album_height'])) : 150);
    $extended_album_description_enable = (isset($_POST['extended_album_description_enable']) ? esc_html(stripslashes($_POST['extended_album_description_enable'])) : 1);
    $image_browser_width = (isset($_POST['image_browser_width']) ? esc_html(stripslashes($_POST['image_browser_width'])) : 800);
    $image_browser_title_enable = (isset($_POST['image_browser_title_enable']) ? esc_html(stripslashes($_POST['image_browser_title_enable'])) : 1);
    $image_browser_description_enable = (isset($_POST['image_browser_description_enable']) ? esc_html(stripslashes($_POST['image_browser_description_enable'])) : 1);
    $blog_style_width = (isset($_POST['blog_style_width']) ? esc_html(stripslashes($_POST['blog_style_width'])) : 800);
    $blog_style_title_enable = (isset($_POST['blog_style_title_enable']) ? esc_html(stripslashes($_POST['blog_style_title_enable'])) : 1);
    $blog_style_images_per_page = (isset($_POST['blog_style_images_per_page']) ? esc_html(stripslashes($_POST['blog_style_images_per_page'])) : 5);
    $blog_style_enable_page = (isset($_POST['blog_style_enable_page']) ? esc_html(stripslashes($_POST['blog_style_enable_page'])) : 1);
    $slideshow_type = (isset($_POST['slideshow_type']) ? esc_html(stripslashes($_POST['slideshow_type'])) : 'fade');
    $slideshow_interval = (isset($_POST['slideshow_interval']) ? esc_html(stripslashes($_POST['slideshow_interval'])) : 5);
    $slideshow_width = (isset($_POST['slideshow_width']) ? esc_html(stripslashes($_POST['slideshow_width'])) : 800);
    $slideshow_height = (isset($_POST['slideshow_height']) ? esc_html(stripslashes($_POST['slideshow_height'])) : 600);
    $slideshow_enable_autoplay = (isset($_POST['slideshow_enable_autoplay']) ? esc_html(stripslashes($_POST['slideshow_enable_autoplay'])) : 1);
    $slideshow_enable_shuffle = (isset($_POST['slideshow_enable_shuffle']) ? esc_html(stripslashes($_POST['slideshow_enable_shuffle'])) : 1);
    $slideshow_enable_ctrl = (isset($_POST['slideshow_enable_ctrl']) ? esc_html(stripslashes($_POST['slideshow_enable_ctrl'])) : 1);
    $slideshow_enable_filmstrip = (isset($_POST['slideshow_enable_filmstrip']) ? esc_html(stripslashes($_POST['slideshow_enable_filmstrip'])) : 1);
    $slideshow_filmstrip_height = (isset($_POST['slideshow_filmstrip_height']) ? esc_html(stripslashes($_POST['slideshow_filmstrip_height'])) : 70);
    $slideshow_enable_title = (isset($_POST['slideshow_enable_title']) ? esc_html(stripslashes($_POST['slideshow_enable_title'])) : 0);
    $slideshow_title_position = (isset($_POST['slideshow_title_position']) ? esc_html(stripslashes($_POST['slideshow_title_position'])) : 'top-right');
    $slideshow_title_full_width = (isset($_POST['slideshow_title_full_width']) ? esc_html(stripslashes($_POST['slideshow_title_full_width'])) : 0);
    $slideshow_enable_description = (isset($_POST['slideshow_enable_description']) ? esc_html(stripslashes($_POST['slideshow_enable_description'])) : 1);
    $slideshow_description_position = (isset($_POST['slideshow_description_position']) ? esc_html(stripslashes($_POST['slideshow_description_position'])) : 'bottom-right');
    $slideshow_enable_music = (isset($_POST['slideshow_enable_music']) ? esc_html(stripslashes($_POST['slideshow_enable_music'])) : 0);
    $slideshow_audio_url = (isset($_POST['slideshow_audio_url']) ? esc_html(stripslashes($_POST['slideshow_audio_url'])) : '');
    $popup_width = (isset($_POST['popup_width']) ? esc_html(stripslashes($_POST['popup_width'])) : 800);
    $popup_height = (isset($_POST['popup_height']) ? esc_html(stripslashes($_POST['popup_height'])) : 600);
    $popup_type = (isset($_POST['popup_type']) ? esc_html(stripslashes($_POST['popup_type'])) : 'fade');
    $popup_interval = (isset($_POST['popup_interval']) ? esc_html(stripslashes($_POST['popup_interval'])) : 5);
    $popup_enable_filmstrip = (isset($_POST['popup_enable_filmstrip']) ? esc_html(stripslashes($_POST['popup_enable_filmstrip'])) : 1);
    $popup_filmstrip_height = (isset($_POST['popup_filmstrip_height']) ? esc_html(stripslashes($_POST['popup_filmstrip_height'])) : 50);
    $popup_enable_ctrl_btn = (isset($_POST['popup_enable_ctrl_btn']) ? esc_html(stripslashes($_POST['popup_enable_ctrl_btn'])) : 1);
    $popup_enable_fullscreen = (isset($_POST['popup_enable_fullscreen']) ? esc_html(stripslashes($_POST['popup_enable_fullscreen'])) : 1);
    $popup_enable_comment = (isset($_POST['popup_enable_comment']) ? esc_html(stripslashes($_POST['popup_enable_comment'])) : 1);
    $popup_enable_email = (isset($_POST['popup_enable_email']) ? esc_html(stripslashes($_POST['popup_enable_email'])) : 0);
    $popup_enable_captcha = (isset($_POST['popup_enable_captcha']) ? esc_html(stripslashes($_POST['popup_enable_captcha'])) : 0);
    $popup_enable_download = (isset($_POST['popup_enable_download']) ? esc_html(stripslashes($_POST['popup_enable_download'])) : 0);
    $popup_enable_fullsize_image = (isset($_POST['popup_enable_fullsize_image']) ? esc_html(stripslashes($_POST['popup_enable_fullsize_image'])) : 0);
    $popup_enable_facebook = (isset($_POST['popup_enable_facebook']) ? esc_html(stripslashes($_POST['popup_enable_facebook'])) : 1);
    $popup_enable_twitter = (isset($_POST['popup_enable_twitter']) ? esc_html(stripslashes($_POST['popup_enable_twitter'])) : 1);
    $popup_enable_google = (isset($_POST['popup_enable_google']) ? esc_html(stripslashes($_POST['popup_enable_google'])) : 1);
    $popup_enable_pinterest = (isset($_POST['popup_enable_pinterest']) ? esc_html(stripslashes($_POST['popup_enable_pinterest'])) : 0);
    $popup_enable_tumblr = (isset($_POST['popup_enable_tumblr']) ? esc_html(stripslashes($_POST['popup_enable_tumblr'])) : 0);
    $watermark_type = (isset($_POST['watermark_type']) ? esc_html(stripslashes($_POST['watermark_type'])) : 'none');
    $watermark_position = (isset($_POST['watermark_position']) ? esc_html(stripslashes($_POST['watermark_position'])) : 'bottom-right');
    $watermark_width = (isset($_POST['watermark_width']) ? esc_html(stripslashes($_POST['watermark_width'])) : 600);
    $watermark_height = (isset($_POST['watermark_height']) ? esc_html(stripslashes($_POST['watermark_height'])) : 600);
    $watermark_url = (isset($_POST['watermark_url']) ? esc_html(stripslashes($_POST['watermark_url'])) : WD_BWG_URL . '/images/watermark.png');
    $watermark_text = (isset($_POST['watermark_text']) ? esc_html(stripslashes($_POST['watermark_text'])) : 'web-dorado.com');
    $watermark_link = (isset($_POST['watermark_link']) ? esc_html(stripslashes($_POST['watermark_link'])) : 'http://www.web-dorado.com');
    $watermark_opacity = (isset($_POST['watermark_opacity']) ? esc_html(stripslashes($_POST['watermark_opacity'])) : 30);
    $watermark_font_size = (isset($_POST['watermark_font_size']) ? esc_html(stripslashes($_POST['watermark_font_size'])) : 20);
    $watermark_font = (isset($_POST['watermark_font']) ? esc_html(stripslashes($_POST['watermark_font'])) : '');
    $watermark_color = (isset($_POST['watermark_color']) ? esc_html(stripslashes($_POST['watermark_color'])) : '');
    $built_in_watermark_type = (isset($_POST['built_in_watermark_type']) ? esc_html(stripslashes($_POST['built_in_watermark_type'])) : 'none');
    $built_in_watermark_position = (isset($_POST['built_in_watermark_position']) ? esc_html(stripslashes($_POST['built_in_watermark_position'])) : 'middle-center');
    $built_in_watermark_size = (isset($_POST['built_in_watermark_size']) ? esc_html(stripslashes($_POST['built_in_watermark_size'])) : 15);
    $built_in_watermark_url = (isset($_POST['built_in_watermark_url']) ? esc_html(stripslashes($_POST['built_in_watermark_url'])) : WD_BWG_URL . '/images/watermark.png');
    $built_in_watermark_text = (isset($_POST['built_in_watermark_text']) ? esc_html(stripslashes($_POST['built_in_watermark_text'])) : 'web-dorado.com');
    $built_in_watermark_opacity = (isset($_POST['built_in_watermark_opacity']) ? esc_html(stripslashes($_POST['built_in_watermark_opacity'])) : 30);
    $built_in_watermark_font_size = (isset($_POST['built_in_watermark_font_size']) ? esc_html(stripslashes($_POST['built_in_watermark_font_size'])) : 20);
    $built_in_watermark_font = (isset($_POST['built_in_watermark_font']) ? esc_html(stripslashes($_POST['built_in_watermark_font'])) : '');
    $built_in_watermark_color = (isset($_POST['built_in_watermark_color']) ? esc_html(stripslashes($_POST['built_in_watermark_color'])) : '');
    $gallery_role = (isset($_POST['gallery_role']) ? esc_html(stripslashes($_POST['gallery_role'])) : 0);
    $image_right_click = (isset($_POST['image_right_click']) ? esc_html(stripslashes($_POST['image_right_click'])) : 0);
    $popup_fullscreen = (isset($_POST['popup_fullscreen']) ? esc_html(stripslashes($_POST['popup_fullscreen'])) : 0);
    $album_role = (isset($_POST['album_role']) ? esc_html(stripslashes($_POST['album_role'])) : 0);
    $image_role = (isset($_POST['image_role']) ? esc_html(stripslashes($_POST['image_role'])) : 0);
    $popup_autoplay = (isset($_POST['popup_autoplay']) ? esc_html(stripslashes($_POST['popup_autoplay'])) : 0);
    $album_view_type = (isset($_POST['album_view_type']) ? esc_html(stripslashes($_POST['album_view_type'])) : 'thumbnail');
    $show_search_box = (isset($_POST['show_search_box']) ? esc_html(stripslashes($_POST['show_search_box'])) : 0);
    $search_box_width = (isset($_POST['search_box_width']) ? esc_html(stripslashes($_POST['search_box_width'])) : 180);
    $preload_images = (isset($_POST['preload_images']) ? esc_html(stripslashes($_POST['preload_images'])) : 1);
    $preload_images_count = (isset($_POST['preload_images_count']) ? esc_html(stripslashes($_POST['preload_images_count'])) : 10);
    $popup_enable_info = (isset($_POST['popup_enable_info']) ? esc_html(stripslashes($_POST['popup_enable_info'])) : 1);
    $popup_info_always_show = (isset($_POST['popup_info_always_show']) ? esc_html(stripslashes($_POST['popup_info_always_show'])) : 0);
    $popup_enable_rate = (isset($_POST['popup_enable_rate']) ? esc_html(stripslashes($_POST['popup_enable_rate'])) : 0);
    $thumb_click_action = (isset($_POST['thumb_click_action']) ? esc_html(stripslashes($_POST['thumb_click_action'])) : 'open_lightbox');
    $thumb_link_target = (isset($_POST['thumb_link_target']) ? esc_html(stripslashes($_POST['thumb_link_target'])) : 1);
    $comment_moderation = (isset($_POST['comment_moderation']) ? esc_html(stripslashes($_POST['comment_moderation'])) : 0);
    $popup_hit_counter = (isset($_POST['popup_hit_counter']) ? esc_html(stripslashes($_POST['popup_hit_counter'])) : 0);
    $enable_ML_import = (isset($_POST['enable_ML_import']) ? esc_html(stripslashes($_POST['enable_ML_import'])) : 0);
    $autoupdate_interval = (isset($_POST['autoupdate_interval_hour']) && isset($_POST['autoupdate_interval_min']) ? ((int) $_POST['autoupdate_interval_hour'] * 60 + (int) $_POST['autoupdate_interval_min']) : 30);
    /*minimum autoupdate interval is 1 min*/
    $autoupdate_interval = ($autoupdate_interval >= 1 ? $autoupdate_interval : 1 );
    $instagram_client_id = (isset($_POST['instagram_client_id']) ? esc_html(stripslashes($_POST['instagram_client_id'])) : '');
    $showthumbs_name = (isset($_POST['thumb_name']) ? esc_html(stripslashes($_POST['thumb_name'])) : 1);
    $show_album_name = (isset($_POST['show_album_name_enable']) ? esc_html(stripslashes($_POST['show_album_name_enable'])) : 1);
    $show_image_counts = (isset($_POST['show_image_counts']) ? esc_html(stripslashes($_POST['show_image_counts'])) : 0);
    $play_icon = (isset($_POST['play_icon']) ? esc_html(stripslashes($_POST['play_icon'])) : 1);
    $show_masonry_thumb_description = (isset($_POST['show_masonry_thumb_description']) ? esc_html(stripslashes($_POST['show_masonry_thumb_description'])) : 0);
    $popup_info_full_width = (isset($_POST['popup_info_full_width']) ? esc_html(stripslashes($_POST['popup_info_full_width'])) : 0);
		$show_sort_images = (isset($_POST['show_sort_images']) ? esc_html(stripslashes($_POST['show_sort_images'])) : 0);
		$enable_seo = (isset($_POST['enable_seo']) ? esc_html(stripslashes($_POST['enable_seo'])) : 1);
    $autohide_lightbox_navigation = (isset($_POST['autohide_lightbox_navigation']) ? esc_html(stripslashes($_POST['autohide_lightbox_navigation'])) : 1);
    $autohide_slideshow_navigation = (isset($_POST['autohide_slideshow_navigation']) ? esc_html(stripslashes($_POST['autohide_slideshow_navigation'])) : 1);
    $read_metadata = (isset($_POST['read_metadata']) ? esc_html(stripslashes($_POST['read_metadata'])) : 0);
    $enable_loop = (isset($_POST['enable_loop']) ? esc_html(stripslashes($_POST['enable_loop'])) : 1);
    $enable_addthis = (isset($_POST['enable_addthis']) ? esc_html(stripslashes($_POST['enable_addthis'])) : 0);
    $addthis_profile_id = (isset($_POST['addthis_profile_id']) ? esc_html(stripslashes($_POST['addthis_profile_id'])) : '');

    $carousel_interval = (isset($_POST['carousel_interval']) ? esc_html(stripslashes($_POST['carousel_interval'])) : 5);
    $carousel_width = (isset($_POST['carousel_width']) ? esc_html(stripslashes($_POST['carousel_width'])) : 300);
    $carousel_height = (isset($_POST['carousel_height']) ? esc_html(stripslashes($_POST['carousel_height'])) : 300);
    $carousel_image_par = (isset($_POST['carousel_image_par']) ? esc_html(stripslashes($_POST['carousel_image_par'])) : 0.75);
	  $carousel_image_column_number = (isset($_POST['carousel_image_column_number']) ? esc_html(stripslashes($_POST['carousel_image_column_number'])) : 5);
    $carousel_enable_title = (isset($_POST['carousel_enable_title']) ? esc_html(stripslashes($_POST['carousel_enable_title'])) : 0);
   	$carousel_enable_autoplay = (isset($_POST['carousel_enable_autoplay']) ? esc_html(stripslashes($_POST['carousel_enable_autoplay'])) : 0);
    $carousel_r_width = (isset($_POST['carousel_r_width']) ? esc_html(stripslashes($_POST['carousel_r_width'])) : 800);
    $carousel_fit_containerWidth = (isset($_POST['carousel_fit_containerWidth']) ? esc_html(stripslashes($_POST['carousel_fit_containerWidth'])) : 1);
    $carousel_prev_next_butt = (isset($_POST['carousel_prev_next_butt']) ? esc_html(stripslashes($_POST['carousel_prev_next_butt'])) : 1);
    $carousel_play_pause_butt = (isset($_POST['carousel_play_pause_butt']) ? esc_html(stripslashes($_POST['carousel_play_pause_butt'])) : 1);
    $bwg_permissions = (isset($_POST['permissions']) ? esc_html(stripslashes($_POST['permissions'])) : 'manage_options');
    $facebook_app_id = (isset($_POST['facebook_app_id']) ? esc_html(stripslashes($_POST['facebook_app_id'])) : '');
	$facebook_app_secret = (isset($_POST['facebook_app_secret']) ? esc_html(stripslashes($_POST['facebook_app_secret'])) : '');
	$show_tag_box = (isset($_POST['show_tag_box']) ? esc_html(stripslashes($_POST['show_tag_box'])) : 0);
  $show_hide_custom_post = (isset($_POST['show_hide_custom_post']) ? esc_html(stripslashes($_POST['show_hide_custom_post'])) : 0);
  $show_hide_post_meta = (isset($_POST['show_hide_post_meta']) ? esc_html(stripslashes($_POST['show_hide_post_meta'])) : 0);

    $save = $wpdb->update($wpdb->prefix . 'bwg_option', array(
      'images_directory' => $images_directory,
      'masonry' => $masonry,
      'mosaic' => $mosaic,
      'resizable_mosaic' => $resizable_mosaic,
      'mosaic_total_width'=> $mosaic_total_width,
      'image_column_number' => $image_column_number,
      'images_per_page' => $images_per_page,
      'thumb_width' => $thumb_width,
      'thumb_height' => $thumb_height,
      'upload_thumb_width' => $upload_thumb_width,
      'upload_thumb_height' => $upload_thumb_height,
      'upload_img_width' => $upload_img_width,
      'upload_img_height' => $upload_img_height,
      'image_enable_page' => $image_enable_page,
      'image_title_show_hover' => $image_title_show_hover,
      'album_column_number' => $album_column_number,
      'albums_per_page' => $albums_per_page,
      'album_title_show_hover' => $album_title_show_hover,
      'album_thumb_width' => $album_thumb_width,
      'album_thumb_height' => $album_thumb_height,
      'album_enable_page' => $album_enable_page,
      'extended_album_height' => $extended_album_height,
      'extended_album_description_enable' => $extended_album_description_enable,
      'image_browser_width' => $image_browser_width,
      'image_browser_title_enable' => $image_browser_title_enable,
      'image_browser_description_enable' => $image_browser_description_enable,
      'blog_style_width' => $blog_style_width,
      'blog_style_title_enable' => $blog_style_title_enable,
      'blog_style_images_per_page' => $blog_style_images_per_page,
      'blog_style_enable_page' => $blog_style_enable_page,
      'slideshow_type' => $slideshow_type,
      'slideshow_interval' => $slideshow_interval,
      'slideshow_width' => $slideshow_width,
      'slideshow_height' => $slideshow_height,
      'slideshow_enable_autoplay' => $slideshow_enable_autoplay,
      'slideshow_enable_shuffle' => $slideshow_enable_shuffle,
      'slideshow_enable_ctrl' => $slideshow_enable_ctrl,
      'slideshow_enable_filmstrip' => $slideshow_enable_filmstrip,
      'slideshow_filmstrip_height' => $slideshow_filmstrip_height,
      'slideshow_enable_title' => $slideshow_enable_title,
      'slideshow_title_position' => $slideshow_title_position,
      'slideshow_title_full_width' => $slideshow_title_full_width,
      'slideshow_enable_description' => $slideshow_enable_description,
      'slideshow_description_position' => $slideshow_description_position,
      'slideshow_enable_music' => $slideshow_enable_music,
      'slideshow_audio_url' => $slideshow_audio_url,
      'popup_width' => $popup_width,
      'popup_height' => $popup_height,
      'popup_type' => $popup_type,
      'popup_interval' => $popup_interval,
      'popup_enable_filmstrip' => $popup_enable_filmstrip,
      'popup_filmstrip_height' => $popup_filmstrip_height,
      'popup_enable_ctrl_btn' => $popup_enable_ctrl_btn,
      'popup_enable_fullscreen' => $popup_enable_fullscreen,
      'popup_enable_comment' => $popup_enable_comment,
      'popup_enable_email' => $popup_enable_email,
      'popup_enable_captcha' => $popup_enable_captcha,
      'popup_enable_download' => $popup_enable_download,
      'popup_enable_fullsize_image' => $popup_enable_fullsize_image,
      'popup_enable_facebook' => $popup_enable_facebook,
      'popup_enable_twitter' => $popup_enable_twitter,
      'popup_enable_google' => $popup_enable_google,
      'popup_enable_pinterest' => $popup_enable_pinterest,
      'popup_enable_tumblr' => $popup_enable_tumblr,
      'watermark_type' => $watermark_type,
      'watermark_position' => $watermark_position,
      'watermark_width' => $watermark_width,
      'watermark_height' => $watermark_height,
      'watermark_url' => $watermark_url,
      'watermark_text' => $watermark_text,
      'watermark_link' => $watermark_link,
      'watermark_font_size' => $watermark_font_size,
      'watermark_font' => $watermark_font,
      'watermark_color' => $watermark_color,
      'watermark_opacity' => $watermark_opacity,
      'built_in_watermark_type' => $built_in_watermark_type,
      'built_in_watermark_position' => $built_in_watermark_position,
      'built_in_watermark_size' => $built_in_watermark_size,
      'built_in_watermark_url' => $built_in_watermark_url,
      'built_in_watermark_text' => $built_in_watermark_text,
      'built_in_watermark_font_size' => $built_in_watermark_font_size,
      'built_in_watermark_font' => $built_in_watermark_font,
      'built_in_watermark_color' => $built_in_watermark_color,
      'built_in_watermark_opacity' => $built_in_watermark_opacity,
      'gallery_role' => $gallery_role,
      'image_right_click' => $image_right_click,
      'popup_fullscreen' => $popup_fullscreen,
      'album_role' => $album_role,
      'image_role' => $image_role,
      'popup_autoplay' => $popup_autoplay,
      'album_view_type' => $album_view_type,
      'show_search_box' => $show_search_box,
      'search_box_width' => $search_box_width,
      'preload_images' => $preload_images,
      'preload_images_count' => $preload_images_count,
      'popup_enable_info' => $popup_enable_info,
      'popup_info_always_show' => $popup_info_always_show,
      'popup_enable_rate' => $popup_enable_rate,
      'thumb_click_action' => $thumb_click_action,
      'thumb_link_target' => $thumb_link_target,
      'comment_moderation' => $comment_moderation,
      'popup_hit_counter' => $popup_hit_counter,
      'enable_ML_import' => $enable_ML_import,
      'autoupdate_interval' => $autoupdate_interval,
      'instagram_client_id' => $instagram_client_id,
      'showthumbs_name' => $showthumbs_name,
      'show_album_name' => $show_album_name,
      'show_image_counts' => $show_image_counts,
      'play_icon' => $play_icon,
      'show_masonry_thumb_description' => $show_masonry_thumb_description,
      'popup_info_full_width' => $popup_info_full_width,
      'show_sort_images' => $show_sort_images,
      'enable_seo' => $enable_seo,
      'autohide_lightbox_navigation' => $autohide_lightbox_navigation,
      'autohide_slideshow_navigation' => $autohide_slideshow_navigation,
      'read_metadata' => $read_metadata,
      'enable_loop' => $enable_loop,
      'enable_addthis' => $enable_addthis,
      'addthis_profile_id' => $addthis_profile_id,

      'carousel_interval' => $carousel_interval,
      'carousel_width' => $carousel_width,
      'carousel_height' => $carousel_height,
	    'carousel_image_column_number' => $carousel_image_column_number,
      'carousel_image_par' => $carousel_image_par,
      'carousel_enable_title' => $carousel_enable_title,
	    'carousel_enable_autoplay' => $carousel_enable_autoplay,
      'carousel_r_width' => $carousel_r_width,
      'carousel_fit_containerWidth' => $carousel_fit_containerWidth,
      'carousel_prev_next_butt' => $carousel_prev_next_butt,
      'carousel_play_pause_butt' => $carousel_play_pause_butt,
      'permissions' => $bwg_permissions,
      'facebook_app_id' => $facebook_app_id,
	  'facebook_app_secret' => $facebook_app_secret,
	  'show_tag_box' => $show_tag_box,
    'show_hide_custom_post' => $show_hide_custom_post,
    'show_hide_post_meta' => $show_hide_post_meta,
      ), array('id' => 1));

    if ($save !== FALSE) {
      if ($old_images_directory && $old_images_directory != $images_directory) {
        rename(ABSPATH . $old_images_directory . '/photo-gallery', ABSPATH . $images_directory . '/photo-gallery');
      }
      if (!is_dir(ABSPATH . $images_directory . '/photo-gallery')) {
        mkdir(ABSPATH . $images_directory . '/photo-gallery', 0777);
      }
      echo WDWLibrary::message(__('Item Succesfully Saved.', 'bwg_back'), 'updated');

    }
    else {
      echo WDWLibrary::message('Error. Please install plugin again.', 'error');
    }
  }

  ////////////////////////////////////////////////////////////////////////////////////////
  // Getters & Setters                                                                  //
  ////////////////////////////////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////////////////////////////////
  // Private Methods                                                                    //
  ////////////////////////////////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////////////////////////////////
  // Listeners                                                                          //
  ////////////////////////////////////////////////////////////////////////////////////////
}


text:
using System;
using System.Threading;
using System.Threading.Tasks;

namespace Proto.Utils
{
    public static class TaskExtensions
    {
        public static async Task<TResult> WithTimeout<TResult>(this Task<TResult> task, TimeSpan timeout)
        {
            using var timeoutCancellationTokenSource = new CancellationTokenSource();

            var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token));
            if (completedTask != task) throw new TimeoutException("The operation has timed out.");

            timeoutCancellationTokenSource.Cancel();
            return await task; // Very important in order to propagate exceptions
        }

    }

    public static class Retry
    {
        public const int Forever = 0;
        public static async Task<T> Try<T>(Func<Task<T>> body, int retryCount = 10, int backoffMilliSeconds = 100, int maxBackoffMilliseconds = 5000, Action<int,Exception>? onError=null, Action<Exception>? onFailed=null)
        {
            for (var i = 0; retryCount == 0 || i < retryCount; i++)
            {
                try
                {
                    var res = await body();
                    return res;
                }
                catch(Exception x)
                {
                    onError?.Invoke(i,x);

                    if (i == retryCount - 1)
                    {
                        onFailed?.Invoke(x);
                        throw;
                    }

                    var backoff = Math.Min(i * backoffMilliSeconds, maxBackoffMilliseconds);
                    await Task.Delay(backoff);
                }
            }

            throw new Exception("This should never happen...");
        }

        public static async Task Try(Func<Task> body, int retryCount = 10, int backoffMilliSeconds = 100, int maxBackoffMilliseconds = 5000, Action<int,Exception>? onError=null, Action<Exception>? onFailed=null, bool ignoreFailure=false)
        {
            for (var i = 0; retryCount == 0 || i < retryCount; i++)
            {
                try
                {
                    await body();
                    return;
                }
                catch(Exception x)
                {
                    onError?.Invoke(i,x);

                    if (i == retryCount - 1)
                    {
                        onFailed?.Invoke(x);

                        if (ignoreFailure)
                            return;

                        throw;
                    }

                    var backoff = Math.Min(i * backoffMilliSeconds, maxBackoffMilliseconds);
                    await Task.Delay(backoff);
                }
            }

            throw new Exception("This should never happen...");
        }
    }
}