text:
/*************************************************************************/
/*  spatial_editor_plugin.h                                              */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                    http://www.godotengine.org                         */
/*************************************************************************/
/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md)    */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/
#ifndef SPATIAL_EDITOR_PLUGIN_H
#define SPATIAL_EDITOR_PLUGIN_H

#include "editor/editor_node.h"
#include "editor/editor_plugin.h"
#include "scene/3d/immediate_geometry.h"
#include "scene/3d/light.h"
#include "scene/3d/visual_instance.h"
#include "scene/gui/panel_container.h"
/**
	@author Juan Linietsky <reduzio@gmail.com>
*/

class Camera;
class SpatialEditor;
class SpatialEditorGizmos;

class SpatialEditorGizmo : public SpatialGizmo {

	GDCLASS(SpatialEditorGizmo, SpatialGizmo);

	bool selected;

public:
	void set_selected(bool p_selected) { selected = p_selected; }
	bool is_selected() const { return selected; }

	virtual String get_handle_name(int p_idx) const;
	virtual Variant get_handle_value(int p_idx) const;
	virtual void set_handle(int p_idx, Camera *p_camera, const Point2 &p_point);
	virtual void commit_handle(int p_idx, const Variant &p_restore, bool p_cancel = false);

	virtual bool intersect_frustum(const Camera *p_camera, const Vector<Plane> &p_frustum);
	virtual bool intersect_ray(const Camera *p_camera, const Point2 &p_point, Vector3 &r_pos, Vector3 &r_normal, int *r_gizmo_handle = NULL, bool p_sec_first = false);
	SpatialEditorGizmo();
};

class SpatialEditorViewport : public Control {

	GDCLASS(SpatialEditorViewport, Control);
	friend class SpatialEditor;
	enum {

		VIEW_TOP,
		VIEW_BOTTOM,
		VIEW_LEFT,
		VIEW_RIGHT,
		VIEW_FRONT,
		VIEW_REAR,
		VIEW_CENTER_TO_ORIGIN,
		VIEW_CENTER_TO_SELECTION,
		VIEW_ALIGN_SELECTION_WITH_VIEW,
		VIEW_PERSPECTIVE,
		VIEW_ENVIRONMENT,
		VIEW_ORTHOGONAL,
		VIEW_AUDIO_LISTENER,
		VIEW_GIZMOS,
	};

public:
	enum {
		GIZMO_BASE_LAYER = 27,
		GIZMO_EDIT_LAYER = 26,
		GIZMO_GRID_LAYER = 25
	};

private:
	int index;
	String name;
	void _menu_option(int p_option);
	Size2 prev_size;

	EditorNode *editor;
	EditorSelection *editor_selection;
	UndoRedo *undo_redo;

	Button *preview_camera;

	MenuButton *view_menu;

	Control *surface;
	Viewport *viewport;
	Camera *camera;
	bool transforming;
	bool orthogonal;
	float gizmo_scale;

	bool freelook_active;

	struct _RayResult {

		Spatial *item;
		float depth;
		int handle;
		_FORCE_INLINE_ bool operator<(const _RayResult &p_rr) const { return depth < p_rr.depth; }
	};

	void _update_name();
	void _compute_edit(const Point2 &p_point);
	void _clear_selected();
	void _select_clicked(bool p_append, bool p_single);
	void _select(Spatial *p_node, bool p_append, bool p_single);
	ObjectID _select_ray(const Point2 &p_pos, bool p_append, bool &r_includes_current, int *r_gizmo_handle = NULL, bool p_alt_select = false);
	void _find_items_at_pos(const Point2 &p_pos, bool &r_includes_current, Vector<_RayResult> &results, bool p_alt_select = false);
	Vector3 _get_ray_pos(const Vector2 &p_pos) const;
	Vector3 _get_ray(const Vector2 &p_pos);
	Point2 _point_to_screen(const Vector3 &p_point);
	Transform _get_camera_transform() const;
	int get_selected_count() const;

	Vector3 _get_camera_pos() const;
	Vector3 _get_camera_normal() const;
	Vector3 _get_screen_to_space(const Vector3 &p_vector3);

	void _select_region();
	bool _gizmo_select(const Vector2 &p_screenpos, bool p_highlight_only = false);

	float get_znear() const;
	float get_zfar() const;
	float get_fov() const;

	ObjectID clicked;
	Vector<_RayResult> selection_results;
	bool clicked_includes_current;
	bool clicked_wants_append;

	PopupMenu *selection_menu;

	enum NavigationScheme {
		NAVIGATION_GODOT,
		NAVIGATION_MAYA,
		NAVIGATION_MODO,
	};

	enum NavigationZoomStyle {
		NAVIGATION_ZOOM_VERTICAL,
		NAVIGATION_ZOOM_HORIZONTAL
	};

	enum NavigationMode {
		NAVIGATION_NONE,
		NAVIGATION_PAN,
		NAVIGATION_ZOOM,
		NAVIGATION_ORBIT,
		NAVIGATION_LOOK
	};
	enum TransformMode {
		TRANSFORM_NONE,
		TRANSFORM_ROTATE,
		TRANSFORM_TRANSLATE,
		TRANSFORM_SCALE

	};
	enum TransformPlane {
		TRANSFORM_VIEW,
		TRANSFORM_X_AXIS,
		TRANSFORM_Y_AXIS,
		TRANSFORM_Z_AXIS,
	};

	struct EditData {
		TransformMode mode;
		TransformPlane plane;
		Transform original;
		Vector3 click_ray;
		Vector3 click_ray_pos;
		Vector3 center;
		Vector3 orig_gizmo_pos;
		int edited_gizmo;
		Point2 mouse_pos;
		bool snap;
		Ref<SpatialEditorGizmo> gizmo;
		int gizmo_handle;
		Variant gizmo_initial_value;
		Vector3 gizmo_initial_pos;
	} _edit;

	struct Cursor {

		Vector3 pos;
		float x_rot, y_rot, distance;
		bool region_select;
		Point2 region_begin, region_end;

		Cursor() {
			x_rot = y_rot = 0.5;
			distance = 4;
			region_select = false;
		}
	} cursor;

	void scale_cursor_distance(real_t scale);

	real_t zoom_indicator_delay;

	RID move_gizmo_instance[3], rotate_gizmo_instance[3];

	String last_message;
	String message;
	float message_time;

	void set_message(String p_message, float p_time = 5);

	//
	void _update_camera();
	Transform to_camera_transform(const Cursor &p_cursor) const;
	void _draw();

	void _smouseenter();
	void _sinput(const Ref<InputEvent> &p_ie);
	void _update_freelook(real_t delta);
	SpatialEditor *spatial_editor;

	Camera *previewing;
	Camera *preview;

	void _preview_exited_scene();
	void _toggle_camera_preview(bool);
	void _init_gizmo_instance(int p_idx);
	void _finish_gizmo_instances();
	void _selection_result_pressed(int);
	void _selection_menu_hide();
	void _list_select(Ref<InputEventMouseButton> b);
	Point2i _get_warped_mouse_motion(const Ref<InputEventMouseMotion> &p_ev_mouse_motion) const;

protected:
	void _notification(int p_what);
	static void _bind_methods();

public:
	void update_transform_gizmo_view();

	void set_can_preview(Camera *p_preview);
	void set_state(const Dictionary &p_state);
	Dictionary get_state() const;
	void reset();
	bool is_freelook_active() const { return freelook_active; }

	void focus_selection();

	Viewport *get_viewport_node() { return viewport; }

	SpatialEditorViewport(SpatialEditor *p_spatial_editor, EditorNode *p_editor, int p_index);
};

class SpatialEditorSelectedItem : public Object {

	GDCLASS(SpatialEditorSelectedItem, Object);

public:
	Rect3 aabb;
	Transform original; // original location when moving
	Transform last_xform; // last transform
	Spatial *sp;
	RID sbox_instance;

	SpatialEditorSelectedItem() { sp = NULL; }
	~SpatialEditorSelectedItem();
};

class SpatialEditor : public VBoxContainer {

	GDCLASS(SpatialEditor, VBoxContainer);

public:
	enum ToolMode {

		TOOL_MODE_SELECT,
		TOOL_MODE_MOVE,
		TOOL_MODE_ROTATE,
		TOOL_MODE_SCALE,
		TOOL_MODE_LIST_SELECT,
		TOOL_MAX

	};

private:
	static const unsigned int VIEWPORTS_COUNT = 4;

	EditorNode *editor;
	EditorSelection *editor_selection;

	Control *viewport_base;
	SpatialEditorViewport *viewports[VIEWPORTS_COUNT];
	VSplitContainer *shader_split;
	HSplitContainer *palette_split;

	/////

	ToolMode tool_mode;
	bool orthogonal;

	VisualServer::ScenarioDebugMode scenario_debug;

	RID light;
	RID light_instance;
	Transform light_transform;

	RID origin;
	RID origin_instance;
	RID grid[3];
	RID grid_instance[3];
	bool grid_visible[3]; //currently visible
	float last_grid_snap;
	bool grid_enable[3]; //should be always visible if true
	bool grid_enabled;

	Ref<Mesh> move_gizmo[3], rotate_gizmo[3];
	Ref<SpatialMaterial> gizmo_color[3];
	Ref<SpatialMaterial> gizmo_hl;

	int over_gizmo_handle;

	Ref<Mesh> selection_box;
	RID indicators;
	RID indicators_instance;
	RID cursor_mesh;
	RID cursor_instance;
	Ref<SpatialMaterial> indicator_mat;
	Ref<SpatialMaterial> cursor_material;

	/*
	struct Selected {
		AABB aabb;
		Transform original; // original location when moving
		Transform last_xform; // last transform
		Spatial *sp;
		RID poly_instance;
	};

	Map<uint32_t,Selected> selected;
*/
	struct Gizmo {

		bool visible;
		float scale;
		Transform transform;
	} gizmo;

	enum MenuOption {

		MENU_TOOL_SELECT,
		MENU_TOOL_MOVE,
		MENU_TOOL_ROTATE,
		MENU_TOOL_SCALE,
		MENU_TOOL_LIST_SELECT,
		MENU_TRANSFORM_USE_SNAP,
		MENU_TRANSFORM_CONFIGURE_SNAP,
		MENU_TRANSFORM_LOCAL_COORDS,
		MENU_TRANSFORM_DIALOG,
		MENU_VIEW_USE_1_VIEWPORT,
		MENU_VIEW_USE_2_VIEWPORTS,
		MENU_VIEW_USE_2_VIEWPORTS_ALT,
		MENU_VIEW_USE_3_VIEWPORTS,
		MENU_VIEW_USE_3_VIEWPORTS_ALT,
		MENU_VIEW_USE_4_VIEWPORTS,
		MENU_VIEW_USE_DEFAULT_LIGHT,
		MENU_VIEW_USE_DEFAULT_SRGB,
		MENU_VIEW_DISPLAY_NORMAL,
		MENU_VIEW_DISPLAY_WIREFRAME,
		MENU_VIEW_DISPLAY_OVERDRAW,
		MENU_VIEW_DISPLAY_SHADELESS,
		MENU_VIEW_ORIGIN,
		MENU_VIEW_GRID,
		MENU_VIEW_CAMERA_SETTINGS,

	};

	Button *tool_button[TOOL_MAX];

	MenuButton *transform_menu;
	MenuButton *view_menu;

	ConfirmationDialog *snap_dialog;
	ConfirmationDialog *xform_dialog;
	ConfirmationDialog *settings_dialog;

	bool snap_enabled;
	LineEdit *snap_translate;
	LineEdit *snap_rotate;
	LineEdit *snap_scale;
	PanelContainer *menu_panel;

	LineEdit *xform_translate[3];
	LineEdit *xform_rotate[3];
	LineEdit *xform_scale[3];
	OptionButton *xform_type;

	VBoxContainer *settings_vbc;
	SpinBox *settings_fov;
	SpinBox *settings_znear;
	SpinBox *settings_zfar;
	DirectionalLight *settings_dlight;
	ImmediateGeometry *settings_sphere;
	Camera *settings_camera;
	float settings_default_light_rot_x;
	float settings_default_light_rot_y;

	ViewportContainer *settings_light_base;
	Viewport *settings_light_vp;
	ColorPickerButton *settings_ambient_color;
	Ref<Image> settings_light_dir_image;

	void _xform_dialog_action();
	void _menu_item_pressed(int p_option);

	HBoxContainer *hbc_menu;

	//
	//
	void _generate_selection_box();
	UndoRedo *undo_redo;

	void _instance_scene();
	void _init_indicators();
	void _finish_indicators();

	void _toggle_maximize_view(Object *p_viewport);

	Node *custom_camera;

	Object *_get_editor_data(Object *p_what);

	Ref<Environment> viewport_environment;

	Spatial *selected;

	void _request_gizmo(Object *p_obj);

	static SpatialEditor *singleton;

	void _node_removed(Node *p_node);
	SpatialEditorGizmos *gizmos;
	SpatialEditor();

	void _update_ambient_light_color(const Color &p_color);
	void _update_default_light_angle();
	void _default_light_angle_input(const Ref<InputEvent> &p_event);

	bool is_any_freelook_active() const;

protected:
	void _notification(int p_what);
	//void _gui_input(InputEvent p_event);
	void _unhandled_key_input(Ref<InputEvent> p_event);

	static void _bind_methods();

public:
	static SpatialEditor *get_singleton() { return singleton; }
	void snap_cursor_to_plane(const Plane &p_plane);

	float get_znear() const { return settings_znear->get_value(); }
	float get_zfar() const { return settings_zfar->get_value(); }
	float get_fov() const { return settings_fov->get_value(); }

	Transform get_gizmo_transform() const { return gizmo.transform; }
	bool is_gizmo_visible() const { return gizmo.visible; }

	ToolMode get_tool_mode() const { return tool_mode; }
	bool is_snap_enabled() const { return snap_enabled; }
	float get_translate_snap() const { return snap_translate->get_text().to_double(); }
	float get_rotate_snap() const { return snap_rotate->get_text().to_double(); }
	float get_scale_snap() const { return snap_scale->get_text().to_double(); }

	Ref<Mesh> get_move_gizmo(int idx) const { return move_gizmo[idx]; }
	Ref<Mesh> get_rotate_gizmo(int idx) const { return rotate_gizmo[idx]; }

	void update_transform_gizmo();

	void select_gizmo_highlight_axis(int p_axis);
	void set_custom_camera(Node *p_camera) { custom_camera = p_camera; }

	void set_undo_redo(UndoRedo *p_undo_redo) { undo_redo = p_undo_redo; }
	Dictionary get_state() const;
	void set_state(const Dictionary &p_state);

	Ref<Environment> get_viewport_environment() { return viewport_environment; }

	UndoRedo *get_undo_redo() { return undo_redo; }

	void add_control_to_menu_panel(Control *p_control);

	VSplitContainer *get_shader_split();
	HSplitContainer *get_palette_split();

	Spatial *get_selected() { return selected; }

	int get_over_gizmo_handle() const { return over_gizmo_handle; }
	void set_over_gizmo_handle(int idx) { over_gizmo_handle = idx; }

	void set_can_preview(Camera *p_preview);

	SpatialEditorViewport *get_editor_viewport(int p_idx) {
		ERR_FAIL_INDEX_V(p_idx, 4, NULL);
		return viewports[p_idx];
	}

	Camera *get_camera() { return NULL; }
	void edit(Spatial *p_spatial);
	void clear();
	SpatialEditor(EditorNode *p_editor);
	~SpatialEditor();
};

class SpatialEditorPlugin : public EditorPlugin {

	GDCLASS(SpatialEditorPlugin, EditorPlugin);

	SpatialEditor *spatial_editor;
	EditorNode *editor;

protected:
	static void _bind_methods();

public:
	void snap_cursor_to_plane(const Plane &p_plane);

	SpatialEditor *get_spatial_editor() { return spatial_editor; }
	virtual String get_name() const { return "3D"; }
	bool has_main_screen() const { return true; }
	virtual void make_visible(bool p_visible);
	virtual void edit(Object *p_object);
	virtual bool handles(Object *p_object) const;

	virtual Dictionary get_state() const;
	virtual void set_state(const Dictionary &p_state);
	virtual void clear() { spatial_editor->clear(); }

	SpatialEditorPlugin(EditorNode *p_node);
	~SpatialEditorPlugin();
};

#endif


text:
package org.apache.geronimo.monitoring.jmx.snapshot;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;

import javax.management.MBeanServer;

import org.apache.geronimo.monitoring.jmx.MasterRemoteControlJMX;
import org.apache.geronimo.monitoring.snapshot.SnapshotConfigXMLBuilder;

/**
 * Thread that is in charge of executing every x milliseconds. Upon each
 * iteration, a snapshot of the server's information is recorded.
 */
public class SnapshotThread extends Thread {

    volatile private long SNAPSHOT_DURATION;
    private MBeanServer mbServer = null;
    int threadStatus = 1;
    // list of mbean names that we will be taking snapshots of
    private ArrayList<String> mbeanNames;

    public SnapshotThread(long snapshot_length, MBeanServer mbServer) {
        SNAPSHOT_DURATION = snapshot_length;
        this.mbServer = mbServer;
        mbeanNames = new ArrayList<String>();
    }

    /**
     * Gets the elapsed time in milliseconds between each snapshot.
     *
     * @return long
     */
    public long getSnapshotDuration() {
        return SNAPSHOT_DURATION;
    }

    public Integer SnapshotStatus() {
        return threadStatus;

    }

    /**
     * Adds the mbean name to list in memory. To update the snapshot-config.xml
     * coder must use SnapshotConfigXMLBuilder class.
     *
     * @param mbeanName
     */
    public void addMBeanForSnapshot(String mbeanName) {
        mbeanNames.add(mbeanName);
    }

    /**
     * Removes the mbean name to list in memory. To update the
     * snapshot-config.xml coder must use SnapshotConfigXMLBuilder class.
     *
     * @param mbeanName
     */
    public void removeMBeanForSnapshot(String mbeanName) {
        mbeanNames.remove(mbeanName);
    }

    /**
     * Sets the elapsed time in milliseconds between each snapshot.
     *
     * @param snapshot_length
     */
    public void setSnapshotDuration(long snapshot_length) {
        if (snapshot_length == Long.MAX_VALUE)
            threadStatus = -1;
        SNAPSHOT_DURATION = snapshot_length;
    }

    public void run() {
        // get any saved mbean names from snapshot-config.xml
        mbeanNames = SnapshotConfigXMLBuilder.getMBeanNames();
        // in the case where nothing is present, grab a set of default mbeans
        if (mbeanNames.size() <= 0) {
            mbeanNames = getDefaultMBeanList();
        }
        // pause the thread from running every SNAPSHOT_DURATION seconds
        loop: while (true) {
            try {
                // store the data
                SnapshotProcessor.takeSnapshot();
                // wait for next snapshot
                for(long nSleep = SNAPSHOT_DURATION/1000; nSleep>0; nSleep--)
                {
                   Thread.sleep(1000);
                   if(SNAPSHOT_DURATION == Long.MAX_VALUE)
                       break loop;
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // flag turned on to know when the thread stops
        threadStatus = 0;
    }

    /**
     * @return A list of all default mbeans; namely, all connector or container
     *         mbean names Prereq: in order to be a connector or container mbean
     *         the name must contain "Connector"/"Container" and
     *         "Tomcat"/"Jetty"
     */
    private ArrayList<String> getDefaultMBeanList() {
        Set<String> mbeans = (new MasterRemoteControlJMX())
                .getStatisticsProviderMBeanNames();
        ArrayList<String> retval = new ArrayList<String>();
        for (Iterator it = mbeans.iterator(); it.hasNext();) {
            String name = (String) it.next();
            if (((name.contains("Connector") || name.contains("Container"))
                    && (name.contains("Jetty") || name.contains("Tomcat"))|| name.contains("JVM"))) {
                // this is a connector, so add to the list
                retval.add(name);
                // update the snapshot-config.xml to include these
                SnapshotConfigXMLBuilder.addMBeanName(name);
            }
        }
        return retval;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Httpful;

/**
 * Models an HTTP response
 *
 * @author Nate Good <me@nategood.com>
 */
class Response
{

    public $body,
           $raw_body,
           $headers,
           $raw_headers,
           $request,
           $code = 0,
           $content_type,
           $parent_type,
           $charset,
           $meta_data,
           $is_mime_vendor_specific = false,
           $is_mime_personal = false;

    private $parsers;
    /**
     * @param string $body
     * @param string $headers
     * @param Request $request
     * @param array $meta_data
     */
    public function __construct($body, $headers, Request $request, array $meta_data = array())
    {
        $this->request      = $request;
        $this->raw_headers  = $headers;
        $this->raw_body     = $body;
        $this->meta_data    = $meta_data;

        $this->code         = $this->_parseCode($headers);
        $this->headers      = Response\Headers::fromString($headers);

        $this->_interpretHeaders();

        $this->body         = $this->_parse($body);
    }

    /**
     * Status Code Definitions
     *
     * Informational 1xx
     * Successful    2xx
     * Redirection   3xx
     * Client Error  4xx
     * Server Error  5xx
     *
     * http://pretty-rfc.herokuapp.com/RFC2616#status.codes
     *
     * @return bool Did we receive a 4xx or 5xx?
     */
    public function hasErrors()
    {
        return $this->code >= 400;
    }

    /**
     * @return return bool
     */
    public function hasBody()
    {
        return !empty($this->body);
    }

    /**
     * Parse the response into a clean data structure
     * (most often an associative array) based on the expected
     * Mime type.
     * @return array|string|object the response parse accordingly
     * @param string Http response body
     */
    public function _parse($body)
    {
        // If the user decided to forgo the automatic
        // smart parsing, short circuit.
        if (!$this->request->auto_parse) {
            return $body;
        }

        // If provided, use custom parsing callback
        if (isset($this->request->parse_callback)) {
            return call_user_func($this->request->parse_callback, $body);
        }

        // Decide how to parse the body of the response in the following order
        //  1. If provided, use the mime type specifically set as part of the `Request`
        //  2. If a MimeHandler is registered for the content type, use it
        //  3. If provided, use the "parent type" of the mime type from the response
        //  4. Default to the content-type provided in the response
        $parse_with = $this->request->expected_type;
        if (empty($this->request->expected_type)) {
            $parse_with = Httpful::hasParserRegistered($this->content_type)
                ? $this->content_type
                : $this->parent_type;
        }

       return Httpful::get($parse_with)->parse($body);
    }

    /**
     * Parse text headers from response into
     * array of key value pairs
     * @return array parse headers
     * @param string $headers raw headers
     */
    public function _parseHeaders($headers)
    {
        $headers = preg_split("/(\r|\n)+/", $headers, -1, \PREG_SPLIT_NO_EMPTY);
        $parse_headers = array();
        for ($i = 1; $i < count($headers); $i++) {
            list($key, $raw_value) = explode(':', $headers[$i], 2);
            $key = trim($key);
            $value = trim($raw_value);
            if (array_key_exists($key, $parse_headers)) {
                // See HTTP RFC Sec 4.2 Paragraph 5
                // http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
                // If a header appears more than once, it must also be able to
                // be represented as a single header with a comma-separated
                // list of values.  We transform accordingly.
                $parse_headers[$key] .= ',' . $value;
            } else {
                $parse_headers[$key] = $value;
            }
        }
        return $parse_headers;
    }

    public function _parseCode($headers)
    {
        $parts = explode(' ', substr($headers, 0, strpos($headers, "\r\n")));
        if (count($parts) < 2 || !is_numeric($parts[1])) {
            throw new \Exception("Unable to parse response code from HTTP response due to malformed response");
        }
        return intval($parts[1]);
    }

    /**
     * After we've parse the headers, let's clean things
     * up a bit and treat some headers specially
     */
    public function _interpretHeaders()
    {
        // Parse the Content-Type and charset
        $content_type = isset($this->headers['Content-Type']) ? $this->headers['Content-Type'] : '';
        $content_type = explode(';', $content_type);

        $this->content_type = $content_type[0];
        if (count($content_type) == 2 && strpos($content_type[1], '=') !== false) {
            list($nill, $this->charset) = explode('=', $content_type[1]);
        }

        // RFC 2616 states "text/*" Content-Types should have a default
        // charset of ISO-8859-1. "application/*" and other Content-Types
        // are assumed to have UTF-8 unless otherwise specified.
        // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1
        // http://www.w3.org/International/O-HTTP-charset.en.php
        if (!isset($this->charset)) {
            $this->charset = substr($this->content_type, 5) === 'text/' ? 'iso-8859-1' : 'utf-8';
        }

        // Is vendor type? Is personal type?
        if (strpos($this->content_type, '/') !== false) {
            list($type, $sub_type) = explode('/', $this->content_type);
            $this->is_mime_vendor_specific = substr($sub_type, 0, 4) === 'vnd.';
            $this->is_mime_personal = substr($sub_type, 0, 4) === 'prs.';
        }

        // Parent type (e.g. xml for application/vnd.github.message+xml)
        $this->parent_type = $this->content_type;
        if (strpos($this->content_type, '+') !== false) {
            list($vendor, $this->parent_type) = explode('+', $this->content_type, 2);
            $this->parent_type = Mime::getFullMime($this->parent_type);
        }
    }

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


text:
pub use self::simple_request::{SimpleRequest};
pub use self::request::{Request, AsUrl};
pub use self::response::{Response};

pub use self::iron::{
    Url,
    Handler,
    HandleResult,
    HandleSuccessResult,
    HandleResultStrict,
    WrapUrl
};

pub mod request;
mod simple_request;
mod response;
mod iron;


text:
package com.amazonaws.services.config.model.transform;

import static com.amazonaws.util.StringUtils.UTF8;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
import java.util.List;

import com.amazonaws.AmazonClientException;
import com.amazonaws.services.config.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.json.*;

/**
 * ConfigurationRecorderMarshaller
 */
public class ConfigurationRecorderJsonMarshaller {

    /**
     * Marshall the given parameter object, and output to a JSONWriter
     */
    public void marshall(ConfigurationRecorder configurationRecorder,
            JSONWriter jsonWriter) {
        if (configurationRecorder == null) {
            throw new AmazonClientException(
                    "Invalid argument passed to marshall(...)");
        }

        try {
            jsonWriter.object();

            if (configurationRecorder.getName() != null) {
                jsonWriter.key("name").value(configurationRecorder.getName());
            }

            if (configurationRecorder.getRoleARN() != null) {
                jsonWriter.key("roleARN").value(
                        configurationRecorder.getRoleARN());
            }

            if (configurationRecorder.getRecordingGroup() != null) {
                jsonWriter.key("recordingGroup");
                RecordingGroupJsonMarshaller.getInstance().marshall(
                        configurationRecorder.getRecordingGroup(), jsonWriter);
            }

            jsonWriter.endObject();
        } catch (Throwable t) {
            throw new AmazonClientException(
                    "Unable to marshall request to JSON: " + t.getMessage(), t);
        }
    }

    private static ConfigurationRecorderJsonMarshaller instance;

    public static ConfigurationRecorderJsonMarshaller getInstance() {
        if (instance == null)
            instance = new ConfigurationRecorderJsonMarshaller();
        return instance;
    }

}


text:
@implementation HLURLInfoReader
+(void)readr:(NSString *)url callback:(HLURLInfoCallback)callback;
{
    NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:
                                     [NSURL URLWithString:url]];
    [request setHTTPMethod:@"HEAD"];
    [[[NSURLSession sharedSession] dataTaskWithRequest:request
                                     completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                                         if (callback) { callback(url,response.MIMEType,response.expectedContentLength,error);
                                         }
                                     }] resume];

}
@end


text:
<!-- Generated by //third_party/blink/web_tests/bluetooth/generate.py -->
<!DOCTYPE html>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/resources/testdriver.js"></script>
<script src="/resources/testdriver-vendor.js"></script>
<script src="/bluetooth/resources/bluetooth-test.js"></script>
<script src="/bluetooth/resources/bluetooth-fake-devices.js"></script>
<script src="/common/gc.js"></script>
<script>
'use strict';
bluetooth_test(() => {
  return setBluetoothFakeAdapter('DisconnectingDuringServiceRetrievalAdapter')
    .then(() => requestDeviceWithTrustedClick({
      filters: [{services: ['heart_rate']}]
    }))
    .then(device => device.gatt.connect())
    .then(gatt => assert_promise_rejects_with_message(
      gatt.getPrimaryServices('heart_rate'),
      new DOMException(
        'GATT Server is disconnected. Cannot retrieve services. ' +
        '(Re)connect first with `device.gatt.connect`.',
        'NetworkError')));
}, 'Device disconnects during getPrimaryServices call. Reject with NetworkError.');

</script>


text:
<launch>
  <node pkg="package" type="test_ns_invalid" ns="" />
</launch>


text:
'''
ssh_thread.py -- manages parallel execution of shell commands on remote hosts
Copyright 2012 -- Ben England
Licensed under the Apache License at http://www.apache.org/licenses/LICENSE-2.0
See Appendix on this page for instructions pertaining to license.
'''

import threading
import os
import errno
import copy
import time
import subprocess
import logging
# fs-drift modules
from fs_drift.fsd_log import start_log
from fs_drift.common import OK, NOTOK, FsDriftException
from fs_drift.unit_test_module import get_unit_test_module

# this class is just used to create a python thread
# for each remote host that we want to use as a workload generator
# the thread just executes an ssh command to run this program on a remote host

class ssh_thread(threading.Thread):

    ssh_prefix = ['ssh', '-x', '-o', 'StrictHostKeyChecking=no']

    def __str__(self):
        return 'ssh-thread:%s:%s:%s' % \
            (self.remote_host, str(self.status), self.remote_cmd)

    def __init__(self, log, remote_host, remote_cmd):
        threading.Thread.__init__(self)
        self.remote_host = remote_host
        self.remote_cmd = remote_cmd
        self.status = NOTOK
        self.log = log
        self.args = copy.deepcopy(self.ssh_prefix)
        self.args.append(remote_host)
        self.args.append(remote_cmd)
        tmpdir = os.getenv('TMPDIR')
        if tmpdir == None:
            tmpdir = '/tmp'
        self.popen_obj = None  # filled in latter

    def run(self):
        self.log.info(self.args)
        self.popen_obj = subprocess.Popen(self.args)
        self.popen_obj.wait()
        self.status = self.popen_obj.returncode

    def terminate(self):
        if self.popen_obj != None:
            try:
                self.popen_obj.terminate()
            except OSError as e:
                if e.errno != errno.ESRCH:
                    raise e
                self.log.debug('tried to kill non existent process %d',
                               self.popen_obj.pid)
        self.status = NOTOK

if __name__ == '__main__':
    unittest_module = get_unit_test_module()

    log = start_log('ssh_thread')

    class Test(unittest_module.TestCase):
        def setUp(self):
            pass

        def test_a_mkThrd(self):
            sthrd = ssh_thread(log, 'localhost', 'sleep 1')
            sthrd.start()
            sthrd.join()
            if sthrd.status != OK:
                raise FsDriftException('return status %d' % sthrd.status)

        def test_b_abortThrd(self):
            sthrd = ssh_thread(log, 'localhost', 'sleep 60')
            sthrd.start()
            time.sleep(1)
            log.debug('subprocess pid is %d' % sthrd.popen_obj.pid)
            sthrd.terminate()
            assert(sthrd.status == NOTOK)

    unittest_module.main()


text:
/**
 * (c) 2014/2015 by Christian Schenk
**/
package de.schenk.jrtrace.enginex.testclasses;

import de.schenk.jrtrace.annotations.XClass;
import de.schenk.jrtrace.annotations.XMethod;

/** to instrument selected eclipse classes that were problematic once */

@XClass(classes = { "org\\.eclipse\\.jdt\\.ui\\.text\\.JavaSourceViewerConfiguration" }, regex = true)
public class ProblemCaseJavaSourceViewerconfiguration {

	@XMethod(names = ".*")
	public void doit() {

	}
}


text:
define([
    'jquery'
], function($){
    /**
     * @constructor
     * @param params
     * @param {Object} params
     * @param {String} params.id
     * @param {Banner.TYPE} params.type
     * @param {HTMLElement|jQuery|String} [params.mountNode] Banner will render at this node
     * @param {String} [params.url]
     * @param {String} [params.imageUrl]
     * @param {Number} [params.width]
     * @param {Number} [params.height]
     * @param {String} [params.template]
     * @param {String} [params.target] `_self` or `_blank`
     * @param {Object} [params.linkCss] CSS props hash for jQuery.css
     * @param {Object} [params.closeButtonCss] CSS props hash for jQuery.css
     * @param {Function} [params.onCreate] Called when banner is created
     * @param {Function} [params.onClick] Called when user clicks on banner
     */
    function Banner(params) {
        if (!params.id || !params.type)
            throw new Error('Banner `id` and `type` sould be provided');

        if (!(params.type in Banner.TYPE))
            throw new Error('Unsupported banner type `'+ params.type +'`');

        var mountNode = ('mountNode' in params) ? params.mountNode : Banner.defaults[params.type].mountNode;
        if (!mountNode) throw new Error('You must provide mount node for `' + params.id + '` banner');
        mountNode = (typeof mountNode === 'string') ? document.getElementById(mountNode) : mountNode;
        if (!mountNode) throw new Error('Mount node for `' + params.id + '` doesnt exist');
        this.mountNode = mountNode;

        this.id = params.id;
        this.type = params.type;
        this.url = 'url' in params ? params.url : null;
        this.imageUrl = 'imageUrl' in params ? params.imageUrl : null;
        this.width = 'width' in params ? params.width : Banner.defaults[params.type].width;
        this.height = 'height' in params ? params.height : Banner.defaults[params.type].height;
        this.template = 'template' in params ? params.template : null;
        this.target = 'target' in params ? params.target : '_self';
        this.linkCss = 'linkCss' in params ? params.linkCss : null;
        this.closeButtonCss = 'closeButtonCss' in params ? params.closeButtonCss : null;

        this.onCreate = ('onCreate' in params && typeof params.onCreate === 'function') ? params.onCreate : null;
        this.onClick = ('onClick' in params && typeof params.onClick === 'function') ? params.onClick : null;
    }

    /**
     * @const
     */
    Banner.TYPE = {
        slideup: 'slideup',
        inplace: 'inplace'
    };

    /**
     * @const
     */
    Banner.defaults = {
        slideup: {
            width: 622,
            height: 90,
            mountNode: $('body')
        },
        inplace: {
            width: 'auto',
            height: 'auto',
            mountNode: null
        }
    };

    /**
     * @static
     */
    Banner.getCookieNameFor = function (id) {
        return 'banner_' + id;
    };

    /**
     * @type {Array<jQuery>}
     */
    Banner.prototype.nodes = null;

    /**
     * @return {Array<jQuery>}
     */
    Banner.prototype._createNodes = function () {
        var banner = this,
            nodes;

        var nodesClasses = {
            container: [
                'jb-promotion',
                'jb-' + banner.type + '-promotion',
                'id_' + banner.id,
                banner.type === Banner.TYPE.slideup ? 'is_hidden' : ''
            ],
            body: [
                'jb-promotion__body',
                'jb-' + banner.type + '-promotion__body'
            ],
            closeButton: [
                'jb-promotion__close-button',
                'jb-' + banner.type + '-promotion__close-button'
            ],
            link: [
                'jb-promotion__link',
                'jb-' + banner.type + '-promotion__link'
            ]
        };

        nodes = {
            container: $('

'),
            body: $('

'),
            link: banner.url ? $('') : '',
            closeButton: $('

')
        };

        nodes.body.css({
            width: banner.width,
            height: banner.height,
            backgroundImage: banner.imageUrl ? 'url("'+ banner.imageUrl +'")' : 'none'
        });

        if (banner.url && banner.linkCss) nodes.link.css(banner.linkCss);
        if (banner.closeButtonCss) nodes.closeButton.css(banner.closeButtonCss);
        if (banner.template) nodes.body.html(banner.template);

        return nodes;
    };

    Banner.prototype.render = function () {
        var banner = this,
            mountNode = this.mountNode,
            nodes;

        nodes = this.nodes = this._createNodes();

        nodes.body
            .append(nodes.link)
            .append(nodes.closeButton);

        nodes.container
            .append(nodes.body)
            .appendTo(mountNode);

        nodes.closeButton.on('click', banner.closeHandler.bind(banner));
        if (banner.url) {
            nodes.link.on('click', function () {
                if (banner.onClick) banner.onClick.call(banner);
                banner.closeHandler.call(banner);
            });
        }

        if (banner.type === Banner.TYPE.slideup)
            setTimeout(banner.show.bind(banner), 300);

        if (banner.onCreate) banner.onCreate.call(banner);
    };

    Banner.prototype.closeHandler = function () {
        var cookieName = this.getCookieName();
        setCookie(cookieName, '0', 365, '/');
        this.hide();
    };

    Banner.prototype.show = function () {
        this.nodes.container.removeClass('is_hidden');
    };

    Banner.prototype.hide = function () {
        this.nodes.container.addClass('is_hidden');
    };

    Banner.prototype.getCookieName = function () {
        return Banner.getCookieNameFor(this.id);
    };

    Banner.prototype.destroy = function () {
        var banner = this,
            nodes = this.nodes;

        nodes.closeButton.off('click', banner.closeHandler);
        if (banner.url && banner.onClick) nodes.link.off('click', banner.onClick);
        nodes.container.remove();
    };

    function setCookie(name, value, lifespan, access_path) {
        var cookietext = name + "=" + escape(value);
        if (lifespan != null) {
            var today = new Date();
            var expiredate = new Date();
            expiredate.setTime(today.getTime() + 1000 * 60 * 60 * 24 * lifespan);
            cookietext += "; expires=" + expiredate.toGMTString();
        }
        if (access_path != null) {
            cookietext += "; PATH=" + access_path;
        }
        document.cookie = cookietext;
        return null;
    }

    function getCookie(Name) {
        var search = Name + "=";
        var CookieString = document.cookie;
        var result = null;
        if (CookieString.length > 0) {
            offset = CookieString.indexOf(search);
            if (offset != -1) {
                offset += search.length;
                end = CookieString.indexOf(";", offset);
                if (end == -1) {
                    end = CookieString.length;
                }
                result = unescape(CookieString.substring(offset, end));
            }
        }
        return result;
    }

    var bannersRotator = {};

    bannersRotator.instances = [];

    bannersRotator.createBanner = function (params) {
        if (this.isBannerShouldBeShown(params.id)) {
            try {
                var banner = new Banner(params);
                banner.render();
                this.instances.push(banner);
            } catch (e) {
            }
        }
    };

    bannersRotator.isBannerShouldBeShown = function (id) {
        var cookieName = Banner.getCookieNameFor(id);
        var cookieValue = getCookie(cookieName);
        return cookieValue === null || cookieValue !== '0';
    };

    window.bannersRotator = bannersRotator;
    window.bannersRotator.Banner = Banner;

    return bannersRotator
});


text:
author: slowe
comments: true
date: 2007-12-05 23:04:10+00:00
layout: post
slug: managing-lun-space-requirements-with-netapp-storage
title: Managing LUN Space Requirements with NetApp Storage
wordpress_id: 589
categories: Explanation
tags:
- NetApp
- ONTAP
- SAN
- Snapshot
- Snapshots
- Storage
---

If you've worked with Network Appliance storage before, you're probably already familiar with the idea of snap reserve (storage space set aside to accommodate for Snapshots) and fractional reserve (used with LUNs). I'm going to hold the in-depth discussion of why you need snap reserve and fractional reserve for a different day, but I did want to pass on these commands that were shared with me by a colleague of mine. These Data ONTAP commands, available with Data ONTAP 7.2 or later (some commands are available in Data ONTAP 7.1), will help you manage the space requirements for LUNs on a NetApp storage area network (SAN).

I'll try to explain the commands along the way, but I would recommend you review the documentation available from the NOW site for more complete information.

	vol options <volname> fractional_reserve 0

This command sets the fractional reserve to zero percent, down from the default of 100 percent. Note that fractional reserve only applies to LUNs, not to NAS storage presented via CIFS or NFS.

	snap autodelete <volname> trigger snap_reserve

This sets the trigger at which Data ONTAP will begin deleting Snapshots. In this case, Snapshots will start getting deleted when the snap reserve for the volume gets nearly full. The current size of the snap reserve can be viewed for a particular volume with the `snap reserve <volname>` command.

	snap autodelete <volname> defer_delete none

This command instructs Data ONTAP not to exhibit any preference in the types of Snapshots that are deleted. Options for this command include "user_created" (delete user-created Snapshot copies last) or "prefix" (Snapshot copies with a specified prefix string).

	snap autodelete <volname> target_free_space 10

With this setting in place, Snapshots will be deleted until there is 10% free space in the volume.

	snap autodelete <volname> on

Now that the Snapshot autodelete options have been configured, this command will actually turn the functionality on.

	vol options <volname> try_first snap_delete

When a FlexVol runs into an issue with space, this option tells Data ONTAP to first try to delete Snapshots in order to free up space. This command works in conjunction with the next command:

	vol autosize <volname> on

This enables Data ONTAP to automatically grow the size of a FlexVol if the need arises. This command works hand-in-hand with the previous command; Data ONTAP will first try to delete Snapshots to free up space, then grow the FlexVol according to the autosize configuration options. Between these two options---Snapshot autodelete and volume autogrow---you can reduce the fractional reserve from the default of 100 and still make sure that you don't run into problems taking Snapshots of your LUNs.

If you have a NOW login, you can get more information on Snapshot autodelete [here](http://now.netapp.com/NOW/knowledge/docs/ontap/rel723/html/ontap/onlinebk/2snap15.htm); more information on volume autogrow is available [here](http://now.netapp.com/NOW/knowledge/docs/ontap/rel723/html/ontap/mgmtsag/6vol10.htm). Be aware that SnapDrive may require different settings in order to accommodate its functionality, as it moves LUN management out of the storage system and onto the host. Finally, the values presented here are only examples; be sure to use values that are appropriate for your environment.

Credit for compiling this list goes to my colleague Chauncey Willard. Good work!


text:
<?xml version = "1.0" encoding = "UTF-8"?>
<record xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.ddb.de/professionell/mabxml/mabxml-1.xsd">

	$if(record.leader)$<leader>$record.leader$</leader>$endif$

	$if(record.LDR)$<controlfield tag="LDR">$record.LDR$</controlfield>$endif$

	$if(record.FMT)$<controlfield tag="FMT">$record.FMT$</controlfield>$endif$

	$if(record.id)$<datafield tag="001" ind1="-" ind2="1">
	<subfield code="a">$record.id$</subfield>
</datafield>$endif$

	$if(record.datumDerErsterfassung)$<datafield tag="002" ind1="a" ind2="1">
	<subfield code="a">$record.datumDerErsterfassung$</subfield>
</datafield>$endif$

	$if(record.datumLetzteKorrektur)$<datafield tag="003" ind1="-" ind2="1">
	<subfield code="a">$record.datumLetzteKorrektur$</subfield>
</datafield>$endif$

	$if(record.id)$<datafield tag="026" ind1="-" ind2="1">
	<subfield code="a">HBZ$record.id$</subfield>
</datafield>$endif$

	$if(record.angabenZumDatensatz)$<controlfield tag="030">$record.angabenZumDatensatz$</controlfield>$endif$

	$if(record.laenderCodeDINEN23166)$<datafield tag="036" ind1="a" ind2="1">
	<subfield code="a">$record.laenderCodeDINEN23166$</subfield>
</datafield>$endif$

	$if(record.sprachenCodeDIN2335)$<datafield tag="037" ind1="b" ind2="1">
	<subfield code="a">$record.sprachenCodeDIN2335$</subfield>
</datafield>$endif$

	$if(record.datentraeger)$<controlfield tag="050">$record.datentraeger$</controlfield>$endif$

	$if(record.veroeffentlichungsSpezifischeAngabenString)$<controlfield tag="051">$record.veroeffentlichungsSpezifischeAngabenString$</controlfield>$endif$

	$if(record.identifizierungsmerkmalInstitution)$<datafield tag="070" ind1="-" ind2="1">
	<subfield code="a">$record.identifizierungsmerkmalInstitution$</subfield>
</datafield>$endif$

	$if(record.edowebMarker)$<datafield tag="078" ind1="r" ind2="1">
	<subfield code="a">$record.edowebMarker$</subfield>
</datafield>$endif$

	$if(person1)$<datafield tag="100" ind1="-" ind2="1">
	<subfield code="p">$person1.nameVerweisungsform$</subfield>
	<subfield code="9">$person1.id$</subfield>
</datafield>$endif$

	$if(person2)$<datafield tag="104" ind1="-" ind2="1">
	<subfield code="p">$person2.nameVerweisungsform$</subfield>
	<subfield code="9">$person2.id$</subfield>
</datafield>$endif$

	$if(person3)$<datafield tag="108" ind1="-" ind2="1">
	<subfield code="p">$person3.nameVerweisungsform$</subfield>
	<subfield code="9">$person3.id$</subfield>
</datafield>$endif$

	$if(corporateBody1)$<datafield tag="200" ind1="-" ind2="1">
	<subfield code="p">$corporateBody1.nameVerweisungsform$</subfield>
	<subfield code="9">$corporateBody1.id$</subfield>
</datafield>$endif$

	$if(corporateBody2)$<datafield tag="204" ind1="-" ind2="1">
	<subfield code="p">$corporateBody2.nameVerweisungsform$</subfield>
	<subfield code="9">$corporateBody2.id$</subfield>
</datafield>$endif$

	$if(corporateBody3)$<datafield tag="208" ind1="-" ind2="1">
	<subfield code="p">$corporateBody3.nameVerweisungsform$</subfield>
	<subfield code="9">$corporateBody3.id$</subfield>
</datafield>$endif$

	$if(record.hauptsachtitelAnsetzung)$<datafield tag="310" ind1="-" ind2="1">
	<subfield code="a">$record.hauptsachtitelAnsetzung$</subfield>
</datafield>$endif$

	$if(record.hauptsachtitelVorlage)$<datafield tag="331" ind1="-" ind2="1">
	<subfield code="a">$record.hauptsachtitelVorlage$</subfield>
</datafield>$endif$

	$if(record.allgemeineMaterialbenennung)$<datafield tag="334" ind1="-" ind2="1">
	<subfield code="a">$record.allgemeineMaterialbenennung$</subfield>
</datafield>$endif$

	$if(record.ersterVerlagsort)$<datafield tag="410" ind1="-" ind2="1">
	<subfield code="a">$record.ersterVerlagsort$</subfield>
</datafield>$endif$

	$if(record.erscheinungsjahrAnsetzung)$<datafield tag="425" ind1="-" ind2="1">
	<subfield code="a">$record.erscheinungsjahrAnsetzung$</subfield>
</datafield>$endif$

	$if(record.umfang)$<datafield tag="433" ind1="-" ind2="1">
	<subfield code="a">$record.umfang$</subfield>
</datafield>$endif$

	$if(record.gesamttitelMitZaehlungDerStuecktitel)$<datafield tag="451" ind1="-" ind2="1">
	<subfield code="a">$record.gesamttitelMitZaehlungDerStuecktitel$</subfield>
</datafield>$endif$

	$if(record.idGesamttitel)$<datafield tag="453" ind1="-" ind2="1">
	<subfield code="a">$record.idGesamttitel$</subfield>
</datafield>$endif$

	<datafield tag="652" ind1="a" ind2="1">
		<subfield code="a">Archivierte Online-Ressource</subfield>
	</datafield>

	$if(record.urn)$<datafield tag="552" ind1="b" ind2="1">
	<subfield code="a">$record.urn$</subfield>
</datafield>$endif$

	$if(record.archivierteOnlineResource)$<datafield tag="652" ind1="a" ind2="1">
	<subfield code="a">$record.archivierteOnlineResource$</subfield>
</datafield>$endif$

	$if(record.httpAdresse)$<datafield tag="655" ind1="e" ind2="1">
	<subfield code="u">$record.httpAdresse$</subfield>
	<subfield code="x">kostenfrei</subfield>
	<subfield code="x">Langzeitarchvierung</subfield>
	<subfield code="g">$record.urn$</subfield>
</datafield>$endif$

	$if(record.klassifikationRpb)$<datafield tag="700" ind1="l" ind2="1">
	<subfield code="a">$record.klassifikationRpb$</subfield>
</datafield>$endif$

	$if(record.klassifikationDnb)$<datafield tag="700" ind1="d" ind2="1">
	<subfield code="a">$record.klassifikationDnb$</subfield>
</datafield>$endif$

	$if(record.klassifikationDdc)$<datafield tag="700" ind1="b" ind2="1">
	<subfield code="a">$record.klassifikationDdc$</subfield>
</datafield>$endif$

</record>


text:
import imp
import os
import sys
import unittest

def _GetDirAbove(dirname):
  """Returns the directory "above" this file containing |dirname| (which must
  also be "above" this file)."""
  path = os.path.abspath(__file__)
  while True:
    path, tail = os.path.split(path)
    assert tail
    if tail == dirname:
      return path

try:
  imp.find_module('mojom')
except ImportError:
  sys.path.append(os.path.join(_GetDirAbove('pylib'), 'pylib'))
import mojom.parse.ast as ast
import mojom.parse.conditional_features as conditional_features
import mojom.parse.parser as parser

ENABLED_FEATURES = frozenset({'red', 'green', 'blue'})

class ConditionalFeaturesTest(unittest.TestCase):
  """Tests |mojom.parse.conditional_features|."""

  def parseAndAssertEqual(self, source, expected_source):
    definition = parser.Parse(source, "my_file.mojom")
    conditional_features.RemoveDisabledDefinitions(definition, ENABLED_FEATURES)
    expected = parser.Parse(expected_source, "my_file.mojom")
    self.assertEquals(definition, expected)

  def testFilterConst(self):
    """Test that Consts are correctly filtered."""
    const_source = """
      [EnableIf=blue]
      const int kMyConst1 = 1;
      [EnableIf=orange]
      const double kMyConst2 = 2;
      const int kMyConst3 = 3;
    """
    expected_source = """
      [EnableIf=blue]
      const int kMyConst1 = 1;
      const int kMyConst3 = 3;
    """
    self.parseAndAssertEqual(const_source, expected_source)

  def testFilterEnum(self):
    """Test that EnumValues are correctly filtered from an Enum."""
    enum_source = """
      enum MyEnum {
        [EnableIf=purple]
        VALUE1,
        [EnableIf=blue]
        VALUE2,
        VALUE3,
      };
    """
    expected_source = """
      enum MyEnum {
        [EnableIf=blue]
        VALUE2,
        VALUE3
      };
    """
    self.parseAndAssertEqual(enum_source, expected_source)

  def testFilterImport(self):
    """Test that imports are correctly filtered from a Mojom."""
    import_source = """
      [EnableIf=blue]
      import "foo.mojom";
      import "bar.mojom";
      [EnableIf=purple]
      import "baz.mojom";
    """
    expected_source = """
      [EnableIf=blue]
      import "foo.mojom";
      import "bar.mojom";
    """
    self.parseAndAssertEqual(import_source, expected_source)

  def testFilterInterface(self):
    """Test that definitions are correctly filtered from an Interface."""
    interface_source = """
      interface MyInterface {
        [EnableIf=blue]
        enum MyEnum {
          [EnableIf=purple]
          VALUE1,
          VALUE2,
        };
        [EnableIf=blue]
        const int32 kMyConst = 123;
        [EnableIf=purple]
        MyMethod();
      };
    """
    expected_source = """
      interface MyInterface {
        [EnableIf=blue]
        enum MyEnum {
          VALUE2,
        };
        [EnableIf=blue]
        const int32 kMyConst = 123;
      };
    """
    self.parseAndAssertEqual(interface_source, expected_source)

  def testFilterMethod(self):
    """Test that Parameters are correctly filtered from a Method."""
    method_source = """
      interface MyInterface {
        [EnableIf=blue]
        MyMethod([EnableIf=purple] int32 a) => ([EnableIf=red] int32 b);
      };
    """
    expected_source = """
      interface MyInterface {
        [EnableIf=blue]
        MyMethod() => ([EnableIf=red] int32 b);
      };
    """
    self.parseAndAssertEqual(method_source, expected_source)

  def testFilterStruct(self):
    """Test that definitions are correctly filtered from a Struct."""
    struct_source = """
      struct MyStruct {
        [EnableIf=blue]
        enum MyEnum {
          VALUE1,
          [EnableIf=purple]
          VALUE2,
        };
        [EnableIf=yellow]
        const double kMyConst = 1.23;
        [EnableIf=green]
        int32 a;
        double b;
        [EnableIf=purple]
        int32 c;
        [EnableIf=blue]
        double d;
        int32 e;
        [EnableIf=orange]
        double f;
      };
    """
    expected_source = """
      struct MyStruct {
        [EnableIf=blue]
        enum MyEnum {
          VALUE1,
        };
        [EnableIf=green]
        int32 a;
        double b;
        [EnableIf=blue]
        double d;
        int32 e;
      };
    """
    self.parseAndAssertEqual(struct_source, expected_source)

  def testFilterUnion(self):
    """Test that UnionFields are correctly filtered from a Union."""
    union_source = """
      union MyUnion {
        [EnableIf=yellow]
        int32 a;
        [EnableIf=red]
        bool b;
      };
    """
    expected_source = """
      union MyUnion {
        [EnableIf=red]
        bool b;
      };
    """
    self.parseAndAssertEqual(union_source, expected_source)

  def testSameNameFields(self):
    mojom_source = """
      enum Foo {
        [EnableIf=red]
        VALUE1 = 5,
        [EnableIf=yellow]
        VALUE1 = 6,
      };
      [EnableIf=red]
      const double kMyConst = 1.23;
      [EnableIf=yellow]
      const double kMyConst = 4.56;
    """
    expected_source = """
      enum Foo {
        [EnableIf=red]
        VALUE1 = 5,
      };
      [EnableIf=red]
      const double kMyConst = 1.23;
    """
    self.parseAndAssertEqual(mojom_source, expected_source)

  def testMultipleEnableIfs(self):
    source = """
      enum Foo {
        [EnableIf=red,EnableIf=yellow]
        kBarValue = 5,
      };
    """
    definition = parser.Parse(source, "my_file.mojom")
    self.assertRaises(conditional_features.EnableIfError,
                      conditional_features.RemoveDisabledDefinitions,
                      definition, ENABLED_FEATURES)

if __name__ == '__main__':
  unittest.main()


text:
package io.unravelling.carboncopy.producers;

import io.unravelling.carboncopy.config.CarbonCopyConfiguration.ConnectionConfiguration;
import io.unravelling.carboncopy.factories.connections.KafkaConnectionFactory;

import javax.jms.JMSException;
import javax.jms.Message;

import org.springframework.kafka.core.KafkaTemplate;

/**
 * Producer for Kafka targets.
 *
 * @author Tiago Veiga Lázaro
 * @version 2.4.0
 * @since 2.4.0
 */
public class KafkaProducer extends GenericProducer implements CarbonProducer {

  /**
   * Template used to send messages to Kafka.
   */
  private final KafkaTemplate<String, String> kafkaTemplate;

  /**
   * Constructor of the producer.
   *
   * @param connectionConfiguration Connection configuration to use to build the producer.
   */
  public KafkaProducer(final ConnectionConfiguration connectionConfiguration) {
    super(connectionConfiguration);

    this.kafkaTemplate = KafkaConnectionFactory.getKafkaTemplate(connectionConfiguration);
  }

  /**
   * Sends a message to the target. A string message must be supported.
   *
   * @param message Message to be sent.
   */
  @Override
  public void send(final String message) {
    log.debug("Sending message to topic {}...", getDestinationName());

    this.kafkaTemplate.send(getDestinationName(), message);

    log.debug("Text message sent.");
  }

  /**
   * Sends a message to the target. A JMS format message must be supported.
   *
   * @param message Message to be sent.
   */
  @Override
  public void send(final Message message) {
    log.debug("Sending message to topic {}...", getDestinationName());

    try {
      this.kafkaTemplate.send(getDestinationName(), message.getBody(String.class));
      message.acknowledge();
    } catch (JMSException jmsException) {
      log.error("Error while opening the JMS message.", jmsException);
    }

    log.debug("Original JMS message sent to Kafka and confirmed in JMS.");
  }

  /**
   * Closes the pending resources, such as connections.
   */
  @Override
  public void close() {
    // do nothing
  }
}


text:
/**
 * Represents the application api.  If the variable is already defined use it,
 * otherwise create an empty object.
 *
 * @type {EScreeningDashboardApp|*|EScreeningDashboardApp|*|{}|{}}
 */
var EScreeningDashboardApp = EScreeningDashboardApp || {};
/**
 * Represents the application static variable. Use existing static variable, if one already exists,
 * otherwise create a new one.
 *
 * @static
 * @type {*|EScreeningDashboardApp.models|*|EScreeningDashboardApp.models|Object|*|Object|*}
 */
EScreeningDashboardApp.models = EScreeningDashboardApp.models || EScreeningDashboardApp.namespace("gov.va.escreening.models");
/**
 * Represents the application static variable. Use existing static variable, if one already exists,
 * otherwise create a new one.
 *
 * @static
 * @type {*|EScreeningDashboardApp.models.QuestionTransformer|*|EScreeningDashboardApp.models.QuestionTransformer|Object|*|Object|*}
 */
EScreeningDashboardApp.models.QuestionTransformer =  EScreeningDashboardApp.namespace("gov.va.escreening.models.QuestionTransformer");
/**
 * Static method for the QuestionTransformer class that is responsible for transforming the JSON Representation of the
 * Question domain model object.
 *
 * @static
 * @method
 * @param {String}  jsonResponse  Represents the JSON response of a service call request.
 * @returns {EScreeningDashboardApp.models.Question} An existing Question domain model that have been returned from a service call request.
 *
 * @author Bryan Henderson
 */
EScreeningDashboardApp.models.QuestionTransformer.transformJSONPayload = function (jsonResponse) {
    'use strict';
    /**
     * Represent the existing Question.
     *
     * @private
     * @field
     * @type {EScreeningDashboardApp.models.Question}
     */
    var existingQuestion = null;

    if (!Object.isDefined(jsonResponse)) {
        throw new BytePushers.exceptions.InvalidParameterException("jsonResponse can not be null or undefined.");
    }

    if (!Object.isDefined(jsonResponse.question)) {
        throw new BytePushers.exceptions.InvalidParameterException("jsonResponse.question can not be null or undefined.");
    }

    existingQuestion = EScreeningDashboardApp.models.QuestionTransformer.transformJSONQuestion(jsonResponse.question);

    return existingQuestion;
};
/**
 * Static method for the QuestionTransformer class that is responsible for transforming the JSON Representation of the
 * Question domain model object.
 *
 * @static
 * @method
 * @param {String}  jsonQuestion  Represents the JSON representation of question returned from the service call request.
 * @returns {EScreeningDashboardApp.models.Question} An existing Question domain model that have been returned from a service call request.
 *
 * @author Bryan Henderson
 */
EScreeningDashboardApp.models.QuestionTransformer.transformJSONQuestion = function (jsonQuestion) {
    'use strict';
    /**
     * Represent the existing question.
     *
     * @private
     * @field
     * @type {EScreeningDashboardApp.models.Question}
     */
    var existingQuestion;

    if (!Object.isDefined(jsonQuestion)) {
        throw new BytePushers.exceptions.InvalidParameterException("jsonQuestion can not be null or undefined.");
    }

    existingQuestion = new EScreeningDashboardApp.models.Question(jsonQuestion);

    return existingQuestion;
};


text:
Flashcards app for INFSCI 1025 group project.

## Screenshots
![Add card](screenshots/add-card.png)
Add a new card

![Review card](screenshots/review-card.png)
"Learn" a card

![Review card score](screenshots/review-card-score.png)
Score your performance


text:
package es.ujaen.rlc00008.gnbwallet.ui.base;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import javax.inject.Inject;

import butterknife.ButterKnife;
import es.ujaen.rlc00008.gnbwallet.MyLog;
import es.ujaen.rlc00008.gnbwallet.R;
import es.ujaen.rlc00008.gnbwallet.domain.interactors.ActivateInteractor;
import es.ujaen.rlc00008.gnbwallet.domain.interactors.ChallengeInteractor;
import es.ujaen.rlc00008.gnbwallet.domain.interactors.DeactivateInteractor;
import es.ujaen.rlc00008.gnbwallet.domain.interactors.GetCVVInteractor;
import es.ujaen.rlc00008.gnbwallet.domain.interactors.GetPinInteractor;
import es.ujaen.rlc00008.gnbwallet.domain.interactors.GetTransactionsInteractor;
import es.ujaen.rlc00008.gnbwallet.domain.interactors.LoggedDataInteractor;
import es.ujaen.rlc00008.gnbwallet.domain.interactors.LoginInteractor;
import es.ujaen.rlc00008.gnbwallet.domain.interactors.LogoutInteractor;
import es.ujaen.rlc00008.gnbwallet.domain.interactors.SetFavoriteInteractor;
import es.ujaen.rlc00008.gnbwallet.domain.interactors.UnsetFavoriteInteractor;
import es.ujaen.rlc00008.gnbwallet.ui.fragments.dialogs.GenericDialogFragment;

/**
 * Created by Ricardo on 22/5/16.
 */
public abstract class BaseFragment extends Fragment implements
		GenericDialogFragment.GenericDialogListener {

	private static final String POPUP_FRAGMENT_TAG = "POPUP_FRAGMENT_TAG";

	@Inject protected Context context;

	@Inject protected LoginInteractor loginInteractor;
	@Inject protected LogoutInteractor logoutInteractor;
	@Inject protected LoggedDataInteractor loggedDataInteractor;
	@Inject protected ChallengeInteractor challengeInteractor;
	@Inject protected ActivateInteractor activateInteractor;
	@Inject protected DeactivateInteractor deactivateInteractor;
	@Inject protected SetFavoriteInteractor setFavoriteInteractor;
	@Inject protected UnsetFavoriteInteractor unsetFavoriteInteractor;
	@Inject protected GetPinInteractor getPinInteractor;
	@Inject protected GetCVVInteractor getCVVInteractor;
	@Inject protected GetTransactionsInteractor getTransactionsInteractor;

	protected ProgressDialog progressDialog;

	protected View mainView;

	@Override
	public void onAttach(Context context) {
		this.context = context;
		if (context instanceof BaseActivity) {
			((BaseActivity) this.context).component().inject(this);
		} else {
			throw new RuntimeException("context not instanceof BaseActivity");
		}
		super.onAttach(context);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mainView = inflater.inflate(getContentView(), container, false);

		ButterKnife.bind(this, mainView);

		prepareInterface(mainView);

		return mainView;
	}

	@Override
	public void onPause() {
		super.onPause();
		if (getView() != null) {
			hideKeyBoard(getView().getWindowToken());
		}
	}

	/**
	 * Handle the back button press event
	 *
	 * @return - true if the event is consumed by this method - false otherwise
	 */
	public boolean backPressed() {
		return false;
	}

	protected void showKeyBoard(final EditText myEditText) {
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				try {
					myEditText.requestFocus();
					InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.showSoftInput(myEditText, 0);
				} catch (Exception e) {
					MyLog.printStackTrace(e);
				}
			}
		}, 100);
	}

	protected void hideKeyBoard(IBinder windowToken) {
		try {
			InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(windowToken, 0);
		} catch (Exception e) {
			MyLog.printStackTrace(e);
		}
	}

	protected void hideKeyBoard(EditText myEditText) {
		try {
			InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);
		} catch (Exception e) {
			MyLog.printStackTrace(e);
		}
	}

	protected BaseFragment findFragmentById(int containerId) {
		try {
			return (BaseFragment) getChildFragmentManager().findFragmentById(containerId);
		} catch (Exception e) {
			MyLog.printStackTrace(e);
		}
		return null;
	}

	protected void replaceFragment(BaseFragment fragment, int containerId) {
		getChildFragmentManager().
				beginTransaction().
				replace(containerId, fragment)
				.commit();
		getActivity().overridePendingTransition(0, 0);
	}

	protected void replaceFragment(BaseFragment fragment, int containerId, String backStackName) {
		getChildFragmentManager()
				.beginTransaction()
				.addToBackStack(backStackName)
				.replace(containerId, fragment)
				.commit();
		getActivity().overridePendingTransition(0, 0);
	}

	protected void replaceFragment(BaseFragment fragment, int containerId, int enterAnim, int exitAnim) {
		getChildFragmentManager()
				.beginTransaction()
				.replace(containerId, fragment)
				.setCustomAnimations(enterAnim, exitAnim)
				.commit();
	}

	protected void removeFragment(int containerId) {
		try {
			BaseFragment fragment = findFragmentById(containerId);
			if (fragment != null) {
				getChildFragmentManager().beginTransaction()
						.remove(getChildFragmentManager().findFragmentById(containerId)).commit();
			}
		} catch (Exception e) {
			MyLog.printStackTrace(e);
		}
	}

	public void showLoading() {

		progressDialog = new ProgressDialog(getActivity());
		progressDialog.setMessage(getResources().getString(R.string._loading));
		progressDialog.setCancelable(false);
		progressDialog.show();
	}

	public void hideLoading() {

		if (progressDialog != null && progressDialog.isShowing()) {
			progressDialog.dismiss();
		}
	}

	/**
	 * Muestra un DialogFragment - fullScreen
	 */
	public void showPopUpFragment(BaseDialogFragment fragment) {
		try {
			fragment.show(getChildFragmentManager(), POPUP_FRAGMENT_TAG);
		} catch (Exception e) {
			MyLog.printStackTrace(e);
		}
	}

	/**
	 * Shows a DialogFragment - fullScreen with OK icon
	 */
	public void showOkFragment(String message) {
		BaseDialogFragment baseDialogFragment = GenericDialogFragment.newInstance(R.drawable.icn_check, message);
		showPopUpFragment(baseDialogFragment);
	}

	/**
	 * Muestra un DialogFragment - fullScreen with Error icon
	 */
	public void showErrorFragment(String message) {
		BaseDialogFragment baseDialogFragment = GenericDialogFragment.newInstance(R.drawable.icn_cancelled, message);
		showPopUpFragment(baseDialogFragment);
	}

	/**
	 * Oculta el pop-up fragment en la vista superior de la Activity
	 */
	public void hidePopUpFragment() {
		try {
			BaseDialogFragment fragment = (BaseDialogFragment) getChildFragmentManager().findFragmentByTag(POPUP_FRAGMENT_TAG);
			if (fragment != null) {
				fragment.dismiss();
			}
		} catch (Exception e) {
			MyLog.printStackTrace(e);
		}
	}

	/**
	 * Devuelve true si se está visualizando el pop-up fragment en la vista superior de la Activity
	 */
	public boolean isPopUpFragmentShowing() {
		try {
			BaseDialogFragment fragment = (BaseDialogFragment) getChildFragmentManager().findFragmentByTag(POPUP_FRAGMENT_TAG);
			return (fragment != null);
		} catch (Exception e) {
			MyLog.printStackTrace(e);
		}
		return false;
	}

	@Override
	public void genericDialogCancel() {
		hidePopUpFragment();
	}

	@Override
	public void genericDialogLeftClick() {
		hidePopUpFragment();
	}

	@Override
	public void genericDialogRightClick() {
		hidePopUpFragment();
	}

	protected abstract int getContentView();

	protected abstract void prepareInterface(View mainView);
}


text:
.my-datepicker {
    font-family: Arial, Helvetica, sans-serif;
    color: white;
    border: #609 1px solid;
    display: block;
    width: 180px;
    z-index: 1000;
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
    border-radius: 3px;
}

.my-datepicker-container {
    display: inline-block;
    position: relative;
}

.my-datepicker-container input {
    border: 1px solid #609;
    outline: none;
    padding: 3px;
    margin: 0;
}

/* this is a fun ie6 hack to get drop downs to stay behind the popup window.  This should always be just underneath .myDatePicker */
iframe.ie6_blocker {
    position: absolute;
    z-index: 999;
}

.my-datepicker thead th {
    /* dow headings */
    background: url(images/hrow.gif) repeat-x;
    font-weight: bold;
    height: 20px;
    font-size: 11px;
    color: black;
}

.my-datepicker .my-datepicker-buttons {
    text-align: center;
    padding: 2px 0;
    vertical-align: middle;
    background: url(images/hrow.gif) repeat-x;
}

.my-datepicker .my-datepicker-footer {
    /* bottom line */
    background-color: #ddd;
    padding: 3px;
    font-size: 11px;
    text-align: center;
    color: black;
}

.my-datepicker table {
    margin: 0;
    padding: 0;
}

.my-datepicker-header {
    padding: 3px 0;
    background-color: #ddd;
    text-align: center;
}

.my-datepicker-header span {
    font-size: 11px;
    color: black;
    font-weight: bold;
}

.my-datepicker-header select {
    font-size: 11px;
}

.my-datepicker-header a:hover {
    color: white;
}

.my-datepicker-header a {
    width: 18px;
    height: 17px;
    text-decoration: none;
    font-size: 11px;
    color: black !important;
}

.my-datepicker-header a.close {
    float: right;
    display: none;
}

.my-datepicker-header select.month {
    width: 80px;
    margin: 0 1px;
}

.my-datepicker-header select.year {
    width: 50px;
    margin: 0 2px;
}

.my-datepicker-header a.prev {
    float: left;
    background: url(images/prev.gif) center no-repeat transparent;
    margin-left: 3px;
}

.my-datepicker-header a.next {
    float: right;
    background: url(images/next.gif) center no-repeat transparent;
    margin-right: 3px;
}

.my-datepicker-body td {
    /* weekday */
    font-size: 11px;
    width: 18px;
    height: 18px;
    background-color: white;
    text-align: center;
    vertical-align: middle;
}

.my-datepicker-body td.weekend {
    /* weekend */
    background-color: white;
}

.my-datepicker-body td div {
    /* days */
    color: black;
}

.my-datepicker-body td div.other {
    color: #aaa;
}

.my-datepicker-body td.selected div {
    /* selected date */
    color: red;
}

.my-datepicker-body td.selected {
    background-color: white;
}

.my-datepicker-body td.focus {
    /* day under cursor */
    background-color: #90c;
}

.my-datepicker-body td.focus div {
    /* day under cursor */
    color: white;
}

.my-datepicker-body td.today {
    /* current date */
    border: 1px dashed red;
}

.my-datepicker-body td.disabled div {
    color: #454545;
}

.my-datepicker-buttons a {
    color: black;
    vertical-align: middle;
    font-size: 9px;
}

.my-datepicker-select-button {
    position: absolute;
    top: 0;
    right : 0;
    background: #fff url(images/calb.png) no-repeat 1px 1px;
    width: 20px;
    height: 22px;
    margin: 0;
    border: solid #609 1px;
    border-left-style: none;
}


text:
import $ from 'jquery';

function LinkageSelector(options) {
    this.settings = $.extend({}, LinkageSelector.defaults, options);

    if (this.settings.dataUrl) {
        $.getJSON(this.settings.dataUrl, data => this.init(data));
    } else {
        this.init(this.settings.data);
    }
}

LinkageSelector.prototype = {
    constructor: LinkageSelector,

    convertToArrayData: function(data) {
        const keys = this.settings.dataKeys;

        function convertArray(arr) {
            return $.map(arr, name => {
                const item = {};
                item[keys.name] = name;
                item[keys.value] = name;
                return item;
            });
        }

        function convertObject(obj) {
            return $.map(obj, (children, name) => {
                const item = {};
                item[keys.name] = name;
                item[keys.value] = name;
                item[keys.children] = $.isArray(children) ? convertArray(children) : convertObject(children);
                return item;
            });
        }

        return convertObject(data);
    },

    getDepth: function(data) {
        return Math.max.apply(Math, $.map(data, item => 1 + (item[this.settings.dataKeys.children] ? this.getDepth(item[this.settings.dataKeys.children]) : 0)));
    },

    setStyle: function(el, notEmpty) {
        switch (this.settings.emptyStyle) {
            case 'disabled':
                el.disabled = !notEmpty;
                break;
            case 'hidden':
                el.style.display = notEmpty ? 'inline-block' : 'none';
                break;
            default:
        }
    },

    getValue: function() {
        return $.map(this.selects, el => el.value);
    },

    setValue: function(value, silent) {
        this.selects[0].value = value[0];
        this.updateSelect.apply(this, [this.selects[1]].concat(value.slice(1)));
        if (!silent) this.settings.onChange.call(this, this.getValue());
    },

    resetValue: function(silent) {
        this.selects[0].selectedIndex = 0;
        this.updateSelect(this.selects[1]);
        if (!silent) this.settings.onChange.call(this, this.getValue());
    },

    updateSelect: function(el, elValue) {
        const lvl = this.$selects.index(el);
        const parentValue = this.selects[lvl - 1].value;
        const parentSelected = parentValue && (this.settings.placeholder ? !this.selects[lvl - 1].options[0].selected : true);

        this.setStyle(el, parentSelected);
        if (this.settings.required) el.required = parentSelected;

        el.options.length = this.settings.placeholder ? 1 : 0;
        el.selectedIndex = el.options.length - 1;

        if (parentSelected && this.selectOptions[lvl - 1]) {
            const keys = this.settings.dataKeys;

            $.each(this.selectOptions[lvl - 1], (idx, item) => {
                if (item[keys.value] === parentValue) {
                    const children = item[keys.children];

                    this.selectOptions[lvl] = children;

                    $.each(children, (idx, child) => el.options.add(new Option(child[keys.name], child[keys.value])));

                    if (elValue) el.value = elValue;

                    this.setStyle(el, !!children.length);
                    if (this.settings.required) el.required = !!children.length;

                    return false;
                }

                return true;
            });
        }

        if (lvl + 1 < this.selects.length) this.updateSelect.apply(this, [this.selects[lvl + 1]].concat(Array.prototype.slice.call(arguments, 2)));
    },

    init: function(data) {
        this.$container = $(this.settings.container);
        this.container = this.$container[0];
        this.$selects = this.$container.find(this.settings.selector);
        this.selects = this.$selects.get();
        this.data = $.isArray(data) ? data : this.convertToArrayData(data);
        this.selectOptions = [this.data];

        if (!this.selects.length) {
            const frag = document.createDocumentFragment();

            for (let i = 0, depth = this.getDepth(this.data); i < depth; i++) {
                const el = document.createElement('select');
                this.selects.push(el);
                frag.appendChild(el);
            }

            this.$selects = $(this.selects);
            this.settings.onRender.call(this, this.selects);
            this.container.appendChild(frag);
        }

        this.$selects.each((idx, el) => {
            el.options.length = 0;
        });

        if (this.settings.placeholder) {
            const placeholder = this.settings.placeholder;

            this.$selects.each((idx, el) => {
                const parts = (typeof placeholder === 'string' ? placeholder : placeholder[idx]).split('|');
                el.options.add(new Option(parts[0], parts[1], true, true));
                el.options[0].disabled = true;
            });
        }

        const firstSelect = this.selects[0];
        firstSelect.required = this.settings.required;
        $.each(this.data, (idx, item) => {
            firstSelect.options.add(new Option(item[this.settings.dataKeys.name], item[this.settings.dataKeys.value]));
        });

        this.$selects.slice(0, this.selects.length - 1).each((idx, el) => {
            $(el).on('change', () => this.updateSelect(this.selects[idx + 1]));
        });

        this.$selects.on('change', () => this.settings.onChange.call(this, this.getValue()));

        if (this.settings.defaultValue) {
            this.setValue(this.settings.defaultValue, true);
        } else {
            this.$selects.slice(1).each((idx, el) => this.setStyle(el, false));
        }
    }
};

LinkageSelector.defaults = {
    data: {},
    dataUrl: null,
    container: document.body,
    selector: 'select',
    placeholder: '请选择',
    defaultValue: null,
    dataKeys: { name: 'name', value: 'code', children: 'childs' },
    required: true,
    emptyStyle: 'disabled',
    onRender: function() {},
    onChange: function() {}
};

$.fn.linkageSelector = function(options, param) {
    if (typeof options === 'string') {
        return $.data(this[0], 'LinkageSelector')[options](param);
    } else {
        return this.each(function() {
            $.data(this, 'LinkageSelector', new LinkageSelector($.extend({ container: this }, options)));
        });
    }
};

$.fn.linkageSelector.defaults = LinkageSelector.defaults;

export default LinkageSelector;


text:
package gov.nih.nci.cagrid.metadata.xmi;

import gov.nih.nci.cagrid.metadata.MetadataUtils;
import gov.nih.nci.cagrid.metadata.dataservice.DomainModel;
import gov.nih.nci.cagrid.testing.system.haste.Step;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 *  Sdk40XmiToModelStep
 *  TODO:DOCUMENT ME
 *
 * @author David Ervin
 *
 * @created Apr 4, 2008 12:31:53 PM
 * @version $Id: GenericXmiToModelStep.java,v 1.1 2008-04-04 16:54:32 dervin Exp $
 */
public class GenericXmiToModelStep extends Step {

    private String xmiInputFile;
    private String domainModelOutputFile;
    private XmiFileType xmiType;
    private String projectName;
    private String projectVersion;

    public GenericXmiToModelStep(String xmiInputFile, String domainModelOutputFile, XmiFileType xmiType,
        String projectName, String projectVersion) {
        this.xmiInputFile = xmiInputFile;
        this.domainModelOutputFile = domainModelOutputFile;
        this.xmiType = xmiType;
        this.projectName = projectName;
        this.projectVersion = projectVersion;
    }

    public void runStep() throws Throwable {
        File xmiFile = new File(xmiInputFile);
        assertTrue("Source XMI file did not exist", xmiFile.exists());
        XMIParser parser = new XMIParser(projectName, projectVersion);
        DomainModel model = null;
        try {
            model = parser.parse(xmiFile, xmiType);
        } catch (Exception ex) {
            ex.printStackTrace();
            fail("Error parsing XMI to Domain Model: " + ex.getMessage());
        }
        try {
            FileWriter writer = new FileWriter(domainModelOutputFile);
            MetadataUtils.serializeDomainModel(model, writer);
            writer.flush();
            writer.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            fail("Error writing Domain Model to disk: " + ex.getMessage());
        } catch (Exception ex) {
            ex.printStackTrace();
            fail("Error serializing domain model: " + ex.getMessage());
        }
    }
}


text:
require "rails_helper"

describe "Revisions" do
  feature "creating a revision" do
    before(:each) do
      user = FactoryGirl.create(:user)
      sign_in(user)
      @innovation = FactoryGirl.create(:innovation, user: user)
      TagSet.create(title: "FirstToDisclose")
      @title = @innovation.title
      @abstract = @innovation.abstract
      @body = @innovation.body
      @consented = @innovation.consented
      @user = @innovation.user
    end

    it "should maintain the innovation's attributes when updating" do
      visit edit_innovation_path(@innovation)

      fill_in "Title", with: "A New Title!"
      fill_in "Abstract", with: "A new abstract for this innovation" * 10
      fill_in "Body", with: "A new body for this innovation" * 20
      check "innovation_consented"
      click_on "Update Innovation"

      revision = @innovation.revisions.first

      expect(revision.title).to eq(@title)
      expect(revision.abstract).to eq(@abstract)
      expect(revision.body).to eq(@body)
      expect(revision.consented).to eq(@consented)
      expect(revision.user).to eq(@user)
      expect(@innovation.revisions.count).to eq(1)
    end
  end

  feature "viewing revisions" do
    before(:each) do
      @innovation = FactoryGirl.create(:innovation)
      @revision_1 = FactoryGirl.create(:revision, innovation: @innovation, created_at: Time.now + 1)
      @revision_2 = FactoryGirl.create(:revision, innovation: @innovation, created_at: Time.now + 2, title: "Even newer title for this innovation")
    end

    it "should display all revisions for an innovation" do
      visit innovation_path(@innovation)

      click_on "View Revision History"

      expect(page).to have_link @innovation.title
      expect(page).to have_link "#{@revision_1.title}"
      expect(page).to have_link "#{@revision_2.title}"
    end

    it "should display an individual revision" do
      visit revisions_path({ innovation_id: @innovation.id })

      click_on "#{@revision_1.title}"

      expect(page).to have_link @innovation.title
      expect(page).to have_content @revision_1.title
      expect(page).to have_content @revision_1.abstract
      expect(page).to have_content @revision_1.body
      expect(page).to have_content @revision_1.created_at
    end
  end
end