answer stringlengths 15 1.25M |
|---|
// Compiled by ClojureScript 0.0-2197
goog.provide('cljs.core.async.impl.channels');
goog.require('cljs.core');
goog.require('cljs.core.async.impl.buffers');
goog.require('cljs.core.async.impl.buffers');
goog.require('cljs.core.async.impl.dispatch');
goog.require('cljs.core.async.impl.dispatch');
goog.require('cljs.core.async.impl.protocols');
goog.require('cljs.core.async.impl.protocols');
cljs.core.async.impl.channels.box = (function box(val){if(typeof cljs.core.async.impl.channels.t13280 !== 'undefined')
{} else
{
/**
* @constructor
*/
cljs.core.async.impl.channels.t13280 = (function (val,box,meta13281){
this.val = val;
this.box = box;
this.meta13281 = meta13281;
this.cljs$lang$protocol_mask$partition1$ = 0;
this.cljs$lang$protocol_mask$partition0$ = 425984;
})
cljs.core.async.impl.channels.t13280.cljs$lang$type = true;
cljs.core.async.impl.channels.t13280.cljs$lang$ctorStr = "cljs.core.async.impl.channels/t13280";
cljs.core.async.impl.channels.t13280.cljs$lang$ctorPrWriter = (function (this__4029__auto__,<API key>,opt__4031__auto__){return cljs.core._write.call(null,<API key>,"cljs.core.async.impl.channels/t13280");
});
cljs.core.async.impl.channels.t13280.prototype.cljs$core$IDeref$_deref$arity$1 = (function (_){var self__ = this;
var ___$1 = this;return self__.val;
});
cljs.core.async.impl.channels.t13280.prototype.cljs$core$IMeta$_meta$arity$1 = (function (_13282){var self__ = this;
var _13282__$1 = this;return self__.meta13281;
});
cljs.core.async.impl.channels.t13280.prototype.cljs$core$IWithMeta$_with_meta$arity$2 = (function (_13282,meta13281__$1){var self__ = this;
var _13282__$1 = this;return (new cljs.core.async.impl.channels.t13280(self__.val,self__.box,meta13281__$1));
});
cljs.core.async.impl.channels.__GT_t13280 = (function __GT_t13280(val__$1,box__$1,meta13281){return (new cljs.core.async.impl.channels.t13280(val__$1,box__$1,meta13281));
});
}
return (new cljs.core.async.impl.channels.t13280(val,box,null));
});
/**
* @constructor
*/
cljs.core.async.impl.channels.PutBox = (function (handler,val){
this.handler = handler;
this.val = val;
})
cljs.core.async.impl.channels.PutBox.cljs$lang$type = true;
cljs.core.async.impl.channels.PutBox.cljs$lang$ctorStr = "cljs.core.async.impl.channels/PutBox";
cljs.core.async.impl.channels.PutBox.cljs$lang$ctorPrWriter = (function (this__4032__auto__,<API key>,opts__4034__auto__){return cljs.core._write.call(null,<API key>,"cljs.core.async.impl.channels/PutBox");
});
cljs.core.async.impl.channels.__GT_PutBox = (function __GT_PutBox(handler,val){return (new cljs.core.async.impl.channels.PutBox(handler,val));
});
cljs.core.async.impl.channels.put_active_QMARK_ = (function put_active_QMARK_(box){return cljs.core.async.impl.protocols.active_QMARK_.call(null,box.handler);
});
cljs.core.async.impl.channels.MAX_DIRTY = 64;
/**
* @constructor
*/
cljs.core.async.impl.channels.ManyToManyChannel = (function (takes,dirty_takes,puts,dirty_puts,buf,closed){
this.takes = takes;
this.dirty_takes = dirty_takes;
this.puts = puts;
this.dirty_puts = dirty_puts;
this.buf = buf;
this.closed = closed;
})
cljs.core.async.impl.channels.ManyToManyChannel.cljs$lang$type = true;
cljs.core.async.impl.channels.ManyToManyChannel.cljs$lang$ctorStr = "cljs.core.async.impl.channels/ManyToManyChannel";
cljs.core.async.impl.channels.ManyToManyChannel.cljs$lang$ctorPrWriter = (function (this__4029__auto__,<API key>,opt__4031__auto__){return cljs.core._write.call(null,<API key>,"cljs.core.async.impl.channels/ManyToManyChannel");
});
cljs.core.async.impl.channels.ManyToManyChannel.prototype.cljs$core$async$impl$protocols$Channel$ = true;
cljs.core.async.impl.channels.ManyToManyChannel.prototype.cljs$core$async$impl$protocols$Channel$close_BANG_$arity$1 = (function (this$){var self__ = this;
var this$__$1 = this;if(self__.closed)
{return null;
} else
{self__.closed = true;
while(true){
var taker_13283 = self__.takes.pop();if((taker_13283 == null))
{} else
{if(cljs.core.async.impl.protocols.active_QMARK_.call(null,taker_13283))
{var take_cb_13284 = cljs.core.async.impl.protocols.commit.call(null,taker_13283);cljs.core.async.impl.dispatch.run.call(null,((function (take_cb_13284,taker_13283,this$__$1){
return (function (){return take_cb_13284.call(null,null);
});})(take_cb_13284,taker_13283,this$__$1))
);
} else
{}
{
continue;
}
}
break;
}
return null;
}
});
cljs.core.async.impl.channels.ManyToManyChannel.prototype.cljs$core$async$impl$protocols$ReadPort$ = true;
cljs.core.async.impl.channels.ManyToManyChannel.prototype.cljs$core$async$impl$protocols$ReadPort$take_BANG_$arity$2 = (function (this$,handler){var self__ = this;
var this$__$1 = this;if(!(cljs.core.async.impl.protocols.active_QMARK_.call(null,handler)))
{return null;
} else
{if((!((self__.buf == null))) && ((cljs.core.count.call(null,self__.buf) > 0)))
{var _ = cljs.core.async.impl.protocols.commit.call(null,handler);return cljs.core.async.impl.channels.box.call(null,cljs.core.async.impl.protocols.remove_BANG_.call(null,self__.buf));
} else
{while(true){
var putter = self__.puts.pop();if(!((putter == null)))
{var put_handler = putter.handler;var val = putter.val;if(cljs.core.async.impl.protocols.active_QMARK_.call(null,put_handler))
{var put_cb = cljs.core.async.impl.protocols.commit.call(null,put_handler);var _ = cljs.core.async.impl.protocols.commit.call(null,handler);cljs.core.async.impl.dispatch.run.call(null,put_cb);
return cljs.core.async.impl.channels.box.call(null,val);
} else
{{
continue;
}
}
} else
{if(self__.closed)
{var _ = cljs.core.async.impl.protocols.commit.call(null,handler);return cljs.core.async.impl.channels.box.call(null,null);
} else
{if((self__.dirty_takes > cljs.core.async.impl.channels.MAX_DIRTY))
{self__.dirty_takes = 0;
self__.takes.cleanup(cljs.core.async.impl.protocols.active_QMARK_);
} else
{self__.dirty_takes = (self__.dirty_takes + 1);
}
if((self__.takes.length < cljs.core.async.impl.protocols.MAX_QUEUE_SIZE))
{} else
{throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str([cljs.core.str("No more than "),cljs.core.str(cljs.core.async.impl.protocols.MAX_QUEUE_SIZE),cljs.core.str(" pending takes are allowed on a single channel.")].join('')),cljs.core.str("\n"),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"<","<",-1640531467,null),cljs.core.list(new cljs.core.Symbol(null,".-length",".-length",1395928862,null),new cljs.core.Symbol(null,"takes","takes",-1530407291,null)),new cljs.core.Symbol("impl","MAX-QUEUE-SIZE","impl/MAX-QUEUE-SIZE",-1989946393,null))))].join('')));
}
self__.takes.unbounded_unshift(handler);
return null;
}
}
break;
}
}
}
});
cljs.core.async.impl.channels.ManyToManyChannel.prototype.cljs$core$async$impl$protocols$WritePort$ = true;
cljs.core.async.impl.channels.ManyToManyChannel.prototype.cljs$core$async$impl$protocols$WritePort$put_BANG_$arity$3 = (function (this$,val,handler){var self__ = this;
var this$__$1 = this;if(!((val == null)))
{} else
{throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str("Can't put nil in on a channel"),cljs.core.str("\n"),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"not","not",-1640422260,null),cljs.core.list(new cljs.core.Symbol(null,"nil?","nil?",-1637150201,null),new cljs.core.Symbol(null,"val","val",-1640415014,null)))))].join('')));
}
var closed__$1 = self__.closed;if((closed__$1) || (!(cljs.core.async.impl.protocols.active_QMARK_.call(null,handler))))
{return cljs.core.async.impl.channels.box.call(null,null);
} else
{while(true){
var taker = self__.takes.pop();if(!((taker == null)))
{if(cljs.core.async.impl.protocols.active_QMARK_.call(null,taker))
{var take_cb = cljs.core.async.impl.protocols.commit.call(null,taker);var _ = cljs.core.async.impl.protocols.commit.call(null,handler);cljs.core.async.impl.dispatch.run.call(null,((function (take_cb,_,taker,closed__$1,this$__$1){
return (function (){return take_cb.call(null,val);
});})(take_cb,_,taker,closed__$1,this$__$1))
);
return cljs.core.async.impl.channels.box.call(null,null);
} else
{{
continue;
}
}
} else
{if(!(((self__.buf == null)) || (cljs.core.async.impl.protocols.full_QMARK_.call(null,self__.buf))))
{var _ = cljs.core.async.impl.protocols.commit.call(null,handler);cljs.core.async.impl.protocols.add_BANG_.call(null,self__.buf,val);
return cljs.core.async.impl.channels.box.call(null,null);
} else
{if((self__.dirty_puts > cljs.core.async.impl.channels.MAX_DIRTY))
{self__.dirty_puts = 0;
self__.puts.cleanup(cljs.core.async.impl.channels.put_active_QMARK_);
} else
{self__.dirty_puts = (self__.dirty_puts + 1);
}
if((self__.puts.length < cljs.core.async.impl.protocols.MAX_QUEUE_SIZE))
{} else
{throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str([cljs.core.str("No more than "),cljs.core.str(cljs.core.async.impl.protocols.MAX_QUEUE_SIZE),cljs.core.str(" pending puts are allowed on a single channel."),cljs.core.str(" Consider using a windowed buffer.")].join('')),cljs.core.str("\n"),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,"<","<",-1640531467,null),cljs.core.list(new cljs.core.Symbol(null,".-length",".-length",1395928862,null),new cljs.core.Symbol(null,"puts","puts",-1637078787,null)),new cljs.core.Symbol("impl","MAX-QUEUE-SIZE","impl/MAX-QUEUE-SIZE",-1989946393,null))))].join('')));
}
self__.puts.unbounded_unshift((new cljs.core.async.impl.channels.PutBox(handler,val)));
return null;
}
}
break;
}
}
});
cljs.core.async.impl.channels.<API key> = (function <API key>(takes,dirty_takes,puts,dirty_puts,buf,closed){return (new cljs.core.async.impl.channels.ManyToManyChannel(takes,dirty_takes,puts,dirty_puts,buf,closed));
});
cljs.core.async.impl.channels.chan = (function chan(buf){return (new cljs.core.async.impl.channels.ManyToManyChannel(cljs.core.async.impl.buffers.ring_buffer.call(null,32),0,cljs.core.async.impl.buffers.ring_buffer.call(null,32),0,buf,null));
}); |
package org.eclipse.kapua.service.elasticsearch.client.exception;
import org.eclipse.kapua.service.elasticsearch.client.<API key>;
/**
* {@link ClientException} to throw when {@link <API key>} fails to initialize.
*
* @since 1.3.0
*/
public class <API key> extends ClientException {
private static final long serialVersionUID = <API key>;
private final String reason;
/**
* Constructor.
*
* @param reason The reason of the exception.
* @since 1.3.0
*/
public <API key>(String reason) {
this(null, reason);
}
/**
* Constructor.
*
* @param cause The root {@link Throwable} of this {@link <API key>}.
* @param reason The reason of the exception.
* @since 1.3.0
*/
public <API key>(Throwable cause, String reason) {
super(ClientErrorCodes.<API key>, cause);
this.reason = reason;
}
/**
* Gets the reason of the initialization error.
*
* @return The reason of the initialization error.
* @since 1.3.0
*/
public String getReason() {
return reason;
}
} |
package com.planetmayo.debrief.satc.model.contributions;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import org.junit.Test;
import com.planetmayo.debrief.satc.model.ModelTestBase;
import com.planetmayo.debrief.satc.model.legs.StraightRoute;
import com.planetmayo.debrief.satc.model.states.BoundedState;
import com.planetmayo.debrief.satc.model.states.ProblemSpace;
import com.planetmayo.debrief.satc.support.TestSupport;
import com.planetmayo.debrief.satc.util.GeoSupport;
import com.planetmayo.debrief.satc.util.ObjectUtils;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.Point;
@SuppressWarnings("deprecation")
public class <API key> extends ModelTestBase
{
public static final String THE_PATH = "tests/com/planetmayo/debrief/satc/model/contributions/data/<API key>.txt";
public static final String THE_SHORT_PATH = "tests/com/planetmayo/debrief/satc/model/contributions/data/<API key>.txt";
private <API key> bmc;
@Test
public void testLoadFrom() throws Exception
{
bmc = new <API key>();
assertFalse("should be empty", bmc.hasData());
bmc.loadFrom(TestSupport.getShortData());
assertTrue("should not be empty", bmc.hasData());
assertEquals("correct start date", new Date(110, 00, 12, 12, 13, 29),
bmc.getStartDate());
assertEquals("correct finish date", new Date(110, 00, 12, 12, 24, 29),
bmc.getFinishDate());
assertEquals(Math.toRadians(3d), bmc.getBearingError(), EPS);
}
@Test
public void testActUpon() throws Exception
{
testLoadFrom();
ProblemSpace ps = new ProblemSpace();
bmc.actUpon(ps);
for (BoundedState state : ps.states())
{
Geometry geo = state.getLocation().getGeometry();
Coordinate[] coords = geo.getCoordinates();
for (int i = 0; i <= 4; i++)
{
Coordinate coordinate = coords[i];
assertNotNull("we should have a coordinate", coordinate);
}
}
assertEquals("read in all lines", 5, ps.size());
}
@Test
public void testErrorCalc()
{
bmc = new <API key>();
bmc.loadFrom(TestSupport.getLongData());
double score;
// ok, create a well-performing route to use
Point startP = GeoSupport.getFactory().createPoint(new Coordinate(-30.005, 0.010));
Date startT = ObjectUtils.safeParseDate(new SimpleDateFormat("yyMMdd HHmmss"),
"100112 121300");
Point endP = GeoSupport.getFactory().createPoint(new Coordinate(-30.075, 0.010));
Date endT = ObjectUtils.safeParseDate(new SimpleDateFormat("yyMMdd HHmmss"),
"100112 122836");
StraightRoute goodRoute = new StraightRoute("rName", startP, startT, endP,
endT);
// and a performing route to use
startP = GeoSupport.getFactory().createPoint(new Coordinate(-30.003, -0.05));
startT = ObjectUtils.safeParseDate(new SimpleDateFormat("yyMMdd HHmmss"),
"100112 121300");
endP = GeoSupport.getFactory().createPoint(new Coordinate(-30.075, 0.010));
endT = ObjectUtils.safeParseDate(new SimpleDateFormat("yyMMdd HHmmss"), "100112 122836");
StraightRoute badRoute = new StraightRoute("rName", startP, startT, endP,
endT);
// we'll need some states, so the route can correctly segment itself
ArrayList<BoundedState> states = new ArrayList<BoundedState>();
// inject some early states for which there isn't a measurement
states.add(new BoundedState(parseDate("yyMMdd HHmmss", "100112 121300")));
states.add(new BoundedState(parseDate("yyMMdd HHmmss", "100112 121301")));
// now for our real states
states.add(new BoundedState(parseDate("yyMMdd HHmmss", "100112 121459")));
states.add(new BoundedState(parseDate("yyMMdd HHmmss", "100112 121629")));
states.add(new BoundedState(parseDate("yyMMdd HHmmss", "100112 121814")));
// inject a state for which there isn't a measurement
states.add(new BoundedState(parseDate("yyMMdd HHmmss", "100112 122300")));
// and carry on
states.add(new BoundedState(parseDate("yyMMdd HHmmss", "100112 122329")));
states.add(new BoundedState(parseDate("yyMMdd HHmmss", "100112 122829")));
// inject some late states for which there isn't a measurement
states.add(new BoundedState(parseDate("yyMMdd HHmmss", "100112 122832")));
states.add(new BoundedState(parseDate("yyMMdd HHmmss", "100112 122836")));
// test when we shouldn't run
bmc.setActive(false);
bmc.setWeight(0);
score = bmc.<API key>(null);
assertEquals("should not be able to calc", 0, score, 0.0001);
// ok, make it active
bmc.setActive(true);
score = bmc.<API key>(null);
assertEquals("still should not be able to calc", 0, score, 0.0001);
// ok, let it start
bmc.setWeight(1);
score = bmc.<API key>(null);
assertEquals("still should not be able to calc", 0, score, 0.0001);
score = bmc.<API key>(goodRoute);
assertEquals("still should not be able to calc", 0, score, 0.0001);
// ok, flesh out the routes
goodRoute.generateSegments(states);
badRoute.generateSegments(states);
score = bmc.<API key>(goodRoute);
// NOTE: BMC no longer produces an error score. The bearing isn't a forecast, it's an absolute measurement.
// assertTrue("still should not be able to calc", 0 != score);
// System.out.println("good score:" + score);
// score = bmc.<API key>(badRoute);
// assertTrue("still should not be able to calc", 0 != score);
// System.out.println("bad score:" + score);
}
} |
/**
* @file
*
* @brief RTEMS Rate Monotonic Get Status
* @ingroup ClassicRateMon
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <rtems/system.h>
#include <rtems/rtems/status.h>
#include <rtems/rtems/support.h>
#include <rtems/score/isr.h>
#include <rtems/score/object.h>
#include <rtems/rtems/ratemon.h>
#include <rtems/score/thread.h>
#ifndef <API key>
#include <rtems/score/timespec.h>
#endif
rtems_status_code <API key>(
rtems_id id,
<API key> *status
)
{
Thread_CPU_usage_t executed;
Objects_Locations location;
<API key> since_last_period;
<API key> *the_period;
bool valid_status;
if ( !status )
return <API key>;
the_period = _Rate_monotonic_Get( id, &location );
switch ( location ) {
case OBJECTS_LOCAL:
status->owner = the_period->owner->Object.id;
status->state = the_period->state;
/*
* If the period is inactive, there is no information.
*/
if ( status->state == <API key> ) {
#ifndef <API key>
<API key>( &status->since_last_period );
<API key>( &status-><API key> );
#else
status->since_last_period = 0;
status-><API key> = 0;
#endif
} else {
/*
* Grab the current status.
*/
valid_status =
<API key>(
the_period, &since_last_period, &executed
);
if (!valid_status) {
<API key>();
return RTEMS_NOT_DEFINED;
}
#ifndef <API key>
<API key>(
&since_last_period, &status->since_last_period
);
<API key>(
&executed, &status-><API key>
);
#else
status->since_last_period = since_last_period;
status-><API key> = executed;
#endif
}
<API key>();
return RTEMS_SUCCESSFUL;
#if defined(<API key>)
case OBJECTS_REMOTE: /* should never return this */
#endif
case OBJECTS_ERROR:
break;
}
return RTEMS_INVALID_ID;
} |
<!DOCTYPE html>
<html>
<body>
<div id="result"></div>
<script>
// Check browser support
if (typeof(Storage) != "undefined") {
// Store
localStorage.getItem("result");
//localStorage.setItem("lastname", "Smith1");
// Retrieve
//document.getElementById("result").innerHTML = localStorage.getItem("lastname");
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
</script>
<input type="text" value="Hello" name="name"/>
<a type="button" href="a.html">add</a>
</body>
</html> |
class <API key> < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
<API key> with: :exception
before_filter :<API key>, if: :devise_controller?
protected
def <API key>
<API key>.for(:account_update) << :avatar
end
end |
#include <stdbool.h>
/* Compile-time constants. */
#define HEAP_MIN_SIZE (32*1024)
#ifndef HEAP_MAX_SIZE
# ifdef <API key>
# define HEAP_MAX_SIZE (2 * <API key>)
# else
# define HEAP_MAX_SIZE (1024*1024) /* must be a power of two */
# endif
#endif
/* HEAP_MIN_SIZE and HEAP_MAX_SIZE limit the size of mmap()ed heaps
that are dynamically created for multi-threaded programs. The
maximum size must be a power of two, for fast determination of
which heap belongs to a chunk. It should be much larger than the
mmap threshold, so that requests with a size just below that
threshold can be fulfilled without creating too many heaps. */
#ifndef THREAD_STATS
#define THREAD_STATS 0
#endif
/* If THREAD_STATS is non-zero, some statistics on mutex locking are
computed. */
#define top(ar_ptr) ((ar_ptr)->top)
/* A heap is a single contiguous memory region holding (coalesceable)
malloc_chunks. It is allocated with mmap() and always starts at an
address aligned to HEAP_MAX_SIZE. */
typedef struct _heap_info {
mstate ar_ptr; /* Arena for this heap. */
struct _heap_info *prev; /* Previous heap. */
size_t size; /* Current size in bytes. */
size_t mprotect_size; /* Size in bytes that has been mprotected
PROT_READ|PROT_WRITE. */
/* Make sure the following data is properly aligned, particularly
that sizeof (heap_info) + 2 * SIZE_SZ is a multiple of
MALLOC_ALIGNMENT. */
char pad[-6 * SIZE_SZ & MALLOC_ALIGN_MASK];
} heap_info;
/* Get a compile-time error if the heap_info padding is not correct
to make alignment work as expected in sYSMALLOc. */
extern int <API key>[(sizeof (heap_info)
+ 2 * SIZE_SZ) % MALLOC_ALIGNMENT
? -1 : 1];
/* Thread specific data */
static tsd_key_t arena_key;
static mutex_t list_lock = MUTEX_INITIALIZER;
#ifdef PER_THREAD
static size_t narenas = 1;
static mstate free_list;
#endif
#if THREAD_STATS
static int stat_n_heaps;
#define THREAD_STAT(x) x
#else
#define THREAD_STAT(x) do ; while(0)
#endif
/* Mapped memory in non-main arenas (reliable only for NO_THREADS). */
static unsigned long arena_mem;
/* Already initialized? */
int <API key> = -1;
/* arena_get() acquires an arena and locks the corresponding mutex.
First, try the one last locked successfully by this thread. (This
is the common case and handled with a macro for speed.) Then, loop
once over the circularly linked list of arenas. If no arena is
readily available, create a new one. In this latter case, `size'
is just a hint as to how much memory will be required immediately
in the new arena. */
#define arena_get(ptr, size) do { \
arena_lookup(ptr); \
arena_lock(ptr, size); \
} while(0)
#define arena_lookup(ptr) do { \
void *vptr = NULL; \
ptr = (mstate)tsd_getspecific(arena_key, vptr); \
} while(0)
#ifdef PER_THREAD
# define arena_lock(ptr, size) do { \
if(ptr) \
(void)mutex_lock(&ptr->mutex); \
else \
ptr = arena_get2(ptr, (size), NULL); \
} while(0)
#else
# define arena_lock(ptr, size) do { \
if(ptr && !mutex_trylock(&ptr->mutex)) { \
THREAD_STAT(++(ptr->stat_lock_direct)); \
} else \
ptr = arena_get2(ptr, (size), NULL); \
} while(0)
#endif
/* find the heap and corresponding arena for a given ptr */
#define heap_for_ptr(ptr) \
((heap_info *)((unsigned long)(ptr) & ~(HEAP_MAX_SIZE-1)))
#define arena_for_chunk(ptr) \
(<API key>(ptr) ? heap_for_ptr(ptr)->ar_ptr : &main_arena)
/* atfork support. */
static __malloc_ptr_t (*save_malloc_hook) (size_t __size,
const __malloc_ptr_t);
static void (*save_free_hook) (__malloc_ptr_t __ptr,
const __malloc_ptr_t);
static void* save_arena;
#ifdef ATFORK_MEM
ATFORK_MEM;
#endif
/* Magic value for the thread-specific arena pointer when
malloc_atfork() is in use. */
#define ATFORK_ARENA_PTR ((void*)-1)
/* The following hooks are used while the `atfork' handling mechanism
is active. */
static void*
malloc_atfork(size_t sz, const void *caller)
{
void *vptr = NULL;
void *victim;
tsd_getspecific(arena_key, vptr);
if(vptr == ATFORK_ARENA_PTR) {
/* We are the only thread that may allocate at all. */
if(save_malloc_hook != malloc_check) {
return _int_malloc(&main_arena, sz);
} else {
if(top_check()<0)
return 0;
victim = _int_malloc(&main_arena, sz+1);
return mem2mem_check(victim, sz);
}
} else {
/* Suspend the thread until the `atfork' handlers have completed.
By that time, the hooks will have been reset as well, so that
mALLOc() can be used again. */
(void)mutex_lock(&list_lock);
(void)mutex_unlock(&list_lock);
return __libc_malloc(sz);
}
}
static void
free_atfork(void* mem, const void *caller)
{
void *vptr = NULL;
mstate ar_ptr;
mchunkptr p; /* chunk corresponding to mem */
if (mem == 0) /* free(0) has no effect */
return;
p = mem2chunk(mem); /* do not bother to replicate free_check here */
if (chunk_is_mmapped(p)) /* release mmapped memory. */
{
munmap_chunk(p);
return;
}
ar_ptr = arena_for_chunk(p);
tsd_getspecific(arena_key, vptr);
_int_free(ar_ptr, p, vptr == ATFORK_ARENA_PTR, 1);
}
/* Counter for number of times the list is locked by the same thread. */
static unsigned int <API key>;
/* The following two functions are registered via thread_atfork() to
make sure that the mutexes remain in a consistent state in the
fork()ed version of a thread. Also adapt the malloc and free hooks
temporarily, because the `atfork' handler mechanism may use
malloc/free internally (e.g. in LinuxThreads). */
static void
ptmalloc_lock_all (void)
{
mstate ar_ptr;
if(<API key> < 1)
return;
if (mutex_trylock(&list_lock))
{
void *my_arena;
tsd_getspecific(arena_key, my_arena);
if (my_arena == ATFORK_ARENA_PTR)
/* This is the same thread which already locks the global list.
Just bump the counter. */
goto out;
/* This thread has to wait its turn. */
(void)mutex_lock(&list_lock);
}
for(ar_ptr = &main_arena;;) {
(void)mutex_lock(&ar_ptr->mutex);
ar_ptr = ar_ptr->next;
if(ar_ptr == &main_arena) break;
}
save_malloc_hook = __malloc_hook;
save_free_hook = __free_hook;
__malloc_hook = malloc_atfork;
__free_hook = free_atfork;
/* Only the current thread may perform malloc/free calls now. */
tsd_getspecific(arena_key, save_arena);
tsd_setspecific(arena_key, ATFORK_ARENA_PTR);
out:
++<API key>;
}
static void
ptmalloc_unlock_all (void)
{
mstate ar_ptr;
if(<API key> < 1)
return;
if (--<API key> != 0)
return;
tsd_setspecific(arena_key, save_arena);
__malloc_hook = save_malloc_hook;
__free_hook = save_free_hook;
for(ar_ptr = &main_arena;;) {
(void)mutex_unlock(&ar_ptr->mutex);
ar_ptr = ar_ptr->next;
if(ar_ptr == &main_arena) break;
}
(void)mutex_unlock(&list_lock);
}
#ifdef __linux__
/* In NPTL, unlocking a mutex in the child process after a
fork() is currently unsafe, whereas re-initializing it is safe and
does not leak resources. Therefore, a special atfork handler is
installed for the child. */
static void
<API key> (void)
{
mstate ar_ptr;
if(<API key> < 1)
return;
tsd_setspecific(arena_key, save_arena);
__malloc_hook = save_malloc_hook;
__free_hook = save_free_hook;
#ifdef PER_THREAD
free_list = NULL;
#endif
for(ar_ptr = &main_arena;;) {
mutex_init(&ar_ptr->mutex);
#ifdef PER_THREAD
if (ar_ptr != save_arena) {
ar_ptr->next_free = free_list;
free_list = ar_ptr;
}
#endif
ar_ptr = ar_ptr->next;
if(ar_ptr == &main_arena) break;
}
mutex_init(&list_lock);
<API key> = 0;
}
#else
#define <API key> ptmalloc_unlock_all
#endif
/* Initialization routine. */
#include <string.h>
extern char **_environ;
static char *
internal_function
next_env_entry (char ***position)
{
char **current = *position;
char *result = NULL;
while (*current != NULL)
{
if (__builtin_expect ((*current)[0] == 'M', 0)
&& (*current)[1] == 'A'
&& (*current)[2] == 'L'
&& (*current)[3] == 'L'
&& (*current)[4] == 'O'
&& (*current)[5] == 'C'
&& (*current)[6] == '_')
{
result = &(*current)[7];
/* Save current position for next visit. */
*position = ++current;
break;
}
++current;
}
return result;
}
#ifdef SHARED
static void *
__failing_morecore (ptrdiff_t d)
{
return (void *) MORECORE_FAILURE;
}
extern struct dl_open_hook *_dl_open_hook;
libc_hidden_proto (_dl_open_hook);
#endif
static void
ptmalloc_init (void)
{
if(<API key> >= 0) return;
<API key> = 0;
#ifdef SHARED
/* In case this libc copy is in a non-default namespace, never use brk.
Likewise if dlopened from statically linked program. */
Dl_info di;
struct link_map *l;
if (_dl_open_hook != NULL
|| (_dl_addr (ptmalloc_init, &di, &l, NULL) != 0
&& l->l_ns != LM_ID_BASE))
__morecore = __failing_morecore;
#endif
tsd_key_create(&arena_key, NULL);
tsd_setspecific(arena_key, (void *)&main_arena);
thread_atfork(ptmalloc_lock_all, ptmalloc_unlock_all, <API key>);
const char *s = NULL;
if (__builtin_expect (_environ != NULL, 1))
{
char **runp = _environ;
char *envline;
while (__builtin_expect ((envline = next_env_entry (&runp)) != NULL,
0))
{
size_t len = strcspn (envline, "=");
if (envline[len] != '=')
/* This is a "MALLOC_" variable at the end of the string
without a '=' character. Ignore it since otherwise we
will access invalid memory below. */
continue;
switch (len)
{
case 6:
if (memcmp (envline, "CHECK_", 6) == 0)
s = &envline[7];
break;
case 8:
if (! __builtin_expect (<API key>, 0))
{
if (memcmp (envline, "TOP_PAD_", 8) == 0)
__libc_mallopt(M_TOP_PAD, atoi(&envline[9]));
else if (memcmp (envline, "PERTURB_", 8) == 0)
__libc_mallopt(M_PERTURB, atoi(&envline[9]));
}
break;
case 9:
if (! __builtin_expect (<API key>, 0))
{
if (memcmp (envline, "MMAP_MAX_", 9) == 0)
__libc_mallopt(M_MMAP_MAX, atoi(&envline[10]));
#ifdef PER_THREAD
else if (memcmp (envline, "ARENA_MAX", 9) == 0)
__libc_mallopt(M_ARENA_MAX, atoi(&envline[10]));
#endif
}
break;
#ifdef PER_THREAD
case 10:
if (! __builtin_expect (<API key>, 0))
{
if (memcmp (envline, "ARENA_TEST", 10) == 0)
__libc_mallopt(M_ARENA_TEST, atoi(&envline[11]));
}
break;
#endif
case 15:
if (! __builtin_expect (<API key>, 0))
{
if (memcmp (envline, "TRIM_THRESHOLD_", 15) == 0)
__libc_mallopt(M_TRIM_THRESHOLD, atoi(&envline[16]));
else if (memcmp (envline, "MMAP_THRESHOLD_", 15) == 0)
__libc_mallopt(M_MMAP_THRESHOLD, atoi(&envline[16]));
}
break;
default:
break;
}
}
}
if(s && s[0]) {
__libc_mallopt(M_CHECK_ACTION, (int)(s[0] - '0'));
if (check_action != 0)
__malloc_check_init();
}
void (*hook) (void) = force_reg (<API key>);
if (hook != NULL)
(*hook)();
<API key> = 1;
}
/* There are platforms (e.g. Hurd) with a link-time hook mechanism. */
#ifdef <API key>
<API key>(ptmalloc_lock_all, ptmalloc_unlock_all, \
<API key>)
#endif
/* Managing heaps and arenas (for concurrent threads) */
#if MALLOC_DEBUG > 1
/* Print the complete contents of a single heap to stderr. */
static void
dump_heap(heap_info *heap)
{
char *ptr;
mchunkptr p;
fprintf(stderr, "Heap %p, size %10lx:\n", heap, (long)heap->size);
ptr = (heap->ar_ptr != (mstate)(heap+1)) ?
(char*)(heap + 1) : (char*)(heap + 1) + sizeof(struct malloc_state);
p = (mchunkptr)(((unsigned long)ptr + MALLOC_ALIGN_MASK) &
~MALLOC_ALIGN_MASK);
for(;;) {
fprintf(stderr, "chunk %p size %10lx", p, (long)p->size);
if(p == top(heap->ar_ptr)) {
fprintf(stderr, " (top)\n");
break;
} else if(p->size == (0|PREV_INUSE)) {
fprintf(stderr, " (fence)\n");
break;
}
fprintf(stderr, "\n");
p = next_chunk(p);
}
}
#endif /* MALLOC_DEBUG > 1 */
/* If consecutive mmap (0, HEAP_MAX_SIZE << 1, ...) calls return decreasing
addresses as opposed to increasing, new_heap would badly fragment the
address space. In that case remember the second HEAP_MAX_SIZE part
aligned to HEAP_MAX_SIZE from last mmap (0, HEAP_MAX_SIZE << 1, ...)
call (if it is already aligned) and try to reuse it next time. We need
no locking for it, as kernel ensures the atomicity for us - worst case
we'll call mmap (addr, HEAP_MAX_SIZE, ...) for some value of addr in
multiple threads, but only one will succeed. */
static char *aligned_heap_area;
/* Create a new heap. size is automatically rounded up to a multiple
of the page size. */
static heap_info *
internal_function
new_heap(size_t size, size_t top_pad)
{
size_t page_mask = GLRO(dl_pagesize) - 1;
char *p1, *p2;
unsigned long ul;
heap_info *h;
if(size+top_pad < HEAP_MIN_SIZE)
size = HEAP_MIN_SIZE;
else if(size+top_pad <= HEAP_MAX_SIZE)
size += top_pad;
else if(size > HEAP_MAX_SIZE)
return 0;
else
size = HEAP_MAX_SIZE;
size = (size + page_mask) & ~page_mask;
/* A memory region aligned to a multiple of HEAP_MAX_SIZE is needed.
No swap space needs to be reserved for the following large
mapping (on Linux, this is the case for all non-writable mappings
anyway). */
p2 = MAP_FAILED;
if(aligned_heap_area) {
p2 = (char *)MMAP(aligned_heap_area, HEAP_MAX_SIZE, PROT_NONE,
MAP_NORESERVE);
aligned_heap_area = NULL;
if (p2 != MAP_FAILED && ((unsigned long)p2 & (HEAP_MAX_SIZE-1))) {
__munmap(p2, HEAP_MAX_SIZE);
p2 = MAP_FAILED;
}
}
if(p2 == MAP_FAILED) {
p1 = (char *)MMAP(0, HEAP_MAX_SIZE<<1, PROT_NONE, MAP_NORESERVE);
if(p1 != MAP_FAILED) {
p2 = (char *)(((unsigned long)p1 + (HEAP_MAX_SIZE-1))
& ~(HEAP_MAX_SIZE-1));
ul = p2 - p1;
if (ul)
__munmap(p1, ul);
else
aligned_heap_area = p2 + HEAP_MAX_SIZE;
__munmap(p2 + HEAP_MAX_SIZE, HEAP_MAX_SIZE - ul);
} else {
/* Try to take the chance that an allocation of only HEAP_MAX_SIZE
is already aligned. */
p2 = (char *)MMAP(0, HEAP_MAX_SIZE, PROT_NONE, MAP_NORESERVE);
if(p2 == MAP_FAILED)
return 0;
if((unsigned long)p2 & (HEAP_MAX_SIZE-1)) {
__munmap(p2, HEAP_MAX_SIZE);
return 0;
}
}
}
if(__mprotect(p2, size, PROT_READ|PROT_WRITE) != 0) {
__munmap(p2, HEAP_MAX_SIZE);
return 0;
}
h = (heap_info *)p2;
h->size = size;
h->mprotect_size = size;
THREAD_STAT(stat_n_heaps++);
return h;
}
/* Grow a heap. size is automatically rounded up to a
multiple of the page size. */
static int
grow_heap(heap_info *h, long diff)
{
size_t page_mask = GLRO(dl_pagesize) - 1;
long new_size;
diff = (diff + page_mask) & ~page_mask;
new_size = (long)h->size + diff;
if((unsigned long) new_size > (unsigned long) HEAP_MAX_SIZE)
return -1;
if((unsigned long) new_size > h->mprotect_size) {
if (__mprotect((char *)h + h->mprotect_size,
(unsigned long) new_size - h->mprotect_size,
PROT_READ|PROT_WRITE) != 0)
return -2;
h->mprotect_size = new_size;
}
h->size = new_size;
return 0;
}
/* Shrink a heap. */
static int
shrink_heap(heap_info *h, long diff)
{
long new_size;
new_size = (long)h->size - diff;
if(new_size < (long)sizeof(*h))
return -1;
/* Try to re-map the extra heap space freshly to save memory, and
make it inaccessible. */
if (__builtin_expect (<API key>, 0))
{
if((char *)MMAP((char *)h + new_size, diff, PROT_NONE,
MAP_FIXED) == (char *) MAP_FAILED)
return -2;
h->mprotect_size = new_size;
}
else
madvise ((char *)h + new_size, diff, MADV_DONTNEED);
/*fprintf(stderr, "shrink %p %08lx\n", h, new_size);*/
h->size = new_size;
return 0;
}
/* Delete a heap. */
#define delete_heap(heap) \
do { \
if ((char *)(heap) + HEAP_MAX_SIZE == aligned_heap_area) \
aligned_heap_area = NULL; \
__munmap((char*)(heap), HEAP_MAX_SIZE); \
} while (0)
static int
internal_function
heap_trim(heap_info *heap, size_t pad)
{
mstate ar_ptr = heap->ar_ptr;
unsigned long pagesz = GLRO(dl_pagesize);
mchunkptr top_chunk = top(ar_ptr), p, bck, fwd;
heap_info *prev_heap;
long new_size, top_size, extra;
/* Can this heap go away completely? */
while(top_chunk == chunk_at_offset(heap, sizeof(*heap))) {
prev_heap = heap->prev;
p = chunk_at_offset(prev_heap, prev_heap->size - (MINSIZE-2*SIZE_SZ));
assert(p->size == (0|PREV_INUSE)); /* must be fencepost */
p = prev_chunk(p);
new_size = chunksize(p) + (MINSIZE-2*SIZE_SZ);
assert(new_size>0 && new_size<(long)(2*MINSIZE));
if(!prev_inuse(p))
new_size += p->prev_size;
assert(new_size>0 && new_size<HEAP_MAX_SIZE);
if(new_size + (HEAP_MAX_SIZE - prev_heap->size) < pad + MINSIZE + pagesz)
break;
ar_ptr->system_mem -= heap->size;
arena_mem -= heap->size;
delete_heap(heap);
heap = prev_heap;
if(!prev_inuse(p)) { /* consolidate backward */
p = prev_chunk(p);
unlink(p, bck, fwd);
}
assert(((unsigned long)((char*)p + new_size) & (pagesz-1)) == 0);
assert( ((char*)p + new_size) == ((char*)heap + heap->size) );
top(ar_ptr) = top_chunk = p;
set_head(top_chunk, new_size | PREV_INUSE);
/*check_chunk(ar_ptr, top_chunk);*/
}
top_size = chunksize(top_chunk);
extra = (top_size - pad - MINSIZE - 1) & ~(pagesz - 1);
if(extra < (long)pagesz)
return 0;
/* Try to shrink. */
if(shrink_heap(heap, extra) != 0)
return 0;
ar_ptr->system_mem -= extra;
arena_mem -= extra;
/* Success. Adjust top accordingly. */
set_head(top_chunk, (top_size - extra) | PREV_INUSE);
/*check_chunk(ar_ptr, top_chunk);*/
return 1;
}
/* Create a new arena with initial size "size". */
static mstate
_int_new_arena(size_t size)
{
mstate a;
heap_info *h;
char *ptr;
unsigned long misalign;
h = new_heap(size + (sizeof(*h) + sizeof(*a) + MALLOC_ALIGNMENT),
mp_.top_pad);
if(!h) {
/* Maybe size is too large to fit in a single heap. So, just try
to create a minimally-sized arena and let _int_malloc() attempt
to deal with the large request via mmap_chunk(). */
h = new_heap(sizeof(*h) + sizeof(*a) + MALLOC_ALIGNMENT, mp_.top_pad);
if(!h)
return 0;
}
a = h->ar_ptr = (mstate)(h+1);
malloc_init_state(a);
/*a->next = NULL;*/
a->system_mem = a->max_system_mem = h->size;
arena_mem += h->size;
/* Set up the top chunk, with proper alignment. */
ptr = (char *)(a + 1);
misalign = (unsigned long)chunk2mem(ptr) & MALLOC_ALIGN_MASK;
if (misalign > 0)
ptr += MALLOC_ALIGNMENT - misalign;
top(a) = (mchunkptr)ptr;
set_head(top(a), (((char*)h + h->size) - ptr) | PREV_INUSE);
tsd_setspecific(arena_key, (void *)a);
mutex_init(&a->mutex);
(void)mutex_lock(&a->mutex);
#ifdef PER_THREAD
(void)mutex_lock(&list_lock);
#endif
/* Add the new arena to the global list. */
a->next = main_arena.next;
<API key> ();
main_arena.next = a;
#ifdef PER_THREAD
(void)mutex_unlock(&list_lock);
#endif
THREAD_STAT(++(a->stat_lock_loop));
return a;
}
#ifdef PER_THREAD
static mstate
get_free_list (void)
{
mstate result = free_list;
if (result != NULL)
{
(void)mutex_lock(&list_lock);
result = free_list;
if (result != NULL)
free_list = result->next_free;
(void)mutex_unlock(&list_lock);
if (result != NULL)
{
(void)mutex_lock(&result->mutex);
tsd_setspecific(arena_key, (void *)result);
THREAD_STAT(++(result->stat_lock_loop));
}
}
return result;
}
/* Lock and return an arena that can be reused for memory allocation.
Avoid AVOID_ARENA as we have already failed to allocate memory in
it and it is currently locked. */
static mstate
reused_arena (mstate avoid_arena)
{
mstate result;
static mstate next_to_use;
if (next_to_use == NULL)
next_to_use = &main_arena;
result = next_to_use;
do
{
if (!mutex_trylock(&result->mutex))
goto out;
result = result->next;
}
while (result != next_to_use);
/* Avoid AVOID_ARENA as we have already failed to allocate memory
in that arena and it is currently locked. */
if (result == avoid_arena)
result = result->next;
/* No arena available. Wait for the next in line. */
(void)mutex_lock(&result->mutex);
out:
tsd_setspecific(arena_key, (void *)result);
THREAD_STAT(++(result->stat_lock_loop));
next_to_use = result->next;
return result;
}
#endif
static mstate
internal_function
arena_get2(mstate a_tsd, size_t size, mstate avoid_arena)
{
mstate a;
#ifdef PER_THREAD
static size_t narenas_limit;
a = get_free_list ();
if (a == NULL)
{
/* Nothing immediately available, so generate a new arena. */
if (narenas_limit == 0)
{
if (mp_.arena_max != 0)
narenas_limit = mp_.arena_max;
else if (narenas > mp_.arena_test)
{
int n = __get_nprocs ();
if (n >= 1)
narenas_limit = NARENAS_FROM_NCORES (n);
else
/* We have no information about the system. Assume two
cores. */
narenas_limit = NARENAS_FROM_NCORES (2);
}
}
repeat:;
size_t n = narenas;
/* NB: the following depends on the fact that (size_t)0 - 1 is a
very large number and that the underflow is OK. If arena_max
is set the value of arena_test is irrelevant. If arena_test
is set but narenas is not yet larger or equal to arena_test
narenas_limit is 0. There is no possibility for narenas to
be too big for the test to always fail since there is not
enough address space to create that many arenas. */
if (__builtin_expect (n <= narenas_limit - 1, 0))
{
if (<API key> (&narenas, n + 1, n))
goto repeat;
a = _int_new_arena (size);
if (__builtin_expect (a == NULL, 0))
catomic_decrement (&narenas);
}
else
a = reused_arena (avoid_arena);
}
#else
if(!a_tsd)
a = a_tsd = &main_arena;
else {
a = a_tsd->next;
if(!a) {
/* This can only happen while initializing the new arena. */
(void)mutex_lock(&main_arena.mutex);
THREAD_STAT(++(main_arena.stat_lock_wait));
return &main_arena;
}
}
/* Check the global, circularly linked list for available arenas. */
bool retried = false;
repeat:
do {
if(!mutex_trylock(&a->mutex)) {
if (retried)
(void)mutex_unlock(&list_lock);
THREAD_STAT(++(a->stat_lock_loop));
tsd_setspecific(arena_key, (void *)a);
return a;
}
a = a->next;
} while(a != a_tsd);
/* If not even the list_lock can be obtained, try again. This can
happen during `atfork', or for example on systems where thread
creation makes it temporarily impossible to obtain _any_
locks. */
if(!retried && mutex_trylock(&list_lock)) {
/* We will block to not run in a busy loop. */
(void)mutex_lock(&list_lock);
/* Since we blocked there might be an arena available now. */
retried = true;
a = a_tsd;
goto repeat;
}
/* Nothing immediately available, so generate a new arena. */
a = _int_new_arena(size);
(void)mutex_unlock(&list_lock);
#endif
return a;
}
#ifdef PER_THREAD
static void __attribute__ ((section ("<API key>")))
<API key> (void)
{
void *vptr = NULL;
mstate a = tsd_getspecific(arena_key, vptr);
tsd_setspecific(arena_key, NULL);
if (a != NULL)
{
(void)mutex_lock(&list_lock);
a->next_free = free_list;
free_list = a;
(void)mutex_unlock(&list_lock);
}
}
text_set_element (<API key>, <API key>);
#endif
/*
* Local variables:
* c-basic-offset: 2
* End:
*/ |
using System;
using System.Diagnostics;
using System.Threading;
namespace ICSharpCode.AvalonEdit.Utils
{
<summary>
Invokes an action when it is disposed.
</summary>
<remarks>
This class ensures the callback is invoked at most once,
even when Dispose is called on multiple threads.
</remarks>
sealed class CallbackOnDispose : IDisposable
{
Action action;
public CallbackOnDispose(Action action)
{
Debug.Assert(action != null);
this.action = action;
}
public void Dispose()
{
Action a = Interlocked.Exchange(ref action, null);
if (a != null) {
a();
}
}
}
} |
package com.aelitis.net.upnpms.impl;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import com.aelitis.net.upnpms.*;
public class
Test
{
private static void
dump(
UPNPMSContainer container,
String indent )
throws Exception
{
System.out.println( indent + container.getTitle() + " - " + container.getID());
indent += " ";
List<UPNPMSNode> kids = container.getChildren();
for ( UPNPMSNode kid: kids ){
if ( kid instanceof UPNPMSContainer ){
dump((UPNPMSContainer)kid, indent );
}else{
System.out.println( indent + kid.getTitle() + " - " + kid.getID());
}
}
}
public static void
main(
String[] args )
{
try{
UPNPMSBrowser browser =
new UPNPMSBrowserImpl(
"Vuze",
Arrays.asList( new URL[]{ new URL( "http://192.168.1.5:2869/upnphost/udhisapi.dll?control=uuid:<API key>+urn:upnp-org:serviceId:ContentDirectory" )}),
new <API key>()
{
public void
setPreferredURL(URL url)
{
}
});
UPNPMSContainer root = browser.getRoot();
dump( root, "" );
}catch( Throwable e ){
e.printStackTrace();
}
}
} |
from geoalchemy2.elements import WKTElement
from osmnames.prepare_data.prepare_data import <API key>
def <API key>(session, tables):
session.add(
tables.osm_linestring(
id=1,
osm_id=1111,
name="Rigiweg",
parent_id=1337,
geometry=WKTElement("""LINESTRING(944848.776557897 5985402.86960293,
944850.474743831 5985427.66032806,944850.064193386
5985444.35251452)""", srid=3857)
)
)
session.add(
tables.osm_linestring(
id=2,
osm_id=2222,
name="Rigiweg",
parent_id=1337,
geometry=WKTElement("""LINESTRING(944850.064193386 5985444.35251452,
944841.125390515 5985474.18953402,944830.553716556 5985520.36149253,
944826.821439784 5985550.17127335)""", srid=3857)
)
)
session.commit()
<API key>()
assert session.query(tables.<API key>).get(1).member_ids == [1, 2]
assert session.query(tables.osm_linestring).get(1).merged_into == 1111
assert session.query(tables.osm_linestring).get(2).merged_into == 1111
def <API key>(session, tables):
# following geometries are simplified from the osm linestring with the osm_id 35901448
session.add(
tables.osm_linestring(
id=1,
osm_id=1111,
name="Dorfstrasse",
parent_id=1337,
geometry=WKTElement("""LINESTRING(945262.014242162 5985606.22988835,
945125.963423109 5985669.20516832,944921.48130943 5985680.63151807,
944732.478813664 5985815.76883825,
944577.598658291 5985883.07702847)""", srid=3857)
)
)
session.add(
tables.osm_linestring(
id=2,
osm_id=2222,
name="Dorfstrasse",
parent_id=1337,
geometry=WKTElement("""LINESTRING(944410.8312014 5985761.48265348,
944216.360920161 5985861.25509228)""", srid=3857)
)
)
session.add(
tables.osm_linestring(
id=3,
osm_id=3333,
name="Dorfstrasse",
parent_id=1337,
geometry=WKTElement("""LINESTRING(944410.8312014 5985761.48265348,
944577.598658291 5985883.07702847)""", srid=3857)
)
)
session.add(
tables.osm_linestring(
id=4,
osm_id=4444,
name="Dorfstrasse",
parent_id=1337,
geometry=WKTElement("""LINESTRING(945286.283371876 5985592.46613797,
945284.781130476 5985609.66739185,945262.014242162 5985606.22988835,
945266.045101078 5985588.14864235,
945286.283371876 5985592.46613797)""", srid=3857)
)
)
session.commit()
<API key>()
assert session.query(tables.<API key>).get(1).member_ids == [1, 2, 3, 4]
assert session.query(tables.osm_linestring).get(1).merged_into == 1111
assert session.query(tables.osm_linestring).get(2).merged_into == 1111
assert session.query(tables.osm_linestring).get(3).merged_into == 1111
assert session.query(tables.osm_linestring).get(4).merged_into == 1111
def <API key>(session, tables):
# the following geometries do not touch directly but has to be merged
session.add(
tables.osm_linestring(
id=1,
name="Oberseestrasse",
parent_id=1337,
osm_id=24055427,
geometry=WKTElement("""LINESTRING(981453.976751762
5978726.11248254,981467.114366002 5978716.22031828,981491.02892942
5978722.30674579,981536.264123906 5978726.22239555)""", srid=3857)
)
)
session.add(
tables.osm_linestring(
id=2,
name="Oberseestrasse",
parent_id=1337,
osm_id=308577271,
geometry=WKTElement("""LINESTRING(981558.359202398
5978726.38726504,981674.610293174 5978708.37529047)""", srid=3857)
)
)
session.commit()
<API key>()
assert session.query(tables.<API key>).get(1).member_ids == [1, 2]
assert session.query(tables.osm_linestring).get(1).merged_into == 24055427
assert session.query(tables.osm_linestring).get(2).merged_into == 24055427
def <API key>(session, tables):
session.add(
tables.osm_linestring(
id=1,
name="Rigiweg",
parent_id=1337,
geometry=WKTElement("""LINESTRING(944848.776557897 5985402.86960293,
944850.474743831 5985427.66032806,944850.064193386
5985444.35251452)""", srid=3857)
)
)
session.add(
tables.osm_linestring(
id=2,
name="Rigiweg",
parent_id=9999,
geometry=WKTElement("""LINESTRING(944850.064193386 5985444.35251452,
944841.125390515 5985474.18953402,944830.553716556 5985520.36149253,
944826.821439784 5985550.17127335)""", srid=3857)
)
)
session.commit()
<API key>()
assert session.query(tables.osm_linestring).get(1).merged_into is None
assert session.query(tables.osm_linestring).get(2).merged_into is None
def <API key>(session, tables):
session.add(
tables.osm_linestring(
id=1,
name="Rigiweg",
parent_id=1337,
geometry=WKTElement("""LINESTRING(944848.776557897 5985402.86960293,
944850.474743831 5985427.66032806,944850.064193386
5985444.35251452)""", srid=3857)
)
)
session.add(
tables.osm_linestring(
id=2,
name="Zueristrasse",
parent_id=1337,
geometry=WKTElement("""LINESTRING(944850.064193386 5985444.35251452,
944841.125390515 5985474.18953402,944830.553716556 5985520.36149253,
944826.821439784 5985550.17127335)""", srid=3857)
)
)
session.commit()
<API key>()
assert session.query(tables.osm_linestring).get(1).merged_into is None
assert session.query(tables.osm_linestring).get(2).merged_into is None |
INC_DIR= ../../include
LIB_DIR= ../../lib
BIN_DIR= ../../bin
LDFLAG=-pthread -lgstreamer-0.10 -lgobject-2.0 -lgmodule-2.0 -lgthread-2.0 -lrt -lxml2 -lglib-2.0 -L/usr/X11R6/lib -L/usr/local/lib -L$(LIB_DIR)
LIBS= -lARgsub_lite -lARvideo -lAR -lpthread -lglut -lGLU -lGL -lXi -lX11 -lm -pthread -lgstreamer-0.10 -lgobject-2.0 -lgmodule-2.0 -lgthread-2.0 -lrt -lxml2 -lglib-2.0
CFLAG= -O -pthread -I/usr/include/gstreamer-0.10 -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/include/libxml2 -I/usr/X11R6/include -g -I$(INC_DIR)
OBJS =
HEADERS =
all: $(BIN_DIR)/simpleLite
$(BIN_DIR)/simpleLite: simpleLite.o $(OBJS)
cc -o $(BIN_DIR)/simpleLite simpleLite.o $(OBJS) $(LDFLAG) $(LIBS)
simpleLite.o: simpleLite.c $(HEADERS)
cc -c $(CFLAG) simpleLite.c
clean:
rm -f *.o
rm -f $(BIN_DIR)/simpleLite
allclean:
rm -f *.o
rm -f $(BIN_DIR)/simpleLite
rm -f Makefile |
<?php
defined('_JEXEC') or die;
/**
* Assignments: URL
*/
class <API key>
{
function passHomePage(&$parent, &$params, $selection = array(), $assignment = 'all')
{
$home = JFactory::getApplication()->getMenu('site')->getDefault(JFactory::getLanguage()->getTag());
// return if option or other set values do not match the homepage menu item values
if ($parent->params->option)
{
// check if option is different to home menu
if (!$home || !isset($home->query['option']) || $home->query['option'] != $parent->params->option)
{
return $parent->pass(0, $assignment);
}
if (!$parent->params->option)
{
// set the view/task/layout in the menu item to empty if not set
$home->query['view'] = isset($home->query['view']) ? $home->query['view'] : '';
$home->query['task'] = isset($home->query['task']) ? $home->query['task'] : '';
$home->query['layout'] = isset($home->query['layout']) ? $home->query['layout'] : '';
}
// check set values against home menu query items
foreach ($home->query as $k => $v)
{
if ((isset($parent->params->{$k}) && $parent->params->{$k} != $v)
|| (
(!isset($parent->params->{$k}) || in_array($v, array('virtuemart', 'mijoshop')))
&& JFactory::getApplication()->input->get($k) != $v
)
)
{
return $parent->pass(0, $assignment);
}
}
// check post values against home menu params
foreach ($home->params->toObject() as $k => $v)
{
if (($v && isset($_POST[$k]) && $_POST[$k] != $v)
|| (!$v && isset($_POST[$k]) && $_POST[$k])
)
{
return $parent->pass(0, $assignment);
}
}
}
$pass = $this->checkPass($home);
if (!$pass)
{
$pass = $this->checkPass($home, 1);
}
return $parent->pass($pass, $assignment);
}
function checkPass(&$home, $addlang = 0)
{
$pass = 0;
$uri = JURI::getInstance();
if ($addlang)
{
$sef = $uri->getVar('lang');
if (empty($sef))
{
$langs = array_keys(JLanguageHelper::getLanguages('sef'));
$path = JString::substr($uri->toString(array('scheme', 'user', 'pass', 'host', 'port', 'path')), JString::strlen($uri->base()));
$path = preg_replace('#^index\.php/?#', '', $path);
$parts = explode('/', $path);
$part = reset($parts);
if (in_array($part, $langs))
{
$sef = $part;
}
}
if (empty($sef))
{
return 0;
}
}
$query = $uri->toString(array('query'));
if (strpos($query, 'option=') === false && strpos($query, 'Itemid=') === false)
{
$url = $uri->toString(array('host', 'path'));
}
else
{
$url = $uri->toString(array('host', 'path', 'query'));
}
$url = preg_replace('#^www\.#', '', $url);
// replace ampersand chars
$url = str_replace('&', '&', $url);
// remove any language vars
$url = preg_replace('#((\?)lang=[a-z-_]*(&|$)|&lang=[a-z-_]*)#', '\2', $url);
// remove trailing nonsense
$url = trim(preg_replace('#/?\??&?$#', '', $url));
// remove the index.php/
$url = preg_replace('#/index\.php(/|$)#', '/', $url);
// remove trailing /
$url = trim(preg_replace('#/$#', '', $url));
$root = JURI::root();
// remove the http(s)
$root = preg_replace('#^.*?://#', '', $root);
$root = preg_replace('#^www\.#', '', $root);
//remove the port
$root = preg_replace('#:[0-9]+#', '', $root);
// so also passes on urls with trailing /, ?, &, /?, etc...
$root = preg_replace('#(Itemid=[0-9]*).*^#', '\1', $root);
// remove trailing /
$root = trim(preg_replace('#/$#', '', $root));
if ($addlang)
{
$root .= '/' . $sef;
}
if (!$pass)
{
/* Pass urls:
* [root]
*/
$regex = '#^' . $root . '$#i';
$pass = preg_match($regex, $url);
}
if (!$pass)
{
/* Pass urls:
* [root]?Itemid=[menu-id]
* [root]/?Itemid=[menu-id]
* [root]/index.php?Itemid=[menu-id]
* [root]/[menu-alias]
* [root]/[menu-alias]?Itemid=[menu-id]
* [root]/index.php?[menu-alias]
* [root]/index.php?[menu-alias]?Itemid=[menu-id]
* [root]/[menu-link]
* [root]/[menu-link]&Itemid=[menu-id]
*/
$regex = '#^' . $root
. '(/('
. 'index\.php'
. '|'
. '(index\.php\?)?' . preg_quote($home->alias, '
. '|'
. preg_quote($home->link, '
. ')?)?'
. '(/?[\?&]Itemid=' . (int) $home->id . ')?'
. '$
$pass = preg_match($regex, $url);
}
return $pass;
}
} |
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Programming/Coding Assignment
% LaTeX Template
%
% This template has been downloaded from:
% http:
%
% Original author:
% Ted Pavlic (http:
%
% Note:
% The \lipsum[#] commands throughout this template generate dummy text
% to fill the template out. These commands should all be removed when
% writing assignment content.
%
% This template uses a Perl script as an example snippet of code, most other
% languages are also usable. Configure them in the "CODE INCLUSION
% CONFIGURATION" section.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PACKAGES AND OTHER DOCUMENT CONFIGURATIONS
%
\documentclass{article}
\usepackage{amsmath}
\usepackage{fancyhdr} % Required for custom headers
\usepackage{lastpage} % Required to determine the last page for the footer
\usepackage{extramarks} % Required for headers and footers
\usepackage[usenames,dvipsnames]{color} % Required for custom colors
\usepackage{graphicx} % Required to insert images
\usepackage{subcaption}
\usepackage{listings} % Required for insertion of code
\usepackage{courier} % Required for the courier font
\usepackage{lipsum} % Used for inserting dummy 'Lorem ipsum' text into the template
% % % % % % % % %
\usepackage{listings}
\usepackage{color}
\definecolor{dkgreen}{rgb}{0,0.6,0}
\definecolor{gray}{rgb}{0.5,0.5,0.5}
\definecolor{mauve}{rgb}{0.58,0,0.82}
\lstset{frame=tb,
language=Python,
aboveskip=3mm,
belowskip=3mm,
showstringspaces=false,
columns=flexible,
basicstyle={\small\ttfamily},
numbers=none,
numberstyle=\tiny\color{gray},
keywordstyle=\color{blue},
commentstyle=\color{dkgreen},
stringstyle=\color{mauve},
breaklines=true,
breakatwhitespace=true,
tabsize=3
}
% % % % % % % % %
% Margins
\topmargin=-0.45in
\evensidemargin=0in
\oddsidemargin=0in
\textwidth=6.5in
\textheight=9.0in
\headsep=0.25in
\linespread{1.1} % Line spacing
% Set up the header and footer
\pagestyle{fancy}
\lhead{\hmwkAuthorName} % Top left header
\chead{\hmwkClass\ (\hmwkClassTime): \hmwkTitle} % Top center head
\rhead{\firstxmark} % Top right header
\lfoot{\lastxmark} % Bottom left footer
\cfoot{} % Bottom center footer
\rfoot{Page\ \thepage\ of\ \protect\pageref{LastPage}} % Bottom right footer
\renewcommand\headrulewidth{0.4pt} % Size of the header rule
\renewcommand\footrulewidth{0.4pt} % Size of the footer rule
\setlength\parindent{0pt} % Removes all indentation from paragraphs
%
% CODE INCLUSION CONFIGURATION
%
\definecolor{MyDarkGreen}{rgb}{0.0,0.4,0.0} % This is the color used for comments
\lstloadlanguages{Perl} % Load Perl syntax for listings, for a list of other languages supported see: ftp://ftp.tex.ac.uk/tex-archive/macros/latex/contrib/listings/listings.pdf
\lstset{language=Perl, % Use Perl in this example
frame=single, % Single frame around code
basicstyle=\small\ttfamily, % Use small true type font
keywordstyle=[1]\color{Blue}\bf, % Perl functions bold and blue
keywordstyle=[2]\color{Purple}, % Perl function arguments purple
keywordstyle=[3]\color{Blue}\underbar, % Custom functions underlined and blue
identifierstyle=, % Nothing special about identifiers
commentstyle=\usefont{T1}{pcr}{m}{sl}\color{MyDarkGreen}\small, % Comments small dark green courier font
stringstyle=\color{Purple}, % Strings are purple
showstringspaces=false, % Don't put marks in string spaces
tabsize=5, % 5 spaces per tab
%
% Put standard Perl functions not included in the default language here
morekeywords={rand},
%
% Put Perl function parameters here
morekeywords=[2]{on, off, interp},
%
% Put user defined functions here
morekeywords=[3]{test},
%
morecomment=[l][\color{Blue}]{...}, % Line continuation (...) like blue comment
numbers=left, % Line numbers on left
firstnumber=1, % Line numbers start with line 1
numberstyle=\tiny\color{Blue}, % Line numbers are blue and small
stepnumber=5 % Line numbers go in steps of 5
}
% Creates a new command to include a perl script, the first parameter is the filename of the script (without .pl), the second parameter is the caption
\newcommand{\perlscript}[2]{
\begin{itemize}
\item[]\lstinputlisting[caption=#2,label=#1]{#1.pl}
\end{itemize}
}
%
% DOCUMENT STRUCTURE COMMANDS
% Skip this unless you know what you're doing
%
% Header and footer for when a page split occurs within a problem environment
\newcommand{\enterProblemHeader}[1]{
\nobreak\extramarks{#1}{#1 continued on next page\ldots}\nobreak
\nobreak\extramarks{#1 (continued)}{#1 continued on next page\ldots}\nobreak
}
% Header and footer for when a page split occurs between problem environments
\newcommand{\exitProblemHeader}[1]{
\nobreak\extramarks{#1 (continued)}{#1 continued on next page\ldots}\nobreak
\nobreak\extramarks{#1}{}\nobreak
}
\setcounter{secnumdepth}{0} % Removes default section numbers
\newcounter{<API key>} % Creates a counter to keep track of the number of problems
\newcommand{\homeworkProblemName}{}
\newenvironment{homeworkProblem}[1][Part \arabic{<API key>}]{ % Makes a new environment called homeworkProblem which takes 1 argument (custom name) but the default is "Problem
\stepcounter{<API key>} % Increase counter for number of problems
\renewcommand{\homeworkProblemName}{#1} % Assign \homeworkProblemName the name of the problem
\section{\homeworkProblemName} % Make a section in the document with the custom problem count
\enterProblemHeader{\homeworkProblemName} % Header and footer within the environment
}{
\exitProblemHeader{\homeworkProblemName} % Header and footer after the environment
}
\newcommand{\problemAnswer}[1]{ % Defines the problem answer command with the content as the only argument
\noindent\framebox[\columnwidth][c]{\begin{minipage}{0.98\columnwidth}#1\end{minipage}} % Makes the box around the problem answer and puts the content inside
}
\newcommand{\homeworkSectionName}{}
\newenvironment{homeworkSection}[1]{ % New environment for sections within homework problems, takes 1 argument - the name of the section
\renewcommand{\homeworkSectionName}{#1} % Assign \homeworkSectionName to the name of the section from the environment argument
\subsection{\homeworkSectionName} % Make a subsection with the custom name of the subsection
\enterProblemHeader{\homeworkProblemName\ [\homeworkSectionName]} % Header and footer within the environment
}{
\enterProblemHeader{\homeworkProblemName} % Header and footer after the environment
}
%
% NAME AND CLASS SECTION
%
\newcommand{\hmwkTitle}{Project 4} % Assignment title
\newcommand{\hmwkDueDate}{Triangulation Matting} % Due date
\newcommand{\hmwkClass}{CSC320} % Course/class
\newcommand{\hmwkClassTime}{L0101} % Class/lecture time
\newcommand{\hmwkAuthorName}{Ramaneek Gill and Ryan D'Souza} % Your name
%
% TITLE PAGE
%
\title{
\vspace{2in}
\textmd{\textbf{\hmwkClass:\ \hmwkTitle}}\\
\normalsize\vspace{0.1in}\small{\hmwkDueDate}\\
\vspace{0.1in}
\vspace{3in}
}
\author{\textbf{\hmwkAuthorName}}
%\date{} % Insert date here if you want it to appear below your name
%
\begin{document}
\maketitle
\clearpage
%
% PART 1
%
\begin{homeworkProblem}
\noindent
$$
C =
\begin{bmatrix}
C_1\\
C_2
\end{bmatrix}
, \hspace{10mm} B =
\begin{bmatrix}
B_1\\
B_2
\end{bmatrix} \\
$$
\\
$$C = F + (1-\alpha)B$$
$$C = F + B - B\alpha$$
$$C - B = F - B\alpha$$
$$\Rightarrow$$
$$
\left(\begin{matrix}
1 & 0 & 0 & -B^{r}_1 \\
0 & 1 & 0 & -B^{g}_1 \\
0 & 0 & 1 & -B^{b}_1 \\
1 & 0 & 0 & -B^{r}_2 \\
0 & 1 & 0 & -B^{g}_2 \\
0 & 0 & 1 & -B^{b}_2 \\
\end{matrix} \right)
\left(\begin{matrix}
F_r \\
F_g \\
F_b \\
\alpha
\end{matrix}\right) =
\left(
\begin{matrix}
C^{r}_1 -B^{r}_1 \\
C^{g}_1 -B^{g}_1 \\
C^{b}_1 -B^{b}_1 \\
C^{r}_2 -B^{r}_2 \\
C^{g}_2-B^{g}_2 \\
C^{b}_2-B^{b}_2 \\
\end{matrix}
\right).
$$
\end{homeworkProblem}
%
% PART 2
%
\begin{homeworkProblem}
\noindent
The input images were 4 input images. 2 were composite images of a flower with a white background and other one with a black background. The two different background images (white and black) were also given. These 4 input images were used with another image (a window background) to produce a new composite image a flower as the foreground with triangulation matting.\\
\begin{figure}[h!]
\centering
\begin{subfigure}[b]{0.3\textwidth}
\includegraphics[width=\textwidth]{flower-foreground.png}
\caption{The foreground computed from using two composite images with the same foreground but different backgrounds}
\label{fig:1a}
\end{subfigure}%
~
\begin{subfigure}[b]{0.3\textwidth}
\includegraphics[width=\textwidth]{<API key>.png}
\caption{The alpha channel computed}
\label{fig:1b}
\end{subfigure}
~
\begin{subfigure}[b]{0.3\textwidth}
\includegraphics[width=\textwidth]{window-and-flower.png}
\caption{The custom composite image with the same foreground but new background}
\label{fig:1c}
\end{subfigure}
\caption{Images computed through the triangulation matting algorithm}\label{fig:dataset}
\end{figure}
\end{homeworkProblem}
\clearpage
%
% PART 3
%
\begin{homeworkProblem}
\noindent
There is no way I can produce an image where the foreground is the exact same with two different backgrounds since I don't have a tripod, my only camera is the one included in my phone so the results will be very shaky. Below are my 5 input images and the results of the triangulation matting.\\
I got these images by doing the following:\\
1. Take a picture of a background.\\
2. Move foreground object in front of background (the mug in the figures below) and take a picture.\\
3. Change background, leave mug in same exact place and take a picture.\\
4. Remove foreground and take a picture.\\
5. Try to do all of these steps while balancing the camera (android phone) on a stable surface and try to move its angle of view as little as possible.\\
\\
The fifth step (the lack of a tripod) was the reason the output from the triangulation matting algorithm was horrible. The input image backgrounds were not as similar we want them to be since the camera can view a very different image (because of projection) when comparing the data pixel-wise. From an object recognition standpoint the input images are perfect.
\begin{figure}[h!]
\centering
\begin{subfigure}[b]{0.49\textwidth}
\includegraphics[width=\textwidth]{my-images/b1.jpg}
\caption{Background 1}
\label{fig:1a}
\end{subfigure}%
~
\begin{subfigure}[b]{0.49\textwidth}
\includegraphics[width=\textwidth]{my-images/b2.jpg}
\caption{Background 2}
\label{fig:1b}
\end{subfigure}
\caption{Background input images}\label{fig:dataset}
\end{figure}
%c1 and c2
\begin{figure}[h!]
\centering
\begin{subfigure}[b]{0.49\textwidth}
\includegraphics[width=\textwidth]{my-images/c1.jpg}
\caption{Composite 1, (includes b1)}
\label{fig:1a}
\end{subfigure}%
~
\begin{subfigure}[b]{0.49\textwidth}
\includegraphics[width=\textwidth]{my-images/c2.jpg}
\caption{Composite 2, (includes b2)}
\label{fig:1b}
\end{subfigure}
\caption{Composite input images}\label{fig:dataset}
\end{figure}
\begin{figure}[h!]
\centering
\begin{subfigure}[b]{0.75\textwidth}
\includegraphics[width=\textwidth]{my-images/new-b.jpg}
\caption{A background we want to combine with the mug (foreground object) in the two images directly above.}
\label{fig:1a}
\end{subfigure}%
\caption{New background input image}\label{fig:dataset}
\end{figure}
Now for the results of the triangulation matting algorithm:
\begin{figure}[h!]
\centering
\begin{subfigure}[b]{0.49\textwidth}
\includegraphics[width=\textwidth]{my-alpha.png}
\caption{Alpha image computed with the images in Figure 2 and 3.}
\label{fig:1a}
\end{subfigure}%
~
\begin{subfigure}[b]{0.49\textwidth}
\includegraphics[width=\textwidth]{my-f.png}
\caption{Foreground image computed with the images in Figure 2 and 3.}
\label{fig:1b}
\end{subfigure}
\caption{Composite input images}\label{fig:dataset}
\end{figure}
\begin{figure}[h!]
\centering
\begin{subfigure}[b]{0.75\textwidth}
\includegraphics[width=\textwidth]{my-new-c.png}
\caption{The new composite image produced by doing triangulation matting with figure 4 and 5. Pretty lousy results eh? Blame the output of these input images on my lack of skills as a photographer, not a computer scientist!
}
\label{fig:1a}
\end{subfigure}%
\caption{New background input image}\label{fig:dataset}
\end{figure}
\end{homeworkProblem}
\clearpage
\section{p4.py:}
\begin{lstlisting}
from pylab import *
import numpy as np
import random
import matplotlib.cbook as cbook
import random
import time
from scipy.misc import imread
from scipy.misc import imsave
from scipy.misc import imresize
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import os
matplotlib
gray()
os.chdir('C:/Users/Ramaneek/SkyDrive/Documents/Github/CSC320-Winter-2014/project 4/')
# c = f + (1-alpha)b
## MAIN
b1 = imread('images/flowers-backA.jpg')/255.0
c1 = imread('images/flowers-compA.jpg')/255.0
b2 = imread('images/flowers-backB.jpg')/255.0
c2 = imread('images/flowers-compB.jpg')/255.0
new_b = imread('images/window.jpg')/255.0
print "Read the input images"
new_c = np.zeros(new_b.shape)
alpha = np.zeros((b1.shape[0], b1.shape[1]))
f = np.zeros(b1.shape)
for i in range(b1.shape[0]):
for j in range(b2.shape[1]):
#set A
A = np.matrix([ [1,0,0,-b1[i,j,0]],
[0,1,0,-b1[i,j,1]],
[0,0,1,-b1[i,j,2]],
[1,0,0,-b2[i,j,0]],
[0,1,0,-b2[i,j,1]],
[0,0,1,-b2[i,j,2]] ])
#get the pseudo inverse of A
A_pinv = linalg.pinv(A)
#set b
b = np.matrix([ [c1[i,j,0]-b1[i,j,0]],
[c1[i,j,1]-b1[i,j,1]],
[c1[i,j,2]-b1[i,j,2]],
[c2[i,j,0]-b2[i,j,0]],
[c2[i,j,1]-b2[i,j,1]],
[c2[i,j,2]-b2[i,j,2]] ])
#solve for x by A^-1*b
x = np.clip(dot(A_pinv,b), 0, 1)
#set foreground
for k in range(3):
f[i,j,k] = x[k]
#set alpha channel
alpha[i,j] = x[3]
#set new composite image
for k in range(3):
new_c[i,j,k] = f[i,j,k] + np.dot((1-alpha[i,j]), new_b[i,j,k])
print "Computed alpha channel and isolated the foreground"
figure(1)
imshow(alpha)
figure(2)
imshow(f)
figure(3)
imshow(new_c)
show()
\end{lstlisting}
\end{document} |
<?php
// Require thumbnail provider class
require_once( <API key> . '/php/providers/<API key>.php' );
class Youku_Thumbnails extends <API key> {
// Human-readable name of the video provider
public $service_name = 'Youku';
const service_name = 'Youku';
// Slug for the video provider
public $service_slug = 'youku';
const service_slug = 'youku';
public static function register_provider( $providers ) {
$providers[self::service_slug] = new self;
return $providers;
}
// Regex strings
public $regexes = array(
'
'
);
// Thumbnail URL
public function get_thumbnail_url( $id ) {
$request = "http://v.youku.com/player/getPlayList/VideoIDS/$id/";
$response = wp_remote_get( $request, array( 'sslverify' => false ) );
if( is_wp_error( $response ) ) {
$result = new WP_Error( '<API key>', __( 'Error retrieving video information from the URL <a href="' . $request . '">' . $request . '</a> using <code>wp_remote_get()</code><br />If opening that URL in your web browser returns anything else than an error page, the problem may be related to your web server and might be something your host administrator can solve.<br />Details: ' . $response->get_error_message() ) );
} else {
$result = json_decode( $response['body'] );
$result = $result->data[0]->logo;
}
return $result;
}
// Test cases
public $test_cases = array(
array(
'markup' => '<embed src="http://player.youku.com/player.php/sid/XMzQyMzk5MzQ4/v.swf" quality="high" width="480" height="400" align="middle" allowScriptAccess="sameDomain" allowFullscreen="true" type="application/x-shockwave-flash"></embed>',
'expected' => 'http://g1.ykimg.com/<API key>',
'expected_hash' => '<API key>',
'name' => 'Flash embed'
),
array(
'markup' => 'http://v.youku.com/v_show/id_XMzQyMzk5MzQ4.html',
'expected' => 'http://g1.ykimg.com/<API key>',
'expected_hash' => '<API key>',
'name' => 'Link'
),
);
}
// Add to provider array
add_filter( '<API key>', array( 'Youku_Thumbnails', 'register_provider' ) );
?> |
if(!dojo._hasResource["dojox.charting.themes.PlotKit.blue"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dojox.charting.themes.PlotKit.blue"] = true;
dojo.provide("dojox.charting.themes.PlotKit.blue");
dojo.require("dojox.charting.Theme");
(function(){
var dxc=dojox.charting;
dxc.themes.PlotKit.blue=new dxc.Theme({
chart:{
stroke:null,
fill: "white"
},
plotarea:{
stroke:null,
fill: "#e7eef6"
},
axis:{
stroke:{ color:"#fff",width:2 },
line:{ color:"#fff",width:1 },
majorTick:{ color:"#fff", width:2, length:12 },
minorTick:{ color:"#fff", width:1, length:8 },
font:"normal normal normal 8pt Tahoma",
fontColor:"#999"
},
series:{
outline:{ width: 0.1, color:"#fff" },
stroke:{ width: 1.5, color:"#666" },
fill:new dojo.Color([0x66, 0x66, 0x66, 0.8]),
font:"normal normal normal 7pt Tahoma", // label
fontColor:"#000"
},
marker:{ // any markers on a series.
stroke:{ width:2 },
fill:"#333",
font:"normal normal normal 7pt Tahoma", // label
fontColor:"#000"
},
colors:[]
});
dxc.themes.PlotKit.blue.defineColors({ hue:217, saturation:60, low:40, high:88 });
})();
} |
#ifndef __AUTHSESSION_H__
#define __AUTHSESSION_H__
#include "Common.h"
#include "ByteBuffer.h"
#include "Socket.h"
#include "BigNumber.h"
#include <memory>
#include <boost/asio/ip/tcp.hpp>
using boost::asio::ip::tcp;
struct AuthHandler;
class AuthSession : public Socket<AuthSession>
{
public:
static std::unordered_map<uint8, AuthHandler> InitHandlers();
AuthSession(tcp::socket&& socket) : Socket(std::move(socket)),
_isAuthenticated(false), _build(0), _expversion(0), <API key>(SEC_PLAYER)
{
N.SetHexStr("<API key>");
g.SetDword(7);
}
void Start() override
{
AsyncRead();
}
void SendPacket(ByteBuffer& packet);
protected:
void ReadHandler() override;
private:
bool <API key>();
bool HandleLogonProof();
bool <API key>();
bool <API key>();
bool HandleRealmList();
//data transfer handle for patch
bool HandleXferResume();
bool HandleXferCancel();
bool HandleXferAccept();
void SetVSFields(const std::string& rI);
BigNumber N, s, g, v;
BigNumber b, B;
BigNumber K;
BigNumber _reconnectProof;
bool _isAuthenticated;
std::string _tokenKey;
std::string _login;
std::string _localizationName;
std::string _os;
uint16 _build;
uint8 _expversion;
AccountTypes <API key>;
};
#pragma pack(push, 1)
struct AuthHandler
{
uint32 status;
size_t packetSize;
bool (AuthSession::*handler)();
};
#pragma pack(pop)
#endif |
# arch/lm32/boot/Makefile
# This file is subject to the terms and conditions of the GNU General Public
# for more details.
targets := vmlinux.bin
ifneq ($(DTB),)
obj-y += $(DTB).dtb.o
endif
quiet_cmd_cp = CP $< $@$2
cmd_cp = cat $< >$@$2 || (rm -f $@ && echo false)
$(obj)/simpleImage.%: vmlinux FORCE
$(call if_changed,objcopy)
$(obj)/vmlinux.bin: vmlinux FORCE
$(call if_changed,objcopy)
@echo 'Kernel: $@ is ready' ' (#'`cat .version`')'
# Rule to build device tree blobs
$(obj)/%.dtb: $(src)/dts/%.dts
$(call cmd,dtc)
clean-files += vmlinux.bin *.dtb.S |
#include <sdcc-lib.h>
#if <API key>
unsigned long _modulong (unsigned long a, unsigned long b);
#endif
/* Assembler-functions are provided for:
mcs51 small
mcs51 small stack-auto
*/
#if !defined(__SDCC_USE_XSTACK) && !defined(<API key>)
# if defined(__SDCC_mcs51)
# if defined(__SDCC_MODEL_SMALL)
# if defined(__SDCC_STACK_AUTO) && !defined(SDCC_PARMS_IN_BANK1)
# define <API key>
# else
# define _MODSLONG_ASM_SMALL
# endif
# endif
# endif
#endif
#if defined _MODSLONG_ASM_SMALL
static void
_modslong_dummy (void) __naked
{
__asm
#define a0 dpl
#define a1 dph
#define a2 b
#define a3 r1
.globl __modslong
#if defined(SDCC_PARMS_IN_BANK1)
#define b0 (b1_0)
#define b1 (b1_1)
#define b2 (b1_2)
#define b3 (b1_3)
#else
// _modslong_PARM_2 shares the same memory with _modulong_PARM_2
// and is defined in _modulong.c
#define b0 (__modslong_PARM_2)
#define b1 (__modslong_PARM_2 + 1)
#define b2 (__modslong_PARM_2 + 2)
#define b3 (__modslong_PARM_2 + 3)
#endif
__modslong:
; a3 in acc
; b3 in (__modslong_PARM_2 + 3)
mov a3,a ; save a3
clr F0 ; Flag 0 in PSW
; available to user for general purpose
jnb acc.7,a_not_negative
setb F0
clr a ; a = -a;
clr c
subb a,a0
mov a0,a
clr a
subb a,a1
mov a1,a
clr a
subb a,a2
mov a2,a
clr a
subb a,a3
mov a3,a
a_not_negative:
mov a,b3
jnb acc.7,b_not_negative
clr a ; b = -b;
clr c
subb a,b0
mov b0,a
clr a
subb a,b1
mov b1,a
clr a
subb a,b2
mov b2,a
clr a
subb a,b3
mov b3,a
b_not_negative:
mov a,a3 ; restore a3 in acc
lcall __modulong
jnb F0,not_negative
; result in (a == r1), b, dph, dpl
clr a
clr c
subb a,a0
mov a0,a
clr a
subb a,a1
mov a1,a
clr a
subb a,a2
mov a2,a
clr a
subb a,a3
; result in a, b, dph, dpl
not_negative:
ret
__endasm;
}
#elif defined <API key>
static void
_modslong_dummy (void) __naked
{
__asm
#define a0 dpl
#define a1 dph
#define a2 b
#define a3 r1
#define b0 r2
#define b1 r3
#define b2 r4
#define b3 r5
ar2 = 2 ; BUG register set is not considered
ar3 = 3
ar4 = 4
ar5 = 5
.globl __modslong
__modslong:
; a3 in acc
mov a3,a ; save a3
clr F0 ; F0 (Flag 0)
; available to user for general purpose
jnb acc.7,a_not_negative
setb F0
clr a ; a = -a;
clr c
subb a,a0
mov a0,a
clr a
subb a,a1
mov a1,a
clr a
subb a,a2
mov a2,a
clr a
subb a,a3
mov a3,a
a_not_negative:
mov a,sp
add a,#-2-3 ; 2 bytes return address, 3 bytes param b
mov r0,a ; r1 points to b0
mov ar2,@r0 ; load b0
inc r0 ; r0 points to b1
mov ar3,@r0 ; b1
inc r0
mov ar4,@r0 ; b2
inc r0
mov a,@r0 ; b3
mov b3,a
jnb acc.7,b_not_negative
clr a ; b = -b;
clr c
subb a,b0
mov b0,a
clr a
subb a,b1
mov b1,a
clr a
subb a,b2
mov b2,a
clr a
subb a,b3
mov b3,a
b_not_negative:
lcall __modlong
jnb F0,not_negative
; result in (a == r1), b, dph, dpl
clr a
clr c
subb a,a0
mov a0,a
clr a
subb a,a1
mov a1,a
clr a
subb a,a2
mov a2,a
clr a
subb a,a3 ; result in a, b, dph, dpl
not_negative:
ret
__endasm;
}
#else // _MODSLONG_ASM
long
_modslong (long a, long b)
{
long r;
r = _modulong((a < 0 ? -a : a),
(b < 0 ? -b : b));
if (a < 0)
return -r;
else
return r;
}
#endif // _MODSLONG_ASM |
<?php
class <API key> extends ViewControl
{
public $nLookupType;
public $lookupTable;
public $displayFieldName;
public $linkFieldName;
public $linkAndDisplaySame;
public $pSet;
public $lookupPSet;
public $cipherer;
public $lookupQueryObj;
public $displayFieldIndex;
public $LookupSQL;
public $<API key>;
public function <API key>($field, $container, $pageObject)
{
parent::ViewControl($field, $container, $pageObject);
$this->nLookupType = null;
$this->lookupTable = "";
$this->displayFieldName = "";
$this->linkFieldName = "";
$this->linkAndDisplaySame = false;
$this->lookupPSet = null;
$this->cipherer = null;
$this->lookupQueryObj = null;
$this->displayFieldIndex = 0;
$this->LookupSQL = "";
if($this->container->pSet->getEditFormat($field) != <API key>)
{
$this->pSet = new ProjectSettings($this->container->pSet->_table,
$this->container->pSet-><API key>($field, <API key>));
}
else
$this->pSet = $this->container->pSet;
$this->nLookupType = $this->pSet->getLookupType($this->field);
$this->lookupTable = $this->pSet->getLookupTable($this->field);
$this->displayFieldName = $this->pSet->getDisplayField($this->field);
$this->linkFieldName = $this->pSet->getLinkField($this->field);
$this->linkAndDisplaySame = $this->displayFieldName == $this->linkFieldName;
if($this->nLookupType == LT_QUERY){
$this->lookupPSet = new ProjectSettings($this->lookupTable, $this->container->pageType);
$this->cipherer = new RunnerCipherer($this->lookupTable);
if($this->pSet->getCustomDisplay($this->field))
$this->lookupPSet->getSQLQuery()->AddCustomExpression($this->displayFieldName, $this->lookupPSet, $this->pSet->_table, $this->field);
$this->lookupQueryObj = $this->lookupPSet->getSQLQuery()->CloneObject();
$this->lookupQueryObj-><API key>($this->lookupPSet-><API key>());
$lookupIndexes = <API key>($this->pSet, $this->field);
$this->displayFieldIndex = $lookupIndexes["displayFieldIndex"];
}else{
$this->cipherer = new RunnerCipherer($this->pSet->_table);
$this->LookupSQL = "SELECT ";
$this->LookupSQL.= $this->pSet->getLWDisplayField($this->field);
$this->LookupSQL.= " FROM ".AddTableWrappers($this->pSet->getLookupTable($this->field))." WHERE ";
}
$this-><API key> = new <API key>($this->pSet, $this->container->pageType, $pageObject);
$this-><API key>->isLocal = true;
}
public function showDBValue(&$data, $keylink)
{
global $conn, $strTableName;
$value = $data[$this->field];
if(!strlen($value))
return "";
$where = "";
$out = "";
$lookupvalue = $value;
$iquery = "field=".htmlspecialchars(rawurlencode($this->field)).$keylink;
$where = GetLWWhere($this->field, $this->container->pageType);
if($this->pSet->multiSelect($this->field))
{
$arr = splitvalues($value);
$numeric = true;
$type = $this->pSet->getLWLinkFieldType($this->field);
if(!$type)
{
foreach($arr as $val)
if(strlen($val) && !is_numeric($val))
{
$numeric=false;
break;
}
}
else
$numeric = !NeedQuotes($type);
$in = "";
foreach($arr as $val)
{
if($numeric && !strlen($val))
continue;
if(strlen($in))
$in.= ",";
if($numeric)
$in.= ($val+0);
else
$in.= db_prepare_string($this->cipherer->EncryptField($this->nLookupType == LT_QUERY ? $this->linkFieldName : $this->field, $val));
}
if(strlen($in))
{
if($this->nLookupType == LT_QUERY){
$inWhere = GetFullFieldName($this->linkFieldName, $this->lookupTable, false)." in (".$in.")";
if(strlen($where))
$inWhere.=" and (".$where.")";
$LookupSQL = $this->lookupQueryObj->toSql(whereAdd($this->lookupQueryObj->m_where->toSql($this->lookupQueryObj), $inWhere));
}else{
$LookupSQL = $this->LookupSQL.$this->pSet->getLWLinkField($this->field)." in (".$in.")";
if(strlen($where))
$LookupSQL.=" and (".$where.")";
}
LogInfo($LookupSQL);
$rsLookup = db_query($LookupSQL,$conn);
$found = false;
$lookupArrTmp = array();
$lookupArr = array();
while($lookuprow=db_fetch_numarray($rsLookup))
{
$lookupArrTmp[] = $lookuprow[$this->displayFieldIndex];
}
$lookupArr = array_unique($lookupArrTmp);
$localData = $data;
foreach($lookupArr as $lookupvalue)
{
if($found)
$out.= ",";
$found = true;
if($this->pSet->getViewFormat($this->field) != "Custom"){
$localData[$this->field] = $lookupvalue;
}
$outVal = $this-><API key>->showDBValue($this->field, $localData, $keylink, $lookupvalue);
$out.= $this->nLookupType == LT_QUERY || $this->linkAndDisplaySame ?
$this->cipherer->DecryptField($this->nLookupType == LT_QUERY ? $this->displayFieldName : $this->field, $outVal) : $outVal;
}
return $out;
}
}
else
{
$found = false;
$strdata = $this->cipherer->MakeDBValue($this->nLookupType == LT_QUERY ? $this->linkFieldName : $this->field, $value, "", "", true);
if($this->nLookupType == LT_QUERY){
$strWhere = GetFullFieldName($this->linkFieldName, $this->lookupTable, false)." = " . $strdata;
if(strlen($where))
$strWhere.= " and (".$where.")";
$LookupSQL = $this->lookupQueryObj->toSql(whereAdd($this->lookupQueryObj->m_where->toSql($this->lookupQueryObj), $strWhere));
}else{
$strWhere = $this->pSet->getLWLinkField($this->field)." = " . $strdata;
if(strlen($where))
$strWhere.= " and (".$where.")";
$LookupSQL = $this->LookupSQL.$strWhere;
}
LogInfo($LookupSQL);
$rsLookup = db_query($LookupSQL,$conn);
if($lookuprow = db_fetch_numarray($rsLookup)){
$lookupvalue = $lookuprow[$this->displayFieldIndex];
$found = true;
}
}
if(!$out){
if($found && ($this->nLookupType == LT_QUERY || $this->linkAndDisplaySame)){
$lookupvalue = $this->cipherer->DecryptField($this->nLookupType == LT_QUERY ? $this->displayFieldName : $this->field, $lookupvalue);
}
$localData = $data;
if($this->pSet->getViewFormat($this->field) != "Custom"){
$localData[$this->field] = $lookupvalue;
}
$out = $this-><API key>->showDBValue($this->field, $localData, $keylink, $lookupvalue);
}
return $out;
}
}
?> |
=head1 NAME
<API key> - Build the virt-p2v kickstart
=head1 SYNOPSIS
<API key> [-o p2v.ks] [--proxy=http://...] repo [repo...]
=head1 DESCRIPTION
L<virt-p2v(1)> converts a physical machine to run virtualized on KVM,
managed by libvirt, OpenStack, oVirt, Red Hat Enterprise
Virtualisation (RHEV), or one of the other targets supported by
L<virt-v2v(1)>.
Kickstart is a format used by Red Hat-derived distributions (such as
Fedora, Red Hat Enterprise Linux, CentOS, Scientific Linux, and
others) to describe how to make live CDs, install the distro, make
"Spins" and so on. It is driven by a kickstart file.
<API key> builds a kickstart file which can be used to
build a bootable P2V ISO, live CD, USB key, or PXE image. This tool
only builds the kickstart file, but this manual page describes some of
the ways you can use the kickstart file.
=head1 BUILDING THE KICKSTART FILE
Using <API key> is very simple:
<API key> fedora
will build a kickstart file for Fedora. The kickstart file will be
called F<p2v.ks> and located in the current directory.
The parameters are a list of one or more repositories. Some built-in
repositories are available: C<fedora>, C<rawhide> or C<koji>. You can
also use a URL as a parameter to point to a repository, for example:
<API key> https://dl.fedoraproject.org/pub/fedora/linux/releases/21/Everything/x86_64/os/
To control the name of the output file, use the I<-o> parameter. To
tell kickstart to use a proxy server or web cache to download files,
use the I<--proxy> parameter.
=head1 BUILDING A LIVE CD / ISO
Once you have the kickstart file, you can use L<livecd-creator(8)>
to make a live CD:
sudo livecd-creator p2v.ks
Before running this note that you should probably run
C<livecd-creator> in a disposable virtual machine for these reasons:
=over 4
=item *
You have to disable SELinux when running the tool.
=item *
This tool has to be run as root, and has some nasty failure modes.
=item *
You can only create the exact same Live CD distro as the host
distro. Cross-builds will fail in strange ways (eg. RHBZ#1092327).
=back
=head1 BUILDING A FEDORA SPIN USING KOJI
This requires C<spin-livecd> permissions on Koji, which are not given
out usually, even to Fedora packagers. However assuming you have been
given these permissions (or have your own Koji instance, I guess),
then you can do:
koji spin-livecd [--scratch] virt-p2v 1.XX.YY rawhide x86_64 p2v.ks
=over 4
=item *
Add the C<--scratch> option to do a scratch build (recommended for
testing).
=item *
C<1.XX.YY> should match the libguestfs version
=item *
Instead of C<rawhide> you can use any Koji target.
=back
=head1 BUILDING A BOOTABLE USB KEY
Use the L<livecd-iso-to-disk(8)> program to convert the ISO created
above to a USB key:
sudo livecd-iso-to-disk livecd-p2v.iso /dev/sdX
=head1 BUILDING A PXE BOOT IMAGE
Use the C<<API key>> program to convert the ISO created
above to a PXE boot image.
sudo <API key> livecd-p2v.iso
This creates a C<tftpboot> subdirectory under the current directory
containing the files required to PXE boot virt-p2v:
$ ls -1R tftpboot/
tftpboot/:
initrd0.img
pxelinux.0
pxelinux.cfg/
vmlinuz0
tftpboot/pxelinux.cfg:
default
=head1 TESTING VIRT-P2V USING QEMU
=head2 TESTING THE P2V ISO USING QEMU
You can use qemu to test-boot the P2V ISO:
qemu-kvm -m 1024 -hda /tmp/guest.img -cdrom /tmp/livecd-p2v.iso -boot d
Note that C<-hda> is the (virtual) system that you want to convert
(for test purposes). It could be any guest type supported by
L<virt-v2v(1)>, including Windows or Red Hat Enterprise Linux.
=head2 TESTING PXE SUPPORT USING QEMU
=over 4
=item *
Unpack the tftpboot directory into F</tmp> (so it appears as
F</tmp/tftpboot>).
=item *
Copy F<pxelinux.0> and F<ldlinux.c32> from syslinux (usually from
F</usr/share/syslinux>) into F</tmp/tftpboot>.
=item *
Adjust the C<APPEND> line in F</tmp/tftpboot/pxelinux.cfg/default> if
required. See L<virt-p2v(1)/KERNEL COMMAND LINE CONFIGURATION>.
=item *
Run qemu like this so that it acts as a TFTP and BOOTP server,
emulating a netboot:
qemu-kvm \
-m 4096 -hda /tmp/guest.img \
-boot n \
-netdev user,id=unet,tftp=/tmp/tftpboot,bootfile=/pxelinux.0 \
-device virtio-net-pci,netdev=unet \
-serial stdio
Note that this requires considerably more memory because the PXE image
is loaded into memory. Also that qemu's TFTP server is very slow and
the virt-p2v PXE image is very large, so it can appear to "hang" after
pxelinux starts up.
=back
=head1 OPTIONS
=over 4
=item B<--help>
Display help.
=item B<-o> OUTPUT
=item B<--output> OUTPUT
Write kickstart to C<OUTPUT>. If not specified, the default is
F<p2v.ks> in the current directory.
=item B<--proxy> URL
Tell the kickstart to use a proxy server or web cache for downloads.
=item B<-V>
=item B<--version>
Display version number and exit.
=back
=head1 FILES
=over 4
=item F<$libexecdir/virt-p2v>
The L<virt-p2v(1)> binary which is copied into the kickstart file.
=item F<$datadir/issue>
=item F<$datadir/launch-virt-p2v.in>
=item F<$datadir/p2v.ks.in>
=item F<$datadir/p2v.service>
Various data files that are used to make the kickstart.
=back
=head1 ENVIRONMENT VARIABLES
=over 4
=item C<VIRT_P2V_DATA_DIR>
The directory where <API key> looks for data files and
the virt-p2v binary (see L</FILES> above). If not set, a compiled-in
location is used.
=back
=head1 SEE ALSO
L<virt-p2v(1)>,
L<virt-p2v-make-disk(1)>,
L<virt-v2v(1)>,
L<livecd-creator(8)>,
L<livecd-iso-to-disk(8)>,
L<http://libguestfs.org/>.
=head1 AUTHORS
Richard W.M. Jones L<http://people.redhat.com/~rjones/>
=head1 COPYRIGHT
Copyright (C) 2009-2015 Red Hat Inc. |
<?php
/**
* Esperantolanguage file
*
* @author Felipe Castro <fefcas@uol.com.br>
* @author Felipe Castro <fefcas@gmail.com>
* @author Felipe Castro <fefcas (cxe) gmail (punkto) com>
* @author Felipo Kastro <fefcas@gmail.com>
* @author Robert Bogenschneider <robog@gmx.de>
* @author Erik Pedersen <erik pedersen@shaw.ca>
* @author Erik Pedersen <erik.pedersen@shaw.ca>
* @author Robert Bogenschneider <robog@GMX.de>
*/
$lang['menu'] = 'Administri Kromaĵojn';
$lang['download'] = 'Elŝuti kaj instali novan kromaĵon';
$lang['manage'] = 'Instalitaj kromaĵoj';
$lang['btn_info'] = 'info';
$lang['btn_update'] = 'ĝisdatigo';
$lang['btn_delete'] = 'forigi';
$lang['btn_settings'] = 'agordoj';
$lang['btn_download'] = 'Elŝuti';
$lang['btn_enable'] = 'Konservi';
$lang['url'] = 'URL';
$lang['installed'] = 'Instalite:';
$lang['lastupdate'] = 'Laste ĝisdatigite:';
$lang['source'] = 'Fonto:';
$lang['unknown'] = 'nekonate';
$lang['updating'] = 'Ĝisdatiganta ...';
$lang['updated'] = 'Kromaĵo %s estas sukcese ĝisdatigita';
$lang['updates'] = 'La jenaj kromaĵoj estas sukcese ĝisdatigitaj';
$lang['update_none'] = 'Neniu ĝisdatigo troviĝas.';
$lang['deleting'] = 'Foriganta ...';
$lang['deleted'] = 'Kromaĵo %s estas forigita.';
$lang['downloading'] = 'Elŝutanta ...';
$lang['downloaded'] = 'La kromaĵo %s estas sukcese instalita';
$lang['downloads'] = 'La jenaj kromaĵoj estas sukcese instalitaj:';
$lang['download_none'] = 'Neniu kromaĵo troveblas, aŭ eble okazis nekonata problemo dum elŝuto kaj instalo.';
$lang['plugin'] = 'Kromaĵo:';
$lang['components'] = 'Komponeroj';
$lang['noinfo'] = 'Tiu ĉi kromaĵo liveris neniun informon: eble ĝi ne validas.';
$lang['name'] = 'Nomo:';
$lang['date'] = 'Dato:';
$lang['type'] = 'Tipo:';
$lang['desc'] = 'Priskribo:';
$lang['author'] = 'Aŭtoro:';
$lang['www'] = 'Retpaĝo:';
$lang['error'] = 'Nekonata eraro okazis.';
$lang['error_download'] = 'Maleblas elŝuti la kromaĵan dosieron: %s';
$lang['error_badurl'] = 'Suspektinda malbona URL - maleblas difini la dosieran nomon el la URL';
$lang['error_dircreate'] = 'Maleblas krei provizoran dosierujon por ricevi elŝutaĵon';
$lang['error_decompress'] = 'La administrilo de kromaĵoj ne kapablis malkompakti la elŝutitan dosieron. Tio povas esti pro malkompleta elŝuto, tiaokaze vi devus provi refoje; aŭ eble la kompakta formato ne estas konata, tiaokaze vi bezonos elŝuti kaj instali la kromaĵon permane.';
$lang['error_copy'] = 'Okazis eraro de dosierkopio dum provo instali dosierojn por la kromaĵo <em>%s</em>: la disko povus esti plenplena aŭ aliro-rajtoj povus esti misdifinitaj. Tio povus rezulti en malkomplete instalita kromaĵo kaj igi vian vikion malstabila.';
$lang['error_delete'] = 'Okazis eraro dum provo forigi la kromaĵon <em>%s</em>. Plejprobable tio sekvas de nesufiĉa rajto por aliri la dosieron aŭ ties ujon.';
$lang['enabled'] = 'La kromaĵo %s estas ebligita.';
$lang['notenabled'] = 'La kromaĵo %s ne povis esti ebligita, kontrolu dosier-permesojn.';
$lang['disabled'] = 'La kromaĵo %s estas malebligita.';
$lang['notdisabled'] = 'La kromaĵo %s ne povis esti malebligita, kontrolu dosier-permesojn.'; |
/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
#include <sys/mount.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include "util.h"
#include "mkdir.h"
#include "hashmap.h"
#include "strv.h"
#include "fileio.h"
#include "path-util.h"
#include "special.h"
#include "unit-name.h"
#include "bus-util.h"
#include "bus-error.h"
#include "conf-parser.h"
#include "clean-ipc.h"
#include "logind-user.h"
#include "smack-util.h"
User* user_new(Manager *m, uid_t uid, gid_t gid, const char *name) {
User *u;
assert(m);
assert(name);
u = new0(User, 1);
if (!u)
return NULL;
u->name = strdup(name);
if (!u->name)
goto fail;
if (asprintf(&u->state_file, "/run/systemd/users/"UID_FMT, uid) < 0)
goto fail;
if (hashmap_put(m->users, ULONG_TO_PTR((unsigned long) uid), u) < 0)
goto fail;
u->manager = m;
u->uid = uid;
u->gid = gid;
return u;
fail:
free(u->state_file);
free(u->name);
free(u);
return NULL;
}
void user_free(User *u) {
assert(u);
if (u->in_gc_queue)
LIST_REMOVE(gc_queue, u->manager->user_gc_queue, u);
while (u->sessions)
session_free(u->sessions);
if (u->slice) {
hashmap_remove(u->manager->user_units, u->slice);
free(u->slice);
}
if (u->service) {
hashmap_remove(u->manager->user_units, u->service);
free(u->service);
}
free(u->slice_job);
free(u->service_job);
free(u->runtime_path);
hashmap_remove(u->manager->users, ULONG_TO_PTR((unsigned long) u->uid));
free(u->name);
free(u->state_file);
free(u);
}
int user_save(User *u) {
_cleanup_free_ char *temp_path = NULL;
_cleanup_fclose_ FILE *f = NULL;
int r;
assert(u);
assert(u->state_file);
if (!u->started)
return 0;
r = mkdir_safe_label("/run/systemd/users", 0755, 0, 0);
if (r < 0)
goto finish;
r = fopen_temporary(u->state_file, &f, &temp_path);
if (r < 0)
goto finish;
fchmod(fileno(f), 0644);
fprintf(f,
"# This is private data. Do not parse.\n"
"NAME=%s\n"
"STATE=%s\n",
u->name,
<API key>(user_get_state(u)));
if (u->runtime_path)
fprintf(f, "RUNTIME=%s\n", u->runtime_path);
if (u->service)
fprintf(f, "SERVICE=%s\n", u->service);
if (u->service_job)
fprintf(f, "SERVICE_JOB=%s\n", u->service_job);
if (u->slice)
fprintf(f, "SLICE=%s\n", u->slice);
if (u->slice_job)
fprintf(f, "SLICE_JOB=%s\n", u->slice_job);
if (u->display)
fprintf(f, "DISPLAY=%s\n", u->display->id);
if (<API key>(&u->timestamp))
fprintf(f,
"REALTIME="USEC_FMT"\n"
"MONOTONIC="USEC_FMT"\n",
u->timestamp.realtime,
u->timestamp.monotonic);
if (u->sessions) {
Session *i;
bool first;
fputs("SESSIONS=", f);
first = true;
LIST_FOREACH(sessions_by_user, i, u->sessions) {
if (first)
first = false;
else
fputc(' ', f);
fputs(i->id, f);
}
fputs("\nSEATS=", f);
first = true;
LIST_FOREACH(sessions_by_user, i, u->sessions) {
if (!i->seat)
continue;
if (first)
first = false;
else
fputc(' ', f);
fputs(i->seat->id, f);
}
fputs("\nACTIVE_SESSIONS=", f);
first = true;
LIST_FOREACH(sessions_by_user, i, u->sessions) {
if (!session_is_active(i))
continue;
if (first)
first = false;
else
fputc(' ', f);
fputs(i->id, f);
}
fputs("\nONLINE_SESSIONS=", f);
first = true;
LIST_FOREACH(sessions_by_user, i, u->sessions) {
if (session_get_state(i) == SESSION_CLOSING)
continue;
if (first)
first = false;
else
fputc(' ', f);
fputs(i->id, f);
}
fputs("\nACTIVE_SEATS=", f);
first = true;
LIST_FOREACH(sessions_by_user, i, u->sessions) {
if (!session_is_active(i) || !i->seat)
continue;
if (first)
first = false;
else
fputc(' ', f);
fputs(i->seat->id, f);
}
fputs("\nONLINE_SEATS=", f);
first = true;
LIST_FOREACH(sessions_by_user, i, u->sessions) {
if (session_get_state(i) == SESSION_CLOSING || !i->seat)
continue;
if (first)
first = false;
else
fputc(' ', f);
fputs(i->seat->id, f);
}
fputc('\n', f);
}
fflush(f);
if (ferror(f) || rename(temp_path, u->state_file) < 0) {
r = -errno;
unlink(u->state_file);
unlink(temp_path);
}
finish:
if (r < 0)
log_error_errno(r, "Failed to save user data %s: %m", u->state_file);
return r;
}
int user_load(User *u) {
_cleanup_free_ char *display = NULL, *realtime = NULL, *monotonic = NULL;
Session *s = NULL;
int r;
assert(u);
r = parse_env_file(u->state_file, NEWLINE,
"RUNTIME", &u->runtime_path,
"SERVICE", &u->service,
"SERVICE_JOB", &u->service_job,
"SLICE", &u->slice,
"SLICE_JOB", &u->slice_job,
"DISPLAY", &display,
"REALTIME", &realtime,
"MONOTONIC", &monotonic,
NULL);
if (r < 0) {
if (r == -ENOENT)
return 0;
log_error_errno(r, "Failed to read %s: %m", u->state_file);
return r;
}
if (display)
s = hashmap_get(u->manager->sessions, display);
if (s && s->display && display_is_local(s->display))
u->display = s;
if (realtime) {
unsigned long long l;
if (sscanf(realtime, "%llu", &l) > 0)
u->timestamp.realtime = l;
}
if (monotonic) {
unsigned long long l;
if (sscanf(monotonic, "%llu", &l) > 0)
u->timestamp.monotonic = l;
}
return r;
}
static int <API key>(User *u) {
char *p;
int r;
assert(u);
r = mkdir_safe_label("/run/user", 0755, 0, 0);
if (r < 0)
return log_error_errno(r, "Failed to create /run/user: %m");
if (!u->runtime_path) {
if (asprintf(&p, "/run/user/" UID_FMT, u->uid) < 0)
return log_oom();
} else
p = u->runtime_path;
if (path_is_mount_point(p, false) <= 0) {
_cleanup_free_ char *t = NULL;
mkdir(p, 0700);
if (mac_smack_use())
r = asprintf(&t, "mode=0700,smackfsroot=*,uid=" UID_FMT ",gid=" GID_FMT ",size=%zu", u->uid, u->gid, u->manager->runtime_dir_size);
else
r = asprintf(&t, "mode=0700,uid=" UID_FMT ",gid=" GID_FMT ",size=%zu", u->uid, u->gid, u->manager->runtime_dir_size);
if (r < 0) {
r = log_oom();
goto fail;
}
r = mount("tmpfs", p, "tmpfs", MS_NODEV|MS_NOSUID, t);
if (r < 0) {
log_error_errno(r, "Failed to mount per-user tmpfs directory %s: %m", p);
goto fail;
}
}
u->runtime_path = p;
return 0;
fail:
free(p);
u->runtime_path = NULL;
return r;
}
static int user_start_slice(User *u) {
char *job;
int r;
assert(u);
if (!u->slice) {
<API key> sd_bus_error error = SD_BUS_ERROR_NULL;
char lu[DECIMAL_STR_MAX(uid_t) + 1], *slice;
sprintf(lu, UID_FMT, u->uid);
r = build_subslice(SPECIAL_USER_SLICE, lu, &slice);
if (r < 0)
return r;
r = manager_start_unit(u->manager, slice, &error, &job);
if (r < 0) {
log_error("Failed to start user slice: %s", bus_error_message(&error, r));
free(slice);
} else {
u->slice = slice;
free(u->slice_job);
u->slice_job = job;
}
}
if (u->slice)
hashmap_put(u->manager->user_units, u->slice, u);
return 0;
}
static int user_start_service(User *u) {
<API key> sd_bus_error error = SD_BUS_ERROR_NULL;
char *job;
int r;
assert(u);
if (!u->service) {
char lu[DECIMAL_STR_MAX(uid_t) + 1], *service;
sprintf(lu, UID_FMT, u->uid);
service = unit_name_build("user", lu, ".service");
if (!service)
return log_oom();
r = manager_start_unit(u->manager, service, &error, &job);
if (r < 0) {
log_error("Failed to start user service: %s", bus_error_message(&error, r));
free(service);
} else {
u->service = service;
free(u->service_job);
u->service_job = job;
}
}
if (u->service)
hashmap_put(u->manager->user_units, u->service, u);
return 0;
}
int user_start(User *u) {
int r;
assert(u);
if (u->started)
return 0;
log_debug("New user %s logged in.", u->name);
/* Make XDG_RUNTIME_DIR */
r = <API key>(u);
if (r < 0)
return r;
/* Create cgroup */
r = user_start_slice(u);
if (r < 0)
return r;
/* Spawn user systemd */
r = user_start_service(u);
if (r < 0)
return r;
if (!<API key>(&u->timestamp))
dual_timestamp_get(&u->timestamp);
u->started = true;
/* Save new user data */
user_save(u);
user_send_signal(u, true);
return 0;
}
static int user_stop_slice(User *u) {
<API key> sd_bus_error error = SD_BUS_ERROR_NULL;
char *job;
int r;
assert(u);
if (!u->slice)
return 0;
r = manager_stop_unit(u->manager, u->slice, &error, &job);
if (r < 0) {
log_error("Failed to stop user slice: %s", bus_error_message(&error, r));
return r;
}
free(u->slice_job);
u->slice_job = job;
return r;
}
static int user_stop_service(User *u) {
<API key> sd_bus_error error = SD_BUS_ERROR_NULL;
char *job;
int r;
assert(u);
if (!u->service)
return 0;
r = manager_stop_unit(u->manager, u->service, &error, &job);
if (r < 0) {
log_error("Failed to stop user service: %s", bus_error_message(&error, r));
return r;
}
free(u->service_job);
u->service_job = job;
return r;
}
static int <API key>(User *u) {
int r;
assert(u);
if (!u->runtime_path)
return 0;
r = rm_rf(u->runtime_path, false, false, false);
if (r < 0)
log_error_errno(r, "Failed to remove runtime directory %s: %m", u->runtime_path);
if (umount2(u->runtime_path, MNT_DETACH) < 0)
log_error_errno(errno, "Failed to unmount user runtime directory %s: %m", u->runtime_path);
r = rm_rf(u->runtime_path, false, true, false);
if (r < 0)
log_error_errno(r, "Failed to remove runtime directory %s: %m", u->runtime_path);
free(u->runtime_path);
u->runtime_path = NULL;
return r;
}
int user_stop(User *u, bool force) {
Session *s;
int r = 0, k;
assert(u);
/* Stop jobs have already been queued */
if (u->stopping) {
user_save(u);
return r;
}
LIST_FOREACH(sessions_by_user, s, u->sessions) {
k = session_stop(s, force);
if (k < 0)
r = k;
}
/* Kill systemd */
k = user_stop_service(u);
if (k < 0)
r = k;
/* Kill cgroup */
k = user_stop_slice(u);
if (k < 0)
r = k;
u->stopping = true;
user_save(u);
return r;
}
int user_finalize(User *u) {
Session *s;
int r = 0, k;
assert(u);
if (u->started)
log_debug("User %s logged out.", u->name);
LIST_FOREACH(sessions_by_user, s, u->sessions) {
k = session_finalize(s);
if (k < 0)
r = k;
}
/* Kill XDG_RUNTIME_DIR */
k = <API key>(u);
if (k < 0)
r = k;
/* Clean SysV + POSIX IPC objects */
if (u->manager->remove_ipc) {
k = clean_ipc(u->uid);
if (k < 0)
r = k;
}
unlink(u->state_file);
<API key>(u);
if (u->started) {
user_send_signal(u, false);
u->started = false;
}
return r;
}
int user_get_idle_hint(User *u, dual_timestamp *t) {
Session *s;
bool idle_hint = true;
dual_timestamp ts = { 0, 0 };
assert(u);
LIST_FOREACH(sessions_by_user, s, u->sessions) {
dual_timestamp k;
int ih;
ih = <API key>(s, &k);
if (ih < 0)
return ih;
if (!ih) {
if (!idle_hint) {
if (k.monotonic < ts.monotonic)
ts = k;
} else {
idle_hint = false;
ts = k;
}
} else if (idle_hint) {
if (k.monotonic > ts.monotonic)
ts = k;
}
}
if (t)
*t = ts;
return idle_hint;
}
int <API key>(User *u) {
_cleanup_free_ char *cc = NULL;
char *p = NULL;
cc = cescape(u->name);
if (!cc)
return -ENOMEM;
p = strappenda("/var/lib/systemd/linger/", cc);
return access(p, F_OK) >= 0;
}
bool user_check_gc(User *u, bool drop_not_started) {
assert(u);
if (drop_not_started && !u->started)
return false;
if (u->sessions)
return true;
if (<API key>(u) > 0)
return true;
if (u->slice_job && <API key>(u->manager, u->slice_job))
return true;
if (u->service_job && <API key>(u->manager, u->service_job))
return true;
return false;
}
void <API key>(User *u) {
assert(u);
if (u->in_gc_queue)
return;
LIST_PREPEND(gc_queue, u->manager->user_gc_queue, u);
u->in_gc_queue = true;
}
UserState user_get_state(User *u) {
Session *i;
assert(u);
if (u->stopping)
return USER_CLOSING;
if (u->slice_job || u->service_job)
return USER_OPENING;
if (u->sessions) {
bool all_closing = true;
LIST_FOREACH(sessions_by_user, i, u->sessions) {
SessionState state;
state = session_get_state(i);
if (state == SESSION_ACTIVE)
return USER_ACTIVE;
if (state != SESSION_CLOSING)
all_closing = false;
}
return all_closing ? USER_CLOSING : USER_ONLINE;
}
if (<API key>(u) > 0)
return USER_LINGERING;
return USER_CLOSING;
}
int user_kill(User *u, int signo) {
assert(u);
if (!u->slice)
return -ESRCH;
return manager_kill_unit(u->manager, u->slice, KILL_ALL, signo, NULL);
}
void user_elect_display(User *u) {
Session *graphical = NULL, *text = NULL, *other = NULL, *s;
assert(u);
/* This elects a primary session for each user, which we call
* the "display". We try to keep the assignment stable, but we
* "upgrade" to better choices. */
LIST_FOREACH(sessions_by_user, s, u->sessions) {
if (s->class != SESSION_USER)
continue;
if (s->stopping)
continue;
if (<API key>(s->type))
graphical = s;
else if (s->type == SESSION_TTY)
text = s;
else
other = s;
}
if (graphical &&
(!u->display ||
u->display->class != SESSION_USER ||
u->display->stopping ||
!<API key>(u->display->type))) {
u->display = graphical;
return;
}
if (text &&
(!u->display ||
u->display->class != SESSION_USER ||
u->display->stopping ||
u->display->type != SESSION_TTY)) {
u->display = text;
return;
}
if (other &&
(!u->display ||
u->display->class != SESSION_USER ||
u->display->stopping))
u->display = other;
}
static const char* const user_state_table[_USER_STATE_MAX] = {
[USER_OFFLINE] = "offline",
[USER_OPENING] = "opening",
[USER_LINGERING] = "lingering",
[USER_ONLINE] = "online",
[USER_ACTIVE] = "active",
[USER_CLOSING] = "closing"
};
<API key>(user_state, UserState);
int <API key>(
const char* unit,
const char *filename,
unsigned line,
const char *section,
unsigned section_line,
const char *lvalue,
int ltype,
const char *rvalue,
void *data,
void *userdata) {
size_t *sz = data;
const char *e;
int r;
assert(filename);
assert(lvalue);
assert(rvalue);
assert(data);
e = endswith(rvalue, "%");
if (e) {
unsigned long ul;
char *f;
errno = 0;
ul = strtoul(rvalue, &f, 10);
if (errno != 0 || f != e) {
log_syntax(unit, LOG_ERR, filename, line, errno ? errno : EINVAL, "Failed to parse percentage value, ignoring: %s", rvalue);
return 0;
}
if (ul <= 0 || ul >= 100) {
log_syntax(unit, LOG_ERR, filename, line, errno ? errno : EINVAL, "Percentage value out of range, ignoring: %s", rvalue);
return 0;
}
*sz = PAGE_ALIGN((size_t) ((physical_memory() * (uint64_t) ul) / (uint64_t) 100));
} else {
off_t o;
r = parse_size(rvalue, 1024, &o);
if (r < 0 || (off_t) (size_t) o != o) {
log_syntax(unit, LOG_ERR, filename, line, r < 0 ? -r : ERANGE, "Failed to parse size value, ignoring: %s", rvalue);
return 0;
}
*sz = PAGE_ALIGN((size_t) o);
}
return 0;
} |
<?php
if($view_params['layout_structure'] == 'full') return false;
$video_atts = array(
'bg_video' => $view_params['bg_video'],
'poster_image' => $view_params['poster_image'],
'video_loop' => $view_params['video_loop'],
'mp4' => $view_params['mp4'],
'webm' => $view_params['webm'],
'ogv' => $view_params['ogv'],
'stream_host_website' => $view_params['stream_host_website'],
'stream_video_id' => $view_params['stream_video_id'],
);
?>
<div class="mk-half-layout <?php echo $view_params['layout_structure']; ?>_layout">
<?php echo <API key>('mk_page_section', 'components/video-background', true, $video_atts); ?>
</div>
<div class="<API key> <API key> <?php echo $view_params['layout_structure']; ?>_layout">
<?php echo <API key>( $view_params['content'] ); ?>
</div> |
//recursive
class Solution {
public:
int maxDepth(TreeNode* root){
if(root==nullptr) return 0;
return max(maxDepth(root->left), maxDepth(root->right))+1;
}
};
//DFSdepth+10
//BFSqueue
//DFSiterative
//stack
// stackstack
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
struct node{
TreeNode* p;
int cnt;
node(TreeNode* p, int cnt):p(p),cnt(cnt){}
};
int maxDepth(TreeNode* root) {
if(root==NULL) return 0;
stack<node> s;
s.push(node(root, 1));
int max = 1;
while(!s.empty()){
node cur = s.top();
s.pop();
if(cur.p->right){
s.push(node(cur.p->right, cur.cnt+1));
if(cur.cnt+1>max) max = cur.cnt+1;
}
if(cur.p->left){
s.push(node(cur.p->left, cur.cnt+1));
if(cur.cnt+1>max) max = cur.cnt+1;
}
}
return max;
}
}; |
from __future__ import print_function
# Listen to hotplug events. Can be used to listen for hotplug events and
# similar things, like network connections being (un)plugged.
import os
import socket
import six
class NetlinkSocket(socket.socket):
def __init__(self):
<API key> = 15 # hasn't landed in socket yet, see linux/netlink.h
socket.socket.__init__(self, socket.AF_NETLINK, socket.SOCK_DGRAM, <API key>)
self.bind((os.getpid(), -1))
def parse(self):
data = six.ensure_str(self.recv(512))
event = {}
for item in data.split('\x00'):
if not item:
# terminator
yield event
event = {}
else:
try:
k, v = item.split('=', 1)
event[k] = v
except:
event[None] = item
# Quick unit test (you can run this on any Linux machine)
if __name__ == '__main__':
nls = NetlinkSocket()
print("socket no:", nls.fileno())
while True:
for item in nls.parse():
print(repr(item)) |
<?php
class Language
{
static private $xml;
/**
* Load a language xml file into a SimpleXML Object for use in this class
* @param string $language Language to be loaded
* @return void The given language xml file is stored into memory
*/
public static function loadLangPack($language)
{
$lang_file = DOC_ROOT . '/cc-content/languages/' . $language . '.xml';
self::$xml = simplexml_load_file($lang_file);
}
/**
* Retrieve text from the loaded language xml file
* @param string $node The name of the language xml node to retrieve
* @param array $replace Optional Replacements for placeholders (See Functions::Replace for more deails)
* @return string The requested string is returned with replacements made
* to it or boolean false if requested node is invalid
*/
public static function getText($node, $replace = array())
{
// Retrieve node text if it exists
if (isset(self::$xml->terms->$node)) {
$string = self::$xml->terms->$node;
// Check for text replacements
if (!empty($replace)) {
$string = Functions::replace($string, $replace);
}
return (string) $string;
} else {
return false;
}
}
/**
* Retrieve custom text from the loaded language xml file
* @param string $node The name of the custom language xml node to retrieve
* @param array $replace Optional Replacements for placeholders (See Functions::Replace for more deails)
* @return string The requested string is returned with replacements made
* to it or boolean false if requested node is invalid
*/
public static function getCustomText($node, $replace = array())
{
// Retrieve node text if it exists
if (isset(self::$xml->custom->$node)) {
$string = self::$xml->custom->$node;
// Check for text replacements
if (!empty($replace)) {
$string = Functions::replace($string, $replace);
}
return $string;
} else {
return false;
}
}
/**
* Output the formal human readable name of the loaded language
* @param boolean $native (optional) Whether or not to return the native translation for the current language
* @return string The language name in the language xml file
*/
public static function getLanguage($native = false)
{
return ($native) ? self::$xml->information->native_name : self::$xml->information->lang_name;
}
/**
* Output the CSS-friendly name of the loaded language for use in stylesheets
* @return string The CSS language name in the language xml file
*/
public static function getCSSName()
{
return self::$xml->information->css_name;
}
/**
* Retrieve all the meta information for a given page
* @param string $page Page whose information to look up
* @return object Returns simple xml object representing that page's node
*/
public static function getMeta($page)
{
return (empty(self::$xml->meta->$page)) ? new stdClass() : self::$xml->meta->$page;
}
/**
* Retrieve a list of active languages
* @return array Returns a list of active languages
*/
public static function getActiveLanguages()
{
$active = Settings::get('active_languages');
return json_decode($active);
}
} |
<?php
class payplus6 extends EpayPlugin {
var $plugin_info;
function pluginInstall($args)
{
// mkdir
FileHandler::makeDir(sprintf(_XE_PATH_."files/epay/%s/log",$args->plugin_srl));
// copy files
FileHandler::copyFile(_XE_PATH_.'modules/epay/plugins/payplus6/.htaccess',sprintf(_XE_PATH_."files/epay/%s/.htaccess",$args->plugin_srl));
FileHandler::copyFile(_XE_PATH_.'modules/epay/plugins/payplus6/readme.txt',sprintf(_XE_PATH_."files/epay/%s/readme.txt",$args->plugin_srl));
}
function payplus6()
{
parent::EpayPlugin();
}
function init(&$args)
{
$this->plugin_info = new StdClass();
foreach ($args as $key=>$val)
{
$this->plugin_info->{$key} = $val;
}
foreach ($args->extra_var as $key=>$val)
{
$this->plugin_info->{$key} = $val->value;
}
if ($this->plugin_info->service_mode == 'test')
{
$this->plugin_info->site_cd = "T0000" ;
$this->plugin_info->site_key = "3grptw1.zW0GSo4PQdaGvsF__";
}
Context::set('plugin_info', $this->plugin_info);
}
/**
* item_name
* price
* purchaser_name
* purchaser_email
* purchaser_telnum
*/
function getFormData($args)
{
if (!$args->price) return $this->makeObject(0,'No input of price');
if (!$args->epay_module_srl) return $this->makeObject(-1,'No input of epay_module_srl');
if (!$args->module_srl) return $this->makeObject(-1,'No input of module_srl');
Context::set('module_srl', $args->module_srl);
Context::set('epay_module_srl', $args->epay_module_srl);
Context::set('plugin_srl', $this->plugin_info->plugin_srl);
Context::set('item_name', $args->item_name);
Context::set('purchaser_name', $args->purchaser_name);
Context::set('purchaser_email', $args->purchaser_email);
Context::set('purchaser_cellphone', $args->purchaser_cellphone);
Context::set('purchaser_telnum', $args->purchaser_telnum);
Context::set('<API key>', $args-><API key>);
Context::set('join_form', $args->join_form);
$oTemplate = &TemplateHandler::getInstance();
$tpl_path = _XE_PATH_."modules/epay/plugins/payplus6/tpl";
$tpl_file = 'formdata.html';
$form_data = $oTemplate->compile($tpl_path, $tpl_file);
$output = $this->makeObject();
$output->data = $form_data;
return $output;
}
function processReview($args) {
/*
$inipayhome = sprintf(_XE_PATH_."files/epay/%s", $args->plugin_srl);
Context::set('encfield', $inipay->GetResult('encfield'));
Context::set('certid', $inipay->GetResult('certid'));
Context::set('inicis_id', $this->inicis_id);
$_SESSION['PAYPLUS_PRICE'] = $args->price;
*/
if(isset($args->service_period) && is_array($args->service_period))
{
Context::set('good_expr', '1:' . $args->service_period[0] . $args->service_period[1]);
}
else
{
Context::set('good_expr', '0');
}
Context::set('order_srl', $args->order_srl);
Context::set('price', $args->price);
Context::set('buyr_name', $args->purchaser_name);
Context::set('buyr_mail', $args->purchaser_email);
Context::set('buyr_tel1', $args->purchaser_cellphone);
Context::set('buyr_tel2', $args->purchaser_telnum);
Context::set('params', $args);
$oTemplate = &TemplateHandler::getInstance();
$tpl_path = _XE_PATH_."modules/epay/plugins/payplus6/tpl";
$tpl_file = 'review.html';
$tpl_data = $oTemplate->compile($tpl_path, $tpl_file);
$output = $this->makeObject();
$output->add('tpl_data', $tpl_data);
return $output;
}
function processPayment($args) {
$vars = Context::getRequestVars();
extract(get_object_vars($vars));
require("libs/pp_ax_hub_lib.php");
// initialize variables
$amount = $good_mny;
$c_PayPlus = new C_PP_CLI;
$c_PayPlus->mf_clear();
if ($req_tx == "pay")
{
$c_PayPlus->mf_set_encx_data($enc_data, $enc_info);
}
else if ($req_tx == 'mod')
{
$tran_cd = '00200000';
$c_PayPlus->mf_set_modx_data('tno', $tno);
$c_PayPlus->mf_set_modx_data('mod_type', $mod_type);
$c_PayPlus->mf_set_modx_data('mod_ip', $cust_ip);
$c_PayPlus->mf_set_modx_data('mod_desc', $mod_desc);
}
if ($tran_cd != "")
{
$g_conf_bin_dir = dirname(__FILE__);
$g_conf_home_dir = sprintf(_XE_PATH_."files/epay/%s", $args->plugin_srl);
if ($this->plugin_info->service_mode == 'test')
{
$g_conf_gw_url = "testpaygw.kcp.co.kr";
}
else
{
$g_conf_gw_url = "paygw.kcp.co.kr"; // real service
}
$g_conf_site_cd = $this->plugin_info->site_cd;
$g_conf_site_key = $this->plugin_info->site_key;
$g_conf_site_name = $this->plugin_info->site_name;
$g_conf_log_level = "3";
$g_conf_gw_port = "8090";
$c_PayPlus->mf_do_tx($trace_no, $g_conf_bin_dir, $g_conf_home_dir, $g_conf_site_cd, $g_conf_site_key, $tran_cd, "",
$g_conf_gw_url, $g_conf_gw_port, "payplus_cli_slib", $ordr_idxx,
$cust_ip, "3" , 0, 0);
$res_cd = $c_PayPlus->m_res_cd;
$res_msg = iconv('EUC-KR', 'UTF-8', $c_PayPlus->m_res_msg);
}
else
{
$c_PayPlus->m_res_cd = "9562";
$c_PayPlus->m_res_msg = " |Payplus Plugin tran_cd .";
}
if ($req_tx == 'pay')
{
if ($res_cd == '0000')
{
$tno = $c_PayPlus->mf_get_res_data('tno'); // KCP
$amount = $c_PayPlus->mf_get_res_data('amount'); // KCP
$pnt_issue = $c_PayPlus->mf_get_res_data('pnt_issue');
if ($use_pay_method == '100000000000')
{
$card_cd = $c_PayPlus->mf_get_res_data("card_cd");
$card_name = $c_PayPlus->mf_get_res_data("card_name");
$app_time = $c_PayPlus->mf_get_res_data("app_time");
$app_no = $c_PayPlus->mf_get_res_data("app_no");
$noinf = $c_PayPlus->mf_get_res_data("noinf");
$quota = $c_PayPlus->mf_get_res_data("quota");
}
if ( $use_pay_method == "001000000000" )
{
$bankname = iconv('EUC-KR','UTF-8',$c_PayPlus->mf_get_res_data("bankname"));
$depositor = iconv('EUC-KR','UTF-8',$c_PayPlus->mf_get_res_data("depositor"));
$account = $c_PayPlus->mf_get_res_data("account");
$va_date = $c_PayPlus->mf_get_res_data("va_date");
}
}
}
// error check
if ($res_cd != '0000')
{
$output = $this->makeObject(-1, $res_msg);
$output->add('state', constant('STATE_FAILURE')); // failure
}
else
{
$output = $this->makeObject(0, $utf8ResultMsg);
if ($this->getPaymethod($use_pay_method)=='VA')
{
$output->add('state', constant('STATE_NOTCOMPLETED')); // not completed
} else {
$output->add('state', constant('STATE_COMPLETED')); // completed (success)
}
}
$output->add('payment_method', $this->getPaymethod($use_pay_method));
$output->add('payment_amount', $amount);
$output->add('result_code', $res_cd);
$output->add('result_message', $res_msg);
$output->add('vact_bankname', $bankname);
$output->add('vact_num', $account);
$output->add('vact_name', $depositor);
$output->add('vact_date', $va_date);
$output->add('pg_tid', $tno);
return $output;
}
function processReport(&$transaction) {
$payplushome = sprintf(_XE_PATH_."files/epay/%s", $transaction->plugin_srl);
$TEMP_IP = $_SERVER["REMOTE_ADDR"];
$PG_IP = substr($TEMP_IP,0, 10);
//PG IP
if ($PG_IP != "203.238.36") {
return $this->makeObject(-1, 'msg_invalid_request');
}
$logfile = fopen($payplushome."/log/vbank_" . date("Ymd") . ".log", "a+");
fwrite( $logfile,"************************************************\n");
$vars = Context::getRequestVars();
foreach ($vars as $key=>$val) {
fwrite( $logfile,$key." : ".$val."\n");
}
fwrite( $logfile,"************************************************\n\n");
fclose( $logfile );
$output = $this->makeObject();
$output->order_srl = Context::get('ordr_idxx');
$output->amount = Context::get('totl_mnyx');
if ($output->amount == $transaction->payment_amount)
{
$output->setError(0);
$output->state = '2';
}
else
{
$output->setError(-1);
$output->setMessage('amount not match');
$output->state = '1';
}
return $output;
}
function getReceipt($pg_tid)
{
Context::set('tid', $pg_tid);
$oTemplate = &TemplateHandler::getInstance();
$tpl_path = _XE_PATH_."modules/epay/plugins/payplus6/tpl";
$tpl_file = 'receipt.html';
$tpl = $oTemplate->compile($tpl_path, $tpl_file);
return $tpl;
}
// MUST return order_srl
function getReport() {
$output = $this->makeObject();
$output->order_srl = Context::get('ordr_idxx');
$output->amount = Context::get('totl_mnyx');
return $output;
}
function getPaymethod($paymethod) {
switch ($paymethod) {
case '001000000000':
return 'VA';
case '100000000000':
return 'CC';
case '000010000000':
return 'MP';
case '010000000000':
return 'IB';
default:
return ' ';
}
}
}
/* End of file payplus6.plugin.php */
/* Location: ./modules/epay/plugins/payplus6/payplus6.plugin.php */ |
define([
"jquery" , "underscore" , "backbone"
, "collections/snippets" , "collections/my-form-snippets"
, "views/tab" , "views/my-form"
, "text!data/input.json", "text!data/radio.json", "text!data/select.json", "text!data/buttons.json", "text!data/extras.json"
, "text!templates/app/render.html", "text!templates/app/about.html",
], function(
$, _, Backbone
, SnippetsCollection, <API key>
, TabView, MyFormView
, inputJSON, radioJSON, selectJSON, buttonsJSON, extrasJSON
, renderTab, aboutTab
){
return {
initialize: function(){
//Bootstrap tabs from json.
new TabView({
title: "Input"
, collection: new SnippetsCollection(JSON.parse(inputJSON))
});
new TabView({
title: "Radios / Checkboxes"
, collection: new SnippetsCollection(JSON.parse(radioJSON))
});
new TabView({
title: "Select"
, collection: new SnippetsCollection(JSON.parse(selectJSON))
});
new TabView({
title: "Buttons"
, collection: new SnippetsCollection(JSON.parse(buttonsJSON))
});
new TabView({
title: "Extras"
, collection: new SnippetsCollection(JSON.parse(extrasJSON))
});
new TabView({
title: "Rendered"
, content: renderTab
});
new TabView({
title: "About"
, content: aboutTab
});
//Make the first tab active!
$("#components .tab-pane").first().addClass("active");
$("#formtabs li").first().addClass("active");
// Bootstrap "My Form" with 'Form Name' snippet.
new MyFormView({
title: "Original"
, collection: new <API key>([
{ "title" : "Form Name"
, "fields": {
"name" : {
"label" : "Form Name"
, "type" : "input"
, "value" : "Form Name"
}
}
}
])
});
}
}
}); |
<?php // $Id: version.php,v 1.4 2009/07/15 18:23:19 adelamarre Exp $
Code fragment to define the version of label
This fragment is called by <API key>() and /admin/index.php
$module->version = 2009042404;
$module->requires = 2007101509; // Requires this Moodle version
$module->cron = 0; // Period for cron to check this module (secs)
?> |
<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>pair_style smtbq command — LAMMPS documentation</title>
<link rel="stylesheet" href="_static/css/theme.css" type="text/css" />
<link rel="stylesheet" href="_static/<API key>/LightBox2/lightbox2/css/lightbox.css" type="text/css" />
<link rel="top" title="LAMMPS documentation" href="index.html"/>
<script src="_static/js/modernizr.min.js"></script>
</head>
<body class="wy-body-for-nav" role="document">
<div class="wy-grid-for-nav">
<nav data-toggle="wy-nav-shift" class="wy-nav-side">
<div class="wy-side-nav-search">
<a href="Manual.html" class="icon icon-home"> LAMMPS
</a>
<div role="search">
<form id="rtd-search-form" class="wy-form" action="search.html" method="get">
<input type="text" name="q" placeholder="Search docs" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div>
<div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
<ul>
<li class="toctree-l1"><a class="reference internal" href="Section_intro.html">1. Introduction</a></li>
<li class="toctree-l1"><a class="reference internal" href="Section_start.html">2. Getting Started</a></li>
<li class="toctree-l1"><a class="reference internal" href="Section_commands.html">3. Commands</a></li>
<li class="toctree-l1"><a class="reference internal" href="Section_packages.html">4. Packages</a></li>
<li class="toctree-l1"><a class="reference internal" href="Section_accelerate.html">5. Accelerating LAMMPS performance</a></li>
<li class="toctree-l1"><a class="reference internal" href="Section_howto.html">6. How-to discussions</a></li>
<li class="toctree-l1"><a class="reference internal" href="Section_example.html">7. Example problems</a></li>
<li class="toctree-l1"><a class="reference internal" href="Section_perf.html">8. Performance & scalability</a></li>
<li class="toctree-l1"><a class="reference internal" href="Section_tools.html">9. Additional tools</a></li>
<li class="toctree-l1"><a class="reference internal" href="Section_modify.html">10. Modifying & extending LAMMPS</a></li>
<li class="toctree-l1"><a class="reference internal" href="Section_python.html">11. Python interface to LAMMPS</a></li>
<li class="toctree-l1"><a class="reference internal" href="Section_errors.html">12. Errors</a></li>
<li class="toctree-l1"><a class="reference internal" href="Section_history.html">13. Future and history</a></li>
</ul>
</div>
</nav>
<section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">
<nav class="wy-nav-top" role="navigation" aria-label="top navigation">
<i data-toggle="wy-nav-top" class="fa fa-bars"></i>
<a href="Manual.html">LAMMPS</a>
</nav>
<div class="wy-nav-content">
<div class="rst-content">
<div role="navigation" aria-label="breadcrumbs navigation">
<ul class="wy-breadcrumbs">
<li><a href="Manual.html">Docs</a> »</li>
<li>pair_style smtbq command</li>
<li class="<API key>">
<a href="http://lammps.sandia.gov">Website</a>
<a href="Section_commands.html#comm">Commands</a>
</li>
</ul>
<hr/>
</div>
<div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
<div itemprop="articleBody">
<div class="section" id="<API key>">
<span id="index-0"></span><h1>pair_style smtbq command</h1>
<div class="section" id="syntax">
<h2>Syntax</h2>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">pair_style</span> <span class="n">smtbq</span>
</pre></div>
</div>
</div>
<div class="section" id="examples">
<h2>Examples</h2>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">pair_style</span> <span class="n">smtbq</span>
<span class="n">pair_coeff</span> <span class="o">*</span> <span class="o">*</span> <span class="n">ffield</span><span class="o">.</span><span class="n">smtbq</span><span class="o">.</span><span class="n">Al2O3</span> <span class="n">O</span> <span class="n">Al</span>
</pre></div>
</div>
</div>
<div class="section" id="description">
<h2>Description</h2>
<p>This pair stylecomputes a variable charge SMTB-Q (Second-Moment
tight-Binding QEq) potential as described in <a class="reference internal" href="#smtb-q-1"><span class="std std-ref">SMTB-Q_1</span></a> and
<a class="reference internal" href="#smtb-q-2"><span class="std std-ref">SMTB-Q_2</span></a>. Briefly, the energy of metallic-oxygen systems
is given by three contributions:</p>
<img alt="_images/pair_smtbq1.jpg" class="align-center" src="_images/pair_smtbq1.jpg" />
<p>where <em>E<sub>tot</sub></em> is the total potential energy of the system,
<em>E<sub>ES</sub></em> is the electrostatic part of the total energy,
<em>E<sub>OO</sub></em> is the interaction between oxygens and
<em>E<sub>MO</sub></em> is a short-range interaction between metal and oxygen
atoms. This interactions depend on interatomic distance
<em>r<sub>ij</sub></em> and/or the charge <em>Q<sub>i</sub></em> of atoms
<em>i</em>. Cut-off function enables smooth convergence to zero interaction.</p>
<p>The parameters appearing in the upper expressions are set in the
ffield.SMTBQ.Syst file where Syst corresponds to the selected system
(e.g. field.SMTBQ.Al2O3). Exemples for TiO<sub>2</sub>,
Al<sub>2</sub>O<sub>3</sub> are provided. A single pair_coeff command
is used with the SMTBQ styles which provides the path to the potential
file with parameters for needed elements. These are mapped to LAMMPS
atom types by specifying additional arguments after the potential
filename in the pair_coeff command. Note that atom type 1 must always
correspond to oxygen atoms. As an example, to simulate a TiO2 system,
atom type 1 has to be oxygen and atom type 2 Ti. The following
pair_coeff command should then be used:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">pair_coeff</span> <span class="o">*</span> <span class="o">*</span> <span class="n">PathToLammps</span><span class="o">/</span><span class="n">potentials</span><span class="o">/</span><span class="n">ffield</span><span class="o">.</span><span class="n">smtbq</span><span class="o">.</span><span class="n">TiO2</span> <span class="n">O</span> <span class="n">Ti</span>
</pre></div>
</div>
<p>The electrostatic part of the energy consists of two components</p>
<p>self-energy of atom <em>i</em> in the form of a second order charge dependent
polynomial and a long-range Coulombic electrostatic interaction. The
latter uses the wolf summation method described in <a class="reference internal" href="#wolf"><span class="std std-ref">Wolf</span></a>,
spherically truncated at a longer cutoff, <em>R<sub>coul</sub></em>. The
charge of each ion is modeled by an orbital Slater which depends on
the principal quantum number (<em>n</em>) of the outer orbital shared by the
ion.</p>
<p>Interaction between oxygen, <em>E<sub>OO</sub></em>, consists of two parts,
an attractive and a repulsive part. The attractive part is effective
only at short range (< r<sub>2</sub><sup>OO</sup>). The attractive
contribution was optimized to study surfaces reconstruction
(e.g. <a class="reference internal" href="#smtb-q-2"><span class="std std-ref">SMTB-Q_2</span></a> in TiO<sub>2</sub>) and is not necessary
for oxide bulk modeling. The repulsive part is the Pauli interaction
between the electron clouds of oxygen. The Pauli repulsion and the
coulombic electrostatic interaction have same cut off value. In the
ffield.SMTBQ.Syst, the keyword <em>‘buck’</em> allows to consider only the
repulsive O-O interactions. The keyword <em>‘buckPlusAttr’</em> allows to
consider the repulsive and the attractive O-O interactions.</p>
<p>The short-range interaction between metal-oxygen, <em>E<sub>MO</sub></em> is
based on the second moment approximation of the density of states with
a N-body potential for the band energy term,
<em>E<sup>i</sup><sub>cov</sub></em>, and a Born-Mayer type repulsive terms
as indicated by the keyword <em>‘second_moment’</em> in the
ffield.SMTBQ.Syst. The energy band term is given by:</p>
<img alt="_images/pair_smtbq2.jpg" class="align-center" src="_images/pair_smtbq2.jpg" />
<p>where <em>&#951<sub>i</sub></em> is the stoichiometry of atom <em>i</em>,
<em>&#948Q<sub>i</sub></em> is the charge delocalization of atom <em>i</em>,
compared to its formal charge
<em>Q<sup>F</sup><sub>i</sub></em>. n<sub>0</sub>, the number of hybridized
orbitals, is calculated with to the atomic orbitals shared
<em>d<sub>i</sub></em> and the stoichiometry
<em>&#951<sub>i</sub></em>. <em>r<sub>c1</sub></em> and <em>r<sub>c2</sub></em> are the two
cutoff radius around the fourth neighbors in the cutoff function.</p>
<p>In the formalism used here, <em>&#958<sup>0</sup></em> is the energy
parameter. <em>&#958<sup>0</sup></em> is in tight-binding approximation the
hopping integral between the hybridized orbitals of the cation and the
anion. In the literature we find many ways to write the hopping
integral depending on whether one takes the point of view of the anion
or cation. These are equivalent vision. The correspondence between the
two visions is explained in appendix A of the article in the
SrTiO<sub>3</sub> <a class="reference internal" href="#smtb-q-3"><span class="std std-ref">SMTB-Q_3</span></a> (parameter <em>&#946</em> shown in
this article is in fact the <em>&#946<sub>O</sub></em>). To summarize the
relationship between the hopping integral <em>&#958<sup>0</sup></em> and the
others, we have in an oxide C<sub>n</sub>O<sub>m</sub> the following
relationship:</p>
<img alt="_images/pair_smtbq3.jpg" class="align-center" src="_images/pair_smtbq3.jpg" />
<p>Thus parameter &#956, indicated above, is given by : &#956 = (&#8730n
+ &#8730m) &#8260 2</p>
<p>The potential offers the possibility to consider the polarizability of
the electron clouds of oxygen by changing the slater radius of the
charge density around the oxygens through the parameters <em>rBB, rB and
rS</em> in the ffield.SMTBQ.Syst. This change in radius is performed
according to the method developed by E. Maras
<a class="reference internal" href="#smtb-q-2"><span class="std std-ref">SMTB-Q_2</span></a>. This method needs to determine the number of
nearest neighbors around the oxygen. This calculation is based on
first (<em>r<sub>1n</sub></em>) and second (<em>r<sub>2n</sub></em>) distances
neighbors.</p>
<p>The SMTB-Q potential is a variable charge potential. The equilibrium
charge on each atom is calculated by the electronegativity
equalization (QEq) method. See <a class="reference internal" href="#rick"><span class="std std-ref">Rick</span></a> for further detail. One
can adjust the frequency, the maximum number of iterative loop and the
convergence of the equilibrium charge calculation. To obtain the
energy conservation in NVE thermodynamic ensemble, we recommend to use
a convergence parameter in the interval 10<sup>-5</sup> -
10<sup>-6</sup> eV.</p>
<p>The ffield.SMTBQ.Syst files are provided for few systems. They consist
of nine parts and the lines beginning with ‘#’ are comments (note that
the number of comment lines matter). The first sections are on the
potential parameters and others are on the simulation options and
might be modified. Keywords are character type and must be enclosed in
quotation marks (‘’).</p>
<ol class="arabic simple">
<li>Number of different element in the oxide:</li>
</ol>
<ul class="simple">
<li>N<sub>elem</sub>= 2 or 3</li>
<li>Divided line</li>
</ul>
<ol class="arabic simple" start="2">
<li>Atomic parameters</li>
</ol>
<p>For the anion (oxygen)</p>
<ul class="simple">
<li>Name of element (char) and stoichiometry in oxide</li>
<li>Formal charge and mass of element</li>
<li>Principal quantic number of outer orbital (<em>n</em>), electronegativity (<em>&#967<sup>0</sup><sub>i</simulationub></em>) and hardness (<em>J<sup>0</sup><sub>i</sub></em>)</li>
<li>Ionic radius parameters : max coordination number (<em>coordBB</em> = 6 by default), bulk coordination number <em>(coordB)</em>, surface coordination number <em>(coordS)</em> and <em>rBB, rB and rS</em> the slater radius for each coordination number. (<b>note : If you don’t want to change the slater radius, use three identical radius values</b>)</li>
<li>Number of orbital shared by the element in the oxide (<em>d<sub>i</sub></em>)</li>
<li>Divided line</li>
</ul>
<p>For each cations (metal):</p>
<ul class="simple">
<li>Name of element (char) and stoichiometry in oxide</li>
<li>Formal charge and mass of element</li>
<li>Number of electron in outer orbital <em>(ne)</em>, electronegativity (<em>&#967<sup>0</sup><sub>i</simulationub></em>), hardness (<em>J<sup>0</sup><sub>i</sub></em>) and <em>r<sub>Salter</sub></em> the slater radius for the cation.</li>
<li>Number of orbitals shared by the elements in the oxide (<em>d<sub>i</sub></em>)</li>
<li>Divided line</li>
</ul>
<ol class="arabic simple" start="3">
<li>Potential parameters:</li>
</ol>
<ul class="simple">
<li>Keyword for element1, element2 and interaction potential (‘second_moment’ or ‘buck’ or ‘buckPlusAttr’) between element 1 and 2. If the potential is ‘second_moment’, specify ‘oxide’ or ‘metal’ for metal-oxygen or metal-metal interactions respectively.</li>
<li>Potential parameter: <pre><br/> If type of potential is ‘second_moment’ : <em>A (eV)</em>, <em>p</em>, <em>&#958<sup>0</sup></em> (eV) and <em>q</em> <br/> <em>r<sub>c1</sub></em> (&#197), <em>r<sub>c2</sub></em> (&#197) and <em>r<sub>0</sub></em> (&#197) <br/> If type of potential is ‘buck’ : <em>C</em> (eV) and <em>&#961</em> (&#197) <br/> If type of potential is ‘buckPlusAttr’ : <em>C</em> (eV) and <em>&#961</em> (&#197) <br/> <em>D</em> (eV), <em>B</em> (&#197<sup>-1</sup>), <em>r<sub>1</sub><sup>OO</sup></em> (&#197) and <em>r<sub>2</sub><sup>OO</sup></em> (&#197) </pre></li>
<li>Divided line</li>
</ul>
<ol class="arabic simple" start="4">
<li>Tables parameters:</li>
</ol>
<ul class="simple">
<li>Cutoff radius for the Coulomb interaction (<em>R<sub>coul</sub></em>)</li>
<li>Starting radius (<em>r<sub>min</sub></em> = 1,18845 &#197) and increments (<em>dr</em> = 0,001 &#197) for creating the potential table.</li>
<li>Divided line</li>
</ul>
<ol class="arabic simple" start="5">
<li>Rick model parameter:</li>
</ol>
<ul class="simple">
<li><em>Nevery</em> : parameter to set the frequency (<em>1/Nevery</em>) of the charge resolution. The charges are evaluated each <em>Nevery</em> time steps.</li>
<li>Max number of iterative loop (<em>loopmax</em>) and precision criterion (<em>prec</em>) in eV of the charge resolution</li>
<li>Divided line</li>
</ul>
<ol class="arabic simple" start="6">
<li>Coordination parameter:</li>
</ol>
<ul class="simple">
<li>First (<em>r<sub>1n</sub></em>) and second (<em>r<sub>2n</sub></em>) neighbor distances in &#197</li>
<li>Divided line</li>
</ul>
<ol class="arabic simple" start="7">
<li>Charge initialization mode:</li>
</ol>
<ul class="simple">
<li>Keyword (<em>QInitMode</em>) and initial oxygen charge (<em>Q<sub>init</sub></em>). If keyword = ‘true’, all oxygen charges are initially set equal to <em>Q<sub>init</sub></em>. The charges on the cations are initially set in order to respect the neutrality of the box. If keyword = ‘false’, all atom charges are initially set equal to 0 if you use “create_atom”#create_atom command or the charge specified in the file structure using <a class="reference internal" href="read_data.html"><span class="doc">read_data</span></a> command.</li>
<li>Divided line</li>
</ul>
<ol class="arabic simple" start="8">
<li>Mode for the electronegativity equalization (Qeq)</li>
</ol>
<ul class="simple">
<li>Keyword mode: <pre> <br/> QEqAll (one QEq group) | no parameters <br/> QEqAllParallel (several QEq groups) | no parameters <br/> Surface | zlim (QEq only for z>zlim) </pre></li>
<li>Parameter if necessary</li>
<li>Divided line</li>
</ul>
<ol class="arabic simple" start="9">
<li>Verbose</li>
</ol>
<ul class="simple">
<li>If you want the code to work in verbose mode or not : ‘true’ or ‘false’</li>
<li>If you want to print or not in file ‘Energy_component.txt’ the three main contributions to the energy of the system according to the description presented above : ‘true’ or ‘false’ and <em>N<sub>Energy</sub></em>. This option writes in file every <em>N<sub>Energy</sub></em> time step. If the value is ‘false’ then <em>N<sub>Energy</sub></em> = 0. The file take into account the possibility to have several QEq group <em>g</em> then it writes: time step, number of atoms in group <em>g</em>, electrostatic part of energy, <em>E<sub>ES</sub></em>, the interaction between oxygen, <em>E<sub>OO</sub></em>, and short range metal-oxygen interaction, <em>E<sub>MO</sub></em>.</li>
<li>If you want to print in file ‘<API key>.txt’ the electronegativity component (<em>&#8706E<sub>tot</sub> &#8260&#8706Q<sub>i</sub></em>) or not: ‘true’ or ‘false’ and <em>N<sub>Electroneg</sub></em>.This option writes in file every <em>N<sub>Electroneg</sub></em> time step. If the value is ‘false’ then <em>N<sub>Electroneg</sub></em> = 0. The file consist in atom number <em>i</em>, atom type (1 for oxygen and # higher than 1 for metal), atom position: <em>x</em>, <em>y</em> and <em>z</em>, atomic charge of atom <em>i</em>, electrostatic part of atom <em>i</em> electronegativity, covalent part of atom <em>i</em> electronegativity, the hopping integral of atom <em>i</em> <em>(Z&#946<sup>2</sup>)<sub>i<sub></em> and box electronegativity.</li>
</ul>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This last option slows down the calculation dramatically. Use
only with a single processor simulation.</p>
</div>
<hr class="docutils" />
<p><strong>Mixing, shift, table, tail correction, restart, rRESPA info:</strong></p>
<p>This pair style does not support the <a class="reference internal" href="pair_modify.html"><span class="doc">pair_modify</span></a>
mix, shift, table, and tail options.</p>
<p>This pair style does not write its information to <a class="reference internal" href="restart.html"><span class="doc">binary restart files</span></a>, since it is stored in potential files. Thus, you
needs to re-specify the pair_style and pair_coeff commands in an input
script that reads a restart file.</p>
<p>This pair style can only be used via the <em>pair</em> keyword of the
<a class="reference internal" href="run_style.html"><span class="doc">run_style respa</span></a> command. It does not support the
<em>inner</em>, <em>middle</em>, <em>outer</em> keywords.</p>
<hr class="docutils" />
<p><strong>Restriction:</strong></p>
<p>This pair style is part of the USER-SMTBQ package and is only enabled
if LAMMPS is built with that package. See the <a class="reference internal" href="Section_start.html#start-3"><span class="std std-ref">Making LAMMPS</span></a> section for more info.</p>
<p>This potential requires using atom type 1 for oxygen and atom type
higher than 1 for metal atoms.</p>
<p>This pair style requires the <a class="reference internal" href="newton.html"><span class="doc">newton</span></a> setting to be “on”
for pair interactions.</p>
<p>The SMTB-Q potential files provided with LAMMPS (see the potentials
directory) are parameterized for metal <a class="reference internal" href="units.html"><span class="doc">units</span></a>.</p>
<hr class="docutils" />
<p><strong>Citing this work:</strong></p>
<p>Please cite related publication: N. Salles, O. Politano, E. Amzallag
and R. Tetot, Comput. Mater. Sci. 111 (2016) 181-189</p>
<hr class="docutils" />
<p id="smtb-q-1"><strong>(SMTB-Q_1)</strong> N. Salles, O. Politano, E. Amzallag, R. Tetot,
Comput. Mater. Sci. 111 (2016) 181-189</p>
<p id="smtb-q-2"><strong>(SMTB-Q_2)</strong> E. Maras, N. Salles, R. Tetot, T. Ala-Nissila,
H. Jonsson, J. Phys. Chem. C 2015, 119, 10391-10399</p>
<p id="smtb-q-3"><strong>(SMTB-Q_3)</strong> R. Tetot, N. Salles, S. Landron, E. Amzallag, Surface
Science 616, 19-8722 28 (2013)</p>
<p id="wolf"><strong>(Wolf)</strong> D. Wolf, P. Keblinski, S. R. Phillpot, J. Eggebrecht, J Chem
Phys, 110, 8254 (1999).</p>
<p id="rick"><strong>(Rick)</strong> S. W. Rick, S. J. Stuart, B. J. Berne, J Chem Phys 101, 6141
(1994).</p>
</div>
</div>
</div>
</div>
<footer>
<hr/>
<div role="contentinfo">
<p>
© Copyright 2013 Sandia Corporation.
</p>
</div>
Built with <a href="http:
</footer>
</div>
</div>
</section>
</div>
<script type="text/javascript">
var <API key> = {
URL_ROOT:'./',
VERSION:'',
COLLAPSE_INDEX:false,
FILE_SUFFIX:'.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=<API key>"></script>
<script type="text/javascript" src="_static/<API key>/LightBox2/lightbox2/js/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="_static/<API key>/LightBox2/lightbox2/js/lightbox.min.js"></script>
<script type="text/javascript" src="_static/<API key>/LightBox2/lightbox2-customize/jquery-noconflict.js"></script>
<script type="text/javascript" src="_static/js/theme.js"></script>
<script type="text/javascript">
jQuery(function () {
SphinxRtdTheme.StickyNav.enable();
});
</script>
</body>
</html> |
<?php
if ( !defined('_JEXEC') && defined('_VALID_MOS') ) define( '_JEXEC', true );
defined('_JEXEC') or die('...Direct Access to this location is not allowed...');
Copyright (C) 2006-2007 Acajoom Services. All rights reserved.
http:
class mosMenuBarCustom {
function cancel( $alt='Cancel', $href='' ) {
compa::showIcon('cancel.png','back','cancel');
compa::showIcon('cancel_f2.png','back','cancel',0);
if ( $href ) {
$link = $href;
} else {
$link = 'javascript:window.history.back();';
}
?>
<td>
<a class="toolbar" href="<?php echo $link; ?>" onmouseout="MM_swapImgRestore();" onmouseover="MM_swapImage('cancel','','<?php echo $image2; ?>',1);">
<?php echo $image; ?>
<?php echo $alt;?>
</a>
</td>
<?php
}
}
class menuAcajoom {
function REGISTERED() {
mosMenuBar::startTable();
mosMenuBar::custom('export', 'archive.png', 'archive_f2.png', _ACA_MENU_EXPORT , false);
mosMenuBar::spacer();
mosMenuBar::custom('import', 'upload.png', 'upload_f2.png', _ACA_MENU_IMPORT , false);
mosMenuBar::spacer(50);
mosMenuBar::addNew();
mosMenuBar::spacer();
mosMenuBar::editList();
mosMenuBar::spacer();
mosMenuBar::deleteList('' , 'delete');
mosMenuBar::spacer(50);
mosMenuBar::cancel();
mosMenuBar::spacer();
mosMenuBar::custom('cpanel', 'tool.png', 'tool_f2.png', _ACA_MENU_CPANEL, false);
mosMenuBar::endTable();
}
function SHOWSUBSCRIBER() {
mosMenuBar::startTable();
mosMenuBar::custom('updateOneSub', 'save.png', 'save_f2.png', _ACA_UPDATE , false);
//mosMenuBar::spacer(50);
//mosMenuBar::deleteList('' , 'deleteOneSub');
mosMenuBar::spacer(50);
mosMenuBar::custom('cancelSub', 'cancel.png', 'cancel_f2.png', _ACA_CANCEL , false);
mosMenuBar::spacer();
mosMenuBar::custom('cpanel', 'tool.png', 'tool_f2.png', _ACA_MENU_CPANEL, false);
mosMenuBar::endTable();
}
function NEWSUBSCRIBER() {
mosMenuBar::startTable();
mosMenuBar::save('doNew', _ACA_SAVE );
mosMenuBar::spacer(50);
mosMenuBar::custom('cancelSub', 'cancel.png', 'cancel_f2.png', _ACA_CANCEL , false);
mosMenuBar::spacer();
mosMenuBar::custom('cpanel', 'tool.png', 'tool_f2.png', _ACA_MENU_CPANEL, false);
mosMenuBar::endTable();
}
function IMPORT() {
mosMenuBar::startTable();
mosMenuBar::custom('doImport', 'upload.png', 'upload_f2.png', _ACA_MENU_IMPORT , false);
mosMenuBar::spacer(50);
mosMenuBar::back();
mosMenuBar::spacer();
mosMenuBar::custom('cpanel', 'tool.png', 'tool_f2.png', _ACA_MENU_CPANEL, false);
mosMenuBar::endTable();
}
function EXPORT() {
mosMenuBar::startTable();
mosMenuBar::custom('doExport', 'archive.png', 'archive_f2.png', _ACA_MENU_EXPORT , false);
mosMenuBar::spacer(50);
mosMenuBar::back();
mosMenuBar::spacer();
mosMenuBar::custom('cpanel', 'tool.png', 'tool_f2.png', _ACA_MENU_CPANEL, false);
mosMenuBar::endTable();
}
function SHOW_LIST() {
mosMenuBar::startTable();
if (class_exists('pro'))
mosMenuBar::custom('forms','html.png','html_f2.png', _ACA_FORM_BUTTON ,false);
mosMenuBar::spacer(50);
mosMenuBar::custom('publish','publish.png','publish_f2.png', _ACA_PUBLISHED ,true);
mosMenuBar::spacer();
mosMenuBar::custom('unpublish','publish.png','publish_f2.png', _ACA_UNPUBLISHED ,true);
mosMenuBar::spacer(50);
mosMenuBar::addNew();
mosMenuBar::spacer();
mosMenuBar::editList();
mosMenuBar::spacer();
mosMenuBar::custom( 'copy', 'copy.png', 'copy_f2.png', _ACA_MENU_COPY , true);
mosMenuBar::spacer();
mosMenuBar::deleteList('' , 'delete');
mosMenuBar::spacer(50);
mosMenuBar::back();
mosMenuBar::spacer();
mosMenuBar::custom('cpanel', 'tool.png', 'tool_f2.png', _ACA_MENU_CPANEL, false);
mosMenuBar::endTable();
}
function EDIT_LIST($task) {
mosMenuBar::startTable();
mosMenuBar::save('update', _ACA_SAVE );
mosMenuBar::spacer(50);
mosMenuBar::cancel($task);
mosMenuBar::spacer();
mosMenuBar::custom('cpanel', 'tool.png', 'tool_f2.png', _ACA_MENU_CPANEL, false);
mosMenuBar::endTable();
}
function NEW_LIST($task) {
mosMenuBar::startTable();
mosMenuBar::save('doNew', _ACA_SAVE );
mosMenuBar::spacer(50);
mosMenuBar::cancel($task);
mosMenuBar::spacer();
mosMenuBar::custom('cpanel', 'tool.png', 'tool_f2.png', _ACA_MENU_CPANEL, false);
mosMenuBar::endTable();
}
function SHOW_MAILINGS() {
mosMenuBar::startTable();
//mosMenuBar::custom('publishMailing','publish.png','publish_f2.png', _ACA_PUBLISHED ,true);
//mosMenuBar::spacer();
mosMenuBar::custom('unpublishMailing','publish.png','publish_f2.png', _ACA_UNPUBLISHED ,true);
mosMenuBar::spacer(50);
mosMenuBar::custom('preview', 'preview.png', 'preview_f2.png', _ACA_MENU_PREVIEW , true );
$listype = 0;
if (isset($_GET['listype'])){ $listype = $_GET['listype']; }
elseif (isset($_POST['droplist'])){ $maliste = explode('-',$_POST['droplist']); $listype = $maliste[0];}
elseif (isset($_POST['listid'])){
$maliste = lists::getLists($_POST['listid'],0,null,'listnameA',false,false,false,false);
$listype = $maliste[0]->list_type;
}
if ($listype==1) {
mosMenuBar::spacer(50);
mosMenuBar::custom('sendNewsletter','forward.png','forward_f2.png', _ACA_MENU_SEND ,true);
}
mosMenuBar::spacer(50);
mosMenuBar::addNew();
mosMenuBar::spacer();
mosMenuBar::editList();
mosMenuBar::spacer();
mosMenuBar::spacer();
mosMenuBar::deleteList('' , 'deleteMailing');
mosMenuBar::spacer(50);
mosMenuBar::back();
mosMenuBar::spacer();
mosMenuBar::custom('cpanel', 'tool.png', 'tool_f2.png', _ACA_MENU_CPANEL, false);
mosMenuBar::endTable();
}
function NEWMAILING() {
mosMenuBar::startTable();
mosMenuBar::spacer();
mosMenuBar::custom('savePreview', 'preview.png', 'preview_f2.png', _ACA_MENU_PREVIEW , false);
$listype = 0;
if (isset($_GET['listype'])){ $listype = $_GET['listype']; }
elseif (isset($_POST['droplist'])){ $maliste = explode('-',$_POST['droplist']); $listype = $maliste[0];}
elseif (isset($_POST['listype'])){ $listype = $_POST['listype'];}
elseif (isset($_GET['listid'])){
$maliste = lists::getLists($_GET['listid'],0,null,'listnameA',false,false,false,false);
$listype = $maliste[0]->list_type;
}
if ($listype==1) {
mosMenuBar::spacer(50);
mosMenuBar::custom('saveSend','forward.png','forward_f2.png', _ACA_MENU_SEND ,false);
}
mosMenuBar::spacer(50);
mosMenuBar::save();
mosMenuBar::spacer();
mosMenuBar::spacer(50);
mosMenuBar::cancel('show');
mosMenuBar::spacer();
mosMenuBar::custom('cpanel', 'tool.png', 'tool_f2.png', _ACA_MENU_CPANEL, false);
mosMenuBar::endTable();
}
function PREVIEWMAILING($task) {
mosMenuBar::startTable();
mosMenuBar::custom('preview', 'forward.png', 'forward_f2.png', _ACA_MENU_SEND_TEST , false);
mosMenuBar::spacer(50);
mosMenuBar::cancel('show');
mosMenuBar::spacer();
mosMenuBar::custom('cpanel', 'tool.png', 'tool_f2.png', _ACA_MENU_CPANEL, false);
mosMenuBar::endTable();
}
function CONFIGURATION() {
mosMenuBar::startTable();
if (class_exists('aca_archive') ) {
mosMenuBar :: custom('archiveAll', 'unarchive.png', 'unarchive_f2.png', <API key>, false);
mosMenuBar::spacer(50);
}
if ( class_exists('autonews') ) {
mosMenuBar::custom('reset','checked_out.png','checked_out.png', 'Reset S.N. Counter' ,false);
mosMenuBar::spacer(50);
}
if (class_exists('auto')) $flag = auto::viewCron(); else $flag = false;
if ($flag) {
mosMenuBar::custom('sendQueue','forward.png','forward_f2.png', <API key> ,false);
mosMenuBar::spacer(50);
}
if ( $GLOBALS[ACA.'type'] =='Plus' OR $GLOBALS[ACA.'type']=='PRO' ) {
mosMenuBar::custom('syncUsers','addusers.png','addusers.png', <API key> ,false);
mosMenuBar::spacer(50);
}
mosMenuBar::save();
mosMenuBar::spacer();
mosMenuBar::apply();
mosMenuBar::spacer(50);
mosMenuBar::cancel();
mosMenuBar::spacer();
mosMenuBar::custom('cpanel', 'tool.png', 'tool_f2.png', _ACA_MENU_CPANEL, false);
mosMenuBar::endTable();
}
function CANCEL_ONLY($task) {
mosMenuBar::startTable();
mosMenuBar::cancel($task);
mosMenuBar::spacer();
mosMenuBar::custom('cpanel', 'tool.png', 'tool_f2.png', _ACA_MENU_CPANEL, false);
mosMenuBar::endTable();
}
function STATISTICS() {
mosMenuBar::startTable();
mosMenuBar::custom('view', 'move.png', 'move_f2.png', <API key>, true);
mosMenuBar::spacer(50);
mosMenuBar::back();
mosMenuBar::spacer();
mosMenuBar::custom('cpanel', 'tool.png', 'tool_f2.png', _ACA_MENU_CPANEL, false);
mosMenuBar::endTable();
}
function UPDATE() {
mosMenuBar::startTable();
/*mosMenuBar::custom('complete', 'upload.png', 'upload_f2.png', _ACA_CHECK , false);
mosMenuBar::spacer(50);
mosMenuBar::cancel();
*/
mosMenuBar::spacer();
mosMenuBar::custom('cpanel', 'tool.png', 'tool_f2.png', _ACA_MENU_CPANEL, false);
mosMenuBar::endTable();
}
function DOUPDATE() {
mosMenuBar::startTable();
/*
mosMenuBar::custom('doUpdate', 'upload.png', 'upload_f2.png', _ACA_UPDATE , false);
mosMenuBar::spacer(50);
mosMenuBar::cancel();
*/
mosMenuBar::spacer();
mosMenuBar::custom('cpanel', 'tool.png', 'tool_f2.png', _ACA_MENU_CPANEL, false);
mosMenuBar::endTable();
}
function ABOUT() {
mosMenuBar::startTable();
mosMenuBar::back();
mosMenuBar::spacer();
mosMenuBar::custom('cpanel', 'tool.png', 'tool_f2.png', _ACA_MENU_CPANEL, false);
mosMenuBar::endTable();
}
} |
// vim: set tabstop=4 shiftwidth=4 expandtab:
// Self
#include "<API key>.h"
#include <QImage>
// KDE
#include <KDebug>
#include <KLocale>
// Local
#include "document/<API key>.h"
#include "document/document.h"
#include "document/documentjob.h"
namespace Gwenview
{
struct <API key>
{
QSize mSize;
QImage mOriginalImage;
};
class ResizeJob : public ThreadedDocumentJob
{
public:
ResizeJob(const QSize& size)
: mSize(size)
{}
virtual void threadedStart()
{
if (!checkDocumentEditor()) {
return;
}
QImage image = document()->image();
image = image.scaled(mSize, Qt::IgnoreAspectRatio, Qt::<API key>);
document()->editor()->setImage(image);
setError(NoError);
}
private:
QSize mSize;
};
<API key>::<API key>(const QSize& size)
: d(new <API key>)
{
d->mSize = size;
setText(i18nc("(qtundo-format)", "Resize"));
}
<API key>::~<API key>()
{
delete d;
}
void <API key>::redo()
{
d->mOriginalImage = document()->image();
redoAsDocumentJob(new ResizeJob(d->mSize));
}
void <API key>::undo()
{
if (!document()->editor()) {
kWarning() << "!document->editor()";
return;
}
document()->editor()->setImage(d->mOriginalImage);
}
} // namespace |
#pragma once
#include <svgpp/definitions.hpp>
#include <svgpp/utility/gil/common.hpp>
#include <boost/gil/channel_algorithm.hpp>
#include <boost/gil/<API key>.hpp>
namespace svgpp
{
namespace gil_detail
{
namespace gil = boost::gil;
template<class BlendModeTag, class ChannelValue>
struct blend_channel_fn;
template<class ChannelValue>
struct blend_alpha_fn;
// TODO: default implementation for non-8 bit channels
// TODO: clamp_channels is not needed for premultiplied values
// For signed channels we call unsigned analog, converting forward and back
template<class BlendModeTag>
struct blend_channel_fn<BlendModeTag, gil::bits8s>
{
gil::bits8s operator()(gil::bits8s channel_a, gil::bits8s channel_b, gil::bits8s alpha_a, gil::bits8s alpha_b) const
{
typedef gil::detail::<API key><gil::bits8s> to_unsigned;
typedef gil::detail::<API key><gil::bits8s> from_unsigned;
blend_channel_fn<BlendModeTag, gil::bits8> converter_unsigned;
return from_unsigned()(converter_unsigned(
to_unsigned()(channel_a), to_unsigned()(channel_b), to_unsigned()(alpha_a), to_unsigned()(alpha_b)));
}
};
// normal cr = (1 - alpha_a) * channel_b + channel_a
template<>
struct blend_channel_fn<tag::value::normal, gil::bits8>
{
gil::bits8 operator()(int channel_a, int channel_b, int alpha_a, int alpha_b) const
{
return clamp_channel_bits8(((255 - alpha_a) * channel_b) / 255 + channel_a);
}
};
// multiply cr = (1-alpha_a)*channel_b + (1-alpha_b)*channel_a + channel_a*channel_b
template<>
struct blend_channel_fn<tag::value::multiply, gil::bits8>
{
gil::bits8 operator()(int channel_a, int channel_b, int alpha_a, int alpha_b) const
{
return clamp_channel_bits8(((255 - alpha_a) * channel_b + (255 - alpha_b) * channel_a + channel_a * channel_b) / 255);
}
};
// screen cr = channel_b + channel_a - channel_a * channel_b
template<>
struct blend_channel_fn<tag::value::screen, gil::bits8>
{
gil::bits8 operator()(int channel_a, int channel_b, int alpha_a, int alpha_b) const
{
return clamp_channel_bits8(channel_b + channel_a - channel_a * channel_b / 255);
}
};
// darken cr = Min ((1 - alpha_a) * channel_b + channel_a, (1 - alpha_b) * channel_a + channel_b)
template<>
struct blend_channel_fn<tag::value::darken, gil::bits8>
{
gil::bits8 operator()(int channel_a, int channel_b, int alpha_a, int alpha_b) const
{
return clamp_channel_bits8(std::min((255 - alpha_a) * channel_b / 255 + channel_a, (255 - alpha_b) * channel_a / 255 + channel_b));
}
};
// lighten cr = Max ((1 - alpha_a) * channel_b + channel_a, (1 - alpha_b) * channel_a + channel_b)
template<>
struct blend_channel_fn<tag::value::lighten, gil::bits8>
{
gil::bits8 operator()(int channel_a, int channel_b, int alpha_a, int alpha_b) const
{
return clamp_channel_bits8(std::max((255 - alpha_a) * channel_b / 255 + channel_a, (255 - alpha_b) * channel_a / 255 + channel_b));
}
};
// qr = 1 - (1-alpha_a)*(1-alpha_b)
template<>
struct blend_alpha_fn<gil::bits8>
{
gil::bits8 operator()(int alpha_a, int alpha_b) const
{
return clamp_channel_bits8(255 - (255 - alpha_a) * (255 - alpha_b) / 255);
}
};
} // namespace gil_detail
namespace gil_utility
{
template<class BlendModeTag>
struct blend_pixel
{
template<class Color>
Color operator()(const Color & pixa, const Color & pixb) const
{
namespace gil = boost::gil;
typename gil::color_element_type<Color, gil::alpha_t>::type
alpha_a = gil::get_color(pixa, gil::alpha_t()),
alpha_b = gil::get_color(pixb, gil::alpha_t());
Color result;
gil::get_color(result, gil::red_t())
= gil_detail::blend_channel_fn<BlendModeTag, typename gil::color_element_type<Color, gil::red_t>::type>()(
gil::get_color(pixa, gil::red_t()), gil::get_color(pixb, gil::red_t()),
alpha_a, alpha_b);
gil::get_color(result, gil::green_t())
= gil_detail::blend_channel_fn<BlendModeTag, typename gil::color_element_type<Color, gil::green_t>::type>()(
gil::get_color(pixa, gil::green_t()), gil::get_color(pixb, gil::green_t()),
alpha_a, alpha_b);
gil::get_color(result, gil::blue_t())
= gil_detail::blend_channel_fn<BlendModeTag, typename gil::color_element_type<Color, gil::blue_t>::type>()(
gil::get_color(pixa, gil::blue_t()), gil::get_color(pixb, gil::blue_t()),
alpha_a, alpha_b);
gil::get_color(result, gil::alpha_t()) =
gil_detail::blend_alpha_fn<typename gil::color_element_type<Color, gil::alpha_t>::type>()(alpha_a, alpha_b);
return result;
}
};
}} |
/* $HEADER$ */
#include <linux/pm.h>
#include <linux/wait.h>
#include <linux/cpu.h>
#include <wlan_hdd_includes.h>
#include <wlan_qct_driver.h>
#if defined(WLAN_OPEN_SOURCE) && defined(CONFIG_HAS_WAKELOCK)
#include <linux/wakelock.h>
#endif
#include "halTypes.h"
#include "sme_Api.h"
#include <vos_api.h>
#include <vos_sched.h>
#include <macInitApi.h>
#include <wlan_qct_sys.h>
#include <wlan_btc_svc.h>
#include <wlan_nlink_common.h>
#include <wlan_hdd_main.h>
#include <wlan_hdd_assoc.h>
#include <wlan_hdd_dev_pwr.h>
#include <wlan_nlink_srv.h>
#include <wlan_hdd_misc.h>
#include <dbglog_host.h>
#include <linux/semaphore.h>
#include <wlan_hdd_hostapd.h>
#include "cfgApi.h"
#include <wcnss_api.h>
#include <linux/inetdevice.h>
#include <wlan_hdd_cfg.h>
#include <wlan_hdd_cfg80211.h>
#include <net/addrconf.h>
#ifdef IPA_OFFLOAD
#include <wlan_hdd_ipa.h>
#endif
#include <wlan_hdd_p2p.h>
#include "wlan_hdd_power.h"
#include "<API key>.h"
#include <wlan_qct_wda.h>
#if defined(HIF_PCI)
#include "if_pci.h"
#elif defined(HIF_USB)
#include "if_usb.h"
#elif defined(HIF_SDIO)
#include "if_ath_sdio.h"
#endif
#include "ol_fw.h"
/* Time in msec */
#ifdef <API key>
#define <API key> 40000
#else
#define <API key> 30000
#endif
static eHalStatus g_full_pwr_status;
static eHalStatus g_standby_status;
extern VOS_STATUS <API key>(hdd_context_t* pHddCtx);
extern void <API key>(hdd_context_t *pHddCtx);
extern struct notifier_block hdd_netdev_notifier;
extern tVOS_CON_MODE hdd_get_conparam ( void );
static struct timer_list ssr_timer;
static bool ssr_timer_started;
//Callback invoked by PMC to report status of standby request
void <API key> (void *callbackContext, eHalStatus status)
{
hdd_context_t *pHddCtx = (hdd_context_t*)callbackContext;
hddLog(<API key>, "%s: Standby status = %d", __func__, status);
g_standby_status = status;
if(eHAL_STATUS_SUCCESS == status)
{
pHddCtx->hdd_ps_state = <API key>;
}
else
{
hddLog(<API key>,"%s: sme_RequestStandby failed",__func__);
}
complete(&pHddCtx->standby_comp_var);
}
//Callback invoked by PMC to report status of full power request
void <API key>(void *callbackContext, eHalStatus status)
{
hdd_context_t *pHddCtx = (hdd_context_t*)callbackContext;
hddLog(<API key>, "%s: Full Power status = %d", __func__, status);
g_full_pwr_status = status;
if(eHAL_STATUS_SUCCESS == status)
{
pHddCtx->hdd_ps_state = eHDD_SUSPEND_NONE;
}
else
{
hddLog(<API key>,"%s: <API key> failed",__func__);
}
complete(&pHddCtx->full_pwr_comp_var);
}
eHalStatus hdd_exit_standby(hdd_context_t *pHddCtx)
{
eHalStatus status = VOS_STATUS_SUCCESS;
unsigned long rc;
hddLog(<API key>, "%s: WLAN being resumed from standby",__func__);
INIT_COMPLETION(pHddCtx->full_pwr_comp_var);
g_full_pwr_status = eHAL_STATUS_FAILURE;
status = <API key>(pHddCtx->hHal, <API key>, pHddCtx,
<API key>);
if(status == <API key>)
{
//Block on a completion variable. Can't wait forever though
rc = <API key>(
&pHddCtx->full_pwr_comp_var,
msecs_to_jiffies(<API key>));
if (!rc) {
hddLog(<API key>,
FL("wait on full_pwr_comp_var failed"));
}
status = g_full_pwr_status;
if(g_full_pwr_status != eHAL_STATUS_SUCCESS)
{
hddLog(<API key>,"%s: <API key> failed",__func__);
VOS_ASSERT(0);
goto failure;
}
}
else if(status != eHAL_STATUS_SUCCESS)
{
hddLog(<API key>,"%s: <API key> failed - status %d",
__func__, status);
VOS_ASSERT(0);
goto failure;
}
else
pHddCtx->hdd_ps_state = eHDD_SUSPEND_NONE;
failure:
//No blocking to reduce latency. No other device should be depending on WLAN
//to finish resume and WLAN won't be instantly on after resume
return status;
}
//Helper routine to put the chip into standby
VOS_STATUS hdd_enter_standby(hdd_context_t *pHddCtx)
{
eHalStatus halStatus = eHAL_STATUS_SUCCESS;
VOS_STATUS vosStatus = VOS_STATUS_SUCCESS;
unsigned long rc;
//Disable IMPS/BMPS as we do not want the device to enter any power
//save mode on its own during suspend sequence
<API key>(pHddCtx->hHal, <API key>);
<API key>(pHddCtx->hHal, <API key>);
//Note we do not disable queues unnecessarily. Queues should already be disabled
//if STA is disconnected or the queue will be disabled as and when disconnect
//happens because of standby procedure.
//Ensure that device is in full power first. There is scope for optimization
//here especially in scenarios where PMC is already in IMPS or REQUEST_IMPS.
//Core s/w needs to be optimized to handle this. Until then we request full
//power before issuing request for standby.
INIT_COMPLETION(pHddCtx->full_pwr_comp_var);
g_full_pwr_status = eHAL_STATUS_FAILURE;
halStatus = <API key>(pHddCtx->hHal, <API key>,
pHddCtx, <API key>);
if(halStatus == <API key>)
{
//Block on a completion variable. Can't wait forever though
rc = <API key>(
&pHddCtx->full_pwr_comp_var,
msecs_to_jiffies(<API key>));
if (!rc) {
hddLog(<API key>,
FL("wait on full_pwr_comp_var failed"));
}
if(g_full_pwr_status != eHAL_STATUS_SUCCESS)
{
hddLog(<API key>,"%s: <API key> Failed",__func__);
VOS_ASSERT(0);
vosStatus = <API key>;
goto failure;
}
}
else if(halStatus != eHAL_STATUS_SUCCESS)
{
hddLog(<API key>,"%s: <API key> failed - status %d",
__func__, halStatus);
VOS_ASSERT(0);
vosStatus = <API key>;
goto failure;
}
if(pHddCtx-><API key> == TRUE) {
<API key>(pHddCtx, FALSE);
pHddCtx-><API key> = FALSE;
}
//Request standby. Standby will cause the STA to disassociate first. TX queues
//will be disabled (by HDD) when STA disconnects. You do not want to disable TX
//queues here. Also do not assert if the failure code is <API key> as PMC
//will send this failure code in case of concurrent sessions. Power Save cannot be supported
//when there are concurrent sessions.
INIT_COMPLETION(pHddCtx->standby_comp_var);
g_standby_status = eHAL_STATUS_FAILURE;
halStatus = sme_RequestStandby(pHddCtx->hHal, <API key>, pHddCtx);
if (halStatus == <API key>)
{
//Wait till WLAN device enters standby mode
rc = <API key>(&pHddCtx->standby_comp_var,
msecs_to_jiffies(<API key>));
if (!rc) {
hddLog(<API key>,
FL("wait on standby_comp_var failed"));
}
if (g_standby_status != eHAL_STATUS_SUCCESS && g_standby_status != <API key>)
{
hddLog(<API key>,"%s: sme_RequestStandby failed",__func__);
VOS_ASSERT(0);
vosStatus = <API key>;
goto failure;
}
}
else if (halStatus != eHAL_STATUS_SUCCESS && halStatus != <API key>) {
hddLog(<API key>,"%s: sme_RequestStandby failed - status %d",
__func__, halStatus);
VOS_ASSERT(0);
vosStatus = <API key>;
goto failure;
}
else
pHddCtx->hdd_ps_state = <API key>;
failure:
//Restore IMPS config
if(pHddCtx->cfg_ini->fIsImpsEnabled)
sme_EnablePowerSave(pHddCtx->hHal, <API key>);
//Restore BMPS config
if(pHddCtx->cfg_ini->fIsBmpsEnabled)
sme_EnablePowerSave(pHddCtx->hHal, <API key>);
return vosStatus;
}
//Helper routine for Deep sleep entry
VOS_STATUS <API key>(hdd_context_t *pHddCtx, hdd_adapter_t *pAdapter)
{
eHalStatus halStatus;
VOS_STATUS vosStatus = VOS_STATUS_SUCCESS;
unsigned long rc;
//Stop the Interface TX queue.
hddLog(LOG1, FL("Disabling queues"));
netif_tx_disable(pAdapter->dev);
netif_carrier_off(pAdapter->dev);
//Disable IMPS,BMPS as we do not want the device to enter any power
//save mode on it own during suspend sequence
<API key>(pHddCtx->hHal, <API key>);
<API key>(pHddCtx->hHal, <API key>);
//Ensure that device is in full power as we will touch H/W during vos_Stop
INIT_COMPLETION(pHddCtx->full_pwr_comp_var);
g_full_pwr_status = eHAL_STATUS_FAILURE;
halStatus = <API key>(pHddCtx->hHal, <API key>,
pHddCtx, <API key>);
if(halStatus == <API key>)
{
//Block on a completion variable. Can't wait forever though
rc = <API key>(
&pHddCtx->full_pwr_comp_var,
msecs_to_jiffies(<API key>));
if (!rc) {
hddLog(<API key>,
FL("wait on full_pwr_comp_var failed"));
}
if(g_full_pwr_status != eHAL_STATUS_SUCCESS){
hddLog(<API key>,"%s: <API key> failed",__func__);
VOS_ASSERT(0);
}
}
else if(halStatus != eHAL_STATUS_SUCCESS)
{
hddLog(<API key>,"%s: Request for Full Power failed",__func__);
VOS_ASSERT(0);
}
//Issue a disconnect. This is required to inform the supplicant that
//STA is getting disassociated and for GUI to be updated properly
INIT_COMPLETION(pAdapter->disconnect_comp_var);
halStatus = sme_RoamDisconnect(pHddCtx->hHal, pAdapter->sessionId, <API key>);
//Success implies disconnect command got queued up successfully
if(halStatus == eHAL_STATUS_SUCCESS)
{
//Block on a completion variable. Can't wait forever though.
rc = <API key>(
&pAdapter->disconnect_comp_var,
msecs_to_jiffies(<API key>));
if (!rc) {
hddLog(<API key>,
FL("wait on disconnect_comp_var failed"));
}
}
//None of the steps should fail after this. Continue even in case of failure
vosStatus = vos_stop( pHddCtx->pvosContext );
if (!<API key>( vosStatus ))
{
hddLog(<API key>, "%s: vos_stop return failed %d",
__func__, vosStatus);
VOS_ASSERT(0);
}
pHddCtx->hdd_ps_state = <API key>;
//Restore IMPS config
if(pHddCtx->cfg_ini->fIsImpsEnabled)
sme_EnablePowerSave(pHddCtx->hHal, <API key>);
//Restore BMPS config
if(pHddCtx->cfg_ini->fIsBmpsEnabled)
sme_EnablePowerSave(pHddCtx->hHal, <API key>);
return vosStatus;
}
VOS_STATUS hdd_exit_deep_sleep(hdd_context_t *pHddCtx, hdd_adapter_t *pAdapter)
{
VOS_STATUS vosStatus;
eHalStatus halStatus;
tANI_U32 type, subType;
VOS_TRACE( VOS_MODULE_ID_HDD, <API key>,
"%s: calling hdd_set_sme_config",__func__);
vosStatus = hdd_set_sme_config( pHddCtx );
VOS_ASSERT( <API key>( vosStatus ) );
if (!<API key>(vosStatus))
{
VOS_TRACE(VOS_MODULE_ID_HDD, <API key>,
"%s: Failed in hdd_set_sme_config",__func__);
goto err_deep_sleep;
}
VOS_TRACE( VOS_MODULE_ID_HDD, <API key>,
"%s: calling vos_start",__func__);
vosStatus = vos_start( pHddCtx->pvosContext );
VOS_ASSERT( <API key>( vosStatus ) );
if (!<API key>(vosStatus))
{
VOS_TRACE(VOS_MODULE_ID_HDD, <API key>,
"%s: Failed in vos_start",__func__);
goto err_deep_sleep;
}
VOS_TRACE( VOS_MODULE_ID_HDD, <API key>,
"%s: calling <API key>",__func__);
vosStatus = <API key>( pHddCtx );
VOS_ASSERT( <API key>( vosStatus ) );
if (!<API key>(vosStatus))
{
VOS_TRACE(VOS_MODULE_ID_HDD, <API key>,
"%s: Failed in <API key>",__func__);
goto err_voss_stop;
}
vosStatus = vos_get_vdev_types(pAdapter->device_mode, &type, &subType);
if (VOS_STATUS_SUCCESS != vosStatus)
{
hddLog(<API key>, "failed to get vdev type");
goto err_voss_stop;
}
//Open a SME session for future operation
halStatus = sme_OpenSession( pHddCtx->hHal, hdd_smeRoamCallback, pAdapter,
(tANI_U8 *)&pAdapter->macAddressCurrent, &pAdapter->sessionId,
type, subType);
if ( !HAL_STATUS_SUCCESS( halStatus ) )
{
hddLog(<API key>,"sme_OpenSession() failed with status code %08d [x%08x]",
halStatus, halStatus );
goto err_voss_stop;
}
pHddCtx->hdd_ps_state = eHDD_SUSPEND_NONE;
//Trigger the initial scan
<API key>(pHddCtx);
return VOS_STATUS_SUCCESS;
err_voss_stop:
vos_stop(pHddCtx->pvosContext);
err_deep_sleep:
return <API key>;
}
#ifdef <API key>
void <API key>(hdd_adapter_t *pAdapter, v_BOOL_t fenable)
{
eHalStatus ret;
<API key> <API key>;
hdd_station_ctx_t *pHddStaCtx = <API key>(pAdapter);
if(fenable)
{
if ((<API key> == pHddStaCtx->conn_info.connState) &&
(GTK_OFFLOAD_ENABLE == pHddStaCtx->gtkOffloadReqParams.ulFlags ))
{
vos_mem_copy(&<API key>,
&pHddStaCtx->gtkOffloadReqParams,
sizeof (<API key>));
ret = sme_SetGTKOffload(<API key>(pAdapter),
&<API key>, pAdapter->sessionId);
if (eHAL_STATUS_SUCCESS != ret)
{
VOS_TRACE(VOS_MODULE_ID_HDD, <API key>,
"%s: sme_SetGTKOffload failed, returned %d",
__func__, ret);
return;
}
VOS_TRACE(VOS_MODULE_ID_HDD, <API key>,
"%s: sme_SetGTKOffload successful", __func__);
}
}
else
{
if ((<API key> == pHddStaCtx->conn_info.connState) &&
(0 == memcmp(&pHddStaCtx->gtkOffloadReqParams.bssId,
&pHddStaCtx->conn_info.bssId, VOS_MAC_ADDR_SIZE)) &&
(GTK_OFFLOAD_ENABLE == pHddStaCtx->gtkOffloadReqParams.ulFlags))
{
/* Host driver has previously offloaded GTK rekey */
ret = sme_GetGTKOffload(<API key>(pAdapter),
<API key>,
pAdapter, pAdapter->sessionId);
if (eHAL_STATUS_SUCCESS != ret)
{
VOS_TRACE(VOS_MODULE_ID_HDD, <API key>,
"%s: sme_GetGTKOffload failed, returned %d",
__func__, ret);
return;
}
else
{
VOS_TRACE(VOS_MODULE_ID_HDD, <API key>,
"%s: sme_GetGTKOffload successful",
__func__);
/* Sending GTK offload disable */
memcpy(&<API key>, &pHddStaCtx->gtkOffloadReqParams,
sizeof (<API key>));
<API key>.ulFlags = GTK_OFFLOAD_DISABLE;
ret = sme_SetGTKOffload(<API key>(pAdapter),
&<API key>, pAdapter->sessionId);
if (eHAL_STATUS_SUCCESS != ret)
{
VOS_TRACE(VOS_MODULE_ID_HDD, <API key>,
"%s: failed to disable GTK offload, returned %d",
__func__, ret);
return;
}
VOS_TRACE(VOS_MODULE_ID_HDD, <API key>,
"%s: successfully disabled GTK offload request to HAL",
__func__);
}
}
}
return;
}
#endif /*<API key>*/
#ifdef WLAN_NS_OFFLOAD
static int <API key>(struct notifier_block *nb,
unsigned long data, void *arg)
{
struct inet6_ifaddr *ifa = (struct inet6_ifaddr *)arg;
struct net_device *ndev = ifa->idev->dev;
hdd_context_t *hdd_ctx;
hdd_adapter_t *adapter;
int status;
hdd_ctx = container_of(nb, hdd_context_t, ipv6_notifier);
status = <API key>(hdd_ctx);
if (0 != status) {
hddLog(LOGE, FL("HDD context is invalid"));
return NOTIFY_DONE;
}
adapter = <API key>(ndev);
if (<API key> != adapter->magic) return NOTIFY_DONE;
if (adapter->dev != ndev) return NOTIFY_DONE;
if (WLAN_HDD_GET_CTX(adapter) != hdd_ctx) return NOTIFY_DONE;
if (adapter->device_mode == <API key> ||
(adapter->device_mode == WLAN_HDD_P2P_CLIENT)) {
if (hdd_ctx->cfg_ini->nEnableSuspend ==
<API key>)
schedule_work(&adapter-><API key>);
else
hddLog(LOG1, FL("Not scheduling ipv6 wq nEnableSuspend: %d"),
hdd_ctx->cfg_ini->nEnableSuspend);
}
return NOTIFY_DONE;
}
/**
* <API key>() - IPv6 change notifier callback
* @nb: pointer to notifier block
* @data: data
* @arg: arg
*
* This is the IPv6 notifier callback function gets invoked
* if any change in IP and then invoke the function @<API key>
* to reconfigure the offload parameters.
*
* Return: 0 on success, error number otherwise.
*/
int <API key>(struct notifier_block *nb,
unsigned long data, void *arg)
{
int ret;
vos_ssr_protect(__func__);
ret = <API key>(nb, data, arg);
vos_ssr_unprotect(__func__);
return ret;
}
static void hdd_conf_ns_offload(hdd_adapter_t *pAdapter, int fenable)
{
struct inet6_dev *in6_dev;
struct inet6_ifaddr *ifp;
struct list_head *p;
tANI_U8 selfIPv6Addr[<API key>][<API key>] = {{0,}};
tANI_BOOLEAN selfIPv6AddrValid[<API key>] = {0};
tSirHostOffloadReq offLoadRequest;
hdd_context_t *pHddCtx;
int i =0;
eHalStatus returnStatus;
uint32_t count = 0, scope;
ENTER();
hddLog(LOG1, FL(" fenable = %d"), fenable);
pHddCtx = WLAN_HDD_GET_CTX(pAdapter);
/* In SAP/P2PGo mode, ARP/NS offload feature capability
* is controlled by one bit.
*/
if ((WLAN_HDD_SOFTAP == pAdapter->device_mode ||
WLAN_HDD_P2P_GO == pAdapter->device_mode) &&
!pHddCtx->ap_arpns_support) {
hddLog(LOG1, FL("NS Offload is not supported in SAP/P2PGO mode"));
return;
}
if (fenable) {
in6_dev = __in6_dev_get(pAdapter->dev);
if (NULL != in6_dev) {
list_for_each(p, &in6_dev->addr_list) {
if (count >= <API key>) {
hddLog(LOG1, FL("Reached max supported NS Offload addresses"));
break;
}
ifp = list_entry(p, struct inet6_ifaddr, if_list);
scope = ipv6_addr_src_scope(&ifp->addr);
switch (scope) {
case <API key>:
case <API key>:
vos_mem_copy(&selfIPv6Addr[count], &ifp->addr.s6_addr,
sizeof(ifp->addr.s6_addr));
selfIPv6AddrValid[count] = SIR_IPV6_ADDR_VALID;
hddLog (LOG1,
FL("Index %d scope = %s Address : %pI6"),
count, (scope == <API key>) ?
"LINK LOCAL": "GLOBAL", selfIPv6Addr[count]);
count += 1;
break;
default:
hddLog(LOGE, "The Scope %d is not supported",
ipv6_addr_src_scope(&ifp->addr));
}
}
vos_mem_zero(&offLoadRequest, sizeof(offLoadRequest));
for (i = 0; i < count; i++) {
offLoadRequest.nsOffloadInfo.selfIPv6Addr[i][0] = 0xFF;
offLoadRequest.nsOffloadInfo.selfIPv6Addr[i][1] = 0x02;
offLoadRequest.nsOffloadInfo.selfIPv6Addr[i][11] = 0x01;
offLoadRequest.nsOffloadInfo.selfIPv6Addr[i][12] = 0xFF;
offLoadRequest.nsOffloadInfo.selfIPv6Addr[i][13] =
selfIPv6Addr[i][13];
offLoadRequest.nsOffloadInfo.selfIPv6Addr[i][14] =
selfIPv6Addr[i][14];
offLoadRequest.nsOffloadInfo.selfIPv6Addr[i][15] =
selfIPv6Addr[i][15];
offLoadRequest.nsOffloadInfo.slotIdx = i;
vos_mem_copy(&offLoadRequest.nsOffloadInfo.targetIPv6Addr[i],
&selfIPv6Addr[i][0], <API key>);
offLoadRequest.nsOffloadInfo.targetIPv6AddrValid[i] =
SIR_IPV6_ADDR_VALID;
hddLog (LOG1,
FL("<API key>: %d"),
pHddCtx-><API key>);
if ((VOS_TRUE == pHddCtx-><API key>)
&& ((<API key> ==
pHddCtx-><API key>) ||
(<API key> ==
pHddCtx-><API key>))) {
hddLog(LOG1,
FL("Set offLoadRequest with <API key>"));
offLoadRequest.enableOrDisable =
<API key>;
}
vos_mem_copy(&offLoadRequest.params.hostIpv6Addr,
&offLoadRequest.nsOffloadInfo.targetIPv6Addr[i],
sizeof(tANI_U8)*<API key>);
hddLog (LOG1,
FL("Setting NSOffload with solicitedIp: %pI6, targetIp: %pI6, Index %d"),
&offLoadRequest.nsOffloadInfo.selfIPv6Addr[i],
&offLoadRequest.nsOffloadInfo.targetIPv6Addr[i], i);
}
offLoadRequest.offloadType = SIR_IPV6_NS_OFFLOAD;
offLoadRequest.enableOrDisable = SIR_OFFLOAD_ENABLE;
vos_mem_copy(&offLoadRequest.nsOffloadInfo.selfMacAddr,
&pAdapter->macAddressCurrent.bytes, SIR_MAC_ADDR_LEN);
/* set number of ns offload address count */
offLoadRequest.<API key> = count;
/* Configure the Firmware with this */
returnStatus = sme_SetHostOffload(<API key>(pAdapter),
pAdapter->sessionId, &offLoadRequest);
if (eHAL_STATUS_SUCCESS != returnStatus) {
hddLog(LOGE,
FL("Failed to enable HostOffload feature with status: %d"),
returnStatus);
}
}
else {
hddLog(LOGE,
FL("IPv6 dev does not exist. Failed to request NSOffload"));
return;
}
} else {
/* Disable NSOffload */
vos_mem_zero((void *)&offLoadRequest, sizeof(tSirHostOffloadReq));
offLoadRequest.enableOrDisable = SIR_OFFLOAD_DISABLE;
offLoadRequest.offloadType = SIR_IPV6_NS_OFFLOAD;
if (eHAL_STATUS_SUCCESS !=
sme_SetHostOffload(<API key>(pAdapter),
pAdapter->sessionId, &offLoadRequest)) {
hddLog(LOGE, FL("Failed to disable NS Offload"));
}
}
EXIT();
return;
}
/**
* <API key>() - IP V6 change notifier work handler
* @work: Pointer to work context
*
* Return: none
*/
static void <API key>(struct work_struct *work)
{
hdd_adapter_t* pAdapter =
container_of(work, hdd_adapter_t, <API key>);
hdd_context_t *pHddCtx;
int status;
ENTER();
pHddCtx = WLAN_HDD_GET_CTX(pAdapter);
status = <API key>(pHddCtx);
if (0 != status)
return;
if ( VOS_FALSE == pHddCtx-><API key>)
{
pHddCtx-><API key> =
pHddCtx-><API key>;
pHddCtx-><API key> = VOS_TRUE;
}
if ((<API key> ==
(<API key>(pAdapter))->conn_info.connState)
&& (pHddCtx->hdd_wlan_suspended))
{
/*
* This invocation being part of the IPv6 registration callback,
* we are passing second parameter as 2 to avoid registration
* of IPv6 notifier again
*/
if (pHddCtx->cfg_ini->fhostNSOffload)
hdd_conf_ns_offload(pAdapter, 2);
}
EXIT();
}
/**
* <API key>() - IP V6 change notifier work handler
* @work: Pointer to work context
*
* Return: none
*/
void <API key>(struct work_struct *work)
{
vos_ssr_protect(__func__);
<API key>(work);
vos_ssr_unprotect(__func__);
}
#endif
/*
* Function: <API key>
* Central function to configure the supported offloads,
* either enable or disable them.
*/
void <API key>(hdd_adapter_t *pAdapter, v_BOOL_t fenable)
{
hdd_context_t *pHddCtx = NULL;
v_CONTEXT_t *pVosContext = NULL;
VOS_STATUS vstatus = <API key>;
ENTER();
hddLog(<API key>, FL("Configuring offloads with flag: %d"),
fenable);
pVosContext = <API key>(VOS_MODULE_ID_SYS, NULL);
if (NULL == pVosContext)
{
hddLog(<API key>, FL(" Global VOS context is Null"));
return;
}
//Get the HDD context.
pHddCtx = (hdd_context_t *)vos_get_context(VOS_MODULE_ID_HDD, pVosContext );
if (NULL == pHddCtx)
{
hddLog(<API key>, "%s: HDD context is Null", __func__);
return;
}
if ((<API key> == pAdapter->device_mode) ||
(WLAN_HDD_P2P_CLIENT == pAdapter->device_mode) ||
(WLAN_HDD_SOFTAP == pAdapter->device_mode) ||
(WLAN_HDD_P2P_GO == pAdapter->device_mode))
{
if (fenable)
{
if ((<API key> ==
(<API key>(pAdapter))->conn_info.connState) ||
(WLAN_HDD_SOFTAP == pAdapter->device_mode) ||
(WLAN_HDD_P2P_GO == pAdapter->device_mode))
{
if ((pHddCtx->cfg_ini->fhostArpOffload))
{
/*
* Configure the ARP Offload.
* Even if it fails we have to reconfigure the MC/BC
* filter flag as we want RIVA not to drop BroadCast
* Packets
*/
hddLog(<API key>,
FL("Calling ARP Offload with flag: %d"), fenable);
vstatus = <API key>(pAdapter, fenable);
pHddCtx-><API key> &=
~(<API key>);
if (!<API key>(vstatus))
{
hddLog(<API key>,
"Failed to enable ARPOFfloadFeature %d",
vstatus);
}
}
//Configure GTK_OFFLOAD
#ifdef <API key>
<API key>(pAdapter, fenable);
#endif
#ifdef WLAN_NS_OFFLOAD
if (pHddCtx->cfg_ini->fhostNSOffload)
{
/*
* Configure the NS Offload.
* Even if it fails we have to reconfigure the MC/BC filter flag
* as we want RIVA not to drop Multicast Packets
*/
hddLog(<API key>,
FL("Calling NS Offload with flag: %d"), fenable);
hdd_conf_ns_offload(pAdapter, fenable);
pHddCtx-><API key> &=
~(<API key>);
}
#endif
/*
* This variable saves the state if offload were configured
* or not. helps in recovering when pcie fails to suspend
* because of ongoing scan and state is no longer associated.
*/
pAdapter->offloads_configured = TRUE;
}
}
else
{
//Disable ARPOFFLOAD
if ( (<API key> ==
(<API key>(pAdapter))->conn_info.connState) ||
(pAdapter->offloads_configured == TRUE)
)
{
pAdapter->offloads_configured = FALSE;
if (pHddCtx->cfg_ini->fhostArpOffload)
{
vstatus = <API key>(pAdapter, fenable);
if (!<API key>(vstatus))
{
hddLog(<API key>,
"Failed to disable ARPOffload Feature %d", vstatus);
}
}
//Disable GTK_OFFLOAD
#ifdef <API key>
<API key>(pAdapter, fenable);
#endif
#ifdef WLAN_NS_OFFLOAD
//Disable NSOFFLOAD
if (pHddCtx->cfg_ini->fhostNSOffload)
{
hdd_conf_ns_offload(pAdapter, fenable);
}
#endif
}
}
}
EXIT();
return;
}
/**
* <API key>() - IP V4 change notifier work handler
* @work: Pointer to work context
*
* Return: none
*/
static void <API key>(struct work_struct *work)
{
hdd_adapter_t* pAdapter =
container_of(work, hdd_adapter_t, <API key>);
hdd_context_t *pHddCtx;
int status;
hddLog(LOG1, FL("Reconfiguring ARP Offload"));
pHddCtx = WLAN_HDD_GET_CTX(pAdapter);
status = <API key>(pHddCtx);
if (0 != status)
{
hddLog(LOGE, FL("HDD context is invalid"));
return;
}
if ( VOS_FALSE == pHddCtx-><API key>)
{
pHddCtx-><API key> =
pHddCtx-><API key>;
pHddCtx-><API key> = VOS_TRUE;
}
if ((<API key> ==
(<API key>(pAdapter))->conn_info.connState)
&& (pHddCtx->hdd_wlan_suspended))
{
// This invocation being part of the IPv4 registration callback,
// we are passing second parameter as 2 to avoid registration
// of IPv4 notifier again.
<API key>(pAdapter, 2);
}
}
/**
* <API key>() - IP V4 change notifier work handler
* @work: Pointer to work context
*
* Return: none
*/
void <API key>(struct work_struct *work)
{
vos_ssr_protect(__func__);
<API key>(work);
vos_ssr_unprotect(__func__);
}
static int <API key>(struct notifier_block *nb,
unsigned long data, void *arg)
{
struct in_ifaddr *ifa = (struct in_ifaddr *)arg;
struct in_ifaddr **ifap = NULL;
struct in_device *in_dev;
struct net_device *ndev = ifa->ifa_dev->dev;
hdd_context_t *hdd_ctx;
hdd_adapter_t *adapter;
int status;
hdd_ctx = container_of(nb, hdd_context_t, ipv4_notifier);
status = <API key>(hdd_ctx);
if (0 != status) {
hddLog(LOGE, FL("HDD context is invalid"));
return NOTIFY_DONE;
}
adapter = <API key>(ndev);
if (!adapter) return NOTIFY_DONE;
if (<API key> != adapter->magic) return NOTIFY_DONE;
if (adapter->dev != ndev) return NOTIFY_DONE;
if (WLAN_HDD_GET_CTX(adapter) != hdd_ctx) return NOTIFY_DONE;
if (!(adapter->device_mode == <API key> ||
adapter->device_mode == WLAN_HDD_P2P_CLIENT))
return NOTIFY_DONE;
if ((hdd_ctx->cfg_ini->nEnableSuspend !=
<API key>) ||
(!hdd_ctx->cfg_ini->fhostArpOffload)) {
hddLog(LOG1, FL("Offload not enabled MCBC=%d, ARPOffload=%d"),
hdd_ctx->cfg_ini->nEnableSuspend,
hdd_ctx->cfg_ini->fhostArpOffload);
return NOTIFY_DONE;
}
in_dev = __in_dev_get_rtnl(adapter->dev);
if (in_dev != NULL) {
for (ifap = &in_dev->ifa_list;
(ifa = *ifap) != NULL;
ifap = &ifa->ifa_next) {
if (!strcmp(adapter->dev->name,
ifa->ifa_label))
break; /* found */
}
}
if (ifa && ifa->ifa_local)
schedule_work(&adapter-><API key>);
return NOTIFY_DONE;
}
/**
* <API key>() - IPv4 change notifier callback
* @nb: pointer to notifier block
* @data: data
* @arg: arg
*
* This is the IPv4 notifier callback function gets invoked
* if any change in IP and then invoke the function @<API key>
* to reconfigure the offload parameters.
*
* Return: 0 on success, error number otherwise.
*/
int <API key>(struct notifier_block *nb,
unsigned long data, void *arg)
{
int ret;
vos_ssr_protect(__func__);
ret = <API key>(nb, data, arg);
vos_ssr_unprotect(__func__);
return ret;
}
VOS_STATUS <API key>(hdd_adapter_t *pAdapter, int fenable)
{
struct in_ifaddr **ifap = NULL;
struct in_ifaddr *ifa = NULL;
struct in_device *in_dev;
int i = 0;
tSirHostOffloadReq offLoadRequest;
hdd_context_t *pHddCtx = WLAN_HDD_GET_CTX(pAdapter);
hddLog(LOG1, FL("fenable = %d"), fenable);
/* In SAP/P2PGo mode, ARP/NS offload feature capability
* is controlled by one bit.
*/
if ((WLAN_HDD_SOFTAP == pAdapter->device_mode ||
WLAN_HDD_P2P_GO == pAdapter->device_mode) &&
!pHddCtx->ap_arpns_support) {
hddLog(LOG1, FL("APR Offload is not supported in SAP/P2PGO mode"));
return VOS_STATUS_SUCCESS;
}
if(fenable)
{
if ((in_dev = __in_dev_get_rtnl(pAdapter->dev)) != NULL)
{
for (ifap = &in_dev->ifa_list; (ifa = *ifap) != NULL;
ifap = &ifa->ifa_next)
{
if (!strcmp(pAdapter->dev->name, ifa->ifa_label))
{
break; /* found */
}
}
}
if(ifa && ifa->ifa_local)
{
offLoadRequest.offloadType = <API key>;
offLoadRequest.enableOrDisable = SIR_OFFLOAD_ENABLE;
hddLog(<API key>, "%s: Enabled", __func__);
if (((<API key> ==
pHddCtx-><API key>) ||
(<API key> ==
pHddCtx-><API key>)) &&
(VOS_TRUE == pHddCtx-><API key>))
{
offLoadRequest.enableOrDisable =
<API key>;
hddLog(<API key>,
"offload: inside arp offload conditional check");
}
hddLog(<API key>, "offload: arp filter programmed = %d",
offLoadRequest.enableOrDisable);
//converting u32 to IPV4 address
for(i = 0 ; i < 4; i++)
{
offLoadRequest.params.hostIpv4Addr[i] =
(ifa->ifa_local >> (i*8) ) & 0xFF ;
}
hddLog(<API key>, " Enable SME HostOffload: %d.%d.%d.%d",
offLoadRequest.params.hostIpv4Addr[0],
offLoadRequest.params.hostIpv4Addr[1],
offLoadRequest.params.hostIpv4Addr[2],
offLoadRequest.params.hostIpv4Addr[3]);
if (eHAL_STATUS_SUCCESS !=
sme_SetHostOffload(<API key>(pAdapter),
pAdapter->sessionId, &offLoadRequest))
{
hddLog(<API key>, "%s: Failed to enable HostOffload "
"feature", __func__);
return <API key>;
}
}
else
{
hddLog(<API key>, FL("IP Address is not assigned\n"));
}
return VOS_STATUS_SUCCESS;
}
else
{
vos_mem_zero((void *)&offLoadRequest, sizeof(tSirHostOffloadReq));
offLoadRequest.enableOrDisable = SIR_OFFLOAD_DISABLE;
offLoadRequest.offloadType = <API key>;
if (eHAL_STATUS_SUCCESS !=
sme_SetHostOffload(<API key>(pAdapter),
pAdapter->sessionId, &offLoadRequest))
{
hddLog(<API key>, "%s: Failure to disable host "
"offload feature", __func__);
return <API key>;
}
return VOS_STATUS_SUCCESS;
}
}
/*
* This function is called before setting mcbc filters
* to modify filter value considering Different Offloads
*/
void <API key>(hdd_context_t* pHddCtx,
tANI_U8 *pMcBcFilter)
{
if (NULL == pHddCtx)
{
hddLog(<API key>, FL("NULL HDD context passed"));
return;
}
*pMcBcFilter = pHddCtx-><API key>;
if (pHddCtx->cfg_ini->fhostArpOffload)
{
/* ARP offload is enabled, do not block bcast packets at RXP
* Will be using Bitmasking to reset the filter. As we have
* disable Broadcast filtering, Anding with the negation
* of Broadcast BIT
*/
hddLog(<API key>, FL("ARP offload is enabled"));
*pMcBcFilter &= ~(<API key>);
}
#ifdef WLAN_NS_OFFLOAD
if (pHddCtx->cfg_ini->fhostNSOffload)
{
/* NS offload is enabled, do not block mcast packets at RXP
* Will be using Bitmasking to reset the filter. As we have
* disable Multicast filtering, Anding with the negation
* of Multicast BIT
*/
hddLog(<API key>, FL("NS offload is enabled"));
*pMcBcFilter &= ~(<API key>);
}
#endif
pHddCtx-><API key> = *pMcBcFilter;
}
void <API key>(hdd_context_t* pHddCtx, v_BOOL_t setfilter)
{
eHalStatus halStatus = eHAL_STATUS_FAILURE;
<API key> wlanRxpFilterParam =
vos_mem_malloc(sizeof(<API key>));
if (NULL == wlanRxpFilterParam)
{
hddLog(<API key>,
"%s: vos_mem_alloc failed ", __func__);
return;
}
hddLog(<API key>,
"%s: Configuring Mcast/Bcast Filter Setting. setfilter %d", __func__, setfilter);
if (TRUE == setfilter)
{
<API key>(pHddCtx,
&wlanRxpFilterParam-><API key>);
}
else
{
/*Use the current configured value to clear*/
wlanRxpFilterParam-><API key> =
pHddCtx-><API key>;
}
wlanRxpFilterParam->setMcstBcstFilter = setfilter;
halStatus = <API key>(pHddCtx->hHal, wlanRxpFilterParam);
if (setfilter && (eHAL_STATUS_SUCCESS == halStatus))
pHddCtx-><API key> = TRUE;
hddLog(<API key>, "%s to post set/reset filter to"
"lower mac with status %d"
"<API key> = %d"
"setMcstBcstFilter = %d",(eHAL_STATUS_SUCCESS != halStatus) ?
"Failed" : "Success", halStatus,
wlanRxpFilterParam-><API key>,
wlanRxpFilterParam->setMcstBcstFilter);
if (eHAL_STATUS_SUCCESS != halStatus)
vos_mem_free(wlanRxpFilterParam);
}
static void <API key>(hdd_context_t* pHddCtx,
hdd_adapter_t *pAdapter,
void (*callback)(void *callbackContext,
boolean suspended),
void *callbackContext)
{
eHalStatus halStatus = eHAL_STATUS_FAILURE;
<API key> wlanSuspendParam =
vos_mem_malloc(sizeof(<API key>));
if (VOS_FALSE == pHddCtx-><API key>) {
pHddCtx-><API key> =
pHddCtx-><API key>;
pHddCtx-><API key> = VOS_TRUE;
hddLog(<API key>, "offload: <API key>");
hddLog(<API key>, "<API key> saved = %d",
pHddCtx-><API key>);
}
if(NULL == wlanSuspendParam)
{
hddLog(<API key>,
"%s: vos_mem_alloc failed ", __func__);
return;
}
hddLog(<API key>,
"%s: send wlan suspend indication", __func__);
if((pHddCtx->cfg_ini->nEnableSuspend == <API key>))
{
//Configure supported OffLoads
<API key>(pAdapter, TRUE);
wlanSuspendParam-><API key> = pHddCtx-><API key>;
}
if ((<API key> ==
(<API key>(pAdapter))->conn_info.connState) ||
(<API key> ==
(<API key>(pAdapter))->conn_info.connState))
wlanSuspendParam->connectedState = TRUE;
else
wlanSuspendParam->connectedState = FALSE;
wlanSuspendParam->sessionId = pAdapter->sessionId;
halStatus = <API key>(pHddCtx->hHal, wlanSuspendParam,
callback, callbackContext);
if(eHAL_STATUS_SUCCESS == halStatus)
{
pHddCtx-><API key> = TRUE;
} else {
hddLog(<API key>,
FL("<API key> returned failure %d"), halStatus);
vos_mem_free(wlanSuspendParam);
}
}
static void hdd_conf_resume_ind(hdd_adapter_t *pAdapter)
{
hdd_context_t* pHddCtx = WLAN_HDD_GET_CTX(pAdapter);
eHalStatus halStatus = eHAL_STATUS_FAILURE;
halStatus = <API key>(pHddCtx->hHal,
NULL
);
if (eHAL_STATUS_SUCCESS != halStatus)
{
hddLog(<API key>,
"%s: <API key> return failure %d",
__func__, halStatus);
}
hddLog(<API key>,
"%s: send wlan resume indication", __func__);
/* Disable supported OffLoads */
<API key>(pAdapter, FALSE);
pHddCtx-><API key> = FALSE;
if (VOS_TRUE == pHddCtx-><API key>) {
pHddCtx-><API key> =
pHddCtx-><API key>;
pHddCtx-><API key> = VOS_FALSE;
}
hddLog(<API key>,
"offload: in hdd_conf_resume_ind, restoring <API key>");
hddLog(<API key>, "<API key> = %d",
pHddCtx-><API key>);
}
//Suspend routine registered with Android OS
void hdd_suspend_wlan(void (*callback)(void *callbackContext, boolean suspended),
void *callbackContext)
{
hdd_context_t *pHddCtx = NULL;
v_CONTEXT_t pVosContext = NULL;
VOS_STATUS status;
hdd_adapter_t *pAdapter = NULL;
<API key> *pAdapterNode = NULL, *pNext = NULL;
bool hdd_enter_bmps = FALSE;
hddLog(<API key>, "%s: WLAN being suspended by Android OS",__func__);
//Get the global VOSS context.
pVosContext = <API key>(VOS_MODULE_ID_SYS, NULL);
if(!pVosContext) {
hddLog(<API key>,"%s: Global VOS context is Null", __func__);
return;
}
//Get the HDD context.
pHddCtx = (hdd_context_t *)vos_get_context(VOS_MODULE_ID_HDD, pVosContext );
if(!pHddCtx) {
hddLog(<API key>,"%s: HDD context is Null",__func__);
return;
}
if (pHddCtx->isLogpInProgress) {
hddLog(<API key>,
"%s: Ignore suspend wlan, LOGP in progress!", __func__);
return;
}
hdd_set_pwrparams(pHddCtx);
status = <API key> ( pHddCtx, &pAdapterNode );
while ( NULL != pAdapterNode && VOS_STATUS_SUCCESS == status )
{
pAdapter = pAdapterNode->pAdapter;
if ( (<API key> != pAdapter->device_mode)
&& (WLAN_HDD_SOFTAP != pAdapter->device_mode)
&& (WLAN_HDD_P2P_CLIENT != pAdapter->device_mode) )
{
goto send_suspend_ind;
}
/* Avoid multiple enter/exit BMPS in this while loop using
* hdd_enter_bmps flag
*/
if (FALSE == hdd_enter_bmps && (BMPS == pmcGetPmcState(pHddCtx->hHal)))
{
hdd_enter_bmps = TRUE;
/* If device was already in BMPS, and dynamic DTIM is set,
* exit(set the device to full power) and enter BMPS again
* to reflect new DTIM value */
wlan_hdd_enter_bmps(pAdapter, <API key>);
wlan_hdd_enter_bmps(pAdapter, <API key>);
pHddCtx-><API key> = TRUE;
}
#ifdef <API key>
if (pHddCtx->cfg_ini->nEnableSuspend == <API key>)
{
//stop the interface before putting the chip to standby
hddLog(LOG1, FL("Disabling queues"));
netif_tx_disable(pAdapter->dev);
netif_carrier_off(pAdapter->dev);
}
else if (pHddCtx->cfg_ini->nEnableSuspend ==
<API key>)
{
//Execute deep sleep procedure
<API key>(pHddCtx, pAdapter);
}
#endif
send_suspend_ind:
//stop all TX queues before suspend
hddLog(LOG1, FL("Disabling queues"));
netif_tx_disable(pAdapter->dev);
<API key>(pVosContext, true);
/* Keep this suspend indication at the end (before processing next adaptor)
* for discrete. This indication is considered as trigger point to start
* WOW (if wow is enabled). */
/*Suspend notification sent down to driver*/
<API key>(pHddCtx, pAdapter, callback, callbackContext);
status = <API key> ( pHddCtx, pAdapterNode, &pNext );
pAdapterNode = pNext;
}
pHddCtx->hdd_wlan_suspended = TRUE;
#ifdef <API key>
if(pHddCtx->cfg_ini->nEnableSuspend == <API key>)
{
hdd_enter_standby(pHddCtx);
}
#endif
return;
}
static void <API key>
(
v_PVOID_t callbackContext,
tPmcState newState
)
{
hdd_context_t *pHddCtx = callbackContext;
/* if the driver was not in BMPS during early suspend,
* the dynamic DTIM is now updated at Riva */
if ((newState == BMPS) && pHddCtx->hdd_wlan_suspended
&& pHddCtx->cfg_ini->enableDynamicDTIM
&& (pHddCtx-><API key> == FALSE))
{
pHddCtx-><API key> = TRUE;
}
spin_lock(&pHddCtx->filter_lock);
if ((newState == BMPS) && pHddCtx->hdd_wlan_suspended)
{
spin_unlock(&pHddCtx->filter_lock);
if (VOS_FALSE == pHddCtx-><API key>)
{
pHddCtx-><API key> =
pHddCtx-><API key>;
pHddCtx-><API key> = VOS_TRUE;
hddLog(<API key>, "offload: callback to associated");
hddLog(<API key>, "saving <API key> = %d",
pHddCtx-><API key>);
hddLog(<API key>,
"offload: calling <API key>");
}
<API key>(pHddCtx, TRUE);
if(pHddCtx-><API key> != TRUE)
hddLog(<API key>, "%s: Not able to set mcast/bcast filter ", __func__);
}
else
{
/* Android framework can send resume request when the WCN chip is
* in IMPS mode. When the chip exits IMPS mode the firmware will
* restore all the registers to the state they were before the chip
* entered IMPS and so our hardware filter settings configured by the
* resume request will be lost. So reconfigure the filters on detecting
* a change in the power state of the WCN chip.
*/
spin_unlock(&pHddCtx->filter_lock);
if (IMPS != newState)
{
spin_lock(&pHddCtx->filter_lock);
if (FALSE == pHddCtx->hdd_wlan_suspended)
{
spin_unlock(&pHddCtx->filter_lock);
hddLog(<API key>,
"Not in IMPS/BMPS and suspended state");
<API key>(pHddCtx, FALSE);
}
else
{
spin_unlock(&pHddCtx->filter_lock);
}
}
}
}
void <API key>(hdd_context_t *pHddCtx)
{
v_CONTEXT_t pVosContext;
tHalHandle smeContext;
pVosContext = <API key>(VOS_MODULE_ID_SYS, NULL);
if (NULL == pVosContext)
{
hddLog(LOGE, "%s: Invalid pContext", __func__);
return;
}
smeContext = vos_get_context(VOS_MODULE_ID_SME, pVosContext);
if (NULL == smeContext)
{
hddLog(LOGE, "%s: Invalid smeContext", __func__);
return;
}
spin_lock_init(&pHddCtx->filter_lock);
if (<API key> ==
pHddCtx->cfg_ini->nEnableSuspend)
{
if(!pHddCtx->cfg_ini-><API key>)
{
<API key>(smeContext,
<API key>, pHddCtx);
}
/* TODO: For Power Save Offload case */
}
}
void <API key>(hdd_context_t *pHddCtx)
{
v_CONTEXT_t pVosContext;
tHalHandle smeContext;
pVosContext = <API key>(VOS_MODULE_ID_SYS, NULL);
if (NULL == pVosContext)
{
hddLog(LOGE, "%s: Invalid pContext", __func__);
return;
}
smeContext = vos_get_context(VOS_MODULE_ID_SME, pVosContext);
if (NULL == smeContext)
{
hddLog(LOGE, "%s: Invalid smeContext", __func__);
return;
}
if (<API key> ==
pHddCtx->cfg_ini->nEnableSuspend)
{
if(!pHddCtx->cfg_ini-><API key>)
{
<API key>(smeContext,
<API key>);
}
/* TODO: For Power Save Offload case */
}
}
void hdd_resume_wlan(void)
{
hdd_context_t *pHddCtx = NULL;
hdd_adapter_t *pAdapter = NULL;
<API key> *pAdapterNode = NULL, *pNext = NULL;
VOS_STATUS status;
v_CONTEXT_t pVosContext = NULL;
hddLog(<API key>, "%s: WLAN being resumed by Android OS",__func__);
//Get the global VOSS context.
pVosContext = <API key>(VOS_MODULE_ID_SYS, NULL);
if(!pVosContext) {
hddLog(<API key>,"%s: Global VOS context is Null", __func__);
return;
}
//Get the HDD context.
pHddCtx = (hdd_context_t *)vos_get_context(VOS_MODULE_ID_HDD, pVosContext );
if(!pHddCtx) {
hddLog(<API key>,"%s: HDD context is Null",__func__);
return;
}
if (pHddCtx->isLogpInProgress)
{
hddLog(<API key>,
"%s: Ignore resume wlan, LOGP in progress!", __func__);
return;
}
pHddCtx->hdd_wlan_suspended = FALSE;
/*loop through all adapters. Concurrency */
status = <API key> ( pHddCtx, &pAdapterNode );
while ( NULL != pAdapterNode && VOS_STATUS_SUCCESS == status )
{
pAdapter = pAdapterNode->pAdapter;
if ( (<API key> != pAdapter->device_mode)
&& (WLAN_HDD_SOFTAP != pAdapter->device_mode)
&& (WLAN_HDD_P2P_CLIENT != pAdapter->device_mode) )
{
goto send_resume_ind;
}
#ifdef <API key>
if(pHddCtx->hdd_ps_state == <API key>)
{
hddLog(<API key>, "%s: WLAN being resumed from deep sleep",__func__);
hdd_exit_deep_sleep(pAdapter);
}
#endif
if(pHddCtx-><API key> == TRUE)
{
/*Switch back to DTIM 1*/
<API key> powerRequest = { 0 };
powerRequest.uIgnoreDTIM = pHddCtx-><API key>;
powerRequest.uListenInterval = pHddCtx->hdd_actual_LI_value;
powerRequest.uMaxLIModulatedDTIM = pHddCtx->cfg_ini->fMaxLIModulatedDTIM;
/*Disabled ModulatedDTIM if enabled on suspend*/
if(pHddCtx->cfg_ini->enableModulatedDTIM)
powerRequest.uDTIMPeriod = 0;
/* Update ignoreDTIM and ListedInterval in CFG with default values */
ccmCfgSetInt(pHddCtx->hHal, WNI_CFG_IGNORE_DTIM, powerRequest.uIgnoreDTIM,
NULL, eANI_BOOLEAN_FALSE);
ccmCfgSetInt(pHddCtx->hHal, <API key>, powerRequest.uListenInterval,
NULL, eANI_BOOLEAN_FALSE);
VOS_TRACE(VOS_MODULE_ID_HDD, <API key>,
"Switch to DTIM%d",powerRequest.uListenInterval);
sme_SetPowerParams( <API key>(pAdapter), &powerRequest, FALSE);
if (BMPS == pmcGetPmcState(pHddCtx->hHal))
{
/* put the device into full power */
wlan_hdd_enter_bmps(pAdapter, <API key>);
/* put the device back into BMPS */
wlan_hdd_enter_bmps(pAdapter, <API key>);
pHddCtx-><API key> = FALSE;
}
}
send_resume_ind:
//wake the tx queues
hddLog(LOG1, FL("Enabling queues"));
<API key>(pVosContext, false);
<API key>(pAdapter->dev);
hdd_conf_resume_ind(pAdapter);
status = <API key> ( pHddCtx, pAdapterNode, &pNext );
pAdapterNode = pNext;
}
#ifdef IPA_OFFLOAD
hdd_ipa_resume(pHddCtx);
#endif
#ifdef <API key>
if(pHddCtx->hdd_ps_state == <API key>)
{
hdd_exit_standby(pHddCtx);
}
#endif
return;
}
VOS_STATUS <API key>(void)
{
v_CONTEXT_t pVosContext = NULL;
hddLog(<API key>, "%s: WLAN being reset",__func__);
//Get the global VOSS context.
pVosContext = <API key>(VOS_MODULE_ID_SYS, NULL);
if(!pVosContext)
{
hddLog(<API key>,"%s: Global VOS context is Null", __func__);
return <API key>;
}
hddLog(<API key>, "%s: Preventing the phone from going to suspend",__func__);
// Prevent the phone from going to sleep
hdd_prevent_suspend(<API key>);
return VOS_STATUS_SUCCESS;
}
static void hdd_ssr_timer_init(void)
{
init_timer(&ssr_timer);
}
static void hdd_ssr_timer_del(void)
{
del_timer(&ssr_timer);
ssr_timer_started = false;
}
static void hdd_ssr_timer_cb(unsigned long data)
{
hddLog(<API key>, "%s: HDD SSR timer expired!", __func__);
VOS_BUG(0);
}
static void hdd_ssr_timer_start(int msec)
{
if(ssr_timer_started)
{
hddLog(<API key>, "%s: Trying to start SSR timer when "
"it's running!", __func__);
}
ssr_timer.expires = jiffies + msecs_to_jiffies(msec);
ssr_timer.function = hdd_ssr_timer_cb;
add_timer(&ssr_timer);
ssr_timer_started = true;
}
/* the HDD interface to WLAN driver shutdown,
* the primary shutdown function in SSR
*/
VOS_STATUS hdd_wlan_shutdown(void)
{
VOS_STATUS vosStatus;
v_CONTEXT_t pVosContext = NULL;
hdd_context_t *pHddCtx = NULL;
pVosSchedContext vosSchedContext = NULL;
hddLog(<API key>, "%s: WLAN driver shutting down! ",__func__);
/* If SSR never completes, then do kernel panic. */
hdd_ssr_timer_init();
hdd_ssr_timer_start(<API key>);
/* Get the global VOSS context. */
pVosContext = <API key>(VOS_MODULE_ID_SYS, NULL);
if(!pVosContext) {
hddLog(<API key>,"%s: Global VOS context is Null", __func__);
return <API key>;
}
/* Get the HDD context. */
pHddCtx = (hdd_context_t*)vos_get_context(VOS_MODULE_ID_HDD, pVosContext);
if(!pHddCtx) {
hddLog(<API key>,"%s: HDD context is Null",__func__);
return <API key>;
}
pHddCtx->isLogpInProgress = TRUE;
<API key>(VOS_MODULE_ID_VOSS, TRUE);
<API key>();
#ifdef MSM_PLATFORM
if (<API key> ==
<API key>(&pHddCtx->bus_bw_timer))
{
vos_timer_stop(&pHddCtx->bus_bw_timer);
}
#endif
<API key>(pHddCtx);
#ifdef IPA_UC_OFFLOAD
<API key>();
#endif
vosStatus = <API key>(pHddCtx);
if ( !<API key>( vosStatus ) )
{
hddLog(<API key>,"%s: <API key> failed",__func__);
}
/* Disable IMPS/BMPS as we do not want the device to enter any power
* save mode on its own during reset sequence
*/
<API key>(pHddCtx->hHal, <API key>);
<API key>(pHddCtx->hHal, <API key>);
<API key>(pHddCtx->hHal, <API key>);
vosSchedContext = get_vos_sched_ctxt();
/* Wakeup all driver threads */
if(TRUE == pHddCtx->isMcThreadSuspended){
complete(&vosSchedContext->ResumeMcEvent);
pHddCtx->isMcThreadSuspended= FALSE;
}
if(TRUE == pHddCtx->isTxThreadSuspended){
complete(&vosSchedContext->ResumeTxEvent);
pHddCtx->isTxThreadSuspended= FALSE;
}
if(TRUE == pHddCtx->isRxThreadSuspended){
complete(&vosSchedContext->ResumeRxEvent);
pHddCtx->isRxThreadSuspended= FALSE;
}
#ifdef QCA_CONFIG_SMP
if (TRUE == pHddCtx-><API key>) {
complete(&vosSchedContext->ResumeTlshimRxEvent);
pHddCtx-><API key> = FALSE;
}
#endif
/* Reset the Suspend Variable */
pHddCtx->isWlanSuspended = FALSE;
/* Stop all the threads; we do not want any messages to be a processed,
* any more and the best way to ensure that is to terminate the threads
* gracefully.
*/
/* Wait for MC to exit */
hddLog(<API key>, "%s: Shutting down MC thread",__func__);
set_bit(<API key>, &vosSchedContext->mcEventFlag);
set_bit(MC_POST_EVENT_MASK, &vosSchedContext->mcEventFlag);
<API key>(&vosSchedContext->mcWaitQueue);
wait_for_completion(&vosSchedContext->McShutdown);
/* Wait for TX to exit */
hddLog(<API key>, "%s: Shutting down TX thread",__func__);
set_bit(<API key>, &vosSchedContext->txEventFlag);
set_bit(TX_POST_EVENT_MASK, &vosSchedContext->txEventFlag);
<API key>(&vosSchedContext->txWaitQueue);
wait_for_completion(&vosSchedContext->TxShutdown);
/* Wait for RX to exit */
hddLog(<API key>, "%s: Shutting down RX thread",__func__);
set_bit(<API key>, &vosSchedContext->rxEventFlag);
set_bit(RX_POST_EVENT_MASK, &vosSchedContext->rxEventFlag);
<API key>(&vosSchedContext->rxWaitQueue);
wait_for_completion(&vosSchedContext->RxShutdown);
#ifdef QCA_CONFIG_SMP
/* Wait for TLshim RX to exit */
hddLog(<API key>, "%s: Shutting down TLshim RX thread",
__func__);
<API key>(vosSchedContext->cpuHotPlugNotifier);
set_bit(<API key>, &vosSchedContext->tlshimRxEvtFlg);
set_bit(RX_POST_EVENT_MASK, &vosSchedContext->tlshimRxEvtFlg);
<API key>(&vosSchedContext->tlshimRxWaitQueue);
hddLog(<API key>, "%s: Waiting for TLshim RX thread to exit",
__func__);
wait_for_completion(&vosSchedContext->TlshimRxShutdown);
vosSchedContext->TlshimRxThread = NULL;
hddLog(<API key>, "%s: Waiting for dropping RX packets",
__func__);
<API key>(vosSchedContext, WLAN_MAX_STA_COUNT);
hddLog(<API key>, "%s: Waiting for freeing freeQ", __func__);
<API key>(vosSchedContext);
#endif
hddLog(<API key>, "%s: Doing WDA STOP", __func__);
vosStatus = WDA_stop(pVosContext, <API key>);
if (!<API key>(vosStatus))
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Failed to stop WDA", __func__);
VOS_ASSERT(<API key>(vosStatus));
WDA_setNeedShutdown(pVosContext);
}
hddLog(<API key>, "%s: Doing SME STOP",__func__);
/* Stop SME - Cannot invoke vos_stop as vos_stop relies
* on threads being running to process the SYS Stop
*/
vosStatus = sme_Stop(pHddCtx->hHal, <API key>);
if (!<API key>(vosStatus))
{
VOS_TRACE( VOS_MODULE_ID_VOSS, <API key>,
"%s: Failed to stop sme %d", __func__, vosStatus);
VOS_ASSERT(0);
}
hddLog(<API key>, "%s: Doing MAC STOP",__func__);
/* Stop MAC (PE and HAL) */
vosStatus = macStop(pHddCtx->hHal, <API key>);
if (!<API key>(vosStatus))
{
VOS_TRACE( VOS_MODULE_ID_VOSS, <API key>,
"%s: Failed to stop mac %d", __func__, vosStatus);
VOS_ASSERT(0);
}
hddLog(<API key>, "%s: Doing TL STOP",__func__);
/* Stop TL */
vosStatus = WLANTL_Stop(pVosContext);
if (!<API key>(vosStatus))
{
VOS_TRACE( VOS_MODULE_ID_VOSS, <API key>,
"%s: Failed to stop TL %d", __func__, vosStatus);
VOS_ASSERT(0);
}
<API key>(pHddCtx);
hddLog(<API key>, "%s: Flush Queues",__func__);
/* Clean up message queues of TX, RX and MC thread */
<API key>(vosSchedContext);
<API key>(vosSchedContext);
<API key>(vosSchedContext);
/* Deinit all the TX, RX and MC queues */
<API key>(vosSchedContext);
hddLog(<API key>, "%s: Doing VOS Shutdown",__func__);
/* shutdown VOSS */
vos_shutdown(pVosContext);
/*mac context has already been released in mac_close call
so setting it to NULL in hdd context*/
pHddCtx->hHal = (tHalHandle)NULL;
if (<API key>("wlan"))
{
hddLog(<API key>, "%s: failed to free power on lock",
__func__);
}
#ifdef WLAN_FEATURE_LPSS
<API key>(NULL, NULL, 0, 0);
#endif
hddLog(<API key>, "%s: WLAN driver shutdown complete"
,__func__);
return VOS_STATUS_SUCCESS;
}
/* the HDD interface to WLAN driver re-init.
* This is called to initialize/start WLAN driver after a shutdown.
*/
VOS_STATUS hdd_wlan_re_init(void *hif_sc)
{
VOS_STATUS vosStatus;
v_CONTEXT_t pVosContext = NULL;
hdd_context_t *pHddCtx = NULL;
eHalStatus halStatus;
hdd_adapter_t *pAdapter;
int i;
hdd_prevent_suspend(<API key>);
<API key>(VOS_MODULE_ID_VOSS, TRUE);
/* Get the VOS context */
pVosContext = <API key>(VOS_MODULE_ID_SYS, NULL);
if(pVosContext == NULL)
{
hddLog(<API key>, "%s: Failed <API key>",
__func__);
goto err_re_init;
}
/* Get the HDD context */
pHddCtx = (hdd_context_t *)vos_get_context(VOS_MODULE_ID_HDD, pVosContext);
if(!pHddCtx)
{
hddLog(<API key>, "%s: HDD context is Null", __func__);
goto err_re_init;
}
if (!hif_sc) {
hddLog(<API key>, "%s: hif_sc is NULL", __func__);
goto err_re_init;
}
((VosContextType*)pVosContext)->pHIFContext = hif_sc;
/* The driver should always be initialized in STA mode after SSR */
hdd_set_conparam(0);
/* Re-open VOSS, it is a re-open b'se control transport was never closed. */
vosStatus = vos_open(&pVosContext, 0);
if (!<API key>(vosStatus))
{
hddLog(<API key>,"%s: vos_open failed",__func__);
goto err_re_init;
}
#if !defined(REMOVE_PKT_LOG)
<API key>(hif_sc,
vos_get_context(VOS_MODULE_ID_TXRX, pVosContext));
#endif
/* Save the hal context in Adapter */
pHddCtx->hHal = (tHalHandle)vos_get_context( VOS_MODULE_ID_SME, pVosContext );
if ( NULL == pHddCtx->hHal )
{
hddLog(<API key>,"%s: HAL context is null",__func__);
goto err_vosclose;
}
/* Set the SME configuration parameters. */
vosStatus = hdd_set_sme_config(pHddCtx);
if ( VOS_STATUS_SUCCESS != vosStatus )
{
hddLog(<API key>,"%s: Failed hdd_set_sme_config",__func__);
goto err_vosclose;
}
vosStatus = vos_preStart( pHddCtx->pvosContext );
if ( !<API key>( vosStatus ) )
{
hddLog(<API key>,"%s: vos_preStart failed",__func__);
goto err_vosclose;
}
vosStatus = <API key>(pHddCtx);
if (!<API key>(vosStatus)) {
hddLog(<API key>,
"%s: Failed to init channel list", __func__);
goto err_vosclose;
}
/* In the integrated architecture we update the configuration from
the INI file and from NV before vOSS has been started so that
the final contents are available to send down to the cCPU */
/* Apply the cfg.ini to cfg.dat */
if (FALSE == <API key>(pHddCtx))
{
hddLog(<API key>,"%s: config update failed",__func__ );
goto err_vosclose;
}
/* Set the MAC Address, currently this is used by HAL to add self sta.
* Remove this once self sta is added as part of session open. */
halStatus = cfgSetStr(pHddCtx->hHal, WNI_CFG_STA_ID,
(v_U8_t *)&pHddCtx->cfg_ini->intfMacAddr[0],
sizeof(pHddCtx->cfg_ini->intfMacAddr[0]));
if (!HAL_STATUS_SUCCESS(halStatus))
{
hddLog(<API key>,"%s: Failed to set MAC Address. "
"HALStatus is %08d [x%08x]",__func__, halStatus, halStatus);
goto err_vosclose;
}
/* Start VOSS which starts up the SME/MAC/HAL modules and everything else
Note: Firmware image will be read and downloaded inside vos_start API */
vosStatus = vos_start( pVosContext );
if ( !<API key>( vosStatus ) )
{
hddLog(<API key>,"%s: vos_start failed",__func__);
goto err_vosclose;
}
#ifdef IPA_UC_OFFLOAD
if (<API key>())
hddLog(LOGE, "%s: HDD IPA UC reinit failed", __func__);
#endif
vosStatus = <API key>( pHddCtx );
if ( !<API key>( vosStatus ) )
{
hddLog(<API key>,"%s: <API key> failed",
__func__);
goto err_vosstop;
}
/* Try to get an adapter from mode ID */
pAdapter = hdd_get_adapter(pHddCtx, <API key>);
if (!pAdapter) {
pAdapter = hdd_get_adapter(pHddCtx, WLAN_HDD_SOFTAP);
if (!pAdapter) {
pAdapter = hdd_get_adapter(pHddCtx, WLAN_HDD_IBSS);
if (!pAdapter) {
hddLog(<API key>, "%s: Failed to get Adapter!",
__func__);
}
}
}
/* Get WLAN Host/FW/HW version */
if (pAdapter)
<API key>(pAdapter, NULL, NULL);
/* Pass FW version to HIF layer */
hif_set_fw_info(hif_sc, pHddCtx->target_fw_version);
/* Restart all adapters */
<API key>(pHddCtx);
/* Reconfigure FW logs after SSR */
if (pAdapter) {
if (pHddCtx->fw_log_settings.enable != 0) {
<API key>(pAdapter->sessionId,
<API key>,
pHddCtx->fw_log_settings.enable , DBG_CMD);
} else {
<API key>(pAdapter->sessionId,
<API key>,
pHddCtx->fw_log_settings.enable, DBG_CMD);
}
if (pHddCtx->fw_log_settings.dl_report != 0) {
<API key>(pAdapter->sessionId,
<API key>,
pHddCtx->fw_log_settings.dl_report, DBG_CMD);
<API key>(pAdapter->sessionId,
WMI_DBGLOG_TYPE,
pHddCtx->fw_log_settings.dl_type, DBG_CMD);
<API key>(pAdapter->sessionId,
<API key>,
pHddCtx->fw_log_settings.dl_loglevel, DBG_CMD);
for (i = 0; i < MAX_MOD_LOGLEVEL; i++) {
if (pHddCtx->fw_log_settings.dl_mod_loglevel[i] != 0) {
<API key>(pAdapter->sessionId,
<API key>,
pHddCtx->fw_log_settings.dl_mod_loglevel[i],
DBG_CMD);
}
}
}
}
/* Register TM level change handler function to the platform */
<API key>(pHddCtx);
pHddCtx-><API key> = FALSE;
pHddCtx->btCoexModeSet = false;
<API key>(pHddCtx);
hdd_ssr_timer_del();
<API key>(<API key>, NULL, 0);
/* Allow the phone to go to sleep */
hdd_allow_suspend(<API key>);
/* register for riva power on lock */
if (<API key>("wlan"))
{
hddLog(<API key>,"%s: req riva power on lock failed",
__func__);
goto <API key>;
}
<API key>(VOS_MODULE_ID_VOSS, FALSE);
/* Register for p2p ack indication */
<API key>(pHddCtx->hHal, <API key>);
#ifdef <API key>
<API key>(pHddCtx->hHal,
<API key>);
#endif /* <API key> */
<API key>(pHddCtx->hHal, <API key>);
#ifdef WLAN_FEATURE_LPSS
<API key>(pHddCtx);
<API key>(pHddCtx->target_fw_version,
pHddCtx->target_hw_version,
pHddCtx->target_hw_name);
#endif
/* set chip power save failure detected callback */
<API key>(pHddCtx->hHal,
<API key>);
ol_pktlog_init(hif_sc);
goto success;
<API key>:
#ifdef <API key>
<API key>(pHddCtx);
#endif
<API key>(pHddCtx);
err_vosstop:
vos_stop(pVosContext);
err_vosclose:
vos_close(pVosContext);
vos_sched_close(pVosContext);
if (pHddCtx)
{
/* Unregister the Net Device Notifier */
<API key>(&hdd_netdev_notifier);
/* Clean up HDD Nlink Service */
send_btc_nlink_msg(<API key>, 0);
#ifdef <API key>
<API key>();
nl_srv_exit(pHddCtx->ptt_pid);
#else
nl_srv_exit();
#endif /* <API key> */
/* Free up dynamically allocated members inside HDD Adapter */
kfree(pHddCtx->cfg_ini);
pHddCtx->cfg_ini= NULL;
<API key>(pHddCtx);
wiphy_unregister(pHddCtx->wiphy);
wiphy_free(pHddCtx->wiphy);
}
vos_preClose(&pVosContext);
#ifdef MEMORY_DEBUG
vos_mem_exit();
#endif
err_re_init:
/* Allow the phone to go to sleep */
hdd_allow_suspend(<API key>);
<API key>(VOS_MODULE_ID_VOSS, FALSE);
VOS_BUG(0);
return -EPERM;
success:
/* Trigger replay of BTC events */
send_btc_nlink_msg(<API key>, 0);
pHddCtx->isLogpInProgress = FALSE;
return VOS_STATUS_SUCCESS;
} |
<?php
$site_title = "Toolchain";
?>
<?php
include("../header.html");
?>
<?php
include("../nav.html");
?>
<tr>
<td id="main_content_td">
<div id="main_content">
<h1>Overview: Toolchain</h1>
The figure below depicts the complete XMLVM toolchain. Each of the
boxes represent an artifact while the arrows denote the various
transformations between those artifacts. The input to the XMLVM
toolchain is either a Java class file or a .NET executable. A Java
class file is translated to XMLVM<sub>JVM</sub> which is an XML-document
describing the contents of that class file. Likewise XMLVM<sub>CLR</sub> is an
XML-document describing the contents of a .NET executable. XMLVM<sub>CLR</sub>
can be cross-compiled to XMLVM<sub>JVM</sub> with the help of a data flow
analysis (DFA) which is shown as XMLVM<sub>CLR-DFA</sub> in the figure below.
XMLVM<sub>JVM</sub> serves as a canonical representation as it acts as a
boundary between the front- and back-end of the cross-compiler. Once
XMLVM<sub>JVM</sub> has been generated, it can be mapped to various high-level
programming languages. It is also possible to map XMLVM<sub>JVM</sub> to a
Java class file again. This allows various permutations of the XMLVM
toolchain. Each of those different arrangements of the XMLVM toolchain
is described in more detail on a separate page. First, we describe how
a <a href="../clr2jvm">.NET application can be translated to XMLVM<sub>JVM</sub></a>. Next, we
discuss how <a href="../javascript">XMLVM<sub>JVM</sub> can be cross-compiled
to JavaScript</a> to generate
AJAX applications. Note that with the front-end it is possible
to generate AJAX applications from Java or any of the .NET
applications. The final use case we present here is a backend for
Objective-C which effectively allows <a href="../iphone">Java applications to be
cross-compiled to native iPhone applications</a>.
<div style="text-align:center">
<img src="toolchain_summary.jpg" style="display:inline" alt="XMLVM Toolchain Summary"/>
</div>
<?php
include("../footer.html");
?> |
/* ScriptData
SDName: Illidari_Council
SD%Complete: 95
SDComment: Circle of Healing not working properly.
SDCategory: Black Temple
EndScriptData */
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "SpellScript.h"
#include "SpellAuraEffects.h"
#include "black_temple.h"
enum IllidariCouncil
{
//Speech'n'Sounds
SAY_GATH_SPECIAL1 = 2,
SAY_GATH_SPECIAL2 = 3,
SAY_GATH_SLAY = 4,
SAY_GATH_COMNT = 5,
SAY_GATH_DEATH = 6,
SAY_MALA_SPECIAL1 = 2,
SAY_MALA_SPECIAL2 = 3,
SAY_MALA_SLAY = 4,
SAY_MALA_COMNT = 5,
SAY_MALA_DEATH = 6,
SAY_ZERE_SPECIAL1 = 2,
SAY_ZERE_SPECIAL2 = 3,
SAY_ZERE_SLAY = 4,
SAY_ZERE_COMNT = 5,
SAY_ZERE_DEATH = 6,
SAY_VERA_SPECIAL1 = 2,
SAY_VERA_SPECIAL2 = 3,
SAY_VERA_SLAY = 4,
SAY_VERA_COMNT = 5,
SAY_VERA_DEATH = 6,
AKAMAID = 23089,
// High Nethermancer Zerevor's spells
SPELL_FLAMESTRIKE = 41481,
SPELL_BLIZZARD = 41482,
SPELL_ARCANE_BOLT = 41483,
<API key> = 41524,
SPELL_DAMPEN_MAGIC = 41478,
// Lady Malande's spells
<API key> = 41471,
<API key> = 41455,
<API key> = 41475,
<API key> = 33619,
SPELL_DIVINE_WRATH = 41472,
SPELL_HEAL_VISUAL = 24171,
// Gathios the Shatterer's spells
<API key> = 41450,
<API key> = 41451,
SPELL_CONSECRATION = 41541,
<API key> = 41468,
<API key> = 41469,
SPELL_SEAL_OF_BLOOD = 41459,
<API key> = 41453,
SPELL_DEVOTION_AURA = 41452,
// Veras Darkshadow's spells
SPELL_DEADLY_POISON = 41485,
SPELL_ENVENOM = 41487,
SPELL_VANISH = 41479,
SPELL_BERSERK = 45078
};
#define ERROR_INST_DATA "SD2 ERROR: Instance Data for Black Temple not set properly; Illidari Council event will not function properly."
struct CouncilYells
{
int32 entry;
uint32 timer;
};
static CouncilYells CouncilAggro[]=
{
{0, 5000}, // Gathios
{0, 5500}, // Veras
{0, 5000}, // Malande
{0, 0}, // Zerevor
};
// Need to get proper timers for this later
static CouncilYells CouncilEnrage[]=
{
{1, 2000}, // Gathios
{1, 6000}, // Veras
{1, 5000}, // Malande
{1, 0}, // Zerevor
};
class <API key> : public CreatureScript
{
public:
<API key>() : CreatureScript("<API key>") { }
CreatureAI* GetAI(Creature* c) const override
{
return new <API key>(c);
}
struct <API key> : public ScriptedAI
{
<API key>(Creature* creature) : ScriptedAI(creature)
{
for (uint8 i = 0; i < 4; ++i)
Council[i] = 0;
}
uint64 Council[4];
uint32 EnrageTimer;
uint32 AggroYellTimer;
uint8 YellCounter; // Serves as the counter for both the aggro and enrage yells
bool EventStarted;
void Reset() override
{
EnrageTimer = 900000; // 15 minutes
AggroYellTimer = 500;
YellCounter = 0;
EventStarted = false;
}
// finds and stores the GUIDs for each Council member using instance data system.
void LoadCouncilGUIDs()
{
if (InstanceScript* instance = me->GetInstanceScript())
{
Council[0] = instance->GetData64(<API key>);
Council[1] = instance->GetData64(<API key>);
Council[2] = instance->GetData64(DATA_LADY_MALANDE);
Council[3] = instance->GetData64(<API key>);
} else TC_LOG_ERROR("scripts", ERROR_INST_DATA);
}
void EnterCombat(Unit* /*who*/) override { }
void AttackStart(Unit* /*who*/) override { }
void MoveInLineOfSight(Unit* /*who*/) override { }
void UpdateAI(uint32 diff) override
{
if (!EventStarted)
return;
if (YellCounter > 3)
return;
if (AggroYellTimer)
{
if (AggroYellTimer <= diff)
{
if (Creature* pMember = ObjectAccessor::GetCreature(*me, Council[YellCounter]))
{
pMember->AI()->Talk(CouncilAggro[YellCounter].entry);
AggroYellTimer = CouncilAggro[YellCounter].timer;
}
++YellCounter;
if (YellCounter > 3)
YellCounter = 0; // Reuse for Enrage Yells
} else AggroYellTimer -= diff;
}
if (EnrageTimer)
{
if (EnrageTimer <= diff)
{
if (Creature* pMember = ObjectAccessor::GetCreature(*me, Council[YellCounter]))
{
pMember->CastSpell(pMember, SPELL_BERSERK, true);
pMember->AI()->Talk(CouncilEnrage[YellCounter].entry);
EnrageTimer = CouncilEnrage[YellCounter].timer;
}
++YellCounter;
} else EnrageTimer -= diff;
}
}
};
};
class <API key> : public CreatureScript
{
public:
<API key>() : CreatureScript("<API key>") { }
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<<API key>>(creature);
}
struct <API key> : public ScriptedAI
{
<API key>(Creature* creature) : ScriptedAI(creature)
{
instance = creature->GetInstanceScript();
for (uint8 i = 0; i < 4; ++i)
Council[i] = 0;
}
InstanceScript* instance;
uint64 Council[4];
uint32 CheckTimer;
uint32 EndEventTimer;
uint8 DeathCount;
bool EventBegun;
void Reset() override
{
CheckTimer = 2000;
EndEventTimer = 0;
DeathCount = 0;
Creature* pMember = nullptr;
for (uint8 i = 0; i < 4; ++i)
{
pMember = ObjectAccessor::GetCreature((*me), Council[i]);
if (!pMember)
continue;
if (!pMember->IsAlive())
{
pMember->RemoveCorpse();
pMember->Respawn();
}
pMember->AI()->EnterEvadeMode();
}
instance->SetBossState(<API key>, NOT_STARTED);
if (Creature* VoiceTrigger = ObjectAccessor::GetCreature(*me, instance->GetData64(<API key>)))
VoiceTrigger->AI()->EnterEvadeMode();
EventBegun = false;
me->RemoveFlag(UNIT_FIELD_FLAGS, <API key>);
me->SetFlag(UNIT_FIELD_FLAGS, <API key>);
me->SetDisplayId(11686);
}
void EnterCombat(Unit* /*who*/) override { }
void AttackStart(Unit* /*who*/) override { }
void MoveInLineOfSight(Unit* /*who*/) override { }
void StartEvent(Unit* target)
{
if (target && target->IsAlive())
{
Council[0] = instance->GetData64(<API key>);
Council[1] = instance->GetData64(<API key>);
Council[2] = instance->GetData64(DATA_LADY_MALANDE);
Council[3] = instance->GetData64(<API key>);
// Start the event for the Voice Trigger
if (Creature* VoiceTrigger = ObjectAccessor::GetCreature(*me, instance->GetData64(<API key>)))
{
CAST_AI(<API key>::<API key>, VoiceTrigger->AI())->LoadCouncilGUIDs();
CAST_AI(<API key>::<API key>, VoiceTrigger->AI())->EventStarted = true;
}
for (uint8 i = 0; i < 4; ++i)
{
if (Council[i])
{
if (Creature* member = ObjectAccessor::GetCreature(*me, Council[i]))
if (member->IsAlive())
member->AI()->AttackStart(target);
}
}
instance->SetBossState(<API key>, IN_PROGRESS);
EventBegun = true;
}
}
void UpdateAI(uint32 diff) override
{
if (!EventBegun)
return;
if (EndEventTimer)
{
if (EndEventTimer <= diff)
{
if (DeathCount > 3)
{
if (Creature* VoiceTrigger = ObjectAccessor::GetCreature(*me, instance->GetData64(<API key>)))
VoiceTrigger->DealDamage(VoiceTrigger, VoiceTrigger->GetHealth(), NULL, DIRECT_DAMAGE, <API key>, NULL, false);
instance->SetBossState(<API key>, DONE);
//me->SummonCreature(AKAMAID, 746.466980f, 304.394989f, 311.90208f, 6.272870f, <API key>, 0);
me->DealDamage(me, me->GetHealth(), NULL, DIRECT_DAMAGE, <API key>, NULL, false);
return;
}
Creature* pMember = (ObjectAccessor::GetCreature(*me, Council[DeathCount]));
if (pMember && pMember->IsAlive())
pMember->DealDamage(pMember, pMember->GetHealth(), NULL, DIRECT_DAMAGE, <API key>, NULL, false);
++DeathCount;
EndEventTimer = 1500;
} else EndEventTimer -= diff;
}
if (CheckTimer)
{
if (CheckTimer <= diff)
{
uint8 EvadeCheck = 0;
for (uint8 i = 0; i < 4; ++i)
{
if (Council[i])
{
if (Creature* Member = (ObjectAccessor::GetCreature((*me), Council[i])))
{
// This is the evade/death check.
if (Member->IsAlive() && !Member->GetVictim())
++EvadeCheck; //If all members evade, we reset so that players can properly reset the event
else if (!Member->IsAlive()) // If even one member dies, kill the rest, set instance data, and kill self.
{
EndEventTimer = 1000;
CheckTimer = 0;
return;
}
}
}
}
if (EvadeCheck > 3)
Reset();
CheckTimer = 2000;
} else CheckTimer -= diff;
}
}
};
};
struct <API key> : public ScriptedAI
{
<API key>(Creature* creature) : ScriptedAI(creature)
{
instance = creature->GetInstanceScript();
for (uint8 i = 0; i < 4; ++i)
Council[i] = 0;
LoadedGUIDs = false;
}
uint64 Council[4];
InstanceScript* instance;
bool LoadedGUIDs;
void EnterCombat(Unit* who) override
{
if (Creature* controller = ObjectAccessor::GetCreature(*me, instance->GetData64(<API key>)))
CAST_AI(<API key>::<API key>, controller->AI())->StartEvent(who);
DoZoneInCombat();
// Load GUIDs on first aggro because the Creature guids are only set as the creatures are created in world-
// this means that for each creature, it will attempt to LoadGUIDs even though some of the other creatures are
// not in world, and thus have no GUID set in the instance data system. Putting it in aggro ensures that all the creatures
// have been loaded and have their GUIDs set in the instance data system.
if (!LoadedGUIDs)
LoadGUIDs();
}
void EnterEvadeMode() override
{
for (uint8 i = 0; i < 4; ++i)
{
if (Unit* unit = ObjectAccessor::GetUnit(*me, Council[i]))
if (unit != me && unit->GetVictim())
{
AttackStart(unit->GetVictim());
return;
}
}
ScriptedAI::EnterEvadeMode();
}
void DamageTaken(Unit* done_by, uint32 &damage) override
{
if (done_by == me)
return;
damage /= 4;
for (uint8 i = 0; i < 4; ++i)
{
if (Creature* unit = ObjectAccessor::GetCreature(*me, Council[i]))
if (unit != me && damage < unit->GetHealth())
{
unit->ModifyHealth(-int32(damage));
unit-><API key>(damage);
}
}
}
void LoadGUIDs()
{
Council[0] = instance->GetData64(DATA_LADY_MALANDE);
Council[1] = instance->GetData64(<API key>);
Council[2] = instance->GetData64(<API key>);
Council[3] = instance->GetData64(<API key>);
LoadedGUIDs = true;
}
};
class <API key> : public CreatureScript
{
public:
<API key>() : CreatureScript("<API key>") { }
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<<API key>>(creature);
}
struct <API key> : public <API key>
{
<API key>(Creature* creature) : <API key>(creature) { }
uint32 ConsecrationTimer;
uint32 <API key>;
uint32 SealTimer;
uint32 AuraTimer;
uint32 BlessingTimer;
void Reset() override
{
ConsecrationTimer = 40000;
<API key> = 10000;
SealTimer = 40000;
AuraTimer = 90000;
BlessingTimer = 60000;
}
void KilledUnit(Unit* /*victim*/) override
{
Talk(SAY_GATH_SLAY);
}
void JustDied(Unit* /*killer*/) override
{
Talk(SAY_GATH_DEATH);
}
Unit* SelectCouncilMember()
{
Unit* unit = me;
uint32 member = 0; // He chooses Lady Malande most often
if (rand()%10 == 0) // But there is a chance he picks someone else.
member = urand(1, 3);
if (member != 2) // No need to create another pointer to us using Unit::GetUnit
unit = ObjectAccessor::GetUnit(*me, Council[member]);
return unit;
}
void CastAuraOnCouncil()
{
uint32 spellid = 0;
switch (urand(0, 1))
{
case 0: spellid = SPELL_DEVOTION_AURA; break;
case 1: spellid = <API key>; break;
}
for (uint8 i = 0; i < 4; ++i)
{
Unit* unit = ObjectAccessor::GetUnit(*me, Council[i]);
if (unit)
unit->CastSpell(unit, spellid, true, 0, 0, me->GetGUID());
}
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
if (BlessingTimer <= diff)
{
if (Unit* unit = SelectCouncilMember())
{
switch (urand(0, 1))
{
case 0:
DoCast(unit, <API key>);
break;
case 1:
DoCast(unit, <API key>);
break;
}
}
BlessingTimer = 60000;
} else BlessingTimer -= diff;
if (ConsecrationTimer <= diff)
{
DoCast(me, SPELL_CONSECRATION);
ConsecrationTimer = 40000;
} else ConsecrationTimer -= diff;
if (<API key> <= diff)
{
if (Unit* target = SelectTarget(<API key>, 0))
{
// is in ~10-40 yd range
if (me->IsInRange(target, 10.0f, 40.0f, false))
{
DoCast(target, <API key>);
<API key> = 20000;
}
}
} else <API key> -= diff;
if (SealTimer <= diff)
{
switch (urand(0, 1))
{
case 0: DoCast(me, <API key>); break;
case 1: DoCast(me, SPELL_SEAL_OF_BLOOD); break;
}
SealTimer = 40000;
} else SealTimer -= diff;
if (AuraTimer <= diff)
{
CastAuraOnCouncil();
AuraTimer = 90000;
} else AuraTimer -= diff;
<API key>();
}
};
};
class <API key> : public CreatureScript
{
public:
<API key>() : CreatureScript("<API key>") { }
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<<API key>>(creature);
}
struct <API key> : public <API key>
{
<API key>(Creature* creature) : <API key>(creature) { }
uint32 BlizzardTimer;
uint32 FlamestrikeTimer;
uint32 ArcaneBoltTimer;
uint32 DampenMagicTimer;
uint32 Cooldown;
uint32 <API key>;
void Reset() override
{
BlizzardTimer = urand(30, 91) * 1000;
FlamestrikeTimer = urand(30, 91) * 1000;
ArcaneBoltTimer = 10000;
DampenMagicTimer = 2000;
<API key> = 14000;
Cooldown = 0;
}
void KilledUnit(Unit* /*victim*/) override
{
Talk(SAY_ZERE_SLAY);
}
void JustDied(Unit* /*killer*/) override
{
Talk(SAY_ZERE_DEATH);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
if (Cooldown)
{
if (Cooldown <= diff) Cooldown = 0;
else
{
Cooldown -= diff;
return; // Don't cast any other spells if global cooldown is still ticking
}
}
if (DampenMagicTimer <= diff)
{
DoCast(me, SPELL_DAMPEN_MAGIC);
Cooldown = 1000;
DampenMagicTimer = 67200; // almost 1, 12 minutes
ArcaneBoltTimer += 1000; // Give the Mage some time to spellsteal Dampen.
} else DampenMagicTimer -= diff;
if (<API key> <= diff)
{
DoCastVictim(<API key>);
Cooldown = 1000;
<API key> = 14000;
} else <API key> -= diff;
if (ArcaneBoltTimer <= diff)
{
DoCastVictim(SPELL_ARCANE_BOLT);
ArcaneBoltTimer = 3000;
Cooldown = 2000;
} else ArcaneBoltTimer -= diff;
if (BlizzardTimer <= diff)
{
if (Unit* target = SelectTarget(<API key>, 0))
{
DoCast(target, SPELL_BLIZZARD);
BlizzardTimer = urand(45, 91) * 1000;
FlamestrikeTimer += 10000;
Cooldown = 1000;
}
} else BlizzardTimer -= diff;
if (FlamestrikeTimer <= diff)
{
if (Unit* target = SelectTarget(<API key>, 0))
{
DoCast(target, SPELL_FLAMESTRIKE);
FlamestrikeTimer = urand(55, 101) * 1000;
BlizzardTimer += 10000;
Cooldown = 2000;
}
} else FlamestrikeTimer -= diff;
}
};
};
class boss_lady_malande : public CreatureScript
{
public:
boss_lady_malande() : CreatureScript("boss_lady_malande") { }
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<boss_lady_malandeAI>(creature);
}
struct boss_lady_malandeAI : public <API key>
{
boss_lady_malandeAI(Creature* creature) : <API key>(creature) { }
uint32 EmpoweredSmiteTimer;
uint32 <API key>;
uint32 DivineWrathTimer;
uint32 <API key>;
void Reset() override
{
EmpoweredSmiteTimer = 38000;
<API key> = 20000;
DivineWrathTimer = 40000;
<API key> = 0;
}
void KilledUnit(Unit* /*victim*/) override
{
Talk(SAY_MALA_SLAY);
}
void JustDied(Unit* /*killer*/) override
{
Talk(SAY_MALA_DEATH);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
if (EmpoweredSmiteTimer <= diff)
{
if (Unit* target = SelectTarget(<API key>, 0))
{
DoCast(target, <API key>);
EmpoweredSmiteTimer = 38000;
}
} else EmpoweredSmiteTimer -= diff;
if (<API key> <= diff)
{
DoCast(me, <API key>);
<API key> = 60000;
} else <API key> -= diff;
if (DivineWrathTimer <= diff)
{
if (Unit* target = SelectTarget(<API key>, 0))
{
DoCast(target, SPELL_DIVINE_WRATH);
DivineWrathTimer = urand(40, 81) * 1000;
}
} else DivineWrathTimer -= diff;
if (<API key> <= diff)
{
DoCast(me, <API key>);
<API key> = 65000;
} else <API key> -= diff;
<API key>();
}
};
};
class <API key> : public CreatureScript
{
public:
<API key>() : CreatureScript("<API key>") { }
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<<API key>>(creature);
}
struct <API key> : public <API key>
{
<API key>(Creature* creature) : <API key>(creature) { }
uint64 EnvenomTargetGUID;
uint32 DeadlyPoisonTimer;
uint32 VanishTimer;
uint32 AppearEnvenomTimer;
bool HasVanished;
void Reset() override
{
EnvenomTargetGUID = 0;
DeadlyPoisonTimer = 20000;
VanishTimer = urand(60, 121) * 1000;
AppearEnvenomTimer = 150000;
HasVanished = false;
me->SetVisible(true);
me->RemoveFlag(UNIT_FIELD_FLAGS, <API key>);
}
void KilledUnit(Unit* /*victim*/) override
{
Talk(SAY_VERA_SLAY);
}
void JustDied(Unit* /*killer*/) override
{
Talk(SAY_VERA_DEATH);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
if (!HasVanished)
{
if (DeadlyPoisonTimer <= diff)
{
DoCastVictim(SPELL_DEADLY_POISON);
DeadlyPoisonTimer = urand(15, 46) * 1000;
} else DeadlyPoisonTimer -= diff;
if (AppearEnvenomTimer <= diff) // Cast Envenom. This is cast 4 seconds after Vanish is over
{
DoCastVictim(SPELL_ENVENOM);
AppearEnvenomTimer = 90000;
} else AppearEnvenomTimer -= diff;
if (VanishTimer <= diff) // Disappear and stop attacking, but follow a random unit
{
if (Unit* target = SelectTarget(<API key>, 0))
{
VanishTimer = 30000;
AppearEnvenomTimer= 28000;
HasVanished = true;
me->SetVisible(false);
me->SetFlag(UNIT_FIELD_FLAGS, <API key>);
DoResetThreat();
// Chase a unit. Check before <API key> prevents from attacking
me->AddThreat(target, 500000.0f);
me->GetMotionMaster()->MoveChase(target);
}
} else VanishTimer -= diff;
<API key>();
}
else
{
if (VanishTimer <= diff) // Become attackable and poison current target
{
Unit* target = me->GetVictim();
DoCast(target, SPELL_DEADLY_POISON);
me->RemoveFlag(UNIT_FIELD_FLAGS, <API key>);
DoResetThreat();
me->AddThreat(target, 3000.0f); // Make Veras attack his target for a while, he will cast Envenom 4 seconds after.
DeadlyPoisonTimer += 6000;
VanishTimer = 90000;
AppearEnvenomTimer = 4000;
HasVanished = false;
} else VanishTimer -= diff;
if (AppearEnvenomTimer <= diff) // Appear 2 seconds before becoming attackable (Shifting out of vanish)
{
me->GetMotionMaster()->Clear();
me->GetMotionMaster()->MoveChase(me->GetVictim());
me->SetVisible(true);
AppearEnvenomTimer = 6000;
} else AppearEnvenomTimer -= diff;
}
}
};
};
// <API key>
class <API key> : public SpellScriptLoader
{
public:
<API key>() : SpellScriptLoader("<API key>") { }
class <API key> : public AuraScript
{
PrepareAuraScript(<API key>);
bool Validate(SpellInfo const* /*spellInfo*/) override
{
return sSpellMgr->GetSpellInfo(<API key>);
}
void Trigger(AuraEffect* aurEff, DamageInfo & dmgInfo, uint32 & absorbAmount)
{
Unit* target = GetTarget();
if (dmgInfo.GetAttacker() == target)
return;
int32 bp = absorbAmount / 2;
target->CastCustomSpell(dmgInfo.GetAttacker(), <API key>, &bp, NULL, NULL, true, NULL, aurEff);
}
void Register() override
{
AfterEffectAbsorb += AuraEffectAbsorbFn(<API key>::Trigger, EFFECT_0);
}
};
AuraScript* GetAuraScript() const override
{
return new <API key>();
}
};
void <API key>()
{
new <API key>();
new <API key>();
new <API key>();
new boss_lady_malande();
new <API key>();
new <API key>();
new <API key>();
} |
#pragma once
#include <jumptargetdisplay.hh>
#include <qitemdelegate.h>
class JumpDisplayDelegate : public QItemDelegate
{
Q_OBJECT
public:
JumpDisplayDelegate(bool isForward, QObject *parent = 0);
void update(const emilpro::InstructionList_t &insnList, unsigned nVisibleInsns);
void paint(QPainter *painter, const <API key> &option,
const QModelIndex &index) const;
QSize sizeHint(const <API key> &option,
const QModelIndex &index) const;
private:
void drawLine(QPainter *painter, int x, int w, QRect *rect) const;
void drawLineStart(QPainter *painter, bool backward, int x, int w, QRect *rect) const;
void drawLineEnd(QPainter *painter, bool backward, int x, int w, QRect *rect) const;
unsigned int m_nLanes;
unsigned int m_laneWidth;
emilpro::JumpTargetDisplay m_jumpLanes;
}; |
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <ncurses.h>
#include <fcntl.h>
#include "estructuras.h"
#include "semaforos.h"
#define TRUE 1
#define FALSE 0
int creaSemaforos(MAPA * mapa) {
int i;
int error = FALSE;
char nombreSemaforoJug[] = "ComeCocosJug-0";
char nombreSemaforoFant[] = "ComeCocosFant-0";
eliminaSemaforos(mapa, TRUE);
for(i = 0; i < mapa->numJugadores; i++) {
if(NULL == (mapa->semaforo.jugador = calloc(mapa->numJugadores, sizeof(sem_t *)))) {
printf("Error de memoria (semaforo - jugador)\n");
error = TRUE;
}
}
for(i = 0; i < mapa->numFantasmas; i++) {
if(NULL == (mapa->semaforo.fantasma = calloc(mapa->numFantasmas, sizeof(sem_t *)))) {
printf("Error de memoria (semaforo - fantasma)\n");
error = TRUE;
}
}
for(i = 0; (error == FALSE) && (i < mapa->numJugadores); i++) {
if(SEM_FAILED == (mapa->semaforo.jugador[i] = sem_open(nombreSemaforoJug, O_CREAT, 0600, 0))) {
printf("Error en semaforo.jugador[%d]\n", i);
error = TRUE;
}
nombreSemaforoJug[13]++;
}
for(i = 0; (error == FALSE) && (i < mapa->numFantasmas); i++) {
if(SEM_FAILED == (mapa->semaforo.fantasma[i] = sem_open(nombreSemaforoFant, O_CREAT, 0600, 0))) {
printf("Error en semaforo.fantasma[%d]\n", i);
error = TRUE;
}
nombreSemaforoFant[14]++;
}
return error;
}
void eliminaSemaforos(MAPA * mapa, int primeraVez) {
int i;
char nombreSemaforoJug[] = "ComeCocosJug-0";
char nombreSemaforoFant[] = "ComeCocosFant-0";
for(i = 0; i < mapa->numJugadores; i++) {
if(primeraVez == FALSE) {
sem_close(mapa->semaforo.jugador[i]);
}
sem_unlink(nombreSemaforoJug);
nombreSemaforoJug[13]++;
}
for(i = 0; i < mapa->numFantasmas; i++) {
if(primeraVez == FALSE) {
sem_close(mapa->semaforo.fantasma[i]);
}
sem_unlink(nombreSemaforoFant);
nombreSemaforoFant[14]++;
}
for(i = 0; i < mapa->numJugadores; i++) {
if(NULL != mapa->semaforo.jugador) {
free(mapa->semaforo.jugador);
mapa->semaforo.jugador = NULL;
}
}
for(i = 0; i < mapa->numFantasmas; i++) {
if(NULL != mapa->semaforo.fantasma) {
free(mapa->semaforo.fantasma);
mapa->semaforo.fantasma = NULL;
}
}
}
void subirSemaforos(MAPA * mapa) {
int i;
for(i = 0; i < mapa->numJugadores; i++) {
sem_post(mapa->semaforo.jugador[i]);
}
for(i = 0; i < mapa->numFantasmas; i++) {
sem_post(mapa->semaforo.fantasma[i]);
}
} |
/* vim: set sw=8: -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
#ifndef SPELL_H
#define SPELL_H
/*
TODO stuff we need to do for this spell module:
eliminate all the stderr fprintfs
rip out the support for ICHAR_IS_CHAR
*/
#ifdef __cplusplus
extern "C"
{
#endif
typedef struct _sp_suggestions {
int count;
short *score;
unsigned short **word;
} sp_suggestions;
int SpellCheckInit(char *hashname);
void SpellCheckCleanup(void);
int SpellCheckNWord16(const unsigned short *word16, int length);
int <API key>(const unsigned short *word16, int length, sp_suggestions *sg);
#ifdef __cplusplus
}
#endif
#endif /* SPELL_H */ |
#ifndef <API key>
#define <API key> "$Id: regs-timer.h,v 1.2 2008/07/31 06:51:59 eyryu Exp $"
#define S3C_TIMERREG(x) (S3C_VA_TIMER + (x))
#define S3C_TIMERREG2(tmr,reg) S3C_TIMERREG((reg)+0x0c+((tmr)*0x0c))
#define S3C2410_TCFG0 S3C_TIMERREG(0x00)
#define S3C2410_TCFG1 S3C_TIMERREG(0x04)
#define S3C2410_TCON S3C_TIMERREG(0x08)
#define <API key> (255<<0)
#define <API key> (255<<8)
#define <API key> (8)
#define <API key> (255<<16)
#define <API key> (16)
#define <API key> (0<<16)
#define <API key> (1<<16)
#define <API key> (2<<16)
#define <API key> (3<<16)
#define <API key> (4<<16)
#define <API key> (15<<16)
#define <API key> (16)
#define <API key> (0<<12)
#define <API key> (1<<12)
#define <API key> (2<<12)
#define <API key> (3<<12)
#define <API key> (4<<12)
#define <API key> (15<<12)
#define <API key> (0<<8)
#define <API key> (1<<8)
#define <API key> (2<<8)
#define <API key> (3<<8)
#define <API key> (4<<8)
#define <API key> (15<<8)
#define <API key> (0<<4)
#define <API key> (1<<4)
#define <API key> (2<<4)
#define <API key> (3<<4)
#define <API key> (4<<4)
#define <API key> (15<<4)
#define <API key> (0<<0)
#define <API key> (1<<0)
#define <API key> (2<<0)
#define <API key> (3<<0)
#define <API key> (4<<0)
#define <API key> (15<<0)
/* for each timer, we have an count buffer, an compare buffer and
* an observation buffer
*/
/* WARNING - timer 4 has no buffer reg, and it's observation is at +4 */
#define S3C2410_TCNTB(tmr) S3C_TIMERREG2(tmr, 0x00)
#define S3C2410_TCMPB(tmr) S3C_TIMERREG2(tmr, 0x04)
#define S3C2410_TCNTO(tmr) S3C_TIMERREG2(tmr, (((tmr) == 4) ? 0x04 : 0x08))
#define <API key> (1<<22)
#define <API key> (1<<21)
#define <API key> (1<<20)
#define <API key> (1<<19)
#define <API key> (1<<18)
#define <API key> (1<<17)
#define <API key> (1<<16)
#define <API key> (1<<15)
#define <API key> (1<<14)
#define <API key> (1<<13)
#define <API key> (1<<12)
#define <API key> (1<<11)
#define <API key> (1<<10)
#define <API key> (1<<9)
#define <API key> (1<<8)
#define <API key> (1<<4)
#define <API key> (1<<3)
#define <API key> (1<<2)
#define <API key> (1<<1)
#define <API key> (1<<0)
#if defined(CONFIG_PLAT_S3C64XX) || defined(CONFIG_PLAT_S5PC1XX)
#define S3C_TCFG0 S3C_TIMERREG(0x00)
#define S3C_TCFG1 S3C_TIMERREG(0x04)
#define S3C_TCON S3C_TIMERREG(0x08)
#define S3C_TINT_CSTAT S3C_TIMERREG(0x44)
#define <API key> (255<<0)
#define <API key> (255<<8)
#define <API key> (8)
#define <API key> (0)
#define <API key> (255<<16)
#define <API key> (16)
#define S3C_TCFG1_MUX4_DIV1 (0<<16)
#define S3C_TCFG1_MUX4_DIV2 (1<<16)
#define S3C_TCFG1_MUX4_DIV4 (2<<16)
#define S3C_TCFG1_MUX4_DIV8 (3<<16)
#define <API key> (4<<16)
#define <API key> (5<<16)
#define S3C_TCFG1_MUX4_MASK (15<<16)
#define S3C_TCFG1_MUX3_DIV1 (0<<12)
#define S3C_TCFG1_MUX3_DIV2 (1<<12)
#define S3C_TCFG1_MUX3_DIV4 (2<<12)
#define S3C_TCFG1_MUX3_DIV8 (3<<12)
#define <API key> (4<<12)
#define <API key> (5<<12)
#define S3C_TCFG1_MUX3_MASK (15<<12)
#define S3C_TCFG1_MUX2_DIV1 (0<<8)
#define S3C_TCFG1_MUX2_DIV2 (1<<8)
#define S3C_TCFG1_MUX2_DIV4 (2<<8)
#define S3C_TCFG1_MUX2_DIV8 (3<<8)
#define <API key> (4<<8)
#define <API key> (5<<8)
#define S3C_TCFG1_MUX2_MASK (15<<8)
#define S3C_TCFG1_MUX1_DIV1 (0<<4)
#define S3C_TCFG1_MUX1_DIV2 (1<<4)
#define S3C_TCFG1_MUX1_DIV4 (2<<4)
#define S3C_TCFG1_MUX1_DIV8 (3<<4)
#define <API key> (4<<4)
#define <API key> (5<<4)
#define S3C_TCFG1_MUX1_MASK (15<<4)
#define S3C_TCFG1_MUX0_DIV1 (0<<0)
#define S3C_TCFG1_MUX0_DIV2 (1<<0)
#define S3C_TCFG1_MUX0_DIV4 (2<<0)
#define S3C_TCFG1_MUX0_DIV8 (3<<0)
#define <API key> (4<<0)
#define <API key> (5<<0)
#define S3C_TCFG1_MUX0_MASK (15<<0)
/* for each timer, we have an count buffer, an compare buffer and
* an observation buffer
*/
/* WARNING - timer 4 has no buffer reg, and it's observation is at +4 */
/* 32bit timer used */
#define S3C_TCNTB(tmr) S3C_TIMERREG2(tmr, 0x00)
#define S3C_TCMPB(tmr) S3C_TIMERREG2(tmr, 0x04)
#define S3C_TCNTO(tmr) S3C_TIMERREG2(tmr, (((tmr) == 4) ? 0x04 : 0x08))
#define S3C_TCON_T4RELOAD (1<<22)
#define <API key> (1<<21)
#define S3C_TCON_T4START (1<<20)
#define S3C_TCON_T3RELOAD (1<<19)
#define S3C_TCON_T3INVERT (1<<18)
#define <API key> (1<<17)
#define S3C_TCON_T3START (1<<16)
#define S3C_TCON_T2RELOAD (1<<15)
#define S3C_TCON_T2INVERT (1<<14)
#define <API key> (1<<13)
#define S3C_TCON_T2START (1<<12)
#define S3C_TCON_T1RELOAD (1<<11)
#define S3C_TCON_T1INVERT (1<<10)
#define <API key> (1<<9)
#define S3C_TCON_T1START (1<<8)
#define S3C_TCON_T0DEADZONE (1<<4)
#define S3C_TCON_T0RELOAD (1<<3)
#define S3C_TCON_T0INVERT (1<<2)
#define <API key> (1<<1)
#define S3C_TCON_T0START (1<<0)
/* Interrupt Control and Status register*/
#define <API key> (1<<9)
#define <API key> (1<<8)
#define <API key> (1<<7)
#define <API key> (1<<6)
#define <API key> (1<<5)
#define <API key> (1<<4)
#define <API key> (1<<3)
#define <API key> (1<<2)
#define <API key> (1<<1)
#define <API key> (1<<0)
#endif
#endif /* <API key> */ |
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/log2.h>
#include <linux/hrtimer.h>
#include <linux/reboot.h>
#include <linux/mfd/pm8xxx/core.h>
#include <linux/input/pmic8xxx-pwrkey.h>
#define PON_CNTL_1 0x1C
#define PON_CNTL_PULL_UP BIT(7)
#define <API key> (0x7)
#define REBOOT_PWRKEY_DUR 8000
/**
* struct pmic8xxx_pwrkey - pmic8xxx pwrkey information
* @key_press_irq: key press irq number
* @pdata: platform data
*/
struct pmic8xxx_pwrkey {
struct input_dev *pwr;
int key_press_irq;
int key_release_irq;
bool press;
const struct <API key> *pdata;
};
static s64 prev_time;
static bool btn_pressed = false;
static irqreturn_t pwrkey_press_irq(int irq, void *_pwrkey)
{
struct pmic8xxx_pwrkey *pwrkey = _pwrkey;
//printk("ngxson: pwr button press\n");
prev_time = ktime_to_ms(ktime_get());
btn_pressed = true;
if (pwrkey->press == true) {
pwrkey->press = false;
return IRQ_HANDLED;
} else {
pwrkey->press = true;
}
input_report_key(pwrkey->pwr, KEY_POWER, 1);
input_sync(pwrkey->pwr);
return IRQ_HANDLED;
}
static irqreturn_t pwrkey_release_irq(int irq, void *_pwrkey)
{
struct pmic8xxx_pwrkey *pwrkey = _pwrkey;
//printk("ngxson: pwr button release\n");
if(((ktime_to_ms(ktime_get()) - prev_time) > REBOOT_PWRKEY_DUR) && btn_pressed) {
printk("ngxson: reboot now\n");
machine_restart(NULL);
}
btn_pressed = false;
if (pwrkey->press == false) {
input_report_key(pwrkey->pwr, KEY_POWER, 1);
input_sync(pwrkey->pwr);
pwrkey->press = true;
} else {
pwrkey->press = false;
}
input_report_key(pwrkey->pwr, KEY_POWER, 0);
input_sync(pwrkey->pwr);
return IRQ_HANDLED;
}
#ifdef CONFIG_PM_SLEEP
static int <API key>(struct device *dev)
{
struct pmic8xxx_pwrkey *pwrkey = dev_get_drvdata(dev);
if (device_may_wakeup(dev)) {
enable_irq_wake(pwrkey->key_press_irq);
enable_irq_wake(pwrkey->key_release_irq);
}
return 0;
}
static int <API key>(struct device *dev)
{
struct pmic8xxx_pwrkey *pwrkey = dev_get_drvdata(dev);
if (device_may_wakeup(dev)) {
disable_irq_wake(pwrkey->key_press_irq);
disable_irq_wake(pwrkey->key_release_irq);
}
return 0;
}
#endif
static SIMPLE_DEV_PM_OPS(<API key>,
<API key>, <API key>);
static int __devinit <API key>(struct platform_device *pdev)
{
struct input_dev *pwr;
int key_release_irq = platform_get_irq(pdev, 0);
int key_press_irq = platform_get_irq(pdev, 1);
int err;
unsigned int delay;
u8 pon_cntl;
struct pmic8xxx_pwrkey *pwrkey;
const struct <API key> *pdata =
dev_get_platdata(&pdev->dev);
if (!pdata) {
dev_err(&pdev->dev, "power key platform data not supplied\n");
return -EINVAL;
}
/* Valid range of pwr key trigger delay is 1/64 sec to 2 seconds. */
if (pdata-><API key> > USEC_PER_SEC * 2 ||
pdata-><API key> < USEC_PER_SEC / 64) {
dev_err(&pdev->dev, "invalid power key trigger delay\n");
return -EINVAL;
}
pwrkey = kzalloc(sizeof(*pwrkey), GFP_KERNEL);
if (!pwrkey)
return -ENOMEM;
pwrkey->pdata = pdata;
pwr = <API key>();
if (!pwr) {
dev_dbg(&pdev->dev, "Can't allocate power button\n");
err = -ENOMEM;
goto free_pwrkey;
}
<API key>(pwr, EV_KEY, KEY_POWER);
pwr->name = "pmic8xxx_pwrkey";
pwr->phys = "pmic8xxx_pwrkey/input0";
pwr->dev.parent = &pdev->dev;
delay = (pdata-><API key> << 6) / USEC_PER_SEC;
delay = ilog2(delay);
err = pm8xxx_readb(pdev->dev.parent, PON_CNTL_1, &pon_cntl);
if (err < 0) {
dev_err(&pdev->dev, "failed reading PON_CNTL_1 err=%d\n", err);
goto free_input_dev;
}
pon_cntl &= ~<API key>;
pon_cntl |= (delay & <API key>);
if (pdata->pull_up)
pon_cntl |= PON_CNTL_PULL_UP;
else
pon_cntl &= ~PON_CNTL_PULL_UP;
err = pm8xxx_writeb(pdev->dev.parent, PON_CNTL_1, pon_cntl);
if (err < 0) {
dev_err(&pdev->dev, "failed writing PON_CNTL_1 err=%d\n", err);
goto free_input_dev;
}
err = <API key>(pwr);
if (err) {
dev_dbg(&pdev->dev, "Can't register power key: %d\n", err);
goto free_input_dev;
}
pwrkey->key_press_irq = key_press_irq;
pwrkey->key_release_irq = key_release_irq;
pwrkey->pwr = pwr;
<API key>(pdev, pwrkey);
/* check power key status during boot */
err = <API key>(pdev->dev.parent, key_press_irq);
if (err < 0) {
dev_err(&pdev->dev, "reading irq status failed\n");
goto unreg_input_dev;
}
pwrkey->press = !!err;
if (pwrkey->press) {
input_report_key(pwrkey->pwr, KEY_POWER, 1);
input_sync(pwrkey->pwr);
}
err = <API key>(key_press_irq, pwrkey_press_irq,
IRQF_TRIGGER_RISING, "<API key>", pwrkey);
if (err < 0) {
dev_dbg(&pdev->dev, "Can't get %d IRQ for pwrkey: %d\n",
key_press_irq, err);
goto unreg_input_dev;
}
err = <API key>(key_release_irq, pwrkey_release_irq,
IRQF_TRIGGER_RISING, "<API key>", pwrkey);
if (err < 0) {
dev_dbg(&pdev->dev, "Can't get %d IRQ for pwrkey: %d\n",
key_release_irq, err);
goto free_press_irq;
}
device_init_wakeup(&pdev->dev, pdata->wakeup);
return 0;
free_press_irq:
free_irq(key_press_irq, NULL);
unreg_input_dev:
<API key>(pdev, NULL);
<API key>(pwr);
pwr = NULL;
free_input_dev:
input_free_device(pwr);
free_pwrkey:
kfree(pwrkey);
return err;
}
static int __devexit <API key>(struct platform_device *pdev)
{
struct pmic8xxx_pwrkey *pwrkey = <API key>(pdev);
int key_release_irq = platform_get_irq(pdev, 0);
int key_press_irq = platform_get_irq(pdev, 1);
device_init_wakeup(&pdev->dev, 0);
free_irq(key_press_irq, pwrkey);
free_irq(key_release_irq, pwrkey);
<API key>(pwrkey->pwr);
<API key>(pdev, NULL);
kfree(pwrkey);
return 0;
}
static struct platform_driver <API key> = {
.probe = <API key>,
.remove = __devexit_p(<API key>),
.driver = {
.name = <API key>,
.owner = THIS_MODULE,
.pm = &<API key>,
},
};
static int __devinit <API key>(void)
{
return <API key>(&<API key>);
}
module_init(<API key>);
MODULE_ALIAS("platform:pmic8xxx_pwrkey");
MODULE_DESCRIPTION("PMIC8XXX Power Key driver");
MODULE_LICENSE("GPL v2");
MODULE_AUTHOR("Trilok Soni <tsoni@codeaurora.org>"); |
// \file vjournal.cc
// Conversion routines for vjournals (VCALENDAR, etc)
#include <opensync/opensync.h>
#include <opensync/opensync-time.h>
#include "vjournal.h"
#include "environment.h"
#include "trace.h"
#include <stdint.h>
#include <glib.h>
#include <strings.h>
#include <sstream>
using namespace Barry::Sync;
VJournalConverter::VJournalConverter()
: m_Data(0)
{
}
VJournalConverter::VJournalConverter(uint32_t newRecordId)
: m_Data(0),
m_RecordId(newRecordId)
{
}
VJournalConverter::~VJournalConverter()
{
if( m_Data )
g_free(m_Data);
}
// Transfers ownership of m_Data to the caller
char* VJournalConverter::ExtractData()
{
Trace trace("VMemoConverter::ExtractData");
char *ret = m_Data;
m_Data = 0;
return ret;
}
bool VJournalConverter::ParseData(const char *data)
{
Trace trace("VJournalConverter::ParseData");
try {
vTimeConverter vtc;
vJournal vjournal(vtc);
m_Memo = vjournal.ToBarry(data, m_RecordId);
}
catch( Barry::ConvertError &ce ) {
trace.logf("ERROR: vjournal:Barry::ConvertError exception: %s", ce.what());
m_last_errmsg = ce.what();
return false;
}
return true;
}
// Barry storage operator
void VJournalConverter::operator()(const Barry::Memo &rec)
{
Trace trace("VJournalConverter::operator()");
// Delete data if some already exists
if( m_Data ) {
g_free(m_Data);
m_Data = 0;
}
try {
vTimeConverter vtc;
vJournal vjournal(vtc);
vjournal.ToMemo(rec);
m_Data = vjournal.ExtractVJournal();
}
catch( Barry::ConvertError &ce ) {
trace.logf("ERROR: vjournal:Barry::ConvertError exception: %s", ce.what());
m_last_errmsg = ce.what();
}
}
// Barry builder operator
bool VJournalConverter::operator()(Barry::Memo &rec, Barry::Builder &)
{
Trace trace("VMemoConverter::builder operator()");
rec = m_Memo;
return true;
}
// Handles calling of the Barry::Controller to fetch a specific
// record, indicated by index (into the RecordStateTable).
// Returns a g_malloc'd string of data containing the vevent20
// data. It is the responsibility of the caller to free it.
// This is intended to be passed into the GetChanges() function.
char* VJournalConverter::GetRecordData(BarryEnvironment *env, unsigned int dbId,
Barry::RecordStateTable::IndexType index)
{
Trace trace("VMemoConverter::GetRecordData()");
using namespace Barry;
VJournalConverter memo2journal;
RecordParser<Memo, VJournalConverter> parser(memo2journal);
env->GetDesktop()->GetRecord(dbId, index, parser);
return memo2journal.ExtractData();
}
bool VJournalConverter::CommitRecordData(BarryEnvironment *env, unsigned int dbId,
Barry::RecordStateTable::IndexType StateIndex, uint32_t recordId,
const char *data, bool add, std::string &errmsg)
{
Trace trace("VJournalConverter::CommitRecordData()");
uint32_t newRecordId;
if( add ) {
// use given id if possible
if( recordId && !env->m_JournalSync.m_Table.GetIndex(recordId) ) {
// recordId is unique and non-zero
newRecordId = recordId;
}
else {
trace.log("Can't use recommended recordId, generating new one.");
newRecordId = env->m_JournalSync.m_Table.MakeNewRecordId();
}
}
else {
newRecordId = env->m_JournalSync.m_Table.StateMap[StateIndex].RecordId;
}
trace.logf("newRecordId: %u", newRecordId);
VJournalConverter convert(newRecordId);
if( !convert.ParseData(data) ) {
std::ostringstream oss;
oss << "unable to parse change data for new RecordId: "
<< newRecordId
<< " (" << convert.GetLastError() << ") data: " << data;
errmsg = oss.str();
trace.log(errmsg.c_str());
return false;
}
Barry::RecordBuilder<Barry::Memo, VJournalConverter> builder(convert);
if( add ) {
trace.log("adding record");
env->GetDesktop()->AddRecord(dbId, builder);
}
else {
trace.log("setting record");
env->GetDesktop()->SetRecord(dbId, StateIndex, builder);
trace.log("clearing dirty flag");
env->GetDesktop()->ClearDirty(dbId, StateIndex);
}
return true;
} |
<?php
defined('_JEXEC') or die('Restricted access');
if ($registerType == "communitybuilder" && file_exists(JPATH_ADMINISTRATOR . '/components/com_comprofiler/plugin.foundation.php'))
$passwordName = 'passwd';
else
$passwordName = 'password';
if ($params->get('showLoginForm'))
{
if ($params->get('forgotColor') == 'white')
$forgotColor = ' icon-white';
else
$forgotColor = '';
$forgotUsername = $helper->getForgotUser($params->get('register_type'), $params->get('showForgotUsername'), $forgotLink, $forgotUsernameLink, $forgotColor);
$forgotPassword = $helper->getForgotPassword($params->get('register_type'), $params->get('showForgotPassword'), $forgotLink, $forgotPasswordLink, $forgotColor);
?>
<div class="<API key> vertical <?php echo $joomlaSpan; ?>">
<form action="<?php echo JRoute::_('index.php', true, $params->get('usesecure')); ?>" method="post" id="sclogin-form<?php echo $module->id; ?>">
<fieldset class="input-block-level userdata">
<div class="control-group" id="<API key>">
<div class="controls input-block-level">
<div class="input-append input-block-level">
<input name="username" tabindex="1" id="sclogin-username" class="input-block-level" alt="username" type="text"
placeholder="<?php echo JText::_('<API key>'); ?>">
<?php echo $forgotUsername; ?>
</div>
</div>
</div>
<div class="control-group" id="<API key>">
<div class="controls input-block-level">
<div class="input-append input-block-level">
<input name="<?php echo $passwordName; ?>" tabindex="2" id="sclogin-passwd" class="input-block-level" alt="password" type="password"
placeholder="<?php echo JText::_('<API key>') ?>">
<?php echo $forgotPassword; ?>
</div>
</div>
</div>
<div class="control-group" id="<API key>">
<button type="submit" name="Submit" class="btn btn-primary <?php if (!$<API key>)
{
echo 'span12';
} ?>"><?php echo JText::_('MOD_SCLOGIN_LOGIN') ?></button>
<?php if ($<API key>) : ?>
<a class="btn" href="<?php echo $registerLink; ?>"><?php echo JText::_('<API key>'); ?></a>
<?php endif; ?>
</div>
<?php if (JPluginHelper::isEnabled('system', 'remember')) : ?>
<div class="control-group" id="<API key>">
<label for="sclogin-remember">
<input id="sclogin-remember" type="checkbox" name="remember" class="inputbox" value="yes" alt="Remember Me" />
<?php echo JText::_('JGLOBAL_REMEMBER_ME'); ?>
</label>
</div>
<?php endif; ?>
<?php
if ($registerType == "communitybuilder" && file_exists(JPATH_ADMINISTRATOR . '/components/com_comprofiler/plugin.foundation.php')) // Use Community Builder's login
{
include_once(JPATH_ADMINISTRATOR . '/components/com_comprofiler/plugin.foundation.php');
global $_CB_framework;
echo '<input type="hidden" name="option" value="com_comprofiler" />' . "\n";
echo '<input type="hidden" name="task" value="login" />' . "\n";
echo '<input type="hidden" name="op2" value="login" />' . "\n";
echo '<input type="hidden" name="lang" value="' . $_CB_framework->getCfg('lang') . '" />' . "\n";
echo '<input type="hidden" name="force_session" value="1" />' . "\n"; // makes sure to create joomla 1.0.11+12 session/bugfix
echo '<input type="hidden" name="return" value="B:' . base64_encode(cbSef(base64_decode($jLoginUrl))) . '"/>';
echo cbGetSpoofInputTag('login');
}
else
{
echo '<input type="hidden" name="option" value="com_users"/>';
echo '<input type="hidden" name="task" value="user.login"/>';
echo '<input type="hidden" name="return" value="' . $jLoginUrl . '"/>';
}
echo '<input type="hidden" name="mod_id" value="' . $module->id . '"/>';
echo JHTML::_('form.token'); ?>
</fieldset>
</form>
</div>
<?php
} |
# @param {String} word
# @return {Boolean}
def detect_capital_use(word)
if word.upcase == word || word.downcase == word
return true
elsif word[1..-1].downcase == word[1..-1]
return true
else
return false
end
end
p detect_capital_use("USA")
p detect_capital_use("UsA")
p detect_capital_use("usa")
p detect_capital_use("Usa") |
using Server.Items;
using System.Collections.Generic;
namespace Server.Mobiles
{
public class SBCobbler : SBInfo
{
private readonly List<GenericBuyInfo> m_BuyInfo = new InternalBuyInfo();
private readonly IShopSellInfo m_SellInfo = new InternalSellInfo();
public override IShopSellInfo SellInfo => m_SellInfo;
public override List<GenericBuyInfo> BuyInfo => m_BuyInfo;
public class InternalBuyInfo : List<GenericBuyInfo>
{
public InternalBuyInfo()
{
Add(new GenericBuyInfo(typeof(ThighBoots), 15, 20, 0x1711, Utility.RandomNeutralHue()));
Add(new GenericBuyInfo(typeof(Shoes), 8, 20, 0x170f, Utility.RandomNeutralHue()));
Add(new GenericBuyInfo(typeof(Boots), 10, 20, 0x170b, Utility.RandomNeutralHue()));
Add(new GenericBuyInfo(typeof(Sandals), 5, 20, 0x170d, Utility.RandomNeutralHue()));
}
}
public class InternalSellInfo : GenericSellInfo
{
public InternalSellInfo()
{
Add(typeof(Shoes), 4);
Add(typeof(Boots), 5);
Add(typeof(ThighBoots), 7);
Add(typeof(Sandals), 2);
}
}
}
} |
#ifndef <API key>
#define <API key>
#if ENABLE(INSPECTOR)
#include "<API key>.h"
#include <wtf/PassOwnPtr.h>
namespace JSC {
class JSGlobalObject;
}
namespace Inspector {
class <API key> final : public <API key> {
public:
<API key>(<API key>*, JSC::JSGlobalObject&);
virtual void <API key>(<API key>*, <API key>*) override;
virtual void <API key>(<API key>) override;
virtual JSC::VM* globalVM() override;
virtual InjectedScript <API key>(ErrorString*, const int* executionContextId) override;
// FIXME: JavaScript inspector does not yet have a console object to mute.
virtual void muteConsole() override { }
virtual void unmuteConsole() override { }
private:
std::unique_ptr<<API key>> <API key>;
RefPtr<<API key>> m_backendDispatcher;
JSC::JSGlobalObject& m_globalObject;
};
} // namespace Inspector
#endif // ENABLE(INSPECTOR)
#endif // !defined(<API key>) |
#main-leftarea { background:url("images/green/leftarea-bg.png"); }
#main-leftarea .topbg { background:url("images/green/leftarea-topbg.png") repeat-x; }
span#active-arrow { background:url("images/green/active-arrow.png") no-repeat; }
#main-leftarea #glow { background:url("images/black/glow-bg.png") no-repeat; } |
{template 'common/header-gw'}
<ol class="breadcrumb">
<li><a href="./?refresh"><i class="fa fa-home"></i></a></li>
<li><a href="{url 'system/welcome'}"></a></li>
<li class=""><a href="{url 'system/tools'}"></a></li>
<li class="active"><a href="{php echo url('system/tools');}"> BOM</a></li>
</ol>
<ul class="nav nav-tabs">
<li class="active"><a href="{php echo url('system/tools');}"> BOM</a></li>
</ul>
<div class="main">
{if $do == 'bom'}
<form action="" method="post" class="form-horizontal form">
<h5 class="page-header">BOM</h5>
<div class="form-group">
<label class="col-xs-12 col-sm-2 col-md-2 col-lg-1 control-label"></label>
<div class="col-sm-10">
<div class="help-block">utf-8bom, BOM, . </div>
<div class="help-block"><strong>: API, BOM. </strong></div>
<div class="help-block"><strong>: , BOM. </strong></div>
<div class="help-block"><strong>: Windows . </strong></div>
</div>
</div>
<div class="form-group">
<label class="col-xs-12 col-sm-2 col-md-2 col-lg-1 control-label"></label>
<div class="col-sm-10">
<div class="help-block">, , </div>
</div>
</div>
{if isset($bomtree)}
<div class="form-group">
<label class="col-xs-12 col-sm-2 col-md-2 col-lg-1 control-label"></label>
<div class="col-sm-10">
{if empty($bomtree)}
<div class="help-block"><strong>BOM</strong></div>
{else}
<div class="alert alert-info" style="line-height:20px;">
{loop $bomtree $line}
<div>{$line}</div>
{/loop}
</div>
{/if}
<div class="help-block">, , </div>
</div>
</div>
{/if}
<div class="form-group">
<div class="col-sm-offset-2 col-md-offset-2 col-lg-offset-1 col-xs-12 col-sm-10 col-md-10 col-lg-11">
<input name="submit" type="submit" value="BOM" class="btn btn-primary span3" />
{if isset($bomtree) && !empty($bomtree)}<input name="dispose" type="submit" class="btn btn-info " value="BOM"/>{/if}
<input type="hidden" name="token" value="{$_W['token']}" />
</div>
</div>
</form>
{/if}
</div>
{template 'common/footer-gw'} |
#include "xfs.h"
#include "xfs_fs.h"
#include "xfs_bit.h"
#include "xfs_log.h"
#include "xfs_inum.h"
#include "xfs_trans.h"
#include "xfs_sb.h"
#include "xfs_ag.h"
#include "xfs_dir.h"
#include "xfs_dir2.h"
#include "xfs_alloc.h"
#include "xfs_dmapi.h"
#include "xfs_quota.h"
#include "xfs_mount.h"
#include "xfs_bmap_btree.h"
#include "xfs_alloc_btree.h"
#include "xfs_ialloc_btree.h"
#include "xfs_attr_sf.h"
#include "xfs_dir_sf.h"
#include "xfs_dir2_sf.h"
#include "xfs_dinode.h"
#include "xfs_inode.h"
#include "xfs_ialloc.h"
#include "xfs_itable.h"
#include "xfs_btree.h"
#include "xfs_bmap.h"
#include "xfs_rtalloc.h"
#include "xfs_error.h"
#include "xfs_rw.h"
#include "xfs_acl.h"
#include "xfs_cap.h"
#include "xfs_mac.h"
#include "xfs_attr.h"
#include "xfs_buf_item.h"
#include "xfs_trans_priv.h"
#include "xfs_qm.h"
STATIC void <API key>(xfs_trans_t *);
/*
* Add the locked dquot to the transaction.
* The dquot must be locked, and it cannot be associated with any
* transaction.
*/
void
xfs_trans_dqjoin(
xfs_trans_t *tp,
xfs_dquot_t *dqp)
{
xfs_dq_logitem_t *lp;
ASSERT(! <API key>(tp, dqp));
ASSERT(XFS_DQ_IS_LOCKED(dqp));
ASSERT(<API key>(dqp));
lp = &dqp->q_logitem;
/*
* Get a log_item_desc to point at the new item.
*/
(void) xfs_trans_add_item(tp, (xfs_log_item_t*)(lp));
/*
* Initialize i_transp so we can later determine if this dquot is
* associated with this transaction.
*/
dqp->q_transp = tp;
}
/*
* This is called to mark the dquot as needing
* to be logged when the transaction is committed. The dquot must
* already be associated with the given transaction.
* Note that it marks the entire transaction as dirty. In the ordinary
* case, this gets called via xfs_trans_commit, after the transaction
* is already dirty. However, there's nothing stop this from getting
* called directly, as done by <API key>. Hence, the TRANS_DIRTY
* flag.
*/
void
xfs_trans_log_dquot(
xfs_trans_t *tp,
xfs_dquot_t *dqp)
{
xfs_log_item_desc_t *lidp;
ASSERT(<API key>(tp, dqp));
ASSERT(XFS_DQ_IS_LOCKED(dqp));
lidp = xfs_trans_find_item(tp, (xfs_log_item_t*)(&dqp->q_logitem));
ASSERT(lidp != NULL);
tp->t_flags |= XFS_TRANS_DIRTY;
lidp->lid_flags |= XFS_LID_DIRTY;
}
/*
* Carry forward whatever is left of the quota blk reservation to
* the spanky new transaction
*/
STATIC void
<API key>(
xfs_trans_t *otp,
xfs_trans_t *ntp)
{
xfs_dqtrx_t *oq, *nq;
int i,j;
xfs_dqtrx_t *oqa, *nqa;
if (!otp->t_dqinfo)
return;
<API key>(ntp);
oqa = otp->t_dqinfo->dqa_usrdquots;
nqa = ntp->t_dqinfo->dqa_usrdquots;
/*
* Because the quota blk reservation is carried forward,
* it is also necessary to carry forward the DQ_DIRTY flag.
*/
if(otp->t_flags & XFS_TRANS_DQ_DIRTY)
ntp->t_flags |= XFS_TRANS_DQ_DIRTY;
for (j = 0; j < 2; j++) {
for (i = 0; i < XFS_QM_TRANS_MAXDQS; i++) {
if (oqa[i].qt_dquot == NULL)
break;
oq = &oqa[i];
nq = &nqa[i];
nq->qt_dquot = oq->qt_dquot;
nq->qt_bcount_delta = nq->qt_icount_delta = 0;
nq->qt_rtbcount_delta = 0;
/*
* Transfer whatever is left of the reservations.
*/
nq->qt_blk_res = oq->qt_blk_res - oq->qt_blk_res_used;
oq->qt_blk_res = oq->qt_blk_res_used;
nq->qt_rtblk_res = oq->qt_rtblk_res -
oq->qt_rtblk_res_used;
oq->qt_rtblk_res = oq->qt_rtblk_res_used;
nq->qt_ino_res = oq->qt_ino_res - oq->qt_ino_res_used;
oq->qt_ino_res = oq->qt_ino_res_used;
}
oqa = otp->t_dqinfo->dqa_grpdquots;
nqa = ntp->t_dqinfo->dqa_grpdquots;
}
}
/*
* Wrap around mod_dquot to account for both user and group quotas.
*/
STATIC void
<API key>(
xfs_trans_t *tp,
xfs_inode_t *ip,
uint field,
long delta)
{
xfs_mount_t *mp;
ASSERT(tp);
mp = tp->t_mountp;
if (!XFS_IS_QUOTA_ON(mp) ||
ip->i_ino == mp->m_sb.sb_uquotino ||
ip->i_ino == mp->m_sb.sb_gquotino)
return;
if (tp->t_dqinfo == NULL)
<API key>(tp);
if (XFS_IS_UQUOTA_ON(mp) && ip->i_udquot)
(void) xfs_trans_mod_dquot(tp, ip->i_udquot, field, delta);
if (XFS_IS_OQUOTA_ON(mp) && ip->i_gdquot)
(void) xfs_trans_mod_dquot(tp, ip->i_gdquot, field, delta);
}
STATIC xfs_dqtrx_t *
xfs_trans_get_dqtrx(
xfs_trans_t *tp,
xfs_dquot_t *dqp)
{
int i;
xfs_dqtrx_t *qa;
for (i = 0; i < XFS_QM_TRANS_MAXDQS; i++) {
qa = <API key>(tp, dqp);
if (qa[i].qt_dquot == NULL ||
qa[i].qt_dquot == dqp) {
return (&qa[i]);
}
}
return (NULL);
}
/*
* Make the changes in the transaction structure.
* The moral equivalent to xfs_trans_mod_sb().
* We don't touch any fields in the dquot, so we don't care
* if it's locked or not (most of the time it won't be).
*/
void
xfs_trans_mod_dquot(
xfs_trans_t *tp,
xfs_dquot_t *dqp,
uint field,
long delta)
{
xfs_dqtrx_t *qtrx;
ASSERT(tp);
qtrx = NULL;
if (tp->t_dqinfo == NULL)
<API key>(tp);
/*
* Find either the first free slot or the slot that belongs
* to this dquot.
*/
qtrx = xfs_trans_get_dqtrx(tp, dqp);
ASSERT(qtrx);
if (qtrx->qt_dquot == NULL)
qtrx->qt_dquot = dqp;
switch (field) {
/*
* regular disk blk reservation
*/
case <API key>:
qtrx->qt_blk_res += (ulong)delta;
break;
/*
* inode reservation
*/
case <API key>:
qtrx->qt_ino_res += (ulong)delta;
break;
/*
* disk blocks used.
*/
case XFS_TRANS_DQ_BCOUNT:
if (qtrx->qt_blk_res && delta > 0) {
qtrx->qt_blk_res_used += (ulong)delta;
ASSERT(qtrx->qt_blk_res >= qtrx->qt_blk_res_used);
}
qtrx->qt_bcount_delta += delta;
break;
case <API key>:
qtrx->qt_delbcnt_delta += delta;
break;
/*
* Inode Count
*/
case XFS_TRANS_DQ_ICOUNT:
if (qtrx->qt_ino_res && delta > 0) {
qtrx->qt_ino_res_used += (ulong)delta;
ASSERT(qtrx->qt_ino_res >= qtrx->qt_ino_res_used);
}
qtrx->qt_icount_delta += delta;
break;
/*
* rtblk reservation
*/
case <API key>:
qtrx->qt_rtblk_res += (ulong)delta;
break;
/*
* rtblk count
*/
case <API key>:
if (qtrx->qt_rtblk_res && delta > 0) {
qtrx->qt_rtblk_res_used += (ulong)delta;
ASSERT(qtrx->qt_rtblk_res >= qtrx->qt_rtblk_res_used);
}
qtrx->qt_rtbcount_delta += delta;
break;
case <API key>:
qtrx->qt_delrtb_delta += delta;
break;
default:
ASSERT(0);
}
tp->t_flags |= XFS_TRANS_DQ_DIRTY;
}
/*
* Given an array of dqtrx structures, lock all the dquots associated
* and join them to the transaction, provided they have been modified.
* We know that the highest number of dquots (of one type - usr OR grp),
* involved in a transaction is 2 and that both usr and grp combined - 3.
* So, we don't attempt to make this very generic.
*/
STATIC void
<API key>(
xfs_trans_t *tp,
xfs_dqtrx_t *q)
{
ASSERT(q[0].qt_dquot != NULL);
if (q[1].qt_dquot == NULL) {
xfs_dqlock(q[0].qt_dquot);
xfs_trans_dqjoin(tp, q[0].qt_dquot);
} else {
ASSERT(XFS_QM_TRANS_MAXDQS == 2);
xfs_dqlock2(q[0].qt_dquot, q[1].qt_dquot);
xfs_trans_dqjoin(tp, q[0].qt_dquot);
xfs_trans_dqjoin(tp, q[1].qt_dquot);
}
}
/*
* Called by xfs_trans_commit() and similar in spirit to
* <API key>().
* Go thru all the dquots belonging to this transaction and modify the
* INCORE dquot to reflect the actual usages.
* Unreserve just the reservations done by this transaction.
* dquot is still left locked at exit.
*/
STATIC void
<API key>(
xfs_trans_t *tp)
{
int i, j;
xfs_dquot_t *dqp;
xfs_dqtrx_t *qtrx, *qa;
xfs_disk_dquot_t *d;
long totalbdelta;
long totalrtbdelta;
if (! (tp->t_flags & XFS_TRANS_DQ_DIRTY))
return;
ASSERT(tp->t_dqinfo);
qa = tp->t_dqinfo->dqa_usrdquots;
for (j = 0; j < 2; j++) {
if (qa[0].qt_dquot == NULL) {
qa = tp->t_dqinfo->dqa_grpdquots;
continue;
}
/*
* Lock all of the dquots and join them to the transaction.
*/
<API key>(tp, qa);
for (i = 0; i < XFS_QM_TRANS_MAXDQS; i++) {
qtrx = &qa[i];
/*
* The array of dquots is filled
* sequentially, not sparsely.
*/
if ((dqp = qtrx->qt_dquot) == NULL)
break;
ASSERT(XFS_DQ_IS_LOCKED(dqp));
ASSERT(<API key>(tp, dqp));
/*
* adjust the actual number of blocks used
*/
d = &dqp->q_core;
/*
* The issue here is - sometimes we don't make a blkquota
* reservation intentionally to be fair to users
* (when the amount is small). On the other hand,
* delayed allocs do make reservations, but that's
* outside of a transaction, so we have no
* idea how much was really reserved.
* So, here we've accumulated delayed allocation blks and
* non-delay blks. The assumption is that the
* delayed ones are always reserved (outside of a
* transaction), and the others may or may not have
* quota reservations.
*/
totalbdelta = qtrx->qt_bcount_delta +
qtrx->qt_delbcnt_delta;
totalrtbdelta = qtrx->qt_rtbcount_delta +
qtrx->qt_delrtb_delta;
#ifdef QUOTADEBUG
if (totalbdelta < 0)
ASSERT(be64_to_cpu(d->d_bcount) >=
(xfs_qcnt_t) -totalbdelta);
if (totalrtbdelta < 0)
ASSERT(be64_to_cpu(d->d_rtbcount) >=
(xfs_qcnt_t) -totalrtbdelta);
if (qtrx->qt_icount_delta < 0)
ASSERT(be64_to_cpu(d->d_icount) >=
(xfs_qcnt_t) -qtrx->qt_icount_delta);
#endif
if (totalbdelta)
be64_add(&d->d_bcount, (xfs_qcnt_t)totalbdelta);
if (qtrx->qt_icount_delta)
be64_add(&d->d_icount, (xfs_qcnt_t)qtrx->qt_icount_delta);
if (totalrtbdelta)
be64_add(&d->d_rtbcount, (xfs_qcnt_t)totalrtbdelta);
/*
* Get any default limits in use.
* Start/reset the timer(s) if needed.
*/
if (d->d_id) {
<API key>(tp->t_mountp, d);
<API key>(tp->t_mountp, d);
}
dqp->dq_flags |= XFS_DQ_DIRTY;
/*
* add this to the list of items to get logged
*/
xfs_trans_log_dquot(tp, dqp);
/*
* Take off what's left of the original reservation.
* In case of delayed allocations, there's no
* reservation that a transaction structure knows of.
*/
if (qtrx->qt_blk_res != 0) {
if (qtrx->qt_blk_res != qtrx->qt_blk_res_used) {
if (qtrx->qt_blk_res >
qtrx->qt_blk_res_used)
dqp->q_res_bcount -= (xfs_qcnt_t)
(qtrx->qt_blk_res -
qtrx->qt_blk_res_used);
else
dqp->q_res_bcount -= (xfs_qcnt_t)
(qtrx->qt_blk_res_used -
qtrx->qt_blk_res);
}
} else {
/*
* These blks were never reserved, either inside
* a transaction or outside one (in a delayed
* allocation). Also, this isn't always a
* negative number since we sometimes
* deliberately skip quota reservations.
*/
if (qtrx->qt_bcount_delta) {
dqp->q_res_bcount +=
(xfs_qcnt_t)qtrx->qt_bcount_delta;
}
}
/*
* Adjust the RT reservation.
*/
if (qtrx->qt_rtblk_res != 0) {
if (qtrx->qt_rtblk_res != qtrx->qt_rtblk_res_used) {
if (qtrx->qt_rtblk_res >
qtrx->qt_rtblk_res_used)
dqp->q_res_rtbcount -= (xfs_qcnt_t)
(qtrx->qt_rtblk_res -
qtrx->qt_rtblk_res_used);
else
dqp->q_res_rtbcount -= (xfs_qcnt_t)
(qtrx->qt_rtblk_res_used -
qtrx->qt_rtblk_res);
}
} else {
if (qtrx->qt_rtbcount_delta)
dqp->q_res_rtbcount +=
(xfs_qcnt_t)qtrx->qt_rtbcount_delta;
}
/*
* Adjust the inode reservation.
*/
if (qtrx->qt_ino_res != 0) {
ASSERT(qtrx->qt_ino_res >=
qtrx->qt_ino_res_used);
if (qtrx->qt_ino_res > qtrx->qt_ino_res_used)
dqp->q_res_icount -= (xfs_qcnt_t)
(qtrx->qt_ino_res -
qtrx->qt_ino_res_used);
} else {
if (qtrx->qt_icount_delta)
dqp->q_res_icount +=
(xfs_qcnt_t)qtrx->qt_icount_delta;
}
ASSERT(dqp->q_res_bcount >=
be64_to_cpu(dqp->q_core.d_bcount));
ASSERT(dqp->q_res_icount >=
be64_to_cpu(dqp->q_core.d_icount));
ASSERT(dqp->q_res_rtbcount >=
be64_to_cpu(dqp->q_core.d_rtbcount));
}
/*
* Do the group quotas next
*/
qa = tp->t_dqinfo->dqa_grpdquots;
}
}
/*
* Release the reservations, and adjust the dquots accordingly.
* This is called only when the transaction is being aborted. If by
* any chance we have done dquot modifications incore (ie. deltas) already,
* we simply throw those away, since that's the expected behavior
* when a transaction is curtailed without a commit.
*/
STATIC void
<API key>(
xfs_trans_t *tp)
{
int i, j;
xfs_dquot_t *dqp;
xfs_dqtrx_t *qtrx, *qa;
boolean_t locked;
if (!tp->t_dqinfo || !(tp->t_flags & XFS_TRANS_DQ_DIRTY))
return;
qa = tp->t_dqinfo->dqa_usrdquots;
for (j = 0; j < 2; j++) {
for (i = 0; i < XFS_QM_TRANS_MAXDQS; i++) {
qtrx = &qa[i];
/*
* We assume that the array of dquots is filled
* sequentially, not sparsely.
*/
if ((dqp = qtrx->qt_dquot) == NULL)
break;
/*
* Unreserve the original reservation. We don't care
* about the number of blocks used field, or deltas.
* Also we don't bother to zero the fields.
*/
locked = B_FALSE;
if (qtrx->qt_blk_res) {
xfs_dqlock(dqp);
locked = B_TRUE;
dqp->q_res_bcount -=
(xfs_qcnt_t)qtrx->qt_blk_res;
}
if (qtrx->qt_ino_res) {
if (!locked) {
xfs_dqlock(dqp);
locked = B_TRUE;
}
dqp->q_res_icount -=
(xfs_qcnt_t)qtrx->qt_ino_res;
}
if (qtrx->qt_rtblk_res) {
if (!locked) {
xfs_dqlock(dqp);
locked = B_TRUE;
}
dqp->q_res_rtbcount -=
(xfs_qcnt_t)qtrx->qt_rtblk_res;
}
if (locked)
xfs_dqunlock(dqp);
}
qa = tp->t_dqinfo->dqa_grpdquots;
}
}
STATIC int
xfs_quota_error(uint flags)
{
if (flags & XFS_QMOPT_ENOSPC)
return ENOSPC;
return EDQUOT;
}
/*
* This reserves disk blocks and inodes against a dquot.
* Flags indicate if the dquot is to be locked here and also
* if the blk reservation is for RT or regular blocks.
* Sending in XFS_QMOPT_FORCE_RES flag skips the quota check.
*/
STATIC int
xfs_trans_dqresv(
xfs_trans_t *tp,
xfs_mount_t *mp,
xfs_dquot_t *dqp,
long nblks,
long ninos,
uint flags)
{
int error;
xfs_qcnt_t hardlimit;
xfs_qcnt_t softlimit;
time_t timer;
xfs_qwarncnt_t warns;
xfs_qwarncnt_t warnlimit;
xfs_qcnt_t count;
xfs_qcnt_t *resbcountp;
xfs_quotainfo_t *q = mp->m_quotainfo;
if (! (flags & XFS_QMOPT_DQLOCK)) {
xfs_dqlock(dqp);
}
ASSERT(XFS_DQ_IS_LOCKED(dqp));
if (flags & <API key>) {
hardlimit = be64_to_cpu(dqp->q_core.d_blk_hardlimit);
if (!hardlimit)
hardlimit = q->qi_bhardlimit;
softlimit = be64_to_cpu(dqp->q_core.d_blk_softlimit);
if (!softlimit)
softlimit = q->qi_bsoftlimit;
timer = be32_to_cpu(dqp->q_core.d_btimer);
warns = be16_to_cpu(dqp->q_core.d_bwarns);
warnlimit = XFS_QI_BWARNLIMIT(dqp->q_mount);
resbcountp = &dqp->q_res_bcount;
} else {
ASSERT(flags & <API key>);
hardlimit = be64_to_cpu(dqp->q_core.d_rtb_hardlimit);
if (!hardlimit)
hardlimit = q->qi_rtbhardlimit;
softlimit = be64_to_cpu(dqp->q_core.d_rtb_softlimit);
if (!softlimit)
softlimit = q->qi_rtbsoftlimit;
timer = be32_to_cpu(dqp->q_core.d_rtbtimer);
warns = be16_to_cpu(dqp->q_core.d_rtbwarns);
warnlimit = XFS_QI_RTBWARNLIMIT(dqp->q_mount);
resbcountp = &dqp->q_res_rtbcount;
}
error = 0;
if ((flags & XFS_QMOPT_FORCE_RES) == 0 &&
dqp->q_core.d_id &&
<API key>(dqp->q_mount)) {
#ifdef QUOTADEBUG
cmn_err(CE_DEBUG, "BLK Res: nblks=%ld + resbcount=%Ld"
" > hardlimit=%Ld?", nblks, *resbcountp, hardlimit);
#endif
if (nblks > 0) {
/*
* dquot is locked already. See if we'd go over the
* hardlimit or exceed the timelimit if we allocate
* nblks.
*/
if (hardlimit > 0ULL &&
(hardlimit <= nblks + *resbcountp)) {
error = xfs_quota_error(flags);
goto error_return;
}
if (softlimit > 0ULL &&
(softlimit <= nblks + *resbcountp)) {
if ((timer != 0 && get_seconds() > timer) ||
(warns != 0 && warns >= warnlimit)) {
error = xfs_quota_error(flags);
goto error_return;
}
}
}
if (ninos > 0) {
count = be64_to_cpu(dqp->q_core.d_icount);
timer = be32_to_cpu(dqp->q_core.d_itimer);
warns = be16_to_cpu(dqp->q_core.d_iwarns);
warnlimit = XFS_QI_IWARNLIMIT(dqp->q_mount);
hardlimit = be64_to_cpu(dqp->q_core.d_ino_hardlimit);
if (!hardlimit)
hardlimit = q->qi_ihardlimit;
softlimit = be64_to_cpu(dqp->q_core.d_ino_softlimit);
if (!softlimit)
softlimit = q->qi_isoftlimit;
if (hardlimit > 0ULL && count >= hardlimit) {
error = xfs_quota_error(flags);
goto error_return;
} else if (softlimit > 0ULL && count >= softlimit) {
if ((timer != 0 && get_seconds() > timer) ||
(warns != 0 && warns >= warnlimit)) {
error = xfs_quota_error(flags);
goto error_return;
}
}
}
}
/*
* Change the reservation, but not the actual usage.
* Note that q_res_bcount = q_core.d_bcount + resv
*/
(*resbcountp) += (xfs_qcnt_t)nblks;
if (ninos != 0)
dqp->q_res_icount += (xfs_qcnt_t)ninos;
/*
* note the reservation amt in the trans struct too,
* so that the transaction knows how much was reserved by
* it against this particular dquot.
* We don't do this when we are reserving for a delayed allocation,
* because we don't have the luxury of a transaction envelope then.
*/
if (tp) {
ASSERT(tp->t_dqinfo);
ASSERT(flags & <API key>);
if (nblks != 0)
xfs_trans_mod_dquot(tp, dqp,
flags & <API key>,
nblks);
if (ninos != 0)
xfs_trans_mod_dquot(tp, dqp,
<API key>,
ninos);
}
ASSERT(dqp->q_res_bcount >= be64_to_cpu(dqp->q_core.d_bcount));
ASSERT(dqp->q_res_rtbcount >= be64_to_cpu(dqp->q_core.d_rtbcount));
ASSERT(dqp->q_res_icount >= be64_to_cpu(dqp->q_core.d_icount));
error_return:
if (! (flags & XFS_QMOPT_DQLOCK)) {
xfs_dqunlock(dqp);
}
return (error);
}
/*
* Given dquot(s), make disk block and/or inode reservations against them.
* The fact that this does the reservation against both the usr and
* grp/prj quotas is important, because this follows a both-or-nothing
* approach.
*
* flags = XFS_QMOPT_DQLOCK indicate if dquot(s) need to be locked.
* XFS_QMOPT_FORCE_RES evades limit enforcement. Used by chown.
* XFS_QMOPT_ENOSPC returns ENOSPC not EDQUOT. Used by pquota.
* <API key> reserves regular disk blocks
* <API key> reserves realtime disk blocks
* dquots are unlocked on return, if they were not locked by caller.
*/
int
<API key>(
xfs_trans_t *tp,
xfs_mount_t *mp,
xfs_dquot_t *udqp,
xfs_dquot_t *gdqp,
long nblks,
long ninos,
uint flags)
{
int resvd = 0, error;
if (!XFS_IS_QUOTA_ON(mp))
return 0;
if (tp && tp->t_dqinfo == NULL)
<API key>(tp);
ASSERT(flags & <API key>);
if (udqp) {
error = xfs_trans_dqresv(tp, mp, udqp, nblks, ninos,
(flags & ~XFS_QMOPT_ENOSPC));
if (error)
return error;
resvd = 1;
}
if (gdqp) {
error = xfs_trans_dqresv(tp, mp, gdqp, nblks, ninos, flags);
if (error) {
/*
* can't do it, so backout previous reservation
*/
if (resvd) {
flags |= XFS_QMOPT_FORCE_RES;
xfs_trans_dqresv(tp, mp, udqp,
-nblks, -ninos, flags);
}
return error;
}
}
/*
* Didn't change anything critical, so, no need to log
*/
return 0;
}
/*
* Lock the dquot and change the reservation if we can.
* This doesn't change the actual usage, just the reservation.
* The inode sent in is locked.
*/
STATIC int
<API key>(
xfs_trans_t *tp,
xfs_mount_t *mp,
xfs_inode_t *ip,
long nblks,
long ninos,
uint flags)
{
int error;
if (!XFS_IS_QUOTA_ON(mp))
return 0;
if (XFS_IS_PQUOTA_ON(mp))
flags |= XFS_QMOPT_ENOSPC;
ASSERT(ip->i_ino != mp->m_sb.sb_uquotino);
ASSERT(ip->i_ino != mp->m_sb.sb_gquotino);
ASSERT(<API key>(ip));
ASSERT(<API key>(ip->i_mount));
ASSERT((flags & ~(XFS_QMOPT_FORCE_RES | XFS_QMOPT_ENOSPC)) ==
<API key> ||
(flags & ~(XFS_QMOPT_FORCE_RES | XFS_QMOPT_ENOSPC)) ==
<API key>);
/*
* Reserve nblks against these dquots, with trans as the mediator.
*/
error = <API key>(tp, mp,
ip->i_udquot, ip->i_gdquot,
nblks, ninos,
flags);
return error;
}
/*
* This routine is called to allocate a quotaoff log item.
*/
xfs_qoff_logitem_t *
<API key>(
xfs_trans_t *tp,
xfs_qoff_logitem_t *startqoff,
uint flags)
{
xfs_qoff_logitem_t *q;
ASSERT(tp != NULL);
q = <API key>(tp->t_mountp, startqoff, flags);
ASSERT(q != NULL);
/*
* Get a log_item_desc to point at the new item.
*/
(void) xfs_trans_add_item(tp, (xfs_log_item_t*)q);
return (q);
}
/*
* This is called to mark the quotaoff logitem as needing
* to be logged when the transaction is committed. The logitem must
* already be associated with the given transaction.
*/
void
<API key>(
xfs_trans_t *tp,
xfs_qoff_logitem_t *qlp)
{
xfs_log_item_desc_t *lidp;
lidp = xfs_trans_find_item(tp, (xfs_log_item_t *)qlp);
ASSERT(lidp != NULL);
tp->t_flags |= XFS_TRANS_DIRTY;
lidp->lid_flags |= XFS_LID_DIRTY;
}
STATIC void
<API key>(
xfs_trans_t *tp)
{
(tp)->t_dqinfo = kmem_zone_zalloc(xfs_Gqm->qm_dqtrxzone, KM_SLEEP);
}
STATIC void
<API key>(
xfs_trans_t *tp)
{
if (!tp->t_dqinfo)
return;
kmem_zone_free(xfs_Gqm->qm_dqtrxzone, (tp)->t_dqinfo);
(tp)->t_dqinfo = NULL;
}
xfs_dqtrxops_t xfs_trans_dquot_ops = {
.qo_dup_dqinfo = <API key>,
.qo_free_dqinfo = <API key>,
.qo_mod_dquot_byino = <API key>,
.<API key> = <API key>,
.<API key> = <API key>,
.<API key> = <API key>,
.<API key> = <API key>,
}; |
#ifndef _AML_AUDIN_REGS_H
#define _AML_AUDIN_REGS_H
#define AUDIN_SPDIF_MODE 0x2800
#define <API key> 0x2801
#define <API key> 0x2802
#define <API key> 0x2803
#define AUDIN_SPDIF_MISC 0x2804
#define <API key> 0x2805
#define AUDIN_SPDIF_END 0x280f
#define AUDIN_I2SIN_CTRL 0x2810
#define AUDIN_SOURCE_SEL 0x2811
#define AUDIN_DECODE_FORMAT 0x2812
#define <API key> 0x2813
#define <API key> 0x2814
#define <API key> 0x2815
#define <API key> 0x2816
#define <API key> 0x2817
#define <API key> 0x2818
#define <API key> 0x2819
#define AUDIN_FIFO0_START 0x2820
#define AUDIN_FIFO0_END 0x2821
#define AUDIN_FIFO0_PTR 0x2822
#define AUDIN_FIFO0_INTR 0x2823
#define AUDIN_FIFO0_RDPTR 0x2824
#define AUDIN_FIFO0_CTRL 0x2825
#define AUDIN_FIFO0_CTRL1 0x2826
#define AUDIN_FIFO0_LVL0 0x2827
#define AUDIN_FIFO0_LVL1 0x2828
#define AUDIN_FIFO0_LVL2 0x2829
#define AUDIN_FIFO0_REQID 0x2830
#define AUDIN_FIFO0_WRAP 0x2831
#define AUDIN_FIFO1_START 0x2833
#define AUDIN_FIFO1_END 0x2834
#define AUDIN_FIFO1_PTR 0x2835
#define AUDIN_FIFO1_INTR 0x2836
#define AUDIN_FIFO1_RDPTR 0x2837
#define AUDIN_FIFO1_CTRL 0x2838
#define AUDIN_FIFO1_CTRL1 0x2839
#define AUDIN_FIFO1_LVL0 0x2840
#define AUDIN_FIFO1_LVL1 0x2841
#define AUDIN_FIFO1_LVL2 0x2842
#define AUDIN_FIFO1_REQID 0x2843
#define AUDIN_FIFO1_WRAP 0x2844
#define AUDIN_FIFO2_START 0x2845
#define AUDIN_FIFO2_END 0x2846
#define AUDIN_FIFO2_PTR 0x2847
#define AUDIN_FIFO2_INTR 0x2848
#define AUDIN_FIFO2_RDPTR 0x2849
#define AUDIN_FIFO2_CTRL 0x284a
#define AUDIN_FIFO2_CTRL1 0x284b
#define AUDIN_FIFO2_LVL0 0x284c
#define AUDIN_FIFO2_LVL1 0x284d
#define AUDIN_FIFO2_LVL2 0x284e
#define AUDIN_FIFO2_REQID 0x284f
#define AUDIN_FIFO2_WRAP 0x2850
#define AUDIN_INT_CTRL 0x2851
#define AUDIN_FIFO_INT 0x2852
#define PCMIN_CTRL0 0x2860
#define PCMIN_CTRL1 0x2861
#define PCMIN1_CTRL0 0x2862
#define PCMIN1_CTRL1 0x2863
#define PCMOUT_CTRL0 0x2870
#define PCMOUT_CTRL1 0x2871
#define PCMOUT_CTRL2 0x2872
#define PCMOUT_CTRL3 0x2873
#define PCMOUT1_CTRL0 0x2874
#define PCMOUT1_CTRL1 0x2875
#define PCMOUT1_CTRL2 0x2876
#define PCMOUT1_CTRL3 0x2877
#define AUDOUT_CTRL 0x2880
#define AUDOUT_CTRL1 0x2881
#define AUDOUT_BUF0_STA 0x2882
#define AUDOUT_BUF0_EDA 0x2883
#define AUDOUT_BUF0_WPTR 0x2884
#define AUDOUT_BUF1_STA 0x2885
#define AUDOUT_BUF1_EDA 0x2886
#define AUDOUT_BUF1_WPTR 0x2887
#define AUDOUT_FIFO_RPTR 0x2888
#define AUDOUT_INTR_PTR 0x2889
#define AUDOUT_FIFO_STS 0x288a
#define AUDOUT1_CTRL 0x2890
#define AUDOUT1_CTRL1 0x2891
#define AUDOUT1_BUF0_STA 0x2892
#define AUDOUT1_BUF0_EDA 0x2893
#define AUDOUT1_BUF0_WPTR 0x2894
#define AUDOUT1_BUF1_STA 0x2895
#define AUDOUT1_BUF1_EDA 0x2896
#define AUDOUT1_BUF1_WPTR 0x2897
#define AUDOUT1_FIFO_RPTR 0x2898
#define AUDOUT1_INTR_PTR 0x2899
#define AUDOUT1_FIFO_STS 0x289a
#define <API key> 0x28a0
#define <API key> 0x28a1
#define <API key> 0x28a2
#define <API key> 0x28a3
#define <API key> 0x28a4
#define <API key> 0x28a5
#define <API key> 0x28a6
#define AUDIN_FIFO0_PIO_STS 0x28b0
#define AUDIN_FIFO0_PIO_RDL 0x28b1
#define AUDIN_FIFO0_PIO_RDH 0x28b2
#define AUDIN_FIFO1_PIO_STS 0x28b3
#define AUDIN_FIFO1_PIO_RDL 0x28b4
#define AUDIN_FIFO1_PIO_RDH 0x28b5
#define AUDIN_FIFO2_PIO_STS 0x28b6
#define AUDIN_FIFO2_PIO_RDL 0x28b7
#define AUDIN_FIFO2_PIO_RDH 0x28b8
#define AUDOUT_FIFO_PIO_STS 0x28b9
#define AUDOUT_FIFO_PIO_WRL 0x28ba
#define AUDOUT_FIFO_PIO_WRH 0x28bb
#define <API key> 0x28bc
#define <API key> 0x28bd
#define <API key> 0x28be
#define AUD_RESAMPLE_CTRL0 0x28bf
#define AUD_RESAMPLE_CTRL1 0x28c0
#define AUD_RESAMPLE_STATUS 0x28c1
#define AUDIN_ADDR_END 0x28c2
/* I2S CLK and LRCLK direction. 0 : input 1 : output. */
#define I2SIN_DIR 0
/* I2S clk selection : 0 : from pad input. 1 : from AIU. */
#define I2SIN_CLK_SEL 1
#define I2SIN_LRCLK_SEL 2
#define I2SIN_POS_SYNC 3
#define I2SIN_LRCLK_SKEW 4
#define I2SIN_LRCLK_INVT 7
/* 9:8 : 0 16 bit. 1 : 18 bits 2 : 20 bits 3 : 24bits. */
#define I2SIN_SIZE 8
#define I2SIN_CHAN_EN 10
#define I2SIN_EN 15
#define AUDIN_FIFO0_EN 0
/* write 1 to load address to AUDIN_FIFO0. */
#define AUDIN_FIFO0_LOAD 2
#define AUDIN_FIFO0_DIN_SEL 3
/* 0 spdifIN */
/* 1 i2Sin */
/* 2 PCMIN */
/* 3 HDMI in */
/* 4 DEMODULATOR IN */
/* 10:8 data endian control. */
#define AUDIN_FIFO0_ENDIAN 8
/* 14:11 channel number. */
#define AUDIN_FIFO0_CHAN 11
/* urgent request enable. */
#define AUDIN_FIFO0_UG 15
#define AUDIN_FIFO1_EN 0
/* write 1 to load address to AUDIN_FIFO0. */
#define AUDIN_FIFO1_LOAD 2
#define AUDIN_FIFO1_DIN_SEL 3
/* 0 spdifIN */
/* 1 i2Sin */
/* 2 PCMIN */
/* 3 HDMI in */
/* 4 DEMODULATOR IN */
/* 10:8 data endian control. */
#define AUDIN_FIFO1_ENDIAN 8
/* 14:11 channel number. */
#define AUDIN_FIFO1_CHAN 11
/* urgent request enable. */
#define AUDIN_FIFO1_UG 15
#endif /* _AML_AUDIN_REGS_H */ |
<?php die("Access Denied"); ?>#x#s:21:"s:13:"i:1394739873;";"; |
#include "game/game_mode.h"
#include <assert.h>
#include <SDL.h>
#include "game/game_time.h"
#include "graphic/video.h"
#include "interface/interface.h"
#include "map/camera.h"
#include "map/map.h"
#include "map/maps_list.h"
#include "map/water.h"
#include "particles/particle.h"
#include "tool/math_tools.h"
#include "tool/resource_manager.h"
#include "tool/string_tools.h"
#define GO_UP_TIME 1 // min
#define GO_UP_STEP 15 // pixels
#define <API key> 30 // seconds
#define <API key> 30 // amplitude
#define MS_BETWEEN_SHIFTS 20
#define PATTERN_HEIGHT 64
#define WAVE_INC 5
#define WAVE_HEIGHT_A 5
#define WAVE_HEIGHT_B 8
static const Double DEGREE = TWO_PI/360;
Water::Water()
: type_color(NULL)
, height_mvt(0)
, shift1(0)
, water_height(0)
, time_raise(0)
, water_type("no")
, <API key>(0)
, next_wave_shift(0)
{
memset(height, 0, sizeof(height));
}
Water::~Water()
{
if (type_color)
delete type_color;
}
/*
* Water consists of 1) water.png texture, which is the actual wave and
* 2) water_bottom.png, which is water below the wave. Composing the water in
* this way is done because of optimization purposes.
*
* The water consists of three waves, which are drawn using SIN functions in
* different phases.
*
* The water is drawn in patterns of 180 x 128 block. The value 180 comes
* from SIN(2x) period.
*
* The pattern surface is rendered using water.png and SIN functions, while
* the bottom is just painted with a transparent color.
*/
void Water::Init()
{
ASSERT(water_type != "no");
std::string image = "gfx/";
image += water_type;
Profile *res = GetResourceManager().LoadXMLProfile("graphism.xml", false);
type_color = new Color(GetResourceManager().LoadColor(res, "water_colors/" + water_type));
#ifdef HAVE_HANDHELD
surface = GetResourceManager().LoadImage(res, image, false);
pattern.NewSurface(Point2i(PATTERN_WIDTH, PATTERN_HEIGHT),
SDL_SWSURFACE|SDL_SRCCOLORKEY, false);
pattern.SetColorKey(SDL_SRCCOLORKEY, 0);
#else
surface = GetResourceManager().LoadImage(res, image, true);
pattern.NewSurface(Point2i(PATTERN_WIDTH, PATTERN_HEIGHT),
SDL_SWSURFACE|SDL_SRCALPHA, true);
#endif
shift1 = 0;
next_wave_shift = 0;
GetResourceManager().UnLoadXMLProfile(res);
}
void Water::Reset()
{
water_type = ActiveMap()->GetWaterType();
if (type_color)
delete type_color;
type_color = NULL;
if (!IsActive())
return;
Init();
water_height = <API key>;
time_raise = 1000 * GameMode::GetInstance()-><API key>;
Refresh(); // Calculate first height position
}
void Water::Free()
{
if (!IsActive()) {
return;
}
surface.Free();
pattern.Free();
}
void Water::Refresh()
{
if (!IsActive()) {
return;
}
height_mvt = 0;
uint now = Time::GetInstance()->Read();
if (next_wave_shift <= now) {
shift1 += 2*DEGREE;
next_wave_shift += MS_BETWEEN_SHIFTS;
}
// Height Calculation:
if (time_raise < now) {
<API key> = now;
if (time_raise + <API key> * 1000 > now) {
static const Double A = GO_UP_STEP/(<API key>*(Double)1000.0);
uint dt = now - time_raise;
height_mvt = GO_UP_STEP + (int)((GO_UP_STEP *
sin(((dt* (<API key>-(Double)0.25))
/ (<API key>*(Double)1000.0))*TWO_PI)
)/(A*dt+ONE));
} else {
time_raise += GO_UP_TIME * 60 * 1000;
water_height += GO_UP_STEP;
}
}
<API key>();
}
void Water::<API key>()
{
Double angle1 = -shift1;
Double angle2 = shift1;
for (uint x = 0; x < PATTERN_WIDTH; x++) {
// TODO: delete the first dimension of wave_height (now unused)
height[x] = static_cast<int>(sin(angle1)*WAVE_HEIGHT_A + sin(angle2)*WAVE_HEIGHT_B);
angle1 += 2*DEGREE;
angle2 += 4*DEGREE;
}
}
void Water::<API key>()
{
pattern.Fill(0x00000000);
/* Locks on SDL_Surface must be taken when accessing pixel member */
surface.Lock();
pattern.Lock();
/* Copy directly the surface image into the pattern image. This doesn't use
* blit in order to save CPU but it makes this code not really easy to read...
* The copy is done pixel per pixel */
uint bpp = surface.GetBytesPerPixel();
int spitch = surface.GetPitch();
int dpitch = pattern.GetPitch();
switch (bpp)
{
case 2:
{
spitch >>= 1;
dpitch >>= 1;
const Uint16 *src_origin = (Uint16 *)surface.GetPixels();
Uint16 *dst_origin = (Uint16 *)pattern.GetPixels()
+ (15 + WAVE_INC*(WAVE_COUNT-1)) * dpitch;
for (uint x = 0; x < PATTERN_WIDTH; x++) {
const Uint16 *src = src_origin;
Uint16 *dst = dst_origin + x + height[x] * dpitch;
for (int y=0; y < surface.GetHeight(); y++) {
dst[0] = src[0];
dst += dpitch;
src += spitch;
}
}
break;
}
case 4:
{
spitch >>= 2;
dpitch >>= 2;
const Uint32 *src_origin = (Uint32 *)surface.GetPixels();
Uint32 *dst_origin = (Uint32 *)pattern.GetPixels()
+ (15 + WAVE_INC*(WAVE_COUNT-1)) * dpitch;
for (uint x = 0; x < PATTERN_WIDTH; x++) {
const Uint32 *src = src_origin;
Uint32 *dst = dst_origin + x + height[x] * dpitch;
for (int y=0; y < surface.GetHeight(); y++) {
dst[0] = src[0];
dst += dpitch;
src += spitch;
}
}
break;
}
default:
Error("Unexpected surface format");
}
pattern.Unlock();
surface.Unlock();
}
void Water::Draw()
{
if (!IsActive()) {
return;
}
const Camera* cam = Camera::GetConstInstance();
int screen_bottom = (int)cam->GetPosition().y + (int)cam->GetSize().y;
int water_top = GetWorld().GetHeight() - (water_height + height_mvt) - 20;
if (screen_bottom < water_top) {
return; // save precious CPU time
}
int x0 = cam->GetPosition().x % PATTERN_WIDTH;
int cameraRightPosition = cam->GetPosition().x + cam->GetSize().x;
int y = water_top + (WAVE_HEIGHT_A + WAVE_HEIGHT_B) * 2 + WAVE_INC;
int h = cam->GetSize().y - (y - cam->GetPosition().y);
if (h > 0) {
Rectanglei bottom(0, cam->GetSize().y-h, cam->GetSize().x, h);
GetMainWindow().BoxColor(bottom, *type_color);
bottom.SetPosition(bottom.GetPosition() + cam->GetPosition());
GetWorld().ToRedrawOnMap(bottom);
}
<API key>();
y = water_top;
for (int wave = 0; wave < WAVE_COUNT; wave++) {
for (int x = cam->GetPosition().x - x0 - ((PATTERN_WIDTH/4) * wave);
x < cameraRightPosition;
x += PATTERN_WIDTH) {
AbsoluteDraw(pattern, Point2i(x, y));
}
y += wave * WAVE_INC;
}
}
int Water::GetHeight(int x) const
{
if (IsActive()) {
//printf("Height would have been %i\n", height[x % PATTERN_WIDTH]);
int h = height[x % PATTERN_WIDTH];
return h + GetWorld().GetHeight() - int(water_height + height_mvt);
} else {
return GetWorld().GetHeight();
}
}
void Water::Splash(const Point2i& pos) const
{
if (water_type == "no")
return;
ParticleEngine::AddNow(Point2i(pos.x, pos.y-5), 5, particle_WATER, true, -1, 20);
}
void Water::Smoke(const Point2i& pos) const
{
ParticleEngine::AddNow(Point2i(pos.x, pos.y-5), 2, particle_SMOKE, true, 0, 1);
} |
#ifndef <API key>
#define <API key>
/* utility */
#include "shared.h" /* bool type */
/* common */
#include "fc_types.h"
#include "featured_text.h" /* enum text_link_type type */
#include "map.h"
/* include */
#include "colors_g.h"
#include "tilespec.h"
struct canvas_store; /* opaque type, real type is gui-dep */
struct view {
int gui_x0, gui_y0;
int width, height; /* Size in pixels. */
int tile_width, tile_height; /* Size in tiles. Rounded up. */
int store_width, store_height;
bool <API key>; /* TRUE if cached drawing is possible. */
struct canvas *store, *tmp_store;
};
void mapdeco_init(void);
void mapdeco_free(void);
void <API key>(const struct tile *ptile, bool highlight);
bool <API key>(const struct tile *ptile);
void <API key>(void);
void <API key>(const struct tile *ptile, bool crosshair);
bool <API key>(const struct tile *ptile);
void <API key>(void);
void <API key>(const struct unit *punit);
void <API key>(const struct tile *ptile,
enum direction8 dir);
void <API key>(const struct tile *ptile,
enum direction8 dir);
bool <API key>(const struct tile *ptile,
enum direction8 dir);
void <API key>(void);
extern struct view mapview;
/* HACK: Callers can set this to FALSE to disable sliding. It should be
* reenabled afterwards. */
extern bool can_slide;
#define BORDER_WIDTH 2
#define GOTO_WIDTH 2
#define gui_rect_iterate(GRI_x0, GRI_y0, GRI_width, GRI_height, \
_t, _e, _c, _x, _y) \
{ \
int _x##_0 = (GRI_x0), _y##_0 = (GRI_y0); \
int _x##_w = (GRI_width), _y##_h = (GRI_height); \
\
if (_x##_w < 0) { \
_x##_0 += _x##_w; \
_x##_w = -_x##_w; \
} \
if (_y##_h < 0) { \
_y##_0 += _y##_h; \
_y##_h = -_y##_h; \
} \
if (_x##_w > 0 && _y##_h > 0) { \
struct tile_edge _t
struct tile_corner _t
int _t##_xi, _t##_yi, _t##_si, _t##_di; \
int _x, _y; \
const int _t##_r1 = (<API key>(tileset) ? 2 : 1); \
const int _t##_r2 = _t##_r1 * 2; /* double the ratio */ \
const int _t##_w = tileset_tile_width(tileset); \
const int _t##_h = tileset_tile_height(tileset); \
/* Don't divide by _r2 yet, to avoid integer rounding errors. */ \
const int _t##_x0 = DIVIDE(_x##_0 * _t##_r2, _t##_w) - _t##_r1 / 2; \
const int _t##_y0 = DIVIDE(_y##_0 * _t##_r2, _t##_h) - _t##_r1 / 2; \
const int _t##_x1 = DIVIDE((_x##_0 + _x##_w) * _t##_r2 + _t##_w - 1,\
_t##_w) + _t##_r1; \
const int _t##_y1 = DIVIDE((_y##_0 + _y##_h) * _t##_r2 + _t##_h - 1,\
_t##_h) + _t##_r1; \
const int _t##_count = (_t##_x1 - _t##_x0) * (_t##_y1 - _t##_y0); \
int _t##_index = 0; \
\
freelog(LOG_DEBUG, "Iterating over %d-%d x %d-%d rectangle.", \
_t##_x1, _t##_x0, _t##_y1, _t##_y0); \
for (; _t##_index < _t##_count; _t##_index++) { \
struct tile *_t = NULL; \
struct tile_edge *_e = NULL; \
struct tile_corner *_c = NULL; \
\
_t##_xi = _t##_x0 + (_t##_index % (_t##_x1 - _t##_x0)); \
_t##_yi = _t##_y0 + (_t##_index / (_t##_x1 - _t##_x0)); \
_t##_si = _t##_xi + _t##_yi; \
_t##_di = _t##_yi - _t##_xi; \
if (2 == _t##_r1 /*<API key>(tileset)*/) { \
if ((_t##_xi + _t##_yi) % 2 != 0) { \
continue; \
} \
if (_t##_xi % 2 == 0 && _t##_yi % 2 == 0) { \
if ((_t##_xi + _t##_yi) % 4 == 0) { \
/* Tile */ \
_t = map_pos_to_tile(_t##_si / 4 - 1, _t##_di / 4); \
} else { \
/* Corner */ \
_c = &_t
_c->tile[0] = map_pos_to_tile((_t##_si - 6) / 4, \
(_t##_di - 2) / 4); \
_c->tile[1] = map_pos_to_tile((_t##_si - 2) / 4, \
(_t##_di - 2) / 4); \
_c->tile[2] = map_pos_to_tile((_t##_si - 2) / 4, \
(_t##_di + 2) / 4); \
_c->tile[3] = map_pos_to_tile((_t##_si - 6) / 4, \
(_t##_di + 2) / 4); \
if (tileset_hex_width(tileset) > 0) { \
_e = &_t
_e->type = EDGE_UD; \
_e->tile[0] = _c->tile[0]; \
_e->tile[1] = _c->tile[2]; \
} else if (tileset_hex_height(tileset) > 0) { \
_e = &_t
_e->type = EDGE_LR; \
_e->tile[0] = _c->tile[1]; \
_e->tile[1] = _c->tile[3]; \
} \
} \
} else { \
/* Edge. */ \
_e = &_t
if (_t##_si % 4 == 0) { \
_e->type = EDGE_NS; \
_e->tile[0] = map_pos_to_tile((_t##_si - 4) / 4, \
(_t##_di - 2) / 4); \
_e->tile[1] = map_pos_to_tile((_t##_si - 4) / 4, \
(_t##_di + 2) / 4); \
} else { \
_e->type = EDGE_WE; \
_e->tile[0] = map_pos_to_tile((_t##_si - 6) / 4, \
_t##_di / 4); \
_e->tile[1] = map_pos_to_tile((_t##_si - 2) / 4, \
_t##_di / 4); \
} \
} \
} else { \
if (_t##_si % 2 == 0) { \
if (_t##_xi % 2 == 0) { \
/* Corner. */ \
_c = &_t
_c->tile[0] = map_pos_to_tile(_t##_xi / 2 - 1, \
_t##_yi / 2 - 1); \
_c->tile[1] = map_pos_to_tile(_t##_xi / 2, \
_t##_yi / 2 - 1); \
_c->tile[2] = map_pos_to_tile(_t##_xi / 2, \
_t##_yi / 2); \
_c->tile[3] = map_pos_to_tile(_t##_xi / 2 - 1, \
_t##_yi / 2); \
} else { \
/* Tile. */ \
_t = map_pos_to_tile((_t##_xi - 1) / 2, \
(_t##_yi - 1) / 2); \
} \
} else { \
/* Edge. */ \
_e = &_t
if (_t##_yi % 2 == 0) { \
_e->type = EDGE_NS; \
_e->tile[0] = map_pos_to_tile((_t##_xi - 1) / 2, \
_t##_yi / 2 - 1); \
_e->tile[1] = map_pos_to_tile((_t##_xi - 1) / 2, \
_t##_yi / 2); \
} else { \
_e->type = EDGE_WE; \
_e->tile[0] = map_pos_to_tile(_t##_xi / 2 - 1, \
(_t##_yi - 1) / 2); \
_e->tile[1] = map_pos_to_tile(_t##_xi / 2, \
(_t##_yi - 1) / 2); \
} \
} \
} \
_x = _t##_xi * _t##_w / _t##_r2 - _t##_w / 2; \
_y = _t##_yi * _t##_h / _t##_r2 - _t##_h / 2;
#define <API key> \
} \
} \
}
void <API key>(struct tile *ptile,
bool full_refresh, bool write_to_screen);
void <API key>(struct unit *punit, struct tile *ptile,
bool full_refresh, bool write_to_screen);
void <API key>(struct city *pcity, struct tile *ptile,
bool full_refresh, bool write_to_screen);
void <API key>(bool write_to_screen);
void map_to_gui_vector(const struct tileset *t,
int *gui_dx, int *gui_dy, int map_dx, int map_dy);
bool tile_to_canvas_pos(int *canvas_x, int *canvas_y, struct tile *ptile);
struct tile *canvas_pos_to_tile(int canvas_x, int canvas_y);
struct tile *<API key>(int canvas_x, int canvas_y);
void <API key>(int *xmin, int *ymin,
int *xmax, int *ymax,
int *xsize, int *ysize);
void <API key>(int *xstep, int *ystep);
void <API key>(int *scroll_x, int *scroll_y);
void <API key>(int scroll_x, int scroll_y);
void set_mapview_origin(int gui_x0, int gui_y0);
struct tile *<API key>(void);
void <API key>(struct tile *ptile);
bool <API key>(struct tile *ptile);
bool <API key>(struct tile *ptile);
void put_unit(const struct unit *punit,
struct canvas *pcanvas, int canvas_x, int canvas_y);
void put_city(struct city *pcity,
struct canvas *pcanvas, int canvas_x, int canvas_y);
void put_terrain(struct tile *ptile,
struct canvas *pcanvas, int canvas_x, int canvas_y);
void <API key>(struct unit *punit,
struct canvas *pcanvas,
int canvas_x, int canvas_y, int *upkeep_cost,
int happy_cost);
void toggle_city_color(struct city *pcity);
void toggle_unit_color(struct unit *punit);
void <API key>(struct tile *ptile);
void put_one_element(struct canvas *pcanvas, enum mapview_layer layer,
struct tile *ptile,
const struct tile_edge *pedge,
const struct tile_corner *pcorner,
const struct unit *punit, struct city *pcity,
int canvas_x, int canvas_y,
const struct city *citymode);
void put_drawn_sprites(struct canvas *pcanvas,
int canvas_x, int canvas_y,
int count, struct drawn_sprite *pdrawn,
bool fog);
void update_map_canvas(int canvas_x, int canvas_y, int width, int height);
void <API key>(void);
void <API key>(struct city *pcity);
void <API key>(int canvas_x, int canvas_y,
int width, int height);
bool show_unit_orders(struct unit *punit);
void draw_segment(struct tile *ptile, enum direction8 dir);
void undraw_segment(struct tile *ptile, enum direction8 dir);
void <API key>(struct unit *punit0, int hp0,
struct unit *punit1, int hp1);
void <API key>(struct unit *punit,
struct tile *ptile, int dx, int dy);
struct city *<API key>(const struct tile *ptile,
struct unit **punit);
struct city *find_city_near_tile(const struct tile *ptile);
void <API key>(struct city *pcity,
char *buf, size_t buf_len);
void <API key>(struct city *pcity,
char *name_buffer,
size_t name_buffer_len,
char *growth_buffer,
size_t growth_buffer_len,
enum color_std *grwoth_color);
void <API key>(struct city *pcity,
char *trade_routes_buffer,
size_t <API key>,
enum color_std *trade_routes_color);
bool map_canvas_resized(int width, int height);
void <API key>(void);
void <API key>(int *width, int *height);
void put_spaceship(struct canvas *pcanvas, int canvas_x, int canvas_y,
const struct player *pplayer);
void link_marks_init(void);
void link_marks_free(void);
void link_marks_draw_all(void);
void <API key>(void);
void <API key>(void);
void link_mark_add_new(enum text_link_type type, int id);
void link_mark_restore(enum text_link_type type, int id);
#endif /* <API key> */ |
module Animate
{
/**
* This represents a combo property for assets that the user can select from a list.
*/
export class PGComboAsset extends PropertyGridEditor
{
constructor( grid: PropertyGrid )
{
super( grid );
}
/**
* Checks a property to see if it can edit it
* @param {Prop<any>} prop The property being edited
* @returns {boolean}
*/
canEdit(prop: Prop<any>): boolean
{
if (prop instanceof PropAsset && prop.type == PropertyType.ASSET)
return true;
else
return false;
}
/**
* Given a property, the grid editor must produce HTML that can be used to edit the property
* @param {Prop<any>} prop The property being edited
* @param {Component} container The container acting as this editors parent
*/
edit(prop: Prop<any>, container: Component)
{
var p = <PropAsset>prop;
// Create HTML
var editor: JQuery = jQuery(`<div class='property-grid-label'>${p.name}</div><div class='property-grid-value'><select class='prop-combo' style = 'width:90%;'></select><div class='eye-picker'><img src='media/eye.png' /></div></div><div class='fix'></div>`);
var selector: JQuery = jQuery( "select", editor );
var eye: JQuery = jQuery( ".eye-picker", editor );
// Add to DOM
container.element.append(editor);
var resource = p.getVal();
var selectedID = (resource ? resource.entry._id : null);
var classNames = p.classNames;
var nodes = TreeViewScene.getSingleton().getAssets( classNames );
// Create the blank options and select it if nothing else is chosen
selector.append(`<option value='' ${(!selectedID ? "selected='selected'" : "" )}></option>` );
// Sort alphabetically
nodes = nodes.sort( function ( a: <API key>, b: <API key> )
{
var textA = a.resource.entry.name.toUpperCase();
var textB = b.resource.entry.name.toUpperCase();
return ( textA < textB ) ? -1 : ( textA > textB ) ? 1 : 0;
});
var len: number = nodes.length;
for ( var i = 0; i < len; i++ )
selector.append(`<option title='${nodes[i].resource.entry.shallowId + " : " + nodes[i].resource.entry.className}' value='${nodes[i].resource.entry.shallowId}' ${(selectedID == nodes[i].resource.entry.shallowId ? "selected='selected'" : "")}>${nodes[i].resource.entry.name}</option>` );
var that = this;
// When we select a new asset
var onSelect = function (e: JQueryEventObject )
{
var val = parseFloat(selector.val());
var asset: Asset = User.get.project.<API key><Asset>(val, ResourceType.ASSET);
p.setVal(asset);
};
// When we click on the target
var onEye = function (e: JQueryEventObject)
{
var val = parseInt( selector.val() );
var asset: Asset = User.get.project.<API key><Asset>(val, ResourceType.ASSET);
if ( asset )
TreeViewScene.getSingleton().selectNode(TreeViewScene.getSingleton().findNode( "resource", asset ), true );
else
TreeViewScene.getSingleton().selectNode(TreeViewScene.getSingleton().findNode("className", classNames[0] ), true );
};
// Add listeners
eye.on( "mouseup", onEye );
selector.on( "change", onSelect );
}
}
} |
# -*- coding: utf-8 -*-
# This file is a plugin for EventGhost.
# EventGhost is free software: you can redistribute it and/or modify it under
# any later version.
# EventGhost is distributed in the hope that it will be useful, but WITHOUT
# more details.
ur"""<rst>
Plugin for the CyberLink Universal Remote Control
"""
import eg
eg.RegisterPlugin(
name = "CyberLink Universal Remote Control",
author = "Bitmonster",
version = "1.0.1",
kind = "remote",
guid = "{<API key>}",
description = __doc__,
hardwareId = "USB\\VID_0766&PID_0204",
)
KEY_CODES_1 = {
(0, 0, 30, 0, 0, 0, 0, 0): "Num1",
(0, 0, 31, 0, 0, 0, 0, 0): "Num2",
(0, 0, 32, 0, 0, 0, 0, 0): "Num3",
(0, 0, 33, 0, 0, 0, 0, 0): "Num4",
(0, 0, 34, 0, 0, 0, 0, 0): "Num5",
(0, 0, 35, 0, 0, 0, 0, 0): "Num6",
(0, 0, 36, 0, 0, 0, 0, 0): "Num7",
(0, 0, 37, 0, 0, 0, 0, 0): "Num8",
(0, 0, 38, 0, 0, 0, 0, 0): "Num9",
(0, 0, 39, 0, 0, 0, 0, 0): "Num0",
(0, 0, 76, 0, 0, 0, 0, 0): "Clear",
(0, 0, 40, 0, 0, 0, 0, 0): "Ok",
(0, 0, 79, 0, 0, 0, 0, 0): "Right",
(0, 0, 80, 0, 0, 0, 0, 0): "Left",
(0, 0, 81, 0, 0, 0, 0, 0): "Down",
(0, 0, 82, 0, 0, 0, 0, 0): "Up",
}
KEY_CODES_2 = {
(3, 0, 0, 2): "Info",
(3, 0, 0, 4): "Rewind",
(3, 0, 0, 8): "Forward",
(3, 0, 0, 64): "Play",
(3, 0, 0, 128): "Pause",
}
KEY_CODES_3 = {
(3, 0, 1): "ChannelUp",
(3, 0, 2): "ChannelDown",
(3, 0, 4): "Back",
(3, 0, 16): "Stop",
(3, 1, 0): "NextTrack",
(3, 2, 0): "PreviousTrack",
(3, 4, 0): "Radio",
(3, 16, 0): "Mute",
(3, 32, 0): "VolumeUp",
(3, 64, 0): "VolumeDown",
(3, 128, 0): "Record",
(4, 0, 1): "Angel",
(4, 0, 2): "Language",
(4, 0, 4): "DvdMenu",
(4, 0, 8): "Subtitle",
(4, 0, 16): "SAP",
(4, 0, 32): "Teletext",
(4, 0, 64): "LastChannel",
(4, 1, 0): "Home",
(4, 2, 0): "TV",
(4, 8, 0): "Green",
(4, 16, 0): "Yellow",
(4, 32, 0): "Blue",
(4, 128, 0): "Red",
}
KEY_CODES_4 = {
(2, 2): "Power",
}
class <API key>(eg.PluginBase):
def __start__(self):
self.buffer = []
self.expectedLength = 0
self.winUsb = eg.WinUsb(self)
self.winUsb.Device(self.Callback, 8).AddHardwareId(
"CyberLink Universal Remote Control (Keypad)",
"USB\\VID_0766&PID_0204&MI_00"
)
self.winUsb.Device(self.Callback, 4).AddHardwareId(
"CyberLink Universal Remote Control (Buttons)",
"USB\\VID_0766&PID_0204&MI_01"
)
self.winUsb.Start()
self.last_data = []
def __stop__(self):
self.winUsb.Stop()
def Callback(self, data):
if self.last_data != data:
# print data
if data in KEY_CODES_1:
self.<API key>(KEY_CODES_1[data])
self.last_data = data
elif data in KEY_CODES_2:
self.<API key>(KEY_CODES_2[data])
self.last_data = data
elif data[:3] in KEY_CODES_3:
self.<API key>(KEY_CODES_3[data[:3]])
self.last_data = data
elif data[:2] in KEY_CODES_4:
self.<API key>(KEY_CODES_4[data[:2]])
self.last_data = data
elif len(data) == len(self.last_data):
self.EndLastEvent()
self.last_data = []
# print "EndLastEvent" |
<?php
defined('_JEXEC') or die;
jimport('joomla.plugin.plugin');
class <API key> extends JPlugin{
var $_twojtoolbox = null;
protected $regex = '/\{2jtoolbox_content\s+([a-z0-9]*)\s+id:([0-9]*)\s+begin(\s+title:([^}]*)){0,1}\}.*\{2jtoolbox_content\s+\\1\s+id:\\2\s+end\}/isU';
protected $regex_easy = '/\{2jtoolbox_content\s+([a-z0-9]*)\s+id:([0-9]*)\s+begin(\s+title:([^}]*)){0,1}\}.*\{2jtoolbox_content\s+\\1\s+id:\\2\s+end\}/is';
protected $regex_single = '/{2jtoolbox\s+([a-z0-9]*)\s+id:([0-9]*)}/i';
function __construct(& $subject, $config){
parent::__construct($subject, $config);
}
public function onContentPrepare($context, &$article, &$params, $page = 0){
if (strpos($article->text, '{2jtoolbox') === false) return true;
JLoader::register('<API key>', JPATH_SITE.'/components/com_twojtoolbox/helpers/twojtoolboxsite.php');
if( !class_exists('<API key>') ) return '';
if( ($new_article_text = <API key>( ( strlen($article->text)<100000 ? $this->regex : $this->regex_easy ) , '<API key>::<API key>', $article->text) )!==NULL ){
$article->text = $new_article_text;
}
$matches = array();
preg_match_all($this->regex_single, $article->text, $matches, PREG_SET_ORDER);
if( count($matches) ){
foreach ($matches as $match) {
if(count($match)==3 && (int)$match[2] ){
$parent_acticle_id = '';
if(isset($article->id) && $article->id > 0 ){
$parent_acticle_id = $article->id;
}
if( JRequest::getVar('<API key>'.(int)$match[2], 0, '', 'int') > 3 ){
$output = 'cicle';
} else $output = <API key>::getPluginContent((int)$match[2], $parent_acticle_id);
$article->text = preg_replace("|$match[0]|", $output, $article->text, 1);
}
}
}
}
function onAfterRoute(){
$app = JFactory::getApplication();
$document = JFactory::getDocument();
$format = $document->getType('raw');
$tmpl =JRequest::getCmd('tmpl', '');
$print =JRequest::getCmd('print', 0);
if ($app->isAdmin() || $print || $tmpl=='component' || $format!='html' ){
return;
}
$menu = $app->getMenu()->getActive();
if( !isset($menu->id) ) return;
$itemid = $menu->id;
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('id');
$query->where('itemid = '. (int) $itemid, 'OR' );
$query->where('itemid = -1', 'OR');
$query->from('#__twojtoolbox_menu');
$db->setQuery($query);
//echo (string) $query;
if( $plugins_for_page = $db->loadColumn() ){
for($i=0;$i<count($plugins_for_page);$i++){
$query->clear();
$query->select('plu.*, ite.id AS item_id, ite.title AS item_title, ite.params, ite.state');
$query->where('ite.`id` = '. (int) $plugins_for_page[$i]);
$query->where('plu.`type` = ite.`type`');
$query->where('plu.`daemon` = 1 ');
$query->where('ite.`state` = 1');
$query->from('#__twojtoolbox AS ite, #<API key> AS plu');
$db->setQuery($query);
if( $plugin_info = $db->loadObject() ){
require_once (JPATH_SITE.'/components/com_twojtoolbox/pluginclass.php');
jimport('joomla.filesystem.file');
$plugin_classfile = JPATH_SITE.'/'.
'components/'.
'com_twojtoolbox/'.
'plugins/'.
$plugin_info->type.'/'.
$plugin_info->v_active.'/'.
'twoj_'.$plugin_info->type.'_plugin.php';
if( !JFile::exists($plugin_classfile) ) return JText::_('<API key>');
require_once ($plugin_classfile);
$class = 'TwoJToolBox'.ucfirst($plugin_info->type);
if (class_exists($class)) $instance = new $class($plugin_info);
else return JText::sprintf('<API key>', $class);
if( $instance->error_text ) return $instance->error_text;
$instance->getDaemon();
}
}
}
}
function onAfterInitialise(){
$app = JFactory::getApplication();
$user = JFactory::getUser();
$document = JFactory::getDocument();
$format = $document->getType('raw');
$tmpl =JRequest::getCmd('tmpl', '');
$print =JRequest::getCmd('print', 0);
if ($app->isAdmin() || $print || $tmpl=='component' || $format!='html' ) {
return;
}
JRequest::setVar('<API key>', array());
JRequest::setVar('<API key>', array());
}
function onBeforeCompileHead(){
$app = JFactory::getApplication();
$document = JFactory::getDocument();
$format = $document->getType('raw');
$tmpl =JRequest::getCmd('tmpl', '');
$print =JRequest::getCmd('print', 0);
if ($app->isAdmin() || $print || $tmpl=='component' || $format!='html' ) {
return;
}
JLoader::register('<API key>', JPATH_SITE.'/components/com_twojtoolbox/helpers/twojtoolboxsite.php');
$cache = JFactory::getCache('twojtoolboxplugin', 'output');
$cache_enable = $cache->getCaching();
if($cache_enable) $get_id = JCache::makeId();
$<API key> = JComponentHelper::getParams('com_twojtoolbox')->get('twojcache', 1);
if ($cache_enable && $jslist_cache = $cache->get($get_id.'js')) {
$document->addScript($jslist_cache);
} else {
$js_list = JRequest::getVar('<API key>', array(), '', 'array');
if( count($js_list) ){
$in_js = array('init');
for($i=0;$i<count($js_list);++$i){
if( !in_array($js_list[$i], $in_js) ) $in_js[] = $js_list[$i];
}
$url_js = <API key>::scriptCompile( implode( '2jbrs2', $in_js), 'js' );
if(!$url_js || !$<API key> ) $url_js = JURI::root(true)."/index.php?option=com_twojtoolbox&format=raw&task=ajax.getjs&need=".implode( '2jbrs2', $in_js)."&name=2jscript.js";
$document->addScript($url_js);
if($cache_enable) $cache->store( $url_js, $get_id.'js');
}
}
if ($cache_enable && $csslist_cache = $cache->get($get_id.'css')) {
$document->addStyleSheet($csslist_cache);
} else {
$css_list = JRequest::getVar('<API key>', array(), '', 'array');
if( count($css_list) ){
$in_css = array();
for($i=0;$i<count($css_list);++$i){
if( !in_array($css_list[$i], $in_css) ) $in_css[] = $css_list[$i];
}
$url_css = <API key>::scriptCompile( implode( '2jbrs2', $in_css), 'css' );
if(!$url_css || !$<API key> ) $url_css = JURI::root(true) . "/index.php?option=com_twojtoolbox&format=raw&task=ajax.getcss&need=".implode( '2jbrs2', $in_css)."&name=2j.style.css";
$document->addStyleSheet($url_css);
if($cache_enable) $cache->store( $url_css, $get_id.'css');
}
}
}
} |
/** \file
\ingroup Trinityd
*/
#include "Common.h"
#include "ObjectAccessor.h"
#include "World.h"
#include "WorldSocketMgr.h"
#include "Database/DatabaseEnv.h"
#include "ScriptMgr.h"
#include "BattlegroundMgr.h"
#include "MapManager.h"
#include "Timer.h"
#include "WorldRunnable.h"
#define WORLD_SLEEP_CONST 50
#ifdef _WIN32
#include "ServiceWin32.h"
extern int m_ServiceStatus;
#endif
Heartbeat for the World
void WorldRunnable::run()
{
uint32 realCurrTime = 0;
uint32 realPrevTime = getMSTime();
uint32 prevSleepTime = 0; // used for balanced full tick time length near WORLD_SLEEP_CONST
sScriptMgr->OnStartup();
- While we have not World::m_stopEvent, update the world
while (!World::IsStopped())
{
++World::m_worldLoopCounter;
realCurrTime = getMSTime();
uint32 diff = getMSTimeDiff(realPrevTime,realCurrTime);
sWorld->Update( diff );
realPrevTime = realCurrTime;
// diff (D0) include time of previous sleep (d0) + tick time (t0)
// we want that next d1 + t1 == WORLD_SLEEP_CONST
// we can't know next t1 and then can use (t0 + d1) == WORLD_SLEEP_CONST requirement
// d1 = WORLD_SLEEP_CONST - t0 = WORLD_SLEEP_CONST - (D0 - d0) = WORLD_SLEEP_CONST + d0 - D0
if (diff <= WORLD_SLEEP_CONST+prevSleepTime)
{
prevSleepTime = WORLD_SLEEP_CONST+prevSleepTime-diff;
ACE_Based::Thread::Sleep(prevSleepTime);
}
else
prevSleepTime = 0;
#ifdef _WIN32
if (m_ServiceStatus == 0)
World::StopNow(SHUTDOWN_EXIT_CODE);
while (m_ServiceStatus == 2)
Sleep(1000);
#endif
}
sScriptMgr->OnShutdown();
sWorld->KickAll(); // save and kick all players
sWorld->UpdateSessions( 1 ); // real players unload required UpdateSessions call
// unload battleground templates before different singletons destroyed
sBattlegroundMgr-><API key>();
sWorldSocketMgr->StopNetwork();
sObjectAccessor->UnloadAll(); // unload 'i_player2corpse' storage and remove from world
sMapMgr->UnloadAll(); // unload all grids (including locked in memory)
} |
#include <common.h>
#include <asm/mach-types.h>
#include <asm/arch/memory.h>
#include <malloc.h>
#if defined(CONFIG_CMD_NET)
#include <asm/arch/aml_eth_reg.h>
#include <asm/arch/aml_eth_pinmux.h>
#include <asm/arch/io.h>
#endif /*(CONFIG_CMD_NET)*/
#if defined(CONFIG_AML_I2C)
#include <aml_i2c.h>
#include <asm/arch/io.h>
#endif /*CONFIG_AML_I2C*/
<API key>;
#if defined(CONFIG_CMD_NET)
static void setup_net_chip(void)
{
//m8 only use externel clock
/* setup ethernet clk */
WRITE_CBUS_REG(HHI_ETH_CLK_CNTL, 0x4f00); // clock Input 50 inverted : bit14 =1 Div : 6:0 = 0 En : bit8 = 1 Sel : bit 11:9 = 7
/* setup ethernet pinmux use gpioz(5-14) */
SET_CBUS_REG_MASK(PERIPHS_PIN_MUX_6, (1 << 15) | (1 << 14) | (1 << 13) | (1 << 12) |
(1 << 11) | (1 << 8 ) | (1 << 7 ) | (1 << 10) | (1 << 6 ) | (1 << 5 ));
/* setup ethernet mode */
WRITE_CBUS_REG(PREG_ETHERNET_ADDR0, 0x241);//bit6-4 :100 rmii mode
CLEAR_CBUS_REG_MASK(HHI_MEM_PD_REG0, (1 << 3) | (1<<2));
/* hardware reset ethernet phy : gpioz14 connect phyreset pin*/
CLEAR_CBUS_REG_MASK(PREG_PAD_GPIO1_EN_N, 1 << 31);
CLEAR_CBUS_REG_MASK(PREG_PAD_GPIO1_O, 1 << 31);
udelay(2000);
SET_CBUS_REG_MASK(PREG_PAD_GPIO1_O, 1 << 31);
}
int board_eth_init(bd_t *bis)
{
setup_net_chip();
udelay(1000);
extern int aml_eth_init(bd_t *bis);
aml_eth_init(bis);
return 0;
}
#endif /* (CONFIG_CMD_NET) */
u32 get_board_rev(void)
{
return 0x20;
}
#if CONFIG_CMD_MMC
#include <mmc.h>
#include <asm/arch/sdio.h>
static int sdio_init(unsigned port)
{
switch(port)
{
case SDIO_PORT_A:
break;
case SDIO_PORT_B:
//todo add card detect
setbits_le32(<API key>,1<<29);//CARD_6
break;
case SDIO_PORT_C:
//enable pull up
clrbits_le32(P_PAD_PULL_UP_REG3, 0xff<<0);
break;
case SDIO_PORT_XC_A:
break;
case SDIO_PORT_XC_B:
break;
case SDIO_PORT_XC_C:
break;
default:
break;
}
return cpu_sdio_init(port);
}
extern unsigned <API key>;
static int sdio_detect(unsigned port)
{
int ret;
switch(port)
{
case SDIO_PORT_A:
break;
case SDIO_PORT_B:
setbits_le32(<API key>,1<<29);//CARD_6
ret=readl(P_PREG_PAD_GPIO5_I)&(1<<29)?0:1;
if(!(readl(P_PREG_PAD_GPIO0_I)&(1<<26))){ //sd_d3 low, debug board in
if(!(readl(P_PREG_PAD_GPIO0_I)&(1<<22))){
printf("sdio debug board detected, sd card with 1bit mode\n");
<API key> = 1;
}
else{
printf("sdio debug board detected, no sd card in\n");
<API key> = 0;
return 1;
}
}
break;
case SDIO_PORT_C:
break;
case SDIO_PORT_XC_A:
break;
case SDIO_PORT_XC_B:
break;
case SDIO_PORT_XC_C:
break;
default:
break;
}
return 0;
}
static void sdio_pwr_prepare(unsigned port)
{
@todo NOT FINISH
do nothing here
<API key>(port);
}
static void sdio_pwr_on(unsigned port)
{
switch(port)
{
case SDIO_PORT_A:
break;
case SDIO_PORT_B:
clrbits_le32(P_PREG_PAD_GPIO5_O,(1<<31)); //CARD_8
clrbits_le32(<API key>,(1<<31));
@todo NOT FINISH
break;
case SDIO_PORT_C:
break;
case SDIO_PORT_XC_A:
break;
case SDIO_PORT_XC_B:
break;
case SDIO_PORT_XC_C:
break;
default:
break;
}
return;
}
static void sdio_pwr_off(unsigned port)
{
@todo NOT FINISH
switch(port)
{
case SDIO_PORT_A:
break;
case SDIO_PORT_B:
setbits_le32(P_PREG_PAD_GPIO5_O,(1<<31)); //CARD_8
clrbits_le32(<API key>,(1<<31));
break;
case SDIO_PORT_C:
break;
case SDIO_PORT_XC_A:
break;
case SDIO_PORT_XC_B:
break;
case SDIO_PORT_XC_C:
break;
default:
break;
}
return;
}
#define CONFIG_TSD 1
static void board_mmc_register(unsigned port)
{
struct aml_card_sd_info *aml_priv=cpu_sdio_get(port);
struct mmc *mmc = (struct mmc *)malloc(sizeof(struct mmc));
if(aml_priv==NULL||mmc==NULL)
return;
memset(mmc,0,sizeof(*mmc));
aml_priv->sdio_init=sdio_init;
aml_priv->sdio_detect=sdio_detect;
aml_priv->sdio_pwr_off=sdio_pwr_off;
aml_priv->sdio_pwr_on=sdio_pwr_on;
aml_priv->sdio_pwr_prepare=sdio_pwr_prepare;
#ifdef CONFIG_TSD
// if(mmc->block_dev.dev > 0)//tsd
mmc->block_dev.if_type = IF_TYPE_SD;
#else
// if(mmc->block_dev.dev > 0)//emmc
mmc->block_dev.if_type = IF_TYPE_MMC;
#endif
sdio_register(mmc, aml_priv);
#if 0
strncpy(mmc->name,aml_priv->name,31);
mmc->priv = aml_priv;
aml_priv->removed_flag = 1;
aml_priv->inited_flag = 0;
aml_priv->sdio_init=sdio_init;
aml_priv->sdio_detect=sdio_detect;
aml_priv->sdio_pwr_off=sdio_pwr_off;
aml_priv->sdio_pwr_on=sdio_pwr_on;
aml_priv->sdio_pwr_prepare=sdio_pwr_prepare;
mmc->send_cmd = aml_sd_send_cmd;
mmc->set_ios = aml_sd_cfg_swth;
mmc->init = aml_sd_init;
mmc->rca = 1;
mmc->voltages = MMC_VDD_33_34;
mmc->host_caps = MMC_MODE_4BIT | MMC_MODE_HS;
//mmc->host_caps = MMC_MODE_4BIT;
mmc->bus_width = 1;
mmc->clock = 300000;
mmc->f_min = 200000;
mmc->f_max = 50000000;
mmc_register(mmc);
#endif
}
int board_mmc_init(bd_t *bis)
{
board_mmc_register(SDIO_PORT_A);
// board_mmc_register(SDIO_PORT_B);
// board_mmc_register(SDIO_PORT_C);
// board_mmc_register(SDIO_PORT_B1);
return 0;
}
#endif
#ifdef <API key>
#include <asm/arch/usb.h>
#include <asm/arch/gpio.h>
static int <API key>(char bc_mode)
{
switch(bc_mode){
case BC_MODE_DCP:
case BC_MODE_CDP:
//Pull up chargging current > 500mA
break;
case BC_MODE_UNKNOWN:
case BC_MODE_SDP:
default:
//Limit chargging current <= 500mA
//Or detet dec-charger
break;
}
return 0;
}
//note: try with some M3 pll but only following can work
//<API key> @ 1 (24MHz)
//<API key> @ 0 (12MHz)
//<API key> @ 27(336MHz); @Rev2663 M3 SKT board DDR is 336MHz
// 43 (528MHz); M3 SKT board DDR not stable for 528MHz
struct amlogic_usb_config g_usb_config_m6_skt={
<API key>,
1, //PLL divider: (clock/12 -1)
<API key>,
USB_ID_MODE_SW_HOST,
NULL,//gpio_set_vbus_power, //set_vbus_power
NULL,
};
struct amlogic_usb_config <API key>={
<API key>,
1, //PLL divider: (clock/12 -1)
<API key>,
<API key>,
NULL,//gpio_set_vbus_power, //set_vbus_power
<API key>,
};
#endif /*<API key>*/
#ifdef CONFIG_IR_REMOTE
void board_ir_init(void)
{
writel(0x00005801,<API key>);
writel(0x30fa0013,P_AO_IR_DEC_REG0);
writel(0x0ee8be40,P_AO_IR_DEC_REG1);
writel(0x01d801ac,<API key>);
writel(0x00f800ca,<API key>);
writel(0x0044002c,P_AO_IR_DEC_BIT_0);
printf("IR init done!\n");
}
#endif
int board_init(void)
{
gd->bd->bi_arch_number=<API key>;
gd->bd->bi_boot_params=BOOT_PARAMS_OFFSET;
#if <API key> //temp test
nand_init();
#endif
#ifdef CONFIG_AML_I2C
board_i2c_init();
#endif /*CONFIG_AML_I2C*/
#ifdef CONFIG_IR_REMOTE
board_ir_init();
#endif
#ifdef <API key>
board_usb_init(&g_usb_config_m6_skt,BOARD_USB_MODE_HOST);
board_usb_init(&<API key>,<API key>);
#endif /*<API key>*/
return 0;
}
#ifdef CONFIG_NAND_AML_M3 //temp test
//#include <amlogic/nand/platform.h>
#include <asm/arch/nand.h>
#include <linux/mtd/partitions.h>
static struct aml_nand_platform <API key>[] = {
#if defined <API key> || defined <API key>
{
.name = NAND_BOOT_NAME,
.chip_enable_pad = AML_NAND_CE0,
.ready_busy_pad = AML_NAND_CE0,
.platform_nand_data = {
.chip = {
.nr_chips = 1,
.options = (NAND_TIMING_MODE5 | <API key>),
},
},
.rbpin_mode=1,
.short_pgsz=384,
.ran_mode=0,
.T_REA = 20,
.T_RHOH = 15,
},
#endif
{
.name = NAND_NORMAL_NAME,
.chip_enable_pad = (AML_NAND_CE0) | (AML_NAND_CE1 << 4),// | (AML_NAND_CE2 << 8) | (AML_NAND_CE3 << 12)),
.ready_busy_pad = (AML_NAND_CE0) | (AML_NAND_CE1 << 4),// | (AML_NAND_CE1 << 8) | (AML_NAND_CE1 << 12)),
.platform_nand_data = {
.chip = {
.nr_chips = 2,
.options = (NAND_TIMING_MODE5 | <API key> | NAND_TWO_PLANE_MODE),
},
},
.rbpin_mode = 1,
.short_pgsz = 0,
.ran_mode = 0,
.T_REA = 20,
.T_RHOH = 15,
}
};
struct aml_nand_device aml_nand_mid_device = {
.aml_nand_platform = <API key>,
.dev_num = ARRAY_SIZE(<API key>),
};
#endif
static int do_msr(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
const char *cmd;
/* need at least two arguments */
if (argc > 2)
goto usage;
int nIndex = 0;
int nCounter = 64;
if( 2 == argc)
{
cmd = argv[1];
char *endp;
nIndex = simple_strtoul(argv[1], &endp, 10);
if(nIndex < 0 || nIndex > 63)
goto usage;
nCounter = 1;
}
extern unsigned long clk_util_clk_msr(unsigned long clk_mux);
//printf("\n");
for(;((nIndex < 64) && nCounter);nCounter--,nIndex++)
printf("MSR clock[%d] = %dMHz\n",nIndex,clk_util_clk_msr(nIndex));
return 0;
usage:
return cmd_usage(cmdtp);
}
U_BOOT_CMD(
msr, 2, 1, do_msr,
"Meson msr sub-system",
" [0...63] - measure clock frequency\n"
" - no clock index will measure all clock"
);
#ifdef CONFIG_SARADC
#include <asm/saradc.h>
/*following key value are test with board
[M6_SKT_V_1.0 20120112]
ref doc:
1. M6_SKT_V1.pdf
*/
/* adc_init(&g_adc_info, ARRAY_SIZE(g_adc_info)); */
/*following is test code to test ADC & key pad*/
static int do_adc(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
if(argc > 2)
goto usage;
u32 nDelay = 0xffff;
int nKeyVal = 0;
int nCnt = 0;
char *endp;
int nMaxCnt;
int adc_chan = 0; //m8 adc channel 0;m6 adc channel 4
if(2 == argc)
nMaxCnt = simple_strtoul(argv[1], &endp, 10);
else
nMaxCnt = 10;
saradc_enable();
while(nCnt < nMaxCnt)
{
udelay(nDelay);
nKeyVal = get_adc_sample(adc_chan);
if(nKeyVal > 1021)
continue;
printf("SARADC CH-4 Get key : %d [%d]\n", nKeyVal,(100*nKeyVal)/1024);
nCnt++;
}
saradc_disable();
return 0;
usage:
return cmd_usage(cmdtp);
}
U_BOOT_CMD(
adc, 2, 1, do_adc,
"M6 ADC test",
"[times] - read `times' adc key through channel-4, default to read 10 times\n"
" 10bit ADC. key value: min=0; max=1024\n"
" SKT BOARD #20: Key1=13 Key2=149 key3=274 key4=393 key5=514\n"
);
#endif //CONFIG_SARADC |
/* FILENAME */
/* stereo.h */
/* DESCRIPTION */
/* TMS320C5505 USB Stick. */
/* Header file for converting from stereo to mono. */
/* REVISION */
/* Revision: 1.00 */
/* Author : Richard Sikora */
/* HISTORY */
/* Revision 1.00 */
#ifndef STEREO_H
#define STEREO_H
signed int stereo_to_mono(signed int left_channel, signed int right_channel);
#endif
/* End of stereo.h */ |
using System;
namespace VIQA.Common.Interfaces
{
public interface IAlerting
{
Exception ThrowError(string errorMsg);
}
} |
#ifndef _R8169_H_
#define _R8169_H_
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
/** FIXME: include/linux/pci_regs.h has these PCI regs, maybe
we need such a file in gPXE?
**/
#define PCI_EXP_DEVCTL 8 /* Device Control */
#define <API key> 0x7000 /* <API key> */
#define PCI_EXP_LNKCTL 16 /* Link Control */
#define <API key> 0x100 /* Enable clkreq */
#define <API key> 0x0800 /* Enable No Snoop */
/** FIXME: update mii.h in src/include/mii.h from Linux sources
so we don't have to include these definitiions.
**/
/* The forced speed, 10Mb, 100Mb, gigabit, 2.5Gb, 10GbE. */
#define SPEED_10 10
#define SPEED_100 100
#define SPEED_1000 1000
#define SPEED_2500 2500
#define SPEED_10000 10000
/* Duplex, half or full. */
#define DUPLEX_HALF 0x00
#define DUPLEX_FULL 0x01
/* Generic MII registers. */
#define MII_BMCR 0x00 /* Basic mode control register */
#define MII_BMSR 0x01 /* Basic mode status register */
#define MII_PHYSID1 0x02 /* PHYS ID 1 */
#define MII_PHYSID2 0x03 /* PHYS ID 2 */
#define MII_ADVERTISE 0x04 /* Advertisement control reg */
#define MII_LPA 0x05 /* Link partner ability reg */
#define MII_EXPANSION 0x06 /* Expansion register */
#define MII_CTRL1000 0x09 /* 1000BASE-T control */
#define MII_STAT1000 0x0a /* 1000BASE-T status */
#define MII_ESTATUS 0x0f /* Extended Status */
#define MII_DCOUNTER 0x12 /* Disconnect counter */
#define MII_FCSCOUNTER 0x13 /* False carrier counter */
#define MII_NWAYTEST 0x14 /* N-way auto-neg test reg */
#define MII_RERRCOUNTER 0x15 /* Receive error counter */
#define MII_SREVISION 0x16 /* Silicon revision */
#define MII_RESV1 0x17 /* Reserved... */
#define MII_LBRERROR 0x18 /* Lpback, rx, bypass error */
#define MII_PHYADDR 0x19 /* PHY address */
#define MII_RESV2 0x1a /* Reserved... */
#define MII_TPISTATUS 0x1b /* TPI status for 10mbps */
#define MII_NCONFIG 0x1c /* Network interface config */
/* Basic mode control register. */
#define BMCR_RESV 0x003f /* Unused... */
#define BMCR_SPEED1000 0x0040 /* MSB of Speed (1000) */
#define BMCR_CTST 0x0080 /* Collision test */
#define BMCR_FULLDPLX 0x0100 /* Full duplex */
#define BMCR_ANRESTART 0x0200 /* Auto negotiation restart */
#define BMCR_ISOLATE 0x0400 /* Disconnect DP83840 from MII */
#define BMCR_PDOWN 0x0800 /* Powerdown the DP83840 */
#define BMCR_ANENABLE 0x1000 /* Enable auto negotiation */
#define BMCR_SPEED100 0x2000 /* Select 100Mbps */
#define BMCR_LOOPBACK 0x4000 /* TXD loopback bits */
#define BMCR_RESET 0x8000 /* Reset the DP83840 */
/* Basic mode status register. */
#define BMSR_ERCAP 0x0001 /* Ext-reg capability */
#define BMSR_JCD 0x0002 /* Jabber detected */
#define BMSR_LSTATUS 0x0004 /* Link status */
#define BMSR_ANEGCAPABLE 0x0008 /* Able to do auto-negotiation */
#define BMSR_RFAULT 0x0010 /* Remote fault detected */
#define BMSR_ANEGCOMPLETE 0x0020 /* Auto-negotiation complete */
#define BMSR_RESV 0x00c0 /* Unused... */
#define BMSR_ESTATEN 0x0100 /* Extended Status in R15 */
#define BMSR_100HALF2 0x0200 /* Can do 100BASE-T2 HDX */
#define BMSR_100FULL2 0x0400 /* Can do 100BASE-T2 FDX */
#define BMSR_10HALF 0x0800 /* Can do 10mbps, half-duplex */
#define BMSR_10FULL 0x1000 /* Can do 10mbps, full-duplex */
#define BMSR_100HALF 0x2000 /* Can do 100mbps, half-duplex */
#define BMSR_100FULL 0x4000 /* Can do 100mbps, full-duplex */
#define BMSR_100BASE4 0x8000 /* Can do 100mbps, 4k packets */
#define AUTONEG_DISABLE 0x00
#define AUTONEG_ENABLE 0x01
#define MII_ADVERTISE 0x04 /* Advertisement control reg */
#define ADVERTISE_SLCT 0x001f /* Selector bits */
#define ADVERTISE_CSMA 0x0001 /* Only selector supported */
#define ADVERTISE_10HALF 0x0020 /* Try for 10mbps half-duplex */
#define ADVERTISE_1000XFULL 0x0020 /* Try for 1000BASE-X full-duplex */
#define ADVERTISE_10FULL 0x0040 /* Try for 10mbps full-duplex */
#define ADVERTISE_1000XHALF 0x0040 /* Try for 1000BASE-X half-duplex */
#define ADVERTISE_100HALF 0x0080 /* Try for 100mbps half-duplex */
#define <API key> 0x0080 /* Try for 1000BASE-X pause */
#define ADVERTISE_100FULL 0x0100 /* Try for 100mbps full-duplex */
#define <API key> 0x0100 /* Try for 1000BASE-X asym pause */
#define ADVERTISE_100BASE4 0x0200 /* Try for 100mbps 4k packets */
#define ADVERTISE_PAUSE_CAP 0x0400 /* Try for pause */
#define <API key> 0x0800 /* Try for asymetric pause */
#define ADVERTISE_RESV 0x1000 /* Unused... */
#define ADVERTISE_RFAULT 0x2000 /* Say we can detect faults */
#define ADVERTISE_LPACK 0x4000 /* Ack link partners response */
#define ADVERTISE_NPAGE 0x8000 /* Next page bit */
#define ADVERTISE_FULL (ADVERTISE_100FULL | ADVERTISE_10FULL | \
ADVERTISE_CSMA)
#define ADVERTISE_ALL (ADVERTISE_10HALF | ADVERTISE_10FULL | \
ADVERTISE_100HALF | ADVERTISE_100FULL)
/* 1000BASE-T Control register */
#define ADVERTISE_1000FULL 0x0200 /* Advertise 1000BASE-T full duplex */
#define ADVERTISE_1000HALF 0x0100 /* Advertise 1000BASE-T half duplex */
/* MAC address length */
#define MAC_ADDR_LEN 6
#define <API key> 12
#define RX_FIFO_THRESH 7 /* 7 means NO threshold, Rx buffer level before first PCI xfer. */
#define RX_DMA_BURST 6 /* Maximum PCI burst, '6' is 1024 */
#define TX_DMA_BURST 6 /* Maximum PCI burst, '6' is 1024 */
#define EarlyTxThld 0x3F /* 0x3F means NO early transmit */
#define RxPacketMaxSize 0x3FE8 /* 16K - 1 - ETH_HLEN - VLAN - CRC... */
#define SafeMtu 0x1c20 /* ... actually life sucks beyond ~7k */
#define InterFrameGap 0x03 /* 3 means InterFrameGap = the shortest one */
#define R8169_REGS_SIZE 256
#define R8169_NAPI_WEIGHT 64
#define NUM_TX_DESC 8 /* Number of Tx descriptor registers */
#define NUM_RX_DESC 8 /* Number of Rx descriptor registers */
#define RX_BUF_SIZE 1536 /* Rx Buffer size */
#define R8169_TX_RING_BYTES (NUM_TX_DESC * sizeof(struct TxDesc))
#define R8169_RX_RING_BYTES (NUM_RX_DESC * sizeof(struct RxDesc))
#define TX_RING_ALIGN 256
#define RX_RING_ALIGN 256
#define RTL8169_TX_TIMEOUT (6*HZ)
#define RTL8169_PHY_TIMEOUT (10*HZ)
#define RTL_EEPROM_SIG cpu_to_le32(0x8129)
#define RTL_EEPROM_SIG_MASK cpu_to_le32(0xffff)
#define RTL_EEPROM_SIG_ADDR 0x0000
/* write/read MMIO register */
#define RTL_W8(reg, val8) writeb ((val8), ioaddr + (reg))
#define RTL_W16(reg, val16) writew ((val16), ioaddr + (reg))
#define RTL_W32(reg, val32) writel ((val32), ioaddr + (reg))
#define RTL_R8(reg) readb (ioaddr + (reg))
#define RTL_R16(reg) readw (ioaddr + (reg))
#define RTL_R32(reg) ((unsigned long) readl (ioaddr + (reg)))
enum mac_version {
RTL_GIGA_MAC_VER_01 = 0x01, // 8169
RTL_GIGA_MAC_VER_02 = 0x02, // 8169S
RTL_GIGA_MAC_VER_03 = 0x03, // 8110S
RTL_GIGA_MAC_VER_04 = 0x04, // 8169SB
RTL_GIGA_MAC_VER_05 = 0x05, // 8110SCd
RTL_GIGA_MAC_VER_06 = 0x06, // 8110SCe
RTL_GIGA_MAC_VER_07 = 0x07, // 8102e
RTL_GIGA_MAC_VER_08 = 0x08, // 8102e
RTL_GIGA_MAC_VER_09 = 0x09, // 8102e
RTL_GIGA_MAC_VER_10 = 0x0a, // 8101e
RTL_GIGA_MAC_VER_11 = 0x0b, // 8168Bb
RTL_GIGA_MAC_VER_12 = 0x0c, // 8168Be
RTL_GIGA_MAC_VER_13 = 0x0d, // 8101Eb
RTL_GIGA_MAC_VER_14 = 0x0e, // 8101 ?
RTL_GIGA_MAC_VER_15 = 0x0f, // 8101 ?
RTL_GIGA_MAC_VER_16 = 0x11, // 8101Ec
RTL_GIGA_MAC_VER_17 = 0x10, // 8168Bf
RTL_GIGA_MAC_VER_18 = 0x12, // 8168CP
RTL_GIGA_MAC_VER_19 = 0x13, // 8168C
RTL_GIGA_MAC_VER_20 = 0x14, // 8168C
RTL_GIGA_MAC_VER_21 = 0x15, // 8168C
RTL_GIGA_MAC_VER_22 = 0x16, // 8168C
RTL_GIGA_MAC_VER_23 = 0x17, // 8168CP
RTL_GIGA_MAC_VER_24 = 0x18, // 8168CP
RTL_GIGA_MAC_VER_25 = 0x19, // 8168D
};
#define _R(NAME,MAC,MASK) \
{ .name = NAME, .mac_version = MAC, .RxConfigMask = MASK }
static const struct {
const char *name;
u8 mac_version;
u32 RxConfigMask; /* Clears the bits supported by this chip */
} rtl_chip_info[] = {
_R("RTL8169", RTL_GIGA_MAC_VER_01, 0xff7e1880), // 8169
_R("RTL8169s", RTL_GIGA_MAC_VER_02, 0xff7e1880), // 8169S
_R("RTL8110s", RTL_GIGA_MAC_VER_03, 0xff7e1880), // 8110S
_R("RTL8169sb/8110sb", RTL_GIGA_MAC_VER_04, 0xff7e1880), // 8169SB
_R("RTL8169sc/8110sc", RTL_GIGA_MAC_VER_05, 0xff7e1880), // 8110SCd
_R("RTL8169sc/8110sc", RTL_GIGA_MAC_VER_06, 0xff7e1880), // 8110SCe
_R("RTL8102e", RTL_GIGA_MAC_VER_07, 0xff7e1880), // PCI-E
_R("RTL8102e", RTL_GIGA_MAC_VER_08, 0xff7e1880), // PCI-E
_R("RTL8102e", RTL_GIGA_MAC_VER_09, 0xff7e1880), // PCI-E
_R("RTL8101e", RTL_GIGA_MAC_VER_10, 0xff7e1880), // PCI-E
_R("RTL8168b/8111b", RTL_GIGA_MAC_VER_11, 0xff7e1880), // PCI-E
_R("RTL8168b/8111b", RTL_GIGA_MAC_VER_12, 0xff7e1880), // PCI-E
_R("RTL8101e", RTL_GIGA_MAC_VER_13, 0xff7e1880), // PCI-E 8139
_R("RTL8100e", RTL_GIGA_MAC_VER_14, 0xff7e1880), // PCI-E 8139
_R("RTL8100e", RTL_GIGA_MAC_VER_15, 0xff7e1880), // PCI-E 8139
_R("RTL8168b/8111b", RTL_GIGA_MAC_VER_17, 0xff7e1880), // PCI-E
_R("RTL8101e", RTL_GIGA_MAC_VER_16, 0xff7e1880), // PCI-E
_R("RTL8168cp/8111cp", RTL_GIGA_MAC_VER_18, 0xff7e1880), // PCI-E
_R("RTL8168c/8111c", RTL_GIGA_MAC_VER_19, 0xff7e1880), // PCI-E
_R("RTL8168c/8111c", RTL_GIGA_MAC_VER_20, 0xff7e1880), // PCI-E
_R("RTL8168c/8111c", RTL_GIGA_MAC_VER_21, 0xff7e1880), // PCI-E
_R("RTL8168c/8111c", RTL_GIGA_MAC_VER_22, 0xff7e1880), // PCI-E
_R("RTL8168cp/8111cp", RTL_GIGA_MAC_VER_23, 0xff7e1880), // PCI-E
_R("RTL8168cp/8111cp", RTL_GIGA_MAC_VER_24, 0xff7e1880), // PCI-E
_R("RTL8168d/8111d", RTL_GIGA_MAC_VER_25, 0xff7e1880) // PCI-E
};
#undef _R
enum cfg_version {
RTL_CFG_0 = 0x00,
RTL_CFG_1,
RTL_CFG_2
};
#if 0
/** Device Table from Linux Driver **/
static struct pci_device_id rtl8169_pci_tbl[] = {
{ PCI_DEVICE(<API key>, 0x8129), 0, 0, RTL_CFG_0 },
{ PCI_DEVICE(<API key>, 0x8136), 0, 0, RTL_CFG_2 },
{ PCI_DEVICE(<API key>, 0x8167), 0, 0, RTL_CFG_0 },
{ PCI_DEVICE(<API key>, 0x8168), 0, 0, RTL_CFG_1 },
{ PCI_DEVICE(<API key>, 0x8169), 0, 0, RTL_CFG_0 },
{ PCI_DEVICE(PCI_VENDOR_ID_DLINK, 0x4300), 0, 0, RTL_CFG_0 },
{ PCI_DEVICE(PCI_VENDOR_ID_AT, 0xc107), 0, 0, RTL_CFG_0 },
{ PCI_DEVICE(0x16ec, 0x0116), 0, 0, RTL_CFG_0 },
{ <API key>, 0x1032,
PCI_ANY_ID, 0x0024, 0, 0, RTL_CFG_0 },
{ 0x0001, 0x8168,
PCI_ANY_ID, 0x2410, 0, 0, RTL_CFG_2 },
{0,},
};
#endif
enum rtl_registers {
MAC0 = 0, /* Ethernet hardware address. */
MAC4 = 4,
MAR0 = 8, /* Multicast filter. */
CounterAddrLow = 0x10,
CounterAddrHigh = 0x14,
TxDescStartAddrLow = 0x20,
TxDescStartAddrHigh = 0x24,
TxHDescStartAddrLow = 0x28,
<API key> = 0x2c,
FLASH = 0x30,
ERSR = 0x36,
ChipCmd = 0x37,
TxPoll = 0x38,
IntrMask = 0x3c,
IntrStatus = 0x3e,
TxConfig = 0x40,
RxConfig = 0x44,
RxMissed = 0x4c,
Cfg9346 = 0x50,
Config0 = 0x51,
Config1 = 0x52,
Config2 = 0x53,
Config3 = 0x54,
Config4 = 0x55,
Config5 = 0x56,
MultiIntr = 0x5c,
PHYAR = 0x60,
PHYstatus = 0x6c,
RxMaxSize = 0xda,
CPlusCmd = 0xe0,
IntrMitigate = 0xe2,
RxDescAddrLow = 0xe4,
RxDescAddrHigh = 0xe8,
EarlyTxThres = 0xec,
FuncEvent = 0xf0,
FuncEventMask = 0xf4,
FuncPresetState = 0xf8,
FuncForceEvent = 0xfc,
};
enum rtl8110_registers {
TBICSR = 0x64,
TBI_ANAR = 0x68,
TBI_LPAR = 0x6a,
};
enum <API key> {
CSIDR = 0x64,
CSIAR = 0x68,
#define CSIAR_FLAG 0x80000000
#define CSIAR_WRITE_CMD 0x80000000
#define CSIAR_BYTE_ENABLE 0x0f
#define <API key> 12
#define CSIAR_ADDR_MASK 0x0fff
EPHYAR = 0x80,
#define EPHYAR_FLAG 0x80000000
#define EPHYAR_WRITE_CMD 0x80000000
#define EPHYAR_REG_MASK 0x1f
#define EPHYAR_REG_SHIFT 16
#define EPHYAR_DATA_MASK 0xffff
DBG_REG = 0xd1,
#define FIX_NAK_1 (1 << 4)
#define FIX_NAK_2 (1 << 3)
};
enum <API key> {
/* InterruptStatusBits */
SYSErr = 0x8000,
PCSTimeout = 0x4000,
SWInt = 0x0100,
TxDescUnavail = 0x0080,
RxFIFOOver = 0x0040,
LinkChg = 0x0020,
RxOverflow = 0x0010,
TxErr = 0x0008,
TxOK = 0x0004,
RxErr = 0x0002,
RxOK = 0x0001,
/* RxStatusDesc */
RxFOVF = (1 << 23),
RxRWT = (1 << 22),
RxRES = (1 << 21),
RxRUNT = (1 << 20),
RxCRC = (1 << 19),
/* ChipCmdBits */
CmdReset = 0x10,
CmdRxEnb = 0x08,
CmdTxEnb = 0x04,
RxBufEmpty = 0x01,
/* TXPoll register p.5 */
HPQ = 0x80, /* Poll cmd on the high prio queue */
NPQ = 0x40, /* Poll cmd on the low prio queue */
FSWInt = 0x01, /* Forced software interrupt */
/* Cfg9346Bits */
Cfg9346_Lock = 0x00,
Cfg9346_Unlock = 0xc0,
/* rx_mode_bits */
AcceptErr = 0x20,
AcceptRunt = 0x10,
AcceptBroadcast = 0x08,
AcceptMulticast = 0x04,
AcceptMyPhys = 0x02,
AcceptAllPhys = 0x01,
/* RxConfigBits */
RxCfgFIFOShift = 13,
RxCfgDMAShift = 8,
/* TxConfigBits */
<API key> = 24,
TxDMAShift = 8, /* DMA burst value (0-7) is shift this many bits */
/* Config1 register p.24 */
LEDS1 = (1 << 7),
LEDS0 = (1 << 6),
MSIEnable = (1 << 5), /* Enable Message Signaled Interrupt */
Speed_down = (1 << 4),
MEMMAP = (1 << 3),
IOMAP = (1 << 2),
VPD = (1 << 1),
PMEnable = (1 << 0), /* Power Management Enable */
/* Config2 register p. 25 */
PCI_Clock_66MHz = 0x01,
PCI_Clock_33MHz = 0x00,
/* Config3 register p.25 */
MagicPacket = (1 << 5), /* Wake up when receives a Magic Packet */
LinkUp = (1 << 4), /* Wake up when the cable connection is re-established */
Beacon_en = (1 << 0), /* 8168 only. Reserved in the 8168b */
/* Config5 register p.27 */
BWF = (1 << 6), /* Accept Broadcast wakeup frame */
MWF = (1 << 5), /* Accept Multicast wakeup frame */
UWF = (1 << 4), /* Accept Unicast wakeup frame */
LanWake = (1 << 1), /* LanWake enable/disable */
PMEStatus = (1 << 0), /* PME status can be reset by PCI RST# */
/* TBICSR p.28 */
TBIReset = 0x80000000,
TBILoopback = 0x40000000,
TBINwEnable = 0x20000000,
TBINwRestart = 0x10000000,
TBILinkOk = 0x02000000,
TBINwComplete = 0x01000000,
/* CPlusCmd p.31 */
EnableBist = (1 << 15), // 8168 8101
Mac_dbgo_oe = (1 << 14), // 8168 8101
Normal_mode = (1 << 13), // unused
Force_half_dup = (1 << 12), // 8168 8101
Force_rxflow_en = (1 << 11), // 8168 8101
Force_txflow_en = (1 << 10), // 8168 8101
Cxpl_dbg_sel = (1 << 9), // 8168 8101
ASF = (1 << 8), // 8168 8101
PktCntrDisable = (1 << 7), // 8168 8101
Mac_dbgo_sel = 0x001c, // 8168
RxVlan = (1 << 6),
RxChkSum = (1 << 5),
PCIDAC = (1 << 4),
PCIMulRW = (1 << 3),
INTT_0 = 0x0000, // 8168
INTT_1 = 0x0001, // 8168
INTT_2 = 0x0002, // 8168
INTT_3 = 0x0003, // 8168
/* rtl8169_PHYstatus */
TBI_Enable = 0x80,
TxFlowCtrl = 0x40,
RxFlowCtrl = 0x20,
_1000bpsF = 0x10,
_100bps = 0x08,
_10bps = 0x04,
LinkStatus = 0x02,
FullDup = 0x01,
/* _TBICSRBit */
TBILinkOK = 0x02000000,
/* DumpCounterCommand */
CounterDump = 0x8,
};
enum desc_status_bit {
DescOwn = (1 << 31), /* Descriptor is owned by NIC */
RingEnd = (1 << 30), /* End of descriptor ring */
FirstFrag = (1 << 29), /* First segment of a packet */
LastFrag = (1 << 28), /* Final segment of a packet */
/* Tx private */
LargeSend = (1 << 27), /* TCP Large Send Offload (TSO) */
MSSShift = 16, /* MSS value position */
MSSMask = 0xfff, /* MSS value + LargeSend bit: 12 bits */
IPCS = (1 << 18), /* Calculate IP checksum */
UDPCS = (1 << 17), /* Calculate UDP/IP checksum */
TCPCS = (1 << 16), /* Calculate TCP/IP checksum */
TxVlanTag = (1 << 17), /* Add VLAN tag */
/* Rx private */
PID1 = (1 << 18), /* Protocol ID bit 1/2 */
PID0 = (1 << 17), /* Protocol ID bit 2/2 */
#define RxProtoUDP (PID1)
#define RxProtoTCP (PID0)
#define RxProtoIP (PID1 | PID0)
#define RxProtoMask RxProtoIP
IPFail = (1 << 16), /* IP checksum failed */
UDPFail = (1 << 15), /* UDP/IP checksum failed */
TCPFail = (1 << 14), /* TCP/IP checksum failed */
RxVlanTag = (1 << 16), /* VLAN tag available */
};
#define RsvdMask 0x3fffc000
struct TxDesc {
volatile uint32_t opts1;
volatile uint32_t opts2;
volatile uint32_t addr_lo;
volatile uint32_t addr_hi;
};
struct RxDesc {
volatile uint32_t opts1;
volatile uint32_t opts2;
volatile uint32_t addr_lo;
volatile uint32_t addr_hi;
};
enum features {
RTL_FEATURE_WOL = (1 << 0),
RTL_FEATURE_MSI = (1 << 1),
RTL_FEATURE_GMII = (1 << 2),
};
static void rtl_hw_start_8169(struct net_device *);
static void rtl_hw_start_8168(struct net_device *);
static void rtl_hw_start_8101(struct net_device *);
struct rtl8169_private {
struct pci_device *pci_dev;
struct net_device *netdev;
uint8_t *hw_addr;
void *mmio_addr;
uint32_t irqno;
int chipset;
int mac_version;
int cfg_index;
u16 intr_event;
struct io_buffer *tx_iobuf[NUM_TX_DESC];
struct io_buffer *rx_iobuf[NUM_RX_DESC];
struct TxDesc *tx_base;
struct RxDesc *rx_base;
uint32_t tx_curr;
uint32_t rx_curr;
uint32_t tx_tail;
uint32_t tx_fill_ctr;
u16 cp_cmd;
int phy_auto_nego_reg;
int phy_1000_ctrl_reg;
int ( *set_speed ) (struct net_device *, u8 autoneg, u16 speed, u8 duplex );
void ( *phy_reset_enable ) ( void *ioaddr );
void ( *hw_start ) ( struct net_device * );
unsigned int ( *phy_reset_pending ) ( void *ioaddr );
unsigned int ( *link_ok ) ( void *ioaddr );
int pcie_cap;
unsigned features;
};
static const unsigned int rtl8169_rx_config =
(RX_FIFO_THRESH << RxCfgFIFOShift) | (RX_DMA_BURST << RxCfgDMAShift);
#endif /* _R8169_H_ */
/*
* Local variables:
* c-basic-offset: 8
* c-indent-level: 8
* tab-width: 8
* End:
*/ |
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <errno.h>
#include "posixtest.h"
#define INTERVAL 1
#define TIMEOUT 5
struct testdata {
pthread_mutex_t mutex;
pthread_cond_t cond;
} td;
int t1_start = 0;
int signaled = 0;
void *t1_func(void *arg)
{
int rc;
struct timespec timeout;
struct timeval curtime;
(void) arg;
if (pthread_mutex_lock(&td.mutex) != 0) {
fprintf(stderr, "Thread1 failed to acquire the mutex\n");
exit(PTS_UNRESOLVED);
}
fprintf(stderr, "Thread1 started\n");
t1_start = 1; /* let main thread continue */
if (gettimeofday(&curtime, NULL) != 0) {
fprintf(stderr, "Fail to get current time\n");
exit(PTS_UNRESOLVED);
}
timeout.tv_sec = curtime.tv_sec + TIMEOUT;
timeout.tv_nsec = curtime.tv_usec * 1000;
fprintf(stderr, "Thread1 is waiting for the cond\n");
rc = <API key>(&td.cond, &td.mutex, &timeout);
if (rc != 0) {
if (rc == ETIMEDOUT) {
fprintf(stderr,
"Thread1 stops waiting when time is out\n");
exit(PTS_UNRESOLVED);
} else {
fprintf(stderr, "<API key> return %d\n",
rc);
printf("Test FAILED\n");
exit(PTS_FAIL);
}
}
if (signaled == 0) {
fprintf(stderr, "Thread1 did not block on the cond at all\n");
exit(PTS_UNRESOLVED);
}
fprintf(stderr, "Thread1 wakened and got returned value 0\n");
if (<API key>(&td.mutex) != 0) {
fprintf(stderr, "Thread1 failed to release the mutex\n");
exit(PTS_UNRESOLVED);
}
fprintf(stderr, "Thread1 released the mutex\n");
return NULL;
}
int main(void)
{
pthread_t thread1;
struct timespec thread_start_ts = {0, 100000};
if (pthread_mutex_init(&td.mutex, NULL) != 0) {
fprintf(stderr, "Fail to initialize mutex\n");
return PTS_UNRESOLVED;
}
if (pthread_cond_init(&td.cond, NULL) != 0) {
fprintf(stderr, "Fail to initialize cond\n");
return PTS_UNRESOLVED;
}
if (pthread_create(&thread1, NULL, t1_func, NULL) != 0) {
fprintf(stderr, "Fail to create thread 1\n");
return PTS_UNRESOLVED;
}
while (!t1_start) /* wait for thread1 started */
nanosleep(&thread_start_ts, NULL);
/* acquire the mutex released by pthread_cond_wait() within thread 1 */
if (pthread_mutex_lock(&td.mutex) != 0) {
fprintf(stderr, "Main failed to acquire mutex\n");
return PTS_UNRESOLVED;
}
if (<API key>(&td.mutex) != 0) {
fprintf(stderr, "Main failed to release mutex\n");
return PTS_UNRESOLVED;
}
sleep(INTERVAL);
fprintf(stderr, "Time to wake up thread1 by signaling a condition\n");
signaled = 1;
if (pthread_cond_signal(&td.cond) != 0) {
fprintf(stderr, "Main failed to signal the condition\n");
return PTS_UNRESOLVED;
}
pthread_join(thread1, NULL);
printf("Test PASSED\n");
return PTS_PASS;
} |
#include "otpch.h"
#include <csignal>
#include "signals.h"
#include "tasks.h"
#include "game.h"
#include "actions.h"
#include "configmanager.h"
#include "spells.h"
#include "talkaction.h"
#include "movement.h"
#include "weapons.h"
#include "raids.h"
#include "quests.h"
#include "mounts.h"
#include "globalevent.h"
#include "monster.h"
#include "events.h"
extern Dispatcher g_dispatcher;
extern ConfigManager g_config;
extern Actions* g_actions;
extern Monsters g_monsters;
extern TalkActions* g_talkActions;
extern MoveEvents* g_moveEvents;
extern Spells* g_spells;
extern Weapons* g_weapons;
extern Game g_game;
extern CreatureEvents* g_creatureEvents;
extern GlobalEvents* g_globalEvents;
extern Events* g_events;
extern Chat* g_chat;
extern LuaEnvironment g_luaEnvironment;
using ErrorCode = boost::system::error_code;
Signals::Signals(boost::asio::io_service& service) :
set(service)
{
set.add(SIGINT);
set.add(SIGTERM);
#ifndef _WIN32
set.add(SIGUSR1);
set.add(SIGHUP);
#endif
asyncWait();
}
void Signals::asyncWait()
{
set.async_wait([this] (ErrorCode err, int signal) {
if (err) {
std::cerr << "Signal handling error: " << err.message() << std::endl;
return;
}
<API key>(signal);
asyncWait();
});
}
void Signals::<API key>(int signal)
{
switch(signal) {
case SIGINT: //Shuts the server down
g_dispatcher.addTask(createTask(sigintHandler));
break;
case SIGTERM: //Shuts the server down
g_dispatcher.addTask(createTask(sigtermHandler));
break;
#ifndef _WIN32
case SIGHUP: //Reload config/data
g_dispatcher.addTask(createTask(sighupHandler));
break;
case SIGUSR1: //Saves game state
g_dispatcher.addTask(createTask(sigusr1Handler));
break;
#endif
default:
break;
}
}
void Signals::sigtermHandler()
{
//Dispatcher thread
std::cout << "SIGTERM received, shutting game server down..." << std::endl;
g_game.setGameState(GAME_STATE_SHUTDOWN);
}
void Signals::sigusr1Handler()
{
//Dispatcher thread
std::cout << "SIGUSR1 received, saving the game state..." << std::endl;
g_game.saveGameState();
}
void Signals::sighupHandler()
{
//Dispatcher thread
std::cout << "SIGHUP received, reloading config files..." << std::endl;
g_actions->reload();
std::cout << "Reloaded actions." << std::endl;
g_config.reload();
std::cout << "Reloaded config." << std::endl;
g_game.reloadCommands();
std::cout << "Reloaded commands." << std::endl;
g_creatureEvents->reload();
std::cout << "Reloaded creature scripts." << std::endl;
g_moveEvents->reload();
std::cout << "Reloaded movements." << std::endl;
Npcs::reload();
std::cout << "Reloaded npcs." << std::endl;
g_game.raids.reload();
g_game.raids.startup();
std::cout << "Reloaded raids." << std::endl;
g_spells->reload();
std::cout << "Reloaded monsters." << std::endl;
g_monsters.reload();
std::cout << "Reloaded spells." << std::endl;
g_talkActions->reload();
std::cout << "Reloaded talk actions." << std::endl;
Item::items.reload();
std::cout << "Reloaded items." << std::endl;
g_weapons->reload();
g_weapons->loadDefaults();
std::cout << "Reloaded weapons." << std::endl;
g_game.quests.reload();
std::cout << "Reloaded quests." << std::endl;
g_game.mounts.reload();
std::cout << "Reloaded mounts." << std::endl;
g_globalEvents->reload();
std::cout << "Reloaded globalevents." << std::endl;
g_events->load();
std::cout << "Reloaded events." << std::endl;
g_chat->load();
std::cout << "Reloaded chatchannels." << std::endl;
g_luaEnvironment.loadFile("data/global.lua");
std::cout << "Reloaded global.lua." << std::endl;
lua_gc(g_luaEnvironment.getLuaState(), LUA_GCCOLLECT, 0);
}
void Signals::sigintHandler()
{
//Dispatcher thread
std::cout << "SIGINT received, shutting game server down..." << std::endl;
g_game.setGameState(GAME_STATE_SHUTDOWN);
} |
package com.oracle.graal.replacements;
import com.oracle.graal.api.replacements.<API key>;
import com.oracle.graal.compiler.common.spi.<API key>;
import com.oracle.graal.compiler.common.type.Stamp;
import com.oracle.graal.compiler.common.type.StampFactory;
import com.oracle.graal.compiler.common.type.TypeReference;
import com.oracle.graal.debug.GraalError;
import com.oracle.graal.nodes.graphbuilderconf.<API key>.InjectionProvider;
import com.oracle.graal.word.WordTypes;
import jdk.vm.ci.meta.JavaKind;
import jdk.vm.ci.meta.MetaAccessProvider;
import jdk.vm.ci.meta.ResolvedJavaType;
public class <API key> implements InjectionProvider {
private final MetaAccessProvider metaAccess;
private final <API key> snippetReflection;
private final <API key> foreignCalls;
private final WordTypes wordTypes;
public <API key>(MetaAccessProvider metaAccess, <API key> snippetReflection, <API key> foreignCalls, WordTypes wordTypes) {
this.metaAccess = metaAccess;
this.snippetReflection = snippetReflection;
this.foreignCalls = foreignCalls;
this.wordTypes = wordTypes;
}
@Override
public Stamp getReturnStamp(Class<?> type, boolean nonNull) {
JavaKind kind = JavaKind.fromJavaClass(type);
if (kind == JavaKind.Object) {
ResolvedJavaType returnType = metaAccess.lookupJavaType(type);
if (wordTypes.isWord(returnType)) {
return wordTypes.getWordStamp(returnType);
} else {
return StampFactory.object(TypeReference.<API key>(returnType), nonNull);
}
} else {
return StampFactory.forKind(kind);
}
}
@Override
public <T> T getInjectedArgument(Class<T> type) {
T injected = snippetReflection.<API key>(type);
if (injected != null) {
return injected;
} else if (type.equals(<API key>.class)) {
return type.cast(foreignCalls);
} else if (type.equals(<API key>.class)) {
return type.cast(snippetReflection);
} else {
throw new GraalError("Cannot handle injected argument of type %s.", type.getName());
}
}
} |
/* ScriptData
SDName: Argent Challenge Encounter.
SD%Complete: 50 %
SDComment: AI for Argent Soldiers are not implemented. AI from bosses need more improvements.
SDCategory: Trial of the Champion
EndScriptData */
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "SpellScript.h"
#include "<API key>.h"
#include "ScriptedEscortAI.h"
/*
enum Yells
{
// Eadric the Pure
SAY_INTRO = 0,
SAY_AGGRO = 1,
EMOTE_RADIANCE = 2,
<API key> = 3,
<API key> = 4,
SAY_KILL_PLAYER = 5,
SAY_DEFEATED = 6,
// Argent Confessor Paletress
SAY_INTRO_1 = 0,
SAY_INTRO_2 = 1,
SAY_AGGRO = 2,
SAY_MEMORY_SUMMON = 3,
SAY_MEMORY_DEATH = 4,
SAY_KILL_PLAYER = 5,
SAY_DEFEATED = 6,
// Memory of X
<API key> = 0
};
*/
enum Spells
{
// Eadric the Pure
<API key> = 68197,
<API key> = 66863,
<API key> = 66867,
SPELL_RADIANCE = 66935,
SPELL_VENGEANCE = 66865,
//Paletress
SPELL_SMITE = 66536,
SPELL_SMITE_H = 67674,
SPELL_HOLY_FIRE = 66538,
SPELL_HOLY_FIRE_H = 67676,
SPELL_RENEW = 66537,
SPELL_RENEW_H = 67675,
SPELL_HOLY_NOVA = 66546,
SPELL_SHIELD = 66515,
SPELL_CONFESS = 66680,
SPELL_SUMMON_MEMORY = 66545,
//Memory
SPELL_OLD_WOUNDS = 66620,
SPELL_OLD_WOUNDS_H = 67679,
SPELL_SHADOWS_PAST = 66619,
<API key> = 67678,
<API key> = 66552,
<API key> = 67677
};
class OrientationCheck : public std::unary_function<Unit*, bool>
{
public:
explicit OrientationCheck(Unit* _caster) : caster(_caster) { }
bool operator()(WorldObject* object)
{
return !object->isInFront(caster, 2.5f) || !object->IsWithinDist(caster, 40.0f);
}
private:
Unit* caster;
};
class <API key> : public SpellScriptLoader
{
public:
<API key>() : SpellScriptLoader("<API key>") { }
class <API key> : public SpellScript
{
PrepareSpellScript(<API key>);
void FilterTargets(std::list<WorldObject*>& unitList)
{
unitList.remove_if(OrientationCheck(GetCaster()));
}
void Register()
{
<API key> += <API key>(<API key>::FilterTargets, EFFECT_0, <API key>);
<API key> += <API key>(<API key>::FilterTargets, EFFECT_1, <API key>);
}
};
SpellScript* GetSpellScript() const
{
return new <API key>();
}
};
class boss_eadric : public CreatureScript
{
public:
boss_eadric() : CreatureScript("boss_eadric") { }
struct boss_eadricAI : public ScriptedAI
{
boss_eadricAI(Creature* creature) : ScriptedAI(creature)
{
instance = creature->GetInstanceScript();
creature->SetReactState(REACT_PASSIVE);
creature->SetFlag(UNIT_FIELD_FLAGS, <API key>);
}
InstanceScript* instance;
uint32 uiVenganceTimer;
uint32 uiRadianceTimer;
uint32 <API key>;
uint32 uiResetTimer;
bool bDone;
void Reset()
{
uiVenganceTimer = 10000;
uiRadianceTimer = 16000;
<API key> = 25000;
uiResetTimer = 5000;
bDone = false;
}
void DamageTaken(Unit* /*done_by*/, uint32 &damage)
{
if (damage >= me->GetHealth())
{
damage = 0;
EnterEvadeMode();
me->setFaction(35);
bDone = true;
}
}
void MovementInform(uint32 MovementType, uint32 /*Data*/)
{
if (MovementType != POINT_MOTION_TYPE)
return;
if (instance)
instance->SetData(<API key>, DONE);
me->DisappearAndDie();
}
void UpdateAI(const uint32 uiDiff)
{
if (bDone && uiResetTimer <= uiDiff)
{
me->GetMotionMaster()->MovePoint(0, 746.87f, 665.87f, 411.75f);
bDone = false;
} else uiResetTimer -= uiDiff;
if (!UpdateVictim())
return;
if (<API key> <= uiDiff)
{
me-><API key>(true);
if (Unit* target = SelectTarget(<API key>, 0, 250, true))
{
if (target && target->isAlive())
{
DoCast(target, <API key>);
DoCast(target, <API key>);
}
}
<API key> = 25000;
} else <API key> -= uiDiff;
if (uiVenganceTimer <= uiDiff)
{
DoCast(me, SPELL_VENGEANCE);
uiVenganceTimer = 10000;
} else uiVenganceTimer -= uiDiff;
if (uiRadianceTimer <= uiDiff)
{
DoCastAOE(SPELL_RADIANCE);
uiRadianceTimer = 16000;
} else uiRadianceTimer -= uiDiff;
<API key>();
}
};
CreatureAI* GetAI(Creature* creature) const
{
return new boss_eadricAI(creature);
}
};
class boss_paletress : public CreatureScript
{
public:
boss_paletress() : CreatureScript("boss_paletress") { }
struct boss_paletressAI : public ScriptedAI
{
boss_paletressAI(Creature* creature) : ScriptedAI(creature)
{
instance = creature->GetInstanceScript();
MemoryGUID = 0;
creature->SetReactState(REACT_PASSIVE);
creature->SetFlag(UNIT_FIELD_FLAGS, <API key>);
creature->RestoreFaction();
}
InstanceScript* instance;
uint64 MemoryGUID;
bool bHealth;
bool bDone;
uint32 uiHolyFireTimer;
uint32 uiHolySmiteTimer;
uint32 uiRenewTimer;
uint32 uiResetTimer;
void Reset()
{
me->RemoveAllAuras();
uiHolyFireTimer = urand(9000, 12000);
uiHolySmiteTimer = urand(5000, 7000);
uiRenewTimer = urand(2000, 5000);
uiResetTimer = 7000;
bHealth = false;
bDone = false;
if (Creature* pMemory = Unit::GetCreature(*me, MemoryGUID))
if (pMemory->isAlive())
pMemory->RemoveFromWorld();
}
void SetData(uint32 uiId, uint32 /*uiValue*/)
{
if (uiId == 1)
me->RemoveAura(SPELL_SHIELD);
}
void DamageTaken(Unit* /*done_by*/, uint32 &damage)
{
if (damage >= me->GetHealth())
{
damage = 0;
EnterEvadeMode();
me->setFaction(35);
bDone = true;
}
}
void MovementInform(uint32 MovementType, uint32 Point)
{
if (MovementType != POINT_MOTION_TYPE || Point != 0)
return;
if (instance)
instance->SetData(<API key>, DONE);
me->DisappearAndDie();
}
void UpdateAI(const uint32 uiDiff)
{
if (bDone && uiResetTimer <= uiDiff)
{
me->GetMotionMaster()->MovePoint(0, 746.87f, 665.87f, 411.75f);
bDone = false;
} else uiResetTimer -= uiDiff;
if (!UpdateVictim())
return;
if (uiHolyFireTimer <= uiDiff)
{
if (Unit* target = SelectTarget(<API key>, 0, 250, true))
{
if (target && target->isAlive())
DoCast(target, SPELL_HOLY_FIRE);
}
if (me->HasAura(SPELL_SHIELD))
uiHolyFireTimer = 13000;
else
uiHolyFireTimer = urand(9000, 12000);
} else uiHolyFireTimer -= uiDiff;
if (uiHolySmiteTimer <= uiDiff)
{
if (Unit* target = SelectTarget(<API key>, 0, 250, true))
{
if (target && target->isAlive())
DoCast(target, SPELL_SMITE);
}
if (me->HasAura(SPELL_SHIELD))
uiHolySmiteTimer = 9000;
else
uiHolySmiteTimer = urand(5000, 7000);
} else uiHolySmiteTimer -= uiDiff;
if (me->HasAura(SPELL_SHIELD))
{
if (uiRenewTimer <= uiDiff)
{
me-><API key>(true);
uint8 uiTarget = urand(0, 1);
switch (uiTarget)
{
case 0:
DoCast(me, SPELL_RENEW);
break;
case 1:
if (Creature* pMemory = Unit::GetCreature(*me, MemoryGUID))
if (pMemory->isAlive())
DoCast(pMemory, SPELL_RENEW);
break;
}
uiRenewTimer = urand(15000, 17000);
} else uiRenewTimer -= uiDiff;
}
if (!bHealth && !HealthAbovePct(25))
{
me-><API key>(true);
DoCastAOE(SPELL_HOLY_NOVA, false);
DoCast(me, SPELL_SHIELD);
DoCastAOE(SPELL_SUMMON_MEMORY, false);
DoCastAOE(SPELL_CONFESS, false);
bHealth = true;
}
<API key>();
}
void JustSummoned(Creature* summon)
{
MemoryGUID = summon->GetGUID();
}
};
CreatureAI* GetAI(Creature* creature) const
{
return new boss_paletressAI(creature);
}
};
class npc_memory : public CreatureScript
{
public:
npc_memory() : CreatureScript("npc_memory") { }
struct npc_memoryAI : public ScriptedAI
{
npc_memoryAI(Creature* creature) : ScriptedAI(creature) {}
uint32 uiOldWoundsTimer;
uint32 uiShadowPastTimer;
uint32 uiWakingNightmare;
void Reset()
{
uiOldWoundsTimer = 12000;
uiShadowPastTimer = 5000;
uiWakingNightmare = 7000;
}
void UpdateAI(const uint32 uiDiff)
{
if (!UpdateVictim())
return;
if (uiOldWoundsTimer <= uiDiff)
{
if (Unit* target = SelectTarget(<API key>, 0))
{
if (target && target->isAlive())
DoCast(target, SPELL_OLD_WOUNDS);
}
uiOldWoundsTimer = 12000;
}else uiOldWoundsTimer -= uiDiff;
if (uiWakingNightmare <= uiDiff)
{
DoCast(me, <API key>);
uiWakingNightmare = 7000;
}else uiWakingNightmare -= uiDiff;
if (uiShadowPastTimer <= uiDiff)
{
if (Unit* target = SelectTarget(<API key>, 1))
{
if (target && target->isAlive())
DoCast(target, SPELL_SHADOWS_PAST);
}
uiShadowPastTimer = 5000;
}else uiShadowPastTimer -= uiDiff;
<API key>();
}
void JustDied(Unit* /*killer*/)
{
if (TempSummon* summ = me->ToTempSummon())
if (Unit* summoner = summ->GetSummoner())
if (summoner->isAlive())
summoner->GetAI()->SetData(1, 0);
}
};
CreatureAI* GetAI(Creature* creature) const
{
return new npc_memoryAI(creature);
}
};
class npc_argent_soldier : public CreatureScript
{
public:
npc_argent_soldier() : CreatureScript("npc_argent_soldier") { }
// THIS AI NEEDS MORE IMPROVEMENTS
struct <API key> : public npc_escortAI
{
<API key>(Creature* creature) : npc_escortAI(creature)
{
instance = creature->GetInstanceScript();
me->SetReactState(REACT_DEFENSIVE);
SetDespawnAtEnd(false);
uiWaypoint = 0;
}
InstanceScript* instance;
uint8 uiWaypoint;
void WaypointReached(uint32 waypointId)
{
if (waypointId == 0)
{
switch (uiWaypoint)
{
case 0:
me->SetFacingTo(5.81f);
break;
case 1:
me->SetFacingTo(4.60f);
break;
case 2:
me->SetFacingTo(2.79f);
break;
}
}
}
void SetData(uint32 uiType, uint32 /*uiData*/)
{
switch (me->GetEntry())
{
case <API key>:
switch (uiType)
{
case 0:
AddWaypoint(0, 712.14f, 628.42f, 411.88f);
break;
case 1:
AddWaypoint(0, 742.44f, 650.29f, 411.79f);
break;
case 2:
AddWaypoint(0, 783.33f, 615.29f, 411.84f);
break;
}
break;
case NPC_ARGENT_MONK:
switch (uiType)
{
case 0:
AddWaypoint(0, 713.12f, 632.97f, 411.90f);
break;
case 1:
AddWaypoint(0, 746.73f, 650.24f, 411.56f);
break;
case 2:
AddWaypoint(0, 781.32f, 610.54f, 411.82f);
break;
}
break;
case NPC_PRIESTESS:
switch (uiType)
{
case 0:
AddWaypoint(0, 715.06f, 637.07f, 411.91f);
break;
case 1:
AddWaypoint(0, 750.72f, 650.20f, 411.77f);
break;
case 2:
AddWaypoint(0, 779.77f, 607.03f, 411.81f);
break;
}
break;
}
Start(false, true, 0);
uiWaypoint = uiType;
}
void UpdateAI(const uint32 uiDiff)
{
npc_escortAI::UpdateAI(uiDiff);
if (!UpdateVictim())
return;
<API key>();
}
void JustDied(Unit* /*killer*/)
{
if (instance)
instance->SetData(<API key>, instance->GetData(<API key>) + 1);
}
};
CreatureAI* GetAI(Creature* creature) const
{
return new <API key>(creature);
}
};
void <API key>()
{
new boss_eadric();
new <API key>();
new boss_paletress();
new npc_memory();
new npc_argent_soldier();
} |
#include "<API key>.h"
#include "DataKey.h"
#include "Document.h"
#include "DocumentSerialize.h"
#include "EngaugeAssert.h"
#include "Logger.h"
#include "MainWindow.h"
#include <QApplication>
#include <QClipboard>
#include <QTextStream>
#include "QtToString.h"
#include <QXmlStreamReader>
#include "Xml.h"
const QString CMD_DESCRIPTION ("Select Coordinate System");
<API key>::<API key>(MainWindow &mainWindow,
Document &document,
CoordSystemIndex coordSystemIndex) :
CmdAbstract(mainWindow,
document,
CMD_DESCRIPTION),
<API key> (document.coordSystemIndex()),
<API key> (coordSystemIndex)
{
LOG4CPP_INFO_S ((*mainCat)) << "<API key>::<API key>";
}
<API key>::<API key> (MainWindow &mainWindow,
Document &document,
const QString &cmdDescription,
QXmlStreamReader &reader) :
CmdAbstract (mainWindow,
document,
cmdDescription)
{
LOG4CPP_INFO_S ((*mainCat)) << "<API key>::<API key>";
<API key> attributes = reader.attributes();
QStringList <API key>;
<API key> << <API key>
<< <API key>;
<API key> (attributes,
<API key>,
reader);
<API key> = attributes.value(<API key>).toInt ();
<API key> = attributes.value(<API key>).toInt ();
}
<API key>::~<API key> ()
{
}
void <API key>::cmdRedo ()
{
LOG4CPP_INFO_S ((*mainCat)) << "<API key>::cmdRedo"
<< " index=" << <API key> << "->" << <API key>;
restoreState ();
<API key> (document ());
mainWindow().updateCoordSystem (<API key>);
<API key> (document ());
}
void <API key>::cmdUndo ()
{
LOG4CPP_INFO_S ((*mainCat)) << "<API key>::cmdUndo"
<< " index=" << <API key> << "->" << <API key>;
restoreState ();
<API key> (document ());
mainWindow().updateCoordSystem (<API key>);
<API key> (document ());
}
void <API key>::saveXml (QXmlStreamWriter &writer) const
{
writer.writeStartElement(<API key>);
writer.writeAttribute(<API key>, <API key>);
writer.writeAttribute(<API key>, QUndoCommand::text ());
writer.writeAttribute(<API key>, QString::number (<API key>));
writer.writeAttribute(<API key>, QString::number (<API key>));
baseAttributes (writer);
writer.writeEndElement();
} |
<?php
class <API key> {
// Events //
// Constants //
// Variables //
// Constructor & Destructor //
public function __construct() {
}
// Public Methods //
public function get_theme_row_data($id) {
global $wpdb;
$row = $wpdb->get_row($wpdb->prepare('SELECT * FROM ' . $wpdb->prefix . 'bwg_theme WHERE id="%d"', $id));
return $row;
}
public function <API key>($id) {
global $wpdb;
$row = $wpdb->get_row($wpdb->prepare('SELECT * FROM ' . $wpdb->prefix . 'bwg_gallery WHERE published=1 AND id="%d"', $id));
return $row;
}
public function get_image_rows_data($id, $images_per_page, $sort_by, $bwg) {
global $wpdb;
if ($sort_by == 'size' || $sort_by == 'resolution') {
$sort_by = ' CAST(' . $sort_by . ' AS SIGNED) ';
}
elseif (($sort_by != 'alt') && ($sort_by != 'date') && ($sort_by != 'filetype')) {
$sort_by = '`order`';
}
if (isset($_POST['page_number_' . $bwg]) && $_POST['page_number_' . $bwg]) {
$limit = ((int) $_POST['page_number_' . $bwg] - 1) * $images_per_page;
}
else {
$limit = 0;
}
if ($images_per_page) {
$limit_str = 'LIMIT ' . $limit . ',' . $images_per_page;
}
else {
$limit_str = '';
}
$row = $wpdb->get_results($wpdb->prepare('SELECT * FROM ' . $wpdb->prefix . 'bwg_image WHERE published=1 AND gallery_id="%d" ORDER BY ' . $sort_by . ' ASC ' . $limit_str, $id));
return $row;
}
public function page_nav($id, $images_per_page, $bwg) {
global $wpdb;
$total = $wpdb->get_var($wpdb->prepare('SELECT COUNT(*) FROM ' . $wpdb->prefix . 'bwg_image WHERE published=1 AND gallery_id="%d"', $id));
$page_nav['total'] = $total;
if (isset($_POST['page_number_' . $bwg]) && $_POST['page_number_' . $bwg]) {
$limit = ((int) $_POST['page_number_' . $bwg] - 1) * $images_per_page;
}
else {
$limit = 0;
}
$page_nav['limit'] = (int) ($limit / $images_per_page + 1);
return $page_nav;
}
// Getters & Setters //
// Private Methods //
// Listeners //
} |
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class CI_User_agent {
var $agent = NULL;
var $is_browser = FALSE;
var $is_robot = FALSE;
var $is_mobile = FALSE;
var $languages = array();
var $charsets = array();
var $platforms = array();
var $browsers = array();
var $mobiles = array();
var $robots = array();
var $platform = '';
var $browser = '';
var $version = '';
var $mobile = '';
var $robot = '';
/**
* Constructor
*
* Sets the User Agent and runs the compilation routine
*
* @access public
* @return void
*/
function CI_User_agent()
{
if (isset($_SERVER['HTTP_USER_AGENT']))
{
$this->agent = trim($_SERVER['HTTP_USER_AGENT']);
}
if ( ! is_null($this->agent))
{
if ($this->_load_agent_file())
{
$this->_compile_data();
}
}
log_message('debug', "Table Class Initialized");
}
/**
* Compile the User Agent Data
*
* @access private
* @return bool
*/
function _load_agent_file()
{
if ( ! @include(APPPATH.'config/user_agents'.EXT))
{
return FALSE;
}
$return = FALSE;
if (isset($platforms))
{
$this->platforms = $platforms;
unset($platforms);
$return = TRUE;
}
if (isset($browsers))
{
$this->browsers = $browsers;
unset($browsers);
$return = TRUE;
}
if (isset($mobiles))
{
$this->mobiles = $mobiles;
unset($mobiles);
$return = TRUE;
}
if (isset($robots))
{
$this->robots = $robots;
unset($robots);
$return = TRUE;
}
return $return;
}
/**
* Compile the User Agent Data
*
* @access private
* @return bool
*/
function _compile_data()
{
$this->_set_platform();
foreach (array('_set_browser', '_set_robot', '_set_mobile') as $function)
{
if ($this->$function() === TRUE)
{
break;
}
}
}
/**
* Set the Platform
*
* @access private
* @return mixed
*/
function _set_platform()
{
if (is_array($this->platforms) AND count($this->platforms) > 0)
{
foreach ($this->platforms as $key => $val)
{
if (preg_match("|".preg_quote($key)."|i", $this->agent))
{
$this->platform = $val;
return TRUE;
}
}
}
$this->platform = 'Unknown Platform';
}
/**
* Set the Browser
*
* @access private
* @return bool
*/
function _set_browser()
{
if (is_array($this->browsers) AND count($this->browsers) > 0)
{
foreach ($this->browsers as $key => $val)
{
if (preg_match("|".preg_quote($key).".*?([0-9\.]+)|i", $this->agent, $match))
{
$this->is_browser = TRUE;
$this->version = $match[1];
$this->browser = $val;
$this->_set_mobile();
return TRUE;
}
}
}
return FALSE;
}
/**
* Set the Robot
*
* @access private
* @return bool
*/
function _set_robot()
{
if (is_array($this->robots) AND count($this->robots) > 0)
{
foreach ($this->robots as $key => $val)
{
if (preg_match("|".preg_quote($key)."|i", $this->agent))
{
$this->is_robot = TRUE;
$this->robot = $val;
return TRUE;
}
}
}
return FALSE;
}
/**
* Set the Mobile Device
*
* @access private
* @return bool
*/
function _set_mobile()
{
if (is_array($this->mobiles) AND count($this->mobiles) > 0)
{
foreach ($this->mobiles as $key => $val)
{
if (FALSE !== (strpos(strtolower($this->agent), $key)))
{
$this->is_mobile = TRUE;
$this->mobile = $val;
return TRUE;
}
}
}
return FALSE;
}
/**
* Set the accepted languages
*
* @access private
* @return void
*/
function _set_languages()
{
if ((count($this->languages) == 0) AND isset($_SERVER['<API key>']) AND $_SERVER['<API key>'] != '')
{
$languages = preg_replace('/(;q=.+)/i', '', trim($_SERVER['<API key>']));
$this->languages = explode(',', $languages);
}
if (count($this->languages) == 0)
{
$this->languages = array('Undefined');
}
}
/**
* Set the accepted character sets
*
* @access private
* @return void
*/
function _set_charsets()
{
if ((count($this->charsets) == 0) AND isset($_SERVER['HTTP_ACCEPT_CHARSET']) AND $_SERVER['HTTP_ACCEPT_CHARSET'] != '')
{
$charsets = preg_replace('/(;q=.+)/i', '', trim($_SERVER['HTTP_ACCEPT_CHARSET']));
$this->charsets = explode(',', $charsets);
}
if (count($this->charsets) == 0)
{
$this->charsets = array('Undefined');
}
}
/**
* Is Browser
*
* @access public
* @return bool
*/
function is_browser()
{
return $this->is_browser;
}
/**
* Is Robot
*
* @access public
* @return bool
*/
function is_robot()
{
return $this->is_robot;
}
/**
* Is Mobile
*
* @access public
* @return bool
*/
function is_mobile()
{
return $this->is_mobile;
}
/**
* Is this a referral from another site?
*
* @access public
* @return bool
*/
function is_referral()
{
return ( ! isset($_SERVER['HTTP_REFERER']) OR $_SERVER['HTTP_REFERER'] == '') ? FALSE : TRUE;
}
/**
* Agent String
*
* @access public
* @return string
*/
function agent_string()
{
return $this->agent;
}
/**
* Get Platform
*
* @access public
* @return string
*/
function platform()
{
return $this->platform;
}
/**
* Get Browser Name
*
* @access public
* @return string
*/
function browser()
{
return $this->browser;
}
/**
* Get the Browser Version
*
* @access public
* @return string
*/
function version()
{
return $this->version;
}
/**
* Get The Robot Name
*
* @access public
* @return string
*/
function robot()
{
return $this->robot;
}
/**
* Get the Mobile Device
*
* @access public
* @return string
*/
function mobile()
{
return $this->mobile;
}
/**
* Get the referrer
*
* @access public
* @return bool
*/
function referrer()
{
return ( ! isset($_SERVER['HTTP_REFERER']) OR $_SERVER['HTTP_REFERER'] == '') ? '' : trim($_SERVER['HTTP_REFERER']);
}
/**
* Get the accepted languages
*
* @access public
* @return array
*/
function languages()
{
if (count($this->languages) == 0)
{
$this->_set_languages();
}
return $this->languages;
}
/**
* Get the accepted Character Sets
*
* @access public
* @return array
*/
function charsets()
{
if (count($this->charsets) == 0)
{
$this->_set_charsets();
}
return $this->charsets;
}
/**
* Test for a particular language
*
* @access public
* @return bool
*/
function accept_lang($lang = 'en')
{
return (in_array(strtolower($lang), $this->languages(), TRUE)) ? TRUE : FALSE;
}
/**
* Test for a particular character set
*
* @access public
* @return bool
*/
function accept_charset($charset = 'utf-8')
{
return (in_array(strtolower($charset), $this->charsets(), TRUE)) ? TRUE : FALSE;
}
}
?> |
#include "backend/rendering/<API key>.h"
#include "backend/keys/cswordkey.h"
namespace Rendering {
<API key>::<API key>(
bool addText,
const DisplayOptions &displayOptions,
const FilterOptions &filterOptions)
: <API key>(addText, displayOptions, filterOptions)
{
// Intentionally empty
}
QString <API key>::renderEntry(const KeyTreeItem &i,
CSwordKey * k)
{
Q_UNUSED(k);
if (!m_addText)
return QString(i.key()).append("\n");
const BtConstModuleList modules = i.modules();
CSwordKey * key = CSwordKey::createInstance(modules.first());
QString renderedText = QString(i.key()).append(":\n");
QString entry;
Q_FOREACH(CSwordModuleInfo const * const module, modules) {
key->setModule(module);
key->setKey(i.key());
\todo Check this code
entry.append(key->strippedText()).append("\n");
renderedText.append( entry );
}
delete key;
return renderedText;
}
QString <API key>::finishText(const QString &text, const KeyTree &tree) {
Q_UNUSED(tree);
return text;
}
} |
<?php
namespace eZ\Bundle\EzPublishCoreBundle\Imagine\Filter\Loader;
use Imagine\Image\ImageInterface;
use Liip\ImagineBundle\Imagine\Filter\Loader\LoaderInterface;
/**
* Grayscale filter loader.
* Makes an image use grayscale.
*/
class <API key> implements LoaderInterface
{
public function load(ImageInterface $image, array $options = [])
{
$image->effects()->grayscale();
return $image;
}
} |
<p class="gift-wrapping" style="clear:both; padding-top: .5em;">
<label><?php echo str_replace( array( '{checkbox}', '{price}' ), array( $checkbox, $price_text ), wp_kses_post( $<API key> ) ); ?></label>
</p> |
package android.support.v4.p004h;
import android.view.MotionEvent;
/* renamed from: android.support.v4.h.bg */
class bg {
public static int m956a(MotionEvent motionEvent) {
return motionEvent.getSource();
}
} |
// Use of this source code is governed by a BSD-style
package modcmd
import (
"context"
"fmt"
"strings"
"cmd/go/internal/base"
"cmd/go/internal/imports"
"cmd/go/internal/modload"
"golang.org/x/mod/module"
)
var cmdWhy = &base.Command{
UsageLine: "go mod why [-m] [-vendor] packages...",
Short: "explain why packages or modules are needed",
Long: `
Why shows a shortest path in the import graph from the main module to
each of the listed packages. If the -m flag is given, why treats the
arguments as a list of modules and finds a path to any package in each
of the modules.
By default, why queries the graph of packages matched by "go list all",
which includes tests for reachable packages. The -vendor flag causes why
to exclude tests of dependencies.
The output is a sequence of stanzas, one for each package or module
name on the command line, separated by blank lines. Each stanza begins
with a comment line "# package" or "# module" giving the target
package or module. Subsequent lines give a path through the import
graph, one package per line. If the package or module is not
referenced from the main module, the stanza will display a single
parenthesized note indicating that fact.
For example:
$ go mod why golang.org/x/text/language golang.org/x/text/encoding
# golang.org/x/text/language
rsc.io/quote
rsc.io/sampler
golang.org/x/text/language
# golang.org/x/text/encoding
(main module does not need package golang.org/x/text/encoding)
$
`,
}
var (
whyM = cmdWhy.Flag.Bool("m", false, "")
whyVendor = cmdWhy.Flag.Bool("vendor", false, "")
)
func init() {
cmdWhy.Run = runWhy // break init cycle
base.AddModCommonFlags(&cmdWhy.Flag)
}
func runWhy(ctx context.Context, cmd *base.Command, args []string) {
modload.ForceUseModules = true
modload.RootMode = modload.NeedRoot
loadOpts := modload.PackageOpts{
Tags: imports.AnyTags(),
LoadTests: !*whyVendor,
SilenceErrors: true,
UseVendorAll: *whyVendor,
}
if *whyM {
listU := false
listVersions := false
listRetractions := false
for _, arg := range args {
if strings.Contains(arg, "@") {
base.Fatalf("go mod why: module query not allowed")
}
}
mods := modload.ListModules(ctx, args, listU, listVersions, listRetractions)
byModule := make(map[module.Version][]string)
_, pkgs := modload.LoadPackages(ctx, loadOpts, "all")
for _, path := range pkgs {
m := modload.PackageModule(path)
if m.Path != "" {
byModule[m] = append(byModule[m], path)
}
}
sep := ""
for _, m := range mods {
best := ""
bestDepth := 1000000000
for _, path := range byModule[module.Version{Path: m.Path, Version: m.Version}] {
d := modload.WhyDepth(path)
if d > 0 && d < bestDepth {
best = path
bestDepth = d
}
}
why := modload.Why(best)
if why == "" {
vendoring := ""
if *whyVendor {
vendoring = " to vendor"
}
why = "(main module does not need" + vendoring + " module " + m.Path + ")\n"
}
fmt.Printf("%s# %s\n%s", sep, m.Path, why)
sep = "\n"
}
} else {
// Resolve to packages.
matches, _ := modload.LoadPackages(ctx, loadOpts, args...)
modload.LoadPackages(ctx, loadOpts, "all") // rebuild graph, from main module (not from named packages)
sep := ""
for _, m := range matches {
for _, path := range m.Pkgs {
why := modload.Why(path)
if why == "" {
vendoring := ""
if *whyVendor {
vendoring = " to vendor"
}
why = "(main module does not need" + vendoring + " package " + path + ")\n"
}
fmt.Printf("%s# %s\n%s", sep, path, why)
sep = "\n"
}
}
}
} |
/*
* GK Font
*/
@charset "UTF-8";
@font-face {
font-family: "gkfont";
src: url("../fonts/gk-font/gkfont.eot");
src: url("../fonts/gk-font/gkfont.eot?#iefix") format("embedded-opentype"), url("../fonts/gk-font/gkfont.ttf") format("truetype"), url("../fonts/gk-font/gkfont.svg#gkfont") format("svg"), url("../fonts/gk-font/gkfont.woff") format("woff");
font-weight: normal;
font-style: normal;
}
[class^="gk-icon-"]:before,
[class*=" gk-icon-"]:before {
font-family: "gkfont";
font-style: normal;
font-weight: normal;
speak: none;
line-height: 1;
-<API key>: antialiased;
}
.gk-icon-arrow-left:before { content: "1"; }
.gk-icon-arrow-right:before { content: "2"; }
.gk-icon-cross:before { content: "3"; }
html {
-<API key>: antialiased;
min-height: 100%;
}
body {
/*background: #eee;*/
background: url("../images/sketch.png") repeat scroll 0 0 #EEEEEE;
color: #888;
font-size: 15px;
font-weight: 300;
line-height: 1.9;
margin: 0;
min-height: 100%;
padding: 0;
-ms-word-wrap: break-word;
word-wrap: break-word;
}
body.solidBg {
background: #eee;
<API key>: scroll;
background-size: auto;
background-repeat: repeat;
}
body.solidBg.pattern1 { background-image: url('../images/patterns/pattern1.png'); }
body.solidBg.pattern2 { background-image: url('../images/patterns/pattern2.png'); }
body.solidBg.pattern3 { background-image: url('../images/patterns/pattern3.png'); }
body.solidBg.pattern4 { background-image: url('../images/patterns/pattern4.png'); }
body.solidBg.pattern5 { background-image: url('../images/patterns/pattern5.png'); }
body.solidBg.pattern6 { background-image: url('../images/patterns/pattern6.png'); }
body.solidBg.pattern7 { background-image: url('../images/patterns/pattern7.png'); }
body.solidBg.pattern8 { background-image: url('../images/patterns/pattern8.png'); }
body.solidBg.pattern9 { background-image: url('../images/patterns/pattern9.png'); }
body.solidBg.pattern10 { background-image: url('../images/patterns/pattern10.png'); }
body.solidBg.pattern11 { background-image: url('../images/patterns/pattern11.png'); }
body.solidBg.pattern12 { background-image: url('../images/patterns/pattern12.png'); }
body[data-mobile="true"] #main-menu-mobile select {
font-size: 50px;
}
#gk-bg {
min-height: 100%;
width: 100%;
}
#gk-header {
/*background: #fff!important;*/
background-size: cover;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
-o-box-sizing: border-box;
box-sizing: border-box;
background-image: url("../images/header-blue.jpg");
}
.ie8mode #gk-header {
background: transparent url('../images/style1/header_bg_ie.png') repeat-x 0 0;
}
body.solidBg #gk-header,
body.solidBg .ie8mode #gk-header {
background: transparent url('../images/style2/header_bg_solid.jpg') no-repeat 0 0;
}
a:hover,
a:active,
a:focus,
#gk-mainbody header h1 a:active,
#gk-mainbody header h1 a:focus,
#gk-mainbody header h1 a:hover,
#gk-mainbody header h2 a:active,
#gk-mainbody header h2 a:focus,
#gk-mainbody header h2 a:hover,
article header ul a:active,
article header ul a:focus,
article header ul a:hover,
#comments a:active,
#comments a:focus,
#comments a:hover {
color: #272727;
}
a,
#comments a,
article header ul a,
#gk-mainbody header h1 a,
#gk-mainbody header h2 a,
.frontpage #gk-mainbody header h2 a {
color: #db4a37;
text-decoration: none;
-webkit-transition: color 0.2s linear, background-color 0.2s linear;
-moz-transition: color 0.2s linear, background-color 0.2s linear;
-o-transition: color 0.2s linear, background-color 0.2s linear;
transition: color 0.2s linear, background-color 0.2s linear;
}
.frontpage #gk-mainbody header h2 a {
color: #272727;
}
.frontpage #gk-mainbody header h2 a:active,
.frontpage #gk-mainbody header h2 a:focus,
.frontpage #gk-mainbody header h2 a:hover {
color: #db4a37;
}
h1,
h2,
h3,
h4,
h5,
h6 {
color: #272727;
font-weight: 400;
line-height: 1.2;
margin: 0 0 12px 0;
padding: 0;
text-transform: uppercase;
}
h1 {
font-size: 46px;
font-weight: 300;
margin: 0 0 12px;
}
h2,
.page-title {
font-size: 42px;
font-weight: 300;
margin: 0 0 18px 0;
}
h3 {
font-size: 24px;
}
h4 {
font-size: 20px;
}
h5 {
font-size: 17px;
font-weight: 500;
}
h6 {
font-size: 13px;
font-weight: 500;
}
ul {
list-style: none;
margin: 0;
padding: 0;
}
ol {
margin: 0;
padding: 0;
}
ul li,
ol li {
line-height: 2.0;
}
p {
margin: 0.5em 0 1.5em;
}
img {
height: auto;
max-width: 100%;
}
iframe {
max-width: 100%!important;
}
/* buttons */
.btn,
button,
.button,
.readon,
.nav-btn a,
.more-link,
.gk-button,
a.gk-button,
input[type="button"],
input[type="submit"],
.gk-price-table dd a,
.nav-prev a,
.nav-next a {
background: transparent;
border: 1px solid #db4a37;
color: #db4a37!important;
cursor: pointer;
display: block;
float: left;
font-size: 12px;
font-weight: 500!important;
height: 30px;
line-height: 30px;
margin: 0 5px 2px 2px;
padding: 0 25px;
text-align: center;
text-transform: uppercase!important;
-webkit-transition: all .3s ease-out;
-moz-transition: all .3s ease-out;
-o-transition: all .3s ease-out;
transition: all .3s ease-out;
}
.btn:hover,
.btn:active,
.btn.active,
.btn.disabled,
.btn[disabled],
.nav-btn a:active,
.nav-btn a:focus,
.nav-btn a:hover,
button:hover,
input[type="button"]:hover,
input[type="submit"]:hover,
button:active,
input[type="button"]:active,
input[type="submit"]:active,
button.disabled,
input[type="button"].disabled,
input[type="submit"].disabled,
a.gk-button:hover,
a.gk-button:active,
a.gk-button.active,
a.gk-button.disabled,
a.gk-button[disabled],
.readon:active,
.readon:focus,
.readon:hover,
.btn:focus,
button:focus,
a.gk-button:focus,
input[type="button"]:focus,
input[type="submit"]:focus,
.more-link:active,
.more-link:focus,
.more-link:hover,
.gk-price-table dd a:active,
.gk-price-table dd a:focus,
.gk-price-table dd a:hover,
.button:active,
.button:focus,
.button:hover,
.nav-prev a:active,
.nav-next a:active,
.nav-prev a:focus,
.nav-next a:focus,
.nav-prev a:hover,
.nav-next a:hover {
border-color: #272727;
color: #272727!important;
}
.btn,
.button,
.readon {
text-transform: lowercase;
}
/* input fields */
input[type="text"],
input[type="password"],
input[type="email"],
input[type="www"],
input[type="tel"],
textarea {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
-o-box-sizing: border-box;
box-sizing: border-box;
border: 1px solid #ddd;
-<API key>: 2px;
-moz-border-radius: 2px;
border-radius: 2px;
font-size: 14px;
font-weight: 300;
color: #888;
height: 40px;
max-width: 100%!important;
padding: 0 10px;
}
textarea {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
-o-box-sizing: border-box;
box-sizing: border-box;
height: auto;
max-width: 100%!important;
padding: 24px;
}
input[type="text"]:focus,
input[type="password"]:focus,
input[type="url"]:focus,
input[type="email"]:focus,
input[type="tel"]:focus,
textarea:focus {
background: #fffef4;
}
label {
color: #272727;
font-size: 14px;
font-weight: 400;
padding: 0 6px 0 0;
}
#comments label {
padding: 12px 0 6px;
}
select {
height: inherit;
max-width: 100%;
padding: 6px
}
#searchsubmit {
float: none;
display: inline-block;
}
/* Additional button styles */
.border,
.gk-price-table dd a {
background: transparent!important;
border: 1px solid #ddd;
color: #888!important;
}
.border:hover,
.gk-price-table dd a:hover {
background: #db4a37!important;
border-color: #db4a37!important;
color: #fff!important;
}
.gk-price-table .gk-premium dd a:hover {
border-color: #fff;
}
#gk-bottom2 .border {
border-color: #fff;
}
#gk-bottom2 .box .border:hover {
background: #fff!important;
border-color: #fff!important;
color: #db4a37!important;
}
article {
margin: 0;
}
.tag-page article,
.category-page article,
.search-page article,
.archive article,
.<API key> article,
.home .gk-is-homepage article,
.home #gk-mainbody article {
margin: 0 0 80px 0;
}
#gk-mainbody.tag-page > article h2,
#gk-mainbody.search-page > article h2 {
font-size: 28px;
line-height: 36px;
}
.tag-page > hr + article,
.tag-page > article:first-child,
.search-page > hr + article,
.search-page > #searchform + article {
padding: 0 20px 0 0;
}
.tag-page > hr,
.search-page > hr {
border: none;
clear: both;
}
.gk-page {
margin: 0 auto;
width: 100%;
}
#gk-mainbody {
padding: 0 0 30px 0;
}
#gk-mainbody.contains-widget {
padding: 0;
}
.frontpage #gk-mainbody {
padding-top: 0;
}
#gk-mainbody-columns {
/*background: #fff;*/
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
/*padding: 60px 50px 0 50px*/
}
#gk-mainbody-columns > section {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
-o-box-sizing: border-box;
box-sizing: border-box;
display: block;
float: left;
padding: 0;
}
#gk-mainbody-columns > aside {
background: none;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
-o-box-sizing: border-box;
box-sizing: border-box;
display: block;
float: left;
padding: 2px;
}
#gk-mainbody-columns.gk-column-left > section {
float: right;
}
#gk-mainbody-columns.gk-column-left > aside {
float: left;
padding: 0 70px 32px 0;
}
#gk-top {
/*background: #fff;*/
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
box-sizing: border-box;
min-height: 62px;
padding: 0 5px;
width: 100%;
}
#gk-header-bottom {
background: #db4a37;
padding: 40px 50px 0 50px;
}
#gk-header-bottom > div {
margin: 0 -20px;
}
/* Logo */
a.cssLogo {
margin: 0;
padding: 0;
text-indent: -999em;
text-shadow: none;
width: 130px;
display: block;
float: left;
margin: 0;
}
a.cssLogo {
background: transparent url('../images/logo.png') no-repeat 0 0;
/* You can specify there logo size and background */
height: 55px;
width: 145px;
}
a.textLogo {
color: #fff;
display: block;
float: left;
font-size: 18px;
font-weight: 500;
height: auto;
letter-spacing: 2px;
line-height: 24px;
margin: 0;
overflow: hidden;
padding: 20px 5px 5px 0;
text-align: center;
text-indent: 0;
text-transform: uppercase;
width: auto;
}
a.textLogo > span {
color: #db4a37;
}
a.textLogo small {
color: #f5f5f5;
font-size: 14px;
font-weight: bold;
line-height: 20px;
margin-left: 10px;
text-align: center;
}
/* Header */
#gk-header {
<API key>: 15px;
<API key>: 15px;
clear: both;
padding-bottom: 15px;
}
#gk-user-area {
background-image: linear-gradient(to bottom, #75C9E0, #1785A3);
border: 1px solid;
<API key>: 30px;
float: right;
font-size: 11px;
font-weight: 500;
line-height: 20px;
padding: 5px 10px;
text-transform: uppercase;
}
#gk-user-area a {
color: #fff;
}
#gk-user-area a:active,
#gk-user-area a:focus,
#gk-user-area a:hover {
color: #fff;
}
#gk-user-area a + a:before {
content: "/";
padding: 0 7px 0 4px;
}
section.intro {
font-size: 110%;
padding: 0;
}
.box:after,
article:after,
#respond:after,
#gk-top:after,
#gk-header-bottom:after,
.widget-area:after,
#gk-top:after,
#gk-top1:after,
#gk-top2:after,
#gk-bottom1:after,
#gk-bottom2:after,
#gk-bottom3:after,
#gk-bottom4:after,
#gk-mainbody:after,
#gk-mainbody-columns:after,
#gk-footer:after,
section.content:after {
clear: both;
content: "";
display: table;
}
#gk-mainbody-top {
margin: 0 0 30px 0;
}
#gk-mainbody-bottom {
margin: 0 0 30px 0;
}
/* frontpage posts */
.frontpage .pagenav {
clear: both;
padding-top: 40px;
}
.frontpage #gk-mainbody article {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
float: left;
margin: -60px 0 -31px 0;
padding-bottom: 52px;
width: 50%;
}
.frontpage #gk-mainbody article {
padding-top: 90px;
}
.frontpage #gk-mainbody article:first-child,
.frontpage #gk-mainbody article:nth-child(2) {
padding-top: 52px;
}
.frontpage #gk-mainbody article:nth-child(2n+1) {
border-right: 1px solid #ddd;
clear: both;
padding-right: 50px;
}
.frontpage #gk-mainbody article:nth-child(2n+2) {
float: right;
padding-left: 50px;
}
.frontpage #gk-mainbody article .summary {
padding-left: 75px;
}
.frontpage #gk-mainbody article.no-sidebar .summary {
padding-left: 0;
}
.frontpage article figure.featured-image {
margin-bottom: 25px;
}
.frontpage article header ul {
margin-bottom: 0;
}
.frontpage #gk-mainbody article > header {
padding-bottom: 1px;
}
.frontpage article figure.featured-image:hover img {
-webkit-transform: scale(1.0);
-moz-transform: scale(1.0);
-ms-transform: scale(1.0);
-o-transform: scale(1.0);
transform: scale(1.0);
opacity: 1;
}
.frontpage #gk-mainbody header h2 {
font-size: 28px;
margin-bottom: 19px;
}
#gk-bottom1,
#gk-bottom2,
#gk-bottom3,
#gk-bottom4{
background: #fff;
overflow: hidden;
padding: 0 50px;
}
#gk-bottom4 {
background: #272727;
font-size: 14px;
}
#gk-top1 .box,
#gk-top2 .box,
#gk-bottom1 .box,
#gk-bottom2 .box,
#gk-bottom3 .box {
background: #fff;
padding: 0 20px;
}
#gk-bottom4 .box {
color: #555;
padding: 0 20px;
}
#gk-bottom4 .box a {
color: #888;
}
#gk-bottom4 .box .box-title,
#gk-bottom4 .box .box-title small {
color: #888!important;
}
#gk-bottom4 .box .box-title:after {
display: none;
}
#gk-bottom4 .box .block-title {
color: #888!important;
font-size: 14px;
font-weight: 500;
line-height: 1.2;
margin-bottom: 30px;
}
#gk-bottom4 .box .textwidget ul + .block-title {
margin-top: 40px;
}
#gk-bottom4 .box li {
padding: 0;
}
#gk-bottom4 .box li:before {
display: none;
}
#gk-bottom4 .gk-columns {
margin: 0;
}
#gk-bottom4 .box a:active,
#gk-bottom4 .box a:focus,
#gk-bottom4 .box a:hover {
color: #fff;
}
#gk-bottom1 .box,
#gk-bottom2 .box,
#gk-bottom3 .box,
#gk-bottom4 .box {
padding-bottom: 30px;
padding-top: 70px;
}
#gk-bottom1.gk-single-widget > div,
#gk-bottom2.gk-single-widget > div,
#gk-bottom3.gk-single-widget > div,
#gk-bottom4.gk-single-widget > div {
margin: 0 -50px!important;
width: auto!important;
}
#gk-bottom1.gk-single-widget .box,
#gk-bottom2.gk-single-widget .box,
#gk-bottom3.gk-single-widget .box,
#gk-bottom4.gk-single-widget .box {
min-width: 100%;
padding: 70px 50px!important;
width: auto!important;
}
#gk-top1 .widget-area,
#gk-top2 .widget-area,
#gk-bottom1 .widget-area,
#gk-bottom2 .widget-area,
#gk-bottom3 .widget-area,
#gk-bottom4 .widget-area{
margin: 0 -20px!important;
}
#gk-footer {
background: #272727;
border-top: 1px solid #404040;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
-o-box-sizing: border-box;
box-sizing: border-box;
color: #888;
font-size: 10px;
font-weight: 500;
line-height: 62px;
margin-bottom: 160px;
padding: 0 50px;
text-transform: uppercase;
}
#gk-footer > div {
padding: 0;
}
.gk-footer-border + #gk-footer > div {
border-top: 1px solid #f1857a;
}
#gk-footer a {
color: #ddd;
}
#gk-footer a:active,
#gk-footer a:focus,
#gk-footer a:hover {
color: #db4a37;
}
#footer-menu {
font-size: 11px;
float: left;
}
#footer-menu li {
border: none;
float: left;
line-height: 62px;
margin: 0 0 0 7px!important;
padding: 0;
position: relative;
}
#footer-menu li:first-child {
margin-left: 0!important;
}
#footer-menu li:before {
background: #ddd;
border-right: 1px solid #3f3f3f;
content: "";
display: block;
height: 1px;
left: -4px;
position: absolute;
top: 49%;
width: 1px;
}
#footer-menu li:first-child:before {
display: none;
}
#footer-menu ul {
display: none;
}
float: right;
margin: 0;
padding: 0;
}
#gk-footer .gk-framework-logo {
clear: both;
display: block;
margin: 12px auto 0 auto;
padding: 40px 0 50px 0;
opacity: 0.6;
}
/* Style switcher */
#gk-footer + #gk-style-area {
margin-top: -100px!important;
}
#gk-style-area {
display: block;
line-height: 10px;
margin: 16px 0 60px 0!important;
padding: 0!important;
text-align: center;
}
#gk-style-area a {
display: inline-block;
height: 8px;
line-height: 1.0;
margin: 0 0 0 1px;
text-indent: -9999px;
-webkit-transform: scale(1.0);
-moz-transform: scale(1.0);
-ms-transform: scale(1.0);
-o-transform: scale(1.0);
transform: scale(1.0);
-webkit-transition: -webkit-transform 0.2s ease-out;
-moz-transition: -moz-transform 0.2s ease-out;
-o-transition: -o-transform 0.2s ease-out;
transition: transform 0.2s ease-out;
width: 8px;
}
#gk-style-area a:first-child {
margin-left: 0;
}
#gk-style-area a:hover {
-webkit-transform: scale(1.5);
-moz-transform: scale(1.5);
-ms-transform: scale(1.5);
-o-transform: scale(1.5);
transform: scale(1.5);
}
#gk-color1 { background: #db4a37; }
#gk-color2 { background: #72c4b9; }
#gk-color3 { background: #7090c8; }
#gk-color4 { background: #f2b33d; }
#gk-color5 { background: #bb6883; }
#gk-color6 { background: #5e6281; }
.box {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
-o-box-sizing: border-box;
box-sizing: border-box;
padding: 0 10px;
}
#gk-mainbody-top .box,
#gk-mainbody-bottom .box {
padding: 0;
}
#gk-top1 .box,
#gk-top2 .box,
#gk-bottom1 .box,
#gk-bottom2 .box,
#gk-bottom3 .box,
#gk-bottom4 .box,
#gk-header-bottom .box {
float: left;
}
#gk-top1 .box,
#gk-top2 .box,
#gk-bottom1 .box,
#gk-bottom2 .box,
#gk-bottom3 .box,
#gk-bottom4 .box {
padding-bottom: 30px!important;
}
.widget-area .col1 { width: 100%; }
.widget-area .col2 { width: 50%; }
.widget-area .col3 { width: 33.3%; }
.widget-area .col4 { width: 25%; }
.widget-area .col5 { width: 20%; }
.widget-area .col6 { width: 16.6%; }
.widget-area .box.last1 { width: 100%; }
.widget-area .box.last2 { width: 50%; }
.widget-area .box.last3 { width: 33.3%; }
.widget-area .box.last4 { width: 25%; }
.widget-area .box.last5 { width: 20%; }
.widget-area .box.double.last2 {
width: 60%;
}
.widget-area .box.double.last2 ~ .box.last2 {
width: 40%;
}
.widget-area .nth1 {
clear: both;
}
.onlyDesktop {
display: block!important;
}
.onlyTablets {
display: none!important;
}
.onlySmartphones {
display: none!important;
}
.<API key> {
display: none!important;
}
/*
.<API key> .rtmedia-like {
background: url('../images/heart-plus.png') no-repeat!important;
height: 25px!important;
width: 25px!important;
}
.rtmedia-like span {
display: none!important;
}
.<API key> .rtmedia-like:hover {
opacity: 0.8;
border: 0 none!important;
}
.<API key> .rtmedia-unlike {
background: url('../images/heart-minus.png') no-repeat!important;
height: 25px!important;
width: 25px!important;
}
.rtmedia-unlike span {
display: none!important;
}
.<API key> .rtmedia-unlike:hover {
opacity: 0.8;
border: 0 none!important;
}
.rtmicon-thumbs-up:before {
content: "" !important;
}
*/
.<API key> .my-like {
background: url('../images/heart-plus.png') no-repeat!important;
height: 25px!important;
width: 25px!important;
}
.my-like span {
display: none!important;
}
.<API key> .my-like:hover {
opacity: 0.8;
border: 0 none!important;
}
.<API key> .my-unlike {
background: url('../images/heart-minus.png') no-repeat!important;
height: 25px!important;
width: 25px!important;
}
.my-unlike span {
display: none!important;
}
.<API key> .my-unlike:hover {
opacity: 0.8;
border: 0 none!important;
}
.rtmicon-thumbs-up:before {
content: "" !important;
}
.<API key>:before
{
display:none !important;
}
.only-follow-shown
{
font-size:10px;
color:gray;
}
.my-member-social
{
line-height:36px;
}
.my-member-social img
{
margin-top:0px;
margin-bottom:0px;
padding-top:0px;
padding-bottom:0px;
width:32px;
height:32px;
}
#gk-logo a > img {
padding:5px;
} |
<?php
error_reporting(E_COMPILE_ERROR|E_ERROR|E_CORE_ERROR);
require('./roots.php');
require($root_path.'include/<API key>.php');
$lang_tables[]='date_time.php';
$lang_tables[]='reporting.php';
require($root_path.'include/<API key>.php');
#Load and create paginator object
require_once($root_path.'include/care_api_classes/class_encounter.php');
require_once($root_path.'include/care_api_classes/class_lab.php');
require_once($root_path.'include/care_api_classes/class_tz_reporting.php');
/**
* Getting the timeframe...
*/
$debug=false;
$PRINTOUT=FALSE;
if (empty($_GET['printout'])) {
if (empty($_POST['month']) && empty($_POST['year'])) {
if ($debug) echo "no time value is set, were using now the current month<br>";
$month=date("n",time());
$year=date("Y",time());
$start_timeframe = mktime (0,0,0,$month, 1, $year);
$end_timeframe = mktime (0,0,0,$month+1, 0, $year); // Last day of requested month
} else {
if ($debug) echo "Getting an new time range...<br>";
$start_timeframe = mktime (0,0,0,$_POST['month'], 1, $_POST['year']);
$end_timeframe = mktime (0,0,0,$_POST['month']+1, 0, $_POST['year']);
}
} else {
$PRINTOUT=TRUE;
} // end of if (empty($_GET['printout']))
if (empty($_POST['group_id']) && empty($_GET['group_id'])) {
if ($debug) echo "--->Ignition call, setting the requested laboratory group to 1<br>";
$group_id="";
} else {
if ($debug) echo "--->getting an post variable about the requested group id<br>";
if (empty($_GET['group_id']))
$group_id=$_POST['group_id'];
else
$group_id=$_GET['group_id'];
}
/**
* getting summary of OPD...
*/
$rep_obj = new selianreport();
$lab_obj=new Lab();
$db->debug=false;
$sql_l ="DROP TABLE IF EXISTS `tmp_laboratory`";
$db->Execute($sql_l);
$sql="CREATE TEMPORARY TABLE tmp_laboratory TYPE=HEAP (SELECT
group_id as GroupID,
id as GroupName,
nr as TestNr,
nr as TestID,
shortname as TestName,
name as FullTestName
FROM <API key>
WHERE status!='hidden')";
/*
$sql="CREATE TABLE tmp_laboratory (SELECT
<API key>.id as GroupID,
<API key>.name as GroupName,
<API key>.id as TestID,
<API key>.shortname as TestName
FROM <API key>
INNER JOIN <API key> ON <API key>.group_id=<API key>.id WHERE is_enabled=1)";
*/
$db->Execute($sql);
$sql="CREATE TEMPORARY TABLE <API key> (TestID INT NOT NULL, is_positive INT NOT NULL, date INT NOT NULL ) TYPE=HEAP ";
$db->Execute($sql);
//$sql="Select * from <API key> where encounter_nr=2006500443";
$sql="Select nr,paramater_name as serial_value, parameter_value as add_value ,UNIX_TIMESTAMP(<API key>.create_time) as date
from <API key> INNER JOIN <API key>
ON <API key>.paramater_name = <API key>.id
WHERE UNIX_TIMESTAMP(<API key>.create_time) >=$start_timeframe
AND UNIX_TIMESTAMP(<API key>.create_time) <= '$end_timeframe'
ORDER BY <API key>.create_time DESC";
//echo $sql;
$db_obj=$db->Execute($sql);
$row=$db_obj->GetArray();
while (list($u,$v)=each($row)){
//$a = unserialize($v['serial_value']); // Here we can find the value given to each test-id
//$b = unserialize($v['add_value']); // Here we can find the information if it was a check box or not
//echo "array a:"; print_r($a); echo "<br>";
//echo "array b:"; print_r($b); echo "<br>";
$nr = $v['nr'];
$a = $v['serial_value'];
$b = $v['add_value'];
if (strpos($a,'+')===0)
$sql="INSERT INTO <API key> (TestID,is_positive, date) VALUES (".$nr.",1,".$v['date'].")";
else
$sql="INSERT INTO <API key> (TestID,is_positive, date) VALUES (".$nr.",0,".$v['date'].")";
$db->Execute($sql);
//echo $sql;
if ($debug) echo date("F j, Y, g:i a", $v['date'])."<br>";
//echo (strpos($av,'check'))."<br>";
if (strpos($a,'check')===0)
$sql="update <API key> set is_positive=1 where TestID=$nr AND date='$v[date]'";
//$sql="INSERT INTO <API key> (TestID,is_positive, date) VALUES (".$au.",1,".$v['date'].")";
else
$sql="update <API key> set is_positive=0 where TestID=$nr AND date='$v[date]'";
//$sql="INSERT INTO <API key> (TestID,is_positive, date) VALUES (".$au.",0,".$v['date'].")";
$db->Execute($sql);
if ($debug) echo date("F j, Y, g:i a", $v['date'])."<br>";
}
$<API key> = "SELECT count(TestID) FROM tmp_laboratory";
$db_prt = $db->Execute($<API key>);
$db_row = $db_prt->FetchRow();
$number_of_columns = $db_row[0];
//echo "Amount of available tests: ".$db_row[0];
function <API key>($group_id) {
global $db;
$sql ="SELECT DISTINCT GroupID, GroupName, FullTestName FROM tmp_laboratory WHERE GroupID=-1 ORDER BY GroupID";
$db_obj=$db->Execute($sql);
echo "<option value=''></option>";
$row = $db_obj->GetArray();
while (list($u,$v)=each($row)) {
if ($group_id == $v['GroupName'])
echo "<option value=".$v['GroupName']." selected>".$v['FullTestName']."</option>";
else
echo "<option value=".$v['GroupName'].">".$v['FullTestName']."</option>";
}
}
function <API key>($group_id) {
global $db;
global $PRINTOUT;
// Table definition will be organized by the variable $table_head from here:
$table_head = "<tr>\n";
if ($PRINTOUT)
$table_head .= "<td> </td>\n";
else
$table_head .= "<td bgcolor=\"#ffffaa\"> </td>\n";
// Line of all groups
$sql_groups = "SELECT count(GroupID) as colspan, GroupID,FullTestName FROM tmp_laboratory WHERE GroupID='".$group_id."' GROUP BY GroupID";
$db_prt = $db->Execute($sql_groups);
$db_array = $db_prt->GetArray();
while (list($u,$v)=each($db_array)) {
$table_head .= "<td colspan=\"".$v['colspan']."\" bgcolor=\"#ffffaa\" id=\"".$v['GroupID']."\"> <div align=\"center\"><h1>".$v['GroupID']."</h1></div></td>\n" ;
}
$table_head.="</tr>\n<tr>";
if ($PRINTOUT)
$table_head .= "<td>day</td>\n";
else
$table_head .= "<td bgcolor=\"#CC9933\">Date</td>\n";
$sql_tests = "SELECT TestID, TestName, FullTestName FROM tmp_laboratory WHERE GroupID='".$group_id."'";
$db_prt=$db->Execute($sql_tests);
$db_row=$db_prt->GetArray();
while (list($u,$v)=each($db_row)) {
if (empty($v['FullTestName']))
$testname=$v['TestName'];
else
$testname=$v['FullTestName'];
if ($PRINTOUT)
$table_head .= "<td id=\"".$v['TestID']."\">".$testname."</td>\n" ;
else
$table_head .= "<td bgcolor=\"#CC9933\" id=\"".$v['TestID']."\">".$testname."</td>\n" ;
}
echo $table_head;
}
function NumberOfTests($TestID,$day_as_timestamp) {
global $db;
$debug=false;
// getting the day: start_time_frame plus day is what we need:
$start_time = $day_as_timestamp;
$end_time = $day_as_timestamp+(24*60*60-1);
if ($debug) echo "Looking for test $TestID by time range: day: ".date("d.m.y",$day_as_timestamp)." starttime: ".date("d.m.y :: G:i:s",$start_time)." endtime: ".date("d.m.y :: G:i:s",$end_time)."<br>";
$sql = "Select Count(TestID) as number_of_tests FROM <API key> WHERE TestID=".$TestID." AND ( ".$start_time." <= date AND date <= ".$end_time." )";
$db_ptr = $db->Execute($sql);
$row = $db_ptr->FetchRow();
if ($debug) echo "hits:".$row['number_of_tests']."<br><br>";
$return_value = $row['number_of_tests'];
if ($pos=<API key>($TestID,$day_as_timestamp)) {
$return_value .= "($pos+)";
}
return $return_value;
}
function <API key>($TestID,$day_as_timestamp) {
global $db;
$debug = false;
// getting the day: start_time_frame plus day is what we need:
$start_time = $day_as_timestamp;
$end_time = $day_as_timestamp+(24*60*60-1);
if ($debug) echo "Looking for test $TestID by time range: day: ".date("d.m.y",$day_as_timestamp)." starttime: ".date("d.m.y :: G:i:s",$start_time)." endtime: ".date("d.m.y :: G:i:s",$end_time)."<br>";
$sql = "Select Count(is_positive) as <API key> FROM <API key> WHERE TestID=".$TestID." AND ( ".$start_time." <= date AND date <= ".$end_time." ) AND is_positive=1";
$db_ptr = $db->Execute($sql);
$row = $db_ptr->FetchRow();
if ($debug) echo "hits:".$row['<API key>']."<br><br>";
return $row['<API key>'];
}
function <API key>($TestID,$start_time) {
global $db;
$debug=FALSE;
if (empty($TestID)) return "-1";
$end_time = mktime(0,0,0,date("n",$start_time)+1,1,date("Y",$start_time))-1;
// getting the day: start_time_frame plus day is what we need:
if ($debug) echo "Looking for test $TestID by time range: day: ".date("d.m.y",$start_time)." starttime: ".date("d.m.y :: G:i:s",$start_time)." endtime: ".date("d.m.y :: G:i:s",$end_time)."<br>";
$sql = "Select Count(TestID) as number_of_tests FROM <API key> WHERE TestID=".$TestID." AND ( ".$start_time." <= date AND date <= ".$end_time." )";
if ($debug) echo $sql."<br>";
$db_ptr = $db->Execute($sql);
$row = $db_ptr->FetchRow();
if ($debug) echo "hits:".$row['number_of_tests']."<br><br>";
$return_value = $row['number_of_tests'];
if ($pos=<API key>($TestID,$start_time)) {
$return_value .= "($pos+)";
}
return $return_value;
}
function <API key>($TestID,$start_time) {
global $db;
$debug = FALSE;
$end_time = mktime(0,0,0,date("n",$start_time)+1,1,date("Y",$start_time))-1;
// getting the day: start_time_frame plus day is what we need:
if ($debug) echo "Looking for test $TestID by time range: day: ".date("d.m.y",$start_time)." starttime: ".date("d.m.y :: G:i:s",$start_time)." endtime: ".date("d.m.y :: G:i:s",$end_time)."<br>";
$sql = "Select Count(is_positive) as <API key> FROM <API key> WHERE TestID=".$TestID." AND ( ".$start_time." <= date AND date <= ".$end_time." ) AND is_positive=1";
$db_ptr = $db->Execute($sql);
$row = $db_ptr->FetchRow();
if ($debug) echo "hits:".$row['<API key>']."<br><br>";
return $row['<API key>'];
}
function _get_requested_day($start_time_frame, $day) {
/**
* Private function: getting the exact date, beginning with start_time_frame (UNIX timestamp)
* adding the value given in the variable "day"
* Return value is an UNIX-Timestamp
*/
$sec_to_add = $day * 24 * 60 * 60;
return $requested_day = $start_time_frame + $sec_to_add;
}
function <API key>($group_id, $start_time_frame, $end_time_frame) {
global $db;
global $PRINTOUT;
global $<API key>, $LDtill;
$table ="<tr>\n";
echo $<API key>." <b>".date("F j, Y",$start_time_frame)."</b> ".$LDtill." <b>".date("F j, Y",$end_time_frame)."</b><br>";
$<API key> = date ("d",$start_time_frame);
$<API key> = date ("d",$end_time_frame);
// is "today" between start_time_frame and end_time_frame - or even older??
$SHOW_ITALIC=FALSE;
if (($start_time_frame<time() && $end_time_frame) || $start_time_frame>time())
$SHOW_ITALIC=TRUE; // Yes, then we should might display it in italic ...
for ($day=$<API key>; $day<=$<API key> ; $day++) {
$current_day = _get_requested_day($start_time_frame, $day-1);
$table.="<tr>\n";
if ($current_day > time())
if ($PRINTOUT)
$table .= "<td><i>".date("j/m/Y",_get_requested_day($start_time_frame, $day-1))."</i></td>\n";
else
$table .= "<td bgcolor=\"#ffffff\"><i>".date("j/m/Y",_get_requested_day($start_time_frame, $day-1))."</i></td>\n";
else
$table .= "<td bgcolor=\"#ffffaa\">".date("j/m/Y",_get_requested_day($start_time_frame, $day-1))."</td>\n";
$sql = "SELECT TestID FROM tmp_laboratory WHERE GroupID='".$group_id."'";
$db_ptr=$db->Execute($sql);
$arr_ret = $db_ptr -> GetArray();
while (list($u,$v)=each($arr_ret)) {
if (empty($v['TestID'])) {
$number_of_hits = "-1";
} else {
$number_of_hits = NumberOfTests($v['TestID'],_get_requested_day($start_time_frame, $day-1));
}
$amount_string = "0";
if ($number_of_hits>0)
$amount_string = "<b>$number_of_hits</b>";
else
$amount_string = "0";
if ($current_day > time())
if ($PRINTOUT)
$table .= "<td id=\"".$v['TestID']."\" align=\"center\">--</td>\n";
else
$table .= "<td bgcolor=\"#ffffff\" id=\"".$v['TestID']."\" align=\"center\">--</td>\n";
else
$table .= "<td bgcolor=\"#ffffaa\" id=\"".$v['TestID']."\" align=\"center\">".$amount_string."</td>\n";
}
$table .="</tr>\n";
}
echo $table;
}
function DisplayResultRow($group_id, $start_time_frame, $end_time_frame) {
global $db;
global $PRINTOUT;
$table ="<tr>\n";
$<API key> = date ("d",$start_time_frame);
$<API key> = date ("d",$end_time_frame);
$table.="<tr>\n";
$table .= "<td bgcolor=\"#CC9933\" align = \"center\"><strong>∑</strong></td>\n";
$sql = "SELECT TestID FROM tmp_laboratory WHERE GroupID='".$group_id."'";
$db_ptr=$db->Execute($sql);
$arr_ret = $db_ptr -> GetArray();
while (list($u,$v)=each($arr_ret)) {
$number_of_hits = <API key>($v['TestID'],$start_time_frame);
$amount_string = "0";
if ($number_of_hits>0)
$amount_string = "<b>$number_of_hits</b>";
if ($PRINTOUT)
$table .= "<td id=\"".$v['TestID']."\" align=\"center\">".$amount_string."</td>\n";
else
$table .= "<td bgcolor=\"#CC9933\" id=\"".$v['TestID']."\" align=\"center\">".$amount_string."</td>\n";
}
$table .="</tr>\n";
echo $table;
}
require_once('include/inc_timeframe.php');
require_once('gui/gui_laboratory.php');
?> |
#pragma once
#include "IDLTypes.h"
#include "JSDOMConvertBase.h"
namespace WebCore {
template<> struct Converter<IDLAny> : DefaultConverter<IDLAny> {
using ReturnType = JSC::JSValue;
static JSC::JSValue convert(JSC::ExecState&, JSC::JSValue value)
{
return value;
}
static JSC::JSValue convert(const JSC::Strong<JSC::Unknown>& value)
{
return value.get();
}
};
template<> struct JSConverter<IDLAny> {
static constexpr bool needsState = false;
static constexpr bool needsGlobalObject = false;
static JSC::JSValue convert(const JSC::JSValue& value)
{
return value;
}
static JSC::JSValue convert(const JSC::Strong<JSC::Unknown>& value)
{
return value.get();
}
};
} // namespace WebCore |
/**
* @file
*
* @brief RTEMS File Systems Block Routines
* @ingroup rtems_rfs
*
* These functions manage blocks in the RFS file system. A block is an area of
* the media and its size is set for a each specific media. The block size is
* set when the file system is set up and needs to be matched for it to be
* read correctly.
*
* Blocks are managed as groups. A block group or "group" is part of the total
* number of blocks being managed by the file system and exist to allow
* resources to localised. A file in a directory will be allocated blocks in
* the same group as the directory, and the blocks for the file will also be
* allocated in the same group.
*
* A group consist of a block bitmap, inodes and data blocks. The first block
* of the file system will hold the superblock. The block bitmap is a
* collection of blocks that hold a map of bits, one bit per block for each
* block in the group. When a file system is mounted the block bitmaps are
* read and a summary bit map is made. The summary bitmap has a single bit for
* 32 bits in the bitmap and is set when all 32 bits it maps to are set. This
* speeds up the search for a free block by a factor of 32.
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <inttypes.h>
#include <rtems/rfs/rtems-rfs-block.h>
#include <rtems/rfs/rtems-rfs-data.h>
#include <rtems/rfs/rtems-rfs-group.h>
#include <rtems/rfs/rtems-rfs-inode.h>
void
<API key> (<API key>* fs,
rtems_rfs_pos pos,
rtems_rfs_block_pos* bpos)
{
bpos->bno = pos / <API key> (fs);
bpos->boff = pos % <API key> (fs);
}
rtems_rfs_pos
<API key> (<API key>* fs,
rtems_rfs_block_pos* bpos)
{
return (bpos->bno * <API key> (fs)) + bpos->boff;
}
void
<API key> (<API key>* fs,
rtems_rfs_pos pos,
<API key>* size)
{
if (pos == 0)
<API key> (size);
else
{
size->count = pos / <API key> (fs) + 1;
size->offset = pos % <API key> (fs);
}
}
rtems_rfs_pos
<API key> (<API key>* fs,
<API key>* size)
{
uint32_t offset;
uint64_t block_size;
if (size->count == 0)
return 0;
if (size->offset == 0)
offset = <API key> (fs);
else
offset = size->offset;
block_size = <API key> (fs);
return (((uint64_t) (size->count - 1)) * block_size) + offset;
}
int
<API key> (<API key>* fs,
<API key>* inode,
rtems_rfs_block_map* map)
{
int b;
int rc;
/*
* Set the count to 0 so at least find fails, then open the handle and make
* sure the inode has been loaded into memory. If we did not load the inode
* do not unload it. The caller may assume it is still loaded when we return.
*/
map->dirty = false;
map->inode = NULL;
<API key> (&map->size);
<API key> (&map->bpos);
rc = <API key> (fs, &map->singly_buffer);
if (rc > 0)
return rc;
rc = <API key> (fs, &map->doubly_buffer);
if (rc > 0)
return rc;
rc = <API key> (fs, inode);
if (rc > 0)
{
<API key> (fs, &map->singly_buffer);
<API key> (fs, &map->doubly_buffer);
return rc;
}
/*
* Extract the block and block count data from the inode into the targets
* byte order.
*/
map->inode = inode;
for (b = 0; b < <API key>; b++)
map->blocks[b] = <API key> (inode, b);
map->size.count = <API key> (inode);
map->size.offset = <API key> (inode);
map->last_map_block = <API key> (inode);
map->last_data_block = <API key> (inode);
rc = <API key> (fs, inode, false);
return rc;
}
int
<API key> (<API key>* fs,
rtems_rfs_block_map* map)
{
int rc = 0;
int brc;
if (map->dirty && map->inode)
{
brc = <API key> (fs, map->inode);
if (brc > 0)
rc = brc;
if (rc == 0)
{
int b;
for (b = 0; b < <API key>; b++)
<API key> (map->inode, b, map->blocks[b]);
<API key> (map->inode, map->size.count);
<API key> (map->inode, map->size.offset);
<API key> (map->inode, map->last_map_block);
<API key> (map->inode, map->last_data_block);
brc = <API key> (fs, map->inode, true);
if (brc > 0)
rc = brc;
map->dirty = false;
}
}
map->inode = NULL;
brc = <API key> (fs, &map->singly_buffer);
if ((brc > 0) && (rc == 0))
rc = brc;
brc = <API key> (fs, &map->doubly_buffer);
if ((brc > 0) && (rc == 0))
rc = brc;
return rc;
}
/**
* Find a block indirectly held in a table of block numbers.
*
* @param fs The file system.
* @param buffer The handle to access the block data by.
* @param block The block number of the table of block numbers.
* @param offset The offset in the table of the block number to return. This is
* a block number offset not a byte offset into the table.
* @param result Pointer to the result of the search.
* @return int The error number (errno). No error if 0.
*/
static int
<API key> (<API key>* fs,
<API key>* buffer,
rtems_rfs_block_no block,
int offset,
rtems_rfs_block_no* result)
{
int rc;
/*
* If the handle has a buffer and this request is a different block the current
* buffer is released.
*/
rc = <API key> (fs, buffer, block, true);
if (rc > 0)
return rc;
*result = <API key> (buffer, offset);
if ((*result + 1) == 0)
*result = 0;
if (*result >= rtems_rfs_fs_blocks (fs))
{
if (rtems_rfs_trace (<API key>))
printf ("rtems-rfs: block-find: invalid block in table:"
" block=%" PRId32 ", indirect=%" PRId32 "/%d\n", *result, block, offset);
*result = 0;
rc = EIO;
}
return 0;
}
int
<API key> (<API key>* fs,
rtems_rfs_block_map* map,
rtems_rfs_block_pos* bpos,
rtems_rfs_block_no* block)
{
int rc = 0;
*block = 0;
/*
* Range checking here makes the remaining logic simpler.
*/
if (<API key> (bpos, &map->size))
return ENXIO;
/*
* If the block position is the same and we have found the block just return it.
*/
if ((bpos->bno == map->bpos.bno) && (map->bpos.block != 0))
{
*block = map->bpos.block;
}
else
{
/*
* Determine the type of access we need to perform. If the number of blocks
* is less than or equal to the number of slots in the inode the blocks are
* directly accessed.
*/
if (map->size.count <= <API key>)
{
*block = map->blocks[bpos->bno];
}
else
{
/*
* The map is either singly or doubly indirect.
*/
rtems_rfs_block_no direct;
rtems_rfs_block_no singly;
direct = bpos->bno % fs->blocks_per_block;
singly = bpos->bno / fs->blocks_per_block;
if (map->size.count <= fs-><API key>)
{
/*
* This is a single indirect table of blocks anchored off a slot in the
* inode.
*/
rc = <API key> (fs,
&map->singly_buffer,
map->blocks[singly],
direct, block);
}
else
{
/*
* The map is doubly indirect.
*/
rtems_rfs_block_no doubly;
doubly = singly / fs->blocks_per_block;
singly %= fs->blocks_per_block;
if (map->size.count < fs-><API key>)
{
rc = <API key> (fs,
&map->doubly_buffer,
map->blocks[doubly],
singly, &singly);
if (rc == 0)
{
rc = <API key> (fs,
&map->singly_buffer,
singly, direct, block);
}
}
else
{
/*
* This should never happen. Here so Joel can remove once his coverage
* testing gets to the file systems.
*/
rc = ENXIO;
}
}
}
}
if (rc == 0)
{
<API key> (&map->bpos, bpos);
map->bpos.block = *block;
}
return rc;
}
int
<API key> (<API key>* fs,
rtems_rfs_block_map* map,
rtems_rfs_pos_rel offset,
rtems_rfs_block_no* block)
{
rtems_rfs_block_pos bpos;
<API key> (&bpos, &map->bpos);
<API key> (fs, offset, &bpos);
return <API key> (fs, map, &bpos, block);
}
int
<API key> (<API key>* fs,
rtems_rfs_block_map* map,
rtems_rfs_block_no* block)
{
rtems_rfs_block_pos bpos;
bpos.bno = map->bpos.bno + 1;
bpos.boff = 0;
bpos.block = 0;
return <API key> (fs, map, &bpos, block);
}
/**
* Allocate an indirect block to a map.
*
* @param fs The file system data.
* @param map The map the allocation is for.
* @param buffer The buffer the indirect block is accessed by.
* @param block The block number of the indirect block allocated.
* @param upping True is upping the map to the next indirect level.
* @return int The error number (errno). No error if 0.
*/
static int
<API key> (<API key>* fs,
rtems_rfs_block_map* map,
<API key>* buffer,
rtems_rfs_block_no* block,
bool upping)
{
<API key> new_block;
int rc;
/*
* Save the new block locally because upping can have *block pointing to the
* slots which are cleared when upping.
*/
rc = <API key> (fs, map->last_map_block, false, &new_block);
if (rc > 0)
return rc;
rc = <API key> (fs, buffer, new_block, false);
if (rc > 0)
{
<API key> (fs, false, new_block);
return rc;
}
memset (<API key> (buffer), 0xff, <API key> (fs));
if (upping)
{
int b;
if (rtems_rfs_trace (<API key>))
printf ("rtems-rfs: block-map-grow: upping: block-count=%" PRId32 "\n",
map->size.count);
for (b = 0; b < <API key>; b++)
<API key> (buffer, b, map->blocks[b]);
memset (map->blocks, 0, sizeof (map->blocks));
}
<API key> (buffer);
*block = new_block;
map->last_map_block = new_block;
return 0;
}
int
<API key> (<API key>* fs,
rtems_rfs_block_map* map,
size_t blocks,
rtems_rfs_block_no* new_block)
{
int b;
if (rtems_rfs_trace (<API key>))
printf ("rtems-rfs: block-map-grow: entry: blocks=%zd count=%" PRIu32 "\n",
blocks, map->size.count);
if ((map->size.count + blocks) >= <API key> (fs))
return EFBIG;
/*
* Allocate a block at a time. The buffer handles hold the blocks so adding
* this way does not thrash the cache with lots of requests.
*/
for (b = 0; b < blocks; b++)
{
<API key> block;
int rc;
/*
* Allocate the block. If an indirect block is needed and cannot be
* allocated free this block.
*/
rc = <API key> (fs, map->last_data_block,
false, &block);
if (rc > 0)
return rc;
if (map->size.count < <API key>)
map->blocks[map->size.count] = block;
else
{
/*
* Single indirect access is occuring. It could still be doubly indirect.
*/
rtems_rfs_block_no direct;
rtems_rfs_block_no singly;
direct = map->size.count % fs->blocks_per_block;
singly = map->size.count / fs->blocks_per_block;
if (map->size.count < fs-><API key>)
{
/*
* Singly indirect tables are being used. Allocate a new block for a
* mapping table if direct is 0 or we are moving up (upping). If upping
* move the direct blocks into the table and if not this is the first
* entry of a new block.
*/
if ((direct == 0) ||
((singly == 0) && (direct == <API key>)))
{
/*
* Upping is when we move from direct to singly indirect.
*/
bool upping;
upping = map->size.count == <API key>;
rc = <API key> (fs, map,
&map->singly_buffer,
&map->blocks[singly],
upping);
}
else
{
rc = <API key> (fs, &map->singly_buffer,
map->blocks[singly], true);
}
if (rc > 0)
{
<API key> (fs, false, block);
return rc;
}
}
else
{
/*
* Doubly indirect tables are being used.
*/
rtems_rfs_block_no doubly;
rtems_rfs_block_no singly_block;
doubly = singly / fs->blocks_per_block;
singly %= fs->blocks_per_block;
/*
* Allocate a new block for a singly indirect table if direct is 0 as
* it is the first entry of a new block. We may also need to allocate a
* doubly indirect block as well. Both always occur when direct is 0
* and the doubly indirect block when singly is 0.
*/
if (direct == 0)
{
rc = <API key> (fs, map,
&map->singly_buffer,
&singly_block,
false);
if (rc > 0)
{
<API key> (fs, false, block);
return rc;
}
/*
* Allocate a new block for a doubly indirect table if singly is 0 as
* it is the first entry of a new singly indirect block.
*/
if ((singly == 0) ||
((doubly == 0) && (singly == <API key>)))
{
bool upping;
upping = map->size.count == fs-><API key>;
rc = <API key> (fs, map,
&map->doubly_buffer,
&map->blocks[doubly],
upping);
if (rc > 0)
{
<API key> (fs, false, singly_block);
<API key> (fs, false, block);
return rc;
}
}
else
{
rc = <API key> (fs, &map->doubly_buffer,
map->blocks[doubly], true);
if (rc > 0)
{
<API key> (fs, false, singly_block);
<API key> (fs, false, block);
return rc;
}
}
<API key> (&map->doubly_buffer,
singly,
singly_block);
}
else
{
rc = <API key> (fs,
&map->doubly_buffer,
map->blocks[doubly],
true);
if (rc > 0)
{
<API key> (fs, false, block);
return rc;
}
singly_block = <API key> (&map->doubly_buffer,
singly);
rc = <API key> (fs, &map->singly_buffer,
singly_block, true);
if (rc > 0)
{
<API key> (fs, false, block);
return rc;
}
}
}
<API key> (&map->singly_buffer, direct, block);
}
map->size.count++;
map->size.offset = 0;
if (b == 0)
*new_block = block;
map->last_data_block = block;
map->dirty = true;
}
return 0;
}
/**
* Shrink an indirect block.
*
* @param fs The file system data.
* @param map The map the allocation is for.
* @param buffer The buffer the indirect block is accessed by.
* @param indirect The index index in the inode's block table.
* @param index The index in the indirect table of the block.
* @return int The error number (errno). No error if 0.
*/
static int
<API key> (<API key>* fs,
rtems_rfs_block_map* map,
<API key>* buffer,
rtems_rfs_block_no indirect,
rtems_rfs_block_no index)
{
int rc = 0;
/*
* If this is the first block in the indirect table (index == 0), ie the last
* block to be freed and the indirect block is now also free, or we have only
* one indirect table and we can fit the remaining blocks into the inode,
* then either move to the next indirect block or move the remaining blocks
* into the inode and free the indirect table's block.
*/
if ((index == 0) ||
((indirect == 0) && (index == <API key>)))
{
rtems_rfs_block_no block_to_free = map->blocks[indirect];
if ((indirect == 0) && (index == <API key>))
{
/*
* Move to direct inode access.
*/
int b;
for (b = 0; b < <API key>; b++)
map->blocks[b] = <API key> (buffer, b);
}
else
{
/*
* One less singly indirect block in the inode.
*/
map->blocks[indirect] = 0;
}
rc = <API key> (fs, false, block_to_free);
if (rc > 0)
return rc;
map->last_map_block = block_to_free;
}
return rc;
}
int
<API key> (<API key>* fs,
rtems_rfs_block_map* map,
size_t blocks)
{
if (rtems_rfs_trace (<API key>))
printf ("rtems-rfs: block-map-shrink: entry: blocks=%zd count=%" PRIu32 "\n",
blocks, map->size.count);
if (map->size.count == 0)
return 0;
if (blocks > map->size.count)
blocks = map->size.count;
while (blocks)
{
rtems_rfs_block_no block;
rtems_rfs_block_no block_to_free;
int rc;
block = map->size.count - 1;
if (block < <API key>)
{
/*
* We have less than <API key> so they are held in the
* inode.
*/
block_to_free = map->blocks[block];
map->blocks[block] = 0;
}
else
{
/*
* Single indirect access is occuring. It could still be doubly indirect.
*
* The 'direct' variable is the offset in to the indirect table of
* blocks, and 'singly' is the inode block index of the singly indirect
* table of block numbers.
*/
rtems_rfs_block_no direct;
rtems_rfs_block_no singly;
direct = block % fs->blocks_per_block;
singly = block / fs->blocks_per_block;
if (block < fs-><API key>)
{
/*
* Request the indirect block and then obtain the block number from the
* indirect block.
*/
rc = <API key> (fs, &map->singly_buffer,
map->blocks[singly], true);
if (rc > 0)
return rc;
block_to_free = <API key> (&map->singly_buffer,
direct);
rc = <API key> (fs, map, &map->singly_buffer,
singly, direct);
if (rc)
return rc;
}
else if (block < fs-><API key>)
{
/*
* Doubly indirect tables are being used. The 'doubly' variable is the
* index in to the inode's block table and points to a singly indirect
* table of block numbers. The 'doubly_singly' variable is the index
* into the doubly indirect table pointing to the singly indirect table
* of block numbers that form the map. This is used later to determine
* if the current doubly indirect table needs to be freed. The 'direct'
* value is still valid for doubly indirect tables.
*/
rtems_rfs_block_no doubly;
rtems_rfs_block_no doubly_singly;
doubly = singly / fs->blocks_per_block;
doubly_singly = singly % fs->blocks_per_block;
rc = <API key> (fs, &map->doubly_buffer,
map->blocks[doubly], true);
if (rc > 0)
return rc;
singly = <API key> (&map->doubly_buffer,
doubly_singly);
/*
* Read the singly indirect table and get the block number.
*/
rc = <API key> (fs, &map->singly_buffer,
singly, true);
if (rc > 0)
return rc;
block_to_free = <API key> (&map->singly_buffer,
direct);
if (direct == 0)
{
rc = <API key> (fs, false, singly);
if (rc > 0)
return rc;
map->last_map_block = singly;
rc = <API key> (fs, map, &map->doubly_buffer,
doubly, doubly_singly);
if (rc)
return rc;
}
}
else
{
rc = EIO;
break;
}
}
rc = <API key> (fs, false, block_to_free);
if (rc > 0)
return rc;
map->size.count
map->size.offset = 0;
map->last_data_block = block_to_free;
map->dirty = true;
blocks
}
if (map->size.count == 0)
{
map->last_map_block = 0;
map->last_data_block = 0;
}
/*
* Keep the position inside the map.
*/
if (<API key> (&map->bpos, &map->size))
<API key> (&map->size, &map->bpos);
return 0;
}
int
<API key> (<API key>* fs,
rtems_rfs_block_map* map)
{
return <API key> (fs, map, map->size.count);
} |
#include <stdint.h>
#include <device/pci_def.h>
#include <arch/io.h>
#include <device/pnp_def.h>
#include <cpu/x86/lapic.h>
#include <stdlib.h>
#include <console/console.h>
#include "drivers/pc80/udelay_io.c"
#include "lib/delay.c"
#include "southbridge/intel/esb6300/early_smbus.c"
#include "northbridge/intel/e7525/raminit.h"
#include "cpu/x86/lapic/boot_cpu.c"
#include "cpu/x86/mtrr/earlymtrr.c"
#include "debug.c"
#include "watchdog.c"
#include "southbridge/intel/esb6300/reset.c"
#include "superio/winbond/w83627hf/early_serial.c"
#include <superio/winbond/w83627hf/w83627hf.h>
#include "northbridge/intel/e7525/memory_initialized.c"
#include "cpu/x86/bist.h"
#include <spd.h>
#define CONSOLE_SERIAL_DEV PNP_DEV(0x2e, W83627HF_SP1)
#define HIDDEN_SERIAL_DEV PNP_DEV(0x2e, W83627HF_SP2)
#define DUMMY_DEV PNP_DEV(0x2e, 0)
#define DEVPRES_CONFIG ( \
DEVPRES_D1F0 | \
DEVPRES_D2F0 | \
DEVPRES_D3F0 | \
DEVPRES_D4F0 | \
DEVPRES_D6F0 | \
0 )
#define DEVPRES1_CONFIG (DEVPRES1_D0F1 | DEVPRES1_D8F0)
static inline int spd_read_byte(unsigned device, unsigned address)
{
return smbus_read_byte(device, address);
}
#include "northbridge/intel/e7525/raminit.c"
#include "lib/generic_sdram.c"
#include "arch/x86/lib/stages.c"
static void main(unsigned long bist)
{
static const struct mem_controller mch[] = {
{
.node_id = 0,
.f0 = PCI_DEV(0, 0x00, 0),
.f1 = PCI_DEV(0, 0x00, 1),
.f2 = PCI_DEV(0, 0x00, 2),
.f3 = PCI_DEV(0, 0x00, 3),
.channel0 = {DIMM3, DIMM2, DIMM1, DIMM0, },
.channel1 = {DIMM7, DIMM6, DIMM5, DIMM4, },
}
};
if (bist == 0) {
/* Skip this if there was a built in self test failure */
early_mtrr_init();
if (memory_initialized())
skip_romstage();
}
<API key>(DUMMY_DEV);
<API key>(CONSOLE_SERIAL_DEV, CONFIG_TTYS0_BASE);
console_init();
/* MOVE ME TO A BETTER LOCATION !!! */
/* config LPC decode for flash memory access */
device_t dev;
dev = pci_locate_device(PCI_ID(0x8086, 0x25a1), 0);
if (dev == PCI_DEV_INVALID)
die("Missing 6300ESB?");
pci_write_config32(dev, 0xe8, 0x00000000);
pci_write_config8(dev, 0xf0, 0x00);
#if 0
<API key>();
print_pci_devices();
#endif
#if 1
enable_smbus();
#endif
#if 0
int i;
for(i = 0; i < 1; i++)
dump_spd_registers();
#endif
disable_watchdogs();
sdram_initialize(ARRAY_SIZE(mch), mch);
#if 1
dump_pci_device(PCI_DEV(0, 0x00, 0));
// dump_bar14(PCI_DEV(0, 0x00, 0));
#endif
} |
/*
* Functions related to interactive commands via "callgrind.cmd"
*/
#include "config.h"
#include "global.h"
#include <<API key>.h> // VG_N_THREADS
// Version for the syntax in command/result files for interactive control
#define COMMAND_VERSION "1.0"
static Char outbuf[FILENAME_LEN + FN_NAME_LEN + OBJ_NAME_LEN];
static Char* command_file = 0;
static Char* command_file2 = 0;
static Char* <API key> = 0;
static Char* result_file = 0;
static Char* result_file2 = 0;
static Char* current_result_file = 0;
static Char* info_file = 0;
static Char* out_file = 0;
static Int thisPID = 0;
/**
* Setup for interactive control of a callgrind run
*/
static void setup_control(void)
{
Int fd, size;
SysRes res;
Char* dir;
CLG_ASSERT(thisPID != 0);
fd = -1;
dir = CLG_(get_out_directory)();
out_file = CLG_(get_out_file)();
/* name of command file */
size = VG_(strlen)(dir) + VG_(strlen)(DEFAULT_COMMANDNAME) +10;
command_file = (char*) CLG_MALLOC("cl.command.sc.1", size);
CLG_ASSERT(command_file != 0);
VG_(sprintf)(command_file, "%s/%s.%d",
dir, DEFAULT_COMMANDNAME, thisPID);
/* This is for compatibility with the "Force Now" Button of current
* KCachegrind releases, as it doesn't use ".pid" to distinguish
* different callgrind instances from same base directory.
*/
command_file2 = (char*) CLG_MALLOC("cl.command.sc.2", size);
CLG_ASSERT(command_file2 != 0);
VG_(sprintf)(command_file2, "%s/%s",
dir, DEFAULT_COMMANDNAME);
size = VG_(strlen)(dir) + VG_(strlen)(DEFAULT_RESULTNAME) +10;
result_file = (char*) CLG_MALLOC("cl.command.sc.3", size);
CLG_ASSERT(result_file != 0);
VG_(sprintf)(result_file, "%s/%s.%d",
dir, DEFAULT_RESULTNAME, thisPID);
/* If we get a command from a command file without .pid, use
* a result file without .pid suffix
*/
result_file2 = (char*) CLG_MALLOC("cl.command.sc.4", size);
CLG_ASSERT(result_file2 != 0);
VG_(sprintf)(result_file2, "%s/%s",
dir, DEFAULT_RESULTNAME);
info_file = (char*) CLG_MALLOC("cl.command.sc.5",
VG_(strlen)(DEFAULT_INFONAME) + 10);
CLG_ASSERT(info_file != 0);
VG_(sprintf)(info_file, "%s.%d", DEFAULT_INFONAME, thisPID);
CLG_DEBUG(1, "Setup for interactive control (PID: %d):\n", thisPID);
CLG_DEBUG(1, " output file: '%s'\n", out_file);
CLG_DEBUG(1, " command file: '%s'\n", command_file);
CLG_DEBUG(1, " result file: '%s'\n", result_file);
CLG_DEBUG(1, " info file: '%s'\n", info_file);
/* create info file to indicate that we are running */
res = VG_(open)(info_file, VKI_O_WRONLY|VKI_O_TRUNC, 0);
if (res.isError) {
res = VG_(open)(info_file, VKI_O_CREAT|VKI_O_WRONLY,
VKI_S_IRUSR|VKI_S_IWUSR);
if (res.isError) {
VG_(message)(Vg_DebugMsg,
"warning: can't write info file '%s'", info_file);
info_file = 0;
fd = -1;
}
}
if (!res.isError)
fd = (Int) res.res;
if (fd>=0) {
Char buf[512];
Int i;
WRITE_STR3(fd,
"# This file is generated by Callgrind-" VERSION ".\n"
"# It is used to enable controlling the supervision of\n"
"# '", VG_(args_the_exename), "'\n"
"# by external tools.\n\n");
VG_(sprintf)(buf, "version: " COMMAND_VERSION "\n");
VG_(write)(fd, (void*)buf, VG_(strlen)(buf));
WRITE_STR3(fd, "base: ", dir, "\n");
WRITE_STR3(fd, "dumps: ", out_file, "\n");
WRITE_STR3(fd, "control: ", command_file, "\n");
WRITE_STR3(fd, "result: ", result_file, "\n");
WRITE_STR2(fd, "cmd: ", VG_(args_the_exename));
for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
HChar* arg = * (HChar**)VG_(indexXA)( VG_(args_for_client), i );
if (!arg) continue;
WRITE_STR2(fd, " ", arg);
}
VG_(write)(fd, "\n", 1);
VG_(close)(fd);
}
}
void CLG_(init_command)()
{
thisPID = VG_(getpid)();
setup_control();
}
void CLG_(finish_command)()
{
/* unlink info file */
if (info_file) VG_(unlink)(info_file);
}
static Int createRes(Int fd)
{
SysRes res;
if (fd > -2) return fd;
/* fd == -2: No error, but we need to create the file */
CLG_ASSERT(current_result_file != 0);
res = VG_(open)(current_result_file,
VKI_O_CREAT|VKI_O_WRONLY|VKI_O_TRUNC,
VKI_S_IRUSR|VKI_S_IWUSR);
/* VG_(open) can return any negative number on error. Remap errors to -1,
* to not confuse it with our special value -2
*/
if (res.isError) fd = -1;
else fd = (Int) res.res;
return fd;
}
/* Run Info: Persistant information of the callgrind run */
static Int dump_info(Int fd)
{
Char* buf = outbuf;
int i;
if ( (fd = createRes(fd)) <0) return fd;
/* creator */
VG_(sprintf)(buf, "creator: callgrind-" VERSION "\n");
VG_(write)(fd, (void*)buf, VG_(strlen)(buf));
/* version */
VG_(sprintf)(buf, "version: " COMMAND_VERSION "\n");
VG_(write)(fd, (void*)buf, VG_(strlen)(buf));
/* "pid:" line */
VG_(sprintf)(buf, "pid: %d\n", VG_(getpid)());
VG_(write)(fd, (void*)buf, VG_(strlen)(buf));
/* "base:" line */
WRITE_STR3(fd, "base: ", out_file, "\n");
/* "cmd:" line */
WRITE_STR2(fd, "cmd: ", VG_(args_the_exename));
for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) {
HChar* arg = * (HChar**)VG_(indexXA)( VG_(args_for_client), i );
if (!arg) continue;
WRITE_STR2(fd, " ", arg);
}
VG_(write)(fd, "\n", 1);
return fd;
}
/* Helper for dump_state */
Int dump_fd;
void static <API key>(thread_info* ti)
{
Char* buf = outbuf;
int t = CLG_(current_tid);
Int p, i;
static FullCost sum = 0, tmp = 0;
BBCC *from, *to;
call_entry* ce;
p = VG_(sprintf)(buf, "events-%d: ", t);
CLG_(init_cost_lz)( CLG_(sets).full, &sum );
CLG_(copy_cost_lz)( CLG_(sets).full, &tmp, ti->lastdump_cost );
CLG_(add_diff_cost)( CLG_(sets).full, sum,
ti->lastdump_cost,
ti->states.entry[0]->cost);
CLG_(copy_cost)( CLG_(sets).full, ti->lastdump_cost, tmp );
p += CLG_(sprint_mappingcost)(buf + p, CLG_(dumpmap), sum);
p += VG_(sprintf)(buf+p, "\n");
VG_(write)(dump_fd, (void*)buf, p);
p = VG_(sprintf)(buf, "frames-%d: %d\n", t,
CLG_(current_call_stack).sp);
VG_(write)(dump_fd, (void*)buf, p);
ce = 0;
for(i = 0; i < CLG_(current_call_stack).sp; i++) {
ce = CLG_(get_call_entry)(i);
/* if this frame is skipped, we don't have counters */
if (!ce->jcc) continue;
from = ce->jcc->from;
p = VG_(sprintf)(buf, "function-%d-%d: %s\n",t, i,
from->cxt->fn[0]->name);
VG_(write)(dump_fd, (void*)buf, p);
p = VG_(sprintf)(buf, "calls-%d-%d: ",t, i);
p+= VG_(sprintf)(buf+p, "%llu\n", ce->jcc->call_counter);
VG_(write)(dump_fd, (void*)buf, p);
/* FIXME: EventSets! */
CLG_(copy_cost)( CLG_(sets).full, sum, ce->jcc->cost );
CLG_(copy_cost)( CLG_(sets).full, tmp, ce->enter_cost );
CLG_(add_diff_cost)( CLG_(sets).full, sum,
ce->enter_cost, CLG_(current_state).cost );
CLG_(copy_cost)( CLG_(sets).full, ce->enter_cost, tmp );
p = VG_(sprintf)(buf, "events-%d-%d: ",t, i);
p += CLG_(sprint_mappingcost)(buf + p, CLG_(dumpmap), sum );
p += VG_(sprintf)(buf+p, "\n");
VG_(write)(dump_fd, (void*)buf, p);
}
if (ce && ce->jcc) {
to = ce->jcc->to;
p = VG_(sprintf)(buf, "function-%d-%d: %s\n",t, i,
to->cxt->fn[0]->name );
VG_(write)(dump_fd, (void*)buf, p);
}
}
/* Dump info on current callgrind state */
static Int dump_state(Int fd)
{
Char* buf = outbuf;
thread_info** th;
int t, p;
Int orig_tid = CLG_(current_tid);
if ( (fd = createRes(fd)) <0) return fd;
VG_(sprintf)(buf, "instrumentation: %s\n",
CLG_(instrument_state) ? "on":"off");
VG_(write)(fd, (void*)buf, VG_(strlen)(buf));
if (!CLG_(instrument_state)) return fd;
VG_(sprintf)(buf, "executed-bbs: %llu\n", CLG_(stat).bb_executions);
VG_(write)(fd, (void*)buf, VG_(strlen)(buf));
VG_(sprintf)(buf, "executed-calls: %llu\n", CLG_(stat).call_counter);
VG_(write)(fd, (void*)buf, VG_(strlen)(buf));
VG_(sprintf)(buf, "distinct-bbs: %d\n", CLG_(stat).distinct_bbs);
VG_(write)(fd, (void*)buf, VG_(strlen)(buf));
VG_(sprintf)(buf, "distinct-calls: %d\n", CLG_(stat).distinct_jccs);
VG_(write)(fd, (void*)buf, VG_(strlen)(buf));
VG_(sprintf)(buf, "distinct-functions: %d\n", CLG_(stat).distinct_fns);
VG_(write)(fd, (void*)buf, VG_(strlen)(buf));
VG_(sprintf)(buf, "distinct-contexts: %d\n", CLG_(stat).distinct_contexts);
VG_(write)(fd, (void*)buf, VG_(strlen)(buf));
/* "events:" line. Given here because it will be dynamic in the future */
p = VG_(sprintf)(buf, "events: ");
CLG_(sprint_eventmapping)(buf+p, CLG_(dumpmap));
VG_(write)(fd, (void*)buf, VG_(strlen)(buf));
VG_(write)(fd, "\n", 1);
/* "part:" line (number of last part. Is 0 at start */
VG_(sprintf)(buf, "\npart: %d\n", CLG_(get_dump_counter)());
VG_(write)(fd, (void*)buf, VG_(strlen)(buf));
/* threads */
th = CLG_(get_threads)();
p = VG_(sprintf)(buf, "threads:");
for(t=1;t<VG_N_THREADS;t++) {
if (!th[t]) continue;
p += VG_(sprintf)(buf+p, " %d", t);
}
p += VG_(sprintf)(buf+p, "\n");
VG_(write)(fd, (void*)buf, p);
VG_(sprintf)(buf, "current-tid: %d\n", orig_tid);
VG_(write)(fd, (void*)buf, VG_(strlen)(buf));
/* current event counters */
dump_fd = fd;
CLG_(forall_threads)(<API key>);
return fd;
}
void CLG_(check_command)()
{
/* check for dumps needed */
static Char buf[512];
static Char cmdBuffer[512];
Char *cmdPos = 0, *cmdNextLine = 0;
Int fd, bytesRead = 0, do_kill = 0;
SysRes res;
Int currentPID;
static Int check_counter = 0;
/* Check for PID change, i.e. whether we run as child after a fork.
* If yes, we setup interactive control for the new process
*/
currentPID = VG_(getpid)();
if (thisPID != currentPID) {
thisPID = currentPID;
setup_control();
}
/* Toggle between 2 command files, with/without ".pid" postfix
* (needed for compatibility with KCachegrind, which wants to trigger
* a dump by writing into a command file without the ".pid" postfix)
*/
check_counter++;
if (check_counter % 2) {
<API key> = command_file;
current_result_file = result_file;
}
else {
<API key> = command_file2;
current_result_file = result_file2;
}
res = VG_(open)(<API key>, VKI_O_RDONLY,0);
if (!res.isError) {
fd = (Int) res.res;
bytesRead = VG_(read)(fd,cmdBuffer,500);
cmdBuffer[500] = 0; /* no command overrun please */
VG_(close)(fd);
/* don't delete command file on read error (e.g. EAGAIN) */
if (bytesRead>0) {
cmdPos = cmdBuffer;
}
}
/* force creation of result file if needed */
fd = -2;
while((bytesRead>0) && *cmdPos) {
/* Calculate pointer for next line */
cmdNextLine = cmdPos+1;
while((bytesRead>0) && *cmdNextLine && (*cmdNextLine != '\n')) {
cmdNextLine++;
bytesRead
}
if ((bytesRead>0) && (*cmdNextLine == '\n')) {
*cmdNextLine = 0;
cmdNextLine++;
bytesRead
}
/* Command with integer option */
if ((*cmdPos >= '0') && (*cmdPos <='9')) {
int value = *cmdPos-'0';
cmdPos++;
while((*cmdPos >= '0') && (*cmdPos <='9')) {
value = 10*value + (*cmdPos-'0');
cmdPos++;
}
while((*cmdPos == ' ') || (*cmdPos == '\t')) cmdPos++;
switch(*cmdPos) {
#if CLG_ENABLE_DEBUG
/* verbosity */
case 'V':
case 'v':
CLG_(clo).verbose = value;
break;
#endif
default:
break;
}
cmdPos = cmdNextLine;
continue;
}
/* Command with boolean/switch option */
if ((*cmdPos=='+') ||
(*cmdPos=='-')) {
int value = (cmdPos[0] == '+');
cmdPos++;
while((*cmdPos == ' ') || (*cmdPos == '\t')) cmdPos++;
switch(*cmdPos) {
case 'I':
case 'i':
CLG_(<API key>)("Command", value);
break;
default:
break;
}
cmdPos = cmdNextLine;
continue;
}
/* regular command */
switch(*cmdPos) {
case 'D':
case 'd':
/* DUMP */
/* skip command */
while(*cmdPos && (*cmdPos != ' ')) cmdPos++;
if (*cmdPos)
VG_(sprintf)(buf, "Dump Command:%s", cmdPos);
else
VG_(sprintf)(buf, "Dump Command");
CLG_(dump_profile)(buf, False);
break;
case 'Z':
case 'z':
CLG_(zero_all_cost)(False);
break;
case 'K':
case 'k':
/* Kill: Delay to be able to remove command file before. */
do_kill = 1;
break;
case 'I':
case 'i':
fd = dump_info(fd);
break;
case 's':
case 'S':
fd = dump_state(fd);
break;
case 'O':
case 'o':
/* Options Info */
if ( (fd = createRes(fd)) <0) break;
VG_(sprintf)(buf, "\ndesc: Option: --skip-plt=%s\n",
CLG_(clo).skip_plt ? "yes" : "no");
VG_(write)(fd, (void*)buf, VG_(strlen)(buf));
VG_(sprintf)(buf, "desc: Option: --collect-jumps=%s\n",
CLG_(clo).collect_jumps ? "yes" : "no");
VG_(write)(fd, (void*)buf, VG_(strlen)(buf));
VG_(sprintf)(buf, "desc: Option: --separate-recs=%d\n",
CLG_(clo).separate_recursions);
VG_(write)(fd, (void*)buf, VG_(strlen)(buf));
VG_(sprintf)(buf, "desc: Option: --separate-callers=%d\n",
CLG_(clo).separate_callers);
VG_(write)(fd, (void*)buf, VG_(strlen)(buf));
break;
default:
break;
}
cmdPos = cmdNextLine;
}
/* If command executed, delete command file */
if (cmdPos) VG_(unlink)(<API key>);
if (fd>=0) VG_(close)(fd);
if (do_kill) {
VG_(message)(Vg_UserMsg,
"Killed because of command from %s", <API key>);
CLG_(fini)(0);
VG_(exit)(1);
}
} |
/* The migration of target macros to target hooks works as follows:
1. Create a target hook that uses the existing target macros to
implement the same functionality.
2. Convert all the MI files to use the hook instead of the macro.
3. Repeat for a majority of the remaining target macros. This will
take some time.
4. Tell target maintainers to start migrating.
5. Eventually convert the backends to override the hook instead of
defining the macros. This will take some time too.
6. TBD when, poison the macros. Unmigrated targets will break at
this point.
Note that we expect steps 1-3 to be done by the people that
understand what the MI does with each macro, and step 5 to be done
by the target maintainers for their respective targets.
Note that steps 1 and 2 don't have to be done together, but no
target can override the new hook until step 2 is complete for it.
Once the macros are poisoned, we will revert to the old migration
rules - migrate the macro, callers, and targets all at once. This
comment can thus be removed at that point. */
#include "config.h"
#include "system.h"
#include "coretypes.h"
#include "target.h"
#include "function.h"
#include "rtl.h"
#include "tree.h"
#include "tree-ssa-alias.h"
#include "gimple-expr.h"
#include "tm_p.h"
#include "stringpool.h"
#include "tree-ssanames.h"
#include "optabs.h"
#include "regs.h"
#include "recog.h"
#include "diagnostic-core.h"
#include "fold-const.h"
#include "stor-layout.h"
#include "varasm.h"
#include "flags.h"
#include "explow.h"
#include "calls.h"
#include "expr.h"
#include "output.h"
#include "reload.h"
#include "intl.h"
#include "opts.h"
#include "gimplify.h"
bool
<API key> (machine_mode mode ATTRIBUTE_UNUSED,
rtx addr ATTRIBUTE_UNUSED,
bool strict ATTRIBUTE_UNUSED)
{
#ifdef <API key>
/* Defer to the old implementation using a goto. */
if (strict)
return <API key> (mode, addr);
else
return memory_address_p (mode, addr);
#else
gcc_unreachable ();
#endif
}
void
<API key> (rtx fun ATTRIBUTE_UNUSED)
{
#ifdef <API key>
<API key> (asm_out_file, fun);
#endif
}
int
<API key> (const_rtx x, unsigned flags)
{
int i;
/* Any floating arithmetic may trap. */
if ((SCALAR_FLOAT_MODE_P (GET_MODE (x)) && flag_trapping_math))
return 1;
for (i = 0; i < XVECLEN (x, 0); ++i)
{
if (may_trap_p_1 (XVECEXP (x, 0, i), flags))
return 1;
}
return 0;
}
machine_mode
<API key> (const_tree type ATTRIBUTE_UNUSED,
machine_mode mode,
int *punsignedp ATTRIBUTE_UNUSED,
const_tree funtype ATTRIBUTE_UNUSED,
int for_return ATTRIBUTE_UNUSED)
{
if (type != NULL_TREE && for_return == 2)
return promote_mode (type, mode, punsignedp);
return mode;
}
machine_mode
<API key> (const_tree type,
machine_mode mode,
int *punsignedp,
const_tree funtype ATTRIBUTE_UNUSED,
int for_return ATTRIBUTE_UNUSED)
{
return promote_mode (type, mode, punsignedp);
}
machine_mode
<API key> (machine_mode m1, machine_mode m2)
{
if (m1 == m2)
return m1;
return VOIDmode;
}
bool
<API key> (const_tree type,
const_tree fntype ATTRIBUTE_UNUSED)
{
return (TYPE_MODE (type) == BLKmode);
}
rtx
<API key> (rtx x, rtx orig_x ATTRIBUTE_UNUSED,
machine_mode mode ATTRIBUTE_UNUSED)
{
return x;
}
bool
<API key> (rtx *disp ATTRIBUTE_UNUSED,
rtx *offset ATTRIBUTE_UNUSED,
machine_mode mode ATTRIBUTE_UNUSED)
{
return false;
}
rtx
<API key> (void)
{
error ("__builtin_saveregs not supported by this target");
return const0_rtx;
}
void
<API key> (cumulative_args_t ca ATTRIBUTE_UNUSED,
machine_mode mode ATTRIBUTE_UNUSED,
tree type ATTRIBUTE_UNUSED,
int *pretend_arg_size ATTRIBUTE_UNUSED,
int second_time ATTRIBUTE_UNUSED)
{
}
/* The default implementation of <API key>. */
rtx
<API key> (void)
{
return <API key>;
}
/* Generic hook that takes a CUMULATIVE_ARGS pointer and returns false. */
bool
<API key> (cumulative_args_t ca ATTRIBUTE_UNUSED)
{
return false;
}
bool
<API key> (cumulative_args_t ca ATTRIBUTE_UNUSED)
{
return (targetm.calls.<API key>
!= <API key>);
}
machine_mode
<API key> (void)
{
return targetm.unwind_word_mode ();
}
machine_mode
<API key> (void)
{
return word_mode;
}
machine_mode
<API key> (void)
{
return word_mode;
}
machine_mode
<API key> (void)
{
return word_mode;
}
/* The default implementation of <API key>. */
unsigned HOST_WIDE_INT
<API key> (machine_mode mode)
{
return <API key> ? GET_MODE_BITSIZE (mode) - 1 : 0;
}
/* The default implementation of <API key>. */
unsigned int
<API key> (machine_mode mode ATTRIBUTE_UNUSED)
{
return have_insn_for (DIV, mode) ? 3 : 2;
}
/* The default implementation of <API key>. */
int
<API key> (machine_mode mode ATTRIBUTE_UNUSED,
machine_mode mode_rep ATTRIBUTE_UNUSED)
{
return UNKNOWN;
}
/* Generic hook that takes a CUMULATIVE_ARGS pointer and returns true. */
bool
<API key> (cumulative_args_t a ATTRIBUTE_UNUSED)
{
return true;
}
/* Return machine mode for non-standard suffix
or VOIDmode if non-standard suffixes are unsupported. */
machine_mode
<API key> (char suffix ATTRIBUTE_UNUSED)
{
return VOIDmode;
}
/* The generic C++ ABI specifies this is a 64-bit value. */
tree
<API key> (void)
{
return <API key>;
}
/* Returns the size of the cookie to use when allocating an array
whose elements have the indicated TYPE. Assumes that it is already
known that a cookie is needed. */
tree
<API key> (tree type)
{
tree cookie_size;
/* We need to allocate an additional max (sizeof (size_t), alignof
(true_type)) bytes. */
tree sizetype_size;
tree type_align;
sizetype_size = size_in_bytes (sizetype);
type_align = size_int (TYPE_ALIGN_UNIT (type));
if (tree_int_cst_lt (type_align, sizetype_size))
cookie_size = sizetype_size;
else
cookie_size = type_align;
return cookie_size;
}
/* Return true if a parameter must be passed by reference. This version
of the <API key> hook uses just MUST_PASS_IN_STACK. */
bool
<API key> (cumulative_args_t c ATTRIBUTE_UNUSED,
machine_mode mode ATTRIBUTE_UNUSED, const_tree type ATTRIBUTE_UNUSED,
bool named_arg ATTRIBUTE_UNUSED)
{
return targetm.calls.must_pass_in_stack (mode, type);
}
/* Return true if a parameter follows callee copies conventions. This
version of the hook is true for all named arguments. */
bool
<API key> (cumulative_args_t ca ATTRIBUTE_UNUSED,
machine_mode mode ATTRIBUTE_UNUSED,
const_tree type ATTRIBUTE_UNUSED, bool named)
{
return named;
}
/* Emit to STREAM the assembler syntax for insn operand X. */
void
<API key> (FILE *stream ATTRIBUTE_UNUSED, rtx x ATTRIBUTE_UNUSED,
int code ATTRIBUTE_UNUSED)
{
#ifdef PRINT_OPERAND
PRINT_OPERAND (stream, x, code);
#else
gcc_unreachable ();
#endif
}
/* Emit to STREAM the assembler syntax for an insn operand whose memory
address is X. */
void
<API key> (FILE *stream ATTRIBUTE_UNUSED,
machine_mode /*mode*/,
rtx x ATTRIBUTE_UNUSED)
{
#ifdef <API key>
<API key> (stream, x);
#else
gcc_unreachable ();
#endif
}
/* Return true if CODE is a valid punctuation character for the
`print_operand' hook. */
bool
<API key> (unsigned char code ATTRIBUTE_UNUSED)
{
#ifdef <API key>
return <API key> (code);
#else
return false;
#endif
}
/* The default implementation of <API key>. */
tree
<API key> (const char *name ATTRIBUTE_UNUSED)
{
const char *skipped = name + (*name == '*' ? 1 : 0);
const char *stripped = targetm.strip_name_encoding (skipped);
if (*name != '*' && user_label_prefix[0])
stripped = ACONCAT ((user_label_prefix, stripped, NULL));
return get_identifier (stripped);
}
/* True if MODE is valid for the target. By "valid", we mean able to
be manipulated in non-trivial ways. In particular, this means all
the arithmetic is supported.
By default we guess this means that any C type is supported. If
we can't map the mode back to a type that would be available in C,
then reject it. Special case, here, is the double-word arithmetic
supported by optabs.c. */
bool
<API key> (machine_mode mode)
{
int precision = GET_MODE_PRECISION (mode);
switch (GET_MODE_CLASS (mode))
{
case MODE_PARTIAL_INT:
case MODE_INT:
if (precision == CHAR_TYPE_SIZE)
return true;
if (precision == SHORT_TYPE_SIZE)
return true;
if (precision == INT_TYPE_SIZE)
return true;
if (precision == LONG_TYPE_SIZE)
return true;
if (precision == LONG_LONG_TYPE_SIZE)
return true;
if (precision == 2 * BITS_PER_WORD)
return true;
return false;
case MODE_FLOAT:
if (precision == FLOAT_TYPE_SIZE)
return true;
if (precision == DOUBLE_TYPE_SIZE)
return true;
if (precision == <API key>)
return true;
return false;
case MODE_DECIMAL_FLOAT:
case MODE_FRACT:
case MODE_UFRACT:
case MODE_ACCUM:
case MODE_UACCUM:
return false;
default:
gcc_unreachable ();
}
}
/* Return true if libgcc supports floating-point mode MODE (known to
be supported as a scalar mode). */
bool
<API key> (machine_mode mode)
{
switch (mode)
{
#ifdef HAVE_SFmode
case SFmode:
#endif
#ifdef HAVE_DFmode
case DFmode:
#endif
#ifdef HAVE_XFmode
case XFmode:
#endif
#ifdef HAVE_TFmode
case TFmode:
#endif
return true;
default:
return false;
}
}
/* Make some target macros useable by target-independent code. */
bool
<API key> (void)
{
return !!WORDS_BIG_ENDIAN;
}
bool
<API key> (void)
{
return !!<API key>;
}
/* True if the target supports floating-point exceptions and rounding
modes. */
bool
<API key> (void)
{
#ifdef HAVE_adddf3
return HAVE_adddf3;
#else
return false;
#endif
}
/* True if the target supports decimal floating point. */
bool
<API key> (void)
{
return <API key>;
}
/* True if the target supports fixed-point arithmetic. */
bool
<API key> (void)
{
return ENABLE_FIXED_POINT;
}
/* True if the target supports GNU indirect functions. */
bool
default_has_ifunc_p (void)
{
return <API key>;
}
/* NULL if INSN insn is valid within a low-overhead loop, otherwise returns
an error message.
This function checks whether a given INSN is valid within a low-overhead
loop. If INSN is invalid it returns the reason for that, otherwise it
returns NULL. A called function may clobber any special registers required
for low-overhead looping. Additionally, some targets (eg, PPC) use the count
register for branch on table instructions. We reject the doloop pattern in
these cases. */
const char *
<API key> (const rtx_insn *insn)
{
if (CALL_P (insn))
return "Function call in loop.";
if (tablejump_p (insn, NULL, NULL) || computed_jump_p (insn))
return "Computed branch in the loop.";
return NULL;
}
/* Mapping of builtin functions to vectorized variants. */
tree
<API key> (unsigned int, tree, tree)
{
return NULL_TREE;
}
/* Mapping of target builtin functions to vectorized variants. */
tree
<API key> (tree, tree, tree)
{
return NULL_TREE;
}
/* Vectorized conversion. */
tree
<API key> (unsigned int code ATTRIBUTE_UNUSED,
tree dest_type ATTRIBUTE_UNUSED,
tree src_type ATTRIBUTE_UNUSED)
{
return NULL_TREE;
}
/* Default vectorizer cost model values. */
int
<API key> (enum vect_cost_for_stmt type_of_cost,
tree vectype,
int misalign ATTRIBUTE_UNUSED)
{
unsigned elements;
switch (type_of_cost)
{
case scalar_stmt:
case scalar_load:
case scalar_store:
case vector_stmt:
case vector_load:
case vector_store:
case vec_to_scalar:
case scalar_to_vec:
case <API key>:
case vec_perm:
case vec_promote_demote:
return 1;
case unaligned_load:
case unaligned_store:
return 2;
case cond_branch_taken:
return 3;
case vec_construct:
elements = <API key> (vectype);
return elements / 2 + 1;
default:
gcc_unreachable ();
}
}
/* Reciprocal. */
tree
<API key> (tree)
{
return NULL_TREE;
}
bool
<API key> (
cumulative_args_t ca ATTRIBUTE_UNUSED,
machine_mode mode ATTRIBUTE_UNUSED,
const_tree type ATTRIBUTE_UNUSED, bool named ATTRIBUTE_UNUSED)
{
return false;
}
bool
<API key> (
cumulative_args_t ca ATTRIBUTE_UNUSED,
machine_mode mode ATTRIBUTE_UNUSED,
const_tree type ATTRIBUTE_UNUSED, bool named ATTRIBUTE_UNUSED)
{
return true;
}
int
<API key> (
cumulative_args_t ca ATTRIBUTE_UNUSED,
machine_mode mode ATTRIBUTE_UNUSED,
tree type ATTRIBUTE_UNUSED, bool named ATTRIBUTE_UNUSED)
{
return 0;
}
void
<API key> (cumulative_args_t ca ATTRIBUTE_UNUSED,
machine_mode mode ATTRIBUTE_UNUSED,
const_tree type ATTRIBUTE_UNUSED,
bool named ATTRIBUTE_UNUSED)
{
gcc_unreachable ();
}
rtx
<API key> (cumulative_args_t ca ATTRIBUTE_UNUSED,
machine_mode mode ATTRIBUTE_UNUSED,
const_tree type ATTRIBUTE_UNUSED,
bool named ATTRIBUTE_UNUSED)
{
gcc_unreachable ();
}
rtx
<API key> (cumulative_args_t ca ATTRIBUTE_UNUSED,
machine_mode mode ATTRIBUTE_UNUSED,
const_tree type ATTRIBUTE_UNUSED,
bool named ATTRIBUTE_UNUSED)
{
gcc_unreachable ();
}
unsigned int
<API key> (machine_mode mode ATTRIBUTE_UNUSED,
const_tree type ATTRIBUTE_UNUSED)
{
return PARM_BOUNDARY;
}
unsigned int
<API key> (machine_mode mode ATTRIBUTE_UNUSED,
const_tree type ATTRIBUTE_UNUSED)
{
return PARM_BOUNDARY;
}
void
hook_void_bitmap (bitmap regs ATTRIBUTE_UNUSED)
{
}
const char *
<API key> (
const_tree typelist ATTRIBUTE_UNUSED,
const_tree funcdecl ATTRIBUTE_UNUSED,
const_tree val ATTRIBUTE_UNUSED)
{
return NULL;
}
/* Initialize the stack protection decls. */
/* Stack protection related decls living in libgcc. */
static GTY(()) tree <API key>;
tree
<API key> (void)
{
tree t = <API key>;
if (t == NULL)
{
rtx x;
t = build_decl (UNKNOWN_LOCATION,
VAR_DECL, get_identifier ("__stack_chk_guard"),
ptr_type_node);
TREE_STATIC (t) = 1;
TREE_PUBLIC (t) = 1;
DECL_EXTERNAL (t) = 1;
TREE_USED (t) = 1;
TREE_THIS_VOLATILE (t) = 1;
DECL_ARTIFICIAL (t) = 1;
DECL_IGNORED_P (t) = 1;
/* Do not share RTL as the declaration is visible outside of
current function. */
x = DECL_RTL (t);
RTX_FLAG (x, used) = 1;
<API key> = t;
}
return t;
}
static GTY(()) tree stack_chk_fail_decl;
tree
<API key> (void)
{
tree t = stack_chk_fail_decl;
if (t == NULL_TREE)
{
t = <API key> (void_type_node, NULL_TREE);
t = build_decl (UNKNOWN_LOCATION,
FUNCTION_DECL, get_identifier ("__stack_chk_fail"), t);
TREE_STATIC (t) = 1;
TREE_PUBLIC (t) = 1;
DECL_EXTERNAL (t) = 1;
TREE_USED (t) = 1;
TREE_THIS_VOLATILE (t) = 1;
TREE_NOTHROW (t) = 1;
DECL_ARTIFICIAL (t) = 1;
DECL_IGNORED_P (t) = 1;
DECL_VISIBILITY (t) = VISIBILITY_DEFAULT;
<API key> (t) = 1;
stack_chk_fail_decl = t;
}
return build_call_expr (t, 0);
}
tree
<API key> (void)
{
#ifndef HAVE_GAS_HIDDEN
return <API key> ();
#else
tree t = stack_chk_fail_decl;
if (!flag_pic)
return <API key> ();
if (t == NULL_TREE)
{
t = <API key> (void_type_node, NULL_TREE);
t = build_decl (UNKNOWN_LOCATION, FUNCTION_DECL,
get_identifier ("<API key>"), t);
TREE_STATIC (t) = 1;
TREE_PUBLIC (t) = 1;
DECL_EXTERNAL (t) = 1;
TREE_USED (t) = 1;
TREE_THIS_VOLATILE (t) = 1;
TREE_NOTHROW (t) = 1;
DECL_ARTIFICIAL (t) = 1;
DECL_IGNORED_P (t) = 1;
<API key> (t) = 1;
DECL_VISIBILITY (t) = VISIBILITY_HIDDEN;
stack_chk_fail_decl = t;
}
return build_call_expr (t, 0);
#endif
}
bool
<API key> (const_rtx x,
int outer_code ATTRIBUTE_UNUSED)
{
return COMMUTATIVE_P (x);
}
rtx
<API key> (const_tree ret_type ATTRIBUTE_UNUSED,
const_tree fn_decl_or_type,
bool outgoing ATTRIBUTE_UNUSED)
{
/* The old interface doesn't handle receiving the function type. */
if (fn_decl_or_type
&& !DECL_P (fn_decl_or_type))
fn_decl_or_type = NULL;
#ifdef FUNCTION_VALUE
return FUNCTION_VALUE (ret_type, fn_decl_or_type);
#else
gcc_unreachable ();
#endif
}
rtx
<API key> (machine_mode mode ATTRIBUTE_UNUSED,
const_rtx fun ATTRIBUTE_UNUSED)
{
#ifdef LIBCALL_VALUE
return LIBCALL_VALUE (mode);
#else
gcc_unreachable ();
#endif
}
/* The default hook for <API key>. */
bool
<API key> (const unsigned int regno ATTRIBUTE_UNUSED)
{
#ifdef <API key>
return <API key> (regno);
#else
gcc_unreachable ();
#endif
}
rtx
<API key> (void)
{
/* If the reg that the virtual arg pointer will be translated into is
not a fixed reg or is the stack pointer, make a copy of the virtual
arg pointer, and address parms via the copy. The frame pointer is
considered fixed even though it is not marked as such. */
if ((ARG_POINTER_REGNUM == <API key>
|| ! (fixed_regs[ARG_POINTER_REGNUM]
|| ARG_POINTER_REGNUM == <API key>)))
return copy_to_reg (<API key>);
else
return <API key>;
}
rtx
<API key> (const_tree ARG_UNUSED (fndecl_or_type), bool incoming_p)
{
if (incoming_p)
{
#ifdef <API key>
return gen_rtx_REG (Pmode, <API key>);
#endif
}
#ifdef STATIC_CHAIN_REGNUM
return gen_rtx_REG (Pmode, STATIC_CHAIN_REGNUM);
#endif
{
static bool issued_error;
if (!issued_error)
{
issued_error = true;
sorry ("nested functions not supported on this target");
}
/* It really doesn't matter what we return here, so long at it
doesn't cause the rest of the compiler to crash. */
return gen_rtx_MEM (Pmode, stack_pointer_rtx);
}
}
void
<API key> (rtx ARG_UNUSED (m_tramp), tree ARG_UNUSED (t_func),
rtx ARG_UNUSED (r_chain))
{
sorry ("nested function trampolines not supported on this target");
}
int
<API key> (tree fundecl ATTRIBUTE_UNUSED,
tree funtype ATTRIBUTE_UNUSED,
int size ATTRIBUTE_UNUSED)
{
return 0;
}
reg_class_t
<API key> (void)
{
return NO_REGS;
}
reg_class_t
<API key> (int regno ATTRIBUTE_UNUSED,
reg_class_t cl)
{
return cl;
}
extern bool
default_lra_p (void)
{
return false;
}
int
<API key> (int hard_regno ATTRIBUTE_UNUSED)
{
return 0;
}
extern bool
<API key> (void)
{
return false;
}
extern bool
<API key> (void)
{
return false;
}
reg_class_t
<API key> (bool in_p ATTRIBUTE_UNUSED, rtx x ATTRIBUTE_UNUSED,
reg_class_t reload_class_i ATTRIBUTE_UNUSED,
machine_mode reload_mode ATTRIBUTE_UNUSED,
<API key> *sri)
{
enum reg_class rclass = NO_REGS;
enum reg_class reload_class = (enum reg_class) reload_class_i;
if (sri->prev_sri && sri->prev_sri->t_icode != CODE_FOR_nothing)
{
sri->icode = sri->prev_sri->t_icode;
return NO_REGS;
}
#ifdef <API key>
if (in_p)
rclass = <API key> (reload_class, reload_mode, x);
#endif
#ifdef <API key>
if (! in_p)
rclass = <API key> (reload_class, reload_mode, x);
#endif
if (rclass != NO_REGS)
{
enum insn_code icode
= <API key> (in_p ? reload_in_optab : reload_out_optab,
reload_mode);
if (icode != CODE_FOR_nothing
&& !<API key> (icode, in_p, x))
icode = CODE_FOR_nothing;
else if (icode != CODE_FOR_nothing)
{
const char *insn_constraint, *scratch_constraint;
enum reg_class insn_class, scratch_class;
gcc_assert (insn_data[(int) icode].n_operands == 3);
insn_constraint = insn_data[(int) icode].operand[!in_p].constraint;
if (!*insn_constraint)
insn_class = ALL_REGS;
else
{
if (in_p)
{
gcc_assert (*insn_constraint == '=');
insn_constraint++;
}
insn_class = (<API key>
(lookup_constraint (insn_constraint)));
gcc_assert (insn_class != NO_REGS);
}
scratch_constraint = insn_data[(int) icode].operand[2].constraint;
/* The scratch register's constraint must start with "=&",
except for an input reload, where only "=" is necessary,
and where it might be beneficial to re-use registers from
the input. */
gcc_assert (scratch_constraint[0] == '='
&& (in_p || scratch_constraint[1] == '&'));
scratch_constraint++;
if (*scratch_constraint == '&')
scratch_constraint++;
scratch_class = (<API key>
(lookup_constraint (scratch_constraint)));
if (reg_class_subset_p (reload_class, insn_class))
{
gcc_assert (scratch_class == rclass);
rclass = NO_REGS;
}
else
rclass = insn_class;
}
if (rclass == NO_REGS)
sri->icode = icode;
else
sri->t_icode = icode;
}
return rclass;
}
/* By default, if flag_pic is true, then neither local nor global relocs
should be placed in readonly memory. */
int
<API key> (void)
{
return flag_pic ? 3 : 0;
}
/* By default, do no modification. */
tree <API key> (tree decl ATTRIBUTE_UNUSED,
tree id)
{
return id;
}
/* Default to natural alignment for vector types. */
HOST_WIDE_INT
<API key> (const_tree type)
{
return tree_to_shwi (TYPE_SIZE (type));
}
bool
<API key> (const_tree type, bool is_packed)
{
if (is_packed)
return false;
/* Assuming that types whose size is > pointer-size are not guaranteed to be
naturally aligned. */
if (<API key> (TYPE_SIZE (type), bitsize_int (POINTER_SIZE)) > 0)
return false;
/* Assuming that types whose size is <= pointer-size
are naturally aligned. */
return true;
}
/* By default, assume that a target supports any factor of misalignment
memory access if it supports movmisalign patten.
is_packed is true if the memory access is defined in a packed struct. */
bool
<API key> (machine_mode mode,
const_tree type
ATTRIBUTE_UNUSED,
int misalignment
ATTRIBUTE_UNUSED,
bool is_packed
ATTRIBUTE_UNUSED)
{
if (optab_handler (movmisalign_optab, mode) != CODE_FOR_nothing)
return true;
return false;
}
/* By default, only attempt to parallelize bitwise operations, and
possibly adds/subtracts using bit-twiddling. */
machine_mode
<API key> (machine_mode mode ATTRIBUTE_UNUSED)
{
return word_mode;
}
/* By default only the size derived from the preferred vector mode
is tried. */
unsigned int
<API key> (void)
{
return 0;
}
/* By defaults a vector of integers is used as a mask. */
machine_mode
<API key> (unsigned nunits, unsigned vector_size)
{
unsigned elem_size = vector_size / nunits;
machine_mode elem_mode
= <API key> (elem_size * BITS_PER_UNIT, MODE_INT);
machine_mode vector_mode;
gcc_assert (elem_size * nunits == vector_size);
vector_mode = mode_for_vector (elem_mode, nunits);
if (!VECTOR_MODE_P (vector_mode)
|| !targetm.<API key> (vector_mode))
vector_mode = BLKmode;
return vector_mode;
}
/* By default, the cost model accumulates three separate costs (prologue,
loop body, and epilogue) for a vectorized loop or block. So allocate an
array of three unsigned ints, set it to zero, and return its address. */
void *
default_init_cost (struct loop *loop_info ATTRIBUTE_UNUSED)
{
unsigned *cost = XNEWVEC (unsigned, 3);
cost[vect_prologue] = cost[vect_body] = cost[vect_epilogue] = 0;
return cost;
}
/* By default, the cost model looks up the cost of the given statement
kind and mode, multiplies it by the occurrence count, accumulates
it into the cost specified by WHERE, and returns the cost added. */
unsigned
<API key> (void *data, int count, enum vect_cost_for_stmt kind,
struct _stmt_vec_info *stmt_info, int misalign,
enum <API key> where)
{
unsigned *cost = (unsigned *) data;
unsigned retval = 0;
tree vectype = stmt_info ? stmt_vectype (stmt_info) : NULL_TREE;
int stmt_cost = targetm.vectorize.<API key> (kind, vectype,
misalign);
/* Statements in an inner loop relative to the loop being
vectorized are weighted more heavily. The value here is
arbitrary and could potentially be improved with analysis. */
if (where == vect_body && stmt_info && <API key> (stmt_info))
count *= 50; /* FIXME. */
retval = (unsigned) (count * stmt_cost);
cost[where] += retval;
return retval;
}
/* By default, the cost model just returns the accumulated costs. */
void
default_finish_cost (void *data, unsigned *prologue_cost,
unsigned *body_cost, unsigned *epilogue_cost)
{
unsigned *cost = (unsigned *) data;
*prologue_cost = cost[vect_prologue];
*body_cost = cost[vect_body];
*epilogue_cost = cost[vect_epilogue];
}
/* Free the cost data. */
void
<API key> (void *data)
{
free (data);
}
/* Determine whether or not a pointer mode is valid. Assume defaults
of ptr_mode or Pmode - can be overridden. */
bool
<API key> (machine_mode mode)
{
return (mode == ptr_mode || mode == Pmode);
}
/* Determine whether the memory reference specified by REF may alias
the C libraries errno location. */
bool
<API key> (ao_ref *ref)
{
tree base = ao_ref_base (ref);
/* The default implementation assumes the errno location is
a declaration of type int or is always accessed via a
pointer to int. We assume that accesses to errno are
not deliberately obfuscated (even in conforming ways). */
if (TYPE_UNSIGNED (TREE_TYPE (base))
|| TYPE_MODE (TREE_TYPE (base)) != TYPE_MODE (integer_type_node))
return false;
/* The default implementation assumes an errno location
declaration is never defined in the current compilation unit. */
if (DECL_P (base)
&& !TREE_STATIC (base))
return true;
else if (TREE_CODE (base) == MEM_REF
&& TREE_CODE (TREE_OPERAND (base, 0)) == SSA_NAME)
{
struct ptr_info_def *pi = SSA_NAME_PTR_INFO (TREE_OPERAND (base, 0));
return !pi || pi->pt.anything || pi->pt.nonlocal;
}
return false;
}
/* Return the mode for a pointer to a given ADDRSPACE,
defaulting to ptr_mode for all address spaces. */
machine_mode
<API key> (addr_space_t addrspace ATTRIBUTE_UNUSED)
{
return ptr_mode;
}
/* Return the mode for an address in a given ADDRSPACE,
defaulting to Pmode for all address spaces. */
machine_mode
<API key> (addr_space_t addrspace ATTRIBUTE_UNUSED)
{
return Pmode;
}
/* Named address space version of valid_pointer_mode.
To match the above, the same modes apply to all address spaces. */
bool
<API key> (machine_mode mode,
addr_space_t as ATTRIBUTE_UNUSED)
{
return targetm.valid_pointer_mode (mode);
}
/* Some places still assume that all pointer or address modes are the
standard Pmode and ptr_mode. These optimizations become invalid if
the target actually supports multiple different modes. For now,
we disable such optimizations on such targets, using this function. */
bool
<API key> (void)
{
if (targetm.addr_space.address_mode != <API key>)
return false;
if (targetm.addr_space.pointer_mode != <API key>)
return false;
return true;
}
/* Named address space version of <API key>.
By default, all address spaces have the same form. */
bool
<API key> (machine_mode mode, rtx mem,
bool strict,
addr_space_t as ATTRIBUTE_UNUSED)
{
return targetm.<API key> (mode, mem, strict);
}
/* Named address space version of LEGITIMIZE_ADDRESS.
By default, all address spaces have the same form. */
rtx
<API key> (rtx x, rtx oldx, machine_mode mode,
addr_space_t as ATTRIBUTE_UNUSED)
{
return targetm.legitimize_address (x, oldx, mode);
}
/* The default hook for determining if one named address space is a subset of
another and to return which address space to use as the common address
space. */
bool
<API key> (addr_space_t subset, addr_space_t superset)
{
return (subset == superset);
}
/* The default hook for determining if 0 within a named address
space is a valid address. */
bool
<API key> (addr_space_t as ATTRIBUTE_UNUSED)
{
return false;
}
/* The default hook for debugging the address space is to return the
address space number to indicate DW_AT_address_class. */
int
<API key> (addr_space_t as)
{
return as;
}
/* The default hook for <API key>. This hook should never be
called for targets with only a generic address space. */
rtx
<API key> (rtx op ATTRIBUTE_UNUSED,
tree from_type ATTRIBUTE_UNUSED,
tree to_type ATTRIBUTE_UNUSED)
{
gcc_unreachable ();
}
bool
<API key> (unsigned int regno ATTRIBUTE_UNUSED)
{
return true;
}
/* The default implementation of <API key>. */
bool
<API key> (const_rtx addr ATTRIBUTE_UNUSED,
addr_space_t addrspace ATTRIBUTE_UNUSED)
{
return false;
}
bool
<API key> (tree ARG_UNUSED (fndecl),
tree ARG_UNUSED (name),
tree ARG_UNUSED (args),
int ARG_UNUSED (flags))
{
warning (OPT_Wattributes,
"target attribute is not supported on this machine");
return false;
}
bool
<API key> (tree ARG_UNUSED (args),
tree ARG_UNUSED (pop_target))
{
/* If args is NULL the caller is <API key> (). In that case,
emit no warning because "#pragma GCC pop_target" is valid on targets that
do not have the "target" pragma. */
if (args)
warning (OPT_Wpragmas,
"#pragma GCC target is not supported for this machine");
return false;
}
bool
<API key> (tree caller, tree callee)
{
bool ret = false;
tree callee_opts = <API key> (callee);
tree caller_opts = <API key> (caller);
/* If callee has no option attributes, then it is ok to inline */
if (!callee_opts)
ret = true;
/* If caller has no option attributes, but callee does then it is not ok to
inline */
else if (!caller_opts)
ret = false;
/* If both caller and callee have attributes, assume that if the
pointer is different, the two functions have different target
options since <API key> uses a hash table for the
options. */
else
ret = (callee_opts == caller_opts);
return ret;
}
/* If the machine does not have a case insn that compares the bounds,
this means extra overhead for dispatch tables, which raises the
threshold for using them. */
unsigned int
<API key> (void)
{
return (targetm.have_casesi () ? 4 : 5);
}
bool
<API key> (void)
{
return <API key>;
}
/* By default we assume that c99 functions are present at the runtime,
but sincos is not. */
bool
<API key> (enum function_class fn_class)
{
if (fn_class == function_c94
|| fn_class == function_c99_misc
|| fn_class == <API key>)
return true;
return false;
}
bool
<API key> (enum function_class fn_class ATTRIBUTE_UNUSED)
{
return true;
}
bool
<API key> (enum function_class fn_class ATTRIBUTE_UNUSED)
{
return false;
}
tree
<API key> (tree ARG_UNUSED (type))
{
return NULL_TREE;
}
/* Compute cost of moving registers to/from memory. */
int
<API key> (machine_mode mode ATTRIBUTE_UNUSED,
reg_class_t rclass ATTRIBUTE_UNUSED,
bool in ATTRIBUTE_UNUSED)
{
#ifndef MEMORY_MOVE_COST
return (4 + <API key> (mode, (enum reg_class) rclass, in));
#else
return MEMORY_MOVE_COST (mode, (enum reg_class) rclass, in);
#endif
}
/* Compute cost of moving data from a register of class FROM to one of
TO, using MODE. */
int
<API key> (machine_mode mode ATTRIBUTE_UNUSED,
reg_class_t from ATTRIBUTE_UNUSED,
reg_class_t to ATTRIBUTE_UNUSED)
{
#ifndef REGISTER_MOVE_COST
return 2;
#else
return REGISTER_MOVE_COST (mode, (enum reg_class) from, (enum reg_class) to);
#endif
}
/* For hooks which use the MOVE_RATIO macro, this gives the legacy default
behaviour. SPEED_P is true if we are compiling for speed. */
unsigned int
get_move_ratio (bool speed_p ATTRIBUTE_UNUSED)
{
unsigned int move_ratio;
#ifdef MOVE_RATIO
move_ratio = (unsigned int) MOVE_RATIO (speed_p);
#else
#if defined (HAVE_movmemqi) || defined (HAVE_movmemhi) || defined (HAVE_movmemsi) || defined (HAVE_movmemdi) || defined (HAVE_movmemti)
move_ratio = 2;
#else /* No movmem patterns, pick a default. */
move_ratio = ((speed_p) ? 15 : 3);
#endif
#endif
return move_ratio;
}
/* Return TRUE if the move_by_pieces/set_by_pieces infrastructure should be
used; return FALSE if the movmem/setmem optab should be expanded, or
a call to memcpy emitted. */
bool
<API key> (unsigned HOST_WIDE_INT size,
unsigned int alignment,
enum by_pieces_operation op,
bool speed_p)
{
unsigned int max_size = 0;
unsigned int ratio = 0;
switch (op)
{
case CLEAR_BY_PIECES:
max_size = STORE_MAX_PIECES;
ratio = CLEAR_RATIO (speed_p);
break;
case MOVE_BY_PIECES:
max_size = MOVE_MAX_PIECES;
ratio = get_move_ratio (speed_p);
break;
case SET_BY_PIECES:
max_size = STORE_MAX_PIECES;
ratio = SET_RATIO (speed_p);
break;
case STORE_BY_PIECES:
max_size = STORE_MAX_PIECES;
ratio = get_move_ratio (speed_p);
break;
}
return <API key> (size, alignment, max_size + 1) < ratio;
}
bool
<API key> (void)
{
#ifdef <API key>
return true;
#else
return false;
#endif
}
/* The default implementation of <API key>. */
reg_class_t
<API key> (rtx x ATTRIBUTE_UNUSED,
reg_class_t rclass)
{
#ifdef <API key>
return (reg_class_t) <API key> (x, (enum reg_class) rclass);
#else
return rclass;
#endif
}
/* The default implementation of <API key>. */
reg_class_t
<API key> (rtx x ATTRIBUTE_UNUSED,
reg_class_t rclass)
{
return rclass;
}
/* The default implementation of <API key>. */
reg_class_t
<API key> (reg_class_t rclass ATTRIBUTE_UNUSED)
{
return NO_REGS;
}
/* The default implementation of <API key>. */
bool
<API key> (reg_class_t rclass)
{
return (reg_class_size[(int) rclass] == 1);
}
/* The default implementation of <API key>. */
unsigned char
<API key> (reg_class_t rclass ATTRIBUTE_UNUSED,
machine_mode mode ATTRIBUTE_UNUSED)
{
#ifdef CLASS_MAX_NREGS
return (unsigned char) CLASS_MAX_NREGS ((enum reg_class) rclass, mode);
#else
return ((GET_MODE_SIZE (mode) + UNITS_PER_WORD - 1) / UNITS_PER_WORD);
#endif
}
/* Determine the debugging unwind mechanism for the target. */
enum unwind_info_type
<API key> (void)
{
/* If the target wants to force the use of dwarf2 unwind info, let it. */
/* ??? Change all users to the hook, then poison this. */
#ifdef DWARF2_FRAME_INFO
if (DWARF2_FRAME_INFO)
return UI_DWARF2;
#endif
/* Otherwise, only turn it on if dwarf2 debugging is enabled. */
#ifdef <API key>
if (write_symbols == DWARF2_DEBUG || write_symbols == <API key>)
return UI_DWARF2;
#endif
return UI_NONE;
}
/* Determine the correct mode for a Dwarf frame register that represents
register REGNO. */
machine_mode
<API key> (int regno)
{
machine_mode save_mode = reg_raw_mode[regno];
if (<API key> (regno, save_mode))
save_mode = <API key> (regno, 1, true);
return save_mode;
}
/* To be used by targets where reg_raw_mode doesn't return the right
mode for registers used in <API key> and apply_builtin_arg. */
machine_mode
<API key> (int regno)
{
return reg_raw_mode[regno];
}
/* Return true if a leaf function should stay leaf even with profiling
enabled. */
bool
<API key> ()
{
return false;
}
/* Return true if the state of option OPTION should be stored in PCH files
and checked by default_pch_valid_p. Store the option's current state
in STATE if so. */
static inline bool
<API key> (int option, struct cl_option_state *state)
{
if ((cl_options[option].flags & CL_TARGET) == 0)
return false;
if ((cl_options[option].flags & CL_PCH_IGNORE) != 0)
return false;
if (option_flag_var (option, &global_options) == &target_flags)
if (targetm.<API key>)
return false;
return get_option_state (&global_options, option, state);
}
/* Default version of get_pch_validity.
By default, every flag difference is fatal; that will be mostly right for
most targets, but completely right for very few. */
void *
<API key> (size_t *sz)
{
struct cl_option_state state;
size_t i;
char *result, *r;
*sz = 2;
if (targetm.<API key>)
*sz += sizeof (target_flags);
for (i = 0; i < cl_options_count; i++)
if (<API key> (i, &state))
*sz += state.size;
result = r = XNEWVEC (char, *sz);
r[0] = flag_pic;
r[1] = flag_pie;
r += 2;
if (targetm.<API key>)
{
memcpy (r, &target_flags, sizeof (target_flags));
r += sizeof (target_flags);
}
for (i = 0; i < cl_options_count; i++)
if (<API key> (i, &state))
{
memcpy (r, state.data, state.size);
r += state.size;
}
return result;
}
/* Return a message which says that a PCH file was created with a different
setting of OPTION. */
static const char *
pch_option_mismatch (const char *option)
{
return xasprintf (_("created and used with differing settings of '%s'"),
option);
}
/* Default version of pch_valid_p. */
const char *
default_pch_valid_p (const void *data_p, size_t len)
{
struct cl_option_state state;
const char *data = (const char *)data_p;
size_t i;
/* -fpic and -fpie also usually make a PCH invalid. */
if (data[0] != flag_pic)
return _("created and used with different settings of -fpic");
if (data[1] != flag_pie)
return _("created and used with different settings of -fpie");
data += 2;
/* Check target_flags. */
if (targetm.<API key>)
{
int tf;
const char *r;
memcpy (&tf, data, sizeof (target_flags));
data += sizeof (target_flags);
len -= sizeof (target_flags);
r = targetm.<API key> (tf);
if (r != NULL)
return r;
}
for (i = 0; i < cl_options_count; i++)
if (<API key> (i, &state))
{
if (memcmp (data, state.data, state.size) != 0)
return pch_option_mismatch (cl_options[i].opt_text);
data += state.size;
len -= state.size;
}
return NULL;
}
/* Default version of cstore_mode. */
machine_mode
default_cstore_mode (enum insn_code icode)
{
return insn_data[(int) icode].operand[0].mode;
}
/* Default version of <API key>. */
bool
<API key> (const_tree, machine_mode)
{
return false;
}
rtx
<API key> (rtx addr ATTRIBUTE_UNUSED,
rtx ptr ATTRIBUTE_UNUSED,
rtx bnd ATTRIBUTE_UNUSED)
{
gcc_unreachable ();
}
void
<API key> (rtx val ATTRIBUTE_UNUSED,
rtx addr ATTRIBUTE_UNUSED,
rtx bounds ATTRIBUTE_UNUSED,
rtx to ATTRIBUTE_UNUSED)
{
gcc_unreachable ();
}
rtx
<API key> (rtx slot ATTRIBUTE_UNUSED)
{
gcc_unreachable ();
}
void
<API key> (rtx slot ATTRIBUTE_UNUSED,
rtx bounds ATTRIBUTE_UNUSED)
{
gcc_unreachable ();
}
/* Default version of <API key>. */
void
<API key> (int *, rtx *, rtx *, bool)
{
}
/* Default implementation of <API key>. */
void
<API key> (tree *, tree *, tree *)
{
}
#ifndef PAD_VARARGS_DOWN
#define PAD_VARARGS_DOWN BYTES_BIG_ENDIAN
#endif
/* Build an indirect-ref expression over the given TREE, which represents a
piece of a va_arg() expansion. */
tree
<API key> (tree addr)
{
addr = <API key> (EXPR_LOCATION (addr), addr);
return addr;
}
/* The "standard" implementation of va_arg: read the value from the
current (padded) address and increment by the (padded) size. */
tree
<API key> (tree valist, tree type, gimple_seq *pre_p,
gimple_seq *post_p)
{
tree addr, t, type_size, rounded_size, valist_tmp;
unsigned HOST_WIDE_INT align, boundary;
bool indirect;
/* All of the alignment and movement below is for args-grow-up machines.
As of 2004, there are only 3 ARGS_GROW_DOWNWARD targets, and they all
implement their own specialized <API key> routines. */
if (ARGS_GROW_DOWNWARD)
gcc_unreachable ();
indirect = pass_by_reference (NULL, TYPE_MODE (type), type, false);
if (indirect)
type = build_pointer_type (type);
align = PARM_BOUNDARY / BITS_PER_UNIT;
boundary = targetm.calls.<API key> (TYPE_MODE (type), type);
/* When we align parameter on stack for caller, if the parameter
alignment is beyond <API key>, it will be
aligned at <API key>. We will match callee
here with caller. */
if (boundary > <API key>)
boundary = <API key>;
boundary /= BITS_PER_UNIT;
/* Hoist the valist value into a temporary for the moment. */
valist_tmp = <API key> (valist, pre_p, NULL);
/* va_list pointer is aligned to PARM_BOUNDARY. If argument actually
requires greater alignment, we must perform dynamic alignment. */
if (boundary > align
&& !integer_zerop (TYPE_SIZE (type)))
{
t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist_tmp,
<API key> (valist_tmp, boundary - 1));
gimplify_and_add (t, pre_p);
t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist_tmp,
fold_build2 (BIT_AND_EXPR, TREE_TYPE (valist),
valist_tmp,
build_int_cst (TREE_TYPE (valist), -boundary)));
gimplify_and_add (t, pre_p);
}
else
boundary = align;
/* If the actual alignment is less than the alignment of the type,
adjust the type accordingly so that we don't assume strict alignment
when dereferencing the pointer. */
boundary *= BITS_PER_UNIT;
if (boundary < TYPE_ALIGN (type))
{
type = <API key> (type);
TYPE_ALIGN (type) = boundary;
}
/* Compute the rounded size of the type. */
type_size = size_in_bytes (type);
rounded_size = round_up (type_size, align);
/* Reduce rounded_size so it's sharable with the postqueue. */
gimplify_expr (&rounded_size, pre_p, post_p, is_gimple_val, fb_rvalue);
/* Get AP. */
addr = valist_tmp;
if (PAD_VARARGS_DOWN && !integer_zerop (rounded_size))
{
/* Small args are padded downward. */
t = fold_build2_loc (input_location, GT_EXPR, sizetype,
rounded_size, size_int (align));
t = fold_build3 (COND_EXPR, sizetype, t, size_zero_node,
size_binop (MINUS_EXPR, rounded_size, type_size));
addr = <API key> (addr, t);
}
/* Compute new value for AP. */
t = <API key> (valist_tmp, rounded_size);
t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist, t);
gimplify_and_add (t, pre_p);
addr = fold_convert (build_pointer_type (type), addr);
if (indirect)
addr = <API key> (addr);
return <API key> (addr);
}
tree
<API key> (void)
{
tree res = make_node (POINTER_BOUNDS_TYPE);
TYPE_PRECISION (res) = TYPE_PRECISION (size_type_node) * 2;
TYPE_NAME (res) = get_identifier ("__bounds_type");
SET_TYPE_MODE (res, targetm.chkp_bound_mode ());
layout_type (res);
return res;
}
enum machine_mode
<API key> (void)
{
return VOIDmode;
}
tree
<API key> (unsigned int fcode ATTRIBUTE_UNUSED)
{
return NULL_TREE;
}
rtx
<API key> (const_tree ret_type ATTRIBUTE_UNUSED,
const_tree fn_decl_or_type ATTRIBUTE_UNUSED,
bool outgoing ATTRIBUTE_UNUSED)
{
gcc_unreachable ();
}
tree
<API key> (HOST_WIDE_INT lb ATTRIBUTE_UNUSED,
HOST_WIDE_INT ub ATTRIBUTE_UNUSED)
{
return NULL_TREE;
}
int
<API key> (tree var ATTRIBUTE_UNUSED,
tree lb ATTRIBUTE_UNUSED,
tree ub ATTRIBUTE_UNUSED,
tree *stmts ATTRIBUTE_UNUSED)
{
return 0;
}
void
<API key> (cumulative_args_t ca ATTRIBUTE_UNUSED,
enum machine_mode mode ATTRIBUTE_UNUSED,
tree type ATTRIBUTE_UNUSED,
int *pretend_arg_size ATTRIBUTE_UNUSED,
int second_time ATTRIBUTE_UNUSED)
{
}
/* An implementation of <API key> for targets that do
not support nested low-overhead loops. */
bool
<API key> (const widest_int &, const widest_int &,
unsigned int loop_depth, bool)
{
return loop_depth == 1;
}
/* Default implementation of <API key>. */
bool
<API key> (int, machine_mode, machine_mode, optimization_type)
{
return true;
}
#include "gt-targhooks.h" |
#define DESCRIPTION "SDIO Platform Driver"
#define AUTHOR "Atheros Communications, Inc."
//??for .h
struct <API key> {
struct list_head node;
struct <API key> *controller;
struct device dev;
};
struct sdioplatform_driver {
struct device_driver drv;
int (*probe)(struct <API key> *);
void (*remove)(struct <API key> *);
int (*suspend)(struct <API key> *, pm_message_t);
int (*resume)(struct <API key> *);
};
struct <API key> {
struct device *dev;
};
struct <API key> {
struct device_driver drv;
int (*probe)(struct <API key> *);
void (*remove)(struct <API key> *);
int (*suspend)(struct <API key> *, pm_message_t);
int (*resume)(struct <API key> *);
};
#define <API key>(d) container_of(d, struct <API key>, dev)
#define <API key>(d) container_of(d, struct sdioplatform_driver, drv)
#define <API key>(d) container_of(d, struct <API key>, dev)
#define <API key>(d) container_of(d, struct <API key>, drv)
#define SDIOPLATFORM_ATTR(name, fmt, args...) \
static ssize_t sdio_##name##_show (struct device *dev, struct device_attribute *attr, char *buf) \
{ \
struct <API key> *peripheral = <API key>(dev); \
return sprintf(buf, fmt, args); \
}
SDIOPLATFORM_ATTR(bus_id, "%s\n", bus_id);
#define <API key>(name) __ATTR(name, S_IRUGO, sdioplatform_##name##_show, NULL)
static struct device_attribute <API key>[] = {
<API key>(bus_id),
__ATTR_NULL
};
static struct bus_type <API key> = {
.name = "sdioplatform",
.dev_attrs = <API key>,
.match = <API key>,
.hotplug = NULL,
.suspend = <API key>,
.resume = <API key>,
};
/* controller functions */
static int <API key>(struct device *dev)
{
struct <API key> *drv = <API key>(dev->driver);
struct <API key> *controller = <API key>(dev);
return drv->probe(controller);
}
static int <API key>(struct device *dev)
{
struct <API key> *drv = <API key>(dev->driver);
struct <API key> *controller = <API key>(dev);
return drv->remove(controller);
}
/*
* <API key> - register a controller driver
*/
int <API key>(struct <API key> *drv)
{
drv->drv.bus = &<API key>;
drv->drv.probe = <API key>;
drv->drv.remove = <API key>;
return driver_register(&drv->drv);
}
/*
* <API key> - unregister a controller driver
*/
void <API key>(struct sdioplatform_driver *drv)
{
driver_unregister(&drv->drv);
}
/*
* <API key> - register a controller device
*/
int <API key>(char *name, struct <API key> *dev)
{
if (!dev) {
return -EINVAL;
}
strncpy(dev->dev.bus_id, BUS_ID_SIZE, name);
return device_register(&dev->dev);
}
/*
* <API key> - unregister a controller device
*/
int <API key>(char *name, struct <API key> *dev)
{
if (!dev) {
return -EINVAL;
}
return device_unregister(&dev->dev);
}
/* peripheral functions */
static int <API key>(struct device *dev)
{
struct sdioplatform_driver *drv = <API key>(dev->driver);
struct <API key> *peripheral = <API key>(dev);
return drv->probe(peripheral);
}
static int <API key>(struct device *dev)
{
struct <API key> *drv = <API key>(dev->driver);
struct <API key> *controller = <API key>(dev);
return drv->remove(controller);
}
/*
* <API key> - register a driver
*/
int <API key>(struct sdioplatform_driver *drv)
{
drv->drv.bus = &<API key>;
drv->drv.probe = <API key>;
drv->drv.remove = <API key>;
return driver_register(&drv->drv);
}
/*
* <API key> - unregister a driver
*/
void <API key>(struct sdioplatform_driver *drv)
{
driver_unregister(&drv->drv);
}
/*
* <API key> - register a peripheral device
*/
int <API key>(char *name, struct <API key> *dev)
{
if (!dev) {
return -EINVAL;
}
strncpy(dev->dev.bus_id, BUS_ID_SIZE, name);
return device_register(&dev->dev);
}
/*
* <API key> - unregister a peripheral device
*/
int <API key>(char *name, struct <API key> *dev)
{
if (!dev) {
return -EINVAL;
}
return device_unregister(&dev->dev);
}
static int <API key>(struct device *dev, struct device_driver *drv)
{
/* probes handle the matching */
return 1;
}
static int <API key>(struct device *dev, pm_message_t state)
{
struct sdioplatform_driver *drv = <API key>(dev->driver);
struct <API key> *peripheral = <API key>(dev);
int ret = 0;
if (peripheral->driver && drv->suspend) {
ret = drv->suspend(peripheral, state);
}
return ret;
}
static int <API key>(struct device *dev)
{
struct sdioplatform_driver *drv = <API key>(dev->driver);
struct <API key> *peripheral = <API key>(dev);
int ret = 0;
if (peripheral->driver && drv->resume) {
ret = drv->resume(card);
}
return ret;
}
/*
* module init
*/
static int __init <API key>(void) {
int ret = bus_register(&<API key>);
return ret;
}
/*
* module cleanup
*/
static void __exit <API key>(void) {
REL_PRINT(SDDBG_TRACE, ("SDIO unloaded\n"));
<API key>();
}
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION(DESCRIPTION);
MODULE_AUTHOR(AUTHOR);
module_init(<API key>);
module_exit(<API key>);
EXPORT_SYMBOL(<API key>);
EXPORT_SYMBOL(<API key>);
EXPORT_SYMBOL(<API key>);
EXPORT_SYMBOL(<API key>);
EXPORT_SYMBOL(<API key>);
EXPORT_SYMBOL(<API key>);
EXPORT_SYMBOL(<API key>);
EXPORT_SYMBOL(<API key>); |
/**
* \defgroup threshold Thresholding
*
* This feature is used to reduce the number of logged alerts for noisy rules.
* This can be tuned to significantly reduce false alarms, and it can also be
* used to write a newer breed of rules. Thresholding commands limit the number
* of times a particular event is logged during a specified time interval.
*
* @{
*/
/**
* \file
*
* \author Breno Silva <breno.silva@gmail.com>
* \author Victor Julien <victor@inliniac.net>
*
* Threshold part of the detection engine.
*/
#include "suricata-common.h"
#include "debug.h"
#include "detect.h"
#include "flow.h"
#include "host.h"
#include "host-storage.h"
#include "ippair.h"
#include "ippair-storage.h"
#include "detect-parse.h"
#include "<API key>.h"
#include "<API key>.h"
#include "<API key>.h"
#include "detect-engine-port.h"
#include "detect-engine-mpm.h"
#include "<API key>.h"
#include "detect-engine.h"
#include "<API key>.h"
#include "detect-content.h"
#include "detect-uricontent.h"
#include "util-hash.h"
#include "util-time.h"
#include "util-error.h"
#include "util-debug.h"
#include "util-var-name.h"
#include "tm-threads.h"
static int host_threshold_id = -1; /**< host storage id for thresholds */
static int ippair_threshold_id = -1; /**< ip pair storage id for thresholds */
int <API key>(void)
{
return host_threshold_id;
}
void ThresholdInit(void)
{
host_threshold_id = HostStorageRegister("threshold", sizeof(void *), NULL, ThresholdListFree);
if (host_threshold_id == -1) {
FatalError(SC_ERR_FATAL,
"Can't initiate host storage for thresholding");
}
ippair_threshold_id = <API key>("threshold", sizeof(void *), NULL, ThresholdListFree);
if (ippair_threshold_id == -1) {
FatalError(SC_ERR_FATAL,
"Can't initiate IP pair storage for thresholding");
}
}
int <API key>(Host *host)
{
return HostGetStorageById(host, host_threshold_id) ? 1 : 0;
}
int <API key>(IPPair *pair)
{
return <API key>(pair, ippair_threshold_id) ? 1 : 0;
}
/**
* \brief Return next DetectThresholdData for signature
*
* \param sig Signature pointer
* \param p Packet structure
* \param sm Pointer to a Signature Match pointer
*
* \retval tsh Return the threshold data from signature or NULL if not found
*
*
*/
const DetectThresholdData *<API key>(const Signature *sig,
Packet *p, const SigMatchData **psm, int list)
{
const SigMatchData *smd = NULL;
const DetectThresholdData *tsh = NULL;
if (sig == NULL)
return NULL;
if (*psm == NULL) {
smd = sig->sm_arrays[list];
} else {
/* Iteration in progress, using provided value */
smd = *psm;
}
if (p == NULL)
return NULL;
while (1) {
if (smd->type == DETECT_THRESHOLD ||
smd->type == <API key>)
{
tsh = (DetectThresholdData *)smd->ctx;
if (smd->is_last) {
*psm = NULL;
} else {
*psm = smd + 1;
}
return tsh;
}
if (smd->is_last) {
break;
}
smd++;
}
*psm = NULL;
return NULL;
}
/**
* \brief Remove timeout threshold hash elements
*
* \param head Current head element of storage
* \param tv Current time
*
* \retval <API key> Return new head element or NULL if all expired
*
*/
static <API key>* <API key>(<API key> *head, struct timeval *tv)
{
<API key> *tmp = head;
<API key> *prev = NULL;
<API key> *new_head = head;
while (tmp != NULL) {
/* check if the 'check' timestamp is not before the creation ts.
* This can happen due to the async nature of the host timeout
* code that also calls this code from a management thread. */
if (TIMEVAL_EARLIER(*tv, tmp->tv1) || TIMEVAL_DIFF_SEC(*tv, tmp->tv1) <= tmp->seconds) {
prev = tmp;
tmp = tmp->next;
continue;
}
/* timed out */
<API key> *tde = tmp;
if (prev != NULL) {
prev->next = tmp->next;
}
else {
new_head = tmp->next;
}
tmp = tde->next;
SCFree(tde);
}
return new_head;
}
int <API key>(Host *host, struct timeval *tv)
{
<API key>* head = HostGetStorageById(host, host_threshold_id);
<API key>* new_head = <API key>(head, tv);
if (new_head != head) {
HostSetStorageById(host, host_threshold_id, new_head);
}
return new_head == NULL;
}
int <API key>(IPPair *pair, struct timeval *tv)
{
<API key>* head = <API key>(pair, ippair_threshold_id);
<API key>* new_head = <API key>(head, tv);
if (new_head != head) {
<API key>(pair, ippair_threshold_id, new_head);
}
return new_head == NULL;
}
static <API key> *
<API key>(const DetectThresholdData *td, Packet *p,
uint32_t sid, uint32_t gid)
{
SCEnter();
<API key> *ste = SCCalloc(1, sizeof(<API key>));
if (unlikely(ste == NULL)) {
SCReturnPtr(NULL, "<API key>");
}
ste->sid = sid;
ste->gid = gid;
ste->track = td->track;
ste->seconds = td->seconds;
SCReturnPtr(ste, "<API key>");
}
static <API key> *<API key>(Host *h,
uint32_t sid, uint32_t gid)
{
<API key> *e;
for (e = HostGetStorageById(h, host_threshold_id); e != NULL; e = e->next) {
if (e->sid == sid && e->gid == gid)
break;
}
return e;
}
static <API key> *<API key>(IPPair *pair,
uint32_t sid, uint32_t gid)
{
<API key> *e;
for (e = <API key>(pair, ippair_threshold_id); e != NULL; e = e->next) {
if (e->sid == sid && e->gid == gid)
break;
}
return e;
}
static int <API key>(Packet *p,
const DetectThresholdData *td, uint32_t sid, uint32_t gid)
{
int ret = 0;
DetectAddress *m = NULL;
switch (td->track) {
case TRACK_DST:
m = <API key>(&td->addrs, &p->dst);
SCLogDebug("TRACK_DST");
break;
case TRACK_SRC:
m = <API key>(&td->addrs, &p->src);
SCLogDebug("TRACK_SRC");
break;
/* suppress if either src or dst is a match on the suppress
* address list */
case TRACK_EITHER:
m = <API key>(&td->addrs, &p->src);
if (m == NULL) {
m = <API key>(&td->addrs, &p->dst);
}
break;
case TRACK_RULE:
default:
SCLogError(<API key>,
"track mode %d is not supported", td->track);
break;
}
if (m == NULL)
ret = 1;
else
ret = 2; /* suppressed but still need actions */
return ret;
}
static inline void RateFilterSetAction(Packet *p, PacketAlert *pa, uint8_t new_action)
{
switch (new_action) {
case TH_ACTION_ALERT:
PACKET_ALERT(p);
pa->flags |= <API key>;
break;
case TH_ACTION_DROP:
PACKET_DROP(p);
pa->flags |= <API key>;
break;
case TH_ACTION_REJECT:
PACKET_REJECT(p);
pa->flags |= <API key>;
break;
case TH_ACTION_PASS:
PACKET_PASS(p);
pa->flags |= <API key>;
break;
default:
/* Weird, leave the default action */
break;
}
}
/**
* \brief Check if the entry reached threshold count limit
*
* \param lookup_tsh Current threshold entry
* \param td Threshold settings
* \param packet_time used to compare against previous detection and to set timeouts
*
* \retval int 1 if threshold reached for this entry
*
*/
static int IsThresholdReached(<API key>* lookup_tsh, const DetectThresholdData *td, struct timeval packet_time)
{
int ret = 0;
/* Check if we have a timeout enabled, if so,
* we still matching (and enabling the new_action) */
if (lookup_tsh->tv_timeout != 0) {
if ((packet_time.tv_sec - lookup_tsh->tv_timeout) > td->timeout) {
/* Ok, we are done, timeout reached */
lookup_tsh->tv_timeout = 0;
}
else {
/* Already matching */
ret = 1;
} /* else - if ((packet_time - lookup_tsh->tv_timeout) > td->timeout) */
}
else {
/* Update the matching state with the timeout interval */
if (TIMEVAL_DIFF_SEC(packet_time, lookup_tsh->tv1) < td->seconds) {
lookup_tsh->current_count++;
if (lookup_tsh->current_count > td->count) {
/* Then we must enable the new action by setting a
* timeout */
lookup_tsh->tv_timeout = packet_time.tv_sec;
ret = 1;
}
}
else {
lookup_tsh->tv1 = packet_time;
lookup_tsh->current_count = 1;
}
} /* else - if (lookup_tsh->tv_timeout != 0) */
return ret;
}
static void <API key>(Host *h, <API key> *e, struct timeval packet_time)
{
if (h && e) {
e->current_count = 1;
e->tv1 = packet_time;
e->tv_timeout = 0;
e->next = HostGetStorageById(h, host_threshold_id);
HostSetStorageById(h, host_threshold_id, e);
}
}
static void <API key>(IPPair *pair, <API key> *e, struct timeval packet_time)
{
if (pair && e) {
e->current_count = 1;
e->tv1 = packet_time;
e->tv_timeout = 0;
e->next = <API key>(pair, ippair_threshold_id);
<API key>(pair, ippair_threshold_id, e);
}
}
/**
* \retval 2 silent match (no alert but apply actions)
* \retval 1 normal match
* \retval 0 no match
*
* If a new <API key> is generated to track the threshold
* for this rule, then it will be returned in new_tsh.
*/
static int <API key>(Packet *p, <API key> *lookup_tsh,
<API key> **new_tsh, const DetectThresholdData *td,
uint32_t sid, uint32_t gid, PacketAlert *pa)
{
int ret = 0;
switch(td->type) {
case TYPE_LIMIT:
{
SCLogDebug("limit");
if (lookup_tsh != NULL) {
if (TIMEVAL_DIFF_SEC(p->ts, lookup_tsh->tv1) < td->seconds) {
lookup_tsh->current_count++;
if (lookup_tsh->current_count <= td->count) {
ret = 1;
} else {
ret = 2;
}
} else {
lookup_tsh->tv1 = p->ts;
lookup_tsh->current_count = 1;
ret = 1;
}
} else {
*new_tsh = <API key>(td, p, sid, gid);
ret = 1;
}
break;
}
case TYPE_THRESHOLD:
{
SCLogDebug("threshold");
if (lookup_tsh != NULL) {
if (TIMEVAL_DIFF_SEC(p->ts, lookup_tsh->tv1) < td->seconds) {
lookup_tsh->current_count++;
if (lookup_tsh->current_count >= td->count) {
ret = 1;
lookup_tsh->current_count = 0;
}
} else {
lookup_tsh->tv1 = p->ts;
lookup_tsh->current_count = 1;
}
} else {
if (td->count == 1) {
ret = 1;
} else {
*new_tsh = <API key>(td, p, sid, gid);
}
}
break;
}
case TYPE_BOTH:
{
SCLogDebug("both");
if (lookup_tsh != NULL) {
if (TIMEVAL_DIFF_SEC(p->ts, lookup_tsh->tv1) < td->seconds) {
/* within time limit */
lookup_tsh->current_count++;
if (lookup_tsh->current_count == td->count) {
ret = 1;
} else if (lookup_tsh->current_count > td->count) {
/* silent match */
ret = 2;
}
} else {
/* expired, so reset */
lookup_tsh->tv1 = p->ts;
lookup_tsh->current_count = 1;
/* if we have a limit of 1, this is a match */
if (lookup_tsh->current_count == td->count) {
ret = 1;
}
}
} else {
*new_tsh = <API key>(td, p, sid, gid);
/* for the first match we return 1 to
* indicate we should alert */
if (td->count == 1) {
ret = 1;
}
}
break;
}
/* detection_filter */
case TYPE_DETECTION:
{
SCLogDebug("detection_filter");
if (lookup_tsh != NULL) {
if (TIMEVAL_DIFF_SEC(p->ts, lookup_tsh->tv1) < td->seconds) {
/* within timeout */
lookup_tsh->current_count++;
if (lookup_tsh->current_count > td->count) {
ret = 1;
}
} else {
/* expired, reset */
lookup_tsh->tv1 = p->ts;
lookup_tsh->current_count = 1;
}
} else {
*new_tsh = <API key>(td, p, sid, gid);
}
break;
}
/* rate_filter */
case TYPE_RATE:
{
SCLogDebug("rate_filter");
ret = 1;
if (lookup_tsh && IsThresholdReached(lookup_tsh, td, p->ts)) {
RateFilterSetAction(p, pa, td->new_action);
} else if (!lookup_tsh) {
*new_tsh = <API key>(td, p, sid, gid);
}
break;
}
/* case TYPE_SUPPRESS: is not handled here */
default:
SCLogError(<API key>, "type %d is not supported", td->type);
}
return ret;
}
static int <API key>(IPPair *pair, Packet *p, const DetectThresholdData *td,
uint32_t sid, uint32_t gid, PacketAlert *pa)
{
int ret = 0;
<API key> *lookup_tsh = <API key>(pair, sid, gid);
SCLogDebug("ippair lookup_tsh %p sid %u gid %u", lookup_tsh, sid, gid);
<API key> *new_tsh = NULL;
ret = <API key>(p, lookup_tsh, &new_tsh, td, sid, gid, pa);
if (new_tsh != NULL) {
<API key>(pair, new_tsh, p->ts);
}
return ret;
}
/**
* \retval 2 silent match (no alert but apply actions)
* \retval 1 normal match
* \retval 0 no match
*/
static int <API key>(Host *h, Packet *p, const DetectThresholdData *td,
uint32_t sid, uint32_t gid, PacketAlert *pa)
{
int ret = 0;
<API key> *lookup_tsh = <API key>(h, sid, gid);
SCLogDebug("lookup_tsh %p sid %u gid %u", lookup_tsh, sid, gid);
<API key> *new_tsh = NULL;
ret = <API key>(p, lookup_tsh, &new_tsh, td, sid, gid, pa);
if (new_tsh != NULL) {
<API key>(h, new_tsh, p->ts);
}
return ret;
}
static int <API key>(DetectEngineCtx *de_ctx, Packet *p,
const DetectThresholdData *td, const Signature *s, PacketAlert *pa)
{
int ret = 0;
<API key>* lookup_tsh = (<API key> *)de_ctx->ths_ctx.th_entry[s->num];
SCLogDebug("by_rule lookup_tsh %p num %u", lookup_tsh, s->num);
<API key> *new_tsh = NULL;
ret = <API key>(p, lookup_tsh, &new_tsh, td, s->id, s->gid, pa);
if (new_tsh != NULL) {
new_tsh->tv1 = p->ts;
new_tsh->current_count = 1;
new_tsh->tv_timeout = 0;
de_ctx->ths_ctx.th_entry[s->num] = new_tsh;
}
return ret;
}
/**
* \brief Make the threshold logic for signatures
*
* \param de_ctx Dectection Context
* \param tsh_ptr Threshold element
* \param p Packet structure
* \param s Signature structure
*
* \retval 2 silent match (no alert but apply actions)
* \retval 1 alert on this event
* \retval 0 do not alert on this event
*/
int <API key>(DetectEngineCtx *de_ctx, <API key> *det_ctx,
const DetectThresholdData *td, Packet *p, const Signature *s, PacketAlert *pa)
{
SCEnter();
int ret = 0;
if (td == NULL) {
SCReturnInt(0);
}
if (td->type == TYPE_SUPPRESS) {
ret = <API key>(p,td,s->id,s->gid);
} else if (td->track == TRACK_SRC) {
Host *src = HostGetHostFromHash(&p->src);
if (src) {
ret = <API key>(src,p,td,s->id,s->gid,pa);
HostRelease(src);
}
} else if (td->track == TRACK_DST) {
Host *dst = HostGetHostFromHash(&p->dst);
if (dst) {
ret = <API key>(dst,p,td,s->id,s->gid,pa);
HostRelease(dst);
}
} else if (td->track == TRACK_BOTH) {
IPPair *pair = <API key>(&p->src, &p->dst);
if (pair) {
ret = <API key>(pair, p, td, s->id, s->gid, pa);
IPPairRelease(pair);
}
} else if (td->track == TRACK_RULE) {
SCMutexLock(&de_ctx->ths_ctx.<API key>);
ret = <API key>(de_ctx,p,td,s,pa);
SCMutexUnlock(&de_ctx->ths_ctx.<API key>);
}
SCReturnInt(ret);
}
/**
* \brief Init threshold context hash tables
*
* \param de_ctx Dectection Context
*
*/
void ThresholdHashInit(DetectEngineCtx *de_ctx)
{
if (SCMutexInit(&de_ctx->ths_ctx.<API key>, NULL) != 0) {
FatalError(SC_ERR_FATAL,
"Threshold: Failed to initialize hash table mutex.");
}
}
/**
* \brief Realloc threshold context hash tables
*
* \param de_ctx Detection Context
*/
void <API key>(DetectEngineCtx *de_ctx)
{
/* Return if we are already big enough */
uint32_t num = de_ctx->signum + 1;
if (num <= de_ctx->ths_ctx.th_size)
return;
void *ptmp = SCRealloc(de_ctx->ths_ctx.th_entry, num * sizeof(<API key> *));
if (ptmp == NULL) {
SCLogWarning(SC_ERR_MEM_ALLOC, "Error allocating memory for rule thresholds"
" (tried to allocate %"PRIu32" th_entrys for rule tracking)", num);
} else {
de_ctx->ths_ctx.th_entry = ptmp;
for (uint32_t i = de_ctx->ths_ctx.th_size; i < num; ++i) {
de_ctx->ths_ctx.th_entry[i] = NULL;
}
de_ctx->ths_ctx.th_size = num;
}
}
/**
* \brief Destroy threshold context hash tables
*
* \param de_ctx Dectection Context
*
*/
void <API key>(DetectEngineCtx *de_ctx)
{
if (de_ctx->ths_ctx.th_entry != NULL)
SCFree(de_ctx->ths_ctx.th_entry);
SCMutexDestroy(&de_ctx->ths_ctx.<API key>);
}
/**
* \brief this function will free all the entries of a list
* DetectTagDataEntry
*
* \param td pointer to <API key>
*/
void ThresholdListFree(void *ptr)
{
if (ptr != NULL) {
<API key> *entry = ptr;
while (entry != NULL) {
<API key> *next_entry = entry->next;
SCFree(entry);
entry = next_entry;
}
}
} |
#include "zutil.h"
#include "inftrees.h"
#include "inflate.h"
#include "inffast.h"
#ifndef ASMINF
/* Allow machine dependent optimization for post-increment or pre-increment.
Based on testing to date,
Pre-increment preferred for:
- PowerPC G3 (Adler)
- MIPS R5000 (Randers-Pehrson)
Post-increment preferred for:
- none
No measurable difference:
- Pentium III (Anderson)
- M68060 (Nikl)
*/
#ifdef POSTINC
# define OFF 0
# define PUP(a) *(a)++
#else
# define OFF 1
# define PUP(a) *++(a)
#endif
/*
Decode literal, length, and distance codes and write out the resulting
literal and match bytes until either not enough input or output is
available, an end-of-block is encountered, or a data error is encountered.
When large enough input and output buffers are supplied to inflate(), for
example, a 16K input buffer and a 64K output buffer, more than 95% of the
inflate execution time is spent in this routine.
Entry assumptions:
state->mode == LEN
strm->avail_in >= 6
strm->avail_out >= 258
start >= strm->avail_out
state->bits < 8
On return, state->mode is one of:
LEN -- ran out of enough output space or enough available input
TYPE -- reached end of block code, inflate() to interpret next block
BAD -- error in block data
Notes:
- The maximum input bits used by a length/distance pair is 15 bits for the
length code, 5 bits for the length extra, 15 bits for the distance code,
and 13 bits for the distance extra. This totals 48 bits, or six bytes.
Therefore if strm->avail_in >= 6, then there is enough input to avoid
checking for available input while decoding.
- The maximum bytes that a single length/distance pair can output is 258
bytes, which is the maximum length that can be coded. inflate_fast()
requires strm->avail_out >= 258 for each loop to avoid checking for
output space.
*/
void inflate_fast(strm, start)
z_streamp strm;
unsigned start; /* inflate()'s starting value for strm->avail_out */
{
struct inflate_state FAR *state;
unsigned char FAR *in; /* local strm->next_in */
unsigned char FAR *last; /* while in < last, enough input available */
unsigned char FAR *out; /* local strm->next_out */
unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
unsigned char FAR *end; /* while out < end, enough space available */
#ifdef INFLATE_STRICT
unsigned dmax; /* maximum distance from zlib header */
#endif
unsigned wsize; /* window size or zero if not using window */
unsigned whave; /* valid bytes in the window */
unsigned write; /* window write index */
unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
unsigned long hold; /* local strm->hold */
unsigned bits; /* local strm->bits */
code const FAR *lcode; /* local strm->lencode */
code const FAR *dcode; /* local strm->distcode */
unsigned lmask; /* mask for first level of length codes */
unsigned dmask; /* mask for first level of distance codes */
code this; /* retrieved table entry */
unsigned op; /* code bits, operation, extra bits, or */
/* window position, window bytes to copy */
unsigned len; /* match length, unused bytes */
unsigned dist; /* match distance */
unsigned char FAR *from; /* where to copy match from */
/* copy state to local variables */
state = (struct inflate_state FAR *)strm->state;
in = strm->next_in - OFF;
last = in + (strm->avail_in - 5);
out = strm->next_out - OFF;
beg = out - (start - strm->avail_out);
end = out + (strm->avail_out - 257);
#ifdef INFLATE_STRICT
dmax = state->dmax;
#endif
wsize = state->wsize;
whave = state->whave;
write = state->write;
window = state->window;
hold = state->hold;
bits = state->bits;
lcode = state->lencode;
dcode = state->distcode;
lmask = (1U << state->lenbits) - 1;
dmask = (1U << state->distbits) - 1;
/* decode literals and length/distances until end-of-block or not enough
input data or output space */
do {
if (bits < 15) {
hold += (unsigned long)(PUP(in)) << bits;
bits += 8;
hold += (unsigned long)(PUP(in)) << bits;
bits += 8;
}
this = lcode[hold & lmask];
dolen:
op = (unsigned)(this.bits);
hold >>= op;
bits -= op;
op = (unsigned)(this.op);
if (op == 0) { /* literal */
Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ?
"inflate: literal '%c'\n" :
"inflate: literal 0x%02x\n", this.val));
PUP(out) = (unsigned char)(this.val);
}
else if (op & 16) { /* length base */
len = (unsigned)(this.val);
op &= 15; /* number of extra bits */
if (op) {
if (bits < op) {
hold += (unsigned long)(PUP(in)) << bits;
bits += 8;
}
len += (unsigned)hold & ((1U << op) - 1);
hold >>= op;
bits -= op;
}
Tracevv((stderr, "inflate: length %u\n", len));
if (bits < 15) {
hold += (unsigned long)(PUP(in)) << bits;
bits += 8;
hold += (unsigned long)(PUP(in)) << bits;
bits += 8;
}
this = dcode[hold & dmask];
dodist:
op = (unsigned)(this.bits);
hold >>= op;
bits -= op;
op = (unsigned)(this.op);
if (op & 16) { /* distance base */
dist = (unsigned)(this.val);
op &= 15; /* number of extra bits */
if (bits < op) {
hold += (unsigned long)(PUP(in)) << bits;
bits += 8;
if (bits < op) {
hold += (unsigned long)(PUP(in)) << bits;
bits += 8;
}
}
dist += (unsigned)hold & ((1U << op) - 1);
#ifdef INFLATE_STRICT
if (dist > dmax) {
strm->msg = (char *)"invalid distance too far back";
state->mode = BAD;
break;
}
#endif
hold >>= op;
bits -= op;
Tracevv((stderr, "inflate: distance %u\n", dist));
op = (unsigned)(out - beg); /* max distance in output */
if (dist > op) { /* see if copy from window */
op = dist - op; /* distance back in window */
if (op > whave) {
strm->msg = (char *)"invalid distance too far back";
state->mode = BAD;
break;
}
from = window - OFF;
if (write == 0) { /* very common case */
from += wsize - op;
if (op < len) { /* some from window */
len -= op;
do {
PUP(out) = PUP(from);
} while (--op);
from = out - dist; /* rest from output */
}
}
else if (write < op) { /* wrap around window */
from += wsize + write - op;
op -= write;
if (op < len) { /* some from end of window */
len -= op;
do {
PUP(out) = PUP(from);
} while (--op);
from = window - OFF;
if (write < len) { /* some from start of window */
op = write;
len -= op;
do {
PUP(out) = PUP(from);
} while (--op);
from = out - dist; /* rest from output */
}
}
}
else { /* contiguous in window */
from += write - op;
if (op < len) { /* some from window */
len -= op;
do {
PUP(out) = PUP(from);
} while (--op);
from = out - dist; /* rest from output */
}
}
while (len > 2) {
PUP(out) = PUP(from);
PUP(out) = PUP(from);
PUP(out) = PUP(from);
len -= 3;
}
if (len) {
PUP(out) = PUP(from);
if (len > 1)
PUP(out) = PUP(from);
}
}
else {
from = out - dist; /* copy direct from output */
do { /* minimum length is three */
PUP(out) = PUP(from);
PUP(out) = PUP(from);
PUP(out) = PUP(from);
len -= 3;
} while (len > 2);
if (len) {
PUP(out) = PUP(from);
if (len > 1)
PUP(out) = PUP(from);
}
}
}
else if ((op & 64) == 0) { /* 2nd level distance code */
this = dcode[this.val + (hold & ((1U << op) - 1))];
goto dodist;
}
else {
strm->msg = (char *)"invalid distance code";
state->mode = BAD;
break;
}
}
else if ((op & 64) == 0) { /* 2nd level length code */
this = lcode[this.val + (hold & ((1U << op) - 1))];
goto dolen;
}
else if (op & 32) { /* end-of-block */
Tracevv((stderr, "inflate: end of block\n"));
state->mode = TYPE;
break;
}
else {
strm->msg = (char *)"invalid literal/length code";
state->mode = BAD;
break;
}
} while (in < last && out < end);
/* return unused bytes (on entry, bits < 8, so in won't go too far back) */
len = bits >> 3;
in -= len;
bits -= len << 3;
hold &= (1U << bits) - 1;
/* update state and return */
strm->next_in = in + OFF;
strm->next_out = out + OFF;
strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
strm->avail_out = (unsigned)(out < end ?
257 + (end - out) : 257 - (out - end));
state->hold = hold;
state->bits = bits;
return;
}
/*
inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
- Using bit fields for code structure
- Different op definition to avoid & for extra bits (do & for table bits)
- Three separate decoding do-loops for direct, window, and write == 0
- Special case for distance > 1 copies to do overlapped load and store copy
- Explicit branch predictions (based on measured branch probabilities)
- Deferring match copy and interspersed it with decoding subsequent codes
- Swapping literal/length else
- Swapping window/direct else
- Larger unrolled copy loops (three is about right)
- Moving len -= 3 statement into middle of loop
*/
#endif /* !ASMINF */ |
<?php
use yii\widgets\ListView;
/* @var $this yii\web\View */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = Yii::t('frontend', 'News');
?>
<div class="news-index">
<!-- <div class="horizontal-ad-large visible-lg">-->
<!-- </div>-->
<?= ListView::widget([
'dataProvider' => $dataProvider,
'itemView' => '_list_view',
'layout' => "{items}<div align='center'>{pager}</div>",
'itemOptions' => [
'class' => 'news-item',
],
'options' => [
'class' => 'news-list',
],
'pager' => [
'prevPageLabel' => '<span class="glyphicon <API key>"></span>',
'nextPageLabel' => '<span class="glyphicon <API key>"></span>',
],
]) ?>
</div> |
<?php
namespace TYPO3\CMS\Install\ViewHelpers;
use TYPO3\CMS\Fluid\Core\ViewHelper\AbstractViewHelper;
use TYPO3Fluid\Fluid\Core\Rendering\<API key>;
use TYPO3Fluid\Fluid\Core\ViewHelper\Traits\<API key>;
/**
* Utility class for phpinfo()
* @internal
*/
class PhpInfoViewHelper extends AbstractViewHelper
{
use <API key>;
/**
* @var bool
*/
protected $escapeOutput = false;
/**
* @var bool
*/
protected $escapeChildren = false;
/**
* @param array $arguments
* @param \Closure $<API key>
* @param <API key> $renderingContext
*
* @return string
*/
public static function renderStatic(array $arguments, \Closure $<API key>, <API key> $renderingContext)
{
return self::<API key>(
self::changeHtmlToHtml5(
self::getPhpInfo()
)
);
}
/**
* Get information about PHP's configuration
*
* @return string HTML page with the configuration options
*/
protected static function getPhpInfo()
{
ob_start();
phpinfo();
return ob_get_clean();
}
/**
* Remove all HTML outside the body tag from HTML string
*
* @param string $html Complete HTML markup for page
* @return string Content of the body tag
*/
protected static function <API key>($html)
{
// Delete anything outside of the body tag and the body tag itself
$html = preg_replace('/^.*?<body.*?>/is', '', $html);
$html = preg_replace('/<\/body>.*?$/is', '', $html);
return $html;
}
/**
* Change HTML markup to HTML5
*
* @param string $html HTML markup to be cleaned
* @return string
*/
protected static function changeHtmlToHtml5($html)
{
// Delete obsolete attributes
$html = preg_replace('#\s(cellpadding|border|width)="[^"]+"#', '', $html);
// Replace font tag with span
return str_replace(['<font', '</font>'], ['<span', '</span>'], $html);
}
} |
<?php
/**
* Functions for Follet internal usage. Not meant to be used outside the Follet
* Framework scope.
*
* @package Follet_Core
* @since 1.0
*/
/**
* Check if Bootstrap is active.
*
* @internal
*
* @return boolean
* @since 1.0
*/
function <API key>() {
$bootstrap = get_theme_support( 'bootstrap' ) && wp_style_is( '<API key>' );
return $bootstrap;
}
/**
* Apply extra styles to wp_link_pages.
*
* @internal
*
* @param string $link Link to the current page in loop.
* @param integer $i Number of the current page in loop.
* @return string Filtered link to the current page in loop.
* @since 1.0
*/
function <API key>( $link, $i ) {
global $page;
$bootstrap = <API key>();
if ( ! is_home() && ! is_archive() && ! is_search() && $i == $page ) {
$link = _wp_link_page( $i ) . $link . '</a>';
}
$replace = $bootstrap ? 'class="btn btn-default page-' . $i . '" href' : 'class="" href';
$link = $bootstrap ? str_replace( 'href', $replace, $link ) : $link;
if ( $i == $page ) {
$link = str_replace( 'class="', 'class="active ', $link );
}
return $link;
}
/**
* This function is used to filter the read-more link when called next to an
* excerpt.
*
* @internal
*
* @param string $content Default content to be filtered.
* @return string Filtered content.
* @since 1.0.2
*/
function <API key>( $content ) {
$link_begin = apply_filters(
'<API key>',
'<a class="more-link" href="' . get_permalink() . '">'
);
$link_end = apply_filters(
'<API key>',
'</a>'
);
$content = $link_begin . $content . $link_end;
$content = apply_filters( '<API key>', $content );
return $content;
} |
/*
* <API key>: 2018 Erik Duisters <e.duisters1@gmail.com>
*
* <API key>: GPL-2.0-only OR GPL-3.0-only OR <API key>
*/
package org.kde.kdeconnect.Plugins.SftpPlugin;
import android.content.Context;
import android.os.Build;
import org.apache.sshd.common.Session;
import org.apache.sshd.common.file.FileSystemFactory;
import org.apache.sshd.common.file.FileSystemView;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class <API key> implements FileSystemFactory {
final private Context context;
final Map<String, String> roots;
<API key>(Context context) {
this.context = context;
this.roots = new HashMap<>();
}
void initRoots(List<SftpPlugin.StorageInfo> storageInfoList) {
for (SftpPlugin.StorageInfo curStorageInfo : storageInfoList) {
if (curStorageInfo.isFileUri()) {
if (curStorageInfo.uri.getPath() != null){
roots.put(curStorageInfo.displayName, curStorageInfo.uri.getPath());
}
} else if (curStorageInfo.isContentUri()){
roots.put(curStorageInfo.displayName, curStorageInfo.uri.toString());
}
}
}
@Override
public FileSystemView <API key>(final Session username) {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
if (roots.size() == 0) {
throw new RuntimeException("roots cannot be empty");
}
String[] rootsAsString = new String[roots.size()];
roots.keySet().toArray(rootsAsString);
return new <API key>(roots, rootsAsString[0], username.getUsername(), context);
} else {
return new <API key>(roots, username.getUsername(), context);
}
}
} |
#pragma once
#include "BaseButtonInputType.h"
#include "IntPoint.h"
namespace WebCore {
class ImageInputType final : public BaseButtonInputType {
public:
explicit ImageInputType(HTMLInputElement&);
private:
const AtomicString& formControlType() const override;
bool <API key>() const override;
bool appendFormData(DOMFormData&, bool) const override;
bool supportsValidation() const override;
RenderPtr<RenderElement> createInputRenderer(RenderStyle&&) override;
void <API key>(Event&) override;
void altAttributeChanged() override;
void srcAttributeChanged() override;
void attach() override;
bool <API key>() override;
bool <API key>() override;
bool isImageButton() const override;
bool isEnumeratable() override;
bool <API key>() override;
unsigned height() const override;
unsigned width() const override;
IntPoint m_clickLocation; // Valid only during HTMLFormElement::<API key>().
};
} // namespace WebCore |
c
c
c
c
c
c
c
c
c
c ## subroutine emm3hb1 -- MM3 vdw & hbond energy & derivs ##
c
c
c
c
c "emm3hb1" calculates the MM3 exp-6 van der Waals and directional
c charge transfer hydrogen bonding energy with respect to Cartesian
c coordinates
c
c literature references:
c
c J.-H. Lii and N. L. Allinger, "Directional Hydrogen Bonding in
c the MM3 Force Field. I", Journal of Physical Organic Chemistry,
c 7, 591-609 (1994)
c
c J.-H. Lii and N. L. Allinger, "Directional Hydrogen Bonding in
c the MM3 Force Field. II", Journal of Computational Chemistry,
c 19, 1001-1016 (1998)
c
c
subroutine emm3hb1
implicit none
real*8 elrc,vlrc
include 'cutoff.i'
include 'energi.i'
include 'vdwpot.i'
include 'virial.i'
c
c
c choose the method for summing over pairwise interactions
c
if (use_lights) then
call emm3hb1b
else if (use_vlist) then
call emm3hb1c
else
call emm3hb1a
end if
c
c apply long range van der Waals correction if desired
c
if (use_vcorr) then
call evcorr1 (elrc,vlrc)
ev = ev + elrc
vir(1,1) = vir(1,1) + vlrc
vir(2,2) = vir(2,2) + vlrc
vir(3,3) = vir(3,3) + vlrc
end if
return
end
c
c
c
c
c ## subroutine emm3hb1a -- double loop MM3 vdw-hbond derivs ##
c
c
c
c
c "emm3hb1a" calculates the MM3 exp-6 van der Waals and directional
c charge transfer hydrogen bonding energy with respect to Cartesian
c coordinates using a pairwise double loop
c
c
subroutine emm3hb1a
implicit none
include 'sizes.i'
include 'atmlst.i'
include 'atmtyp.i'
include 'atoms.i'
include 'bond.i'
include 'bound.i'
include 'cell.i'
include 'chgpot.i'
include 'couple.i'
include 'deriv.i'
include 'energi.i'
include 'group.i'
include 'inter.i'
include 'molcul.i'
include 'shunt.i'
include 'usage.i'
include 'vdw.i'
include 'vdwpot.i'
include 'virial.i'
integer i,j,k
integer ii,iv,it
integer kk,kv,kt
integer ia,ib,ic
integer, allocatable :: iv14(:)
real*8 e,de,rv,eps
real*8 rdn,fgrp
real*8 p,p2,p6,p12
real*8 xi,yi,zi
real*8 xr,yr,zr
real*8 redi,rediv
real*8 redk,redkv
real*8 dedx,dedy,dedz
real*8 rik,rik2,rik3
real*8 rik4,rik5,rvterm
real*8 taper,dtaper
real*8 expcut,expcut2
real*8 expterm,expmin2
real*8 expmerge
real*8 dot,cosine,sine
real*8 fterm,fcbuck,term
real*8 deddr,ideal,ratio
real*8 deddt,terma,termc
real*8 xia,yia,zia
real*8 xib,yib,zib
real*8 xic,yic,zic
real*8 xab,yab,zab
real*8 xcb,ycb,zcb
real*8 rab2,rab,rcb2
real*8 xp,yp,zp,rp
real*8 dedxia,dedyia,dedzia
real*8 dedxib,dedyib,dedzib
real*8 dedxic,dedyic,dedzic
real*8 vxx,vyy,vzz
real*8 vyx,vzx,vzy
real*8, allocatable :: xred(:)
real*8, allocatable :: yred(:)
real*8, allocatable :: zred(:)
real*8, allocatable :: vscale(:)
logical proceed,usei,use_hb
character*6 mode
c
c
c zero out the van der Waals energy and first derivatives
c
ev = 0.0d0
do i = 1, n
dev(1,i) = 0.0d0
dev(2,i) = 0.0d0
dev(3,i) = 0.0d0
end do
c
c perform dynamic allocation of some local arrays
c
allocate (iv14(n))
allocate (xred(n))
allocate (yred(n))
allocate (zred(n))
allocate (vscale(n))
c
c set arrays needed to scale connected atom interactions
c
do i = 1, n
vscale(i) = 1.0d0
iv14(i) = 0
end do
c
c set the coefficients for the switching function
c
mode = 'VDW'
call switch (mode)
c
c special cutoffs for very short and very long range terms
c
expmin2 = 0.01d0
expcut = 2.0d0
expcut2 = expcut * expcut
expmerge = (abuck*exp(-bbuck/expcut) - cbuck*(expcut**6))
& / (expcut**12)
c
c apply any reduction factor to the atomic coordinates
c
do k = 1, nvdw
i = ivdw(k)
iv = ired(i)
rdn = kred(i)
xred(i) = rdn*(x(i)-x(iv)) + x(iv)
yred(i) = rdn*(y(i)-y(iv)) + y(iv)
zred(i) = rdn*(z(i)-z(iv)) + z(iv)
end do
c
c find van der Waals energy and derivatives via double loop
c
do ii = 1, nvdw-1
i = ivdw(ii)
iv = ired(i)
redi = kred(i)
rediv = 1.0d0 - redi
it = jvdw(i)
xi = xred(i)
yi = yred(i)
zi = zred(i)
usei = (use(i) .or. use(iv))
c
c set interaction scaling coefficients for connected atoms
c
do j = 1, n12(i)
vscale(i12(j,i)) = v2scale
end do
do j = 1, n13(i)
vscale(i13(j,i)) = v3scale
end do
do j = 1, n14(i)
vscale(i14(j,i)) = v4scale
iv14(i14(j,i)) = i
end do
do j = 1, n15(i)
vscale(i15(j,i)) = v5scale
end do
c
c decide whether to compute the current interaction
c
do kk = ii+1, nvdw
k = ivdw(kk)
kv = ired(k)
proceed = .true.
if (use_group) call groups (proceed,fgrp,i,k,0,0,0,0)
if (proceed) proceed = (usei .or. use(k) .or. use(kv))
c
c compute the energy contribution for this interaction
c
if (proceed) then
kt = jvdw(k)
xr = xi - xred(k)
yr = yi - yred(k)
zr = zi - zred(k)
call image (xr,yr,zr)
rik2 = xr*xr + yr*yr + zr*zr
c
c check for an interaction distance less than the cutoff
c
if (rik2 .le. off2) then
use_hb = .false.
fterm = 1.0d0
rv = radmin(kt,it)
eps = epsilon(kt,it)
if (iv14(k) .eq. i) then
rv = radmin4(kt,it)
eps = epsilon4(kt,it)
else if (radhbnd(kt,it) .ne. 0.0d0) then
use_hb = .true.
rv = radhbnd(kt,it)
eps = epshbnd(kt,it) / dielec
if (atomic(i) .eq. 1) then
ia = i
ib = i12(1,i)
ic = k
else
ia = k
ib = i12(1,k)
ic = i
end if
xia = x(ia)
yia = y(ia)
zia = z(ia)
xib = x(ib)
yib = y(ib)
zib = z(ib)
xic = x(ic)
yic = y(ic)
zic = z(ic)
xab = xia - xib
yab = yia - yib
zab = zia - zib
xcb = xic - xib
ycb = yic - yib
zcb = zic - zib
call image (xcb,ycb,zcb)
xp = ycb*zab - zcb*yab
yp = zcb*xab - xcb*zab
zp = xcb*yab - ycb*xab
rp = sqrt(xp*xp + yp*yp + zp*zp)
rab2 = xab*xab + yab*yab + zab*zab
rcb2 = xcb*xcb + ycb*ycb + zcb*zcb
rcb2 = max(0.0001d0,rcb2)
dot = xab*xcb + yab*ycb + zab*zcb
cosine = dot / sqrt(rab2*rcb2)
sine = sqrt(abs(1.0d0-cosine**2))
rab = sqrt(rab2)
ideal = bl(bndlist(1,ia))
ratio = rab / ideal
fterm = cosine * ratio
deddt = -sine * ratio
deddr = cosine / (rab*ideal)
end if
eps = eps * vscale(k)
p2 = (rv*rv) / rik2
p6 = p2 * p2 * p2
rik = sqrt(rik2)
if (p2 .le. expmin2) then
e = 0.0d0
de = 0.0d0
else if (p2 .le. expcut2) then
p = sqrt(p2)
rvterm = -bbuck / rv
expterm = abuck * exp(-bbuck/p)
fcbuck = fterm * cbuck * p6
e = eps * (expterm - fcbuck)
de = eps * (rvterm*expterm+6.0d0*fcbuck/rik)
else
use_hb = .false.
p12 = p6 * p6
e = expmerge * eps * p12
de = -12.0d0 * e / rik
end if
c
c use energy switching if near the cutoff distance
c
if (rik2 .gt. cut2) then
rik3 = rik2 * rik
rik4 = rik2 * rik2
rik5 = rik2 * rik3
taper = c5*rik5 + c4*rik4 + c3*rik3
& + c2*rik2 + c1*rik + c0
dtaper = 5.0d0*c5*rik4 + 4.0d0*c4*rik3
& + 3.0d0*c3*rik2 + 2.0d0*c2*rik + c1
de = e*dtaper + de*taper
e = e * taper
end if
c
c scale the interaction based on its group membership
c
if (use_group) then
e = e * fgrp
de = de * fgrp
if (use_hb) then
deddt = deddt * fgrp
deddr = deddr * fgrp
end if
end if
c
c find the chain rule terms for derivative components
c
de = de / rik
dedx = de * xr
dedy = de * yr
dedz = de * zr
c
c increment the total van der Waals energy and derivatives
c
ev = ev + e
if (i .eq. iv) then
dev(1,i) = dev(1,i) + dedx
dev(2,i) = dev(2,i) + dedy
dev(3,i) = dev(3,i) + dedz
else
dev(1,i) = dev(1,i) + dedx*redi
dev(2,i) = dev(2,i) + dedy*redi
dev(3,i) = dev(3,i) + dedz*redi
dev(1,iv) = dev(1,iv) + dedx*rediv
dev(2,iv) = dev(2,iv) + dedy*rediv
dev(3,iv) = dev(3,iv) + dedz*rediv
end if
if (k .eq. kv) then
dev(1,k) = dev(1,k) - dedx
dev(2,k) = dev(2,k) - dedy
dev(3,k) = dev(3,k) - dedz
else
redk = kred(k)
redkv = 1.0d0 - redk
dev(1,k) = dev(1,k) - dedx*redk
dev(2,k) = dev(2,k) - dedy*redk
dev(3,k) = dev(3,k) - dedz*redk
dev(1,kv) = dev(1,kv) - dedx*redkv
dev(2,kv) = dev(2,kv) - dedy*redkv
dev(3,kv) = dev(3,kv) - dedz*redkv
end if
c
c find the chain rule terms for hydrogen bonding components
c
if (use_hb) then
term = eps * cbuck * p6
deddt = deddt * term
deddr = deddr * term
if (rik2 .gt. cut2) then
deddt = deddt * taper
deddr = deddr * taper
end if
terma = deddt / (rab2*max(rp,1.0d-6))
termc = -deddt / (rcb2*max(rp,1.0d-6))
dedxia = terma * (yab*zp-zab*yp) - deddr*xab
dedyia = terma * (zab*xp-xab*zp) - deddr*yab
dedzia = terma * (xab*yp-yab*xp) - deddr*zab
dedxic = termc * (ycb*zp-zcb*yp)
dedyic = termc * (zcb*xp-xcb*zp)
dedzic = termc * (xcb*yp-ycb*xp)
dedxib = -dedxia - dedxic
dedyib = -dedyia - dedyic
dedzib = -dedzia - dedzic
c
c increment the derivatives for directional hydrogen bonding
c
dev(1,ia) = dev(1,ia) + dedxia
dev(2,ia) = dev(2,ia) + dedyia
dev(3,ia) = dev(3,ia) + dedzia
dev(1,ib) = dev(1,ib) + dedxib
dev(2,ib) = dev(2,ib) + dedyib
dev(3,ib) = dev(3,ib) + dedzib
dev(1,ic) = dev(1,ic) + dedxic
dev(2,ic) = dev(2,ic) + dedyic
dev(3,ic) = dev(3,ic) + dedzic
end if
c
c increment the internal virial tensor components
c
vxx = xr * dedx
vyx = yr * dedx
vzx = zr * dedx
vyy = yr * dedy
vzy = zr * dedy
vzz = zr * dedz
if (use_hb) then
vxx = xab*dedxia + xcb*dedxic
vyx = yab*dedxia + ycb*dedxic
vzx = zab*dedxia + zcb*dedxic
vyy = yab*dedyia + ycb*dedyic
vzy = zab*dedyia + zcb*dedyic
vzz = zab*dedzia + zcb*dedzic
end if
vir(1,1) = vir(1,1) + vxx
vir(2,1) = vir(2,1) + vyx
vir(3,1) = vir(3,1) + vzx
vir(1,2) = vir(1,2) + vyx
vir(2,2) = vir(2,2) + vyy
vir(3,2) = vir(3,2) + vzy
vir(1,3) = vir(1,3) + vzx
vir(2,3) = vir(2,3) + vzy
vir(3,3) = vir(3,3) + vzz
c
c increment the total intermolecular energy
c
if (molcule(i) .ne. molcule(k)) then
einter = einter + e
end if
end if
end if
end do
c
c reset interaction scaling coefficients for connected atoms
c
do j = 1, n12(i)
vscale(i12(j,i)) = 1.0d0
end do
do j = 1, n13(i)
vscale(i13(j,i)) = 1.0d0
end do
do j = 1, n14(i)
vscale(i14(j,i)) = 1.0d0
end do
do j = 1, n15(i)
vscale(i15(j,i)) = 1.0d0
end do
end do
c
c for periodic boundary conditions with large cutoffs
c neighbors must be found by the replicates method
c
if (.not. use_replica) return
c
c calculate interaction energy with other unit cells
c
do ii = 1, nvdw
i = ivdw(ii)
iv = ired(i)
redi = kred(i)
rediv = 1.0d0 - redi
it = jvdw(i)
xi = xred(i)
yi = yred(i)
zi = zred(i)
usei = (use(i) .or. use(iv))
c
c set interaction scaling coefficients for connected atoms
c
do j = 1, n12(i)
vscale(i12(j,i)) = v2scale
end do
do j = 1, n13(i)
vscale(i13(j,i)) = v3scale
end do
do j = 1, n14(i)
vscale(i14(j,i)) = v4scale
iv14(i14(j,i)) = i
end do
do j = 1, n15(i)
vscale(i15(j,i)) = v5scale
end do
c
c decide whether to compute the current interaction
c
do kk = ii, nvdw
k = ivdw(kk)
kv = ired(k)
proceed = .true.
if (use_group) call groups (proceed,fgrp,i,k,0,0,0,0)
if (proceed) proceed = (usei .or. use(k) .or. use(kv))
c
c compute the energy contribution for this interaction
c
if (proceed) then
kt = jvdw(k)
do j = 1, ncell
xr = xi - xred(k)
yr = yi - yred(k)
zr = zi - zred(k)
call imager (xr,yr,zr,j)
rik2 = xr*xr + yr*yr + zr*zr
c
c check for an interaction distance less than the cutoff
c
if (rik2 .le. off2) then
use_hb = .false.
fterm = 1.0d0
rv = radmin(kt,it)
eps = epsilon(kt,it)
if (radhbnd(kt,it) .ne. 0.0d0) then
use_hb = .true.
rv = radhbnd(kt,it)
eps = epshbnd(kt,it) / dielec
if (atomic(i) .eq. 1) then
ia = i
ib = i12(1,i)
ic = k
else
ia = k
ib = i12(1,k)
ic = i
end if
xia = x(ia)
yia = y(ia)
zia = z(ia)
xib = x(ib)
yib = y(ib)
zib = z(ib)
xic = x(ic)
yic = y(ic)
zic = z(ic)
xab = xia - xib
yab = yia - yib
zab = zia - zib
xcb = xic - xib
ycb = yic - yib
zcb = zic - zib
call imager (xcb,ycb,zcb,j)
xp = ycb*zab - zcb*yab
yp = zcb*xab - xcb*zab
zp = xcb*yab - ycb*xab
rp = sqrt(xp*xp + yp*yp + zp*zp)
rab2 = xab*xab + yab*yab + zab*zab
rcb2 = xcb*xcb + ycb*ycb + zcb*zcb
rcb2 = max(0.0001d0,rcb2)
dot = xab*xcb + yab*ycb + zab*zcb
cosine = dot / sqrt(rab2*rcb2)
sine = sqrt(abs(1.0d0-cosine**2))
rab = sqrt(rab2)
ideal = bl(bndlist(1,ia))
ratio = rab / ideal
fterm = cosine * ratio
deddt = -sine * ratio
deddr = cosine / (rab*ideal)
end if
if (use_polymer) then
if (rik2 .le. polycut2) then
if (iv14(k) .eq. i) then
fterm = 1.0d0
rv = radmin4(kt,it)
eps = epsilon4(kt,it)
end if
eps = eps * vscale(k)
end if
end if
p2 = (rv*rv) / rik2
p6 = p2 * p2 * p2
rik = sqrt(rik2)
if (p2 .le. expmin2) then
e = 0.0d0
de = 0.0d0
else if (p2 .le. expcut2) then
p = sqrt(p2)
rvterm = -bbuck / rv
expterm = abuck * exp(-bbuck/p)
fcbuck = fterm * cbuck * p6
e = eps * (expterm - fcbuck)
de = eps * (rvterm*expterm+6.0d0*fcbuck/rik)
else
use_hb = .false.
p12 = p6 * p6
e = expmerge * eps * p12
de = -12.0d0 * e / rik
end if
c
c use energy switching if near the cutoff distance
c
if (rik2 .gt. cut2) then
rik3 = rik2 * rik
rik4 = rik2 * rik2
rik5 = rik2 * rik3
taper = c5*rik5 + c4*rik4 + c3*rik3
& + c2*rik2 + c1*rik + c0
dtaper = 5.0d0*c5*rik4 + 4.0d0*c4*rik3
& + 3.0d0*c3*rik2 + 2.0d0*c2*rik + c1
de = e*dtaper + de*taper
e = e * taper
end if
c
c scale the interaction based on its group membership
c
if (use_group) then
e = e * fgrp
de = de * fgrp
if (use_hb) then
deddt = deddt * fgrp
deddr = deddr * fgrp
end if
end if
c
c find the chain rule terms for derivative components
c
de = de / rik
dedx = de * xr
dedy = de * yr
dedz = de * zr
c
c increment the total van der Waals energy and derivatives
c
if (i .eq. k) e = 0.5d0 * e
ev = ev + e
if (i .eq. iv) then
dev(1,i) = dev(1,i) + dedx
dev(2,i) = dev(2,i) + dedy
dev(3,i) = dev(3,i) + dedz
else
dev(1,i) = dev(1,i) + dedx*redi
dev(2,i) = dev(2,i) + dedy*redi
dev(3,i) = dev(3,i) + dedz*redi
dev(1,iv) = dev(1,iv) + dedx*rediv
dev(2,iv) = dev(2,iv) + dedy*rediv
dev(3,iv) = dev(3,iv) + dedz*rediv
end if
if (i .ne. k) then
if (k .eq. kv) then
dev(1,k) = dev(1,k) - dedx
dev(2,k) = dev(2,k) - dedy
dev(3,k) = dev(3,k) - dedz
else
redk = kred(k)
redkv = 1.0d0 - redk
dev(1,k) = dev(1,k) - dedx*redk
dev(2,k) = dev(2,k) - dedy*redk
dev(3,k) = dev(3,k) - dedz*redk
dev(1,kv) = dev(1,kv) - dedx*redkv
dev(2,kv) = dev(2,kv) - dedy*redkv
dev(3,kv) = dev(3,kv) - dedz*redkv
end if
end if
c
c find the chain rule terms for hydrogen bonding components
c
if (use_hb) then
term = eps * cbuck * p6
deddt = deddt * term
deddr = deddr * term
if (rik2 .gt. cut2) then
deddt = deddt * taper
deddr = deddr * taper
end if
terma = deddt / (rab2*max(rp,1.0d-6))
termc = -deddt / (rcb2*max(rp,1.0d-6))
dedxia = terma * (yab*zp-zab*yp) - deddr*xab
dedyia = terma * (zab*xp-xab*zp) - deddr*yab
dedzia = terma * (xab*yp-yab*xp) - deddr*zab
dedxic = termc * (ycb*zp-zcb*yp)
dedyic = termc * (zcb*xp-xcb*zp)
dedzic = termc * (xcb*yp-ycb*xp)
dedxib = -dedxia - dedxic
dedyib = -dedyia - dedyic
dedzib = -dedzia - dedzic
c
c increment the derivatives for directional hydrogen bonding
c
dev(1,ia) = dev(1,ia) + dedxia
dev(2,ia) = dev(2,ia) + dedyia
dev(3,ia) = dev(3,ia) + dedzia
dev(1,ib) = dev(1,ib) + dedxib
dev(2,ib) = dev(2,ib) + dedyib
dev(3,ib) = dev(3,ib) + dedzib
dev(1,ic) = dev(1,ic) + dedxic
dev(2,ic) = dev(2,ic) + dedyic
dev(3,ic) = dev(3,ic) + dedzic
end if
c
c increment the internal virial tensor components
c
vxx = xr * dedx
vyx = yr * dedx
vzx = zr * dedx
vyy = yr * dedy
vzy = zr * dedy
vzz = zr * dedz
if (use_hb) then
vxx = xab*dedxia + xcb*dedxic
vyx = yab*dedxia + ycb*dedxic
vzx = zab*dedxia + zcb*dedxic
vyy = yab*dedyia + ycb*dedyic
vzy = zab*dedyia + zcb*dedyic
vzz = zab*dedzia + zcb*dedzic
end if
vir(1,1) = vir(1,1) + vxx
vir(2,1) = vir(2,1) + vyx
vir(3,1) = vir(3,1) + vzx
vir(1,2) = vir(1,2) + vyx
vir(2,2) = vir(2,2) + vyy
vir(3,2) = vir(3,2) + vzy
vir(1,3) = vir(1,3) + vzx
vir(2,3) = vir(2,3) + vzy
vir(3,3) = vir(3,3) + vzz
c
c increment the total intermolecular energy
c
einter = einter + e
end if
end do
end if
end do
c
c reset interaction scaling coefficients for connected atoms
c
do j = 1, n12(i)
vscale(i12(j,i)) = 1.0d0
end do
do j = 1, n13(i)
vscale(i13(j,i)) = 1.0d0
end do
do j = 1, n14(i)
vscale(i14(j,i)) = 1.0d0
end do
do j = 1, n15(i)
vscale(i15(j,i)) = 1.0d0
end do
end do
c
c perform deallocation of some local arrays
c
deallocate (iv14)
deallocate (xred)
deallocate (yred)
deallocate (zred)
deallocate (vscale)
return
end
c
c
c
c
c ## subroutine emm3hb1b -- MM3 vdw-hbond derivs via lights ##
c
c
c
c
c "emm3hb1b" calculates the MM3 exp-6 van der Waals and directional
c charge transfer hydrogen bonding energy with respect to Cartesian
c coordinates using the method of lights
c
c
subroutine emm3hb1b
implicit none
include 'sizes.i'
include 'atmlst.i'
include 'atmtyp.i'
include 'atoms.i'
include 'bond.i'
include 'bound.i'
include 'boxes.i'
include 'cell.i'
include 'chgpot.i'
include 'couple.i'
include 'deriv.i'
include 'energi.i'
include 'group.i'
include 'inter.i'
include 'iounit.i'
include 'light.i'
include 'molcul.i'
include 'shunt.i'
include 'usage.i'
include 'vdw.i'
include 'vdwpot.i'
include 'virial.i'
integer i,j,k
integer ii,iv,it
integer kk,kv,kt
integer ia,ib,ic
integer kgy,kgz
integer start,stop
integer, allocatable :: iv14(:)
real*8 e,de,rv,eps
real*8 rdn,fgrp
real*8 p,p2,p6,p12
real*8 xi,yi,zi
real*8 xr,yr,zr
real*8 redi,rediv
real*8 redk,redkv
real*8 dedx,dedy,dedz
real*8 rik,rik2,rik3
real*8 rik4,rik5,rvterm
real*8 taper,dtaper
real*8 expcut,expcut2
real*8 expterm,expmin2
real*8 expmerge,fcbuck
real*8 dot,cosine,sine
real*8 term,terma,termc
real*8 fterm,ideal,ratio
real*8 deddr,deddt
real*8 xia,yia,zia
real*8 xib,yib,zib
real*8 xic,yic,zic
real*8 xab,yab,zab
real*8 xcb,ycb,zcb
real*8 rab2,rab,rcb2
real*8 xp,yp,zp,rp
real*8 dedxia,dedyia,dedzia
real*8 dedxib,dedyib,dedzib
real*8 dedxic,dedyic,dedzic
real*8 vxx,vyy,vzz
real*8 vyx,vzx,vzy
real*8, allocatable :: xred(:)
real*8, allocatable :: yred(:)
real*8, allocatable :: zred(:)
real*8, allocatable :: vscale(:)
real*8, allocatable :: xsort(:)
real*8, allocatable :: ysort(:)
real*8, allocatable :: zsort(:)
logical proceed,usei
logical prime,repeat
logical use_hb
character*6 mode
c
c
c zero out the van der Waals energy and first derivatives
c
ev = 0.0d0
do i = 1, n
dev(1,i) = 0.0d0
dev(2,i) = 0.0d0
dev(3,i) = 0.0d0
end do
c
c perform dynamic allocation of some local arrays
c
allocate (iv14(n))
allocate (xred(n))
allocate (yred(n))
allocate (zred(n))
allocate (vscale(n))
allocate (xsort(8*n))
allocate (ysort(8*n))
allocate (zsort(8*n))
c
c set arrays needed to scale connected atom interactions
c
do i = 1, n
vscale(i) = 1.0d0
iv14(i) = 0
end do
c
c set the coefficients for the switching function
c
mode = 'VDW'
call switch (mode)
c
c special cutoffs for very short and very long range terms
c
expmin2 = 0.01d0
expcut = 2.0d0
expcut2 = expcut * expcut
expmerge = (abuck*exp(-bbuck/expcut) - cbuck*(expcut**6))
& / (expcut**12)
c
c apply any reduction factor to the atomic coordinates
c
do j = 1, nvdw
i = ivdw(j)
iv = ired(i)
rdn = kred(i)
xred(j) = rdn*(x(i)-x(iv)) + x(iv)
yred(j) = rdn*(y(i)-y(iv)) + y(iv)
zred(j) = rdn*(z(i)-z(iv)) + z(iv)
end do
c
c transfer the interaction site coordinates to sorting arrays
c
do i = 1, nvdw
xsort(i) = xred(i)
ysort(i) = yred(i)
zsort(i) = zred(i)
end do
c
c use the method of lights to generate neighbors
c
call lights (off,nvdw,xsort,ysort,zsort)
c
c now, loop over all atoms computing the interactions
c
do ii = 1, nvdw
i = ivdw(ii)
iv = ired(i)
redi = kred(i)
rediv = 1.0d0 - redi
it = jvdw(i)
xi = xsort(rgx(ii))
yi = ysort(rgy(ii))
zi = zsort(rgz(ii))
usei = (use(i) .or. use(iv))
c
c set interaction scaling coefficients for connected atoms
c
do j = 1, n12(i)
vscale(i12(j,i)) = v2scale
end do
do j = 1, n13(i)
vscale(i13(j,i)) = v3scale
end do
do j = 1, n14(i)
vscale(i14(j,i)) = v4scale
iv14(i14(j,i)) = i
end do
do j = 1, n15(i)
vscale(i15(j,i)) = v5scale
end do
c
c loop over method of lights neighbors of current atom
c
if (kbx(ii) .le. kex(ii)) then
repeat = .false.
start = kbx(ii) + 1
stop = kex(ii)
else
repeat = .true.
start = 1
stop = kex(ii)
end if
10 continue
do j = start, stop
kk = locx(j)
kgy = rgy(kk)
if (kby(ii) .le. key(ii)) then
if (kgy.lt.kby(ii) .or. kgy.gt.key(ii)) goto 20
else
if (kgy.lt.kby(ii) .and. kgy.gt.key(ii)) goto 20
end if
kgz = rgz(kk)
if (kbz(ii) .le. kez(ii)) then
if (kgz.lt.kbz(ii) .or. kgz.gt.kez(ii)) goto 20
else
if (kgz.lt.kbz(ii) .and. kgz.gt.kez(ii)) goto 20
end if
k = ivdw(kk-((kk-1)/nvdw)*nvdw)
kv = ired(k)
prime = (kk .le. nvdw)
c
c decide whether to compute the current interaction
c
proceed = .true.
if (use_group) call groups (proceed,fgrp,i,k,0,0,0,0)
if (proceed) proceed = (usei .or. use(k) .or. use(kv))
if (proceed) proceed = (vscale(k) .ne. 0.0d0)
c
c compute the energy contribution for this interaction
c
if (proceed) then
kt = jvdw(k)
xr = xi - xsort(j)
yr = yi - ysort(kgy)
zr = zi - zsort(kgz)
if (use_bounds) then
if (abs(xr) .gt. xcell2) xr = xr - sign(xcell,xr)
if (abs(yr) .gt. ycell2) yr = yr - sign(ycell,yr)
if (abs(zr) .gt. zcell2) zr = zr - sign(zcell,zr)
if (monoclinic) then
xr = xr + zr*beta_cos
zr = zr * beta_sin
else if (triclinic) then
xr = xr + yr*gamma_cos + zr*beta_cos
yr = yr*gamma_sin + zr*beta_term
zr = zr * gamma_term
end if
end if
rik2 = xr*xr + yr*yr + zr*zr
c
c check for an interaction distance less than the cutoff
c
if (rik2 .le. off2) then
use_hb = .false.
fterm = 1.0d0
rv = radmin(kt,it)
eps = epsilon(kt,it)
if (iv14(k).eq.i .and. prime) then
rv = radmin4(kt,it)
eps = epsilon4(kt,it)
else if (radhbnd(kt,it) .ne. 0.0d0) then
use_hb = .true.
rv = radhbnd(kt,it)
eps = epshbnd(kt,it) / dielec
if (atomic(i) .eq. 1) then
ia = i
ib = i12(1,i)
ic = k
else
ia = k
ib = i12(1,k)
ic = i
end if
xia = x(ia)
yia = y(ia)
zia = z(ia)
xib = x(ib)
yib = y(ib)
zib = z(ib)
xic = x(ic)
yic = y(ic)
zic = z(ic)
xab = xia - xib
yab = yia - yib
zab = zia - zib
xcb = xic - xib
ycb = yic - yib
zcb = zic - zib
if (use_bounds) then
if (abs(xcb) .gt. xcell2)
& xcb = xcb - sign(xcell,xcb)
if (abs(ycb) .gt. ycell2)
& ycb = ycb - sign(ycell,ycb)
if (abs(zcb) .gt. zcell2)
& zcb = zcb - sign(zcell,zcb)
if (monoclinic) then
xcb = xcb + zcb*beta_cos
zcb = zcb * beta_sin
else if (triclinic) then
xcb = xcb + ycb*gamma_cos + zcb*beta_cos
ycb = ycb*gamma_sin + zcb*beta_term
zcb = zcb * gamma_term
end if
end if
xp = ycb*zab - zcb*yab
yp = zcb*xab - xcb*zab
zp = xcb*yab - ycb*xab
rp = sqrt(xp*xp + yp*yp + zp*zp)
rab2 = xab*xab + yab*yab + zab*zab
rcb2 = xcb*xcb + ycb*ycb + zcb*zcb
rcb2 = max(0.0001d0,rcb2)
dot = xab*xcb + yab*ycb + zab*zcb
cosine = dot / sqrt(rab2*rcb2)
sine = sqrt(abs(1.0d0-cosine**2))
rab = sqrt(rab2)
ideal = bl(bndlist(1,ia))
ratio = rab / ideal
fterm = cosine * ratio
deddt = -sine * ratio
deddr = cosine / (rab*ideal)
end if
if (prime) eps = eps * vscale(k)
p2 = (rv*rv) / rik2
p6 = p2 * p2 * p2
rik = sqrt(rik2)
if (p2 .le. expmin2) then
e = 0.0d0
de = 0.0d0
else if (p2 .le. expcut2) then
p = sqrt(p2)
rvterm = -bbuck / rv
expterm = abuck * exp(-bbuck/p)
fcbuck = fterm * cbuck * p6
e = eps * (expterm - fcbuck)
de = eps * (rvterm*expterm+6.0d0*fcbuck/rik)
else
use_hb = .false.
p12 = p6 * p6
e = expmerge * eps * p12
de = -12.0d0 * e / rik
end if
c
c use energy switching if near the cutoff distance
c
if (rik2 .gt. cut2) then
rik3 = rik2 * rik
rik4 = rik2 * rik2
rik5 = rik2 * rik3
taper = c5*rik5 + c4*rik4 + c3*rik3
& + c2*rik2 + c1*rik + c0
dtaper = 5.0d0*c5*rik4 + 4.0d0*c4*rik3
& + 3.0d0*c3*rik2 + 2.0d0*c2*rik + c1
de = e*dtaper + de*taper
e = e * taper
end if
c
c scale the interaction based on its group membership
c
if (use_group) then
e = e * fgrp
de = de * fgrp
if (use_hb) then
deddt = deddt * fgrp
deddr = deddr * fgrp
end if
end if
c
c find the chain rule terms for derivative components
c
de = de / rik
dedx = de * xr
dedy = de * yr
dedz = de * zr
c
c increment the total van der Waals energy and derivatives
c
ev = ev + e
if (i .eq. iv) then
dev(1,i) = dev(1,i) + dedx
dev(2,i) = dev(2,i) + dedy
dev(3,i) = dev(3,i) + dedz
else
dev(1,i) = dev(1,i) + dedx*redi
dev(2,i) = dev(2,i) + dedy*redi
dev(3,i) = dev(3,i) + dedz*redi
dev(1,iv) = dev(1,iv) + dedx*rediv
dev(2,iv) = dev(2,iv) + dedy*rediv
dev(3,iv) = dev(3,iv) + dedz*rediv
end if
if (k .eq. kv) then
dev(1,k) = dev(1,k) - dedx
dev(2,k) = dev(2,k) - dedy
dev(3,k) = dev(3,k) - dedz
else
redk = kred(k)
redkv = 1.0d0 - redk
dev(1,k) = dev(1,k) - dedx*redk
dev(2,k) = dev(2,k) - dedy*redk
dev(3,k) = dev(3,k) - dedz*redk
dev(1,kv) = dev(1,kv) - dedx*redkv
dev(2,kv) = dev(2,kv) - dedy*redkv
dev(3,kv) = dev(3,kv) - dedz*redkv
end if
c
c find the chain rule terms for hydrogen bonding components
c
if (use_hb) then
term = eps * cbuck * p6
deddt = deddt * term
deddr = deddr * term
if (rik2 .gt. cut2) then
deddt = deddt * taper
deddr = deddr * taper
end if
terma = deddt / (rab2*rp)
termc = -deddt / (rcb2*rp)
dedxia = terma * (yab*zp-zab*yp) - deddr*xab
dedyia = terma * (zab*xp-xab*zp) - deddr*yab
dedzia = terma * (xab*yp-yab*xp) - deddr*zab
dedxic = termc * (ycb*zp-zcb*yp)
dedyic = termc * (zcb*xp-xcb*zp)
dedzic = termc * (xcb*yp-ycb*xp)
dedxib = -dedxia - dedxic
dedyib = -dedyia - dedyic
dedzib = -dedzia - dedzic
c
c increment the derivatives for directional hydrogen bonding
c
dev(1,ia) = dev(1,ia) + dedxia
dev(2,ia) = dev(2,ia) + dedyia
dev(3,ia) = dev(3,ia) + dedzia
dev(1,ib) = dev(1,ib) + dedxib
dev(2,ib) = dev(2,ib) + dedyib
dev(3,ib) = dev(3,ib) + dedzib
dev(1,ic) = dev(1,ic) + dedxic
dev(2,ic) = dev(2,ic) + dedyic
dev(3,ic) = dev(3,ic) + dedzic
end if
c
c increment the internal virial tensor components
c
vxx = xr * dedx
vyx = yr * dedx
vzx = zr * dedx
vyy = yr * dedy
vzy = zr * dedy
vzz = zr * dedz
if (use_hb) then
vxx = xab*dedxia + xcb*dedxic
vyx = yab*dedxia + ycb*dedxic
vzx = zab*dedxia + zcb*dedxic
vyy = yab*dedyia + ycb*dedyic
vzy = zab*dedyia + zcb*dedyic
vzz = zab*dedzia + zcb*dedzic
end if
vir(1,1) = vir(1,1) + vxx
vir(2,1) = vir(2,1) + vyx
vir(3,1) = vir(3,1) + vzx
vir(1,2) = vir(1,2) + vyx
vir(2,2) = vir(2,2) + vyy
vir(3,2) = vir(3,2) + vzy
vir(1,3) = vir(1,3) + vzx
vir(2,3) = vir(2,3) + vzy
vir(3,3) = vir(3,3) + vzz
c
c increment the total intermolecular energy
c
if (.not.prime .or. molcule(i).ne.molcule(k)) then
einter = einter + e
end if
end if
end if
20 continue
end do
if (repeat) then
repeat = .false.
start = kbx(ii) + 1
stop = nlight
goto 10
end if
c
c reset interaction scaling coefficients for connected atoms
c
do j = 1, n12(i)
vscale(i12(j,i)) = 1.0d0
end do
do j = 1, n13(i)
vscale(i13(j,i)) = 1.0d0
end do
do j = 1, n14(i)
vscale(i14(j,i)) = 1.0d0
end do
do j = 1, n15(i)
vscale(i15(j,i)) = 1.0d0
end do
end do
c
c perform deallocation of some local arrays
c
deallocate (iv14)
deallocate (xred)
deallocate (yred)
deallocate (zred)
deallocate (vscale)
deallocate (xsort)
deallocate (ysort)
deallocate (zsort)
return
end
c
c
c
c
c ## subroutine emm3hb1c -- MM3 vdw-hbond derivs via list ##
c
c
c
c
c "emm3hb1c" calculates the MM3 exp-6 van der Waals and directional
c charge transfer hydrogen bonding energy with respect to Cartesian
c coordinates using a pairwise neighbor list
c
c
subroutine emm3hb1c
implicit none
include 'sizes.i'
include 'atmlst.i'
include 'atmtyp.i'
include 'atoms.i'
include 'bond.i'
include 'bound.i'
include 'chgpot.i'
include 'couple.i'
include 'deriv.i'
include 'energi.i'
include 'group.i'
include 'inter.i'
include 'molcul.i'
include 'neigh.i'
include 'shunt.i'
include 'usage.i'
include 'vdw.i'
include 'vdwpot.i'
include 'virial.i'
integer i,j,k
integer ii,iv,it
integer kk,kv,kt
integer ia,ib,ic
integer, allocatable :: iv14(:)
real*8 e,de,rv,eps
real*8 rdn,fgrp
real*8 p,p2,p6,p12
real*8 xi,yi,zi
real*8 xr,yr,zr
real*8 redi,rediv
real*8 redk,redkv
real*8 dedx,dedy,dedz
real*8 rik,rik2,rik3
real*8 rik4,rik5,rvterm
real*8 taper,dtaper
real*8 expcut,expcut2
real*8 expterm,expmin2
real*8 expmerge
real*8 dot,cosine,sine
real*8 fterm,fcbuck,term
real*8 deddr,ideal,ratio
real*8 deddt,terma,termc
real*8 xia,yia,zia
real*8 xib,yib,zib
real*8 xic,yic,zic
real*8 xab,yab,zab
real*8 xcb,ycb,zcb
real*8 rab2,rab,rcb2
real*8 xp,yp,zp,rp
real*8 dedxia,dedyia,dedzia
real*8 dedxib,dedyib,dedzib
real*8 dedxic,dedyic,dedzic
real*8 vxx,vyy,vzz
real*8 vyx,vzx,vzy
real*8, allocatable :: xred(:)
real*8, allocatable :: yred(:)
real*8, allocatable :: zred(:)
real*8, allocatable :: vscale(:)
logical proceed,usei,use_hb
character*6 mode
c
c
c zero out the van der Waals energy and first derivatives
c
ev = 0.0d0
do i = 1, n
dev(1,i) = 0.0d0
dev(2,i) = 0.0d0
dev(3,i) = 0.0d0
end do
c
c perform dynamic allocation of some local arrays
c
allocate (iv14(n))
allocate (xred(n))
allocate (yred(n))
allocate (zred(n))
allocate (vscale(n))
c
c set arrays needed to scale connected atom interactions
c
do i = 1, n
vscale(i) = 1.0d0
iv14(i) = 0
end do
c
c set the coefficients for the switching function
c
mode = 'VDW'
call switch (mode)
c
c special cutoffs for very short and very long range terms
c
expmin2 = 0.01d0
expcut = 2.0d0
expcut2 = expcut * expcut
expmerge = (abuck*exp(-bbuck/expcut) - cbuck*(expcut**6))
& / (expcut**12)
c
c apply any reduction factor to the atomic coordinates
c
do k = 1, nvdw
i = ivdw(k)
iv = ired(i)
rdn = kred(i)
xred(i) = rdn*(x(i)-x(iv)) + x(iv)
yred(i) = rdn*(y(i)-y(iv)) + y(iv)
zred(i) = rdn*(z(i)-z(iv)) + z(iv)
end do
c
c find van der Waals energy and derivatives via neighbor list
c
do ii = 1, nvdw
i = ivdw(ii)
iv = ired(i)
redi = kred(i)
rediv = 1.0d0 - redi
it = jvdw(i)
xi = xred(i)
yi = yred(i)
zi = zred(i)
usei = (use(i) .or. use(iv))
c
c set interaction scaling coefficients for connected atoms
c
do j = 1, n12(i)
vscale(i12(j,i)) = v2scale
end do
do j = 1, n13(i)
vscale(i13(j,i)) = v3scale
end do
do j = 1, n14(i)
vscale(i14(j,i)) = v4scale
iv14(i14(j,i)) = i
end do
do j = 1, n15(i)
vscale(i15(j,i)) = v5scale
end do
c
c decide whether to compute the current interaction
c
do kk = 1, nvlst(ii)
k = ivdw(vlst(kk,ii))
kv = ired(k)
proceed = .true.
if (use_group) call groups (proceed,fgrp,i,k,0,0,0,0)
if (proceed) proceed = (usei .or. use(k) .or. use(kv))
c
c compute the energy contribution for this interaction
c
if (proceed) then
kt = jvdw(k)
xr = xi - xred(k)
yr = yi - yred(k)
zr = zi - zred(k)
call image (xr,yr,zr)
rik2 = xr*xr + yr*yr + zr*zr
c
c check for an interaction distance less than the cutoff
c
if (rik2 .le. off2) then
use_hb = .false.
fterm = 1.0d0
rv = radmin(kt,it)
eps = epsilon(kt,it)
if (iv14(k) .eq. i) then
rv = radmin4(kt,it)
eps = epsilon4(kt,it)
else if (radhbnd(kt,it) .ne. 0.0d0) then
use_hb = .true.
rv = radhbnd(kt,it)
eps = epshbnd(kt,it) / dielec
if (atomic(i) .eq. 1) then
ia = i
ib = i12(1,i)
ic = k
else
ia = k
ib = i12(1,k)
ic = i
end if
xia = x(ia)
yia = y(ia)
zia = z(ia)
xib = x(ib)
yib = y(ib)
zib = z(ib)
xic = x(ic)
yic = y(ic)
zic = z(ic)
xab = xia - xib
yab = yia - yib
zab = zia - zib
xcb = xic - xib
ycb = yic - yib
zcb = zic - zib
call image (xcb,ycb,zcb)
xp = ycb*zab - zcb*yab
yp = zcb*xab - xcb*zab
zp = xcb*yab - ycb*xab
rp = sqrt(xp*xp + yp*yp + zp*zp)
rab2 = xab*xab + yab*yab + zab*zab
rcb2 = xcb*xcb + ycb*ycb + zcb*zcb
rcb2 = max(0.0001d0,rcb2)
dot = xab*xcb + yab*ycb + zab*zcb
cosine = dot / sqrt(rab2*rcb2)
sine = sqrt(abs(1.0d0-cosine**2))
rab = sqrt(rab2)
ideal = bl(bndlist(1,ia))
ratio = rab / ideal
fterm = cosine * ratio
deddt = -sine * ratio
deddr = cosine / (rab*ideal)
end if
eps = eps * vscale(k)
p2 = (rv*rv) / rik2
p6 = p2 * p2 * p2
rik = sqrt(rik2)
if (p2 .le. expmin2) then
e = 0.0d0
de = 0.0d0
else if (p2 .le. expcut2) then
p = sqrt(p2)
rvterm = -bbuck / rv
expterm = abuck * exp(-bbuck/p)
fcbuck = fterm * cbuck * p6
e = eps * (expterm - fcbuck)
de = eps * (rvterm*expterm+6.0d0*fcbuck/rik)
else
use_hb = .false.
p12 = p6 * p6
e = expmerge * eps * p12
de = -12.0d0 * e / rik
end if
c
c use energy switching if near the cutoff distance
c
if (rik2 .gt. cut2) then
rik3 = rik2 * rik
rik4 = rik2 * rik2
rik5 = rik2 * rik3
taper = c5*rik5 + c4*rik4 + c3*rik3
& + c2*rik2 + c1*rik + c0
dtaper = 5.0d0*c5*rik4 + 4.0d0*c4*rik3
& + 3.0d0*c3*rik2 + 2.0d0*c2*rik + c1
de = e*dtaper + de*taper
e = e * taper
end if
c
c scale the interaction based on its group membership
c
if (use_group) then
e = e * fgrp
de = de * fgrp
if (use_hb) then
deddt = deddt * fgrp
deddr = deddr * fgrp
end if
end if
c
c find the chain rule terms for derivative components
c
de = de / rik
dedx = de * xr
dedy = de * yr
dedz = de * zr
c
c increment the total van der Waals energy and derivatives
c
ev = ev + e
if (i .eq. iv) then
dev(1,i) = dev(1,i) + dedx
dev(2,i) = dev(2,i) + dedy
dev(3,i) = dev(3,i) + dedz
else
dev(1,i) = dev(1,i) + dedx*redi
dev(2,i) = dev(2,i) + dedy*redi
dev(3,i) = dev(3,i) + dedz*redi
dev(1,iv) = dev(1,iv) + dedx*rediv
dev(2,iv) = dev(2,iv) + dedy*rediv
dev(3,iv) = dev(3,iv) + dedz*rediv
end if
if (k .eq. kv) then
dev(1,k) = dev(1,k) - dedx
dev(2,k) = dev(2,k) - dedy
dev(3,k) = dev(3,k) - dedz
else
redk = kred(k)
redkv = 1.0d0 - redk
dev(1,k) = dev(1,k) - dedx*redk
dev(2,k) = dev(2,k) - dedy*redk
dev(3,k) = dev(3,k) - dedz*redk
dev(1,kv) = dev(1,kv) - dedx*redkv
dev(2,kv) = dev(2,kv) - dedy*redkv
dev(3,kv) = dev(3,kv) - dedz*redkv
end if
c
c find the chain rule terms for hydrogen bonding components
c
if (use_hb) then
term = eps * cbuck * p6
deddt = deddt * term
deddr = deddr * term
if (rik2 .gt. cut2) then
deddt = deddt * taper
deddr = deddr * taper
end if
terma = deddt / (rab2*max(rp,1.0d-6))
termc = -deddt / (rcb2*max(rp,1.0d-6))
dedxia = terma * (yab*zp-zab*yp) - deddr*xab
dedyia = terma * (zab*xp-xab*zp) - deddr*yab
dedzia = terma * (xab*yp-yab*xp) - deddr*zab
dedxic = termc * (ycb*zp-zcb*yp)
dedyic = termc * (zcb*xp-xcb*zp)
dedzic = termc * (xcb*yp-ycb*xp)
dedxib = -dedxia - dedxic
dedyib = -dedyia - dedyic
dedzib = -dedzia - dedzic
c
c increment the derivatives for directional hydrogen bonding
c
dev(1,ia) = dev(1,ia) + dedxia
dev(2,ia) = dev(2,ia) + dedyia
dev(3,ia) = dev(3,ia) + dedzia
dev(1,ib) = dev(1,ib) + dedxib
dev(2,ib) = dev(2,ib) + dedyib
dev(3,ib) = dev(3,ib) + dedzib
dev(1,ic) = dev(1,ic) + dedxic
dev(2,ic) = dev(2,ic) + dedyic
dev(3,ic) = dev(3,ic) + dedzic
end if
c
c increment the internal virial tensor components
c
vxx = xr * dedx
vyx = yr * dedx
vzx = zr * dedx
vyy = yr * dedy
vzy = zr * dedy
vzz = zr * dedz
if (use_hb) then
vxx = xab*dedxia + xcb*dedxic
vyx = yab*dedxia + ycb*dedxic
vzx = zab*dedxia + zcb*dedxic
vyy = yab*dedyia + ycb*dedyic
vzy = zab*dedyia + zcb*dedyic
vzz = zab*dedzia + zcb*dedzic
end if
vir(1,1) = vir(1,1) + vxx
vir(2,1) = vir(2,1) + vyx
vir(3,1) = vir(3,1) + vzx
vir(1,2) = vir(1,2) + vyx
vir(2,2) = vir(2,2) + vyy
vir(3,2) = vir(3,2) + vzy
vir(1,3) = vir(1,3) + vzx
vir(2,3) = vir(2,3) + vzy
vir(3,3) = vir(3,3) + vzz
c
c increment the total intermolecular energy
c
if (molcule(i) .ne. molcule(k)) then
einter = einter + e
end if
end if
end if
end do
c
c reset interaction scaling coefficients for connected atoms
c
do j = 1, n12(i)
vscale(i12(j,i)) = 1.0d0
end do
do j = 1, n13(i)
vscale(i13(j,i)) = 1.0d0
end do
do j = 1, n14(i)
vscale(i14(j,i)) = 1.0d0
end do
do j = 1, n15(i)
vscale(i15(j,i)) = 1.0d0
end do
end do
c
c perform deallocation of some local arrays
c
deallocate (iv14)
deallocate (xred)
deallocate (yred)
deallocate (zred)
deallocate (vscale)
return
end |
<!DOCTYPE html PUBLIC "-
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Content-Style-Type" content="text/css">
<title></title>
<meta name="Generator" content="Cocoa HTML Writer">
<meta name="CocoaVersion" content="949.43">
<style type="text/css">
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica}
p.p2 {margin: 0.0px 0.0px 16.0px 0.0px; font: 16.0px Times; min-height: 19.0px}
p.p3 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica; min-height: 14.0px}
p.p4 {margin: 0.0px 0.0px 0.0px 0.0px; font: 9.0px Monaco}
p.p5 {margin: 0.0px 0.0px 0.0px 0.0px; font: 9.0px Monaco; min-height: 12.0px}
p.p6 {margin: 0.0px 0.0px 0.0px 0.0px; font: 9.0px Monaco; color: #2c7014}
span.s1 {font: 18.0px Helvetica}
span.s2 {color: #001bb9}
span.s3 {color: #2c7014}
span.s4 {color: #000000}
span.Apple-tab-span {white-space:pre}
</style>
</head>
<body>
<p class="p1"><span class="s1"><b>Pfset<span class="Apple-tab-span"> </span><span class="Apple-tab-span"> </span><span class="Apple-tab-span"> </span></b></span><b>insert an environment into the event prototype before evaluating the supplied pattern.</b></p>
<p class="p2"><br></p>
<p class="p1"><b>superclass: FuncFilterPattern</b></p>
<p class="p3"><br></p>
<p class="p1">Good for setting default values or loading server objects.</p>
<p class="p3"><br></p>
<p class="p1"><b>Pfset(func, pattern, cleanupFunc)</b></p>
<p class="p3"><br></p>
<p class="p1"><br>
<b>func:</b> Use environment variable syntax (e.g., ~x = 0) to store values in the internal environment. These values are copied into the event prototype before running the supplied pattern.</p>
<p class="p1"><br>
<b>pattern:</b> An event pattern (such as Pbind).</p>
<p class="p1"><br>
<b>cleanupFunc:</b> Optional. A function to evaluate when the pattern is stopped, or when the supplied pattern runs out of values. For example, if you loaded a Buffer in the initializer function, you could free it in the cleanupFunc.</p>
<p class="p3"><br></p>
<p class="p4">(</p>
<p class="p4"><span class="s2">var</span> a, b;</p>
<p class="p4">a = <span class="s2">Pfset</span>({</p>
<p class="p4"><span class="Apple-tab-span"> </span>~legato = 0.3;</p>
<p class="p4"><span class="Apple-tab-span"> </span>~detune = rrand(0, 30);</p>
<p class="p4">}, <span class="s2">Pbind</span>(<span class="s3">\dur</span>, 0.5));</p>
<p class="p4">x = a.asStream;</p>
<p class="p4">9.do({ x.next(<span class="s2">Event</span>.new).postln; });</p>
<p class="p4">)</p>
<p class="p3"><br></p>
<p class="p1">Pfset does not override values placed into the event by the inner pattern:</p>
<p class="p3"><br></p>
<p class="p3"><br></p>
<p class="p4">(</p>
<p class="p4"><span class="s2">var</span> a, b;</p>
<p class="p4">a = <span class="s2">Pfset</span>({</p>
<p class="p4"><span class="Apple-tab-span"> </span>~dur = 0.3;</p>
<p class="p4">}, <span class="s2">Pbind</span>(<span class="s3">\dur</span>, 0.5));</p>
<p class="p4">x = a.asStream;</p>
<p class="p4">9.do({ x.next(<span class="s2">Event</span>.new).postln; });</p>
<p class="p4">)</p>
<p class="p5"><br></p>
<p class="p5"><br></p>
<p class="p1">sound example</p>
<p class="p5"><br></p>
<p class="p4">(</p>
<p class="p6"><span class="s2">SynthDef</span><span class="s4">(</span>\sinegrain<span class="s4">,<span class="<API key>"> </span></span></p>
<p class="p4"><span class="Apple-tab-span"> </span>{ <span class="s2">arg</span> out=0, freq=440, sustain=0.02;</p>
<p class="p4"><span class="Apple-tab-span"> </span><span class="Apple-tab-span"> </span><span class="s2">var</span> env;</p>
<p class="p4"><span class="Apple-tab-span"> </span><span class="Apple-tab-span"> </span>env = <span class="s2">EnvGen</span>.kr(<span class="s2">Env</span>.perc(0.001, sustain), 1, doneAction:2);</p>
<p class="p4"><span class="Apple-tab-span"> </span><span class="Apple-tab-span"> </span><span class="s2">Out</span>.ar(out, <span class="s2">SinOsc</span>.ar(freq, 0, env * 0.1))</p>
<p class="p4"><span class="Apple-tab-span"> </span>}).memStore;</p>
<p class="p4">)</p>
<p class="p5"><br></p>
<p class="p5"><br></p>
<p class="p4">(</p>
<p class="p4">a = <span class="s2">Pbind</span>(<span class="s3">\dur</span>, 0.5, <span class="s3">\instrument</span>, <span class="s3">\sinegrain</span>, <span class="s3">\x</span>, <span class="s2">Pfunc</span> { rrand(500, 600) });</p>
<p class="p4">a = <span class="s2">Pfset</span>({ ~freq = { ~x.postln * 2 }; ~legato = 3; },<span class="<API key>"> </span>a);</p>
<p class="p4">a.play;</p>
<p class="p4">)</p>
<p class="p5"><br></p>
<p class="p5"><br></p>
</body>
</html> |
package huitca1212.alubia13.business;
import android.content.Context;
import huitca1212.alubia13.business.listener.AllBusinessListener;
import huitca1212.alubia13.business.listener.<API key>;
import huitca1212.alubia13.model.album.AlbumWrapper;
import huitca1212.alubia13.service.AlubiaService;
import huitca1212.alubia13.utils.FileUtils;
public class AlbumBusiness {
private static final String ALBUM_FILENAME = "album_alubia.json";
private static boolean dbOperationSuccess = false;
public static void getAlbumContent(Context ctx, AllBusinessListener<AlbumWrapper> listener) {
<API key>(ctx, listener);
}
public static void <API key>(final Context ctx, final AllBusinessListener<AlbumWrapper> listener) {
new DefaultAsyncTask(new <API key>() {
AlbumWrapper albumWrapper;
@Override
public String onBackground() {
String data = FileUtils.readFileToData(ctx, ALBUM_FILENAME);
if (data != null) {
albumWrapper = AlubiaService.<API key>(data, AlbumWrapper.class);
if (albumWrapper != null) {
return DefaultAsyncTask.ASYNC_TASK_OK;
}
}
return DefaultAsyncTask.ASYNC_TASK_ERROR;
}
@Override
public void onFinish(String result) {
if (result.equals(DefaultAsyncTask.ASYNC_TASK_OK)) {
listener.onDatabaseSuccess(albumWrapper);
dbOperationSuccess = true;
}
<API key>(ctx, listener);
}
}).execute();
}
public static void <API key>(final Context ctx, final AllBusinessListener<AlbumWrapper> listener) {
new DefaultAsyncTask(new <API key>() {
String dataString;
AlbumWrapper dataObject;
@Override
public String onBackground() {
String url = "/album_alubia.json";
dataString = AlubiaService.<API key>(url);
if (dataString != null && FileUtils.writeDataToFile(ctx, ALBUM_FILENAME, dataString)) {
dataObject = AlubiaService.<API key>(dataString, AlbumWrapper.class);
if (dataObject != null) {
return DefaultAsyncTask.ASYNC_TASK_OK;
} else {
return DefaultAsyncTask.<API key>;
}
} else {
return DefaultAsyncTask.<API key>;
}
}
@Override
public void onFinish(String result) {
if (result.equals(DefaultAsyncTask.ASYNC_TASK_OK)) {
listener.onServerSuccess(dataObject);
} else {
if (!dbOperationSuccess) {
listener.onFailure(result);
}
}
}
}).execute();
}
} |
<div class="wrap">
<h1><?php _e('Watu PRO Modules', 'watupro')?></h1>
<?php if(!empty($_POST['upload'])):?>
<p><?php _e('If you have just uploaded a module, please reactivate WatuPRO from the Wordpress plugins page.', 'watupro')?></p>
<?php endif;?>
<h2><?php _e("Currently available modules", 'watupro')?></h2>
<ul>
<li><strong><?php _e('Intelligence module -', 'watupro')?></strong> <?php echo watupro_intel()?__("Installed", 'watupro'):__("Not installed", 'watupro')?></li>
<li><strong><?php _e('Reporting module -', 'watupro')?></strong> <?php echo watupro_module('reports')?__("Installed", 'watupro'):__("Not installed", 'watupro')?></li>
</ul>
<p><a href="http://calendarscripts.info/watupro/modules.html" target="_blank"><?php _e('For more info about the additional modules please click here.', 'watupro')?></a></p>
<p><?php printf(__('Check also our <a href="%s" target="_blank">free add-ons and bridges</a>.', 'watupro'), 'http://calendarscripts.info/watupro/bridges.html');?></p>
<?php if(!get_option('<API key>')):?>
<h2><?php _e('Upload new module', 'watupro')?></h2>
<p><?php _e('Please upload only module files purchased from the', 'watupro')?> <a href="http://calendarscripts.info/watupro" target="_blank"><?php _e('official WatuPRO site.', 'watupro')?></a></p>
<form method="post" enctype="multipart/form-data">
<p><label>Module file:</label> <input type="file" name="module"></p>
<input type="submit" value="Upload File">
<input type="hidden" name="upload" value="1">
<?php wp_nonce_field('<API key>');?>
</form>
<?php else:?>
<p><strong><?php _e("Uploading modules is disabled on this blog for security reasons", 'watupro')?></strong></p>
<?php endif;?>
<p><?php _e("If you wish to disable the module upload feature for security reasons, please manually enter '<API key>' in your wp_options table. Although in general you shouldn't give your administrator's login details to any person you don't trust.", 'watupro')?></p>
</div> |
<?php
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
/**
* @package Kaltura
* @subpackage Client
*/
class <API key> extends <API key>
{
public function <API key>()
{
return '<API key>';
}
public function __construct(SimpleXMLElement $xml = null)
{
parent::__construct($xml);
if(is_null($xml))
return;
if(count($xml->csvVersion))
$this->csvVersion = (int)$xml->csvVersion;
if(empty($xml->columns))
$this->columns = array();
else
$this->columns = <API key>::unmarshalItem($xml->columns);
}
/**
* The version of the csv file
*
*
* @var <API key>
* @readonly
*/
public $csvVersion = null;
/**
* Array containing CSV headers
*
*
* @var array of KalturaString
*/
public $columns;
} |
#include "config.h"
#include "system.h"
#include "coretypes.h"
#include "backend.h"
#include "target.h"
#include "rtl.h"
#include "tree.h"
#include "gimple.h"
#include "timevar.h"
#include "cgraph.h"
#include "lto-streamer.h"
#include "print-tree.h"
#include "varasm.h"
#include "langhooks.h"
#include "output.h"
#include "ipa-utils.h"
#include "calls.h"
static const char *ipa_ref_use_name[] = {"read","write","addr","alias","chkp"};
const char * const <API key>[]=
{
"",
"undef",
"prevailing_def",
"<API key>",
"preempted_reg",
"preempted_ir",
"resolved_ir",
"resolved_exec",
"resolved_dyn",
"<API key>"
};
/* Follow the <API key> chain starting at ALIAS
until we find an identifier that is not itself a transparent alias. */
static inline tree
<API key> (tree alias)
{
tree target = alias;
while (<API key> (target))
{
gcc_checking_assert (TREE_CHAIN (target));
target = TREE_CHAIN (target);
}
gcc_checking_assert (! <API key> (target)
&& ! TREE_CHAIN (target));
return target;
}
/* Hash asmnames ignoring the user specified marks. */
hashval_t
symbol_table::<API key> (const_tree asmname)
{
if (IDENTIFIER_POINTER (asmname)[0] == '*')
{
const char *decl_str = IDENTIFIER_POINTER (asmname) + 1;
size_t ulp_len = strlen (user_label_prefix);
if (ulp_len == 0)
;
else if (strncmp (decl_str, user_label_prefix, ulp_len) == 0)
decl_str += ulp_len;
return htab_hash_string (decl_str);
}
return htab_hash_string (IDENTIFIER_POINTER (asmname));
}
/* Return true if assembler names NAME1 and NAME2 leads to the same symbol
name. */
bool
symbol_table::<API key> (const char *name1, const char *name2)
{
if (name1 != name2)
{
if (name1[0] == '*')
{
size_t ulp_len = strlen (user_label_prefix);
name1 ++;
if (ulp_len == 0)
;
else if (strncmp (name1, user_label_prefix, ulp_len) == 0)
name1 += ulp_len;
else
return false;
}
if (name2[0] == '*')
{
size_t ulp_len = strlen (user_label_prefix);
name2 ++;
if (ulp_len == 0)
;
else if (strncmp (name2, user_label_prefix, ulp_len) == 0)
name2 += ulp_len;
else
return false;
}
return !strcmp (name1, name2);
}
return true;
}
/* Compare ASMNAME with the DECL_ASSEMBLER_NAME of DECL. */
bool
symbol_table::<API key> (tree decl, const_tree asmname)
{
tree decl_asmname = DECL_ASSEMBLER_NAME (decl);
const char *decl_str;
const char *asmname_str;
if (decl_asmname == asmname)
return true;
decl_str = IDENTIFIER_POINTER (decl_asmname);
asmname_str = IDENTIFIER_POINTER (asmname);
return <API key> (decl_str, asmname_str);
}
/* Returns nonzero if P1 and P2 are equal. */
/* Insert NODE to assembler name hash. */
void
symbol_table::<API key> (symtab_node *node,
bool with_clones)
{
if (is_a <varpool_node *> (node) && DECL_HARD_REGISTER (node->decl))
return;
gcc_checking_assert (!node-><API key>
&& !node-><API key>);
if (assembler_name_hash)
{
symtab_node **aslot;
cgraph_node *cnode;
tree decl = node->decl;
tree name = DECL_ASSEMBLER_NAME (node->decl);
/* C++ FE can produce decls without associated assembler name and insert
them to symtab to hold section or TLS information. */
if (!name)
return;
hashval_t hash = <API key> (name);
aslot = assembler_name_hash->find_slot_with_hash (name, hash, INSERT);
gcc_assert (*aslot != node);
node-><API key> = (symtab_node *)*aslot;
if (*aslot != NULL)
(*aslot)-><API key> = node;
*aslot = node;
/* Update also possible inline clones sharing a decl. */
cnode = dyn_cast <cgraph_node *> (node);
if (cnode && cnode->clones && with_clones)
for (cnode = cnode->clones; cnode; cnode = cnode->next_sibling_clone)
if (cnode->decl == decl)
<API key> (cnode, true);
}
}
/* Remove NODE from assembler name hash. */
void
symbol_table::<API key> (symtab_node *node,
bool with_clones)
{
if (assembler_name_hash)
{
cgraph_node *cnode;
tree decl = node->decl;
if (node-><API key>)
node-><API key>-><API key>
= node-><API key>;
if (node-><API key>)
{
node-><API key>-><API key>
= node-><API key>;
}
else
{
tree name = DECL_ASSEMBLER_NAME (node->decl);
symtab_node **slot;
if (!name)
return;
hashval_t hash = <API key> (name);
slot = assembler_name_hash->find_slot_with_hash (name, hash,
NO_INSERT);
gcc_assert (*slot == node);
if (!node-><API key>)
assembler_name_hash->clear_slot (slot);
else
*slot = node-><API key>;
}
node-><API key> = NULL;
node-><API key> = NULL;
/* Update also possible inline clones sharing a decl. */
cnode = dyn_cast <cgraph_node *> (node);
if (cnode && cnode->clones && with_clones)
for (cnode = cnode->clones; cnode; cnode = cnode->next_sibling_clone)
if (cnode->decl == decl)
<API key> (cnode, true);
}
}
/* Arrange node to be first in its entry of assembler_name_hash. */
void
symbol_table::<API key> (symtab_node *node)
{
<API key> (node, false);
<API key> (node, false);
}
/* Initalize asm name hash unless. */
void
symbol_table::<API key> (void)
{
symtab_node *node;
if (!assembler_name_hash)
{
assembler_name_hash = hash_table<asmname_hasher>::create_ggc (10);
FOR_EACH_SYMBOL (node)
<API key> (node, false);
}
}
/* Set the DECL_ASSEMBLER_NAME and update symtab hashtables. */
void
symbol_table::<API key> (tree decl, tree name)
{
symtab_node *node = NULL;
/* We can have user ASM names on things, like global register variables, that
are not in the symbol table. */
if ((TREE_CODE (decl) == VAR_DECL
&& (TREE_STATIC (decl) || DECL_EXTERNAL (decl)))
|| TREE_CODE (decl) == FUNCTION_DECL)
node = symtab_node::get (decl);
if (!<API key> (decl))
{
<API key> (decl, name);
if (node)
<API key> (node, true);
}
else
{
if (name == DECL_ASSEMBLER_NAME (decl))
return;
tree alias = (<API key> (DECL_ASSEMBLER_NAME (decl))
? TREE_CHAIN (DECL_ASSEMBLER_NAME (decl))
: NULL);
if (node)
<API key> (node, true);
const char *old_name = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl));
if (<API key> (DECL_ASSEMBLER_NAME (decl))
&& DECL_RTL_SET_P (decl))
warning (0, "%D renamed after being referenced in assembly", decl);
<API key> (decl, name);
if (alias)
{
<API key> (name) = 1;
TREE_CHAIN (name) = alias;
}
/* If we change assembler name, also all transparent aliases must
be updated. There are three kinds - those having same assembler name,
those being renamed in varasm.c and weakref being renamed by the
assembler. */
if (node)
{
<API key> (node, true);
ipa_ref *ref;
for (unsigned i = 0; node-><API key> (i, ref); i++)
{
struct symtab_node *alias = ref->referring;
if (alias->transparent_alias && !alias->weakref
&& symbol_table::<API key>
(old_name, IDENTIFIER_POINTER (
DECL_ASSEMBLER_NAME (alias->decl))))
<API key> (alias->decl, name);
else if (alias->transparent_alias
&& <API key> (alias->decl))
{
gcc_assert (TREE_CHAIN (DECL_ASSEMBLER_NAME (alias->decl))
&& <API key>
(DECL_ASSEMBLER_NAME (alias->decl)));
TREE_CHAIN (DECL_ASSEMBLER_NAME (alias->decl)) =
<API key>
(DECL_ASSEMBLER_NAME (node->decl));
}
#ifdef ASM_OUTPUT_WEAKREF
else gcc_assert (!alias->transparent_alias || alias->weakref);
#else
else gcc_assert (!alias->transparent_alias);
#endif
}
gcc_assert (!node->transparent_alias || !node->definition
|| node->weakref
|| TREE_CHAIN (DECL_ASSEMBLER_NAME (decl))
|| symbol_table::<API key>
(IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl)),
IDENTIFIER_POINTER
(DECL_ASSEMBLER_NAME
(node->get_alias_target ()->decl))));
}
}
}
/* Hash sections by their names. */
hashval_t
section_name_hasher::hash (section_hash_entry *n)
{
return htab_hash_string (n->name);
}
/* Return true if section P1 name equals to P2. */
bool
section_name_hasher::equal (section_hash_entry *n1, const char *name)
{
return n1->name == name || !strcmp (n1->name, name);
}
/* Add node into symbol table. This function is not used directly, but via
cgraph/varpool node creation routines. */
void
symtab_node::register_symbol (void)
{
symtab->register_symbol (this);
if (!decl->decl_with_vis.symtab_node)
decl->decl_with_vis.symtab_node = this;
ref_list.clear ();
/* Be sure to do this last; C++ FE might create new nodes via
DECL_ASSEMBLER_NAME langhook! */
symtab-><API key> (this, false);
}
/* Remove NODE from same comdat group. */
void
symtab_node::<API key> (void)
{
if (same_comdat_group)
{
symtab_node *prev;
for (prev = same_comdat_group;
prev->same_comdat_group != this;
prev = prev->same_comdat_group)
;
if (same_comdat_group == prev)
prev->same_comdat_group = NULL;
else
prev->same_comdat_group = same_comdat_group;
same_comdat_group = NULL;
set_comdat_group (NULL);
}
}
/* Remove node from symbol table. This function is not used directly, but via
cgraph/varpool node removal routines. */
void
symtab_node::unregister (void)
{
<API key> ();
<API key> ();
/* Remove reference to section. */
<API key> (NULL);
<API key> ();
symtab->unregister (this);
/* During LTO symtab merging we temporarily corrupt decl to symtab node
hash. */
gcc_assert (decl->decl_with_vis.symtab_node || in_lto_p);
if (decl->decl_with_vis.symtab_node == this)
{
symtab_node *replacement_node = NULL;
if (cgraph_node *cnode = dyn_cast <cgraph_node *> (this))
replacement_node = cnode->find_replacement ();
decl->decl_with_vis.symtab_node = replacement_node;
}
if (!is_a <varpool_node *> (this) || !DECL_HARD_REGISTER (decl))
symtab-><API key> (this, false);
if (<API key>)
symtab->init_priority_hash->remove (this);
}
/* Remove symbol from symbol table. */
void
symtab_node::remove (void)
{
if (cgraph_node *cnode = dyn_cast <cgraph_node *> (this))
cnode->remove ();
else if (varpool_node *vnode = dyn_cast <varpool_node *> (this))
vnode->remove ();
}
/* Add NEW_ to the same comdat group that OLD is in. */
void
symtab_node::<API key> (symtab_node *old_node)
{
gcc_assert (old_node->get_comdat_group ());
gcc_assert (!same_comdat_group);
gcc_assert (this != old_node);
set_comdat_group (old_node->get_comdat_group ());
same_comdat_group = old_node;
if (!old_node->same_comdat_group)
old_node->same_comdat_group = this;
else
{
symtab_node *n;
for (n = old_node->same_comdat_group;
n->same_comdat_group != old_node;
n = n->same_comdat_group)
;
n->same_comdat_group = this;
}
}
/* Dissolve the same_comdat_group list in which NODE resides. */
void
symtab_node::<API key> (void)
{
symtab_node *n = this;
symtab_node *next;
if (!same_comdat_group)
return;
do
{
next = n->same_comdat_group;
n->same_comdat_group = NULL;
/* Clear comdat_group for comdat locals, since
make_decl_local doesn't. */
if (!TREE_PUBLIC (n->decl))
n->set_comdat_group (NULL);
n = next;
}
while (n != this);
}
/* Return printable assembler name of NODE.
This function is used only for debugging. When assembler name
is unknown go with identifier name. */
const char *
symtab_node::asm_name () const
{
if (!<API key> (decl))
return name ();
return IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl));
}
/* Return printable identifier name. */
const char *
symtab_node::name () const
{
if (!DECL_NAME (decl))
{
if (<API key> (decl))
return asm_name ();
else
return "<unnamed>";
}
return lang_hooks.decl_printable_name (decl, 2);
}
/* Return ipa reference from this symtab_node to
REFERED_NODE or <API key>. USE_TYPE specify type
of the use. */
ipa_ref *
symtab_node::create_reference (symtab_node *referred_node,
enum ipa_ref_use use_type)
{
return create_reference (referred_node, use_type, NULL);
}
/* Return ipa reference from this symtab_node to
REFERED_NODE or <API key>. USE_TYPE specify type
of the use and STMT the statement (if it exists). */
ipa_ref *
symtab_node::create_reference (symtab_node *referred_node,
enum ipa_ref_use use_type, gimple *stmt)
{
ipa_ref *ref = NULL, *ref2 = NULL;
ipa_ref_list *list, *list2;
ipa_ref_t *old_references;
gcc_checking_assert (!stmt || is_a <cgraph_node *> (this));
gcc_checking_assert (use_type != IPA_REF_ALIAS || !stmt);
list = &ref_list;
old_references = vec_safe_address (list->references);
vec_safe_grow (list->references, vec_safe_length (list->references) + 1);
ref = &list->references->last ();
list2 = &referred_node->ref_list;
/* IPA_REF_ALIAS is always inserted at the beginning of the list. */
if(use_type == IPA_REF_ALIAS)
{
list2->referring.safe_insert (0, ref);
ref->referred_index = 0;
for (unsigned int i = 1; i < list2->referring.length (); i++)
list2->referring[i]->referred_index = i;
}
else
{
list2->referring.safe_push (ref);
ref->referred_index = list2->referring.length () - 1;
}
ref->referring = this;
ref->referred = referred_node;
ref->stmt = stmt;
ref->lto_stmt_uid = 0;
ref->use = use_type;
ref->speculative = 0;
/* If vector was moved in memory, update pointers. */
if (old_references != list->references->address ())
{
int i;
for (i = 0; iterate_reference(i, ref2); i++)
ref2->referred_ref_list ()->referring[ref2->referred_index] = ref2;
}
return ref;
}
/* If VAL is a reference to a function or a variable, add a reference from
this symtab_node to the corresponding symbol table node. USE_TYPE specify
type of the use and STMT the statement (if it exists). Return the new
reference or NULL if none was created. */
ipa_ref *
symtab_node::<API key> (tree val, enum ipa_ref_use use_type,
gimple *stmt)
{
STRIP_NOPS (val);
if (TREE_CODE (val) != ADDR_EXPR)
return NULL;
val = get_base_var (val);
if (val && (TREE_CODE (val) == FUNCTION_DECL
|| TREE_CODE (val) == VAR_DECL))
{
symtab_node *referred = symtab_node::get (val);
gcc_checking_assert (referred);
return create_reference (referred, use_type, stmt);
}
return NULL;
}
/* Clone all references from symtab NODE to this symtab_node. */
void
symtab_node::clone_references (symtab_node *node)
{
ipa_ref *ref = NULL, *ref2 = NULL;
int i;
for (i = 0; node->iterate_reference (i, ref); i++)
{
bool speculative = ref->speculative;
unsigned int stmt_uid = ref->lto_stmt_uid;
ref2 = create_reference (ref->referred, ref->use, ref->stmt);
ref2->speculative = speculative;
ref2->lto_stmt_uid = stmt_uid;
}
}
/* Clone all referring from symtab NODE to this symtab_node. */
void
symtab_node::clone_referring (symtab_node *node)
{
ipa_ref *ref = NULL, *ref2 = NULL;
int i;
for (i = 0; node->iterate_referring(i, ref); i++)
{
bool speculative = ref->speculative;
unsigned int stmt_uid = ref->lto_stmt_uid;
ref2 = ref->referring->create_reference (this, ref->use, ref->stmt);
ref2->speculative = speculative;
ref2->lto_stmt_uid = stmt_uid;
}
}
/* Clone reference REF to this symtab_node and set its stmt to STMT. */
ipa_ref *
symtab_node::clone_reference (ipa_ref *ref, gimple *stmt)
{
bool speculative = ref->speculative;
unsigned int stmt_uid = ref->lto_stmt_uid;
ipa_ref *ref2;
ref2 = create_reference (ref->referred, ref->use, stmt);
ref2->speculative = speculative;
ref2->lto_stmt_uid = stmt_uid;
return ref2;
}
/* Find the structure describing a reference to REFERRED_NODE
and associated with statement STMT. */
ipa_ref *
symtab_node::find_reference (symtab_node *referred_node,
gimple *stmt, unsigned int lto_stmt_uid)
{
ipa_ref *r = NULL;
int i;
for (i = 0; iterate_reference (i, r); i++)
if (r->referred == referred_node
&& !r->speculative
&& ((stmt && r->stmt == stmt)
|| (lto_stmt_uid && r->lto_stmt_uid == lto_stmt_uid)
|| (!stmt && !lto_stmt_uid && !r->stmt && !r->lto_stmt_uid)))
return r;
return NULL;
}
/* Remove all references that are associated with statement STMT. */
void
symtab_node::<API key> (gimple *stmt)
{
ipa_ref *r = NULL;
int i = 0;
while (iterate_reference (i, r))
if (r->stmt == stmt)
r->remove_reference ();
else
i++;
}
/* Remove all stmt references in non-speculative references.
Those are not maintained during inlining & clonning.
The exception are speculative references that are updated along
with callgraph edges associated with them. */
void
symtab_node::<API key> (void)
{
ipa_ref *r = NULL;
int i;
for (i = 0; iterate_reference (i, r); i++)
if (!r->speculative)
{
r->stmt = NULL;
r->lto_stmt_uid = 0;
}
}
/* Remove all references in ref list. */
void
symtab_node::<API key> (void)
{
while (vec_safe_length (ref_list.references))
ref_list.references->last ().remove_reference ();
vec_free (ref_list.references);
}
/* Remove all referring items in ref list. */
void
symtab_node::<API key> (void)
{
while (ref_list.referring.length ())
ref_list.referring.last ()->remove_reference ();
ref_list.referring.release ();
}
/* Dump references in ref list to FILE. */
void
symtab_node::dump_references (FILE *file)
{
ipa_ref *ref = NULL;
int i;
for (i = 0; iterate_reference (i, ref); i++)
{
fprintf (file, "%s/%i (%s)",
ref->referred->asm_name (),
ref->referred->order,
ipa_ref_use_name [ref->use]);
if (ref->speculative)
fprintf (file, " (speculative)");
}
fprintf (file, "\n");
}
/* Dump referring in list to FILE. */
void
symtab_node::dump_referring (FILE *file)
{
ipa_ref *ref = NULL;
int i;
for (i = 0; iterate_referring(i, ref); i++)
{
fprintf (file, "%s/%i (%s)",
ref->referring->asm_name (),
ref->referring->order,
ipa_ref_use_name [ref->use]);
if (ref->speculative)
fprintf (file, " (speculative)");
}
fprintf (file, "\n");
}
static const char * const symtab_type_names[] = {"symbol", "function", "variable"};
/* Dump base fields of symtab nodes to F. Not to be used directly. */
void
symtab_node::dump_base (FILE *f)
{
static const char * const visibility_types[] = {
"default", "protected", "hidden", "internal"
};
fprintf (f, "%s/%i (%s)", asm_name (), order, name ());
dump_addr (f, " @", (void *)this);
fprintf (f, "\n Type: %s", symtab_type_names[type]);
if (definition)
fprintf (f, " definition");
if (analyzed)
fprintf (f, " analyzed");
if (alias)
fprintf (f, " alias");
if (transparent_alias)
fprintf (f, " transparent_alias");
if (weakref)
fprintf (f, " weakref");
if (cpp_implicit_alias)
fprintf (f, " cpp_implicit_alias");
if (alias_target)
fprintf (f, " target:%s",
DECL_P (alias_target)
? IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME
(alias_target))
: IDENTIFIER_POINTER (alias_target));
if (body_removed)
fprintf (f, "\n Body removed by <API key>");
fprintf (f, "\n Visibility:");
if (in_other_partition)
fprintf (f, " in_other_partition");
if (<API key>)
fprintf (f, " <API key>");
if (force_output)
fprintf (f, " force_output");
if (forced_by_abi)
fprintf (f, " forced_by_abi");
if (externally_visible)
fprintf (f, " externally_visible");
if (no_reorder)
fprintf (f, " no_reorder");
if (resolution != LDPR_UNKNOWN)
fprintf (f, " %s",
<API key>[(int)resolution]);
if (TREE_ASM_WRITTEN (decl))
fprintf (f, " asm_written");
if (DECL_EXTERNAL (decl))
fprintf (f, " external");
if (TREE_PUBLIC (decl))
fprintf (f, " public");
if (DECL_COMMON (decl))
fprintf (f, " common");
if (DECL_WEAK (decl))
fprintf (f, " weak");
if (DECL_DLLIMPORT_P (decl))
fprintf (f, " dll_import");
if (DECL_COMDAT (decl))
fprintf (f, " comdat");
if (get_comdat_group ())
fprintf (f, " comdat_group:%s",
IDENTIFIER_POINTER (get_comdat_group_id ()));
if (DECL_ONE_ONLY (decl))
fprintf (f, " one_only");
if (get_section ())
fprintf (f, " section:%s",
get_section ());
if (implicit_section)
fprintf (f," (implicit_section)");
if (<API key> (decl))
fprintf (f, " <API key>");
if (DECL_VISIBILITY (decl))
fprintf (f, " visibility:%s",
visibility_types [DECL_VISIBILITY (decl)]);
if (DECL_VIRTUAL_P (decl))
fprintf (f, " virtual");
if (DECL_ARTIFICIAL (decl))
fprintf (f, " artificial");
if (TREE_CODE (decl) == FUNCTION_DECL)
{
if (<API key> (decl))
fprintf (f, " constructor");
if (<API key> (decl))
fprintf (f, " destructor");
}
fprintf (f, "\n");
if (same_comdat_group)
fprintf (f, " Same comdat group as: %s/%i\n",
same_comdat_group->asm_name (),
same_comdat_group->order);
if (<API key>)
fprintf (f, " next sharing asm name: %i\n",
<API key>->order);
if (<API key>)
fprintf (f, " previous sharing asm name: %i\n",
<API key>->order);
if (address_taken)
fprintf (f, " Address is taken.\n");
if (aux)
{
fprintf (f, " Aux:");
dump_addr (f, " @", (void *)aux);
}
fprintf (f, " References: ");
dump_references (f);
fprintf (f, " Referring: ");
dump_referring (f);
if (lto_file_data)
fprintf (f, " Read from file: %s\n",
lto_file_data->file_name);
}
/* Dump symtab node to F. */
void
symtab_node::dump (FILE *f)
{
if (cgraph_node *cnode = dyn_cast <cgraph_node *> (this))
cnode->dump (f);
else if (varpool_node *vnode = dyn_cast <varpool_node *> (this))
vnode->dump (f);
}
/* Dump symbol table to F. */
void
symtab_node::dump_table (FILE *f)
{
symtab_node *node;
fprintf (f, "Symbol table:\n\n");
FOR_EACH_SYMBOL (node)
node->dump (f);
}
/* Return the cgraph node that has ASMNAME for its DECL_ASSEMBLER_NAME.
Return NULL if there's no such node. */
symtab_node *
symtab_node::get_for_asmname (const_tree asmname)
{
symtab_node *node;
symtab-><API key> ();
hashval_t hash = symtab-><API key> (asmname);
symtab_node **slot
= symtab->assembler_name_hash->find_slot_with_hash (asmname, hash,
NO_INSERT);
if (slot)
{
node = *slot;
return node;
}
return NULL;
}
/* Dump symtab node NODE to stderr. */
DEBUG_FUNCTION void
symtab_node::debug (void)
{
dump (stderr);
}
/* Verify common part of symtab nodes. */
DEBUG_FUNCTION bool
symtab_node::verify_base (void)
{
bool error_found = false;
symtab_node *hashed_node;
if (is_a <cgraph_node *> (this))
{
if (TREE_CODE (decl) != FUNCTION_DECL)
{
error ("function symbol is not function");
error_found = true;
}
}
else if (is_a <varpool_node *> (this))
{
if (TREE_CODE (decl) != VAR_DECL)
{
error ("variable symbol is not variable");
error_found = true;
}
}
else
{
error ("node has unknown type");
error_found = true;
}
if (symtab->state != LTO_STREAMING)
{
hashed_node = symtab_node::get (decl);
if (!hashed_node)
{
error ("node not found node->decl->decl_with_vis.symtab_node");
error_found = true;
}
if (hashed_node != this
&& (!is_a <cgraph_node *> (this)
|| !dyn_cast <cgraph_node *> (this)->clone_of
|| dyn_cast <cgraph_node *> (this)->clone_of->decl != decl))
{
error ("node differs from node->decl->decl_with_vis.symtab_node");
error_found = true;
}
}
if (symtab->assembler_name_hash)
{
hashed_node = symtab_node::get_for_asmname (DECL_ASSEMBLER_NAME (decl));
if (hashed_node && hashed_node-><API key>)
{
error ("assembler name hash list corrupted");
error_found = true;
}
while (hashed_node)
{
if (hashed_node == this)
break;
hashed_node = hashed_node-><API key>;
}
if (!hashed_node
&& !(is_a <varpool_node *> (this)
&& DECL_HARD_REGISTER (decl)))
{
error ("node not found in symtab assembler name hash");
error_found = true;
}
}
if (<API key>
&& <API key>-><API key> != this)
{
error ("double linked list of assembler names corrupted");
error_found = true;
}
if (body_removed && definition)
{
error ("node has body_removed but is definition");
error_found = true;
}
if (analyzed && !definition)
{
error ("node is analyzed byt it is not a definition");
error_found = true;
}
if (cpp_implicit_alias && !alias)
{
error ("node is alias but not implicit alias");
error_found = true;
}
if (alias && !definition && !weakref)
{
error ("node is alias but not definition");
error_found = true;
}
if (weakref && !transparent_alias)
{
error ("node is weakref but not an transparent_alias");
error_found = true;
}
if (transparent_alias && !alias)
{
error ("node is transparent_alias but not an alias");
error_found = true;
}
if (same_comdat_group)
{
symtab_node *n = same_comdat_group;
if (!n->get_comdat_group ())
{
error ("node is in same_comdat_group list but has no comdat_group");
error_found = true;
}
if (n->get_comdat_group () != get_comdat_group ())
{
error ("same_comdat_group list across different groups");
error_found = true;
}
if (n->type != type)
{
error ("mixing different types of symbol in same comdat groups is not supported");
error_found = true;
}
if (n == this)
{
error ("node is alone in a comdat group");
error_found = true;
}
do
{
if (!n->same_comdat_group)
{
error ("same_comdat_group is not a circular list");
error_found = true;
break;
}
n = n->same_comdat_group;
}
while (n != this);
if (comdat_local_p ())
{
ipa_ref *ref = NULL;
for (int i = 0; iterate_referring (i, ref); ++i)
{
if (!<API key> (ref->referring))
{
error ("comdat-local symbol referred to by %s outside its "
"comdat",
<API key> (ref->referring->name()));
error_found = true;
}
}
}
}
if (implicit_section && !get_section ())
{
error ("implicit_section flag is set but section isn't");
error_found = true;
}
if (get_section () && get_comdat_group ()
&& !implicit_section
&& !lookup_attribute ("section", DECL_ATTRIBUTES (decl)))
{
error ("Both section and comdat group is set");
error_found = true;
}
/* TODO: Add string table for sections, so we do not keep holding duplicated
strings. */
if (alias && definition
&& get_section () != get_alias_target ()->get_section ()
&& (!get_section()
|| !get_alias_target ()->get_section ()
|| strcmp (get_section(),
get_alias_target ()->get_section ())))
{
error ("Alias and target's section differs");
get_alias_target ()->dump (stderr);
error_found = true;
}
if (alias && definition
&& get_comdat_group () != get_alias_target ()->get_comdat_group ())
{
error ("Alias and target's comdat groups differs");
get_alias_target ()->dump (stderr);
error_found = true;
}
if (transparent_alias && definition && !weakref)
{
symtab_node *to = get_alias_target ();
const char *name1
= IDENTIFIER_POINTER (
<API key> (DECL_ASSEMBLER_NAME (decl)));
const char *name2
= IDENTIFIER_POINTER (
<API key> (DECL_ASSEMBLER_NAME (to->decl)));
if (!symbol_table::<API key> (name1, name2))
{
error ("Transparent alias and target's assembler names differs");
get_alias_target ()->dump (stderr);
error_found = true;
}
}
if (transparent_alias && definition
&& get_alias_target()->transparent_alias && get_alias_target()->analyzed)
{
error ("Chained transparent aliases");
get_alias_target ()->dump (stderr);
error_found = true;
}
return error_found;
}
/* Verify consistency of NODE. */
DEBUG_FUNCTION void
symtab_node::verify (void)
{
if (seen_error ())
return;
timevar_push (TV_CGRAPH_VERIFY);
if (cgraph_node *node = dyn_cast <cgraph_node *> (this))
node->verify_node ();
else
if (verify_base ())
{
debug ();
internal_error ("symtab_node::verify failed");
}
timevar_pop (TV_CGRAPH_VERIFY);
}
/* Verify symbol table for internal consistency. */
DEBUG_FUNCTION void
symtab_node::verify_symtab_nodes (void)
{
symtab_node *node;
hash_map<tree, symtab_node *> comdat_head_map (251);
FOR_EACH_SYMBOL (node)
{
node->verify ();
if (node->get_comdat_group ())
{
symtab_node **entry, *s;
bool existed;
entry = &comdat_head_map.get_or_insert (node->get_comdat_group (),
&existed);
if (!existed)
*entry = node;
else if (!DECL_EXTERNAL (node->decl))
{
for (s = (*entry)->same_comdat_group;
s != NULL && s != node && s != *entry;
s = s->same_comdat_group)
;
if (!s || s == *entry)
{
error ("Two symbols with same comdat_group are not linked by "
"the same_comdat_group list.");
(*entry)->debug ();
node->debug ();
internal_error ("symtab_node::verify failed");
}
}
}
}
}
/* Make DECL local. FIXME: We shouldn't need to mess with rtl this early,
but other code such as <API key> generates rtl. */
void
symtab_node::make_decl_local (void)
{
rtx rtl, symbol;
if (weakref)
{
weakref = false;
<API key> (DECL_ASSEMBLER_NAME (decl)) = 0;
TREE_CHAIN (DECL_ASSEMBLER_NAME (decl)) = NULL_TREE;
symtab-><API key>
(decl, DECL_ASSEMBLER_NAME (get_alias_target ()->decl));
DECL_ATTRIBUTES (decl) = remove_attribute ("weakref",
DECL_ATTRIBUTES (decl));
}
/* Avoid clearing comdat_groups on comdat-local decls. */
else if (TREE_PUBLIC (decl) == 0)
return;
/* Localizing a symbol also make all its transparent aliases local. */
ipa_ref *ref;
for (unsigned i = 0; <API key> (i, ref); i++)
{
struct symtab_node *alias = ref->referring;
if (alias->transparent_alias)
alias->make_decl_local ();
}
if (TREE_CODE (decl) == VAR_DECL)
{
DECL_COMMON (decl) = 0;
/* ADDRESSABLE flag is not defined for public symbols. */
TREE_ADDRESSABLE (decl) = 1;
TREE_STATIC (decl) = 1;
}
else
gcc_assert (TREE_CODE (decl) == FUNCTION_DECL);
DECL_COMDAT (decl) = 0;
DECL_WEAK (decl) = 0;
DECL_EXTERNAL (decl) = 0;
<API key> (decl) = 0;
DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
TREE_PUBLIC (decl) = 0;
DECL_DLLIMPORT_P (decl) = 0;
if (!DECL_RTL_SET_P (decl))
return;
/* Update rtl flags. */
make_decl_rtl (decl);
rtl = DECL_RTL (decl);
if (!MEM_P (rtl))
return;
symbol = XEXP (rtl, 0);
if (GET_CODE (symbol) != SYMBOL_REF)
return;
SYMBOL_REF_WEAK (symbol) = DECL_WEAK (decl);
}
/* Copy visibility from N.
This is useful when THIS becomes a transparent alias of N. */
void
symtab_node::<API key> (symtab_node *n)
{
gcc_checking_assert (n->weakref == weakref);
ipa_ref *ref;
for (unsigned i = 0; <API key> (i, ref); i++)
{
struct symtab_node *alias = ref->referring;
if (alias->transparent_alias)
alias-><API key> (n);
}
if (TREE_CODE (decl) == VAR_DECL)
{
DECL_COMMON (decl) = DECL_COMMON (n->decl);
/* ADDRESSABLE flag is not defined for public symbols. */
if (TREE_PUBLIC (decl) && !TREE_PUBLIC (n->decl))
TREE_ADDRESSABLE (decl) = 1;
TREE_STATIC (decl) = TREE_STATIC (n->decl);
}
else gcc_assert (TREE_CODE (decl) == FUNCTION_DECL);
DECL_COMDAT (decl) = DECL_COMDAT (n->decl);
DECL_WEAK (decl) = DECL_WEAK (n->decl);
DECL_EXTERNAL (decl) = DECL_EXTERNAL (n->decl);
<API key> (decl) = <API key> (n->decl);
DECL_VISIBILITY (decl) = DECL_VISIBILITY (n->decl);
TREE_PUBLIC (decl) = TREE_PUBLIC (n->decl);
DECL_DLLIMPORT_P (decl) = DECL_DLLIMPORT_P (n->decl);
resolution = n->resolution;
set_comdat_group (n->get_comdat_group ());
<API key> (symtab_node::set_section,
const_cast<char *>(n->get_section ()), true);
externally_visible = n->externally_visible;
if (!DECL_RTL_SET_P (decl))
return;
/* Update rtl flags. */
make_decl_rtl (decl);
rtx rtl = DECL_RTL (decl);
if (!MEM_P (rtl))
return;
rtx symbol = XEXP (rtl, 0);
if (GET_CODE (symbol) != SYMBOL_REF)
return;
SYMBOL_REF_WEAK (symbol) = DECL_WEAK (decl);
}
/* Walk the alias chain to return the symbol NODE is alias of.
If NODE is not an alias, return NODE.
Assumes NODE is known to be alias. */
symtab_node *
symtab_node::<API key> (enum availability *availability)
{
bool transparent_p = false;
/* To determine visibility of the target, we follow ELF semantic of aliases.
Here alias is an alternative assembler name of a given definition. Its
availability prevails the availability of its target (i.e. static alias of
weak definition is available.
Transaparent alias is just alternative anme of a given symbol used within
one compilation unit and is translated prior hitting the object file. It
inherits the visibility of its target.
Weakref is a different animal (and noweak definition is weak).
If we ever get into supporting targets with different semantics, a target
hook will be needed here. */
if (availability)
{
transparent_p = transparent_alias;
if (!transparent_p)
*availability = get_availability ();
else
*availability = AVAIL_NOT_AVAILABLE;
}
symtab_node *node = this;
while (node)
{
if (node->alias && node->analyzed)
node = node->get_alias_target ();
else
{
if (!availability || (!transparent_p && node->analyzed))
;
else if (node->analyzed && !node->transparent_alias)
*availability = node->get_availability ();
else
*availability = AVAIL_NOT_AVAILABLE;
return node;
}
if (node && availability && transparent_p
&& node->transparent_alias)
{
*availability = node->get_availability ();
transparent_p = false;
}
}
if (availability)
*availability = AVAIL_NOT_AVAILABLE;
return NULL;
}
/* C++ FE sometimes change linkage flags after producing same body aliases.
FIXME: C++ produce implicit aliases for virtual functions and vtables that
are obviously equivalent. The way it is doing so is however somewhat
kludgy and interferes with the visibility code. As a result we need to
copy the visibility from the target to get things right. */
void
symtab_node::<API key> (symtab_node *target)
{
if (is_a <cgraph_node *> (this))
{
<API key> (decl)
= <API key> (target->decl);
<API key> (decl)
= <API key> (target->decl);
}
/* FIXME: It is not really clear why those flags should not be copied for
functions, too. */
else
{
DECL_WEAK (decl) = DECL_WEAK (target->decl);
DECL_EXTERNAL (decl) = DECL_EXTERNAL (target->decl);
DECL_VISIBILITY (decl) = DECL_VISIBILITY (target->decl);
}
if (TREE_PUBLIC (decl))
{
tree group;
DECL_EXTERNAL (decl) = DECL_EXTERNAL (target->decl);
DECL_COMDAT (decl) = DECL_COMDAT (target->decl);
group = target->get_comdat_group ();
set_comdat_group (group);
if (group && !same_comdat_group)
<API key> (target);
}
externally_visible = target->externally_visible;
}
/* Set section, do not recurse into aliases.
When one wants to change section of a symbol and its aliases,
use set_section. */
void
symtab_node::<API key> (const char *section)
{
const char *current = get_section ();
section_hash_entry **slot;
if (current == section
|| (current && section
&& !strcmp (current, section)))
return;
if (current)
{
x_section->ref_count
if (!x_section->ref_count)
{
hashval_t hash = htab_hash_string (x_section->name);
slot = symtab->section_hash->find_slot_with_hash (x_section->name,
hash, INSERT);
ggc_free (x_section);
symtab->section_hash->clear_slot (slot);
}
x_section = NULL;
}
if (!section)
{
implicit_section = false;
return;
}
if (!symtab->section_hash)
symtab->section_hash = hash_table<section_name_hasher>::create_ggc (10);
slot = symtab->section_hash->find_slot_with_hash (section,
htab_hash_string (section),
INSERT);
if (*slot)
x_section = (section_hash_entry *)*slot;
else
{
int len = strlen (section);
*slot = x_section = ggc_cleared_alloc<section_hash_entry> ();
x_section->name = ggc_vec_alloc<char> (len + 1);
memcpy (x_section->name, section, len + 1);
}
x_section->ref_count++;
}
/* Worker for set_section. */
bool
symtab_node::set_section (symtab_node *n, void *s)
{
n-><API key> ((char *)s);
return false;
}
/* Set section of symbol and its aliases. */
void
symtab_node::set_section (const char *section)
{
gcc_assert (!this->alias);
<API key>
(symtab_node::set_section, const_cast<char *>(section), true);
}
/* Return the initialization priority. */
priority_type
symtab_node::get_init_priority ()
{
if (!this-><API key>)
return <API key>;
symbol_priority_map *h = symtab->init_priority_hash->get (this);
return h ? h->init : <API key>;
}
/* Return the finalization priority. */
priority_type
cgraph_node::get_fini_priority ()
{
if (!this-><API key>)
return <API key>;
symbol_priority_map *h = symtab->init_priority_hash->get (this);
return h ? h->fini : <API key>;
}
/* Return the initialization and finalization priority information for
DECL. If there is no previous priority information, a freshly
allocated structure is returned. */
symbol_priority_map *
symtab_node::priority_info (void)
{
if (!symtab->init_priority_hash)
symtab->init_priority_hash = hash_map<symtab_node *, symbol_priority_map>::create_ggc (13);
bool existed;
symbol_priority_map *h
= &symtab->init_priority_hash->get_or_insert (this, &existed);
if (!existed)
{
h->init = <API key>;
h->fini = <API key>;
<API key> = true;
}
return h;
}
/* Set initialization priority to PRIORITY. */
void
symtab_node::set_init_priority (priority_type priority)
{
symbol_priority_map *h;
if (is_a <cgraph_node *> (this))
gcc_assert (<API key> (this->decl));
if (priority == <API key>)
{
gcc_assert (get_init_priority() == priority);
return;
}
h = priority_info ();
h->init = priority;
}
/* Set fialization priority to PRIORITY. */
void
cgraph_node::set_fini_priority (priority_type priority)
{
symbol_priority_map *h;
gcc_assert (<API key> (this->decl));
if (priority == <API key>)
{
gcc_assert (get_fini_priority() == priority);
return;
}
h = priority_info ();
h->fini = priority;
}
/* Worker for <API key>. */
bool
symtab_node::<API key> (symtab_node *n,
void *data ATTRIBUTE_UNUSED)
{
n->implicit_section = true;
return false;
}
/* Add reference recording that symtab node is alias of TARGET.
The function can fail in the case of aliasing cycles; in this case
it returns false. */
bool
symtab_node::resolve_alias (symtab_node *target, bool transparent)
{
symtab_node *n;
gcc_assert (!analyzed && !vec_safe_length (ref_list.references));
/* Never let cycles to creep into the symbol table alias references;
those will make alias walkers to be infinite. */
for (n = target; n && n->alias;
n = n->analyzed ? n->get_alias_target () : NULL)
if (n == this)
{
if (is_a <cgraph_node *> (this))
error ("function %q+D part of alias cycle", decl);
else if (is_a <varpool_node *> (this))
error ("variable %q+D part of alias cycle", decl);
else
gcc_unreachable ();
alias = false;
return false;
}
/* "analyze" the node - i.e. mark the reference. */
definition = true;
alias = true;
analyzed = true;
transparent |= transparent_alias;
transparent_alias = transparent;
if (transparent)
while (target->transparent_alias && target->analyzed)
target = target->get_alias_target ();
create_reference (target, IPA_REF_ALIAS, NULL);
/* Add alias into the comdat group of its target unless it is already there. */
if (same_comdat_group)
<API key> ();
set_comdat_group (NULL);
if (target->get_comdat_group ())
<API key> (target);
if ((get_section () != target->get_section ()
|| target->get_comdat_group ()) && get_section () && !implicit_section)
{
error ("section of alias %q+D must match section of its target", decl);
}
<API key> (symtab_node::set_section,
const_cast<char *>(target->get_section ()), true);
if (target->implicit_section)
<API key> (<API key>, NULL, true);
/* Alias targets become redundant after alias is resolved into an reference.
We do not want to keep it around or we would have to mind updating them
when renaming symbols. */
alias_target = NULL;
if (!transparent && cpp_implicit_alias && symtab->state >= CONSTRUCTION)
<API key> (target);
/* If alias has address taken, so does the target. */
if (address_taken)
target-><API key> ()->address_taken = true;
/* All non-transparent aliases of THIS are now in fact aliases of TARGET.
If alias is transparent, also all transparent aliases of THIS are now
aliases of TARGET.
Also merge same comdat group lists. */
ipa_ref *ref;
for (unsigned i = 0; <API key> (i, ref);)
{
struct symtab_node *alias_alias = ref->referring;
if (alias_alias->get_comdat_group ())
{
alias_alias-><API key> ();
alias_alias->set_comdat_group (NULL);
if (target->get_comdat_group ())
alias_alias-><API key> (target);
}
if (!alias_alias->transparent_alias || transparent)
{
alias_alias-><API key> ();
alias_alias->create_reference (target, IPA_REF_ALIAS, NULL);
}
else i++;
}
return true;
}
/* Worker searching noninterposable alias. */
bool
symtab_node::<API key> (symtab_node *node, void *data)
{
if (!node->transparent_alias && <API key> (node->decl))
{
symtab_node *fn = node-><API key> ();
/* Ensure that the alias is well formed this may not be the case
of user defined aliases and currently it is not always the case
of C++ same body aliases (that is a bug). */
if (TREE_TYPE (node->decl) != TREE_TYPE (fn->decl)
|| DECL_CONTEXT (node->decl) != DECL_CONTEXT (fn->decl)
|| (TREE_CODE (node->decl) == FUNCTION_DECL
&& <API key> (node->decl)
!= <API key> (fn->decl))
|| DECL_ATTRIBUTES (node->decl) != DECL_ATTRIBUTES (fn->decl))
return false;
*(symtab_node **)data = node;
return true;
}
return false;
}
/* If node can not be overwriten by static or dynamic linker to point to
different definition, return NODE. Otherwise look for alias with such
property and if none exists, introduce new one. */
symtab_node *
symtab_node::<API key> (void)
{
tree new_decl;
symtab_node *new_node = NULL;
/* First try to look up existing alias or base object
(if that is already non-overwritable). */
symtab_node *node = <API key> ();
gcc_assert (!node->alias && !node->weakref);
node-><API key> (symtab_node::<API key>,
(void *)&new_node, true);
if (new_node)
return new_node;
#ifndef ASM_OUTPUT_DEF
/* If aliases aren't supported by the assembler, fail. */
return NULL;
#endif
/* Otherwise create a new one. */
new_decl = copy_node (node->decl);
DECL_DLLIMPORT_P (new_decl) = 0;
DECL_NAME (new_decl) = clone_function_name (node->decl, "localalias");
if (TREE_CODE (new_decl) == FUNCTION_DECL)
<API key> (new_decl) = NULL;
DECL_INITIAL (new_decl) = NULL;
<API key> (new_decl, DECL_NAME (new_decl));
SET_DECL_RTL (new_decl, NULL);
/* Update the properties. */
DECL_EXTERNAL (new_decl) = 0;
TREE_PUBLIC (new_decl) = 0;
DECL_COMDAT (new_decl) = 0;
DECL_WEAK (new_decl) = 0;
/* Since the aliases can be added to vtables, keep DECL_VIRTUAL flag. */
DECL_VIRTUAL_P (new_decl) = DECL_VIRTUAL_P (node->decl);
if (TREE_CODE (new_decl) == FUNCTION_DECL)
{
<API key> (new_decl) = 0;
<API key> (new_decl) = 0;
new_node = cgraph_node::create_alias (new_decl, node->decl);
}
else
{
TREE_READONLY (new_decl) = TREE_READONLY (node->decl);
DECL_INITIAL (new_decl) = error_mark_node;
new_node = varpool_node::create_alias (new_decl, node->decl);
}
new_node->resolve_alias (node);
gcc_assert (<API key> (new_decl)
&& targetm.binds_local_p (new_decl));
return new_node;
}
/* Return true if symtab node and TARGET represents
semantically equivalent symbols. */
bool
symtab_node::<API key> (symtab_node *target)
{
enum availability avail;
symtab_node *ba;
symtab_node *bb;
/* Equivalent functions are equivalent. */
if (decl == target->decl)
return true;
/* If symbol is not overwritable by different implementation,
walk to the base object it defines. */
ba = <API key> (&avail);
if (avail >= AVAIL_AVAILABLE)
{
if (target == ba)
return true;
}
else
ba = this;
bb = target-><API key> (&avail);
if (avail >= AVAIL_AVAILABLE)
{
if (this == bb)
return true;
}
else
bb = target;
return bb == ba;
}
/* Classify symbol symtab node for partitioning. */
enum <API key>
symtab_node::<API key> (void)
{
/* Inline clones are always duplicated.
This include external delcarations. */
cgraph_node *cnode = dyn_cast <cgraph_node *> (this);
if (DECL_ABSTRACT_P (decl))
return SYMBOL_EXTERNAL;
if (cnode && cnode->global.inlined_to)
return SYMBOL_DUPLICATE;
/* Transparent aliases are always duplicated. */
if (transparent_alias)
return definition ? SYMBOL_DUPLICATE : SYMBOL_EXTERNAL;
/* External declarations are external. */
if (DECL_EXTERNAL (decl))
return SYMBOL_EXTERNAL;
if (varpool_node *vnode = dyn_cast <varpool_node *> (this))
{
if (alias && definition && !<API key> ()->definition)
return SYMBOL_EXTERNAL;
/* Constant pool references use local symbol names that can not
be promoted global. We should never put into a constant pool
objects that can not be duplicated across partitions. */
if (<API key> (decl))
return SYMBOL_DUPLICATE;
if (DECL_HARD_REGISTER (decl))
return SYMBOL_DUPLICATE;
gcc_checking_assert (vnode->definition);
}
/* Functions that are cloned may stay in callgraph even if they are unused.
Handle them as external; <API key> take care to make
proper things to happen (i.e. to make them appear in the boundary but
with body streamed, so clone can me materialized). */
else if (!dyn_cast <cgraph_node *> (this)->function_symbol ()->definition)
return SYMBOL_EXTERNAL;
/* Linker discardable symbols are duplicated to every use unless they are
keyed. */
if (DECL_ONE_ONLY (decl)
&& !force_output
&& !forced_by_abi
&& !<API key> ())
return SYMBOL_DUPLICATE;
return SYMBOL_PARTITION;
}
/* Return true when symbol is known to be non-zero. */
bool
symtab_node::nonzero_address ()
{
/* Weakrefs may be NULL when their target is not defined. */
if (alias && weakref)
{
if (analyzed)
{
symtab_node *target = <API key> ();
if (target->alias && target->weakref)
return false;
/* We can not recurse to target::nonzero. It is possible that the
target is used only via the alias.
We may walk references and look for strong use, but we do not know
if this strong use will survive to final binary, so be
conservative here.
??? Maybe we could do the lookup during late optimization that
could be useful to eliminate the NULL pointer checks in LTO
programs. */
if (target->definition && !DECL_EXTERNAL (target->decl))
return true;
if (target->resolution != LDPR_UNKNOWN
&& target->resolution != LDPR_UNDEF
&& !target->can_be_discarded_p ()
&& <API key>)
return true;
return false;
}
else
return false;
}
/* With !<API key> we assume that symbols may
bind to NULL. This is on by default on embedded targets only.
Otherwise all non-WEAK symbols must be defined and thus non-NULL or
linking fails. Important case of WEAK we want to do well are comdats.
Those are handled by later check for definition.
When parsing, beware the cases when WEAK attribute is added later. */
if (!DECL_WEAK (decl)
&& <API key>)
{
<API key> = true;
return true;
}
/* If target is defined and not extern, we know it will be output and thus
it will bind to non-NULL.
Play safe for <API key> where weak definition maye
be re-defined by NULL. */
if (definition && !DECL_EXTERNAL (decl)
&& (<API key> || !DECL_WEAK (decl)))
{
if (!DECL_WEAK (decl))
<API key> = true;
return true;
}
/* As the last resort, check the resolution info. */
if (resolution != LDPR_UNKNOWN
&& resolution != LDPR_UNDEF
&& !can_be_discarded_p ()
&& <API key>)
return true;
return false;
}
/* Return 0 if symbol is known to have different address than S2,
Return 1 if symbol is known to have same address as S2,
return -1 otherwise.
If MEMORY_ACCESSED is true, assume that both memory pointer to THIS
and S2 is going to be accessed. This eliminates the situations when
either THIS or S2 is NULL and is seful for comparing bases when deciding
about memory aliasing. */
int
symtab_node::equal_address_to (symtab_node *s2, bool memory_accessed)
{
enum availability avail1, avail2;
/* A Shortcut: equivalent symbols are always equivalent. */
if (this == s2)
return 1;
/* Unwind transparent aliases first; those are always equal to their
target. */
if (this->transparent_alias && this->analyzed)
return this->get_alias_target ()->equal_address_to (s2);
while (s2->transparent_alias && s2->analyzed)
s2 = s2->get_alias_target();
if (this == s2)
return 1;
/* For non-interposable aliases, lookup and compare their actual definitions.
Also check if the symbol needs to bind to given definition. */
symtab_node *rs1 = <API key> (&avail1);
symtab_node *rs2 = s2-><API key> (&avail2);
bool binds_local1 = rs1->analyzed && <API key> (this->decl);
bool binds_local2 = rs2->analyzed && <API key> (s2->decl);
bool really_binds_local1 = binds_local1;
bool really_binds_local2 = binds_local2;
/* Addresses of vtables and virtual functions can not be used by user
code and are used only within speculation. In this case we may make
symbol equivalent to its alias even if interposition may break this
rule. Doing so will allow us to turn speculative inlining into
non-speculative more agressively. */
if (DECL_VIRTUAL_P (this->decl) && avail1 >= AVAIL_AVAILABLE)
binds_local1 = true;
if (DECL_VIRTUAL_P (s2->decl) && avail2 >= AVAIL_AVAILABLE)
binds_local2 = true;
/* If both definitions are available we know that even if they are bound
to other unit they must be defined same way and therefore we can use
equivalence test. */
if (rs1 != rs2 && avail1 >= AVAIL_AVAILABLE && avail2 >= AVAIL_AVAILABLE)
binds_local1 = binds_local2 = true;
if ((binds_local1 ? rs1 : this)
== (binds_local2 ? rs2 : s2))
{
/* We made use of the fact that alias is not weak. */
if (binds_local1 && rs1 != this)
<API key> = true;
if (binds_local2 && rs2 != s2)
s2-><API key> = true;
return 1;
}
/* If both symbols may resolve to NULL, we can not really prove them
different. */
if (!memory_accessed && !nonzero_address () && !s2->nonzero_address ())
return -1;
/* Except for NULL, functions and variables never overlap. */
if (TREE_CODE (decl) != TREE_CODE (s2->decl))
return 0;
/* If one of the symbols is unresolved alias, punt. */
if (rs1->alias || rs2->alias)
return -1;
/* If we have a non-interposale definition of at least one of the symbols
and the other symbol is different, we know other unit can not interpose
it to the first symbol; all aliases of the definition needs to be
present in the current unit. */
if (((really_binds_local1 || really_binds_local2)
/* If we have both definitions and they are different, we know they
will be different even in units they binds to. */
|| (binds_local1 && binds_local2))
&& rs1 != rs2)
{
/* We make use of the fact that one symbol is not alias of the other
and that the definition is non-interposable. */
<API key> = true;
s2-><API key> = true;
rs1-><API key> = true;
rs2-><API key> = true;
return 0;
}
/* TODO: Alias oracle basically assume that addresses of global variables
are different unless they are declared as alias of one to another while
the code folding comparsions doesn't.
We probably should be consistent and use this fact here, too, but for
the moment return false only when we are called from the alias oracle. */
return memory_accessed && rs1 != rs2 ? 0 : -1;
}
/* Worker for <API key>. */
bool
symtab_node::<API key> (bool (*callback) (symtab_node *,
void *),
void *data,
bool <API key>)
{
ipa_ref *ref;
FOR_EACH_ALIAS (this, ref)
{
symtab_node *alias = ref->referring;
if (<API key>
|| alias->get_availability () > AVAIL_INTERPOSABLE)
if (alias-><API key> (callback, data,
<API key>))
return true;
}
return false;
}
/* Return true if address of N is possibly compared. */
static bool
address_matters_1 (symtab_node *n, void *)
{
struct ipa_ref *ref;
if (!n-><API key> ())
return false;
if (n->externally_visible || n->force_output)
return true;
for (unsigned int i = 0; n->iterate_referring (i, ref); i++)
if (ref->address_matters_p ())
return true;
return false;
}
/* Return true if symbol's address may possibly be compared to other
symbol's address. */
bool
symtab_node::address_matters_p ()
{
gcc_assert (!alias);
return <API key> (address_matters_1, NULL, true);
}
/* Return true if symbol's alignment may be increased. */
bool
symtab_node::<API key> (void)
{
symtab_node *target = <API key> ();
/* For now support only variables. */
if (TREE_CODE (decl) != VAR_DECL)
return false;
/* With -<API key> we may have already output the constant. */
if (TREE_ASM_WRITTEN (target->decl))
return false;
/* If target is already placed in an anchor, we can not touch its
alignment. */
if (DECL_RTL_SET_P (target->decl)
&& MEM_P (DECL_RTL (target->decl))
&& <API key> (XEXP (DECL_RTL (target->decl), 0)))
return false;
/* Constant pool entries may be shared. */
if (<API key> (target->decl))
return false;
/* We cannot change alignment of symbols that may bind to symbols
in other translation unit that may contain a definition with lower
alignment. */
if (!<API key> (decl))
return false;
/* When compiling partition, be sure the symbol is not output by other
partition. */
if (flag_ltrans
&& (target->in_other_partition
|| target-><API key> () == SYMBOL_DUPLICATE))
return false;
/* Do not override the alignment as specified by the ABI when the used
attribute is set. */
if (DECL_PRESERVE_P (decl) || DECL_PRESERVE_P (target->decl))
return false;
/* Do not override explicit alignment set by the user when an explicit
section name is also used. This is a common idiom used by many
software projects. */
if (DECL_SECTION_NAME (target->decl) != NULL && !target->implicit_section)
return false;
return true;
}
/* Worker for symtab_node::increase_alignment. */
static bool
<API key> (symtab_node *n, void *v)
{
unsigned int align = (size_t)v;
if (DECL_ALIGN (n->decl) < align
&& n-><API key> ())
{
DECL_ALIGN (n->decl) = align;
DECL_USER_ALIGN (n->decl) = 1;
}
return false;
}
/* Increase alignment of THIS to ALIGN. */
void
symtab_node::increase_alignment (unsigned int align)
{
gcc_assert (<API key> () && align < MAX_OFILE_ALIGNMENT);
<API key>()-><API key> (<API key>,
(void *)(size_t) align,
true);
gcc_assert (DECL_ALIGN (decl) >= align);
}
/* Helper for symtab_node::<API key>. */
static bool
get_alignment_1 (symtab_node *n, void *v)
{
*((unsigned int *)v) = MAX (*((unsigned int *)v), DECL_ALIGN (n->decl));
return false;
}
/* Return desired alignment of the definition. This is NOT alignment useful
to access THIS, because THIS may be interposable and DECL_ALIGN should
be used instead. It however must be guaranteed when output definition
of THIS. */
unsigned int
symtab_node::<API key> ()
{
unsigned int align = 0;
gcc_assert (!alias);
<API key> (get_alignment_1, &align, true);
return align;
}
/* Return symbol used to separate symbol name from suffix. */
char
symbol_table::<API key> ()
{
#ifndef NO_DOT_IN_LABEL
return '.';
#elif !defined NO_DOLLAR_IN_LABEL
return '$';
#else
return '_';
#endif
} |
#include <asm-generic/device.h> |
LIST_HEAD(class_list_head, g_class);
TAILQ_HEAD(g_tailq_head, g_geom);
extern int g_collectstats;
extern int g_debugflags;
/*
* 1 G_T_TOPOLOGY
* 2 G_T_BIO
* 4 G_T_ACCESS
* 8 (unused)
* 16 Allow footshooting on rank#1 providers
* 32 G_T_DETAILS
*/
#define G_F_DISKIOCTL 64
#define G_F_CTLDUMP 128
/*
* We actually have a number of drivers sharing the same major number
* so we coordinate the major/minor usage here
*/
#define GEOM_MAJOR 4
#define GEOM_MINOR_STATS 0
#define <API key> 10
/* geom_dump.c */
void g_confxml(void *, int flag);
void g_conf_specific(struct sbuf *sb, struct g_class *mp, struct g_geom *gp, struct g_provider *pp, struct g_consumer *cp);
void g_confdot(void *, int flag);
void g_conftxt(void *, int flag);
/* geom_event.c */
void g_event_init(void);
void g_run_events(void);
void g_do_wither(void);
/* geom_subr.c */
extern struct class_list_head g_classes;
extern char *g_wait_event, *g_wait_sim, *g_wait_up, *g_wait_down;
int g_wither_washer(void);
/* geom_io.c */
void g_io_init(void);
void g_io_schedule_down(struct thread *tp);
void g_io_schedule_up(struct thread *tp);
/* geom_kern.c / geom_kernsim.c */
void g_init(void);
extern int g_shutdown;
/* geom_ctl.c */
void g_ctl_init(void); |
#include <l4/scout-gfx/grid_layout>
#include <l4/scout-gfx/layout>
#include "layout_internal.h"
#include <vector>
namespace Scout_gfx {
class G_box
{
public:
explicit G_box(Layout_item *i) : _i(i) {}
Area preferred_size() const { return _i->preferred_size(); }
Area max_size() const { return _i->aligned_max_size(); }
Area min_size() const { return _i->min_size(); }
Orientations expanding() const { return _i->expanding(); }
bool empty() const { return _i->empty(); }
bool <API key>() const { return _i-><API key>(); }
int height_for_width(int w) const { return _i->height_for_width(w); }
int <API key>(int w) const { return _i-><API key>(w); }
Mag_gfx::Alignment alignment() const { return _i->alignment(); }
void set_alignment(Mag_gfx::Alignment a) { _i->set_alignment(a); }
void set_geometry(Rect const &g) { _i-><API key>(g); }
Rect geometry() const { return _i->geometry(); }
Layout_item *item() const { return _i; }
int h_stretch() const { return 0; }
int v_stretch() const { return 0; }
private:
friend class G_layout_d;
Layout_item *_i;
int r;
int c;
int tr;
int tc;
};
class G_layout_d
{
public:
int i_spacing;
int o_border;
unsigned top_level : 1;
unsigned enabled : 1;
unsigned activated : 1;
//uint autoNewChild : 1;
//QLayout::SizeConstraint constraint;
Rect rect;
G_layout_d();
void add(G_box *, int r, int c);
void add(G_box *, int r1, int r2, int c1, int c2);
Area preferred_size(int sp) const;
Area min_size(int sp) const;
Area max_size(int sp) const;
Orientations expanding(int spacing) const;
void distribute(Rect, int);
int n_rows() const { return _rc; }
int n_cols() const { return _cc; }
void expand(int r, int c)
{ set_size(std::max(r, _rc), std::max(c, _cc)); }
void set_row_stretch(int r, int s)
{
expand(r + 1, 0);
_r_str[r] = s;
invalidate();
}
void set_col_stretch(int c, int s)
{
expand(0, c + 1);
_c_str[c] = s;
invalidate();
}
int row_stretch(int r) const { return _r_str[r]; }
int col_stretch(int c) const { return _c_str[c]; }
void set_row_spacing(int r, int s)
{
expand(r + 1, 0);
_r_sp[r] = s;
invalidate();
}
void set_col_spacing(int c, int s)
{
expand(0, c + 1);
_c_sp[c] = s;
invalidate();
}
int row_spacing(int r) const { return _r_sp[r]; }
int col_spacing(int c) const { return _c_sp[c]; }
void set_rev(bool r, bool c)
{
_h_rev = c;
_v_rev = r;
}
bool horz_reversed() const { return _h_rev; }
bool vert_reversed() const { return _v_rev; }
void invalidate()
{
_need_refresh = true;
_need_distribute = true;
_hfw_w = -1;
}
bool need_refresh() const { return _need_refresh || _need_distribute; }
bool <API key>(int space);
int height_for_width(int, int, int);
int <API key>(int, int, int);
void next_pos(int *r, int *c)
{
*r = _n_r;
*c = _n_c;
}
int size() const { return _t.size(); }
Rect cell_rect(int r, int c) const;
Layout_item *item(int idx) const
{
if (idx < (int)_t.size())
return _t[idx]->item();
else
return 0;
}
Layout_item *remove_item(int idx)
{
if (idx >= (int)_t.size())
return 0;
Items::iterator x = _t.begin() + idx;
G_box *b = *x;
_t.erase(x);
if (!b)
return 0;
Layout_item *i = b->item();
delete b;
i-><API key>(0);
invalidate();
return i;
}
void get_pos(int idx, int *r, int *c, int *rspawn, int *cspawn)
{
if (idx >= (int)_t.size())
return;
G_box *b = _t[idx];
int _tor = b->tr < 0 ? _rc - 1 : b->tr;
int _toc = b->tc < 0 ? _cc - 1 : b->tc;
*r = b->r;
*c = b->c;
*rspawn = _tor - *r + 1;
*cspawn = _toc - *c + 1;
}
void clear();
private:
void set_next_pos_after(int r, int c);
void recalc_hfw(int w, int s);
void add_hfw_data(G_box *b, int w);
void init();
Area find_size(int Layout_info::*, int) const;
void add_data(G_box *, bool r = true, bool c = true);
void set_size(int r, int c);
void setup_layout(int space);
void setup_hfw(int space);
int _rc;
int _cc;
Layout_info::Array _rd;
Layout_info::Array _cd;
Layout_info::Array *_hfwd;
std::vector<int> _r_str;
std::vector<int> _c_str;
std::vector<int> _r_sp;
std::vector<int> _c_sp;
typedef std::vector<G_box*> Items;
Items _t;
int _hfw_w;
int _hfw_h;
int _hfw_min_h;
int _n_r;
int _n_c;
friend class Grid_layout;
unsigned _h_rev : 1;
unsigned _v_rev : 1;
unsigned _need_refresh : 1;
unsigned _need_distribute : 1;
unsigned _has_hfw : 1;
unsigned _add_vert : 1;
};
G_layout_d::G_layout_d()
: i_spacing(-1), o_border(-1), top_level(false),
enabled(true), activated(true),
_rc(0), _cc(0), _hfwd(0), _hfw_w(-1), _n_r(0), _n_c(0),
_h_rev(false), _v_rev(false),
_need_refresh(true), _need_distribute(true)
{}
void
G_layout_d::clear()
{
for (Items::iterator i = _t.begin(); i != _t.end(); ++i)
if (*i)
{
(*i)->item()-><API key>(0);
delete *i;
}
_t.clear();
if (_hfwd)
delete _hfwd;
}
bool
G_layout_d::<API key>(int space)
{
const_cast<G_layout_d*>(this)->setup_layout(space);
return _has_hfw;
}
void
G_layout_d::recalc_hfw(int w, int spacing)
{
if (!_hfwd)
_hfwd = new Layout_info::Array(_rc);
setup_hfw(spacing);
Layout_info::Array &rd = *_hfwd;
int h = 0, mh = 0, n = 0;
for (int r = 0; r < _rc; ++r)
{
h += rd[r].pref_sz;
mh += rd[r].min_sz;
if (!rd[r].empty)
++n;
}
if (n)
{
h += (n - 1) * spacing;
mh += (n - 1) * spacing;
}
_hfw_w = w;
_hfw_h = std::min<int>(Area::Max_h, h);
_hfw_min_h = std::min<int>(Area::Max_h, mh);
}
int
G_layout_d::height_for_width(int w, int margin, int spacing)
{
setup_layout(spacing);
if (!_has_hfw)
return -1;
if (w + 2 * margin != _hfw_w)
{
Layout_info::calc(_cd, 0, _cc, 0, w - 2 * margin, spacing);
recalc_hfw(w - 2* margin, spacing);
}
return _hfw_h + 2 * margin;
}
int
G_layout_d::<API key>(int w, int margin, int spacing)
{
height_for_width(w, margin, spacing);
return _has_hfw ? (_hfw_min_h + 2 * margin) : -1;
}
Area
G_layout_d::find_size(int Layout_info::*size, int spacer) const
{
G_layout_d *self = const_cast<G_layout_d*>(this);
self->setup_layout(spacer);
int w = 0, h = 0, n = 0;
for (int r = 0; r < _rc; ++r)
{
h += _rd[r].*size;
if (!_rd[r].empty)
++n;
}
if (n)
h += (n - 1) * spacer;
n = 0;
for (int c = 0; c < _cc; ++c)
{
w += _cd[c].*size;
if (!_cd[c].empty)
++n;
}
if (n)
w += (n - 1) * spacer;
w = std::min<int>(Area::Max_w, w);
h = std::min<int>(Area::Max_h, h);
return Area(w, h);
}
Orientations
G_layout_d::expanding(int spacing) const
{
G_layout_d *self = const_cast<G_layout_d*>(this);
self->setup_layout(spacing);
Orientations res;
for (int r = 0; r < _rc; ++r)
if (_rd[r].exp)
{
res |= Vert;
break;
}
for (int c = 0; c < _cc; ++c)
if (_cd[c].exp)
{
res |= Horz;
break;
}
return res;
}
Area
G_layout_d::preferred_size(int sp) const
{ return find_size(&Layout_info::pref_sz, sp); }
Area
G_layout_d::min_size(int sp) const
{ return find_size(&Layout_info::min_sz, sp); }
Area
G_layout_d::max_size(int sp) const
{ return find_size(&Layout_info::max_sz, sp); }
void
G_layout_d::set_size(int r, int c)
{
if ((int)_rd.size() < r)
{
int new_r = std::max(r, _rc * 2);
_rd.resize(new_r);
_r_str.resize(new_r);
_r_sp.resize(new_r);
for (int i = _rc; i < new_r; ++i)
{
Layout_info &d = _rd[i];
d.init();
d.max_sz = 0;
d.pos = 0;
d.size = 0;
_r_str[i] = 0;
_r_sp[i] = 0;
}
}
if ((int)_cd.size() < c)
{
int new_c = std::max(c, _cc * 2);
_cd.resize(new_c);
_c_str.resize(new_c);
_c_sp.resize(new_c);
for (int i = _cc; i < new_c; ++i)
{
Layout_info &d = _cd[i];
d.init();
d.max_sz = 0;
d.pos = 0;
d.size = 0;
_c_str[i] = 0;
_c_sp[i] = 0;
}
}
_rc = r;
_cc = c;
}
void
G_layout_d::set_next_pos_after(int r, int c)
{
if (_add_vert)
{
if (c > _n_c || (c == _n_c && r >= _n_r))
{
_n_r = r + 1;
_n_c = c;
if (_n_r >= _rc)
{
_n_r = 0;
++_n_c;
}
}
}
else
{
if (r > _n_r || (r == _n_r && c >= _n_c))
{
_n_r = r;
_n_c = c + 1;
if (_n_c >= _cc)
{
_n_c = 0;
++_n_r;
}
}
}
}
void
G_layout_d::add(G_box *b, int r, int c)
{
expand(r + 1, c + 1);
b->r = b->tr = r;
b->c = b->tc = c;
_t.push_back(b);
invalidate();
set_next_pos_after(r, c);
}
void
G_layout_d::add(G_box *b, int r1, int r2, int c1, int c2)
{
expand(r2 + 1, c2 + 1);
b->r = r1;
b->tr = r2;
b->c = c1;
b->tc = c2;
_t.push_back(b);
invalidate();
if (c2 < 0)
c2 = _cc - 1;
set_next_pos_after(r2, c2);
}
void
G_layout_d::add_data(G_box *b, bool r, bool c)
{
Area prs = b->preferred_size();
Area mis = b->min_size();
Area mas = b->max_size();
if (b->empty())
return;
if (c)
{
Layout_info &cd = _cd[b->c];
if (!_c_str[b->c])
cd.stretch = std::max(cd.stretch, b->h_stretch());
cd.pref_sz = std::max(prs.w(), cd.pref_sz);
cd.min_sz = std::max(mis.w(), cd.min_sz);
bool ex = cd.exp;
bool em = cd.empty;
max_exp_calc(cd.max_sz, ex, em, mas.w(), b->expanding() & Horz, b->empty());
cd.exp = ex;
cd.empty = em;
}
if (r)
{
Layout_info &rd = _rd[b->r];
if (_r_str[b->r])
rd.stretch = std::max(rd.stretch, b->v_stretch());
rd.pref_sz = std::max(prs.h(), rd.pref_sz);
rd.min_sz = std::max(mis.h(), rd.min_sz);
bool ex = rd.exp;
bool em = rd.empty;
max_exp_calc(rd.max_sz, ex, em, mas.h(), b->expanding() & Vert, b->empty());
rd.exp = ex;
rd.empty = em;
}
}
namespace {
static void
dmb(Layout_info::Array &chain, int spacing, int start, int end,
int min_sz, int pref_sz, std::vector<int> &stretcha, int stretch)
{
int i;
int w = 0;
int wh = 0;
int max = 0;
for (i = start; i <= end; ++i)
{
w += chain[i].min_sz;
wh += chain[i].pref_sz;
if (chain[i].empty)
chain[i].max_sz = Area::Max_w;
max += chain[i].max_sz;
chain[i].empty = false;
if (stretcha[i] == 0)
chain[i].stretch = std::max(chain[i].stretch, stretch);
}
w += spacing * (end - start);
wh += spacing * (end - start);
max += spacing * (end - start);
if (max < min_sz)
{ // implies w < minSize
/*
We must increase the maximum size of at least one of the
items. qGeomCalc() will put the extra space in between the
items. We must recover that extra space and put it
somewhere. It does not really matter where, since the user
can always specify stretch factors and avoid this code.
*/
Layout_info::calc(chain, start, end - start + 1, 0, min_sz, spacing);
int pos = 0;
for (i = start; i <= end; ++i)
{
int next_p = (i == end) ? min_sz - 1 : chain[i + 1].pos;
int real_sz = next_p - pos;
if (i != end)
real_sz -= spacing;
if (chain[i].min_sz < real_sz)
chain[i].min_sz = real_sz;
if (chain[i].max_sz < chain[i].min_sz)
chain[i].max_sz = chain[i].min_sz;
pos = next_p;
}
}
else if (w < min_sz)
{
Layout_info::calc(chain, start, end - start + 1, 0, min_sz, spacing);
for (i = start; i <= end; ++i)
if (chain[i].min_sz < chain[i].size)
chain[i].min_sz = chain[i].size;
}
if (wh < pref_sz)
{
Layout_info::calc(chain, start, end - start + 1, 0, pref_sz, spacing);
for (i = start; i <= end; ++i)
if (chain[i].pref_sz < chain[i].size)
chain[i].pref_sz = chain[i].size;
}
}
static void
setup_data(Layout_info::Array &d, int cnt, std::vector<int> const &str,
std::vector<int> const &sp)
{
for (int i = 0; i < cnt; ++i)
{
Layout_info &_d = d[i];
int _st = str[i];
int _sp = sp[i];
_d.init(_st, _sp);
_d.max_sz = _st ? (int)Area::Max_h : _sp;
}
}
static void
set_expansion(Layout_info::Array &d, int cnt)
{
for (int i = 0; i < cnt; ++i)
d[i].exp = d[i].exp || d[i].stretch > 0;
}
}
void
G_layout_d::setup_layout(int spacing)
{
if (!_need_refresh)
return;
_has_hfw = false;
setup_data(_rd, _rc, _r_str, _r_sp);
setup_data(_cd, _cc, _c_str, _c_sp);
for (int pass = 0; pass < 2; ++pass)
{
for (unsigned i = 0; i < _t.size(); ++i)
{
G_box *box = _t[i];
int r1 = box->r;
int c1 = box->c;
int r2 = box->tr;
int c2 = box->tc;
if (r2 < 0)
r2 = _rc - 1;
if (c2 < 0)
c2 = _cc - 1;
Area pref = box->preferred_size();
Area min = box->min_size();
if (box-><API key>())
_has_hfw = true;
if (r1 == r2)
{
if (pass == 0)
add_data(box, true, false);
}
else
{
if (pass == 1)
dmb(_rd, spacing, r1, r2, min.h(), pref.h(),
_r_str, box->v_stretch());
}
if (c1 == c2)
{
if (pass == 0)
add_data(box, false, true);
}
else
{
if (pass == 1)
dmb(_cd, spacing, c1, c2, min.w(), pref.w(),
_c_str, box->h_stretch());
}
}
}
set_expansion(_rd, _rc);
set_expansion(_cd, _cc);
_need_refresh = false;
}
void
G_layout_d::add_hfw_data(G_box *box, int w)
{
Layout_info::Array &rd = *_hfwd;
Layout_info &d = rd[box->r];
if (box-><API key>())
{
int pref = box->height_for_width(w);
d.pref_sz = std::max(pref, d.pref_sz);
d.min_sz = std::max(pref, d.min_sz);
}
else
{
Area pref = box->preferred_size();
Area mis = box->min_size();
d.pref_sz = std::max(pref.h(), d.pref_sz);
d.min_sz = std::max(mis.h(), d.min_sz);
}
}
void
G_layout_d::setup_hfw(int spacing)
{
Layout_info::Array &rd = *_hfwd;
for (int i = 0; i < _rc; ++i)
{
Layout_info &d = rd[i];
d = _rd[i];
d.min_sz = d.pref_sz = _r_sp[i];
}
for (int pass = 0; pass < 2; ++pass)
{
for (unsigned i = 0; i < _t.size(); ++i)
{
G_box *box = _t[i];
int r1 = box->r;
int c1 = box->c;
int r2 = box->tr;
int c2 = box->tc;
if (r2 < 0)
r2 = _rc-1;
if (c2 < 0)
c2 = _cc-1;
int w = _cd[c2].pos + _cd[c2].size - _cd[c1].pos;
if (r1 == r2)
{
if (pass == 0)
add_hfw_data(box, w);
}
else
{
if (pass == 1)
{
Area pref = box->preferred_size();
Area min = box->min_size();
if (box-><API key>())
{
int hfwh = box->height_for_width(w);
if (hfwh > pref.h())
pref.h(hfwh);
if (hfwh > min.h())
min.h(hfwh);
}
dmb(rd, spacing, r1, r2, min.h(), pref.h(),
_r_str, box->v_stretch());
}
}
}
}
set_expansion(rd, _rc);
}
void
G_layout_d::distribute(Rect r, int spacing)
{
bool visual_h_rev = _h_rev;
#if 0
Layout_item *parent = parent_layout_item();
if (parent && parent->is_right_to_left())
visual_h_rev = !visual_h_rev;
#endif
setup_layout(spacing);
Layout_info::calc(_cd, 0, _cc, r.x1(), r.w(), spacing);
Layout_info::Array *rdp;
if (_has_hfw)
{
recalc_hfw(r.w(), spacing);
Layout_info::calc(*_hfwd, 0, _rc, r.y1(), r.h(), spacing);
rdp = _hfwd;
}
else
{
Layout_info::calc(_rd, 0, _rc, r.y1(), r.h(), spacing);
rdp = &_rd;
}
Layout_info::Array &rd = *rdp;
bool reverse = ((r.y2() > rect.y2()) || (r.y2() == rect.y2()
&& ((r.x2() > rect.x2()) != visual_h_rev)));
int n = _t.size();
for (int i = 0; i < n; ++i)
{
G_box *box = _t[reverse ? n-i-1 : i];
int r2 = box->tr;
int c2 = box->tc;
if (r2 < 0)
r2 = _rc-1;
if (c2 < 0)
c2 = _cc-1;
int x = _cd[box->c].pos;
int y = rd[box->r].pos;
int x2p = _cd[c2].pos + _cd[c2].size; // x2+1
int y2p = rd[r2].pos + rd[r2].size; // y2+1
int w = x2p - x;
int h = y2p - y;
if (visual_h_rev)
x = r.x1() + r.x2() - x - w + 1;
if (_v_rev)
y = r.y1() + r.y2() - y - h + 1;
box->set_geometry(Rect(Point(x, y), Area(w, h)));
}
_need_distribute = false;
}
Rect
G_layout_d::cell_rect(int row, int col) const
{
if (row < 0 || row >= _rc || col < 0 || col >= _cc)
return Rect();
Layout_info::Array const *rdp;
if (_has_hfw && _hfwd)
rdp = _hfwd;
else
rdp = &_rd;
return Rect(Point(_cd[col].pos, (*rdp)[row].pos),
Area(_cd[col].size, (*rdp)[row].size));
}
class G_layout_p : public Layout, private G_layout_d
{
public:
G_layout_p() { expand(1,1); }
~G_layout_p();
};
Grid_layout::Grid_layout()
: _d(new G_layout_d())
{
_d->expand(1,1);
}
Grid_layout::~Grid_layout()
{
_d->clear();
delete _d;
}
void
Grid_layout::<API key>(int n, Orientation orient)
{
if (orient == Horizontal)
{
_d->expand(1, n);
_d->_add_vert = false;
}
else
{
_d->expand(n, 1);
_d->_add_vert = true;
}
}
int
Grid_layout::row_count() const { return _d->n_rows(); }
int
Grid_layout::col_count() const { return _d->n_cols(); }
Area
Grid_layout::preferred_size() const
{
int m = margin();
return _d->preferred_size(spacing()) + Area(2 * m, 2 * m);
}
Area
Grid_layout::min_size() const
{
int m = margin();
return _d->min_size(spacing()) + Area(2 * m, 2 * m);
}
Area
Grid_layout::max_size() const
{
int m = margin();
Area s = _d->max_size(spacing()) + Area(2 * m, 2 * m);
s = s.min(Area(Area::Max_w, Area::Max_h));
return s;
}
bool
Grid_layout::<API key>() const
{ return _d-><API key>(spacing()); }
int
Grid_layout::height_for_width(int w) const
{ return _d->height_for_width(w, margin(), spacing()); }
int
Grid_layout::<API key>(int w) const
{ return _d-><API key>(w, margin(), spacing()); }
int
Grid_layout::count() const
{ return _d->size(); }
Layout_item *
Grid_layout::item(int idx) const
{ return _d->item(idx); }
Layout_item *
Grid_layout::remove_item(int idx)
{ return _d->remove_item(idx); }
void
Grid_layout::get_item_pos(int idx, int *row, int *column,
int *row_span, int *column_span)
{ _d->get_pos(idx, row, column, row_span, column_span); }
void
Grid_layout::set_geometry(Rect const &rect)
{
if (!_d->need_refresh() && rect == geometry())
return;
Rect cr = /*alignment() ? aligned_rect(rect) : */ rect;
int m = margin();
Rect s = cr.grow(-m);
_d->distribute(s, spacing());
_geom = rect;
}
Rect
Grid_layout::cell_rect(int r, int c) const
{ return _d->cell_rect(r, c); }
void
Grid_layout::add_item(Layout_item *i)
{
int r, c;
_d->next_pos(&r, &c);
add_item(i, r, c);
}
void
Grid_layout::add_item(Layout_item *i, int r, int c, int rs, int cs, Alignment a)
{
G_box *b = new G_box(i);
b->set_alignment(a);
_d->add(b, r, rs < 0 ? -1 : r + rs - 1, c, (cs < 0) ? - 1 : c + cs - 1);
i-><API key>(this);
invalidate();
}
void
Grid_layout::row_stretch(int r, int s)
{
_d->set_row_stretch(r, s);
invalidate();
}
int
Grid_layout::row_stretch(int r) const
{ return _d->row_stretch(r); }
void
Grid_layout::col_stretch(int c, int s)
{
_d->set_col_stretch(c, s);
invalidate();
}
int
Grid_layout::col_stretch(int c) const
{ return _d->col_stretch(c); }
void
Grid_layout::row_min_height(int r, int m)
{
_d->set_row_spacing(r, m);
invalidate();
}
int
Grid_layout::row_min_height(int r) const
{ return _d->row_spacing(r); }
void
Grid_layout::col_min_width(int c, int m)
{
_d->set_col_spacing(c, m);
invalidate();
}
int
Grid_layout::col_min_width(int c) const
{ return _d->col_spacing(c); }
Orientations
Grid_layout::expanding() const
{ return _d->expanding(spacing()); }
void
Grid_layout::invalidate()
{
_d->invalidate();
Layout::invalidate();
}
bool
Grid_layout::empty() const
{
for (int i = 0; i < count(); ++i)
if (!item(i)->empty())
return false;
return true;
}
} |
<!DOCTYPE html PUBLIC "-
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/js.cookie.js"></script>
<title>BenchmarkTest00883</title>
</head>
<body>
<form action="/benchmark/BenchmarkTest00883" method="POST" id="<API key>">
<div><label>Please enter your details:</label></div>
<br/>
<div><label>Email:</label></div>
<div><input type="text" id="email" name="email"></input></div>
<div><label>Password:</label></div>
<div><input type="text" id="password" name="password" value=""></input></div>
<div> </div>
<div><label>Parameter: vector <BR> Value:</label>
<input type="text" id="vector" name="vector" value="SafeText"></input></div>
<br/>
<div><input type="submit" value="Login" /></div>
</form>
</body>
</html> |
/* RAM driver for SMSC LPC47B272 Super I/O chip. */
#include <arch/io.h>
#include <device/device.h>
#include <device/pnp.h>
#include <superio/conf_mode.h>
#include <console/console.h>
#include <device/smbus.h>
#include <string.h>
#include <pc80/keyboard.h>
#include <stdlib.h>
#include "lpc47b272.h"
/**
* Initialize the specified Super I/O device.
*
* Devices other than COM ports and the keyboard controller are ignored.
* For COM ports, we configure the baud rate.
*
* @param dev Pointer to structure describing a Super I/O device.
*/
static void lpc47b272_init(struct device *dev)
{
if (!dev->enabled)
return;
switch(dev->path.pnp.device) {
case LPC47B272_KBC:
pc_keyboard_init(NO_AUX_DEVICE);
break;
}
}
static struct device_operations ops = {
.read_resources = pnp_read_resources,
.set_resources = pnp_set_resources,
.enable_resources = <API key>,
.enable = pnp_alt_enable,
.init = lpc47b272_init,
.ops_pnp_mode = &pnp_conf_mode_55_aa,
};
static struct pnp_info pnp_dev_info[] = {
{ &ops, LPC47B272_FDC, PNP_IO0 | PNP_IRQ0 | PNP_DRQ0, 0x07f8, },
{ &ops, LPC47B272_PP, PNP_IO0 | PNP_IRQ0 | PNP_DRQ0, 0x07f8, },
{ &ops, LPC47B272_SP1, PNP_IO0 | PNP_IRQ0, 0x07f8, },
{ &ops, LPC47B272_SP2, PNP_IO0 | PNP_IRQ0, 0x07f8, },
{ &ops, LPC47B272_KBC, PNP_IO0 | PNP_IO1 | PNP_IRQ0 | PNP_IRQ1, 0x07ff, 0x07ff, },
{ &ops, LPC47B272_RT, PNP_IO0, 0x0780, },
};
/**
* Create device structures and allocate resources to devices specified in the
* pnp_dev_info array (above).
*
* @param dev Pointer to structure describing a Super I/O device.
*/
static void enable_dev(struct device *dev)
{
pnp_enable_devices(dev, &pnp_ops, ARRAY_SIZE(pnp_dev_info),
pnp_dev_info);
}
struct chip_operations <API key> = {
CHIP_NAME("SMSC LPC47B272 Super I/O")
.enable_dev = enable_dev
}; |
!
! Copyright (C) 2001-2020 Quantum ESPRESSO group
! This file is distributed under the terms of the
! GNU General Public License. See the file `License'
! in the root directory of the present distribution,
! or http:
!
!
!
SUBROUTINE nsg_adj
!
!
! This routine tries to suggest to the code the right atomic orbital to
! localize the charge on.
!
USE kinds, ONLY : DP
USE ions_base, ONLY : nat, ntyp => nsp, ityp
USE ldaU, ONLY : Hubbard_lmax, Hubbard_l, starting_ns, &
nsgnew, neighood, is_hubbard
USE lsda_mod, ONLY : nspin
USE io_global, ONLY : stdout
IMPLICIT NONE
!
INTEGER, PARAMETER :: ldmx = 7
INTEGER :: na, na1, nt, is, m1, m2, i, viz, ldim
REAL(DP) :: lambda(ldmx)
COMPLEX(DP) :: vet(ldmx,ldmx), f(ldmx,ldmx), temp
!
IF (ALL(starting_ns == -1.d0)) RETURN
!
WRITE(stdout,*) "Modify starting ns matrices according to input values"
!
IF (2*Hubbard_lmax+1 > ldmx) CALL errore('ns_adj',' ldmx is too small',ldmx)
!
DO na = 1, nat
!
nt = ityp(na)
!
IF (is_hubbard(nt)) THEN
!
ldim = 2*Hubbard_l(nt) + 1
!
DO is = 1, nspin
!
DO viz = 1, neighood(na)%num_neigh
na1 = neighood(na)%neigh(viz)
IF (na1.EQ.na) THEN
f(:,:) = (0.d0, 0.d0)
DO m1 = 1, ldim
DO m2 = 1, ldim
f(m1,m2) = nsgnew(m2,m1,viz,na,is)
ENDDO
ENDDO
GO TO 7
ENDIF
ENDDO
!
7 CONTINUE
!
CALL cdiagh(ldim, f, ldmx, lambda, vet)
!
DO i = 1, ldim
IF (starting_ns(i,is,nt) >= 0.d0) lambda(i) = starting_ns(i,is,nt)
ENDDO
!
DO m1 = 1,ldim
DO m2 = m1, ldim
temp = 0.d0
DO i = 1,ldim
temp = temp + CONJG(vet(m1,i))*lambda(i)*vet(m2,i)
ENDDO
nsgnew(m2,m1,viz,na,is) = DBLE(temp)
nsgnew(m1,m2,viz,na,is) = nsgnew(m2,m1,viz,na,is)
ENDDO
ENDDO
!
ENDDO
!
ENDIF
!
ENDDO
!
! Uncomment the line below if needed (useful for debugging purposes)
!CALL write_nsg
!
RETURN
!
END SUBROUTINE nsg_adj
! |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.