text:
/*
 * Intel Cache Quality-of-Service Monitoring (CQM) support.
 *
 * Based very, very heavily on work by Peter Zijlstra.
 */

#include <linux/perf_event.h>
#include <linux/slab.h>
#include <asm/cpu_device_id.h>
#include "perf_event.h"

#define MSR_IA32_PQR_ASSOC	0x0c8f
#define MSR_IA32_QM_CTR		0x0c8e
#define MSR_IA32_QM_EVTSEL	0x0c8d

static u32 cqm_max_rmid = -1;
static unsigned int cqm_l3_scale; /* supposedly cacheline size */

/**
 * struct intel_pqr_state - State cache for the PQR MSR
 * @rmid:		The cached Resource Monitoring ID
 * @closid:		The cached Class Of Service ID
 * @rmid_usecnt:	The usage counter for rmid
 *
 * The upper 32 bits of MSR_IA32_PQR_ASSOC contain closid and the
 * lower 10 bits rmid. The update to MSR_IA32_PQR_ASSOC always
 * contains both parts, so we need to cache them.
 *
 * The cache also helps to avoid pointless updates if the value does
 * not change.
 */
struct intel_pqr_state {
	u32			rmid;
	u32			closid;
	int			rmid_usecnt;
};

/*
 * The cached intel_pqr_state is strictly per CPU and can never be
 * updated from a remote CPU. Both functions which modify the state
 * (intel_cqm_event_start and intel_cqm_event_stop) are called with
 * interrupts disabled, which is sufficient for the protection.
 */
static DEFINE_PER_CPU(struct intel_pqr_state, pqr_state);

/*
 * Protects cache_cgroups and cqm_rmid_free_lru and cqm_rmid_limbo_lru.
 * Also protects event->hw.cqm_rmid
 *
 * Hold either for stability, both for modification of ->hw.cqm_rmid.
 */
static DEFINE_MUTEX(cache_mutex);
static DEFINE_RAW_SPINLOCK(cache_lock);

/*
 * Groups of events that have the same target(s), one RMID per group.
 */
static LIST_HEAD(cache_groups);

/*
 * Mask of CPUs for reading CQM values. We only need one per-socket.
 */
static cpumask_t cqm_cpumask;

#define RMID_VAL_ERROR		(1ULL << 63)
#define RMID_VAL_UNAVAIL	(1ULL << 62)

#define QOS_L3_OCCUP_EVENT_ID	(1 << 0)

#define QOS_EVENT_MASK	QOS_L3_OCCUP_EVENT_ID

/*
 * This is central to the rotation algorithm in __intel_cqm_rmid_rotate().
 *
 * This rmid is always free and is guaranteed to have an associated
 * near-zero occupancy value, i.e. no cachelines are tagged with this
 * RMID, once __intel_cqm_rmid_rotate() returns.
 */
static u32 intel_cqm_rotation_rmid;

#define INVALID_RMID		(-1)

/*
 * Is @rmid valid for programming the hardware?
 *
 * rmid 0 is reserved by the hardware for all non-monitored tasks, which
 * means that we should never come across an rmid with that value.
 * Likewise, an rmid value of -1 is used to indicate "no rmid currently
 * assigned" and is used as part of the rotation code.
 */
static inline bool __rmid_valid(u32 rmid)
{
	if (!rmid || rmid == INVALID_RMID)
		return false;

	return true;
}

static u64 __rmid_read(u32 rmid)
{
	u64 val;

	/*
	 * Ignore the SDM, this thing is _NOTHING_ like a regular perfcnt,
	 * it just says that to increase confusion.
	 */
	wrmsr(MSR_IA32_QM_EVTSEL, QOS_L3_OCCUP_EVENT_ID, rmid);
	rdmsrl(MSR_IA32_QM_CTR, val);

	/*
	 * Aside from the ERROR and UNAVAIL bits, assume this thing returns
	 * the number of cachelines tagged with @rmid.
	 */
	return val;
}

enum rmid_recycle_state {
	RMID_YOUNG = 0,
	RMID_AVAILABLE,
	RMID_DIRTY,
};

struct cqm_rmid_entry {
	u32 rmid;
	enum rmid_recycle_state state;
	struct list_head list;
	unsigned long queue_time;
};

/*
 * cqm_rmid_free_lru - A least recently used list of RMIDs.
 *
 * Oldest entry at the head, newest (most recently used) entry at the
 * tail. This list is never traversed, it's only used to keep track of
 * the lru order. That is, we only pick entries of the head or insert
 * them on the tail.
 *
 * All entries on the list are 'free', and their RMIDs are not currently
 * in use. To mark an RMID as in use, remove its entry from the lru
 * list.
 *
 *
 * cqm_rmid_limbo_lru - list of currently unused but (potentially) dirty RMIDs.
 *
 * This list is contains RMIDs that no one is currently using but that
 * may have a non-zero occupancy value associated with them. The
 * rotation worker moves RMIDs from the limbo list to the free list once
 * the occupancy value drops below __intel_cqm_threshold.
 *
 * Both lists are protected by cache_mutex.
 */
static LIST_HEAD(cqm_rmid_free_lru);
static LIST_HEAD(cqm_rmid_limbo_lru);

/*
 * We use a simple array of pointers so that we can lookup a struct
 * cqm_rmid_entry in O(1). This alleviates the callers of __get_rmid()
 * and __put_rmid() from having to worry about dealing with struct
 * cqm_rmid_entry - they just deal with rmids, i.e. integers.
 *
 * Once this array is initialized it is read-only. No locks are required
 * to access it.
 *
 * All entries for all RMIDs can be looked up in the this array at all
 * times.
 */
static struct cqm_rmid_entry **cqm_rmid_ptrs;

static inline struct cqm_rmid_entry *__rmid_entry(u32 rmid)
{
	struct cqm_rmid_entry *entry;

	entry = cqm_rmid_ptrs[rmid];
	WARN_ON(entry->rmid != rmid);

	return entry;
}

/*
 * Returns < 0 on fail.
 *
 * We expect to be called with cache_mutex held.
 */
static u32 __get_rmid(void)
{
	struct cqm_rmid_entry *entry;

	lockdep_assert_held(&cache_mutex);

	if (list_empty(&cqm_rmid_free_lru))
		return INVALID_RMID;

	entry = list_first_entry(&cqm_rmid_free_lru, struct cqm_rmid_entry, list);
	list_del(&entry->list);

	return entry->rmid;
}

static void __put_rmid(u32 rmid)
{
	struct cqm_rmid_entry *entry;

	lockdep_assert_held(&cache_mutex);

	WARN_ON(!__rmid_valid(rmid));
	entry = __rmid_entry(rmid);

	entry->queue_time = jiffies;
	entry->state = RMID_YOUNG;

	list_add_tail(&entry->list, &cqm_rmid_limbo_lru);
}

static int intel_cqm_setup_rmid_cache(void)
{
	struct cqm_rmid_entry *entry;
	unsigned int nr_rmids;
	int r = 0;

	nr_rmids = cqm_max_rmid + 1;
	cqm_rmid_ptrs = kmalloc(sizeof(struct cqm_rmid_entry *) *
				nr_rmids, GFP_KERNEL);
	if (!cqm_rmid_ptrs)
		return -ENOMEM;

	for (; r <= cqm_max_rmid; r++) {
		struct cqm_rmid_entry *entry;

		entry = kmalloc(sizeof(*entry), GFP_KERNEL);
		if (!entry)
			goto fail;

		INIT_LIST_HEAD(&entry->list);
		entry->rmid = r;
		cqm_rmid_ptrs[r] = entry;

		list_add_tail(&entry->list, &cqm_rmid_free_lru);
	}

	/*
	 * RMID 0 is special and is always allocated. It's used for all
	 * tasks that are not monitored.
	 */
	entry = __rmid_entry(0);
	list_del(&entry->list);

	mutex_lock(&cache_mutex);
	intel_cqm_rotation_rmid = __get_rmid();
	mutex_unlock(&cache_mutex);

	return 0;
fail:
	while (r--)
		kfree(cqm_rmid_ptrs[r]);

	kfree(cqm_rmid_ptrs);
	return -ENOMEM;
}

/*
 * Determine if @a and @b measure the same set of tasks.
 *
 * If @a and @b measure the same set of tasks then we want to share a
 * single RMID.
 */
static bool __match_event(struct perf_event *a, struct perf_event *b)
{
	/* Per-cpu and task events don't mix */
	if ((a->attach_state & PERF_ATTACH_TASK) !=
	    (b->attach_state & PERF_ATTACH_TASK))
		return false;

#ifdef CONFIG_CGROUP_PERF
	if (a->cgrp != b->cgrp)
		return false;
#endif

	/* If not task event, we're machine wide */
	if (!(b->attach_state & PERF_ATTACH_TASK))
		return true;

	/*
	 * Events that target same task are placed into the same cache group.
	 */
	if (a->hw.target == b->hw.target)
		return true;

	/*
	 * Are we an inherited event?
	 */
	if (b->parent == a)
		return true;

	return false;
}

#ifdef CONFIG_CGROUP_PERF
static inline struct perf_cgroup *event_to_cgroup(struct perf_event *event)
{
	if (event->attach_state & PERF_ATTACH_TASK)
		return perf_cgroup_from_task(event->hw.target, event->ctx);

	return event->cgrp;
}
#endif

/*
 * Determine if @a's tasks intersect with @b's tasks
 *
 * There are combinations of events that we explicitly prohibit,
 *
 *		   PROHIBITS
 *     system-wide    -> 	cgroup and task
 *     cgroup 	      ->	system-wide
 *     		      ->	task in cgroup
 *     task 	      -> 	system-wide
 *     		      ->	task in cgroup
 *
 * Call this function before allocating an RMID.
 */
static bool __conflict_event(struct perf_event *a, struct perf_event *b)
{
#ifdef CONFIG_CGROUP_PERF
	/*
	 * We can have any number of cgroups but only one system-wide
	 * event at a time.
	 */
	if (a->cgrp && b->cgrp) {
		struct perf_cgroup *ac = a->cgrp;
		struct perf_cgroup *bc = b->cgrp;

		/*
		 * This condition should have been caught in
		 * __match_event() and we should be sharing an RMID.
		 */
		WARN_ON_ONCE(ac == bc);

		if (cgroup_is_descendant(ac->css.cgroup, bc->css.cgroup) ||
		    cgroup_is_descendant(bc->css.cgroup, ac->css.cgroup))
			return true;

		return false;
	}

	if (a->cgrp || b->cgrp) {
		struct perf_cgroup *ac, *bc;

		/*
		 * cgroup and system-wide events are mutually exclusive
		 */
		if ((a->cgrp && !(b->attach_state & PERF_ATTACH_TASK)) ||
		    (b->cgrp && !(a->attach_state & PERF_ATTACH_TASK)))
			return true;

		/*
		 * Ensure neither event is part of the other's cgroup
		 */
		ac = event_to_cgroup(a);
		bc = event_to_cgroup(b);
		if (ac == bc)
			return true;

		/*
		 * Must have cgroup and non-intersecting task events.
		 */
		if (!ac || !bc)
			return false;

		/*
		 * We have cgroup and task events, and the task belongs
		 * to a cgroup. Check for for overlap.
		 */
		if (cgroup_is_descendant(ac->css.cgroup, bc->css.cgroup) ||
		    cgroup_is_descendant(bc->css.cgroup, ac->css.cgroup))
			return true;

		return false;
	}
#endif
	/*
	 * If one of them is not a task, same story as above with cgroups.
	 */
	if (!(a->attach_state & PERF_ATTACH_TASK) ||
	    !(b->attach_state & PERF_ATTACH_TASK))
		return true;

	/*
	 * Must be non-overlapping.
	 */
	return false;
}

struct rmid_read {
	u32 rmid;
	atomic64_t value;
};

static void __intel_cqm_event_count(void *info);

/*
 * Exchange the RMID of a group of events.
 */
static u32 intel_cqm_xchg_rmid(struct perf_event *group, u32 rmid)
{
	struct perf_event *event;
	struct list_head *head = &group->hw.cqm_group_entry;
	u32 old_rmid = group->hw.cqm_rmid;

	lockdep_assert_held(&cache_mutex);

	/*
	 * If our RMID is being deallocated, perform a read now.
	 */
	if (__rmid_valid(old_rmid) && !__rmid_valid(rmid)) {
		struct rmid_read rr = {
			.value = ATOMIC64_INIT(0),
			.rmid = old_rmid,
		};

		on_each_cpu_mask(&cqm_cpumask, __intel_cqm_event_count,
				 &rr, 1);
		local64_set(&group->count, atomic64_read(&rr.value));
	}

	raw_spin_lock_irq(&cache_lock);

	group->hw.cqm_rmid = rmid;
	list_for_each_entry(event, head, hw.cqm_group_entry)
		event->hw.cqm_rmid = rmid;

	raw_spin_unlock_irq(&cache_lock);

	return old_rmid;
}

/*
 * If we fail to assign a new RMID for intel_cqm_rotation_rmid because
 * cachelines are still tagged with RMIDs in limbo, we progressively
 * increment the threshold until we find an RMID in limbo with <=
 * __intel_cqm_threshold lines tagged. This is designed to mitigate the
 * problem where cachelines tagged with an RMID are not steadily being
 * evicted.
 *
 * On successful rotations we decrease the threshold back towards zero.
 *
 * __intel_cqm_max_threshold provides an upper bound on the threshold,
 * and is measured in bytes because it's exposed to userland.
 */
static unsigned int __intel_cqm_threshold;
static unsigned int __intel_cqm_max_threshold;

/*
 * Test whether an RMID has a zero occupancy value on this cpu.
 */
static void intel_cqm_stable(void *arg)
{
	struct cqm_rmid_entry *entry;

	list_for_each_entry(entry, &cqm_rmid_limbo_lru, list) {
		if (entry->state != RMID_AVAILABLE)
			break;

		if (__rmid_read(entry->rmid) > __intel_cqm_threshold)
			entry->state = RMID_DIRTY;
	}
}

/*
 * If we have group events waiting for an RMID that don't conflict with
 * events already running, assign @rmid.
 */
static bool intel_cqm_sched_in_event(u32 rmid)
{
	struct perf_event *leader, *event;

	lockdep_assert_held(&cache_mutex);

	leader = list_first_entry(&cache_groups, struct perf_event,
				  hw.cqm_groups_entry);
	event = leader;

	list_for_each_entry_continue(event, &cache_groups,
				     hw.cqm_groups_entry) {
		if (__rmid_valid(event->hw.cqm_rmid))
			continue;

		if (__conflict_event(event, leader))
			continue;

		intel_cqm_xchg_rmid(event, rmid);
		return true;
	}

	return false;
}

/*
 * Initially use this constant for both the limbo queue time and the
 * rotation timer interval, pmu::hrtimer_interval_ms.
 *
 * They don't need to be the same, but the two are related since if you
 * rotate faster than you recycle RMIDs, you may run out of available
 * RMIDs.
 */
#define RMID_DEFAULT_QUEUE_TIME 250	/* ms */

static unsigned int __rmid_queue_time_ms = RMID_DEFAULT_QUEUE_TIME;

/*
 * intel_cqm_rmid_stabilize - move RMIDs from limbo to free list
 * @nr_available: number of freeable RMIDs on the limbo list
 *
 * Quiescent state; wait for all 'freed' RMIDs to become unused, i.e. no
 * cachelines are tagged with those RMIDs. After this we can reuse them
 * and know that the current set of active RMIDs is stable.
 *
 * Return %true or %false depending on whether stabilization needs to be
 * reattempted.
 *
 * If we return %true then @nr_available is updated to indicate the
 * number of RMIDs on the limbo list that have been queued for the
 * minimum queue time (RMID_AVAILABLE), but whose data occupancy values
 * are above __intel_cqm_threshold.
 */
static bool intel_cqm_rmid_stabilize(unsigned int *available)
{
	struct cqm_rmid_entry *entry, *tmp;

	lockdep_assert_held(&cache_mutex);

	*available = 0;
	list_for_each_entry(entry, &cqm_rmid_limbo_lru, list) {
		unsigned long min_queue_time;
		unsigned long now = jiffies;

		/*
		 * We hold RMIDs placed into limbo for a minimum queue
		 * time. Before the minimum queue time has elapsed we do
		 * not recycle RMIDs.
		 *
		 * The reasoning is that until a sufficient time has
		 * passed since we stopped using an RMID, any RMID
		 * placed onto the limbo list will likely still have
		 * data tagged in the cache, which means we'll probably
		 * fail to recycle it anyway.
		 *
		 * We can save ourselves an expensive IPI by skipping
		 * any RMIDs that have not been queued for the minimum
		 * time.
		 */
		min_queue_time = entry->queue_time +
			msecs_to_jiffies(__rmid_queue_time_ms);

		if (time_after(min_queue_time, now))
			break;

		entry->state = RMID_AVAILABLE;
		(*available)++;
	}

	/*
	 * Fast return if none of the RMIDs on the limbo list have been
	 * sitting on the queue for the minimum queue time.
	 */
	if (!*available)
		return false;

	/*
	 * Test whether an RMID is free for each package.
	 */
	on_each_cpu_mask(&cqm_cpumask, intel_cqm_stable, NULL, true);

	list_for_each_entry_safe(entry, tmp, &cqm_rmid_limbo_lru, list) {
		/*
		 * Exhausted all RMIDs that have waited min queue time.
		 */
		if (entry->state == RMID_YOUNG)
			break;

		if (entry->state == RMID_DIRTY)
			continue;

		list_del(&entry->list);	/* remove from limbo */

		/*
		 * The rotation RMID gets priority if it's
		 * currently invalid. In which case, skip adding
		 * the RMID to the the free lru.
		 */
		if (!__rmid_valid(intel_cqm_rotation_rmid)) {
			intel_cqm_rotation_rmid = entry->rmid;
			continue;
		}

		/*
		 * If we have groups waiting for RMIDs, hand
		 * them one now provided they don't conflict.
		 */
		if (intel_cqm_sched_in_event(entry->rmid))
			continue;

		/*
		 * Otherwise place it onto the free list.
		 */
		list_add_tail(&entry->list, &cqm_rmid_free_lru);
	}

	return __rmid_valid(intel_cqm_rotation_rmid);
}

/*
 * Pick a victim group and move it to the tail of the group list.
 * @next: The first group without an RMID
 */
static void __intel_cqm_pick_and_rotate(struct perf_event *next)
{
	struct perf_event *rotor;
	u32 rmid;

	lockdep_assert_held(&cache_mutex);

	rotor = list_first_entry(&cache_groups, struct perf_event,
				 hw.cqm_groups_entry);

	/*
	 * The group at the front of the list should always have a valid
	 * RMID. If it doesn't then no groups have RMIDs assigned and we
	 * don't need to rotate the list.
	 */
	if (next == rotor)
		return;

	rmid = intel_cqm_xchg_rmid(rotor, INVALID_RMID);
	__put_rmid(rmid);

	list_rotate_left(&cache_groups);
}

/*
 * Deallocate the RMIDs from any events that conflict with @event, and
 * place them on the back of the group list.
 */
static void intel_cqm_sched_out_conflicting_events(struct perf_event *event)
{
	struct perf_event *group, *g;
	u32 rmid;

	lockdep_assert_held(&cache_mutex);

	list_for_each_entry_safe(group, g, &cache_groups, hw.cqm_groups_entry) {
		if (group == event)
			continue;

		rmid = group->hw.cqm_rmid;

		/*
		 * Skip events that don't have a valid RMID.
		 */
		if (!__rmid_valid(rmid))
			continue;

		/*
		 * No conflict? No problem! Leave the event alone.
		 */
		if (!__conflict_event(group, event))
			continue;

		intel_cqm_xchg_rmid(group, INVALID_RMID);
		__put_rmid(rmid);
	}
}

/*
 * Attempt to rotate the groups and assign new RMIDs.
 *
 * We rotate for two reasons,
 *   1. To handle the scheduling of conflicting events
 *   2. To recycle RMIDs
 *
 * Rotating RMIDs is complicated because the hardware doesn't give us
 * any clues.
 *
 * There's problems with the hardware interface; when you change the
 * task:RMID map cachelines retain their 'old' tags, giving a skewed
 * picture. In order to work around this, we must always keep one free
 * RMID - intel_cqm_rotation_rmid.
 *
 * Rotation works by taking away an RMID from a group (the old RMID),
 * and assigning the free RMID to another group (the new RMID). We must
 * then wait for the old RMID to not be used (no cachelines tagged).
 * This ensure that all cachelines are tagged with 'active' RMIDs. At
 * this point we can start reading values for the new RMID and treat the
 * old RMID as the free RMID for the next rotation.
 *
 * Return %true or %false depending on whether we did any rotating.
 */
static bool __intel_cqm_rmid_rotate(void)
{
	struct perf_event *group, *start = NULL;
	unsigned int threshold_limit;
	unsigned int nr_needed = 0;
	unsigned int nr_available;
	bool rotated = false;

	mutex_lock(&cache_mutex);

again:
	/*
	 * Fast path through this function if there are no groups and no
	 * RMIDs that need cleaning.
	 */
	if (list_empty(&cache_groups) && list_empty(&cqm_rmid_limbo_lru))
		goto out;

	list_for_each_entry(group, &cache_groups, hw.cqm_groups_entry) {
		if (!__rmid_valid(group->hw.cqm_rmid)) {
			if (!start)
				start = group;
			nr_needed++;
		}
	}

	/*
	 * We have some event groups, but they all have RMIDs assigned
	 * and no RMIDs need cleaning.
	 */
	if (!nr_needed && list_empty(&cqm_rmid_limbo_lru))
		goto out;

	if (!nr_needed)
		goto stabilize;

	/*
	 * We have more event groups without RMIDs than available RMIDs,
	 * or we have event groups that conflict with the ones currently
	 * scheduled.
	 *
	 * We force deallocate the rmid of the group at the head of
	 * cache_groups. The first event group without an RMID then gets
	 * assigned intel_cqm_rotation_rmid. This ensures we always make
	 * forward progress.
	 *
	 * Rotate the cache_groups list so the previous head is now the
	 * tail.
	 */
	__intel_cqm_pick_and_rotate(start);

	/*
	 * If the rotation is going to succeed, reduce the threshold so
	 * that we don't needlessly reuse dirty RMIDs.
	 */
	if (__rmid_valid(intel_cqm_rotation_rmid)) {
		intel_cqm_xchg_rmid(start, intel_cqm_rotation_rmid);
		intel_cqm_rotation_rmid = __get_rmid();

		intel_cqm_sched_out_conflicting_events(start);

		if (__intel_cqm_threshold)
			__intel_cqm_threshold--;
	}

	rotated = true;

stabilize:
	/*
	 * We now need to stablize the RMID we freed above (if any) to
	 * ensure that the next time we rotate we have an RMID with zero
	 * occupancy value.
	 *
	 * Alternatively, if we didn't need to perform any rotation,
	 * we'll have a bunch of RMIDs in limbo that need stabilizing.
	 */
	threshold_limit = __intel_cqm_max_threshold / cqm_l3_scale;

	while (intel_cqm_rmid_stabilize(&nr_available) &&
	       __intel_cqm_threshold < threshold_limit) {
		unsigned int steal_limit;

		/*
		 * Don't spin if nobody is actively waiting for an RMID,
		 * the rotation worker will be kicked as soon as an
		 * event needs an RMID anyway.
		 */
		if (!nr_needed)
			break;

		/* Allow max 25% of RMIDs to be in limbo. */
		steal_limit = (cqm_max_rmid + 1) / 4;

		/*
		 * We failed to stabilize any RMIDs so our rotation
		 * logic is now stuck. In order to make forward progress
		 * we have a few options:
		 *
		 *   1. rotate ("steal") another RMID
		 *   2. increase the threshold
		 *   3. do nothing
		 *
		 * We do both of 1. and 2. until we hit the steal limit.
		 *
		 * The steal limit prevents all RMIDs ending up on the
		 * limbo list. This can happen if every RMID has a
		 * non-zero occupancy above threshold_limit, and the
		 * occupancy values aren't dropping fast enough.
		 *
		 * Note that there is prioritisation at work here - we'd
		 * rather increase the number of RMIDs on the limbo list
		 * than increase the threshold, because increasing the
		 * threshold skews the event data (because we reuse
		 * dirty RMIDs) - threshold bumps are a last resort.
		 */
		if (nr_available < steal_limit)
			goto again;

		__intel_cqm_threshold++;
	}

out:
	mutex_unlock(&cache_mutex);
	return rotated;
}

static void intel_cqm_rmid_rotate(struct work_struct *work);

static DECLARE_DELAYED_WORK(intel_cqm_rmid_work, intel_cqm_rmid_rotate);

static struct pmu intel_cqm_pmu;

static void intel_cqm_rmid_rotate(struct work_struct *work)
{
	unsigned long delay;

	__intel_cqm_rmid_rotate();

	delay = msecs_to_jiffies(intel_cqm_pmu.hrtimer_interval_ms);
	schedule_delayed_work(&intel_cqm_rmid_work, delay);
}

/*
 * Find a group and setup RMID.
 *
 * If we're part of a group, we use the group's RMID.
 */
static void intel_cqm_setup_event(struct perf_event *event,
				  struct perf_event **group)
{
	struct perf_event *iter;
	bool conflict = false;
	u32 rmid;

	list_for_each_entry(iter, &cache_groups, hw.cqm_groups_entry) {
		rmid = iter->hw.cqm_rmid;

		if (__match_event(iter, event)) {
			/* All tasks in a group share an RMID */
			event->hw.cqm_rmid = rmid;
			*group = iter;
			return;
		}

		/*
		 * We only care about conflicts for events that are
		 * actually scheduled in (and hence have a valid RMID).
		 */
		if (__conflict_event(iter, event) && __rmid_valid(rmid))
			conflict = true;
	}

	if (conflict)
		rmid = INVALID_RMID;
	else
		rmid = __get_rmid();

	event->hw.cqm_rmid = rmid;
}

static void intel_cqm_event_read(struct perf_event *event)
{
	unsigned long flags;
	u32 rmid;
	u64 val;

	/*
	 * Task events are handled by intel_cqm_event_count().
	 */
	if (event->cpu == -1)
		return;

	raw_spin_lock_irqsave(&cache_lock, flags);
	rmid = event->hw.cqm_rmid;

	if (!__rmid_valid(rmid))
		goto out;

	val = __rmid_read(rmid);

	/*
	 * Ignore this reading on error states and do not update the value.
	 */
	if (val & (RMID_VAL_ERROR | RMID_VAL_UNAVAIL))
		goto out;

	local64_set(&event->count, val);
out:
	raw_spin_unlock_irqrestore(&cache_lock, flags);
}

static void __intel_cqm_event_count(void *info)
{
	struct rmid_read *rr = info;
	u64 val;

	val = __rmid_read(rr->rmid);

	if (val & (RMID_VAL_ERROR | RMID_VAL_UNAVAIL))
		return;

	atomic64_add(val, &rr->value);
}

static inline bool cqm_group_leader(struct perf_event *event)
{
	return !list_empty(&event->hw.cqm_groups_entry);
}

static u64 intel_cqm_event_count(struct perf_event *event)
{
	unsigned long flags;
	struct rmid_read rr = {
		.value = ATOMIC64_INIT(0),
	};

	/*
	 * We only need to worry about task events. System-wide events
	 * are handled like usual, i.e. entirely with
	 * intel_cqm_event_read().
	 */
	if (event->cpu != -1)
		return __perf_event_count(event);

	/*
	 * Only the group leader gets to report values. This stops us
	 * reporting duplicate values to userspace, and gives us a clear
	 * rule for which task gets to report the values.
	 *
	 * Note that it is impossible to attribute these values to
	 * specific packages - we forfeit that ability when we create
	 * task events.
	 */
	if (!cqm_group_leader(event))
		return 0;

	/*
	 * Getting up-to-date values requires an SMP IPI which is not
	 * possible if we're being called in interrupt context. Return
	 * the cached values instead.
	 */
	if (unlikely(in_interrupt()))
		goto out;

	/*
	 * Notice that we don't perform the reading of an RMID
	 * atomically, because we can't hold a spin lock across the
	 * IPIs.
	 *
	 * Speculatively perform the read, since @event might be
	 * assigned a different (possibly invalid) RMID while we're
	 * busying performing the IPI calls. It's therefore necessary to
	 * check @event's RMID afterwards, and if it has changed,
	 * discard the result of the read.
	 */
	rr.rmid = ACCESS_ONCE(event->hw.cqm_rmid);

	if (!__rmid_valid(rr.rmid))
		goto out;

	on_each_cpu_mask(&cqm_cpumask, __intel_cqm_event_count, &rr, 1);

	raw_spin_lock_irqsave(&cache_lock, flags);
	if (event->hw.cqm_rmid == rr.rmid)
		local64_set(&event->count, atomic64_read(&rr.value));
	raw_spin_unlock_irqrestore(&cache_lock, flags);
out:
	return __perf_event_count(event);
}

static void intel_cqm_event_start(struct perf_event *event, int mode)
{
	struct intel_pqr_state *state = this_cpu_ptr(&pqr_state);
	u32 rmid = event->hw.cqm_rmid;

	if (!(event->hw.cqm_state & PERF_HES_STOPPED))
		return;

	event->hw.cqm_state &= ~PERF_HES_STOPPED;

	if (state->rmid_usecnt++) {
		if (!WARN_ON_ONCE(state->rmid != rmid))
			return;
	} else {
		WARN_ON_ONCE(state->rmid);
	}

	state->rmid = rmid;
	wrmsr(MSR_IA32_PQR_ASSOC, rmid, state->closid);
}

static void intel_cqm_event_stop(struct perf_event *event, int mode)
{
	struct intel_pqr_state *state = this_cpu_ptr(&pqr_state);

	if (event->hw.cqm_state & PERF_HES_STOPPED)
		return;

	event->hw.cqm_state |= PERF_HES_STOPPED;

	intel_cqm_event_read(event);

	if (!--state->rmid_usecnt) {
		state->rmid = 0;
		wrmsr(MSR_IA32_PQR_ASSOC, 0, state->closid);
	} else {
		WARN_ON_ONCE(!state->rmid);
	}
}

static int intel_cqm_event_add(struct perf_event *event, int mode)
{
	unsigned long flags;
	u32 rmid;

	raw_spin_lock_irqsave(&cache_lock, flags);

	event->hw.cqm_state = PERF_HES_STOPPED;
	rmid = event->hw.cqm_rmid;

	if (__rmid_valid(rmid) && (mode & PERF_EF_START))
		intel_cqm_event_start(event, mode);

	raw_spin_unlock_irqrestore(&cache_lock, flags);

	return 0;
}

static void intel_cqm_event_destroy(struct perf_event *event)
{
	struct perf_event *group_other = NULL;

	mutex_lock(&cache_mutex);

	/*
	 * If there's another event in this group...
	 */
	if (!list_empty(&event->hw.cqm_group_entry)) {
		group_other = list_first_entry(&event->hw.cqm_group_entry,
					       struct perf_event,
					       hw.cqm_group_entry);
		list_del(&event->hw.cqm_group_entry);
	}

	/*
	 * And we're the group leader..
	 */
	if (cqm_group_leader(event)) {
		/*
		 * If there was a group_other, make that leader, otherwise
		 * destroy the group and return the RMID.
		 */
		if (group_other) {
			list_replace(&event->hw.cqm_groups_entry,
				     &group_other->hw.cqm_groups_entry);
		} else {
			u32 rmid = event->hw.cqm_rmid;

			if (__rmid_valid(rmid))
				__put_rmid(rmid);
			list_del(&event->hw.cqm_groups_entry);
		}
	}

	mutex_unlock(&cache_mutex);
}

static int intel_cqm_event_init(struct perf_event *event)
{
	struct perf_event *group = NULL;
	bool rotate = false;

	if (event->attr.type != intel_cqm_pmu.type)
		return -ENOENT;

	if (event->attr.config & ~QOS_EVENT_MASK)
		return -EINVAL;

	/* unsupported modes and filters */
	if (event->attr.exclude_user   ||
	    event->attr.exclude_kernel ||
	    event->attr.exclude_hv     ||
	    event->attr.exclude_idle   ||
	    event->attr.exclude_host   ||
	    event->attr.exclude_guest  ||
	    event->attr.sample_period) /* no sampling */
		return -EINVAL;

	INIT_LIST_HEAD(&event->hw.cqm_group_entry);
	INIT_LIST_HEAD(&event->hw.cqm_groups_entry);

	event->destroy = intel_cqm_event_destroy;

	mutex_lock(&cache_mutex);

	/* Will also set rmid */
	intel_cqm_setup_event(event, &group);

	if (group) {
		list_add_tail(&event->hw.cqm_group_entry,
			      &group->hw.cqm_group_entry);
	} else {
		list_add_tail(&event->hw.cqm_groups_entry,
			      &cache_groups);

		/*
		 * All RMIDs are either in use or have recently been
		 * used. Kick the rotation worker to clean/free some.
		 *
		 * We only do this for the group leader, rather than for
		 * every event in a group to save on needless work.
		 */
		if (!__rmid_valid(event->hw.cqm_rmid))
			rotate = true;
	}

	mutex_unlock(&cache_mutex);

	if (rotate)
		schedule_delayed_work(&intel_cqm_rmid_work, 0);

	return 0;
}

EVENT_ATTR_STR(llc_occupancy, intel_cqm_llc, "event=0x01");
EVENT_ATTR_STR(llc_occupancy.per-pkg, intel_cqm_llc_pkg, "1");
EVENT_ATTR_STR(llc_occupancy.unit, intel_cqm_llc_unit, "Bytes");
EVENT_ATTR_STR(llc_occupancy.scale, intel_cqm_llc_scale, NULL);
EVENT_ATTR_STR(llc_occupancy.snapshot, intel_cqm_llc_snapshot, "1");

static struct attribute *intel_cqm_events_attr[] = {
	EVENT_PTR(intel_cqm_llc),
	EVENT_PTR(intel_cqm_llc_pkg),
	EVENT_PTR(intel_cqm_llc_unit),
	EVENT_PTR(intel_cqm_llc_scale),
	EVENT_PTR(intel_cqm_llc_snapshot),
	NULL,
};

static struct attribute_group intel_cqm_events_group = {
	.name = "events",
	.attrs = intel_cqm_events_attr,
};

PMU_FORMAT_ATTR(event, "config:0-7");
static struct attribute *intel_cqm_formats_attr[] = {
	&format_attr_event.attr,
	NULL,
};

static struct attribute_group intel_cqm_format_group = {
	.name = "format",
	.attrs = intel_cqm_formats_attr,
};

static ssize_t
max_recycle_threshold_show(struct device *dev, struct device_attribute *attr,
			   char *page)
{
	ssize_t rv;

	mutex_lock(&cache_mutex);
	rv = snprintf(page, PAGE_SIZE-1, "%u\n", __intel_cqm_max_threshold);
	mutex_unlock(&cache_mutex);

	return rv;
}

static ssize_t
max_recycle_threshold_store(struct device *dev,
			    struct device_attribute *attr,
			    const char *buf, size_t count)
{
	unsigned int bytes, cachelines;
	int ret;

	ret = kstrtouint(buf, 0, &bytes);
	if (ret)
		return ret;

	mutex_lock(&cache_mutex);

	__intel_cqm_max_threshold = bytes;
	cachelines = bytes / cqm_l3_scale;

	/*
	 * The new maximum takes effect immediately.
	 */
	if (__intel_cqm_threshold > cachelines)
		__intel_cqm_threshold = cachelines;

	mutex_unlock(&cache_mutex);

	return count;
}

static DEVICE_ATTR_RW(max_recycle_threshold);

static struct attribute *intel_cqm_attrs[] = {
	&dev_attr_max_recycle_threshold.attr,
	NULL,
};

static const struct attribute_group intel_cqm_group = {
	.attrs = intel_cqm_attrs,
};

static const struct attribute_group *intel_cqm_attr_groups[] = {
	&intel_cqm_events_group,
	&intel_cqm_format_group,
	&intel_cqm_group,
	NULL,
};

static struct pmu intel_cqm_pmu = {
	.hrtimer_interval_ms = RMID_DEFAULT_QUEUE_TIME,
	.attr_groups	     = intel_cqm_attr_groups,
	.task_ctx_nr	     = perf_sw_context,
	.event_init	     = intel_cqm_event_init,
	.add		     = intel_cqm_event_add,
	.del		     = intel_cqm_event_stop,
	.start		     = intel_cqm_event_start,
	.stop		     = intel_cqm_event_stop,
	.read		     = intel_cqm_event_read,
	.count		     = intel_cqm_event_count,
};

static inline void cqm_pick_event_reader(int cpu)
{
	int phys_id = topology_physical_package_id(cpu);
	int i;

	for_each_cpu(i, &cqm_cpumask) {
		if (phys_id == topology_physical_package_id(i))
			return;	/* already got reader for this socket */
	}

	cpumask_set_cpu(cpu, &cqm_cpumask);
}

static void intel_cqm_cpu_starting(unsigned int cpu)
{
	struct intel_pqr_state *state = &per_cpu(pqr_state, cpu);
	struct cpuinfo_x86 *c = &cpu_data(cpu);

	state->rmid = 0;
	state->closid = 0;
	state->rmid_usecnt = 0;

	WARN_ON(c->x86_cache_max_rmid != cqm_max_rmid);
	WARN_ON(c->x86_cache_occ_scale != cqm_l3_scale);
}

static void intel_cqm_cpu_exit(unsigned int cpu)
{
	int phys_id = topology_physical_package_id(cpu);
	int i;

	/*
	 * Is @cpu a designated cqm reader?
	 */
	if (!cpumask_test_and_clear_cpu(cpu, &cqm_cpumask))
		return;

	for_each_online_cpu(i) {
		if (i == cpu)
			continue;

		if (phys_id == topology_physical_package_id(i)) {
			cpumask_set_cpu(i, &cqm_cpumask);
			break;
		}
	}
}

static int intel_cqm_cpu_notifier(struct notifier_block *nb,
				  unsigned long action, void *hcpu)
{
	unsigned int cpu  = (unsigned long)hcpu;

	switch (action & ~CPU_TASKS_FROZEN) {
	case CPU_DOWN_PREPARE:
		intel_cqm_cpu_exit(cpu);
		break;
	case CPU_STARTING:
		intel_cqm_cpu_starting(cpu);
		cqm_pick_event_reader(cpu);
		break;
	}

	return NOTIFY_OK;
}

static const struct x86_cpu_id intel_cqm_match[] = {
	{ .vendor = X86_VENDOR_INTEL, .feature = X86_FEATURE_CQM_OCCUP_LLC },
	{}
};

static int __init intel_cqm_init(void)
{
	char *str, scale[20];
	int i, cpu, ret;

	if (!x86_match_cpu(intel_cqm_match))
		return -ENODEV;

	cqm_l3_scale = boot_cpu_data.x86_cache_occ_scale;

	/*
	 * It's possible that not all resources support the same number
	 * of RMIDs. Instead of making scheduling much more complicated
	 * (where we have to match a task's RMID to a cpu that supports
	 * that many RMIDs) just find the minimum RMIDs supported across
	 * all cpus.
	 *
	 * Also, check that the scales match on all cpus.
	 */
	cpu_notifier_register_begin();

	for_each_online_cpu(cpu) {
		struct cpuinfo_x86 *c = &cpu_data(cpu);

		if (c->x86_cache_max_rmid < cqm_max_rmid)
			cqm_max_rmid = c->x86_cache_max_rmid;

		if (c->x86_cache_occ_scale != cqm_l3_scale) {
			pr_err("Multiple LLC scale values, disabling\n");
			ret = -EINVAL;
			goto out;
		}
	}

	/*
	 * A reasonable upper limit on the max threshold is the number
	 * of lines tagged per RMID if all RMIDs have the same number of
	 * lines tagged in the LLC.
	 *
	 * For a 35MB LLC and 56 RMIDs, this is ~1.8% of the LLC.
	 */
	__intel_cqm_max_threshold =
		boot_cpu_data.x86_cache_size * 1024 / (cqm_max_rmid + 1);

	snprintf(scale, sizeof(scale), "%u", cqm_l3_scale);
	str = kstrdup(scale, GFP_KERNEL);
	if (!str) {
		ret = -ENOMEM;
		goto out;
	}

	event_attr_intel_cqm_llc_scale.event_str = str;

	ret = intel_cqm_setup_rmid_cache();
	if (ret)
		goto out;

	for_each_online_cpu(i) {
		intel_cqm_cpu_starting(i);
		cqm_pick_event_reader(i);
	}

	__perf_cpu_notifier(intel_cqm_cpu_notifier);

	ret = perf_pmu_register(&intel_cqm_pmu, "intel_cqm", -1);
	if (ret)
		pr_err("Intel CQM perf registration failed: %d\n", ret);
	else
		pr_info("Intel CQM monitoring enabled\n");

out:
	cpu_notifier_register_done();

	return ret;
}
device_initcall(intel_cqm_init);


text:
<idea-plugin>
  <application-components>
    <!-- the same interface-class and different implementation-class -->
    <component>
      <interface-class>ApplicationComponentInterface</interface-class>
      <implementation-class>ApplicationComponent</implementation-class>
    </component>
    <component>
      <interface-class><error descr="Multiple components with the same 'interface-class' are not allowed">ApplicationComponentInterface</error></interface-class>
      <implementation-class>ApplicationComponent2</implementation-class>
    </component>

    <!-- different interface-class for the same implementation-class: -->
    <component>
      <interface-class>java.lang.Number</interface-class>
      <implementation-class>java.lang.Double</implementation-class>
    </component>
    <component>
      <interface-class>java.lang.Comparable</interface-class>
      <implementation-class>java.lang.Double</implementation-class>
    </component>
  </application-components>

  <project-components>
    <!-- shouldn't be reported as the previous is application-level and this is project-level: -->
    <component>
      <interface-class>java.lang.Number</interface-class>
      <implementation-class>java.lang.Double</implementation-class>
    </component>
  </project-components>

  <module-components>
    <!-- within the same module type -->
    <component>
      <interface-class>MyModuleComponentInterface</interface-class>
      <implementation-class>MyModuleComponent</implementation-class>
      <option name="type" value="JAVA"/>
    </component>
    <component>
      <interface-class><error descr="Multiple components with the same 'interface-class' are not allowed">MyModuleComponentInterface</error></interface-class>
      <implementation-class>MyModuleComponent2</implementation-class>
      <option name="type" value="JAVA"/>
    </component>

    <!-- different module type -->
    <component>
      <interface-class>MyModuleComponentInterface</interface-class>
      <implementation-class>MyModuleComponent3</implementation-class>
      <option name="type" value="OTHER"/>
    </component>

    <!-- within the same null type -->
    <component>
      <interface-class>MyModuleComponentInterface</interface-class>
      <implementation-class>MyModuleComponent</implementation-class>
    </component>
    <component>
      <interface-class><error descr="Multiple components with the same 'interface-class' are not allowed">MyModuleComponentInterface</error></interface-class>
      <implementation-class>MyModuleComponent2</implementation-class>
    </component>
  </module-components>
</idea-plugin>

redpajama_set_name: RedPajamaGithub


text:
{% block label %}{% include field.label_template %}{% endblock %}

{{ field.help_text }}

        {% block extra_description_container %}{% endblock %}

        {% block field %}
            {% block input %}{% include field.input_template %}{% endblock %}
            {% block errors %}{% include field.errors_template %}{% endblock %}

            {% block extra_content %}{% endblock %}
        {% endblock %}


text:
package com.junitlet.assertion;

class AssertType {
	private Class<?> type;
	private boolean applyForSubClasses;

	AssertType(Class<?> type, boolean applyForSubClasses) {
		this.type = type;
		this.applyForSubClasses = applyForSubClasses;
	}

	public Class<?> getType() {
		return type;
	}

	public boolean isApplyForSubClasses() {
		return applyForSubClasses;
	}

}


text:
<?php

namespace HumusSupervisorModule\Service;

use HumusSupervisorModule\Controller\ListenerController;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class ListenerControllerFactory implements FactoryInterface
{
    /**
     * Create service
     *
     * @param ServiceLocatorInterface $serviceLocator
     * @return mixed
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        /* @var $serviceLocator \Zend\Mvc\Controller\ControllerManager */
        $sm = $serviceLocator->getServiceLocator();

        $pluginManager = $sm->get('HumusSupervisorModule\\ListenerManager');

        $controller = new ListenerController();
        $controller->setListenerManager($pluginManager);

        return $controller;
    }
}


text:
import os

from pants.auth.cookies import Cookies
from pants.testutil.test_base import TestBase
from pants.util.contextutil import temporary_dir

class TestCookies(TestBase):
    def test_cookie_file_permissions(self):
        with temporary_dir() as tmpcookiedir:
            cookie_file = os.path.join(tmpcookiedir, "pants.test.cookies")

            self.context(
                for_subsystems=[Cookies], options={Cookies.options_scope: {"path": cookie_file}}
            )

            cookies = Cookies.global_instance()
            self.assertFalse(os.path.exists(cookie_file))
            cookies.update([])
            self.assertTrue(os.path.exists(cookie_file))
            file_permissions = os.stat(cookie_file).st_mode
            self.assertEqual(int("0100600", 8), file_permissions)


text:
<?php

/**
 * @class  widget
 * @author NAVER (developers@xpressengine.com)
 * @brief widget module's high class
 */
class widget extends ModuleObject
{
	/**
	 * @brief Implement if additional tasks are necessary when installing
	 */
	function moduleInstall()
	{
		// Create cache directory used by widget
		FileHandler::makeDir('./files/cache/widget');
		FileHandler::makeDir('./files/cache/widget_cache');
		// Add this widget compile the trigger for the display.after
		$oModuleController = getController('module');
		$oModuleController->insertTrigger('display', 'widget', 'controller', 'triggerWidgetCompile', 'before');

		return new Object();
	}

	/**
	 * @brief a method to check if successfully installed
	 */
	function checkUpdate()
	{
		$oModuleModel = getModel('module');
		// widget compile display.after trigger for further (04/14/2009)
		if(!$oModuleModel->getTrigger('display', 'widget', 'controller', 'triggerWidgetCompile', 'before')) return true;

		return false;
	}

	/**
	 * @brief Execute update
	 */
	function moduleUpdate()
	{
		$oModuleModel = getModel('module');
		$oModuleController = getController('module');
		// widget compile display.after trigger for further (04/14/2009)
		if(!$oModuleModel->getTrigger('display', 'widget', 'controller', 'triggerWidgetCompile', 'before'))
		{
			$oModuleController->insertTrigger('display', 'widget', 'controller', 'triggerWidgetCompile', 'before');
		}

		return new Object(0, 'success_updated');
	}

	/**
	 * @brief Re-generate the cache file
	 */
	function recompileCache()
	{
	}
}
/* End of file widget.class.php */
/* Location: ./modules/widget/widget.class.php */


text:
# BearFramework\App\Data\DataLockedException

```php
BearFramework\App\Data\DataLockedException extends Exception implements Throwable, Stringable {

	/* Methods */
	public __construct ( [ string $message = '' [, int $code = 0 [, Exception $previous ]]] )

}
```

## Extends

##### [Exception](http://php.net/manual/en/class.exception.php)

## Implements

##### [Throwable](http://php.net/manual/en/class.throwable.php)

##### [Stringable](http://php.net/manual/en/class.stringable.php)

## Methods

##### public [__construct](bearframework.app.data.datalockedexception.__construct.method.md) ( [ string $message = '' [, int $code = 0 [, [Exception](http://php.net/manual/en/class.exception.php) $previous ]]] )

### Inherited from [Exception](http://php.net/manual/en/class.exception.php)

##### public final void [getCode](http://php.net/manual/en/exception.getcode.php) ( void )

##### public final void [getFile](http://php.net/manual/en/exception.getfile.php) ( void )

##### public final void [getLine](http://php.net/manual/en/exception.getline.php) ( void )

##### public final void [getMessage](http://php.net/manual/en/exception.getmessage.php) ( void )

##### public final void [getPrevious](http://php.net/manual/en/exception.getprevious.php) ( void )

##### public final void [getTrace](http://php.net/manual/en/exception.gettrace.php) ( void )

##### public final void [getTraceAsString](http://php.net/manual/en/exception.gettraceasstring.php) ( void )

## Details

Location: ~/src/App/Data/DataLockedException.php

---

[back to index](index.md)


text:
<?php

namespace Iyzipay;

class Constants
{
    const SINGLE_INSTALLMENT = 1;
}


text:
<?php

/*

	the BROWSER RADIO config file -- php part of it

	remember to also set config options in play.js
	remmeber to also set config options in radio.js

*/

// the URL path to the index.php page
$app_path = '/radio/';

// name your station
$radio_name = 'RADIOOOO';

// where is your "iTunes Music Library.xml" file ?
$library_file = '/Users/yourname/Music/iTunes/iTunes Music Library.xml';

// what's the file path base inside your iTunes Library XML file?
// hint: you can usually figure this out by right-clicking a song in iTunes and clicking "Get Info"
//       the "Where" section at the bottom of the "Summary" tab has this path
$itunes_file_location_base = 'file://localhost/Users/yourname/Music/';

// what's the URL to the node.js play system that comes with this?
$nodejs_playback_url_base = 'http://localhost:1337/play?file=';

// IP range restrictions
$ip_range_restricts = array('192.168.0.0/16', '10.0.0.0/8');

?>


text:
Command-line utility to perform Jalangi2's instrumentation and analysis

    node src/js/commands/jalangi.js -h
    usage: jalangi.js [-h] [--analysis ANALYSIS] [--initParam INITPARAM]
                  [--inlineIID] [--inlineSource]
                  [--astHandlerModule ASTHANDLERMODULE]
                  ...

Positional arguments:

    script_and_args       script to record and CLI arguments for that script

Optional arguments:

    -h, --help            Show this help message and exit.
    --analysis ANALYSIS   absolute path to analysis file to run
    --initParam INITPARAM
                        initialization parameter for analysis, specified as
                        key:value
    --inlineIID           Inline IID to (beginLineNo, beginColNo, endLineNo,
                        endColNo) in J$.iids in the instrumented file
    --inlineSource        Inline original source as string in J$.iids.code in
                        the instrumented file
    --astHandlerModule ASTHANDLERMODULE
                        Path to a node module that exports a function to be
                        used for additional AST handling after instrumentation

## esnstrument_cli.js

Command-line utility to perform instrumentation

    node src/js/commands/esnstrument_cli.js -h
    usage: esnstrument_cli.js [-h] [--inlineIID] [--inlineSource]
                          [--initParam INITPARAM] [--noResultsGUI]
                          [--astHandlerModule ASTHANDLERMODULE]
                          [--outDir OUTDIR] [--out OUT] [--url URL]
                          [--extra_app_scripts EXTRA_APP_SCRIPTS]
                          [--analysis ANALYSIS]
                          file

Positional arguments:

    file                  file to instrument

Optional arguments:

    -h, --help            Show this help message and exit.
    --inlineIID           Inline IID to (beginLineNo, beginColNo, endLineNo,
                        endColNo) in J$.iids in the instrumented file
    --inlineSource        Inline original source as string in J$.iids.code in
                        the instrumented file
    --initParam INITPARAM
                        initialization parameter for analysis, specified as
                        key:value
    --noResultsGUI        disable insertion of results GUI code in HTML
    --astHandlerModule ASTHANDLERMODULE
                        Path to a node module that exports a function to be
                        used for additional AST handling after instrumentation
    --outDir OUTDIR       Directory containing scripts inlined in html
    --out OUT             Instrumented file name (with path). The default is to
                        append _jalangi_ to the original JS file name
    --url URL             URL of the file to be instrumented. The URL is stored
                        as metadata in the source map and is not used for
                        retrieving the file.
    --extra_app_scripts EXTRA_APP_SCRIPTS
                        list of extra application scripts to be injected and
                        instrumented, separated by path.delimiter
    --analysis ANALYSIS   Analysis script.

## instrument.js

Utility to apply Jalangi instrumentation to files or a folder.

    node src/js/commands/instrument.js -h
    usage: instrument.js [-h] [-x EXCLUDE] [--only_include ONLY_INCLUDE] [-i]
                     [--inlineIID] [--inlineSource] [--inlineJalangi]
                     [--analysis ANALYSIS] [--initParam INITPARAM] [-d] [-c]
                     [--extra_app_scripts EXTRA_APP_SCRIPTS] [--no_html]
                     --outputDir OUTPUTDIR [--verbose]
                     [--astHandlerModule ASTHANDLERMODULE]
                     inputFiles[inputFiles ...]

Positional arguments:

    inputFiles            either a list of JavaScript files to instrument, or a
                        single directory under which all JavaScript and HTML
                        files should be instrumented (modulo the --no_html
                        and --exclude flags)

Optional arguments:

    -h, --help            Show this help message and exit.
    -x EXCLUDE, --exclude EXCLUDE
                        do not instrument any scripts whose file path
                        contains this substring
    --only_include ONLY_INCLUDE
                        list of path prefixes specifying which
                        sub-directories should be instrumented, separated by
                        path.delimiter
    -i, --instrumentInline
                        instrument inline scripts
    --inlineIID           Inline IID to (beginLineNo, beginColNo, endLineNo,
                        endColNo) in J$.iids in the instrumented file
    --inlineSource        Inline original source as string in J$.iids.code in
                        the instrumented file
    --inlineJalangi       Inline Jalangi runtime source code into HTML files
    --analysis ANALYSIS   Analysis script.
    --initParam INITPARAM
                        initialization parameter for analysis, specified as
                        key:value
    -d, --direct_in_output
                        Store instrumented app directly in output directory
                        (by default, creates a sub-directory of output
                        directory)
    -c, --copy_runtime    Copy Jalangi runtime files into instrumented app in
                        jalangi_rt sub-directory
    --extra_app_scripts EXTRA_APP_SCRIPTS
                        list of extra application scripts to be injected and
                        instrumented, separated by path.delimiter
    --no_html             don't inject Jalangi runtime into HTML files
    --outputDir OUTPUTDIR
                        directory in which to place instrumented files
    --verbose             print verbose output
    --astHandlerModule ASTHANDLERMODULE
                        Path to a node module that exports a function to be
                        used for additional AST handling after instrumentation
## direct.js

Command-line utility to perform Jalangi2's analysis

    node src/js/commands/direct.js -h
    usage: direct.js [-h] [--analysis ANALYSIS] [--initParam INITPARAM] ...

Positional arguments:

    script_and_args       script to record and CLI arguments for that script

Optional arguments:

    -h, --help            Show this help message and exit.
    --analysis ANALYSIS   absolute path to analysis file to run
    --initParam INITPARAM
                        initialization parameter for analysis, specified as
                        key:value


text:
<?php

namespace MusicBrainz\Value;

use MusicBrainz\Value;

/**
 * A join phrase
 */
class JoinPhrase implements Value
{
    /**
     * The join phrase
     *
     * @var string
     */
    private $joinPhrase;

    /**
     * Constructs a join phrase.
     *
     * @param string $joinPhrase The joinPhrase
     */
    public function __construct(string $joinPhrase = '')
    {
        $this->joinPhrase = $joinPhrase;
    }

    /**
     * Returns the join phrase.
     *
     * @return string
     */
    public function __toString(): string
    {
        return $this->joinPhrase;
    }
}


text:
package org.kumoricon.site.attendee;

public interface CheckInConfirmationHandler {
    void attendeeInformationVerified();
}


text:
from copy import deepcopy
from datetime import datetime

import rstr

from portality import constants, regex
from doajtest.fixtures.v2.common import JOURNAL_LIKE_BIBJSON, EDITORIAL_FORM_EXPANDED, SUBJECT_FORM_EXPANDED, NOTES_FORM_EXPANDED, OWNER_FORM_EXPANDED, SEAL_FORM_EXPANDED
from doajtest.fixtures.v2.journals import JOURNAL_FORM_EXPANDED, JOURNAL_FORM
from portality.lib import dates
from portality.models.v2.application import Application

class ApplicationFixtureFactory(object):
    @staticmethod
    def make_update_request_source():
        template = deepcopy(APPLICATION_SOURCE)
        template["admin"]["current_journal"] = '123456789987654321'
        return template

    @staticmethod
    def make_application_source():
        return deepcopy(APPLICATION_SOURCE)

    @staticmethod
    def make_many_application_sources(count=2, in_doaj=False):
        application_sources = []
        for i in range(0, count):
            template = deepcopy(APPLICATION_SOURCE)
            template['id'] = 'applicationid{0}'.format(i)
            # now some very quick and very dirty date generation
            fakemonth = i
            if fakemonth < 1:
                fakemonth = 1
            if fakemonth > 9:
                fakemonth = 9
            template['created_date'] = "2000-0{fakemonth}-01T00:00:00Z".format(fakemonth=fakemonth)
            template["bibjson"]["pissn"] = rstr.xeger(regex.ISSN_COMPILED)
            template["bibjson"]["eissn"] = rstr.xeger(regex.ISSN_COMPILED)
            template['bibjson']['title'] = 'Test Title {}'.format(i)
            application_sources.append(deepcopy(template))
            template["admin"]["current_journal"] = '123456789'
        return application_sources

    @staticmethod
    def make_application_form(role="maned"):
        form = deepcopy(APPLICATION_FORM)
        if role == "assed" or role == "editor":
            del form["editor_group"]
        elif role == "publisher":
            form = deepcopy(JOURNAL_FORM)
            del form["pissn"]
            del form["eissn"]

        return form

    @staticmethod
    def make_application_form_info():
        return deepcopy(APPLICATION_FORM_EXPANDED)

    @classmethod
    def incoming_application(cls):
        return deepcopy(INCOMING_SOURCE)

    @classmethod
    def make_application_spread(cls, desired_output, period):
        desired_output = deepcopy(desired_output)
        header = desired_output[0]
        del desired_output[0]
        del header[0]
        ranges = []
        for h in header:
            start = None
            end = None
            if period == "month":
                startts = dates.parse(h, "%Y-%m")
                year, month = divmod(startts.month+1, 12)
                if month == 0:
                    month = 12
                    year = year - 1
                endts = datetime(startts.year + year, month, 1)
                start = dates.format(startts)
                end = dates.format(endts)
            elif period == "year":
                startts = dates.parse(h, "%Y")
                endts = datetime(startts.year + 1, 1, 1)
                start = dates.format(startts)
                end = dates.format(endts)

            ranges.append((start, end))

        apps = []
        for row in desired_output:
            country = row[0]
            del row[0]
            for i in range(len(row)):
                count = row[i]
                start, end = ranges[i]
                for j in range(count):
                    s = Application()
                    s.set_created(dates.random_date(start, end))
                    s.bibjson().country = country
                    apps.append(s)

        return apps

APPLICATION_SOURCE = {
    "id" : "abcdefghijk",
    "created_date" :  "2000-01-01T00:00:00Z",
    "last_manual_update" : "2001-01-01T00:00:00Z",
    "last_updated" : "2002-01-01T00:00:00Z",
    "admin": {
        "application_status" : constants.APPLICATION_STATUS_PENDING,
        "application_type" : constants.APPLICATION_TYPE_UPDATE_REQUEST,
        "current_journal" : "poiuytrewq",
        "editor" : "associate",
        "editor_group" : "editorgroup",
        "notes" : [
            {"note" : "Second Note", "date" : "2014-05-22T00:00:00Z", "id" : "1234"},
            {"note": "First Note", "date": "2014-05-21T14:02:45Z", "id" : "abcd"}
        ],
        "owner" : "publisher",
        "related_journal" : "987654321123456789",
        "seal": False,
        "date_applied" : "2003-01-01T00:00:00Z"
    },
    "bibjson" : JOURNAL_LIKE_BIBJSON
}

_isbj = deepcopy(JOURNAL_LIKE_BIBJSON)
del _isbj["subject"]
del _isbj["replaces"]
del _isbj["is_replaced_by"]
del _isbj["discontinued_date"]

INCOMING_SOURCE = {
    "id" : "ignore_me",
    "created_date" : "2001-01-01T00:00:00Z",
    "last_updated" : "2001-01-01T00:00:00Z",

    "bibjson": _isbj,
    "admin" : {
        "current_journal" : "1234567890"
    }
}

WORKFLOW_FORM_EXPANDED = {
    "application_status" : constants.APPLICATION_STATUS_PENDING
}

APPLICATION_FORM_EXPANDED = deepcopy(JOURNAL_FORM_EXPANDED)
APPLICATION_FORM_EXPANDED.update(deepcopy(NOTES_FORM_EXPANDED))
APPLICATION_FORM_EXPANDED.update(deepcopy(SUBJECT_FORM_EXPANDED))
APPLICATION_FORM_EXPANDED.update(deepcopy(OWNER_FORM_EXPANDED))
APPLICATION_FORM_EXPANDED.update(deepcopy(EDITORIAL_FORM_EXPANDED))
APPLICATION_FORM_EXPANDED.update(deepcopy(SEAL_FORM_EXPANDED))
APPLICATION_FORM_EXPANDED.update(deepcopy(WORKFLOW_FORM_EXPANDED))

from portality.crosswalks.application_form import ApplicationFormXWalk
APPLICATION_FORM = ApplicationFormXWalk.forminfo2multidict(APPLICATION_FORM_EXPANDED)


text:
public class Automovil {

    private String modelo;
    private String placa;
    private String serie;
    private String marca;
    private boolean encendido;
    private boolean abierto;
    private boolean arrancado;
    private String contrasenia;
    private int velocidad;
    public static int MAX_VELOCIDAD = 120;
    static int enumeradorCarro = 1;

    /**
     * @return the MAX_VELOCIDAD
     */
    public static int getMAX_VELOCIDAD() {
        return MAX_VELOCIDAD;
    }

    public Automovil(){
        modelo = "";
        placa = "";
        setSerie();
        marca = "";
        encendido = false;
        abierto = false;
        arrancado = false;
        velocidad = 0;
        contrasenia = "123";
    }

    public Automovil(String pmodelo, String pplaca, String pmarca){
        modelo = pmodelo;
        placa = pplaca;
        setSerie();
        marca = pmarca;
        encendido = false;
        abierto = false;
        arrancado = false;
        velocidad = 0;
        contrasenia = "123";
    }

    public Automovil(String pplaca){
        modelo = "";
        placa = pplaca;
        setSerie();
        marca = "";
        encendido = false;
        abierto = false;
        arrancado = false;
        velocidad = 0;
        contrasenia = "123";
    }

    /**
     * @return the modelo
     */
    public String getModelo() {
        return modelo;
    }

    /**
     * @param modelo the modelo to set
     */
    public void setModelo(String modelo) {
        this.modelo = modelo;
    }

    /**
     * @return the placa
     */
    public String getPlaca() {
        return placa;
    }

    /**
     * @param placa the placa to set
     */
    public void setPlaca(String placa) {
        this.placa = placa;
    }

    /**
     * @return the serie
     */
    public String getSerie() {
        return serie;
    }

    /**
     * @param serie the serie to set
     */
    private void setSerie() {
        this.serie = generarSerial();
    }

    /**
     * @return the marca
     */
    public String getMarca() {
        return marca;
    }

    /**
     * @param marca the marca to set
     */
    public void setMarca(String marca) {
        this.marca = marca;
    }

    /**
     * @return the encendido
     */
    public boolean isEncendido() {
        return encendido;
    }

    /**
     * @param encendido the encendido to set
     */
    public void setEncendido(boolean encendido) {
        this.encendido = encendido;
    }

    /**
     * @return the abierto
     */
    public boolean isAbierto() {
        return abierto;
    }

    /**
     * @param abierto the abierto to set
     */
    public void setAbierto(boolean abierto) {
        this.abierto = abierto;
    }

    /**
     * @return the arrancado
     */
    public boolean isArrancado() {
        return arrancado;
    }

    /**
     * @param arrancado the arrancado to set
     */
    public void setArrancado(boolean arrancado) {
        this.arrancado = arrancado;
    }

    /**
     * @return the velocidad
     */
    public int getVelocidad() {
        return velocidad;
    }

    /**
     * @param velocidad the velocidad to set
     */
    public void setVelocidad(int velocidad) {
        this.velocidad = velocidad;
        if(velocidad <= 0){
            setArrancado(false);
        }
    }

    /**
     * @param pass the pass to set
     */
    public void setPass(String ppass) {
        this.contrasenia = ppass;
    }

    static int getEnumerador(){
        int resul = enumeradorCarro;
        return resul;
    }

    private String generarSerial(){
        Automovil serializador = null;
        int numSerie = serializador.getEnumerador();
        String resul = "SC-" + numSerie;
        enumeradorCarro++;
        return resul;
    }

    private int getVelMax(){
        int resul = MAX_VELOCIDAD;
        return resul;
    }

    public String toString(){
        String model = "Modelo: " + getModelo();
        String plate = "Placa: " + getPlaca();
        String serialNum = "Serie: " + getSerie();
        String brand = "Marca:" + getMarca();
        String on = "Encendido: " + isEncendido();
        String open = "Abierto: " + isAbierto();
        String driving = "Arrancado:" + isArrancado();
        String pass = "Contrasenia: " + contrasenia;
        String speed = "Velocidad: " + getVelocidad();
        String resul = model + "\n" + plate + "\n" + serialNum + "\n" + brand + "\n" + on + "\n" + open + "\n" + driving + "\n" + pass + "\n" + speed;
        return resul;
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /*Comienza lógica de negocio*/
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    public void encender(){
        if(isAbierto()){
            if(!isEncendido()){
                setEncendido(true);
            }
        }
    }

    public void apagar(){
        if(isAbierto()){
            if(isEncendido()){
                detener();
                setEncendido(false);
            }
        }
    }

    public void arrancar(){
        if(isAbierto()){
            if(isEncendido()){
                if(!isArrancado()){
                    setArrancado(true);
                    acelerar();
                }
            }
        }
    }

    public void acelerar(){
        if(isAbierto()){
            if(isArrancado()){
                int incremento = 5;
                int velActual = getVelocidad();
                int nuevaVel = velActual + incremento;
                int maxVel = this.getVelMax();
                if(nuevaVel > maxVel){
                    nuevaVel = maxVel;
                }
                if(nuevaVel > velActual){
                    setVelocidad(nuevaVel);
                }
            }
        }
    }

    public void frenar(){
        if(isAbierto()){
            int velActual = getVelocidad();
            int indiceFrenado = 5;
            int nuevaVel = 0;
            if(velActual >= indiceFrenado){
                nuevaVel = velActual - indiceFrenado;
            }
            if(nuevaVel < 0){
                nuevaVel = 0;
            }
            setVelocidad(nuevaVel);
        }
    }

    public void detener(){
        if(isAbierto()){
            setVelocidad(0);
        }
    }

    public boolean abrir(String ppass){
        boolean seAbrio = ppass.equals(contrasenia);
        if(seAbrio){
            setAbierto(true);
        }
        return seAbrio;
    }

    public void cerrar(){
        if(isAbierto()){
            apagar();
            setAbierto(false);
        }
    }

}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Anal. Mus. nac. Hist. nat. B. Aires 27: (1915)

#### Original name
Thripomyces italicus Speg., 1915

### Remarks
null


text:
package io.devcon5.misc;

import java.util.function.Consumer;

/**
 * Simple initializer that may be invoked to initialize a specific instance
 * Created by Gerald Mücke on 11.09.2015.
 */
public final class Initializer {

    private Initializer(){}

    public static <T> T init(T instance, Consumer<T> initializer){
        initializer.accept(instance);
        return instance;
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <stroke android:color="@color/material_blue_grey_800" android:width="2px"></stroke>
    <size android:width="70dp" android:height="70dp"></size>
    <solid android:color="@color/accent_material_light"></solid>
</shape>


text:
$(document).ready(function () {
    $("#pedidos").click(function (e) {
        var pedido = e.target;
        $("#numPedido").val(pedido.id);
    });
});

$(document).ready(function () {
    $("#filtrar").click(function (e) {
        var nombre = $("#nombre").val();
        var apellido = $("#apellido").val();
        var fechaDesde = $("#fechaDesde").val();
        var fechaHasta = $("#fechaHasta").val();
        var url = document.location.origin + '/Ventas/FiltroPedidos?name=' + nombre + '&lastName=' + apellido + '&inicio=' + fechaDesde + '&final=' + fechaHasta;
        $.ajax(url).done(function (data) {
            $("#pedidos").empty();
            $("#pedidos").html(data);
        });

    });
});


text:
package com.blazebit.persistence.impl;

import com.blazebit.persistence.FinalSetOperationCriteriaBuilder;
import com.blazebit.persistence.LeafOngoingFinalSetOperationCriteriaBuilder;
import com.blazebit.persistence.LeafOngoingSetOperationCriteriaBuilder;
import com.blazebit.persistence.StartOngoingSetOperationCriteriaBuilder;
import com.blazebit.persistence.parser.expression.ExpressionCopyContext;
import com.blazebit.persistence.spi.SetOperationType;

import java.util.Map;

/**
 *
 * @param <T> The query result type
 * @author Christian Beikov
 * @since 1.1.0
 */
public class LeafOngoingSetOperationCriteriaBuilderImpl<T> extends AbstractCriteriaBuilder<T, LeafOngoingSetOperationCriteriaBuilder<T>, LeafOngoingSetOperationCriteriaBuilder<T>, StartOngoingSetOperationCriteriaBuilder<T, LeafOngoingFinalSetOperationCriteriaBuilder<T>>> implements LeafOngoingSetOperationCriteriaBuilder<T>, LeafOngoingFinalSetOperationCriteriaBuilder<T> {

    public LeafOngoingSetOperationCriteriaBuilderImpl(MainQuery mainQuery, QueryContext queryContext, boolean isMainQuery, Class<T> clazz, BuilderListener<Object> listener, FinalSetOperationCriteriaBuilderImpl<T> finalSetOperationBuilder) {
        super(mainQuery, queryContext, isMainQuery, clazz, null, listener, finalSetOperationBuilder);
    }

    public LeafOngoingSetOperationCriteriaBuilderImpl(AbstractCommonQueryBuilder<T, ?, ?, ?, ?> builder, MainQuery mainQuery, QueryContext queryContext, Map<JoinManager, JoinManager> joinManagerMapping, ExpressionCopyContext copyContext) {
        super(builder, mainQuery, queryContext, joinManagerMapping, copyContext);
    }

    @Override
    AbstractCommonQueryBuilder<T, LeafOngoingSetOperationCriteriaBuilder<T>, LeafOngoingSetOperationCriteriaBuilder<T>, StartOngoingSetOperationCriteriaBuilder<T, LeafOngoingFinalSetOperationCriteriaBuilder<T>>, BaseFinalSetOperationCriteriaBuilderImpl<T, ?>> copy(QueryContext queryContext, Map<JoinManager, JoinManager> joinManagerMapping, ExpressionCopyContext copyContext) {
        return new LeafOngoingSetOperationCriteriaBuilderImpl<>(this, queryContext.getParent().mainQuery, queryContext, joinManagerMapping, copyContext);
    }

    @Override
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public FinalSetOperationCriteriaBuilder<T> endSet() {
        subListener.verifyBuilderEnded();
        this.setOperationEnded = true;
        // Only check the query if it's not empty
        if (isEmpty()) {
            if (finalSetOperationBuilder.setOperationManager.hasSetOperations()) {
                finalSetOperationBuilder.setOperationManager.removeOperand(this);
            }
        } else {
            prepareAndCheck();
        }
        listener.onBuilderEnded(this);
        // This final set operation builder is the exception that is already marked as ended here
        finalSetOperationBuilder.setOperationEnded = true;
        return (FinalSetOperationCriteriaBuilder<T>) (FinalSetOperationCriteriaBuilder) finalSetOperationBuilder;
    }

    @Override
    protected BaseFinalSetOperationCriteriaBuilderImpl<T, ?> createFinalSetOperationBuilder(SetOperationType operator, boolean nested) {
        return createFinalSetOperationBuilder(operator, nested, nested);
    }

    @Override
    protected LeafOngoingSetOperationCriteriaBuilder<T> createSetOperand(BaseFinalSetOperationCriteriaBuilderImpl<T, ?> finalSetOperationBuilder) {
        subListener.verifyBuilderEnded();
        listener.onBuilderEnded(this);
        return createLeaf(finalSetOperationBuilder);
    }

    @Override
    protected StartOngoingSetOperationCriteriaBuilder<T, LeafOngoingFinalSetOperationCriteriaBuilder<T>> createSubquerySetOperand(BaseFinalSetOperationCriteriaBuilderImpl<T, ?> finalSetOperationBuilder, BaseFinalSetOperationCriteriaBuilderImpl<T, ?> resultFinalSetOperationBuilder) {
        subListener.verifyBuilderEnded();
        listener.onBuilderEnded(this);
        LeafOngoingFinalSetOperationCriteriaBuilder<T> leafCb = createLeaf(resultFinalSetOperationBuilder);
        return createStartOngoing(finalSetOperationBuilder, leafCb);
    }

}


text:
package com.rapid7.conqueso.client;

import static org.junit.Assert.*;

import java.util.Map;

public class ConquesoTestHelper {

    public static void assertContainsProperty(String propName, PropertyType propType, String defaultValue,
            String description, Map<String, PropertyDefinition> results) {
        assertEquals(new PropertyDefinition(propName, propType, defaultValue, description), results.get(propName));
    }

    public static void assertExampleConfigProperties(Map<String, PropertyDefinition> results) {
        assertEquals(ExampleConfigClass.EXPECTED_PROPERTIES, results);
    }

}


text:
<!DOCTYPE html>

  <title>Class Methods or Nah?</title>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="../stylesheets/default.css">
  <link rel="stylesheet" type="text/css" href="../stylesheets/blog-stylesheets2.css">
  <link href='http://fonts.googleapis.com/css?family=Noto+Sans:400,400italic' rel='stylesheet' type='text/css'>

But I'm not a Blogger?

{01}
          Git it, Got it? Good.

{02}
          Into Hell's Kitchen?

{03}
          It's like, Box Inception or Something.

{04}
          Hashes & Arrays

{05}
          "ART"

{06}
          How to Use .maps

{07}
          #TALKPAY

{08}
          Classes You'll Like

{09}
          Pairing is Caring

{10}
          Class Methods or Nah?

{11}
          Stereotype Me, I'm _______.

{12} JavaScripting, sans Ruby.

{13}
          Values, huh?

{14}
          Intronet

{15}
          Conflict.

{16}

And I'm not really a coffee person. I like cappuccinos, though.

Class Methods or Nah?

May 14, 2015

        For this blog, I'm gonna be piggybacking off of the Ticket example from Chapter 3 of The Well Grounded Rubyist, because well, of all the resources I've gone through it provided the best example in my opinion. One quick thing to keep in mind: "objects are instances of classes."

       Let's say we have a class, Credit_Cards. If we wanted to, we could create a new Credit_Cards object to create say, a Visa credit card. Any method defined within our Credit_Cards class using the convention 'def methodname' is an instance method, meaning we can pass it as a message to our new Visa card object since it's an instance of the class Credit_Cards. In short, a Class instance method works for an instance of a Class. An example of how to create a class method and how to call it can be seen in the figure below. Note that there are other ways for creating and calling class methods though.

      Class methods on the otherhand are inaccessible by class instances though (supposedly you can if you explicitly reference them, but let's not worry about that for now). Class methods work by being passed as messages to the actual Class in which they're defined (remember, classes are objects, too), rather than to an instance of the class. The question of when to use a class method may be a tricky one to answer, but one "simple" answer may arise after answering the question, "Is this operation that a single instance should be able to do?"

      The last question may not make much sense, so let's consider the Class.new method. Class.new is a class method because well, it wouldn't make sense to have it as an instance method. If it were, then an instance of a class would basically be able to instantiate another instance of the same class and so forth. So in terms of our credit card example, a credit card would be able to "create" another credit card. That might be cool, but it wouldn't be if you ended up racking more debt. Not desirable. And just imagine if instead of credit cards, we were using a Dollar_Bills class. Each dollar would be able to generate another dollar... Well that may not be so bad, but it's probably illegal. Anyways, the point is, there's things that instances should be able to do and shouldn't be able to do.

      Something that our Visa credit card most likely wouldn't be able to do is tell you which of your credit cards have the highest credit limit. Why? Because it only knows about itself in this case, being its own instance. You can probably have a method that prints a specific card's credit limit, but if we really wanted to see which of your current cards had the highest limit, it would make more sense to not look at 1 specific card and look at things in a collective way.

      Having a class method instead, like "highest_limit" to find the card with the highest credit would be best suited for our example where running "Credit_cards.new()" creates a single credit card. It is worth noting however, that a class method may not be necessary if we were to have instead passed in an array of cards in say, a Card_Comparer class that had an instance method to run operations for us.

      And like instance methods, class methods can take in a number of arguments as you can see from the example above. So again, when it comes down to whether or not to use them, it may really just come down to a matter of "Should a single instance be able to do this or nah?"


text:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Python on Blog - maurodec.com</title>
    <link>http://maurodec.com/tags/python/</link>
    <description>Recent content in Python on Blog - maurodec.com</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <lastBuildDate>Sun, 07 Feb 2021 00:00:00 -2100</lastBuildDate><atom:link href="http://maurodec.com/tags/python/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>Python Decorators</title>
      <link>http://maurodec.com/blog/decorators/</link>
      <pubDate>Sun, 07 Feb 2021 00:00:00 -2100</pubDate>

      <guid>http://maurodec.com/blog/decorators/</guid>
      <description>
Originally described in the &ldquo;Design Patterns: Elements of Reusable
Object-Oriented Software&rdquo; book, decorators are a powerful design pattern that
allows us to extend or augment an object&rsquo;s functionality. In this post I will
show with some practical examples how this can be achieved in Python via the
@decorator syntax.
</description>
    </item>

    <item>
      <title>Python Classes, namedtuples and __slots__</title>
      <link>http://maurodec.com/blog/classes-namedtuples-slots/</link>
      <pubDate>Sun, 29 Apr 2018 00:00:00 +0000</pubDate>

      <guid>http://maurodec.com/blog/classes-namedtuples-slots/</guid>
      <description>
Data types are needed in pretty much every program that needs to store and
manipulate data. These types usually have little to no behavior and simply
exist to keep track of information in a structured and orderly way. Recently,
PEP 557 (Data Classes) was
accepted, however, it won&rsquo;t appear until Python 3.7.

In this Blog Post we will explore what options currently exist in Python 2.7
and 3.6 and how they differ from each other.
</description>
    </item>

    <item>
      <title>Amet - Flattening a Python dictionary as environment variables</title>
      <link>http://maurodec.com/blog/amet/</link>
      <pubDate>Thu, 20 Apr 2017 00:00:00 -0300</pubDate>

      <guid>http://maurodec.com/blog/amet/</guid>
      <description>
I recently had to build an ETL job in Python that was initially going to be
deployed on AWS. Little did I know that a last minute change from AWS to
Heroku would cause me to change how the job&rsquo;s configuration was going to be
read significantly.
</description>
    </item>

    <item>
      <title>Why I learned Python</title>
      <link>http://maurodec.com/blog/learning-python/</link>
      <pubDate>Fri, 07 Apr 2017 00:00:00 -0300</pubDate>

      <guid>http://maurodec.com/blog/learning-python/</guid>
      <description>
About eleven years ago, after finishing my first semester in University I
decided to learn how to program in Python. In this post I will talk about why I
found Python interesting at the time as well as how it felt to me as someone
with little programming knowledge.
</description>
    </item>

  </channel>
</rss>


text:
#ifndef GrD3DTextureRenderTarget_DEFINED
#define GrD3DTextureRenderTarget_DEFINED

#include "include/gpu/d3d/GrD3DTypes.h"
#include "src/gpu/ganesh/d3d/GrD3DRenderTarget.h"
#include "src/gpu/ganesh/d3d/GrD3DTexture.h"

class GrD3DGpu;

#ifdef SK_BUILD_FOR_WIN
// Windows gives bogus warnings about inheriting asTexture/asRenderTarget via dominance.
#pragma warning(push)
#pragma warning(disable: 4250)
#endif

struct GrD3DTextureResourceInfo;

class GrD3DTextureRenderTarget: public GrD3DTexture, public GrD3DRenderTarget {
public:
    static sk_sp<GrD3DTextureRenderTarget> MakeNewTextureRenderTarget(GrD3DGpu*, SkBudgeted,
                                                                      SkISize dimensions,
                                                                      int sampleCnt,
                                                                      const D3D12_RESOURCE_DESC&,
                                                                      GrProtected isProtected,
                                                                      GrMipmapStatus,
                                                                      std::string_view label);

    static sk_sp<GrD3DTextureRenderTarget> MakeWrappedTextureRenderTarget(
            GrD3DGpu*, SkISize dimensions, int sampleCnt, GrWrapCacheable,
            const GrD3DTextureResourceInfo&, sk_sp<GrD3DResourceState>);

    GrBackendFormat backendFormat() const override { return this->getBackendFormat(); }

protected:
    void onAbandon() override {
        // In order to correctly handle calling texture idle procs, GrD3DTexture must go first.
        GrD3DTexture::onAbandon();
        GrD3DRenderTarget::onAbandon();
    }

    void onRelease() override {
        // In order to correctly handle calling texture idle procs, GrD3DTexture must go first.
        GrD3DTexture::onRelease();
        GrD3DRenderTarget::onRelease();
    }

private:
    // MSAA, not-wrapped
    GrD3DTextureRenderTarget(GrD3DGpu* gpu,
                             SkBudgeted budgeted,
                             SkISize dimensions,
                             const GrD3DTextureResourceInfo& info,
                             sk_sp<GrD3DResourceState> state,
                             const GrD3DDescriptorHeap::CPUHandle& shaderResourceView,
                             const GrD3DTextureResourceInfo& msaaInfo,
                             sk_sp<GrD3DResourceState> msaaState,
                             const GrD3DDescriptorHeap::CPUHandle& colorRenderTargetView,
                             const GrD3DDescriptorHeap::CPUHandle& resolveRenderTargetView,
                             GrMipmapStatus,
                             std::string_view label);

    // non-MSAA, not-wrapped
    GrD3DTextureRenderTarget(GrD3DGpu* gpu,
                             SkBudgeted budgeted,
                             SkISize dimensions,
                             const GrD3DTextureResourceInfo& info,
                             sk_sp<GrD3DResourceState> state,
                             const GrD3DDescriptorHeap::CPUHandle& shaderResourceView,
                             const GrD3DDescriptorHeap::CPUHandle& renderTargetView,
                             GrMipmapStatus,
                             std::string_view label);

    // MSAA, wrapped
    GrD3DTextureRenderTarget(GrD3DGpu* gpu,
                             SkISize dimensions,
                             const GrD3DTextureResourceInfo& info,
                             sk_sp<GrD3DResourceState> state,
                             const GrD3DDescriptorHeap::CPUHandle& shaderResourceView,
                             const GrD3DTextureResourceInfo& msaaInfo,
                             sk_sp<GrD3DResourceState> msaaState,
                             const GrD3DDescriptorHeap::CPUHandle& colorRenderTargetView,
                             const GrD3DDescriptorHeap::CPUHandle& resolveRenderTargetView,
                             GrMipmapStatus,
                             GrWrapCacheable,
                             std::string_view label);

    // non-MSAA, wrapped
    GrD3DTextureRenderTarget(GrD3DGpu* gpu,
                             SkISize dimensions,
                             const GrD3DTextureResourceInfo& info,
                             sk_sp<GrD3DResourceState> state,
                             const GrD3DDescriptorHeap::CPUHandle& shaderResourceView,
                             const GrD3DDescriptorHeap::CPUHandle& renderTargetView,
                             GrMipmapStatus,
                             GrWrapCacheable,
                             std::string_view label);

    // GrGLRenderTarget accounts for the texture's memory and any MSAA renderbuffer's memory.
    size_t onGpuMemorySize() const override;

    void onSetLabel() override;

    // In Direct3D we call the release proc after we are finished with the underlying
    // GrD3DImage::Resource object (which occurs after the GPU has finished all work on it).
    void onSetRelease(sk_sp<RefCntedReleaseProc> releaseHelper) override {
        // Forward the release proc on to GrD3DImage
        this->setResourceRelease(std::move(releaseHelper));
    }
};

#ifdef SK_BUILD_FOR_WIN
#pragma warning(pop)
#endif

#endif


text:
package cmd

import (
	"fmt"
	"os"

	"errors"
	"github.com/fatih/color"
	"github.com/hokaccha/go-prettyjson"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

var cfgFile string

var (
	autocompleteTarget string
	autocompleteType   string
)

// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
	Use:   "mirrorhub",
	Short: "Mirrorhub root command.",
}

var autocompleteCmd = &cobra.Command{
	Use:   "autocomplete",
	Short: "Generate shell autocompletion script for Mirrorhub",
	RunE: func(cmd *cobra.Command, args []string) error {
		if autocompleteType != "bash" {
			return errors.New("Only Bash is supported for now")
		}
		err := cmd.Root().GenBashCompletionFile(autocompleteTarget)
		if err != nil {
			return err
		}
		color.Green("Bash completion file for Mirrorhub saved to: " + autocompleteTarget)
		return nil
	},
}

// Execute adds all child commands to the root command sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
	if err := RootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}
}

func init() {
	cobra.OnInitialize(initConfig)

	RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.mirrorhub.yaml)")
	RootCmd.AddCommand(autocompleteCmd)

	autocompleteCmd.PersistentFlags().StringVarP(&autocompleteTarget, "completionfile", "", "/etc/bash_completion.d/mirrorhub.sh", "Autocompletion file")
	autocompleteCmd.PersistentFlags().StringVarP(&autocompleteType, "type", "", "bash", "Autocompletion type (currently only bash supported)")
	autocompleteCmd.PersistentFlags().SetAnnotation("completionfile", cobra.BashCompFilenameExt, []string{})
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
	if cfgFile != "" { // enable ability to specify config file via flag
		viper.SetConfigFile(cfgFile)
	}
	viper.SetConfigName(".mirrorhub") // name of config file (without extension)
	viper.SetEnvPrefix("MIRRORHUB")
	viper.AddConfigPath("$HOME")
	viper.AddConfigPath(".config")
	viper.AddConfigPath("/etc/mirrorhub")
	viper.AddConfigPath(".")
	viper.AutomaticEnv()

	viper.ReadInConfig()

	viper.SetDefault("Email", "admin@mirrorhub.io")
	viper.SetDefault("Password", "")
	viper.SetDefault("API", map[string]string{
		"gateway": "localhost:8080",
		"base":    "localhost:9000",
	})

}

func exit(msg string) {
	color.Red(msg)
	os.Exit(1)
}

func ret(val interface{}, err error) {
	s, _ := prettyjson.Marshal(val)
	if err != nil {
		s, _ = prettyjson.Marshal(err.Error())
		color.Red(string(s))
		os.Exit(1)
	}
	fmt.Println(string(s))
	os.Exit(0)
}