answer stringlengths 15 1.25M |
|---|
package sun.security.krb5.internal;
import sun.security.krb5.KrbCryptoException;
public interface SeqNumber {
public void randInit();
public void init(int start);
public int current();
public int next();
public int step();
} |
/*! \file
*
* \brief res_stasis playback support.
*
* \author David M. Lee, II <dlee@digium.com>
*/
#include "asterisk.h"
<API key>(__FILE__, "$Revision$")
#include "asterisk/app.h"
#include "asterisk/astobj2.h"
#include "asterisk/bridge.h"
#include "asterisk/bridge_internal.h"
#include "asterisk/file.h"
#include "asterisk/logger.h"
#include "asterisk/module.h"
#include "asterisk/paths.h"
#include "asterisk/stasis_app_impl.h"
#include "asterisk/stasis_app_playback.h"
#include "asterisk/<API key>.h"
#include "asterisk/stasis_channels.h"
#include "asterisk/stringfields.h"
#include "asterisk/uuid.h"
#include "asterisk/say.h"
/*! Number of hash buckets for playback container. Keep it prime! */
#define PLAYBACK_BUCKETS 127
/*! Default number of milliseconds of media to skip */
#define <API key> 3000
#define SOUND_URI_SCHEME "sound:"
#define <API key> "recording:"
#define NUMBER_URI_SCHEME "number:"
#define DIGITS_URI_SCHEME "digits:"
#define <API key> "characters:"
/*! Container of all current playbacks */
static struct ao2_container *playbacks;
/*! Playback control object for res_stasis */
struct stasis_app_playback {
<API key>(
AST_STRING_FIELD(id); /*!< Playback unique id */
AST_STRING_FIELD(media); /*!< Playback media uri */
AST_STRING_FIELD(language); /*!< Preferred language */
AST_STRING_FIELD(target); /*!< Playback device uri */
);
/*! Control object for the channel we're playing back to */
struct stasis_app_control *control;
/*! Number of milliseconds to skip before playing */
long offsetms;
/*! Number of milliseconds to skip for forward/reverse operations */
int skipms;
/*! Condition for waiting on done to be set */
ast_cond_t done_cond;
/*! Number of milliseconds of media that has been played */
long playedms;
/*! Current playback state */
enum <API key> state;
/*! Set when playback has been completed */
unsigned int done:1;
/*! Set when the playback can be controlled */
unsigned int controllable:1;
};
static struct ast_json *playback_to_json(struct stasis_message *message,
const struct <API key> *sanitize)
{
struct ast_channel_blob *channel_blob = stasis_message_data(message);
struct ast_json *blob = channel_blob->blob;
const char *state =
ast_json_string_get(ast_json_object_get(blob, "state"));
const char *type;
if (!strcmp(state, "playing")) {
type = "PlaybackStarted";
} else if (!strcmp(state, "done")) {
type = "PlaybackFinished";
} else {
return NULL;
}
return ast_json_pack("{s: s, s: O}",
"type", type,
"playback", blob);
}
<API key>(<API key>,
.to_json = playback_to_json,
);
static void playback_dtor(void *obj)
{
struct stasis_app_playback *playback = obj;
<API key>(playback);
ast_cond_destroy(&playback->done_cond);
}
static struct stasis_app_playback *playback_create(
struct stasis_app_control *control)
{
RAII_VAR(struct stasis_app_playback *, playback, NULL, ao2_cleanup);
char id[AST_UUID_STR_LEN];
int res;
if (!control) {
return NULL;
}
playback = ao2_alloc(sizeof(*playback), playback_dtor);
if (!playback || <API key>(playback, 128)) {
return NULL;
}
res = ast_cond_init(&playback->done_cond, NULL);
if (res != 0) {
ast_log(LOG_ERROR, "Error creating done condition: %s\n",
strerror(errno));
return NULL;
}
<API key>(id, sizeof(id));
<API key>(playback, id, id);
playback->control = control;
ao2_ref(playback, +1);
return playback;
}
static int playback_hash(const void *obj, int flags)
{
const struct stasis_app_playback *playback = obj;
const char *id = flags & OBJ_KEY ? obj : playback->id;
return ast_str_hash(id);
}
static int playback_cmp(void *obj, void *arg, int flags)
{
struct stasis_app_playback *lhs = obj;
struct stasis_app_playback *rhs = arg;
const char *rhs_id = flags & OBJ_KEY ? arg : rhs->id;
if (strcmp(lhs->id, rhs_id) == 0) {
return CMP_MATCH | CMP_STOP;
} else {
return 0;
}
}
static const char *state_to_string(enum <API key> state)
{
switch (state) {
case <API key>:
return "queued";
case <API key>:
return "playing";
case <API key>:
return "paused";
case <API key>:
case <API key>:
case <API key>:
/* It doesn't really matter how we got here, but all of these
* states really just mean 'done' */
return "done";
case <API key>:
break;
}
return "?";
}
static void playback_publish(struct stasis_app_playback *playback)
{
RAII_VAR(struct ast_json *, json, NULL, ast_json_unref);
RAII_VAR(struct <API key> *, snapshot, NULL, ao2_cleanup);
RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
ast_assert(playback != NULL);
json = <API key>(playback);
if (json == NULL) {
return;
}
message = <API key>(
<API key>(playback->control),
<API key>(), json);
if (message == NULL) {
return;
}
<API key>(playback->control, message);
}
static int <API key>(struct stasis_app_playback *playback,
const char *uniqueid)
{
int res;
SCOPED_AO2LOCK(lock, playback);
if (playback->state == <API key>) {
ast_log(LOG_NOTICE, "%s: Playback canceled for %s\n",
uniqueid, playback->media);
res = -1;
} else {
res = 0;
playback->state = <API key>;
}
playback_publish(playback);
return res;
}
static void <API key>(struct stasis_app_playback *playback,
long playedms, int res, const char *uniqueid)
{
SCOPED_AO2LOCK(lock, playback);
playback->playedms = playedms;
if (res == 0) {
playback->state = <API key>;
} else {
if (playback->state == <API key>) {
ast_log(LOG_NOTICE, "%s: Playback stopped for %s\n",
uniqueid, playback->media);
} else {
ast_log(LOG_WARNING, "%s: Playback failed for %s\n",
uniqueid, playback->media);
playback->state = <API key>;
}
}
playback_publish(playback);
}
/*!
* \brief RAII_VAR function to mark a playback as done when leaving scope.
*/
static void mark_as_done(struct stasis_app_playback *playback)
{
SCOPED_AO2LOCK(lock, playback);
playback->done = 1;
ast_cond_broadcast(&playback->done_cond);
}
static void play_on_channel(struct stasis_app_playback *playback,
struct ast_channel *chan)
{
RAII_VAR(struct stasis_app_playback *, mark_when_done, playback,
mark_as_done);
int res;
long offsetms;
/* Even though these local variables look fairly pointless, the avoid
* having a bunch of NULL's passed directly into
* <API key>() */
const char *fwd = NULL;
const char *rev = NULL;
const char *stop = NULL;
const char *pause = NULL;
const char *restart = NULL;
ast_assert(playback != NULL);
offsetms = playback->offsetms;
res = <API key>(playback, <API key>(chan));
if (res != 0) {
return;
}
if (ast_channel_state(chan) != AST_STATE_UP) {
ast_indicate(chan, <API key>);
}
if (ast_begins_with(playback->media, SOUND_URI_SCHEME)) {
playback->controllable = 1;
/* Play sound */
res = <API key>(chan, playback->media + strlen(SOUND_URI_SCHEME),
fwd, rev, stop, pause, restart, playback->skipms, playback->language,
&offsetms);
} else if (ast_begins_with(playback->media, <API key>)) {
/* Play recording */
RAII_VAR(struct <API key> *, recording, NULL,
ao2_cleanup);
const char *relname =
playback->media + strlen(<API key>);
recording = <API key>(relname);
if (!recording) {
ast_log(LOG_ERROR, "Attempted to play recording '%s' on channel '%s' but recording does not exist",
ast_channel_name(chan), relname);
return;
}
playback->controllable = 1;
res = <API key>(chan,
<API key>(recording), fwd, rev, stop, pause,
restart, playback->skipms, playback->language, &offsetms);
} else if (ast_begins_with(playback->media, NUMBER_URI_SCHEME)) {
int number;
if (sscanf(playback->media + strlen(NUMBER_URI_SCHEME), "%30d", &number) != 1) {
ast_log(LOG_ERROR, "Attempted to play number '%s' on channel '%s' but number is invalid",
ast_channel_name(chan), playback->media + strlen(NUMBER_URI_SCHEME));
return;
}
res = ast_say_number(chan, number, stop, playback->language, NULL);
} else if (ast_begins_with(playback->media, DIGITS_URI_SCHEME)) {
res = ast_say_digit_str(chan, playback->media + strlen(DIGITS_URI_SCHEME),
stop, playback->language);
} else if (ast_begins_with(playback->media, <API key>)) {
res = <API key>(chan, playback->media + strlen(<API key>),
stop, playback->language, AST_SAY_CASE_NONE);
} else {
/* Play URL */
ast_log(LOG_ERROR, "Attempted to play URI '%s' on channel '%s' but scheme is unsupported",
ast_channel_name(chan), playback->media);
return;
}
<API key>(playback, offsetms, res,
<API key>(chan));
return;
}
/*!
* \brief Special case code to play while a channel is in a bridge.
*
* \param bridge_channel The channel's bridge_channel.
* \param playback_id Id of the playback to start.
*/
static void <API key>(struct ast_bridge_channel *bridge_channel,
const char *playback_id)
{
RAII_VAR(struct stasis_app_playback *, playback, NULL, ao2_cleanup);
playback = <API key>(playback_id);
if (!playback) {
ast_log(LOG_ERROR, "Couldn't find playback %s\n",
playback_id);
return;
}
play_on_channel(playback, bridge_channel->chan);
}
/*!
* \brief \ref RAII_VAR function to remove a playback from the global list when
* leaving scope.
*/
static void <API key>(struct stasis_app_playback *playback)
{
ao2_unlink_flags(playbacks, playback,
OBJ_POINTER | OBJ_UNLINK | OBJ_NODATA);
}
static int play_uri(struct stasis_app_control *control,
struct ast_channel *chan, void *data)
{
RAII_VAR(struct stasis_app_playback *, playback, NULL,
<API key>);
struct ast_bridge *bridge;
int res;
playback = data;
if (!control) {
return -1;
}
bridge = <API key>(control);
if (bridge) {
struct ast_bridge_channel *bridge_chan;
/* Queue up playback on the bridge */
ast_bridge_lock(bridge);
bridge_chan = bridge_find_channel(bridge, chan);
if (bridge_chan) {
<API key>(
bridge_chan,
<API key>,
playback->id,
NULL); /* moh_class */
}
ast_bridge_unlock(bridge);
/* Wait for playback to complete */
ao2_lock(playback);
while (!playback->done) {
res = ast_cond_wait(&playback->done_cond,
<API key>(playback));
if (res != 0) {
ast_log(LOG_ERROR,
"Error waiting for playback to complete: %s\n",
strerror(errno));
}
}
ao2_unlock(playback);
} else {
play_on_channel(playback, chan);
}
return 0;
}
static void set_target_uri(
struct stasis_app_playback *playback,
enum <API key> target_type,
const char *target_id)
{
const char *type = NULL;
switch (target_type) {
case <API key>:
type = "channel";
break;
case <API key>:
type = "bridge";
break;
}
ast_assert(type != NULL);
<API key>(playback, target, "%s:%s", type, target_id);
}
struct stasis_app_playback *<API key>(
struct stasis_app_control *control, const char *uri,
const char *language, const char *target_id,
enum <API key> target_type,
int skipms, long offsetms)
{
RAII_VAR(struct stasis_app_playback *, playback, NULL, ao2_cleanup);
if (skipms < 0 || offsetms < 0) {
return NULL;
}
ast_debug(3, "%s: Sending play(%s) command\n",
<API key>(control), uri);
playback = playback_create(control);
if (skipms == 0) {
skipms = <API key>;
}
<API key>(playback, media, uri);
<API key>(playback, language, language);
set_target_uri(playback, target_type, target_id);
playback->skipms = skipms;
playback->offsetms = offsetms;
ao2_link(playbacks, playback);
playback->state = <API key>;
playback_publish(playback);
/* A ref is kept in the playbacks container; no need to bump */
<API key>(control, play_uri, playback);
/* Although this should be bumped for the caller */
ao2_ref(playback, +1);
return playback;
}
enum <API key> <API key>(
struct stasis_app_playback *control)
{
SCOPED_AO2LOCK(lock, control);
return control->state;
}
const char *<API key>(
struct stasis_app_playback *control)
{
/* id is immutable; no lock needed */
return control->id;
}
struct stasis_app_playback *<API key>(const char *id)
{
return ao2_find(playbacks, id, OBJ_KEY);
}
struct ast_json *<API key>(
const struct stasis_app_playback *playback)
{
RAII_VAR(struct ast_json *, json, NULL, ast_json_unref);
if (playback == NULL) {
return NULL;
}
json = ast_json_pack("{s: s, s: s, s: s, s: s, s: s}",
"id", playback->id,
"media_uri", playback->media,
"target_uri", playback->target,
"language", playback->language,
"state", state_to_string(playback->state));
return ast_json_ref(json);
}
typedef int (*<API key>)(struct stasis_app_playback *playback);
static int playback_noop(struct stasis_app_playback *playback)
{
return 0;
}
static int playback_cancel(struct stasis_app_playback *playback)
{
SCOPED_AO2LOCK(lock, playback);
playback->state = <API key>;
return 0;
}
static int playback_stop(struct stasis_app_playback *playback)
{
SCOPED_AO2LOCK(lock, playback);
if (!playback->controllable) {
return -1;
}
playback->state = <API key>;
return <API key>(playback->control,
<API key>);
}
static int playback_restart(struct stasis_app_playback *playback)
{
SCOPED_AO2LOCK(lock, playback);
if (!playback->controllable) {
return -1;
}
return <API key>(playback->control,
<API key>);
}
static int playback_pause(struct stasis_app_playback *playback)
{
SCOPED_AO2LOCK(lock, playback);
if (!playback->controllable) {
return -1;
}
playback->state = <API key>;
playback_publish(playback);
return <API key>(playback->control,
<API key>);
}
static int playback_unpause(struct stasis_app_playback *playback)
{
SCOPED_AO2LOCK(lock, playback);
if (!playback->controllable) {
return -1;
}
playback->state = <API key>;
playback_publish(playback);
return <API key>(playback->control,
<API key>);
}
static int playback_reverse(struct stasis_app_playback *playback)
{
SCOPED_AO2LOCK(lock, playback);
if (!playback->controllable) {
return -1;
}
return <API key>(playback->control,
<API key>);
}
static int playback_forward(struct stasis_app_playback *playback)
{
SCOPED_AO2LOCK(lock, playback);
if (!playback->controllable) {
return -1;
}
return <API key>(playback->control,
<API key>);
}
/*!
* \brief A sparse array detailing how commands should be handled in the
* various playback states. Unset entries imply invalid operations.
*/
<API key> operations[<API key>][<API key>] = {
[<API key>][<API key>] = playback_cancel,
[<API key>][<API key>] = playback_noop,
[<API key>][<API key>] = playback_stop,
[<API key>][<API key>] = playback_restart,
[<API key>][<API key>] = playback_pause,
[<API key>][<API key>] = playback_noop,
[<API key>][<API key>] = playback_reverse,
[<API key>][<API key>] = playback_forward,
[<API key>][<API key>] = playback_stop,
[<API key>][<API key>] = playback_noop,
[<API key>][<API key>] = playback_unpause,
[<API key>][<API key>] = playback_noop,
[<API key>][<API key>] = playback_noop,
[<API key>][<API key>] = playback_noop,
};
enum <API key> <API key>(
struct stasis_app_playback *playback,
enum <API key> operation)
{
<API key> cb;
SCOPED_AO2LOCK(lock, playback);
ast_assert(playback->state >= 0 && playback->state < <API key>);
if (operation < 0 || operation >= <API key>) {
ast_log(LOG_ERROR, "Invalid playback operation %d\n", operation);
return -1;
}
cb = operations[playback->state][operation];
if (!cb) {
if (playback->state != <API key>) {
/* So we can be specific in our error message. */
return <API key>;
} else {
/* And, really, all operations should be valid during
* playback */
ast_log(LOG_ERROR,
"Unhandled operation during playback: %d\n",
operation);
return <API key>;
}
}
return cb(playback) ?
<API key> : <API key>;
}
static int load_module(void)
{
int r;
r = <API key>(<API key>);
if (r != 0) {
return <API key>;
}
playbacks = ao2_container_alloc(PLAYBACK_BUCKETS, playback_hash,
playback_cmp);
if (!playbacks) {
return <API key>;
}
return <API key>;
}
static int unload_module(void)
{
ao2_cleanup(playbacks);
playbacks = NULL;
<API key>(<API key>);
return 0;
}
AST_MODULE_INFO(ASTERISK_GPL_KEY, <API key>, "Stasis application playback support",
.load = load_module,
.unload = unload_module,
.nonoptreq = "res_stasis,<API key>"); |
#include <glib.h>
#include <stdio.h>
#include "histogram.h"
#define <API key> ((gint8) 10)
static const gint8 cards_per_type[<API key>] =
{
4,
4,
4,
4,
4,
4,
4,
4,
16,
4
};
Histogram *create_histogram( gint num_decks )
{
Histogram *hist;
hist = g_new(Histogram, 1);
if (hist == NULL)
{
g_error("Failed to allocated memory for histogram\n");
}
else
{
hist->histogram = g_new0(gint, <API key>);
if (hist->histogram == NULL)
{
}
else
{
reset_histogram( hist );
hist->num_decks = num_decks;
}
}
return hist;
}
void update_histogram( Histogram *hist, gint8 card )
{
hist->histogram[card - TWO]++;
}
gint get_histogram_count( Histogram *hist, gint8 card )
{
return hist->histogram[card - TWO];
}
gint get_bust_odds( Histogram *hist, gint8 value )
{
gint percent_failure = 0;
gint index;
gint count;
gint bust_value = BUST - value;
gint num_ok = 0;
gint num_bust = 0;
if ( value >= 21 )
{
/* If we have busted already or have a blackjack, then the bust odds are 100% */
percent_failure = PERCENT;
}
else if (bust_value > 10)
{
/* If need more than 10 to bust than is cannot happen so then the bust odds are 0% */
percent_failure = 0;
}
else
{
for (index = TWO; index < bust_value; index++)
{
count = get_histogram_count(hist, index);
num_ok += (cards_per_type[index - TWO] * hist->num_decks) - count;
}
/*
* An ace has a value of one, so the only time an ace would cause a bust
* is if we hit on 21, and this is not a valid thing to do. Therefore, ace's
* are always OK.
*/
count = get_histogram_count(hist, ACE);
num_ok += (cards_per_type[ACE - TWO] * hist->num_decks) - count;
for (; index <= TEN; index++)
{
count = get_histogram_count(hist, index);
num_bust += (cards_per_type[index - TWO] * hist->num_decks) - count;
}
percent_failure = (num_bust * PERCENT) / (num_bust + num_ok);
}
return percent_failure;
}
void reset_histogram ( Histogram *hist )
{
gint index;
for (index = 0; index < <API key>; index++)
{
hist->histogram[index] = 0;
}
}
void destory_histogram ( Histogram *hist )
{
g_free( hist->histogram );
g_free( hist );
} |
#pragma once
#include <wtf/Vector.h>
namespace WebCore {
WEBCORE_EXPORT void <API key>(size_t);
template <class Collection, class Iterator>
class <API key> {
public:
explicit <API key>(const Collection&);
typedef typename std::iterator_traits<Iterator>::value_type NodeType;
unsigned nodeCount(const Collection&);
NodeType* nodeAt(const Collection&, unsigned index);
bool hasValidCache(const Collection& collection) const { return m_current != collection.collectionEnd() || m_nodeCountValid || m_listValid; }
void invalidate(const Collection&);
size_t memoryCost()
{
// memoryCost() may be invoked concurrently from a GC thread, and we need to be careful
// about what data we access here and how. Accessing m_cachedList.capacity() is safe
// because it doesn't involve any pointer chasing.
return m_cachedList.capacity() * sizeof(NodeType*);
}
private:
unsigned <API key>(const Collection&);
NodeType* traverseBackwardTo(const Collection&, unsigned);
NodeType* traverseForwardTo(const Collection&, unsigned);
Iterator m_current;
unsigned m_currentIndex;
unsigned m_nodeCount;
Vector<NodeType*> m_cachedList;
bool m_nodeCountValid : 1;
bool m_listValid : 1;
};
template <class Collection, class Iterator>
inline <API key><Collection, Iterator>::<API key>(const Collection& collection)
: m_current(collection.collectionEnd())
, m_currentIndex(0)
, m_nodeCount(0)
, m_nodeCountValid(false)
, m_listValid(false)
{
}
template <class Collection, class Iterator>
inline unsigned <API key><Collection, Iterator>::nodeCount(const Collection& collection)
{
if (!m_nodeCountValid) {
if (!hasValidCache(collection))
collection.<API key>();
m_nodeCount = <API key>(collection);
m_nodeCountValid = true;
}
return m_nodeCount;
}
template <class Collection, class Iterator>
unsigned <API key><Collection, Iterator>::<API key>(const Collection& collection)
{
auto current = collection.collectionBegin();
auto end = collection.collectionEnd();
if (current == end)
return 0;
unsigned oldCapacity = m_cachedList.capacity();
while (current != end) {
m_cachedList.append(&*current);
unsigned traversed;
collection.<API key>(current, 1, traversed);
ASSERT(traversed == (current != end ? 1 : 0));
}
m_listValid = true;
if (unsigned capacityDifference = m_cachedList.capacity() - oldCapacity)
<API key>(capacityDifference * sizeof(NodeType*));
return m_cachedList.size();
}
template <class Collection, class Iterator>
inline typename <API key><Collection, Iterator>::NodeType* <API key><Collection, Iterator>::traverseBackwardTo(const Collection& collection, unsigned index)
{
ASSERT(m_current != collection.collectionEnd());
ASSERT(index < m_currentIndex);
bool firstIsCloser = index < m_currentIndex - index;
if (firstIsCloser || !collection.<API key>()) {
m_current = collection.collectionBegin();
m_currentIndex = 0;
if (index)
collection.<API key>(m_current, index, m_currentIndex);
ASSERT(m_current != collection.collectionEnd());
return &*m_current;
}
collection.<API key>(m_current, m_currentIndex - index);
m_currentIndex = index;
ASSERT(m_current != collection.collectionEnd());
return &*m_current;
}
template <class Collection, class Iterator>
inline typename <API key><Collection, Iterator>::NodeType* <API key><Collection, Iterator>::traverseForwardTo(const Collection& collection, unsigned index)
{
ASSERT(m_current != collection.collectionEnd());
ASSERT(index > m_currentIndex);
ASSERT(!m_nodeCountValid || index < m_nodeCount);
bool lastIsCloser = m_nodeCountValid && m_nodeCount - index < index - m_currentIndex;
if (lastIsCloser && collection.<API key>()) {
ASSERT(hasValidCache(collection));
m_current = collection.collectionLast();
if (index < m_nodeCount - 1)
collection.<API key>(m_current, m_nodeCount - index - 1);
m_currentIndex = index;
ASSERT(m_current != collection.collectionEnd());
return &*m_current;
}
if (!hasValidCache(collection))
collection.<API key>();
unsigned traversedCount;
collection.<API key>(m_current, index - m_currentIndex, traversedCount);
m_currentIndex = m_currentIndex + traversedCount;
if (m_current == collection.collectionEnd()) {
ASSERT(m_currentIndex < index);
// Failed to find the index but at least we now know the size.
m_nodeCount = m_currentIndex + 1;
m_nodeCountValid = true;
return nullptr;
}
ASSERT(hasValidCache(collection));
return &*m_current;
}
template <class Collection, class Iterator>
inline typename <API key><Collection, Iterator>::NodeType* <API key><Collection, Iterator>::nodeAt(const Collection& collection, unsigned index)
{
if (m_nodeCountValid && index >= m_nodeCount)
return nullptr;
if (m_listValid)
return m_cachedList[index];
auto end = collection.collectionEnd();
if (m_current != end) {
if (index > m_currentIndex)
return traverseForwardTo(collection, index);
if (index < m_currentIndex)
return traverseBackwardTo(collection, index);
return &*m_current;
}
bool lastIsCloser = m_nodeCountValid && m_nodeCount - index < index;
if (lastIsCloser && collection.<API key>()) {
ASSERT(hasValidCache(collection));
m_current = collection.collectionLast();
if (index < m_nodeCount - 1)
collection.<API key>(m_current, m_nodeCount - index - 1);
m_currentIndex = index;
ASSERT(m_current != end);
return &*m_current;
}
if (!hasValidCache(collection))
collection.<API key>();
m_current = collection.collectionBegin();
m_currentIndex = 0;
if (index && m_current != end) {
collection.<API key>(m_current, index, m_currentIndex);
ASSERT(m_current != end || m_currentIndex < index);
}
if (m_current == end) {
// Failed to find the index but at least we now know the size.
m_nodeCount = index ? m_currentIndex + 1 : 0;
m_nodeCountValid = true;
return nullptr;
}
ASSERT(hasValidCache(collection));
return &*m_current;
}
template <class Collection, class Iterator>
void <API key><Collection, Iterator>::invalidate(const Collection& collection)
{
m_current = collection.collectionEnd();
m_nodeCountValid = false;
m_listValid = false;
m_cachedList.shrink(0);
}
} |
/*
Patch by Polystar (Peter Vestman, Petter Edblom):
Corrected rfci handling in rate control messages
Added crc6 and crc10 checks for header and payload
*/
#include "config.h"
#include <glib.h>
#include <epan/packet.h>
#include <epan/prefs.h>
#include <epan/wmem/wmem.h>
#include <epan/expert.h>
#include <epan/crc10-tvb.h>
#include <wsutil/crc10.h>
#include <wsutil/crc6.h>
void <API key>(void);
void proto_register_iuup(void);
typedef struct _iuup_rfci_t {
guint id;
guint sum_len;
guint num_of_subflows;
struct {
guint len;
} subflow[8];
struct _iuup_rfci_t* next;
} iuup_rfci_t;
typedef struct {
guint32 id;
guint num_of_subflows;
iuup_rfci_t* rfcis;
iuup_rfci_t* last_rfci;
} iuup_circuit_t;
static int proto_iuup = -1;
static int hf_iuup_direction = -1;
static int hf_iuup_circuit_id = -1;
static int hf_iuup_pdu_type = -1;
static int <API key> = -1;
static int hf_iuup_fqc = -1;
static int hf_iuup_rfci = -1;
static int hf_iuup_hdr_crc = -1;
static int hf_iuup_payload_crc = -1;
static int hf_iuup_ack_nack = -1;
static int <API key> = -1;
static int <API key> = -1;
static int <API key> = -1;
static int <API key> = -1;
static int hf_iuup_init_ti = -1;
static int <API key> = -1;
static int <API key> = -1;
static int <API key> = -1;
static int <API key> = -1;
static int hf_iuup_time_align = -1;
static int hf_iuup_spare_bytes = -1;
static int hf_iuup_spare_03 = -1;
/* static int hf_iuup_spare_0f = -1; */
/* static int hf_iuup_spare_c0 = -1; */
static int hf_iuup_spare_e0 = -1;
static int hf_iuup_spare_ff = -1;
static int hf_iuup_delay = -1;
static int hf_iuup_advance = -1;
static int hf_iuup_delta = -1;
static int <API key> = -1;
static int <API key>[] = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
static int <API key> = -1;
static int <API key> = -1;
static int hf_iuup_payload = -1;
static int <API key> = -1;
static int hf_iuup_init_rfci[] = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
static int <API key>[64][8] = {
{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1}
};
static int <API key>[] = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
static int <API key>[] = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
static int hf_iuup_init_ipti[] = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
static int <API key>[64][8] = {
{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1}
};
static int <API key>[] = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
static gint ett_iuup = -1;
static gint ett_rfci = -1;
static gint ett_ipti = -1;
static gint ett_support = -1;
static gint ett_time = -1;
static gint ett_rfciinds = -1;
static gint ett_payload = -1;
static gint <API key> = -1;
static expert_field ei_iuup_hdr_crc_bad = EI_INIT;
static expert_field <API key> = EI_INIT;
static expert_field <API key> = EI_INIT;
static expert_field <API key> = EI_INIT;
static expert_field ei_iuup_ack_nack = EI_INIT;
static expert_field ei_iuup_time_align = EI_INIT;
static expert_field <API key> = EI_INIT;
static expert_field ei_iuup_pdu_type = EI_INIT;
static GHashTable* circuits = NULL;
static dissector_handle_t data_handle = NULL;
static gboolean dissect_fields = FALSE;
static gboolean <API key> = FALSE;
static guint <API key> = 0;
#define <API key> 0
#define PDUTYPE_DATA_NO_CRC 1
#define <API key> 14
static const value_string iuup_pdu_types[] = {
{<API key>,"Data with CRC"},
{PDUTYPE_DATA_NO_CRC,"Data without CRC"},
{<API key>,"Control Procedure"},
{0,NULL}
};
static const value_string <API key>[] = {
{<API key>,"Data (CRC)"},
{PDUTYPE_DATA_NO_CRC,"Data (no CRC)"},
{<API key>,""},
{0,NULL}
};
#define ACKNACK_ACK 0x4
#define ACKNACK_NACK 0x8
#define ACKNACK_RESERVED 0xc
#define ACKNACK_PROC 0x0
static const value_string iuup_acknack_vals[] = {
{ACKNACK_PROC >> 2,"Procedure"},
{ACKNACK_ACK >> 2,"ACK"},
{ACKNACK_NACK >> 2,"NACK"},
{ACKNACK_RESERVED >> 2,"Reserved"},
{0,NULL}
};
static const value_string <API key>[] = {
{ACKNACK_PROC,""},
{ACKNACK_ACK,"ACK "},
{ACKNACK_NACK,"NACK "},
{ACKNACK_RESERVED,"Reserved "},
{0,NULL}
};
#define PROC_INIT 0
#define PROC_RATE 1
#define PROC_TIME 2
#define PROC_ERROR 3
static const value_string iuup_procedures[] = {
{PROC_INIT,"Initialization"},
{PROC_RATE,"Rate Control"},
{PROC_TIME,"Time Alignment"},
{PROC_ERROR,"Error Event"},
{4,"Reserved(4)"},
{5,"Reserved(5)"},
{6,"Reserved(6)"},
{7,"Reserved(7)"},
{8,"Reserved(8)"},
{9,"Reserved(9)"},
{10,"Reserved(10)"},
{11,"Reserved(11)"},
{12,"Reserved(12)"},
{13,"Reserved(13)"},
{14,"Reserved(14)"},
{15,"Reserved(15)"},
{0,NULL}
};
static const value_string <API key>[] = {
{PROC_INIT,"Initialization "},
{PROC_RATE,"Rate Control "},
{PROC_TIME,"Time Alignment "},
{PROC_ERROR,"Error Event "},
{0,NULL}
};
static const value_string <API key>[] = {
{0, "Reporting local error"},
{1, "First forwarding of error event report"},
{2, "Second forwarding of error event report"},
{3, "Reserved"},
{0,NULL}
};
static const value_string iuup_error_causes[] = {
{0, "CRC error of frame header"},
{1, "CRC error of frame payload"},
{2, "Unexpected frame number"},
{3, "Frame loss"},
{4, "PDU type unknown"},
{5, "Unknown procedure"},
{6, "Unknown reserved value"},
{7, "Unknown field"},
{8, "Frame too short"},
{9, "Missing fields"},
{16, "Unexpected PDU type"},
{18, "Unexpected procedure"},
{19, "Unexpected RFCI"},
{20, "Unexpected value"},
{42, "Initialisation failure"},
{43, "Initialisation failure (network error, timer expiry)"},
{44, "Initialisation failure (Iu UP function error, repeated NACK)"},
{45, "Rate control failure"},
{46, "Error event failure"},
{47, "Time Alignment not supported"},
{48, "Requested Time Alignment not possible"},
{49, "Iu UP Mode version not supported"},
{0,NULL}
};
static const value_string iuup_rfci_indicator[] = {
{0, "RFCI allowed"},
{1, "RFCI barred"},
{0,NULL}
};
static const value_string iuup_ti_vals[] = {
{0, "IPTIs not present"},
{1, "IPTIs present in frame"},
{0,NULL}
};
static const value_string <API key>[] = {
{0, "not supported"},
{1, "supported"},
{0,NULL}
};
static const value_string <API key>[] = {
{0, "one octet used"},
{1, "two octets used"},
{0,NULL}
};
static const value_string <API key>[] = {
{0, "this frame is the last frame for the procedure"},
{1, "additional frames will be sent for the procedure"},
{0,NULL}
};
static const value_string iuup_init_lri_vals[] = {
{0, "Not last RFCI"},
{1, "Last RFCI in current frame"},
{0,NULL}
};
static const value_string <API key>[] = {
{0, "PDU type 0"},
{1, "PDU type 1"},
{0,NULL}
};
static const value_string iuup_fqcs[] = {
{0, "Frame Good"},
{1, "Frame BAD"},
{2, "Frame bad due to radio"},
{3, "spare"},
{0,NULL}
};
static proto_item*
<API key>(proto_tree* tree, int hf, tvbuff_t* tvb, int offset, int bit_offset, guint bits, guint8** buf) {
static const guint8 masks[] = {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe};
int len = (bits + bit_offset)/8 + (((bits + bit_offset)%8) ? 0 : 1);
guint8* shifted_buffer;
proto_item* pi;
int i;
DISSECTOR_ASSERT(bit_offset < 8);
shifted_buffer = (guint8 *)tvb_memdup(wmem_packet_scope(),tvb,offset,len+1);
for(i = 0; i < len; i++) {
shifted_buffer[i] <<= bit_offset;
shifted_buffer[i] |= (shifted_buffer[i+1] & masks[bit_offset]) >> (8 - bit_offset);
}
shifted_buffer[len] <<= bit_offset;
shifted_buffer[len] &= masks[(bits + bit_offset)%8];
if (buf)
*buf = shifted_buffer;
pi = <API key>(tree, hf, tvb, offset, len + (((bits + bit_offset)%8) ? 1 : 0) , shifted_buffer);
<API key>(pi, " (%i Bits)", bits);
return pi;
}
static void <API key>(tvbuff_t* tvb, packet_info* pinfo, proto_tree* tree, guint rfci_id _U_, int offset) {
iuup_circuit_t* iuup_circuit;
iuup_rfci_t *rfci;
int last_offset = tvb_length(tvb) - 1;
guint bit_offset = 0;
proto_item* pi;
pi = proto_tree_add_item(tree,hf_iuup_payload,tvb,offset,-1,ENC_NA);
if ( ! dissect_fields ) {
return;
} else if ( ! pinfo->circuit_id
|| ! ( iuup_circuit = (iuup_circuit_t *)g_hash_table_lookup(circuits,GUINT_TO_POINTER(pinfo->circuit_id)) ) ) {
expert_add_info(pinfo, pi, &<API key>);
return;
}
for(rfci = iuup_circuit->rfcis; rfci; rfci = rfci->next)
if ( rfci->id == rfci_id )
break;
if (!rfci) {
expert_add_info(pinfo, pi, &<API key>);
return;
}
tree = <API key>(pi,ett_payload);
do {
guint i;
guint subflows = rfci->num_of_subflows;
proto_tree* flow_tree;
flow_tree = <API key>(tree,tvb,offset,-1,<API key>,NULL,"Payload Frame");
bit_offset = 0;
for(i = 0; i < subflows; i++) {
if (! rfci->subflow[i].len)
continue;
<API key>(flow_tree, <API key>[rfci->id][i], tvb,
offset + (bit_offset/8),
bit_offset % 8,
rfci->subflow[i].len,
NULL);
bit_offset += rfci->subflow[i].len;
}
offset += (bit_offset / 8) + ((bit_offset % 8) ? 1 : 0);
} while (offset <= last_offset);
}
static guint dissect_rfcis(tvbuff_t* tvb, packet_info* pinfo _U_, proto_tree* tree, int* offset, iuup_circuit_t* iuup_circuit) {
proto_item* pi;
proto_tree* pt;
guint8 oct;
guint c = 0;
guint i;
do {
iuup_rfci_t *rfci = wmem_new0(wmem_file_scope(), iuup_rfci_t);
guint len = 0;
DISSECTOR_ASSERT(c < 64);
pi = proto_tree_add_item(tree,<API key>,tvb,*offset,-1,ENC_NA);
pt = <API key>(pi,ett_rfci);
proto_tree_add_item(pt,<API key>[c],tvb,*offset,1,ENC_BIG_ENDIAN);
proto_tree_add_item(pt,<API key>[c],tvb,*offset,1,ENC_BIG_ENDIAN);
proto_tree_add_item(pt,hf_iuup_init_rfci[c],tvb,*offset,1,ENC_BIG_ENDIAN);
oct = tvb_get_guint8(tvb,*offset);
rfci->id = oct & 0x3f;
rfci->num_of_subflows = iuup_circuit->num_of_subflows;
len = (oct & 0x40) ? 2 : 1;
proto_item_set_text(pi,"RFCI %i Initialization",rfci->id);
proto_item_set_len(pi,(len*iuup_circuit->num_of_subflows)+1);
(*offset)++;
for(i = 0; i < iuup_circuit->num_of_subflows; i++) {
guint subflow_len;
if (len == 2) {
subflow_len = tvb_get_ntohs(tvb,*offset);
} else {
subflow_len = tvb_get_guint8(tvb,*offset);
}
rfci->subflow[i].len = subflow_len;
rfci->sum_len += subflow_len;
proto_tree_add_uint(pt,<API key>[c][i],tvb,*offset,len,subflow_len);
(*offset) += len;
}
if (iuup_circuit->last_rfci) {
iuup_circuit->last_rfci = iuup_circuit->last_rfci->next = rfci;
} else {
iuup_circuit->last_rfci = iuup_circuit->rfcis = rfci;
}
c++;
} while ( ! (oct & 0x80) );
return c - 1;
}
static void dissect_iuup_init(tvbuff_t* tvb, packet_info* pinfo, proto_tree* tree) {
int offset = 4;
guint8 oct = tvb_get_guint8(tvb,offset);
guint n = (oct & 0x0e) >> 1;
gboolean ti = oct & 0x10;
guint i;
guint rfcis;
proto_item* pi;
proto_tree* support_tree = NULL;
proto_tree* iptis_tree;
iuup_circuit_t* iuup_circuit = NULL;
if (pinfo->circuit_id) {
iuup_circuit = (iuup_circuit_t *)g_hash_table_lookup(circuits,GUINT_TO_POINTER(pinfo->circuit_id));
if (iuup_circuit) {
g_hash_table_remove(circuits,GUINT_TO_POINTER(pinfo->circuit_id));
}
iuup_circuit = wmem_new0(wmem_file_scope(), iuup_circuit_t);
} else {
iuup_circuit = wmem_new0(wmem_packet_scope(), iuup_circuit_t);
}
iuup_circuit->id = pinfo->circuit_id;
iuup_circuit->num_of_subflows = n;
iuup_circuit->rfcis = NULL;
iuup_circuit->last_rfci = NULL;
if (pinfo->circuit_id) {
g_hash_table_insert(circuits,GUINT_TO_POINTER(iuup_circuit->id),iuup_circuit);
}
if (tree) {
proto_tree_add_item(tree,hf_iuup_spare_e0,tvb,offset,1,ENC_BIG_ENDIAN);
proto_tree_add_item(tree,hf_iuup_init_ti,tvb,offset,1,ENC_BIG_ENDIAN);
proto_tree_add_item(tree,<API key>,tvb,offset,1,ENC_BIG_ENDIAN);
proto_tree_add_item(tree,<API key>,tvb,offset,1,ENC_BIG_ENDIAN);
}
offset++;
rfcis = dissect_rfcis(tvb, pinfo, tree, &offset, iuup_circuit);
if (!tree) return;
if (ti) {
iptis_tree = <API key>(tree,tvb,offset,(rfcis/2)+(rfcis%2),ett_ipti,NULL,"IPTIs");
for (i = 0; i <= rfcis; i++) {
proto_tree_add_item(iptis_tree,hf_iuup_init_ipti[i],tvb,offset,1,ENC_BIG_ENDIAN);
if ((i%2)) {
offset++;
}
}
if ((i%2)) {
offset++;
}
}
if (tree) {
pi = proto_tree_add_item(tree,<API key>,tvb,offset,2,ENC_BIG_ENDIAN);
support_tree = <API key>(pi,ett_support);
for (i = 0; i < 16; i++) {
proto_tree_add_item(support_tree,<API key>[i],tvb,offset,2,ENC_BIG_ENDIAN);
}
}
offset += 2;
proto_tree_add_item(tree,<API key>,tvb,offset,1,ENC_BIG_ENDIAN);
}
static void <API key>(tvbuff_t* tvb, packet_info* pinfo _U_, proto_tree* tree) {
guint num = tvb_get_guint8(tvb,4) & 0x3f;
guint i;
proto_item* pi;
proto_tree* inds_tree;
int offset = 4;
pi = proto_tree_add_item(tree,<API key>,tvb,4,1,ENC_BIG_ENDIAN);
inds_tree = <API key>(pi,ett_rfciinds);
for (i = 0; i < num; i++) {
if (! (i % 8) ) offset++;
proto_tree_add_item(inds_tree,<API key>[i],tvb,offset,1,ENC_BIG_ENDIAN);
}
}
static void add_hdr_crc(tvbuff_t* tvb, packet_info* pinfo, proto_item* iuup_tree, guint16 crccheck)
{
proto_item *crc_item;
crc_item = proto_tree_add_item(iuup_tree,hf_iuup_hdr_crc,tvb,2,1,ENC_BIG_ENDIAN);
if (crccheck) {
<API key>(crc_item, "%s", " [incorrect]");
expert_add_info(pinfo, crc_item, &ei_iuup_hdr_crc_bad);
}
}
static guint16
<API key>(tvbuff_t *tvb, int offset, int length)
{
guint16 crc10;
guint16 extra_16bits;
guint8 extra_8bits[2];
crc10 = <API key>(0, tvb, offset + 2, length);
extra_16bits = tvb_get_ntohs(tvb, offset) & 0x3FF;
extra_8bits[0] = extra_16bits >> 2;
extra_8bits[1] = (extra_16bits << 6) & 0xFF;
crc10 = <API key>(crc10, extra_8bits, 2);
return crc10;
}
static void add_payload_crc(tvbuff_t* tvb, packet_info* pinfo, proto_item* iuup_tree)
{
proto_item *crc_item;
int length = tvb_length(tvb);
guint16 crccheck = <API key>(tvb, 2, length - 4);
crc_item = proto_tree_add_item(iuup_tree,hf_iuup_payload_crc,tvb,2,2,ENC_BIG_ENDIAN);
if (crccheck) {
<API key>(crc_item, "%s", " [incorrect]");
expert_add_info(pinfo, crc_item, &<API key>);
}
}
#define ACKNACK_MASK 0x0c
#define PROCEDURE_MASK 0x0f
#define FQC_MASK 0xc0
#define PDUTYPE_MASK 0xf0
static void dissect_iuup(tvbuff_t* tvb_in, packet_info* pinfo, proto_tree* tree) {
proto_item* pi;
proto_item* iuup_item = NULL;
proto_item* pdutype_item = NULL;
proto_tree* iuup_tree = NULL;
proto_item* proc_item = NULL;
proto_item* ack_item = NULL;
guint8 first_octet;
guint8 second_octet;
guint8 pdutype;
guint phdr = 0;
guint16 hdrcrc6;
guint16 crccheck;
tvbuff_t* tvb = tvb_in;
col_set_str(pinfo->cinfo, COL_PROTOCOL, "IuUP");
if (<API key>) {
int len = tvb_length(tvb_in) - 2;
phdr = tvb_get_ntohs(tvb,0);
proto_tree_add_item(tree,hf_iuup_direction,tvb,0,2,ENC_BIG_ENDIAN);
proto_tree_add_item(tree,hf_iuup_circuit_id,tvb,0,2,ENC_BIG_ENDIAN);
phdr &= 0x7fff;
pinfo->circuit_id = phdr;
tvb = <API key>(tvb_in,2,len);
}
first_octet = tvb_get_guint8(tvb,0);
second_octet = tvb_get_guint8(tvb,1);
hdrcrc6 = tvb_get_guint8(tvb, 2) >> 2;
crccheck = <API key>(hdrcrc6, first_octet, second_octet);
pdutype = ( first_octet & PDUTYPE_MASK ) >> 4;
if (tree) {
iuup_item = proto_tree_add_item(tree,proto_iuup,tvb,0,-1,ENC_NA);
iuup_tree = <API key>(iuup_item,ett_iuup);
pdutype_item = proto_tree_add_item(iuup_tree,hf_iuup_pdu_type,tvb,0,1,ENC_BIG_ENDIAN);
}
col_add_str(pinfo->cinfo, COL_INFO, val_to_str(pdutype, <API key>, "Unknown PDU Type(%u) "));
switch(pdutype) {
case <API key>:
col_append_fstr(pinfo->cinfo, COL_INFO,"FN: %x RFCI: %u", (guint)(first_octet & 0x0f) ,(guint)(second_octet & 0x3f));
proto_tree_add_item(iuup_tree,<API key>,tvb,0,1,ENC_BIG_ENDIAN);
pi = proto_tree_add_item(iuup_tree,hf_iuup_fqc,tvb,1,1,ENC_BIG_ENDIAN);
if (first_octet & FQC_MASK) {
expert_add_info(pinfo, pi, &<API key>);
}
if (!tree) return;
proto_tree_add_item(iuup_tree,hf_iuup_rfci,tvb,1,1,ENC_BIG_ENDIAN);
add_hdr_crc(tvb, pinfo, iuup_tree, crccheck);
add_payload_crc(tvb, pinfo, iuup_tree);
<API key>(tvb,pinfo,iuup_tree,second_octet & 0x3f,4);
return;
case PDUTYPE_DATA_NO_CRC:
col_append_fstr(pinfo->cinfo, COL_INFO," RFCI %u", (guint)(second_octet & 0x3f));
proto_tree_add_item(iuup_tree,<API key>,tvb,0,1,ENC_BIG_ENDIAN);
pi = proto_tree_add_item(iuup_tree,hf_iuup_fqc,tvb,1,1,ENC_BIG_ENDIAN);
if (first_octet & FQC_MASK) {
expert_add_info(pinfo, pi, &<API key>);
}
if (!tree)
return;
proto_tree_add_item(iuup_tree,hf_iuup_rfci,tvb,1,1,ENC_BIG_ENDIAN);
add_hdr_crc(tvb, pinfo, iuup_tree, crccheck);
<API key>(tvb,pinfo,iuup_tree,second_octet & 0x3f,3);
return;
case <API key>:
if (tree) {
ack_item = proto_tree_add_item(iuup_tree,hf_iuup_ack_nack,tvb,0,1,ENC_BIG_ENDIAN);
proto_tree_add_item(iuup_tree,<API key>,tvb,0,1,ENC_BIG_ENDIAN);
proto_tree_add_item(iuup_tree,<API key>,tvb,1,1,ENC_BIG_ENDIAN);
proc_item = proto_tree_add_item(iuup_tree,<API key>,tvb,1,1,ENC_BIG_ENDIAN);
add_hdr_crc(tvb, pinfo, iuup_tree, crccheck);
}
col_append_str(pinfo->cinfo, COL_INFO,
val_to_str(first_octet & ACKNACK_MASK,
<API key>, "[action:%u] "));
col_append_str(pinfo->cinfo, COL_INFO,
val_to_str(second_octet & PROCEDURE_MASK,
<API key>, "[proc:%u] "));
switch ( first_octet & ACKNACK_MASK ) {
case ACKNACK_ACK:
switch(second_octet & PROCEDURE_MASK) {
case PROC_INIT:
if (!tree) return;
proto_tree_add_item(iuup_tree,hf_iuup_spare_03,tvb,2,1,ENC_BIG_ENDIAN);
proto_tree_add_item(iuup_tree,hf_iuup_spare_ff,tvb,3,1,ENC_BIG_ENDIAN);
return;
case PROC_RATE:
if (!tree) return;
<API key>(tvb,pinfo,iuup_tree);
return;
case PROC_TIME:
case PROC_ERROR:
break;
default:
expert_add_info(pinfo, proc_item, &<API key>);
return;
}
break;
case ACKNACK_NACK:
pi = proto_tree_add_item(iuup_tree,<API key>,tvb,4,1,ENC_BIG_ENDIAN);
expert_add_info(pinfo, pi, &<API key>);
return;
case ACKNACK_RESERVED:
expert_add_info(pinfo, ack_item, &ei_iuup_ack_nack);
return;
case ACKNACK_PROC:
break;
}
switch( second_octet & PROCEDURE_MASK ) {
case PROC_INIT:
if (tree) add_payload_crc(tvb, pinfo, iuup_tree);
dissect_iuup_init(tvb,pinfo,iuup_tree);
return;
case PROC_RATE:
if (!tree) return;
add_payload_crc(tvb, pinfo, iuup_tree);
<API key>(tvb,pinfo,iuup_tree);
return;
case PROC_TIME:
{
proto_tree* time_tree;
guint ta;
ta = tvb_get_guint8(tvb,4);
pi = proto_tree_add_item(iuup_tree,hf_iuup_time_align,tvb,4,1,ENC_BIG_ENDIAN);
time_tree = <API key>(pi,ett_time);
if (ta >= 1 && ta <= 80) {
pi = proto_tree_add_uint(time_tree,hf_iuup_delay,tvb,4,1,ta * 500);
<API key>(pi);
pi = <API key>(time_tree,hf_iuup_delta,tvb,4,1,((gfloat)((gint)(ta) * 500))/(gfloat)1000000.0);
<API key>(pi);
} else if (ta >= 129 && ta <= 208) {
pi = proto_tree_add_uint(time_tree,hf_iuup_advance,tvb,4,1,(ta-128) * 500);
<API key>(pi);
pi = <API key>(time_tree,hf_iuup_delta,tvb,4,1,((gfloat)((gint)(-(((gint)ta)-128))) * 500)/(gfloat)1000000.0);
<API key>(pi);
} else {
expert_add_info(pinfo, pi, &ei_iuup_time_align);
}
proto_tree_add_item(iuup_tree,hf_iuup_spare_bytes,tvb,5,-1,ENC_NA);
return;
}
case PROC_ERROR:
col_append_str(pinfo->cinfo, COL_INFO, val_to_str(tvb_get_guint8(tvb,4) & 0x3f,iuup_error_causes,"Unknown (%u)"));
proto_tree_add_item(iuup_tree,<API key>,tvb,4,1,ENC_BIG_ENDIAN);
pi = proto_tree_add_item(iuup_tree,<API key>,tvb,4,1,ENC_BIG_ENDIAN);
expert_add_info(pinfo, pi, &<API key>);
proto_tree_add_item(iuup_tree,hf_iuup_spare_bytes,tvb,5,-1,ENC_NA);
return;
default: /* bad */
expert_add_info(pinfo, proc_item, &<API key>);
return;
}
default:
expert_add_info(pinfo, pdutype_item, &ei_iuup_pdu_type);
return;
}
}
static gboolean dissect_iuup_heur(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree) {
int len = tvb_length(tvb);
guint8 first_octet = tvb_get_guint8(tvb,0);
guint8 second_octet = tvb_get_guint8(tvb,1);
guint16 hdrcrc6 = tvb_get_guint8(tvb, 2) >> 2;
if (<API key>(hdrcrc6, first_octet, second_octet)) return FALSE;
switch ( first_octet & 0xf0 ) {
case 0x00: {
if (len<7) return FALSE;
if (<API key>(tvb, 4, len-4) ) return FALSE;
break;
}
case 0x10:
/* a FALSE positive factory */
if (len<5) return FALSE;
break;
case 0xe0:
if (len<5) return FALSE;
if( (second_octet & 0x0f) > 3) return FALSE;
break;
default:
return FALSE;
}
dissect_iuup(tvb, pinfo, tree);
return TRUE;
}
static void find_iuup(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree) {
int len = tvb_length(tvb);
int offset = 0;
while (len > 3) {
if ( dissect_iuup_heur(<API key>(tvb,offset), pinfo, tree) )
return;
offset++;
len
}
call_dissector(data_handle, tvb, pinfo, tree);
}
static void init_iuup(void) {
if (circuits)
<API key>(circuits);
circuits = g_hash_table_new(g_direct_hash,g_direct_equal);
}
void <API key>(void) {
static gboolean <API key> = FALSE;
static dissector_handle_t iuup_handle;
static guint <API key> = 0;
if (!<API key>) {
iuup_handle = find_dissector("iuup");
<API key>("<API key>","VND.3GPP.IUFP", iuup_handle);
data_handle = find_dissector("data");
<API key> = TRUE;
} else {
if ( <API key> > 95 ) {
<API key>("rtp.pt", <API key>, iuup_handle);
}
}
<API key> = <API key>;
if ( <API key> > 95 ) {
dissector_add_uint("rtp.pt", <API key>, iuup_handle);
}
}
#define HFS_RFCI(i) \
{ &<API key>[i], { "RFCI " #i, "iuup.rfci." #i, FT_UINT8, BASE_DEC, VALS(iuup_rfci_indicator),0x80>>(i%8),NULL,HFILL}}, \
{ &hf_iuup_init_rfci[i], { "RFCI " #i, "iuup.rfci." #i, FT_UINT8, BASE_DEC, NULL,0x3f,NULL,HFILL}}, \
{ &<API key>[i][0], { "RFCI " #i " Flow 0 Len", "iuup.rfci."#i".flow.0.len", FT_UINT16, BASE_DEC, NULL,0x0,NULL,HFILL}}, \
{ &<API key>[i][1], { "RFCI " #i " Flow 1 Len", "iuup.rfci."#i".flow.1.len", FT_UINT16, BASE_DEC, NULL,0x0,NULL,HFILL}}, \
{ &<API key>[i][2], { "RFCI " #i " Flow 2 Len", "iuup.rfci."#i".flow.2.len", FT_UINT16, BASE_DEC, NULL,0x0,NULL,HFILL}}, \
{ &<API key>[i][3], { "RFCI " #i " Flow 3 Len", "iuup.rfci."#i".flow.3.len", FT_UINT16, BASE_DEC, NULL,0x0,NULL,HFILL}}, \
{ &<API key>[i][4], { "RFCI " #i " Flow 4 Len", "iuup.rfci."#i".flow.4.len", FT_UINT16, BASE_DEC, NULL,0x0,NULL,HFILL}}, \
{ &<API key>[i][5], { "RFCI " #i " Flow 5 Len", "iuup.rfci."#i".flow.5.len", FT_UINT16, BASE_DEC, NULL,0x0,NULL,HFILL}}, \
{ &<API key>[i][6], { "RFCI " #i " Flow 6 Len", "iuup.rfci."#i".flow.6.len", FT_UINT16, BASE_DEC, NULL,0x0,NULL,HFILL}}, \
{ &<API key>[i][7], { "RFCI " #i " Flow 7 Len", "iuup.rfci."#i".flow.7.len", FT_UINT16, BASE_DEC, NULL,0x0,NULL,HFILL}}, \
{ &<API key>[i], { "RFCI " #i " LI", "iuup.rfci."#i".li", FT_UINT8, BASE_HEX, VALS(<API key>),0x40,"Length Indicator",HFILL}}, \
{ &<API key>[i], { "RFCI " #i " LRI", "iuup.rfci."#i".lri", FT_UINT8, BASE_HEX, VALS(iuup_init_lri_vals),0x80,"Last Record Indicator",HFILL}}, \
{ &<API key>[i][0], { "RFCI " #i " Flow 0", "iuup.rfci."#i".flow.0", FT_BYTES, BASE_NONE, NULL,0x0,NULL,HFILL}}, \
{ &<API key>[i][1], { "RFCI " #i " Flow 1", "iuup.rfci."#i".flow.1", FT_BYTES, BASE_NONE, NULL,0x0,NULL,HFILL}}, \
{ &<API key>[i][2], { "RFCI " #i " Flow 2", "iuup.rfci."#i".flow.2", FT_BYTES, BASE_NONE, NULL,0x0,NULL,HFILL}}, \
{ &<API key>[i][3], { "RFCI " #i " Flow 3", "iuup.rfci."#i".flow.3", FT_BYTES, BASE_NONE, NULL,0x0,NULL,HFILL}}, \
{ &<API key>[i][4], { "RFCI " #i " Flow 4", "iuup.rfci."#i".flow.4", FT_BYTES, BASE_NONE, NULL,0x0,NULL,HFILL}}, \
{ &<API key>[i][5], { "RFCI " #i " Flow 5", "iuup.rfci."#i".flow.5", FT_BYTES, BASE_NONE, NULL,0x0,NULL,HFILL}}, \
{ &<API key>[i][6], { "RFCI " #i " Flow 6", "iuup.rfci."#i".flow.6", FT_BYTES, BASE_NONE, NULL,0x0,NULL,HFILL}}, \
{ &<API key>[i][7], { "RFCI " #i " Flow 7", "iuup.rfci."#i".flow.7", FT_BYTES, BASE_NONE, NULL,0x0,NULL,HFILL}}, \
{ &hf_iuup_init_ipti[i], { "RFCI " #i " IPTI", "iuup.rfci."#i".ipti", FT_UINT8, BASE_HEX, NULL,i%2 ? 0x0F : 0xF0,NULL,HFILL}}
void proto_register_iuup(void) {
static hf_register_info hf[] = {
{ &hf_iuup_direction, { "Frame Direction", "iuup.direction", FT_UINT16, BASE_DEC, NULL,0x8000,NULL,HFILL}},
{ &hf_iuup_circuit_id, { "Circuit ID", "iuup.circuit_id", FT_UINT16, BASE_DEC, NULL,0x7fff,NULL,HFILL}},
{ &hf_iuup_pdu_type, { "PDU Type", "iuup.pdu_type", FT_UINT8, BASE_DEC, VALS(iuup_pdu_types),0xf0,NULL,HFILL}},
{ &<API key>, { "Frame Number", "iuup.framenum", FT_UINT8, BASE_DEC, NULL,0x0F,NULL,HFILL}},
{ &hf_iuup_fqc, { "FQC", "iuup.fqc", FT_UINT8, BASE_DEC, VALS(iuup_fqcs),0xc0,"Frame Quality Classification",HFILL}},
{ &hf_iuup_rfci, { "RFCI", "iuup.rfci", FT_UINT8, BASE_HEX, NULL, 0x3f, "RAB sub-Flow Combination Indicator",HFILL}},
{ &hf_iuup_hdr_crc, { "Header CRC", "iuup.header_crc", FT_UINT8, BASE_HEX, NULL,0xfc,NULL,HFILL}},
{ &hf_iuup_payload_crc, { "Payload CRC", "iuup.payload_crc", FT_UINT16, BASE_HEX, NULL,0x03FF,NULL,HFILL}},
{ &hf_iuup_ack_nack, { "Ack/Nack", "iuup.ack", FT_UINT8, BASE_DEC, VALS(iuup_acknack_vals),0x0c,NULL,HFILL}},
{ &<API key>, { "Frame Number", "iuup.framenum_t14", FT_UINT8, BASE_DEC, NULL,0x03,NULL,HFILL}},
{ &<API key>, { "Mode Version", "iuup.mode", FT_UINT8, BASE_HEX, NULL,0xf0,NULL,HFILL}},
{ &<API key>, { "Procedure", "iuup.procedure", FT_UINT8, BASE_DEC, VALS(iuup_procedures),0x0f,NULL,HFILL}},
{ &<API key>, { "Error Cause", "iuup.error_cause", FT_UINT8, BASE_DEC, VALS(iuup_error_causes),0xfc,NULL,HFILL}},
{ &<API key>, { "Error DISTANCE", "iuup.error_distance", FT_UINT8, BASE_DEC, VALS(<API key>),0xc0,NULL,HFILL}},
{ &<API key>, { "Error Cause", "iuup.errorevt_cause", FT_UINT8, BASE_DEC, NULL,0x3f,NULL,HFILL}},
{ &hf_iuup_time_align, { "Time Align", "iuup.time_align", FT_UINT8, BASE_HEX, NULL,0x0,NULL,HFILL}},
{ &<API key>, { "RFCI Data Pdu Type", "iuup.data_pdu_type", FT_UINT8, BASE_HEX, VALS(<API key>),0xF0,NULL,HFILL}},
{ &hf_iuup_spare_03, { "Spare", "iuup.spare", FT_UINT8, BASE_HEX, NULL,0x03,NULL,HFILL}},
#if 0
{ &hf_iuup_spare_0f, { "Spare", "iuup.spare", FT_UINT8, BASE_HEX, NULL,0x0f,NULL,HFILL}},
#endif
#if 0
{ &hf_iuup_spare_c0, { "Spare", "iuup.spare", FT_UINT8, BASE_HEX, NULL,0xc0,NULL,HFILL}},
#endif
{ &hf_iuup_spare_e0, { "Spare", "iuup.spare", FT_UINT8, BASE_HEX, NULL,0xe0,NULL,HFILL}},
{ &hf_iuup_spare_ff, { "Spare", "iuup.spare", FT_UINT8, BASE_HEX, NULL,0xff,NULL,HFILL}},
{ &hf_iuup_spare_bytes, { "Spare", "iuup.spare_bytes", FT_BYTES, BASE_NONE, NULL,0x0,NULL,HFILL}},
{ &hf_iuup_delay, { "Delay", "iuup.delay", FT_UINT32, BASE_HEX, NULL,0x0,NULL,HFILL}},
{ &hf_iuup_advance, { "Advance", "iuup.advance", FT_UINT32, BASE_HEX, NULL,0x0,NULL,HFILL}},
{ &hf_iuup_delta, { "Delta Time", "iuup.delta", FT_FLOAT, BASE_NONE, NULL,0x0,NULL,HFILL}},
{ &hf_iuup_init_ti, { "TI", "iuup.ti", FT_UINT8, BASE_DEC, VALS(iuup_ti_vals),0x10,"Timing Information",HFILL}},
{ &<API key>, { "Subflows", "iuup.subflows", FT_UINT8, BASE_DEC, NULL,0x0e,"Number of Subflows",HFILL}},
{ &<API key>, { "Chain Indicator", "iuup.chain_ind", FT_UINT8, BASE_DEC, VALS(<API key>),0x01,NULL,HFILL}},
{ &hf_iuup_payload, { "Payload Data", "iuup.payload_data", FT_BYTES, BASE_NONE, NULL,0x00,NULL,HFILL}},
{ &<API key>, { "Iu UP Mode Versions Supported", "iuup.support_mode", FT_UINT16, BASE_HEX, NULL,0x0,NULL,HFILL}},
{ &<API key>[ 0], { "Version 16", "iuup.support_mode.version16", FT_UINT16, BASE_HEX, VALS(<API key>),0x8000,NULL,HFILL}},
{ &<API key>[ 1], { "Version 15", "iuup.support_mode.version15", FT_UINT16, BASE_HEX, VALS(<API key>),0x4000,NULL,HFILL}},
{ &<API key>[ 2], { "Version 14", "iuup.support_mode.version14", FT_UINT16, BASE_HEX, VALS(<API key>),0x2000,NULL,HFILL}},
{ &<API key>[ 3], { "Version 13", "iuup.support_mode.version13", FT_UINT16, BASE_HEX, VALS(<API key>),0x1000,NULL,HFILL}},
{ &<API key>[ 4], { "Version 12", "iuup.support_mode.version12", FT_UINT16, BASE_HEX, VALS(<API key>),0x0800,NULL,HFILL}},
{ &<API key>[ 5], { "Version 11", "iuup.support_mode.version11", FT_UINT16, BASE_HEX, VALS(<API key>),0x0400,NULL,HFILL}},
{ &<API key>[ 6], { "Version 10", "iuup.support_mode.version10", FT_UINT16, BASE_HEX, VALS(<API key>),0x0200,NULL,HFILL}},
{ &<API key>[ 7], { "Version 9", "iuup.support_mode.version9", FT_UINT16, BASE_HEX, VALS(<API key>),0x0100,NULL,HFILL}},
{ &<API key>[ 8], { "Version 8", "iuup.support_mode.version8", FT_UINT16, BASE_HEX, VALS(<API key>),0x0080,NULL,HFILL}},
{ &<API key>[ 9], { "Version 7", "iuup.support_mode.version7", FT_UINT16, BASE_HEX, VALS(<API key>),0x0040,NULL,HFILL}},
{ &<API key>[10], { "Version 6", "iuup.support_mode.version6", FT_UINT16, BASE_HEX, VALS(<API key>),0x0020,NULL,HFILL}},
{ &<API key>[11], { "Version 5", "iuup.support_mode.version5", FT_UINT16, BASE_HEX, VALS(<API key>),0x0010,NULL,HFILL}},
{ &<API key>[12], { "Version 4", "iuup.support_mode.version4", FT_UINT16, BASE_HEX, VALS(<API key>),0x0008,NULL,HFILL}},
{ &<API key>[13], { "Version 3", "iuup.support_mode.version3", FT_UINT16, BASE_HEX, VALS(<API key>),0x0004,NULL,HFILL}},
{ &<API key>[14], { "Version 2", "iuup.support_mode.version2", FT_UINT16, BASE_HEX, VALS(<API key>),0x0002,NULL,HFILL}},
{ &<API key>[15], { "Version 1", "iuup.support_mode.version1", FT_UINT16, BASE_HEX, VALS(<API key>),0x0001,NULL,HFILL}},
{ &<API key>, { "Number of RFCI Indicators", "iuup.p", FT_UINT8, BASE_HEX, NULL,0x3f,NULL,HFILL}},
{ &<API key>, { "RFCI Initialization", "iuup.rfci.init", FT_BYTES, BASE_NONE, NULL,0x0,NULL,HFILL}},
HFS_RFCI(0),HFS_RFCI(1),HFS_RFCI(2),HFS_RFCI(3),HFS_RFCI(4),HFS_RFCI(5),HFS_RFCI(6),HFS_RFCI(7),
HFS_RFCI(8),HFS_RFCI(9),HFS_RFCI(10),HFS_RFCI(11),HFS_RFCI(12),HFS_RFCI(13),HFS_RFCI(14),HFS_RFCI(15),
HFS_RFCI(16),HFS_RFCI(17),HFS_RFCI(18),HFS_RFCI(19),HFS_RFCI(20),HFS_RFCI(21),HFS_RFCI(22),HFS_RFCI(23),
HFS_RFCI(24),HFS_RFCI(25),HFS_RFCI(26),HFS_RFCI(27),HFS_RFCI(28),HFS_RFCI(29),HFS_RFCI(30),HFS_RFCI(31),
HFS_RFCI(32),HFS_RFCI(33),HFS_RFCI(34),HFS_RFCI(35),HFS_RFCI(36),HFS_RFCI(37),HFS_RFCI(38),HFS_RFCI(39),
HFS_RFCI(40),HFS_RFCI(41),HFS_RFCI(42),HFS_RFCI(43),HFS_RFCI(44),HFS_RFCI(45),HFS_RFCI(46),HFS_RFCI(47),
HFS_RFCI(48),HFS_RFCI(49),HFS_RFCI(50),HFS_RFCI(51),HFS_RFCI(52),HFS_RFCI(53),HFS_RFCI(54),HFS_RFCI(55),
HFS_RFCI(56),HFS_RFCI(57),HFS_RFCI(58),HFS_RFCI(59),HFS_RFCI(60),HFS_RFCI(61),HFS_RFCI(62),HFS_RFCI(63)
};
gint* ett[] = {
&ett_iuup,
&ett_rfci,
&ett_ipti,
&ett_support,
&ett_time,
&ett_rfciinds,
&ett_payload,
&<API key>
};
static ei_register_info ei[] = {
{ &ei_iuup_hdr_crc_bad, { "iuup.hdr.crc.bad", PI_CHECKSUM, PI_ERROR, "Bad checksum", EXPFILL }},
{ &<API key>, { "iuup.payload.crc.bad", PI_CHECKSUM, PI_ERROR, "Bad checksum", EXPFILL }},
{ &<API key>, { "iuup.payload.undecoded", PI_UNDECODED, PI_WARN, "Undecoded payload", EXPFILL }},
{ &<API key>, { "iuup.error_response", PI_RESPONSE_CODE, PI_ERROR, "Error response", EXPFILL }},
{ &ei_iuup_ack_nack, { "iuup.ack.malformed", PI_MALFORMED, PI_ERROR, "Malformed Ack/Nack", EXPFILL }},
{ &ei_iuup_time_align, { "iuup.time_align.malformed", PI_MALFORMED, PI_ERROR, "Malformed Time Align", EXPFILL }},
{ &<API key>, { "iuup.procedure.malformed", PI_MALFORMED, PI_ERROR, "Malformed Procedure", EXPFILL }},
{ &ei_iuup_pdu_type, { "iuup.pdu_type.malformed", PI_MALFORMED, PI_ERROR, "Malformed PDU Type", EXPFILL }},
};
module_t *iuup_module;
expert_module_t* expert_iuup;
proto_iuup = <API key>("IuUP", "IuUP", "iuup");
<API key>(proto_iuup, hf, array_length(hf));
<API key>(ett, array_length(ett));
expert_iuup = <API key>(proto_iuup);
<API key>(expert_iuup, ei, array_length(ei));
register_dissector("iuup", dissect_iuup, proto_iuup);
register_dissector("find_iuup", find_iuup, proto_iuup);
<API key>(&init_iuup);
iuup_module = <API key>(proto_iuup, <API key>);
<API key>(iuup_module, "dissect_payload",
"Dissect IuUP Payload bits",
"Whether IuUP Payload bits should be dissected",
&dissect_fields);
<API key>(iuup_module, "<API key>",
"Two byte pseudoheader",
"The payload contains a two byte pseudoheader indicating direction and circuit_id",
&<API key>);
<API key>(iuup_module, "dynamic.payload.type",
"IuUP dynamic payload type",
"The dynamic payload type which will be interpreted as IuUP",
10,
&<API key>);
}
/*
* Editor modelines
*
* Local Variables:
* c-basic-offset: 4
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* ex: set shiftwidth=4 tabstop=8 expandtab:
* :indentSize=4:tabSize=8:noTabs=true:
*/ |
# disk.py
# Utilities relating to disk manangement
from kano.utils.shell import run_cmd
def get_free_space(path="/"):
"""
Returns the amount of free space in certain location in MB
:param path: The location to measure the free space at.
:type path: str
:return: Number of free megabytes.
:rtype: int
"""
out, dummy_err, dummy_rv = run_cmd("df {}".format(path))
dummy_device, dummy_size, dummy_used, free, dummy_percent, dummy_mp = \
out.split('\n')[1].split()
return int(free) / 1024
def get_partition_info():
device = '/dev/mmcblk0'
try:
cmd = 'lsblk -n -b {} -o SIZE'.format(device)
stdout, dummy_stderr, returncode = run_cmd(cmd)
if returncode != 0:
from kano.logging import logger
logger.warning("error running lsblk")
return []
lines = stdout.strip().split('\n')
sizes = map(int, lines)
return sizes
except Exception:
return [] |
<?php
// vim: expandtab sw=4 ts=4 sts=4:
require_once __DIR__.'/userlist.lib.php';
/**
* Class toregister a user to a course
*/
class <API key>
{
const
STATUS_OK = 0,
<API key> = 1,
<API key> = 2,
STATUS_SYSTEM_ERROR = 4,
<API key> = 8,
<API key> = 16,
<API key> = 32,
<API key> = 64;
protected
$admin = false,
$tutor = false,
$registerByClass = false,
$userAuthProfile,
$course,
$givenCourseKey,
$<API key> = false,
$categoryId,
$<API key> = false,
$<API key> = false,
$profileId = null,
$class = null,
$forceUnregOfManager = false;
protected $status = 0, $errorMessage = '';
/**
*
* @param AuthProfile $userAuthProfile profile of the user we want to enrol to the cours
* @param Claro_Course $course kernel object representing the course
* @param type $givenCourseKey optionnal given registration key (default null)
* @param type $categoryId optionnal given categoryId (default null)
*/
public function __construct(
AuthProfile $userAuthProfile,
Claro_Course $course,
$givenCourseKey = null,
$categoryId = null )
{
$this->userAuthProfile = $userAuthProfile;
$this->course = $course;
$this->givenCourseKey = $givenCourseKey;
$this->categoryId = $categoryId;
// is the user doing the registration a super user ?
if ( <API key>()
&& <API key>() == $this->course->courseId )
{
$this->isSuperUser = <API key>()
|| <API key>()
|| <API key>( get_module_data( 'CLUSER', 'id' ) );
}
else
{
$this->isSuperUser = <API key>();
}
}
/**
* Get the status of the user registration
* @return int
*/
public function getStatus()
{
return $this->status;
}
/**
* Return the reason why addUser returned false
* @return string
*/
public function getErrorMessage()
{
return $this->errorMessage;
}
/**
* Set the registration key for the registration protected by enrolment key
* @param string $registrationKey
*/
public function <API key>( $registrationKey )
{
$this->givenCourseKey = $registrationKey;
}
/**
* Set the id of the category for the registration by category
* @param int $categoryId
*/
public function setCategoryId( $categoryId )
{
$this->categoryId = $categoryId;
}
/**
* Ignore the registration key while doing the registration even for
* registration using an enrolment key
*/
public function <API key>()
{
$this-><API key> = true;
}
/**
* Ignore the category id while doing the registration even foir
* registration by category
*/
public function <API key>()
{
$this-><API key> = true;
}
/**
* User should be added as a course admin
*/
public function setCourseAdmin()
{
$this->admin = true;
}
/**
* User should be added as a course tutor
*/
public function setCourseTutor()
{
$this->tutor = true;
}
/**
* User should be added as a course tutor
*/
public function <API key>( $profileId )
{
$this->profileId = (int) $profileId;
if ( $profileId == <API key>('manager') )
{
$this->setCourseAdmin();
}
}
/**
* User added through a class
* @param Claro_Class $class
* @since 1.11.9
*/
public function setClass( Claro_Class $class )
{
$this->class = $class;
$this-><API key>();
}
/**
* User added through a class
* @since removed since 1.11.9
*/
protected function <API key>()
{
$this->registerByClass = true;
}
/**
* Force super user (for example at course creation)
*/
public function forceSuperUser()
{
$this->isSuperUser = true;
}
/**
* Force the unregistration even if the user is course manager
*/
public function <API key>()
{
$this->forceUnregOfManager = true;
}
/**
* Force the unregistration of the user
* @param boolean $keepTrackingData
* @param array $moduleDataToPurge
* @return boolean
*/
public function forceRemoveUser( $keepTrackingData = true, $moduleDataToPurge = array() )
{
if ( ! $this-><API key> () )
{
return false;
}
if ( ! $this-><API key> () )
{
$this->status = self::STATUS_SYSTEM_ERROR;
$this->errorMessage = get_lang('User not found in course');
return false;
}
else
{
$batchRegistration = new <API key>( $this->course );
$batchRegistration-><API key>(
array($this->userAuthProfile->getUserId()),
$keepTrackingData,
$moduleDataToPurge,
true );
if ( $batchRegistration->hasError () )
{
Console::error(var_export($batchRegistration->getErrorLog(), true));
return false;
}
else
{
return true;
}
}
}
/**
* Unregister a user
* @param boolean $keepTrackingData
* @param array $moduleDataToPurge
* @return boolean
*/
public function removeUser( $keepTrackingData = true, $moduleDataToPurge = array() )
{
if ( ! $this-><API key> () )
{
return false;
}
if ( ! $this-><API key> () )
{
$this->status = self::STATUS_SYSTEM_ERROR;
$this->errorMessage = get_lang('User not found in course');
return false;
}
else
{
$batchRegistration = new <API key>( $this->course );
$batchRegistration-><API key>(
array($this->userAuthProfile->getUserId()),
$this->class,
$keepTrackingData,
$moduleDataToPurge,
true );
if ( $batchRegistration->hasError () )
{
Console::error(var_export($batchRegistration->getErrorLog(), true));
return false;
}
else
{
return true;
}
}
}
/**
* Subscribe a specific user to a specific course. If this course is a session
* course, the user will also be subscribed to the source course.
* @return boolean TRUE if it succeeds, FALSE otherwise
*/
public function addUser()
{
if ( !$this-><API key>() )
{
return false;
}
$userId = $this->userAuthProfile->getUserId();
$courseCode = $this->course->courseId;
$tbl_mdb_names = <API key>();
$tbl_user = $tbl_mdb_names['user'];
$tbl_rel_course_user = $tbl_mdb_names['rel_course_user'];
if ( Claroline::getDatabase()->query("
SELECT
user_id
FROM
`{$tbl_user}`
WHERE
user_id = " . Claroline::getDatabase()->escape($userId) )->numRows() == 0 )
{
$this->status = self::STATUS_SYSTEM_ERROR;
$this->errorMessage = get_lang('User not found');
return false;
}
else
{
// Previously check if the user isn't already subscribed to the course
$<API key> = Claroline::getDatabase()->query( "
SELECT
count_user_enrol, count_class_enrol
FROM
`{$tbl_rel_course_user}`
WHERE
user_id = " . Claroline::getDatabase()->escape($userId) . "
AND
code_cours = " . Claroline::getDatabase()->quote($courseCode) );
if ( $<API key>->numRows() > 0 )
{
$course_user_list = $<API key>->fetch(Mysql_ResultSet::FETCH_OBJECT);
$count_user_enrol = (int) $course_user_list->count_user_enrol;
$count_class_enrol = (int) $course_user_list->count_class_enrol;
// Increment the count of registration by the user or class
if ( ! $this->registerByClass )
{
$count_user_enrol = 1;
}
else
{
$count_class_enrol++;
}
if ( !Claroline::getDatabase()->exec("
UPDATE
`{$tbl_rel_course_user}`
SET
`count_user_enrol` = " . $count_user_enrol . ",
`count_class_enrol` = " . $count_class_enrol . "
WHERE
user_id = " . Claroline::getDatabase()->escape($userId) . "
AND
code_cours = " . Claroline::getDatabase()->quote($courseCode)
) )
{
$this->status = self::STATUS_SYSTEM_ERROR;
$this->errorMessage = get_lang('Cannot register user in course');
return false;
}
else
{
return true;
}
}
else
{
// First registration to the course
$count_user_enrol = 0;
$count_class_enrol = 0;
// If a validation is requested for this course: isPending is true
// If the current user is course manager: isPending is false
$isPending = !$this->admin && $this-><API key>() ? true : false;
if ( ! $this->registerByClass )
{
$count_user_enrol = 1;
}
else
{
$count_class_enrol = 1;
}
if ( $this->admin )
{
$profileId = <API key>('manager');
}
elseif ( $this->profileId )
{
$profileId = $this->profileId;
}
else
{
$profileId = <API key>($this->getCourseProfile());
}
// if this course is a session course, enrol to the source course
if ( $this->course->sourceCourseId )
{
$sourceCourseCode = $this->course->getSourceCourseCode();
// only enrol the user to the source course only if he is not already there
$<API key> = Claroline::getDatabase()->query( "
SELECT
count_user_enrol, count_class_enrol
FROM
`{$tbl_rel_course_user}`
WHERE
user_id = " . Claroline::getDatabase()->escape($userId) . "
AND
code_cours = " . Claroline::getDatabase()->quote($sourceCourseCode) );
if ( $<API key>->numRows() == 0 )
{
if ( !Claroline::getDatabase()->exec("INSERT INTO `" . $tbl_rel_course_user . "`
SET code_cours = " . Claroline::getDatabase()->quote( $sourceCourseCode ) . ",
user_id = " . (int) $userId . ",
profile_id = " . (int) $profileId . ",
isCourseManager = " . (int) ($this->admin ? 1 : 0 ) . ",
isPending = " . (int) ($isPending ? 1 : 0) . ",
tutor = " . (int) ($this->tutor ? 1 : 0) . ",
count_user_enrol = " . $count_user_enrol . ",
count_class_enrol = " . $count_class_enrol . ",
enrollment_date = NOW()" ) )
{
$this->status = self::STATUS_SYSTEM_ERROR;
$this->errorMessage = get_lang('Cannot register user in source course');
return false;
}
}
}
// register user to new session course
if ( !Claroline::getDatabase()->exec("INSERT INTO `" . $tbl_rel_course_user . "`
SET code_cours = " . Claroline::getDatabase()->quote( $courseCode ) . ",
user_id = " . (int) $userId . ",
profile_id = " . (int) $profileId . ",
isCourseManager = " . (int) ($this->admin ? 1 : 0 ) . ",
isPending = " . (int) ($isPending ? 1 : 0) . ",
tutor = " . (int) ($this->tutor ? 1 : 0) . ",
count_user_enrol = " . $count_user_enrol . ",
count_class_enrol = " . $count_class_enrol . ",
enrollment_date = NOW()" ) )
{
$this->status = self::STATUS_SYSTEM_ERROR;
$this->errorMessage = get_lang('Cannot register user in source course');
return false;
}
else
{
return true;
}
}
} // end else user register in the platform
}
// business logic...
/**
* Is the user registered to the course ?
* @return boolean
*/
protected function <API key>()
{
$tbl_mdb_names = <API key>();
$tbl_rel_course_user = $tbl_mdb_names['rel_course_user'];
$sqlCourseCode = Claroline::getDatabase()->quote( $this->course->courseId );
$sqlUserId = Claroline::getDatabase()->escape($this->userAuthProfile->getUserId());
if ( Claroline::getDatabase()->query("
SELECT
user_id
FROM
`{$tbl_rel_course_user}`
WHERE
user_id = {$sqlUserId}
AND
code_cours = {$sqlCourseCode}" )->numRows() == 0 )
{
return false;
}
else
{
return true;
}
}
/**
* Get user enrolment mode
* @return 'string'pending', 'auto' or null
*/
protected function <API key>()
{
if ( $this->isSuperUser )
{
return 'open';
}
$<API key> = $this->userAuthProfile-><API key>();
if ( empty( $<API key> ) )
{
return $this->course->registration;
}
else
{
return $<API key>;
}
}
/**
* Is the user allowed to enrol to the course
* @return boolean
*/
protected function <API key>()
{
if ( $this->isSuperUser )
{
return true;
}
if ( $this->userAuthProfile-><API key>() )
{
if( $this-><API key>() )
{
if ( $this-><API key> )
{
return true;
}
else
{
if ( $this-><API key>() )
{
return true;
}
else
{
$this->status = self::<API key>;
return false;
}
}
}
else
{
return false;
}
}
else
{
$this->status = self::<API key>;
$this->errorMessage = get_lang('Your profile does not allow you to register to course.');
return false;
}
}
/**
* Check if there is only one manager left in the course
* @return boolean
*/
protected function <API key>( )
{
$tbl_mdb_names = <API key>();
$tbl_rel_course_user = $tbl_mdb_names['rel_course_user'];
$sqlCourseCode = Claroline::getDatabase()->quote( $this->course->courseId );
if ( Claroline::getDatabase ()->query("
SELECT
user_id
FROM
`{$tbl_rel_course_user}`
WHERE
isCourseManager = 1
AND
code_cours = {$sqlCourseCode}" )->numRows() == 1 )
{
return true;
}
else
{
return false;
}
}
/**
* Is the user allowed to unenrol from the course ?
* @return boolean
*/
protected function <API key>()
{
$user = new Claro_User( $this->userAuthProfile->getUserId() );
$user->load();
$coursePrivileges = new <API key>(
new <API key>( $user ),
$this->course );
if ( !$this->forceUnregOfManager && $coursePrivileges->isCourseManager () && $this->userAuthProfile->getUserId() == <API key> () && !<API key> () )
{
$this->status = self::<API key>;
$this->errorMessage = get_lang('Course manager cannot unsubscribe himself'); // unless he is platform admin too
return false;
}
// check if is thelast course manager
if ( $coursePrivileges->isCourseManager () && $this-><API key> () )
{
$this->status = self::<API key>;
$this->errorMessage = get_lang('You cannot unsubscribe the last course manager of the course'); // even if platform admin...
return false;
}
if ( $this->isSuperUser )
{
return true;
}
if ( $this->userAuthProfile-><API key>() )
{
return $this-><API key>();
}
else
{
$this->status = self::<API key>;
$this->errorMessage = get_lang('Your profile does not allow you to unregister from this course.');
return false;
}
}
/**
* Is the validation required ?
* @return boolean
*/
public function <API key>()
{
return !$this->isSuperUser && ($this-><API key>() == 'validation');
}
/**
* Get the profile name in the course
* @return string
*/
protected function getCourseProfile ()
{
return $this->userAuthProfile->getCourseProfile();
}
/**
* Check the registration key provided for the registration
* @return boolean
*/
protected function <API key>()
{
if ( $this-><API key>() == 'open' && !empty( $this->course->registrationKey ) )
{
if( empty( $this->givenCourseKey ) )
{
$this->errorMessage = get_lang('This course requires a key for enrolment');
$this->status = self::<API key>;
return false;
}
if ( $this->givenCourseKey != $this->course->registrationKey )
{
$this->errorMessage = get_lang('Invalid enrolment key given');
$this->status = self::<API key>;
return false;
}
else
{
return true;
}
}
else
{
return true;
}
}
/**
* Is the registration allowed in the current course ?
* @return boolean
*/
protected function <API key>()
{
$curdate = claro_time();
if ( !$this-><API key>
&& !is_null( $this->categoryId )
&& ! $this-><API key>() )
{
$this->status = self::<API key>;
$<API key> = false;
$this->errorMessage = get_lang('You have to be registered to this course\'s category in order to enrol the course');
}
elseif ( $this->isUserLimitExceeded() )
{
$this->status = self::<API key>;
$<API key> = false;
$this->errorMessage = get_lang('The users limit for this course has been reached');
}
elseif ( !in_array( $this-><API key>(), array('open', 'validation') ) )
{
$<API key> = false;
$this->status = self::<API key>;
$this->errorMessage = get_lang(
'This course currently does not allow new enrolments (registration: %registration)',
array('%registration' => $this-><API key>()) );
}
elseif ( !in_array( $this->course->status, array('enable', 'date') ) )
{
$<API key> = false;
$this->status = self::<API key>;
$this->errorMessage = get_lang(
'This course currently does not allow new enrolments (status: %status)',
array('%status' => $this->course->status));
}
elseif ( $this->course->status == 'date' && !empty($this->course->publicationDate) && $this->course->publicationDate >= $curdate )
{
$<API key> = false;
$this->status = self::<API key>;
$this->errorMessage = get_lang(
'This course will be enabled on the %date',
array('%date' => claro_date('d/m/Y', $this->course->publicationDate)));
}
elseif ( $this->course->status == 'date' && !empty($this->course->expirationDate) && $this->course->expirationDate <= $curdate )
{
$<API key> = false;
$this->status = self::<API key>;
$this->errorMessage = get_lang(
'This course has been deactivated on the %date',
array('%date' => claro_date('d/m/Y', $this->course->expirationDate)));
}
elseif ( $this->course->status == 'date'
&& ( empty($this->course->expirationDate) && empty($this->course->publicationDate) ) )
{
$<API key> = false;
$this->status = self::STATUS_SYSTEM_ERROR;
$this->errorMessage = get_lang('This course is not available');
Console::error(
"Invalid publication and expiration date for course " . $this->course->courseId );
}
else
{
$<API key> = true;
}
return $<API key>;
}
/**
* Is unregistration allowed for the course ?
* @return boolean
*/
protected function <API key>()
{
// Check if course available or option set to allow unregistration from unavailable course
if ( get_conf('<API key>', false ) )
{
$<API key> = true;
}
else
{
$curdate = claro_time();
if ( !in_array( $this->course->status, array('enable', 'date') ) )
{
$<API key> = false;
$this->status = self::<API key>;
$this->errorMessage = get_lang(
'This course currently does not allow to unenrol (status: %status)',
array('%status' => $this->course->status));
}
elseif ( $this->course->status == 'date' && !empty($this->course->publicationDate) && $this->course->publicationDate >= $curdate )
{
$<API key> = false;
$this->status = self::<API key>;
$this->errorMessage = get_lang(
'This course will be enabled on the %date',
array('%date' => claro_date('d/m/Y', $this->course->publicationDate)));
}
elseif ( $this->course->status == 'date' && !empty($this->course->expirationDate) && $this->course->expirationDate <= $curdate )
{
$<API key> = false;
$this->status = self::<API key>;
$this->errorMessage = get_lang(
'This course has been deactivated on the %date',
array('%date' => claro_date('d/m/Y', $this->course->expirationDate)));
}
elseif ( $this->course->status == 'date'
&& ( empty($this->course->expirationDate) && empty($this->course->publicationDate) ) )
{
$<API key> = false;
$this->status = self::STATUS_SYSTEM_ERROR;
$this->errorMessage = get_lang('This course is not available');
Console::error(
"Invalid publication and expiration date for course " . $this->course->courseId );
}
else
{
$<API key> = true;
}
}
return $<API key>;
}
/**
* If the course registration requires registration to the course category,
* check if the user is register to the category
* @return boolean
*/
protected function <API key>()
{
if ( $this->isSuperUser )
{
return true;
}
if( get_conf( '<API key>', false ) )
{
if ( !ClaroCategory::<API key>( $this->userAuthProfile->getUserId(), $this->categoryId ) )
{
return false;
}
else
{
return true;
}
}
else
{
return true;
}
}
/**
* Check if there the user number limit is not exceded in the course
* @return type
*/
protected function isUserLimitExceeded()
{
if ( $this->course->userLimit != 0
&& $this->countCourseUsers() >= $this->course->userLimit )
{
return true;
}
else
{
return false;
}
}
/**
* Count the number of non manager users in the course
* @return boolean
*/
protected function countCourseUsers()
{
$tbl_mdb_names = <API key>();
$tbl_rel_course_user = $tbl_mdb_names['rel_course_user'];
return Claroline::getDatabase()->query("
SELECT *
FROM `{$tbl_rel_course_user}`
WHERE code_cours = " . Claroline::getDatabase()->quote($this->course->courseId) . "
AND tutor = 0
AND isCourseManager = 0")->numRows();
}
} |
<?php
namespace oat\taoTests\test\unit\runner\plugins;
use <API key>;
use oat\generis\test\TestCase;
use oat\taoTests\models\runner\plugins\TestPlugin;
/**
* Test the TestPlugin pojo
*
* @author Bertrand Chevrier <bertrand@taotesting.com>
*/
class TestPluginTest extends TestCase
{
/**
* Data provider
* @return array the data
*/
public function accessorsProvider()
{
return [
[
[
'id' => 'foo',
'name' => 'Foo',
'module' => 'plugin/foo',
'category' => 'dummy',
'description' => 'The best foo ever',
'active' => true,
'tags' => ['required']
], [
'id' => 'foo',
'name' => 'Foo',
'module' => 'plugin/foo',
'category' => 'dummy',
'description' => 'The best foo ever',
'active' => true,
'tags' => ['required']
]
], [
[
'id' => '12',
'name' => 21,
'module' => 'plugin/foo',
'category' => 'dummy',
], [
'id' => '12',
'name' => '21',
'module' => 'plugin/foo',
'category' => 'dummy',
'description' => '',
'active' => true,
'tags' => []
]
]
];
}
public function testConstructBadId()
{
$this->expectException(<API key>::class);
new TestPlugin(12, 'foo', 'bar');
}
public function <API key>()
{
$this->expectException(<API key>::class);
new TestPlugin('', 'foo', 'bar');
}
public function <API key>()
{
$this->expectException(<API key>::class);
new TestPlugin('foo', true, 'bar');
}
public function <API key>()
{
$this->expectException(<API key>::class);
new TestPlugin('foo', '', 'bar');
}
public function <API key>()
{
$this->expectException(<API key>::class);
new TestPlugin('foo', 'bar', []);
}
public function <API key>()
{
$this->expectException(<API key>::class);
new TestPlugin('foo', 'bar', null);
}
public function <API key>()
{
$this->expectException(<API key>::class);
TestPlugin::fromArray([]);
}
/**
* Test contructor and getter
* @dataProvider accessorsProvider
*/
public function testConstruct($input, $output)
{
$testPlugin = new TestPlugin($input['id'], $input['module'], $input['category'], $input);
$this->assertEquals($output['id'], $testPlugin->getId());
$this->assertEquals($output['name'], $testPlugin->getName());
$this->assertEquals($output['module'], $testPlugin->getModule());
$this->assertEquals($output['category'], $testPlugin->getCategory());
$this->assertEquals($output['description'], $testPlugin->getDescription());
$this->assertEquals($output['active'], $testPlugin->isActive());
$this->assertEquals($output['tags'], $testPlugin->getTags());
$testPlugin->setActive(!$output['active']);
$this->assertEquals(!$output['active'], $testPlugin->isActive());
}
/**
* Test from array and getters
* @dataProvider accessorsProvider
*/
public function testFromArray($input, $output)
{
$testPlugin = TestPlugin::fromArray($input);
$this->assertEquals($output['id'], $testPlugin->getId());
$this->assertEquals($output['name'], $testPlugin->getName());
$this->assertEquals($output['module'], $testPlugin->getModule());
$this->assertEquals($output['category'], $testPlugin->getCategory());
$this->assertEquals($output['description'], $testPlugin->getDescription());
$this->assertEquals($output['active'], $testPlugin->isActive());
$this->assertEquals($output['tags'], $testPlugin->getTags());
$testPlugin->setActive(!$output['active']);
$this->assertEquals(!$output['active'], $testPlugin->isActive());
}
/**
* Test encoding the object to json
*/
public function testJsonSerialize()
{
$expected = '{"id":"bar","module":"bar\/bar","bundle":"plugins\/bundle.min","position":12,"name":"Bar","description":"The best bar ever","category":"dummy","active":false,"tags":["dummy","goofy"]}';
$testPlugin = new TestPlugin('bar', 'bar/bar', 'dummy', [
'name' => 'Bar',
'description' => 'The best bar ever',
'active' => false,
'position' => 12,
'bundle' => 'plugins/bundle.min',
'tags' => ['dummy', 'goofy']
]);
$serialized = json_encode($testPlugin);
$this->assertEquals($expected, $serialized);
}
} |
#include "<API key>.h"
#include <<API key>.h>
#include <KoColor.h>
#include <kis_image.h>
#include <kis_debug.h>
#include <<API key>.h>
#include <kis_painter.h>
#include <kis_paint_device.h>
#include <<API key>.h>
#include <<API key>.h>
#include "<API key>.h"
#include "kis_dynaop_option.h"
<API key>::<API key>(<API key>* settingsWidget)
: KisPaintOpSettings(settingsWidget)
{
m_options = settingsWidget;
m_options->writeConfiguration( this );
}
<API key> <API key>::clone() const
{
KisPaintOpSettings* settings =
static_cast<KisPaintOpSettings*>( m_options->configuration() );
return settings;
}
bool <API key>::paintIncremental()
{
return m_options-><API key>->paintActionType() == BUILDUP;
}
void <API key>::fromXML(const QDomElement& elt)
{
KisPaintOpSettings::fromXML( elt );
m_options->setConfiguration( this );
}
void <API key>::toXML(QDomDocument& doc, QDomElement& rootElt) const
{
<API key> * settings = m_options->configuration();
settings-><API key>::toXML( doc, rootElt );
delete settings;
}
qreal <API key>::initWidth() const
{
return m_options->m_dynaOption->initWidth();
}
qreal <API key>::mass() const
{
return m_options->m_dynaOption->mass();
}
qreal <API key>::drag() const
{
return m_options->m_dynaOption->drag();
}
bool <API key>::useFixedAngle() const
{
return m_options->m_dynaOption->useFixedAngle();
}
qreal <API key>::xAngle() const
{
return m_options->m_dynaOption->xAngle();
}
qreal <API key>::yAngle() const
{
return m_options->m_dynaOption->yAngle();
}
qreal <API key>::widthRange() const
{
return m_options->m_dynaOption->widthRange();
}
int <API key>::action() const
{
return m_options->m_dynaOption->action();
}
int <API key>::circleRadius() const
{
return m_options->m_dynaOption->circleRadius();
}
int <API key>::lineCount() const
{
return m_options->m_dynaOption->lineCount();
}
qreal <API key>::lineSpacing() const
{
return m_options->m_dynaOption->lineSpacing();
}
bool <API key>::enableLine() const
{
return m_options->m_dynaOption->enableLine();
}
bool <API key>::twoCircles() const
{
return m_options->m_dynaOption->twoCircles();
} |
using System;
using System.Collections;
using Server.Items;
using Server.Network;
namespace Server.Mobiles
{
[CorpseName("a solen queen corpse")]
public class BlackSolenQueen : BaseCreature, IBlackSolen
{
private bool m_BurstSac;
private DateTime recoverDelay;
private static bool m_Laid;
[Constructable]
public BlackSolenQueen()
: base(AIType.AI_Melee, FightMode.Closest, 10, 1, 0.2, 0.4)
{
this.Name = "a black solen queen";
this.Body = 807;
this.BaseSoundID = 959;
this.Hue = 0x453;
this.SetStr(296, 320);
this.SetDex(121, 145);
this.SetInt(76, 100);
this.SetHits(151, 162);
this.SetDamage(10, 15);
this.SetDamageType(ResistanceType.Physical, 70);
this.SetDamageType(ResistanceType.Poison, 30);
this.SetResistance(ResistanceType.Physical, 30, 40);
this.SetResistance(ResistanceType.Fire, 30, 35);
this.SetResistance(ResistanceType.Cold, 25, 35);
this.SetResistance(ResistanceType.Poison, 35, 40);
this.SetResistance(ResistanceType.Energy, 25, 30);
this.SetSkill(SkillName.MagicResist, 70.0);
this.SetSkill(SkillName.Tactics, 90.0);
this.SetSkill(SkillName.Wrestling, 90.0);
this.Fame = 4500;
this.Karma = -4500;
this.VirtualArmor = 45;
SolenHelper.PackPicnicBasket(this);
this.PackItem(new ZoogiFungus((Utility.RandomDouble() > 0.05) ? 5 : 25));
if (Utility.RandomDouble() < 0.05)
this.PackItem(new BallOfSummoning());
}
public BlackSolenQueen(Serial serial)
: base(serial)
{
}
public bool BurstSac
{
get
{
return this.m_BurstSac;
}
}
public override int GetAngerSound()
{
return 0x259;
}
public override int GetIdleSound()
{
return 0x259;
}
public override int GetAttackSound()
{
return 0x195;
}
public override int GetHurtSound()
{
return 0x250;
}
public override int GetDeathSound()
{
return 0x25B;
}
public override void GenerateLoot()
{
this.AddLoot(LootPack.Rich);
}
public override void OnGotMeleeAttack(Mobile attacker)
{
if (attacker.Weapon is BaseRanged)
BeginAcidBreath();
else if (this.Map != null && attacker != this && m_Laid == false && 0.20 > Utility.RandomDouble())
{
BSQEggSac sac = new BSQEggSac();
sac.MoveToWorld(this.Location, this.Map);
PlaySound(0x582);
Say(1114445); // * * The solen queen summons her workers to her aid! * *
m_Laid = true;
EggSacTimer e = new EggSacTimer();
e.Start();
}
base.OnGotMeleeAttack(attacker);
}
public override void OnDamagedBySpell(Mobile attacker)
{
base.OnDamagedBySpell(attacker);
if (0.80 >= Utility.RandomDouble())
BeginAcidBreath();
}
#region Acid Breath
private DateTime m_NextAcidBreath;
public void BeginAcidBreath()
{
PlayerMobile m = Combatant as PlayerMobile;
if (m == null || m.Deleted || !m.Alive || !Alive || m_NextAcidBreath > DateTime.Now || !CanBeHarmful(m))
return;
PlaySound(0x118);
MovingEffect(m, 0x36D4, 1, 0, false, false, 0x3F, 0);
TimeSpan delay = TimeSpan.FromSeconds(GetDistanceToSqrt(m) / 5.0);
Timer.DelayCall<Mobile>(delay, new TimerStateCallback<Mobile>(EndAcidBreath), m);
m_NextAcidBreath = DateTime.Now + TimeSpan.FromSeconds(5);
}
public void EndAcidBreath(Mobile m)
{
if (m == null || m.Deleted || !m.Alive || !Alive)
return;
if (0.2 >= Utility.RandomDouble())
m.ApplyPoison(this, Poison.Greater);
AOS.Damage(m, Utility.RandomMinMax(100, 120), 0, 0, 0, 100, 0);
}
#endregion
private class EggSacTimer : Timer
{
public EggSacTimer()
: base(TimeSpan.FromSeconds(10))
{
Priority = TimerPriority.OneSecond;
}
protected override void OnTick()
{
m_Laid = false;
}
}
public override bool IsEnemy(Mobile m)
{
if (SolenHelper.<API key>(m))
return false;
else
return base.IsEnemy(m);
}
public override void OnDamage(int amount, Mobile from, bool willKill)
{
SolenHelper.OnBlackDamage(from);
if (!willKill)
{
if (!this.BurstSac)
{
if (this.Hits < 50)
{
this.<API key>(MessageType.Regular, 0x3B2, true, "* The solen's acid sac is burst open! *");
this.m_BurstSac = true;
}
}
else if (from != null && from != this && this.InRange(from, 1))
{
this.SpillAcid(from, 1);
}
}
base.OnDamage(amount, from, willKill);
}
public override bool OnBeforeDeath()
{
this.SpillAcid(4);
return base.OnBeforeDeath();
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)1);
writer.Write(this.m_BurstSac);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
switch( version )
{
case 1:
{
this.m_BurstSac = reader.ReadBool();
break;
}
}
}
}
public class BSQEggSac : Item, ICarvable
{
private SpawnTimer m_Timer;
public override string DefaultName
{
get { return "egg sac"; }
}
[Constructable]
public BSQEggSac()
: base(4316)
{
Movable = false;
Hue = 350;
m_Timer = new SpawnTimer(this);
m_Timer.Start();
}
public void Carve(Mobile from, Item item)
{
Effects.PlaySound(GetWorldLocation(), Map, 0x027);
Effects.SendLocationEffect(GetWorldLocation(), Map, 0x3728, 10, 10, 0, 0);
from.SendMessage("You destroy the egg sac.");
Delete();
m_Timer.Stop();
}
public BSQEggSac(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
m_Timer = new SpawnTimer(this);
m_Timer.Start();
}
private class SpawnTimer : Timer
{
private Item m_Item;
public SpawnTimer(Item item)
: base(TimeSpan.FromSeconds(Utility.RandomMinMax(5, 10)))
{
Priority = TimerPriority.FiftyMS;
m_Item = item;
}
protected override void OnTick()
{
if (m_Item.Deleted)
return;
Mobile spawn;
switch (Utility.Random(2))
{
case 0:
spawn = new BlackSolenWarrior();
spawn.MoveToWorld(m_Item.Location, m_Item.Map);
m_Item.Delete();
break;
case 1:
spawn = new BlackSolenWorker();
spawn.MoveToWorld(m_Item.Location, m_Item.Map);
m_Item.Delete();
break;
}
}
}
}
} |
<?php
/* core/themes/bartik/templates/<API key>.html.twig */
class <API key> extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
$tags = array();
$filters = array();
$functions = array();
try {
$this->env->getExtension('sandbox')->checkSecurity(
array(),
array(),
array()
);
} catch (<API key> $e) {
$e->setTemplateFile($this->getTemplateName());
if ($e instanceof <API key> && isset($tags[$e->getTagName()])) {
$e->setTemplateLine($tags[$e->getTagName()]);
} elseif ($e instanceof <API key> && isset($filters[$e->getFilterName()])) {
$e->setTemplateLine($filters[$e->getFilterName()]);
} elseif ($e instanceof <API key> && isset($functions[$e->getFunctionName()])) {
$e->setTemplateLine($functions[$e->getFunctionName()]);
}
throw $e;
}
// line 13
echo "<form";
echo $this->env->getExtension('sandbox')-><API key>($this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute((isset($context["attributes"]) ? $context["attributes"] : null), "addClass", array(0 => "search-form", 1 => "search-block-form"), "method"), "html", null, true));
echo ">
";
// line 14
echo $this->env->getExtension('sandbox')-><API key>($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["children"]) ? $context["children"] : null), "html", null, true));
echo "
</form>
";
}
public function getTemplateName()
{
return "core/themes/bartik/templates/<API key>.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 48 => 14, 43 => 13,);
}
}
/* * @file*/
/* * Default theme implementation for a 'form' element.*/
/* * Available variables:*/
/* * - attributes: A list of HTML attributes for the wrapper element.*/
/* * - children: The child elements of the form.*/
/* * @see <API key>()*/
/* <form{{ attributes.addClass('search-form', 'search-block-form') }}>*/
/* {{ children }}*/
/* </form>*/ |
if (window.location.href.indexOf("researchgate.net/profile") > -1) {
<API key>();
}
function <API key>(){
var profileHeader = document.querySelector(".profile-header-name");
var profileName = profileHeader.querySelector("a").getAttribute("content");
var profileInstitution = profileHeader.querySelector(".institution.org").querySelector("meta").getAttribute("content");
var searchString = replaceAll(profileName, " ", "+") + '+' + replaceAll(profileInstitution, " ", "+") + "+-researchgate.net";
var <API key> = '';
googleSearchString = 'https:
window.open(googleSearchString)
void(0);
}
function replaceAll(originalString, searchValue, newValue) {
while (originalString.indexOf(searchValue) > -1) {
originalString = originalString.replace(searchValue, newValue);
}
return originalString;
} |
mo_tube_open_w_can = 0
mo_tube_open_wo_can = 1
<API key> = 2
mo_tube_close_w_can = 3
<API key> = 4
mo_tube_closed = 5
mo_tube_open = 6
<API key> = 7
<API key> = 8
<API key> = 9
<API key> = 10 |
<?php
defined('_JEXEC') or die;
JLoader::register('MenusHelper', JPATH_ADMINISTRATOR . '/components/com_menus/helpers/menus.php');
/**
* Joomla! Language Filter Plugin
*
* @package Joomla.Plugin
* @subpackage System.languagefilter
* @since 1.6
*/
class <API key> extends JPlugin
{
protected static $mode_sef;
protected static $tag;
protected static $sefs;
protected static $lang_codes;
protected static $default_lang;
protected static $default_sef;
protected static $cookie;
private static $_user_lang_code;
public function __construct(&$subject, $config)
{
// Ensure that constructor is called one time
self::$cookie = SID == '';
if (!self::$default_lang) {
$app = JFactory::getApplication();
$router = $app->getRouter();
if ($app->isSite()) {
// setup language data
self::$mode_sef = ($router->getMode() == JROUTER_MODE_SEF) ? true : false;
self::$sefs = JLanguageHelper::getLanguages('sef');
self::$lang_codes = JLanguageHelper::getLanguages('lang_code');
self::$default_lang = JComponentHelper::getParams('com_languages')->get('site', 'en-GB');
self::$default_sef = self::$lang_codes[self::$default_lang]->sef;
$user = JFactory::getUser();
$levels = $user->get<API key>();
foreach (self::$sefs as $sef => &$language)
{
if (isset($language->access) && $language->access && !in_array($language->access, $levels))
{
unset(self::$sefs[$sef]);
}
}
$app->setLanguageFilter(true);
jimport('joomla.environment.uri');
$uri = JURI::getInstance();
if (self::$mode_sef) {
// Get the route path from the request.
$path = JString::substr($uri->toString(), JString::strlen($uri->base()));
// Apache mod_rewrite is Off
$path = JFactory::getConfig()->get('sef_rewrite') ? $path : JString::substr($path, 10);
// Trim any spaces or slashes from the ends of the path and explode into segments.
$path = JString::trim($path, '/ ');
$parts = explode('/', $path);
// The language segment is always at the beginning of the route path if it exists.
$sef = $uri->getVar('lang');
if (!empty($parts) && empty($sef)) {
$sef = reset($parts);
}
}
else {
$sef = $uri->getVar('lang');
}
if (isset(self::$sefs[$sef])) {
$lang_code = self::$sefs[$sef]->lang_code;
// Create a cookie
$conf = JFactory::getConfig();
$cookie_domain = $conf->get('config.cookie_domain', '');
$cookie_path = $conf->get('config.cookie_path', '/');
setcookie(JApplication::getHash('language'), $lang_code, time() + 365 * 86400, $cookie_path, $cookie_domain);
// set the request var
$app->input->set('language', $lang_code);
}
}
parent::__construct($subject, $config);
// Detect browser feature
if ($app->isSite()) {
$app->setDetectBrowser($this->params->get('detect_browser', '1') == '1');
}
}
}
public function onAfterInitialise()
{
$app = JFactory::getApplication();
$app->item_associations = $this->params->get('item_associations', 0);
if ($app->isSite()) {
self::$tag = JFactory::getLanguage()->getTag();
$router = $app->getRouter();
// attach build rules for language SEF
$router->attachBuildRule(array($this, 'buildRule'));
// attach parse rules for language SEF
$router->attachParseRule(array($this, 'parseRule'));
// Adding custom site name
$languages = JLanguageHelper::getLanguages('lang_code');
if (isset($languages[self::$tag]) && $languages[self::$tag]->sitename) {
JFactory::getConfig()->set('sitename', $languages[self::$tag]->sitename);
}
}
}
public function buildRule(&$router, &$uri)
{
$sef = $uri->getVar('lang');
if (empty($sef)) {
$sef = self::$lang_codes[self::$tag]->sef;
}
elseif (!isset(self::$sefs[$sef])) {
$sef = self::$default_sef;
}
$Itemid = $uri->getVar('Itemid');
if (!is_null($Itemid)) {
if ($item = JFactory::getApplication()->getMenu()->getItem($Itemid))
{
if ($item->home && $uri->getVar('option') != 'com_search')
{
$link = $item->link;
$parts = JString::parse_url($link);
if (isset ($parts['query']) && strpos($parts['query'], '&')) {
$parts['query'] = str_replace('&', '&', $parts['query']);
}
parse_str($parts['query'], $vars);
// test if the url contains same vars as in menu link
$test = true;
foreach ($uri->getQuery(true) as $key => $value)
{
if (!in_array($key, array('format', 'Itemid', 'lang')) && !(isset($vars[$key]) && $vars[$key] == $value))
{
$test = false;
break;
}
}
if ($test) {
foreach ($vars as $key => $value)
{
$uri->delVar($key);
}
$uri->delVar('Itemid');
}
}
}
else
{
$uri->delVar('Itemid');
}
}
if (self::$mode_sef) {
$uri->delVar('lang');
if (
$this->params->get('<API key>', 0) == 0 ||
$sef != self::$default_sef ||
$sef != self::$lang_codes[self::$tag]->sef ||
$this->params->get('detect_browser', 1) && JLanguageHelper::detectLanguage() != self::$tag && !self::$cookie
)
{
$uri->setPath($uri->getPath().'/'.$sef.'/');
}
else
{
$uri->setPath($uri->getPath());
}
}
else {
$uri->setVar('lang', $sef);
}
}
public function parseRule(&$router, &$uri)
{
$app = JFactory::getApplication();
$array = array();
$lang_code = $app->input->cookie->getString(JApplication::getHash('language'));
// No cookie - let's try to detect browser language or use site default
if (!$lang_code) {
if ($this->params->get('detect_browser', 1)){
$lang_code = JLanguageHelper::detectLanguage();
} else {
$lang_code = self::$default_lang;
}
}
if (self::$mode_sef) {
$path = $uri->getPath();
$parts = explode('/', $path);
$sef = $parts[0];
// Redirect only if not in post
if (!empty($lang_code) && $app->input->getMethod() != "POST" || count($app->input->post) == 0)
{
if ($this->params->get('<API key>', 0) == 0)
{
// redirect if sef does not exists
if (!isset(self::$sefs[$sef]))
{
// Use the current language sef or the default one
$sef = isset(self::$lang_codes[$lang_code]) ? self::$lang_codes[$lang_code]->sef : self::$default_sef;
$uri->setPath($sef . '/' . $path);
if ($app->getCfg('sef_rewrite')) {
$app->redirect($uri->base().$uri->toString(array('path', 'query', 'fragment')));
}
else {
$path = $uri->toString(array('path', 'query', 'fragment'));
$app->redirect($uri->base().'index.php'.($path ? ('/' . $path) : ''));
}
}
}
else
{
// redirect if sef does not exists and language is not the default one
if (!isset(self::$sefs[$sef]) && $lang_code != self::$default_lang)
{
$sef = isset(self::$lang_codes[$lang_code]) ? self::$lang_codes[$lang_code]->sef : self::$default_sef;
$uri->setPath($sef . '/' . $path);
if ($app->getCfg('sef_rewrite')) {
$app->redirect($uri->base().$uri->toString(array('path', 'query', 'fragment')));
}
else {
$path = $uri->toString(array('path', 'query', 'fragment'));
$app->redirect($uri->base().'index.php'.($path ? ('/' . $path) : ''));
}
}
// redirect if sef is the default one
elseif (isset(self::$sefs[$sef]) &&
self::$default_lang == self::$sefs[$sef]->lang_code &&
(!$this->params->get('detect_browser', 1) || JLanguageHelper::detectLanguage() == self::$tag || self::$cookie)
)
{
array_shift($parts);
$uri->setPath(implode('/', $parts));
if ($app->getCfg('sef_rewrite')) {
$app->redirect($uri->base().$uri->toString(array('path', 'query', 'fragment')));
}
else {
$path = $uri->toString(array('path', 'query', 'fragment'));
$app->redirect($uri->base().'index.php'.($path ? ('/' . $path) : ''));
}
}
}
}
$lang_code = isset(self::$sefs[$sef]) ? self::$sefs[$sef]->lang_code : '';
if ($lang_code && JLanguage::exists($lang_code)) {
array_shift($parts);
$uri->setPath(implode('/', $parts));
}
}
else {
$sef = $uri->getVar('lang');
if (!isset(self::$sefs[$sef])) {
$sef = isset(self::$lang_codes[$lang_code]) ? self::$lang_codes[$lang_code]->sef : self::$default_sef;
$uri->setVar('lang', $sef);
if ($app->input->getMethod() != "POST" || count($app->input->post) == 0)
{
$app->redirect(JURI::base(true).'/index.php?'.$uri->getQuery());
}
}
}
$array = array('lang' => $sef);
return $array;
}
/**
* before store user method
*
* Method is called before user data is stored in the database
*
* @param array $user Holds the old user data.
* @param boolean $isnew True if a new user is stored.
* @param array $new Holds the new user data.
*
* @return void
* @since 1.6
*/
public function onUserBeforeSave($user, $isnew, $new)
{
if ($this->params->get('automatic_change', '1') == '1' && key_exists('params', $user))
{
$registry = new JRegistry;
$registry->loadString($user['params']);
self::$_user_lang_code = $registry->get('language');
if (empty(self::$_user_lang_code)) {
self::$_user_lang_code = self::$default_lang;
}
}
}
/**
* after store user method
*
* Method is called after user data is stored in the database
*
* @param array $user Holds the new user data.
* @param boolean $isnew True if a new user is stored.
* @param boolean $success True if user was succesfully stored in the database.
* @param string $msg Message.
*
* @return void
* @since 1.6
*/
public function onUserAfterSave($user, $isnew, $success, $msg)
{
if ($this->params->get('automatic_change', '1') == '1' && key_exists('params', $user) && $success)
{
$registry = new JRegistry;
$registry->loadString($user['params']);
$lang_code = $registry->get('language');
if (empty($lang_code)) {
$lang_code = self::$default_lang;
}
$app = JFactory::getApplication();
if ($lang_code == self::$_user_lang_code || !isset(self::$lang_codes[$lang_code]))
{
if ($app->isSite())
{
$app->setUserState('com_users.edit.profile.redirect', null);
}
}
else
{
if ($app->isSite())
{
$app->setUserState('com_users.edit.profile.redirect', 'index.php?Itemid='.$app->getMenu()->getDefault($lang_code)->id.'&lang='.$lang_codes[$lang_code]->sef);
self::$tag = $lang_code;
// Create a cookie
$conf = JFactory::getConfig();
$cookie_domain = $conf->get('config.cookie_domain', '');
$cookie_path = $conf->get('config.cookie_path', '/');
setcookie(JApplication::getHash('language'), $lang_code, time() + 365 * 86400, $cookie_path, $cookie_domain);
}
}
}
}
/**
* This method should handle any login logic and report back to the subject
*
* @param array $user Holds the user data
* @param array $options Array holding options (remember, autoregister, group)
*
* @return boolean True on success
* @since 1.5
*/
public function onUserLogin($user, $options = array())
{
$app = JFactory::getApplication();
$menu = $app->getMenu();
if ($app->isSite() && $this->params->get('automatic_change', 1))
{
// Load associations
$assoc = isset($app->menu_associations) ? $app->menu_associations : 0;
if ($assoc)
{
$active = $menu->getActive();
if ($active)
{
$associations = MenusHelper::getAssociations($active->id);
}
}
$lang_code = $user['language'];
if (empty($lang_code))
{
$lang_code = self::$default_lang;
}
if ($lang_code != self::$tag)
{
// Change language
self::$tag = $lang_code;
// Create a cookie
$conf = JFactory::getConfig();
$cookie_domain = $conf->get('config.cookie_domain', '');
$cookie_path = $conf->get('config.cookie_path', '/');
setcookie(JApplication::getHash('language'), $lang_code, time() + 365 * 86400, $cookie_path, $cookie_domain);
// Change the language code
JFactory::getLanguage()->setLanguage($lang_code);
// Change the redirect (language have changed)
if (isset($associations[$lang_code]) && $menu->getItem($associations[$lang_code])) {
$itemid = $associations[$lang_code];
$app->setUserState('users.login.form.return', 'index.php?&Itemid='.$itemid);
}
else
{
$itemid = isset($homes[$lang_code]) ? $homes[$lang_code]->id : $homes['*']->id;
$app->setUserState('users.login.form.return', 'index.php?&Itemid='.$itemid);
}
}
}
}
/**
* This method adds alternate meta tags for associated menu items
*
* @return nothing
* @since 1.7
*/
public function onAfterDispatch()
{
$app = JFactory::getApplication();
$doc = JFactory::getDocument();
$menu = $app->getMenu();
$server = JURI::getInstance()->toString(array('scheme', 'host', 'port'));
$option = $app->input->get('option');
$eName = JString::ucfirst(JString::str_ireplace('com_', '', $option));
if ($app->isSite() && $this->params->get('alternate_meta') && $doc->getType() == 'html')
{
// Get active menu item
$active = $menu->getActive();
// load menu associations
if ($active) {
// Get menu item link
if ($app->getCfg('sef'))
{
$active_link = JRoute::_('index.php?Itemid='.$active->id, false);
}
else
{
$active_link = JRoute::_($active->link.'&Itemid='.$active->id, false);
}
if ($active_link == JUri::base(true).'/')
{
$active_link .= 'index.php';
}
// Get current link
$current_link = JURI::getInstance()->toString(array('path', 'query'));
if ($current_link == JUri::base(true).'/')
{
$current_link .= 'index.php';
}
// Check the exact menu item's URL
if ($active_link == $current_link)
{
$associations = MenusHelper::getAssociations($active->id);
unset($associations[$active->language]);
}
}
// load component associations
$cName = JString::ucfirst($eName.'HelperAssociation');
JLoader::register($cName, JPath::clean(<API key> . '/helpers/association.php'));
if (class_exists($cName) && is_callable(array($cName, 'getAssociations')))
{
$cassociations = call_user_func(array($cName, 'getAssociations'));
$lang_code = $app->input->getString(JApplication::getHash('language'), null, 'cookie');
// No cookie - let's try to detect browser language or use site default
if (!$lang_code) {
if ($this->params->get('detect_browser', 1)){
$lang_code = JLanguageHelper::detectLanguage();
} else {
$lang_code = self::$default_lang;
}
}
unset($cassociations[$lang_code]);
}
// handle the default associations
if ((!empty($associations) || !empty($cassociations)) && $this->params->get('item_associations')) {
foreach (JLanguageHelper::getLanguages() as $language)
{
if (!JLanguage::exists($language->lang_code))
{
continue;
}
if (isset($cassociations[$language->lang_code]))
{
$link = JRoute::_($cassociations[$language->lang_code].'&lang='.$language->sef);
$doc->addHeadLink($server . $link, 'alternate', 'rel', array('hreflang' => $language->lang_code));
}
elseif (isset($associations[$language->lang_code]))
{
$item = $menu->getItem($associations[$language->lang_code]);
if ($item) {
if ($app->getCfg('sef')) {
$link = JRoute::_('index.php?Itemid='.$item->id.'&lang='.$language->sef);
} else {
$link = JRoute::_($item->link.'&Itemid='.$item->id.'&lang='.$language->sef);
}
$doc->addHeadLink($server . $link, 'alternate', 'rel', array('hreflang' => $language->lang_code));
}
}
}
}
// link to the home page of each language
elseif ($active && $active->home)
{
foreach (JLanguageHelper::getLanguages() as $language)
{
if (!JLanguage::exists($language->lang_code))
continue;
$item = $menu->getDefault($language->lang_code);
if ($item && $item->language != $active->language && $item->language != '*') {
if ($app->getCfg('sef')) {
$link = JRoute::_('index.php?Itemid='.$item->id.'&lang='.$language->sef);
} else {
$link = JRoute::_($item->link.'&Itemid='.$item->id.'&lang='.$language->sef);
}
$doc->addHeadLink($server . $link, 'alternate', 'rel', array('hreflang' => $language->lang_code));
}
}
}
}
}
} |
# SMCDEL
[.
You can find a complete literate Haskell documentation in the file
[SMCDEL.pdf](https://github.com/jrclogic/SMCDEL/raw/master/SMCDEL.pdf).
## References
[Johan van Benthem, Jan van Eijck, Malvin Gattinger, and Kaile Su:
*Symbolic Model Checking for Dynamic Epistemic Logic.*
In: Proceedings of The Fifth International Conference on Logic, Rationality and Interaction (LORI-V),
2015](https://doi.org/10.1007/<API key>).
[Johan van Benthem, Jan van Eijck, Malvin Gattinger, and Kaile Su:
*Symbolic Model Checking for Dynamic Epistemic Logic --- S5 and Beyond.*
Journal of Logic and Computation,
2017](https://pure.uva.nl/ws/files/25483686/<API key>.pd.pdf).
[Malvin Gattinger:
*Towards Symbolic Factual Change in DEL.*
ESSLLI 2017 student session,
2017](https://w4eg.de/malvin/illc/<API key>.pdf).
[Malvin Gattinger:
*New Directions in Model Checking Dynamic Epistemic Logic.*
PhD thesis, ILLC, Amsterdam,
2018](https://malv.in/phdthesis/).
## Online
You can try SMCDEL online here: https://w4eg.de/malvin/illc/smcdelweb/
## Dependencies
- [graphviz](https://graphviz.org/)
- [dot2tex](https://github.com/kjellmf/dot2tex)
On Debian, just do `sudo apt install graphviz dot2tex`.
## Basic usage
1) Use *stack* from https:
- `stack build` will compile everything. This might fail if one of
the BDD packages written in C and C++ is missing. In this case,
install those manually and then try `stack build` again.
- `stack install` will put two executables `smcdel` and `smcdel-web`
into ~/.local/bin which should be in your `PATH` variable.
2) Create a text file `MuddyShort.smcdel.txt` which describes the knowledge structure and the formulas you want to check for truth or validity:
-- Three Muddy Children in SMCDEL
VARS 1,2,3
LAW Top
OBS alice: 2,3
bob: 1,3
carol: 1,2
WHERE?
[ ! (1|2|3) ] alice knows whether 1
VALID?
[ ! (1|2|3) ]
[ ! ((~ (alice knows whether 1)) & (~ (bob knows whether 2)) & (~ (carol knows whether 3))) ]
[ ! ((~ (alice knows whether 1)) & (~ (bob knows whether 2)) & (~ (carol knows whether 3))) ]
(alice,bob,carol) comknow that (1 & 2 & 3)
3) Run `smcdel MuddyShort.smcdel.txt` resulting in:
>> smcdel MuddyShort.smcdel.txt
SMCDEL 1.0 by Malvin Gattinger -- https://github.com/jrclogic/SMCDEL
At which states is ... true?
[]
[1]
Is ... valid on the given structure?
True
More example files are in the folder [Examples](https://github.com/jrclogic/SMCDEL/tree/master/Examples).
4) To use the web interface run `smcdel-web` and then open <http://localhost:3000/index.html>.
## Advanced usage
To deal with more complex models and formulas, use SMCDEL as a Haskell module.
Examples can be found in the folders
[src/SMCDEL/Examples](https://github.com/jrclogic/SMCDEL/tree/master/src/SMCDEL/Examples)
and
[bench](https://github.com/jrclogic/SMCDEL/tree/master/bench).
## Used BDD packages
SMCDEL can be used with different BDD packages. To compile and
run the benchmarks you will have to install all of them.
- [Data.HasCacBDD](https:
- [Cudd](https: |
<?php
error_reporting(E_ALL | E_STRICT);
require('extends/UploadHandler.php');
$upload_handler = new UploadHandler(); |
#include "interface.h"
#include "../../local.h"
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/select.h>
#include <errno.h>
//This is an important setting that depends on your network setup
#define SELECT_TIMEOUT_USEC 100
//TOC protos
void ConnectDb(void);
void ConnectDb(void)
{
//Handle quick cases first
//Port is irrelevant here. Make it clear.
mysql_init(&gMysql);
if(DBIP0==NULL)
{
if (mysql_real_connect(&gMysql,DBIP0,DBLOGIN,DBPASSWD,DBNAME,0,DBSOCKET,0))
return;
}
if(DBIP1==NULL)
{
if (mysql_real_connect(&gMysql,DBIP1,DBLOGIN,DBPASSWD,DBNAME,0,DBSOCKET,0))
return;
}
//Now we can use AF_INET/IPPROTO_TCP cases (TCP connections via IP number)
char *cPort="3306";
int iSock,iConRes;
long lFcntlArg;
struct sockaddr_in <API key>;
fd_set myset;
struct timeval tv;
int valopt;
socklen_t lon;
//Default port should really be gathered from a different source
//but for now we use the known MySQL server CentOS default port (*1).
if(DBPORT!=0)
sprintf(cPort,"%u",DBPORT);
if(DBIP0!=NULL)
{
if((iSock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))<0)
{
printf("Content-type: text/plain\n\n");
printf("Could not create ConnectDB() socket DBIP0\n");
exit(0);
}
// Set non-blocking
lFcntlArg=fcntl(iSock,F_GETFL,NULL);
lFcntlArg|=O_NONBLOCK;
fcntl(iSock,F_SETFL,lFcntlArg);
//DBIP0 has priority if we can create a connection we
//move forward immediately.
memset(&<API key>,0,sizeof(<API key>));
<API key>.sin_family=AF_INET;
<API key>.sin_addr.s_addr=inet_addr(DBIP0);
<API key>.sin_port=htons(atoi(cPort));
iConRes=connect(iSock,(struct sockaddr *)&<API key>,sizeof(<API key>));
if(iConRes<0)
{
if(errno==EINPROGRESS)
{
tv.tv_sec=0;
tv.tv_usec=SELECT_TIMEOUT_USEC;
FD_ZERO(&myset);
FD_SET(iSock,&myset);
if(select(iSock+1,NULL,&myset,NULL,&tv)>0)
{
lon=sizeof(int);
getsockopt(iSock,SOL_SOCKET,SO_ERROR,(void*)(&valopt),&lon);
if(!valopt)
{
//Valid fast connection
close(iSock);//Don't need anymore.
mysql_init(&gMysql);
if(mysql_real_connect(&gMysql,DBIP0,DBLOGIN,DBPASSWD,
DBNAME,DBPORT,DBSOCKET,0))
return;
}
}
}
}
close(iSock);//Don't need anymore.
}
if(DBIP1!=NULL)
{
if((iSock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))<0)
{
printf("Content-type: text/plain\n\n");
printf("Could not create ConnectDB() socket DBIP1\n");
exit(0);
}
// Set non-blocking
lFcntlArg=fcntl(iSock,F_GETFL,NULL);
lFcntlArg|=O_NONBLOCK;
fcntl(iSock,F_SETFL,lFcntlArg);
//Fallback to DBIP1
memset(&<API key>,0,sizeof(<API key>));
<API key>.sin_family=AF_INET;
<API key>.sin_addr.s_addr=inet_addr(DBIP1);
<API key>.sin_port=htons(atoi(cPort));
iConRes=connect(iSock,(struct sockaddr *)&<API key>,sizeof(<API key>));
if(iConRes<0)
{
if(errno==EINPROGRESS)
{
tv.tv_sec=0;
tv.tv_usec=SELECT_TIMEOUT_USEC;
FD_ZERO(&myset);
FD_SET(iSock,&myset);
if(select(iSock+1,NULL,&myset,NULL,&tv)>0)
{
lon=sizeof(int);
getsockopt(iSock,SOL_SOCKET,SO_ERROR,(void*)(&valopt),&lon);
if(!valopt)
{
//Valid fast connection
close(iSock);//Don't need anymore.
mysql_init(&gMysql);
if(mysql_real_connect(&gMysql,DBIP1,DBLOGIN,DBPASSWD,
DBNAME,DBPORT,DBSOCKET,0))
return;
}
}
}
}
close(iSock);//Don't need anymore.
}
//Failure exit 4 cases
char cMessage[256];
if(DBIP1!=NULL && DBIP0!=NULL)
sprintf(cMessage,"Could not connect to DBIP0:%1$s or DBIP1:%1$s\n",cPort);
else if(DBIP1==NULL && DBIP0==NULL)
sprintf(cMessage,"Could not connect to local socket\n");
else if(DBIP0!=NULL && DBIP1==NULL)
sprintf(cMessage,"Could not connect to DBIP0:%s or local socket (DBIP1)\n",cPort);
else if(DBIP0==NULL && DBIP1!=NULL)
sprintf(cMessage,"Could not connect to DBIP1:%s or local socket (DBIP0)\n",cPort);
else if(1)
sprintf(cMessage,"Could not connect unexpected case\n");
printf("Content-type: text/plain\n\n");
printf(cMessage);
exit(0);
}//ConnectDb() |
/*
SHARP MZ-700 Emulator 'EmuZ-700'
SHARP MZ-1500 Emulator 'EmuZ-1500'
Skelton for retropc emulator
Author : Takeda.Toshiya
Date : 2010.09.02 -
[ psg*2 ]
*/
#ifndef _PSG_H_
#define _PSG_H_
#include "../vm.h"
#include "../../emu.h"
#include "../device.h"
class PSG : public DEVICE
{
private:
DEVICE *d_psg_l, *d_psg_r;
public:
PSG(VM* parent_vm, EMU* parent_emu) : DEVICE(parent_vm, parent_emu) {}
~PSG() {}
// common function
void write_io8(uint32 addr, uint32 data);
// unitque functions
void set_context_psg_l(DEVICE* device) {
d_psg_l = device;
}
void set_context_psg_r(DEVICE* device) {
d_psg_r = device;
}
};
#endif |
#include <config.h>
#include <asm/arch/cpu.h>
#include <asm/arch/romboot.h>
extern int uclDecompress(char* op, unsigned* o_len, char* ip);
int load_secureos(void)
{
int rc=0;
unsigned len;
// verify secureOS validation
/*
#ifndef <API key>
rc=spldecrypt(<API key>);
if(rc)
goto exit;
#endif
*/
// UCL decompress
#ifdef <API key>
rc=uclDecompress((char*)(<API key>), &len,(char*)(<API key>));
//#else
// rc=uclDecompress((char*)(<API key>), &len,(char*)(<API key>+SECUREOS_HEAD_SIZE));
#endif
#if (defined(<API key>) && defined(<API key>))
aml_cache_disable();
#endif
exit:
return rc;
} |
from GUIComponent import GUIComponent
from VariableText import VariableText
from os import statvfs
from enigma import eLabel
# TODO: Harddisk.py has similiar functions, but only similiar.
# fix this to use same code
class DiskInfo(VariableText, GUIComponent):
FREE = 0
USED = 1
SIZE = 2
def __init__(self, path, type, update = True):
GUIComponent.__init__(self)
VariableText.__init__(self)
self.type = type
self.path = path
if update:
self.update()
def update(self):
try:
stat = statvfs(self.path)
except OSError:
return -1
if self.type == self.FREE:
try:
percent = '(' + str((100 * stat.f_bavail) // stat.f_blocks) + '%)'
free = stat.f_bfree * stat.f_bsize
if free < 10000000:
free = _("%d Kb") % (free >> 10)
elif free < 10000000000:
free = _("%d Mb") % (free >> 20)
else:
free = _("%d Gb") % (free >> 30)
self.setText(" ".join((free, percent, _("free diskspace"))))
except:
# occurs when f_blocks is 0 or a similar error
self.setText("-?-")
GUI_WIDGET = eLabel |
#if HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <errno.h>
#include "util.h"
#include "ops.h"
#include "sema.h"
#include "debug.h"
/* Protects all reference counters in keys. All other accesses to a
key are read only. */
DEFINE_STATIC_LOCK (key_ref_lock);
/* Create a new key. */
gpgme_error_t
_gpgme_key_new (gpgme_key_t *r_key)
{
gpgme_key_t key;
key = calloc (1, sizeof *key);
if (!key)
return <API key> ();
key->_refs = 1;
*r_key = key;
return 0;
}
gpgme_error_t
<API key> (gpgme_key_t key, gpgme_subkey_t *r_subkey)
{
gpgme_subkey_t subkey;
subkey = calloc (1, sizeof *subkey);
if (!subkey)
return <API key> ();
subkey->keyid = subkey->_keyid;
subkey->_keyid[16] = '\0';
if (!key->subkeys)
key->subkeys = subkey;
if (key->_last_subkey)
key->_last_subkey->next = subkey;
key->_last_subkey = subkey;
*r_subkey = subkey;
return 0;
}
static char *
set_user_id_part (char *tail, const char *buf, size_t len)
{
while (len && (buf[len - 1] == ' ' || buf[len - 1] == '\t'))
len
for (; len; len
*tail++ = *buf++;
*tail++ = 0;
return tail;
}
static void
parse_user_id (char *src, char **name, char **email,
char **comment, char *tail)
{
const char *start = NULL;
int in_name = 0;
int in_email = 0;
int in_comment = 0;
while (*src)
{
if (in_email)
{
if (*src == '<')
in_email++;
else if (*src == '>')
{
if (!--in_email && !*email)
{
*email = tail;
tail = set_user_id_part (tail, start, src - start);
}
}
}
else if (in_comment)
{
if (*src == '(')
in_comment++;
else if (*src == ')')
{
if (!--in_comment && !*comment)
{
*comment = tail;
tail = set_user_id_part (tail, start, src - start);
}
}
}
else if (*src == '<')
{
if (in_name)
{
if (!*name)
{
*name = tail;
tail = set_user_id_part (tail, start, src - start);
}
in_name = 0;
}
in_email = 1;
start = src + 1;
}
else if (*src == '(')
{
if (in_name)
{
if (!*name)
{
*name = tail;
tail = set_user_id_part (tail, start, src - start);
}
in_name = 0;
}
in_comment = 1;
start = src + 1;
}
else if (!in_name && *src != ' ' && *src != '\t')
{
in_name = 1;
start = src;
}
src++;
}
if (in_name)
{
if (!*name)
{
*name = tail;
tail = set_user_id_part (tail, start, src - start);
}
}
/* Let unused parts point to an EOS. */
tail
if (!*name)
*name = tail;
if (!*email)
*email = tail;
if (!*comment)
*comment = tail;
}
static void
parse_x509_user_id (char *src, char **name, char **email,
char **comment, char *tail)
{
if (*src == '<' && src[strlen (src) - 1] == '>')
*email = src;
/* Let unused parts point to an EOS. */
tail
if (!*name)
*name = tail;
if (!*email)
*email = tail;
if (!*comment)
*comment = tail;
}
/* Take a name from the --with-colon listing, remove certain escape
sequences sequences and put it into the list of UIDs. */
gpgme_error_t
<API key> (gpgme_key_t key, const char *src, int convert)
{
gpgme_user_id_t uid;
char *dst;
int src_len = strlen (src);
assert (key);
/* We can malloc a buffer of the same length, because the converted
string will never be larger. Actually we allocate it twice the
size, so that we are able to store the parsed stuff there too. */
uid = malloc (sizeof (*uid) + 2 * src_len + 3);
if (!uid)
return <API key> ();
memset (uid, 0, sizeof *uid);
uid->uid = ((char *) uid) + sizeof (*uid);
dst = uid->uid;
if (convert)
<API key> (src, &dst, src_len + 1);
else
memcpy (dst, src, src_len + 1);
dst += strlen (dst) + 1;
if (key->protocol == GPGME_PROTOCOL_CMS)
parse_x509_user_id (uid->uid, &uid->name, &uid->email,
&uid->comment, dst);
else
parse_user_id (uid->uid, &uid->name, &uid->email,
&uid->comment, dst);
if (!key->uids)
key->uids = uid;
if (key->_last_uid)
key->_last_uid->next = uid;
key->_last_uid = uid;
return 0;
}
gpgme_key_sig_t
_gpgme_key_add_sig (gpgme_key_t key, char *src)
{
int src_len = src ? strlen (src) : 0;
gpgme_user_id_t uid;
gpgme_key_sig_t sig;
assert (key); /* XXX */
uid = key->_last_uid;
assert (uid); /* XXX */
/* We can malloc a buffer of the same length, because the converted
string will never be larger. Actually we allocate it twice the
size, so that we are able to store the parsed stuff there too. */
sig = malloc (sizeof (*sig) + 2 * src_len + 3);
if (!sig)
return NULL;
memset (sig, 0, sizeof *sig);
sig->keyid = sig->_keyid;
sig->_keyid[16] = '\0';
sig->uid = ((char *) sig) + sizeof (*sig);
if (src)
{
char *dst = sig->uid;
<API key> (src, &dst, src_len + 1);
dst += strlen (dst) + 1;
if (key->protocol == GPGME_PROTOCOL_CMS)
parse_x509_user_id (sig->uid, &sig->name, &sig->email,
&sig->comment, dst);
else
parse_user_id (sig->uid, &sig->name, &sig->email,
&sig->comment, dst);
}
else
sig->uid = '\0';
if (!uid->signatures)
uid->signatures = sig;
if (uid->_last_keysig)
uid->_last_keysig->next = sig;
uid->_last_keysig = sig;
return sig;
}
/* Acquire a reference to KEY. */
void
gpgme_key_ref (gpgme_key_t key)
{
LOCK (key_ref_lock);
key->_refs++;
UNLOCK (key_ref_lock);
}
/* gpgme_key_unref releases the key object. Note, that this function
may not do an actual release if there are other shallow copies of
the objects. You have to call this function for every newly
created key object as well as for every gpgme_key_ref() done on the
key object. */
void
gpgme_key_unref (gpgme_key_t key)
{
gpgme_user_id_t uid;
gpgme_subkey_t subkey;
if (!key)
return;
LOCK (key_ref_lock);
assert (key->_refs > 0);
if (--key->_refs)
{
UNLOCK (key_ref_lock);
return;
}
UNLOCK (key_ref_lock);
subkey = key->subkeys;
while (subkey)
{
gpgme_subkey_t next = subkey->next;
if (subkey->fpr)
free (subkey->fpr);
if (subkey->card_number)
free (subkey->card_number);
free (subkey);
subkey = next;
}
uid = key->uids;
while (uid)
{
gpgme_user_id_t next_uid = uid->next;
gpgme_key_sig_t keysig = uid->signatures;
while (keysig)
{
gpgme_key_sig_t next_keysig = keysig->next;
<API key> notation = keysig->notations;
while (notation)
{
<API key> next_notation = notation->next;
<API key> (notation);
notation = next_notation;
}
free (keysig);
keysig = next_keysig;
}
free (uid);
uid = next_uid;
}
if (key->issuer_serial)
free (key->issuer_serial);
if (key->issuer_name)
free (key->issuer_name);
if (key->chain_id)
free (key->chain_id);
free (key);
}
/* Support functions. */
/* Create a dummy key to specify an email address. */
gpgme_error_t
gpgme_key_from_uid (gpgme_key_t *r_key, const char *name)
{
gpgme_error_t err;
gpgme_key_t key;
*r_key = NULL;
err = _gpgme_key_new (&key);
if (err)
return err;
/* Note: protocol doesn't matter if only email is provided. */
err = <API key> (key, name, 0);
if (err)
gpgme_key_unref (key);
else
*r_key = key;
return err;
}
/* Compatibility interfaces. */
void
gpgme_key_release (gpgme_key_t key)
{
gpgme_key_unref (key);
}
static const char *
otrust_to_string (int otrust)
{
switch (otrust)
{
case <API key>:
return "n";
case <API key>:
return "m";
case GPGME_VALIDITY_FULL:
return "f";
case <API key>:
return "u";
default:
return "?";
}
}
static const char *
validity_to_string (int validity)
{
switch (validity)
{
case <API key>:
return "q";
case <API key>:
return "n";
case <API key>:
return "m";
case GPGME_VALIDITY_FULL:
return "f";
case <API key>:
return "u";
case <API key>:
default:
return "?";
}
}
static const char *
<API key> (gpgme_subkey_t subkey)
{
static const char *const strings[8] =
{
"",
"c",
"s",
"sc",
"e",
"ec",
"es",
"esc"
};
return strings[(!!subkey->can_encrypt << 2)
| (!!subkey->can_sign << 1)
| (!!subkey->can_certify)];
}
/* Return the value of the attribute WHAT of ITEM, which has to be
representable by a string. */
const char *
<API key> (gpgme_key_t key, _gpgme_attr_t what,
const void *reserved, int idx)
{
gpgme_subkey_t subkey;
gpgme_user_id_t uid;
int i;
if (!key || reserved || idx < 0)
return NULL;
/* Select IDXth subkey. */
subkey = key->subkeys;
for (i = 0; i < idx; i++)
{
subkey = subkey->next;
if (!subkey)
break;
}
/* Select the IDXth user ID. */
uid = key->uids;
for (i = 0; i < idx; i++)
{
uid = uid->next;
if (!uid)
break;
}
switch (what)
{
case GPGME_ATTR_KEYID:
return subkey ? subkey->keyid : NULL;
case GPGME_ATTR_FPR:
return subkey ? subkey->fpr : NULL;
case GPGME_ATTR_ALGO:
return subkey ? <API key> (subkey->pubkey_algo) : NULL;
case GPGME_ATTR_TYPE:
return key->protocol == GPGME_PROTOCOL_CMS ? "X.509" : "PGP";
case GPGME_ATTR_OTRUST:
return otrust_to_string (key->owner_trust);
case GPGME_ATTR_USERID:
return uid ? uid->uid : NULL;
case GPGME_ATTR_NAME:
return uid ? uid->name : NULL;
case GPGME_ATTR_EMAIL:
return uid ? uid->email : NULL;
case GPGME_ATTR_COMMENT:
return uid ? uid->comment : NULL;
case GPGME_ATTR_VALIDITY:
return uid ? validity_to_string (uid->validity) : NULL;
case GPGME_ATTR_KEY_CAPS:
return subkey ? <API key> (subkey) : NULL;
case GPGME_ATTR_SERIAL:
return key->issuer_serial;
case GPGME_ATTR_ISSUER:
return idx ? NULL : key->issuer_name;
case GPGME_ATTR_CHAINID:
return key->chain_id;
default:
return NULL;
}
}
unsigned long
<API key> (gpgme_key_t key, _gpgme_attr_t what,
const void *reserved, int idx)
{
gpgme_subkey_t subkey;
gpgme_user_id_t uid;
int i;
if (!key || reserved || idx < 0)
return 0;
/* Select IDXth subkey. */
subkey = key->subkeys;
for (i = 0; i < idx; i++)
{
subkey = subkey->next;
if (!subkey)
break;
}
/* Select the IDXth user ID. */
uid = key->uids;
for (i = 0; i < idx; i++)
{
uid = uid->next;
if (!uid)
break;
}
switch (what)
{
case GPGME_ATTR_ALGO:
return subkey ? (unsigned long) subkey->pubkey_algo : 0;
case GPGME_ATTR_LEN:
return subkey ? (unsigned long) subkey->length : 0;
case GPGME_ATTR_TYPE:
return key->protocol == GPGME_PROTOCOL_CMS ? 1 : 0;
case GPGME_ATTR_CREATED:
return (subkey && subkey->timestamp >= 0)
? (unsigned long) subkey->timestamp : 0;
case GPGME_ATTR_EXPIRE:
return (subkey && subkey->expires >= 0)
? (unsigned long) subkey->expires : 0;
case GPGME_ATTR_VALIDITY:
return uid ? uid->validity : 0;
case GPGME_ATTR_OTRUST:
return key->owner_trust;
case <API key>:
return !!key->secret;
case <API key>:
return subkey ? subkey->revoked : 0;
case <API key>:
return subkey ? subkey->invalid : 0;
case <API key>:
return subkey ? subkey->expired : 0;
case <API key>:
return subkey ? subkey->disabled : 0;
case <API key>:
return uid ? uid->revoked : 0;
case <API key>:
return uid ? uid->invalid : 0;
case <API key>:
return key->can_encrypt;
case GPGME_ATTR_CAN_SIGN:
return key->can_sign;
case <API key>:
return key->can_certify;
default:
return 0;
}
}
static gpgme_key_sig_t
get_keysig (gpgme_key_t key, int uid_idx, int idx)
{
gpgme_user_id_t uid;
gpgme_key_sig_t sig;
if (!key || uid_idx < 0 || idx < 0)
return NULL;
uid = key->uids;
while (uid && uid_idx > 0)
{
uid = uid->next;
uid_idx
}
if (!uid)
return NULL;
sig = uid->signatures;
while (sig && idx > 0)
{
sig = sig->next;
idx
}
return sig;
}
const char *
<API key> (gpgme_key_t key, int uid_idx,
_gpgme_attr_t what,
const void *reserved, int idx)
{
gpgme_key_sig_t certsig = get_keysig (key, uid_idx, idx);
if (!certsig || reserved)
return NULL;
switch (what)
{
case GPGME_ATTR_KEYID:
return certsig->keyid;
case GPGME_ATTR_ALGO:
return <API key> (certsig->pubkey_algo);
case GPGME_ATTR_USERID:
return certsig->uid;
case GPGME_ATTR_NAME:
return certsig->name;
case GPGME_ATTR_EMAIL:
return certsig->email;
case GPGME_ATTR_COMMENT:
return certsig->comment;
default:
return NULL;
}
}
unsigned long
<API key> (gpgme_key_t key, int uid_idx, _gpgme_attr_t what,
const void *reserved, int idx)
{
gpgme_key_sig_t certsig = get_keysig (key, uid_idx, idx);
if (!certsig || reserved)
return 0;
switch (what)
{
case GPGME_ATTR_ALGO:
return (unsigned long) certsig->pubkey_algo;
case GPGME_ATTR_CREATED:
return certsig->timestamp < 0 ? 0L : (unsigned long) certsig->timestamp;
case GPGME_ATTR_EXPIRE:
return certsig->expires < 0 ? 0L : (unsigned long) certsig->expires;
case <API key>:
return certsig->revoked;
case <API key>:
return certsig->invalid;
case <API key>:
return certsig->expired;
case <API key>:
return certsig->sig_class;
case <API key>:
return certsig->status;
default:
return 0;
}
} |
package com.nationwide.mqtt;
public final class <API key> {
public static final String TCPADDRESS = "tcp://52.4.65.48:1883";
public static final String CLIENTID = "gpspublisher";
public static final int SLEEPTIMEOUT = 10000;
public static final int QOS0 = 0;
public static final boolean RETAINED = false;
public static final String TOPICGPS = "location/gps/coordinates";
public static final String GPS_PAYLOAD = "{lat:41.428917,lon:-93.726277}";
} |
# shotbot
Script to help identify and mobilize political action related to gun violence.
The script currently:
- Fetches a list of yesterday's incidents relating to gun violence (incl. city/state and link to source),
- Finds the geolocation of each of the incidents (lat/long),
- Identifies which state and national legislators represent the area of the incident,
- Gets their contact info (email addresses for state representatives, also Facebook and Twitter info for national legislators),
- Gets campaign contributions made to each representative (national only) from the 'Gun Rights' industry
Shotbot uses data provided by:
- Sunlight Labs (http://sunlightfoundation.com/api/)
- The Center for Responsive Politics' OpenSecrets.org (https:
- The Google Geocoding API (https://developers.google.com/maps/documentation/geocoding)
Based on an idea by S. Schaevitz.
## Usage
Dependencies
Prerequisites to run the script:
pip install beautifulsoup4
pip install sunlight
Also, download and install the CRP API client library from VoteSmart:
https://github.com/votesmart/python-crpapi
Configuration
You'll need to create a config.json file in the same directory as shotbot.py,
with the following key/values:
{
"sunlight_api_key":"<your key here - get one from https://goo.gl/Mfp5qr>",
"crp_api_key":"<your key here - get one from https://goo.gl/BnlL9q>",
"google_api_key":"<your key here - get one from https://goo.gl/DsF2Qu>"
}
Usage
Just run the script to see output in the terminal:
python shotbot.py |
<!DOCTYPE html>
<html lang="zh-cn">
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=GB2312" /><!-- /Added by HTTrack -->
<head>
<meta charset="utf-8" />
<meta name="robots" content="all" />
<meta name="author" content="w3school.com.cn" />
<link rel="stylesheet" type="text/css" href="tc.css" />
<title>W3School V2</title>
</head>
<body id="editor">
<div id="wrapper">
<div id="header">
<h1>W3School TIY</h1>
<div id="ad">
<script type="text/javascript"><!
google_ad_client = "<API key>";
/* 728x90, tiy_big */
google_ad_slot = "7947784850";
google_ad_width = 728;
google_ad_height = 90;
</script>
<script type="text/javascript"
src="../../pagead2.googlesyndication.com/pagead/f.txt">
</script>
</div>
</div>
<form action="http:
<div id="butt">
<input type="button" value="" onClick="submitTryit()">
</div>
<div id="CodeArea">
<h2></h2>
<textarea id="TestCode" wrap="logical">
<html>
<head>
<script type="text/javascript">
function blinklink()
{
if (!document.getElementById('blink').style.color)
{
document.getElementById('blink').style.color="red"
}
if (document.getElementById('blink').style.color=="red")
{
document.getElementById('blink').style.color="black"
}
else
{
document.getElementById('blink').style.color="red"
}
timer=setTimeout("blinklink()",100)
}
function stoptimer()
{
clearTimeout(timer)
}
</script>
</head>
<body onload="blinklink()" onunload="stoptimer()">
<a id="blink" href="../index-2.html"></a>
</body>
</html>
</textarea>
</div>
<input type="hidden" id="code" name="code" />
<input type="hidden" id="bt" name="bt" />
</form>
<div id="result">
<h2>:</h2>
<iframe frameborder="0" name="i" src="loadtext8e4d.html?f=dhtm_blink"></iframe>
</div>
<div id="footer">
<p><a href="../index-2.html" title="W3School ">w3school.com.cn</a></p>
</div>
</div>
<script type="text/javascript">
function submitTryit()
{
var t=document.getElementById("TestCode").value;
t=t.replace(/=/gi,"w3equalsign");
t=t.replace(/script/gi,"w3scrw3ipttag");
document.getElementById("code").value=t;
document.getElementById("tryitform").action="v.html";
validateForm();
document.getElementById("tryitform").submit();
}
function validateForm()
{
var code=document.getElementById("code").value;
if (code.length>5000)
{
document.getElementById("code").value="<h1>Error</h1>";
}
}
</script>
</body>
</html> |
# SecretKey.pm
# - providing an object-oriented approach to GnuPG secret keys
# This module is free software; you can redistribute it and/or modify it
# under the same terms as Perl itself.
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# $Id: SecretKey.pm,v 1.9 2001/09/14 12:34:36 ftobin Exp $
package GnuPG::SecretKey;
use strict;
use base qw( GnuPG::PrimaryKey );
1;
__END__
=head1 NAME
GnuPG::SecretKey - GnuPG Secret Key Objects
=head1 SYNOPSIS
# assumes a GnuPG::Interface object in $gnupg
my @keys = $gnupg->get_secret_keys( 'ftobin' );
# now GnuPG::SecretKey objects are in @keys
=head1 DESCRIPTION
GnuPG::SecretKey objects are generally instantiated
through various methods of GnuPG::Interface.
They embody various aspects of a GnuPG secret key.
This package inherits data members and object methods
from GnuPG::PrimaryKey, which is described here, but rather
in L<GnuPG::PrimaryKey>.
Currently, this package is functionally no different
from GnuPG::PrimaryKey.
=head1 SEE ALSO
L<GnuPG::PrimaryKey>,
=cut |
<?php
namespace PHPRealCoverage\Proxy;
class <API key>
{
private $someParameter;
public function __construct($someParameter)
{
$this->someParameter = $someParameter;
}
public function getSomeParameter()
{
return $this->someParameter;
}
} |
package org.klomp.cassowary.clconstraint;
import org.klomp.cassowary.ClLinearExpression;
import org.klomp.cassowary.ClStrength;
class ClLinearConstraint extends ClConstraint {
protected ClLinearExpression _expression;
public ClLinearConstraint(ClLinearExpression cle, ClStrength strength, double weight) {
super(strength, weight);
_expression = cle;
}
public ClLinearConstraint(ClLinearExpression cle, ClStrength strength) {
super(strength, 1.0);
_expression = cle;
}
public ClLinearConstraint(ClLinearExpression cle) {
super(ClStrength.required, 1.0);
_expression = cle;
}
@Override
public ClLinearExpression expression() {
return _expression;
}
protected void setExpression(ClLinearExpression expr) {
_expression = expr;
}
} |
/* Trivial i2c driver for the maxim DS1621 temperature sensor;
* just implements reading constant conversions with 8-bit
* resolution.
* Demonstrates the implementation of a i2c high-level driver.
*/
#include <rtems.h>
#include <rtems/libi2c.h>
#include <libchip/i2c-ds1621.h>
#include <rtems/libio.h>
static rtems_status_code
ds1621_init (<API key> major, <API key> minor,
void *arg)
{
int sc;
unsigned char csr[2] = { <API key>, 0 }, cmd;
/* First start command acquires a lock for the bus */
/* Initialize; switch continuous conversion on */
sc = <API key> (minor, csr, 1);
if (sc < 0)
return -sc;
sc = <API key> (minor, csr + 1, 1);
if (sc < 0)
return -sc;
csr[1] &= ~DS1621_CSR_1SHOT;
sc = <API key> (minor, csr, 2);
if (sc < 0)
return -sc;
/* Start conversion */
cmd = <API key>;
sc = <API key> (minor, &cmd, 1);
if (sc < 0)
return -sc;
/* sending 'stop' relinquishes the bus mutex -- don't hold it
* across system calls!
*/
return <API key> (minor);
}
static rtems_status_code
ds1621_read (<API key> major, <API key> minor,
void *arg)
{
int sc;
<API key> *rwargs = arg;
unsigned char cmd = <API key>;
sc = <API key> (minor, &cmd, 1);
if (sc < 0)
return -sc;
if (sc < 1)
return RTEMS_IO_ERROR;
sc = <API key>(minor, (unsigned char *)rwargs->buffer, 1);
if (sc < 0) {
rwargs->bytes_moved = 0;
return -sc;
}
rwargs->bytes_moved = 1;
return <API key> (minor);
}
static <API key> myops = {
<API key>: ds1621_init,
read_entry: ds1621_read,
};
static rtems_libi2c_drv_t my_drv_tbl = {
ops: &myops,
size: sizeof (my_drv_tbl),
};
rtems_libi2c_drv_t *<API key> = &my_drv_tbl; |
<html>
<h1>Autoplot Version 1.0</h1>
<p>Autoplot uses das2, an open-source java library for data visualization and data analysis created by the Radio and Plasma Wave Group at the University of Iowa.
</p>
<p>Autoplot was developed under NASA Award TODO 123-3456-78</p>
<p>Contributors:
<li>Jeremy Faden, Cottage Systems, Software and Design
<li>Robert S. Weigel, George Mason University, Design
<li>Edward West, University of Iowa, Consultation
</p>
<br>
<h2>Build Information:</h2>
<li>dasCore.jar: untagged_version(20080108_220703 jbf)
<li>VirboDataSourcePack.jar: untagged_version(20080108_215439 jbf)
<li>QDataSet.jar: untagged_version(20080109_062145 jbf)
<li>WavDataSource.jar: untagged_version(20080109_062145 jbf)
<li>DataSource.jar: untagged_version(20080108_215425 jbf)
<li>fil: untagged_version(20080108_220410 jbf)
</p>
</html> |
package com.pixo.serviceImpl;
import java.util.List;
import java.util.concurrent.<API key>;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Component;
/**
* @author abhibm
*
*
*Utility class to keep all file data for a rest call and clear it at the end of the call
*/
@Component("ListUtility")
public class FIleListUtility {
public static List<JSONObject> listOfFiles = new <API key><JSONObject>();
public void add(JSONObject name) {
listOfFiles.add(name);
}
public String getLog() {
return listOfFiles.toString();
}
public void clear(){
listOfFiles.clear();
}
} |
<?php
/** ensure this file is being included by a parent file */
defined('_JEXEC') or die('Restricted access');
Tienda::load( 'TiendaModelBase', 'models._base' );
class <API key> extends TiendaModelBase
{
protected function _buildQueryWhere(&$query)
{
$filter = $this->getState('filter');
$filter_deleted = $this->getState('filter_deleted');
$filter_userid = $this->getState('filter_userid');
$filter_addressid = $this->getState('filter_addressid');
$filter_shippingid = $this->getState('filter_shippingid');
$<API key> = $this->getState('<API key>');
$<API key> = $this->getState('<API key>');
if ($filter)
{
$key = $this->_db->Quote('%'.$this->_db->getEscaped( trim( strtolower( $filter ) ) ).'%');
$where = array();
$where[] = 'LOWER(tbl.address_id) LIKE '.$key;
$where[] = 'LOWER(tbl.address_1) LIKE '.$key;
$where[] = 'LOWER(tbl.address_2) LIKE '.$key;
$where[] = 'LOWER(tbl.address_zip) LIKE '.$key;
$where[] = 'LOWER(c.country_name) LIKE '.$key;
$where[] = 'LOWER(z.zone_name) LIKE '.$key;
$query->where('('.implode(' OR ', $where).')');
}
if (strlen($filter_deleted))
{
$query->where('tbl.is_deleted = '.$this->_db->Quote($filter_deleted));
}
if ($filter_addressid){
$query->where('tbl.address_id = '.$this->_db->Quote($filter_addressid));
}
if (strlen($filter_userid))
{
$query->where('tbl.user_id = '.$this->_db->Quote($filter_userid));
}
if ($filter_shippingid)
{
$query->where('tbl.is_default_shipping = 1');
}
if ($<API key>)
{
$query->where('tbl.is_default_billing = 1');
}
if ($<API key>)
{
$query->where('tbl.is_default_shipping = 1');
}
}
protected function _buildQueryFields(&$query)
{
$field = array();
$field[] = " tbl.* ";
$field[] = " c.country_name as country_name ";
$field[] = " z.zone_name as zone_name ";
$field[] = " c.country_isocode_2 as country_code ";
$field[] = " z.code as zone_code ";
$query->select( $field );
}
protected function _buildQueryJoins(&$query)
{
$query->join('LEFT', '#__tienda_countries c ON c.country_id = tbl.country_id');
$query->join('LEFT', '#__tienda_zones AS z ON z.zone_id = tbl.zone_id');
}
/**
* @return array
*/
public function getList($refresh = false)
{
$list = parent::getList($refresh);
// If no item in the list, return an array()
if( empty( $list ) ){
return array();
}
foreach($list as $item)
{
$item->link = 'index.php?option=com_tienda&view=addresses&task=edit&id='.$item->address_id;
if (!empty($item->extra_fields))
{
$extra_fields = new DSCParameter(trim($item->extra_fields));
$extra_fields = $extra_fields->toArray();
foreach($extra_fields as $k => $v)
{
$item->$k = $v;
}
}
}
return $list;
}
public function getItem($pk=null, $refresh=false, $emptyState=true)
{
$item = parent::getItem($pk, $refresh, $emptyState);
if (!empty($item->extra_fields))
{
$extra_fields = new DSCParameter(trim($item->extra_fields));
$extra_fields = $extra_fields->toArray();
foreach($extra_fields as $k => $v)
{
$item->$k = $v;
}
}
return $item;
}
} |
\chapter{Simulations}
\label{cha:simulations}
This chapter is about the different simulations available with
SimSpark. In particular the soccer simulation is described in detail.\newline
%-SECTION
%
%
\section{The Soccer Simulation}
\label{sec:soccersimulation}
We implemented a simulation for SimSpark where two teams of up to 6
humanoid robots play soccer against each other.
Figure \ref{fig:soccersim} shows a running soccer simulation with $12$ playing
robots of two teams. This seemingly simple setup poses a challenge to agent
implementers on several levels.
In order to act in a meaningful way on the playing field the first
challenge is to localize your agent on the playing field. To support
this the agents perceive their relative position to a set of
landmarks, called \texttt{flags} on the playing field. These flags
mark corner and goal spots of the playing field. Further the relative
location of other players and the ball on the soccer field are perceived.
If an agent knows where it is and where it wants to be in the near
future the next challenge is to walk there. The structure of the
humanoids are sufficiently realistic to make this non trivial. Further
the agent has to recover and get up if fallen over.
Another challenge is kicking the ball. As trivial this sounds to a
human it is far from trivial for a robot to keep its dynamic balance
when kicking and controlling the direction of the ball.
Agents that are able to move and kick the ball need to cooperate and
form a team. Only the effective application of strategic and
cooperative behaviors forms a successful team.
Most rules of the soccer game are judged by an automatic rule set that
enforces the basic soccer rule set. However more involved situations
like detection unfair behavior still require a human referee.\newline
This soccer simulation is also used as the official competition environment for
the 3D Soccer Simulation League at RoboCup\footnote{For more information on
RoboCup, see also \url{http:
\cite{KAK+97}\cite{KA00}\cite{BMO+05}\cite{MBS+07}. The robots used in the
simulation at the competitions is currently the Nao robot as described in
chapter \ref{cha:robots}.\newline
\begin{figure}[htbp]
\centering
\includegraphics[width=\textwidth]{fig/soccersim}
\caption{A screen shot of the soccer simulation with 6 vs 6 robots}
\label{fig:soccersim}
\end{figure}
%-SUB-SECTION
%
%
\subsection{Environment and Objects on the Field}
The dimensions of the soccer field are $x=18m$ by $y=12m$. The center spot has a
radius of $1.5$ meters. Each goal is $y=2.1m$ by $x=0.6m$ with a height of
$z=0.8m$. The penalty area to each goal is $y=3.9m$ by $x=1.8m$. The soccer
field is surrounded by a border of $10$ meters in each direction. Space outside
this border area is not reachable by an agent. The soccer ball has a radius of
$0.042$ meter and a mass of $26$ grams. For an up to date list of all values
please refer to (./rcssserver3d/naosoccersim.rb).
At each corner of the soccer field, and at the goal posts, a distinctive
flag is placed. The positions of these flags are fixed and known to
each agent. Agents perceive the relative position of a subset of
these flags and are therefore able to localize themselves on the soccer
field. Agents distinguish flags through their identifier as shown in figure
\ref{fig:pitch}. While the markers for the flags are placed on ground level
($z=0.0m$), the goalpost markers are placed on the top of each goalpost at a
height of $z=0.8m$.
\begin{figure}[htbp]
\centering
\includegraphics[width=\textwidth]{fig/pitch2}
\caption{The dimensions of the soccer pitch and the object markers on the
field as perceived by an agent}
\label{fig:pitch}
\end{figure}
%-SUB-SECTION
%
%
\subsection{Rules Judged by the Automatic Referee}
In order to run a soccer game several rules have to be applied.
The automatic referee automatically limits the time of each game
half. It further keeps track which player was the last one to touch
the ball and checks whether the ball enters the goal penalty areas of
the soccer field, or was kicked into touch. Therefore it is able to detect and
score \texttt{goals}, automatically judge \texttt{ball out} and give \texttt{kick
in}, \texttt{corner kick in} or \texttt{goal kick} to the correct team. The
\texttt{offside} rule is implemented but still experimental.
During a \texttt{free kick}, the opponent team has to keep a minimum distance of
$1.3$ meter, as well as $1.0$ meter in case of a \texttt{goal kick}.
With SimSpark Version 1.3 several new rules were applied to the automatic
referee, in order to ensure a smooth gameplay.
The automatic referee tries to avoid mass collisions of robots around the ball,
as well as dead robots lying around on the field, blocking the gameplay.
Furthermore it takes care that no team is blocking the own goal with more than
a certain amount of players. In all cases the robots causing the problem
situation are automatically beamed outside the soccer field. For an up to date
list of all values please refer to (./rcssserver3d/naosoccersim.rb).
%-SUB-SECTION
%
%
\subsection{Rules Judged by the Human Referee}
The human referee acts through a connected monitor. It is responsible
to give the \texttt{kick off} command to start each game half. The
automatic referee currently does not resolve situations where the game
got stuck if for example several player block each other and no one is
able to reach the ball. Further it does not detect fouls like the use
of hands or otherwise behavior on the soccer field.
In these cases the human referee can \texttt{drop ball} the ball,
i.e. put it on a random location on the playing field to unstuck the
game. He is further able to command a \texttt{free kick} where one
player is able to shoot from a short distance to the goal.
%\subsection{Setup Script}
%%% Local Variables:
%%% mode: latex
%%% TeX-master: "user-manual"
%%% End: |
#include "SQLite.h"
#include <sstream>
#include <stdexcept>
#include <sqlite3.h>
using namespace Chronos;
SQLite_DB::SQLite_DB(const std::string &fileName, const bool readOnly, const int BusyTimeoutMs) : strFileName(fileName)
{
int res = sqlite3_open_v2(strFileName.c_str(), &handle,
readOnly ? <API key> : <API key> | SQLITE_OPEN_CREATE, nullptr);
if(res != SQLITE_OK)
{
std::stringstream err;
err << "Failed to open database " << strFileName
<< ": " << sqlite3_errstr(res);
throw std::runtime_error(err.str());
}
res = <API key>(handle, BusyTimeoutMs);
if(res != SQLITE_OK)
{
std::stringstream err;
err << "Failed to set busy timeout:"
<< sqlite3_errstr(res);
throw std::runtime_error(err.str());
}
}
SQLite_DB::~SQLite_DB()
{
if(handle != nullptr)
{
sqlite3_close(handle);
handle = nullptr;
}
}
std::unique_ptr<SQLite_Statement> SQLite_DB::prepare(const std::string &strQuery)
{
sqlite3_stmt *stmt = nullptr;
int res = sqlite3_prepare_v2(handle, strQuery.c_str(), strQuery.size(), &stmt, nullptr);
if(res != SQLITE_OK)
{
std::stringstream err;
err << "Failed to prepare query " << strQuery
<< ": " << sqlite3_errstr(res) << ", "
<< sqlite3_errmsg(handle);
throw std::runtime_error(err.str());
}
return std::unique_ptr<SQLite_Statement>(new SQLite_Statement(stmt));
}
int64_t SQLite_DB::insertId()
{
return <API key>(handle);
}
int SQLite_DB::affectedRows()
{
return sqlite3_changes(handle);
}
SQLite_Statement::SQLite_Statement(sqlite3_stmt *handle) : stmt(handle)
{
}
SQLite_Statement::~SQLite_Statement()
{
if(stmt != nullptr)
{
sqlite3_finalize(stmt);
stmt = nullptr;
}
}
void SQLite_Statement::bind(const std::string &field, int val)
{
int res = sqlite3_bind_int(stmt, fieldIndex(field), val);
if(res != SQLITE_OK)
{
std::stringstream err;
err << "Failed to bind int value " << field
<< ": " << sqlite3_errstr(res);
throw std::runtime_error(err.str());
}
}
void SQLite_Statement::bind(const std::string &field, const std::string &val)
{
int res = sqlite3_bind_text(stmt, fieldIndex(field), val.c_str(), val.size(), SQLITE_TRANSIENT);
if(res != SQLITE_OK)
{
std::stringstream err;
err << "Failed to bind string value " << field
<< ": " << sqlite3_errstr(res);
throw std::runtime_error(err.str());
}
}
int SQLite_Statement::fieldIndex(const std::string &field)
{
int index = <API key>(stmt, field.c_str());
if(index == 0)
{
std::stringstream err;
err << "Field not found: " << field;
throw std::runtime_error(err.str());
}
return index;
}
bool SQLite_Statement::execute()
{
int res = sqlite3_step(stmt);
if(res != SQLITE_OK && res != SQLITE_DONE && res != SQLITE_ROW)
{
std::stringstream err;
err << "Failed to execute query: "
<< sqlite3_errstr(res);
throw std::runtime_error(err.str());
}
if((res == SQLITE_OK || res == SQLITE_ROW) && !columnsFetched)
{
columns.clear();
for(int i = 0; i < <API key>(stmt); ++i)
{
columns.emplace(std::string(sqlite3_column_name(stmt, i)), i);
}
columnsFetched = true;
}
return(res == SQLITE_OK || res == SQLITE_ROW);
}
void SQLite_Statement::reset()
{
columnsFetched = false;
columns.clear();
sqlite3_reset(stmt);
}
int SQLite_Statement::intValue(const std::string &field)
{
auto it = columns.find(field);
if(it == columns.end())
throw std::runtime_error("Field not found: " + field);
return sqlite3_column_int(stmt, it->second);
}
int SQLite_Statement::intValue(int fieldNo)
{
return sqlite3_column_int(stmt, fieldNo);
}
bool SQLite_Statement::isNull(const std::string &field)
{
auto it = columns.find(field);
if(it == columns.end())
throw std::runtime_error("Field not found: " + field);
return sqlite3_column_type(stmt, it->second) == SQLITE_NULL;
}
std::string SQLite_Statement::stringValue(const std::string &field)
{
auto it = columns.find(field);
if(it == columns.end())
throw std::runtime_error("Field not found: " + field);
const unsigned char *columnText = sqlite3_column_text(stmt, it->second);
if(columnText == nullptr)
return {};
return std::string(reinterpret_cast<const char *>(columnText));
}
bool SQLite_Statement::hasField(const std::string &field) const
{
return(columns.find(field) != columns.end());
} |
package org.n52.sos.config.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation that should be applied to a method that takes a single Setting as
* a parameter. The parameter of this method should be of the same type as the
* {@link org.n52.sos.config.SettingDefinition} declared with the same
* {@code key} in a {@link org.n52.sos.config.<API key>}.
* <p/>
* It is needed to apply the {@code Configurable} annotation to a class with a
* method annotated with this annotations for the {@code SettingsManager} to
* recognize it.
* <p/>
* <b>Example usage:</b>
*
* <pre>
* @Setting(<API key>.TOKEN_SEPERATOR_KEY)
* public void setTokenSeperator(String separator) {
* this.separator = separator;
* }
* </pre>
* <p/>
*
* @see Configurable
* @see org.n52.sos.config.SettingDefinition
* @see org.n52.sos.config.<API key>
* @see org.n52.sos.config.SettingsManager <p/>
* @author Christian Autermann <c.autermann@52north.org>
* @since 4.0.0
*/
@Inherited
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Setting {
/**
* The key of the setting.
* <p/>
*
* @return the key
*/
String value();
} |
using System.Collections;
using Db4oUnit.Extensions;
using Db4objects.Db4o.Config;
using Db4objects.Db4o.Tests.Jre5.Collections.Typehandler;
using Db4objects.Db4o.Typehandlers;
namespace Db4objects.Db4o.Tests.Jre5.Collections.Typehandler
{
public class <API key> : <API key>
{
public static void Main(string[] args)
{
new <API key>().RunAll();
}
public class TypedItem
{
internal ArrayList list;
}
public class InterfaceItem
{
internal IList list;
}
public class UntypedItem
{
internal object list;
}
<exception cref="System.Exception"></exception>
protected override void Configure(IConfiguration config)
{
config.RegisterTypeHandler(new <API key>(typeof(ArrayList))
, new <API key>());
}
public virtual void TestTypedItem()
{
<API key>.TypedItem typedItem = new <API key>.TypedItem
();
typedItem.list = new ArrayList();
Store(typedItem);
Db4oAssert.PersistedCount(1, typeof(ArrayList));
}
public virtual void TestInterFaceItem()
{
<API key>.InterfaceItem interfaceItem = new <API key>.InterfaceItem
();
interfaceItem.list = new ArrayList();
Store(interfaceItem);
Db4oAssert.PersistedCount(1, typeof(ArrayList));
}
public virtual void TestUntypedItem()
{
<API key>.UntypedItem untypedItem = new <API key>.UntypedItem
();
untypedItem.list = new ArrayList();
Store(untypedItem);
Db4oAssert.PersistedCount(1, typeof(ArrayList));
}
}
} |
<!DOCTYPE html>
<html lang="zh-CN" <API key>="auto">
<head><meta name="generator" content="Hexo 3.9.0">
<meta charset="UTF-8">
<link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
<link rel="icon" type="image/png" href="/img/favicon.png">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="theme-color" content="#2f4154">
<meta name="description" content="">
<meta name="author" content="TinyKing">
<meta name="keywords" content="undefined">
<title> - TypeScript - </title>
<link rel="stylesheet" href="https://cdn.staticfile.org/<TwitterConsumerkey>/4.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="//at.alicdn.com/t/<API key>.css">
<link rel="stylesheet" href="//at.alicdn.com/t/<API key>.css">
<link rel="stylesheet" href="/css/main.css">
<script src="/js/utils.js"></script>
<script src="/js/color-schema.js"></script>
</head>
<body>
<header style="height: 80vh;">
<nav id="navbar" class="navbar fixed-top navbar-expand-lg navbar-dark scrolling-navbar">
<div class="container">
<a class="navbar-brand"
href="/"> <strong></strong> </a>
<button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
data-target="#<API key>"
aria-controls="<API key>" aria-expanded="false" aria-label="Toggle navigation">
<div class="animated-icon"><span></span><span></span><span></span></div>
</button>
<!-- Collapsible content -->
<div class="collapse navbar-collapse" id="<API key>">
<ul class="navbar-nav ml-auto text-center">
<li class="nav-item">
<a class="nav-link" href="/">
<i class="iconfont icon-home-fill"></i>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/archives/">
<i class="iconfont icon-archive-fill"></i>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/categories/">
<i class="iconfont icon-category-fill"></i>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/tags/">
<i class="iconfont icon-tags-fill"></i>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/about/">
<i class="iconfont icon-user-fill"></i>
</a>
</li>
<li class="nav-item" id="search-btn">
<a class="nav-link" data-toggle="modal" data-target="#modalSearch"> <i
class="iconfont icon-search"></i> </a>
</li>
<li class="nav-item" id="color-toggle-btn">
<a class="nav-link" href="javascript:"> <i
class="iconfont icon-dark" id="color-toggle-icon"></i> </a>
</li>
</ul>
</div>
</div>
</nav>
<div class="banner intro-2" id="background" parallax=true
style="background: url('/img/default.png') no-repeat center center;
background-size: cover;">
<div class="full-bg-img">
<div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
<div class="container page-header text-center fade-in-up">
<span class="h2" id="subtitle">
</span>
</div>
</div>
</div>
</div>
</header>
<main>
<div class="container nopadding-md">
<div class="py-5" id="board"
>
<div class="container">
<div class="row">
<div class="col-12 col-md-10 m-auto">
<div class="list-group">
<p class="h4"> 1 </p>
<hr>
<p class="h5">2019</p>
<a href="/2019/06/05/<API key>/" class="list-group-item <API key>">
<span class="archive-post-title">TypeScript</span>
<time style="float: right;">06-05</time>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</main>
<a id="scroll-top-button" href="#" role="button">
<i class="iconfont icon-arrowup" aria-hidden="true"></i>
</a>
<div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
aria-hidden="true">
<div class="modal-dialog <API key> modal-lg" role="document">
<div class="modal-content">
<div class="modal-header text-center">
<h4 class="modal-title w-100 font-weight-bold"></h4>
<button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body mx-3">
<div class="md-form mb-5">
<input type="text" id="local-search-input" class="form-control validate">
<label data-error="x" data-success="v"
for="local-search-input"></label>
</div>
<div class="list-group" id="local-search-result"></div>
</div>
</div>
</div>
</div>
<footer class="mt-5">
<div class="text-center py-3">
<div>
<a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a>
<i class="iconfont icon-love"></i>
<a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener">
<span>Fluid</span></a>
</div>
<div class="statistics">
<span id="<API key>" style="display: none">
<span id="<API key>"></span>
</span>
<span id="<API key>" style="display: none">
<span id="<API key>"></span>
</span>
</div>
</div>
</footer>
<!-- SCRIPTS -->
<script src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script src="https://cdn.staticfile.org/<TwitterConsumerkey>/4.4.1/js/bootstrap.min.js" ></script>
<script src="/js/debouncer.js" ></script>
<script src="/js/main.js" ></script>
<!-- Plugins -->
<script src="/js/lazyload.js" ></script>
<script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
<script src="/js/clipboard-use.js" ></script>
<script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>
<script src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
<script>
var typed = new Typed('#subtitle', {
strings: [
' ',
" - TypeScript ",
],
cursorChar: "_",
typeSpeed: 70,
loop: false,
});
typed.stop();
$(document).ready(function () {
$(".typed-cursor").addClass("h2");
typed.start();
});
</script>
<script src="/js/local-search.js" ></script>
<script>
var path = "/local-search.xml";
var inputArea = document.querySelector("#local-search-input");
inputArea.onclick = function () {
searchFunc(path, 'local-search-input', 'local-search-result');
this.onclick = null
}
</script>
<script data-ad-client="<API key>" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
</body>
</html> |
#ifndef _LEO_H
#define _LDO_H
#define LDO_NUM 3
typedef enum
{
V365 = 0x80, V360 = 0x81, V355 = 0x82, V350 = 0x83, V345 = 0x84,
V340 = 0x85, V335 = 0x86, V330 = 0x87, V325 = 0x88, V320 = 0x89,
V315 = 0x8A, V310 = 0x8B, V305 = 0x8C, V300 = 0x8D, V295 = 0x8E, V290 = 0x8F,
V285 = 0x90, V280 = 0x91, V275 = 0x92, V270 = 0x93, V265 = 0x94,
V260 = 0x95, V255 = 0x96, V250 = 0x97, V245 = 0x98, V240 = 0x99,
V235 = 0x9A, V230 = 0x9B, V225 = 0x9C, V220 = 0x9D, V215 = 0x9E, V210 = 0x9F,
V205 = 0xA0, V200 = 0xA1, V195 = 0xA2, V190 = 0xA3, V185 = 0xA4,
V180 = 0xA5, V175 = 0xA6, V170 = 0xA7, V165 = 0xA8, V160 = 0xA9,
V155 = 0xAA, V150 = 0xAB, V145 = 0xAC, V140 = 0xAD, V135 = 0xAE, V130 = 0xAF,
V125 = 0xB0, V120 = 0xB1, V115 = 0xB2, V110 = 0xB3, V105 = 0xB4,
V100 = 0xB5, V095 = 0xB6, V090 = 0xB7, V085 = 0xB8, V080 = 0xB9,
V075 = 0xBA, V070 = 0xBB, V065 = 0xBC, V060 = 0xBD, V055 = 0xBE, V050 = 0xBF
}LdoVol;
INT8U Ldo_cmd[LDO_NUM]={
0x01, 0x02, 0x03
};
INT8U Ldo_data[LDO_NUM]={
0x00, 0x00, 0xff
};
#endif |
/*
* @file
* Library of shared code for feedback_client.
*/
/**
* Create HTML with links to attachments.
* @param {Array} attachmentData Data about attachments. Array, each element
* an object with filename and url.
* @param {string} titleToUse Title for the section. Defaults to Attachments.
* @returns {String} HTML.
*/
app.<API key> = function( attachmentData, titleToUse ) {
//Title defaults to Attachment.
if ( ! titleToUse ) {
titleToUse = "Attachments";
}
var linksHtml = "";
linksHtml += "<div class='<API key>'>"
+ "<p class='<API key>'>" + titleToUse + "</p>";
for( var index in attachmentData ) {
var filename = attachmentData[ index ].filename;
var url = attachmentData[ index ].url;
//Make a link.
var link = "<a href='" + url + "' data-target='popup' title='Open'>"
+ filename + "</a>";
linksHtml += "<p class='<API key>'>"
+ link + "</p>";
} //End for.
linksHtml += "</div>";
return linksHtml;
}
/**
* Open attachment links in new window.
*/
app.<API key> = function() {
$(".pane-content").on("click", "a[data-target=popup]", function(event) {
event.preventDefault();
event.stopPropagation();
var filename = $(this).text();
<API key> = window.open(
$(this).attr("href"),
"Attachment " + filename,
"resizable,scrollbars,height=400,width=400"
);
<API key>.document.title = "DOG";
return false; //Cancel standard action.
});
};
app.<API key> = function ( thing ) {
return thing.charAt(0).toUpperCase() + thing.slice(1);
};
/**
* Count the number of nonMT elements in an array.
* From "Speaking JavaScript," p. 279.
* @param {Array} arr The array
* @returns {Number} Number of nonempty elements.
*/
app.countElements = function(arr) {
var elemCount = 0;
arr.forEach(function () {
elemCount++;
});
return elemCount;
}; |
select blocking_session_id, wait_duration_ms, session_id from
sys.dm_os_waiting_tasks
where blocking_session_id is not null
-- blocking_session_id SQL blocking_session_id 87 SQL
dbcc INPUTBUFFER(87) |
package de.quist.app.samyGoRemote;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class <API key> extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
<API key>(R.xml.main_preferences);
}
} |
<?php
/**
* Form Edit Page inheriting from EditPage
*
* @author Daniel Friesen
* @author Yaron Koren
*/
class SFFormEditPage extends EditPage {
protected $form, $form_name;
function __construct( $article, $form_name = '' ) {
global $wgRequest;
parent::__construct( $article );
SFUtils::loadMessages();
$this->action = 'formedit';
$form_name = $wgRequest->getText( 'form', $form_name );
$this->form = Title::makeTitleSafe( SF_NS_FORM, $form_name );
$this->form_name = $form_name;
}
protected function <API key>() {
return false; // sections and forms don't mix
}
function setHeaders() {
parent::setHeaders();
global $wgOut, $wgTitle;
if ( !$this->isConflict ) {
$wgOut->setPageTitle( wfMsg( 'sf_formedit_title',
$this->form->getText(), $wgTitle->getPrefixedText() ) );
}
}
protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
if ( $this->textbox1 != null )
parent::displayPreviewArea( $previewOutput );
}
protected function <API key>( &$request ) {
// @todo This is where $request to save&preview page text should go
}
protected function showContentForm() {
global $sfgIP;
$target_title = $this->mArticle->getTitle();
$target_name = SFUtils::titleString( $target_title );
if ( $target_title->exists() ) {
SFEditData::printEditForm( $this->form_name, $target_name, $this->textbox1 );
} else {
SFAddData::printAddForm( $this->form_name, $target_name, array(), $this->textbox1 );
}
// @todo This needs a proper form builder
}
function showFooter() {
}
} |
package org.adempierelbr.process;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import org.adempierelbr.gia.CounterGIA;
import org.adempierelbr.gia.beans.CR01;
import org.adempierelbr.gia.beans.CR10;
import org.adempierelbr.gia.beans.CR14;
import org.adempierelbr.gia.beans.CR20;
import org.adempierelbr.gia.util.GIAUtil;
import org.adempierelbr.util.AdempiereLBR;
import org.adempierelbr.util.TextUtil;
import org.compiere.model.MPeriod;
import org.compiere.process.<API key>;
import org.compiere.process.SvrProcess;
public class ProcGenerateGIA extends SvrProcess
{
/** Arquivo */
private String p_FilePath = null;
private int p_C_Period_ID = 0;
private CR10[] _CR10; //CFOPS
private CR20[] _CR20; //OCORRENCIAS
private Map<String,CR14[]> _CR14 = new HashMap<String,CR14[]>(); //DETALHES POR ESTADO
/**
* Prepare - e.g., get Parameters.
*/
protected void prepare ()
{
<API key>[] para = getParameter();
for (int i = 0; i < para.length; i++)
{
String name = para[i].getParameterName();
if (para[i].getParameter() == null)
;
else if (name.equals("File_Directory"))
p_FilePath = para[i].getParameter().toString();
else if (name.equals("C_Period_ID")){
p_C_Period_ID = para[i].getParameterAsInt();
}
else
log.log(Level.SEVERE, "prepare - Unknown Parameter: " + name);
} // for
} // prepare
/**
* Do It
*/
protected String doIt () throws Exception
{
long start = System.currentTimeMillis();
MPeriod period = new MPeriod(getCtx(),p_C_Period_ID,get_TrxName());
String fileName = p_FilePath;
StringBuffer result = runGIA(p_C_Period_ID);
if (!(p_FilePath.endsWith(AdempiereLBR.getFileSeparator())))
fileName += AdempiereLBR.getFileSeparator();
fileName += "GIA_" + TextUtil.timeToString(period.getStartDate(), "ddMMyyyy")
+ TextUtil.timeToString(period.getEndDate(), "ddMMyyyy") + ".prf";
TextUtil.generateFile(result.toString(), fileName);
long end = System.currentTimeMillis();
String tempoDecorrido = AdempiereLBR.executionTime(start, end);
return "Arquivo(s) Gerado(s) com Sucesso: " + fileName +
" <br>** Tempo decorrido: <font color=\"008800\">" + tempoDecorrido + "</font>";
} // doIt
/**
* @param ctx
* @return
* @throws Exception
*/
private StringBuffer runGIA (int C_Period_ID) throws Exception
{
log.fine("init");
StringBuffer result = new StringBuffer();
GIAUtil.setEnv(getCtx(), get_TrxName(), C_Period_ID);
CounterGIA.clear();
_CR10 = GIAUtil.createCR10();
_CR20 = GIAUtil.createCR20();
result.append(new CR01());
result.append(GIAUtil.createCR05());
//DETALHES CFOP
if(_CR10 != null){
Arrays.sort(_CR10);
for(CR10 cfop : _CR10){
//CRIA DETALHES POR ESTADO - CFOPS 2.XXX e 6.XXX
if (cfop.getCFOP().charAt(0) == '2' || cfop.getCFOP().charAt(0) == '6'){
_CR14.put(cfop.getCFOP(), GIAUtil.createCR14(cfop.getCFOP()));
}
result.append(cfop);
if (_CR14.containsKey(cfop.getCFOP())){ //DETALHES INTERESTADUAIS
CR14[] estados = _CR14.get(cfop.getCFOP());
Arrays.sort(estados);
for(CR14 estado : estados){
result.append(estado);
} //LOOP ESTADOS
}
} //LOOP CFOPS
}
if (_CR20 != null){
for(CR20 ocorrencia : _CR20){
result.append(ocorrencia);
}
}
return result;
} // runGIA
} // ProcGenerateGIA |
/* This file is part of the NANOS++ library. */
/* NANOS++ is free software: you can redistribute it and/or modify */
/* (at your option) any later version. */
/* NANOS++ is distributed in the hope that it will be useful, */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
#ifndef REGIONDICT_H
#define REGIONDICT_H
#include "error.hpp"
#include "memorymap.hpp"
#include "os.hpp"
#include "regiondict_decl.hpp"
#include "system_decl.hpp"
#include "mutex.hpp"
namespace nanos {
inline RegionVectorEntry::RegionVectorEntry() : _leaf( NULL ), _data( NULL ) {
}
inline RegionVectorEntry::RegionVectorEntry( RegionVectorEntry const &rve ) : _leaf( rve._leaf ), _data( rve._data ) {
}
inline RegionVectorEntry &RegionVectorEntry::operator=( RegionVectorEntry const &rve ) {
_leaf = rve._leaf;
_data = rve._data;
return *this;
}
inline RegionVectorEntry::~RegionVectorEntry() {
}
inline void RegionVectorEntry::setLeaf( RegionNode *rn ) {
_leaf = rn;
}
inline RegionNode *RegionVectorEntry::getLeaf() const {
return _leaf;
}
inline void RegionVectorEntry::setData( Version *d ) {
_data = d;
}
inline Version *RegionVectorEntry::getData() const {
return _data;
}
inline RegionNode::RegionNode( RegionNode *parent, std::size_t value, reg_t id ) : _parent( parent ), _value( value ), _id( id ), _sons( NULL ) {
if ( id > 1 ) {
_memoIntersectInfo = NEW reg_t[ id - 1 ];
::memset(_memoIntersectInfo, 0, sizeof( reg_t ) * (id - 1) );
} else {
_memoIntersectInfo = NULL;
}
//std::cerr << "created node with value " << value << " and id " << id << std::endl;
}
inline RegionNode::RegionNode( RegionNode const& rn ) : _parent( rn._parent ),
_value( rn._value ), _id( rn._id ), _sons( rn._sons ),
_memoIntersectInfo( rn._memoIntersectInfo ) {
}
inline RegionNode &RegionNode::operator=( RegionNode const& rn ) {
_parent = rn._parent;
_value = rn._value;
_id = rn._id;
_sons = rn._sons;
_memoIntersectInfo = rn._memoIntersectInfo;
return *this;
}
inline RegionNode::~RegionNode() {
if ( _sons != NULL ) {
for (std::map<std::size_t, RegionNode *>::const_iterator it = _sons->begin();
it != _sons->end(); it++ ) {
delete it->second;
}
delete _sons;
}
delete[] _memoIntersectInfo;
_memoIntersectInfo = NULL;
}
inline reg_t RegionNode::getId() const {
return _id;
}
inline reg_t RegionNode::getMemoIntersect( reg_t target ) const {
return _memoIntersectInfo[ target-1 ];
}
inline void RegionNode::setMemoIntersect( reg_t target, reg_t value ) const {
_memoIntersectInfo[ target-1 ] = value;
}
inline std::size_t RegionNode::getValue() const {
return _value;
}
inline RegionNode *RegionNode::getParent() const {
return _parent;
}
template <class T>
ContainerDense< T >::ContainerDense( CopyData const &cd ) : _container(64, T())
, _leafCount( 0 )
, _idSeed( 1 )
, _dimensionSizes( cd.getNumDimensions(), 0 )
, _root( NULL, 0, 0 )
, _containerLock()
, _invalidationsLock()
, _masterIdToLocalId()
, _containerMi2LiLock()
, _keepAtOrigin( false )
, _registeredObject( NULL )
, sparse( false ) {
//_container.reserve( 64 );
for ( unsigned int idx = 0; idx < cd.getNumDimensions(); idx += 1 ) {
_dimensionSizes[ idx ] = cd.getDimensions()[ idx ].size;
}
}
template <class T>
ContainerDense< T >::~ContainerDense() {
}
template <class T>
RegionNode * ContainerDense< T >::getRegionNode( reg_t id ) {
LockGuard<ReadWriteLock> lg( _containerLock, read_access );
return _container[ id ].getLeaf();
}
template <class T>
void ContainerDense< T >::addRegionNode( RegionNode *leaf ) {
// no locking needed, only called from addRegion -> _root.addNode() -> addRegionNode
_container[ leaf->getId() ].setLeaf( leaf );
_container[ leaf->getId() ].setData( NULL );
_leafCount++;
}
template <class T>
Version *ContainerDense< T >::getRegionData( reg_t id ) {
LockGuard<ReadWriteLock> lg( _containerLock, read_access );
return _container[ id ].getData();
}
template <class T>
void ContainerDense< T >::setRegionData( reg_t id, Version *data ) {
LockGuard<ReadWriteLock> lg( _containerLock, read_access );
_container[ id ].setData( data );
}
template <class T>
unsigned int ContainerDense< T >::getRegionNodeCount() const {
return _leafCount.value();
}
template <class T>
unsigned int ContainerDense< T >::getNumDimensions() const {
return _dimensionSizes.size();
}
template <class T>
reg_t ContainerDense< T >::addRegion( <API key> const region[] ) {
LockGuard<ReadWriteLock> lg( _containerLock, write_access );
reg_t id = _root.addNode( region, _dimensionSizes.size(), 0, *this );
return id;
}
template <class T>
reg_t ContainerDense< T >::getNewRegionId() {
reg_t id = _idSeed++;
if ( id % 64 == 0 ) {
_container.resize( id + 64 );
}
if (id >= MAX_REG_ID) { std::cerr <<"Max regions reached."<<std::endl;}
return id;
}
template <class T>
reg_t ContainerDense< T >::checkIfRegionExists( <API key> const region[] ) {
LockGuard<ReadWriteLock> lg( _containerLock, read_access );
return _root.checkNode( region, _dimensionSizes.size(), 0 );
}
template <class T>
std::vector< std::size_t > const &ContainerDense< T >::getDimensionSizes() const {
return _dimensionSizes;
}
template <class T>
reg_t ContainerDense< T >::getMaxRegionId() const {
return _idSeed.value();
}
template <class T>
void ContainerDense< T >::invalLock() {
while ( !_invalidationsLock.tryAcquire() ) {
myThread->processTransfers();
}
}
template <class T>
void ContainerDense< T >::invalUnlock() {
return _invalidationsLock.release();
}
template <class T>
void ContainerDense< T >::addMasterRegionId( reg_t masterId, reg_t localId ) {
_containerMi2LiLock.acquire();
_masterIdToLocalId[ masterId ] = localId;
_containerMi2LiLock.release();
}
template <class T>
reg_t ContainerDense< T >::<API key>( reg_t masterId ) {
reg_t result = 0;
_containerMi2LiLock.acquire();
std::map< reg_t, reg_t >::const_iterator it = _masterIdToLocalId.find( masterId );
if ( it != _masterIdToLocalId.end() ) {
result = it->second;
}
_containerMi2LiLock.release();
return result;
}
template <class T>
void ContainerDense< T >::setKeepAtOrigin( bool value ) {
_keepAtOrigin = value;
}
template <class T>
bool ContainerDense< T >::getKeepAtOrigin() const {
return _keepAtOrigin;
}
template <class T>
void ContainerDense< T >::setRegisteredObject( CopyData *cd ) {
_registeredObject = cd;
}
template <class T>
CopyData *ContainerDense< T >::getRegisteredObject() const {
return _registeredObject;
}
template <class T>
ContainerSparse< T >::ContainerSparse( RegionDictionary< ContainerDense > &orig ) :
_container(),
_containerLock(),
_orig( orig ),
sparse( true )
{
}
template <class T>
ContainerSparse< T >::~ContainerSparse() {
}
template <class T>
RegionNode * ContainerSparse< T >::getRegionNode( reg_t id ) const {
std::map< reg_t, RegionVectorEntry >::const_iterator it = _container.lower_bound( id );
if ( it == _container.end() || _container.key_comp()(id, it->first) ) {
RegionNode *leaf = _orig.getRegionNode( id );
return leaf;
}
return it->second.getLeaf();
}
template <class T>
Version *ContainerSparse< T >::getRegionData( reg_t id ) {
//_containerLock.acquire();
while ( !_containerLock.tryAcquire() ) {
myThread->processTransfers();
}
std::map< reg_t, RegionVectorEntry >::iterator it = _container.lower_bound( id );
if ( it == _container.end() || _container.key_comp()(id, it->first) ) {
it = _container.insert( it, std::map< reg_t, RegionVectorEntry >::value_type( id, RegionVectorEntry() ) );
it->second.setLeaf( _orig.getRegionNode( id ) );
_containerLock.release();
return NULL;
}
_containerLock.release();
return it->second.getData();
}
template <class T>
void ContainerSparse< T >::setRegionData( reg_t id, Version *data ) {
if ( _container[ id ].getLeaf() == NULL ) {
std::cerr << "WARNING: null leaf, region "<< id << " region node is " << (void*) _orig.getRegionNode( id ) << " addr orig " << (void*)&_orig <<std::endl;
_container[ id ].setLeaf( _orig.getRegionNode( id ) );
}
_container[ id ].setData( data );
}
template <class T>
unsigned int ContainerSparse< T >::getRegionNodeCount() const {
return _container.size();
}
template <class T>
reg_t ContainerSparse< T >::addRegion( <API key> const region[] ) {
reg_t id = _orig.addRegion( region );
if ( sys.getNetwork()->getNodeNum() > 0) { std::cerr << " ADDED REG " << id << std::endl; }
return id;
}
template <class T>
unsigned int ContainerSparse< T >::getNumDimensions() const {
return _orig.getNumDimensions();
}
template <class T>
reg_t ContainerSparse< T >::checkIfRegionExists( <API key> const region[] ) {
return _orig.checkIfRegionExists( region );
}
template <class T>
typename std::map< reg_t, T >::const_iterator ContainerSparse< T >::begin() {
return _container.begin();
}
template <class T>
typename std::map< reg_t, T >::const_iterator ContainerSparse< T >::end() {
return _container.end();
}
template <class T>
ContainerDense< T > &ContainerSparse< T >::getOrigContainer() {
return _orig;
}
template <class T>
RegionNode *ContainerSparse< T >::getGlobalRegionNode( reg_t id ) const {
return _orig.getRegionNode( id );
}
template <class T>
Version *ContainerSparse< T >::getGlobalRegionData( reg_t id ) {
return _orig.getRegionData( id );
}
template <class T>
RegionDictionary< ContainerDense > *ContainerSparse< T >::<API key>() {
return &_orig;
}
template <class T>
std::vector< std::size_t > const &ContainerSparse< T >::getDimensionSizes() const {
return _orig.getDimensionSizes();
}
template <class T>
reg_t ContainerSparse< T >::getMaxRegionId() const {
return _orig.getMaxRegionId();
}
template < template <class> class Sparsity>
RegionDictionary< Sparsity >::RegionDictionary( CopyData const &cd ) :
Sparsity< RegionVectorEntry >( cd ), Version( 1 ),
_intersects( cd.getNumDimensions(), MemoryMap< std::set< reg_t > >() ),
_keyBaseAddress( cd.getHostBaseAddress() == nullptr ? cd.getBaseAddress() : cd.getHostBaseAddress() ),
_realBaseAddress( cd.getBaseAddress() ), _lock() {
//std::cerr << "CREATING MASTER DICT: tree: " << (void *) &_tree << std::endl;
<API key> dims[ cd.getNumDimensions() ];
for ( unsigned int idx = 0; idx < cd.getNumDimensions(); idx++ ) {
dims[ idx ].size = cd.getDimensions()[ idx ].size;
dims[ idx ].accessed_length = cd.getDimensions()[ idx ].size;
dims[ idx ].lower_bound = 0;
}
reg_t id = this->addRegion( dims );
//std::list< std::pair< reg_t, reg_t > > missingParts;
//unsigned int version;
ensure( id == 1, "Whole region did not get id 1");
(void) id;
}
template < template <class> class Sparsity>
RegionDictionary< Sparsity >::RegionDictionary( <API key> &dict ) : Sparsity< RegionVectorEntry >( dict ), _intersects( dict.getNumDimensions(), MemoryMap< std::set< reg_t > >() ),
_keyBaseAddress( dict.getKeyBaseAddress() ), _realBaseAddress( dict.getRealBaseAddress() ), _lock(), _fixedRegions() {
//std::cerr << "CREATING CACHE DICT: tree: " << (void *) &_tree << " orig tree: " << (void *) &dict._tree << std::endl;
//std::cerr << "Created dir " << (void *) this << " w/dims " << dict.getNumDimensions() << std::endl;
}
template < template <class> class Sparsity>
RegionDictionary< Sparsity >::~RegionDictionary() {
}
template < template <class> class Sparsity>
void RegionDictionary< Sparsity >::lockObject() {
//_lock.acquire();
while ( !_lock.tryAcquire() ) {
myThread->processTransfers();
}
}
template < template <class> class Sparsity>
bool RegionDictionary< Sparsity >::tryLockObject() {
return _lock.tryAcquire();
}
template < template <class> class Sparsity>
void RegionDictionary< Sparsity >::unlockObject() {
_lock.release();
}
template < template <class> class Sparsity>
void RegionDictionary< Sparsity >::_computeIntersect( reg_t regionIdA, reg_t regionIdB, <API key> *outReg ) {
RegionNode const *regA = this->getRegionNode( regionIdA );
RegionNode const *regB = this->getRegionNode( regionIdB );
if ( regionIdA == regionIdB ) {
message( __FUNCTION__, " Dummy check! regA == regB ( ", regionIdA, " )" );
for ( int dimensionCount = this->getNumDimensions() - 1; dimensionCount >= 0; dimensionCount -= 1 ) {
outReg[ dimensionCount ].accessed_length = 0;
outReg[ dimensionCount ].lower_bound = 0;
}
return;
}
//reg_t maxReg = std::max( regionIdA, regionIdB );
//if ( regionIdA > regionIdB ) {
//} else {
//std::cerr << "Computing intersect between reg " << regionIdA << " and "<< regionIdB << "... "<<std::endl;
//printRegion(regionIdA ); std::cerr << std::endl;
//printRegion(regionIdB ); std::cerr << std::endl;
for ( int dimensionCount = this->getNumDimensions() - 1; dimensionCount >= 0; dimensionCount -= 1 ) {
std::size_t accessedLengthA = regA->getValue();
std::size_t accessedLengthB = regB->getValue();
regA = regA->getParent();
regB = regB->getParent();
std::size_t lowerBoundA = regA->getValue();
std::size_t lowerBoundB = regB->getValue();
std::size_t upperBoundA = lowerBoundA + accessedLengthA;
std::size_t upperBoundB = lowerBoundB + accessedLengthB;
std::size_t lowerBoundC = 0;
std::size_t accessedLengthC = 0;
if ( lowerBoundA > lowerBoundB ) {
lowerBoundC = lowerBoundA;
if ( upperBoundA > upperBoundB ) {
accessedLengthC = upperBoundB - lowerBoundA;
} else if ( upperBoundA <= upperBoundB ) {
accessedLengthC = accessedLengthA;
}
} else if ( lowerBoundA < lowerBoundB ) {
lowerBoundC = lowerBoundB;
if ( upperBoundA >= upperBoundB ) {
accessedLengthC = accessedLengthB;
} else if ( upperBoundA < upperBoundB ) {
accessedLengthC = upperBoundA - lowerBoundB;
}
} else {
lowerBoundC = lowerBoundA;
if ( upperBoundA > upperBoundB ) {
accessedLengthC = accessedLengthB;
} else if ( upperBoundA <= upperBoundB ) {
accessedLengthC = accessedLengthA;
}
}
outReg[ dimensionCount ].accessed_length = accessedLengthC;
outReg[ dimensionCount ].lower_bound = lowerBoundC;
regA = regA->getParent();
regB = regB->getParent();
}
}
template < template <class> class Sparsity>
reg_t RegionDictionary< Sparsity >::<API key>( reg_t regionIdA, reg_t regionIdB ) {
{
reg_t maxRegionId = std::max( regionIdA, regionIdB );
reg_t minRegionId = std::min( regionIdA, regionIdB );
RegionNode const *maxReg = this->getRegionNode( maxRegionId );
reg_t data = maxReg->getMemoIntersect( minRegionId );
if ( data == (unsigned int)-1 ) {
//std::cerr << "hit compute!"<<std::endl;
return 0;
} else if ( data != (unsigned int)-2 && data != 0 ) {
return data;
}
}
if ( !this->checkIntersect( regionIdA, regionIdB ) ) {
std::cerr << " Regions do not intersect: " << regionIdA << ", " << regionIdB << std::endl;
}
ensure( this->checkIntersect( regionIdA, regionIdB ) ," Regions do not intersect." );
<API key> resultingRegion[ this->getNumDimensions() ];
_computeIntersect( regionIdA, regionIdB, resultingRegion );
reg_t regId = this->checkIfRegionExists( resultingRegion );
return regId;
}
template < template <class> class Sparsity>
reg_t RegionDictionary<Sparsity>::computeIntersect( reg_t regionIdA, reg_t regionIdB ) {
{
reg_t maxRegionId = std::max( regionIdA, regionIdB );
reg_t minRegionId = std::min( regionIdA, regionIdB );
RegionNode const *maxReg = this->getRegionNode( maxRegionId );
reg_t data = maxReg->getMemoIntersect( minRegionId );
if ( data == (unsigned int)-1 ) {
//std::cerr << "hit compute!"<<std::endl;
return 0;
} else if ( data != (unsigned int)-2 && data != 0 ) {
return data;
}
}
if ( !this->checkIntersect( regionIdA, regionIdB ) ) {
std::cerr << " Regions do not intersect: " << regionIdA << ", " << regionIdB << std::endl;
}
ensure( this->checkIntersect( regionIdA, regionIdB ) ," Regions do not intersect." );
<API key> resultingRegion[ this->getNumDimensions() ];
_computeIntersect( regionIdA, regionIdB, resultingRegion );
reg_t regId = this->addRegion( resultingRegion );
//std::cerr << (void *) this << " Computed intersect bewteen " << regionIdA << " and " << regionIdB << " resulting region is "<< regId << std::endl;
{
reg_t maxRegionId = std::max( regionIdA, regionIdB );
reg_t minRegionId = std::min( regionIdA, regionIdB );
RegionNode *maxReg = this->getRegionNode( maxRegionId );
maxReg->setMemoIntersect( minRegionId, regId );
}
return regId;
}
template < template <class> class Sparsity>
void RegionDictionary< Sparsity >::<API key>( reg_t id, std::list< std::pair< reg_t, reg_t > > &finalParts, unsigned int &version ) {
class LocalFunction {
RegionDictionary &_currentDict;
public:
LocalFunction( RegionDictionary &dict ) : _currentDict( dict ) { }
void _recursive ( reg_t this_id, unsigned int total_dims, unsigned int dim, MemoryMap< std::set< reg_t > >::MemChunkList results[], <API key> current_regions[], std::set<reg_t> *current_sets[], std::map<reg_t, std::set< reg_t > > &resulting_regions, bool compute_region ) {
if ( dim == 0 ) {
for ( MemoryMap< std::set< reg_t > >::MemChunkList::const_iterator it = results[ dim ].begin(); it != results[ dim ].end(); it++ ) {
if ( *(it->second) == NULL ) {
*(it->second) = NEW std::set< reg_t >();
}
current_regions[dim].lower_bound = it->first->getAddress().value();
current_regions[dim].accessed_length = it->first->getLength();
current_sets[dim] = *it->second;
bool this_compute_region = ( compute_region && current_sets[dim] != NULL && !current_sets[dim]->empty() );
reg_t parent_reg = this_id;
if ( this_compute_region ) {
std::set<reg_t> metadata_regs;
for ( std::set<reg_t>::const_iterator sit = current_sets[0]->begin(); sit != current_sets[0]->end(); sit++ ) {
unsigned int count = 1;
for ( unsigned int dim_idx = 1; dim_idx < total_dims; dim_idx += 1 ) {
count += current_sets[dim_idx]->count(*sit);
}
if ( count == total_dims ) {
metadata_regs.insert(*sit);
}
}
if ( this_id == 1 ) {
metadata_regs.insert( 1 );
}
if ( metadata_regs.size() >= 1 ) {
// if ( metadata_regs.size() > 1 ) {
// *myThread->_file << "Multiple regions can be the parent region: ";
// for ( std::set<reg_t>::const_iterator sit = metadata_regs.begin(); sit != metadata_regs.end(); sit++ ) {
// *myThread->_file << *sit << " ";
// *myThread->_file << std::endl;
reg_t max_version_reg = 0;
unsigned int current_version = 0;
//bool has_own_region = false;
unsigned int own_version = 0;
for ( std::set<reg_t>::const_iterator sit = metadata_regs.begin(); sit != metadata_regs.end(); sit++ ) {
Version *entry = _currentDict.getRegionData( *sit );
unsigned int this_version = entry != NULL ? entry->getVersion() : 0;
if (*sit == this_id) {
//has_own_region = true;
own_version = this_version;
}
if ( this_version > current_version ) {
current_version = this_version;
max_version_reg = *sit;
}
}
// if ( metadata_regs.size() > 1 && max_version_reg != 0 ) {
// for ( std::set<reg_t>::const_iterator sit = metadata_regs.begin(); sit != metadata_regs.end(); sit++ ) {
// *myThread->_file << *sit << " ";
// *myThread->_file << std::endl;
if ( own_version == current_version && max_version_reg != 0 ) {
max_version_reg = this_id;
}
parent_reg = ( max_version_reg != 0 ) ? max_version_reg : parent_reg;
}
}
reg_t part = _currentDict.addRegion( current_regions );
resulting_regions[parent_reg].insert( part );
}
} else {
for ( MemoryMap< std::set< reg_t > >::MemChunkList::const_iterator it = results[ dim ].begin(); it != results[ dim ].end(); it++ ) {
if ( *(it->second) == NULL ) {
*(it->second) = NEW std::set< reg_t >();
}
current_regions[dim].lower_bound = it->first->getAddress().value();
current_regions[dim].accessed_length = it->first->getLength();
current_sets[dim] = *it->second;
bool this_compute_region = ( compute_region && current_sets[dim] != NULL && !current_sets[dim]->empty() );
_recursive( this_id, total_dims, dim - 1, results, current_regions, current_sets, resulting_regions, this_compute_region );
}
}
}
void <API key>( reg_t this_id, std::map< reg_t, std::set< reg_t > > &resulting_regions ) {
RegionNode const *regNode = _currentDict.getRegionNode( this_id );
MemoryMap< std::set< reg_t > >::MemChunkList results[ _currentDict.getNumDimensions() ];
for ( int idx = _currentDict.getNumDimensions() - 1; idx >= 0; idx -= 1 ) {
std::size_t accessedLength = regNode->getValue();
regNode = regNode->getParent();
std::size_t lowerBound = regNode->getValue();
regNode = regNode->getParent();
_currentDict._intersects[ idx ].getOrAddChunk( lowerBound, accessedLength, results[ idx ] );
}
std::set<reg_t> *current_sets[ _currentDict.getNumDimensions() ];
<API key> current_regions[ _currentDict.getNumDimensions() ];
if ( _currentDict.getNumDimensions() == 0 ) {
std::cerr << "Invalid DICT: " << &_currentDict << std::endl;
}
ensure(_currentDict.getNumDimensions() > 0, "Invalid, object, 0 dimensions");
_recursive( this_id, _currentDict.getNumDimensions(), _currentDict.getNumDimensions() - 1, results, current_regions, current_sets, resulting_regions, true );
if ( this_id != 1 ) {
for ( int idx = _currentDict.getNumDimensions() - 1; idx >= 0; idx -= 1 ) {
for ( MemoryMap< std::set< reg_t > >::MemChunkList::const_iterator it = results[ idx ].begin(); it != results[ idx ].end(); it++ ) {
(*it->second)->insert( this_id );
}
}
}
}
};
LocalFunction local( *this );
//double tiniCI2 = OS::getMonotonicTime();
std::map< reg_t, std::set< reg_t > > resulting_regions;
local.<API key>( id, resulting_regions );
//double tfiniCI2 = OS::getMonotonicTime();
#endif /* REGIONDICT_H */ |
<?php
$<API key> = array
(
'<API key>' => 'Empty categories and products cache',
'BUTTON_DATA_CACHE' => 'Empty modules cache',
'<API key>' => 'Empty filter cache',
'<API key>' => 'Empty email templates cache',
'BUTTON_OUTPUT_CACHE' => 'Empty page output cache',
'<API key>' => 'Empty properties cache',
'<API key>' => 'Empty submenus cache',
'BUTTON_TEXT_CACHE' => 'Empty text cache',
'<API key>' => 'Categories and products cache emptied.',
'<API key>' => 'Modules cache emptied.',
'<API key>' => 'Filter cache emptied.',
'<API key>' => 'E mail templates cache emptied.',
'<API key>' => 'Page output cache emptied.',
'<API key>' => 'Properties cache emptied.',
'<API key>' => 'Submenus cache emptied',
'<API key>' => 'Text cache emptied.',
'HEADING_TITLE' => 'Clear cache',
'<API key>' => 'Create this cache, if you imported products or categories via an external system or if you changed data via an ERP system or a direct database access.',
'TEXT_DATA_CACHE' => 'Empty the cache, if you made any changes to the category structure or if new modules for the shop have been installed and activated.',
'TEXT_ERROR_MESSAGE' => 'The cache could not be emptied.',
'TEXT_FEATURES_CACHE' => 'In exceptional cases it may be necessary to repair the filter mappings, if products are not found using a filter.',
'<API key>' => 'Empty the cache, if you have made any email template file changes.',
'TEXT_MESSAGE' => 'The cache has been emptied and will be regenerated the next page request in the shop.',
'TEXT_OUTPUT_CACHE' => 'Empty the cache when you make changes to category or product data or settings you have made to effect a change in the output of shop sites, such as text or price changes, new modules, changes in status of categories/products.',
'<API key>' => 'Create this cache, if you have made ??changes to properties that were already assigned to products.',
'TEXT_SUBMENUS_CACHE' => 'If you have emptied the page output cache and work with a large number of categories, it can accelerate the next page load times if you recreate the submenus cache now.',
'TEXT_TEXT_CACHE' => 'Empty the cache, if you have made any text file changes.'
); |
// This program is free software: you can redistribute it and/or modify
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#ifndef <API key>
#define <API key>
#include <omnetpp.h>
/**
* TODO - Generated class
*/
class Ieee1QLayer : public cSimpleModule
{
protected:
virtual void initialize();
virtual void handleMessage(cMessage *msg);
};
#endif |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Drupal Camp</title>
<link rel="stylesheet" href="../css/main.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
</head>
<body> |
package net.sf.freecol.client.gui.panel;
import java.awt.Dimension;
import java.awt.event.ItemEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map.Entry;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.<API key>;
import net.miginfocom.swing.MigLayout;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.client.gui.ChoiceItem;
import net.sf.freecol.client.gui.ImageLibrary;
import net.sf.freecol.client.gui.plaf.<API key>;
import net.sf.freecol.common.i18n.Messages;
import net.sf.freecol.common.model.Ability;
import net.sf.freecol.common.model.Colony;
import net.sf.freecol.common.model.Europe;
import net.sf.freecol.common.model.FreeColObject;
import net.sf.freecol.common.model.Game;
import net.sf.freecol.common.model.Goods;
import net.sf.freecol.common.model.GoodsType;
import net.sf.freecol.common.model.IndianSettlement;
import net.sf.freecol.common.model.Location;
import net.sf.freecol.common.model.Map;
import net.sf.freecol.common.model.Market;
import net.sf.freecol.common.model.Nation;
import net.sf.freecol.common.model.PathNode;
import net.sf.freecol.common.model.Player;
import net.sf.freecol.common.model.Settlement;
import net.sf.freecol.common.model.Stance;
import net.sf.freecol.common.model.StringTemplate;
import net.sf.freecol.common.model.Unit;
import net.sf.freecol.common.model.UnitType;
import net.sf.freecol.common.model.UnitTypeChange.ChangeType;
import net.sf.freecol.common.model.pathfinding.GoalDeciders.<API key>;
import net.sf.freecol.common.resources.ResourceManager;
import static net.sf.freecol.common.util.CollectionUtils.*;
import net.sf.freecol.common.util.LogBuilder;
/**
* Select a location as the destination for a given unit.
*/
public final class <API key> extends FreeColDialog<Location>
implements <API key> {
@SuppressWarnings("unused")
private static final Logger logger = Logger.getLogger(<API key>.class.getName());
/**
* A container for a destination location, with associated
* distance and extra characteristics.
*/
private class Destination {
public final Unit unit;
public final Location location;
public final int turns;
public final String extras;
public final String text;
public final int score;
public ImageIcon icon;
/**
* Create a destination.
*
* @param location The <code>Location</code> to go to.
* @param turns The number of turns it takes to get to the location.
* @param unit The <code>Unit</code> that is moving.
* @param goodsTypes A list of goods types the unit is carrying.
*/
public Destination(Location location, int turns, Unit unit,
List<GoodsType> goodsTypes) {
this.unit = unit;
this.location = location;
this.turns = turns;
this.extras = getExtras(location, unit, goodsTypes);
this.score = calculateScore();
this.icon = null;
final Player player = getMyPlayer();
final ImageLibrary lib = getImageLibrary();
String name = "";
if (location instanceof Europe) {
Europe europe = (Europe)location;
Nation nation = europe.getOwner().getNation();
name = Messages.getName(europe);
this.icon = new ImageIcon(ImageLibrary.getMiscIconImage(nation,
new Dimension(-1, CELL_HEIGHT)));
} else if (location instanceof Map) {
name = Messages.message(location.getLocationLabelFor(player));
this.icon = new ImageIcon(lib.getMiscImage(
ImageLibrary.LOST_CITY_RUMOUR));
} else if (location instanceof Settlement) {
Settlement settlement = (Settlement) location;
name = Messages.message(settlement.getLocationLabelFor(player));
this.icon = new ImageIcon(ImageLibrary.getSettlementImage(
settlement,
new Dimension(64, -1)));
}
StringTemplate template = StringTemplate
.template("<API key>.destinationTurns")
.addName("%location%", name)
.addAmount("%turns%", this.turns)
.addName("%extras%", this.extras);
this.text = Messages.message(template);
}
/**
* Collected extra annotations of interest to a unit proposing to
* visit a location.
*
* @param loc The <code>Location</code> to visit.
* @param unit The <code>Unit</code> proposing to visit.
* @param goodsTypes A list of goods types the unit is carrying.
* @return A string containing interesting annotations about the visit
* or an empty string if nothing is of interest.
*/
private String getExtras(Location loc, Unit unit,
List<GoodsType> goodsTypes) {
final String sep = ", ";
final Player owner = unit.getOwner();
LogBuilder lb = new LogBuilder(32);
boolean dropSep = false;
// Always show our missions, it may influence our choice of
// units to bring, and/or goods.
if (loc instanceof IndianSettlement
&& ((IndianSettlement)loc).hasMissionary(owner)) {
lb.add(ResourceManager.getString("cross"));
}
if (loc instanceof Europe && !goodsTypes.isEmpty()) {
Market market = owner.getMarket();
for (GoodsType goodsType : goodsTypes) {
lb.add(Messages.getName(goodsType), " ",
market.getSalePrice(goodsType, 1), sep);
dropSep = true;
}
} else if (loc instanceof Settlement
&& owner.owns((Settlement)loc)) {
; // Do nothing
} else if (loc instanceof Settlement
&& ((Settlement)loc).getOwner().atWarWith(owner)) {
lb.add("[", Messages.getName(Stance.WAR), "]");
} else if (loc instanceof Settlement) {
if (loc instanceof IndianSettlement) {
// Show skill if relevant
IndianSettlement is = (IndianSettlement)loc;
UnitType sk = is.getLearnableSkill();
if (sk != null) {
Unit up = (unit.getType().canBeUpgraded(sk,
ChangeType.NATIVES)) ? unit : null;
if (unit.isCarrier()) {
up = find(unit.getUnitList(),
u -> u.getType().canBeUpgraded(sk, ChangeType.NATIVES));
}
if (up != null) {
lb.add("[", Messages.getName(sk), "]");
}
}
}
if (!goodsTypes.isEmpty()) {
// Show goods prices if relevant
for (GoodsType g : goodsTypes) {
String sale = owner.getLastSaleString(loc, g);
String more = null;
if (loc instanceof IndianSettlement) {
GoodsType[] wanted
= ((IndianSettlement)loc).getWantedGoods();
if (wanted.length > 0 && g == wanted[0]) {
more = "***";
} else if (wanted.length > 1 && g == wanted[1]) {
more = "**";
} else if (wanted.length > 2 && g == wanted[2]) {
more = "*";
}
}
if (sale != null && more != null) {
lb.add(Messages.getName(g), " ", sale, more, sep);
dropSep = true;
}
}
}
} // else do nothing
if (dropSep) lb.shrink(sep);
return lb.toString();
}
private int calculateScore() {
return (location instanceof Europe || location instanceof Map)
? 10
: (location instanceof Colony)
? ((unit.getOwner().owns((Colony)location)) ? 20 : 30)
: (location instanceof IndianSettlement)
? 40
: 100;
}
}
private class <API key> implements Comparator<Destination> {
protected final Player owner;
public <API key>(Player player) {
this.owner = player;
}
@Override
public int compare(Destination choice1, Destination choice2) {
int score1 = choice1.score;
int score2 = choice2.score;
return (score1 != score2) ? score1 - score2
: compareNames(choice1.location, choice2.location);
}
/**
* Compare the names of two locations.
*
* @param loc1 The first <code>Location</code>.
* @param loc2 The second <code>Location</code>.
*/
protected int compareNames(Location loc1, Location loc2) {
if (!(loc1 instanceof Settlement)) return -1;
if (!(loc2 instanceof Settlement)) return 1;
Settlement s1 = (Settlement)loc1;
String name1 = Messages.message(s1.getLocationLabelFor(owner));
Settlement s2 = (Settlement)loc2;
String name2 = Messages.message(s2.getLocationLabelFor(owner));
return name1.compareTo(name2);
}
}
private class NameComparator extends <API key> {
public NameComparator(Player player) {
super(player);
}
/**
* {@inheritDoc}
*/
@Override
public int compare(Destination choice1, Destination choice2) {
return compareNames(choice1.location, choice2.location);
}
}
private class DistanceComparator extends <API key> {
public DistanceComparator(Player player) {
super(player);
}
/**
* {@inheritDoc}
*/
@Override
public int compare(Destination choice1, Destination choice2) {
int result = choice1.turns - choice2.turns;
return (result != 0) ? result
: compareNames(choice1.location, choice2.location);
}
}
private static class LocationRenderer
extends <API key><Destination> {
/**
* {@inheritDoc}
*/
@Override
public void setLabelValues(JLabel label, Destination value) {
if (value.icon != null) label.setIcon(value.icon);
label.setText(value.text);
}
}
/** The size of each destination cell. */
private static final int CELL_HEIGHT = 48;
/** Show only the player colonies. FIXME: make a client option. */
private static boolean showOnlyMyColonies = true;
/** How to order the destinations. */
private static Comparator<Destination> <API key> = null;
/** The available destinations. */
private final List<Destination> destinations = new ArrayList<>();
/** The list of destinations. */
private final JList<Destination> destinationList;
/** Restrict to only the player colonies? */
private JCheckBox onlyMyColoniesBox;
/** Choice of the comparator. */
private JComboBox<String> comparatorBox;
/**
* The constructor to use.
*
* @param freeColClient The <code>FreeColClient</code> for the game.
* @param frame The owner frame.
*/
public <API key>(FreeColClient freeColClient, JFrame frame,
Unit unit) {
super(freeColClient, frame);
// Collect the goods the unit is carrying and set this.destinations.
final List<GoodsType> goodsTypes = new ArrayList<>();
for (Goods goods : unit.getCompactGoodsList()) {
goodsTypes.add(goods.getType());
}
loadDestinations(unit, goodsTypes);
DefaultListModel<Destination> model
= new DefaultListModel<>();
this.destinationList = new JList<>(model);
this.destinationList.setCellRenderer(new LocationRenderer());
this.destinationList.setFixedCellHeight(CELL_HEIGHT);
this.destinationList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
this.destinationList.<API key>(this);
this.destinationList.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() != 2) return;
Destination d = destinationList.getSelectedValue();
if (d != null) setValue(options.get(0));
}
});
<API key>();
JScrollPane listScroller = new JScrollPane(destinationList);
listScroller.setPreferredSize(new Dimension(300, 300));
String omcb = Messages.message("<API key>.onlyMyColonies");
this.onlyMyColoniesBox = new JCheckBox(omcb, showOnlyMyColonies);
this.onlyMyColoniesBox.addChangeListener((ChangeEvent event) -> {
showOnlyMyColonies = onlyMyColoniesBox.isSelected();
<API key>();
});
this.comparatorBox = new JComboBox<>(new String[] {
Messages.message("<API key>.sortByOwner"),
Messages.message("<API key>.sortByName"),
Messages.message("<API key>.sortByDistance")
});
this.comparatorBox.addItemListener((ItemEvent event) -> {
<API key>();
Collections.sort(<API key>.this.destinations,
<API key>.this.<API key>);
<API key>();
});
this.comparatorBox.setSelectedIndex(
(this.<API key> instanceof NameComparator) ? 1
: (this.<API key> instanceof DistanceComparator) ? 2
: 0);
MigPanel panel = new MigPanel(new MigLayout("wrap 1, fill",
"[align center]", ""));
panel.add(Utility.localizedHeader("<API key>.text", true));
panel.add(listScroller, "newline 30, growx, growy");
panel.add(this.onlyMyColoniesBox, "left");
panel.add(this.comparatorBox, "left");
panel.setSize(panel.getPreferredSize());
List<ChoiceItem<Location>> c = choices();
c.add(new ChoiceItem<>(Messages.message("ok"),
(Location)null).okOption());
c.add(new ChoiceItem<>(Messages.message("<API key>.cancel"),
(Location)null).cancelOption().defaultOption());
initializeDialog(frame, DialogType.QUESTION, true, panel, new ImageIcon(
getImageLibrary().getSmallUnitImage(unit)), c);
}
/**
* Load destinations for a given unit and carried goods types.
*
* @param unit The <code>Unit</code> to select destinations for.
* @param goodsTypes A list of <code>GoodsType</code>s carried.
*/
private void loadDestinations(Unit unit, List<GoodsType> goodsTypes) {
final Player player = unit.getOwner();
final Settlement inSettlement = unit.getSettlement();
final boolean canTrade
= player.hasAbility(Ability.<API key>);
final Europe europe = player.getEurope();
final Game game = getGame();
final Map map = game.getMap();
int turns;
if (unit.isInEurope() && !unit.getType().canMoveToHighSeas()) return;
if (unit.isInEurope()) {
this.destinations.add(new Destination(map, unit.getSailTurns(),
unit, goodsTypes));
} else if (europe != null
&& player.canMoveToEurope()
&& unit.getType().canMoveToHighSeas()
&& (turns = unit.getTurnsToReach(europe)) < Unit.MANY_TURNS) {
this.destinations.add(new Destination(europe, turns,
unit, goodsTypes));
}
for (Settlement s : player.getSettlements()) {
if (s == inSettlement) continue;
if (unit.isNaval()) {
if (!s.isConnectedPort()) continue;
} else {
if (!Map.isSameContiguity(unit.getLocation(),
s.getTile())) continue;
}
if ((turns = unit.getTurnsToReach(s)) < Unit.MANY_TURNS) {
this.destinations.add(new Destination(s, turns,
unit, goodsTypes));
}
}
List<Location> locs = new ArrayList<>();
for (Player p : game.getLivePlayers(player)) {
if (!p.hasContacted(player)
|| (p.isEuropean() && !canTrade)) continue;
for (Settlement s : p.getSettlements()) {
if (unit.isNaval()) {
if (!s.isConnectedPort()) continue;
} else {
if (!Map.isSameContiguity(unit.getLocation(),
s.getTile())) continue;
}
if (s instanceof IndianSettlement
&& !((IndianSettlement)s).hasContacted(player)) continue;
locs.add(s.getTile());
}
}
<API key> md = new <API key>(locs);
unit.search(unit.getLocation(), md.getGoalDecider(), null,
FreeColObject.INFINITY, null);
PathNode path;
for (Entry<Location, PathNode> e : md.getResults().entrySet()) {
Settlement s = e.getKey().getTile().getSettlement();
PathNode p = e.getValue();
turns = p.getTotalTurns();
if (unit.isInEurope()) turns += unit.getSailTurns();
if (p.getMovesLeft() < unit.getInitialMovesLeft()) turns++;
this.destinations.add(new Destination(s, turns, unit, goodsTypes));
}
if (this.<API key> == null) {
this.<API key> = new <API key>(player);
}
Collections.sort(this.destinations, this.<API key>);
}
/**
* Reset the destinations in the model.
*/
private void <API key>() {
final Player player = getMyPlayer();
Destination selected = this.destinationList.getSelectedValue();
DefaultListModel<Destination> model
= new DefaultListModel<>();
for (Destination d : this.destinations) {
if (showOnlyMyColonies) {
if (d.location instanceof Europe
|| d.location instanceof Map
|| (d.location instanceof Colony
&& player.owns((Colony)d.location))) {
model.addElement(d);
}
} else {
model.addElement(d);
}
}
this.destinationList.setModel(model);
this.destinationList.setSelectedValue(selected, true);
if (this.destinationList.getSelectedIndex() < 0) {
this.destinationList.setSelectedIndex(0);
}
recenter(this.destinationList.getSelectedValue());
}
/**
* Show a destination on the map.
*
* @param destination The <code>Destination</code> to display.
*/
private void recenter(Destination destination) {
if (destination != null
&& destination.location.getTile() != null) {
getGUI().setFocus(destination.location.getTile());
}
}
/**
* Set the selected destination comparator.
*/
private void <API key>() {
final Player player = getMyPlayer();
switch (this.comparatorBox.getSelectedIndex()) {
case 1:
this.<API key> = new NameComparator(player);
break;
case 2:
this.<API key> = new DistanceComparator(player);
break;
case 0: default:
this.<API key> = new <API key>(player);
break;
}
}
// Interface <API key>
/**
* {@inheritDoc}
*/
@Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting()) return;
recenter(this.destinationList.getSelectedValue());
}
// Implement FreeColDialog
/**
* {@inheritDoc}
*/
@Override
public Location getResponse() {
Object value = getValue();
if (options.get(0).equals(value)) {
Destination d = this.destinationList.getSelectedValue();
if (d != null) return d.location;
}
return null;
}
// Override Component
/**
* {@inheritDoc}
*/
@Override
public void removeNotify() {
super.removeNotify();
removeAll();
this.destinations.clear();
this.onlyMyColoniesBox = null;
this.comparatorBox = null;
}
/**
* {@inheritDoc}
*/
@Override
public void requestFocus() {
this.destinationList.requestFocus();
}
} |
/* See Documentation/block/row-iosched.txt */
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/blkdev.h>
#include <linux/elevator.h>
#include <linux/bio.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/compiler.h>
#include <linux/blktrace_api.h>
#include <linux/hrtimer.h>
/*
* enum row_queue_prio - Priorities of the ROW queues
*
* This enum defines the priorities (and the number of queues)
* the requests will be distributed to. The higher priority -
* the bigger is the "bus time" (or the dispatch quantum) given
* to that queue.
* ROWQ_PRIO_HIGH_READ - is the higher priority queue.
*
*/
enum row_queue_prio {
ROWQ_PRIO_HIGH_READ = 0,
<API key>,
ROWQ_PRIO_REG_READ,
<API key>,
ROWQ_PRIO_REG_WRITE,
ROWQ_PRIO_LOW_READ,
<API key>,
ROWQ_MAX_PRIO,
};
/*
* The following indexes define the distribution of ROW queues according to
* priorities. Each index defines the first queue in that priority group.
*/
#define ROWQ_HIGH_PRIO_IDX ROWQ_PRIO_HIGH_READ
#define ROWQ_REG_PRIO_IDX ROWQ_PRIO_REG_READ
#define ROWQ_LOW_PRIO_IDX ROWQ_PRIO_LOW_READ
/**
* struct row_queue_params - ROW queue parameters
* @idling_enabled: Flag indicating whether idling is enable on
* the queue
* @quantum: Number of requests to be dispatched from this queue
* in a dispatch cycle
* @is_urgent: Flags indicating whether the queue can notify on
* urgent requests
*
*/
struct row_queue_params {
bool idling_enabled;
int quantum;
bool is_urgent;
};
/*
* This array holds the default values of the different configurables
* for each ROW queue. Each row of the array holds the following values:
* {idling_enabled, quantum, is_urgent}
* Each row corresponds to a queue with the same index (according to
* enum row_queue_prio)
* Note: The quantums are valid inside their priority type. For example:
* For every 10 high priority read requests, 1 high priority sync
* write will be dispatched.
* For every 100 regular read requests 1 regular write request will
* be dispatched.
*/
static const struct row_queue_params row_queues_def[] = {
/* idling_enabled, quantum, is_urgent */
{true, 100, true}, /* ROWQ_PRIO_HIGH_READ */
{false, 6, false}, /* <API key> */
{true, 70, true}, /* ROWQ_PRIO_REG_READ */
{false, 5, false}, /* <API key> */
{false, 5, false}, /* ROWQ_PRIO_REG_WRITE */
{false, 3, false}, /* ROWQ_PRIO_LOW_READ */
{false, 3, false} /* <API key> */
};
/* Default values for idling on read queues (in msec) */
#define ROW_IDLE_TIME_MSEC 12
#define ROW_READ_FREQ_MSEC 20
/**
* struct rowq_idling_data - parameters for idling on the queue
* @last_insert_time: time the last request was inserted
* to the queue
* @begin_idling: flag indicating wether we should idle
*
*/
struct rowq_idling_data {
ktime_t last_insert_time;
bool begin_idling;
};
/**
* struct row_queue - requests grouping structure
* @rdata: parent row_data structure
* @fifo: fifo of requests
* @prio: queue priority (enum row_queue_prio)
* @nr_dispatched: number of requests already dispatched in
* the current dispatch cycle
* @nr_req: number of requests in queue
* @dispatch quantum: number of requests this queue may
* dispatch in a dispatch cycle
* @idle_data: data for idling on queues
*
*/
struct row_queue {
struct row_data *rdata;
struct list_head fifo;
enum row_queue_prio prio;
unsigned int nr_dispatched;
unsigned int nr_req;
int disp_quantum;
/* used only for READ queues */
struct rowq_idling_data idle_data;
};
/**
* struct idling_data - data for idling on empty rqueue
* @idle_time_ms: idling duration (msec)
* @freq_ms: min time between two requests that
* triger idling (msec)
* @hr_timer: idling timer
* @idle_work: the work to be scheduled when idling timer expires
* @idling_queue_idx: index of the queues we're idling on
*
*/
struct idling_data {
s64 idle_time_ms;
s64 freq_ms;
struct hrtimer hr_timer;
struct work_struct idle_work;
enum row_queue_prio idling_queue_idx;
};
/**
* struct starvation_data - data for starvation management
* @starvation_limit: number of times this priority class
* can tolerate being starved
* @starvation_counter: number of requests from higher
* priority classes that were dispatched while this
* priority request were pending
*
*/
struct starvation_data {
int starvation_limit;
int starvation_counter;
};
/**
* struct row_queue - Per block device rqueue structure
* @dispatch_queue: dispatch rqueue
* @row_queues: array of priority request queues
* @rd_idle_data: data for idling after READ request
* @nr_reqs: nr_reqs[0] holds the number of all READ requests in
* scheduler, nr_reqs[1] holds the number of all WRITE
* requests in scheduler
* @urgent_in_flight: flag indicating that there is an urgent
* request that was dispatched to driver and is yet to
* complete.
* @pending_urgent_rq: pointer to the pending urgent request
* @<API key>: I/O priority class that was last dispatched from
* @reg_prio_starvation: starvation data for REGULAR priority queues
* @low_prio_starvation: starvation data for LOW priority queues
* @cycle_flags: used for marking unserved queueus
*
*/
struct row_data {
struct request_queue *dispatch_queue;
struct row_queue row_queues[ROWQ_MAX_PRIO];
struct idling_data rd_idle_data;
unsigned int nr_reqs[2];
bool urgent_in_flight;
struct request *pending_urgent_rq;
int <API key>;
#define <API key> 5000
struct starvation_data reg_prio_starvation;
#define <API key> 10000
struct starvation_data low_prio_starvation;
unsigned int cycle_flags;
};
#define RQ_ROWQ(rq) ((struct row_queue *) ((rq)->elv.priv[0]))
#define row_log(q, fmt, args...) \
blk_add_trace_msg(q, "%s():" fmt , __func__, ##args)
#define row_log_rowq(rdata, rowq_id, fmt, args...) \
blk_add_trace_msg(rdata->dispatch_queue, "rowq%d " fmt, \
rowq_id, ##args)
static inline void <API key>(struct row_data *rd,
enum row_queue_prio qnum)
{
rd->cycle_flags |= (1 << qnum);
}
static inline void <API key>(struct row_data *rd,
enum row_queue_prio qnum)
{
rd->cycle_flags &= ~(1 << qnum);
}
static inline int row_rowq_unserved(struct row_data *rd,
enum row_queue_prio qnum)
{
return rd->cycle_flags & (1 << qnum);
}
static inline void __maybe_unused <API key>(struct row_data *rd)
{
int i;
row_log(rd->dispatch_queue, " Queues status:");
for (i = 0; i < ROWQ_MAX_PRIO; i++)
row_log(rd->dispatch_queue,
"queue%d: dispatched= %d, nr_req=%d", i,
rd->row_queues[i].nr_dispatched,
rd->row_queues[i].nr_req);
}
static void kick_queue(struct work_struct *work)
{
struct idling_data *read_data =
container_of(work, struct idling_data, idle_work);
struct row_data *rd =
container_of(read_data, struct row_data, rd_idle_data);
blk_run_queue(rd->dispatch_queue);
}
static enum hrtimer_restart row_idle_hrtimer_fn(struct hrtimer *hr_timer)
{
struct idling_data *read_data =
container_of(hr_timer, struct idling_data, hr_timer);
struct row_data *rd =
container_of(read_data, struct row_data, rd_idle_data);
row_log_rowq(rd, rd->rd_idle_data.idling_queue_idx,
"Performing delayed work");
/* Mark idling process as done */
rd->row_queues[rd->rd_idle_data.idling_queue_idx].
idle_data.begin_idling = false;
rd->rd_idle_data.idling_queue_idx = ROWQ_MAX_PRIO;
if (!rd->nr_reqs[READ] && !rd->nr_reqs[WRITE])
row_log(rd->dispatch_queue, "No requests in scheduler");
else
<API key>(rd->dispatch_queue,
&read_data->idle_work);
return HRTIMER_NORESTART;
}
/*
* <API key>() - Check if there are REGULAR priority requests
* Pending in scheduler
* @rd: pointer to struct row_data
*
* Returns True if there are REGULAR priority requests in scheduler queues.
* False, otherwise.
*/
static inline bool <API key>(struct row_data *rd)
{
int i;
for (i = ROWQ_REG_PRIO_IDX; i < ROWQ_LOW_PRIO_IDX; i++)
if (!list_empty(&rd->row_queues[i].fifo))
return true;
return false;
}
/*
* row_low_req_pending() - Check if there are LOW priority requests
* Pending in scheduler
* @rd: pointer to struct row_data
*
* Returns True if there are LOW priority requests in scheduler queues.
* False, otherwise.
*/
static inline bool row_low_req_pending(struct row_data *rd)
{
int i;
for (i = ROWQ_LOW_PRIO_IDX; i < ROWQ_MAX_PRIO; i++)
if (!list_empty(&rd->row_queues[i].fifo))
return true;
return false;
}
/*
* row_add_request() - Add request to the scheduler
* @q: requests queue
* @rq: request to add
*
*/
static void row_add_request(struct request_queue *q,
struct request *rq)
{
struct row_data *rd = (struct row_data *)q->elevator->elevator_data;
struct row_queue *rqueue = RQ_ROWQ(rq);
s64 diff_ms;
bool queue_was_empty = list_empty(&rqueue->fifo);
list_add_tail(&rq->queuelist, &rqueue->fifo);
rd->nr_reqs[rq_data_dir(rq)]++;
rqueue->nr_req++;
rq_set_fifo_time(rq, jiffies); /* for statistics*/
if (rq->cmd_flags & REQ_URGENT) {
WARN_ON(1);
blk_dump_rq_flags(rq, "");
rq->cmd_flags &= ~REQ_URGENT;
}
if (row_queues_def[rqueue->prio].idling_enabled) {
if (rd->rd_idle_data.idling_queue_idx == rqueue->prio &&
hrtimer_active(&rd->rd_idle_data.hr_timer)) {
(void)hrtimer_cancel(&rd->rd_idle_data.hr_timer);
row_log_rowq(rd, rqueue->prio,
"Canceled delayed work on %d",
rd->rd_idle_data.idling_queue_idx);
rd->rd_idle_data.idling_queue_idx = ROWQ_MAX_PRIO;
}
diff_ms = ktime_to_ms(ktime_sub(ktime_get(),
rqueue->idle_data.last_insert_time));
if (unlikely(diff_ms < 0)) {
pr_err("%s(): time delta error: diff_ms < 0",
__func__);
rqueue->idle_data.begin_idling = false;
return;
}
if (diff_ms < rd->rd_idle_data.freq_ms) {
rqueue->idle_data.begin_idling = true;
row_log_rowq(rd, rqueue->prio, "Enable idling");
} else {
rqueue->idle_data.begin_idling = false;
row_log_rowq(rd, rqueue->prio, "Disable idling (%ldms)",
(long)diff_ms);
}
rqueue->idle_data.last_insert_time = ktime_get();
}
if (row_queues_def[rqueue->prio].is_urgent &&
!rd->pending_urgent_rq && !rd->urgent_in_flight) {
/* Handle High Priority queues */
if (rqueue->prio < ROWQ_REG_PRIO_IDX &&
rd-><API key> != IOPRIO_CLASS_RT &&
queue_was_empty) {
row_log_rowq(rd, rqueue->prio,
"added (high prio) urgent request");
rq->cmd_flags |= REQ_URGENT;
rd->pending_urgent_rq = rq;
} else if (row_rowq_unserved(rd, rqueue->prio)) {
/* Handle Regular priotity queues */
row_log_rowq(rd, rqueue->prio,
"added urgent request (total on queue=%d)",
rqueue->nr_req);
rq->cmd_flags |= REQ_URGENT;
WARN_ON(rqueue->nr_req > 1);
rd->pending_urgent_rq = rq;
}
} else
row_log_rowq(rd, rqueue->prio,
"added request (total on queue=%d)", rqueue->nr_req);
}
/**
* row_reinsert_req() - Reinsert request back to the scheduler
* @q: requests queue
* @rq: request to add
*
* Reinsert the given request back to the queue it was
* dispatched from as if it was never dispatched.
*
* Returns 0 on success, error code otherwise
*/
static int row_reinsert_req(struct request_queue *q,
struct request *rq)
{
struct row_data *rd = q->elevator->elevator_data;
struct row_queue *rqueue = RQ_ROWQ(rq);
if (!rqueue || rqueue->prio >= ROWQ_MAX_PRIO)
return -EIO;
list_add(&rq->queuelist, &rqueue->fifo);
rd->nr_reqs[rq_data_dir(rq)]++;
rqueue->nr_req++;
row_log_rowq(rd, rqueue->prio,
"%s request reinserted (total on queue=%d)",
(rq_data_dir(rq) == READ ? "READ" : "write"), rqueue->nr_req);
if (rq->cmd_flags & REQ_URGENT) {
/*
* It's not compliant with the design to re-insert
* urgent requests. We want to be able to track this
* down.
*/
WARN_ON(1);
if (!rd->urgent_in_flight) {
pr_err("%s(): no urgent in flight", __func__);
} else {
rd->urgent_in_flight = false;
pr_err("%s(): reinserting URGENT %s req",
__func__,
(rq_data_dir(rq) == READ ? "READ" : "WRITE"));
if (rd->pending_urgent_rq) {
pr_err("%s(): urgent rq is pending",
__func__);
rd->pending_urgent_rq->cmd_flags &= ~REQ_URGENT;
}
rd->pending_urgent_rq = rq;
}
}
return 0;
}
static void row_completed_req(struct request_queue *q, struct request *rq)
{
struct row_data *rd = q->elevator->elevator_data;
if (rq->cmd_flags & REQ_URGENT) {
if (!rd->urgent_in_flight) {
WARN_ON(1);
pr_err("%s(): URGENT req but urgent_in_flight = F",
__func__);
}
rd->urgent_in_flight = false;
rq->cmd_flags &= ~REQ_URGENT;
}
row_log(q, "completed %s %s req.",
(rq->cmd_flags & REQ_URGENT ? "URGENT" : "regular"),
(rq_data_dir(rq) == READ ? "READ" : "WRITE"));
}
/**
* row_urgent_pending() - Return TRUE if there is an urgent
* request on scheduler
* @q: requests queue
*/
static bool row_urgent_pending(struct request_queue *q)
{
struct row_data *rd = q->elevator->elevator_data;
if (rd->urgent_in_flight) {
row_log(rd->dispatch_queue, "%d urgent requests in flight",
rd->urgent_in_flight);
return false;
}
if (rd->pending_urgent_rq) {
row_log(rd->dispatch_queue, "Urgent request pending");
return true;
}
row_log(rd->dispatch_queue, "no urgent request pending/in flight");
return false;
}
/**
* row_remove_request() - Remove given request from scheduler
* @q: requests queue
* @rq: request to remove
*
*/
static void row_remove_request(struct row_data *rd,
struct request *rq)
{
struct row_queue *rqueue = RQ_ROWQ(rq);
list_del_init(&(rq)->queuelist);
if (rd->pending_urgent_rq == rq)
rd->pending_urgent_rq = NULL;
else
BUG_ON(rq->cmd_flags & REQ_URGENT);
rqueue->nr_req
rd->nr_reqs[rq_data_dir(rq)]
}
/*
* row_dispatch_insert() - move request to dispatch queue
* @rd: pointer to struct row_data
* @rq: the request to dispatch
*
* This function moves the given request to the dispatch queue
*
*/
static void row_dispatch_insert(struct row_data *rd, struct request *rq)
{
struct row_queue *rqueue = RQ_ROWQ(rq);
row_remove_request(rd, rq);
elv_dispatch_sort(rd->dispatch_queue, rq);
if (rq->cmd_flags & REQ_URGENT) {
WARN_ON(rd->urgent_in_flight);
rd->urgent_in_flight = true;
}
rqueue->nr_dispatched++;
<API key>(rd, rqueue->prio);
row_log_rowq(rd, rqueue->prio,
" Dispatched request %p nr_disp = %d", rq,
rqueue->nr_dispatched);
if (rqueue->prio < ROWQ_REG_PRIO_IDX) {
rd-><API key> = IOPRIO_CLASS_RT;
if (<API key>(rd))
rd->reg_prio_starvation.starvation_counter++;
if (row_low_req_pending(rd))
rd->low_prio_starvation.starvation_counter++;
} else if (rqueue->prio < ROWQ_LOW_PRIO_IDX) {
rd-><API key> = IOPRIO_CLASS_BE;
rd->reg_prio_starvation.starvation_counter = 0;
if (row_low_req_pending(rd))
rd->low_prio_starvation.starvation_counter++;
} else {
rd-><API key> = IOPRIO_CLASS_IDLE;
rd->low_prio_starvation.starvation_counter = 0;
}
}
/*
* <API key>() - Return the next I/O priority
* class to dispatch requests from
* @rd: pointer to struct row_data
* @force: flag indicating if forced dispatch
*
* This function returns the next I/O priority class to serve
* {IOPRIO_CLASS_NONE, IOPRIO_CLASS_RT, IOPRIO_CLASS_BE, IOPRIO_CLASS_IDLE}.
* If there are no more requests in scheduler or if we're idling on some queue
* IOPRIO_CLASS_NONE will be returned.
* If idling is scheduled on a lower priority queue than the one that needs
* to be served, it will be canceled.
*
*/
static int <API key>(struct row_data *rd, int force)
{
int i;
int ret = IOPRIO_CLASS_NONE;
if (!rd->nr_reqs[READ] && !rd->nr_reqs[WRITE]) {
row_log(rd->dispatch_queue, "No more requests in scheduler");
goto check_idling;
}
/* First, go over the high priority queues */
for (i = 0; i < ROWQ_REG_PRIO_IDX; i++) {
if (!list_empty(&rd->row_queues[i].fifo)) {
if (hrtimer_active(&rd->rd_idle_data.hr_timer)) {
(void)hrtimer_cancel(
&rd->rd_idle_data.hr_timer);
row_log_rowq(rd,
rd->rd_idle_data.idling_queue_idx,
"Canceling delayed work on %d. RT pending",
rd->rd_idle_data.idling_queue_idx);
rd->rd_idle_data.idling_queue_idx =
ROWQ_MAX_PRIO;
}
if (<API key>(rd) &&
(rd->reg_prio_starvation.starvation_counter >=
rd->reg_prio_starvation.starvation_limit))
ret = IOPRIO_CLASS_BE;
else if (row_low_req_pending(rd) &&
(rd->low_prio_starvation.starvation_counter >=
rd->low_prio_starvation.starvation_limit))
ret = IOPRIO_CLASS_IDLE;
else
ret = IOPRIO_CLASS_RT;
goto done;
}
}
/*
* At the moment idling is implemented only for READ queues.
* If enabled on WRITE, this needs updating
*/
if (hrtimer_active(&rd->rd_idle_data.hr_timer)) {
row_log(rd->dispatch_queue, "Delayed work pending. Exiting");
goto done;
}
check_idling:
/* Check for (high priority) idling and enable if needed */
for (i = 0; i < ROWQ_REG_PRIO_IDX && !force; i++) {
if (rd->row_queues[i].idle_data.begin_idling &&
row_queues_def[i].idling_enabled)
goto initiate_idling;
}
/* Regular priority queues */
for (i = ROWQ_REG_PRIO_IDX; i < ROWQ_LOW_PRIO_IDX; i++) {
if (list_empty(&rd->row_queues[i].fifo)) {
/* We can idle only if this is not a forced dispatch */
if (rd->row_queues[i].idle_data.begin_idling &&
!force && row_queues_def[i].idling_enabled)
goto initiate_idling;
} else {
if (row_low_req_pending(rd) &&
(rd->low_prio_starvation.starvation_counter >=
rd->low_prio_starvation.starvation_limit))
ret = IOPRIO_CLASS_IDLE;
else
ret = IOPRIO_CLASS_BE;
goto done;
}
}
if (rd->nr_reqs[READ] || rd->nr_reqs[WRITE])
ret = IOPRIO_CLASS_IDLE;
goto done;
initiate_idling:
hrtimer_start(&rd->rd_idle_data.hr_timer,
ktime_set(0, rd->rd_idle_data.idle_time_ms * NSEC_PER_MSEC),
HRTIMER_MODE_REL);
rd->rd_idle_data.idling_queue_idx = i;
row_log_rowq(rd, i, "Scheduled delayed work on %d. exiting", i);
done:
return ret;
}
static void row_restart_cycle(struct row_data *rd,
int start_idx, int end_idx)
{
int i;
<API key>(rd);
for (i = start_idx; i < end_idx; i++) {
if (rd->row_queues[i].nr_dispatched <
rd->row_queues[i].disp_quantum)
<API key>(rd, i);
rd->row_queues[i].nr_dispatched = 0;
}
row_log(rd->dispatch_queue, "Restarting cycle for class @ %d-%d",
start_idx, end_idx);
}
/*
* row_get_next_queue() - selects the next queue to dispatch from
* @q: requests queue
* @rd: pointer to struct row_data
* @start_idx/end_idx: indexes in the row_queues array to select a queue
* from.
*
* Return index of the queues to dispatch from. Error code if fails.
*
*/
static int row_get_next_queue(struct request_queue *q, struct row_data *rd,
int start_idx, int end_idx)
{
int i = start_idx;
bool restart = true;
int ret = -EIO;
do {
if (list_empty(&rd->row_queues[i].fifo) ||
rd->row_queues[i].nr_dispatched >=
rd->row_queues[i].disp_quantum) {
i++;
if (i == end_idx && restart) {
/* Restart cycle for this priority class */
row_restart_cycle(rd, start_idx, end_idx);
i = start_idx;
restart = false;
}
} else {
ret = i;
break;
}
} while (i < end_idx);
return ret;
}
/*
* <API key>() - selects the next request to dispatch
* @q: requests queue
* @force: flag indicating if forced dispatch
*
* Return 0 if no requests were moved to the dispatch queue.
* 1 otherwise
*
*/
static int <API key>(struct request_queue *q, int force)
{
struct row_data *rd = (struct row_data *)q->elevator->elevator_data;
int ret = 0, currq, <API key>, start_idx, end_idx;
if (force && hrtimer_active(&rd->rd_idle_data.hr_timer)) {
(void)hrtimer_cancel(&rd->rd_idle_data.hr_timer);
row_log_rowq(rd, rd->rd_idle_data.idling_queue_idx,
"Canceled delayed work on %d - forced dispatch",
rd->rd_idle_data.idling_queue_idx);
rd->rd_idle_data.idling_queue_idx = ROWQ_MAX_PRIO;
}
if (rd->pending_urgent_rq) {
row_log(rd->dispatch_queue, "dispatching urgent request");
row_dispatch_insert(rd, rd->pending_urgent_rq);
ret = 1;
goto done;
}
<API key> = <API key>(rd, force);
row_log(rd->dispatch_queue, "Dispatching from %d priority class",
<API key>);
switch (<API key>) {
case IOPRIO_CLASS_NONE:
rd-><API key> = IOPRIO_CLASS_NONE;
goto done;
case IOPRIO_CLASS_RT:
start_idx = ROWQ_HIGH_PRIO_IDX;
end_idx = ROWQ_REG_PRIO_IDX;
break;
case IOPRIO_CLASS_BE:
start_idx = ROWQ_REG_PRIO_IDX;
end_idx = ROWQ_LOW_PRIO_IDX;
break;
case IOPRIO_CLASS_IDLE:
start_idx = ROWQ_LOW_PRIO_IDX;
end_idx = ROWQ_MAX_PRIO;
break;
default:
pr_err("%s(): Invalid I/O priority class", __func__);
goto done;
}
currq = row_get_next_queue(q, rd, start_idx, end_idx);
/* Dispatch */
if (currq >= 0) {
row_dispatch_insert(rd,
rq_entry_fifo(rd->row_queues[currq].fifo.next));
ret = 1;
}
done:
return ret;
}
/*
* row_init_queue() - Init scheduler data structures
* @q: requests queue
*
* Return pointer to struct row_data to be saved in elevator for
* this dispatch queue
*
*/
static void *row_init_queue(struct request_queue *q)
{
struct row_data *rdata;
int i;
rdata = kmalloc_node(sizeof(*rdata),
GFP_KERNEL | __GFP_ZERO, q->node);
if (!rdata)
return NULL;
memset(rdata, 0, sizeof(*rdata));
for (i = 0; i < ROWQ_MAX_PRIO; i++) {
INIT_LIST_HEAD(&rdata->row_queues[i].fifo);
rdata->row_queues[i].disp_quantum = row_queues_def[i].quantum;
rdata->row_queues[i].rdata = rdata;
rdata->row_queues[i].prio = i;
rdata->row_queues[i].idle_data.begin_idling = false;
rdata->row_queues[i].idle_data.last_insert_time =
ktime_set(0, 0);
}
rdata->reg_prio_starvation.starvation_limit =
<API key>;
rdata->low_prio_starvation.starvation_limit =
<API key>;
/*
* Currently idling is enabled only for READ queues. If we want to
* enable it for write queues also, note that idling frequency will
* be the same in both cases
*/
rdata->rd_idle_data.idle_time_ms = ROW_IDLE_TIME_MSEC;
rdata->rd_idle_data.freq_ms = ROW_READ_FREQ_MSEC;
hrtimer_init(&rdata->rd_idle_data.hr_timer,
CLOCK_MONOTONIC, HRTIMER_MODE_REL);
rdata->rd_idle_data.hr_timer.function = &row_idle_hrtimer_fn;
INIT_WORK(&rdata->rd_idle_data.idle_work, kick_queue);
rdata-><API key> = IOPRIO_CLASS_NONE;
rdata->rd_idle_data.idling_queue_idx = ROWQ_MAX_PRIO;
rdata->dispatch_queue = q;
return rdata;
}
/*
* row_exit_queue() - called on unloading the RAW scheduler
* @e: poiner to struct elevator_queue
*
*/
static void row_exit_queue(struct elevator_queue *e)
{
struct row_data *rd = (struct row_data *)e->elevator_data;
int i;
for (i = 0; i < ROWQ_MAX_PRIO; i++)
BUG_ON(!list_empty(&rd->row_queues[i].fifo));
if (hrtimer_cancel(&rd->rd_idle_data.hr_timer))
pr_err("%s(): idle timer was active!", __func__);
rd->rd_idle_data.idling_queue_idx = ROWQ_MAX_PRIO;
kfree(rd);
}
/*
* row_merged_requests() - Called when 2 requests are merged
* @q: requests queue
* @rq: request the two requests were merged into
* @next: request that was merged
*/
static void row_merged_requests(struct request_queue *q, struct request *rq,
struct request *next)
{
struct row_queue *rqueue = RQ_ROWQ(next);
list_del_init(&next->queuelist);
rqueue->nr_req
if (rqueue->rdata->pending_urgent_rq == next) {
pr_err("\n\nROW_WARNING: merging pending urgent!");
rqueue->rdata->pending_urgent_rq = rq;
rq->cmd_flags |= REQ_URGENT;
WARN_ON(!(next->cmd_flags & REQ_URGENT));
next->cmd_flags &= ~REQ_URGENT;
}
rqueue->rdata->nr_reqs[rq_data_dir(rq)]
}
/*
* row_get_queue_prio() - Get queue priority for a given request
*
* This is a helping function which purpose is to determine what
* ROW queue the given request should be added to (and
* dispatched from later on)
*
*/
static enum row_queue_prio row_get_queue_prio(struct request *rq,
struct row_data *rd)
{
const int data_dir = rq_data_dir(rq);
const bool is_sync = rq_is_sync(rq);
enum row_queue_prio q_type = ROWQ_MAX_PRIO;
int ioprio_class = IOPRIO_PRIO_CLASS(rq->elv.icq->ioc->ioprio);
switch (ioprio_class) {
case IOPRIO_CLASS_RT:
if (data_dir == READ)
q_type = ROWQ_PRIO_HIGH_READ;
else if (is_sync)
q_type = <API key>;
else {
pr_err("%s:%s(): got a simple write from RT_CLASS. How???",
rq->rq_disk->disk_name, __func__);
q_type = ROWQ_PRIO_REG_WRITE;
}
break;
case IOPRIO_CLASS_IDLE:
if (data_dir == READ)
q_type = ROWQ_PRIO_LOW_READ;
else if (is_sync)
q_type = <API key>;
else {
pr_err("%s:%s(): got a simple write from IDLE_CLASS. How???",
rq->rq_disk->disk_name, __func__);
q_type = ROWQ_PRIO_REG_WRITE;
}
break;
case IOPRIO_CLASS_NONE:
case IOPRIO_CLASS_BE:
default:
if (data_dir == READ)
q_type = ROWQ_PRIO_REG_READ;
else if (is_sync)
q_type = <API key>;
else
q_type = ROWQ_PRIO_REG_WRITE;
break;
}
return q_type;
}
/*
* row_set_request() - Set ROW data structures associated with this request.
* @q: requests queue
* @rq: pointer to the request
* @gfp_mask: ignored
*
*/
static int
row_set_request(struct request_queue *q, struct request *rq, gfp_t gfp_mask)
{
struct row_data *rd = (struct row_data *)q->elevator->elevator_data;
unsigned long flags;
spin_lock_irqsave(q->queue_lock, flags);
rq->elv.priv[0] =
(void *)(&rd->row_queues[row_get_queue_prio(rq, rd)]);
<API key>(q->queue_lock, flags);
return 0;
}
static ssize_t row_var_show(int var, char *page)
{
return snprintf(page, 100, "%d\n", var);
}
static ssize_t row_var_store(int *var, const char *page, size_t count)
{
int err;
err = kstrtoul(page, 10, (unsigned long *)var);
return count;
}
#define SHOW_FUNCTION(__FUNC, __VAR) \
static ssize_t __FUNC(struct elevator_queue *e, char *page) \
{ \
struct row_data *rowd = e->elevator_data; \
int __data = __VAR; \
return row_var_show(__data, (page)); \
}
SHOW_FUNCTION(<API key>,
rowd->row_queues[ROWQ_PRIO_HIGH_READ].disp_quantum);
SHOW_FUNCTION(<API key>,
rowd->row_queues[ROWQ_PRIO_REG_READ].disp_quantum);
SHOW_FUNCTION(<API key>,
rowd->row_queues[<API key>].disp_quantum);
SHOW_FUNCTION(<API key>,
rowd->row_queues[<API key>].disp_quantum);
SHOW_FUNCTION(<API key>,
rowd->row_queues[ROWQ_PRIO_REG_WRITE].disp_quantum);
SHOW_FUNCTION(<API key>,
rowd->row_queues[ROWQ_PRIO_LOW_READ].disp_quantum);
SHOW_FUNCTION(<API key>,
rowd->row_queues[<API key>].disp_quantum);
SHOW_FUNCTION(<API key>, rowd->rd_idle_data.idle_time_ms);
SHOW_FUNCTION(<API key>, rowd->rd_idle_data.freq_ms);
SHOW_FUNCTION(<API key>,
rowd->reg_prio_starvation.starvation_limit);
SHOW_FUNCTION(<API key>,
rowd->low_prio_starvation.starvation_limit);
#undef SHOW_FUNCTION
#define STORE_FUNCTION(__FUNC, __PTR, MIN, MAX) \
static ssize_t __FUNC(struct elevator_queue *e, \
const char *page, size_t count) \
{ \
struct row_data *rowd = e->elevator_data; \
int __data; \
int ret = row_var_store(&__data, (page), count); \
if (__data < (MIN)) \
__data = (MIN); \
else if (__data > (MAX)) \
__data = (MAX); \
*(__PTR) = __data; \
return ret; \
}
STORE_FUNCTION(<API key>,
&rowd->row_queues[ROWQ_PRIO_HIGH_READ].disp_quantum, 1, INT_MAX);
STORE_FUNCTION(<API key>,
&rowd->row_queues[ROWQ_PRIO_REG_READ].disp_quantum,
1, INT_MAX);
STORE_FUNCTION(<API key>,
&rowd->row_queues[<API key>].disp_quantum,
1, INT_MAX);
STORE_FUNCTION(<API key>,
&rowd->row_queues[<API key>].disp_quantum,
1, INT_MAX);
STORE_FUNCTION(<API key>,
&rowd->row_queues[ROWQ_PRIO_REG_WRITE].disp_quantum,
1, INT_MAX);
STORE_FUNCTION(<API key>,
&rowd->row_queues[ROWQ_PRIO_LOW_READ].disp_quantum,
1, INT_MAX);
STORE_FUNCTION(<API key>,
&rowd->row_queues[<API key>].disp_quantum,
1, INT_MAX);
STORE_FUNCTION(<API key>, &rowd->rd_idle_data.idle_time_ms,
1, INT_MAX);
STORE_FUNCTION(<API key>, &rowd->rd_idle_data.freq_ms,
1, INT_MAX);
STORE_FUNCTION(<API key>,
&rowd->reg_prio_starvation.starvation_limit,
1, INT_MAX);
STORE_FUNCTION(<API key>,
&rowd->low_prio_starvation.starvation_limit,
1, INT_MAX);
#undef STORE_FUNCTION
#define ROW_ATTR(name) \
__ATTR(name, S_IRUGO|S_IWUSR, row_##name##_show, \
row_##name##_store)
static struct elv_fs_entry row_attrs[] = {
ROW_ATTR(hp_read_quantum),
ROW_ATTR(rp_read_quantum),
ROW_ATTR(hp_swrite_quantum),
ROW_ATTR(rp_swrite_quantum),
ROW_ATTR(rp_write_quantum),
ROW_ATTR(lp_read_quantum),
ROW_ATTR(lp_swrite_quantum),
ROW_ATTR(rd_idle_data),
ROW_ATTR(rd_idle_data_freq),
ROW_ATTR(reg_starv_limit),
ROW_ATTR(low_starv_limit),
__ATTR_NULL
};
static struct elevator_type iosched_row = {
.ops = {
.<API key> = row_merged_requests,
.<API key> = <API key>,
.elevator_add_req_fn = row_add_request,
.<API key> = row_reinsert_req,
.<API key> = row_urgent_pending,
.<API key> = row_completed_req,
.<API key> = <API key>,
.<API key> = <API key>,
.elevator_set_req_fn = row_set_request,
.elevator_init_fn = row_init_queue,
.elevator_exit_fn = row_exit_queue,
},
.icq_size = sizeof(struct io_cq),
.icq_align = __alignof__(struct io_cq),
.elevator_attrs = row_attrs,
.elevator_name = "row",
.elevator_owner = THIS_MODULE,
};
static int __init row_init(void)
{
elv_register(&iosched_row);
return 0;
}
static void __exit row_exit(void)
{
elv_unregister(&iosched_row);
}
module_init(row_init);
module_exit(row_exit);
MODULE_LICENSE("GPLv2");
MODULE_DESCRIPTION("Read Over Write IO scheduler"); |
<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8' /><link rel='stylesheet' type='text/css' href='../tononkira.css' /></head><body><ul class="hira-fihirana-list"><li style="color: red;"><b>Fihirana Vaovao</b> <i>p. 402</i></li><li style="color: red;"><b>Vavaka sy Hira</b> <i>p. 441</i></li><li style="color: red;"><b>Fihirana Hasina</b> <i>p. 378</i></li><li style="color: red;"><b>Ankalazao ny Tompo</b> <i>p. 114</i></li></ul><p><strong>Amin'ny andron'ny Tompo. Aleloia.</strong><br />
<br />
1 Ny nofo rehetra handray ny Fanahy. Aleloia. <br />
2 Dia hisy hamantarana izany eny ambony. Aleloia.<br />
<br />
3 Fa hisy hamantarana koa eto an-tany. Aleloia. <br />
4 'Zay miantso ny anarany dia hovonjeny. Aleloia.<br />
<br />
5 Fa tsy mba ho menatra ireo mino azy. Aleloia. <br />
6 Ny teniny haharitra mandrakizay. Aleloia.<br />
</p></body></html> |
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_91) on Fri Nov 11 17:46:57 CET 2016 -->
<title>Javadocs: OCT</title>
<script type="text/javascript">
targetPage = "" + window.location.search;
if (targetPage != "" && targetPage != "undefined")
targetPage = targetPage.substring(1);
if (targetPage.indexOf(":") != -1 || (targetPage != "" && !validURL(targetPage)))
targetPage = "undefined";
function validURL(url) {
try {
url = decodeURIComponent(url);
}
catch (error) {
return false;
}
var pos = url.indexOf(".html");
if (pos == -1 || pos != url.length - 5)
return false;
var allowNumber = false;
var allowSep = false;
var seenDot = false;
for (var i = 0; i < url.length - 5; i++) {
var ch = url.charAt(i);
if ('a' <= ch && ch <= 'z' ||
'A' <= ch && ch <= 'Z' ||
ch == '$' ||
ch == '_' ||
ch.charCodeAt(0) > 127) {
allowNumber = true;
allowSep = true;
} else if ('0' <= ch && ch <= '9'
|| ch == '-') {
if (!allowNumber)
return false;
} else if (ch == '/' || ch == '.') {
if (!allowSep)
return false;
allowNumber = false;
allowSep = false;
if (ch == '.')
seenDot = true;
if (ch == '/' && seenDot)
return false;
} else {
return false;
}
}
return true;
}
function loadFrames() {
if (targetPage != "" && targetPage != "undefined")
top.classFrame.location = top.targetPage;
}
</script>
</head>
<frameset cols="20%,80%" title="Documentation frame" onload="top.loadFrames()">
<frameset rows="30%,70%" title="Left frames" onload="top.loadFrames()">
<frame src="overview-frame.html" name="packageListFrame" title="All Packages">
<frame src="allclasses-frame.html" name="packageFrame" title="All classes and interfaces (except non-static nested types)">
</frameset>
<frame src="overview-summary.html" name="classFrame" title="Package, class and interface descriptions" scrolling="yes">
<noframes>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<h2>Frame Alert</h2>
<p>This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client. Link to <a href="overview-summary.html">Non-frame version</a>.</p>
</noframes>
</frameset>
</html> |
#include <linux/errno.h>
#include <linux/export.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/param.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <linux/timex.h>
#include <linux/kernel_stat.h>
#include <linux/time.h>
#include <linux/clockchips.h>
#include <linux/init.h>
#include <linux/profile.h>
#include <linux/cpu.h>
#include <linux/security.h>
#include <linux/percpu.h>
#include <linux/rtc.h>
#include <linux/jiffies.h>
#include <linux/posix-timers.h>
#include <linux/irq.h>
#include <linux/delay.h>
#include <linux/irq_work.h>
#include <asm/trace.h>
#include <asm/io.h>
#include <asm/processor.h>
#include <asm/nvram.h>
#include <asm/cache.h>
#include <asm/machdep.h>
#include <asm/uaccess.h>
#include <asm/time.h>
#include <asm/prom.h>
#include <asm/irq.h>
#include <asm/div64.h>
#include <asm/smp.h>
#include <asm/vdso_datapage.h>
#include <asm/firmware.h>
#include <asm/cputime.h>
/* powerpc clocksource/clockevent code */
#include <linux/clockchips.h>
#include <linux/timekeeper_internal.h>
static cycle_t rtc_read(struct clocksource *);
static struct clocksource clocksource_rtc = {
.name = "rtc",
.rating = 400,
.flags = <API key>,
.mask = CLOCKSOURCE_MASK(64),
.read = rtc_read,
};
static cycle_t timebase_read(struct clocksource *);
static struct clocksource <API key> = {
.name = "timebase",
.rating = 400,
.flags = <API key>,
.mask = CLOCKSOURCE_MASK(64),
.read = timebase_read,
};
#define DECREMENTER_MAX 0x7fffffff
static int <API key>(unsigned long evt,
struct clock_event_device *dev);
static void <API key>(enum clock_event_mode mode,
struct clock_event_device *dev);
struct clock_event_device <API key> = {
.name = "decrementer",
.rating = 200,
.irq = 0,
.set_next_event = <API key>,
.set_mode = <API key>,
.features = <API key> | <API key>,
};
EXPORT_SYMBOL(<API key>);
DEFINE_PER_CPU(u64, <API key>);
static DEFINE_PER_CPU(struct clock_event_device, decrementers);
#define XSEC_PER_SEC (1024*1024)
#ifdef CONFIG_PPC64
#define SCALE_XSEC(xsec, max) (((xsec) * max) / XSEC_PER_SEC)
#else
/* compute ((xsec << 12) * max) >> 32 */
#define SCALE_XSEC(xsec, max) mulhwu((xsec) << 12, max)
#endif
unsigned long tb_ticks_per_jiffy;
unsigned long tb_ticks_per_usec = 100; /* sane default */
EXPORT_SYMBOL(tb_ticks_per_usec);
unsigned long tb_ticks_per_sec;
EXPORT_SYMBOL(tb_ticks_per_sec); /* for cputime_t conversions */
DEFINE_SPINLOCK(rtc_lock);
EXPORT_SYMBOL_GPL(rtc_lock);
static u64 tb_to_ns_scale __read_mostly;
static unsigned tb_to_ns_shift __read_mostly;
static u64 boot_tb __read_mostly;
extern struct timezone sys_tz;
static long timezone_offset;
unsigned long ppc_proc_freq;
EXPORT_SYMBOL_GPL(ppc_proc_freq);
unsigned long ppc_tb_freq;
EXPORT_SYMBOL_GPL(ppc_tb_freq);
#ifdef <API key>
/*
* Factors for converting from cputime_t (timebase ticks) to
* jiffies, microseconds, seconds, and clock_t (1/USER_HZ seconds).
* These are all stored as 0.64 fixed-point binary fractions.
*/
u64 <API key>;
EXPORT_SYMBOL(<API key>);
u64 <API key>;
EXPORT_SYMBOL(<API key>);
u64 <API key>;
EXPORT_SYMBOL(<API key>);
u64 <API key>;
EXPORT_SYMBOL(<API key>);
DEFINE_PER_CPU(unsigned long, cputime_last_delta);
DEFINE_PER_CPU(unsigned long, <API key>);
cputime_t cputime_one_jiffy;
void (*dtl_consumer)(struct dtl_entry *, u64);
static void <API key>(void)
{
struct div_result res;
div128_by_32(HZ, 0, tb_ticks_per_sec, &res);
<API key> = res.result_low;
div128_by_32(1000000, 0, tb_ticks_per_sec, &res);
<API key> = res.result_low;
div128_by_32(1, 0, tb_ticks_per_sec, &res);
<API key> = res.result_low;
div128_by_32(USER_HZ, 0, tb_ticks_per_sec, &res);
<API key> = res.result_low;
}
/*
* Read the SPURR on systems that have it, otherwise the PURR,
* or if that doesn't exist return the timebase value passed in.
*/
static u64 read_spurr(u64 tb)
{
if (cpu_has_feature(CPU_FTR_SPURR))
return mfspr(SPRN_SPURR);
if (cpu_has_feature(CPU_FTR_PURR))
return mfspr(SPRN_PURR);
return tb;
}
#ifdef CONFIG_PPC_SPLPAR
/*
* Scan the dispatch trace log and count up the stolen time.
* Should be called with interrupts disabled.
*/
static u64 scan_dispatch_log(u64 stop_tb)
{
u64 i = local_paca->dtl_ridx;
struct dtl_entry *dtl = local_paca->dtl_curr;
struct dtl_entry *dtl_end = local_paca->dispatch_log_end;
struct lppaca *vpa = local_paca->lppaca_ptr;
u64 tb_delta;
u64 stolen = 0;
u64 dtb;
if (!dtl)
return 0;
if (i == be64_to_cpu(vpa->dtl_idx))
return 0;
while (i < be64_to_cpu(vpa->dtl_idx)) {
dtb = be64_to_cpu(dtl->timebase);
tb_delta = be32_to_cpu(dtl-><API key>) +
be32_to_cpu(dtl-><API key>);
barrier();
if (i + N_DISPATCH_LOG < be64_to_cpu(vpa->dtl_idx)) {
/* buffer has overflowed */
i = be64_to_cpu(vpa->dtl_idx) - N_DISPATCH_LOG;
dtl = local_paca->dispatch_log + (i % N_DISPATCH_LOG);
continue;
}
if (dtb > stop_tb)
break;
if (dtl_consumer)
dtl_consumer(dtl, i);
stolen += tb_delta;
++i;
++dtl;
if (dtl == dtl_end)
dtl = local_paca->dispatch_log;
}
local_paca->dtl_ridx = i;
local_paca->dtl_curr = dtl;
return stolen;
}
/*
* Accumulate stolen time by scanning the dispatch trace log.
* Called on entry from user mode.
*/
void <API key>(void)
{
u64 sst, ust;
u8 save_soft_enabled = local_paca->soft_enabled;
/* We are called early in the exception entry, before
* soft/hard_enabled are sync'ed to the expected state
* for the exception. We are hard disabled but the PACA
* needs to reflect that so various debug stuff doesn't
* complain
*/
local_paca->soft_enabled = 0;
sst = scan_dispatch_log(local_paca->starttime_user);
ust = scan_dispatch_log(local_paca->starttime);
local_paca->system_time -= sst;
local_paca->user_time -= ust;
local_paca->stolen_time += ust + sst;
local_paca->soft_enabled = save_soft_enabled;
}
static inline u64 <API key>(u64 stop_tb)
{
u64 stolen = 0;
if (get_paca()->dtl_ridx != be64_to_cpu(get_lppaca()->dtl_idx)) {
stolen = scan_dispatch_log(stop_tb);
get_paca()->system_time -= stolen;
}
stolen += get_paca()->stolen_time;
get_paca()->stolen_time = 0;
return stolen;
}
#else /* CONFIG_PPC_SPLPAR */
static inline u64 <API key>(u64 stop_tb)
{
return 0;
}
#endif /* CONFIG_PPC_SPLPAR */
/*
* Account time for a transition between system, hard irq
* or soft irq state.
*/
static u64 vtime_delta(struct task_struct *tsk,
u64 *sys_scaled, u64 *stolen)
{
u64 now, nowscaled, deltascaled;
u64 udelta, delta, user_scaled;
WARN_ON_ONCE(!irqs_disabled());
now = mftb();
nowscaled = read_spurr(now);
get_paca()->system_time += now - get_paca()->starttime;
get_paca()->starttime = now;
deltascaled = nowscaled - get_paca()->startspurr;
get_paca()->startspurr = nowscaled;
*stolen = <API key>(now);
delta = get_paca()->system_time;
get_paca()->system_time = 0;
udelta = get_paca()->user_time - get_paca()->utime_sspurr;
get_paca()->utime_sspurr = get_paca()->user_time;
/*
* Because we don't read the SPURR on every kernel entry/exit,
* deltascaled includes both user and system SPURR ticks.
* Apportion these ticks to system SPURR ticks and user
* SPURR ticks in the same ratio as the system time (delta)
* and user time (udelta) values obtained from the timebase
* over the same interval. The system ticks get accounted here;
* the user ticks get saved up in paca->user_time_scaled to be
* used by <API key>.
*/
*sys_scaled = delta;
user_scaled = udelta;
if (deltascaled != delta + udelta) {
if (udelta) {
*sys_scaled = deltascaled * delta / (delta + udelta);
user_scaled = deltascaled - *sys_scaled;
} else {
*sys_scaled = deltascaled;
}
}
get_paca()->user_time_scaled += user_scaled;
return delta;
}
void <API key>(struct task_struct *tsk)
{
u64 delta, sys_scaled, stolen;
delta = vtime_delta(tsk, &sys_scaled, &stolen);
account_system_time(tsk, 0, delta, sys_scaled);
if (stolen)
account_steal_time(stolen);
}
EXPORT_SYMBOL_GPL(<API key>);
void vtime_account_idle(struct task_struct *tsk)
{
u64 delta, sys_scaled, stolen;
delta = vtime_delta(tsk, &sys_scaled, &stolen);
account_idle_time(delta + stolen);
}
/*
* Transfer the user time accumulated in the paca
* by the exception entry and exit code to the generic
* process user time records.
* Must be called with interrupts disabled.
* Assumes that <API key>/idle() has been called
* recently (i.e. since the last entry from usermode) so that
* get_paca()->user_time_scaled is up to date.
*/
void vtime_account_user(struct task_struct *tsk)
{
cputime_t utime, utimescaled;
utime = get_paca()->user_time;
utimescaled = get_paca()->user_time_scaled;
get_paca()->user_time = 0;
get_paca()->user_time_scaled = 0;
get_paca()->utime_sspurr = 0;
account_user_time(tsk, utime, utimescaled);
}
#else /* ! <API key> */
#define <API key>()
#endif
void __delay(unsigned long loops)
{
unsigned long start;
int diff;
if (__USE_RTC()) {
start = get_rtcl();
do {
/* the RTCL register wraps at 1000000000 */
diff = get_rtcl() - start;
if (diff < 0)
diff += 1000000000;
} while (diff < loops);
} else {
start = get_tbl();
while (get_tbl() - start < loops)
HMT_low();
HMT_medium();
}
}
EXPORT_SYMBOL(__delay);
void udelay(unsigned long usecs)
{
__delay(tb_ticks_per_usec * usecs);
}
EXPORT_SYMBOL(udelay);
#ifdef CONFIG_SMP
unsigned long profile_pc(struct pt_regs *regs)
{
unsigned long pc = instruction_pointer(regs);
if (in_lock_functions(pc))
return regs->link;
return pc;
}
EXPORT_SYMBOL(profile_pc);
#endif
#ifdef CONFIG_IRQ_WORK
/*
* 64-bit uses a byte in the PACA, 32-bit uses a per-cpu variable...
*/
#ifdef CONFIG_PPC64
static inline unsigned long <API key>(void)
{
unsigned long x;
asm volatile("lbz %0,%1(13)"
: "=r" (x)
: "i" (offsetof(struct paca_struct, irq_work_pending)));
return x;
}
static inline void <API key>(void)
{
asm volatile("stb %0,%1(13)" : :
"r" (1),
"i" (offsetof(struct paca_struct, irq_work_pending)));
}
static inline void <API key>(void)
{
asm volatile("stb %0,%1(13)" : :
"r" (0),
"i" (offsetof(struct paca_struct, irq_work_pending)));
}
#else /* 32-bit */
DEFINE_PER_CPU(u8, irq_work_pending);
#define <API key>() __get_cpu_var(irq_work_pending) = 1
#define <API key>() __get_cpu_var(irq_work_pending)
#define <API key>() __get_cpu_var(irq_work_pending) = 0
#endif /* 32 vs 64 bit */
void arch_irq_work_raise(void)
{
preempt_disable();
<API key>();
set_dec(1);
preempt_enable();
}
#else /* CONFIG_IRQ_WORK */
#define <API key>() 0
#define <API key>()
#endif /* CONFIG_IRQ_WORK */
void __timer_interrupt(void)
{
struct pt_regs *regs = get_irq_regs();
u64 *next_tb = &__get_cpu_var(<API key>);
struct clock_event_device *evt = &__get_cpu_var(decrementers);
u64 now;
<API key>(regs);
if (<API key>()) {
<API key>();
irq_work_run();
}
now = get_tb_or_rtc();
if (now >= *next_tb) {
*next_tb = ~(u64)0;
if (evt->event_handler)
evt->event_handler(evt);
__get_cpu_var(irq_stat).timer_irqs_event++;
} else {
now = *next_tb - now;
if (now <= DECREMENTER_MAX)
set_dec((int)now);
/* We may have raced with new irq work */
if (<API key>())
set_dec(1);
__get_cpu_var(irq_stat).timer_irqs_others++;
}
#ifdef CONFIG_PPC64
/* collect purr register values often, for accurate calculations */
if (<API key>(FW_FEATURE_SPLPAR)) {
struct cpu_usage *cu = &__get_cpu_var(cpu_usage_array);
cu->current_tb = mfspr(SPRN_PURR);
}
#endif
<API key>(regs);
}
/*
* timer_interrupt - gets called when the decrementer overflows,
* with interrupts disabled.
*/
void timer_interrupt(struct pt_regs * regs)
{
struct pt_regs *old_regs;
u64 *next_tb = &__get_cpu_var(<API key>);
/* Ensure a positive value is written to the decrementer, or else
* some CPUs will continue to take decrementer exceptions.
*/
set_dec(DECREMENTER_MAX);
/* Some implementations of hotplug will get timer interrupts while
* offline, just ignore these and we also need to set
* <API key> as MAX to make sure __check_irq_replay
* don't replay timer interrupt when return, otherwise we'll trap
* here infinitely :(
*/
if (!cpu_online(smp_processor_id())) {
*next_tb = ~(u64)0;
return;
}
/* Conditionally hard-enable interrupts now that the DEC has been
* bumped to its maximum value
*/
may_hard_irq_enable();
#if defined(CONFIG_PPC32) && defined(CONFIG_PPC_PMAC)
if (atomic_read(&<API key>) != 0)
do_IRQ(regs);
#endif
old_regs = set_irq_regs(regs);
irq_enter();
__timer_interrupt();
irq_exit();
set_irq_regs(old_regs);
}
/*
* Hypervisor decrementer interrupts shouldn't occur but are sometimes
* left pending on exit from a KVM guest. We don't need to do anything
* to clear them, as they are edge-triggered.
*/
void hdec_interrupt(struct pt_regs *regs)
{
}
#ifdef CONFIG_SUSPEND
static void <API key>(void)
{
/* Disable the decrementer, so that it doesn't interfere
* with suspending.
*/
set_dec(DECREMENTER_MAX);
local_irq_disable();
set_dec(DECREMENTER_MAX);
}
static void <API key>(void)
{
local_irq_enable();
}
/* Overrides the weak version in kernel/power/main.c */
void <API key>(void)
{
if (ppc_md.<API key>)
ppc_md.<API key>();
<API key>();
}
/* Overrides the weak version in kernel/power/main.c */
void <API key>(void)
{
<API key>();
if (ppc_md.suspend_enable_irqs)
ppc_md.suspend_enable_irqs();
}
#endif
/*
* Scheduler clock - returns current time in nanosec units.
*
* Note: mulhdu(a, b) (multiply high double unsigned) returns
* the high 64 bits of a * b, i.e. (a * b) >> 64, where a and b
* are 64-bit unsigned numbers.
*/
unsigned long long sched_clock(void)
{
if (__USE_RTC())
return get_rtc();
return mulhdu(get_tb() - boot_tb, tb_to_ns_scale) << tb_to_ns_shift;
}
#ifdef CONFIG_PPC_PSERIES
/*
* Running clock - attempts to give a view of time passing for a virtualised
* kernels.
* Uses the VTB register if available otherwise a next best guess.
*/
unsigned long long running_clock(void)
{
/*
* Don't read the VTB as a host since KVM does not switch in host
* timebase into the VTB when it takes a guest off the CPU, reading the
* VTB would result in reading 'last switched out' guest VTB.
*
* Host kernels are often compiled with CONFIG_PPC_PSERIES checked, it
* would be unsafe to rely only on the #ifdef above.
*/
if (<API key>(FW_FEATURE_LPAR) &&
cpu_has_feature(CPU_FTR_ARCH_207S))
return mulhdu(get_vtb() - boot_tb, tb_to_ns_scale) << tb_to_ns_shift;
/*
* This is a next best approximation without a VTB.
* On a host which is running bare metal there should never be any stolen
* time and on a host which doesn't do any virtualisation TB *should* equal
* VTB so it makes no difference anyway.
*/
return local_clock() - cputime_to_nsecs(kcpustat_this_cpu->cpustat[CPUTIME_STEAL]);
}
#endif
static int __init get_freq(char *name, int cells, unsigned long *val)
{
struct device_node *cpu;
const __be32 *fp;
int found = 0;
/* The cpu node should have timebase and clock frequency properties */
cpu = <API key>(NULL, "cpu");
if (cpu) {
fp = of_get_property(cpu, name, NULL);
if (fp) {
found = 1;
*val = of_read_ulong(fp, cells);
}
of_node_put(cpu);
}
return found;
}
void <API key>(void)
{
#if defined(CONFIG_BOOKE) || defined(CONFIG_40x)
/* Clear any pending timer interrupts */
mtspr(SPRN_TSR, TSR_ENW | TSR_WIS | TSR_DIS | TSR_FIS);
/* Enable decrementer interrupt */
mtspr(SPRN_TCR, TCR_DIE);
#endif /* defined(CONFIG_BOOKE) || defined(CONFIG_40x) */
}
void __init <API key>(void)
{
ppc_tb_freq = DEFAULT_TB_FREQ; /* hardcoded default */
if (!get_freq("ibm,<API key>", 2, &ppc_tb_freq) &&
!get_freq("timebase-frequency", 1, &ppc_tb_freq)) {
printk(KERN_ERR "WARNING: Estimating decrementer frequency "
"(not found)\n");
}
ppc_proc_freq = DEFAULT_PROC_FREQ; /* hardcoded default */
if (!get_freq("ibm,<API key>", 2, &ppc_proc_freq) &&
!get_freq("clock-frequency", 1, &ppc_proc_freq)) {
printk(KERN_ERR "WARNING: Estimating processor frequency "
"(not found)\n");
}
}
int <API key>(struct timespec now)
{
struct rtc_time tm;
if (!ppc_md.set_rtc_time)
return -ENODEV;
to_tm(now.tv_sec + 1 + timezone_offset, &tm);
tm.tm_year -= 1900;
tm.tm_mon -= 1;
return ppc_md.set_rtc_time(&tm);
}
static void <API key>(struct timespec *ts)
{
struct rtc_time tm;
static int first = 1;
ts->tv_nsec = 0;
/* XXX this is a litle fragile but will work okay in the short term */
if (first) {
first = 0;
if (ppc_md.time_init)
timezone_offset = ppc_md.time_init();
/* get_boot_time() isn't guaranteed to be safe to call late */
if (ppc_md.get_boot_time) {
ts->tv_sec = ppc_md.get_boot_time() - timezone_offset;
return;
}
}
if (!ppc_md.get_rtc_time) {
ts->tv_sec = 0;
return;
}
ppc_md.get_rtc_time(&tm);
ts->tv_sec = mktime(tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec);
}
void <API key>(struct timespec *ts)
{
<API key>(ts);
/* Sanitize it in case real time clock is set below EPOCH */
if (ts->tv_sec < 0) {
ts->tv_sec = 0;
ts->tv_nsec = 0;
}
}
/* clocksource code */
static cycle_t rtc_read(struct clocksource *cs)
{
return (cycle_t)get_rtc();
}
static cycle_t timebase_read(struct clocksource *cs)
{
return (cycle_t)get_tb();
}
void update_vsyscall_old(struct timespec *wall_time, struct timespec *wtm,
struct clocksource *clock, u32 mult)
{
u64 new_tb_to_xs, new_stamp_xsec;
u32 frac_sec;
if (clock != &<API key>)
return;
/* Make userspace gettimeofday spin until we're done. */
++vdso_data->tb_update_count;
smp_mb();
/* 19342813113834067 ~= 2^(20+64) / 1e9 */
new_tb_to_xs = (u64) mult * (<API key> >> clock->shift);
new_stamp_xsec = (u64) wall_time->tv_nsec * XSEC_PER_SEC;
do_div(new_stamp_xsec, 1000000000);
new_stamp_xsec += (u64) wall_time->tv_sec * XSEC_PER_SEC;
BUG_ON(wall_time->tv_nsec >= NSEC_PER_SEC);
/* this is tv_nsec / 1e9 as a 0.32 fraction */
frac_sec = ((u64) wall_time->tv_nsec * 18446744073ULL) >> 32;
/*
* tb_update_count is used to allow the userspace gettimeofday code
* to assure itself that it sees a consistent view of the tb_to_xs and
* stamp_xsec variables. It reads the tb_update_count, then reads
* tb_to_xs and stamp_xsec and then reads tb_update_count again. If
* the two values of tb_update_count match and are even then the
* tb_to_xs and stamp_xsec values are consistent. If not, then it
* loops back and reads them again until this criteria is met.
* We expect the caller to have done the first increment of
* vdso_data->tb_update_count already.
*/
vdso_data->tb_orig_stamp = clock->cycle_last;
vdso_data->stamp_xsec = new_stamp_xsec;
vdso_data->tb_to_xs = new_tb_to_xs;
vdso_data->wtom_clock_sec = wtm->tv_sec;
vdso_data->wtom_clock_nsec = wtm->tv_nsec;
vdso_data->stamp_xtime = *wall_time;
vdso_data->stamp_sec_fraction = frac_sec;
smp_wmb();
++(vdso_data->tb_update_count);
}
void update_vsyscall_tz(void)
{
vdso_data->tz_minuteswest = sys_tz.tz_minuteswest;
vdso_data->tz_dsttime = sys_tz.tz_dsttime;
}
static void __init clocksource_init(void)
{
struct clocksource *clock;
if (__USE_RTC())
clock = &clocksource_rtc;
else
clock = &<API key>;
if (<API key>(clock, tb_ticks_per_sec)) {
printk(KERN_ERR "clocksource: %s is already registered\n",
clock->name);
return;
}
printk(KERN_INFO "clocksource: %s mult[%x] shift[%d] registered\n",
clock->name, clock->mult, clock->shift);
}
static int <API key>(unsigned long evt,
struct clock_event_device *dev)
{
__get_cpu_var(<API key>) = get_tb_or_rtc() + evt;
set_dec(evt);
/* We may have raced with new irq work */
if (<API key>())
set_dec(1);
return 0;
}
static void <API key>(enum clock_event_mode mode,
struct clock_event_device *dev)
{
if (mode != <API key>)
<API key>(DECREMENTER_MAX, dev);
}
/* Interrupt handler for the timer broadcast IPI */
void <API key>(void)
{
u64 *next_tb = &__get_cpu_var(<API key>);
*next_tb = get_tb_or_rtc();
__timer_interrupt();
}
static void <API key>(int cpu)
{
struct clock_event_device *dec = &per_cpu(decrementers, cpu);
*dec = <API key>;
dec->cpumask = cpumask_of(cpu);
printk_once(KERN_DEBUG "clockevent: %s mult[%x] shift[%d] cpu[%d]\n",
dec->name, dec->mult, dec->shift, cpu);
<API key>(dec);
}
static void __init <API key>(void)
{
int cpu = smp_processor_id();
<API key>(&<API key>, ppc_tb_freq, 4);
<API key>.max_delta_ns =
clockevent_delta2ns(DECREMENTER_MAX, &<API key>);
<API key>.min_delta_ns =
clockevent_delta2ns(2, &<API key>);
<API key>(cpu);
}
void <API key>(void)
{
/* Start the decrementer on CPUs that have manual control
* such as BookE
*/
<API key>();
/* FIME: Should make unrelatred change to move snapshot_timebase
* call here ! */
<API key>(smp_processor_id());
}
/* This function is only called on the boot processor */
void __init time_init(void)
{
struct div_result res;
u64 scale;
unsigned shift;
if (__USE_RTC()) {
/* 601 processor: dec counts down by 128 every 128ns */
ppc_tb_freq = 1000000000;
} else {
/* Normal PowerPC with timebase register */
ppc_md.calibrate_decr();
printk(KERN_DEBUG "time_init: decrementer frequency = %lu.%.6lu MHz\n",
ppc_tb_freq / 1000000, ppc_tb_freq % 1000000);
printk(KERN_DEBUG "time_init: processor frequency = %lu.%.6lu MHz\n",
ppc_proc_freq / 1000000, ppc_proc_freq % 1000000);
}
tb_ticks_per_jiffy = ppc_tb_freq / HZ;
tb_ticks_per_sec = ppc_tb_freq;
tb_ticks_per_usec = ppc_tb_freq / 1000000;
<API key>();
<API key>();
/*
* Compute scale factor for sched_clock.
* The calibrate_decr() function has set tb_ticks_per_sec,
* which is the timebase frequency.
* We compute 1e9 * 2^64 / tb_ticks_per_sec and interpret
* the 128-bit result as a 64.64 fixed-point number.
* We then shift that number right until it is less than 1.0,
* giving us the scale factor and shift count to use in
* sched_clock().
*/
div128_by_32(1000000000, 0, tb_ticks_per_sec, &res);
scale = res.result_low;
for (shift = 0; res.result_high != 0; ++shift) {
scale = (scale >> 1) | (res.result_high << 63);
res.result_high >>= 1;
}
tb_to_ns_scale = scale;
tb_to_ns_shift = shift;
/* Save the current timebase to pretty up CONFIG_PRINTK_TIME */
boot_tb = get_tb_or_rtc();
/* If platform provided a timezone (pmac), we correct the time */
if (timezone_offset) {
sys_tz.tz_minuteswest = -timezone_offset / 60;
sys_tz.tz_dsttime = 0;
}
vdso_data->tb_update_count = 0;
vdso_data->tb_ticks_per_sec = tb_ticks_per_sec;
/* Start the decrementer on CPUs that have manual control
* such as BookE
*/
<API key>();
/* Register the clocksource */
clocksource_init();
<API key>();
<API key>();
}
#define FEBRUARY 2
#define STARTOFTIME 1970
#define SECDAY 86400L
#define SECYR (SECDAY * 365)
#define leapyear(year) ((year) % 4 == 0 && \
((year) % 100 != 0 || (year) % 400 == 0))
#define days_in_year(a) (leapyear(a) ? 366 : 365)
#define days_in_month(a) (month_days[(a) - 1])
static int month_days[12] = {
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
/*
* This only works for the Gregorian calendar - i.e. after 1752 (in the UK)
*/
void GregorianDay(struct rtc_time * tm)
{
int leapsToDate;
int lastYear;
int day;
int MonthOffset[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
lastYear = tm->tm_year - 1;
/*
* Number of leap corrections to apply up to end of last year
*/
leapsToDate = lastYear / 4 - lastYear / 100 + lastYear / 400;
/*
* This year is a leap year if it is divisible by 4 except when it is
* divisible by 100 unless it is divisible by 400
*
* e.g. 1904 was a leap year, 1900 was not, 1996 is, and 2000 was
*/
day = tm->tm_mon > 2 && leapyear(tm->tm_year);
day += lastYear*365 + leapsToDate + MonthOffset[tm->tm_mon-1] +
tm->tm_mday;
tm->tm_wday = day % 7;
}
void to_tm(int tim, struct rtc_time * tm)
{
register int i;
register long hms, day;
day = tim / SECDAY;
hms = tim % SECDAY;
/* Hours, minutes, seconds are easy */
tm->tm_hour = hms / 3600;
tm->tm_min = (hms % 3600) / 60;
tm->tm_sec = (hms % 3600) % 60;
/* Number of years in days */
for (i = STARTOFTIME; day >= days_in_year(i); i++)
day -= days_in_year(i);
tm->tm_year = i;
/* Number of months in days left */
if (leapyear(tm->tm_year))
days_in_month(FEBRUARY) = 29;
for (i = 1; day >= days_in_month(i); i++)
day -= days_in_month(i);
days_in_month(FEBRUARY) = 28;
tm->tm_mon = i;
/* Days are what is left over (+1) from all that. */
tm->tm_mday = day + 1;
/*
* Determine the day of week
*/
GregorianDay(tm);
}
/*
* Divide a 128-bit dividend by a 32-bit divisor, leaving a 128 bit
* result.
*/
void div128_by_32(u64 dividend_high, u64 dividend_low,
unsigned divisor, struct div_result *dr)
{
unsigned long a, b, c, d;
unsigned long w, x, y, z;
u64 ra, rb, rc;
a = dividend_high >> 32;
b = dividend_high & 0xffffffff;
c = dividend_low >> 32;
d = dividend_low & 0xffffffff;
w = a / divisor;
ra = ((u64)(a - (w * divisor)) << 32) + b;
rb = ((u64) do_div(ra, divisor) << 32) + c;
x = ra;
rc = ((u64) do_div(rb, divisor) << 32) + d;
y = rb;
do_div(rc, divisor);
z = rc;
dr->result_high = ((u64)w << 32) + x;
dr->result_low = ((u64)y << 32) + z;
}
/* We don't need to calibrate delay, we use the CPU timebase for that */
void calibrate_delay(void)
{
/* Some generic code (such as spinlock debug) use loops_per_jiffy
* as the number of __delay(1) in a jiffy, so make it so
*/
loops_per_jiffy = tb_ticks_per_jiffy;
}
static int __init rtc_init(void)
{
struct platform_device *pdev;
if (!ppc_md.get_rtc_time)
return -ENODEV;
pdev = <API key>("rtc-generic", -1, NULL, 0);
return PTR_ERR_OR_ZERO(pdev);
}
module_init(rtc_init); |
<?php
$IdFaq=70;$lang="pl";require_once "publicfaq.php";
?> |
'use strict';
import * as UIkit from 'uikit3';
export class Upload {
private options = {
'url': '',
'multiple': true,
};
public static bootstrap() {
$(".js-upload").each(function() {
let upload = new Upload();
upload.init(this);
});
}
private init(ele) {
let self = this;
let $element = $(ele);
self.options = $.extend(self.options, $element.data('upload-options'));
let progressBar: any = $element.parent().find('progress.uk-progress').get(0);
UIkit.upload($element, {
url: self.options.url,
multiple: self.options.multiple,
beforeSend: function (environment) {
console.log('beforeSend', arguments);
// The environment object can still be modified here.
// var {data, method, headers, xhr, responseType} = environment;
},
beforeAll: function () {
console.log('beforeAll', arguments);
},
load: function () {
console.log('load', arguments);
},
error: function () {
console.log('error', arguments);
},
complete: function () {
console.log('complete', arguments);
},
loadStart: function (e) {
console.log('loadStart', arguments);
progressBar.removeAttribute('hidden');
progressBar.max = e.total;
progressBar.value = e.loaded;
},
progress: function (e) {
// percent = Math.ceil(percent);
console.log('progress', arguments);
progressBar.max = e.total;
progressBar.value = e.loaded;
},
loadEnd: function (e) {
console.log('loadEnd', arguments);
progressBar.max = e.total;
progressBar.value = e.loaded;
},
completeAll: function () {
console.log('completeAll', arguments);
setTimeout(function () {
progressBar.setAttribute('hidden', 'hidden');
}, 1000);
alert('Upload Completed');
}
});
}
}
// defaults: {
// path: '',
// settings: {
// allow: '*.*'
// errorMessage: '',
// noFileIdsMessage: '',
// init: function() {
// let $this = this;
// let $progressbar = $($this.element).parentsUntil('.uk-placeholder').parent().siblings('.uk-progress').first();
// let $bar = $progressbar.find('.uk-progress-bar');
// let elementSettings = {
// action: $this.options.path,
// single: false,
// allcomplete: function(response, xhr) {
// if (xhr.status != 200) {
// this.onError();
// } else {
// $bar.css("width", "100%").text("100%");
// setTimeout(function(){
// $progressbar.addClass("uk-hidden");
// }, 250);
// let responseData = JSON.parse(response);
// if (responseData['userImage']) {
// $('#<API key>').attr('src', responseData['userImage'] + '?' + Math.random());
// } else if (responseData['base64']) {
// let $form = $($this.element).closest('form');
// let prototypeNode = $form.find('div[data-prototype]');
// let prototype = prototypeNode.data('prototype');
// let index = prototypeNode.find(':input[type="checkbox"]').length;
// for (let key in responseData['base64']) {
// let indexedPrototype = prototype.replace(/__name__/g, index);
// let prototypeInputNode = $(indexedPrototype).find(':input');
// prototypeInputNode.attr('checked', 'checked');
// prototypeInputNode.val(responseData['base64'][key]['content']);
// let labelNode = $('<label class="uk-form-label"></label>')
// .attr('for', $form.attr('name') + '_base64' + index + '_checked')
// .html(responseData['base64'][key]['filename']);
// index++;
// let formControlNode = $('<div class="uk-form-controls"></div>')
// .append(prototypeInputNode);
// prototypeNode
// .append(formControlNode)
// .append(labelNode);
// if (responseData['base64'].length == 0) {
// UIkit.notify($this.options.noFileIdsMessage, 'danger');
// } else if (responseData['fileIds']) {
// let prototypeNode = $('form[name="upload"] div[data-prototype]');
// let prototype = prototypeNode.data('prototype');
// let index = prototypeNode.find(':input[type="checkbox"]').length;
// for (let key in responseData['fileIds']) {
// let indexedPrototype = prototype.replace(/__name__/g, index);
// let prototypeInputNode = $(indexedPrototype).find(':input');
// prototypeInputNode.attr('checked', 'checked');
// prototypeInputNode.val(key);
// let labelNode = $('<label class="uk-form-label"></label>')
// .attr('for', 'upload_files_' + index + '_checked')
// .html(responseData['fileIds'][key]);
// index++;
// let formControlNode = $('<div class="uk-form-controls"></div>')
// .append(prototypeInputNode);
// prototypeNode
// .append(formControlNode)
// .append(labelNode);
// if (responseData['fileIds'].length == 0) {
// UIkit.notify($this.options.noFileIdsMessage, 'danger');
// error: function(event) {
// this.onError();
// onError: function() {
// $bar.css("width", "100%").text("100%");
// setTimeout(function(){
// $progressbar.addClass("uk-hidden");
// }, 250);
// UIkit.notify($this.options.errorMessage, 'danger');
// let merged = $.extend($this.options.settings, elementSettings);
// let select = UI.uploadSelect($this.element, merged);
// let drop = UI.uploadDrop($($this.element).parentsUntil('.uk-placeholder').parent(), merged); |
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http:
<head>
<title>Identifier Index</title>
<link rel="stylesheet" href="epydoc.css" type="text/css" />
<script type="text/javascript" src="epydoc.js"></script>
</head>
<body bgcolor="white" text="black" link="blue" vlink="#204080"
alink="#204080">
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Home link -->
<th> <a
href="gluon-module.html">Home</a> </th>
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th bgcolor="#70b0f0" class="navbar-select"
> Indices </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center"
><a class="navbar" target="_top" href="http:
</tr></table></th>
</tr>
</table>
<table width="100%" cellpadding="0" cellspacing="0">
<tr valign="top">
<td width="100%"> </td>
<td>
<table cellpadding="0" cellspacing="0">
<!-- hide/show private -->
<tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink"
onclick="toggle_private();">hide private</a>]</span></td></tr>
<tr><td align="right"><span class="options"
>[<a href="frames.html" target="_top">frames</a
>] | <a href="identifier-index-Y.html"
target="_top">no frames</a>]</span></td></tr>
</table>
</td>
</tr>
</table>
<table border="0" width="100%">
<tr valign="bottom"><td>
<h1 class="epydoc">Identifier Index</h1>
</td><td>
[
<a href="identifier-index-A.html">A</a>
<a href="identifier-index-B.html">B</a>
<a href="identifier-index-C.html">C</a>
<a href="identifier-index-D.html">D</a>
<a href="identifier-index-E.html">E</a>
<a href="identifier-index-F.html">F</a>
<a href="identifier-index-G.html">G</a>
<a href="identifier-index-H.html">H</a>
<a href="identifier-index-I.html">I</a>
<a href="identifier-index-J.html">J</a>
<a href="identifier-index-K.html">K</a>
<a href="identifier-index-L.html">L</a>
<a href="identifier-index-M.html">M</a>
<a href="identifier-index-N.html">N</a>
<a href="identifier-index-O.html">O</a>
<a href="identifier-index-P.html">P</a>
<a href="identifier-index-Q.html">Q</a>
<a href="identifier-index-R.html">R</a>
<a href="identifier-index-S.html">S</a>
<a href="identifier-index-T.html">T</a>
<a href="identifier-index-U.html">U</a>
<a href="identifier-index-V.html">V</a>
<a href="identifier-index-W.html">W</a>
<a href="identifier-index-X.html">X</a>
<a href="identifier-index-Y.html">Y</a>
<a href="identifier-index-Z.html">Z</a>
<a href="identifier-index-_.html">_</a>
]
</td></table>
<table border="0" width="100%">
<tr valign="top"><td valign="top" width="1%"><h2 class="epydoc"><a name="Y">Y</a></h2></td>
<td valign="top">
<table class="link-index" width="100%" border="1">
<tr>
<td width="33%" class="link-index"><a href="gluon.serializers-module.html#yaml">yaml()</a><br />
<span class="index-where">(in <a href="gluon.serializers-module.html" onclick="show_private();">gluon.serializers</a>)</span></td>
<td width="33%" class="link-index"><a href="gluon.dal.Expression-class.html#year">year()</a><br />
<span class="index-where">(in <a href="gluon.dal.Expression-class.html" onclick="show_private();">Expression</a>)</span></td>
<td width="33%" class="link-index"> </td>
</tr>
<tr><td class="link-index"> </td><td class="link-index"> </td><td class="link-index"> </td></tr>
</table>
</td></tr>
</table>
<br /><br />
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Home link -->
<th> <a
href="gluon-module.html">Home</a> </th>
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th bgcolor="#70b0f0" class="navbar-select"
> Indices </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center"
><a class="navbar" target="_top" href="http:
</tr></table></th>
</tr>
</table>
<table border="0" cellpadding="0" cellspacing="0" width="100%%">
<tr>
<td align="left" class="footer">
Generated by Epydoc 3.0.1 on Sun Mar 16 02:36:08 2014
</td>
<td align="right" class="footer">
<a target="mainFrame" href="http://epydoc.sourceforge.net"
>http://epydoc.sourceforge.net</a>
</td>
</tr>
</table>
<script type="text/javascript">
<!
// Private objects are initially displayed (because if
// javascript is turned off then we want them to be
// visible); but by default, we want to hide them. So hide
// them unless we have a cookie that says to show them.
checkCookie();
</script>
</body>
</html> |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DevExpress.Data.Filtering;
using Vinabits_OM_2017.Module.BusinessObjects;
using DevExpress.ExpressApp;
namespace Vinabits_OM_2017.Module.<API key>
{
class <API key> : <API key>
{
public const string OperatorName = "<API key>";
public string Name
{
get { return OperatorName; }
}
public object Evaluate(params object[] operands)
{
bool ret = false;
Employee emp = null;
if (SecuritySystem.CurrentUser != null)
{
emp = (Employee)SecuritySystem.CurrentUser;
}
else if (SecuritySystem.CurrentUserId != null)
{
emp = SecuritySystem.LogonObjectSpace.FindObject<Employee>(new BinaryOperator("Oid", SecuritySystem.CurrentUserId));
}
if (emp != null)
{
foreach (EmployeeRole er in emp.EmployeeRoles)
{
if (er.Name == "Root") { ret = true; }
}
}
return ret;
}
public Type ResultType(params Type[] operands)
{
return typeof(bool);
}
static <API key>()
{
<API key> instance = new <API key>();
if (CriteriaOperator.GetCustomFunction(instance.Name) == null)
{
CriteriaOperator.<API key>(instance);
}
}
public static void Register()
{
}
}
} |
<?php require (__DIR__.'/../utils/utils.php') ?>
<?php
class TabellinoBusiness {
/*
* Restituisce le formazioni/tabellino della giornata richiesta
*/
public function <API key>($partita, $giornata, $giocata) {
$tabellino = array();
if ($giocata == 0) {
$lines = file(host . js_folder . str_replace('XXX', $giornata, formazioni_file));
foreach($lines as $line_num => $line) {
if (strpos($line,'new Z') !== false) {
$riga = explode(",", $line);
if (substr($riga[0], strpos($riga[0], '(') + 1) == $partita) {
$nom = new RigaFormazione();
$nom->partita = $partita;
$nom->codice = $riga[3];
$nom->nome = ImdbUtils::getPlayerNameByCode($riga[3]);
$nom->nomeAbbreviato = ImdbUtils::getNomeAbbreviato($nom->nome);
$nom->squadra = $riga[1];
$nom->squadraDiA = ImdbUtils::getPlayerNameByCode($riga[4]);
$nom->ruolo = $riga[5];
$nom->ruoloGiocatore = ImdbUtils::getPlayerRoleByCode($riga[3]);
$nom->titolare = $riga[6];
array_push($tabellino, $nom);
}
}
}
} else {
$lines = file(host . js_folder . str_replace('XXX', $giornata, tabellini_file));
foreach($lines as $line_num => $line) {
if (strpos($line,'new T') !== false) {
$riga = explode(",", $line);
if (substr($riga[0], strpos($riga[0], '(') + 1) == $partita) {
$codiciGiocatori = explode("%", $riga[3]);
$squadreGiocatori = explode("%", $riga[4]);
$ruoliGiocatori = explode("%", $riga[5]);
$votiGiocatori = explode("%", $riga[6]);
$bonusMalusGiocatori = explode("%", $riga[7]);
$totGiocatori = explode("%", $riga[8]);
for ($i = 0; $i < 19; $i++) {
$nom = new RigaFormazione();
$nom->partita = $partita;
$nom->squadra = $riga[1];
$nom->codice = 'xg' . str_replace('"', '', $codiciGiocatori[$i]);
$nom->nome = ImdbUtils::getPlayerNameByCode($nom->codice);
$nom->nomeAbbreviato = ImdbUtils::getNomeAbbreviato($nom->nome);
$nom->squadraDiA = ImdbUtils::getPlayerNameByCode('xa' . str_replace('"', '', $squadreGiocatori[$i]));
$nom->ruolo = str_replace('"', '', $ruoliGiocatori[$i]);
$nom->ruoloGiocatore = ImdbUtils::getPlayerRoleByCode(str_replace('"', '', $codiciGiocatori[$i]));
$nom->voto = str_replace('"', '', $votiGiocatori[$i]);
$nom->bonusMalus = str_replace('"', '', $bonusMalusGiocatori[$i]);
$nom->votoTotale = str_replace('"', '', $totGiocatori[$i]);
$nom->titolare = $i < 11 ? "0" : "1";
array_push($tabellino, $nom);
}
}
}
}
}
return json_encode($tabellino);
}
} |
"""Emit a message for iteration through dict keys and subscripting dict with key."""
# pylint: disable=line-too-long,missing-docstring,<API key>,<API key>,<API key>,use-dict-literal,<API key>
def bad():
a_dict = {1: 1, 2: 2, 3: 3}
for k in a_dict: # [<API key>]
print(a_dict[k])
another_dict = dict()
for k in another_dict: # [<API key>]
print(another_dict[k])
def good():
a_dict = {1: 1, 2: 2, 3: 3}
for k in a_dict:
print(k)
out_of_scope_dict = dict()
def another_bad():
for k in out_of_scope_dict: # [<API key>]
print(out_of_scope_dict[k])
def another_good():
for k in out_of_scope_dict:
k = 1
k = 2
k = 3
print(out_of_scope_dict[k])
b_dict = {}
for k2 in b_dict: # Should not emit warning, key access necessary
b_dict[k2] = 2
for k2 in b_dict: # Should not emit warning, key access necessary (AugAssign)
b_dict[k2] += 2
# Warning should be emitted in this case
for k6 in b_dict: # [<API key>]
val = b_dict[k6]
b_dict[k6] = 2
for k3 in b_dict: # [<API key>]
val = b_dict[k3]
for k4 in b_dict.keys(): # [<API key>,<API key>]
val = b_dict[k4]
class Foo:
c_dict = {}
# Should emit warning when iterating over a dict attribute of a class
for k5 in Foo.c_dict: # [<API key>]
val = Foo.c_dict[k5]
c_dict = {}
# Should NOT emit warning whey key used to access a different dict
for k5 in Foo.c_dict: # This is fine
val = b_dict[k5]
for k5 in Foo.c_dict: # This is fine
val = c_dict[k5]
# Should emit warning within a list/dict comprehension
val = {k9: b_dict[k9] for k9 in b_dict} # [<API key>]
val = [(k7, b_dict[k7]) for k7 in b_dict] # [<API key>]
# Should emit warning even when using dict attribute of a class within comprehension
val = [(k7, Foo.c_dict[k7]) for k7 in Foo.c_dict] # [<API key>]
val = any(True for k8 in Foo.c_dict if Foo.c_dict[k8]) # [<API key>]
# Should emit warning when dict access done in ``if`` portion of comprehension
val = any(True for k8 in b_dict if b_dict[k8]) # [<API key>]
# Should NOT emit warning whey key used to access a different dict
val = [(k7, b_dict[k7]) for k7 in Foo.c_dict]
val = any(True for k8 in Foo.c_dict if b_dict[k8])
# Should NOT emit warning, essentially same check as above
val = [(k7, c_dict[k7]) for k7 in Foo.c_dict]
val = any(True for k8 in Foo.c_dict if c_dict[k8])
# Should emit warning, using .keys() of Foo.c_dict
val = any(True for k8 in Foo.c_dict.keys() if Foo.c_dict[k8]) # [<API key>,<API key>]
# Test false positive described in #4630
d = {'key': 'value'}
for k in d: # this is fine, with the reassignment of d[k], d[k] is necessary
d[k] += '123'
if '1' in d[k]: # index lookup necessary here, do not emit error
print('found 1')
for k in d: # if this gets rewritten to d.items(), we are back to the above problem
d[k] = d[k] + 1
if '1' in d[k]: # index lookup necessary here, do not emit error
print('found 1')
for k in d: # [<API key>]
if '1' in d[k]: # index lookup necessary here, do not emit error
print('found 1') |
#include <Ice/ConnectionFactory.h>
#include <Ice/ConnectionI.h>
#include <Ice/Instance.h>
#include <Ice/LoggerUtil.h>
#include <Ice/TraceLevels.h>
#include <Ice/<API key>.h>
#include <Ice/Properties.h>
#include <Ice/Transceiver.h>
#include <Ice/Connector.h>
#include <Ice/Acceptor.h>
#include <Ice/ThreadPool.h>
#include <Ice/ObjectAdapterI.h> // For getThreadPool().
#include <Ice/Reference.h>
#include <Ice/EndpointI.h>
#include <Ice/RouterInfo.h>
#include <Ice/LocalException.h>
#include <Ice/Functional.h>
#include <IceUtil/Random.h>
#include <iterator>
using namespace std;
using namespace Ice;
using namespace Ice::Instrumentation;
using namespace IceInternal;
IceUtil::Shared* IceInternal::upCast(<API key>* p) { return p; }
IceUtil::Shared* IceInternal::upCast(<API key>* p) { return p; }
namespace
{
struct <API key> : public std::unary_function<ptrdiff_t, ptrdiff_t>
{
ptrdiff_t operator()(ptrdiff_t d)
{
return IceUtilInternal::random(static_cast<int>(d));
}
};
template <typename K, typename V> void
remove(multimap<K, V>& m, K k, V v)
{
pair<typename multimap<K, V>::iterator, typename multimap<K, V>::iterator> pr = m.equal_range(k);
assert(pr.first != pr.second);
for(typename multimap<K, V>::iterator q = pr.first; q != pr.second; ++q)
{
if(q->second.get() == v.get())
{
m.erase(q);
return;
}
}
assert(false); // Nothing was removed which is an error.
}
template <typename K, typename V> ::IceInternal::Handle<V>
find(const multimap<K,::IceInternal::Handle<V> >& m,
K k,
const ::IceUtilInternal::ConstMemFun<bool, V, ::IceInternal::Handle<V> >& predicate)
{
pair<typename multimap<K, ::IceInternal::Handle<V> >::const_iterator,
typename multimap<K, ::IceInternal::Handle<V> >::const_iterator> pr = m.equal_range(k);
for(typename multimap<K, ::IceInternal::Handle<V> >::const_iterator q = pr.first; q != pr.second; ++q)
{
if(predicate(q->second))
{
return q->second;
}
}
return IceInternal::Handle<V>();
}
}
bool
IceInternal::<API key>::ConnectorInfo::operator==(const ConnectorInfo& other) const
{
return connector == other.connector;
}
void
IceInternal::<API key>::destroy()
{
IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this);
if(_destroyed)
{
return;
}
for_each(_connections.begin(), _connections.end(),
bind2nd(Ice::secondVoidMemFun1<const ConnectorPtr, ConnectionI, ConnectionI::DestructionReason>
(&ConnectionI::destroy), ConnectionI::<API key>));
_destroyed = true;
_communicator = 0;
notifyAll();
}
void
IceInternal::<API key>::<API key>()
{
IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this);
for_each(_connections.begin(), _connections.end(),
Ice::secondVoidMemFun<const ConnectorPtr, ConnectionI>(&ConnectionI::updateObserver));
}
void
IceInternal::<API key>::waitUntilFinished()
{
multimap<ConnectorPtr, ConnectionIPtr> connections;
{
IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this);
// First we wait until the factory is destroyed. We also wait
// until there are no pending connections anymore. Only then
// we can be sure the _connections contains all connections.
while(!_destroyed || !_pending.empty() || <API key> > 0)
{
wait();
}
// We want to wait until all connections are finished outside the
// thread synchronization.
connections = _connections;
}
for_each(connections.begin(), connections.end(),
Ice::secondVoidMemFun<const ConnectorPtr, ConnectionI>(&ConnectionI::waitUntilFinished));
{
IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this);
// Ensure all the connections are finished and reapable at this point.
vector<Ice::ConnectionIPtr> cons;
_reaper->swapConnections(cons);
assert(cons.size() == _connections.size());
cons.clear();
_connections.clear();
<API key>.clear();
}
}
ConnectionIPtr
IceInternal::<API key>::create(const vector<EndpointIPtr>& endpts, bool hasMore,
Ice::<API key> selType, bool& compress)
{
assert(!endpts.empty());
// Apply the overrides.
vector<EndpointIPtr> endpoints = applyOverrides(endpts);
// Try to find a connection to one of the given endpoints.
Ice::ConnectionIPtr connection = findConnection(endpoints, compress);
if(connection)
{
return connection;
}
IceUtil::UniquePtr<Ice::LocalException> exception;
// If we didn't find a connection with the endpoints, we create the connectors
// for the endpoints.
vector<ConnectorInfo> connectors;
for(vector<EndpointIPtr>::const_iterator p = endpoints.begin(); p != endpoints.end(); ++p)
{
// Create connectors for the endpoint.
try
{
vector<ConnectorPtr> cons = (*p)->connectors(selType);
assert(!cons.empty());
for(vector<ConnectorPtr>::const_iterator r = cons.begin(); r != cons.end(); ++r)
{
assert(*r);
connectors.push_back(ConnectorInfo(*r, *p));
}
}
catch(const Ice::LocalException& ex)
{
exception.reset(ex.ice_clone());
handleException(ex, hasMore || p != endpoints.end() - 1);
}
}
if(connectors.empty())
{
assert(exception.get());
exception->ice_throw();
}
// Try to get a connection to one of the connectors. A null result indicates that no
// connection was found and that we should try to establish the connection (and that
// the connectors were added to _pending to prevent other threads from establishing
// the connection).
connection = getConnection(connectors, 0, compress);
if(connection)
{
return connection;
}
// Try to establish the connection to the connectors.
<API key> <API key> = _instance-><API key>();
const <API key>& obsv = _instance->initializationData().observer;
vector<ConnectorInfo>::const_iterator q;
for(q = connectors.begin(); q != connectors.end(); ++q)
{
ObserverPtr observer;
if(obsv)
{
observer = obsv-><API key>(q->endpoint, q->connector->toString());
if(observer)
{
observer->attach();
}
}
try
{
connection = createConnection(q->connector->connect(), *q);
connection->start(0);
if(observer)
{
observer->detach();
}
if(<API key>->overrideCompress)
{
compress = <API key>-><API key>;
}
else
{
compress = q->endpoint->compress();
}
connection->activate();
break;
}
catch(const Ice::<API key>& ex)
{
if(observer)
{
observer->failed(ex.ice_name());
observer->detach();
}
exception.reset(ex.ice_clone());
<API key>(*exception.get(), hasMore || q != connectors.end() - 1);
connection = 0;
break; // No need to continue
}
catch(const Ice::LocalException& ex)
{
if(observer)
{
observer->failed(ex.ice_name());
observer->detach();
}
exception.reset(ex.ice_clone());
<API key>(*exception.get(), hasMore || q != connectors.end() - 1);
connection = 0;
}
}
// Finish creating the connection (this removes the connectors from the _pending
// list and notifies any waiting threads).
if(connection)
{
finishGetConnection(connectors, *q, connection, 0);
}
else
{
finishGetConnection(connectors, *exception.get(), 0);
}
if(!connection)
{
assert(exception.get());
exception->ice_throw();
}
return connection;
}
void
IceInternal::<API key>::create(const vector<EndpointIPtr>& endpts, bool hasMore,
Ice::<API key> selType,
const <API key>& callback)
{
assert(!endpts.empty());
// Apply the overrides.
vector<EndpointIPtr> endpoints = applyOverrides(endpts);
// Try to find a connection to one of the given endpoints.
try
{
bool compress;
Ice::ConnectionIPtr connection = findConnection(endpoints, compress);
if(connection)
{
callback->setConnection(connection, compress);
return;
}
}
catch(const Ice::LocalException& ex)
{
callback->setException(ex);
return;
}
ConnectCallbackPtr cb = new ConnectCallback(this, endpoints, hasMore, callback, selType);
cb->getConnectors();
}
void
IceInternal::<API key>::setRouterInfo(const RouterInfoPtr& routerInfo)
{
IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this);
if(_destroyed)
{
throw <API key>(__FILE__, __LINE__);
}
assert(routerInfo);
// Search for connections to the router's client proxy endpoints,
// and update the object adapter for such connections, so that
// callbacks from the router can be received over such
// connections.
ObjectAdapterPtr adapter = routerInfo->getAdapter();
vector<EndpointIPtr> endpoints = routerInfo->getClientEndpoints();
for(vector<EndpointIPtr>::const_iterator p = endpoints.begin(); p != endpoints.end(); ++p)
{
EndpointIPtr endpoint = *p;
// Modify endpoints with overrides.
if(_instance-><API key>()->overrideTimeout)
{
endpoint = endpoint->timeout(_instance-><API key>()-><API key>);
}
// The Connection object does not take the compression flag of
// endpoints into account, but instead gets the information
// about whether messages should be compressed or not from
// other sources. In order to allow connection sharing for
// endpoints that differ in the value of the compression flag
// only, we always set the compression flag to false here in
// this connection factory.
endpoint = endpoint->compress(false);
for(multimap<ConnectorPtr, ConnectionIPtr>::const_iterator q = _connections.begin();
q != _connections.end(); ++q)
{
if(q->second->endpoint() == endpoint)
{
q->second->setAdapter(adapter);
}
}
}
}
void
IceInternal::<API key>::removeAdapter(const ObjectAdapterPtr& adapter)
{
IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this);
if(_destroyed)
{
return;
}
for(multimap<ConnectorPtr, ConnectionIPtr>::const_iterator p = _connections.begin(); p != _connections.end(); ++p)
{
if(p->second->getAdapter() == adapter)
{
p->second->setAdapter(0);
}
}
}
void
IceInternal::<API key>::<API key>(const <API key>& outAsync)
{
list<ConnectionIPtr> c;
{
IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this);
for(multimap<ConnectorPtr, ConnectionIPtr>::const_iterator p = _connections.begin(); p != _connections.end();
++p)
{
if(p->second->isActiveOrHolding())
{
c.push_back(p->second);
}
}
}
for(list<ConnectionIPtr>::const_iterator p = c.begin(); p != c.end(); ++p)
{
try
{
outAsync->flushConnection(*p);
}
catch(const LocalException&)
{
// Ignore.
}
}
}
IceInternal::<API key>::<API key>(const CommunicatorPtr& communicator,
const InstancePtr& instance) :
_communicator(communicator),
_instance(instance),
_reaper(new ConnectionReaper()),
_destroyed(false),
<API key>(0)
{
}
IceInternal::<API key>::~<API key>()
{
assert(_destroyed);
assert(_connections.empty());
assert(<API key>.empty());
assert(_pending.empty());
assert(<API key> == 0);
}
vector<EndpointIPtr>
IceInternal::<API key>::applyOverrides(const vector<EndpointIPtr>& endpts)
{
<API key> <API key> = _instance-><API key>();
vector<EndpointIPtr> endpoints = endpts;
for(vector<EndpointIPtr>::iterator p = endpoints.begin(); p != endpoints.end(); ++p)
{
// Modify endpoints with overrides.
if(<API key>->overrideTimeout)
{
*p = (*p)->timeout(<API key>-><API key>);
}
}
return endpoints;
}
ConnectionIPtr
IceInternal::<API key>::findConnection(const vector<EndpointIPtr>& endpoints, bool& compress)
{
IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this);
if(_destroyed)
{
throw <API key>(__FILE__, __LINE__);
}
<API key> <API key> = _instance-><API key>();
assert(!endpoints.empty());
for(vector<EndpointIPtr>::const_iterator p = endpoints.begin(); p != endpoints.end(); ++p)
{
ConnectionIPtr connection = find(<API key>, *p, Ice::constMemFun(&ConnectionI::isActiveOrHolding));
if(connection)
{
if(<API key>->overrideCompress)
{
compress = <API key>-><API key>;
}
else
{
compress = (*p)->compress();
}
return connection;
}
}
return 0;
}
ConnectionIPtr
IceInternal::<API key>::findConnection(const vector<ConnectorInfo>& connectors, bool& compress)
{
// This must be called with the mutex locked.
<API key> <API key> = _instance-><API key>();
for(vector<ConnectorInfo>::const_iterator p = connectors.begin(); p != connectors.end(); ++p)
{
if(_pending.find(p->connector) != _pending.end())
{
continue;
}
ConnectionIPtr connection = find(_connections, p->connector, Ice::constMemFun(&ConnectionI::isActiveOrHolding));
if(connection)
{
if(<API key>->overrideCompress)
{
compress = <API key>-><API key>;
}
else
{
compress = p->endpoint->compress();
}
return connection;
}
}
return 0;
}
void
IceInternal::<API key>::<API key>()
{
// Keep track of the number of pending connects. The outgoing connection factory
// waitUntilFinished() method waits for all the pending connects to terminate before
// to return. This ensures that the communicator client thread pool isn't destroyed
// too soon and will still be available to execute the ice_exception() callbacks for
// the asynchronous requests waiting on a connection to be established.
IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this);
if(_destroyed)
{
throw Ice::<API key>(__FILE__, __LINE__);
}
++<API key>;
}
void
IceInternal::<API key>::<API key>()
{
IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this);
--<API key>;
assert(<API key> >= 0);
if(_destroyed && <API key> == 0)
{
notifyAll();
}
}
ConnectionIPtr
IceInternal::<API key>::getConnection(const vector<ConnectorInfo>& connectors,
const ConnectCallbackPtr& cb,
bool& compress)
{
{
IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this);
if(_destroyed)
{
throw Ice::<API key>(__FILE__, __LINE__);
}
// Reap closed connections
vector<Ice::ConnectionIPtr> cons;
_reaper->swapConnections(cons);
for(vector<Ice::ConnectionIPtr>::const_iterator p = cons.begin(); p != cons.end(); ++p)
{
remove(_connections, (*p)->connector(), *p);
remove(<API key>, (*p)->endpoint(), *p);
remove(<API key>, (*p)->endpoint()->compress(true), *p);
}
// Try to get the connection. We may need to wait for other threads to
// finish if one of them is currently establishing a connection to one
// of our connectors.
while(true)
{
if(_destroyed)
{
throw Ice::<API key>(__FILE__, __LINE__);
}
// Search for a matching connection. If we find one, we're done.
Ice::ConnectionIPtr connection = findConnection(connectors, compress);
if(connection)
{
return connection;
}
// Determine whether another thread/request is currently attempting to connect to
// one of our endpoints; if so we wait until it's done.
if(addToPending(cb, connectors))
{
// If a callback is not specified we wait until another thread notifies us about a
// change to the pending list. Otherwise, if a callback is provided we're done:
// when the pending list changes the callback will be notified and will try to
// get the connection again.
if(!cb)
{
wait();
}
else
{
return 0;
}
}
else
{
// If no thread is currently establishing a connection to one of our connectors,
// we get out of this loop and start the connection establishment to one of the
// given connectors.
break;
}
}
}
// At this point, we're responsible for establishing the connection to one of
// the given connectors. If it's a non-blocking connect, calling nextConnector
// will start the connection establishment. Otherwise, we return null to get
// the caller to establish the connection.
if(cb)
{
cb->nextConnector();
}
return 0;
}
ConnectionIPtr
IceInternal::<API key>::createConnection(const TransceiverPtr& transceiver, const ConnectorInfo& ci)
{
IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this);
assert(_pending.find(ci.connector) != _pending.end() && transceiver);
// Create and add the connection to the connection map. Adding the connection to the map
// is necessary to support the interruption of the connection initialization and validation
// in case the communicator is destroyed.
Ice::ConnectionIPtr connection;
try
{
if(_destroyed)
{
throw Ice::<API key>(__FILE__, __LINE__);
}
connection = new ConnectionI(_communicator, _instance, _reaper, transceiver, ci.connector,
ci.endpoint->compress(false), 0);
}
catch(const Ice::LocalException&)
{
try
{
transceiver->close();
}
catch(const Ice::LocalException&)
{
// Ignore
}
throw;
}
_connections.insert(pair<const ConnectorPtr, ConnectionIPtr>(ci.connector, connection));
<API key>.insert(pair<const EndpointIPtr, ConnectionIPtr>(connection->endpoint(), connection));
<API key>.insert(pair<const EndpointIPtr, ConnectionIPtr>(connection->endpoint()->compress(true),
connection));
return connection;
}
void
IceInternal::<API key>::finishGetConnection(const vector<ConnectorInfo>& connectors,
const ConnectorInfo& ci,
const ConnectionIPtr& connection,
const ConnectCallbackPtr& cb)
{
set<ConnectCallbackPtr> connectionCallbacks;
if(cb)
{
connectionCallbacks.insert(cb);
}
set<ConnectCallbackPtr> callbacks;
{
IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this);
for(vector<ConnectorInfo>::const_iterator p = connectors.begin(); p != connectors.end(); ++p)
{
map<ConnectorPtr, set<ConnectCallbackPtr> >::iterator q = _pending.find(p->connector);
if(q != _pending.end())
{
for(set<ConnectCallbackPtr>::const_iterator r = q->second.begin(); r != q->second.end(); ++r)
{
if((*r)->hasConnector(ci))
{
connectionCallbacks.insert(*r);
}
else
{
callbacks.insert(*r);
}
}
_pending.erase(q);
}
}
for(set<ConnectCallbackPtr>::iterator r = connectionCallbacks.begin(); r != connectionCallbacks.end(); ++r)
{
(*r)->removeFromPending();
callbacks.erase(*r);
}
for(set<ConnectCallbackPtr>::iterator r = callbacks.begin(); r != callbacks.end(); ++r)
{
(*r)->removeFromPending();
}
notifyAll();
}
bool compress;
<API key> <API key> = _instance-><API key>();
if(<API key>->overrideCompress)
{
compress = <API key>-><API key>;
}
else
{
compress = ci.endpoint->compress();
}
for(set<ConnectCallbackPtr>::const_iterator p = callbacks.begin(); p != callbacks.end(); ++p)
{
(*p)->getConnection();
}
for(set<ConnectCallbackPtr>::const_iterator p = connectionCallbacks.begin(); p != connectionCallbacks.end(); ++p)
{
(*p)->setConnection(connection, compress);
}
}
void
IceInternal::<API key>::finishGetConnection(const vector<ConnectorInfo>& connectors,
const Ice::LocalException& ex,
const ConnectCallbackPtr& cb)
{
set<ConnectCallbackPtr> failedCallbacks;
if(cb)
{
failedCallbacks.insert(cb);
}
set<ConnectCallbackPtr> callbacks;
{
IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this);
for(vector<ConnectorInfo>::const_iterator p = connectors.begin(); p != connectors.end(); ++p)
{
map<ConnectorPtr, set<ConnectCallbackPtr> >::iterator q = _pending.find(p->connector);
if(q != _pending.end())
{
for(set<ConnectCallbackPtr>::const_iterator r = q->second.begin(); r != q->second.end(); ++r)
{
if((*r)->removeConnectors(connectors))
{
failedCallbacks.insert(*r);
}
else
{
callbacks.insert(*r);
}
}
_pending.erase(q);
}
}
for(set<ConnectCallbackPtr>::iterator r = callbacks.begin(); r != callbacks.end(); ++r)
{
assert(failedCallbacks.find(*r) == failedCallbacks.end());
(*r)->removeFromPending();
}
notifyAll();
}
for(set<ConnectCallbackPtr>::const_iterator p = callbacks.begin(); p != callbacks.end(); ++p)
{
(*p)->getConnection();
}
for(set<ConnectCallbackPtr>::const_iterator p = failedCallbacks.begin(); p != failedCallbacks.end(); ++p)
{
(*p)->setException(ex);
}
}
bool
IceInternal::<API key>::addToPending(const ConnectCallbackPtr& cb,
const vector<ConnectorInfo>& connectors)
{
// Add the callback to each connector pending list.
bool found = false;
for(vector<ConnectorInfo>::const_iterator p = connectors.begin(); p != connectors.end(); ++p)
{
map<ConnectorPtr, set<ConnectCallbackPtr> >::iterator q = _pending.find(p->connector);
if(q != _pending.end())
{
found = true;
if(cb)
{
q->second.insert(cb);
}
}
}
if(found)
{
return true;
}
// If there's no pending connection for the given connectors, we're
// responsible for its establishment. We add empty pending lists,
// other callbacks to the same connectors will be queued.
for(vector<ConnectorInfo>::const_iterator r = connectors.begin(); r != connectors.end(); ++r)
{
if(_pending.find(r->connector) == _pending.end())
{
_pending.insert(pair<ConnectorPtr, set<ConnectCallbackPtr> >(r->connector, set<ConnectCallbackPtr>()));
}
}
return false;
}
void
IceInternal::<API key>::removeFromPending(const ConnectCallbackPtr& cb,
const vector<ConnectorInfo>& connectors)
{
for(vector<ConnectorInfo>::const_iterator p = connectors.begin(); p != connectors.end(); ++p)
{
map<ConnectorPtr, set<ConnectCallbackPtr> >::iterator q = _pending.find(p->connector);
if(q != _pending.end())
{
q->second.erase(cb);
}
}
}
void
IceInternal::<API key>::handleException(const LocalException& ex, bool hasMore)
{
TraceLevelsPtr traceLevels = _instance->traceLevels();
if(traceLevels->retry >= 2)
{
Trace out(_instance->initializationData().logger, traceLevels->retryCat);
out << "couldn't resolve endpoint host";
if(dynamic_cast<const <API key>*>(&ex))
{
out << "\n";
}
else
{
if(hasMore)
{
out << ", trying next endpoint\n";
}
else
{
out << " and no more endpoints to try\n";
}
}
out << ex;
}
}
void
IceInternal::<API key>::<API key>(const LocalException& ex, bool hasMore)
{
TraceLevelsPtr traceLevels = _instance->traceLevels();
if(traceLevels->retry >= 2)
{
Trace out(_instance->initializationData().logger, traceLevels->retryCat);
out << "connection to endpoint failed";
if(dynamic_cast<const <API key>*>(&ex))
{
out << "\n";
}
else
{
if(hasMore)
{
out << ", trying next endpoint\n";
}
else
{
out << " and no more endpoints to try\n";
}
}
out << ex;
}
}
IceInternal::<API key>::ConnectCallback::ConnectCallback(const <API key>& factory,
const vector<EndpointIPtr>& endpoints,
bool hasMore,
const <API key>& cb,
Ice::<API key> selType) :
_factory(factory),
_endpoints(endpoints),
_hasMore(hasMore),
_callback(cb),
_selType(selType)
{
_endpointsIter = _endpoints.begin();
}
// Methods from ConnectionI.StartCallback
void
IceInternal::<API key>::ConnectCallback::<API key>(const ConnectionIPtr& connection)
{
if(_observer)
{
_observer->detach();
}
connection->activate();
_factory->finishGetConnection(_connectors, *_iter, connection, this);
}
void
IceInternal::<API key>::ConnectCallback::<API key>(const ConnectionIPtr& /*connection*/,
const LocalException& ex)
{
assert(_iter != _connectors.end());
if(_observer)
{
_observer->failed(ex.ice_name());
_observer->detach();
}
_factory-><API key>(ex, _hasMore || _iter != _connectors.end() - 1);
if(dynamic_cast<const Ice::<API key>*>(&ex)) // No need to continue.
{
_factory->finishGetConnection(_connectors, ex, this);
}
else if(++_iter != _connectors.end()) // Try the next connector.
{
nextConnector();
}
else
{
_factory->finishGetConnection(_connectors, ex, this);
}
}
// Methods from <API key>
void
IceInternal::<API key>::ConnectCallback::connectors(const vector<ConnectorPtr>& connectors)
{
for(vector<ConnectorPtr>::const_iterator p = connectors.begin(); p != connectors.end(); ++p)
{
_connectors.push_back(ConnectorInfo(*p, *_endpointsIter));
}
if(++_endpointsIter != _endpoints.end())
{
nextEndpoint();
}
else
{
assert(!_connectors.empty());
// We now have all the connectors for the given endpoints. We can try to obtain the
// connection.
_iter = _connectors.begin();
getConnection();
}
}
void
IceInternal::<API key>::ConnectCallback::exception(const Ice::LocalException& ex)
{
_factory->handleException(ex, _hasMore || _endpointsIter != _endpoints.end() - 1);
if(++_endpointsIter != _endpoints.end())
{
nextEndpoint();
}
else if(!_connectors.empty())
{
// We now have all the connectors for the given endpoints. We can try to obtain the
// connection.
_iter = _connectors.begin();
getConnection();
}
else
{
_callback->setException(ex);
_factory-><API key>(); // Must be called last.
}
}
void
IceInternal::<API key>::ConnectCallback::getConnectors()
{
try
{
// Notify the factory that there's an async connect pending. This is necessary
// to prevent the outgoing connection factory to be destroyed before all the
// pending asynchronous connects are finished.
_factory-><API key>();
}
catch(const Ice::LocalException& ex)
{
_callback->setException(ex);
return;
}
nextEndpoint();
}
void
IceInternal::<API key>::ConnectCallback::nextEndpoint()
{
try
{
assert(_endpointsIter != _endpoints.end());
(*_endpointsIter)->connectors_async(_selType, this);
}
catch(const Ice::LocalException& ex)
{
exception(ex);
}
}
void
IceInternal::<API key>::ConnectCallback::getConnection()
{
try
{
// If all the connectors have been created, we ask the factory to get a
// connection.
bool compress;
Ice::ConnectionIPtr connection = _factory->getConnection(_connectors, this, compress);
if(!connection)
{
// A null return value from getConnection indicates that the connection
// is being established and that everthing has been done to ensure that
// the callback will be notified when the connection establishment is
// done or that the callback already obtain the connection.
return;
}
_callback->setConnection(connection, compress);
_factory-><API key>(); // Must be called last.
}
catch(const Ice::LocalException& ex)
{
_callback->setException(ex);
_factory-><API key>(); // Must be called last.
}
}
void
IceInternal::<API key>::ConnectCallback::nextConnector()
{
Ice::ConnectionIPtr connection;
try
{
const <API key>& obsv = _factory->_instance->initializationData().observer;
if(obsv)
{
_observer = obsv-><API key>(_iter->endpoint, _iter->connector->toString());
if(_observer)
{
_observer->attach();
}
}
assert(_iter != _connectors.end());
connection = _factory->createConnection(_iter->connector->connect(), *_iter);
connection->start(this);
}
catch(const Ice::LocalException& ex)
{
<API key>(connection, ex);
}
}
void
IceInternal::<API key>::ConnectCallback::setConnection(const Ice::ConnectionIPtr& connection,
bool compress)
{
// Callback from the factory: the connection to one of the callback
// connectors has been established.
_callback->setConnection(connection, compress);
_factory-><API key>(); // Must be called last.
}
void
IceInternal::<API key>::ConnectCallback::setException(const Ice::LocalException& ex)
{
// Callback from the factory: connection establishment failed.
_callback->setException(ex);
_factory-><API key>(); // Must be called last.
}
bool
IceInternal::<API key>::ConnectCallback::hasConnector(const ConnectorInfo& ci)
{
return find(_connectors.begin(), _connectors.end(), ci) != _connectors.end();
}
bool
IceInternal::<API key>::ConnectCallback::removeConnectors(const vector<ConnectorInfo>& connectors)
{
// Callback from the factory: connecting to the given connectors
// failed, we remove the connectors and return true if there's
// no more connectors left to try.
for(vector<ConnectorInfo>::const_iterator p = connectors.begin(); p != connectors.end(); ++p)
{
_connectors.erase(remove(_connectors.begin(), _connectors.end(), *p), _connectors.end());
}
return _connectors.empty();
}
void
IceInternal::<API key>::ConnectCallback::removeFromPending()
{
_factory->removeFromPending(this, _connectors);
}
bool
IceInternal::<API key>::ConnectCallback::operator<(const ConnectCallback& rhs) const
{
return this < &rhs;
}
void
IceInternal::<API key>::activate()
{
IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this);
setState(StateActive);
}
void
IceInternal::<API key>::hold()
{
IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this);
setState(StateHolding);
}
void
IceInternal::<API key>::destroy()
{
IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this);
setState(StateClosed);
}
void
IceInternal::<API key>::<API key>()
{
IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this);
for_each(_connections.begin(), _connections.end(), Ice::voidMemFun(&ConnectionI::updateObserver));
}
void
IceInternal::<API key>::waitUntilHolding() const
{
set<ConnectionIPtr> connections;
{
IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this);
// First we wait until the connection factory itself is in holding
// state.
while(_state < StateHolding)
{
wait();
}
// We want to wait until all connections are in holding state
// outside the thread synchronization.
connections = _connections;
}
// Now we wait until each connection is in holding state.
for_each(connections.begin(), connections.end(), Ice::constVoidMemFun(&ConnectionI::waitUntilHolding));
}
void
IceInternal::<API key>::waitUntilFinished()
{
set<ConnectionIPtr> connections;
{
IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this);
// First we wait until the factory is destroyed. If we are using
// an acceptor, we also wait for it to be closed.
while(_state != StateFinished)
{
wait();
}
// Clear the OA. See bug 1673 for the details of why this is necessary.
_adapter = 0;
// We want to wait until all connections are finished outside the
// thread synchronization.
connections = _connections;
}
for_each(connections.begin(), connections.end(), Ice::voidMemFun(&ConnectionI::waitUntilFinished));
{
IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this);
// Ensure all the connections are finished and reapable at this point.
vector<Ice::ConnectionIPtr> cons;
_reaper->swapConnections(cons);
assert(cons.size() == _connections.size());
cons.clear();
_connections.clear();
}
}
EndpointIPtr
IceInternal::<API key>::endpoint() const
{
// No mutex protection necessary, _endpoint is immutable.
return _endpoint;
}
list<ConnectionIPtr>
IceInternal::<API key>::connections() const
{
IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this);
list<ConnectionIPtr> result;
// Only copy connections which have not been destroyed.
remove_copy_if(_connections.begin(), _connections.end(), back_inserter(result),
not1(Ice::constMemFun(&ConnectionI::isActiveOrHolding)));
return result;
}
void
IceInternal::<API key>::<API key>(const <API key>& outAsync)
{
list<ConnectionIPtr> c = connections(); // connections() is synchronized, so no need to synchronize here.
for(list<ConnectionIPtr>::const_iterator p = c.begin(); p != c.end(); ++p)
{
try
{
outAsync->flushConnection(*p);
}
catch(const LocalException&)
{
// Ignore.
}
}
}
#if defined(ICE_USE_IOCP) || defined(ICE_OS_WINRT)
bool
IceInternal::<API key>::startAsync(SocketOperation)
{
if(_state >= StateClosed)
{
return false;
}
try
{
_acceptor->startAccept();
}
catch(const Ice::LocalException& ex)
{
{
Error out(_instance->initializationData().logger);
out << "can't accept connections:\n" << ex << '\n' << _acceptor->toString();
}
abort();
}
return true;
}
bool
IceInternal::<API key>::finishAsync(SocketOperation)
{
assert(_acceptor);
try
{
_acceptor->finishAccept();
}
catch(const LocalException& ex)
{
Error out(_instance->initializationData().logger);
out << "couldn't accept connection:\n" << ex << '\n' << _acceptor->toString();
return false;
}
return _state < StateClosed;
}
#endif
void
IceInternal::<API key>::message(ThreadPoolCurrent& current)
{
ConnectionIPtr connection;
ThreadPoolMessage<<API key>> msg(current, *this);
{
IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this);
ThreadPoolMessage<<API key>>::IOScope io(msg);
if(!io)
{
return;
}
if(_state >= StateClosed)
{
return;
}
else if(_state == StateHolding)
{
IceUtil::ThreadControl::yield();
return;
}
// Reap closed connections
vector<Ice::ConnectionIPtr> cons;
_reaper->swapConnections(cons);
for(vector<Ice::ConnectionIPtr>::const_iterator p = cons.begin(); p != cons.end(); ++p)
{
_connections.erase(*p);
}
// Now accept a new connection.
TransceiverPtr transceiver;
try
{
transceiver = _acceptor->accept();
}
catch(const SocketException& ex)
{
if(noMoreFds(ex.error))
{
{
Error out(_instance->initializationData().logger);
out << "fatal error: can't accept more connections:\n" << ex << '\n' << _acceptor->toString();
}
abort();
}
// Ignore socket exceptions.
return;
}
catch(const LocalException& ex)
{
// Warn about other Ice local exceptions.
if(_warn)
{
Warning out(_instance->initializationData().logger);
out << "connection exception:\n" << ex << '\n' << _acceptor->toString();
}
return;
}
assert(transceiver);
try
{
connection = new ConnectionI(_adapter->getCommunicator(), _instance, _reaper, transceiver, 0, _endpoint,
_adapter);
}
catch(const LocalException& ex)
{
try
{
transceiver->close();
}
catch(const Ice::LocalException&)
{
// Ignore.
}
if(_warn)
{
Warning out(_instance->initializationData().logger);
out << "connection exception:\n" << ex << '\n' << _acceptor->toString();
}
return;
}
_connections.insert(connection);
}
assert(connection);
connection->start(this);
}
void
IceInternal::<API key>::finished(ThreadPoolCurrent&)
{
IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this);
assert(_state == StateClosed);
setState(StateFinished);
}
string
IceInternal::<API key>::toString() const
{
IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this);
if(_transceiver)
{
return _transceiver->toString();
}
assert(_acceptor);
return _acceptor->toString();
}
NativeInfoPtr
IceInternal::<API key>::getNativeInfo()
{
if(_transceiver)
{
return _transceiver->getNativeInfo();
}
assert(_acceptor);
return _acceptor->getNativeInfo();
}
void
IceInternal::<API key>::<API key>(const Ice::ConnectionIPtr& connection)
{
IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this);
// Initialy, connections are in the holding state. If the factory is active
// we activate the connection.
if(_state == StateActive)
{
connection->activate();
}
}
void
IceInternal::<API key>::<API key>(const Ice::ConnectionIPtr& /*connection*/,
const Ice::LocalException& ex)
{
IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this);
if(_state >= StateClosed)
{
return;
}
if(_warn && !dynamic_cast<const Ice::SocketException*>(&ex))
{
Warning out(_instance->initializationData().logger);
out << "connection exception:\n" << ex << '\n' << _acceptor->toString();
}
}
// COMPILERFIX: The ConnectionFactory setup is broken out into a separate initialize
// function because when it was part of the constructor C++Builder 2007 apps would
// crash if an execption was thrown from any calls within the constructor.
IceInternal::<API key>::<API key>(const InstancePtr& instance,
const EndpointIPtr& endpoint,
const ObjectAdapterPtr& adapter) :
_instance(instance),
_reaper(new ConnectionReaper()),
_endpoint(endpoint),
_adapter(adapter),
_warn(_instance->initializationData().properties->getPropertyAsInt("Ice.Warn.Connections") > 0),
_state(StateHolding)
{
}
void
IceInternal::<API key>::initialize(const string& oaName)
{
if(_instance-><API key>()->overrideTimeout)
{
const_cast<EndpointIPtr&>(_endpoint) =
_endpoint->timeout(_instance-><API key>()-><API key>);
}
if(_instance-><API key>()->overrideCompress)
{
const_cast<EndpointIPtr&>(_endpoint) =
_endpoint->compress(_instance-><API key>()-><API key>);
}
try
{
const_cast<TransceiverPtr&>(_transceiver) = _endpoint->transceiver(const_cast<EndpointIPtr&>(_endpoint));
if(_transceiver)
{
ConnectionIPtr connection = new ConnectionI(_adapter->getCommunicator(), _instance, _reaper, _transceiver,
0, _endpoint, _adapter);
connection->start(0);
_connections.insert(connection);
}
else
{
const_cast<AcceptorPtr&>(_acceptor) = _endpoint->acceptor(const_cast<EndpointIPtr&>(_endpoint), oaName);
assert(_acceptor);
_acceptor->listen();
dynamic_cast<ObjectAdapterI*>(_adapter.get())->getThreadPool()->initialize(this);
}
}
catch(const Ice::Exception&)
{
if(_transceiver)
{
try
{
_transceiver->close();
}
catch(const Ice::LocalException&)
{
// Ignore
}
}
if(_acceptor)
{
try
{
_acceptor->close();
}
catch(const Ice::LocalException&)
{
// Ignore
}
}
_state = StateFinished;
_connections.clear();
throw;
}
}
IceInternal::<API key>::~<API key>()
{
assert(_state == StateFinished);
assert(_connections.empty());
}
void
IceInternal::<API key>::setState(State state)
{
if(_state == state) // Don't switch twice.
{
return;
}
switch(state)
{
case StateActive:
{
if(_state != StateHolding) // Can only switch from holding to active.
{
return;
}
if(_acceptor)
{
if(_instance->traceLevels()->network >= 1)
{
Trace out(_instance->initializationData().logger, _instance->traceLevels()->networkCat);
out << "accepting " << _endpoint->protocol() << " connections at " << _acceptor->toString();
}
dynamic_cast<ObjectAdapterI*>(_adapter.get())->getThreadPool()->_register(this, SocketOperationRead);
}
for_each(_connections.begin(), _connections.end(), Ice::voidMemFun(&ConnectionI::activate));
break;
}
case StateHolding:
{
if(_state != StateActive) // Can only switch from active to holding.
{
return;
}
if(_acceptor)
{
if(_instance->traceLevels()->network >= 1)
{
Trace out(_instance->initializationData().logger, _instance->traceLevels()->networkCat);
out << "holding " << _endpoint->protocol() << " connections at " << _acceptor->toString();
}
dynamic_cast<ObjectAdapterI*>(_adapter.get())->getThreadPool()->unregister(this, SocketOperationRead);
}
for_each(_connections.begin(), _connections.end(), Ice::voidMemFun(&ConnectionI::hold));
break;
}
case StateClosed:
{
if(_acceptor)
{
dynamic_cast<ObjectAdapterI*>(_adapter.get())->getThreadPool()->finish(this);
}
else
{
state = StateFinished;
}
#if defined(ICE_USE_IOCP) || defined(ICE_OS_WINRT)
// With IOCP and WinRT, we close the acceptor now to cancel all the pending
// asynchronous operations. It's important to wait for the pending asynchronous
// operations to return before ConnectionI::finished(). Otherwise, if there was
// a pending message waiting to be sent, the connection wouldn't know whether
// or not the send failed or succeeded, potentially breaking at-most-once semantics.
if(_acceptor)
{
_acceptor->close();
}
#endif
for_each(_connections.begin(), _connections.end(),
bind2nd(Ice::voidMemFun1(&ConnectionI::destroy), ConnectionI::<API key>));
break;
}
case StateFinished:
{
assert(_state == StateClosed);
#if !defined(ICE_USE_IOCP) && !defined(ICE_OS_WINRT)
if(_acceptor)
{
_acceptor->close();
}
#endif
break;
}
}
_state = state;
notifyAll();
} |
module RemedyView
class Hooks < Redmine::Hook::ViewListener
render_on :<API key>,
:partial => 'issues/remedy_ticket_form'
render_on :<API key>,
:partial => 'issues/remedy_tickets'
end
end |
# -*- coding: utf-8 -*-
# Authors:
# Thomas Woerner <twoerner@redhat.com>
# This program is free software; you can redistribute it and/or modify
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
__all__ = [ "PY2", "getPortID", "getPortRange", "portStr", "getServiceName",
"checkIP", "checkIP6", "checkIPnMask", "checkIP6nMask",
"checkProtocol", "checkInterface", "checkUINT32",
"firewalld_is_active", "tempFile", "readfile", "writefile",
"<API key>", "<API key>",
"<API key>", "<API key>",
"get_nf_nat_helpers", "check_port", "check_address",
"<API key>", "check_mac", "uniqify", "ppid_of_pid",
"max_zone_name_len", "checkUser", "checkUid", "checkCommand",
"checkContext", "joinArgs", "splitArgs",
"b2u", "u2b", "u2b_if_py2" ]
import socket
import os
import os.path
import shlex
import pipes
import re
import string
import sys
import tempfile
from firewall.core.logger import log
from firewall.core.prog import runProg
from firewall.config import FIREWALLD_TEMPDIR, FIREWALLD_PIDFILE, COMMANDS
PY2 = sys.version < '3'
def getPortID(port):
""" Check and Get port id from port string or port id using socket.getservbyname
@param port port string or port id
@return Port id if valid, -1 if port can not be found and -2 if port is too big
"""
if isinstance(port, int):
_id = port
else:
if port:
port = port.strip()
try:
_id = int(port)
except ValueError:
try:
_id = socket.getservbyname(port)
except socket.error:
return -1
if _id > 65535:
return -2
return _id
def getPortRange(ports):
""" Get port range for port range string or single port id
@param ports an integer or port string or port range string
@return Array containing start and end port id for a valid range or -1 if port can not be found and -2 if port is too big for integer input or -1 for invalid ranges or None if the range is ambiguous.
"""
# "<port-id>" case
if isinstance(ports, int) or ports.isdigit():
id1 = getPortID(ports)
if id1 >= 0:
return (id1,)
return id1
splits = ports.split("-")
# "<port-id>-<port-id>" case
if len(splits) == 2 and splits[0].isdigit() and splits[1].isdigit():
id1 = getPortID(splits[0])
id2 = getPortID(splits[1])
if id1 >= 0 and id2 >= 0:
if id1 < id2:
return (id1, id2)
elif id1 > id2:
return (id2, id1)
else: # ids are the same
return (id1,)
# everything else "<port-str>[-<port-str>]"
matched = [ ]
for i in range(len(splits), 0, -1):
id1 = getPortID("-".join(splits[:i]))
port2 = "-".join(splits[i:])
if len(port2) > 0:
id2 = getPortID(port2)
if id1 >= 0 and id2 >= 0:
if id1 < id2:
matched.append((id1, id2))
elif id1 > id2:
matched.append((id2, id1))
else:
matched.append((id1, ))
else:
if id1 >= 0:
matched.append((id1,))
if i == len(splits):
# full match, stop here
break
if len(matched) < 1:
return -1
elif len(matched) > 1:
return None
return matched[0]
def portStr(port, delimiter=":"):
""" Create port and port range string
@param port port or port range int or [int, int]
@param delimiter of the output string for port ranges, default ':'
@return Port or port range string, empty string if port isn't specified, None if port or port range is not valid
"""
if port == "":
return ""
_range = getPortRange(port)
if isinstance(_range, int) and _range < 0:
return None
elif len(_range) == 1:
return "%s" % _range
else:
return "%s%s%s" % (_range[0], delimiter, _range[1])
def portInPortRange(port, range):
_port = getPortID(port)
_range = getPortRange(range)
if len(_range) == 1:
return _port == getPortID(_range[0])
if len(_range) == 2 and \
_port >= getPortID(_range[0]) and _port <= getPortID(_range[1]):
return True
return False
def getServiceName(port, proto):
""" Check and Get service name from port and proto string combination using socket.getservbyport
@param port string or id
@param protocol string
@return Service name if port and protocol are valid, else None
"""
try:
name = socket.getservbyport(int(port), proto)
except socket.error:
return None
return name
def checkIP(ip):
""" Check IPv4 address.
@param ip address string
@return True if address is valid, else False
"""
try:
socket.inet_pton(socket.AF_INET, ip)
except socket.error:
return False
return True
def checkIP6(ip):
""" Check IPv6 address.
@param ip address string
@return True if address is valid, else False
"""
try:
socket.inet_pton(socket.AF_INET6, ip)
except socket.error:
return False
return True
def checkIPnMask(ip):
if "/" in ip:
addr = ip[:ip.index("/")]
mask = ip[ip.index("/")+1:]
if len(addr) < 1 or len(mask) < 1:
return False
else:
addr = ip
mask = None
if not checkIP(addr):
return False
if mask:
if "." in mask:
return checkIP(mask)
else:
try:
i = int(mask)
except ValueError:
return False
if i < 0 or i > 32:
return False
return True
def checkIP6nMask(ip):
if "/" in ip:
addr = ip[:ip.index("/")]
mask = ip[ip.index("/")+1:]
if len(addr) < 1 or len(mask) < 1:
return False
else:
addr = ip
mask = None
if not checkIP6(addr):
return False
if mask:
try:
i = int(mask)
except ValueError:
return False
if i < 0 or i > 128:
return False
return True
def checkProtocol(protocol):
try:
i = int(protocol)
except ValueError:
# string
try:
socket.getprotobyname(protocol)
except socket.error:
return False
else:
if i < 0 or i > 255:
return False
return True
def checkInterface(iface):
""" Check interface string
@param interface string
@return True if interface is valid (maximum 16 chars and does not contain ' ', '/', '!', ':', '*'), else False
"""
if not iface or len(iface) > 16:
return False
for ch in [ ' ', '/', '!', '*' ]:
# !:* are limits for iptables <= 1.4.5
if ch in iface:
return False
# disabled old iptables check
#if iface == "+":
# # limit for iptables <= 1.4.5
# return False
return True
def checkUINT32(val):
try:
x = int(val, 0)
except ValueError:
return False
else:
if x >= 0 and x <= 4294967295:
return True
return False
def firewalld_is_active():
""" Check if firewalld is active
@return True if there is a firewalld pid file and the pid is used by firewalld
"""
if not os.path.exists(FIREWALLD_PIDFILE):
return False
try:
with open(FIREWALLD_PIDFILE, "r") as fd:
pid = fd.readline()
except Exception:
return False
if not os.path.exists("/proc/%s" % pid):
return False
try:
with open("/proc/%s/cmdline" % pid, "r") as fd:
cmdline = fd.readline()
except Exception:
return False
if "firewalld" in cmdline:
return True
return False
def tempFile():
try:
if not os.path.exists(FIREWALLD_TEMPDIR):
os.mkdir(FIREWALLD_TEMPDIR, 0o750)
return tempfile.NamedTemporaryFile(mode='wt', prefix="temp.",
dir=FIREWALLD_TEMPDIR, delete=False)
except Exception as msg:
log.error("Failed to create temporary file: %s" % msg)
raise
return None
def readfile(filename):
try:
with open(filename, "r") as f:
return f.readlines()
except Exception as e:
log.error('Failed to read file "%s": %s' % (filename, e))
return None
def writefile(filename, line):
try:
with open(filename, "w") as f:
f.write(line)
except Exception as e:
log.error('Failed to write to file "%s": %s' % (filename, e))
return False
return True
def <API key>(ipv):
if ipv == "ipv4":
return writefile("/proc/sys/net/ipv4/ip_forward", "1\n")
elif ipv == "ipv6":
return writefile("/proc/sys/net/ipv6/conf/all/forwarding", "1\n")
return False
def get_modinfos(path_templates, prefix):
kver = os.uname()[2]
modules = []
for path in (t % kver for t in path_templates):
if os.path.isdir(path):
for filename in sorted(os.listdir(path)):
if filename.startswith(prefix):
modules.append(filename.split(".")[0])
if modules:
# Ignore status as it is not 0 if even one module had problems
(status, ret) = runProg(COMMANDS["modinfo"], modules)
entry = {}
for m in re.finditer(r"^(\w+):[ \t]*(\S.*?)[ \t]*$", ret, re.MULTILINE):
key, value = m.groups()
# Assume every entry starts with filename
if key == "filename" and "filename" in entry:
yield entry
entry = {}
entry.setdefault(key, [ ]).append(value)
if "filename" in entry:
yield entry
def <API key>():
helpers = { }
for modinfo in get_modinfos(["/lib/modules/%s/kernel/net/netfilter/"], "nf_conntrack_"):
filename = modinfo['filename'][0].split("/")[-1]
name = filename.split(".")[0]
# If module name matches "nf_conntrack_proto_*"
# the we add it to helpers list and goto next module
if filename.startswith("nf_conntrack_proto_"):
helper = name
helper = helper.replace("_", "-")
helper = helper.replace("nf-conntrack-", "")
helpers.setdefault(name, [ ]).append(helper)
continue
# Else we get module alias and if "-helper" in the "alias:" line of modinfo
# then we add it to helpers list and goto next module
if "alias" in modinfo:
for helper in modinfo["alias"]:
if "-helper-" in helper:
helper = helper.replace("nfct-helper-", "")
helper = helper.replace("_", "-")
helpers.setdefault(name, [ ]).append(helper)
return helpers
def get_nf_nat_helpers():
helpers = { }
for modinfo in get_modinfos(["/lib/modules/%s/kernel/net/netfilter/",
"/lib/modules/%s/kernel/net/ipv4/netfilter/",
"/lib/modules/%s/kernel/net/ipv6/netfilter/"], "nf_nat_"):
filename = modinfo['filename'][0].split("/")[-1]
name = filename.split(".")[0]
helper = name
helper = helper.replace("_", "-")
helper = helper.replace("nf-nat-", "")
# If module name matches "nf_nat_proto_*"
# the we add it to helpers list and goto next module
if filename.startswith("nf_nat_proto_"):
helpers.setdefault(name, [ ]).append(helper)
continue
# Else we get module alias and if "NAT helper" in "description:" line of modinfo
# then we add it to helpers list and goto next module
if "description" in modinfo and "NAT helper" in modinfo["description"][0]:
helpers.setdefault(name, [ ]).append(helper)
return helpers
def <API key>():
try:
return int(readfile("/proc/sys/net/netfilter/nf_conntrack_helper")[0])
except Exception:
log.warning("Failed to get and parse nf_conntrack_helper setting")
return 0
def <API key>(flag):
return writefile("/proc/sys/net/netfilter/nf_conntrack_helper",
"1\n" if flag else "0\n")
def check_port(port):
_range = getPortRange(port)
if _range == -2 or _range == -1 or _range is None or \
(len(_range) == 2 and _range[0] >= _range[1]):
if _range == -2:
log.debug2("'%s': port > 65535" % port)
elif _range == -1:
log.debug2("'%s': port is invalid" % port)
elif _range is None:
log.debug2("'%s': port is ambiguous" % port)
elif len(_range) == 2 and _range[0] >= _range[1]:
log.debug2("'%s': range start >= end" % port)
return False
return True
def check_address(ipv, source):
if ipv == "ipv4":
return checkIPnMask(source)
elif ipv == "ipv6":
return checkIP6nMask(source)
else:
return False
def <API key>(ipv, source):
if ipv == "ipv4":
return checkIP(source)
elif ipv == "ipv6":
return checkIP6(source)
else:
return False
def check_mac(mac):
if len(mac) == 12+5:
# 0 1 : 3 4 : 6 7 : 9 10 : 12 13 : 15 16
for i in (2, 5, 8, 11, 14):
if mac[i] != ":":
return False
for i in (0, 1, 3, 4, 6, 7, 9, 10, 12, 13, 15, 16):
if mac[i] not in string.hexdigits:
return False
return True
return False
def uniqify(_list):
# removes duplicates from list, whilst preserving order
output = []
for x in _list:
if x not in output:
output.append(x)
return output
def ppid_of_pid(pid):
""" Get parent for pid """
try:
f = os.popen("ps -o ppid -h -p %d 2>/dev/null" % pid)
pid = int(f.readlines()[0].strip())
f.close()
except Exception:
return None
return pid
def max_zone_name_len():
"""
Netfilter limits length of chain to (currently) 28 chars.
The longest chain we create is FWDI_<zone>_allow,
which leaves 28 - 11 = 17 chars for <zone>.
"""
from firewall.core.base import SHORTCUTS
longest_shortcut = max(map(len, SHORTCUTS.values()))
return 28 - (longest_shortcut + len("__allow"))
def checkUser(user):
if len(user) < 1 or len(user) > os.sysconf('SC_LOGIN_NAME_MAX'):
return False
for c in user:
if c not in string.ascii_letters and \
c not in string.digits and \
c not in [ ".", "-", "_", "$" ]:
return False
return True
def checkUid(uid):
if isinstance(uid, str):
try:
uid = int(uid)
except ValueError:
return False
if uid >= 0 and uid <= 2**31-1:
return True
return False
def checkCommand(command):
if len(command) < 1 or len(command) > 1024:
return False
for ch in [ "|", "\n", "\0" ]:
if ch in command:
return False
if command[0] != "/":
return False
return True
def checkContext(context):
splits = context.split(":")
if len(splits) not in [4, 5]:
return False
# user ends with _u if not root
if splits[0] != "root" and splits[0][-2:] != "_u":
return False
# role ends with _r
if splits[1][-2:] != "_r":
return False
# type ends with _t
if splits[2][-2:] != "_t":
return False
# level might also contain :
if len(splits[3]) < 1:
return False
return True
def joinArgs(args):
if "quote" in dir(shlex):
return " ".join(shlex.quote(a) for a in args)
else:
return " ".join(pipes.quote(a) for a in args)
def splitArgs(_string):
if PY2 and isinstance(_string, unicode): # noqa: F821
# Python2's shlex doesn't like unicode
_string = u2b(_string)
splits = shlex.split(_string)
return map(b2u, splits)
else:
return shlex.split(_string)
def b2u(_string):
""" bytes to unicode """
if isinstance(_string, bytes):
return _string.decode('UTF-8', 'replace')
return _string
def u2b(_string):
""" unicode to bytes """
if not isinstance(_string, bytes):
return _string.encode('UTF-8', 'replace')
return _string
def u2b_if_py2(_string):
""" unicode to bytes only if Python 2"""
if PY2 and isinstance(_string, unicode): # noqa: F821
return _string.encode('UTF-8', 'replace')
return _string |
<?php
if (!defined('_JEXEC')) die('Direct Access to this location is not allowed.');
$sh_LANG['fr']['<API key>'] = 'Creer nouvel flux RSS';
// english
$sh_LANG['en']['<API key>'] = 'Create new RSS feed';
// spanish
$sh_LANG['es']['<API key>'] = 'Nuevo flujo RSS';
// german
$sh_LANG['de']['<API key>'] = 'Neuer RSS';
// hungarian : translation by Jozsef Tamas Herczeg 2007-08-15
$sh_LANG['hu']['<API key>'] = 'Új RSS-csatorna létrehozása';
// italian
$sh_LANG['it']['<API key>'] = 'Create new RSS feed';
// dutch
$sh_LANG['nl']['<API key>'] = 'Maak nieuwe RSS feed';
// romanian
$sh_LANG['ro']['<API key>'] = 'Creaza fulx RSS nou';
?> |
#include "resources/resource.h"
#include "logger.h"
#include "resources/resourcemanager.h"
#include "debug.h"
Resource::~Resource()
{
}
void Resource::incRef()
{
#ifdef DEBUG_IMAGES
logger->log("before incRef for: %p", static_cast<void*>(this));
mRefCount++;
logger->log("after incRef: %p, %d", static_cast<void*>(this), mRefCount);
#else
mRefCount++;
#endif
}
void Resource::decRef()
{
#ifdef DEBUG_IMAGES
logger->log("before decRef for: %p", static_cast<void*>(this));
#endif
// Reference may not already have reached zero
if (mRefCount == 0)
{
logger->log("Warning: mRefCount already zero for %s", mIdPath.c_str());
return;
}
mRefCount
#ifdef DEBUG_IMAGES
logger->log("after decRef: %p, %d", static_cast<void*>(this), mRefCount);
#endif
if (mRefCount == 0 && !mNotCount)
{
// Warn the manager that this resource is no longer used.
ResourceManager *const resman = ResourceManager::getInstance();
resman->release(this);
}
} |
#include "../config.h"
#include "../lib/ftndlib.h"
#include "screen.h"
#include "mutil.h"
#include "ledit.h"
#include "m_global.h"
#include "m_menu.h"
#include "m_domain.h"
int DomainUpdated;
/*
* Count nr of domtrans records in the database.
* Creates the database if it doesn't exist.
*/
int CountDomain(void)
{
FILE *fil;
char ffile[PATH_MAX];
int count;
snprintf(ffile, PATH_MAX, "%s/etc/domain.data", getenv("FTND_ROOT"));
if ((fil = fopen(ffile, "r")) == NULL) {
if ((fil = fopen(ffile, "a+")) != NULL) {
Syslog('+', "Created new %s", ffile);
domainhdr.hdrsize = sizeof(domainhdr);
domainhdr.recsize = sizeof(domtrans);
domainhdr.lastupd = time(NULL);
fwrite(&domainhdr, sizeof(domainhdr), 1, fil);
memset(&domtrans, 0, sizeof(domtrans));
domtrans.Active = TRUE;
snprintf(domtrans.ftndom, 61, ".z1.fidonet");
snprintf(domtrans.intdom, 61, ".z1.fidonet.org");
fwrite(&domtrans, sizeof(domtrans), 1, fil);
snprintf(domtrans.ftndom, 61, ".z2.fidonet");
snprintf(domtrans.intdom, 61, ".z2.fidonet.org");
fwrite(&domtrans, sizeof(domtrans), 1, fil);
snprintf(domtrans.ftndom, 61, ".z3.fidonet");
snprintf(domtrans.intdom, 61, ".z3.fidonet.org");
fwrite(&domtrans, sizeof(domtrans), 1, fil);
snprintf(domtrans.ftndom, 61, ".z4.fidonet");
snprintf(domtrans.intdom, 61, ".z4.fidonet.org");
fwrite(&domtrans, sizeof(domtrans), 1, fil);
snprintf(domtrans.ftndom, 61, ".z5.fidonet");
snprintf(domtrans.intdom, 61, ".z5.fidonet.org");
fwrite(&domtrans, sizeof(domtrans), 1, fil);
snprintf(domtrans.ftndom, 61, ".z6.fidonet");
snprintf(domtrans.intdom, 61, ".z6.fidonet.org");
fwrite(&domtrans, sizeof(domtrans), 1, fil);
snprintf(domtrans.ftndom, 61, ".fidonet");
snprintf(domtrans.intdom, 61, ".ftn");
fwrite(&domtrans, sizeof(domtrans), 1, fil);
fclose(fil);
chmod(ffile, 0640);
return 7;
} else
return -1;
}
fread(&domainhdr, sizeof(domainhdr), 1, fil);
fseek(fil, 0, SEEK_END);
count = (ftell(fil) - domainhdr.hdrsize) / domainhdr.recsize;
fclose(fil);
return count;
}
/*
* Open database for editing. The datafile is copied, if the format
* is changed it will be converted on the fly. All editing must be
* done on the copied file.
*/
int OpenDomain(void);
int OpenDomain(void)
{
FILE *fin, *fout;
char fnin[PATH_MAX], fnout[PATH_MAX];
int oldsize;
snprintf(fnin, PATH_MAX, "%s/etc/domain.data", getenv("FTND_ROOT"));
snprintf(fnout, PATH_MAX, "%s/etc/domain.temp", getenv("FTND_ROOT"));
if ((fin = fopen(fnin, "r")) != NULL) {
if ((fout = fopen(fnout, "w")) != NULL) {
fread(&domainhdr, sizeof(domainhdr), 1, fin);
/*
* In case we are automatic upgrading the data format
* we save the old format. If it is changed, the
* database must always be updated.
*/
oldsize = domainhdr.recsize;
if (oldsize != sizeof(domtrans)) {
DomainUpdated = 1;
Syslog('+', "Updated %s to new format", fnin);
} else
DomainUpdated = 0;
domainhdr.hdrsize = sizeof(domainhdr);
domainhdr.recsize = sizeof(domtrans);
fwrite(&domainhdr, sizeof(domainhdr), 1, fout);
/*
* The datarecord is filled with zero's before each
* read, so if the format changed, the new fields
* will be empty.
*/
memset(&domtrans, 0, sizeof(domtrans));
while (fread(&domtrans, oldsize, 1, fin) == 1) {
fwrite(&domtrans, sizeof(domtrans), 1, fout);
memset(&domtrans, 0, sizeof(domtrans));
}
fclose(fin);
fclose(fout);
return 0;
} else
return -1;
}
return -1;
}
void CloseDomain(int);
void CloseDomain(int force)
{
char fin[PATH_MAX], fout[PATH_MAX];
FILE *fi, *fo;
snprintf(fin, PATH_MAX, "%s/etc/domain.data", getenv("FTND_ROOT"));
snprintf(fout, PATH_MAX, "%s/etc/domain.temp", getenv("FTND_ROOT"));
if (DomainUpdated == 1) {
if (force || (yes_no((char *)"Database is changed, save changes") == 1)) {
working(1, 0, 0);
fi = fopen(fout, "r");
fo = fopen(fin, "w");
fread(&domainhdr, domainhdr.hdrsize, 1, fi);
fwrite(&domainhdr, domainhdr.hdrsize, 1, fo);
while (fread(&domtrans, domainhdr.recsize, 1, fi) == 1) {
if (!domtrans.Deleted)
fwrite(&domtrans, domainhdr.recsize, 1, fo);
}
fclose(fi);
fclose(fo);
unlink(fout);
chmod(fin, 0640);
Syslog('+', "Updated \"domtrans.data\"");
if (!force)
working(6, 0, 0);
return;
}
}
chmod(fin, 0640);
working(1, 0, 0);
unlink(fout);
}
int AppendDomain(void)
{
FILE *fil;
char ffile[PATH_MAX];
snprintf(ffile, PATH_MAX, "%s/etc/domain.temp", getenv("FTND_ROOT"));
if ((fil = fopen(ffile, "a")) != NULL) {
memset(&domtrans, 0, sizeof(domtrans));
/*
* Fill in default values
*/
fwrite(&domtrans, sizeof(domtrans), 1, fil);
fclose(fil);
DomainUpdated = 1;
return 0;
} else
return -1;
}
void DomainScreen(void)
{
clr_index();
set_color(WHITE, BLACK);
ftnd_mvprintw( 5, 2, "17. EDIT DOMAINS");
set_color(CYAN, BLACK);
ftnd_mvprintw( 7, 2, "1. Fidonet");
ftnd_mvprintw( 8, 2, "2. Internet");
ftnd_mvprintw( 9, 2, "3. Active");
ftnd_mvprintw(10, 2, "4. Deleted");
}
/*
* Edit one record, return -1 if record doesn't exist, 0 if ok.
*/
int EditDomainRec(int Area)
{
FILE *fil;
char mfile[PATH_MAX];
int offset;
unsigned int crc, crc1;
clr_index();
working(1, 0, 0);
IsDoing("Edit Domain");
snprintf(mfile, PATH_MAX, "%s/etc/domain.temp", getenv("FTND_ROOT"));
if ((fil = fopen(mfile, "r")) == NULL) {
working(2, 0, 0);
return -1;
}
fread(&domainhdr, sizeof(domainhdr), 1, fil);
offset = domainhdr.hdrsize + ((Area -1) * domainhdr.recsize);
if (fseek(fil, offset, 0) != 0) {
working(2, 0, 0);
return -1;
}
fread(&domtrans, domainhdr.recsize, 1, fil);
fclose(fil);
crc = 0xffffffff;
crc = upd_crc32((char *)&domtrans, crc, domainhdr.recsize);
for (;;) {
DomainScreen();
set_color(WHITE, BLACK);
show_str( 7,18,60, domtrans.ftndom);
show_str( 8,18,60, domtrans.intdom);
show_bool( 9,18, domtrans.Active);
show_bool(10,18, domtrans.Deleted);
switch(select_menu(4)) {
case 0:
crc1 = 0xffffffff;
crc1 = upd_crc32((char *)&domtrans, crc1, domainhdr.recsize);
if (crc != crc1) {
if (yes_no((char *)"Record is changed, save") == 1) {
working(1, 0, 0);
if ((fil = fopen(mfile, "r+")) == NULL) {
working(2, 0, 0);
return -1;
}
fseek(fil, offset, 0);
fwrite(&domtrans, domainhdr.recsize, 1, fil);
fclose(fil);
DomainUpdated = 1;
working(6, 0, 0);
}
}
IsDoing("Browsing Menu");
return 0;
case 1: E_STR( 7,18,60, domtrans.ftndom, "Enter the ^fidonet^ side of this ^domain^.")
case 2: E_STR( 8,18,60, domtrans.intdom, "Enter the ^internet^ side of this ^domain^.")
case 3: E_BOOL( 9,18, domtrans.Active, "If this domain is ^active^")
case 4: E_BOOL(10,18, domtrans.Deleted, "If this record is ^Deleted^")
}
}
}
void EditDomain(void)
{
int records, i, o, y, from, too;
char pick[12];
FILE *fil;
char temp[PATH_MAX];
int offset;
struct domrec tdomtrans;
if (! check_free())
return;
clr_index();
working(1, 0, 0);
IsDoing("Browsing Menu");
if (config_read() == -1) {
working(2, 0, 0);
return;
}
records = CountDomain();
if (records == -1) {
working(2, 0, 0);
return;
}
if (OpenDomain() == -1) {
working(2, 0, 0);
return;
}
o = 0;
for (;;) {
clr_index();
set_color(WHITE, BLACK);
ftnd_mvprintw( 5, 4, "17. DOMAIN MANAGER");
set_color(CYAN, BLACK);
if (records != 0) {
snprintf(temp, PATH_MAX, "%s/etc/domain.temp", getenv("FTND_ROOT"));
working(1, 0, 0);
if ((fil = fopen(temp, "r")) != NULL) {
fread(&domainhdr, sizeof(domainhdr), 1, fil);
y = 7;
set_color(CYAN, BLACK);
for (i = 1; i <= 10; i++) {
if ((o + i) <= records) {
offset = sizeof(domainhdr) + (((o + i) - 1) * domainhdr.recsize);
fseek(fil, offset, 0);
fread(&domtrans, domainhdr.recsize, 1, fil);
if (domtrans.Deleted)
set_color(LIGHTRED, BLACK);
else if (domtrans.Active)
set_color(CYAN, BLACK);
else
set_color(LIGHTBLUE, BLACK);
snprintf(temp, 81, "%3d. %-31s %-31s", o+i, domtrans.ftndom, domtrans.intdom);
temp[75] = 0;
ftnd_mvprintw(y, 3, temp);
y++;
}
}
fclose(fil);
}
}
strcpy(pick, select_menurec(records));
if (strncmp(pick, "-", 1) == 0) {
open_bbs();
CloseDomain(FALSE);
return;
}
if (strncmp(pick, "A", 1) == 0) {
working(1, 0, 0);
if (AppendDomain() == 0) {
records++;
working(1, 0, 0);
} else
working(2, 0, 0);
}
if (strncmp(pick, "D", 1) == 0) {
ftnd_mvprintw(LINES -3, 6, "Enter domain number (1..%d) to delete >", records);
y = 0;
y = edit_int(LINES -3, 44, y, (char *)"Enter record number");
if ((y > 0) && (y <= records) && yes_no((char *)"Remove record")) {
snprintf(temp, PATH_MAX, "%s/etc/domain.temp", getenv("FTND_ROOT"));
if ((fil = fopen(temp, "r+")) != NULL) {
offset = ((y - 1) * domainhdr.recsize) + domainhdr.hdrsize;
fseek(fil, offset, SEEK_SET);
fread(&domtrans, domainhdr.recsize, 1, fil);
domtrans.Deleted = TRUE;
fseek(fil, offset, SEEK_SET);
fwrite(&domtrans, domainhdr.recsize, 1, fil);
DomainUpdated = TRUE;
fclose(fil);
}
}
}
if (strncmp(pick, "M", 1) == 0) {
from = too = 0;
ftnd_mvprintw(LINES -3, 6, "Enter domain number (1..%d) to move >", records);
from = edit_int(LINES -3, 42, from, (char *)"Enter record number");
ftnd_locate(LINES -3, 6);
clrtoeol();
ftnd_mvprintw(LINES -3, 6, "Enter new position (1..%d) >", records);
too = edit_int(LINES -3, 36, too, (char *)"Enter destination record number, other will move away");
if ((from == too) || (from == 0) || (too == 0) || (from > records) || (too > records)) {
errmsg("That makes no sense");
} else if (yes_no((char *)"Proceed move")) {
snprintf(temp, PATH_MAX, "%s/etc/domain.temp", getenv("FTND_ROOT"));
if ((fil = fopen(temp, "r+")) != NULL) {
fseek(fil, ((from -1) * domainhdr.recsize) + domainhdr.hdrsize, SEEK_SET);
fread(&tdomtrans, domainhdr.recsize, 1, fil);
if (from > too) {
for (i = from; i > too; i
fseek(fil, ((i -2) * domainhdr.recsize) + domainhdr.hdrsize, SEEK_SET);
fread(&domtrans, domainhdr.recsize, 1, fil);
fseek(fil, ((i -1) * domainhdr.recsize) + domainhdr.hdrsize, SEEK_SET);
fwrite(&domtrans, domainhdr.recsize, 1, fil);
}
} else {
for (i = from; i < too; i++) {
fseek(fil, (i * domainhdr.recsize) + domainhdr.hdrsize, SEEK_SET);
fread(&domtrans, domainhdr.recsize, 1, fil);
fseek(fil, ((i -1) * domainhdr.recsize) + domainhdr.hdrsize, SEEK_SET);
fwrite(&domtrans, domainhdr.recsize, 1, fil);
}
}
fseek(fil, ((too -1) * domainhdr.recsize) + domainhdr.hdrsize, SEEK_SET);
fwrite(&tdomtrans, domainhdr.recsize, 1, fil);
fclose(fil);
DomainUpdated = TRUE;
}
}
}
if (strncmp(pick, "N", 1) == 0)
if ((o + 10) < records)
o = o + 10;
if (strncmp(pick, "P", 1) == 0)
if ((o - 10) >= 0)
o = o - 10;
if ((atoi(pick) >= 1) && (atoi(pick) <= records)) {
EditDomainRec(atoi(pick));
o = ((atoi(pick) - 1) / 10) * 10;
}
}
}
void InitDomain(void)
{
CountDomain();
OpenDomain();
CloseDomain(TRUE);
}
int domain_doc(FILE *fp, FILE *toc, int page)
{
char temp[PATH_MAX];
FILE *no, *wp;
int j;
snprintf(temp, PATH_MAX, "%s/etc/domain.data", getenv("FTND_ROOT"));
if ((no = fopen(temp, "r")) == NULL)
return page;
page = newpage(fp, page);
addtoc(fp, toc, 17, 0, page, (char *)"Domain manager");
j = 0;
wp = open_webdoc((char *)"domain.html", (char *)"Domain Translation", NULL);
fprintf(wp, "<A HREF=\"index.html\">Main</A>\n");
fprintf(wp, "<P>\n");
fprintf(wp, "<TABLE width='400' border='0' cellspacing='0' cellpadding='2'>\n");
// fprintf(wp, "<COL width='40%%'><COL width='40%%'><COL width='20%%'>\n");
fprintf(wp, "<TBODY>\n");
fprintf(wp, "<TR><TH align='left'>Fidonet</TH><TH align='left'>Internet</TH><TH align='left'>Active</TH></TR>\n");
fprintf(fp, "\n");
fprintf(fp, " Fidonet Internet Active\n");
fprintf(fp, "
fread(&domainhdr, sizeof(domainhdr), 1, no);
while ((fread(&domtrans, domainhdr.recsize, 1, no)) == 1) {
if (j == 50) {
page = newpage(fp, page);
fprintf(fp, "\n");
fprintf(fp, " Fidonet Internet Active\n");
fprintf(fp, "
j = 0;
}
fprintf(wp, "<TR><TD>%s</TD><TD>%s</TD><TD>%s</TD></TR>\n",
domtrans.ftndom, domtrans.intdom, getboolean(domtrans.Active));
fprintf(fp, " %-30s %-30s %s\n", domtrans.ftndom, domtrans.intdom, getboolean(domtrans.Active));
j++;
}
fprintf(wp, "</TBODY>\n");
fprintf(wp, "</TABLE>\n");
close_webdoc(wp);
fclose(no);
return page;
} |
import scala.util.Random
object Simulator {
val NumberOfSimulations: Int = 100000
def <API key>(options: Int, confidence: Double, simulations: Int) : Int = {
var done = false
var trials = 1
while(!done) {
<API key>(options, trials, confidence, simulations) match {
case Some(t) => done = true
case None => trials += 1
}
}
trials
}
def <API key>(choices: Int, trials: Int, confidence: Double, simulations: Int) : Option[Int] = {
val outcomes = SimulateNTimes(choices, trials, simulations)
<API key>(trials, confidence, simulations, outcomes)
}
def SimulateNTimes(choices: Int, trials: Int, simulations: Int) : Array[Int] = {
val rng = new Random()
val outcomes = new Array[Int](trials + 1)
// run Monte Carlo simulation
for (i <- 0 until simulations) {
// simulate flipping a (1/choices) coin for (trials) trials and return the size of the winning bin
// which must always be <= the number of trials
val max_agreement = Simulate(choices, trials, rng)
// update max_agreement count
outcomes(max_agreement) += 1
}
outcomes
}
def Simulate(choices: Int, trials: Int, r: Random) : Int = {
val histogram = new Array[Int](choices)
// randomly select one of k choices for j trials
for (j <- 0 until trials) {
histogram(r.nextInt(choices)) += 1
}
// return the size of the biggest bin
histogram.reduce((biggest, bin) => Math.max(biggest, bin))
}
def <API key>(choices: Int, trials: Int, num_agree: Int, simulations: Int) : Double = {
val outcomes = SimulateNTimes(choices, trials, simulations)
// return the probability that (num_agree) agreements occur
outcomes(num_agree).toDouble / simulations.toDouble
}
def <API key>(trials: Int, confidence: Double, simulations: Int, outcomes: Array[Int]) : Option[Int] = {
var i = 1
var p = 1.0
val alpha = 1.0 - confidence
while (i <= trials && p > alpha) {
var p_i = outcomes(i).toDouble / simulations.toDouble
p -= p_i
i += 1
}
if (i <= trials && p <= alpha) {
Some(i)
} else {
None
}
}
def HowManyMoreTrials(existing_trials: Int, agreement: Int, options: Int, confidence: Double) : Int = {
var num_addl_trials = 0
var done = false
while (!done) {
val expected = agreement + num_addl_trials
val min_required = <API key>(options, existing_trials + num_addl_trials, confidence, NumberOfSimulations)
min_required match {
case Some(min_req) =>
if (min_req > expected) {
num_addl_trials += 1
} else {
done = true
}
case None =>
num_addl_trials += 1
}
}
num_addl_trials
}
def invoked_as_name : String = {
"Simulator"
}
def usage() : Unit = {
val usage = "Usage: \n" +
"To determine the minimum number of trials to run for a given number of choices and confidence:\n" +
"\t" + invoked_as_name + " -r [num choices] [confidence]\n" +
"or\n" +
"To determine how many more trials to run for a given number of agreements, choices, and confidence:\n" +
"\t" + invoked_as_name + " -m [num trials already run] [num that agree] [num choices] [confidence]\n" +
"or\n" +
"To determine the (approximate) probability of having a given number of agreements for some number of choices and trials:\n" +
"\t" + invoked_as_name + " -p [num choices] [num trials] [num that agree]"
println(usage)
}
def validate_numchoices(num_choices: String) : Int = {
val num_choices_i = num_choices.toInt
if (num_choices_i < 2) {
println("ERROR: num_choices must be at least 2.")
usage()
sys.exit(1)
} else {
num_choices_i
}
}
def validate_numtrials(num_trials: String) : Int = {
val num_trials_i = num_trials.toInt
if (num_trials_i < 1) {
println("ERROR: num_trials must be at least 1.")
usage()
sys.exit(1)
} else {
num_trials_i
}
}
def validate_numagree(num_agree: String) : Int = {
val num_agree_i = num_agree.toInt
if (num_agree_i < 0) {
println("ERROR: num_agree must be at least zero.")
usage()
sys.exit(1)
} else {
num_agree_i
}
}
def validate_numrun(num_run: String) : Int = {
val num_run_i = num_run.toInt
if (num_run_i < 0) {
println("ERROR: num_run must be at least zero.")
usage()
sys.exit(1)
} else {
num_run_i
}
}
def validate_confidence(confidence: String) : Double = {
val conf_d = confidence.toDouble
if (conf_d < 0 || conf_d > 1) {
println("ERROR: confidence must be between zero and one inclusive.")
usage()
sys.exit(1)
} else {
conf_d
}
}
def parseOptions(arglist: List[String]) = {
arglist match {
case "-r" :: num_choices :: confidence :: _ =>
() => <API key>(validate_numchoices(num_choices),
validate_confidence(confidence),
NumberOfSimulations)
case "-m" :: num_run :: num_agree :: num_choices :: confidence :: _ =>
() => HowManyMoreTrials(validate_numrun(num_run),
validate_numagree(num_agree),
validate_numchoices(num_choices),
validate_confidence(confidence))
case "-p" :: num_choices :: num_trials :: num_agree :: _ =>
() => <API key>(validate_numchoices(num_choices),
validate_numtrials(num_trials),
validate_numagree(num_agree),
NumberOfSimulations)
case _ => {
usage()
sys.exit(1)
}
}
}
def main(args: Array[String]): Unit = {
val fn = parseOptions(args.toList)
println(fn())
}
} |
.VS-search .VS-icon {
background-repeat: no-repeat;
background-position: center center;
vertical-align: middle;
width: 16px; height: 16px;
}
.VS-search .VS-icon-cancel {
width: 11px; height: 11px;
background-position: center 0;
background-image: url("data:image/png;charset=utf-8;base64,iVBORw0KGgoAAAANSUhEUgAAAAsAAAAWCAYAAAAW5GZjAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAb9JREFUeNqUUr1qAkEQ3j0khQp6kihaeGgEEa18gTQR0iRY+<API key>+<API key>+BQODG6/W+A8MBNk3zfDAY3C6Xy0O2ZS6X6zMSiVwHg8FHLjtq7Xb7RQKj7BeTzVCgJ5PJU2U0GhUk7REuMpkMi8fjFggeMeecrVYrFRId0CgTAgDDMFg4HLbA8IjJgHNgGEr0er0fQIphUmZAwdSUADUB4RFDsz3oSMF6CLzZkQqgGebz+<API key>/9o+yMv7K4/HY/C/XhDUfr//jl7QQVT9fp/<API key>/NZjOmVKvVgq7rR/<API key>/R297mNW+sT2wUbUnA//V/nYrH4QOBNABUQuFQq3TNMuc82sDVrz41G42yvPeODAwZQ0QzwiJEnzLcAAwBJ6WXlwoBgZAAAAABJRU5ErkJggg==");
cursor: pointer;
}
.VS-search .VS-icon-cancel:hover {
background-position: center -11px;
}
.VS-search .VS-icon-search {
width: 12px; height: 12px;
background-image: url("data:image/png;charset=utf-8;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAIAAADZF8uwAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAUZJREFUeNpUUM2qgmAQzS8NiUgLzTIXLZQW1QuI9AY9QPSW9gQ9QiriwpJQEBVrVWT2d7p2L9xZzDdzZs7M+YYqy/J8Ptu2vd/<API key>/<API key>+Db5vo9nOp2iiWGYTqdDCMFe4LquI0aVpGmKR9M0lmUbjQY8YiBJklTb4YkoilBzOBzq9TogeMQIJEmqmlAlo9EIyXa7tSyrKAp4xEBkWUb5q2k8Hh+PR8/zwjCEgufz+<API key>/3/FBUJGu1+<API key>+3242qRNT+G0CMz7IMzH6//<API key>");
}
.VS-search div, .VS-search span, .VS-search a, .VS-search img,
.VS-search ul, .VS-search li, .VS-search form, .VS-search label,
.VS-interface ul, .VS-interface li, .VS-interface {
margin: 0;
padding: 0;
border: 0;
outline: 0;
font-weight: inherit;
font-style: inherit;
font-size: 100%;
font-family: inherit;
vertical-align: baseline;
}
.VS-search :focus {
outline: 0;
}
.VS-search {
line-height: 1;
color: black;
}
.VS-search ol, .VS-search ul {
list-style: none;
}
/* = General and Reset = */
.VS-search {
font-family: Arial, sans-serif;
color: #373737;
font-size: 12px;
}
.VS-search input {
display: block;
border: none;
-moz-box-shadow: none;
-webkit-box-shadow: none;
box-shadow: none;
outline: none;
margin: 0; padding: 4px;
background: transparent;
font-size: 16px;
line-height: 20px;
width: 100%;
}
.VS-interface, .VS-search .dialog, .VS-search input {
font-family: "Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, sans-serif !important;
line-height: 1.1em;
}
/* = Layout = */
.VS-search .VS-search-box {
cursor: text;
position: relative;
/*background: transparent;*/
border: 2px solid #ccc;
/*border-radius: 16px; -<API key>: 16px; -moz-border-radius: 16px;*/
/*background-color: #fafafa;*/
/*-webkit-box-shadow: inset 0px 0px 3px #ccc;*/
/*-moz-box-shadow: inset 0px 0px 3px #ccc;*/
/*box-shadow: inset 0px 0px 3px #ccc;*/
min-height: 28px;
height: auto;
}
.VS-search.VS-readonly .VS-search-box {
cursor: default;
}
.VS-search .VS-search-box.VS-focus {
border-color: #acf;
/*-webkit-box-shadow: inset 0px 0px 3px #acf;*/
/*-moz-box-shadow: inset 0px 0px 3px #acf;*/
/*box-shadow: inset 0px 0px 3px #acf;*/
}
.VS-search .VS-placeholder {
position: absolute;
top: 7px;
left: 4px;
margin: 0 20px 0 22px;
color: #808080;
font-size: 14px;
}
.VS-search .VS-search-box.VS-focus .VS-placeholder,
.VS-search .VS-search-box .VS-placeholder.VS-hidden {
display: none;
}
.VS-search .VS-search-inner {
position: relative;
margin: 0 20px 0 22px;
overflow: hidden;
}
.VS-search input {
width: 100px;
}
.VS-search input,
.VS-search .<API key> {
padding: 6px 0;
float: left;
color: #808080;
font: 13px/17px Helvetica, Arial;
}
.VS-search.VS-focus input {
color: #606060;
}
.VS-search .VS-icon-search {
position: absolute;
left: 9px; top: 8px;
}
.VS-search .VS-icon-cancel {
position: absolute;
right: 9px; top: 8px;
}
.VS-search.VS-readonly .VS-icon-cancel {
display: none;
}
/* = Search Facet = */
.VS-search .search_facet {
float: left;
margin: 0;
padding: 0 0 0 14px;
position: relative;
border: 1px solid transparent;
height: 20px;
margin: 3px -3px 3px 0;
}
.VS-search.VS-readonly .search_facet {
padding-left: 0;
}
.VS-search .search_facet.is_selected {
margin-left: -3px;
-<API key>: 16px;
-moz-border-radius: 16px;
border-radius: 16px;
background-color: #d2e6fd;
background-image: -moz-linear-gradient(top, #d2e6fd, #b0d1f9); /* FF3.6 */
background-image: -webkit-gradient(linear, left top, left bottom, from(#d2e6fd), to(#b0d1f9)); /* Saf4+, Chrome */
background-image: linear-gradient(top, #d2e6fd, #b0d1f9);
border: 1px solid #6eadf5;
}
.VS-search .search_facet .category {
float: left;
text-transform: uppercase;
font-weight: bold;
font-size: 10px;
color: #808080;
padding: 8px 0 5px;
line-height: 13px;
cursor: pointer;
padding: 4px 0 0;
}
.VS-search.VS-readonly .search_facet .category {
cursor: default;
}
.VS-search .search_facet.is_selected .category {
margin-left: 3px;
}
.VS-search .search_facet .<API key> {
float: left;
}
.VS-search .search_facet input {
margin: 0;
padding: 0;
color: #000;
font-size: 13px;
line-height: 16px;
padding: 5px 0 5px 4px;
height: 16px;
width: auto;
z-index: 100;
position: relative;
padding-top: 1px;
padding-bottom: 2px;
padding-right: 3px;
}
.VS-search .search_facet.is_editing input,
.VS-search .search_facet.is_selected input {
color: #000;
}
.VS-search.VS-readonly .search_facet .search_facet_remove {
display: none;
}
.VS-search .search_facet .search_facet_remove {
position: absolute;
left: 0;
top: 4px;
}
.VS-search .search_facet.is_selected .search_facet_remove {
opacity: 0.4;
left: 3px;
filter: alpha(opacity=40);
background-position: center -11px;
}
.VS-search .search_facet .search_facet_remove:hover {
opacity: 1;
}
.VS-search .search_facet.is_editing .category,
.VS-search .search_facet.is_selected .category {
color: #000;
}
.VS-search .search_facet.<API key> .category,
.VS-search .search_facet.<API key> input {
color: darkred;
}
/* = Search Input = */
.VS-search .search_input {
height: 28px;
float: left;
margin-left: -1px;
}
.VS-search .search_input input {
padding: 6px 3px 6px 2px;
line-height: 10px;
height: 22px;
margin-top: -4px;
width: 10px;
z-index: 100;
min-width: 4px;
position: relative;
}
.VS-search .search_input.is_editing input {
color: #202020;
}
/* = Autocomplete = */
.<API key> {
display: none;
}
.VS-interface.ui-autocomplete {
position: absolute;
border: 1px solid #C0C0C0;
border-top: 1px solid #D9D9D9;
background-color: #F6F6F6;
cursor: pointer;
z-index: 10000;
padding: 0;
margin: 0;
width: auto;
min-width: 80px;
max-width: 220px;
max-height: 240px;
overflow-y: auto;
overflow-x: hidden;
font-size: 13px;
top: 5px;
opacity: 0.97;
box-shadow: 3px 4px 5px -2px rgba(0, 0, 0, 0.5); -webkit-box-shadow: 3px 4px 5px -2px rgba(0, 0, 0, 0.5); -moz-box-shadow: 3px 4px 5px -2px rgba(0, 0, 0, 0.5);
}
.VS-interface.ui-autocomplete .<API key> {
text-transform: capitalize;
font-size: 11px;
padding: 4px 4px 4px;
border-top: 1px solid #A2A2A2;
border-bottom: 1px solid #A2A2A2;
background-color: #B7B7B7;
text-shadow: 0 -1px 0 #999;
font-weight: bold;
color: white;
cursor: default;
}
.VS-interface.ui-autocomplete .ui-menu-item {
float: none;
}
.VS-interface.ui-autocomplete .ui-menu-item a {
color: #000;
outline: none;
display: block;
padding: 3px 4px 5px;
border-radius: none;
line-height: 1;
background-color: #F8F8F8;
background-image: -moz-linear-gradient(top, #F8F8F8, #F3F3F3); /* FF3.6 */
background-image: -webkit-gradient(linear, left top, left bottom, from(#F8F8F8), to(#F3F3F3)); /* Saf4+, Chrome */
background-image: linear-gradient(top, #F8F8F8, #F3F3F3);
border-top: 1px solid #FAFAFA;
border-bottom: 1px solid #f0f0f0;
}
.VS-interface.ui-autocomplete .ui-menu-item a:active {
outline: none;
}
.VS-interface.ui-autocomplete .ui-menu-item .ui-state-hover, .VS-interface.ui-autocomplete .ui-menu-item .ui-state-focus {
background-color: #6483F7;
background-image: -moz-linear-gradient(top, #648bF5, #2465f3); /* FF3.6 */
background-image: -webkit-gradient(linear, left top, left bottom, from(#648bF5), to(#2465f3)); /* Saf4+, Chrome */
background-image: linear-gradient(top, #648bF5, #2465f3);
border-top: 1px solid #5b83ec;
border-bottom: 1px solid #1459e9;
border-left: none;
border-right: none;
color: white;
margin: 0;
}
.VS-interface.ui-autocomplete .ui-corner-all {
border-radius: 0;
}
.VS-interface.ui-autocomplete li {
list-style: none;
width: auto;
} |
#ifndef RAYSHADER_LIQUID_H_
# define RAYSHADER_LIQUID_H_
#include <GL/glut.h>
#include <vector>
#include "RipplePoint.h"
//TYPEDEF
typedef std::vector<float> t_HeightRow;
typedef std::vector<t_HeightRow> t_HeightMap2;
typedef std::vector<RipplePoint*> RippleList;
typedef std::vector<glm::vec3> t_HeightMap;
typedef std::vector<glm::vec3> t_NormalMap;
namespace liquid {
//ENUMERATOR
//the render modes for the liquid
enum e_RenderMode {
//don't render
NONE = 0,
//render as particle grid
GRID,
//pass as height map to be ray traced
RAYTRACE
};
} //liquid
class Liquid {
public:
//CONSTRUCTOR
/*!Creates a new liquid simulation
@heightMap a pointer to the height map of the turbulent liquid
@normalMap a pointer to the normals of the height map
@turbulentMin a pointer to the bottom of the turbulent liquid
@turbulentMax a pointer to the top of the turbulent water
@waterBottom a pointer to the bottom of the water*/
Liquid(t_HeightMap* heightMap, t_NormalMap* normalMap,
float* turbulentMin, float* turbulentMax, float* waterBottom,
float seconds);
//DESTRUCTOR
/*!Destroys this liquid*/
~Liquid();
//PUBLIC MEMBER FUNCTIONS
/*!Updates the liquid*/
void update(float seconds);
/*!Renders the liquid
@renderMode the rendering mode of the water*/
void render(liquid::e_RenderMode renderMode);
/*!Adds a ripple to the the liquid*/
void addRipple(RipplePoint* ripple);
/*!Sets the position of the sphere*/
void setSpherePos(float x, float y, float z);
void setVortex(bool vt);
void fill();
private:
//VARIABLES
//the dimensions of the grid (in cell size)
const glm::vec2 GRID_DIM;
//the size of a grid cell
float m_CellSize;
//the height map of the water
t_HeightMap2 m_HeightMap2;
float m_Level;
//the list of active ripple points
RippleList m_Ripples;
bool m_VortexOn;
glm::vec3 m_SpherePos;
float m_SphereRad;
float m_SphereRippleTimer;
bool m_SphereMove;
float m_SphereSpeed;
//ray tracing values
t_HeightMap* m_HeightMap;
t_NormalMap* m_NormalMap;
float* m_TurbulentMin;
float* m_TurbulentMax;
//time
float m_LastTime;
//MACROS
<API key>(Liquid);
//PRIVATE MEMBER FUNCTIONS
float vortex(const glm::vec2& point, float seconds);
/*!Renders the liquid as particles*/
void renderParticles();
/*!Renders the border of the liquid*/
void renderBorder();
/*!Renders the sphere*/
void renderSphere();
/*!Calculates and sets the ray tracing height map*/
void computeHeightMap();
};
#endif |
<?php
/**
* @file
* Contains \Drupal\menu_link_content\Entity\MenuLinkContent.
*/
namespace Drupal\menu_link_content\Entity;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\<API key>;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\FieldDefinition;
use Drupal\Core\Url;
class MenuLinkContent extends ContentEntityBase implements <API key> {
/**
* A flag for whether this entity is wrapped in a plugin instance.
*
* @var bool
*/
protected $insidePlugin = FALSE;
/**
* {@inheritdoc}
*/
public function setInsidePlugin() {
$this->insidePlugin = TRUE;
}
/**
* {@inheritdoc}
*/
public function getTitle() {
return $this->get('title')->value;
}
/**
* {@inheritdoc}
*/
public function getRouteName() {
return $this->get('route_name')->value;
}
/**
* {@inheritdoc}
*/
public function getRouteParameters() {
return $this->get('route_parameters')->first()->getValue();
}
/**
* {@inheritdoc}
*/
public function setRouteParameters(array $route_parameters) {
$this->set('route_parameters', array($route_parameters));
return $this;
}
/**
* {@inheritdoc}
*/
public function getUrl() {
return $this->get('url')->value ?: NULL;
}
/**
* {@inheritdoc}
*/
public function getUrlObject() {
if ($route_name = $this->getRouteName()) {
$url = new Url($route_name, $this->getRouteParameters(), $this->getOptions());
}
else {
$path = $this->getUrl();
if (isset($path)) {
$url = Url::createFromPath($path);
}
else {
$url = new Url('<front>');
}
}
return $url;
}
/**
* {@inheritdoc}
*/
public function getMenuName() {
return $this->get('menu_name')->value;
}
/**
* {@inheritdoc}
*/
public function getOptions() {
return $this->get('options')->first()->getValue();
}
/**
* {@inheritdoc}
*/
public function setOptions(array $options) {
$this->set('options', array($options));
return $this;
}
/**
* {@inheritdoc}
*/
public function getDescription() {
return $this->get('description')->value;
}
/**
* {@inheritdoc}
*/
public function getPluginId() {
return 'menu_link_content:' . $this->uuid();
}
/**
* {@inheritdoc}
*/
public function isHidden() {
return (bool) $this->get('hidden')->value;
}
/**
* {@inheritdoc}
*/
public function isExpanded() {
return (bool) $this->get('expanded')->value;
}
/**
* {@inheritdoc}
*/
public function getParentId() {
return $this->get('parent')->value;
}
/**
* {@inheritdoc}
*/
public function getWeight() {
return (int) $this->get('weight')->value;
}
/**
* Builds up the menu link plugin definition for this entity.
*
* @return array
* The plugin definition corresponding to this entity.
*
* @see \Drupal\Core\Menu\MenuLinkTree::$defaults
*/
protected function getPluginDefinition() {
$definition = array();
$definition['class'] = 'Drupal\menu_link_content\Plugin\Menu\MenuLinkContent';
$definition['menu_name'] = $this->getMenuName();
$definition['route_name'] = $this->getRouteName();
$definition['route_parameters'] = $this->getRouteParameters();
$definition['url'] = $this->getUrl();
$definition['options'] = $this->getOptions();
$definition['title'] = $this->getTitle();
$definition['description'] = $this->getDescription();
$definition['weight'] = $this->getWeight();
$definition['id'] = $this->getPluginId();
$definition['metadata'] = array('entity_id' => $this->id());
$definition['form_class'] = '\Drupal\menu_link_content\Form\MenuLinkContentForm';
$definition['hidden'] = $this->isHidden() ? 1 : 0;
$definition['expanded'] = $this->isExpanded() ? 1 : 0;
$definition['provider'] = 'menu_link_content';
$definition['discovered'] = 0;
$definition['parent'] = $this->getParentId();
return $definition;
}
/**
* {@inheritdoc}
*/
public function postSave(<API key> $storage, $update = TRUE) {
parent::postSave($storage, $update);
/** @var \Drupal\Core\Menu\<API key> $menu_link_manager */
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
// The menu link can just be updated if there is already an menu link entry
// on both entity and menu link plugin level.
if ($update && $menu_link_manager->getDefinition($this->getPluginId())) {
// When the entity is saved via a plugin instance, we should not call
// the menu tree manager to update the definition a second time.
if (!$this->insidePlugin) {
$menu_link_manager->updateDefinition($this->getPluginId(), $this->getPluginDefinition(), FALSE);
}
}
else {
$menu_link_manager->addDefinition($this->getPluginId(), $this->getPluginDefinition());
}
}
/**
* {@inheritdoc}
*/
public static function preDelete(<API key> $storage, array $entities) {
parent::preDelete($storage, $entities);
/** @var \Drupal\Core\Menu\<API key> $menu_link_manager */
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
foreach ($entities as $menu_link) {
/** @var \Drupal\menu_link_content\Entity\MenuLinkContent $menu_link */
$menu_link_manager->removeDefinition($menu_link->getPluginId(), FALSE);
}
}
/**
* {@inheritdoc}
*/
public static function <API key>(EntityTypeInterface $entity_type) {
$fields['id'] = FieldDefinition::create('integer')
->setLabel(t('Entity ID'))
->setDescription(t('The entity ID for this menu link content entity.'))
->setReadOnly(TRUE)
->setSetting('unsigned', TRUE);
$fields['uuid'] = FieldDefinition::create('uuid')
->setLabel(t('UUID'))
->setDescription(t('The content menu link UUID.'))
->setReadOnly(TRUE);
$fields['bundle'] = FieldDefinition::create('string')
->setLabel(t('Bundle'))
->setDescription(t('The content menu link bundle.'))
->setSetting('max_length', EntityTypeInterface::BUNDLE_MAX_LENGTH)
->setReadOnly(TRUE);
$fields['title'] = FieldDefinition::create('string')
->setLabel(t('Menu link title'))
->setDescription(t('The text to be used for this link in the menu.'))
->setRequired(TRUE)
->setTranslatable(TRUE)
->setSettings(array(
'default_value' => '',
'max_length' => 255,
))
->setDisplayOptions('view', array(
'label' => 'hidden',
'type' => 'string',
'weight' => -5,
))
->setDisplayOptions('form', array(
'type' => 'string',
'weight' => -5,
))
-><API key>('form', TRUE);
$fields['description'] = FieldDefinition::create('string')
->setLabel(t('Description'))
->setDescription(t('Shown when hovering over the menu link.'))
->setTranslatable(TRUE)
->setSettings(array(
'default_value' => '',
'max_length' => 255,
))
->setDisplayOptions('view', array(
'label' => 'hidden',
'type' => 'string',
'weight' => 0,
))
->setDisplayOptions('form', array(
'type' => 'string',
'weight' => 0,
));
$fields['menu_name'] = FieldDefinition::create('string')
->setLabel(t('Menu name'))
->setDescription(t('The menu name. All links with the same menu name (such as "tools") are part of the same menu.'))
->setSetting('default_value', 'tools');
$fields['route_name'] = FieldDefinition::create('string')
->setLabel(t('Route name'))
->setDescription(t('The machine name of a defined Symfony Route this menu item represents.'));
$fields['route_parameters'] = FieldDefinition::create('map')
->setLabel(t('Route parameters'))
->setDescription(t('A serialized array of route parameters of this menu link.'));
$fields['url'] = FieldDefinition::create('uri')
->setLabel(t('External link url'))
->setDescription(t('The url of the link, in case you have an external link.'));
$fields['options'] = FieldDefinition::create('map')
->setLabel(t('Options'))
->setDescription(t('A serialized array of options to be passed to the url() or l() function, such as a query string or HTML attributes.'))
->setSetting('default_value', array());
$fields['external'] = FieldDefinition::create('boolean')
->setLabel(t('External'))
->setDescription(t('A flag to indicate if the link points to a full URL starting with a protocol, like http:// (1 = external, 0 = internal).'))
->setSetting('default_value', FALSE);
$fields['weight'] = FieldDefinition::create('integer')
->setLabel(t('Weight'))
->setDescription(t('Link weight among links in the same menu at the same depth. In the menu, the links with high weight will sink and links with a low weight will be positioned nearer the top.'))
->setSetting('default_value', 0)
->setDisplayOptions('view', array(
'label' => 'hidden',
'type' => 'integer',
'weight' => 0,
))
->setDisplayOptions('form', array(
'type' => 'integer',
'weight' => 20,
));
$fields['expanded'] = FieldDefinition::create('boolean')
->setLabel(t('Show as expanded'))
->setDescription(t('If selected and this menu link has children, the menu will always appear expanded.'))
->setSetting('default_value', FALSE)
->setDisplayOptions('view', array(
'label' => 'hidden',
'type' => 'boolean',
'weight' => 0,
))
->setDisplayOptions('form', array(
'settings' => array('display_label' => TRUE),
'weight' => 0,
));
// @todo We manually create a form element for this, since the form logic is
// is inverted to show enabled. Flip this to a status field and use the
$fields['hidden'] = FieldDefinition::create('boolean')
->setLabel(t('Hidden'))
->setDescription(t('A flag for whether the link should be hidden in menus or rendered normally.'))
->setSetting('default_value', FALSE);
$fields['langcode'] = FieldDefinition::create('language')
->setLabel(t('Language code'))
->setDescription(t('The node language code.'));
$fields['parent'] = FieldDefinition::create('string')
->setLabel(t('Parent plugin ID'))
->setDescription(t('The ID of the parent menu link plugin, or empty string when at the top level of the hierarchy.'));
return $fields;
}
} |
app.views.LastPlannerView = Backbone.View.extend({
events: {
},
initialize: function(options){
this.project_id = options['project_id'];
},
render: function(){
_.each(this.$('.activity-wrap'), function(item){
var activity_id = $(item).attr('activity-id');
var activityCard = new app.views.ActivityCard({
el: $(item),
model: new app.models.Activity({id: activity_id})
});
}, this);
var date = moment($('.focal-date').attr('date-selected')).format('DD/MM/YYYY');
$('.focal-date').datepicker({
todayBtn: 'linked',
todayHighlight: true
});
$('.focal-date').datepicker('setDate', date);
$('.focal-date')
.on('changeDate', function(e){
var date = moment(e.date).format('YYYY-MM-DD');
var new_url = URI(window.location.href).setQuery({ date: date })
window.location = new_url;
});
}
}); |
<?php
header('Content-type:text/html; charset=utf-8');
define('DOING_AJAX', true);
$parse_uri = explode('wp-content', $_SERVER['SCRIPT_FILENAME']);
require_once($parse_uri[0] . 'wp-load.php');
require_once($parse_uri[0] . 'wp-admin/includes/admin.php');
if (!is_user_logged_in() || !current_user_can('edit_posts')) {
die(__('You must be logged in to access this script.', 'cmsms_form_builder'));
}
global $post;
if (isset($_POST['type']) && isset($_POST['option']) && isset($_POST['data'])) {
$post_type = $_POST['type'];
$post_option = $_POST['option'];
$post_data = $_POST['data'];
if ($post_type == 'form') {
if ($post_option == 'try') {
$args = array(
'post_type' => 'cmsms_contact_form',
'name' => $post_data,
'post_status' => 'publish',
'posts_per_page' => 1
);
$new_query = new WP_Query($args);
if ($new_query->have_posts()) :
while ($new_query->have_posts()) : $new_query->the_post();
$try = get_post(get_the_ID());
echo $try->post_name;
endwhile;
endif;
wp_reset_query();
} elseif ($post_option == 'delete') {
if (get_post($post_data) != NULL) {
$del_ids = array();
$del_ids[] = $post_data;
$args = array(
'post_type' => 'cmsms_contact_form',
'post_parent' => $post_data,
'post_status' => 'publish'
);
$new_query = new WP_Query($args);
if ($new_query->have_posts()) :
while ($new_query->have_posts()) : $new_query->the_post();
$del_ids[] = get_the_ID();
endwhile;
endif;
wp_reset_query();
foreach ($del_ids as $del_id) {
$del_post = wp_delete_post($del_id, true);
delete_post_meta($del_id, '<API key>');
delete_post_meta($del_id, '<API key>');
if (!isset($test_var)) {
$test_var = true;
echo $del_post->ID;
}
}
} else {
echo 'error';
}
} elseif ($post_option == 'edit') {
if (get_post($post_data) != NULL) {
$parent_post = array();
$parent_post[] = get_post($post_data);
$child_posts = get_posts(array(
'post_type' => 'cmsms_contact_form',
'post_parent' => $post_data,
'orderby' => 'menu_order',
'order' => 'ASC',
'posts_per_page' => -1
));
$posts = array_merge($parent_post, $child_posts);
$results = array();
for ($i = 0; $i < sizeof($posts); $i++) {
$results[$i] = (object) array(
'id' => $posts[$i]->ID,
'label' => $posts[$i]->post_title,
'slug' => $posts[$i]->post_name,
'type' => $posts[$i]->post_excerpt,
'number' => $posts[$i]->menu_order,
'parent_slug' => $posts[$i]->post_parent,
'value' => unserialize($posts[$i]->post_content),
'description' => unserialize(get_post_meta($posts[$i]->ID, '<API key>', true)),
'parameters' => unserialize(get_post_meta($posts[$i]->ID, '<API key>', true))
);
}
$out = json_encode($results);
echo $out;
} else {
echo 'error';
}
}
} elseif ($post_type == 'fields') {
if ($post_option == 'add') {
$data = json_decode(stripslashes($post_data));
if (get_post($data[0]->slug) == NULL) {
foreach ($data as $data_cell) {
$ins_post_ID = wp_insert_post(array(
'post_title' => wp_strip_all_tags($data_cell->label),
'post_name' => generateSlug(wp_strip_all_tags($data_cell->label), 30),
'post_excerpt' => $data_cell->type,
'menu_order' => $data_cell->number,
'post_parent' => 0,
'post_content' => serialize($data_cell->value),
'post_status' => 'publish',
'post_type' => 'cmsms_contact_form'
));
add_post_meta($ins_post_ID, '<API key>', serialize($data_cell->description));
add_post_meta($ins_post_ID, '<API key>', serialize($data_cell->parameters));
if (!isset($test_var)) {
$test_var = true;
$parent_id = $ins_post_ID;
echo $parent_id . ':' . $data_cell->label;
}
wp_update_post(array(
'ID' => $ins_post_ID,
'post_parent' => $parent_id,
'post_type' => 'cmsms_contact_form'
));
}
} else {
echo 'error';
}
} elseif ($post_option == 'delete') {
if (get_post($post_data) != NULL) {
wp_delete_post($post_data, true);
delete_post_meta($post_data, '<API key>');
delete_post_meta($post_data, '<API key>');
} else {
echo 'error';
}
} elseif ($post_option == 'update') {
$data = json_decode(stripslashes($post_data));
$parent_id = $data[0]->id;
if (get_post($data[0]->slug) == NULL) {
foreach ($data as $data_cell) {
if ($data_cell->id != '') {
$upd_post_ID = wp_update_post(array(
'ID' => $data_cell->id,
'post_title' => wp_strip_all_tags($data_cell->label),
'post_name' => generateSlug(wp_strip_all_tags($data_cell->label), 30),
'post_excerpt' => $data_cell->type,
'menu_order' => $data_cell->number,
'post_parent' => $parent_id,
'post_content' => serialize($data_cell->value),
'post_status' => 'publish',
'post_type' => 'cmsms_contact_form'
));
update_post_meta($upd_post_ID, '<API key>', serialize($data_cell->description));
update_post_meta($upd_post_ID, '<API key>', serialize($data_cell->parameters));
if (!isset($test_var)) {
$test_var = true;
$try = get_post($upd_post_ID);
echo $parent_id . ':' . $try->post_title;
}
} else {
$ins_post_ID = wp_insert_post(array(
'post_title' => wp_strip_all_tags($data_cell->label),
'post_name' => generateSlug(wp_strip_all_tags($data_cell->label), 30),
'post_excerpt' => $data_cell->type,
'menu_order' => $data_cell->number,
'post_parent' => 0,
'post_content' => serialize($data_cell->value),
'post_status' => 'publish',
'post_type' => 'cmsms_contact_form'
));
add_post_meta($ins_post_ID, '<API key>', serialize($data_cell->description));
add_post_meta($ins_post_ID, '<API key>', serialize($data_cell->parameters));
wp_update_post(array(
'ID' => $ins_post_ID,
'post_parent' => $parent_id,
'post_type' => 'cmsms_contact_form'
));
}
}
} else {
echo 'error';
}
} else {
echo 'error';
}
} else {
echo 'error';
}
} else {
echo 'error';
} |
<?
# Lifter002: TODO
# Lifter007: TODO
# Lifter003: TODO
# Lifter010: TODO
/**
* <API key>.class.php
*
*
*
*
* @author Peter Thienel <pthienel@web.de>, Suchi & Berg GmbH <info@data-quest.de>
* @access public
* @modulegroup extern
* @module <API key>
* @package studip_extern
*/
// This file is part of Stud.IP
// <API key>.class.php
// Suchi & Berg GmbH <info@data-quest.de>
// This program is free software; you can redistribute it and/or
// as published by the Free Software Foundation; either version 2
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
require_once '<API key>.class.php';
class <API key> extends <API key> {
var $attributes = array('semstart', 'semrange', 'semswitch', 'aliaswise',
'aliassose', 'semclass');
/**
* Constructor
*
* @param array config
*/
function <API key> ($config = '') {
if ($config)
$this->config = $config;
$this->name = '<API key>';
$this->real_name = _("Lehrveranstaltungen");
$this->description = _("Angaben zur Ausgabe von Lehrveranstaltungen.");
}
function getDefaultConfig () {
$config = array(
'semstart' => '',
'semrange' => '',
'semswitch' => '',
'aliaswise' => _("Wintersemester"),
'aliassose' => _("Sommersemester"),
'semclass' => '|1'
);
return $config;
}
function toStringEdit ($post_vars = '', $faulty_values = '',
$edit_form = '', $anker = '') {
// get semester data
$semester = new SemesterData();
$semester_data = $semester->getAllSemesterData();
$out = '';
$table = '';
if ($edit_form == '')
$edit_form = new ExternEditModule($this->config, $post_vars, $faulty_values, $anker);
$edit_form->setElementName($this->getName());
$element_headline = $edit_form->editElementHeadline($this->real_name,
$this->config->getName(), $this->config->getId(), TRUE, $anker);
$headline = $edit_form->editHeadline(_("Allgemeine Angaben"));
$title = _("Startsemester:");
$info = _("Geben Sie das erste anzuzeigende Semester an. Die Angaben \"vorheriges\", \"aktuelles\" und \"nächstes\" beziehen sich immer auf das laufende Semester und werden automatisch angepasst.");
$current_sem = <API key>();
if ($current_sem === FALSE) {
$names = array(_("keine Auswahl"), _("aktuelles"), _("nächstes"));
$values = array("", "current", "next");
}
else if ($current_sem === TRUE) {
$names = array(_("keine Auswahl"), _("vorheriges"), _("aktuelles"));
$values = array("", "previous", "current");
}
else {
$names = array(_("keine Auswahl"), _("vorheriges"), _("aktuelles"), "nächstes");
$values = array("", "previous", "current", "next");
}
foreach ($semester_data as $sem_num => $sem) {
$names[] = $sem["name"];
$values[] = $sem_num + 1;
}
$table = $edit_form->editOptionGeneric("semstart", $title, $info, $values, $names);
$title = _("Anzahl der anzuzeigenden Semester:");
$info = _("Geben Sie an, wieviele Semester (ab o.a. Startsemester) angezeigt werden sollen.");
$names = array(_("keine Auswahl"));
$values = array("");
$i = 1;
foreach ($semester_data as $sem_num => $sem) {
$names[] = $i++;
$values[] = $sem_num + 1;
}
$table .= $edit_form->editOptionGeneric("semrange", $title, $info, $values, $names);
$title = _("Umschalten des aktuellen Semesters:");
$info = _("Geben Sie an, wieviele Wochen vor Semesterende automatisch auf das nächste Semester umgeschaltet werden soll.");
$names = array(_("keine Auswahl"), _("am Semesterende"), _("1 Woche vor Semesterende"));
for ($i = 2; $i < 13; $i++)
$names[] = sprintf(_("%s Wochen vor Semesterende"), $i);
$values = array("", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12");
$table .= $edit_form->editOptionGeneric("semswitch", $title, $info, $values, $names);
$title = _("Bezeichnung Sommersemester:");
$info = _("Alternative Bezeichnung für den Begriff \"Sommersemester\".");
$table .= $edit_form-><API key>("aliassose", $title, $info, 40, 80);
$title = _("Bezeichnung Wintersemester:");
$info = _("Alternative Bezeichnung für den Begriff \"Wintersemester\".");
$table .= $edit_form-><API key>("aliaswise", $title, $info, 40, 80);
$title = _("<API key>:");
$info = _("Wählen Sie aus, welche <API key> angezeigt werden sollen.");
foreach ($GLOBALS['SEM_CLASS'] as $key => $lecture_class) {
$class_names[] = $lecture_class['name'];
$class_values[] = $key;
}
$table .= $edit_form->editCheckboxGeneric("semclass", $title, $info, $class_values, $class_names);
$content_table .= $edit_form->editContentTable($headline, $table);
$content_table .= $edit_form->editBlankContent();
$submit = $edit_form->editSubmit($this->config->getName(),
$this->config->getId(), $this->getName());
$out = $edit_form->editContent($content_table, $submit);
$out .= $edit_form->editBlank();
return $element_headline . $out;
}
function checkValue ($attribute, $value) {
if ($attribute == 'semclass') {
if (!sizeof($_POST[$this->getName() . '_semclass'])) {
return true;
}
}
return FALSE;
}
}
?> |
# -*- coding: utf-8 -*-
from django.db import models
class RssFeed(models.Model):
url = models.URLField(unique=True, db_index=True, default='')
name = models.CharField(blank=True, default='', max_length=100)
lastmodified = models.DateTimeField(editable=False, auto_now=True,
auto_now_add=True, db_index=True)
def __unicode__(self):
if self.name:
return "{}".format(self.name)
elif self.url:
return "RssFeed {}".format(self.url)
else:
return "RssFeed {}".format(self.pk)
class RssArticle(models.Model):
feed = models.ForeignKey(RssFeed)
url = models.URLField(max_length=200, db_index=True, default='')
snippet = models.CharField(max_length=500, default='', blank=True)
is_read = models.BooleanField(default=True)
lastmodified = models.DateTimeField(editable=False, auto_now=True,
auto_now_add=True, db_index=True)
def __unicode__(self):
if self.url:
return "{} {} {}".format(self.feed, self.url, self.snippet[:10])
else:
return "RssArticle {}".format(self.pk)
class Meta:
unique_together = ['feed', 'url'] |
package org.nadozirny_sv.ua.cubic;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.<API key>;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
public final class MainActivity extends AppCompatActivity implements View.OnClickListener,<API key> {
final String mainFolder="/Notes";
private RecyclerView mRecyclerView;
private ProgressBar progressBar;
private NotesAdapter adapter;
private AsyncTask<String, Void, Integer> dataloader;
public ImageButton add_item;
private DrawerLayout mDrawerLayout;
private RelativeLayout mDrawerView;
private ListView mListDeleted;
private LinearLayout mDeletedLayout;
private ArrayList<HashMap<String,Object>> filenames=new ArrayList<HashMap<String,Object>>();
private UndeleteAdapter listAdapter;
private int selected=0;
private MenuItem menuDel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notes_list);
String state = Environment.<API key>();
if (Environment.MEDIA_MOUNTED.equals(state) && !Environment.<API key>.equals(state)) {
if (!(new File(Environment.<API key>()+mainFolder)).exists()) {
new File(Environment.<API key>() + mainFolder).mkdir();
startActivity(new Intent(this, AboutActivity.class));
}
DestDir.get().path=new File(Environment.<API key>()+mainFolder).getAbsolutePath();
}else{
DestDir.get().path=getFilesDir().getAbsolutePath();
}
mRecyclerView=(RecyclerView)findViewById(R.id.notes_list);
mRecyclerView.setLayoutManager(new <API key>(1, <API key>.VERTICAL));
progressBar=(ProgressBar)findViewById(R.id.notes_progress);
add_item= (ImageButton) findViewById(R.id.add_item);
add_item.setOnClickListener(this);
progressBar.setVisibility(View.VISIBLE);
adapter=new NotesAdapter(this);
progressBar.setVisibility(View.GONE);
mRecyclerView.setAdapter(adapter);
ItemTouchHelper.SimpleCallback <API key> =
new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
@Override
public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
if (dX<0) {
View itemView = viewHolder.itemView;
Paint p = new Paint();
p.setARGB(255, 255, 0, 0);
c.drawRect((float) itemView.getLeft(), (float) itemView.getTop(), itemView.getRight()-dX,
(float) itemView.getBottom(), p);
Bitmap b = BitmapFactory.decodeResource(getResources(), android.R.drawable.ic_menu_delete);
int posY=viewHolder.itemView.getTop()+(viewHolder.itemView.getHeight()/2-b.getHeight()/2);
int posX=viewHolder.itemView.getWidth()-b.getWidth();
c.drawBitmap(b, posX, posY, p);
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}
}
}
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder viewHolder1) {
return false;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int i) {
switch(i){
case ItemTouchHelper.LEFT:
adapter.deleteItem(viewHolder.getAdapterPosition());
adapter.notifyItemRemoved(viewHolder.getAdapterPosition());
break;
}
}
};
new ItemTouchHelper(<API key>).<API key>(mRecyclerView);
dataloader=new AsyncLoadtask().execute("");
try {
getSupportActionBar().<API key>(true);
getSupportActionBar().setIcon(R.mipmap.ic_launcher);
}catch(Exception e){
e.printStackTrace();
}
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerView= (RelativeLayout) findViewById(R.id.left_drawer);
mListDeleted=(ListView)findViewById(R.id.deleted);
mDeletedLayout= (LinearLayout) findViewById(R.id.deleted_layout);
adapter.addDeleted=this;
adapter.selectItem=new SelectInterface() {
@Override
public void select(int pos,boolean state) {
if (state){
selected++;
}else{
selected
}
if (selected > 0) {
menuDel.setVisible(true);
}else{
menuDel.setVisible(false);
}
}
};
listAdapter = new UndeleteAdapter(this, R.layout.deleted, filenames);
adapter.clearOldBackup(false);
mListDeleted.setAdapter(listAdapter);
listAdapter.recoverer=new <API key>() {
@Override
public void recoverNote(String name,int i) {
adapter.recoverNote(name);
filenames.remove(i);
listAdapter.<API key>();
adapter.loaddata("");
adapter.<API key>();
if (filenames.size()==0){
mDeletedLayout.setVisibility(View.GONE);
}
}
};
Button mUndelete = (Button) findViewById(R.id.buttonUndelete);
mUndelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//clear recycled files and hide recycle.bin
adapter.clearOldBackup(true);
filenames.clear();
listAdapter.<API key>();
adapter.loaddata("");
adapter.<API key>();
mDeletedLayout.setVisibility(View.GONE);
}
});
}
@Override
public void <API key>(Configuration cfg){
super.<API key>(cfg);
if (Configuration.<API key>==cfg.orientation){
mRecyclerView.setLayoutManager(new <API key>(2, <API key>.VERTICAL));
}else{
mRecyclerView.setLayoutManager(new <API key>(1, <API key>.VERTICAL));
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.<API key>, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
menuDel = menu.findItem(R.id.action_delete);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.<API key>(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String query) {
loadByText(query);
return true;
}
});
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean <API key>(MenuItem item) {
switch(item.getItemId()){
case R.id.action_about:
startActivity(new Intent(this,AboutActivity.class));
return true;
case R.id.action_delete:
adapter.deletedSelected();
selected=0;
menuDel.setVisible(false);
return true;
}
return super.<API key>(item);
}
@Override
public void onClick(View v) {
int[] color_id={R.id.white,R.id.orange_300,R.id.brown_300,R.id.yellow_300,
R.id.red_300,R.id.blue_200,R.id.green_300, R.id.pink_200 };
int[] colors={R.color.white,R.color.orange_300,R.color.brown_300,R.color.yellow_300,
R.color.red_300,R.color.blue_400,R.color.green_300,R.color.pink_200};
for(int i=0;i<color_id.length;i++) {
if (v.getId()==color_id[i]){
adapter.setItemsColor(getResources().getColor(colors[i]));
mDrawerLayout.closeDrawer(mDrawerView);
selected=0;
return;
}
}
switch(v.getId()) {
case R.id.add_item:
adapter.insertItem("Note_" + new SimpleDateFormat("yyMMdd").format(new Date()));
mRecyclerView.scrollToPosition(0);
adapter.editItem(0);
break;
}
}
public void loadByText(String query) {
if (dataloader!=null)
if (dataloader.getStatus() == AsyncLoadtask.Status.RUNNING)
dataloader.cancel(true);
dataloader=new AsyncLoadtask().execute(query);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==1 && resultCode==1)
{
adapter.loaddata("");
adapter.<API key>();
}
}
@Override
public void addDeletedItem(File file) {
HashMap<String,Object> item=new HashMap<String,Object>();
item.put("Name",file.getName());
item.put("selected", false);
filenames.add(item);
listAdapter.<API key>();
mDeletedLayout.setVisibility(View.VISIBLE);
}
public class AsyncLoadtask extends AsyncTask<String,Void,Integer>{
@Override
protected void onPreExecute(){
progressBar.setVisibility(View.VISIBLE);
progressBar.setIndeterminate(true);
}
@Override
protected Integer doInBackground(String... params) {
Integer result=0;
adapter.loaddata(params[0]);
return result;
}
@Override
protected void onPostExecute(Integer result){
adapter.<API key>();
progressBar.setVisibility(View.GONE);
}
}
} |
package com.github.smeny.jpc.emulator.execution.opcodes.pm;
import com.github.smeny.jpc.emulator.execution.*;
import com.github.smeny.jpc.emulator.execution.decoder.*;
import com.github.smeny.jpc.emulator.processor.*;
import com.github.smeny.jpc.emulator.processor.fpu64.*;
import static com.github.smeny.jpc.emulator.processor.Processor.*;
public class fsubr_ST7_ST1 extends Executable
{
public fsubr_ST7_ST1(int blockStart, int eip, int prefices, PeekableInputStream input)
{
super(blockStart, eip);
int modrm = input.readU8();
}
public Branch execute(Processor cpu)
{
double freg0 = cpu.fpu.ST(7);
double freg1 = cpu.fpu.ST(1);
if ((freg0 == Double.NEGATIVE_INFINITY && freg1 == Double.NEGATIVE_INFINITY) || (freg0 == Double.POSITIVE_INFINITY && freg1 == Double.POSITIVE_INFINITY))
cpu.fpu.setInvalidOperation();
cpu.fpu.setST(7, freg1-freg0);
return Branch.None;
}
public boolean isBranch()
{
return false;
}
public String toString()
{
return this.getClass().getName();
}
} |
<?php
/**
* Signals to the factory that the instance can be reused.
*
* Instances of this interface are treated as static. Once you initialise the
* instance, it's kept and used again each time you reference the class using
* the factory.
*
* For instance, the following will remember the initial value:
*
* <code>
* class Abc_Class implements \Textpattern\Container\ReusableInterface
* {
* public $random;
* public function __construct()
* {
* $this->random = rand();
* }
* }
* echo Txp::get('Abc_Class')->random;
* echo Txp::get('Abc_Class')->random;
* echo Txp::get('Abc_Class')->random;
* </code>
*
* All three calls return the same Abc_Class::$random as the instance is kept
* between calls.
*
* @since 4.6.0
* @package Container
*/
namespace Textpattern\Container;
interface ReusableInterface
{
} |
#include "mesh.h"
#include "mesh_xml.h"
#include "aux_texture.h"
#include "aux_logo.h"
#include "vegastrike.h"
#include <iostream>
#include <fstream>
#include <expat.h>
#include <float.h>
#include <assert.h>
#include "ani_texture.h"
#ifndef _WIN32
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#else
#include <direct.h>
#include <process.h>
#endif
#if !defined (_WIN32) && !(defined (__APPLE__) || defined (MACOSX ) ) && !defined (BSD) && !defined(__HAIKU__)
#include <values.h>
#endif
#include "xml_support.h"
#include "vec.h"
#include "config_xml.h"
#include "vs_globals.h"
#include "cmd/script/mission.h"
#include "cmd/script/flightgroup.h"
#include "hashtable.h"
#ifdef max
#undef max
#endif
static inline float max( float x, float y )
{
if (x > y) return x;
else return y;
}
#ifdef min
#undef min
#endif
static inline float min( float x, float y )
{
if (x < y) return x;
else return y;
}
using XMLSupport::EnumMap;
using XMLSupport::Attribute;
using XMLSupport::AttributeList;
using XMLSupport::parse_float;
using XMLSupport::parse_bool;
using XMLSupport::parse_int;
struct GFXMaterial;
const EnumMap::Pair MeshXML::element_names[] = {
EnumMap::Pair( "UNKNOWN", MeshXML::UNKNOWN ),
EnumMap::Pair( "Material", MeshXML::MATERIAL ),
EnumMap::Pair( "LOD", MeshXML::LOD ),
EnumMap::Pair( "Ambient", MeshXML::AMBIENT ),
EnumMap::Pair( "Diffuse", MeshXML::DIFFUSE ),
EnumMap::Pair( "Specular", MeshXML::SPECULAR ),
EnumMap::Pair( "Emissive", MeshXML::EMISSIVE ),
EnumMap::Pair( "Mesh", MeshXML::MESH ),
EnumMap::Pair( "Points", MeshXML::POINTS ),
EnumMap::Pair( "Point", MeshXML::POINT ),
EnumMap::Pair( "Location", MeshXML::LOCATION ),
EnumMap::Pair( "Normal", MeshXML::NORMAL ),
EnumMap::Pair( "Polygons", MeshXML::POLYGONS ),
EnumMap::Pair( "Line", MeshXML::LINE ),
EnumMap::Pair( "Tri", MeshXML::TRI ),
EnumMap::Pair( "Quad", MeshXML::QUAD ),
EnumMap::Pair( "Linestrip", MeshXML::LINESTRIP ),
EnumMap::Pair( "Tristrip", MeshXML::TRISTRIP ),
EnumMap::Pair( "Trifan", MeshXML::TRIFAN ),
EnumMap::Pair( "Quadstrip", MeshXML::QUADSTRIP ),
EnumMap::Pair( "Vertex", MeshXML::VERTEX ),
EnumMap::Pair( "Logo", MeshXML::LOGO ),
EnumMap::Pair( "Ref", MeshXML::REF ),
EnumMap::Pair( "DetailPlane", MeshXML::DETAILPLANE )
};
const EnumMap::Pair MeshXML::attribute_names[] = {
EnumMap::Pair( "UNKNOWN", MeshXML::UNKNOWN ),
EnumMap::Pair( "Scale", MeshXML::SCALE ),
EnumMap::Pair( "Blend", MeshXML::BLENDMODE ),
EnumMap::Pair( "alphatest", MeshXML::ALPHATEST ),
EnumMap::Pair( "texture", MeshXML::TEXTURE ),
EnumMap::Pair( "technique", MeshXML::TECHNIQUE ),
EnumMap::Pair( "alphamap", MeshXML::ALPHAMAP ),
EnumMap::Pair( "sharevertex", MeshXML::SHAREVERT ),
EnumMap::Pair( "red", MeshXML::RED ),
EnumMap::Pair( "green", MeshXML::GREEN ),
EnumMap::Pair( "blue", MeshXML::BLUE ),
EnumMap::Pair( "alpha", MeshXML::ALPHA ),
EnumMap::Pair( "power", MeshXML::POWER ),
EnumMap::Pair( "reflect", MeshXML::REFLECT ),
EnumMap::Pair( "x", MeshXML::X ),
EnumMap::Pair( "y", MeshXML::Y ),
EnumMap::Pair( "z", MeshXML::Z ),
EnumMap::Pair( "i", MeshXML::I ),
EnumMap::Pair( "j", MeshXML::J ),
EnumMap::Pair( "k", MeshXML::K ),
EnumMap::Pair( "Shade", MeshXML::FLATSHADE ),
EnumMap::Pair( "point", MeshXML::POINT ),
EnumMap::Pair( "s", MeshXML::S ),
EnumMap::Pair( "t", MeshXML::T ),
//Logo stuffs
EnumMap::Pair( "Type", MeshXML::TYPE ),
EnumMap::Pair( "Rotate", MeshXML::ROTATE ),
EnumMap::Pair( "Weight", MeshXML::WEIGHT ),
EnumMap::Pair( "Size", MeshXML::SIZE ),
EnumMap::Pair( "Offset", MeshXML::OFFSET ),
EnumMap::Pair( "meshfile", MeshXML::LODFILE ),
EnumMap::Pair( "Animation", MeshXML::ANIMATEDTEXTURE ),
EnumMap::Pair( "Reverse", MeshXML::REVERSE ),
EnumMap::Pair( "LightingOn", MeshXML::LIGHTINGON ),
EnumMap::Pair( "CullFace", MeshXML::CULLFACE ),
EnumMap::Pair( "ForceTexture", MeshXML::FORCETEXTURE ),
EnumMap::Pair( "UseNormals", MeshXML::USENORMALS ),
EnumMap::Pair( "UseTangents", MeshXML::USETANGENTS ),
EnumMap::Pair( "PolygonOffset", MeshXML::POLYGONOFFSET ),
EnumMap::Pair( "DetailTexture", MeshXML::DETAILTEXTURE ),
EnumMap::Pair( "FramesPerSecond", MeshXML::FRAMESPERSECOND )
};
const EnumMap MeshXML::element_map( MeshXML::element_names, sizeof (MeshXML::element_names)/sizeof (MeshXML::element_names[0]) );
const EnumMap MeshXML::attribute_map( MeshXML::attribute_names,
sizeof (MeshXML::attribute_names)/sizeof (MeshXML::attribute_names[0]) );
void Mesh::beginElement( void *userData, const XML_Char *name, const XML_Char **atts )
{
MeshXML *xml = (MeshXML*) userData;
xml->mesh->beginElement( xml, name, AttributeList( atts ) );
}
void Mesh::endElement( void *userData, const XML_Char *name )
{
MeshXML *xml = (MeshXML*) userData;
xml->mesh->endElement( xml, std::string( name ) );
}
enum BLENDFUNC parse_alpha( const char *tmp )
{
if (strcmp( tmp, "ZERO" ) == 0)
return ZERO;
if (strcmp( tmp, "ONE" ) == 0)
return ONE;
if (strcmp( tmp, "SRCCOLOR" ) == 0)
return SRCCOLOR;
if (strcmp( tmp, "INVSRCCOLOR" ) == 0)
return INVSRCCOLOR;
if (strcmp( tmp, "SRCALPHA" ) == 0)
return SRCALPHA;
if (strcmp( tmp, "INVSRCALPHA" ) == 0)
return INVSRCALPHA;
if (strcmp( tmp, "DESTALPHA" ) == 0)
return DESTALPHA;
if (strcmp( tmp, "INVDESTALPHA" ) == 0)
return INVDESTALPHA;
if (strcmp( tmp, "DESTCOLOR" ) == 0)
return DESTCOLOR;
if (strcmp( tmp, "INVDESTCOLOR" ) == 0)
return INVDESTCOLOR;
if (strcmp( tmp, "SRCALPHASAT" ) == 0)
return SRCALPHASAT;
if (strcmp( tmp, "CONSTALPHA" ) == 0)
return CONSTALPHA;
if (strcmp( tmp, "INVCONSTALPHA" ) == 0)
return INVCONSTALPHA;
if (strcmp( tmp, "CONSTCOLOR" ) == 0)
return CONSTCOLOR;
if (strcmp( tmp, "INVCONSTCOLOR" ) == 0)
return INVCONSTCOLOR;
return ZERO;
}
#if 0
std::string parse_alpha( enum BLENDMODE tmp )
{
switch (tmp)
{
case ZERO:
return "ZERO";
case ONE:
return "ONE";
case SRCCOLOR:
return "SRCCOLOR";
case INVSRCCOLOR:
return "INVSRCCOLOR";
case SRCALPHA:
return "SRCALPHA";
case INVSRCALPHA:
return "INVSRCALPHA";
case DESTALPHA:
return "DESTALPHA";
case INVDESTALPHA:
return "INVDESTALPHA";
case DESTCOLOR:
return "DESTCOLOR";
case INVDESTCOLOR:
return "INVDESTCOLOR";
case SRCALPHASAT:
return "SRCALPHASAT";
case CONSTALPHA:
return "CONSTALPHA";
case INVCONSTALPHA:
return "INVCONSTALPHA";
case CONSTCOLOR:
return "CONSTCOLOR";
case INVCONSTCOLOR:
return "INVCONSTCOLOR";
}
return ZERO;
}
#endif
/* Load stages:
*
* 0 - no tags seen
* 1 - waiting for points
* 2 - processing points
* 3 - done processing points, waiting for face data
*
* Note that this is only a debugging aid. Once DTD is written, there
* will be no need for this sort of checking
*/
bool shouldreflect( string r )
{
if (strtoupper( r ) == "FALSE")
return false;
int i;
for (i = 0; i < (int) r.length(); ++i)
if (r[i] != '0' && r[i] != '.' && r[i] != '+' && r[i] != 'e')
return true;
return false;
}
void Mesh::beginElement( MeshXML *xml, const string &name, const AttributeList &attributes )
{
static bool use_detail_texture = XMLSupport::parse_bool( vs_config->getVariable( "graphics", "use_detail_texture", "true" ) );
//static bool flatshadeit=false;
AttributeList::const_iterator iter;
float flotsize = 1;
MeshXML::Names elem = (MeshXML::Names) MeshXML::element_map.lookup( name );
MeshXML::Names top; //FIXME If state stack is empty, top is used uninitialized !!!
top = MeshXML::UNKNOWN; //FIXME this line temporarily added by chuck_starchaser
if (xml->state_stack.size() > 0)
top = *xml->state_stack.rbegin();
xml->state_stack.push_back( elem );
bool texture_found = false;
switch (elem)
{
case MeshXML::DETAILPLANE:
if (use_detail_texture) {
Vector vec( detailPlanes.size() >= 2 ? 1 : 0, detailPlanes.size() == 1 ? 1 : 0, detailPlanes.size() == 0 ? 1 : 0 );
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( MeshXML::attribute_map.lookup( (*iter).name ) )
{
case MeshXML::X:
vec.i = XMLSupport::parse_float( iter->value );
break;
case MeshXML::Y:
vec.j = XMLSupport::parse_float( iter->value );
break;
case MeshXML::Z:
vec.k = XMLSupport::parse_float( iter->value );
break;
}
}
static float detailscale = XMLSupport::parse_float( vs_config->getVariable( "graphics", "<API key>", "1" ) );
if (detailPlanes.size() < 6)
detailPlanes.push_back( vec*detailscale );
}
break;
case MeshXML::MATERIAL:
//assert(xml->load_stage==4);
xml->load_stage = 7;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( MeshXML::attribute_map.lookup( (*iter).name ) )
{
case MeshXML::USENORMALS:
xml->usenormals = XMLSupport::parse_bool( iter->value );
break;
case MeshXML::USETANGENTS:
xml->usetangents = XMLSupport::parse_bool( iter->value );
break;
case MeshXML::POWER:
xml->material.power = XMLSupport::parse_float( (*iter).value );
break;
case MeshXML::REFLECT:
setEnvMap( shouldreflect( (*iter).value ) );
break;
case MeshXML::LIGHTINGON:
setLighting( XMLSupport::parse_bool( vs_config->getVariable( "graphics",
"ForceLighting",
"true" ) )
|| XMLSupport::parse_bool( (*iter).value ) );
break;
case MeshXML::CULLFACE:
forceCullFace( XMLSupport::parse_bool( (*iter).value ) );
break;
}
}
break;
case MeshXML::DIFFUSE:
//assert(xml->load_stage==7);
xml->load_stage = 8;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( MeshXML::attribute_map.lookup( (*iter).name ) )
{
case MeshXML::RED:
xml->material.dr = XMLSupport::parse_float( (*iter).value );
break;
case MeshXML::BLUE:
xml->material.db = XMLSupport::parse_float( (*iter).value );
break;
case MeshXML::ALPHA:
xml->material.da = XMLSupport::parse_float( (*iter).value );
break;
case MeshXML::GREEN:
xml->material.dg = XMLSupport::parse_float( (*iter).value );
break;
}
}
break;
case MeshXML::EMISSIVE:
//assert(xml->load_stage==7);
xml->load_stage = 8;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( MeshXML::attribute_map.lookup( (*iter).name ) )
{
case MeshXML::RED:
xml->material.er = XMLSupport::parse_float( (*iter).value );
break;
case MeshXML::BLUE:
xml->material.eb = XMLSupport::parse_float( (*iter).value );
break;
case MeshXML::ALPHA:
xml->material.ea = XMLSupport::parse_float( (*iter).value );
break;
case MeshXML::GREEN:
xml->material.eg = XMLSupport::parse_float( (*iter).value );
break;
}
}
break;
case MeshXML::SPECULAR:
//assert(xml->load_stage==7);
xml->load_stage = 8;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( MeshXML::attribute_map.lookup( (*iter).name ) )
{
case MeshXML::RED:
xml->material.sr = XMLSupport::parse_float( (*iter).value );
break;
case MeshXML::BLUE:
xml->material.sb = XMLSupport::parse_float( (*iter).value );
break;
case MeshXML::ALPHA:
xml->material.sa = XMLSupport::parse_float( (*iter).value );
break;
case MeshXML::GREEN:
xml->material.sg = XMLSupport::parse_float( (*iter).value );
break;
}
}
break;
case MeshXML::AMBIENT:
//assert(xml->load_stage==7);
xml->load_stage = 8;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( MeshXML::attribute_map.lookup( (*iter).name ) )
{
case MeshXML::RED:
xml->material.ar = XMLSupport::parse_float( (*iter).value );
break;
case MeshXML::BLUE:
xml->material.ab = XMLSupport::parse_float( (*iter).value );
break;
case MeshXML::ALPHA:
xml->material.aa = XMLSupport::parse_float( (*iter).value );
break;
case MeshXML::GREEN:
xml->material.ag = XMLSupport::parse_float( (*iter).value );
break;
}
}
break;
case MeshXML::UNKNOWN:
BOOST_LOG_TRIVIAL(error) << boost::format("Unknown element start tag '%1%' detected") % name;
break;
case MeshXML::MESH:
assert( xml->load_stage == 0 );
assert( xml->state_stack.size() == 1 );
xml->load_stage = 1;
//Read in texture attribute
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( MeshXML::attribute_map.lookup( (*iter).name ) )
{
case MeshXML::REVERSE:
xml->reverse = XMLSupport::parse_bool( (*iter).value );
break;
case MeshXML::FORCETEXTURE:
xml->force_texture = XMLSupport::parse_bool( (*iter).value );
break;
case MeshXML::SCALE:
xml->scale *= XMLSupport::parse_float( (*iter).value );
break;
case MeshXML::SHAREVERT:
xml->sharevert =
( XMLSupport::parse_bool( (*iter).value )
&& XMLSupport::parse_bool( vs_config->getVariable( "graphics", "SharedVertexArrays", "true" ) ) );
break;
case MeshXML::POLYGONOFFSET:
this->polygon_offset = XMLSupport::parse_float( (*iter).value );
break;
case MeshXML::BLENDMODE:
{
char *csrc = strdup( (*iter).value.c_str() );
char *cdst = strdup( (*iter).value.c_str() );
sscanf( ( (*iter).value ).c_str(), "%s %s", csrc, cdst );
SetBlendMode( parse_alpha( csrc ), parse_alpha( cdst ) );
free( csrc );
free( cdst );
break;
}
case MeshXML::ALPHATEST:
{
float tmp = XMLSupport::parse_float( (*iter).value );
if (tmp > 1)
xml->mesh->alphatest = 255;
else if (tmp > 0 && tmp <= 1)
xml->mesh->alphatest = float_to_int( tmp*255.0f );
else xml->mesh->alphatest = 0;
break;
}
case MeshXML::TECHNIQUE:
xml->technique = iter->value;
break;
case MeshXML::DETAILTEXTURE:
if (use_detail_texture)
detailTexture = TempGetTexture( xml, iter->value, FactionUtil::GetFaction( xml->faction ), GFXTRUE );
break;
case MeshXML::TEXTURE:
//NO BREAK..goes to next statement
case MeshXML::ALPHAMAP:
case MeshXML::ANIMATEDTEXTURE:
case MeshXML::UNKNOWN:
{
MeshXML::Names whichtype = MeshXML::UNKNOWN;
int strsize = 0;
if (strtoupper( iter->name ).find( "ANIMATION" ) == 0) {
whichtype = MeshXML::ANIMATEDTEXTURE;
strsize = strlen( "ANIMATION" );
}
if (strtoupper( iter->name ).find( "TEXTURE" ) == 0) {
whichtype = MeshXML::TEXTURE;
strsize = strlen( "TEXTURE" );
}
if (strtoupper( iter->name ).find( "ALPHAMAP" ) == 0) {
whichtype = MeshXML::ALPHAMAP;
strsize = strlen( "ALPHAMAP" );
}
if (whichtype != MeshXML::UNKNOWN) {
unsigned int texindex = 0;
string ind( iter->name.substr( strsize ) );
if ( !ind.empty() )
texindex = XMLSupport::parse_int( ind );
static bool per_pixel_lighting =
XMLSupport::parse_bool( vs_config->getVariable( "graphics", "per_pixel_lighting", "true" ) );
if ( (texindex == 0) || per_pixel_lighting )
while (xml->decals.size() <= texindex)
xml->decals.push_back( MeshXML::ZeTexture() );
switch (whichtype)
{
case MeshXML::ANIMATEDTEXTURE:
xml->decals[texindex].animated_name = iter->value;
break;
case MeshXML::ALPHAMAP:
xml->decals[texindex].alpha_name = iter->value;
break;
default:
xml->decals[texindex].decal_name = iter->value;
}
if (texindex == 0)
texture_found = true;
}
break;
}
}
}
assert( texture_found );
break;
case MeshXML::POINTS:
assert( top == MeshXML::MESH ); //FIXME top was never initialized if state stack was empty
//assert(xml->load_stage == 1);
xml->load_stage = 2;
break;
case MeshXML::POINT:
assert( top == MeshXML::POINTS ); //FIXME top was never initialized if state stack was empty
xml->vertex.s = 0.0;
xml->vertex.t = 0.0;
xml->vertex.i = 0.0;
xml->vertex.j = 0.0;
xml->vertex.k = 0.0;
xml->vertex.x = 0.0;
xml->vertex.y = 0.0;
xml->vertex.z = 0.0;
xml->vertex.tx = 0.0;
xml->vertex.ty = 0.0;
xml->vertex.tz = 0.0;
xml->vertex.tw = 0.0;
xml->point_state = 0; //Point state is used to check that all necessary attributes are recorded
break;
case MeshXML::LOCATION:
assert( top == MeshXML::POINT ); //FIXME top was never initialized if state stack was empty
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( MeshXML::attribute_map.lookup( (*iter).name ) )
{
case MeshXML::UNKNOWN:
BOOST_LOG_TRIVIAL(error) << boost::format("Unknown attribute '%1%' encountered in Location tag") % (*iter).name;
break;
case MeshXML::X:
assert( !(xml->point_state&MeshXML::P_X) );
xml->vertex.x = XMLSupport::parse_float( (*iter).value );
xml->vertex.i = 0;
xml->point_state |= MeshXML::P_X;
break;
case MeshXML::Y:
assert( !(xml->point_state&MeshXML::P_Y) );
xml->vertex.y = XMLSupport::parse_float( (*iter).value );
xml->vertex.j = 0;
xml->point_state |= MeshXML::P_Y;
break;
case MeshXML::Z:
assert( !(xml->point_state&MeshXML::P_Z) );
xml->vertex.z = XMLSupport::parse_float( (*iter).value );
xml->vertex.k = 0;
xml->point_state |= MeshXML::P_Z;
break;
case MeshXML::S:
xml->vertex.s = XMLSupport::parse_float( (*iter).value );
break;
case MeshXML::T:
xml->vertex.t = XMLSupport::parse_float( (*iter).value );
break;
default:
assert( 0 );
}
}
assert( ( xml->point_state&(MeshXML::P_X
|MeshXML::P_Y
|MeshXML::P_Z) )
== (MeshXML::P_X
|MeshXML::P_Y
|MeshXML::P_Z) );
break;
case MeshXML::NORMAL:
assert( top == MeshXML::POINT );
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( MeshXML::attribute_map.lookup( (*iter).name ) )
{
case MeshXML::UNKNOWN:
BOOST_LOG_TRIVIAL(error) << boost::format("Unknown attribute '%1%' encountered in Normal tag") % (*iter).name;
break;
case MeshXML::I:
assert( !(xml->point_state&MeshXML::P_I) );
xml->vertex.i = XMLSupport::parse_float( (*iter).value );
xml->point_state |= MeshXML::P_I;
break;
case MeshXML::J:
assert( !(xml->point_state&MeshXML::P_J) );
xml->vertex.j = XMLSupport::parse_float( (*iter).value );
xml->point_state |= MeshXML::P_J;
break;
case MeshXML::K:
assert( !(xml->point_state&MeshXML::P_K) );
xml->vertex.k = XMLSupport::parse_float( (*iter).value );
xml->point_state |= MeshXML::P_K;
break;
default:
assert( 0 );
}
}
if ( ( xml->point_state&(MeshXML::P_I
|MeshXML::P_J
|MeshXML::P_K) )
!= (MeshXML::P_I
|MeshXML::P_J
|MeshXML::P_K) ) {
if (!xml->recalc_norm) {
xml->vertex.i = xml->vertex.j = xml->vertex.k = 0;
xml->recalc_norm = true;
}
}
break;
case MeshXML::POLYGONS:
assert( top == MeshXML::MESH );
//assert(xml->load_stage==3);
xml->load_stage = 4;
break;
case MeshXML::LINE:
assert( top == MeshXML::POLYGONS );
//assert(xml->load_stage==4);
xml->num_vertices = 2;
xml->active_list = &xml->lines;
xml->active_ind = &xml->lineind;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( MeshXML::attribute_map.lookup( (*iter).name ) )
{
case MeshXML::UNKNOWN:
break;
case MeshXML::FLATSHADE:
if ( (*iter).value == "Flat" ) {
BOOST_LOG_TRIVIAL(error) << "Cannot Flatshade Lines";
} else if ( (*iter).value == "Smooth" ) {
//ignored -- already done
}
break;
default:
assert( 0 );
}
}
break;
case MeshXML::TRI:
assert( top == MeshXML::POLYGONS );
//assert(xml->load_stage==4);
xml->num_vertices = 3;
xml->active_list = &xml->tris;
xml->active_ind = &xml->triind;
xml->trishade.push_back( 0 );
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( MeshXML::attribute_map.lookup( (*iter).name ) )
{
case MeshXML::UNKNOWN:
break;
case MeshXML::FLATSHADE:
if ( (*iter).value == "Flat" )
xml->trishade[xml->trishade.size()-1] = 1;
else if ( (*iter).value == "Smooth" )
xml->trishade[xml->trishade.size()-1] = 0;
break;
default:
assert( 0 );
}
}
break;
case MeshXML::LINESTRIP:
assert( top == MeshXML::POLYGONS );
//assert(xml->load_stage==4);
xml->num_vertices = 2;
xml->linestrips.push_back( vector< GFXVertex > () );
xml->active_list = &(xml->linestrips[xml->linestrips.size()-1]);
xml->lstrcnt = xml->linestripind.size();
xml->active_ind = &xml->linestripind;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( MeshXML::attribute_map.lookup( (*iter).name ) )
{
case MeshXML::UNKNOWN:
break;
case MeshXML::FLATSHADE:
if ( (*iter).value == "Flat" ) {
BOOST_LOG_TRIVIAL(error) << "Cannot Flatshade Linestrips";
} else if ( (*iter).value == "Smooth" ) {
//ignored -- already done
}
break;
default:
assert( 0 );
}
}
break;
case MeshXML::TRISTRIP:
assert( top == MeshXML::POLYGONS );
//assert(xml->load_stage==4);
xml->num_vertices = 3; //minimum number vertices
xml->tristrips.push_back( vector< GFXVertex > () );
xml->active_list = &(xml->tristrips[xml->tristrips.size()-1]);
xml->tstrcnt = xml->tristripind.size();
xml->active_ind = &xml->tristripind;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( MeshXML::attribute_map.lookup( (*iter).name ) )
{
case MeshXML::UNKNOWN:
break;
case MeshXML::FLATSHADE:
if ( (*iter).value == "Flat" ) {
BOOST_LOG_TRIVIAL(error) << "Cannot Flatshade Tristrips";
} else if ( (*iter).value == "Smooth" ) {
//ignored -- already done
}
break;
default:
assert( 0 );
}
}
break;
case MeshXML::TRIFAN:
assert( top == MeshXML::POLYGONS );
//assert(xml->load_stage==4);
xml->num_vertices = 3; //minimum number vertices
xml->trifans.push_back( vector< GFXVertex > () );
xml->active_list = &(xml->trifans[xml->trifans.size()-1]);
xml->tfancnt = xml->trifanind.size();
xml->active_ind = &xml->trifanind;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( MeshXML::attribute_map.lookup( (*iter).name ) )
{
case MeshXML::UNKNOWN:
break;
case MeshXML::FLATSHADE:
if ( (*iter).value == "Flat" ) {
BOOST_LOG_TRIVIAL(error) << "Cannot Flatshade Trifans";
} else if ( (*iter).value == "Smooth" ) {
//ignored -- already done
}
break;
default:
assert( 0 );
}
}
break;
case MeshXML::QUADSTRIP:
assert( top == MeshXML::POLYGONS );
//assert(xml->load_stage==4);
xml->num_vertices = 4; //minimum number vertices
xml->quadstrips.push_back( vector< GFXVertex > () );
xml->active_list = &(xml->quadstrips[xml->quadstrips.size()-1]);
xml->qstrcnt = xml->quadstripind.size();
xml->active_ind = &xml->quadstripind;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( MeshXML::attribute_map.lookup( (*iter).name ) )
{
case MeshXML::UNKNOWN:
break;
case MeshXML::FLATSHADE:
if ( (*iter).value == "Flat" ) {
BOOST_LOG_TRIVIAL(error) << "Cannot Flatshade Quadstrips";
} else if ( (*iter).value == "Smooth" ) {
//ignored -- already done
}
break;
default:
assert( 0 );
}
}
break;
case MeshXML::QUAD:
assert( top == MeshXML::POLYGONS );
//assert(xml->load_stage==4);
xml->num_vertices = 4;
xml->active_list = &xml->quads;
xml->active_ind = &xml->quadind;
xml->quadshade.push_back( 0 );
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( MeshXML::attribute_map.lookup( (*iter).name ) )
{
case MeshXML::UNKNOWN:
break;
case MeshXML::FLATSHADE:
if ( (*iter).value == "Flat" ) {
xml->quadshade[xml->quadshade.size()-1] = 1;
} else if ( (*iter).value == "Smooth" ) {
xml->quadshade[xml->quadshade.size()-1] = 0;
}
break;
default:
assert( 0 );
}
}
break;
case MeshXML::LOD:
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( MeshXML::attribute_map.lookup( (*iter).name ) )
{
case MeshXML::UNKNOWN:
break;
case MeshXML::FRAMESPERSECOND:
framespersecond = XMLSupport::parse_float( (*iter).value );
break;
case MeshXML::LODFILE:
xml->lod.push_back( new Mesh( (*iter).value.c_str(), xml->lodscale, xml->faction, xml->fg, true ) ); //make orig mesh
break;
case MeshXML::SIZE:
flotsize = XMLSupport::parse_float( (*iter).value );
break;
}
}
if ( xml->lodsize.size() != xml->lod.size() )
xml->lodsize.push_back( flotsize );
break;
case MeshXML::VERTEX:
{
assert(
top == MeshXML::TRI || top == MeshXML::QUAD || top == MeshXML::LINE || top == MeshXML::TRISTRIP || top
== MeshXML::TRIFAN || top == MeshXML::QUADSTRIP || top == MeshXML::LINESTRIP );
//assert(xml->load_stage==4);
xml->vertex_state = 0;
unsigned int index=0; //FIXME not all switch cases initialize index --"=0" added temporarily by chuck_starchaser
float s, t; //FIXME not all switch cases initialize s and t ...
s = t = 0.0f; //This initialization line to "=0.0f" added temporarily by chuck_starchaser
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( MeshXML::attribute_map.lookup( (*iter).name ) )
{
case MeshXML::UNKNOWN:
break;
case MeshXML::POINT:
assert( !(xml->vertex_state&MeshXML::V_POINT) );
xml->vertex_state |= MeshXML::V_POINT;
index = XMLSupport::parse_int( (*iter).value );
break;
case MeshXML::S:
assert( !(xml->vertex_state&MeshXML::V_S) );
xml->vertex_state |= MeshXML::V_S;
s = XMLSupport::parse_float( (*iter).value );
break;
case MeshXML::T:
assert( !(xml->vertex_state&MeshXML::V_T) );
xml->vertex_state |= MeshXML::V_T;
t = XMLSupport::parse_float( (*iter).value );
break;
default:
assert( 0 );
}
}
assert( ( xml->vertex_state&(MeshXML::V_POINT
|MeshXML::V_S
|MeshXML::V_T) )
== (MeshXML::V_POINT
|MeshXML::V_S
|MeshXML::V_T) );
assert( index < xml->vertices.size() ); //FIXME not all switch cases initialize index
xml->vertex.s = 0.0;
xml->vertex.t = 0.0;
xml->vertex.i = 0.0;
xml->vertex.j = 0.0;
xml->vertex.k = 0.0;
xml->vertex.x = 0.0;
xml->vertex.y = 0.0;
xml->vertex.z = 0.0;
xml->vertex.tx = 0.0;
xml->vertex.ty = 0.0;
xml->vertex.tz = 0.0;
xml->vertex.tw = 0.0;
xml->vertex = xml->vertices[index]; //FIXME not all switch cases initialize index
xml->vertexcount[index] += 1; //FIXME not all switch cases initialize index
if ( (!xml->vertex.i) && (!xml->vertex.j) && (!xml->vertex.k) )
if (!xml->recalc_norm)
xml->recalc_norm = true;
//xml->vertex.x*=scale;
//xml->vertex.y*=scale;
//xml->vertex.z*=scale;//FIXME
xml->vertex.s = s; //FIXME not all cases in switch above initialized s and t
xml->vertex.t = t; //FIXME not all cases in switch above initialized s and t
xml->active_list->push_back( xml->vertex );
xml->active_ind->push_back( index );
if (xml->reverse) {
unsigned int i;
for (i = xml->active_ind->size()-1; i > 0; i
(*xml->active_ind)[i] = (*xml->active_ind)[i-1];
(*xml->active_ind)[0] = index;
for (i = xml->active_list->size()-1; i > 0; i
(*xml->active_list)[i] = (*xml->active_list)[i-1];
(*xml->active_list)[0] = xml->vertex;
}
xml->num_vertices
break;
}
case MeshXML::LOGO:
{
assert( top == MeshXML::MESH );
//assert (xml->load_stage==4);
xml->load_stage = 5;
xml->vertex_state = 0;
unsigned int typ; //FIXME Not all cases below initialize typ
float rot, siz, offset; //FIXME Not all cases below initialize rot, siz or offset
typ = 0; //FIXME this line temporarily added by chuck_starchaser
rot = siz = offset = 0.0f; //FIXME this line temporarily added by chuck_starchaser
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( MeshXML::attribute_map.lookup( (*iter).name ) )
{
case MeshXML::UNKNOWN:
break;
case MeshXML::TYPE:
assert( !(xml->vertex_state&MeshXML::V_TYPE) );
xml->vertex_state |= MeshXML::V_TYPE;
typ = XMLSupport::parse_int( (*iter).value );
break;
case MeshXML::ROTATE:
assert( !(xml->vertex_state&MeshXML::V_ROTATE) );
xml->vertex_state |= MeshXML::V_ROTATE;
rot = XMLSupport::parse_float( (*iter).value );
break;
case MeshXML::SIZE:
assert( !(xml->vertex_state&MeshXML::V_SIZE) );
xml->vertex_state |= MeshXML::V_SIZE;
siz = XMLSupport::parse_float( (*iter).value );
break;
case MeshXML::OFFSET:
assert( !(xml->vertex_state&MeshXML::V_OFFSET) );
xml->vertex_state |= MeshXML::V_OFFSET;
offset = XMLSupport::parse_float( (*iter).value );
break;
default:
assert( 0 );
}
}
assert( ( xml->vertex_state&(MeshXML::V_TYPE
|MeshXML::V_ROTATE
|MeshXML::V_SIZE
|MeshXML::V_OFFSET) )
== (MeshXML::V_TYPE
|MeshXML::V_ROTATE
|MeshXML::V_SIZE
|MeshXML::V_OFFSET) );
xml->logos.push_back( MeshXML::ZeLogo() );
xml->logos[xml->logos.size()-1].type = typ;
xml->logos[xml->logos.size()-1].rotate = rot;
xml->logos[xml->logos.size()-1].size = siz;
xml->logos[xml->logos.size()-1].offset = offset;
break;
}
case MeshXML::REF:
{
assert( top == MeshXML::LOGO );
//assert (xml->load_stage==5);
xml->load_stage = 6;
unsigned int ind = 0;
float indweight = 1;
bool foundindex = false;
int ttttttt;
ttttttt = 0;
for (iter = attributes.begin(); iter != attributes.end(); iter++) {
switch ( MeshXML::attribute_map.lookup( (*iter).name ) )
{
case MeshXML::UNKNOWN:
break;
case MeshXML::POINT:
assert( ttttttt < 2 );
xml->vertex_state |= MeshXML::V_POINT;
ind = XMLSupport::parse_int( (*iter).value );
foundindex = true;
ttttttt += 2;
break;
case MeshXML::WEIGHT:
assert( (ttttttt&1) == 0 );
ttttttt += 1;
xml->vertex_state |= MeshXML::V_S;
indweight = XMLSupport::parse_float( (*iter).value );
break;
default:
assert( 0 );
}
}
assert( ttttttt == 3 );
if (!foundindex) {
BOOST_LOG_TRIVIAL(error) << "mesh with uninitalized logo";
}
xml->logos[xml->logos.size()-1].refpnt.push_back( ind );
xml->logos[xml->logos.size()-1].refweight.push_back( indweight );
xml->vertex_state += MeshXML::V_REF;
break;
}
default:
assert( 0 );
}
}
void Mesh::endElement( MeshXML *xml, const string &name )
{
MeshXML::Names elem = (MeshXML::Names) MeshXML::element_map.lookup( name );
assert( *xml->state_stack.rbegin() == elem );
xml->state_stack.pop_back();
unsigned int i;
switch (elem)
{
case MeshXML::UNKNOWN:
BOOST_LOG_TRIVIAL(error) << boost::format("Unknown element end tag '%1%' detected") % name;
break;
case MeshXML::POINT:
assert( ( xml->point_state&(MeshXML::P_X
|MeshXML::P_Y
|MeshXML::P_Z
|MeshXML::P_I
|MeshXML::P_J
|MeshXML::P_K) )
== (MeshXML::P_X
|MeshXML::P_Y
|MeshXML::P_Z
|MeshXML::P_I
|MeshXML::P_J
|MeshXML::P_K) );
xml->vertices.push_back( xml->vertex );
xml->vertexcount.push_back( 0 );
break;
case MeshXML::POINTS:
xml->load_stage = 3;
break;
case MeshXML::LINE:
assert( xml->num_vertices == 0 );
break;
case MeshXML::TRI:
assert( xml->num_vertices == 0 );
break;
case MeshXML::QUAD:
assert( xml->num_vertices == 0 );
break;
case MeshXML::LINESTRIP:
assert( xml->num_vertices <= 0 );
for (i = xml->lstrcnt+1; i < xml->linestripind.size(); i++) {
xml->nrmllinstrip.push_back( xml->linestripind[i-1] );
xml->nrmllinstrip.push_back( xml->linestripind[i] );
}
break;
case MeshXML::TRISTRIP:
assert( xml->num_vertices <= 0 );
for (i = xml->tstrcnt+2; i < xml->tristripind.size(); i++) {
if ( (i-xml->tstrcnt)%2 ) {
//normal order
xml->nrmltristrip.push_back( xml->tristripind[i-2] );
xml->nrmltristrip.push_back( xml->tristripind[i-1] );
xml->nrmltristrip.push_back( xml->tristripind[i] );
} else {
//reverse order
xml->nrmltristrip.push_back( xml->tristripind[i-1] );
xml->nrmltristrip.push_back( xml->tristripind[i-2] );
xml->nrmltristrip.push_back( xml->tristripind[i] );
}
}
break;
case MeshXML::TRIFAN:
assert( xml->num_vertices <= 0 );
for (i = xml->tfancnt+2; i < xml->trifanind.size(); i++) {
xml->nrmltrifan.push_back( xml->trifanind[xml->tfancnt] );
xml->nrmltrifan.push_back( xml->trifanind[i-1] );
xml->nrmltrifan.push_back( xml->trifanind[i] );
}
break;
case MeshXML::QUADSTRIP: //have to fix up nrmlquadstrip so that it 'looks' like a quad list for smooth shading
assert( xml->num_vertices <= 0 );
for (i = xml->qstrcnt+3; i < xml->quadstripind.size(); i += 2) {
xml->nrmlquadstrip.push_back( xml->quadstripind[i-3] );
xml->nrmlquadstrip.push_back( xml->quadstripind[i-2] );
xml->nrmlquadstrip.push_back( xml->quadstripind[i] );
xml->nrmlquadstrip.push_back( xml->quadstripind[i-1] );
}
break;
case MeshXML::POLYGONS:
assert( xml->tris.size()%3 == 0 );
assert( xml->quads.size()%4 == 0 );
break;
case MeshXML::REF:
//assert (xml->load_stage==6);
xml->load_stage = 5;
break;
case MeshXML::LOGO:
//assert (xml->load_stage==5);
assert( xml->vertex_state >= MeshXML::V_REF*3 ); //make sure there are at least 3 reference points
xml->load_stage = 4;
break;
case MeshXML::MATERIAL:
//assert(xml->load_stage==7);
xml->load_stage = 4;
break;
case MeshXML::DETAILPLANE:
break;
case MeshXML::DIFFUSE:
//assert(xml->load_stage==8);
xml->load_stage = 7;
break;
case MeshXML::EMISSIVE:
//assert(xml->load_stage==8);
xml->load_stage = 7;
break;
case MeshXML::SPECULAR:
//assert(xml->load_stage==8);
xml->load_stage = 7;
break;
case MeshXML::AMBIENT:
//assert(xml->load_stage==8);
xml->load_stage = 7;
break;
case MeshXML::MESH:
//assert(xml->load_stage==4);//4 is done with poly, 5 is done with Logos
xml->load_stage = 5;
break;
default:
break;
}
}
void updateMax( Vector &mn, Vector &mx, const GFXVertex &ver )
{
mn.i = min( ver.x, mn.i );
mx.i = max( ver.x, mx.i );
mn.j = min( ver.y, mn.j );
mx.j = max( ver.y, mx.j );
mn.k = min( ver.z, mn.k );
mx.k = max( ver.z, mx.k );
}
using namespace VSFileSystem;
void LaunchConverter( const char *input, const char *output, const char *args = "obc" )
{
string intmp = string( "\"" )+input+string( "\"" );
string outtmp = string( "\"" )+output+string( "\"" );
#ifndef _WIN32
int pid = fork();
if (!pid) {
string soundserver_path = VSFileSystem::datadir+"/bin/mesher";
string firstarg = string( "\"" )+soundserver_path+string( "\"" );
pid = execlp( soundserver_path.c_str(), soundserver_path.c_str(), input, output, args, NULL );
soundserver_path = VSFileSystem::datadir+"/mesher";
firstarg = string( "\"" )+soundserver_path+string( "\"" );
pid = execlp( soundserver_path.c_str(), soundserver_path.c_str(), input, output, args, NULL );
BOOST_LOG_TRIVIAL(fatal) << "Unable to spawn converter";
VSExit( -1 );
} else {
if (pid == -1) {
BOOST_LOG_TRIVIAL(fatal) << "Unable to spawn converter";
VSExit( -1 );
}
int mystat = 0;
waitpid( pid, &mystat, 0 );
}
#else
string ss_path = VSFileSystem::datadir+"\\bin\\mesher.exe";
string firstarg = string( "\"" )+ss_path+string( "\"" );
int pid = spawnl( P_WAIT, ss_path.c_str(), firstarg.c_str(), intmp.c_str(), outtmp.c_str(), args, NULL );
if (pid == -1) {
ss_path = VSFileSystem::datadir+"\\mesher.exe";
firstarg = string( "\"" )+ss_path+string( "\"" );
int pid = spawnl( P_WAIT, ss_path.c_str(), firstarg.c_str(), intmp.c_str(), outtmp.c_str(), args, NULL );
if (pid == -1) {
BOOST_LOG_TRIVIAL(error) << boost::format("Unable to spawn obj converter Error (%1%)") % pid;
}
}
#endif
}
bool isBFXM( VSFile &f )
{
char bfxm[4];
f.Read( &bfxm[0], 1 );
f.Read( &bfxm[1], 1 );
f.Read( &bfxm[2], 1 );
f.Read( &bfxm[3], 1 );
f.GoTo( 0 );
return bfxm[0] == 'B' && bfxm[1] == 'F' && bfxm[2] == 'X' && bfxm[3] == 'M';
}
void CopyFile( VSFile &src, VSFile &dst )
{
size_t hm;
size_t srcstruct;
size_t *srcptr = &srcstruct;
while ( ( hm = src.Read( srcptr, sizeof (srcstruct) ) ) )
dst.Write( srcptr, hm );
}
/*
bool loadObj( VSFile &f, std::string str )
{
string fullpath = f.GetFullPath();
VSFile output;
output.OpenCreateWrite( "output.bfxm", BSPFile );
output.Close();
output.OpenReadOnly( "output.bfxm", BSPFile );
string outputpath = output.GetFullPath();
output.Close();
LaunchConverter( fullpath.c_str(), outputpath.c_str() );
output.OpenReadOnly( "output.bfxm", BSPFile );
if ( isBFXM( output ) ) {
output.Close();
f.Close();
f.OpenReadOnly( "output.bfxm", BSPFile );
return true;
} else {
output.Close();
}
VSFile input;
input.OpenCreateWrite( "input.obj", BSPFile );
f.GoTo( 0 );
CopyFile( f, input );
input.Close();
input.OpenReadOnly( "input.obj", BSPFile );
string inputpath = input.GetFullPath();
input.Close();
f.Close();
int where = str.find_last_of( "." );
str = str.substr( 0, where )+".mtl";
f.OpenReadOnly( str, MeshFile );
VSFile inputmtl;
inputmtl.OpenCreateWrite( "input.mtl", BSPFile );
CopyFile( f, inputmtl );
f.Close();
inputmtl.Close();
LaunchConverter( inputpath.c_str(), outputpath.c_str() );
output.OpenReadOnly( "output.bfxm", BSPFile );
if ( isBFXM( output ) ) {
output.Close();
f.OpenReadOnly( "output.bfxm", BSPFile );
return true;
} else {
output.Close();
}
return false;
}
*/
const bool USE_RECALC_NORM = true;
const bool FLAT_SHADE = true;
Mesh* Mesh::LoadMesh( const char *filename,
const Vector &scale,
int faction,
Flightgroup *fg,
const std::vector< std::string > &overridetextures )
{
vector< Mesh* >m = LoadMeshes( filename, scale, faction, fg, overridetextures );
if ( m.empty() )
return 0;
if (m.size() > 1) {
BOOST_LOG_TRIVIAL(warning) << boost::format("Mesh %1% has %2% subcomponents. Only first used!") % filename % ((unsigned int) m.size());
for (unsigned int i = 1; i < m.size(); ++i) {
delete m[i];
}
}
return m[0];
}
Hashtable< std::string, std::vector< Mesh* >, MESH_HASTHABLE_SIZE >bfxmHashTable;
vector< Mesh* >Mesh::LoadMeshes( const char *filename,
const Vector &scale,
int faction,
Flightgroup *fg,
const std::vector< std::string > &overrideTextures )
{
/*
* if (strstr(filename,".xmesh")) {
* Mesh * m = new Mesh (filename,scale,faction,fg);
* vector <Mesh*> ret;
* ret.push_back(m);
* return ret;
* }*/
string hash_name = VSFileSystem::GetHashName( filename, scale, faction );
vector< Mesh* > *oldmesh = bfxmHashTable.Get( hash_name );
if (oldmesh == 0) {
hash_name = VSFileSystem::<API key>( filename, scale, faction );
oldmesh = bfxmHashTable.Get( hash_name );
}
if (0 != oldmesh) {
vector< Mesh* >ret;
for (unsigned int i = 0; i < oldmesh->size(); ++i) {
ret.push_back( new Mesh() );
Mesh *m = (*oldmesh)[i];
ret.back()->LoadExistant( m->orig ? m->orig : m );
}
return ret;
}
VSFile f;
VSError err = f.OpenReadOnly( filename, MeshFile );
if (err > Ok) {
BOOST_LOG_TRIVIAL(error) << boost::format("Cannot Open Mesh File %1%") % filename;
return vector< Mesh* > ();
}
char bfxm[4];
f.Read( &bfxm[0], sizeof(bfxm[0])*4 );
bool isbfxm = (bfxm[0] == 'B' && bfxm[1] == 'F' && bfxm[2] == 'X' && bfxm[3] == 'M');
if ( isbfxm || strstr( filename, ".obj" ) ) {
if (!isbfxm) {
// NOTE : Commented out following block, probably not needed anymore
/* if ( !loadObj( f, filename ) ) {
BOOST_LOG_TRIVIAL(error) << boost::format("Cannot Open Mesh File %1%") % filename;
*/
//cleanexit=1;
//winsys_exit(1);
// return vector< Mesh* > ();
}
f.GoTo( 0 );
hash_name =
(err == VSFileSystem::Shared) ? VSFileSystem::<API key>( filename, scale,
faction ) : VSFileSystem::GetHashName(
filename,
scale,
faction );
vector< Mesh* > retval( LoadMeshes( f, scale, faction, fg, hash_name, overrideTextures ) );
vector< Mesh* > *newvec = new vector< Mesh* > ( retval );
for (unsigned int i = 0; i < retval.size(); ++i) {
retval[i]->hash_name = hash_name;
if (retval[i]->orig)
retval[i]->orig->hash_name = hash_name;
(*newvec)[i] = retval[i]->orig ? retval[i]->orig : retval[i];
}
bfxmHashTable.Put( hash_name, newvec );
return retval;
} else {
f.Close();
bool original = false;
Mesh *m = new Mesh( filename, scale, faction, fg, original );
vector< Mesh* >ret;
ret.push_back( m );
return ret;
}
}
void Mesh::LoadXML( const char *filename,
const Vector &scale,
int faction,
Flightgroup *fg,
bool origthis,
const vector< string > &textureOverride )
{
VSFile f;
VSError err = f.OpenReadOnly( filename, MeshFile );
if (err > Ok) {
BOOST_LOG_TRIVIAL(error) << boost::format("Cannot Open Mesh File %1%") % filename;
//cleanexit=1;
//winsys_exit(1);
return;
}
LoadXML( f, scale, faction, fg, origthis, textureOverride );
f.Close();
}
void Mesh::LoadXML( VSFileSystem::VSFile &f,
const Vector &scale,
int faction,
Flightgroup *fg,
bool origthis,
const vector< string > &textureOverride )
{
std::vector< unsigned int >ind;
MeshXML *xml = new MeshXML;
xml->mesh = this;
xml->fg = fg;
xml->usenormals = false;
xml->usetangents = false;
xml->force_texture = false;
xml->reverse = false;
xml->sharevert = false;
xml->faction = faction;
GFXGetMaterial( 0, xml->material ); //by default it's the default material;
xml->load_stage = 0;
xml->recalc_norm = false;
xml->scale = scale;
xml->lodscale = scale;
XML_Parser parser = XML_ParserCreate( NULL );
XML_SetUserData( parser, xml );
<API key>( parser, &Mesh::beginElement, &Mesh::endElement );
XML_Parse( parser, ( f.ReadFull() ).c_str(), f.Size(), 1 );
XML_ParserFree( parser );
//Now, copy everything into the mesh data structures
if (xml->load_stage != 5) {
BOOST_LOG_TRIVIAL(fatal) << "Warning: mesh load possibly failed";
VSExit( -1 );
}
PostProcessLoading( xml, textureOverride );
numlods = xml->lod.size()+1;
if (origthis) {
orig = NULL;
} else {
orig = new Mesh[numlods];
unsigned int i;
for (i = 0; i < xml->lod.size(); i++) {
orig[i+1] = *xml->lod[i];
orig[i+1].lodsize = xml->lodsize[i];
}
}
delete xml;
}
static void SumNormal( vector< GFXVertex > &vertices, int i1, int i2, int i3, vector< float > &weights )
{
Vector v1( vertices[i2].x-vertices[i1].x,
vertices[i2].y-vertices[i1].y,
vertices[i2].z-vertices[i1].z );
Vector v2( vertices[i3].x-vertices[i1].x,
vertices[i3].y-vertices[i1].y,
vertices[i3].z-vertices[i1].z );
v1.Normalize();
v2.Normalize();
Vector N = v1.Cross( v2 );
float w = 1.f-0.9*fabsf( v1.Dot( v2 ) );
N *= w;
vertices[i1].i += N.i;
vertices[i1].j += N.j;
vertices[i1].k += N.k;
weights[i1] += w;
vertices[i2].i += N.i;
vertices[i2].j += N.j;
vertices[i2].k += N.k;
weights[i2] += w;
vertices[i3].i += N.i;
vertices[i3].j += N.j;
vertices[i3].k += N.k;
weights[i3] += w;
}
static void SumLineNormal( vector< GFXVertex > &vertices, int i1, int i2, vector< float > &weights )
{
Vector v1( vertices[i2].x-vertices[i1].x,
vertices[i2].y-vertices[i1].y,
vertices[i2].z-vertices[i1].z );
static Vector v2( 0.3408, 0.9401, 0.0005 );
v1.Normalize();
Vector N = v1.Cross( v2 );
vertices[i1].i += N.i;
vertices[i1].j += N.j;
vertices[i1].k += N.k;
weights[i1] += 1;
vertices[i2].i += N.i;
vertices[i2].j += N.j;
vertices[i2].k += N.k;
weights[i2] += 1;
}
static void SumNormals( vector< GFXVertex > &vertices,
vector< int > &indices,
size_t begin,
size_t end,
POLYTYPE polytype,
vector< float > &weights )
{
int flip = 0;
size_t i;
switch (polytype)
{
case GFXTRI:
if (end <= 2)
break;
end -= 2;
for (; begin < end; begin += 3)
SumNormal( vertices, indices[begin], indices[begin+1], indices[begin+2], weights );
break;
case GFXQUAD:
if (end <= 3)
break;
end -= 3;
for (; begin < end; begin += 4) {
SumNormal( vertices, indices[begin], indices[begin+1], indices[begin+2], weights );
SumNormal( vertices, indices[begin], indices[begin+2], indices[begin+3], weights );
}
break;
case GFXTRISTRIP:
case GFXQUADSTRIP:
if (end <= 2)
break;
end -= 2;
for (; begin < end; ++begin, flip ^= 1)
SumNormal( vertices, indices[begin], indices[begin+1+flip], indices[begin+2-flip], weights );
break;
case GFXTRIFAN:
if (end <= 2)
break;
end -= 2;
for (i = begin; begin < end; ++begin)
SumNormal( vertices, indices[i], indices[begin+1], indices[begin+2], weights );
break;
case GFXLINESTRIP:
if (end <= 1)
break;
end -= 1;
for (i = begin; begin < end; ++begin)
SumLineNormal( vertices, indices[begin], indices[begin+1], weights );
break;
case GFXLINE:
if (end <= 1)
break;
end -= 1;
for (i = begin; begin < end; begin += 2)
SumLineNormal( vertices, indices[begin], indices[begin+1], weights );
break;
case GFXPOLY:
case GFXPOINT:
break;
}
}
static void ClearTangents( vector< GFXVertex > &vertices )
{
for (vector< GFXVertex >::iterator it = vertices.begin(); it != vertices.end(); ++it)
it->SetTangent( Vector( 0, 0, 0 ), 0 );
}
static float faceTSPolarity( const Vector &T, const Vector &B, const Vector &N )
{
if (T.Cross( B ).Dot( N ) >= 0.f)
return -1.f;
else
return 1.f;
}
static float faceTSWeight( vector< GFXVertex > &vertices, int i1, int i2, int i3 )
{
const GFXVertex &vtx1 = vertices[i1];
const GFXVertex &vtx2 = vertices[i2];
const GFXVertex &vtx3 = vertices[i3];
Vector v1( vtx2.x-vtx1.x,
vtx2.y-vtx1.y,
vtx2.z-vtx1.z );
Vector v2( vtx3.x-vtx1.x,
vtx3.y-vtx1.y,
vtx3.z-vtx1.z );
v1.Normalize();
v2.Normalize();
return 1.f-fabsf( v1.Dot( v2 ) );
}
static void computeTangentspace( vector< GFXVertex > &vertices, int i1, int i2, int i3, Vector &T, Vector &B, Vector &N )
{
const GFXVertex &v1 = vertices[i1];
const GFXVertex &v2 = vertices[i2];
const GFXVertex &v3 = vertices[i3];
//compute deltas. I think that the fact we use (*2-*1) and (*3-*1) is arbitrary, but I could be wrong
Vector p0( v1.x, v1.y, v1.z );
Vector p1( v2.x, v2.y, v2.z );
Vector p2( v3.x, v3.y, v3.z );
p1 -= p0;
p2 -= p0;
float s1, t1;
float s2, t2;
s1 = v2.s-v1.s;
s2 = v3.s-v1.s;
t1 = v2.t-v1.t;
t2 = v3.t-v1.t;
//and now a myracle happens...
T = t2*p1-t1*p2;
B = s1*p2-s2*p1;
N = p1.Cross( p2 );
//normalize
T.Normalize();
B.Normalize();
N.Normalize();
}
static void SumTangent( vector< GFXVertex > &vertices, int i1, int i2, int i3, vector< float > &weights )
{
float w = faceTSWeight( vertices, i1, i2, i3 );
Vector T, B, N;
computeTangentspace( vertices, i1, i2, i3, T, B, N );
float p = faceTSPolarity( T, B, N )*w;
T *= w;
GFXVertex &v1 = vertices[i1];
GFXVertex &v2 = vertices[i2];
GFXVertex &v3 = vertices[i3];
v1.tx += T.x;
v1.ty += T.y;
v1.tz += T.z;
v1.tw += p;
weights[i1] += w;
v2.tx += T.x;
v2.ty += T.y;
v2.tz += T.z;
v2.tw += p;
weights[i2] += w;
v3.tx += T.x;
v3.ty += T.y;
v3.tz += T.z;
v3.tw += p;
weights[i3] += w;
}
static void SumTangents( vector< GFXVertex > &vertices,
vector< int > &indices,
size_t begin,
size_t end,
POLYTYPE polytype,
vector< float > &weights )
{
int flip = 0;
size_t i;
switch (polytype)
{
case GFXTRI:
if (end <= 2)
break;
end -= 2;
for (; begin < end; begin += 3)
SumTangent( vertices, indices[begin], indices[begin+1], indices[begin+2], weights );
break;
case GFXQUAD:
if (end <= 3)
break;
end -= 3;
for (; begin < end; begin += 4) {
SumTangent( vertices, indices[begin], indices[begin+1], indices[begin+2], weights );
SumTangent( vertices, indices[begin], indices[begin+2], indices[begin+3], weights );
}
break;
case GFXTRISTRIP:
case GFXQUADSTRIP:
if (end <= 2)
break;
end -= 2;
for (; begin < end; ++begin, flip ^= 1)
SumTangent( vertices, indices[begin], indices[begin+1+flip], indices[begin+2-flip], weights );
break;
case GFXTRIFAN:
if (end <= 2)
break;
end -= 2;
for (i = begin; begin < end; ++begin)
SumTangent( vertices, indices[i], indices[begin+1], indices[begin+2], weights );
break;
case GFXLINE:
case GFXLINESTRIP:
case GFXPOLY:
case GFXPOINT:
break;
}
}
static void NormalizeTangents( vector< GFXVertex > &vertices, vector< float > &weights )
{
for (size_t i = 0, n = vertices.size(); i < n; ++i) {
GFXVertex &v = vertices[i];
float w = weights[i];
if (w > 0) {
//Average (shader will normalize)
float iw = (w < 0.001) ? 1.f : (1.f / w);
v.tx *= iw;
v.ty *= iw;
v.tz *= iw;
v.tw *= iw;
}
// Don't let null vectors around (they create NaNs within shaders when normalized)
// Since they happen regularly on sphere polar caps, replace them with a suitable value there (+x)
if (Vector(v.tx, v.ty, v.tz).MagnitudeSquared() < 0.00001)
v.tx = 0.001;
}
}
static void NormalizeNormals( vector< GFXVertex > &vertices, vector< float > &weights )
{
for (size_t i = 0, n = vertices.size(); i < n; ++i) {
GFXVertex &v = vertices[i];
float w = weights[i];
if (w > 0) {
//Renormalize
float mag = v.GetNormal().MagnitudeSquared();
if (mag < 0.00001)
mag = 1.f;
else
mag = 1.f/sqrt(mag);
v.i *= mag;
v.j *= mag;
v.k *= mag;
}
}
}
void Mesh::PostProcessLoading( MeshXML *xml, const vector< string > &textureOverride )
{
unsigned int i;
unsigned int a = 0;
unsigned int j;
//begin vertex normal calculations if necessary
if (!xml->usenormals) {
ClearTangents( xml->vertices );
vector< float >weights;
weights.resize( xml->vertices.size(), 0.f );
size_t i, j, n;
SumNormals( xml->vertices, xml->triind, 0, xml->triind.size(), GFXTRI, weights );
SumNormals( xml->vertices, xml->quadind, 0, xml->quadind.size(), GFXQUAD, weights );
SumNormals( xml->vertices, xml->lineind, 0, xml->lineind.size(), GFXLINE, weights );
for ( i = j = 0, n = xml->tristrips.size(); i < n; j += xml->tristrips[i++].size() )
SumNormals( xml->vertices, xml->tristripind, j, j+xml->tristrips[i].size(), GFXTRISTRIP, weights );
for ( i = j = 0, n = xml->quadstrips.size(); i < n; j += xml->quadstrips[i++].size() )
SumNormals( xml->vertices, xml->quadstripind, j, j+xml->quadstrips[i].size(), GFXQUADSTRIP, weights );
for ( i = j = 0, n = xml->trifans.size(); i < n; j += xml->trifans[i++].size() )
SumNormals( xml->vertices, xml->trifanind, j, j+xml->trifans[i].size(), GFXTRIFAN, weights );
for ( i = j = 0, n = xml->linestrips.size(); i < n; j += xml->linestrips[i++].size() )
SumNormals( xml->vertices, xml->linestripind, j, j+xml->linestrips[i].size(), GFXLINESTRIP, weights );
NormalizeNormals( xml->vertices, weights );
} else {
//Flip normals - someone thought VS should flips normals, ask him why.
for (i = 0; i < xml->vertices.size(); ++i) {
GFXVertex &v = xml->vertices[i];
v.i *= -1;
v.j *= -1;
v.k *= -1;
}
}
a = 0;
std::vector< unsigned int > ind;
for (a = 0; a < xml->tris.size(); a += 3)
for (j = 0; j < 3; j++) {
int ix = xml->triind[a+j];
ind.push_back( ix );
xml->tris[a+j].SetNormal( xml->vertices[ix].GetNormal() );
xml->tris[a+j].SetTangent( xml->vertices[ix].GetTangent(),
xml->vertices[ix].GetTangentParity() );
}
a = 0;
for (a = 0; a < xml->quads.size(); a += 4)
for (j = 0; j < 4; j++) {
int ix = xml->quadind[a+j];
ind.push_back( ix );
xml->quads[a+j].SetNormal( xml->vertices[ix].GetNormal() );
xml->quads[a+j].SetTangent( xml->vertices[ix].GetTangent(),
xml->vertices[ix].GetTangentParity() );
}
a = 0;
for (a = 0; a < xml->lines.size(); a += 2)
for (j = 0; j < 2; j++) {
int ix = xml->lineind[a+j];
ind.push_back( ix );
xml->lines[a+j].SetNormal( xml->vertices[ix].GetNormal() );
}
a = 0;
unsigned int k = 0;
unsigned int l = 0;
for (l = a = 0; a < xml->tristrips.size(); a++)
for (k = 0; k < xml->tristrips[a].size(); k++, l++) {
int ix = xml->tristripind[l];
ind.push_back( ix );
xml->tristrips[a][k].SetNormal( xml->vertices[ix].GetNormal() );
xml->tristrips[a][k].SetTangent( xml->vertices[ix].GetTangent(),
xml->vertices[ix].GetTangentParity() );
}
for (l = a = 0; a < xml->trifans.size(); a++)
for (k = 0; k < xml->trifans[a].size(); k++, l++) {
int ix = xml->trifanind[l];
ind.push_back( ix );
xml->trifans[a][k].SetNormal( xml->vertices[ix].GetNormal() );
xml->trifans[a][k].SetTangent( xml->vertices[ix].GetTangent(),
xml->vertices[ix].GetTangentParity() );
}
for (l = a = 0; a < xml->quadstrips.size(); a++)
for (k = 0; k < xml->quadstrips[a].size(); k++, l++) {
int ix = xml->quadstripind[l];
ind.push_back( ix );
xml->quadstrips[a][k].SetNormal( xml->vertices[ix].GetNormal() );
xml->quadstrips[a][k].SetTangent( xml->vertices[ix].GetTangent(),
xml->vertices[ix].GetTangentParity() );
}
for (l = a = 0; a < xml->linestrips.size(); a++)
for (k = 0; k < xml->linestrips[a].size(); k++, l++) {
int ix = xml->linestripind[l];
ind.push_back( ix );
xml->linestrips[a][k].SetNormal( xml->vertices[ix].GetNormal() );
}
//TODO: add alpha handling
//check for per-polygon flat shading
unsigned int trimax = xml->tris.size()/3;
a = 0;
i = 0;
j = 0;
if (!xml->usenormals) {
for (i = 0; i < trimax; i++, a += 3)
if (FLAT_SHADE || xml->trishade[i] == 1) {
for (j = 0; j < 3; j++) {
Vector Cur = xml->vertices[xml->triind[a+j]].GetPosition();
Cur = (xml->vertices[xml->triind[a+( (j+1)%3 )]].GetPosition()-Cur)
.Cross( xml->vertices[xml->triind[a+( (j+2)%3 )]].GetPosition()-Cur );
Normalize( Cur );
xml->tris[a+j].SetNormal( Cur );
}
}
a = 0;
trimax = xml->quads.size()/4;
for (i = 0; i < trimax; i++, a += 4)
if ( xml->quadshade[i] == 1 || (FLAT_SHADE) ) {
for (j = 0; j < 4; j++) {
Vector Cur = xml->vertices[xml->quadind[a+j]].GetPosition();
Cur = (xml->vertices[xml->quadind[a+( (j+1)%4 )]].GetPosition()-Cur)
.Cross( xml->vertices[xml->quadind[a+( (j+2)%4 )]].GetPosition()-Cur );
Normalize( Cur );
xml->quads[a+j].SetNormal( Cur );
}
}
}
string factionname = FactionUtil::GetFaction( xml->faction );
for (unsigned int LC = 0; LC < textureOverride.size(); ++LC)
if (textureOverride[LC] != "") {
while (xml->decals.size() <= LC) {
MeshXML::ZeTexture z;
xml->decals.push_back( z );
}
if (textureOverride[LC].find( ".ani" ) != string::npos) {
xml->decals[LC].decal_name = "";
xml->decals[LC].animated_name = textureOverride[LC];
xml->decals[LC].alpha_name = "";
} else {
xml->decals[LC].animated_name = "";
xml->decals[LC].alpha_name = "";
xml->decals[LC].decal_name = textureOverride[LC];
}
}
while ( Decal.size() < xml->decals.size() )
Decal.push_back( NULL );
{
for (unsigned int i = 0; i < xml->decals.size(); i++)
Decal[i] = ( TempGetTexture( xml, i, factionname ) );
}
while (Decal.back() == NULL && Decal.size() > 1)
Decal.pop_back();
initTechnique( xml->technique );
unsigned int index = 0;
unsigned int totalvertexsize = xml->tris.size()+xml->quads.size()+xml->lines.size();
for (index = 0; index < xml->tristrips.size(); index++)
totalvertexsize += xml->tristrips[index].size();
for (index = 0; index < xml->trifans.size(); index++)
totalvertexsize += xml->trifans[index].size();
for (index = 0; index < xml->quadstrips.size(); index++)
totalvertexsize += xml->quadstrips[index].size();
for (index = 0; index < xml->linestrips.size(); index++)
totalvertexsize += xml->linestrips[index].size();
index = 0;
vector< GFXVertex > vertexlist( totalvertexsize );
mn = Vector( FLT_MAX, FLT_MAX, FLT_MAX );
mx = Vector( -FLT_MAX, -FLT_MAX, -FLT_MAX );
radialSize = 0;
vector< enum POLYTYPE >polytypes;
polytypes.insert( polytypes.begin(), totalvertexsize, GFXTRI );
//enum POLYTYPE * polytypes= new enum POLYTYPE[totalvertexsize];//overkill but what the hell
vector< int >poly_offsets;
poly_offsets.insert( poly_offsets.begin(), totalvertexsize, 0 );
int o_index = 0;
if ( xml->tris.size() ) {
polytypes[o_index] = GFXTRI;
poly_offsets[o_index] = xml->tris.size();
o_index++;
}
if ( xml->quads.size() ) {
polytypes[o_index] = GFXQUAD;
poly_offsets[o_index] = xml->quads.size();
o_index++;
}
if ( xml->lines.size() ) {
polytypes[o_index] = GFXLINE;
poly_offsets[o_index] = xml->lines.size();
o_index++;
}
for (a = 0; a < xml->tris.size(); a++, index++)
vertexlist[index] = xml->tris[a];
for (a = 0; a < xml->quads.size(); a++, index++)
vertexlist[index] = xml->quads[a];
for (a = 0; a < xml->lines.size(); a++, index++)
vertexlist[index] = xml->lines[a];
for (a = 0; a < xml->tristrips.size(); a++) {
for (unsigned int m = 0; m < xml->tristrips[a].size(); m++, index++)
vertexlist[index] = xml->tristrips[a][m];
polytypes[o_index] = GFXTRISTRIP;
poly_offsets[o_index] = xml->tristrips[a].size();
o_index++;
}
for (a = 0; a < xml->trifans.size(); a++) {
for (unsigned int m = 0; m < xml->trifans[a].size(); m++, index++)
vertexlist[index] = xml->trifans[a][m];
polytypes[o_index] = GFXTRIFAN;
poly_offsets[o_index] = xml->trifans[a].size();
o_index++;
}
for (a = 0; a < xml->quadstrips.size(); a++) {
for (unsigned int m = 0; m < xml->quadstrips[a].size(); m++, index++)
vertexlist[index] = xml->quadstrips[a][m];
polytypes[o_index] = GFXQUADSTRIP;
poly_offsets[o_index] = xml->quadstrips[a].size();
o_index++;
}
for (a = 0; a < xml->linestrips.size(); a++) {
for (unsigned int m = 0; m < xml->linestrips[a].size(); m++, index++)
vertexlist[index] = xml->linestrips[a][m];
polytypes[o_index] = GFXLINESTRIP;
poly_offsets[o_index] = xml->linestrips[a].size();
o_index++;
}
for (i = 0; i < index; ++i)
updateMax( mn, mx, vertexlist[i] );
//begin tangent calculations if necessary
if (!xml->usetangents) {
ClearTangents( vertexlist );
vector< float >weights;
vector< int > indices( vertexlist.size() ); //Oops, someday we'll use real indices
weights.resize( vertexlist.size(), 0.f );
size_t i, j, n;
for (i = 0, n = vertexlist.size(); i < n; ++i)
indices[i] = i;
for (i = j = 0, n = polytypes.size(); i < n; j += poly_offsets[i++])
SumTangents( vertexlist, indices, j, j+poly_offsets[i], polytypes[i], weights );
NormalizeTangents( vertexlist, weights );
}
if (mn.i == FLT_MAX && mn.j == FLT_MAX && mn.k == FLT_MAX)
mx.i = mx.j = mx.k = mn.i = mn.j = mn.k = 0;
mn.i *= xml->scale.i;
mn.j *= xml->scale.j;
mn.k *= xml->scale.k;
mx.i *= xml->scale.i;
mx.j *= xml->scale.j;
mx.k *= xml->scale.k;
float x_center = (mn.i+mx.i)/2.0,
y_center = (mn.j+mx.j)/2.0,
z_center = (mn.k+mx.k)/2.0;
local_pos = Vector( x_center, y_center, z_center );
for (a = 0; a < totalvertexsize; a++) {
vertexlist[a].x *= xml->scale.i; //FIXME
vertexlist[a].y *= xml->scale.j;
vertexlist[a].z *= xml->scale.k;
}
for (a = 0; a < xml->vertices.size(); a++) {
xml->vertices[a].x *= xml->scale.i; //FIXME
xml->vertices[a].y *= xml->scale.j;
xml->vertices[a].z *= xml->scale.k;
xml->vertices[a].i *= -1;
xml->vertices[a].k *= -1;
xml->vertices[a].j *= -1;
}
if (o_index || index)
radialSize = .5*(mx-mn).Magnitude();
if (xml->sharevert) {
vlist = new GFXVertexList(
(polytypes.size() ? &polytypes[0] : 0),
xml->vertices.size(),
(xml->vertices.size() ? &xml->vertices[0] : 0), o_index,
(poly_offsets.size() ? &poly_offsets[0] : 0), false,
(ind.size() ? &ind[0] : 0) );
} else {
static bool usopttmp = ( XMLSupport::parse_bool( vs_config->getVariable( "graphics", "<API key>", "false" ) ) );
static float optvertexlimit =
( XMLSupport::parse_float( vs_config->getVariable( "graphics", "<API key>", "1.0" ) ) );
bool cachunk = false;
if ( usopttmp && (vertexlist.size() > 0) ) {
int numopt = totalvertexsize;
GFXVertex *newv;
unsigned int *ind;
GFXOptimizeList( &vertexlist[0], totalvertexsize, &newv, &numopt, &ind );
if (numopt < totalvertexsize*optvertexlimit) {
vlist = new GFXVertexList(
(polytypes.size() ? &polytypes[0] : 0),
numopt, newv, o_index,
(poly_offsets.size() ? &poly_offsets[0] : 0), false,
ind );
cachunk = true;
}
free( ind );
free( newv );
}
if (!cachunk) {
if (vertexlist.size() == 0)
vertexlist.resize( 1 );
vlist = new GFXVertexList(
(polytypes.size() ? &polytypes[0] : 0),
totalvertexsize, &vertexlist[0], o_index,
(poly_offsets.size() ? &poly_offsets[0] : 0) );
}
}
CreateLogos( xml, xml->faction, xml->fg );
//Calculate bounding sphere
if (mn.i == FLT_MAX) {
mn = Vector( 0, 0, 0 );
mx = Vector( 0, 0, 0 );
}
GFXSetMaterial( myMatNum, xml->material );
} |
package org.j3d.aviatrix3d;
// External imports
// None
// Local imports
import org.j3d.aviatrix3d.rendering.SceneCullable;
import org.j3d.aviatrix3d.rendering.ViewportCullable;
import org.j3d.aviatrix3d.rendering.<API key>;
/**
* A viewport that contains a single scene, with no internal layering.
* <p>
*
* @author Justin Couch
* @version $Revision: 1.6 $
*/
public class SimpleViewport extends Viewport
implements ViewportCullable,
<API key>
{
/** Message about code that is not valid parent */
protected static final String HAS_PARENT_MSG = "This scene already has a " +
"parent. Scenes cannot be shared amongst layers multiple times.";
/** The viewport that this layer manages */
private SimpleScene scene;
/** Flag to describe whether this is the currently active sound layer */
private boolean activeSoundLayer;
/** Update handler for the external code. Not created until needed. */
private InternalUpdater internalUpdater;
/**
* Internal implementation of the <API key>. Done as an
* inner class to hide the calls from public consumption.
*/
private class InternalUpdater
implements <API key>
{
/**
* Notify this layer that it is no longer the active audio layer for
* rendering purposes.
*/
public void <API key>()
{
activeSoundLayer = false;
}
}
/**
* Construct a new, empty, viewport instance
*/
public SimpleViewport()
{
super(SIMPLE);
activeSoundLayer = false;
}
// Methods defined by ViewportCullable
/**
* Get the cullable layer child that for the given layer index.
*
* @return The layer cullable at the given index or null
*/
public <API key> getCullableLayer(int viewportIndex)
{
return this;
}
/**
* Check to see if this render pass is the one that also has the
* spatialised audio to be rendered for this frame. If this is a multipass
* layer then there is must return false and potentially one of the render
* passes will be the active audio source. See the package
* documentation for more information about how this state is managed.
*
* @return true if this is the source that should be rendered this
* this frame.
*/
public boolean isAudioSource()
{
return activeSoundLayer;
}
/**
* Returns the number of valid cullable children to process. If there are
* no valid cullable children, return 0.
*
* @return A number greater than or equal to zero
*/
public int numCullableChildren()
{
return scene != null ? 1 : 0;
}
// Methods defined by <API key>
/**
* Check to see if this is a multipass cullable or single pass.
*
* @return true if this is a multipass cullable
*/
public boolean isMultipassViewport()
{
return false;
}
/**
* Get the cullable layer child that for the given layer index.
*
* @return The layer cullable at the given index or null
*/
public SceneCullable getCullableScene()
{
return (scene instanceof SceneCullable) ?
(SceneCullable)scene: null;
}
// Methods defined by Viewport
/**
* Set the dimensions of the viewport in pixels. Coordinates are defined in
* the space of the parent component that is being rendered to.
*
* @param x The lower left x coordinate for the view
* @param y The lower left y coordinate for the view
* @param width The width of the viewport in pixels
* @param height The height of the viewport in pixels
* @throws <API key> An attempt was made to write outside
* of the <API key> callback method
*/
public void setDimensions(int x, int y, int width, int height)
throws <API key>
{
super.setDimensions(x, y, width, height);
if(scene != null)
scene.<API key>(x, y, width, height);
}
// Methods defined by ScenegraphObject
/**
* Set the scenegraph update handler for this node. It will notify
* all its children of the value. A null value will clear the current
* handler.
*
* @param handler The instance to use as a handler
*/
protected void setUpdateHandler(NodeUpdateHandler handler)
{
super.setUpdateHandler(handler);
if(scene != null)
scene.setUpdateHandler(handler);
}
/**
* Notification that this object is live now. Overridden to make sure that
* the live state of the nodes represents the same state as the parent
* scene graph.
*
* @param state true if this should be marked as live now
*/
protected void setLive(boolean state)
{
super.setLive(state);
if(scene != null)
scene.setLive(state);
}
// Local Methods
/**
* Set this layer to be the currently active sound layer. The previously
* active layer will be disabled. This method can only be called during
* the dataChanged() callback.
*/
public void <API key>()
throws <API key>
{
if(isLive() && updateHandler != null &&
!updateHandler.<API key>(this))
throw new <API key>(WRITE_TIMING_MSG);
activeSoundLayer = true;
if(updateHandler != null)
{
if(internalUpdater == null)
internalUpdater = new InternalUpdater();
updateHandler.<API key>(internalUpdater);
}
}
/**
* Check to see if this is the currently active layer for sound rendering.
* This will only return true the frame after calling
* {@link #<API key>()}. The effects, however, will be rendered
* starting the frame that this is set.
*
* @return true if this is the layer that will generate sound rendering
*/
public boolean isActiveSoundLayer()
{
return activeSoundLayer;
}
/**
* Set a new scene instance to be used by this viewport.
* <p>
* Note that a scene cannot have more than one parent, so sharing it
* between viewports will result in an error.
*
* @param sc The scene instance to use, or null to clear
* @throws <API key> An attempt was made to write outside
* of the NodeUpdateListener callback method
* @throws <API key> This scene already has a current parent
* preventing it from being used
*/
public void setScene(SimpleScene sc)
throws <API key>, <API key>
{
if(isLive() && updateHandler != null &&
!updateHandler.<API key>(this))
throw new <API key>(WRITE_TIMING_MSG);
scene = sc;
// No scene? Ignore it.
if(sc == null)
return;
if(sc.hasParent())
throw new <API key>(HAS_PARENT_MSG);
sc.setUpdateHandler(updateHandler);
sc.<API key>(viewX, viewY, viewWidth, viewHeight);
sc.setLive(alive);
}
/**
* Get the currently set scene instance. If no scene is set, null
* is returned.
*
* @return The current scene instance or null
*/
public SimpleScene getScene()
{
return scene;
}
} |
<?php
namespace Spray\BundleIntegration;
use Symfony\Component\HttpKernel\Bundle\Bundle;
/**
* DO NOT USE THIS BUNDLE IN YOUR APPLICATION
*
* This bundle is intended to be used for unittests for this project only.
*
* IntegrationBundle
*/
class IntegrationBundle extends Bundle
{
} |
/* Qualcomm Technologies, Inc. EMAC Gigabit Ethernet Driver */
#include <linux/if_ether.h>
#include <linux/if_vlan.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/of_net.h>
#include <linux/of_device.h>
#include <linux/phy.h>
#include <linux/platform_device.h>
#include <linux/acpi.h>
#include "emac.h"
#include "emac-mac.h"
#include "emac-phy.h"
#include "emac-sgmii.h"
#define EMAC_MSG_DEFAULT (NETIF_MSG_DRV | NETIF_MSG_PROBE | NETIF_MSG_LINK | \
NETIF_MSG_TIMER | NETIF_MSG_IFDOWN | NETIF_MSG_IFUP)
#define EMAC_RRD_SIZE 4
/* The RRD size if timestamping is enabled: */
#define EMAC_TS_RRD_SIZE 6
#define EMAC_TPD_SIZE 4
#define EMAC_RFD_SIZE 2
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define <API key> 8
#define <API key> 5
#define EMAC_PREAMBLE_DEF 7
#define DMAR_DLY_CNT_DEF 15
#define DMAW_DLY_CNT_DEF 4
#define IMR_NORMAL_MASK (\
ISR_ERROR |\
ISR_GPHY_LINK |\
ISR_TX_PKT |\
GPHY_WAKEUP_INT)
#define IMR_EXTENDED_MASK (\
SW_MAN_INT |\
ISR_OVER |\
ISR_ERROR |\
ISR_GPHY_LINK |\
ISR_TX_PKT |\
GPHY_WAKEUP_INT)
#define ISR_TX_PKT (\
TX_PKT_INT |\
TX_PKT_INT1 |\
TX_PKT_INT2 |\
TX_PKT_INT3)
#define ISR_GPHY_LINK (\
GPHY_LINK_UP_INT |\
GPHY_LINK_DOWN_INT)
#define ISR_OVER (\
RFD0_UR_INT |\
RFD1_UR_INT |\
RFD2_UR_INT |\
RFD3_UR_INT |\
RFD4_UR_INT |\
RXF_OF_INT |\
TXF_UR_INT)
#define ISR_ERROR (\
DMAR_TO_INT |\
DMAW_TO_INT |\
TXQ_TO_INT)
/* in sync with enum emac_clk_id */
static const char * const emac_clk_name[] = {
"axi_clk", "cfg_ahb_clk", "high_speed_clk", "mdio_clk", "tx_clk",
"rx_clk", "sys_clk"
};
void emac_reg_update32(void __iomem *addr, u32 mask, u32 val)
{
u32 data = readl(addr);
writel(((data & ~mask) | val), addr);
}
/* reinitialize */
int emac_reinit_locked(struct emac_adapter *adpt)
{
int ret;
mutex_lock(&adpt->reset_lock);
emac_mac_down(adpt);
emac_sgmii_reset(adpt);
ret = emac_mac_up(adpt);
mutex_unlock(&adpt->reset_lock);
return ret;
}
/* NAPI */
static int emac_napi_rtx(struct napi_struct *napi, int budget)
{
struct emac_rx_queue *rx_q =
container_of(napi, struct emac_rx_queue, napi);
struct emac_adapter *adpt = netdev_priv(rx_q->netdev);
struct emac_irq *irq = rx_q->irq;
int work_done = 0;
emac_mac_rx_process(adpt, rx_q, &work_done, budget);
if (work_done < budget) {
napi_complete(napi);
irq->mask |= rx_q->intr;
writel(irq->mask, adpt->base + EMAC_INT_MASK);
}
return work_done;
}
/* Transmit the packet */
static int emac_start_xmit(struct sk_buff *skb, struct net_device *netdev)
{
struct emac_adapter *adpt = netdev_priv(netdev);
return <API key>(adpt, &adpt->tx_q, skb);
}
irqreturn_t emac_isr(int _irq, void *data)
{
struct emac_irq *irq = data;
struct emac_adapter *adpt =
container_of(irq, struct emac_adapter, irq);
struct emac_rx_queue *rx_q = &adpt->rx_q;
u32 isr, status;
/* disable the interrupt */
writel(0, adpt->base + EMAC_INT_MASK);
isr = readl_relaxed(adpt->base + EMAC_INT_STATUS);
status = isr & irq->mask;
if (status == 0)
goto exit;
if (status & ISR_ERROR) {
netif_warn(adpt, intr, adpt->netdev,
"warning: error irq status 0x%lx\n",
status & ISR_ERROR);
/* reset MAC */
schedule_work(&adpt->work_thread);
}
/* Schedule the napi for receive queue with interrupt
* status bit set
*/
if (status & rx_q->intr) {
if (napi_schedule_prep(&rx_q->napi)) {
irq->mask &= ~rx_q->intr;
__napi_schedule(&rx_q->napi);
}
}
if (status & TX_PKT_INT)
emac_mac_tx_process(adpt, &adpt->tx_q);
if (status & ISR_OVER)
<API key>("warning: TX/RX overflow\n");
/* link event */
if (status & ISR_GPHY_LINK)
phy_mac_interrupt(adpt->phydev, !!(status & GPHY_LINK_UP_INT));
exit:
/* enable the interrupt */
writel(irq->mask, adpt->base + EMAC_INT_MASK);
return IRQ_HANDLED;
}
/* Configure VLAN tag strip/insert feature */
static int emac_set_features(struct net_device *netdev,
netdev_features_t features)
{
netdev_features_t changed = features ^ netdev->features;
struct emac_adapter *adpt = netdev_priv(netdev);
/* We only need to reprogram the hardware if the VLAN tag features
* have changed, and if it's already running.
*/
if (!(changed & (<API key> | <API key>)))
return 0;
if (!netif_running(netdev))
return 0;
/* <API key>() uses netdev->features to configure the EMAC,
* so make sure it's set first.
*/
netdev->features = features;
return emac_reinit_locked(adpt);
}
/* Configure Multicast and Promiscuous modes */
static void emac_rx_mode_set(struct net_device *netdev)
{
struct emac_adapter *adpt = netdev_priv(netdev);
struct netdev_hw_addr *ha;
<API key>(adpt);
/* update multicast address filtering */
<API key>(adpt);
<API key>(ha, netdev)
<API key>(adpt, ha->addr);
}
/* Change the Maximum Transfer Unit (MTU) */
static int emac_change_mtu(struct net_device *netdev, int new_mtu)
{
struct emac_adapter *adpt = netdev_priv(netdev);
netif_info(adpt, hw, adpt->netdev,
"changing MTU from %d to %d\n", netdev->mtu,
new_mtu);
netdev->mtu = new_mtu;
if (netif_running(netdev))
return emac_reinit_locked(adpt);
return 0;
}
/* Called when the network interface is made active */
static int emac_open(struct net_device *netdev)
{
struct emac_adapter *adpt = netdev_priv(netdev);
int ret;
/* allocate rx/tx dma buffer & descriptors */
ret = <API key>(adpt);
if (ret) {
netdev_err(adpt->netdev, "error allocating rx/tx rings\n");
return ret;
}
ret = emac_mac_up(adpt);
if (ret) {
<API key>(adpt);
return ret;
}
emac_mac_start(adpt);
return 0;
}
/* Called when the network interface is disabled */
static int emac_close(struct net_device *netdev)
{
struct emac_adapter *adpt = netdev_priv(netdev);
mutex_lock(&adpt->reset_lock);
emac_mac_down(adpt);
<API key>(adpt);
mutex_unlock(&adpt->reset_lock);
return 0;
}
/* Respond to a TX hang */
static void emac_tx_timeout(struct net_device *netdev)
{
struct emac_adapter *adpt = netdev_priv(netdev);
schedule_work(&adpt->work_thread);
}
/* IOCTL support for the interface */
static int emac_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
{
if (!netif_running(netdev))
return -EINVAL;
if (!netdev->phydev)
return -ENODEV;
return phy_mii_ioctl(netdev->phydev, ifr, cmd);
}
/* Provide network statistics info for the interface */
static struct rtnl_link_stats64 *emac_get_stats64(struct net_device *netdev,
struct rtnl_link_stats64 *net_stats)
{
struct emac_adapter *adpt = netdev_priv(netdev);
unsigned int addr = <API key>;
struct emac_stats *stats = &adpt->stats;
u64 *stats_itr = &adpt->stats.rx_ok;
u32 val;
spin_lock(&stats->lock);
while (addr <= <API key>) {
val = readl_relaxed(adpt->base + addr);
*stats_itr += val;
stats_itr++;
addr += sizeof(u32);
}
/* additional rx status */
val = readl_relaxed(adpt->base + <API key>);
adpt->stats.rx_crc_align += val;
val = readl_relaxed(adpt->base + <API key>);
adpt->stats.rx_jabbers += val;
/* update tx status */
addr = <API key>;
stats_itr = &adpt->stats.tx_ok;
while (addr <= <API key>) {
val = readl_relaxed(adpt->base + addr);
*stats_itr += val;
++stats_itr;
addr += sizeof(u32);
}
/* additional tx status */
val = readl_relaxed(adpt->base + <API key>);
adpt->stats.tx_col += val;
/* return parsed statistics */
net_stats->rx_packets = stats->rx_ok;
net_stats->tx_packets = stats->tx_ok;
net_stats->rx_bytes = stats->rx_byte_cnt;
net_stats->tx_bytes = stats->tx_byte_cnt;
net_stats->multicast = stats->rx_mcast;
net_stats->collisions = stats->tx_1_col + stats->tx_2_col * 2 +
stats->tx_late_col + stats->tx_abort_col;
net_stats->rx_errors = stats->rx_frag + stats->rx_fcs_err +
stats->rx_len_err + stats->rx_sz_ov +
stats->rx_align_err;
net_stats->rx_fifo_errors = stats->rx_rxf_ov;
net_stats->rx_length_errors = stats->rx_len_err;
net_stats->rx_crc_errors = stats->rx_fcs_err;
net_stats->rx_frame_errors = stats->rx_align_err;
net_stats->rx_over_errors = stats->rx_rxf_ov;
net_stats->rx_missed_errors = stats->rx_rxf_ov;
net_stats->tx_errors = stats->tx_late_col + stats->tx_abort_col +
stats->tx_underrun + stats->tx_trunc;
net_stats->tx_fifo_errors = stats->tx_underrun;
net_stats->tx_aborted_errors = stats->tx_abort_col;
net_stats->tx_window_errors = stats->tx_late_col;
spin_unlock(&stats->lock);
return net_stats;
}
static const struct net_device_ops emac_netdev_ops = {
.ndo_open = emac_open,
.ndo_stop = emac_close,
.ndo_validate_addr = eth_validate_addr,
.ndo_start_xmit = emac_start_xmit,
.ndo_set_mac_address = eth_mac_addr,
.ndo_change_mtu = emac_change_mtu,
.ndo_do_ioctl = emac_ioctl,
.ndo_tx_timeout = emac_tx_timeout,
.ndo_get_stats64 = emac_get_stats64,
.ndo_set_features = emac_set_features,
.ndo_set_rx_mode = emac_rx_mode_set,
};
/* Watchdog task routine, called to reinitialize the EMAC */
static void emac_work_thread(struct work_struct *work)
{
struct emac_adapter *adpt =
container_of(work, struct emac_adapter, work_thread);
emac_reinit_locked(adpt);
}
/* Initialize various data structures */
static void emac_init_adapter(struct emac_adapter *adpt)
{
u32 reg;
/* descriptors */
adpt->tx_desc_cnt = EMAC_DEF_TX_DESCS;
adpt->rx_desc_cnt = EMAC_DEF_RX_DESCS;
/* dma */
adpt->dma_order = emac_dma_ord_out;
adpt->dmar_block = emac_dma_req_4096;
adpt->dmaw_block = emac_dma_req_128;
adpt->dmar_dly_cnt = DMAR_DLY_CNT_DEF;
adpt->dmaw_dly_cnt = DMAW_DLY_CNT_DEF;
adpt->tpd_burst = <API key>;
adpt->rfd_burst = <API key>;
/* irq moderator */
reg = ((EMAC_DEF_RX_IRQ_MOD >> 1) << <API key>) |
((EMAC_DEF_TX_IRQ_MOD >> 1) << <API key>);
adpt->irq_mod = reg;
/* others */
adpt->preamble = EMAC_PREAMBLE_DEF;
}
/* Get the clock */
static int emac_clks_get(struct platform_device *pdev,
struct emac_adapter *adpt)
{
unsigned int i;
for (i = 0; i < EMAC_CLK_CNT; i++) {
struct clk *clk = devm_clk_get(&pdev->dev, emac_clk_name[i]);
if (IS_ERR(clk)) {
dev_err(&pdev->dev,
"could not claim clock %s (error=%li)\n",
emac_clk_name[i], PTR_ERR(clk));
return PTR_ERR(clk);
}
adpt->clk[i] = clk;
}
return 0;
}
/* Initialize clocks */
static int <API key>(struct platform_device *pdev,
struct emac_adapter *adpt)
{
int ret;
ret = emac_clks_get(pdev, adpt);
if (ret)
return ret;
ret = clk_prepare_enable(adpt->clk[EMAC_CLK_AXI]);
if (ret)
return ret;
ret = clk_prepare_enable(adpt->clk[EMAC_CLK_CFG_AHB]);
if (ret)
return ret;
ret = clk_set_rate(adpt->clk[EMAC_CLK_HIGH_SPEED], 19200000);
if (ret)
return ret;
return clk_prepare_enable(adpt->clk[EMAC_CLK_HIGH_SPEED]);
}
/* Enable clocks; needs <API key> to be called before */
static int <API key>(struct platform_device *pdev,
struct emac_adapter *adpt)
{
int ret;
ret = clk_set_rate(adpt->clk[EMAC_CLK_TX], 125000000);
if (ret)
return ret;
ret = clk_prepare_enable(adpt->clk[EMAC_CLK_TX]);
if (ret)
return ret;
ret = clk_set_rate(adpt->clk[EMAC_CLK_HIGH_SPEED], 125000000);
if (ret)
return ret;
ret = clk_set_rate(adpt->clk[EMAC_CLK_MDIO], 25000000);
if (ret)
return ret;
ret = clk_prepare_enable(adpt->clk[EMAC_CLK_MDIO]);
if (ret)
return ret;
ret = clk_prepare_enable(adpt->clk[EMAC_CLK_RX]);
if (ret)
return ret;
return clk_prepare_enable(adpt->clk[EMAC_CLK_SYS]);
}
static void emac_clks_teardown(struct emac_adapter *adpt)
{
unsigned int i;
for (i = 0; i < EMAC_CLK_CNT; i++)
<API key>(adpt->clk[i]);
}
/* Get the resources */
static int <API key>(struct platform_device *pdev,
struct emac_adapter *adpt)
{
struct net_device *netdev = adpt->netdev;
struct resource *res;
char maddr[ETH_ALEN];
int ret = 0;
/* get mac address */
if (<API key>(&pdev->dev, maddr, ETH_ALEN))
ether_addr_copy(netdev->dev_addr, maddr);
else
eth_hw_addr_random(netdev);
/* Core 0 interrupt */
ret = platform_get_irq(pdev, 0);
if (ret < 0) {
dev_err(&pdev->dev,
"error: missing core0 irq resource (error=%i)\n", ret);
return ret;
}
adpt->irq.irq = ret;
/* base register address */
res = <API key>(pdev, IORESOURCE_MEM, 0);
adpt->base = <API key>(&pdev->dev, res);
if (IS_ERR(adpt->base))
return PTR_ERR(adpt->base);
/* CSR register address */
res = <API key>(pdev, IORESOURCE_MEM, 1);
adpt->csr = <API key>(&pdev->dev, res);
if (IS_ERR(adpt->csr))
return PTR_ERR(adpt->csr);
netdev->base_addr = (unsigned long)adpt->base;
return 0;
}
static const struct of_device_id emac_dt_match[] = {
{
.compatible = "qcom,fsm9900-emac",
},
{}
};
#if IS_ENABLED(CONFIG_ACPI)
static const struct acpi_device_id emac_acpi_match[] = {
{
.id = "QCOM8070",
},
{}
};
MODULE_DEVICE_TABLE(acpi, emac_acpi_match);
#endif
static int emac_probe(struct platform_device *pdev)
{
struct net_device *netdev;
struct emac_adapter *adpt;
struct emac_phy *phy;
u16 devid, revid;
u32 reg;
int ret;
/* The EMAC itself is capable of 64-bit DMA, so try that first. */
ret = <API key>(&pdev->dev, DMA_BIT_MASK(64));
if (ret) {
/* Some platforms may restrict the EMAC's address bus to less
* then the size of DDR. In this case, we need to try a
* smaller mask. We could try every possible smaller mask,
* but that's overkill. Instead, just fall to 32-bit, which
* should always work.
*/
ret = <API key>(&pdev->dev, DMA_BIT_MASK(32));
if (ret) {
dev_err(&pdev->dev, "could not set DMA mask\n");
return ret;
}
}
netdev = alloc_etherdev(sizeof(struct emac_adapter));
if (!netdev)
return -ENOMEM;
dev_set_drvdata(&pdev->dev, netdev);
SET_NETDEV_DEV(netdev, &pdev->dev);
adpt = netdev_priv(netdev);
adpt->netdev = netdev;
adpt->msg_enable = EMAC_MSG_DEFAULT;
phy = &adpt->phy;
mutex_init(&adpt->reset_lock);
spin_lock_init(&adpt->stats.lock);
adpt->irq.mask = RX_PKT_INT0 | IMR_NORMAL_MASK;
ret = <API key>(pdev, adpt);
if (ret)
goto err_undo_netdev;
/* initialize clocks */
ret = <API key>(pdev, adpt);
if (ret) {
dev_err(&pdev->dev, "could not initialize clocks\n");
goto err_undo_netdev;
}
netdev->watchdog_timeo = EMAC_WATCHDOG_TIME;
netdev->irq = adpt->irq.irq;
adpt->rrd_size = EMAC_RRD_SIZE;
adpt->tpd_size = EMAC_TPD_SIZE;
adpt->rfd_size = EMAC_RFD_SIZE;
netdev->netdev_ops = &emac_netdev_ops;
emac_init_adapter(adpt);
/* init external phy */
ret = emac_phy_config(pdev, adpt);
if (ret)
goto err_undo_clocks;
/* init internal sgmii phy */
ret = emac_sgmii_config(pdev, adpt);
if (ret)
goto err_undo_mdiobus;
/* enable clocks */
ret = <API key>(pdev, adpt);
if (ret) {
dev_err(&pdev->dev, "could not initialize clocks\n");
goto err_undo_mdiobus;
}
emac_mac_reset(adpt);
/* set hw features */
netdev->features = NETIF_F_SG | NETIF_F_HW_CSUM | NETIF_F_RXCSUM |
NETIF_F_TSO | NETIF_F_TSO6 | <API key> |
<API key>;
netdev->hw_features = netdev->features;
netdev->vlan_features |= NETIF_F_SG | NETIF_F_HW_CSUM |
NETIF_F_TSO | NETIF_F_TSO6;
/* MTU range: 46 - 9194 */
netdev->min_mtu = <API key> -
(ETH_HLEN + ETH_FCS_LEN + VLAN_HLEN);
netdev->max_mtu = <API key> -
(ETH_HLEN + ETH_FCS_LEN + VLAN_HLEN);
INIT_WORK(&adpt->work_thread, emac_work_thread);
/* Initialize queues */
<API key>(pdev, adpt);
netif_napi_add(netdev, &adpt->rx_q.napi, emac_napi_rtx,
NAPI_POLL_WEIGHT);
ret = register_netdev(netdev);
if (ret) {
dev_err(&pdev->dev, "could not register net device\n");
goto err_undo_napi;
}
reg = readl_relaxed(adpt->base + EMAC_DMA_MAS_CTRL);
devid = (reg & DEV_ID_NUM_BMSK) >> DEV_ID_NUM_SHFT;
revid = (reg & DEV_REV_NUM_BMSK) >> DEV_REV_NUM_SHFT;
reg = readl_relaxed(adpt->base + <API key>);
netif_info(adpt, probe, netdev,
"hardware id %d.%d, hardware version %d.%d.%d\n",
devid, revid,
(reg & MAJOR_BMSK) >> MAJOR_SHFT,
(reg & MINOR_BMSK) >> MINOR_SHFT,
(reg & STEP_BMSK) >> STEP_SHFT);
return 0;
err_undo_napi:
netif_napi_del(&adpt->rx_q.napi);
err_undo_mdiobus:
mdiobus_unregister(adpt->mii_bus);
err_undo_clocks:
emac_clks_teardown(adpt);
err_undo_netdev:
free_netdev(netdev);
return ret;
}
static int emac_remove(struct platform_device *pdev)
{
struct net_device *netdev = dev_get_drvdata(&pdev->dev);
struct emac_adapter *adpt = netdev_priv(netdev);
unregister_netdev(netdev);
netif_napi_del(&adpt->rx_q.napi);
emac_clks_teardown(adpt);
mdiobus_unregister(adpt->mii_bus);
free_netdev(netdev);
if (adpt->phy.digital)
iounmap(adpt->phy.digital);
iounmap(adpt->phy.base);
return 0;
}
static struct platform_driver <API key> = {
.probe = emac_probe,
.remove = emac_remove,
.driver = {
.name = "qcom-emac",
.of_match_table = emac_dt_match,
.acpi_match_table = ACPI_PTR(emac_acpi_match),
},
};
<API key>(<API key>);
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("platform:qcom-emac"); |
#include <common.h>
#include <exports.h>
#include <orion_tuner.h>
int main()
{
int err_code = 0;
TUNER_PARAMS_S tuner_param;
TUNER_STATUS_E tuner_status = 0;
printf("Into main. \n");
err_code = CSTUNER_Open(TUNER_DVBC);
if(err_code < 0)
{
printf("Error: CSTUNER_Init.\n");
return err_code;
}
printf("1 success CSTUNER_Open. \n");
err_code = CSTUNER_Init();
if(err_code < 0) {
printf("Error: CSTUNER_Init.\n");
return err_code;
}
printf("1 success CSTUNER_Init. \n");
tuner_param.frequency = 698;
tuner_param.symbol_rate = 6875;
tuner_param.modulation = QAM_64;
tuner_param.inversion = INVERSION_AUTO;
err_code = <API key>(&tuner_param);
if(err_code < 0) {
printf("Error: <API key>.\n");
return err_code;
}
printf("1 success <API key>. OK . \n");
int cnt = 0;
while(cnt++ < 5) {
CSTUNER_ReadStatus(&tuner_status);
udelay(2000000);
}
printf("Out of Main, Success!\n");
return 0;
} |
<?php
namespace Skypress\Models;
defined( 'ABSPATH' ) or die( 'Cheatin’ uh?' );
/**
* @version 1.0.0
* @since 1.0.0
*
* @author Thomas DENEULIN <thomas@delipress.io>
*/
interface ServiceInterface {} |
<?php
?><!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="profile" href="http://gmpg.org/xfn/11">
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<div id="page" class="site">
<a class="skip-link screen-reader-text" href="#content"><?php esc_html_e( 'Skip to content', 'nmnews' ); ?></a>
<header id="masthead" class="site-header" role="banner">
<div class="container">
<div class="brand">
<?php
if ( is_front_page() && is_home() ) : ?>
<a class="brand-logo" href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><img src="http://localhost/aat/wp-content/uploads/2017/03/namaskar-news.png"></a>
<?php else : ?>
<a class="brand-logo" href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><img src="http://localhost/aat/wp-content/uploads/2017/03/namaskar-news.png"></a>
<?php
endif;
?>
</div>
</div>
<div class="navbar">
<nav>
<div class="nav-wrapper">
<?php
if ( is_front_page() && is_home() ) : ?>
<!--<a class="brand-logo" href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a>-->
<?php else : ?>
<!--<a class="brand-logo" href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a>-->
<?php
endif;
?>
<a href="#" data-activates="mobile-demo" class="button-collapse"><i class="material-icons">menu</i></a>
<div class="navigation">
<?php wp_nav_menu( array( 'theme_location' => 'menu-1', 'menu_id' => 'primary-menu', 'menu_class' => '<API key>') ); ?>
</div>
<?php wp_nav_menu( array( 'theme_location' => 'menu-1', 'menu_id' => 'mobile-demo', 'menu_class' => 'side-nav' ) ); ?>
</div>
</nav>
</div>
</header><!-- #masthead -->
<div id="content" class="site-content"> |
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/timer.h>
#include <linux/init.h>
#include <linux/i2c.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/input.h>
#include <linux/earlysuspend.h>
#include <linux/miscdevice.h>
#include <linux/input/cypress-touchkey.h>
#ifdef <API key>
#include <mach/gpio.h>
#include <mach/gpio-aries.h>
#include <mach/regs-gpio.h>
#endif
#define SCANCODE_MASK 0x07
#define UPDOWN_EVENT_MASK 0x08
#define ESD_STATE_MASK 0x10
#define BACKLIGHT_ON 0x10
#define BACKLIGHT_OFF 0x20
#define OLD_BACKLIGHT_ON 0x1
#define OLD_BACKLIGHT_OFF 0x2
#define DEVICE_NAME "cypress-touchkey"
#ifdef <API key>
extern const unsigned long touch_int_flt_width;
void <API key>(unsigned long width);
#endif
int bl_on = 0;
static DEFINE_SEMAPHORE(enable_sem);
static DEFINE_SEMAPHORE(i2c_sem);
struct <API key> *bl_devdata;
static int bl_timeout = 1600; // This gets overridden by userspace AriesParts
static struct timer_list bl_timer;
static void bl_off(struct work_struct *bl_off_work);
static DECLARE_WORK(bl_off_work, bl_off);
struct <API key> {
struct i2c_client *client;
struct input_dev *input_dev;
struct <API key> *pdata;
struct early_suspend early_suspend;
u8 backlight_on;
u8 backlight_off;
bool is_dead;
bool is_powering_on;
bool has_legacy_keycode;
bool is_sleeping;
};
static int <API key>(struct <API key> *devdata,
u8 *val)
{
int ret;
int retry = 2;
down(&i2c_sem);
while (true) {
ret = i2c_smbus_read_byte(devdata->client);
if (ret >= 0) {
*val = ret;
ret = 0;
break;
}
if (!retry
dev_err(&devdata->client->dev, "i2c read error\n");
break;
}
msleep(10);
}
up(&i2c_sem);
return ret;
}
static int <API key>(struct <API key> *devdata,
u8 val)
{
int ret;
int retry = 2;
down(&i2c_sem);
while (true) {
ret = <API key>(devdata->client, val);
if (!ret) {
ret = 0;
break;
}
if (!retry
dev_err(&devdata->client->dev, "i2c write error\n");
break;
}
msleep(10);
}
up(&i2c_sem);
return ret;
}
static void all_keys_up(struct <API key> *devdata)
{
int i;
for (i = 0; i < devdata->pdata->keycode_cnt; i++)
input_report_key(devdata->input_dev,
devdata->pdata->keycode[i], 0);
input_sync(devdata->input_dev);
}
static void bl_off(struct work_struct *bl_off_work)
{
if (bl_devdata == NULL || unlikely(bl_devdata->is_dead) ||
bl_devdata->is_powering_on || bl_on || bl_devdata->is_sleeping)
return;
<API key>(bl_devdata, bl_devdata->backlight_off);
}
void bl_timer_callback(unsigned long data)
{
schedule_work(&bl_off_work);
}
static void bl_set_timeout() {
if (bl_timeout > 0) {
mod_timer(&bl_timer, jiffies + msecs_to_jiffies(bl_timeout));
}
}
static int recovery_routine(struct <API key> *devdata)
{
int ret = -1;
int retry = 10;
u8 data;
int irq_eint;
if (unlikely(devdata->is_dead)) {
dev_err(&devdata->client->dev, "%s: Device is already dead, "
"skipping recovery\n", __func__);
return -ENODEV;
}
irq_eint = devdata->client->irq;
down(&enable_sem);
all_keys_up(devdata);
disable_irq_nosync(irq_eint);
while (retry
devdata->pdata->touchkey_onoff(TOUCHKEY_OFF);
devdata->pdata->touchkey_onoff(TOUCHKEY_ON);
ret = <API key>(devdata, &data);
if (!ret) {
if (!devdata->is_sleeping) {
enable_irq(irq_eint);
#ifdef <API key>
<API key>(touch_int_flt_width);
#endif
}
goto out;
}
dev_err(&devdata->client->dev, "%s: i2c transfer error retry = "
"%d\n", __func__, retry);
}
devdata->is_dead = true;
devdata->pdata->touchkey_onoff(TOUCHKEY_OFF);
dev_err(&devdata->client->dev, "%s: touchkey died\n", __func__);
out:
dev_err(&devdata->client->dev, "%s: recovery_routine\n", __func__);
up(&enable_sem);
return ret;
}
// Accidental touch key prevention (see mxt224.c)
extern unsigned int touch_state_val;
static irqreturn_t <API key>(int irq, void *touchkey_devdata)
{
u8 data;
int i;
int ret;
int scancode;
struct <API key> *devdata = touchkey_devdata;
#ifdef <API key>
for (i = 0; i < 10; ++i)
{
ret = gpio_get_value(_3_GPIO_TOUCH_INT);
if (ret & 1) {
//dev_err(&devdata->client->dev, "%s: possible phantom key press... "
// "ignore it!\n", __func__);
goto err;
}
}
#endif
ret = <API key>(devdata, &data);
if (ret || (data & ESD_STATE_MASK)) {
ret = recovery_routine(devdata);
if (ret) {
dev_err(&devdata->client->dev, "%s: touchkey recovery "
"failed!\n", __func__);
goto err;
}
}
if (devdata->has_legacy_keycode) {
scancode = (data & SCANCODE_MASK) - 1;
if (scancode < 0 || scancode >= devdata->pdata->keycode_cnt) {
dev_err(&devdata->client->dev, "%s: scancode is out of "
"range\n", __func__);
goto err;
}
/* Don't send down event while the touch screen is being pressed
* to prevent accidental touch key hit.
*/
if ((data & UPDOWN_EVENT_MASK) || !touch_state_val) {
input_report_key(devdata->input_dev,
devdata->pdata->keycode[scancode],
!(data & UPDOWN_EVENT_MASK));
}
} else {
for (i = 0; i < devdata->pdata->keycode_cnt; i++)
input_report_key(devdata->input_dev,
devdata->pdata->keycode[i],
!!(data & (1U << i)));
}
input_sync(devdata->input_dev);
bl_set_timeout();
err:
return IRQ_HANDLED;
}
static irqreturn_t <API key>(int irq, void *touchkey_devdata)
{
struct <API key> *devdata = touchkey_devdata;
#ifdef <API key>
int i = gpio_get_value(_3_GPIO_TOUCH_INT);
if ((i & 1) || devdata->is_powering_on) {
#else
if (devdata->is_powering_on) {
#endif
dev_dbg(&devdata->client->dev, "%s: ignoring spurious boot "
"interrupt\n", __func__);
return IRQ_HANDLED;
}
return IRQ_WAKE_THREAD;
}
static void notify_led_on(void) {
down(&enable_sem);
if (unlikely(bl_devdata->is_dead) || bl_on)
goto out;
if (bl_devdata->is_sleeping) {
bl_devdata->pdata-><API key>(TOUCHKEY_ON);
bl_devdata->pdata->touchkey_onoff(TOUCHKEY_ON);
}
<API key>(bl_devdata, bl_devdata->backlight_on);
bl_on = 1;
printk(KERN_DEBUG "%s: notification led enabled\n", __FUNCTION__);
out:
up(&enable_sem);
}
static void notify_led_off(void) {
// Avoid race condition with touch key resume
down(&enable_sem);
if (unlikely(bl_devdata->is_dead) || !bl_on)
goto out;
if (bl_on && bl_timer.expires < jiffies) // Don't disable if there's a timer scheduled
<API key>(bl_devdata, bl_devdata->backlight_off);
bl_devdata->pdata-><API key>(TOUCHKEY_OFF);
if (bl_devdata->is_sleeping)
bl_devdata->pdata->touchkey_onoff(TOUCHKEY_OFF);
bl_on = 0;
printk(KERN_DEBUG "%s: notification led disabled\n", __FUNCTION__);
out:
up(&enable_sem);
}
#ifdef <API key>
static void <API key>(struct early_suspend *h)
{
struct <API key> *devdata =
container_of(h, struct <API key>, early_suspend);
down(&enable_sem);
devdata->is_powering_on = true;
if (unlikely(devdata->is_dead)) {
goto out;
}
disable_irq(devdata->client->irq);
if (!bl_on)
devdata->pdata->touchkey_onoff(TOUCHKEY_OFF);
all_keys_up(devdata);
devdata->is_sleeping = true;
out:
up(&enable_sem);
}
static void <API key>(struct early_suspend *h)
{
struct <API key> *devdata =
container_of(h, struct <API key>, early_suspend);
// Avoid race condition with LED notification disable
down(&enable_sem);
devdata->pdata->touchkey_onoff(TOUCHKEY_ON);
if (<API key>(devdata, devdata->backlight_on)) {
devdata->is_dead = true;
devdata->pdata->touchkey_onoff(TOUCHKEY_OFF);
dev_err(&devdata->client->dev, "%s: touch keypad not responding"
" to commands, disabling\n", __func__);
up(&enable_sem);
return;
}
devdata->is_dead = false;
enable_irq(devdata->client->irq);
#ifdef <API key>
<API key>(touch_int_flt_width);
#endif
devdata->is_powering_on = false;
devdata->is_sleeping = false;
up(&enable_sem);
bl_set_timeout();
}
#endif
static ssize_t led_status_read(struct device *dev, struct device_attribute *attr, char *buf) {
return sprintf(buf,"%u\n", bl_on);
}
static ssize_t led_status_write(struct device *dev, struct device_attribute *attr, const char *buf, size_t size)
{
unsigned int data;
if (sscanf(buf, "%u\n", &data)) {
if (data == 1)
notify_led_on();
else
notify_led_off();
}
return size;
}
static ssize_t bl_timeout_read(struct device *dev, struct device_attribute *attr, char *buf) {
return sprintf(buf,"%d\n", bl_timeout);
}
static ssize_t bl_timeout_write(struct device *dev, struct device_attribute *attr, const char *buf, size_t size)
{
sscanf(buf, "%d\n", &bl_timeout);
return size;
}
static DEVICE_ATTR(led, S_IRUGO | S_IWUGO , led_status_read, led_status_write);
static DEVICE_ATTR(bl_timeout, S_IRUGO | S_IWUGO, bl_timeout_read, bl_timeout_write);
static struct attribute *bl_led_attributes[] = {
&dev_attr_led.attr,
&dev_attr_bl_timeout.attr, // Not the best place, but creating a new device is more trouble that it's worth
NULL
};
static struct attribute_group bl_led_group = {
.attrs = bl_led_attributes,
};
static struct miscdevice bl_led_device = {
.minor = MISC_DYNAMIC_MINOR,
.name = "notification",
};
static int <API key>(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct device *dev = &client->dev;
struct input_dev *input_dev;
struct <API key> *devdata;
u8 data[3];
int err;
int cnt;
if (!dev->platform_data) {
dev_err(dev, "%s: Platform data is NULL\n", __func__);
return -EINVAL;
}
devdata = kzalloc(sizeof(*devdata), GFP_KERNEL);
if (devdata == NULL) {
dev_err(dev, "%s: failed to create our state\n", __func__);
return -ENODEV;
}
devdata->client = client;
i2c_set_clientdata(client, devdata);
devdata->pdata = client->dev.platform_data;
if (!devdata->pdata->keycode) {
dev_err(dev, "%s: Invalid platform data\n", __func__);
err = -EINVAL;
goto err_null_keycodes;
}
strlcpy(devdata->client->name, DEVICE_NAME, I2C_NAME_SIZE);
input_dev = <API key>();
if (!input_dev) {
err = -ENOMEM;
goto err_input_alloc_dev;
}
devdata->input_dev = input_dev;
dev_set_drvdata(&input_dev->dev, devdata);
input_dev->name = DEVICE_NAME;
input_dev->id.bustype = BUS_HOST;
for (cnt = 0; cnt < devdata->pdata->keycode_cnt; cnt++)
<API key>(input_dev, EV_KEY,
devdata->pdata->keycode[cnt]);
err = <API key>(input_dev);
if (err)
goto err_input_reg_dev;
devdata->is_powering_on = true;
devdata->is_sleeping = false;
devdata->pdata->touchkey_onoff(TOUCHKEY_ON);
err = i2c_master_recv(client, data, sizeof(data));
if (err < sizeof(data)) {
if (err >= 0)
err = -EIO;
dev_err(dev, "%s: error reading hardware version\n", __func__);
goto err_read;
}
dev_info(dev, "%s: hardware rev1 = %#02x, rev2 = %#02x\n", __func__,
data[1], data[2]);
#ifdef <API key>
devdata->has_legacy_keycode = true;
#else
devdata->has_legacy_keycode = data[1] >= 0xc4 || data[1] < 0x9 ||
(data[1] == 0x9 && data[2] < 0x9);
#endif
if (data[1] < 0xc4 && (data[1] >= 0x8 ||
(data[1] == 0x8 && data[2] >= 0x9)) &&
devdata->has_legacy_keycode == false) {
devdata->backlight_on = BACKLIGHT_ON;
devdata->backlight_off = BACKLIGHT_OFF;
} else {
devdata->backlight_on = OLD_BACKLIGHT_ON;
devdata->backlight_off = OLD_BACKLIGHT_OFF;
}
err = <API key>(devdata, devdata->backlight_off);
if (err) {
dev_err(dev, "%s: touch keypad backlight on failed\n",
__func__);
/* The device may not be responding because of bad firmware
*/
goto err_backlight_off;
}
err = <API key>(client->irq, <API key>,
<API key>, <API key>,
DEVICE_NAME, devdata);
if (err) {
dev_err(dev, "%s: Can't allocate irq.\n", __func__);
goto err_req_irq;
}
#ifdef <API key>
<API key>(touch_int_flt_width);
#endif
#ifdef <API key>
devdata->early_suspend.suspend = <API key>;
devdata->early_suspend.resume = <API key>;
#endif
<API key>(&devdata->early_suspend);
devdata->is_powering_on = false;
if (misc_register(&bl_led_device))
printk("%s misc_register(%s) failed\n", __FUNCTION__, bl_led_device.name);
else {
if (sysfs_create_group(&bl_led_device.this_device->kobj, &bl_led_group) < 0)
pr_err("failed to create sysfs group for device %s\n", bl_led_device.name);
}
bl_devdata = devdata;
setup_timer(&bl_timer, bl_timer_callback, 0);
return 0;
err_req_irq:
err_backlight_off:
<API key>(input_dev);
goto touchkey_off;
err_input_reg_dev:
err_read:
input_free_device(input_dev);
touchkey_off:
devdata->is_powering_on = false;
devdata->pdata->touchkey_onoff(TOUCHKEY_OFF);
err_input_alloc_dev:
err_null_keycodes:
kfree(devdata);
return err;
}
static int __devexit i2c_touchkey_remove(struct i2c_client *client)
{
struct <API key> *devdata = i2c_get_clientdata(client);
dev_err(&client->dev, "%s: i2c_touchkey_remove\n", __func__);
misc_deregister(&bl_led_device);
<API key>(&devdata->early_suspend);
/* If the device is dead IRQs are disabled, we need to rebalance them */
if (unlikely(devdata->is_dead))
enable_irq(client->irq);
else {
devdata->pdata->touchkey_onoff(TOUCHKEY_OFF);
devdata->is_powering_on = false;
}
free_irq(client->irq, devdata);
all_keys_up(devdata);
<API key>(devdata->input_dev);
del_timer(&bl_timer);
kfree(devdata);
return 0;
}
static const struct i2c_device_id cypress_touchkey_id[] = {
{ <API key>, 0 },
};
MODULE_DEVICE_TABLE(i2c, cypress_touchkey_id);
struct i2c_driver touchkey_i2c_driver = {
.driver = {
.name = "<API key>",
},
.id_table = cypress_touchkey_id,
.probe = <API key>,
.remove = __devexit_p(i2c_touchkey_remove),
};
static int __init touchkey_init(void)
{
int ret = 0;
ret = i2c_add_driver(&touchkey_i2c_driver);
if (ret)
pr_err("%s: cypress touch keypad registration failed. (%d)\n",
__func__, ret);
return ret;
}
static void __exit touchkey_exit(void)
{
i2c_del_driver(&touchkey_i2c_driver);
}
late_initcall(touchkey_init);
module_exit(touchkey_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("@@@");
MODULE_DESCRIPTION("cypress touch keypad"); |
package org.kde.kdeconnect.Plugins.MprisPlugin;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
import android.widget.RemoteViews;
import org.kde.kdeconnect.Device;
import org.kde.kdeconnect.Helpers.NotificationsHelper;
import org.kde.kdeconnect_tp.R;
public class NotificationPanel {
private static final int notificationId = 182144338; //Random number, fixed id to make sure we don't produce more than one notification
private String deviceId;
private String player;
private NotificationManager nManager;
private NotificationCompat.Builder nBuilder;
private RemoteViews remoteView;
public NotificationPanel(Context context, Device device, String player) {
this.deviceId = device.getDeviceId();
this.player = player;
//FIXME: When the mpris plugin gets destroyed and recreated, we should add this listener again
final MprisPlugin mpris = (MprisPlugin)device.getPlugin("plugin_mpris");
if (mpris != null) {
mpris.<API key>("notification", new Handler() {
@Override
public void handleMessage(Message msg) {
String song = mpris.getCurrentSong();
boolean isPlaying = mpris.isPlaying();
updateStatus(song, isPlaying);
}
});
}
Intent launch = new Intent(context, MprisActivity.class);
launch.putExtra("deviceId", deviceId);
launch.putExtra("player", player);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MprisActivity.class);
stackBuilder.addNextIntent(launch);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
nManager = (NotificationManager) context.getSystemService(Context.<API key>);
remoteView = new RemoteViews(context.getPackageName(), R.layout.mpris_notification);
nBuilder = new NotificationCompat.Builder(context)
.setContentTitle("KDE Connect")
.setLocalOnly(true)
.setSmallIcon(android.R.drawable.ic_media_play)
.setContentIntent(resultPendingIntent)
.setOngoing(true);
String deviceName = device.getName();
String playerOnDevice = context.getString(R.string.<API key>, player, deviceName);
remoteView.setTextViewText(R.id.notification_player, playerOnDevice);
Intent playpause = new Intent(context, <API key>.class);
playpause.putExtra("action", "play");
playpause.putExtra("deviceId", deviceId);
playpause.putExtra("player", player);
PendingIntent btn1 = PendingIntent.getBroadcast(context, NotificationsHelper.getUniqueId(), playpause, 0);
remoteView.<API key>(R.id.<API key>, btn1);
Intent next = new Intent(context, <API key>.class);
next.putExtra("action", "next");
next.putExtra("deviceId", deviceId);
next.putExtra("player", player);
PendingIntent btn2 = PendingIntent.getBroadcast(context, NotificationsHelper.getUniqueId(), next, 0);
remoteView.<API key>(R.id.notification_next, btn2);
Intent prev = new Intent(context, <API key>.class);
prev.putExtra("action", "prev");
prev.putExtra("deviceId", deviceId);
prev.putExtra("player", player);
PendingIntent btn3 = PendingIntent.getBroadcast(context, NotificationsHelper.getUniqueId(), prev, 0);
remoteView.<API key>(R.id.notification_prev, btn3);
nBuilder.setContent(remoteView);
nManager.notify(notificationId, nBuilder.build());
}
protected void updateStatus(String songName, boolean isPlaying) {
if (remoteView == null) return;
remoteView.setTextViewText(R.id.notification_song, songName);
if (isPlaying) {
remoteView.<API key>(R.id.<API key>, android.R.drawable.ic_media_pause);
} else {
remoteView.<API key>(R.id.<API key>, android.R.drawable.ic_media_play);
}
nBuilder.setContent(remoteView);
nManager.notify(notificationId, nBuilder.build());
}
public void dismiss() {
nManager.cancel(notificationId);
remoteView = null;
}
public String getPlayer() {
return player;
}
public String getDeviceId() {
return deviceId;
}
} |
#ifdef HAVE_CONFIG_H
#include <fc_config.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <gtk/gtk.h>
/* utility */
#include "log.h"
#include "mem.h"
#include "shared.h"
#include "support.h"
/* common */
#include "diptreaty.h"
#include "fcintl.h"
#include "game.h"
#include "government.h"
#include "map.h"
#include "packets.h"
#include "player.h"
#include "research.h"
/* client */
#include "chatline.h"
#include "client_main.h"
#include "climisc.h"
#include "options.h"
/* client/gui-gtk-4.0 */
#include "diplodlg.h"
#include "gui_main.h"
#include "gui_stuff.h"
#include "mapview.h"
#include "plrdlg.h"
#define MAX_NUM_CLAUSES 64
struct Diplomacy_dialog {
struct Treaty treaty;
struct gui_dialog* dialog;
GtkWidget *menu0;
GtkWidget *menu1;
GtkWidget *image0;
GtkWidget *image1;
GtkListStore *store;
};
struct Diplomacy_notebook {
struct gui_dialog* dialog;
GtkWidget *notebook;
};
#define SPECLIST_TAG dialog
#define SPECLIST_TYPE struct Diplomacy_dialog
#include "speclist.h"
#define dialog_list_iterate(dialoglist, pdialog) \
TYPED_LIST_ITERATE(struct Diplomacy_dialog, dialoglist, pdialog)
#define <API key> LIST_ITERATE_END
static struct dialog_list *dialog_list;
static struct Diplomacy_notebook *dipl_main;
static struct Diplomacy_dialog *<API key>(struct player *plr0,
struct player *plr1);
static struct Diplomacy_dialog *<API key>(int other_player_id);
static void <API key>(int other_player_id, int initiated_from);
static void <API key>(GtkWidget *w, gpointer data);
static void <API key>(GtkWidget *w, gpointer data);
static void <API key>(GtkWidget *w, gpointer data);
static void <API key>(GtkWidget *w, gpointer data);
static void <API key>(GtkWidget *w, gpointer data);
static void <API key>(GtkWidget *w, gpointer data);
static void <API key>(GtkWidget *w, gpointer data);
static void <API key>(GtkWidget *w, gpointer data);
static void <API key>(GtkWidget *w, gpointer data);
static void <API key>(struct Diplomacy_dialog *pdialog);
static void <API key>(struct Diplomacy_dialog *pdialog);
static void <API key>(GtkWidget *w, gpointer data);
static struct Diplomacy_notebook *<API key>(void);
static void <API key>(void);
static void <API key>(struct gui_dialog *dlg, int response,
gpointer data);
#define <API key> 100
#define <API key> 101
void <API key>(int counterpart, bool I_accepted,
bool other_accepted)
{
struct Diplomacy_dialog *pdialog = <API key>(counterpart);
if (!pdialog) {
return;
}
pdialog->treaty.accept0 = I_accepted;
pdialog->treaty.accept1 = other_accepted;
<API key>(pdialog);
gui_dialog_alert(pdialog->dialog);
}
void <API key>(int counterpart, int initiated_from)
{
<API key>(counterpart, initiated_from);
}
void <API key>(int counterpart, int initiated_from)
{
struct Diplomacy_dialog *pdialog = <API key>(counterpart);
if (!pdialog) {
return;
}
<API key>(pdialog);
}
void <API key>(int counterpart, int giver,
enum clause_type type, int value)
{
struct Diplomacy_dialog *pdialog = <API key>(counterpart);
if (!pdialog) {
return;
}
add_clause(&pdialog->treaty, player_by_number(giver), type, value);
<API key>(pdialog);
gui_dialog_alert(pdialog->dialog);
}
void <API key>(int counterpart, int giver,
enum clause_type type, int value)
{
struct Diplomacy_dialog *pdialog = <API key>(counterpart);
if (!pdialog) {
return;
}
remove_clause(&pdialog->treaty, player_by_number(giver), type, value);
<API key>(pdialog);
gui_dialog_alert(pdialog->dialog);
}
static void <API key>(int other_player_id, int initiated_from)
{
struct Diplomacy_dialog *pdialog = <API key>(other_player_id);
if (!<API key>()) {
return;
}
if (!is_human(client.conn.playing)) {
return; /* Don't show if we are not human controlled. */
}
if (!pdialog) {
pdialog = <API key>(client.conn.playing,
player_by_number(other_player_id));
}
gui_dialog_present(pdialog->dialog);
/* We initated the meeting - Make the tab active */
if (player_by_number(initiated_from) == client.conn.playing) {
/* we have to raise the diplomacy meeting tab as well as the selected
* meeting. */
fc_assert_ret(dipl_main != NULL);
gui_dialog_raise(dipl_main->dialog);
gui_dialog_raise(pdialog->dialog);
if (<API key> != NULL) {
<API key>(pdialog->dialog, <API key>);
}
}
}
static gint sort_advance_names(gconstpointer a, gconstpointer b)
{
const struct advance *padvance1 = (const struct advance *) a;
const struct advance *padvance2 = (const struct advance *) b;
return fc_strcoll(<API key>(padvance1),
<API key>(padvance2));
}
static void popup_add_menu(GtkMenuShell *parent, gpointer data)
{
struct Diplomacy_dialog *pdialog;
struct player *pgiver, *pother;
GtkWidget *item, *menu;
/* init. */
<API key>(GTK_CONTAINER(parent),
(GtkCallback) gtk_widget_destroy, NULL);
pdialog = (struct Diplomacy_dialog *) data;
pgiver = (struct player *) g_object_get_data(G_OBJECT(parent), "plr");
pother = (pgiver == pdialog->treaty.plr0
? pdialog->treaty.plr1 : pdialog->treaty.plr0);
/* Maps. */
menu = gtk_menu_new();
item = <API key>(_("World-map"));
<API key>(GTK_MENU_SHELL(menu),item);
g_object_set_data(G_OBJECT(item), "plr", pgiver);
g_signal_connect(item, "activate",
G_CALLBACK(<API key>), pdialog);
item = <API key>(_("Sea-map"));
<API key>(GTK_MENU_SHELL(menu), item);
g_object_set_data(G_OBJECT(item), "plr", pgiver);
g_signal_connect(item, "activate",
G_CALLBACK(<API key>), pdialog);
item = <API key>(_("_Maps"));
<API key>(GTK_MENU_ITEM(item), menu);
<API key>(GTK_MENU_SHELL(parent), item);
gtk_widget_show(item);
/* Trading: advances */
if (game.info.trading_tech) {
const struct research *gresearch = research_get(pgiver);
const struct research *oresearch = research_get(pother);
GtkWidget *advance_item;
GList *sorting_list = NULL;
advance_item = <API key>(_("_Advances"));
<API key>(GTK_MENU_SHELL(parent), advance_item);
advance_iterate(A_FIRST, padvance) {
Tech_type_id i = advance_number(padvance);
if (<API key>(gresearch, i) == TECH_KNOWN
&& <API key>(oresearch, i,
game.info.<API key>)
&& (<API key>(oresearch, i) == TECH_UNKNOWN
|| <API key>(oresearch, i)
== TECH_PREREQS_KNOWN)) {
sorting_list = g_list_prepend(sorting_list, padvance);
}
} advance_iterate_end;
if (NULL == sorting_list) {
/* No advance. */
<API key>(advance_item, FALSE);
} else {
GList *list_item;
const struct advance *padvance;
sorting_list = g_list_sort(sorting_list, sort_advance_names);
menu = gtk_menu_new();
/* TRANS: All technologies menu item in the diplomatic dialog. */
item = <API key>(_("All advances"));
<API key>(GTK_MENU_SHELL(menu), item);
g_object_set_data(G_OBJECT(item), "player_from",
GINT_TO_POINTER(player_number(pgiver)));
g_object_set_data(G_OBJECT(item), "player_to",
GINT_TO_POINTER(player_number(pother)));
g_signal_connect(item, "activate",
G_CALLBACK(<API key>),
GINT_TO_POINTER(A_LAST));
<API key>(GTK_MENU_SHELL(menu),
<API key>());
for (list_item = sorting_list; NULL != list_item;
list_item = g_list_next(list_item)) {
padvance = (const struct advance *) list_item->data;
item =
<API key>(<API key>(padvance));
<API key>(GTK_MENU_SHELL(menu), item);
g_object_set_data(G_OBJECT(item), "player_from",
GINT_TO_POINTER(player_number(pgiver)));
g_object_set_data(G_OBJECT(item), "player_to",
GINT_TO_POINTER(player_number(pother)));
g_signal_connect(item, "activate",
G_CALLBACK(<API key>),
GINT_TO_POINTER(advance_number(padvance)));
}
<API key>(GTK_MENU_ITEM(advance_item), menu);
g_list_free(sorting_list);
}
gtk_widget_show(advance_item);
}
/* Trading: cities. */
if (game.info.trading_city) {
int i = 0, j = 0, n = city_list_size(pgiver->cities);
struct city **city_list_ptrs;
if (n > 0) {
city_list_ptrs = fc_malloc(sizeof(struct city *) * n);
} else {
city_list_ptrs = NULL;
}
city_list_iterate(pgiver->cities, pcity) {
if (!is_capital(pcity)) {
city_list_ptrs[i] = pcity;
i++;
}
} <API key>;
qsort(city_list_ptrs, i, sizeof(struct city *), city_name_compare);
menu = gtk_menu_new();
for (j = 0; j < i; j++) {
item = <API key>(city_name_get(city_list_ptrs[j]));
<API key>(GTK_MENU_SHELL(menu), item);
g_signal_connect(item, "activate",
G_CALLBACK(<API key>),
GINT_TO_POINTER((player_number(pgiver) << 24) |
(player_number(pother) << 16) |
city_list_ptrs[j]->id));
}
free(city_list_ptrs);
item = <API key>(_("_Cities"));
<API key>(item, (i > 0));
<API key>(GTK_MENU_ITEM(item), menu);
<API key>(GTK_MENU_SHELL(parent), item);
gtk_widget_show(item);
}
/* Give shared vision. */
item = <API key>(_("_Give shared vision"));
g_object_set_data(G_OBJECT(item), "plr", pgiver);
g_signal_connect(item, "activate",
G_CALLBACK(<API key>), pdialog);
if (gives_shared_vision(pgiver, pother)) {
<API key>(item, FALSE);
}
<API key>(GTK_MENU_SHELL(parent), item);
gtk_widget_show(item);
/* Give embassy. */
item = <API key>(_("Give _embassy"));
g_object_set_data(G_OBJECT(item), "plr", pgiver);
g_signal_connect(item, "activate",
G_CALLBACK(<API key>), pdialog);
/* Don't take in account the embassy effects. */
if (<API key>(pother, pgiver)) {
<API key>(item, FALSE);
}
<API key>(GTK_MENU_SHELL(parent), item);
gtk_widget_show(item);
/* Pacts. */
if (pgiver == pdialog->treaty.plr0) {
enum diplstate_type ds;
ds = <API key>(pgiver, pother)->type;
menu = gtk_menu_new();
item = <API key>(Q_("?diplomatic_state:Cease-fire"));
<API key>(GTK_MENU_SHELL(menu),item);
g_signal_connect(item, "activate",
G_CALLBACK(<API key>), pdialog);
<API key>(item, ds != DS_CEASEFIRE && ds != DS_TEAM);
item = <API key>(Q_("?diplomatic_state:Peace"));
<API key>(GTK_MENU_SHELL(menu), item);
g_signal_connect(item, "activate",
G_CALLBACK(<API key>), pdialog);
<API key>(item, ds != DS_PEACE && ds != DS_TEAM);
item = <API key>(Q_("?diplomatic_state:Alliance"));
<API key>(GTK_MENU_SHELL(menu), item);
g_signal_connect(item, "activate",
G_CALLBACK(<API key>), pdialog);
<API key>(item, ds != DS_ALLIANCE && ds != DS_TEAM);
item = <API key>(_("_Pacts"));
<API key>(GTK_MENU_ITEM(item), menu);
<API key>(GTK_MENU_SHELL(parent), item);
gtk_widget_show(item);
}
}
static void row_callback(GtkTreeView *view, GtkTreePath *path,
GtkTreeViewColumn *col, gpointer data)
{
struct Diplomacy_dialog *pdialog = (struct Diplomacy_dialog *)data;
gint i;
gint *index;
index = <API key>(path);
i = 0;
clause_list_iterate(pdialog->treaty.clauses, pclause) {
if (i == index[0]) {
<API key>(&client.conn,
player_number(pdialog->treaty.plr1),
player_number(pclause->from),
pclause->type,
pclause->value);
return;
}
i++;
} <API key>;
}
static struct Diplomacy_notebook *<API key>(void)
{
/* Collect all meetings in one main tab. */
if (!dipl_main) {
GtkWidget *dipl_box, *dipl_sw;
dipl_main = fc_malloc(sizeof(*dipl_main));
gui_dialog_new(&(dipl_main->dialog), GTK_NOTEBOOK(top_notebook),
dipl_main->dialog, TRUE);
dipl_main->notebook = gtk_notebook_new();
<API key>(GTK_NOTEBOOK(dipl_main->notebook),
GTK_POS_RIGHT);
<API key>(GTK_NOTEBOOK(dipl_main->notebook), TRUE);
dipl_sw = <API key>(NULL, NULL);
g_object_set(dipl_sw, "margin", 2, NULL);
<API key>(GTK_SCROLLED_WINDOW(dipl_sw),
<API key>,
<API key>);
gtk_container_add(GTK_CONTAINER(dipl_sw), dipl_main->notebook);
/* Buttons */
<API key>(dipl_main->dialog, NULL,
_("Cancel _all meetings"),
<API key>);
/* Responces for _all_ meetings. */
<API key>(dipl_main->dialog,
<API key>);
<API key>(dipl_main->dialog,
<API key>);
dipl_box = dipl_main->dialog->vbox;
gtk_container_add(GTK_CONTAINER(dipl_box), dipl_sw);
gui_dialog_show_all(dipl_main->dialog);
gui_dialog_present(dipl_main->dialog);
}
return dipl_main;
}
static void <API key>(void)
{
if (dipl_main->dialog) {
gui_dialog_destroy(dipl_main->dialog);
}
free(dipl_main);
dipl_main = NULL;
}
static void <API key>(struct gui_dialog *dlg, int response,
gpointer data)
{
if (!dipl_main) {
return;
}
switch (response) {
default:
log_error("unhandled response in %s: %d", __FUNCTION__, response);
/* No break. */
case <API key>: /* GTK: delete the widget. */
case <API key>: /* Cancel all meetings. */
dialog_list_iterate(dialog_list, adialog) {
/* This will do a round trip to the server ans close the diolag in the
* client. Closing the last dialog will also close the main tab.*/
<API key>(&client.conn,
player_number(
adialog->treaty.plr1));
} <API key>;
break;
}
}
static void diplomacy_destroy(struct Diplomacy_dialog* pdialog)
{
if (NULL != pdialog->dialog) {
/* pdialog->dialog may be NULL if the tab have been destroyed
* by an other way. */
gui_dialog_destroy(pdialog->dialog);
}
dialog_list_remove(dialog_list, pdialog);
free(pdialog);
if (dialog_list) {
/* Diplomatic meetings in one main tab. */
if (dialog_list_size(dialog_list) > 0) {
if (dipl_main && dipl_main->dialog) {
gchar *buf;
buf = g_strdup_printf(_("Diplomacy [%d]"), dialog_list_size(dialog_list));
<API key>(dipl_main->dialog, buf);
g_free(buf);
}
} else if (dipl_main) {
/* No meeting left - destroy main tab. */
<API key>();
}
}
}
static void diplomacy_response(struct gui_dialog *dlg, int response,
gpointer data)
{
struct Diplomacy_dialog *pdialog = NULL;
fc_assert_ret(data);
pdialog = (struct Diplomacy_dialog *)data;
switch (response) {
case GTK_RESPONSE_ACCEPT: /* Accept treaty. */
<API key>(&client.conn,
player_number(
pdialog->treaty.plr1));
break;
default:
log_error("unhandled response in %s: %d", __FUNCTION__, response);
/* No break. */
case <API key>: /* GTK: delete the widget. */
case GTK_RESPONSE_CANCEL: /* GTK: cancel button. */
case <API key>: /* Cancel meetings. */
<API key>(&client.conn,
player_number(
pdialog->treaty.plr1));
break;
}
}
static struct Diplomacy_dialog *<API key>(struct player *plr0,
struct player *plr1)
{
struct Diplomacy_notebook *dipl_dialog;
GtkWidget *vbox, *hbox, *table, *mainbox;
GtkWidget *label, *sw, *view, *image, *spin;
GtkWidget *menubar, *menuitem, *menu, *notebook;
struct sprite *flag_spr;
GtkListStore *store;
GtkCellRenderer *rend;
int i;
struct Diplomacy_dialog *pdialog;
char plr_buf[4 * MAX_LEN_NAME];
gchar *buf;
pdialog = fc_malloc(sizeof(*pdialog));
dialog_list_prepend(dialog_list, pdialog);
init_treaty(&pdialog->treaty, plr0, plr1);
/* Get main diplomacy tab. */
dipl_dialog = <API key>();
buf = g_strdup_printf(_("Diplomacy [%d]"), dialog_list_size(dialog_list));
<API key>(dipl_dialog->dialog, buf);
g_free(buf);
notebook = dipl_dialog->notebook;
gui_dialog_new(&(pdialog->dialog), GTK_NOTEBOOK(notebook), pdialog, FALSE);
/* Buttons */
<API key>(pdialog->dialog, NULL,
_("Accept treaty"), GTK_RESPONSE_ACCEPT);
<API key>(pdialog->dialog, NULL,
_("Cancel meeting"), <API key>);
/* Responces for one meeting. */
<API key>(pdialog->dialog, diplomacy_response);
<API key>(pdialog->dialog, <API key>);
/* Label for the new meeting. */
buf = g_strdup_printf("%s", <API key>(plr1));
<API key>(pdialog->dialog, buf);
/* Sort meeting tabs alphabetically by the tab label. */
for (i = 0; i < <API key>(GTK_NOTEBOOK(notebook)); i++) {
GtkWidget *prev_page
= <API key>(GTK_NOTEBOOK(notebook), i);
struct gui_dialog *prev_dialog
= g_object_get_data(G_OBJECT(prev_page), "gui-dialog-data");
const char *prev_label
= gtk_label_get_text(GTK_LABEL(prev_dialog->v.tab.label));
if (fc_strcasecmp(buf, prev_label) < 0) {
<API key>(GTK_NOTEBOOK(notebook),
pdialog->dialog->vbox, i);
break;
}
}
g_free(buf);
/* Content. */
mainbox = pdialog->dialog->vbox;
vbox = gtk_grid_new();
<API key>(GTK_ORIENTABLE(vbox),
<API key>);
<API key>(GTK_GRID(vbox), 5);
<API key>(vbox, 2);
<API key>(vbox, 2);
<API key>(vbox, 2);
<API key>(vbox, 2);
gtk_container_add(GTK_CONTAINER(mainbox), vbox);
/* Our nation. */
label = gtk_label_new(NULL);
<API key>(label, GTK_ALIGN_CENTER);
<API key>(label, GTK_ALIGN_CENTER);
buf = g_strdup_printf("<span size=\"large\"><u>%s</u></span>",
<API key>(plr0));
<API key>(GTK_LABEL(label), buf);
g_free(buf);
gtk_container_add(GTK_CONTAINER(vbox), label);
hbox = gtk_grid_new();
<API key>(GTK_GRID(hbox), 5);
gtk_container_add(GTK_CONTAINER(vbox), hbox);
/* Our flag */
flag_spr = <API key>(tileset, nation_of_player(plr0));
image = <API key>(flag_spr->surface);
gtk_container_add(GTK_CONTAINER(hbox), image);
/* Our name. */
label = gtk_label_new(NULL);
<API key>(label, TRUE);
<API key>(label, GTK_ALIGN_CENTER);
<API key>(label, GTK_ALIGN_CENTER);
buf = g_strdup_printf("<span size=\"large\" weight=\"bold\">%s</span>",
<API key>(plr0, plr_buf, sizeof(plr_buf)));
<API key>(GTK_LABEL(label), buf);
g_free(buf);
gtk_container_add(GTK_CONTAINER(hbox), label);
image = gtk_image_new();
pdialog->image0 = image;
gtk_container_add(GTK_CONTAINER(hbox), image);
/* Menu for clauses: we. */
menubar = <API key>();
menu = gtk_menu_new();
pdialog->menu0 = menu;
menuitem = <API key>(_("Add Clause..."));
<API key>(GTK_MENU_ITEM(menuitem), menu);
<API key>(GTK_MENU_SHELL(menubar), menuitem);
g_object_set_data(G_OBJECT(menu), "plr", plr0);
g_signal_connect(menu, "show", G_CALLBACK(popup_add_menu), pdialog);
/* Main table for clauses and (if activated) gold trading: we. */
table = gtk_grid_new();
<API key>(table, GTK_ALIGN_CENTER);
<API key>(table, GTK_ALIGN_CENTER);
<API key>(GTK_GRID(table), 16);
gtk_container_add(GTK_CONTAINER(vbox), table);
if (game.info.trading_gold) {
spin = <API key>(0.0, plr0->economic.gold + 0.1,
1.0);
<API key>(GTK_SPIN_BUTTON(spin), 0);
<API key>(GTK_ENTRY(spin), 16);
gtk_grid_attach(GTK_GRID(table), spin, 1, 0, 1, 1);
g_object_set_data(G_OBJECT(spin), "plr", plr0);
<API key>(spin, "value-changed",
G_CALLBACK(<API key>), pdialog);
label = g_object_new(GTK_TYPE_LABEL, "use-underline", TRUE,
"mnemonic-widget", spin, "label", _("Gold:"),
"xalign", 0.0, "yalign", 0.5, NULL);
gtk_grid_attach(GTK_GRID(table), label, 0, 0, 1, 1);
gtk_grid_attach(GTK_GRID(table), menubar, 2, 0, 1, 1);
} else {
gtk_grid_attach(GTK_GRID(table), menubar, 0, 0, 1, 1);
}
/* them. */
vbox = gtk_grid_new();
<API key>(GTK_ORIENTABLE(vbox),
<API key>);
<API key>(GTK_GRID(vbox), 5);
<API key>(vbox, 2);
<API key>(vbox, 2);
<API key>(vbox, 2);
<API key>(vbox, 2);
gtk_container_add(GTK_CONTAINER(mainbox), vbox);
/* Their nation. */
label = gtk_label_new(NULL);
<API key>(label, GTK_ALIGN_CENTER);
<API key>(label, GTK_ALIGN_CENTER);
buf = g_strdup_printf("<span size=\"large\"><u>%s</u></span>",
<API key>(plr1));
<API key>(GTK_LABEL(label), buf);
g_free(buf);
gtk_container_add(GTK_CONTAINER(vbox), label);
hbox = gtk_grid_new();
<API key>(GTK_GRID(hbox), 5);
gtk_container_add(GTK_CONTAINER(vbox), hbox);
/* Their flag */
flag_spr = <API key>(tileset, nation_of_player(plr1));
image = <API key>(flag_spr->surface);
gtk_container_add(GTK_CONTAINER(hbox), image);
/* Their name. */
label = gtk_label_new(NULL);
<API key>(label, TRUE);
<API key>(label, GTK_ALIGN_CENTER);
<API key>(label, GTK_ALIGN_CENTER);
buf = g_strdup_printf("<span size=\"large\" weight=\"bold\">%s</span>",
<API key>(plr1, plr_buf, sizeof(plr_buf)));
<API key>(GTK_LABEL(label), buf);
g_free(buf);
gtk_container_add(GTK_CONTAINER(hbox), label);
image = gtk_image_new();
pdialog->image1 = image;
gtk_container_add(GTK_CONTAINER(hbox), image);
/* Menu for clauses: they. */
menubar = <API key>();
menu = gtk_menu_new();
pdialog->menu1 = menu;
menuitem = <API key>(_("Add Clause..."));
<API key>(GTK_MENU_ITEM(menuitem), menu);
<API key>(GTK_MENU_SHELL(menubar), menuitem);
g_object_set_data(G_OBJECT(menu), "plr", plr1);
g_signal_connect(menu, "show", G_CALLBACK(popup_add_menu), pdialog);
/* Main table for clauses and (if activated) gold trading: they. */
table = gtk_grid_new();
<API key>(table, GTK_ALIGN_CENTER);
<API key>(table, GTK_ALIGN_CENTER);
<API key>(GTK_GRID(table), 16);
gtk_container_add(GTK_CONTAINER(vbox), table);
if (game.info.trading_gold) {
spin = <API key>(0.0, plr1->economic.gold + 0.1,
1.0);
<API key>(GTK_SPIN_BUTTON(spin), 0);
<API key>(GTK_ENTRY(spin), 16);
gtk_grid_attach(GTK_GRID(table), spin, 1, 0, 1, 1);
g_object_set_data(G_OBJECT(spin), "plr", plr1);
<API key>(spin, "value-changed",
G_CALLBACK(<API key>), pdialog);
label = g_object_new(GTK_TYPE_LABEL, "use-underline", TRUE,
"mnemonic-widget", spin, "label", _("Gold:"),
"xalign", 0.0, "yalign", 0.5, NULL);
gtk_grid_attach(GTK_GRID(table), label, 0, 0, 1, 1);
gtk_grid_attach(GTK_GRID(table), menubar, 2, 0, 1, 1);
} else {
gtk_grid_attach(GTK_GRID(table), menubar, 0, 0, 1, 1);
}
/* Clauses. */
mainbox = gtk_grid_new();
<API key>(GTK_ORIENTABLE(mainbox),
<API key>);
gtk_container_add(GTK_CONTAINER(pdialog->dialog->vbox), mainbox);
store = gtk_list_store_new(1, G_TYPE_STRING);
pdialog->store = store;
view = <API key>(GTK_TREE_MODEL(store));
<API key>(view, TRUE);
<API key>(view, TRUE);
<API key>(GTK_TREE_VIEW(view), FALSE);
g_object_unref(store);
<API key>(view, 320, 100);
rend = <API key>();
<API key>(GTK_TREE_VIEW(view), -1, NULL,
rend, "text", 0, NULL);
sw = <API key>(NULL, NULL);
g_object_set(sw, "margin", 2, NULL);
<API key>(GTK_SCROLLED_WINDOW(sw),
<API key>);
<API key>(GTK_SCROLLED_WINDOW(sw),
GTK_POLICY_NEVER, <API key>);
gtk_container_add(GTK_CONTAINER(sw), view);
label = g_object_new(GTK_TYPE_LABEL,
"use-underline", TRUE,
"mnemonic-widget", view,
"label", _("C_lauses:"),
"xalign", 0.0,
"yalign", 0.5,
NULL);
vbox = gtk_grid_new();
<API key>(GTK_ORIENTABLE(vbox),
<API key>);
gtk_container_add(GTK_CONTAINER(mainbox), vbox);
gtk_container_add(GTK_CONTAINER(vbox), label);
gtk_container_add(GTK_CONTAINER(vbox), sw);
gtk_widget_show(mainbox);
g_signal_connect(view, "row_activated", G_CALLBACK(row_callback), pdialog);
<API key>(pdialog);
gui_dialog_show_all(pdialog->dialog);
return pdialog;
}
static void <API key>(struct Diplomacy_dialog *pdialog)
{
GtkListStore *store;
GtkTreeIter it;
bool blank = TRUE;
GdkPixbuf *pixbuf;
store = pdialog->store;
<API key>(store);
clause_list_iterate(pdialog->treaty.clauses, pclause) {
char buf[128];
<API key>(buf, sizeof(buf), pclause);
<API key>(store, &it);
gtk_list_store_set(store, &it, 0, buf, -1);
blank = FALSE;
} <API key>;
if (blank) {
<API key>(store, &it);
gtk_list_store_set(store, &it, 0,
_("--- This treaty is blank. "
"Please add some clauses.
}
pixbuf = get_thumb_pixbuf(pdialog->treaty.accept0);
<API key>(GTK_IMAGE(pdialog->image0), pixbuf);
g_object_unref(G_OBJECT(pixbuf));
pixbuf = get_thumb_pixbuf(pdialog->treaty.accept1);
<API key>(GTK_IMAGE(pdialog->image1), pixbuf);
g_object_unref(G_OBJECT(pixbuf));
}
static void <API key>(GtkWidget *w, gpointer data)
{
int giver, dest, other, tech;
giver = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(w), "player_from"));
dest = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(w), "player_to"));
tech = GPOINTER_TO_INT(data);
if (player_by_number(giver) == client_player()) {
other = dest;
} else {
other = giver;
}
if (A_LAST == tech) {
/* All techs. */
struct player *pgiver = player_by_number(giver);
struct player *pdest = player_by_number(dest);
const struct research *dresearch, *gresearch;
fc_assert_ret(NULL != pgiver);
fc_assert_ret(NULL != pdest);
dresearch = research_get(pdest);
gresearch = research_get(pgiver);
advance_iterate(A_FIRST, padvance) {
Tech_type_id i = advance_number(padvance);
if (<API key>(gresearch, i) == TECH_KNOWN
&& <API key>(dresearch, i,
game.info.<API key>)
&& (<API key>(dresearch, i) == TECH_UNKNOWN
|| <API key>(dresearch, i)
== TECH_PREREQS_KNOWN)) {
<API key>(&client.conn, other, giver,
CLAUSE_ADVANCE, i);
}
} advance_iterate_end;
} else {
/* Only one tech. */
<API key>(&client.conn, other, giver,
CLAUSE_ADVANCE, tech);
}
}
static void <API key>(GtkWidget * w, gpointer data)
{
size_t choice = GPOINTER_TO_UINT(data);
int giver = (choice >> 24) & 0xff, dest = (choice >> 16) & 0xff, other;
int city = choice & 0xffff;
if (player_by_number(giver) == client.conn.playing) {
other = dest;
} else {
other = giver;
}
<API key>(&client.conn, other, giver,
CLAUSE_CITY, city);
}
static void <API key>(GtkWidget *w, gpointer data)
{
struct Diplomacy_dialog *pdialog = (struct Diplomacy_dialog *)data;
struct player *pgiver;
pgiver = (struct player *)g_object_get_data(G_OBJECT(w), "plr");
<API key>(&client.conn,
player_number(pdialog->treaty.plr1),
player_number(pgiver), CLAUSE_MAP, 0);
}
static void <API key>(GtkWidget *w, gpointer data)
{
struct Diplomacy_dialog *pdialog = (struct Diplomacy_dialog *)data;
struct player *pgiver;
pgiver = (struct player *)g_object_get_data(G_OBJECT(w), "plr");
<API key>(&client.conn,
player_number(pdialog->treaty.plr1),
player_number(pgiver), CLAUSE_SEAMAP,
0);
}
static void <API key>(GtkWidget *w, gpointer data,
int type)
{
struct Diplomacy_dialog *pdialog = (struct Diplomacy_dialog *)data;
<API key>(&client.conn,
player_number(pdialog->treaty.plr1),
player_number(pdialog->treaty.plr0),
type, 0);
}
static void <API key>(GtkWidget *w, gpointer data)
{
<API key>(w, data, CLAUSE_CEASEFIRE);
}
static void <API key>(GtkWidget *w, gpointer data)
{
<API key>(w, data, CLAUSE_PEACE);
}
static void <API key>(GtkWidget *w, gpointer data)
{
<API key>(w, data, CLAUSE_ALLIANCE);
}
static void <API key>(GtkWidget *w, gpointer data)
{
struct Diplomacy_dialog *pdialog = (struct Diplomacy_dialog *) data;
struct player *pgiver =
(struct player *) g_object_get_data(G_OBJECT(w), "plr");
<API key>(&client.conn,
player_number(pdialog->treaty.plr1),
player_number(pgiver), CLAUSE_VISION,
0);
}
static void <API key>(GtkWidget *w, gpointer data)
{
struct Diplomacy_dialog *pdialog = (struct Diplomacy_dialog *) data;
struct player *pgiver =
(struct player *) g_object_get_data(G_OBJECT(w), "plr");
<API key>(&client.conn,
player_number(pdialog->treaty.plr1),
player_number(pgiver), CLAUSE_EMBASSY,
0);
}
void <API key>(struct Diplomacy_dialog *pdialog)
{
diplomacy_destroy(pdialog);
}
void <API key>()
{
dialog_list = dialog_list_new();
dipl_main = NULL;
}
void <API key>()
{
dialog_list_destroy(dialog_list);
}
static struct Diplomacy_dialog *<API key>(int other_player_id)
{
struct player *plr0 = client.conn.playing;
struct player *plr1 = player_by_number(other_player_id);
dialog_list_iterate(dialog_list, pdialog) {
if ((pdialog->treaty.plr0 == plr0 && pdialog->treaty.plr1 == plr1) ||
(pdialog->treaty.plr0 == plr1 && pdialog->treaty.plr1 == plr0)) {
return pdialog;
}
} <API key>;
return NULL;
}
static void <API key>(GtkWidget *w, gpointer data)
{
struct Diplomacy_dialog *pdialog = (struct Diplomacy_dialog *) data;
struct player *pgiver =
(struct player *) g_object_get_data(G_OBJECT(w), "plr");
int amount = <API key>(GTK_SPIN_BUTTON(w));
if (amount >= 0 && amount <= pgiver->economic.gold) {
<API key>(&client.conn,
player_number(pdialog->treaty.plr1),
player_number(pgiver),
CLAUSE_GOLD, amount);
} else {
<API key>(ftc_client, _("Invalid amount of gold specified."));
}
}
void <API key>(void)
{
while (dialog_list_size(dialog_list) > 0) {
<API key>(dialog_list_get(dialog_list, 0));
}
} |
program testchi
c Testchi provides an interactive interface to the code that calculates
c the chi**2 of a given SFH model. The user may change the parameters
c of the fit at runtime and see the effect of the changes on the chi**2
c
c Jason Harris, Revised May 24, 2000
c
include '../sfhcode/sfh.h'
character*40 datpre,maskfile,datfile(MCMD)
character*40 ampfile
double precision x(MP),y
integer i,j,ntry
real dat(MCMD,2,NDATA),chem(MP),age(MP)
integer fstat,gtype
integer nstars(MCMD),pnum(MP),mask(MCMD,MBOX)
character*40 cmdfile,chifile
common /cstat/ dat,cmdfile,chifile,nstars,mask,
x chem,age,pnum,fstat,gtype
double precision psynth(MCMD,MP,MBOX)
double precision pdat(MCMD,MBOX),pmod(MCMD,MBOX)
common /cfit/ psynth, pmod, pdat
character*8 suffix(MCMD)
integer npix, ncmd, nbox(MCMD)
real xlo(MCMD), xhi(MCMD), ylo(MCMD), yhi(MCMD), dpix
common /cmds/ suffix, xlo, xhi, ylo, yhi, nbox, dpix, npix, ncmd
integer niso,nheld,ihold(MP)
double precision pheld(MP)
common /hold/ pheld,ihold,niso,nheld
integer np
common /cnp/ np
integer iverb
common /verb/ iverb
c *** Filenames ***
call fetchchar40( 5, datpre )
call fetchchar40( 5, cmdfile )
call fetchchar40( 5, maskfile )
call fetchchar40( 5, ampfile )
call fetchchar40( 5, chifile )
c *** Synthetic CMD parameters ***
call fetchint( 5, niso )
call fetchint( 5, ncmd )
call fetchint( 5, npix )
call fetchreal( 5, dpix )
do icmd=1,ncmd
call fetchchar8( 5, suffix(icmd) )
call fetchreal( 5, xlo(icmd) )
call fetchreal( 5, xhi(icmd) )
call fetchreal( 5, ylo(icmd) )
call fetchreal( 5, yhi(icmd) )
call fetchint( 5, nbox(icmd) )
end do
c *** Runtime parameters ***
call fetchint( 5, fstat )
call fetchint( 5, gtype )
call fetchint( 5, iverb )
do icmd=1,ncmd
nstars(icmd) = 0
do ibox=1,nbox(icmd)
pmod(icmd,ibox) = 0.0D0
pdat(icmd,ibox) = 0.0D0
end do
end do
c Set CMD grid mask
call oldfile(44,maskfile)
108 read(44,*,end=109) i,j,mask(i,j)
goto 108
109 close(44)
c fitstat expects the hold arrays, but we don't need them
c for this program, so just fill null arrays.
do i=1,niso
ihold(i) = 0
pheld(i) = 0.0
end do
nheld = 0
c np is the number of independent, variable amplitudes
np = niso
c *** Read in input photometry:
c *** dat(icmd,1,i) = color; dat(icmd,2,i) = magnitude
do icmd=1,ncmd
call strcat(datpre, suffix(icmd), datfile(icmd))
if (iverb.gt.0) write(*,*) 'Reading ', datfile(icmd)
call oldfile(2,datfile(icmd))
do i=1,NDATA
read(2,*,end=10) dat(icmd,1,i),dat(icmd,2,i)
end do
10 close(2)
nstars(icmd) = i - 1
end do
c Read in SFH amplitudes
call oldfile(24,ampfile)
do i=1,np
read(24,*) rjunk, rjunk, x(i)
if ( ihold(i).eq.1 ) then
x(i) = pheld(i)
endif
end do
close(24)
C Compute the fitting statistic for the model:
call fitstat( x, y, 1 ) ! 1 = write chifile
if ( fstat.eq.0 ) then
write(*,*) 'chi**2 of model: ', y
else if ( fstat.eq.1 ) then
write(*,*) 'Lorentzian stat. of model: ', y
else if ( fstat.eq.2 ) then
write(*,*) 'Poisson stat. of model: ', y
endif
stop
end |
import logging
from threading import RLock
from struct import unpack
class ReadBuffer(object):
"""This class receives incoming data, and stores it in a list of extents
(also referred to as buffers). It allows us to leisurely pop off sequences
of bytes, which we build from the unconsumed extents. As the extents are
depleted, we maintain an index to the first available, non-empty extent.
We will only occasionally cleanup.
"""
__locker = RLock()
# TODO: Reduce this for testing.
__cleanup_interval = 100
def __init__(self):
self.__log = logging.getLogger(self.__class__.__name__)
self.__buffers = []
self.__length = 0
self.__read_buffer_index = 0
self.__hits = 0
def push(self, data):
with self.__class__.__locker:
self.__buffers.append(data)
self.__length += len(data)
def read_message(self):
"""Try to read a message from the buffered data. A message is defined
as a 32-bit integer size, followed that number of bytes. First we try
to non-destructively read the integer. Then, we try to non-
destructively read the remaining bytes. If both are successful, we then
go back to remove the span from the front of the buffers.
"""
with self.__class__.__locker:
result = self.__passive_read(4)
if result is None:
return None
(four_bytes, last_buffer_index, updates1) = result
(length,) = unpack('>I', four_bytes)
result = self.__passive_read(length, last_buffer_index)
if result is None:
return None
(data, last_buffer_index, updates2) = result
# If we get here, we found a message. Remove it from the buffers.
for updates in (updates1, updates2):
for update in updates:
(buffer_index, buffer_, length_consumed) = update
self.__buffers[buffer_index] = buffer_ if buffer_ else ''
self.__length -= length_consumed
self.__read_buffer_index = last_buffer_index
self.__hits += 1
if self.__hits >= self.__class__.__cleanup_interval:
self.__cleanup()
self.__hits = 0
return data
def __passive_read(self, length, start_buffer_index=None):
"""Read the given length of bytes, or return None if we can't provide
[all of] them yet. When the given length is available but ends in the
middle of a buffer, we'll split the buffer. We do this to make it
simpler to continue from that point next time (it's always simpler to
start at the beginning of a buffer), as well as simpler to remove the
found bytes later, if need be.
"""
if length > self.__length:
return None
with self.__class__.__locker:
collected = []
need_bytes = length
i = start_buffer_index if start_buffer_index is not None \
else self.__read_buffer_index
updates = []
while need_bytes > 0:
len_current_buffer = len(self.__buffers[i])
if need_bytes >= len_current_buffer:
# We need at least as many bytes as are in the current
# buffer. Consume them all.
collected.append(self.__buffers[i][:])
updates.append((i, [], len_current_buffer))
need_bytes -= len_current_buffer
else:
# We need less bytes than are in the current buffer. Slice
# the current buffer in half, even if the data isn't going
# anywhere [yet].
first_half = self.__buffers[i][:need_bytes]
second_half = self.__buffers[i][need_bytes:]
self.__buffers[i] = first_half
self.__buffers.insert(i + 1, second_half)
# We only mark the buffer that came from the first half as
# having an update (the second half of the buffer wasn't
# touched).
collected.append(first_half)
updates.append((i, [], need_bytes))
need_bytes = 0
i += 1
sequence = ''.join(collected)
return (sequence, i, updates)
def __cleanup(self):
"""Clip buffers that the top of our list that have been completely
exhausted.
"""
# TODO: Test this.
with self.__class__.__locker:
while self.__read_buffer_index > 0:
del self.__buffers[0]
self.__read_buffer_index -= 1 |
/* data dump of edit-datetime-16.png */
static const unsigned char <API key>[882] = {
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x10, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0xf3, 0xff,
0x61, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0b, 0x13, 0x00, 0x00, 0x0b,
0x13, 0x01, 0x00, 0x9a, 0x9c, 0x18, 0x00, 0x00, 0x00, 0x04, 0x67, 0x41, 0x4d, 0x41, 0x00, 0x00,
0xb1, 0x8e, 0x7c, 0xfb, 0x51, 0x93, 0x00, 0x00, 0x00, 0x20, 0x63, 0x48, 0x52, 0x4d, 0x00, 0x00,
0x7a, 0x25, 0x00, 0x00, 0x80, 0x83, 0x00, 0x00, 0xf9, 0xff, 0x00, 0x00, 0x80, 0xe9, 0x00, 0x00,
0x75, 0x30, 0x00, 0x00, 0xea, 0x60, 0x00, 0x00, 0x3a, 0x98, 0x00, 0x00, 0x17, 0x6f, 0x92, 0x5f,
0xc5, 0x46, 0x00, 0x00, 0x02, 0xe8, 0x49, 0x44, 0x41, 0x54, 0x78, 0xda, 0x6c, 0x93, 0x4d, 0x68,
0x1c, 0x05, 0x14, 0xc7, 0x7f, 0xf3, 0xb1, 0xbb, 0xd9, 0x4e, 0xd3, 0xb0, 0x1b, 0xb3, 0xc9, 0xda,
0x2d, 0x2d, 0x89, 0x9b, 0x1a, 0x0d, 0x22, 0x9a, 0x83, 0xa0, 0x10, 0xd8, 0xb2, 0x37, 0x0f, 0x42,
0x11, 0x54, 0xc4, 0x83, 0x5e, 0x84, 0xc6, 0x4b, 0x8f, 0x5e, 0x0c, 0x08, 0x11, 0x04, 0xa1, 0xe4,
0xe6, 0x07, 0x55, 0xf1, 0xa4, 0x92, 0xda, 0xa2, 0x9e, 0x52, 0x2a, 0x04, 0xb5, 0xa1, 0x46, 0xa3,
0x6d, 0x41, 0xb2, 0xa4, 0xdb, 0x74, 0xb7, 0xb5, 0x25, 0x4d, 0x86, 0xdd, 0xd9, 0x99, 0xd9, 0xf9,
0xd8, 0x99, 0xe7, 0x61, 0xc8, 0x80, 0xe0, 0xbb, 0xbd, 0xf7, 0xe0, 0xf7, 0xfe, 0xfc, 0xdf, 0x7b,
0x9a, 0x88, 0xb0, 0xfe, 0xcb, 0xaf, 0x4c, 0x1f, 0x2d, 0x73, 0xbc, 0x34, 0xc6, 0xb5, 0xbf, 0x6e,
0xac, 0x9c, 0xaa, 0xd5, 0x5a, 0xed, 0x9b, 0xd7, 0xef, 0x3e, 0x39, 0x3d, 0xc5, 0xf1, 0xf1, 0x31,
0x5e, 0x79, 0xfd, 0x0d, 0x7e, 0x5a, 0x5b, 0xdb, 0x38, 0x94, 0xcd, 0x7d, 0x26, 0xbd, 0xae, 0xcc,
0x54, 0x1f, 0x63, 0xb2, 0x7a, 0x92, 0xed, 0x5b, 0xb7, 0x50, 0x01, 0x74, 0x20, 0x13, 0x87, 0x5a,
0x9e, 0x01, 0x6b, 0x3f, 0x5e, 0x7a, 0xf6, 0xe2, 0xe7, 0x9f, 0x9c, 0xca, 0x4b, 0x40, 0x2e, 0xf4,
0x18, 0x8a, 0x7d, 0xfe, 0xb9, 0xfe, 0x5b, 0xe5, 0xdb, 0x2f, 0xcf, 0x4f, 0xfd, 0x7e, 0xf9, 0x87,
0x67, 0x72, 0x71, 0x88, 0x1e, 0x85, 0x59, 0x0d, 0x01, 0x40, 0x11, 0x11, 0x66, 0x2a, 0xe3, 0x67,
0x95, 0x37, 0x3f, 0xfc, 0xe8, 0xef, 0x4e, 0xc8, 0x69, 0xb6, 0x09, 0x87, 0x4b, 0x7c, 0x6f, 0xe5,
0x29, 0xe8, 0x0a, 0x88, 0x82, 0x13, 0x06, 0x9c, 0xc9, 0xb7, 0xb8, 0x92, 0x99, 0xe4, 0x4f, 0x57,
0xe7, 0xe9, 0x11, 0x8d, 0xdc, 0xd7, 0x4b, 0x6f, 0xaf, 0x6f, 0x6d, 0x7f, 0xac, 0x03, 0x44, 0xae,
0x3d, 0xdd, 0x99, 0x9e, 0x07, 0xc5, 0x60, 0xe3, 0xe7, 0xf3, 0xf4, 0x8c, 0x93, 0x48, 0xf5, 0x29,
0x4c, 0xd7, 0x61, 0x7c, 0xf4, 0x30, 0x7e, 0xc7, 0x66, 0xe5, 0xea, 0x57, 0x44, 0xf3, 0x2f, 0x40,
0xbe, 0x8c, 0x19, 0xee, 0x51, 0xf2, 0xec, 0x13, 0x07, 0xea, 0xf1, 0x7d, 0xdf, 0xd3, 0x6d, 0x93,
0x57, 0x67, 0x0c, 0x0a, 0xa7, 0x5f, 0xe6, 0x41, 0x7f, 0x00, 0x9a, 0xcf, 0x85, 0x6b, 0xbb, 0x4c,
0x3e, 0x22, 0x1c, 0x1b, 0x51, 0xd9, 0x78, 0x74, 0x9e, 0x19, 0x0d, 0x9e, 0x3b, 0xd4, 0xe7, 0x5e,
0xcb, 0xa4, 0xef, 0x3a, 0x41, 0x0a, 0x08, 0xa3, 0x98, 0x7e, 0x1c, 0xd3, 0xec, 0xb8, 0x8c, 0xe9,
0xf0, 0x60, 0x90, 0x61, 0xa3, 0x69, 0x42, 0x56, 0x65, 0xdf, 0x17, 0x2c, 0x54, 0x38, 0x5a, 0xa6,
0x3b, 0x10, 0x9a, 0xbb, 0x2e, 0x05, 0x11, 0xfc, 0x41, 0x94, 0x98, 0x20, 0x22, 0x64, 0xe1, 0x9c,
0x13, 0xc6, 0x72, 0x10, 0x8d, 0xf6, 0x5d, 0xd9, 0xb7, 0xec, 0x34, 0xff, 0xe3, 0xc6, 0x4d, 0x69,
0xb5, 0xda, 0x69, 0xfe, 0xb0, 0x63, 0xc9, 0xb0, 0xae, 0x2d, 0x8a, 0x48, 0x02, 0x00, 0xce, 0x89,
0x24, 0x80, 0xbd, 0xf6, 0x8e, 0x00, 0x72, 0xf9, 0xd2, 0x8a, 0x88, 0x88, 0xbc, 0xf6, 0xd2, 0x8b,
0x32, 0x71, 0xc4, 0x90, 0xd1, 0x7c, 0x46, 0xbe, 0xf9, 0xe2, 0x53, 0x11, 0x11, 0x89, 0xed, 0x9e,
0xa8, 0x28, 0x8b, 0x22, 0x92, 0xac, 0x31, 0x91, 0xa2, 0xd0, 0x68, 0x6c, 0x71, 0xe2, 0xf1, 0x27,
0x00, 0xb0, 0xe3, 0xa4, 0xb5, 0x6b, 0x7b, 0xdc, 0xef, 0xda, 0xbc, 0xfb, 0xfe, 0x07, 0xbc, 0xf5,
0xce, 0x59, 0x00, 0x1e, 0xda, 0x0e, 0x31, 0xc9, 0xe4, 0x14, 0x60, 0xf5, 0x2c, 0x0a, 0x85, 0x22,
0xcd, 0xdb, 0x3b, 0x14, 0x8b, 0x45, 0xac, 0x5e, 0x0f, 0x80, 0xd5, 0xd5, 0x55, 0x00, 0xde, 0x5b,
0x5c, 0x64, 0x61, 0x61, 0x01, 0x80, 0xfd, 0x3d, 0x13, 0x60, 0x90, 0x9a, 0x08, 0xe0, 0x38, 0x0e,
0x13, 0x13, 0x13, 0x28, 0x8a, 0x82, 0x6d, 0xdb, 0x84, 0x61, 0x98, 0x80, 0x2d, 0x8b, 0xd9, 0xd9,
0x59, 0xea, 0xf5, 0x3a, 0x4b, 0x4b, 0x4b, 0x09, 0xc0, 0xdc, 0x07, 0x08, 0xfe, 0xa3, 0xc0, 0xf3,
0x3c, 0xba, 0xdd, 0x2e, 0x8e, 0xe3, 0x10, 0x04, 0x01, 0xae, 0xeb, 0x02, 0x30, 0x37, 0x37, 0x47,
0xbb, 0xdd, 0xa6, 0x5e, 0xaf, 0xb3, 0xbe, 0x7e, 0x15, 0x11, 0x21, 0x0a, 0xa3, 0x54, 0x41, 0x0a,
0x18, 0x44, 0x03, 0x7c, 0xdf, 0xc7, 0x75, 0x5d, 0xea, 0xf5, 0x3a, 0x95, 0x4a, 0x85, 0x66, 0xb3,
0x89, 0x61, 0x18, 0xd4, 0x6a, 0x35, 0x6e, 0xdf, 0xd9, 0xa1, 0x52, 0x39, 0x46, 0x63, 0xab, 0xc1,
0x54, 0xb5, 0x0a, 0x24, 0xb7, 0xac, 0x03, 0x68, 0xaa, 0xaa, 0x0e, 0x1b, 0xc3, 0xe4, 0x72, 0x43,
0xf8, 0xbe, 0xc7, 0x85, 0xef, 0x2e, 0x12, 0x04, 0x1e, 0x81, 0x1f, 0xb0, 0xb9, 0xb9, 0x99, 0xfa,
0xdc, 0xba, 0xd3, 0xa6, 0x5c, 0xae, 0x70, 0x64, 0xc4, 0x40, 0x01, 0x2d, 0x05, 0xe4, 0x87, 0x86,
0xb4, 0xe5, 0xe5, 0x65, 0x4c, 0xd3, 0x44, 0x53, 0x14, 0x32, 0xd9, 0x1c, 0x7a, 0x46, 0x47, 0x53,
0x75, 0xb2, 0xb9, 0x0c, 0x71, 0x14, 0xd3, 0xef, 0x7b, 0x14, 0x8b, 0xa3, 0x94, 0x4a, 0x25, 0xb2,
0x59, 0x1d, 0x3d, 0x93, 0xc9, 0xa7, 0xcf, 0xa4, 0x28, 0xca, 0x24, 0xf0, 0x3c, 0xe0, 0x00, 0x31,
0xff, 0x1f, 0x07, 0x75, 0x0d, 0x38, 0x0c, 0x5c, 0x11, 0x91, 0x7b, 0xff, 0x0e, 0x00, 0x33, 0xfc,
0x88, 0x9d, 0xa6, 0xda, 0x71, 0x34, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42,
0x60, 0x82
}; |
package freenet.store;
public interface StorableBlock {
byte[] getRoutingKey();
byte[] getFullKey();
} |
#ifndef __RTL8192C_CMD_H_
#define __RTL8192C_CMD_H_
enum cmd_msg_element_id
{
NONE_CMDMSG_EID,
AP_OFFLOAD_EID=0,
SET_PWRMODE_EID=1,
JOINBSS_RPT_EID=2,
RSVD_PAGE_EID=3,
RSSI_4_EID = 4,
RSSI_SETTING_EID=5,
MACID_CONFIG_EID=6,
MACID_PS_MODE_EID=7,
P2P_PS_OFFLOAD_EID=8,
<API key>=9,
H2C_WO_WLAN_CMD = 26, // Wake on Wlan.
<API key> = 27, // support macid to 64
MACID64_CONFIG_EID = 28, // support macid to 64
P2P_PS_CTW_CMD_EID=32,
H2C_92C_IO_OFFLOAD=44,
<API key>=48,
<API key>=49,
<API key>=60,
H2C_92C_CMD_MAX};
struct cmd_msg_parm {
u8 eid; //element id
u8 sz;
u8 buf[6];
};
enum evt_msg_element_id
{
EVT_DBG_EID=0,
EVT_TSF_EID=1,
EVT_AP_RPT_RSP_EID=2,
EVT_CCX_TXRPT_EID=3,
EVT_BT_RSSI_EID=4,
EVT_BT_OPMODE_EID=5,
EVT_EXT_RA_RPT_EID=6,
EVT_BT_TYPE_RPT_EID=7,
<API key>=8,
EVT_PSD_CONTROL_EID=9,
<API key>=10,
<API key>=11,
EVT_BT_INTO_EID=12,
EVT_BT_RPT_EID=13,
H2C_92C_EVT_MAX};
typedef struct _SETPWRMODE_PARM{
u8 Mode;
u8 SmartPS;
u8 BcnPassTime; // unit: 100ms
}SETPWRMODE_PARM, *PSETPWRMODE_PARM;
typedef struct _SETWOWLAN_PARM{
u8 mode;
u8 gpio_index;
u8 gpio_duration;
u8 second_mode;
u8 reserve;
}SETWOWLAN_PARM, *PSETWOWLAN_PARM;
#define FW_WOWLAN_FUN_EN BIT(0)
#define <API key> BIT(1)
#define FW_WOWLAN_MAGIC_PKT BIT(2)
#define FW_WOWLAN_UNICAST BIT(3)
#define <API key> BIT(4)
#define <API key> BIT(5)
#define <API key> BIT(6)
#define <API key> BIT(7)
#define <API key> BIT(0)
#define <API key> BIT(1)
struct H2C_SS_RFOFF_PARAM{
u8 ROFOn; // 1: on, 0:off
u16 gpio_period; // unit: 1024 us
}__attribute__ ((packed));
typedef struct JOINBSSRPT_PARM{
u8 OpMode; // RT_MEDIA_STATUS
}JOINBSSRPT_PARM, *PJOINBSSRPT_PARM;
typedef struct _RSVDPAGE_LOC{
u8 LocProbeRsp;
u8 LocPsPoll;
u8 LocNullData;
}RSVDPAGE_LOC, *PRSVDPAGE_LOC;
struct P2P_PS_Offload_t {
unsigned char Offload_En:1;
unsigned char role:1; // 1: Owner, 0: Client
unsigned char CTWindow_En:1;
unsigned char NoA0_En:1;
unsigned char NoA1_En:1;
unsigned char AllStaSleep:1; // Only valid in Owner
unsigned char discovery:1;
unsigned char rsvd:1;
};
struct P2P_PS_CTWPeriod_t {
unsigned char CTWPeriod;
};
// host message to firmware cmd
void <API key>(_adapter*padapter, u8 Mode);
void <API key>(_adapter* padapter, u8 mstatus);
u8 <API key>(_adapter*padapter, u8 *param);
u8 <API key>(_adapter*padapter, u32 mask, u8 arg);
u8 <API key>(_adapter*padapter, u32 mask, u8 arg);
void <API key>(PADAPTER pAdapter, u32 bitmap, u8 arg, u8 mac_id);
u8 <API key>(_adapter*padapter,u8 bfwpoll, u16 period);
#ifdef CONFIG_P2P
void <API key>(_adapter* padapter, u8 p2p_ps_state);
#endif //CONFIG_P2P
#ifdef CONFIG_IOL
typedef struct _IO_OFFLOAD_LOC{
u8 LocCmd;
}IO_OFFLOAD_LOC, *PIO_OFFLOAD_LOC;
int <API key>(ADAPTER *adapter, struct xmit_frame *xmit_frame, u32 max_wating_ms);
#endif //CONFIG_IOL
#endif
#ifdef CONFIG_WOWLAN
void <API key>(_adapter* padapter);
void <API key>(_adapter* padapter,u8 bHostIsGoingtoSleep);
#endif // CONFIG_WOWLAN |
from node import NodeChain
from opcode_ import OPCode
def node_to_atom(node, iterator):
arg_size = node.get_arg_size()
atom = NodeChain(node)
while arg_size > 0:
try:
arg = iterator.next()
except StopIteration:
raise ValueError("Not enough arguments")
if isinstance(arg, OPCode):
raise ValueError("Currently not supporting"
" OPCode args")
atom.append(arg)
arg_size -= arg.get_size()
if arg_size < 0:
original_arg_size = node.get_arg_size()
real_arg_size = original_arg_size + abs(arg_size)
raise ValueError("Argument size mismatch,"
"Expecting: %s, Got %s"
"" % (original_arg_size, real_arg_size))
return atom
def break_to_atoms(node_chain):
i = iter(node_chain)
atoms = NodeChain()
for node in i:
atoms.append(node_to_atom(node, i))
return atoms |
package net.pms.newgui;
import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.factories.Borders;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import com.sun.jna.Platform;
import net.pms.Messages;
import net.pms.PMS;
import net.pms.configuration.PmsConfiguration;
import net.pms.dlna.DLNAMediaDatabase;
import net.pms.util.FormLayoutUtil;
import net.pms.util.KeyedComboBoxModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.util.Locale;
public class NavigationShareTab {
private static final Logger LOGGER = LoggerFactory.getLogger(NavigationShareTab.class);
public static final String ALL_DRIVES = Messages.getString("FoldTab.0");
private static final String PANEL_COL_SPEC = "left:pref, 50dlu, pref, 150dlu, pref, 25dlu, pref, 25dlu, pref, default:grow";
private static final String PANEL_ROW_SPEC = "p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 10dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 10dlu, fill:default:grow";
private static final String <API key> = "left:pref, left:pref, pref, pref, pref, 0:grow";
private static final String <API key> = "p, 3dlu, p, 3dlu, fill:default:grow";
private JList FList;
private DefaultListModel df;
private JCheckBox hidevideosettings;
private JCheckBox hidetranscode;
private JCheckBox <API key>;
private JCheckBox hideextensions;
private JCheckBox hideemptyfolders;
private JCheckBox hideengines;
private JButton but5;
private JTextField seekpos;
private JCheckBox thumbgenCheckBox;
private JCheckBox mplayer_thumb;
private JCheckBox dvdiso_thumb;
private JCheckBox image_thumb;
private JCheckBox cacheenable;
private JCheckBox archive;
private JComboBox sortmethod;
private JComboBox audiothumbnail;
private JTextField defaultThumbFolder;
private JCheckBox iphoto;
private JCheckBox aperture;
private JCheckBox itunes;
private JButton select;
private JButton cachereset;
public DefaultListModel getDf() {
return df;
}
private final PmsConfiguration configuration;
NavigationShareTab(PmsConfiguration configuration) {
this.configuration = configuration;
}
private void updateModel() {
if (df.size() == 1 && df.getElementAt(0).equals(ALL_DRIVES)) {
configuration.setFolders("");
} else {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < df.size(); i++) {
if (i > 0) {
sb.append(",");
}
String entry = (String) df.getElementAt(i);
// escape embedded commas. note: backslashing isn't safe as it conflicts with
// Windows path separators:
// http://ps3mediaserver.org/forum/viewtopic.php?f=14&t=8883&start=250#p43520
sb.append(entry.replace(",", ","));
}
configuration.setFolders(sb.toString());
}
}
public JComponent build() {
// Apply the orientation for the locale
Locale locale = new Locale(configuration.getLanguage());
<API key> orientation = <API key>.getOrientation(locale);
String colSpec = FormLayoutUtil.getColSpec(PANEL_COL_SPEC, orientation);
// Set basic layout
FormLayout layout = new FormLayout(colSpec, PANEL_ROW_SPEC);
PanelBuilder builder = new PanelBuilder(layout);
builder.setBorder(Borders.DLU4_BORDER);
builder.setOpaque(true);
CellConstraints cc = new CellConstraints();
// Init all gui components
<API key>(cc);
PanelBuilder builderSharedFolder = <API key>(cc);
// Build gui with initialized components
JComponent cmp = builder.addSeparator(Messages.getString("FoldTab.13"),
FormLayoutUtil.flip(cc.xyw(1, 1, 10), colSpec, orientation));
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
builder.add(thumbgenCheckBox, FormLayoutUtil.flip(cc.xyw(1, 3, 3), colSpec, orientation));
builder.addLabel(Messages.getString("NetworkTab.16"), FormLayoutUtil.flip(cc.xyw(4, 3, 3), colSpec, orientation));
builder.add(seekpos, FormLayoutUtil.flip(cc.xyw(6, 3, 1), colSpec, orientation));
builder.add(mplayer_thumb, FormLayoutUtil.flip(cc.xyw(1, 5, 3), colSpec, orientation));
builder.add(dvdiso_thumb, FormLayoutUtil.flip(cc.xyw(3, 5, 3), colSpec, orientation));
builder.add(image_thumb, FormLayoutUtil.flip(cc.xyw(1, 7, 3), colSpec, orientation));
builder.addLabel(Messages.getString("FoldTab.26"), FormLayoutUtil.flip(cc.xyw(1, 9, 3), colSpec, orientation));
builder.add(audiothumbnail, FormLayoutUtil.flip(cc.xyw(4, 9, 3), colSpec, orientation));
builder.addLabel(Messages.getString("FoldTab.27"), FormLayoutUtil.flip(cc.xyw(1, 11, 1), colSpec, orientation));
builder.add(defaultThumbFolder, FormLayoutUtil.flip(cc.xyw(4, 11, 3), colSpec, orientation));
builder.add(select, FormLayoutUtil.flip(cc.xyw(7, 11, 1), colSpec, orientation));
cmp = builder.addSeparator(Messages.getString("NetworkTab.15"), FormLayoutUtil.flip(cc.xyw(1, 13, 10), colSpec, orientation));
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
builder.add(archive, FormLayoutUtil.flip(cc.xyw(1, 15, 3), colSpec, orientation));
builder.add(hidevideosettings, FormLayoutUtil.flip(cc.xyw(4, 15, 3), colSpec, orientation));
builder.add(hidetranscode, FormLayoutUtil.flip(cc.xyw(8, 15, 3), colSpec, orientation));
builder.add(hideextensions, FormLayoutUtil.flip(cc.xyw(1, 17, 3), colSpec, orientation));
builder.add(hideengines, FormLayoutUtil.flip(cc.xyw(4, 17, 3), colSpec, orientation));
builder.add(hideemptyfolders, FormLayoutUtil.flip(cc.xyw(8, 17, 3), colSpec, orientation));
builder.add(itunes, FormLayoutUtil.flip(cc.xyw(1, 19, 3), colSpec, orientation));
builder.add(iphoto, FormLayoutUtil.flip(cc.xyw(4, 19, 3), colSpec, orientation));
builder.add(aperture, FormLayoutUtil.flip(cc.xyw(8, 19, 3), colSpec, orientation));
builder.add(cacheenable, FormLayoutUtil.flip(cc.xy(1, 21), colSpec, orientation));
builder.add(cachereset, FormLayoutUtil.flip(cc.xyw(4, 21, 3), colSpec, orientation));
builder.add(<API key>, FormLayoutUtil.flip(cc.xyw(8, 21, 3), colSpec, orientation));
builder.addLabel(Messages.getString("FoldTab.18"), FormLayoutUtil.flip(cc.xyw(1, 23, 3), colSpec, orientation));
builder.add(sortmethod, FormLayoutUtil.flip(cc.xyw(4, 23, 3), colSpec, orientation));
builder.add(builderSharedFolder.getPanel(), FormLayoutUtil.flip(cc.xyw(1, 27, 10), colSpec, orientation));
JPanel panel = builder.getPanel();
// Apply the orientation to the panel and all components in it
panel.<API key>(orientation);
JScrollPane scrollPane = new JScrollPane(
panel,
JScrollPane.<API key>,
JScrollPane.<API key>);
return scrollPane;
}
private void <API key>(CellConstraints cc) {
// Generate thumbnails
thumbgenCheckBox = new JCheckBox(Messages.getString("NetworkTab.2"));
thumbgenCheckBox.<API key>(false);
thumbgenCheckBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
configuration.<API key>((e.getStateChange() == ItemEvent.SELECTED));
}
});
if (configuration.<API key>()) {
thumbgenCheckBox.setSelected(true);
}
//ThumbnailSeekPos
seekpos = new JTextField("" + configuration.getThumbnailSeekPos());
seekpos.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
try {
int ab = Integer.parseInt(seekpos.getText());
configuration.setThumbnailSeekPos(ab);
} catch (<API key> nfe) {
LOGGER.debug("Could not parse thumbnail seek position from \"" + seekpos.getText() + "\"");
}
}
});
// <API key>
mplayer_thumb = new JCheckBox(Messages.getString("FoldTab.14"));
mplayer_thumb.<API key>(false);
mplayer_thumb.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
configuration.<API key>((e.getStateChange() == ItemEvent.SELECTED));
}
});
if (configuration.<API key>()) {
mplayer_thumb.setSelected(true);
}
// DvdIsoThumbnails
dvdiso_thumb = new JCheckBox(Messages.getString("FoldTab.19"));
dvdiso_thumb.<API key>(false);
dvdiso_thumb.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
configuration.setDvdIsoThumbnails((e.getStateChange() == ItemEvent.SELECTED));
}
});
if (configuration.isDvdIsoThumbnails()) {
dvdiso_thumb.setSelected(true);
}
// <API key>
image_thumb = new JCheckBox(Messages.getString("FoldTab.21"));
image_thumb.<API key>(false);
image_thumb.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
configuration.<API key>((e.getStateChange() == ItemEvent.SELECTED));
}
});
if (configuration.<API key>()) {
image_thumb.setSelected(true);
}
// <API key>
final KeyedComboBoxModel thumbKCBM = new KeyedComboBoxModel(new Object[]{"0", "1", "2"}, new Object[]{Messages.getString("FoldTab.35"), Messages.getString("FoldTab.23"), Messages.getString("FoldTab.24")});
audiothumbnail = new JComboBox(thumbKCBM);
audiothumbnail.setEditable(false);
thumbKCBM.setSelectedKey("" + configuration.<API key>());
audiothumbnail.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
try {
configuration.<API key>(Integer.parseInt((String) thumbKCBM.getSelectedKey()));
} catch (<API key> nfe) {
LOGGER.debug("Could not parse audio thumbnail method from \"" + thumbKCBM.getSelectedKey() + "\"");
}
}
}
});
// <API key>
defaultThumbFolder = new JTextField(configuration.<API key>());
defaultThumbFolder.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.<API key>(defaultThumbFolder.getText());
}
});
// <API key>: select
select = new JButton("...");
select.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = null;
try {
chooser = new JFileChooser();
} catch (Exception ee) {
chooser = new JFileChooser(new <API key>());
}
chooser.<API key>(JFileChooser.DIRECTORIES_ONLY);
int returnVal = chooser.showDialog((Component) e.getSource(), Messages.getString("FoldTab.28"));
if (returnVal == JFileChooser.APPROVE_OPTION) {
defaultThumbFolder.setText(chooser.getSelectedFile().getAbsolutePath());
configuration.<API key>(chooser.getSelectedFile().getAbsolutePath());
}
}
});
// HideVideoSettings
hidevideosettings = new JCheckBox(Messages.getString("FoldTab.6"));
hidevideosettings.<API key>(false);
if (configuration.<API key>()) {
hidevideosettings.setSelected(true);
}
hidevideosettings.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
configuration.<API key>((e.getStateChange() == ItemEvent.SELECTED));
}
});
hidetranscode = new JCheckBox(Messages.getString("FoldTab.33"));
hidetranscode.<API key>(false);
if (configuration.<API key>()) {
hidetranscode.setSelected(true);
}
hidetranscode.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
configuration.<API key>((e.getStateChange() == ItemEvent.SELECTED));
}
});
<API key> = new JCheckBox(Messages.getString("FoldTab.32"));
<API key>.<API key>(false);
if (configuration.<API key>()) {
<API key>.setSelected(true);
}
<API key>.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
configuration.<API key>((e.getStateChange() == ItemEvent.SELECTED));
}
});
archive = new JCheckBox(Messages.getString("NetworkTab.1"));
archive.<API key>(false);
archive.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
configuration.setArchiveBrowsing(e.getStateChange() == ItemEvent.SELECTED);
}
});
if (configuration.isArchiveBrowsing()) {
archive.setSelected(true);
}
cachereset = new JButton(Messages.getString("NetworkTab.18"));
cacheenable = new JCheckBox(Messages.getString("NetworkTab.17"));
cacheenable.<API key>(false);
cacheenable.setSelected(configuration.getUseCache());
cacheenable.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
configuration.setUseCache((e.getStateChange() == ItemEvent.SELECTED));
cachereset.setEnabled(configuration.getUseCache());
if ((LooksFrame) PMS.get().getFrame() != null) {
((LooksFrame) PMS.get().getFrame()).getFt().<API key>(configuration.getUseCache());
}
}
});
cachereset.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int option = JOptionPane.showConfirmDialog(
(Component) PMS.get().getFrame(),
Messages.getString("NetworkTab.13") + Messages.getString("NetworkTab.19"),
"Question",
JOptionPane.YES_NO_OPTION);
if (option == JOptionPane.YES_OPTION) {
PMS.get().getDatabase().init(true);
}
}
});
cachereset.setEnabled(configuration.getUseCache());
// HideExtensions
hideextensions = new JCheckBox(Messages.getString("FoldTab.5"));
hideextensions.<API key>(false);
if (configuration.isHideExtensions()) {
hideextensions.setSelected(true);
}
hideextensions.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
configuration.setHideExtensions((e.getStateChange() == ItemEvent.SELECTED));
}
});
// HideEngineNames
hideengines = new JCheckBox(Messages.getString("FoldTab.8"));
hideengines.<API key>(false);
if (configuration.isHideEngineNames()) {
hideengines.setSelected(true);
}
hideengines.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
configuration.setHideEngineNames((e.getStateChange() == ItemEvent.SELECTED));
}
});
// HideEmptyFolders
hideemptyfolders = new JCheckBox(Messages.getString("FoldTab.31"));
hideemptyfolders.<API key>(false);
if (configuration.isHideEmptyFolders()) {
hideemptyfolders.setSelected(true);
}
hideemptyfolders.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
configuration.setHideEmptyFolders((e.getStateChange() == ItemEvent.SELECTED));
}
});
// ItunesEnabled
itunes = new JCheckBox(Messages.getString("FoldTab.30"));
itunes.<API key>(false);
if (configuration.getItunesEnabled()) {
itunes.setSelected(true);
}
if (!(Platform.isMac() || Platform.isWindows())) {
itunes.setEnabled(false);
}
itunes.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
configuration.setItunesEnabled((e.getStateChange() == ItemEvent.SELECTED));
}
});
// IphotoEnabled
iphoto = new JCheckBox(Messages.getString("FoldTab.29"));
iphoto.<API key>(false);
if (configuration.getIphotoEnabled()) {
iphoto.setSelected(true);
}
if (!Platform.isMac()) {
iphoto.setEnabled(false);
}
iphoto.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
configuration.setIphotoEnabled((e.getStateChange() == ItemEvent.SELECTED));
}
});
// ApertureEnabled
aperture = new JCheckBox(Messages.getString("FoldTab.34"));
aperture.<API key>(false);
if (configuration.getApertureEnabled()) {
aperture.setSelected(true);
}
if (!Platform.isMac()) {
aperture.setEnabled(false);
}
aperture.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
configuration.setApertureEnabled((e.getStateChange() == ItemEvent.SELECTED));
}
});
// sort method
final KeyedComboBoxModel kcbm = new KeyedComboBoxModel(
new Object[]{
"0", // alphabetical
"4", // natural sort
"3", // ASCIIbetical
"1", // newest first
"2" // oldest first
},
new Object[]{
Messages.getString("FoldTab.15"),
Messages.getString("FoldTab.22"),
Messages.getString("FoldTab.20"),
Messages.getString("FoldTab.16"),
Messages.getString("FoldTab.17")
}
);
sortmethod = new JComboBox(kcbm);
sortmethod.setEditable(false);
kcbm.setSelectedKey("" + configuration.getSortMethod());
sortmethod.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
try {
configuration.setSortMethod(Integer.parseInt((String) kcbm.getSelectedKey()));
} catch (<API key> nfe) {
LOGGER.debug("Could not parse sort method from \"" + kcbm.getSelectedKey() + "\"");
}
}
}
});
}
private PanelBuilder <API key>(CellConstraints cc) {
// Apply the orientation for the locale
Locale locale = new Locale(configuration.getLanguage());
<API key> orientation = <API key>.getOrientation(locale);
String colSpec = FormLayoutUtil.getColSpec(<API key>, orientation);
FormLayout layoutFolders = new FormLayout(colSpec, <API key>);
PanelBuilder builderFolder = new PanelBuilder(layoutFolders);
builderFolder.setOpaque(true);
JComponent cmp = builderFolder.addSeparator(Messages.getString("FoldTab.7"), FormLayoutUtil.flip(cc.xyw(1, 1, 6), colSpec, orientation));
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
JButton but = new JButton(LooksFrame.readImageIcon("folder_new-32.png"));
but.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
JFileChooser chooser = null;
try {
chooser = new JFileChooser();
} catch (Exception ee) {
chooser = new JFileChooser(new <API key>());
}
chooser.<API key>(JFileChooser.DIRECTORIES_ONLY);
//int returnVal = chooser.showDialog((Component) e.getSource(), Messages.getString("FoldTab.9"));
int returnVal = chooser.showOpenDialog((Component) e.getSource());
if (returnVal == JFileChooser.APPROVE_OPTION) {
((DefaultListModel) FList.getModel()).add(FList.getModel().getSize(), chooser.getSelectedFile().getAbsolutePath());
if (FList.getModel().getElementAt(0).equals(ALL_DRIVES)) {
((DefaultListModel) FList.getModel()).remove(0);
}
updateModel();
}
}
});
builderFolder.add(but, FormLayoutUtil.flip(cc.xy(1, 3), colSpec, orientation));
JButton but2 = new JButton(LooksFrame.readImageIcon("button_cancel-32.png"));
//but2.setBorder(BorderFactory.createEtchedBorder());
but2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
if (FList.getSelectedIndex() > -1) {
((DefaultListModel) FList.getModel()).remove(FList.getSelectedIndex());
if (FList.getModel().getSize() == 0) {
((DefaultListModel) FList.getModel()).add(0, ALL_DRIVES);
}
updateModel();
}
}
});
builderFolder.add(but2, FormLayoutUtil.flip(cc.xy(2, 3), colSpec, orientation));
JButton but3 = new JButton(LooksFrame.readImageIcon("kdevelop_down-32.png"));
but3.setToolTipText(Messages.getString("FoldTab.12"));
// but3.setBorder(BorderFactory.createEmptyBorder());
but3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultListModel model = ((DefaultListModel) FList.getModel());
for (int i = 0; i < model.size() - 1; i++) {
if (FList.isSelectedIndex(i)) {
String value = model.get(i).toString();
model.set(i, model.get(i + 1));
model.set(i + 1, value);
FList.setSelectedIndex(i + 1);
updateModel();
break;
}
}
}
});
builderFolder.add(but3, FormLayoutUtil.flip(cc.xy(3, 3), colSpec, orientation));
JButton but4 = new JButton(LooksFrame.readImageIcon("up-32.png"));
but4.setToolTipText(Messages.getString("FoldTab.12"));
// but4.setBorder(BorderFactory.createEmptyBorder());
but4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultListModel model = ((DefaultListModel) FList.getModel());
for (int i = 1; i < model.size(); i++) {
if (FList.isSelectedIndex(i)) {
String value = model.get(i).toString();
model.set(i, model.get(i - 1));
model.set(i - 1, value);
FList.setSelectedIndex(i - 1);
updateModel();
break;
}
}
}
});
builderFolder.add(but4, FormLayoutUtil.flip(cc.xy(4, 3), colSpec, orientation));
but5 = new JButton(LooksFrame.readImageIcon("search-32.png"));
but5.setToolTipText(Messages.getString("FoldTab.2"));
//but5.setBorder(BorderFactory.createEmptyBorder());
but5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (configuration.getUseCache()) {
DLNAMediaDatabase database = PMS.get().getDatabase();
if (database != null) {
if (!database.<API key>()) {
int option = JOptionPane.showConfirmDialog(
(Component) PMS.get().getFrame(),
Messages.getString("FoldTab.3") + Messages.getString("FoldTab.4"),
"Question",
JOptionPane.YES_NO_OPTION);
if (option == JOptionPane.YES_OPTION) {
database.scanLibrary();
but5.setIcon(LooksFrame.readImageIcon("viewmagfit-32.png"));
}
} else {
int option = JOptionPane.showConfirmDialog(
(Component) PMS.get().getFrame(),
Messages.getString("FoldTab.10"),
"Question",
JOptionPane.YES_NO_OPTION);
if (option == JOptionPane.YES_OPTION) {
database.stopScanLibrary();
PMS.get().getFrame().setStatusLine(null);
but5.setIcon(LooksFrame.readImageIcon("search-32.png"));
}
}
}
}
}
});
builderFolder.add(but5, FormLayoutUtil.flip(cc.xy(5, 3), colSpec, orientation));
but5.setEnabled(configuration.getUseCache());
df = new DefaultListModel();
File[] folders = PMS.get().getFoldersConf(false);
if (folders != null && folders.length > 0) {
for (File file : folders) {
df.addElement(file.getAbsolutePath());
}
} else {
df.addElement(ALL_DRIVES);
}
FList = new JList();
FList.setModel(df);
JScrollPane pane = new JScrollPane(FList);
builderFolder.add(pane, FormLayoutUtil.flip(cc.xyw(1, 5, 6), colSpec, orientation));
return builderFolder;
}
public void <API key>(boolean enabled) {
but5.setEnabled(enabled);
but5.setIcon(LooksFrame.readImageIcon("search-32.png"));
}
} |
package com.examstack.common.domain.question;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
// group_2_filed
public class Group2Field implements Serializable {
private Integer groupId;
private String groupName;
private Integer fieldId;
private String fieldName;
private Integer id;
public Integer getGroupId() {
return groupId;
}
public void setGroupId(Integer groupId) {
this.groupId = groupId;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public Integer getFieldId() {
return fieldId;
}
public void setFieldId(Integer fieldId) {
this.fieldId = fieldId;
}
public String getFieldName() {
return fieldName;
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((fieldId == null) ? 0 : fieldId.hashCode());
result = prime * result + ((groupId == null) ? 0 : groupId.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Group2Field))
return false;
Group2Field other = (Group2Field) obj;
if(this.id == other.getId() || (this.groupId == other.getGroupId() && this.fieldId == other.getFieldId()))
{
return true;
}
return false;
}
} |
package org.das2.util;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
/**
*
* @author eew
*/
public class MessageBox extends Dialog {
public static final int OK = 1;
public static final int CANCEL = 2;
public static final int YES = 4;
public static final int NO = 8;
public static final int YES_NO = 12;
public static final int YES_NO_CANCEL = 14;
public static final int OK_CANCEL = 3;
public static final int DEFAULT = 3;
private int result;
private int type;
private Button yes;
private Button no;
private Button ok;
private Button cancel;
/** Creates a new instance of MessageBox */
private MessageBox(Frame owner) {
super(owner);
}
private MessageBoxListener createListener()
{
return new MessageBoxListener();
}
public static int showModalMessage(Frame owner, int type, String title, String message)
{
return showModalMessage(owner, type, title, breakLines(message));
}
public static int showModalMessage(Frame owner, int type, String title, String[] message)
{
MessageBox mb = new MessageBox(owner);
MessageBoxListener mbl = mb.createListener();
Panel messagePanel, buttonPanel;
if (type == 0) type = OK_CANCEL;
mb.type = type;
mb.setTitle(title);
mb.setModal(true);
mb.setLayout(new BorderLayout());
mb.addWindowListener(mbl);
messagePanel = new Panel(new GridLayout(0,1));
for (int i = 0; i < message.length; i++)
{
messagePanel.add(new Label(message[i]));
}
mb.add(messagePanel, "Center");
buttonPanel = new Panel(new FlowLayout(FlowLayout.RIGHT));
if ((type & OK) == OK)
{
mb.ok = new Button("Ok");
mb.ok.addActionListener(mbl);
buttonPanel.add(mb.ok);
}
if ((type & YES) == YES)
{
mb.yes = new Button("Yes");
mb.yes.addActionListener(mbl);
buttonPanel.add(mb.yes);
}
if ((type & NO) == NO)
{
mb.no = new Button("No");
mb.no.addActionListener(mbl);
buttonPanel.add(mb.no);
}
if ((type & CANCEL) == CANCEL)
{
mb.cancel = new Button("Cancel");
mb.cancel.addActionListener(mbl);
buttonPanel.add(mb.cancel);
}
mb.add(messagePanel, "Center");
mb.add(buttonPanel, "South");
mb.pack();
Dimension od = owner.getSize();
Point op = owner.getLocation();
Dimension md = mb.getSize();
mb.setLocation(op.x + (od.width - md.width)/2, op.y + (od.height - md.height)/2);
mb.setVisible(true);
return mb.result;
}
private static String[] breakLines(String s)
{
java.util.StringTokenizer st = new java.util.StringTokenizer(s, "\n", false);
int lines = st.countTokens();
String[] list = new String[lines];
for (int i = 0; i < lines; i++)
list[i] = st.nextToken();
return list;
}
private class MessageBoxListener extends WindowAdapter implements ActionListener
{
public void windowClosing(WindowEvent e)
{
result = CANCEL;
setVisible(false);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == ok)
{
result = OK;
}
else if (e.getSource() == cancel)
{
result = CANCEL;
}
else if (e.getSource() == yes)
{
result = YES;
}
else if (e.getSource() == no)
{
result = NO;
}
setVisible(true);
}
}
} |
require 'gyoku'
module Garbanzo
class Subscription
class Base
module XMLFormatter
def to_xml
Gyoku.xml(self.nodes)
end
end
def self.call(*args)
new.call *args
end
def initialize(connection = Garbanzo.connection)
@connection = connection
end
def call(*args)
ast = ast_builder.build *args
request ast.to_xml
end
private
attr_reader :connection
def request(xml)
response_klass.wrap Request.post(xml, connection.test_mode)
end
def response_klass
Response
end
def ast_builder
ast_builder_klass.new(connection).extend(formatter)
end
def formatter
XMLFormatter
end
end
end
end |
subroutine snr4(blue,sync,snr)
real blue(65)
integer ipk1(1)
equivalence (ipk,ipk1)
ipk1=maxloc(blue)
ns=0
s=0.
do i=1,65
if(abs(i-ipk).gt.1) then
s=s+blue(i)
ns=ns+1
endif
enddo
base=s/ns
blue=blue-base
sq=0.
do i=1,65
if(abs(i-ipk).gt.1) sq=sq+blue(i)**2
enddo
rms=sqrt(sq/(ns-1))
snr=10.0*log10(blue(ipk)/rms) - 30.6
sync=snr+25.5
print*,'B',blue(ipk),rms,sync,blue(ipk)/rms,db(blue(ipk)/rms)
return
end subroutine snr4 |
<div class="announce instapaper_body mkd" data-path="README.mkd" id="readme"><article class="markdown-body entry-content" itemprop="mainContentOfPage"><h1>
<a name="user-content-vimux" class="anchor" href="#vimux" aria-hidden="true"><span class="octicon octicon-link"></span></a>vimux</h1>
<p>Easily interact with tmux from vim.</p>
<p><a href="https:
<p>What inspired me to write vimux was <a href="https://github.com/kikijump/tslime.vim">tslime.vim</a>, a plugin that lets you send input to tmux. While tslime.vim works well, I felt it wasn't optimized for my primary use case which was having a smaller tmux pane that I would use to run tests or play with a REPL.</p>
<p>My goal with vimux is to make interacting with tmux from vim effortless. By default when you call <code>VimuxRunCommand</code> vimux will create a 20% tall horizontal pane under your current tmux pane and execute a command in it without losing focus of vim. Once that pane exists whenever you call <code>VimuxRunCommand</code> again the command will be executed in that pane. As I was using vimux myself I wanted to rerun commands over and over. An example of this was running the current file through rspec. Rather than typing that over and over I wrote <code>VimuxRunLastCommand</code> that will execute the last command you called with <code>VimuxRunCommand</code>.</p>
<p>Other auxiliary functions and the ones I talked about above can be found bellow with a full description and example key binds for your vimrc.</p>
<h2>
<a name="<API key>" class="anchor" href="#installation" aria-hidden="true"><span class="octicon octicon-link"></span></a>Installation</h2>
<p>With <strong><a href="https://github.com/benmills/vim-bundle">vim-bundle</a></strong>: <code>vim-bundle install benmills/vimux</code></p>
<p>Otherwise download the latest <a href="https:
<p><em>Notes:</em> </p>
<ul class="task-list">
<li>Vimux assumes a tmux version >= 1.5. Some older versions might work but it is recommeded to use at least version 1.5.</li>
</ul><h2>
<a name="<API key>" class="anchor" href="#<API key>" aria-hidden="true"><span class="octicon octicon-link"></span></a>Platform-specific Plugins</h2>
<ul class="task-list">
<li>
<a href="https://github.com/skalnik/vim-vroom">vim-vroom</a> runner for rspec, cucumber and test/unit; vimux support via <code>g:vroom_use_vimux</code>
</li>
<li>
<a href="https://github.com/pgr0ss/vimux-ruby-test">vimux-ruby-test</a> a set of commands to easily run ruby tests</li>
<li>
<a href="https://github.com/cloud8421/vimux-cucumber">vimux-cucumber</a> run Cucumber Features through Vimux</li>
<li>
<a href="https://github.com/jgdavey/vim-turbux">vim-turbux</a> Turbo Ruby testing with tmux</li>
<li>
<a href="https://github.com/julienr/vimux-pyutils">vimux-pyutils</a> A set of functions for vimux that allow to run code blocks in ipython</li>
<li>
<a href="https://github.com/pitluga/vimux-nose-test">vimux-nose-test</a> Run nose tests in vimux</li>
<li>
<a href="https://github.com/benmills/vimux-golang">vimux-golang</a> Run go tests in vimux</li>
<li>
<a href="https://github.com/jingweno/vimux-zeus">vimux-zeus</a> Run zeus commands in vimux</li>
<li>
<a href="https://github.com/spiegela/vimix">vimix</a> Run Elixir mix commands in vimux</li>
</ul><h2>
<a name="user-content-usage" class="anchor" href="#usage" aria-hidden="true"><span class="octicon octicon-link"></span></a>Usage</h2>
<p>The full documentation is available <a href="https://raw.github.com/benmills/vimux/master/doc/vimux.txt">online</a> and accessible inside vim <code>:help vimux</code></p></article></div> |
package com.sales.model;
import java.util.List;
public class SAction {
/**
* This field was generated by Abator for iBATIS.
* This field corresponds to the database column s_action.action_id
*
* @abatorgenerated Tue Apr 23 17:36:30 CST 2013
*/
private Integer actionId;
/**
* This field was generated by Abator for iBATIS.
* This field corresponds to the database column s_action.name
*
* @abatorgenerated Tue Apr 23 17:36:30 CST 2013
*/
private String name;
/**
* This field was generated by Abator for iBATIS.
* This field corresponds to the database column s_action.url
*
* @abatorgenerated Tue Apr 23 17:36:30 CST 2013
*/
private String url;
private String isCheck;
private List<SModule> moduleList;
public String getIsCheck() {
return isCheck;
}
public List<SModule> getModuleList() {
return moduleList;
}
public void setModuleList(List<SModule> moduleList) {
this.moduleList = moduleList;
}
public void setIsCheck(String isCheck) {
this.isCheck = isCheck;
}
/**
* This method was generated by Abator for iBATIS.
* This method returns the value of the database column s_action.action_id
*
* @return the value of s_action.action_id
*
* @abatorgenerated Tue Apr 23 17:36:30 CST 2013
*/
public Integer getActionId() {
return actionId;
}
/**
* This method was generated by Abator for iBATIS.
* This method sets the value of the database column s_action.action_id
*
* @param actionId the value for s_action.action_id
*
* @abatorgenerated Tue Apr 23 17:36:30 CST 2013
*/
public void setActionId(Integer actionId) {
this.actionId = actionId;
}
/**
* This method was generated by Abator for iBATIS.
* This method returns the value of the database column s_action.name
*
* @return the value of s_action.name
*
* @abatorgenerated Tue Apr 23 17:36:30 CST 2013
*/
public String getName() {
return name;
}
/**
* This method was generated by Abator for iBATIS.
* This method sets the value of the database column s_action.name
*
* @param name the value for s_action.name
*
* @abatorgenerated Tue Apr 23 17:36:30 CST 2013
*/
public void setName(String name) {
this.name = name;
}
/**
* This method was generated by Abator for iBATIS.
* This method returns the value of the database column s_action.url
*
* @return the value of s_action.url
*
* @abatorgenerated Tue Apr 23 17:36:30 CST 2013
*/
public String getUrl() {
return url;
}
/**
* This method was generated by Abator for iBATIS.
* This method sets the value of the database column s_action.url
*
* @param url the value for s_action.url
*
* @abatorgenerated Tue Apr 23 17:36:30 CST 2013
*/
public void setUrl(String url) {
this.url = url;
}
} |
package br.com.urcontroler.main.view.interfaces;
import br.com.urcontroler.main.MainScreen;
import br.com.urcontroler.main.view.View;
import java.util.logging.Logger;
import javax.swing.JComponent;
/**
* Interface para Views
*
* @author kaciano
* @param <T> Tipo do Bean
*/
public interface ViewListener<T> {
/**
* Acesso aos logs
*/
public static final Logger LOGGER = Logger.getLogger(View.class.getName());
/**
* Retorna se a View pode salvar
*
* @return {@code Boolean} Pode salvar
*/
Boolean canCommit();
/**
* Retorna se a View pode processar
*
* @return {@code Boolean} Pode processar
*/
Boolean canProcces();
/**
* Retorna se a View pode limpar
*
* @return {@code Boolean} Pode limpar
*/
Boolean canClear();
/**
* Retorna se a View pode carregar
*
* @return {@code Boolean} Pode carregar
*/
Boolean canLoad();
void setCommit(boolean save);
void setProcces(boolean process);
void setClear(boolean clear);
void setLoad(boolean load);
void onCommit();
void onProcess();
void onClear();
void onLoad();
/**
* Retorna o Bean da View
*
* @param <T> Tipo de Retorno
* @return {@code BeanListener}
*/
<T> BeanListener getBean();
/**
* Retorna a tela principal
*
* @return {@code MainScreen}
*/
MainScreen getMainScreen();
void showMessage(String msg, int type);
void showBallon(JComponent component, String text);
void showMessageBalloon(String text);
} |
/* line 1, ../sass/subscribe-form.scss */
form.prompt-subscribe label.prompt-topic {
display: none;
}
.loading-indicator {
width: 40px;
height: 40px;
background-color: #ddd;
border-radius: 100%;
-webkit-animation: sk-scaleout 1.0s infinite ease-in-out;
animation: sk-scaleout 1.0s infinite ease-in-out;
visibility: hidden;
opacity: 0;
transition: opacity 0.2s linear, visibility 2s ease;
position: absolute;
top: 0;
margin: 0 auto;
left: 0;
right: 0;
}
.loading-indicator.active {
visibility: visible;
opacity: 1;
}
@-webkit-keyframes sk-scaleout {
0% { -webkit-transform: scale(0) }
100% {
-webkit-transform: scale(1.0);
opacity: 0;
}
}
@keyframes sk-scaleout {
0% {
-webkit-transform: scale(0);
transform: scale(0);
} 100% {
-webkit-transform: scale(1.0);
transform: scale(1.0);
opacity: 0;
}
}
.prompt-subscribe {
position: relative;
}
.prompt-subscribe input {margin-bottom: 5px;}
.om-custom-html-form .prompt-subscribe input {
margin: 5px !important;
width: 30% !important;
}
.message, .message p {
margin: 0;
padding: 0;
}
.prompt-subscribe .inputs, .prompt-subscribe .subscribe {
visibility: hidden;
opacity: 0;
transition: visibility 0.2s ease, opacity 0.2s linear;
}
.prompt-subscribe .inputs.active, .prompt-subscribe .subscribe.active {
visibility: visible;
opacity: 1;
top: 0;
}
.prompt-subscribe .message {
visibility: hidden;
opacity: 0;
transition: opacity 1s linear, visibility 1s ease;
position: absolute;
top: 0;
}
.prompt-subscribe .message.active {
visibility: visible;
opacity: 1;
} |
<?php
define ("<API key>", 0);
define ("SERIAL_DEVICE_SET", 1);
define ("<API key>", 2);
class phpSerial
{
var $_device = null;
var $_windevice = null;
var $_dHandle = null;
var $_dState = <API key>;
var $_buffer = "";
var $_os = "";
/**
* This var says if buffer should be flushed by sendMessage (true) or manualy (false)
*
* @var bool
*/
var $autoflush = true;
/**
* Constructor. Perform some checks about the OS and setserial
*
* @return phpSerial
*/
function phpSerial ()
{
setlocale(LC_ALL, "en_US");
$sysname = php_uname();
if (substr($sysname, 0, 5) === "Linux")
{
$this->_os = "linux";
if($this->_exec("stty --version") === 0)
{
<API key>(array($this, "deviceClose"));
}
else
{
trigger_error("No stty availible, unable to run.", E_USER_ERROR);
}
}
elseif (substr($sysname, 0, 6) === "Darwin")
{
$this->_os = "osx";
// We know stty is available in Darwin.
// stty returns 1 when run from php, because "stty: stdin isn't a
// terminal"
// skip this check
<API key>(array($this, "deviceClose"));
// else
// trigger_error("No stty availible, unable to run.", E_USER_ERROR);
}
elseif(substr($sysname, 0, 7) === "Windows")
{
$this->_os = "windows";
<API key>(array($this, "deviceClose"));
}
else
{
trigger_error("Host OS is neither osx, linux nor windows, unable to run.", E_USER_ERROR);
exit();
}
}
// OPEN/CLOSE DEVICE SECTION -- {START}
/**
* Device set function : used to set the device name/address.
* -> linux : use the device address, like /dev/ttyS0
* -> osx : use the device address, like /dev/tty.serial
* -> windows : use the COMxx device name, like COM1 (can also be used
* with linux)
*
* @param string $device the name of the device to be used
* @return bool
*/
function deviceSet ($device)
{
if ($this->_dState !== <API key>)
{
if ($this->_os === "linux")
{
if (preg_match("@^COM(\d+):?$@i", $device, $matches))
{
$device = "/dev/ttyS" . ($matches[1] - 1);
}
if ($this->_exec("stty -F " . $device) === 0)
{
$this->_device = $device;
$this->_dState = SERIAL_DEVICE_SET;
return true;
}
}
elseif ($this->_os === "osx")
{
if ($this->_exec("stty -f " . $device) === 0)
{
$this->_device = $device;
$this->_dState = SERIAL_DEVICE_SET;
return true;
}
}
elseif ($this->_os === "windows")
{
if (preg_match("@^COM(\d+):?$@i", $device, $matches) and $this->_exec(exec("mode " . $device . " xon=on BAUD=9600")) === 0)
{
$this->_windevice = "COM" . $matches[1];
$this->_device = "\\.\com" . $matches[1];
$this->_dState = SERIAL_DEVICE_SET;
return true;
}
}
trigger_error("Specified serial port is not valid", E_USER_WARNING);
return false;
}
else
{
trigger_error("You must close your device before to set an other one", E_USER_WARNING);
return false;
}
}
/**
* Opens the device for reading and/or writing.
*
* @param string $mode Opening mode : same parameter as fopen()
* @return bool
*/
function deviceOpen ($mode = "r+b")
{
if ($this->_dState === <API key>)
{
trigger_error("The device is already opened", E_USER_NOTICE);
return true;
}
if ($this->_dState === <API key>)
{
trigger_error("The device must be set before to be open", E_USER_WARNING);
return false;
}
if (!preg_match("@^[raw]\+?b?$@", $mode))
{
trigger_error("Invalid opening mode : ".$mode.". Use fopen() modes.", E_USER_WARNING);
return false;
}
$this->_dHandle = @fopen($this->_device, $mode);
if ($this->_dHandle !== false)
{
stream_set_blocking($this->_dHandle, 0);
$this->_dState = <API key>;
return true;
}
$this->_dHandle = null;
trigger_error("Unable to open the device", E_USER_WARNING);
return false;
}
/**
* Closes the device
*
* @return bool
*/
function deviceClose ()
{
if ($this->_dState !== <API key>)
{
return true;
}
if (fclose($this->_dHandle))
{
$this->_dHandle = null;
$this->_dState = SERIAL_DEVICE_SET;
return true;
}
trigger_error("Unable to close the device", E_USER_ERROR);
return false;
}
// OPEN/CLOSE DEVICE SECTION -- {STOP}
// CONFIGURE SECTION -- {START}
/**
* Configure the Baud Rate
* Possible rates : 110, 150, 300, 600, 1200, 2400, 4800, 9600, 38400,
* 57600 and 115200. Note there was a paramter added from original class.
*
* @param int $rate the rate to set the port in
* @return bool
*/
function confBaudRate ($rate)
{
if ($this->_dState !== SERIAL_DEVICE_SET)
{
trigger_error("Unable to set the baud rate : the device is either not set or opened", E_USER_WARNING);
return false;
}
$validBauds = array (
110 => 11,
150 => 15,
300 => 30,
600 => 60,
1200 => 12,
2400 => 24,
4800 => 48,
9600 => 96,
19200 => 19,
38400 => 38400,
57600 => 57600,
115200 => 115200
);
if (isset($validBauds[$rate]))
{
if ($this->_os === "linux")
{
//note this is the only place modified from the original, I submitted a patch on Google Code for this change
$ret = $this->_exec("stty -F " . $this->_device . " raw speed -echo " . (int) $rate, $out);
}
if ($this->_os === "osx")
{
$ret = $this->_exec("stty -f " . $this->_device . " " . (int) $rate, $out);
}
elseif ($this->_os === "windows")
{
$ret = $this->_exec("mode " . $this->_windevice . " BAUD=" . $validBauds[$rate], $out);
}
else return false;
if ($ret !== 0)
{
trigger_error ("Unable to set baud rate: " . $out[1], E_USER_WARNING);
return false;
}
}
}
/**
* Configure parity.
* Modes : odd, even, none
*
* @param string $parity one of the modes
* @return bool
*/
function confParity ($parity)
{
if ($this->_dState !== SERIAL_DEVICE_SET)
{
trigger_error("Unable to set parity : the device is either not set or opened", E_USER_WARNING);
return false;
}
$args = array(
"none" => "-parenb",
"odd" => "parenb parodd",
"even" => "parenb -parodd",
);
if (!isset($args[$parity]))
{
trigger_error("Parity mode not supported", E_USER_WARNING);
return false;
}
if ($this->_os === "linux")
{
$ret = $this->_exec("stty -F " . $this->_device . " " . $args[$parity], $out);
}
elseif ($this->_os === "osx")
{
$ret = $this->_exec("stty -f " . $this->_device . " " . $args[$parity], $out);
}
else
{
$ret = $this->_exec("mode " . $this->_windevice . " PARITY=" . $parity{0}, $out);
}
if ($ret === 0)
{
return true;
}
trigger_error("Unable to set parity : " . $out[1], E_USER_WARNING);
return false;
}
/**
* Sets the length of a character.
*
* @param int $int length of a character (5 <= length <= 8)
* @return bool
*/
function confCharacterLength ($int)
{
if ($this->_dState !== SERIAL_DEVICE_SET)
{
trigger_error("Unable to set length of a character : the device is either not set or opened", E_USER_WARNING);
return false;
}
$int = (int) $int;
if ($int < 5) $int = 5;
elseif ($int > 8) $int = 8;
if ($this->_os === "linux")
{
$ret = $this->_exec("stty -F " . $this->_device . " cs" . $int, $out);
}
elseif ($this->_os === "osx")
{
$ret = $this->_exec("stty -f " . $this->_device . " cs" . $int, $out);
}
else
{
$ret = $this->_exec("mode " . $this->_windevice . " DATA=" . $int, $out);
}
if ($ret === 0)
{
return true;
}
trigger_error("Unable to set character length : " .$out[1], E_USER_WARNING);
return false;
}
/**
* Sets the length of stop bits.
*
* @param float $length the length of a stop bit. It must be either 1,
* 1.5 or 2. 1.5 is not supported under linux and on some computers.
* @return bool
*/
function confStopBits ($length)
{
if ($this->_dState !== SERIAL_DEVICE_SET)
{
trigger_error("Unable to set the length of a stop bit : the device is either not set or opened", E_USER_WARNING);
return false;
}
if ($length != 1 and $length != 2 and $length != 1.5 and !($length == 1.5 and $this->_os === "linux"))
{
trigger_error("Specified stop bit length is invalid", E_USER_WARNING);
return false;
}
if ($this->_os === "linux")
{
$ret = $this->_exec("stty -F " . $this->_device . " " . (($length == 1) ? "-" : "") . "cstopb", $out);
}
elseif ($this->_os === "osx")
{
$ret = $this->_exec("stty -f " . $this->_device . " " . (($length == 1) ? "-" : "") . "cstopb", $out);
}
else
{
$ret = $this->_exec("mode " . $this->_windevice . " STOP=" . $length, $out);
}
if ($ret === 0)
{
return true;
}
trigger_error("Unable to set stop bit length : " . $out[1], E_USER_WARNING);
return false;
}
/**
* Configures the flow control
*
* @param string $mode Set the flow control mode. Availible modes :
* -> "none" : no flow control
* -> "rts/cts" : use RTS/CTS handshaking
* -> "xon/xoff" : use XON/XOFF protocol
* @return bool
*/
function confFlowControl ($mode)
{
if ($this->_dState !== SERIAL_DEVICE_SET)
{
trigger_error("Unable to set flow control mode : the device is either not set or opened", E_USER_WARNING);
return false;
}
$linuxModes = array(
"none" => "clocal -crtscts -ixon -ixoff",
"rts/cts" => "-clocal crtscts -ixon -ixoff",
"xon/xoff" => "-clocal -crtscts ixon ixoff"
);
$windowsModes = array(
"none" => "xon=off octs=off rts=on",
"rts/cts" => "xon=off octs=on rts=hs",
"xon/xoff" => "xon=on octs=off rts=on",
);
if ($mode !== "none" and $mode !== "rts/cts" and $mode !== "xon/xoff") {
trigger_error("Invalid flow control mode specified", E_USER_ERROR);
return false;
}
if ($this->_os === "linux")
$ret = $this->_exec("stty -F " . $this->_device . " " . $linuxModes[$mode], $out);
elseif ($this->_os === "osx")
$ret = $this->_exec("stty -f " . $this->_device . " " . $linuxModes[$mode], $out);
else
$ret = $this->_exec("mode " . $this->_windevice . " " . $windowsModes[$mode], $out);
if ($ret === 0) return true;
else {
trigger_error("Unable to set flow control : " . $out[1], E_USER_ERROR);
return false;
}
}
/**
* Sets a setserial parameter (cf man setserial)
* NO MORE USEFUL !
* -> No longer supported
* -> Only use it if you need it
*
* @param string $param parameter name
* @param string $arg parameter value
* @return bool
*/
function setSetserialFlag ($param, $arg = "")
{
if (!$this->_ckOpened()) return false;
$return = exec ("setserial " . $this->_device . " " . $param . " " . $arg . " 2>&1");
if ($return{0} === "I")
{
trigger_error("setserial: Invalid flag", E_USER_WARNING);
return false;
}
elseif ($return{0} === "/")
{
trigger_error("setserial: Error with device file", E_USER_WARNING);
return false;
}
else
{
return true;
}
}
// CONFIGURE SECTION -- {STOP}
// I/O SECTION -- {START}
/**
* Sends a string to the device
*
* @param string $str string to be sent to the device
* @param float $waitForReply time to wait for the reply (in seconds)
*/
function sendMessage ($str, $waitForReply = 0.1)
{
$this->_buffer .= $str;
if ($this->autoflush === true) $this->serialflush();
usleep((int) ($waitForReply * 1000000));
}
/**
* Reads the port until no new datas are availible, then return the content.
*
* @param int $count number of characters to be read (will stop before
* if less characters are in the buffer)
* @return string
*/
function readPort ($count = 0)
{
if ($this->_dState !== <API key>)
{
trigger_error("Device must be opened to read it", E_USER_WARNING);
return false;
}
if ($this->_os === "linux" || $this->_os === "osx")
{
// Behavior in OSX isn't to wait for new data to recover, but just grabs what's there!
// Doesn't always work perfectly for me in OSX
$content = ""; $i = 0;
if ($count !== 0)
{
do {
if ($i > $count) $content .= fread($this->_dHandle, ($count - $i));
else $content .= fread($this->_dHandle, 128);
} while (($i += 128) === strlen($content));
}
else
{
do {
$content .= fread($this->_dHandle, 128);
} while (($i += 128) === strlen($content));
}
return $content;
}
elseif ($this->_os === "windows")
{
// Windows port reading procedures still buggy
$content = ""; $i = 0;
if ($count !== 0)
{
do {
if ($i > $count) $content .= fread($this->_dHandle, ($count - $i));
else $content .= fread($this->_dHandle, 128);
} while (($i += 128) === strlen($content));
}
else
{
do {
$content .= fread($this->_dHandle, 128);
} while (($i += 128) === strlen($content));
}
return $content;
}
return false;
}
/**
* Flushes the output buffer
* Renamed from flush for osx compat. issues
*
* @return bool
*/
function serialflush ()
{
if (!$this->_ckOpened()) return false;
if (fwrite($this->_dHandle, $this->_buffer) !== false)
{
$this->_buffer = "";
return true;
}
else
{
$this->_buffer = "";
trigger_error("Error while sending message", E_USER_WARNING);
return false;
}
}
// I/O SECTION -- {STOP}
// INTERNAL TOOLKIT -- {START}
function _ckOpened()
{
if ($this->_dState !== <API key>)
{
trigger_error("Device must be opened", E_USER_WARNING);
return false;
}
return true;
}
function _ckClosed()
{
if ($this->_dState !== <API key>)
{
trigger_error("Device must be closed", E_USER_WARNING);
return false;
}
return true;
}
function _exec($cmd, &$out = null)
{
$desc = array(
1 => array("pipe", "w"),
2 => array("pipe", "w")
);
$proc = proc_open($cmd, $desc, $pipes);
$ret = stream_get_contents($pipes[1]);
$err = stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
$retVal = proc_close($proc);
if (func_num_args() == 2) $out = array($ret, $err);
return $retVal;
}
// INTERNAL TOOLKIT -- {STOP}
}
class XBee extends phpSerial {
/**
* Constructor. Parent is phpSerial
*
* @return Xbee
*/
function XBee() {
parent::phpSerial();
}
/**
* Sets up typical Connection 9600 8-N-1
*
* @param String $device is the path to the xbee, defaults to /dev/ttyUSB0
* @return void
*/
public function confDefaults($device = '/dev/ttyUSB0') {
$this -> deviceSet($device);
$this -> confBaudRate(9600);
$this -> confParity('none');
$this -> confCharacterLength(8);
$this -> confStopBits(1);
$this -> confFlowControl('none');
}
/**
* Opens this XBee connection.
*
* Note that you can send raw serial with sendMessage from phpSerial
* @return void
* @param $waitForOpened int amount to sleep after openeing in seconds. Defaults to 0.1
*/
public function open($waitForOpened=0.1) {
$this -> deviceOpen();
usleep((int) ($waitForOpened * 1000000));
}
/**
* Closes this XBee connection
* @return void
*/
public function close() {
$this -> deviceClose();
}
/**
* Sends an XBee frame. $waitForReply is how long to wait on recieving
*
* @param XBeeFrame $frame
* @param int $waitForRply
* @return void
*/
public function send($frame , $waitForReply=0.1) {
$this -> sendMessage($frame -> getFrame(), $waitForReply);
//echo 'Sent: ';print_r(unpack('H*', $frame -> getFrame())); //debug
}
/**
* Reads the XBee until no new data is availible, then returns the content.
* Note that the return is an array of XBeeResponses
*
* @param int $count number of characters to be read (will stop before
* if less characters are in the buffer)
* @return Array $XBeeResponse
*/
public function recieve($count = 0) {
$rawResponse = $this -> readPort($count);
$rawResponse = unpack('H*', $rawResponse);
$response = explode('7e', $rawResponse[1]);
//echo ' responseArr:';print_r($response); //debug
for ($i=1; $i < count($response); $i++) {
$response[$i] = new XBeeResponse($response[$i]);
}
return $response;
}
}
/**
* XbeeFrameBase represents common functions for all types of frames
*
* @package XBeeFrameBase
* @subpackage XBeeFrame
* @subpackage XBeeResponse
*/
abstract class _XBeeFrameBase {
const DEFAULT_START_BYTE = '7E', DEFAULT_FRAME_ID = '01',
REMOTE_API_ID = '17', LOCAL_API_ID = '08',
QUEUED_API_ID = '09', TX_API_ID = '10', TX_EXPLICIT_API_ID = '11';
protected $frame, $frameId, $apiId, $cmdData, $startByte, $address16, $address64, $options, $cmd, $val;
/**
* Contructor for abstract class XbeeFrameBase.
*
*/
protected function _XBeeFrameBase() {
$this -> setStartByte(_XBeeFrameBase::DEFAULT_START_BYTE);
$this -> setFrameId(_XBeeFrameBase::DEFAULT_FRAME_ID);
}
/**
* Assembles frame after all values are set
*
* @return void
*/
protected function _assembleFrame() {
$this -> setFrame(
$this -> getStartByte() .
$this -> _getFramelength($this -> getCmdData()) .
$this -> getCmdData() .
$this -> _calcChecksum($this -> getCmdData())
);
//echo 'Assembled: ';print_r($this -> _unpackBytes($this -> getFrame())); //debug
}
/**
* Calculates checksum for cmdData. Leave off start byte, length and checksum
*
* @param String $data Should be a binary string
* @return String $checksum Should be a binary string
*/
protected function _calcChecksum($data) {
$checksum = 0;
for ($i = 0; $i < strlen($data); $i++) {
$checksum += ord($data[$i]);
}
$checksum = $checksum & 0xFF;
$checksum = 0xFF - $checksum;
$checksum = chr($checksum);
return $checksum;
}
/**
* Calculates lenth for cmdData. Leave off start byte, length and checksum
*
* @param String $data Should be a binary string
* @return String $length Should be a binary string
*/
protected function _getFramelength($data) {
$length = strlen($data);
$length = sprintf("%04x", $length);
$length = $this -> _packBytes($length);
return $length;
}
/**
* Transforms hex into a string
*
* @param String $hex
* @return String $string Should be a binary string
*/
protected function _hexstr($hex) {
$string = '';
for ($i=0; $i < strlen($hex); $i+=2) {
$string .= chr(hexdec($hex[$i] . $hex[$i+1]));
}
return $string;
}
/**
* Transforms string into hex
*
* @param String $str Should be a binary string
* @return String $hex Sould be a hex string
*/
protected function _strhex($str) {
$hex = '';
for ($i=0; $i < strlen($str); $i+=2) {
$hex .= dechex(ord($str[$i])) . dechex(ord($str[$i+1]));
}
return $hex;
}
/**
* Packs a string into binary for sending
*
* @param String $data
* @return String $data Should be a binary string
*/
protected function _packBytes($data) {
return pack('H*', $data);
}
/**
* Unpacks bytes into an array
*
* @param String $data Should be a binary string
* @return Array $data
*/
protected function _unpackBytes($data) {
return unpack('H*', $data);
}
/**
* Sets raw frame, including start byte etc
*
* @param String $frame
* @return void
*/
public function setFrame($frame) {
$this -> frame = $frame;
}
/**
* Gets raw frame data
*
* @return String $FrameData
*/
public function getFrame() {
return $this -> frame;
}
/**
* Sets FrameId according to XBee API
*
* @param String $frameId
* @return void
*/
public function setFrameId($frameId) {
$this -> frameId = $frameId;
}
/**
* Gets frame ID according to XBee API
*
* @return String $frameId
*/
public function getFrameId() {
return $this -> frameId;
}
/**
* Sets ApiId according to XBee API
*
* @param String $apiId
*/
public function setApiId($apiId) {
$this -> apiId = $apiId;
}
/**
* Gets API ID
*
* @return String $apiId
*/
public function getApiId() {
return $this -> apiId;
}
/**
* Sets raw command data, without start byte etc
*
* @param String $cmdData
* @return void
*/
public function setCmdData($cmdData) {
$this -> cmdData = $this -> _packBytes($cmdData);
}
/**
* Gets raw command data, without start byte etc
*
* @return String $cmdData
*/
public function getCmdData() {
return $this -> cmdData;
}
/**
* Sets Start Byte according to XBee API, defaults to 7E
*
* @param String $startByte
*/
public function setStartByte($startByte) {
$this -> startByte = $this -> _packBytes($startByte);
}
/**
* Gets Start Byte according to XBee API, default is 7E
*
* @return String $startByte
*/
public function getStartByte() {
return $this -> startByte;
}
/**
* Sets the 16 bit address
*
* @param String $address16
*/
public function setAddress16($address16) {
$this->address16 = $address16;
}
/**
* Gets the 16 bit address
*
* @return String $address16
*/
public function getAddress16() {
return $this->address16;
}
/**
* Sets the 64 bit address
*
* @param String $address64
*/
public function setAddress64($address64) {
$this->address64 = $address64;
}
/**
* Gets the 64 bit address
*
* @param String $address64
*/
public function getAddress64() {
return $this->address64;
}
/**
* Sets the options of the frame
*
* @param String $options
*/
public function setOptions($options) {
$this->options = $options;
}
/**
* Gets the options of the frame
*
* @return String $options
*/
public function getOptions() {
return $this->options;
}
/**
* Sets the command
*
* @param String $cmd
*/
public function setCmd($cmd) {
$this -> cmd = $cmd;
}
/**
* Gets the command
*
* @return String $cmd
*/
public function getCmd() {
return $this -> cmd;
}
/**
* Sets the value of a packet
*
* @param String $val
*/
public function setValue($val) {
$this -> val = $val;
}
/**
* Gets value of value
*
* @return String $val
*/
public function getValue() {
return $this -> val;
}
}
/**
* XbeeFrame represents a frame to be sent.
*
* @package XBeeFrame
*/
class XBeeFrame extends _XBeeFrameBase {
public function XBeeFrame() {
parent::_XBeeFrameBase();
}
/**
* Represesnts a remote AT Command according to XBee API.
* 64 bit address defaults to eight 00 bytes and $options defaults to 02 immediate
* Assembles frame for sending.
*
* @param $address16, $cmd, $val, $address64, $options
* @return void
*/
public function remoteAtCommand($address16, $cmd, $val, $address64 = '0000000000000000', $options = '02') {
$this -> setApiId(_XBeeFrameBase::REMOTE_API_ID);
$this -> setAddress16($address16);
$this -> setAddress64($address64);
$this -> setOptions($options);
$this -> setCmd($this -> _strhex($cmd));
$this -> setValue($val);
$this -> setCmdData(
$this -> getApiId() .
$this -> getFrameId() .
$this -> getAddress64() .
$this ->getAddress16() .
$this -> getOptions() .
$this -> getCmd() .
$this -> getValue()
);
$this -> _assembleFrame();
}
/**
* Represesnts a local AT Command according to XBee API.
* Takes command and value, value defaults to nothing
*
* @param String $cmd, String $val
* @return void
*/
public function localAtCommand($cmd, $val = '') {
$this -> setApiId(_XBeeFrameBase::LOCAL_API_ID);
$this -> setCmd($this ->_strhex($cmd));
$this -> setCmdData(
$this -> getApiId() .
$this -> getFrameId() .
$this -> getCmd() .
$this -> getValue()
);
$this -> _assembleFrame();
}
/**
* Not Implemented, do not use
*/
public function queuedAtCommand() {
$this -> setApiId(_XBeeFrameBase::QUEUED_API_ID);
trigger_error('queued_at not implemented', E_USER_ERROR);
}
/**
* Not Implemented, do not use
*/
public function txCommand() {
$this -> setApiId(_XBeeFrameBase::TX_API_ID);
trigger_error('tx not implemented', E_USER_ERROR);
}
/**
* Not Implemented, do not use
*/
public function txExplicityCommand() {
$this -> setApiId(_XBeeFrameBase::TX_EXPLICIT_API_ID);
trigger_error('tx_explicit not implemented', E_USER_ERROR);
}
}
/**
* XBeeResponse represents a response to a frame that has been sent.
*
* @package XBeeResponse
*/
class XBeeResponse extends _XBeeFrameBase {
const REMOTE_RESPONSE_ID = '97', LOCAL_RESPONSE_ID = '88';
protected $address16, $address64, $status, $cmd, $nodeId, $signalStrength;
protected $status_bytes = array();
/**
* Constructor. Sets up an XBeeResponse
*
* @param String $response A single frame of response from an XBee
*/
public function XBeeResponse($response) {
parent::_XBeeFrameBase();
$this->status_byte = array('00' => 'OK','01' => 'Error','02'=> 'Invalid Command', '03' => 'Invalid Parameter', '04' => 'No Response' );
$this -> _parse($response);
if ($this -> getApiId() === XBeeResponse::REMOTE_RESPONSE_ID) {
$this -> _parseRemoteAt();
} else if ($this -> getApiId() === XBeeResponse::LOCAL_RESPONSE_ID) {
$this -> _parseLocalAt();
} else {
trigger_error('Could not determine response type or response type is not implemented.', E_USER_WARNING);
}
/* debug
echo '</br>';echo 'Response:';print_r($response);echo '</br>';
echo ' apiId:';print_r($this->getApiId());echo '</br>';echo ' frameId:';print_r($this->getFrameId());echo '</br>';
echo ' add64:';print_r($this->getAddress64());echo '</br>';echo ' add16:';print_r($this->getAddress16());echo '</br>';
echo ' DB:';print_r($this->getSignalStrength());echo '</br>';echo ' NI:';print_r($this->getNodeId());echo '</br>';
echo ' CMD:';print_r($this->getCmd());echo '</br>';echo ' Status:';print_r($this->getStatus());echo '</br>';
echo ' isOk:';print_r($this->isOk());echo '</br>';*/
}
/**
* Parses the command data from the length and checksum
*
* @param String $response A XBee frame response from an XBee
* @return void
*/
private function _parse($response) {
$length = substr($response, 0, 4);
$checksum = substr($response, -2);
$cmdData = substr($response, 4, -2);
$apiId = substr($cmdData, 0, 2);
$frameId = substr($cmdData, 2, 2);
$calculatedChecksum = $this -> _calcChecksum($this -> _packBytes($cmdData));
$calculatedLength = $this -> _getFramelength($this -> _packBytes($cmdData));
$packedChecksum = $this->_packBytes($checksum); //pack for comparison
$packedLength = $this->_packBytes($length); //pack for comparison
if ($packedChecksum === $calculatedChecksum && $packedLength === $calculatedLength) {
$this -> setApiId($apiId);
$cmdData = $this->_unpackBytes($cmdData);
$cmdData=$cmdData[1];
$this -> setCmdData($cmdData);
$this -> setFrameId($frameId);
$this -> setFrame($response);
} else {
trigger_error('Checksum or length check failed.', E_USER_WARNING);
}
}
/**
* Parses remote At command
*
* @return void
*/
private function _parseRemoteAt() {
//A valid remote frame looks like this:
//<apiId1> <frameId1> <address64,8> <address16,8> <command,2> <status,2>
$cmdData = $this->getCmdData();
$cmd = substr($cmdData, 24, 4);
$cmd = $this->_hexstr($cmd);
$frameId = substr($cmdData, 2, 2);
$status = substr($cmdData, 4, 2);
$address64 = substr($cmdData, 4, 16);
$address16 = substr($cmdData, 20, 4);
$signalStrength = substr($cmdData, 30, 2);
$this->_setSignalStrength($signalStrength);
$this->setAddress16($address16);
$this->setAddress64($address64);
$this->_setCmd($cmd);
$this->_setStatus($status);
$this->setFrameId($frameId);
}
/**
* Parses a Local At Command response
*
* @return void
*/
private function _parseLocalAt() {
//A valid local frame looks like this:
//<api_id1> <frameId1> <command2> <status2> <add16> <add64> <DB> <NI> <NULL>
$cmdData = $this->getCmdData();
$cmd = substr($cmdData, 4, 6);
$cmd = $this->_hexstr($cmd);
$frameId = substr($cmdData, 2, 2);
$status = substr($cmdData, 8, 2);
$address64 = substr($cmdData, 14, 16);
$address16 = substr($cmdData, 10, 4);
$signalStrength = substr($cmdData, 30, 2);
$nodeId = $this->_hexstr(substr($cmdData, 32, -2));
$this -> _setNodeId($nodeId);
$this->_setSignalStrength($signalStrength);
$this->setAddress16($address16);
$this->setAddress64($address64);
$this->_setCmd($cmd);
$this->_setStatus($status);
$this->setFrameId($frameId);
}
/**
* Gets signal strength in dB
*
* @return String $signalStrength
*/
public function getSignalStrength() {
return $this -> signalStrength;
}
/**
* Sets signal strength
*
* @param String $strength
*/
private function _setSignalStrength($strength) {
$this->signalStrength = $strength;
}
/**
* Gets Node ID aka NI
*
* @return String $nodeId
*/
public function getNodeId() {
return $this->nodeId;
}
/**
* Sets Node ID aka NI
*
* @param String $nodeId
*/
private function _setNodeId($nodeId) {
$this->nodeId = $nodeId;
}
/**
* Sets status
*
* @param int $status
*/
private function _setStatus($status) {
$this->status = $status;
}
/**
* Returns status. If you want boolean use isOk
*
* 00 = OK
* 01 = Error
* 02 = Invalid Command
* 03 = Invalid Parameter
* 04 = No Response
*
* @return int $status
*/
public function getStatus() {
return $this->status;
}
/**
* Checks if this resonse was positive
*
* @return boolean
*/
public function isOk() {
if ($this->getStatus()=='00') {
return TRUE;
} else {
return FALSE;
}
}
/**
* Sets the command for this frame
*
* @return void
* @param String $cmd The Xbee Command
*/
private function _setCmd($cmd) {
$this->cmd = $cmd;
}
/**
* Returns command.
*
* @return String $cmd
*/
public function getCmd() {
return $this->cmd;
}
}
?> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.