text:
import localforage from 'localforage';

class CachedCollectionManager {
	constructor() {
		this.items = [];
		this._syncEnabled = false;
		this.loginCb = [];
		this.logged = false;

		const _unstoreLoginToken = Accounts._unstoreLoginToken;
		Accounts._unstoreLoginToken = (...args) => {
			_unstoreLoginToken.apply(Accounts, args);
			this.clearAllCacheOnLogout();
		};

		Tracker.autorun(() => {
			if (Meteor.userId() !== null) {
				if (this.logged === false) {
					for (const cb of this.loginCb) {
						cb();
					}
				}
			}

			this.logged = Meteor.userId() !== null;
		});
	}

	register(cachedCollection) {
		this.items.push(cachedCollection);
	}

	clearAllCache() {
		for (const item of this.items) {
			item.clearCache();
		}
	}

	clearAllCacheOnLogout() {
		for (const item of this.items) {
			item.clearCacheOnLogout();
		}
	}

	countQueries() {
		for (const item of this.items) {
			item.countQueries();
		}
	}

	set syncEnabled(value) {
		check(value, Boolean);
		this._syncEnabled = value;
	}

	get syncEnabled() {
		return this._syncEnabled;
	}

	onLogin(cb) {
		this.loginCb.push(cb);
		if (this.logged) {
			cb();
		}
	}
}

TAGT.CachedCollectionManager = new CachedCollectionManager;

class CachedCollection {
	constructor({
		collection,
		name,
		methodName,
		syncMethodName,
		eventName,
		eventType = 'onUser',
		initOnLogin = false,
		useSync = true,
		useCache = true,
		debug = true,
		version = 1,
		maxCacheTime = 60*60*24*30
	}) {
		this.collection = collection || new Meteor.Collection(null);

		this.ready = new ReactiveVar(false);
		this.name = name;
		this.methodName = methodName || `${name}/get`;
		this.syncMethodName = syncMethodName || `${name}/sync`;
		this.eventName = eventName || `${name}-changed`;
		this.eventType = eventType;
		this.useSync = useSync;
		this.useCache = useCache;
		this.debug = debug;
		this.version = version;
		this.initOnLogin = initOnLogin;
		this.updatedAt = new Date(0);
		this.maxCacheTime = maxCacheTime;

		TAGT.CachedCollectionManager.register(this);

		if (initOnLogin === true) {
			TAGT.CachedCollectionManager.onLogin(() => {
				this.log('Init on login');
				this.ready.set(false);
				this.updatedAt = new Date(0);
				this.initiated = false;
				this.init();
			});
		}
	}

	log(...args) {
		if (this.debug === true) {
			console.log(`CachedCollection ${this.name} =>`, ...args);
		}
	}

	countQueries() {
		this.log(`${Object.keys(this.collection._collection.queries).length} queries`);
	}

	recomputeCollectionQueries() {
		this.log(`recomputing ${Object.keys(this.collection._collection.queries).length} queries`);
		_.each(this.collection._collection.queries, (query) => {
			this.collection._collection._recomputeResults(query);
		});
	}

	loadFromCache(callback = () => {}) {
		if (this.useCache === false) {
			return callback(false);
		}

		localforage.getItem(this.name, (error, data) => {
			if (data && data.version < this.version) {
				this.clearCache();
				callback(false);
				return;
			}

			const now = new Date();
			if (data && now - data.updatedAt >= 1000*this.maxCacheTime) {
				this.clearCache();
				callback(false);
				return;
			}

			if (data && data.records && data.records.length > 0) {
				this.log(`${data.records.length} records loaded from cache`);
				data.records.forEach((record) => {
					record.__cache__ = true;
					this.collection.upsert({ _id: record._id }, _.omit(record, '_id'));

					if (record._updatedAt) {
						const _updatedAt = new Date(record._updatedAt);
						if (_updatedAt > this.updatedAt) {
							this.updatedAt = _updatedAt;
						}
					}
				});

				callback(true);
			} else {
				callback(false);
			}
		});
	}

	loadFromServer(callback = () => {}) {
		Meteor.call(this.methodName, (error, data) => {
			this.log(`${data.length} records loaded from server`);
			data.forEach((record) => {
				this.collection.upsert({ _id: record._id }, _.omit(record, '_id'));

				if (record._updatedAt && record._updatedAt > this.updatedAt) {
					this.updatedAt = record._updatedAt;
				}
			});
			this.recomputeCollectionQueries();

			if (this.updatedAt < new Date) {
				this.updatedAt = new Date;
			}

			callback(data);
		});
	}

	loadFromServerAndPopulate() {
		this.loadFromServer((loadedData) => {
			this.ready.set(true);
			this.saveCache(loadedData);
		});
	}

	sync() {
		if (TAGT.CachedCollectionManager.syncEnabled === false || Meteor.connection._outstandingMethodBlocks.length !== 0) {
			return false;
		}

		this.log(`syncing from ${this.updatedAt}`);

		Meteor.call(this.syncMethodName, this.updatedAt, (error, data) => {
			if (data.update && data.update.length > 0) {
				this.log(`${data.update.length} records updated in sync`);

				for (const record of data.update) {
					this.collection.upsert({ _id: record._id }, _.omit(record, '_id'));

					if (record._updatedAt && record._updatedAt > this.updatedAt) {
						this.updatedAt = record._updatedAt;
					}
				}
			}

			if (data.remove && data.remove.length > 0) {
				this.log(`${data.remove.length} records removed in sync`);

				for (const record of data.remove) {
					this.collection.remove({ _id: record._id });

					if (record._deletedAt && record._deletedAt > this.updatedAt) {
						this.updatedAt = record._deletedAt;
					}
				}
			}

			this.saveCache();
		});

		return true;
	}

	saveCache(data) {
		this.log('saving cache');
		if (!data) {
			data = this.collection.find().fetch();
		}

		localforage.setItem(this.name, {
			updatedAt: new Date,
			version: this.version,
			records: data
		});
		this.log('saving cache (done)');
	}

	clearCacheOnLogout() {
		if (this.initOnLogin === true) {
			this.clearCache();
		}
	}

	clearCache() {
		this.log('clearing cache');
		localforage.removeItem(this.name);
		this.collection.remove({});
	}

	setupListener(eventType, eventName) {
		TAGT.Notifications[eventType || this.eventType](eventName || this.eventName, (t, record) => {
			this.log('record received', t, record);
			if (t === 'remove') {
				this.collection.remove(record._id);
			} else {
				this.collection.upsert({ _id: record._id }, _.omit(record, '_id'));
			}

			this.saveCache();
		});
	}

	trySync() {
		// Wait for an empty queue to load data again and sync
		const interval = Meteor.setInterval(() => {
			if (this.sync()) {
				Meteor.clearInterval(interval);
			}
		}, 200);
	}

	init() {
		if (this.initiated === true) {
			return;
		}

		this.initiated = true;
		this.loadFromCache((cacheLoaded) => {
			this.ready.set(cacheLoaded);

			if (cacheLoaded === false) {
				// If there is no cache load data immediately
				this.loadFromServerAndPopulate();
			} else if (this.useSync === true) {
				this.trySync();
			}

			if (this.useSync === true) {
				let connectionWasOnline = true;
				Tracker.autorun(() => {
					const connected = Meteor.connection.status().connected;

					if (connected === true && connectionWasOnline === false) {
						this.trySync();
					}

					connectionWasOnline = connected;
				});
			}

			this.setupListener();
		});
	}
}

TAGT.CachedCollection = CachedCollection;


text:
package org.splash.messaging;

/**
 *
 * Represents a logical grouping for a set of inbound or outbound links
 * for exchanging of messages.
 *
 *
Exceptions

 *

 *
NetworkException : Thrown when the underlying network connection fails.

 *
MessagingException : Thrown when the Session gets to an erroneous state.

 *

 */
public interface Session extends ContextAware
{
    /**
     * If used with
     * {@link Session#disposition(Message, MessageDisposition, int...)} or
     * {@link Session#settle(Message, int...)} it will apply the 'action' to all
     * messages received up to the given message.
     */
    static final int CUMULATIVE = 0x01;

    static final int SETTLE = 0x02;
    /**
     * Establishes a logical Outbound Link with the remote peer for
     * sending messages to the specified destination identified by the address.
     *
     * @param address
     *            The address is an arbitrary string identifying a logical
     *            "destination" within the remote peer, which is capable of
     *            receiving the messages.
     * @param mode
     *            The OutboundLinkMode specifies the level of reliability
     *            expected by the application when sending messages.
     * @see OutboundLinkMode
     */
    OutboundLink createOutboundLink(String address, OutboundLinkMode mode) throws NetworkException, MessagingException;

    /**
     * Establishes a logical Inbound Link with the remote peer for
     * receiving messages from the specified source identified by the address.
     *
     * @param address
     *            The address is an arbitrary string identifying a logical
     *            "message source" within the remote peer.
     * @param mode
     *            The InboundLinkMode specifies the level of reliability
     *            expected by the application when receiving messages.
     *
     *            * @param creditMode The CreditMode specifies how credit is
     *            replenished.
     * @see InboundLinkMode
     */
    InboundLink createInboundLink(String address, InboundLinkMode mode, CreditMode creditMode) throws NetworkException,
            MessagingException;

    /**
     * Sets the disposition for the given message or all messages received up to
     * the given message, if the {@link Session#CUMULATIVE} flag is used.
     *
     * @param msg
     * @param disposition
     */
    void disposition(Message msg, MessageDisposition disposition, int... flags) throws MessageFormatException, MessagingException,  NetworkException;

    /**
     * Settles the given message or all messages received up to the given
     * message, if the {@link Session#CUMULATIVE} flag is used.
     *
     * @param msg
     * @param disposition
     */
    void settle(Message msg, int... flags) throws MessageFormatException, MessagingException, NetworkException;

    /**
     * Terminates the Session and free any resources associated with this
     * Session. If there are any active Links, it will close them first before
     * closing the Session.
     */
    void close() throws NetworkException;
}

redpajama_set_name: RedPajamaGithub


text:
namespace MediaLogue.Domain.Model
{
    public enum Frequency
    {
        Monday,
        Tuesday,
        Wednesday,
        Thursday,
        Friday,
        Saturday,
        Sunday,
        Daily
    }
}


text:
--------------------------------
-- @function [parent=#EaseExponentialOut] clone
-- @param self
-- @return EaseExponentialOut#EaseExponentialOut ret (return value: cc.EaseExponentialOut)

--------------------------------
-- @function [parent=#EaseExponentialOut] update
-- @param self
-- @param #float float

--------------------------------
-- @function [parent=#EaseExponentialOut] reverse
-- @param self
-- @return ActionEase#ActionEase ret (return value: cc.ActionEase)

return nil


text:
{% extends "base.html" %} {% block content %}

 Student Grade list:

Student Name: {{student.name}}

 Student ID: {{student.university_id}}

    {% for dict in student_grade_column %} {% for key, value in dict.items %}
    {{value}} ({{key}})

    {% endfor %} {% endfor %}

    {% for dict in student_grade_value %} {% for key, value in dict.items %} {% if user.is_instructor %} {% if value != "" %}
    {{value}}

       Edit Grade

  Delete Grade

    {% else %}

       Add Grade

    {% endif %}
    {% else %}
    {{value}}

    {% endif %} {% endfor %} {% endfor %}

{% endblock %}


text:
#include <cstdio>
#include <string>
#include <ros/ros.h>

#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/image_encodings.h>

#include "autoware_msgs/image_obj.h"
#include "autoware_msgs/ConfigPedestrianDpm.h"

#include <libdpm_ttic/dpm_ttic.hpp>

#define XSTR(x) #x
#define STR(x) XSTR(x)

static ros::Publisher image_obj_pub;

#if defined(HAS_GPU)
static DPMTTICGPU *gpu_model;
static bool use_gpu = true;
#endif
static DPMTTIC *ttic_model;

static DPMTTICParam ttic_param;

static std::string object_class;static long int counter;

static std::string image_topic_name;

static void set_default_param(DPMTTICParam& param)
{
	param.overlap = 0.4;
	param.threshold = -0.5;
	param.lambda = 10;
	param.num_cells = 8;counter =0;
}

static void result_to_image_obj_message(autoware_msgs::image_obj& msg, const DPMTTICResult result)
{
	for (int i = 0; i < result.num; ++i) {
		autoware_msgs::image_rect rect;

		int base = i * 4;
		rect.x = result.corner_points[base];
		rect.y = result.corner_points[base+1];
		rect.width = result.corner_points[base+2];
		rect.height = result.corner_points[base+3];
		rect.score = result.score[i];

		msg.obj.push_back(rect);
	}
}

static void image_raw_cb(const sensor_msgs::Image& image_source)
{

	cv_bridge::CvImagePtr cv_image = cv_bridge::toCvCopy(image_source, sensor_msgs::image_encodings::BGR8);
	IplImage img = cv_image->image;
	IplImage *img_ptr = &img;

	autoware_msgs::image_obj msg;
	msg.header = image_source.header;
	msg.type = object_class;

#if defined(HAS_GPU)
	if (use_gpu) {
		DPMTTICResult result = gpu_model->detect_objects(img_ptr, ttic_param);
		result_to_image_obj_message(msg, result);
	} else {
#endif
		DPMTTICResult result = ttic_model->detect_objects(img_ptr, ttic_param);
		result_to_image_obj_message(msg, result);
#if defined(HAS_GPU)
	}
#endif

	image_obj_pub.publish(msg);
	counter++;
}

static void config_cb(const autoware_msgs::ConfigPedestrianDpm::ConstPtr& param)
{
	ttic_param.threshold = param->score_threshold;
	ttic_param.overlap   = param->group_threshold;
	ttic_param.lambda    = param->Lambda;
	ttic_param.num_cells = param->num_cells;
}

#if defined(HAS_GPU)
static std::string get_cubin_path(const ros::NodeHandle& n, const char *default_path)
{
	std::string path;
	if (n.hasParam("/car_detector/cubin")) {
		n.getParam("/car_detector/cubin", path);
	} else {
		path = std::string(default_path);
	}

	return path;
}
#endif

int main(int argc, char* argv[])
{
	ros::init(argc, argv, "dpm_ttic");

	ros::NodeHandle n;
	ros::NodeHandle private_nh("~");

	if (!private_nh.getParam("image_raw_topic", image_topic_name)) {
		image_topic_name = "/image_raw";
	}

	if (!private_nh.getParam("detection_class_name", object_class)) {
		object_class = "car";
	}

	std::string comp_csv_path;
	if (!private_nh.getParam("comp_model_path", comp_csv_path)) {
		comp_csv_path = STR(MODEL_DIR) "car_comp.csv";
	}

	std::string root_csv_path;
	if (!private_nh.getParam("root_model_path", root_csv_path)) {
		root_csv_path = STR(MODEL_DIR) "car_root.csv";
	}

	std::string part_csv_path;
	if (!private_nh.getParam("part_model_path", part_csv_path)) {
		part_csv_path = STR(MODEL_DIR) "car_part.csv";
	}

#if defined(HAS_GPU)
	if (!private_nh.getParam("use_gpu", use_gpu)) {
		use_gpu = false;
	}

	std::string cubin = get_cubin_path(n, STR(DEFAULT_CUBIN));
	if (use_gpu) {
		dpm_ttic_gpu_init_cuda(cubin);
	}
#endif

	set_default_param(ttic_param);

	const char *com_csv  = comp_csv_path.c_str();
	const char *root_csv = root_csv_path.c_str();
	const char *part_csv = part_csv_path.c_str();

#if defined(HAS_GPU)
	if (use_gpu) {
		gpu_model = new DPMTTICGPU(com_csv, root_csv, part_csv);
	} else {
#endif
		ttic_model = new DPMTTIC(com_csv, root_csv, part_csv);
#if defined(HAS_GPU)
	}
#endif

	ros::Subscriber sub = n.subscribe(image_topic_name, 1, image_raw_cb);
	image_obj_pub = n.advertise<autoware_msgs::image_obj>("image_obj", 1);

	ros::Subscriber config_sub;
	std::string config_topic("/config");
	config_topic += ros::this_node::getNamespace() + "/dpm";
	config_sub = n.subscribe(config_topic, 1, config_cb);

	ros::spin();
#if defined(HAS_GPU)
	if (use_gpu) {
		dpm_ttic_gpu_cleanup_cuda();
		delete gpu_model;
	} else {
#endif
		delete ttic_model;
#if defined(HAS_GPU)
	}
#endif

	return 0;
}


text:
package hashtable;

/**
* HashTable/HashTableITF.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from HashTable.idl
* vendredi 4 avril 2014 16 h 11 CEST
*/

public interface HashTableITF extends HashTableITFOperations, org.omg.CORBA.Object, org.omg.CORBA.portable.IDLEntity
{
} // interface HashTableITF


text:
package org.assertj.core.api.abstract_;

import static org.assertj.core.util.Arrays.array;
import static org.mockito.Mockito.verify;

import org.assertj.core.api.AbstractAssert;
import org.assertj.core.api.AbstractAssertBaseTest;
import org.assertj.core.api.ConcreteAssert;
import org.junit.jupiter.api.BeforeAll;

/**
 * Tests for <code>{@link AbstractAssert#isIn(Object...)}</code>.
 *
 * @author Yvonne Wang
 */
class AbstractAssert_isIn_with_array_Test extends AbstractAssertBaseTest {

  private static Object[] values;

  @BeforeAll
  static void setUpOnce() {
    values = array("Yoda", "Luke");
  }

  @Override
  protected ConcreteAssert invoke_api_method() {
    return assertions.isIn(values);
  }

  @Override
  protected void verify_internal_effects() {
    verify(objects).assertIsIn(getInfo(assertions), getActual(assertions), values);
  }
}


text: Animated Icon Set For Arlefreak.com


text:
/**
 * @author Valentin Al. Sitnick
 * @version $Revision: 1.1 $
 *
 */

/* *********************************************************************** */

#include "events.h"
#include "utils.h"
#include "fake.h"

static bool test = false;
static bool util = false;
static bool flag = false;

/* *********************************************************************** */

/**
 * test of function SetThreadLocalStorage
 */
void SetThreadLocalStorage0101()
{
    //Fake method for docletting only
}

/* *********************************************************************** */

JNIEXPORT jint JNICALL Agent_OnLoad(prms_AGENT_ONLOAD)
{
    check_AGENT_ONLOAD;

    Callbacks CB;

    cb_tend;
    cb_tstart;
    cb_death;

    AGENT_FOR_EVENTS_TESTS_PART_I; /* events.h */

    jvmtiEvent events[] = { JVMTI_EVENT_THREAD_START,
        JVMTI_EVENT_THREAD_END, JVMTI_EVENT_VM_DEATH };

    AGENT_FOR_EVENTS_TESTS_PART_II;

    fprintf(stderr, "\n-------------------------------------------------\n");
    fprintf(stderr, "\ntest SetThreadLocalStorage0101 is started\n{\n");
    fflush(stderr);

    return JNI_OK;
}

/* *********************************************************************** */

void JNICALL callbackThreadStart(prms_THRD_START)
{
    check_THRD_START;

    if (flag) return;

    jvmtiPhase phase;
    jvmtiThreadInfo tinfo;
    jvmtiError result;
    unsigned char* data = NULL;

    result = jvmti_env->GetPhase(&phase);

    fprintf(stderr, "\tnative: GetPhase result = %d (must be zero) \n", result);
    fprintf(stderr, "\tnative: current phase is %d (must be 4 (LIVE-phase)) \n", phase);
    if ((result != JVMTI_ERROR_NONE) || (phase != JVMTI_PHASE_LIVE)) return;
    result = jvmti_env->GetThreadInfo(thread, &tinfo);
    fprintf(stderr, "\tnative: GetThreadInfo result = %d (must be zero) \n", result);
    fprintf(stderr, "\tnative: current thread name is %s (must be zero) \n", tinfo.name);

    if (result != JVMTI_ERROR_NONE) return;
    if (strcmp(tinfo.name, "agent")) return;

    fprintf(stderr, "\tnative: test started\n");

    flag = true;

    result = jvmti_env->Allocate(1024, &data);
    if (result != JVMTI_ERROR_NONE) return;

    util = true;

    result = jvmti_env->SetThreadLocalStorage(thread, (void*)data);
    fprintf(stderr, "\tnative: SetThreadLocalStorage result = %d (must be zero) \n",
            result);
    fprintf(stderr, "\tnative: Thread Local Storage ptr (set) is %p (must be NON-zero) \n",
            data);
    if (result != JVMTI_ERROR_NONE) return;
    test = true;
}

void JNICALL callbackThreadEnd(prms_THRD_END)
{
    check_THRD_END;

    jvmtiPhase phase;
    jvmtiThreadInfo tinfo;
    jvmtiError result;
    void* data = NULL;

    result = jvmti_env->GetPhase(&phase);

    fprintf(stderr, "\tnative: GetPhase result = %d (must be zero) \n", result);
    fprintf(stderr, "\tnative: current phase is %d (must be 4 (LIVE-phase)) \n", phase);

    if ((result != JVMTI_ERROR_NONE) || (phase != JVMTI_PHASE_LIVE)) return;

    result = jvmti_env->GetThreadInfo(thread, &tinfo);
    fprintf(stderr, "\tnative: GetThreadInfo result = %d (must be zero) \n", result);
    fprintf(stderr, "\tnative: current thread name is %s (must be zero) \n", tinfo.name);

    if (result != JVMTI_ERROR_NONE) return;

    if (strcmp(tinfo.name, "agent")) return;

    result = jvmti_env->GetThreadLocalStorage(thread, &data);

    fprintf(stderr, "\tnative: GetThreadLocalStorage result = %d (must be zero) \n", result);
    fprintf(stderr, "\tnative: Local Storage ptr (get) is %p (must be non-zero)\n", data);

    if (result != JVMTI_ERROR_NONE) return;

    result = jvmti_env->Deallocate((unsigned char*)data);

    fprintf(stderr, "\tnative: Deallocate result = %d (must be zero) \n", result);

    if (result != JVMTI_ERROR_NONE) return;
}

void JNICALL callbackVMDeath(prms_VMDEATH)
{
    check_VMDEATH;

    fprintf(stderr, "\n\tTest of function SetThreadLocalStorage0101       : ");

    if (test && util)
        fprintf(stderr, " passed \n");
    else
        fprintf(stderr, " failed \n");

    fprintf(stderr, "\n} /* test SetThreadLocalStorage0101 is finished */ \n");
    fflush(stderr);
}

/* *********************************************************************** */


text:
package de.dakror.liturfaliarcest.settings;

import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * @author Dakror
 */
public class Attributes {
	/**
	 * Attributes about speed are expressed as ticks
	 *
	 * @author Dakror
	 */
	public enum Attribute {
		HEALTH(0),
		HEALTH_MAX(0),
		DAMAGE(0),
		STAMINA(0),
		STAMINA_COST(0),
		STAMINA_MAX(0),
		MANA(0),
		MANA_COST(0),
		MANA_MAX(0),
		ATTACK_SPEED(0),
		SPEED(0),

		;

		private float defaultValue;

		private Attribute(float defaultValue) {
			this.defaultValue = defaultValue;
		}

		public float getDefaultValue() {
			return defaultValue;
		}
	}

	HashMap<Attribute, Float> attr = new HashMap<>();

	public Attributes() {
		for (Attribute t : Attribute.values())
			attr.put(t, t.getDefaultValue());
	}

	public Attributes(JSONObject data) throws JSONException {
		this();

		JSONArray names = data.names();
		for (int i = 0; i < data.length(); i++) {
			attr.put(Attribute.valueOf(names.getString(i)), (float) data.getDouble(names.getString(i)));
		}
	}

	public float get(Attribute t) {
		return attr.get(t);
	}

	public Attributes set(Attribute t, float value) {
		attr.put(t, value);
		return this;
	}

	public Attributes add(Attribute t, float value) {
		attr.put(t, get(t) + value);

		return this;
	}

	public void setWithMax(Attribute t, float value) {
		Attribute t2 = Attribute.valueOf(t.name() + "_MAX");
		set(t, value);
		set(t2, value);
	}

	public int size() {
		int s = 0;

		for (Attribute r : attr.keySet())
			if (attr.get(r) != 0) s++;

		return s;
	}

	public JSONObject getData() {
		JSONObject o = new JSONObject();
		try {
			for (Attribute a : Attribute.values())
				o.put(a.name(), get(a));
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return o;
	}

	@Override
	public String toString() {
		return attr.toString();
	}

	@Override
	public Attributes clone() {
		try {
			return new Attributes(getData());
		} catch (JSONException e) {
			e.printStackTrace();
			return null;
		}
	}
}


text:
package com.sjsu.cmpe273Server.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import com.mongodb.DuplicateKeyException;
import com.sjsu.cmpe273Server.dao.OutDoorCameraDao;
import com.sjsu.cmpe273Server.model.OutDoorCamera;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.stereotype.Service;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

@Service
public class OutDoorCameraDaoImpl implements OutDoorCameraDao{
	@Autowired
	private MongoOperations mongoOperation;

	public List<OutDoorCamera> getAll(){
		List<OutDoorCamera> outDoorCamera = new ArrayList<>();
		try{
			outDoorCamera = mongoOperation.findAll(OutDoorCamera.class);
		}catch(Exception e){}
	    return outDoorCamera;
	}

	public Optional<OutDoorCamera> read(String serialNumber){
		Query query = new Query();
		query.addCriteria(Criteria.where("serialNumber").is(serialNumber));
		OutDoorCamera outDoorCamera = mongoOperation.findOne(query, OutDoorCamera.class);

		if(outDoorCamera !=null)
			return Optional.of(outDoorCamera);
		else
			return Optional.empty();
	}

	public boolean delete(String serialNumber){
		Query query = new Query();
		query.addCriteria(Criteria.where("serialNumber").is(serialNumber));
		OutDoorCamera outDoorCamera = mongoOperation.findOne(query, OutDoorCamera.class);
		if(outDoorCamera != null)
		{
			mongoOperation.remove(query, OutDoorCamera.class);
			return true;
		}
		else
			return false;
	}

	public Optional<OutDoorCamera> create(OutDoorCamera outDoorCamera){
		try{
			mongoOperation.save(outDoorCamera);
			return Optional.of(outDoorCamera);
		}
		catch(DuplicateKeyException e)
		{
			return Optional.empty();
		}
	}

	public Optional<OutDoorCamera> update(OutDoorCamera outDoorCamera){
		Query query = new Query();
		query.addCriteria(Criteria.where("serialNumber").is(outDoorCamera.getSerialNumber()));
		OutDoorCamera findOutDoorCamera = mongoOperation.findOne(query, OutDoorCamera.class);
		if(findOutDoorCamera != null)
		{
			Update update = new Update();
			update.set("manufacturer", outDoorCamera.getManufacturer());
			update.set("modelNumber", outDoorCamera.getModelNumber());
			update.set("serialNumber", outDoorCamera.getSerialNumber());
			update.set("firmwareVersion", outDoorCamera.getFirmwareVersion());
			update.set("cameraID", outDoorCamera.getCameraID());
			update.set("enableInfrared", outDoorCamera.getEnableInfrared());
			update.set("motionDetection", outDoorCamera.getMotionDetection());
			update.set("enableRecording", outDoorCamera.getEnableRecording());
			update.set("intrusion", outDoorCamera.getIntrusion());

			mongoOperation.upsert(query, update, OutDoorCamera.class);
			return Optional.of(outDoorCamera);
		}
		else
		{
		    return Optional.empty();
		}

	}
}


text:
CrayonCOMMX-Gulp base is a starter boilerplate based on [HTML5 Boilerplate](https://github.com/h5bp/html5-boilerplate), [gulp](http://gulpjs.com/), [bower](http://bower.io/) and [Boostrap Sass](https://github.com/twbs/bootstrap-sass) (among other components), seeking to foster the rapid development of your proyects.
- Source: [https://github.com/CrayonCOMMX/gulpbase](https://github.com/CrayonCOMMX/gulpbase)
- Twitter: [@izaaksom](https://twitter.com/izaaksom)

## Requirements
Perrequisite |  How to check it | How to install
-------------|------------------|-----------------
Node.js >= 0.12.x|node -v| [nvm](https://github.com/creationix/nvm)
gulp >= 3.8.11|gulp -v|npm install -g gulp
Bower >= 1.4.1|bower -v|npm install -g bower

## Installation
```bash
git clone git@github.com:CrayonCOMMX/gulpbase.git
cd gulpbase
npm install
bower install
gulp
```

### Available tasks


text:
#include "drape_frontend/line_shape.hpp"

#include "drape_frontend/line_shape_helper.hpp"

#include "drape/utils/vertex_decl.hpp"
#include "drape/glsl_types.hpp"
#include "drape/glsl_func.hpp"
#include "drape/shader_def.hpp"
#include "drape/attribute_provider.hpp"
#include "drape/batcher.hpp"
#include "drape/texture_manager.hpp"

#include "base/logging.hpp"

namespace df
{

namespace
{

class TextureCoordGenerator
{
public:
  TextureCoordGenerator(dp::TextureManager::StippleRegion const & region)
    : m_region(region)
    , m_maskLength(static_cast<float>(m_region.GetMaskPixelLength()))
  {}

  glsl::vec4 GetTexCoordsByDistance(float distance) const
  {
    return GetTexCoords(distance / m_maskLength);
  }

  glsl::vec4 GetTexCoords(float offset) const
  {
    m2::RectF const & texRect = m_region.GetTexRect();
    return glsl::vec4(offset, texRect.minX(), texRect.SizeX(), texRect.Center().y);
  }

  float GetMaskLength() const
  {
    return m_maskLength;
  }

  dp::TextureManager::StippleRegion const & GetRegion() const
  {
    return m_region;
  }

private:
  dp::TextureManager::StippleRegion const m_region;
  float const m_maskLength;
};

struct BaseBuilderParams
{
  dp::TextureManager::ColorRegion m_color;
  float m_pxHalfWidth;
  float m_depth;
  dp::LineCap m_cap;
  dp::LineJoin m_join;
};

template <typename TVertex>
class BaseLineBuilder : public ILineShapeInfo
{
public:
  BaseLineBuilder(BaseBuilderParams const & params, size_t geomsSize, size_t joinsSize)
    : m_params(params)
    , m_colorCoord(glsl::ToVec2(params.m_color.GetTexRect().Center()))
  {
    m_geometry.reserve(geomsSize);
    m_joinGeom.reserve(joinsSize);
  }

  void GetTexturingInfo(float const globalLength, int & steps, float & maskSize)
  {
    UNUSED_VALUE(globalLength);
    UNUSED_VALUE(steps);
    UNUSED_VALUE(maskSize);
  }

  dp::BindingInfo const & GetBindingInfo() override
  {
    return TVertex::GetBindingInfo();
  }

  ref_ptr<void> GetLineData() override
  {
    return make_ref(m_geometry.data());
  }

  size_t GetLineSize() override
  {
    return m_geometry.size();
  }

  ref_ptr<void> GetJoinData() override
  {
    return make_ref(m_joinGeom.data());
  }

  size_t GetJoinSize() override
  {
    return m_joinGeom.size();
  }

  float GetHalfWidth()
  {
    return m_params.m_pxHalfWidth;
  }

  dp::BindingInfo const & GetCapBindingInfo() override
  {
    return GetBindingInfo();
  }

  dp::GLState GetCapState() override
  {
    return GetState();
  }

  ref_ptr<void> GetCapData() override
  {
    return ref_ptr<void>();
  }

  size_t GetCapSize() override
  {
    return 0;
  }

  float GetSide(bool isLeft) const
  {
    return isLeft ? 1.0 : -1.0;
  }

protected:
  vector<glsl::vec2> const & GenerateCap(LineSegment const & segment, EPointType type,
                                         float sign, bool isStart)
  {
    m_normalBuffer.clear();
    m_normalBuffer.reserve(24);

    GenerateCapNormals(m_params.m_cap,
                       segment.m_leftNormals[type],
                       segment.m_rightNormals[type],
                       sign * segment.m_tangent,
                       GetHalfWidth(), isStart, m_normalBuffer);

    return m_normalBuffer;
  }

  vector<glsl::vec2> const & GenerateJoin(LineSegment const & seg1, LineSegment const & seg2)
  {
    m_normalBuffer.clear();
    m_normalBuffer.reserve(24);

    glsl::vec2 n1 = seg1.m_hasLeftJoin[EndPoint] ? seg1.m_leftNormals[EndPoint] :
                                                   seg1.m_rightNormals[EndPoint];

    glsl::vec2 n2 = seg2.m_hasLeftJoin[StartPoint] ? seg2.m_leftNormals[StartPoint] :
                                                     seg2.m_rightNormals[StartPoint];

    float widthScalar = seg1.m_hasLeftJoin[EndPoint] ? seg1.m_rightWidthScalar[EndPoint].x :
                                                       seg1.m_leftWidthScalar[EndPoint].x;

    GenerateJoinNormals(m_params.m_join, n1, n2, GetHalfWidth(),
                        seg1.m_hasLeftJoin[EndPoint], widthScalar, m_normalBuffer);

    return m_normalBuffer;
  }

protected:
  using V = TVertex;
  using TGeometryBuffer = vector<V>;

  TGeometryBuffer m_geometry;
  TGeometryBuffer m_joinGeom;

  vector<glsl::vec2> m_normalBuffer;

  BaseBuilderParams m_params;
  glsl::vec2 const m_colorCoord;
};

class SolidLineBuilder : public BaseLineBuilder<gpu::LineVertex>
{
  using TBase = BaseLineBuilder<gpu::LineVertex>;
  using TNormal = gpu::LineVertex::TNormal;

  struct CapVertex
  {
    using TPosition = gpu::LineVertex::TPosition;
    using TNormal = gpu::LineVertex::TNormal;
    using TTexCoord = gpu::LineVertex::TTexCoord;

    CapVertex() {}
    CapVertex(TPosition const & pos, TNormal const & normal, TTexCoord const & color)
      : m_position(pos)
      , m_normal(normal)
      , m_color(color)
    {
    }

    TPosition m_position;
    TNormal m_normal;
    TTexCoord m_color;
  };

  using TCapBuffer = vector<CapVertex>;

public:
  using BuilderParams = BaseBuilderParams;

  SolidLineBuilder(BuilderParams const & params, size_t pointsInSpline)
    : TBase(params, pointsInSpline * 2, (pointsInSpline - 2) * 8)
  {}

  dp::GLState GetState() override
  {
    dp::GLState state(gpu::LINE_PROGRAM, dp::GLState::GeometryLayer);
    state.SetColorTexture(m_params.m_color.GetTexture());
    return state;
  }

  dp::BindingInfo const & GetCapBindingInfo() override
  {
    if (m_params.m_cap == dp::ButtCap)
      return TBase::GetCapBindingInfo();

    static unique_ptr<dp::BindingInfo> s_capInfo;
    if (s_capInfo == nullptr)
    {
      dp::BindingFiller<CapVertex> filler(3);
      filler.FillDecl<CapVertex::TPosition>("a_position");
      filler.FillDecl<CapVertex::TNormal>("a_normal");
      filler.FillDecl<CapVertex::TTexCoord>("a_colorTexCoords");

      s_capInfo.reset(new dp::BindingInfo(filler.m_info));
    }

    return *s_capInfo;
  }

  dp::GLState GetCapState() override
  {
    if (m_params.m_cap == dp::ButtCap)
      return TBase::GetCapState();

    dp::GLState state(gpu::CAP_JOIN_PROGRAM, dp::GLState::GeometryLayer);
    state.SetColorTexture(m_params.m_color.GetTexture());
    state.SetDepthFunction(gl_const::GLLess);
    return state;
  }

  ref_ptr<void> GetCapData() override
  {
    return make_ref<void>(m_capGeometry.data());
  }

  size_t GetCapSize() override
  {
    return m_capGeometry.size();
  }

  void SubmitVertex(glsl::vec3 const & pivot, glsl::vec2 const & normal, bool isLeft)
  {
    float const halfWidth = GetHalfWidth();
    m_geometry.emplace_back(V(pivot, TNormal(halfWidth * normal, halfWidth * GetSide(isLeft)), m_colorCoord));
  }

  void SubmitJoin(glsl::vec2 const & pos)
  {
    if (m_params.m_join == dp::RoundJoin)
      CreateRoundCap(pos);
  }

  void SubmitCap(glsl::vec2 const & pos)
  {
    if (m_params.m_cap != dp::ButtCap)
      CreateRoundCap(pos);
  }

private:
  void CreateRoundCap(glsl::vec2 const & pos)
  {
    m_capGeometry.reserve(8);

    float const radius = GetHalfWidth();

    m_capGeometry.push_back(CapVertex(CapVertex::TPosition(pos, m_params.m_depth),
                                      CapVertex::TNormal(-radius, radius, radius),
                                      CapVertex::TTexCoord(m_colorCoord)));
    m_capGeometry.push_back(CapVertex(CapVertex::TPosition(pos, m_params.m_depth),
                                      CapVertex::TNormal(-radius, -radius, radius),
                                      CapVertex::TTexCoord(m_colorCoord)));
    m_capGeometry.push_back(CapVertex(CapVertex::TPosition(pos, m_params.m_depth),
                                      CapVertex::TNormal(radius, radius, radius),
                                      CapVertex::TTexCoord(m_colorCoord)));
    m_capGeometry.push_back(CapVertex(CapVertex::TPosition(pos, m_params.m_depth),
                                      CapVertex::TNormal(radius, -radius, radius),
                                      CapVertex::TTexCoord(m_colorCoord)));
  }

private:
  TCapBuffer m_capGeometry;
};

class DashedLineBuilder : public BaseLineBuilder<gpu::DashedLineVertex>
{
  using TBase = BaseLineBuilder<gpu::DashedLineVertex>;
  using TNormal = gpu::LineVertex::TNormal;

public:
  struct BuilderParams : BaseBuilderParams
  {
    dp::TextureManager::StippleRegion m_stipple;
    float m_glbHalfWidth;
    float m_baseGtoP;
  };

  DashedLineBuilder(BuilderParams const & params, size_t pointsInSpline)
    : TBase(params, pointsInSpline * 8, (pointsInSpline - 2) * 8)
    , m_texCoordGen(params.m_stipple)
    , m_baseGtoPScale(params.m_baseGtoP)
  {}

  void GetTexturingInfo(float const globalLength, int & steps, float & maskSize)
  {
    float const pixelLen = globalLength * m_baseGtoPScale;
    steps = static_cast<int>((pixelLen + m_texCoordGen.GetMaskLength() - 1) / m_texCoordGen.GetMaskLength());
    maskSize = globalLength / steps;
  }

  dp::GLState GetState() override
  {
    dp::GLState state(gpu::DASHED_LINE_PROGRAM, dp::GLState::GeometryLayer);
    state.SetColorTexture(m_params.m_color.GetTexture());
    state.SetMaskTexture(m_texCoordGen.GetRegion().GetTexture());
    return state;
  }

  void SubmitVertex(glsl::vec3 const & pivot, glsl::vec2 const & normal, bool isLeft, float offsetFromStart)
  {
    float const halfWidth = GetHalfWidth();
    m_geometry.emplace_back(V(pivot, TNormal(halfWidth * normal, halfWidth * GetSide(isLeft)),
                              m_colorCoord, m_texCoordGen.GetTexCoordsByDistance(offsetFromStart)));
  }

private:
  TextureCoordGenerator m_texCoordGen;
  float const m_baseGtoPScale;
};

} // namespace

LineShape::LineShape(m2::SharedSpline const & spline, LineViewParams const & params)
  : m_params(params)
  , m_spline(spline)
{
  ASSERT_GREATER(m_spline->GetPath().size(), 1, ());
}

template <typename TBuilder>
void LineShape::Construct(TBuilder & builder) const
{
  ASSERT(false, ("No implementation"));
}

// Specialization optimized for dashed lines.
template <>
void LineShape::Construct<DashedLineBuilder>(DashedLineBuilder & builder) const
{
  vector<m2::PointD> const & path = m_spline->GetPath();
  ASSERT_GREATER(path.size(), 1, ());

  // build geometry
  for (size_t i = 1; i < path.size(); ++i)
  {
    if (path[i].EqualDxDy(path[i - 1], 1.0E-5))
      continue;

    glsl::vec2 const p1 = glsl::vec2(path[i - 1].x, path[i - 1].y);
    glsl::vec2 const p2 = glsl::vec2(path[i].x, path[i].y);
    glsl::vec2 tangent, leftNormal, rightNormal;
    CalculateTangentAndNormals(p1, p2, tangent, leftNormal, rightNormal);

    // calculate number of steps to cover line segment
    float const initialGlobalLength = glsl::length(p2 - p1);
    int steps = 1;
    float maskSize = initialGlobalLength;
    builder.GetTexturingInfo(initialGlobalLength, steps, maskSize);

    // generate vertices
    float currentSize = 0;
    glsl::vec3 currentStartPivot = glsl::vec3(p1, m_params.m_depth);
    for (int step = 0; step < steps; step++)
    {
      currentSize += maskSize;
      glsl::vec3 const newPivot = glsl::vec3(p1 + tangent * currentSize, m_params.m_depth);

      builder.SubmitVertex(currentStartPivot, rightNormal, false /* isLeft */, 0.0);
      builder.SubmitVertex(currentStartPivot, leftNormal, true /* isLeft */, 0.0);
      builder.SubmitVertex(newPivot, rightNormal, false /* isLeft */, maskSize);
      builder.SubmitVertex(newPivot, leftNormal, true /* isLeft */, maskSize);

      currentStartPivot = newPivot;
    }
  }
}

// Specialization optimized for solid lines.
template <>
void LineShape::Construct<SolidLineBuilder>(SolidLineBuilder & builder) const
{
  vector<m2::PointD> const & path = m_spline->GetPath();
  ASSERT_GREATER(path.size(), 1, ());

  // skip joins generation
  float const kJoinsGenerationThreshold = 2.5f;
  bool generateJoins = true;
  if (builder.GetHalfWidth() <= kJoinsGenerationThreshold)
    generateJoins = false;

  // build geometry
  glsl::vec2 firstPoint = glsl::vec2(path.front().x, path.front().y);
  glsl::vec2 lastPoint;
  bool hasConstructedSegments = false;
  for (size_t i = 1; i < path.size(); ++i)
  {
    if (path[i].EqualDxDy(path[i - 1], 1.0E-5))
      continue;

    glsl::vec2 const p1 = glsl::vec2(path[i - 1].x, path[i - 1].y);
    glsl::vec2 const p2 = glsl::vec2(path[i].x, path[i].y);
    glsl::vec2 tangent, leftNormal, rightNormal;
    CalculateTangentAndNormals(p1, p2, tangent, leftNormal, rightNormal);

    glsl::vec3 const startPoint = glsl::vec3(p1, m_params.m_depth);
    glsl::vec3 const endPoint = glsl::vec3(p2, m_params.m_depth);

    builder.SubmitVertex(startPoint, rightNormal, false /* isLeft */);
    builder.SubmitVertex(startPoint, leftNormal, true /* isLeft */);
    builder.SubmitVertex(endPoint, rightNormal, false /* isLeft */);
    builder.SubmitVertex(endPoint, leftNormal, true /* isLeft */);

    // generate joins
    if (generateJoins && i < path.size() - 1)
      builder.SubmitJoin(p2);

    lastPoint = p2;
    hasConstructedSegments = true;
  }

  if (hasConstructedSegments)
  {
    builder.SubmitCap(firstPoint);
    builder.SubmitCap(lastPoint);
  }
}

void LineShape::Prepare(ref_ptr<dp::TextureManager> textures) const
{
  dp::TextureManager::ColorRegion colorRegion;
  textures->GetColorRegion(m_params.m_color, colorRegion);
  float const pxHalfWidth = m_params.m_width / 2.0f;

  auto commonParamsBuilder = [&](BaseBuilderParams & p)
  {
    p.m_cap = m_params.m_cap;
    p.m_color = colorRegion;
    p.m_depth = m_params.m_depth;
    p.m_join = m_params.m_join;
    p.m_pxHalfWidth = pxHalfWidth;
  };

  if (m_params.m_pattern.empty())
  {
    SolidLineBuilder::BuilderParams p;
    commonParamsBuilder(p);

    auto builder = make_unique<SolidLineBuilder>(p, m_spline->GetPath().size());
    Construct<SolidLineBuilder>(*builder);
    m_lineShapeInfo = move(builder);
  }
  else
  {
    dp::TextureManager::StippleRegion maskRegion;
    textures->GetStippleRegion(m_params.m_pattern, maskRegion);

    DashedLineBuilder::BuilderParams p;
    commonParamsBuilder(p);
    p.m_stipple = maskRegion;
    p.m_baseGtoP = m_params.m_baseGtoPScale;
    p.m_glbHalfWidth = pxHalfWidth / m_params.m_baseGtoPScale;

    auto builder = make_unique<DashedLineBuilder>(p, m_spline->GetPath().size());
    Construct<DashedLineBuilder>(*builder);
    m_lineShapeInfo = move(builder);
  }
}

void LineShape::Draw(ref_ptr<dp::Batcher> batcher, ref_ptr<dp::TextureManager> textures) const
{
  if (!m_lineShapeInfo)
    Prepare(textures);

  ASSERT(m_lineShapeInfo != nullptr, ());
  dp::GLState state = m_lineShapeInfo->GetState();

  dp::AttributeProvider provider(1, m_lineShapeInfo->GetLineSize());
  provider.InitStream(0, m_lineShapeInfo->GetBindingInfo(), m_lineShapeInfo->GetLineData());
  batcher->InsertListOfStrip(state, make_ref(&provider), dp::Batcher::VertexPerQuad);

  size_t joinSize = m_lineShapeInfo->GetJoinSize();
  if (joinSize > 0)
  {
    dp::AttributeProvider joinsProvider(1, joinSize);
    joinsProvider.InitStream(0, m_lineShapeInfo->GetBindingInfo(), m_lineShapeInfo->GetJoinData());
    batcher->InsertTriangleList(state, make_ref(&joinsProvider));
  }

  size_t capSize = m_lineShapeInfo->GetCapSize();
  if (capSize > 0)
  {
    dp::AttributeProvider capProvider(1, capSize);
    capProvider.InitStream(0, m_lineShapeInfo->GetCapBindingInfo(), m_lineShapeInfo->GetCapData());
    batcher->InsertListOfStrip(m_lineShapeInfo->GetCapState(), make_ref(&capProvider), dp::Batcher::VertexPerQuad);
  }
}

} // namespace df


text:
var util = require('util');
var events = require('events');

function Pulsar(speed, times) {
  events.EventEmitter.call(this);

  var self = this;
  this.speed = speed;
  this.times = times;

  this.on('newListener', function(eventName, listener) {
    if (eventName === 'pulse') {
      self.start();
    }
  });
}

util.inherits(Pulsar, events.EventEmitter);

Pulsar.prototype.start = function() {
  var self = this;
  var id = setInterval(function() {
    self.emit('pulse');
    self.times--;
    if (self.times === 0) {
      clearInterval(id);
    }
  }, this.speed);
};

var pulsar = new Pulsar(500, 5);

pulsar.on('pulse', function() { //<co id="callout-events-reflection-2-1" />
  console.log('.');
});


text:
<?php

/**
 * Models that represent an entity in the system need to implement iEntity
 * that will make them cachable, taggable, registerable, exportable, etc.
 */
interface iEntity {
	public function getEntityType();
	public function getId();
}
?>


text:
namespace TraktApiSharp.Objects.Post.Users.HiddenItems.Responses
{
    public interface ITraktUserHiddenItemsRemovePostResponse
    {
        ITraktUserHiddenItemsPostResponseGroup Deleted { get; set; }

        ITraktUserHiddenItemsPostResponseNotFoundGroup NotFound { get; set; }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 334762 $ -->
<refentry xml:id="function.variant-idiv" xmlns="http://docbook.org/ns/docbook">
 <refnamediv>
  <refname>variant_idiv</refname>
  <refpurpose>Converts variants to integers and then returns the result from dividing them</refpurpose>
 </refnamediv>
 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <type>mixed</type><methodname>variant_idiv</methodname>
   <methodparam><type>mixed</type><parameter>left</parameter></methodparam>
   <methodparam><type>mixed</type><parameter>right</parameter></methodparam>
  </methodsynopsis>
  <para>
   Converts <parameter>left</parameter> and <parameter>right</parameter> to
   integer values, and then performs integer division.
  </para>
 </refsect1>
 <refsect1 role="parameters">
  &reftitle.parameters;
  <para>
   <variablelist>
    <varlistentry>
     <term><parameter>left</parameter></term>
     <listitem>
      <para>
       The left operand.
      </para>
     </listitem>
    </varlistentry>
    <varlistentry>
     <term><parameter>right</parameter></term>
     <listitem>
      <para>
       The right operand.
      </para>
     </listitem>
    </varlistentry>
   </variablelist>
   &com.variant-arith;
  </para>
 </refsect1>
 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>
   <table>
    <title>Variant Integer Division Rules</title>
    <tgroup cols="2">
     <thead>
      <row>
       <entry>If</entry>
       <entry>Then</entry>
      </row>
     </thead>
     <tbody>
      <row>
       <entry>Both expressions are of the string, date, character, boolean type</entry>
       <entry>Division and integer is returned</entry>
      </row>
      <row>
       <entry>One expression is a string type and the other a
       character</entry>
       <entry>Division</entry>
      </row>
      <row>
       <entry>One expression is numeric and the other is a string</entry>
       <entry>Division</entry>
      </row>
      <row>
       <entry>Both expressions are numeric</entry>
       <entry>Division</entry>
      </row>
      <row>
       <entry>Either expression is NULL</entry>
       <entry>NULL is returned</entry>
      </row>
      <row>
       <entry>Both expressions are empty</entry>
       <entry>A com_exception with code <constant>DISP_E_DIVBYZERO</constant>
       is thrown</entry>
      </row>
     </tbody>
    </tgroup>
   </table>
  </para>
 </refsect1>
 <refsect1 role="seealso">
  &reftitle.seealso;
  <para>
   <simplelist>
    <member><function>variant_div</function></member>
   </simplelist>
  </para>
 </refsect1>
</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
require "spec_helper"

RSpec.describe Sentry::Rails::Tracing::ActionControllerSubscriber, :subscriber, type: :request do
  let(:transport) do
    Sentry.get_current_client.transport
  end

  context "when transaction is sampled" do
    before do
      make_basic_app do |config|
        config.traces_sample_rate = 1.0
        config.rails.tracing_subscribers = [described_class]
      end
    end

    it "records controller action processing event" do
      get "/world"

      expect(transport.events.count).to eq(1)

      transaction = transport.events.first.to_hash
      expect(transaction[:type]).to eq("transaction")
      expect(transaction[:spans].count).to eq(1)

      span = transaction[:spans][0]
      expect(span[:op]).to eq("process_action.action_controller")
      expect(span[:description]).to eq("HelloController#world")
      expect(span[:trace_id]).to eq(transaction.dig(:contexts, :trace, :trace_id))
      expect(span[:data][:payload].keys).not_to include(:request)
      expect(span[:data][:payload].keys).not_to include(:headers)
    end
  end

  context "when transaction is not sampled" do
    before do
      make_basic_app
    end

    it "doesn't record spans" do
      transaction = Sentry::Transaction.new(sampled: false, hub: Sentry.get_current_hub)
      Sentry.get_current_scope.set_span(transaction)

      get "/world"

      transaction.finish

      expect(transport.events.count).to eq(0)
      expect(transaction.span_recorder.spans).to eq([transaction])
    end
  end
end


text:
namespace Encomiendas.Web.Api.Requests
{
    public class NewPasswordRequest
    {
        public string Password { get; set; }
    }
}


text:
/* eslint ember/order-in-components: 0 */
import Component from '@ember/component';
import { computed } from '@ember/object';
import RSVP from 'rsvp';
import Publishable from 'ilios-common/mixins/publishable';
import { validator, buildValidations } from 'ember-cp-validations';
import ValidationErrorDisplay from 'ilios-common/mixins/validation-error-display';

const { alias } = computed;
const { Promise } = RSVP;

const Validations = buildValidations({
  programTitle: [
    validator('presence', true),
    validator('length', {
      min: 3,
      max: 200
    }),
  ],
});

export default Component.extend(Validations, Publishable, ValidationErrorDisplay, {
  didReceiveAttrs(){
    this._super(...arguments);
    this.set('programTitle', this.get('program.title'));
  },
  classNames: ['program-header'],
  program: null,
  canUpdate: false,
  programTitle: null,
  publishTarget: alias('program'),

  actions: {
    changeTitle() {
      const program = this.program;
      const newTitle = this.programTitle;
      this.send('addErrorDisplayFor', 'programTitle');
      return new Promise((resolve, reject) => {
        this.validate().then(({validations}) => {
          if (validations.get('isValid')) {
            this.send('removeErrorDisplayFor', 'programTitle');
            program.set('title', newTitle);
            program.save().then((newprogram) => {
              this.set('programTitle', newprogram.get('title'));
              this.set('program', newprogram);
              resolve();
            });
          } else {
            reject();
          }
        });
      });
    },
    revertTitleChanges(){
      const program = this.program;
      this.set('programTitle', program.get('title'));
    },
  }
});


text:
/*Problem 10. Find palindromes
Write a program that extracts from a given text all palindromes, e.g. "ABBA", "lamal", "exe".*/

var text = '"ABBA", "lamal", "exe", "sos", "not", "palindrome", "test"';

console.log('palindromes are :' + extractPalindromes(text));

function extractPalindromes(text){
    var endResult = [];
    var result = text.split(' ');

    for(var w in result) {
        var word = result[w];
        var palindrome = true;
        var cycleLength = (word.length - 1) / 2;

        for (var i = 0; i < cycleLength; i++) {
            var fDigit = word[i];
            var eDigit = word[word.length - 2 - i];
            if (fDigit !== eDigit) {
                palindrome = false;
            }
        }
        if (palindrome) {
            endResult.push(word);
        }
    }

    return endResult;
}


text:
package sock

import (
	"fmt"
	"net"
	"os"
	"syscall"

	"golang.org/x/net/ipv4"
)

type MulticastSock struct {
	P *ipv4.PacketConn
	U *net.UDPConn
}

func NewUDPConn(laddr *net.UDPAddr, ifname string) (*net.UDPConn, error) {

	/*
		if laddr == nil {
			laddr = &net.UDPAddr{IP: net.IPv4zero, Port: 0}
		}

		s, err1 := syscall.Socket(syscall.AF_INET, syscall.SOCK_DGRAM, syscall.IPPROTO_UDP)
		if err1 != nil {
			return nil, fmt.Errorf("MulticastListener: could not create socket(laddr=%v,ifname=%s): %v", laddr, ifname, err1)
		}
		if err := syscall.SetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1); err != nil {
			syscall.Close(s)
			return nil, fmt.Errorf("MulticastListener: could not set reuse addr socket(laddr=%v,ifname=%s): %v", laddr, ifname, err)
		}
		if ifname != "" {
			if err := syscall.SetsockoptString(s, syscall.SOL_SOCKET, syscall.SO_BINDTODEVICE, ifname); err != nil {
				syscall.Close(s)
				return nil, fmt.Errorf("MulticastListener: could not bind to device socket(laddr=%v, ifname=%s): %v", laddr, ifname, err)
			}
		}

		lsa := syscall.SockaddrInet4{Port: laddr.Port}
		copy(lsa.Addr[:], laddr.IP.To4())

		if err := syscall.Bind(s, &lsa); err != nil {
			syscall.Close(s)
			return nil, fmt.Errorf("MulticastListener: could not bind socket to address %v: %v", laddr, err)
		}
		f := os.NewFile(uintptr(s), "")
		c, err2 := net.FilePacketConn(f)
		f.Close()
		if err2 != nil {
			syscall.Close(s)
			return nil, fmt.Errorf("MulticastListener: could not get packet connection for socket(laddr=%v,ifname=%s): %v", laddr, ifname, err2)
		}
		u := c.(*net.UDPConn)

		return u, nil
	*/

	c, err := udpConn(laddr, ifname)
	if err != nil {
		return nil, err
	}

	u := c.(*net.UDPConn)

	return u, nil
}

func udpConn(laddr *net.UDPAddr, ifname string) (net.PacketConn, error) {
	if laddr == nil {
		laddr = &net.UDPAddr{IP: net.IPv4zero, Port: 0}
	}

	s, err1 := syscall.Socket(syscall.AF_INET, syscall.SOCK_DGRAM, syscall.IPPROTO_UDP)
	if err1 != nil {
		return nil, fmt.Errorf("MulticastListener: could not create socket(laddr=%v,ifname=%s): %v", laddr, ifname, err1)
	}
	if err := syscall.SetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1); err != nil {
		syscall.Close(s)
		return nil, fmt.Errorf("MulticastListener: could not set reuse addr socket(laddr=%v,ifname=%s): %v", laddr, ifname, err)
	}
	if ifname != "" {
		if err := syscall.SetsockoptString(s, syscall.SOL_SOCKET, syscall.SO_BINDTODEVICE, ifname); err != nil {
			syscall.Close(s)
			return nil, fmt.Errorf("MulticastListener: could not bind to device socket(laddr=%v, ifname=%s): %v", laddr, ifname, err)
		}
	}

	lsa := syscall.SockaddrInet4{Port: laddr.Port}
	copy(lsa.Addr[:], laddr.IP.To4())

	if err := syscall.Bind(s, &lsa); err != nil {
		syscall.Close(s)
		return nil, fmt.Errorf("MulticastListener: could not bind socket to address %v: %v", laddr, err)
	}
	f := os.NewFile(uintptr(s), "")
	c, err2 := net.FilePacketConn(f)
	f.Close()
	if err2 != nil {
		syscall.Close(s)
		return nil, fmt.Errorf("MulticastListener: could not get packet connection for socket(laddr=%v,ifname=%s): %v", laddr, ifname, err2)
	}

	return c, nil
}

func MulticastListener(port int, ifname string) (*MulticastSock, error) {

	/*
		s, err1 := syscall.Socket(syscall.AF_INET, syscall.SOCK_DGRAM, syscall.IPPROTO_UDP)
		if err1 != nil {
			return nil, fmt.Errorf("MulticastListener: could not create socket(port=%d,ifname=%s): %v", port, ifname, err1)
		}
		if err := syscall.SetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1); err != nil {
			syscall.Close(s)
			return nil, fmt.Errorf("MulticastListener: could not set reuse addr socket(port=%d,ifname=%s): %v", port, ifname, err)
		}
		if ifname != "" {
			if err := syscall.SetsockoptString(s, syscall.SOL_SOCKET, syscall.SO_BINDTODEVICE, ifname); err != nil {
				syscall.Close(s)
				return nil, fmt.Errorf("MulticastListener: could not bind to device socket(port=%d,ifname=%s): %v", port, ifname, err)
			}
		}

		bindAddr := net.IP(net.IPv4(0, 0, 0, 0))
		lsa := syscall.SockaddrInet4{Port: port}
		copy(lsa.Addr[:], bindAddr.To4())

		if err := syscall.Bind(s, &lsa); err != nil {
			syscall.Close(s)
			return nil, fmt.Errorf("MulticastListener: could not bind socket to address %v,%d: %v", bindAddr, port, err)
		}
		f := os.NewFile(uintptr(s), "")
		c, err2 := net.FilePacketConn(f)
		f.Close()
		if err2 != nil {
			syscall.Close(s)
			return nil, fmt.Errorf("MulticastListener: could not get packet connection for socket(port=%d,ifname=%s): %v", port, ifname, err2)
		}
		u := c.(*net.UDPConn)
		p := ipv4.NewPacketConn(c)

		if err := p.SetControlMessage(ipv4.FlagTTL|ipv4.FlagSrc|ipv4.FlagDst|ipv4.FlagInterface, true); err != nil {
			return nil, fmt.Errorf("MulticastListener: could not set control message flags: %v", err)
		}

		return &MulticastSock{P: p, U: u}, nil
	*/

	c, err := udpConn(&net.UDPAddr{IP: net.IPv4zero, Port: port}, ifname)
	if err != nil {
		return nil, err
	}

	u := c.(*net.UDPConn)
	p := ipv4.NewPacketConn(c)

	if err := p.SetControlMessage(ipv4.FlagTTL|ipv4.FlagSrc|ipv4.FlagDst|ipv4.FlagInterface, true); err != nil {
		return nil, fmt.Errorf("MulticastListener: could not set control message flags: %v", err)
	}

	return &MulticastSock{P: p, U: u}, nil
}

func Join(sock *MulticastSock, group net.IP, ifname string) error {
	ifi, err1 := net.InterfaceByName(ifname)
	if err1 != nil {
		return fmt.Errorf("Join: could not find interface %s: %v", ifname, err1)
	}

	if err := sock.P.JoinGroup(ifi, &net.UDPAddr{IP: group}); err != nil {
		return fmt.Errorf("Join: could not join group %v on interface %s: %v", group, ifname, err)
	}

	return nil
}

func Leave(sock *MulticastSock, group net.IP, ifi *net.Interface) error {
	if err := sock.P.LeaveGroup(ifi, &net.UDPAddr{IP: group}); err != nil {
		return fmt.Errorf("Leave: could not leave group %v on interface %s: %v", group, ifi.Name, err)
	}

	return nil
}

func Close(sock *MulticastSock) {
	sock.P.Close()
	sock.U.Close()
	sock.P = nil
	sock.U = nil
}


text:
package org.apache.camel.component.http4;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.impl.client.HttpClientBuilder;

public class CompositeHttpConfigurer implements HttpClientConfigurer {

    private final List<HttpClientConfigurer> configurers = new ArrayList<>();

    public void addConfigurer(HttpClientConfigurer configurer) {
        if (configurer != null) {
            configurers.add(configurer);
        }
    }

    public void removeConfigurer(HttpClientConfigurer configurer) {
        configurers.remove(configurer);
    }

    public void configureHttpClient(HttpClientBuilder clientBuilder) {
        for (HttpClientConfigurer configurer : configurers) {
            configurer.configureHttpClient(clientBuilder);
        }
    }

    public static CompositeHttpConfigurer combineConfigurers(HttpClientConfigurer oldConfigurer, HttpClientConfigurer newConfigurer) {
        if (oldConfigurer instanceof CompositeHttpConfigurer) {
            ((CompositeHttpConfigurer) oldConfigurer).addConfigurer(newConfigurer);
            return (CompositeHttpConfigurer) oldConfigurer;
        } else {
            CompositeHttpConfigurer answer = new CompositeHttpConfigurer();
            answer.addConfigurer(newConfigurer);
            answer.addConfigurer(oldConfigurer);
            return answer;
        }
    }

}


text:
class CJS_Icon final : public CJS_Object {
 public:
  static int GetObjDefnID();
  static void DefineJSObjects(CFXJS_Engine* pEngine);

  CJS_Icon(v8::Local<v8::Object> pObject, CJS_Runtime* pRuntime);
  ~CJS_Icon() override;

  WideString GetIconName() const { return m_swIconName; }
  void SetIconName(WideString name) { m_swIconName = name; }

  JS_STATIC_PROP(name, name, CJS_Icon)

 private:
  static int ObjDefnID;
  static const char kName[];
  static const JSPropertySpec PropertySpecs[];

  CJS_Result get_name(CJS_Runtime* pRuntime);
  CJS_Result set_name(CJS_Runtime* pRuntime, v8::Local<v8::Value> vp);

  WideString m_swIconName;
};

#endif  // FXJS_CJS_ICON_H_


text:
require 'spec_helper'

describe ApplicationController, :type => :controller do
  describe '#authorize_admin' do
    it 'should not raise any error when the current account is an admin.' do
      account = FactoryGirl.create :account
      FactoryGirl.create :admin, :account_id => account.id
      expect(account).to be_admin

      allow(controller).to receive(:current_account).and_return account

      expect { controller.send(:authorize_admin) }.to_not raise_error
    end

    it 'should raise a routing error when the current is not an admin.' do
      account = FactoryGirl.create :account
      expect(account).to_not be_admin

      allow(controller).to receive(:current_account).and_return account

      expect { controller.send(:authorize_admin) }.to raise_error AbstractController::ActionNotFound
    end

    it 'should raise a routing error when there is no current account.' do
      allow(controller).to receive(:current_account).and_return nil

      expect { controller.send(:authorize_admin) }.to raise_error AbstractController::ActionNotFound
    end
  end
end


text:
layout: article
title: "Mediencenter mit dem Raspberry Pi"
date: 2015-03-26
modified: 2015-03-26
author: Christian
categories: raspberrypi
share: true
excerpt: "Der Mini-Computer für Filme, Musik, Serien und mehr."
tags: [raspberrypi, movies, music]
toc: true
comments: true
image:
  feature:
  teaser: raspberrypi/mediencenter/mediencenter_teaser.png
---

Seit einiger Zeit sind immer über Neuigkeiten und Hobbyprojekte über ihn zu lesen. Der Raspberry Pi. Er ist ein kleiner - sehr kleiner - Computer, der unglaublich wenig Strom braucht und sich leicht an jeden Monitor oder Fernseher per HDMI anschließen lässt. Er hat alles was man für das eigene Hobbyprojekt im Bereich Informatik braucht. Gerade der Preis und Größe des Rechners sind unschlagbar.

Nicht jeder hat aber das Know-How, die Zeit und die Lust sich mit den Grundfunktionen eines Linux-Betriebssystems herumzuschlagen. **Was kann man also ohne viel Informatik-Kenntnisse mit einem Raspberry Pi anstellen?**

## Der Raspberry Pi 2:

		Der Raspberry Pi 2.

Hier eine Auflistung der wichtigsten Details des Raspberry Pi 2:

* 900MHz Quad-Core ARM Cortex-A7 CPU
* 1GB RAM
* 4 USB Ports
* HDMI Port und Composite Video
* Ethernet Port (LAN)
* 3,5mm Audio
* Micro SD Slot
* **Preis: 35€**

Mit der Version 2 des kleinen Computers ist es möglich eine Linux-Distribution oder eine kostenlose Version von Windows 10 zu nutzen.

## Mediencenter

Eine der beliebtesten Anwendungen, die im Netz mir dem Raspberry Pi zu finden sind, ist die des Mediencenters. Der Sinn des Ganzen ist das einfache **Verwalten und Abspielen von Medien aller Art**. Viele Heimanwender steigen derzeit vo Kauf von BluRay und DVD auf Streaming Portale wie Maxdome, Amazon Prime instant video und Netflix um. Dadurch spart man sich z.B. Platz im Regal und den Weg zum Händler bzw. Versandkosten. Möchte man zusätzlich seine Musik in Form von MP3s abspielen, kann ein Mediencenter die Lösung sein.

		Kodi - Ein kostenloses und umfangreiches Media Center für verschiedene Betriebssysteme, mit dem man Filme, Fotos und Musik verwalten und abspielen kann.

Im Netz gibt es einige vielversprechende kostenlose Systeme. Hinter den meisten steckt jeweils eine große oder kleine Community, die das System weiterentwickelt. Dabei kann es monatlich oder sogar wöchentlich zu Updates und Verbesserungen kommen. Viele der Systeme, die sich um das Thema Mediencenter drehen nutzen das Programm **Kodi (früher XBMC)**. Kodi ist ein Programm zur Verwaltung und Abspielen von Filmen, Serien, Musik und Bildern. Die Anzahl der Addons übersteigt locker die 2000, womit man das Programm leicht individuell erweitern kann.

**OpenElec** ist ein System, welches sehr einfach einzurichten ist. Es baut ein eigenes Linux-Betriebssystem um das Programm Kodi herum auf und schafft eine sehr simple und performante Umgebung. Nachfolgend zeige ich, wie man ein solches System einrichtet.

## Voraussetzungen

Bevor wir hier anfangen so ein Mediencenter einzurichten, brauchen wir erst einmal ein paar Dinge:

* Raspberry Pi (am besten Version 2)
* Micro-USB Netzteil (5V, 2A)
* HDMI-Kabel
* Micro-SD Karte (8GB ist ausreichend) mit Adapter
* (optional) Ethernet-Kabel oder USB-WLAN-Stick
* (optional) Raspberry Pi Gehäuse

Man sollte dafür nicht mehr als ca. 60-80€ ausgeben müssen.
Sobald man auf Dienste aus dem Internet ( Youtube, Netflix, etc. ) oder auf externe Laufwerke im LAN zugreifen will (Festplatten am Router oder an einem NAS[^nas]) braucht man natürlich eine Netzwerkverbindung. Falls das jedoch per Ethernet-Kabel sich schwierig gestaltet, nimmt man am besten einen USB-WLAN-Stick. Simpel, klein und günstig auf z.B. Amazon zu kaufen.

[^nas]: NAS: Network Attached Storage, bezeichnet einfach zu verwaltende Dateiserver. Allgemein wird NAS eingesetzt, um ohne hohen Aufwand unabhängige Speicherkapazität in einem Rechnernetz bereitzustellen.

Zusätzlich braucht man einen PC oder Laptop, an dem man die Micro-SD Karte benutzen kann.

## Installieren von OpenElec

Hat man alle Komponenten zusammen, läd man sich am besten zuerst die neueste Version von OpenElec herunter. Unter OpenElec.tv wählt man das Image für den eigenen Raspberry Pi herunter. Die Datei entpackt man am besten mit 7Zip oder einem ähnlichen Programm.

Sobald man dann die *.img Datei hat, läd man sich als Windows-Benutzer das Programm Win32 Disk Imager herunter. Mit diesem Programm kann man das OpenElec Betriebssystem direkt auf die SD-Karte schreiben.

**Wichtig**: Den richtigen Laufwerksbuchstaben wählen! Vorher am besten prüfen welchen Buchstaben die SD-Karte belegt hat.
{: .notice-info}

		Mit dem Tool Win32 Disk Imager lässt sich leicht das System OpenElec auf eine Micro-SD Karte schreiben.
		Image auswählen, Laufwerk der SD-Karte wählen und auf "Write" klicken.

Sobald das erledigt wurde, kann der Raspberry Pi gestartet werden. Zuerst die SD-Karte einstecken, danach HDMI und Strom anschließen. Falls der Fernseher CEC unterstützt kann alles in Kodi mit der eigenen Fernbedienung des TVs gesteuert werden. Wirklich tolles Feature! Ansonsten einfach eine Maus oder Tastatur (Empfehlung: Logitech K400) anschließen. Später ist es auch möglich eine Smartphone-App zur Steuerung zu nutzen.

Zu Beginn wird man Schritt für Schritt durch eine Startkonfiguration geleitet, in der man Sprache, Netzwerk und sonstige Einstellungen vornehmen kann. Danach befindet man sich schon im Hauptmenü. Hier

		Erster Start von OpenElec. Hier wird man nach und nach durch die grundlegenden Einstellungen geführt.

Danach kann man unter Videos die Orte seiner Film und Serien Dateien festlegen.
Als Testvideo kann ich Big Buck Bunny der Blender Foundation empfehlen. Das Video kann kostenfrei in FullHD Qualität (1080p) mit Surround Sound (AC3 und AAC) heruntergeladen werden. Sobald das Testvideo auf einem USB-Stick oder einer externen Festplatte direkt an den Raspberry Pi per USB angesteckt ist, kanns losgehen. Im Hauptmenü unter Videos wählt man "Dateien" aus. Hier könnte man jetzt direkt auf den Datenträger zugreifen und das Video abspielen.

Es könnte aber lästig werden jedes mal die Filme oder Serien direkt auf den Festplatten zu suchen (gerade wenn man dort keine Ordnung hat). Deswegen gibt es unter Kodi eine Datenbank. In diesem Beispiel kann man mit Rechtsklick auf das Wechsellaufwerk den "Inhalt festlegen". Dabei kann man dann unter "Filme", "Serien" oder "Musikvideos" wählen und mehrere Optionen festlegen.

Für Netzwerklaufwerke gibt es unter "Dateien" die Option "Videos hinzufügen". Dort kann man Pfad und Inhalt festlegen.

**Wichtig**: In den Einstellungen die Sprache auf Deutsch (de) stellen! Die Filme werden sonst unter englischem Namen in der Datenbank gespeichert.
{: .notice-info}

Ein **Scraper** ist eine Webseite die für Filme, Serien oder sonstigem Details verlinkt. Man kann darüber also Informationen zu seinen Filmen - wie Trailer, allerlei Bilder, Filmhandlung, Bewertungen etc. - sich automatisiert holen. Standardmäßig ist "The Movie Database" ausgewählt.

Rekursives Scannen bedeutet, dass in dem ausgewählten Pfad alle Unterordner, deren Unterordner etc. nach abspielbaren Dateien durchsucht werden. Damit wird dann die Datenbank gefüttert. Bei einer großen Menge von Filmen kann das auch mal eine Weile dauern. Ist aber nur einmalig zu Beginn. Wenn neue Dateien dazu kommen wird in regelmäßigen Abständen aktualisiert.

		Hauptmenü mit zusätzlichem Reiter "Filme".

Wurde die Datenbank mit den Einträgen gespeist, erscheint das Feld "Filme" im Hauptmenü mit den zuletzt zugefügten Filmen.

		Filmdatenbank mit Ansicht "Medieninformationen".

Geht man direkt auf "Filme" erscheint eine Liste aller Filme der Datenbank. In unseren Fall ist das nur einer. Im Menü Links lässt sich die Art der Ansicht der Liste ändern. Hier habe ich mal die Ansicht "Medieninformationen" gewählt. Man Sieht eine Bewertung, Informationen zum Film und eine Kurzbeschreibung.
Das ist alles das Ergebnis des Scrapers. Wirklich toll!

Sobald man das Video zu ca. 90% gesehen hat, erscheint sogar ein Haken in der Liste. Der Film wird also als "gesehen" markiert. Durch setzen eines Filters findet man dann recht schnell noch nicht gesehene Filme.

		Big Buck Bunny - Blender Foundation | www.blender.org

Der Raspberry Pi 2 kommt damit ohne Probleme klar. Selbst als ich das noch mit dem Raspberry Pi 1 Version B+ getestet hatte, lief das wie geschmiert. Einzig bei Untertitel war der Vorgänger ab und an ein leicht überfordert.

Das wars auch schon fürs Erste. Den Rest findet man leicht selbst oder mit ein wenig Hilfe des Internets heraus. Wenn ihr auf Probleme bei der Installation stoßt, schreibt einfach einen Kommentar!

#### Update:
Schaut euch die [Spielekonsolen-Erweiterung](../Mediencenter_2){:target="_blank"} an! Ab jetzt wird der Controller wieder in die Hand genommen und Klassiker gezockt!


text:
class CGdiplusGuard
{
public:

    CGdiplusGuard()
    {
        m_isOk = ::GdiplusStartup(&m_gdiplusToken, &m_gdiplusStartupInput, NULL) == Gdiplus::Ok? TRUE : FALSE;
    }

    virtual ~CGdiplusGuard()
    {
        ::GdiplusShutdown(m_gdiplusToken);
    }

    inline BOOL isOk()
    {
        return m_isOk;
    }

private:

    CGdiplusGuard(const CGdiplusGuard &);

    CGdiplusGuard & operator = (const CGdiplusGuard &);

private:

    GdiplusStartupInput     m_gdiplusStartupInput;

    ULONG_PTR               m_gdiplusToken;

    BOOL                    m_isOk;
};

#endif  //  _GDIPLUS_GUARD_H_


text:
package edu.rpi.tw.data.csv.querylets;

import org.openrdf.model.Resource;
import org.openrdf.query.BindingSet;

import edu.rpi.tw.data.rdf.sesame.query.impl.OnlyOneContextQuerylet;

public class ExcludeIsReferencedByQuerylet extends OnlyOneContextQuerylet<Boolean> {

   protected boolean exclude = false;

   public ExcludeIsReferencedByQuerylet(Resource context) {
      super(context);
   }

   @Override
   public String getQueryString(Resource context) {
      exclude = false;

      addNamespace("conversion","dcterms");

      String select       = "distinct ?e";
      String graphPattern = "[] conversion:conversion_process [ conversion:enhance ?e ] . \n"+
                            "?e dcterms:isReferencedBy conversion:null .\n";
      String orderBy      = "";

      return this.composeQuery(select, context, graphPattern, orderBy);
   }

   @Override
   public void handleBindingSet(BindingSet bindingSet) {
      exclude = true;
      System.err.println(getClass().getSimpleName()+"(*) ." + exclude+".");
   }

   @Override
   public Boolean get() {
      return exclude;
   }
}


text:
require 'optparse'

module OdroidLCD
  class CLI

    def initialize(argv, mocks = {})
      @options = parse_arguments(argv)
      @argv = argv

      # If we're testing via the command line, set the mock rather than LCD.
      @lcd = if @options[:test]
        @hw_mock = OdroidLCD::HWMock.new
        mock_hw = mocks.merge({odroidlcd_hw: @hw_mock})
        OdroidLCD::LCD.new(mocks: mock_hw)
      else
        OdroidLCD::LCD.new(mocks: mocks)
      end

      # set the default text alignment
      @align = @options[:align] || "left"

      freeze()
    end

    def run
      lines = if @options.has_key?(:file)
        read_file(@options[:file])
      else
        @argv[0,2].map {|line| line.chomp }
      end

      @lcd.set_lines(lines: lines, align: @align)

      if @options[:test]
        show_mocked_lcd()
      end
    end

    def show_mocked_lcd
      puts "[#{@hw_mock.get(row: 0).join}]"
      puts "[#{@hw_mock.get(row: 1).join}]"
    end

    def parse_arguments(argv)
      options = {}
      OptionParser.new do |opts|
        opts.banner = "Usage: odroid-lcd [options] [first line] [second line]"

        opts.on("-f", "--file=FILE", String, "Read content from a file") do |x|
          if x == nil
            puts opts
            exit 2
          end
          options[:file] = x
        end

        opts.on("--test", "Dry run test (does not update the screen)") do |x|
          options[:test] = x
        end

        opts.on("--align=ALIGN", String, "Align text: left, right, center") do |x|
          if x == nil
            puts opts
            exit 2
          end
          options[:align] = x
        end

        opts.on("-h", "--help", "Prints this help") do
          puts opts
          exit
        end

      end.parse!
      options
    end

    def read_file(filename)
      file = if (filename == '-')
        $stdin
      else
        File.open(filename, "r")
      end

      file.readlines.map {|line| line.chomp }
    end

  end
end


text:
// OutputRapDialog.cpp : ±¸Çö ÆÄÀÏÀÔ´Ï´Ù.
//

#include "stdafx.h"
#include "CrazyLang.h"
#include "OutputRapDialog.h"
#include "afxdialogex.h"

// OutputRapDialog ´ëÈ »óÀÚÀÔ´Ï´Ù.

IMPLEMENT_DYNAMIC(OutputRapDialog, CDialog)

OutputRapDialog::OutputRapDialog(CWnd* pParent /*=NULL*/)
	: CDialog(OutputRapDialog::IDD, pParent)
{

	count=6;

}

OutputRapDialog::~OutputRapDialog()
{
}

void OutputRapDialog::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_LIST3, Indication_Sysmbol);
	DDX_Control(pDX, IDC_LIST1, Indication_Memory);
}

BEGIN_MESSAGE_MAP(OutputRapDialog, CDialog)

ON_BN_CLICKED(IDC_BUTTON1, &OutputRapDialog::OnBnClickedButton1)
	ON_WM_ERASEBKGND()
END_MESSAGE_MAP()

// OutputRapDialog ¸Þ½ÃÁö 󸮱âÀÔ´Ï´Ù.

BOOL OutputRapDialog::OnInitDialog()
{
	CDialog::OnInitDialog();

	MoveWindow(0,0,644,638);//ÀÌ ÇÔ¼ö¸¦ »ç¿ëÇÏ¸é ´ëÈ»óÀÚ Å©±â¸¦ Á¶Á¤ ÇÒ¼ö Àֳ׿ä.

	backgroundindicate.LoadBitmapW(IDB_BITMAP5);

	DWORD dwSeed = ::GetTickCount();
	LVITEM item;
	::ZeroMemory(&item, sizeof(item));
	item.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_PARAM;

	Indication_Sysmbol.SetBkColor(RGB(0,0,0));

	ImgList.Create(48,48,ILC_COLOR32,14,0);

	CString strItem=_T("");
	icon=AfxGetApp()->LoadIcon(IDR_MAINFRAME);

	ImgList.Add(AfxGetApp()->LoadIcon(IDI_ICON1));
	ImgList.Add(AfxGetApp()->LoadIcon(IDI_ICON3));
	ImgList.Add(AfxGetApp()->LoadIcon(IDI_ICON4));
	ImgList.Add(AfxGetApp()->LoadIcon(IDI_ICON5));
	ImgList.Add(AfxGetApp()->LoadIcon(IDI_ICON6));
	ImgList.Add(AfxGetApp()->LoadIcon(IDI_ICON7));
	ImgList.Add(AfxGetApp()->LoadIcon(IDI_ICON9));

	ImgList.Add(AfxGetApp()->LoadIcon(IDI_ICON8));// ºóÀ̹ÌÁö
	ImgList.Add(AfxGetApp()->LoadIcon(IDI_ICON8));
	ImgList.Add(AfxGetApp()->LoadIcon(IDI_ICON8));
	ImgList.Add(AfxGetApp()->LoadIcon(IDI_ICON8));
	ImgList.Add(AfxGetApp()->LoadIcon(IDI_ICON8));
	ImgList.Add(AfxGetApp()->LoadIcon(IDI_ICON8));
	ImgList.Add(AfxGetApp()->LoadIcon(IDI_ICON8));// ºóÀ̹ÌÁö

	for(int i=0; i<14; i++)
	{

	item.pszText = strItem.GetBuffer();
	item.iItem = i;
	item.iSubItem=0;
	item.iImage = i;
	Indication_Sysmbol.InsertItem(&item);

	}

	Indication_Sysmbol.SetImageList(&ImgList,LVSIL_NORMAL);

	CString strItemMemory=_T("");
	LVITEM Memoryitem;
	Indication_Memory.InsertColumn(0, _T("MemoryAddress"), LVCFMT_LEFT, 273);
	Indication_Memory.InsertColumn(1, _T("Data"), LVCFMT_LEFT, 273);

	Indication_Memory.SetExtendedStyle(LVS_EX_FULLROWSELECT|LVS_EX_HEADERDRAGDROP|LVS_EX_GRIDLINES);
	Indication_Memory.ModifyStyle(LVS_TYPEMASK, LVS_REPORT);

	return TRUE;  // return TRUE unless you set the focus to a control
	// ¿¹¿Ü: OCX ¼Ó¼º ÆäÀÌÁö´Â FALSE¸¦ ¹ÝȯÇØ¾ß ÇÕ´Ï´Ù.
}

void OutputRapDialog::DebugTextResult(CString Address, CString Value)
{

		 Indication_Memory.InsertItem(0,Address);
		 Indication_Memory.SetItemText(0,1,Value);

}

void OutputRapDialog::DebugTextClear()
{
		Indication_Memory.DeleteAllItems();
}

void OutputRapDialog::OnBnClickedButton1()
{

	HICON icon=AfxGetApp()->LoadIcon(IDI_ICON2);
	HICON nullicon=AfxGetApp()->LoadIcon(IDI_ICON8);

	if(count!=6){
	ImgList.Replace(count,nullicon);
	}
	count++;
	ImgList.Replace(count,nullicon);

		Indication_Memory.SetItemState( -1, 0, LVIS_SELECTED|LVIS_FOCUSED );
		Indication_Memory.SetItemState(count-7, LVIS_FOCUSED | LVIS_SELECTED, LVIS_FOCUSED | LVIS_SELECTED);
		Indication_Memory.EnsureVisible(count-7, false);
		Indication_Memory.SetFocus();
		ImgList.Replace(count,icon);

	if(count==14)
	{

		count=6;

	}

	Invalidate();

	// TODO: ¿©±â¿¡ ÄÁÆ®·Ñ ¾Ë¸² 󸮱â Äڵ带 Ãß°¡ÇÕ´Ï´Ù.
}

BOOL OutputRapDialog::OnEraseBkgnd(CDC* pDC)
{
	// TODO: ¿©±â¿¡ ¸Þ½ÃÁö 󸮱â Äڵ带 Ãß°¡ ¹×/¶Ç´Â ±âº»°ªÀ» È£ÃâÇÕ´Ï´Ù.

if(!backgroundindicate.m_hObject)
		true;

	CRect rect;
	GetClientRect(&rect);

	CDC dc;
	dc.CreateCompatibleDC(pDC);
	CBitmap * pOldBitmap=dc.SelectObject(&backgroundindicate);

	BITMAP bmap;
	backgroundindicate.GetBitmap(&bmap);

	pDC->StretchBlt(0,0,rect.Width(),rect.Height(),&dc,0,0,bmap.bmWidth,bmap.bmHeight,SRCCOPY);

	dc.SelectObject(pOldBitmap);

		return true;
	//return CDialog::OnEraseBkgnd(pDC);
}


text:
import {Component} from './Component';
/**
 * Definition of a ComponentBinder object
 *
 * @export
 * @interface IComponentBinder
 */
export interface IComponentBinder{

    /**
     * Parse and process the declarative bindings from a HTML view/template
     *
     * @param {HTMLElement} view
     * @returns {Promise<boolean>}
     */
    executeBindings(view:HTMLElement):Promise<Component[]>;

    /**
     * Binds a component and attaches it to a HTML element
     *
     * @param {string} componentPath
     * @param {HTMLElement} parentElement
     */
     bind(componentPath:string,parentElement:HTMLElement):Promise<Component>;

    /**
     * Bind a viewmodel against it's view and adds it to the parent view;
     *
     * @param {*} viewModelInstance
     * @param {HTMLElement} view
     * @param {HTMLElement} parentView
     * @returns {Promise<Component>}
     */
    bindModel(viewModelInstance: any, view: HTMLElement,parentView:HTMLElement): Promise<Component>;

    /**
     * Remove the elements binded to a HTML view/template
     *
     * @returns {Promise<boolean>}
     */
    unbind():Promise<boolean>;

}


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

package com.google.gerrit.server.schema;

import com.google.gerrit.common.Nullable;
import com.google.gerrit.entities.AccountGroup;
import com.google.gerrit.entities.GroupReference;
import com.google.gerrit.entities.InternalGroup;
import com.google.gerrit.git.RefUpdateUtil;
import com.google.gerrit.server.account.ServiceUserClassifier;
import com.google.gerrit.server.config.AllUsersName;
import com.google.gerrit.server.extensions.events.GitReferenceUpdated;
import com.google.gerrit.server.git.meta.MetaDataUpdate;
import com.google.gerrit.server.group.db.AuditLogFormatter;
import com.google.gerrit.server.group.db.GroupConfig;
import com.google.gerrit.server.group.db.GroupDelta;
import com.google.gerrit.server.group.db.GroupNameNotes;
import com.google.gerrit.server.index.group.GroupIndex;
import com.google.gerrit.server.index.group.GroupIndexCollection;
import java.io.IOException;
import java.util.Optional;
import org.eclipse.jgit.lib.BatchRefUpdate;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Repository;

/**
 * Schema 184 for Gerrit metadata.
 *
 * <p>Upgrading to this schema version will rename the {@code Non-Interactive Users} group to {@code
 * Service Users}.
 */
public class Schema_184 implements NoteDbSchemaVersion {
  @Override
  public void upgrade(Arguments args, UpdateUI ui) throws Exception {
    try (Repository allUsersRepo = args.repoManager.openRepository(args.allUsers)) {
      AccountGroup.NameKey newName = AccountGroup.nameKey(ServiceUserClassifier.SERVICE_USERS);
      Optional<GroupReference> nonInteractiveUsers =
          GroupNameNotes.loadAllGroups(allUsersRepo).stream()
              .filter(g -> g.getName().equals("Non-Interactive Users"))
              .findAny();
      if (!nonInteractiveUsers.isPresent()) {
        return;
      }

      GroupNameNotes newNameNotes =
          GroupNameNotes.forRename(
              args.allUsers,
              allUsersRepo,
              nonInteractiveUsers.get().getUUID(),
              AccountGroup.nameKey(nonInteractiveUsers.get().getName()),
              newName);
      GroupConfig groupConfig =
          GroupConfig.loadForGroup(
              args.allUsers, allUsersRepo, nonInteractiveUsers.get().getUUID());
      groupConfig.setGroupDelta(
          GroupDelta.builder().setName(newName).build(),
          AuditLogFormatter.createPartiallyWorkingFallBack());
      commit(args.allUsers, args.serverUser, allUsersRepo, groupConfig, newNameNotes);
      index(
          args.groupIndexCollection,
          groupConfig
              .getLoadedGroup()
              .orElseThrow(
                  () -> new IllegalStateException("Created group wasn't automatically loaded")));
    }
  }

  private void commit(
      AllUsersName allUsersName,
      PersonIdent serverUser,
      Repository allUsersRepo,
      GroupConfig groupConfig,
      GroupNameNotes groupNameNotes)
      throws IOException {
    BatchRefUpdate batchRefUpdate = allUsersRepo.getRefDatabase().newBatchUpdate();
    try (MetaDataUpdate metaDataUpdate =
        createMetaDataUpdate(allUsersName, serverUser, allUsersRepo, batchRefUpdate)) {
      groupConfig.commit(metaDataUpdate);
    }
    // MetaDataUpdates unfortunately can't be reused. -> Create a new one.
    try (MetaDataUpdate metaDataUpdate =
        createMetaDataUpdate(allUsersName, serverUser, allUsersRepo, batchRefUpdate)) {
      groupNameNotes.commit(metaDataUpdate);
    }
    RefUpdateUtil.executeChecked(batchRefUpdate, allUsersRepo);
  }

  private MetaDataUpdate createMetaDataUpdate(
      AllUsersName allUsersName,
      PersonIdent serverUser,
      Repository allUsersRepo,
      @Nullable BatchRefUpdate batchRefUpdate) {
    MetaDataUpdate metaDataUpdate =
        new MetaDataUpdate(
            GitReferenceUpdated.DISABLED, allUsersName, allUsersRepo, batchRefUpdate);
    metaDataUpdate.getCommitBuilder().setAuthor(serverUser);
    metaDataUpdate.getCommitBuilder().setCommitter(serverUser);
    return metaDataUpdate;
  }

  private void index(GroupIndexCollection indexCollection, InternalGroup group) {
    for (GroupIndex groupIndex : indexCollection.getWriteIndexes()) {
      groupIndex.replace(group);
    }
  }
}


text:
import sys, os
import argparse
import subprocess
import logging
import ConfigParser

VALID_TYPES = ['image/jpeg', 'image/gif', 'image/tiff', 'image/png']
INVALID_TYPES = ['application/pdf']

# Settings recommended as a starting point by Jon Stroop. See https://groups.google.com/forum/?hl=en#!searchin/iiif-discuss/kdu_compress/iiif-discuss/OFzWFLaWVsE/wF2HaykHcd0J
KDU_COMPRESS_BASE_OPTS = [
                            "-quiet",
                            "-rate", "2.4,1.48331273,.91673033,.56657224,.35016049,.21641118,.13374944,.08266171",
                            "Creversible=yes",
                            "Clevels=7",
                            "Cblk={64,64}",
                            "Cuse_sop=yes",
                            "Cuse_eph=yes",
                            "Corder=RLCP",
                            "ORGgen_plt=yes",
                            "ORGtparts=R",
                            "Stiles={1024,1024}",
                            "-double_buffering", "10",
                            "-num_threads", "4",
                            "-no_weights"
                            ]

KDU_COMPRESS_DEFAULT_OPTS = KDU_COMPRESS_BASE_OPTS[:]
KDU_COMPRESS_DEFAULT_OPTS.extend(["-jp2_space", "sRGB"])

class Convert(object):

    '''
        utilities for use in converting an image file to jp2 format
    '''

    def __init__(self):

        self.logger = logging.getLogger(__name__)

        self.tiffcp_location = '/apps/nuxeo/pkg/bin/tiffcp'
        self.magick_convert_location = '/apps/nuxeo/pkg/bin/convert'
        self.kdu_compress_location = '/apps/nuxeo/kakadu/kdu_compress'
        self.tiff2rgba_location = '/apps/nuxeo/pkg/bin/tiff2rgba'
        self.tifficc_location = '/apps/nuxeo/pkg/bin/tifficc'

    def _pre_check(self, mimetype):
        ''' do a basic pre-check on the object to see if we think it's something know how to deal with '''
        # see if we recognize this mime type
        if mimetype in VALID_TYPES:
            passed = True
            msg = "Mime-type '{}' was pre-checked and recognized as something we can try to convert.".format(mimetype)
            self.logger.info(msg)
        elif mimetype in INVALID_TYPES:
            passed = False
            msg = "Mime-type '{}' was pre-checked and recognized as something we don't want to convert.".format(mimetype)
            self.logger.info(msg)
        else:
            passed = False
            msg = "Mime-type '{}' was unrecognized. We don't know how to deal with this".format(mimetype)
            self.logger.warning(msg)

        return passed, msg

    def _uncompress_tiff(self, compressed_path, uncompressed_path):
        ''' uncompress a tiff using tiffcp. See http://www.libtiff.org/tools.html '''
        try:
            subprocess.check_output([self.tiffcp_location,
                "-c", "none",
                compressed_path,
                uncompressed_path])
            uncompressed = True
            msg = 'File uncompressed. Input: {}, output: {}'.format(compressed_path, uncompressed_path)
            self.logger.info(msg)
        except subprocess.CalledProcessError, e:
            uncompressed = False
            msg = '`tiffcp` command failed: {}\nreturncode was: {}\noutput was: {}'.format(e.cmd, e.returncode, e.output)
            self.logger.error(msg)

        return uncompressed, msg

    def _tiff_to_jp2(self, tiff_path, jp2_path):
        ''' convert a tiff to jp2 using kdu_compress. tiff must be uncompressed.'''
        basic_args = [self.kdu_compress_location, "-i", tiff_path, "-o", jp2_path]
        default_args = basic_args[:]
        default_args.extend(KDU_COMPRESS_DEFAULT_OPTS)
        alt_args = basic_args[:]
        alt_args.extend(KDU_COMPRESS_BASE_OPTS)

        try:
            subprocess.check_output(default_args)
            converted = True
            msg = '{} converted to {}'.format(tiff_path, jp2_path)
            self.logger.info(msg)
        except subprocess.CalledProcessError, e:
            self.logger.info('A kdu_compress command failed. Trying alternate.')
            try:
                subprocess.check_output(alt_args)
                converted = True
                msg = '{} converted to {}'.format(tiff_path, jp2_path)
                self.logger.info(msg)
            except subprocess.CalledProcessError, e:
                converted = False
                msg = 'kdu_compress command failed: {}\nreturncode was: {}\noutput was: {}'.format(e.cmd, e.returncode, e.output)
                self.logger.error(msg)

        return converted, msg

    def _pre_convert(self, input_path, output_path):
        '''
         convert file using ImageMagick `convert`: http://www.imagemagick.org/script/convert.php
        '''
        try:
            subprocess.check_output([self.magick_convert_location,
                         "-compress", "None",
                         "-quality", "100",
                         input_path,
                         output_path])
            preconverted = True
            msg = 'Used ImagMagick convert to convert {} to {}'.format(input_path, output_path)
            self.logger.info(msg)
        except subprocess.CalledProcessError, e:
            preconverted = False
            msg = 'ImageMagic `convert` command failed: {}\nreturncode was: {}\noutput was: {}'.format(e.cmd, e.returncode, e.output)
            self.logger.error(msg)

        return preconverted, msg

    def _tiff_to_srgb_libtiff(self, input_path, output_path):
        '''
        convert color profile to sRGB using libtiff's `tiff2rgba` tool
        '''
        try:
            subprocess.check_output([self.tiff2rgba_location,
                                     "-c", "none",
                                     input_path,
                                     output_path])
            to_srgb = True
            msg = "Used tiff2rgba to convert {} to {}, with color profile sRGB (if not already sRGB)".format(input_path, output_path)
            self.logger.info(msg)
        except subprocess.CalledProcessError, e:
            to_srgb = False
            msg = 'libtiff `tiff2rgba` command failed: {}\nreturncode was: {}\noutput was: {}'.format(e.cmd, e.returncode, e.output)
            self.logger.error(msg)

        return to_srgb, msg

    def _tiff_to_srgb_little_cms(self, input_path, output_path):
        '''
        convert color profile to sRGB using Little CMS's `tifficc` ICC profile applier tool.
        '''
        try:
            subprocess.check_output([self.tifficc_location,
                     input_path,
                     output_path])
            to_srgb = True
            msg = "Used tifficc to convert {} to {}, with color profile sRGB (if not already sRGB)".format(input_path, output_path)
            self.logger.info(msg)
        except subprocess.CalledProcessError, e:
            to_srgb = False
            msg = 'Little CMS `tifficc` command failed: {}\nreturncode was: {}\noutput was: {}'.format(e.cmd, e.returncode, e.output)
            self.logger.error(msg)

        return to_srgb, msg

def main(argv=None):
    pass

if __name__ == "__main__":
    sys.exit(main())


text:
class Role
  def self.user_is_at_least_a?(user, role)
    roles = User.roles
    roles[user.role] >= roles[role]
  end

  def self.highest_role_for_users(*users)
    roles = User.roles
    users.inject(roles.keys.first) do |max_role, user|
      if roles[user.role] > roles[max_role]
        user.role
      else
        max_role
      end
    end
  end

  def self.mentionable_roles
    @mentionable_roles ||= User.roles.keys
      .reject { |r| r == 'curator' }
  end
end


text:
#include "emu10k1_synth_local.h"
#include <linux/init.h>

MODULE_AUTHOR("Takashi Iwai");
MODULE_DESCRIPTION("Routines for control of EMU10K1 WaveTable synth");
MODULE_LICENSE("GPL");

/*
 * create a new hardware dependent device for Emu10k1
 */
static int snd_emu10k1_synth_new_device(struct snd_seq_device *dev)
{
	struct snd_emux *emu;
	struct snd_emu10k1 *hw;
	struct snd_emu10k1_synth_arg *arg;
	unsigned long flags;

	arg = SNDRV_SEQ_DEVICE_ARGPTR(dev);
	if (arg == NULL)
		return -EINVAL;

	if (arg->seq_ports <= 0)
		return 0; /* nothing */
	if (arg->max_voices < 1)
		arg->max_voices = 1;
	else if (arg->max_voices > 64)
		arg->max_voices = 64;

	if (snd_emux_new(&emu) < 0)
		return -ENOMEM;

	snd_emu10k1_ops_setup(emu);
	emu->hw = hw = arg->hwptr;
	emu->max_voices = arg->max_voices;
	emu->num_ports = arg->seq_ports;
	emu->pitch_shift = -501;
	emu->memhdr = hw->memhdr;
	emu->midi_ports = arg->seq_ports < 2 ? arg->seq_ports : 2; /* maximum two ports */
	emu->midi_devidx = hw->audigy ? 2 : 1; /* audigy has two external midis */
	emu->linear_panning = 0;
	emu->hwdep_idx = 2; /* FIXED */

	if (snd_emux_register(emu, dev->card, arg->index, "Emu10k1") < 0) {
		snd_emux_free(emu);
		emu->hw = NULL;
		return -ENOMEM;
	}

	spin_lock_irqsave(&hw->voice_lock, flags);
	hw->synth = emu;
	hw->get_synth_voice = snd_emu10k1_synth_get_voice;
	spin_unlock_irqrestore(&hw->voice_lock, flags);

	dev->driver_data = emu;

	return 0;
}

static int snd_emu10k1_synth_delete_device(struct snd_seq_device *dev)
{
	struct snd_emux *emu;
	struct snd_emu10k1 *hw;
	unsigned long flags;

	if (dev->driver_data == NULL)
		return 0; /* not registered actually */

	emu = dev->driver_data;

	hw = emu->hw;
	spin_lock_irqsave(&hw->voice_lock, flags);
	hw->synth = NULL;
	hw->get_synth_voice = NULL;
	spin_unlock_irqrestore(&hw->voice_lock, flags);

	snd_emux_free(emu);
	return 0;
}

/*
 *  INIT part
 */

static int __init alsa_emu10k1_synth_init(void)
{

	static struct snd_seq_dev_ops ops = {
		snd_emu10k1_synth_new_device,
		snd_emu10k1_synth_delete_device,
	};
	return snd_seq_device_register_driver(SNDRV_SEQ_DEV_ID_EMU10K1_SYNTH, &ops,
					      sizeof(struct snd_emu10k1_synth_arg));
}

static void __exit alsa_emu10k1_synth_exit(void)
{
	snd_seq_device_unregister_driver(SNDRV_SEQ_DEV_ID_EMU10K1_SYNTH);
}

module_init(alsa_emu10k1_synth_init)
module_exit(alsa_emu10k1_synth_exit)


text:
//
//  ZQTableChartController.m
//  QDNSHNEW
//
//  Created by zhaozq on 15/3/17.
//  Copyright (c) 2015年 QDNSHNEW. All rights reserved.
//

#import "ZQTableChartController.h"
#define kScreenHeight     [UIScreen mainScreen].bounds.size.height
#define kScreenWidth      [UIScreen mainScreen].bounds.size.width
@interface ZQTableChartController () <ZQTableChartDelegate>

@end

@implementation ZQTableChartController{

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];

    NSString * path = [[NSBundle mainBundle] pathForResource:@"data" ofType:@""];
    NSData *data = [NSData dataWithContentsOfFile:path];
    NSError *error;
    NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
    NSLog(@"%@",error);
    if (dataDict) {
        [self configTableChartWithDataArray:dataDict[@"dataList"] infoPlist:@"BadLoanTable02" scrollStyle:0];  //BadLoanTable  BadLoanTable01 BadLoanTable02
    }

}

- (void)configTableChartWithDataArray:(NSArray *)dataArr infoPlist:(NSString *)plist scrollStyle:(ZQTableScrollStyle)scrollStyle
{
    if (_tableChart) {
        [_tableChart removeFromSuperview];
    }

    NSString * path = [[NSBundle mainBundle] pathForResource:plist ofType:@".plist"];
    NSDictionary *data = [[NSDictionary alloc] initWithContentsOfFile:path];
    NSArray *leftTitles = [data objectForKey:@"leftTitles"];
    NSArray *rightTitles = [data objectForKey:@"rightTitles"];
    NSArray *leftKeys = [data objectForKey:@"leftKeys"];
    NSArray *rightKeys = [data objectForKey:@"rightKeys"];
    NSArray *widths = [data objectForKey:@"widths"];

    _tableChart = [[ZQTableChartView alloc] initWithFrame:CGRectMake(0, 20, kScreenWidth, kScreenHeight - 20) dataArray:dataArr leftTitles:leftTitles rightTitles:rightTitles leftKeys:leftKeys rightKeys:rightKeys widths:widths delegate:self scrollStyle:scrollStyle];
    _tableChart.tableChartDelegate = self;
    [self.view addSubview:_tableChart];
}

- (void)tableChartHeaderClicked:(NSInteger)tag
{
    NSLog(@"tableChartHeaderClicked  tag:%zd",tag);
}

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

/*
#pragma mark - Navigation

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

@end