answer
stringlengths 15
1.25M
|
|---|
#!/bin/bash
set -e
#it is quite difficult to set PATH for jenkins-slave started by launchd on OSX.
export PATH=/usr/local/bin:$PATH
source "$(dirname $0)/ci_configure_flags.sh"
export <API key>=true
env
files=(*.tar.gz)
if [ "1" != "${#files[*]}" ]; then
echo "ERROR: Found more than one file"
exit 1
fi
dist_archive=${files[0]}
version=$(echo $dist_archive | sed 's/capd.*-\(.*\)\.tar\.gz/\1/')
cp ./capdMake/osx/capd.rb.in capd.rb
sed -i.bac "s/<API key>/$(gsha1sum ${dist_archive} | cut -f1 -d' ')/" capd.rb
sed -i.bac "s|src_URL_PLACEHOLDER|file://${PWD}/${dist_archive}|" capd.rb
sed -i.bac "s|VERSION_PLACEHOLDER|${version}|" capd.rb
rm -f /Library/Caches/Homebrew/capd* /Library/Caches/Homebrew/Formula/capd*
brew uninstall --force capd
brew install --build-bottle capd.rb
brew bottle capd.rb
brew uninstall --force capd
rm -f /Library/Caches/Homebrew/capd* /Library/Caches/Homebrew/Formula/capd*
|
#include "mainwidget.h"
#include <QApplication>
#include <QTranslator>
int main( int argc, char ** argv ){
qRegisterMetaType<sc_reader_t>("sc_reader_t");
qRegisterMetaType<sc_card_t>("sc_card_t");
qRegisterMetaType<QTextCursor>("QTextCursor");
qRegisterMetaType<Error>("Error");
qRegisterMetaType<<API key>>("<API key>");
qRegisterMetaType<CardControlHandler::PersonalData>("CardControlHandler::PersonalData");
qRegisterMetaType<CardControlHandler::SerialData>("CardControlHandler::SerialData");
qRegisterMetaType<<API key>::X509CertificateData>("<API key>::X509CertificateData");
QApplication app( argc, argv );
QTranslator translator;
translator.load(QLocale::system(), "buergerkarte", "_");
app.installTranslator(&translator);
bool hideMainWin = false;
if ( argc == 2 && string(argv[1]) == "startHidden" )
hideMainWin = true;
MainWidget mw;
if ( !hideMainWin )
mw.show();
return app.exec();
}
|
#include "includes.h"
#include "../libgpo/gpo_ini.h"
#include "../libgpo/gpo.h"
#include "libgpo/gpo_proto.h"
#include "libgpo/gpext/gpext.h"
#define GP_EXT_NAME "security"
#define GPTTMPL_UNIX_PATH "Microsoft/Windows NT/SecEdit/GptTmpl.inf"
#define <API key> "Unicode"
#define <API key> "Version"
#define <API key> "Registry Values"
#define <API key> "System Access"
#define <API key> "Kerberos Policy"
#define <API key> "Event Audit"
#define <API key> "Privilege Rights"
#define <API key> "Application Log"
#define <API key> "Security Log"
#define <API key> "System Log"
#define <API key> "Group Membership"
#define <API key> "File Security"
#define <API key> "Service General Setting"
NTSTATUS gpext_security_init(TALLOC_CTX *mem_ctx);
static TALLOC_CTX *ctx = NULL;
struct gpttmpl_table {
const char *section;
const char *parameter;
enum winreg_Type type;
};
#define <API key> "Revision"
#define <API key> "signature"
#define <API key> "\"$CHICAGO$\"" /* whatever this is good for... */
#define <API key> "Unicode"
static NTSTATUS <API key>(struct gp_inifile_context *ini_ctx,
uint32_t *version_out)
{
const char *signature = NULL;
NTSTATUS result;
int version;
bool is_unicode = false;
if (!ini_ctx) {
return <API key>;
}
result = <API key>(ini_ctx, <API key>
":"<API key>, &signature);
if (!NT_STATUS_IS_OK(result)) {
return <API key>;
}
if (!strequal(signature, <API key>)) {
return <API key>;
}
result = gp_inifile_getint(ini_ctx, <API key>
":"<API key>, &version);
if (!NT_STATUS_IS_OK(result)) {
return <API key>;
}
if (version_out) {
*version_out = version;
}
result = gp_inifile_getbool(ini_ctx, <API key>
":"<API key>, &is_unicode);
if (!NT_STATUS_IS_OK(result) || !is_unicode) {
return <API key>;
}
return NT_STATUS_OK;
}
static NTSTATUS <API key>(TALLOC_CTX *mem_ctx,
uint32_t flags,
const char *unix_path,
struct gp_inifile_context **ini_ctx)
{
NTSTATUS status;
uint32_t version;
struct gp_inifile_context *tmp_ctx = NULL;
status = <API key>(mem_ctx, flags, unix_path,
GPTTMPL_UNIX_PATH, &tmp_ctx);
<API key>(status);
status = <API key>(tmp_ctx, &version);
if (!NT_STATUS_IS_OK(status)) {
DEBUG(1,("<API key>: failed: %s\n",
nt_errstr(status)));
TALLOC_FREE(tmp_ctx);
return status;
}
*ini_ctx = tmp_ctx;
return NT_STATUS_OK;
}
static NTSTATUS gpttmpl_process(struct gp_inifile_context *ini_ctx,
struct registry_key *root_key,
uint32_t flags)
{
return NT_STATUS_OK;
}
static NTSTATUS <API key>(TALLOC_CTX *mem_ctx,
uint32_t flags,
struct registry_key *root_key,
const struct security_token *token,
const struct GROUP_POLICY_OBJECT *deleted_gpo_list,
const struct GROUP_POLICY_OBJECT *changed_gpo_list)
{
NTSTATUS status = NT_STATUS_OK;
char *unix_path = NULL;
struct gp_inifile_context *ini_ctx = NULL;
const struct GROUP_POLICY_OBJECT *gpo;
char *gpo_cache_path = cache_path(talloc_tos(), GPO_CACHE_DIR);
if (gpo_cache_path == NULL) {
return NT_STATUS_NO_MEMORY;
}
/* for now do not process the list of deleted group policies
for (gpo = deleted_gpo_list; gpo; gpo = gpo->next) {
}
*/
for (gpo = changed_gpo_list; gpo; gpo = gpo->next) {
gpext_debug_header(0, "<API key>", flags,
gpo, <API key>, NULL);
/* this handler processes the gpttmpl files and merge output to the
* registry */
status = gpo_get_unix_path(mem_ctx, gpo_cache_path,
gpo, &unix_path);
if (!NT_STATUS_IS_OK(status)) {
goto out;
}
status = <API key>(mem_ctx, flags, unix_path,
&ini_ctx);
if (!NT_STATUS_IS_OK(status)) {
goto out;
}
status = gpttmpl_process(ini_ctx, root_key, flags);
if (!NT_STATUS_IS_OK(status)) {
goto out;
}
TALLOC_FREE(ini_ctx);
}
out:
if (!NT_STATUS_IS_OK(status)) {
DEBUG(0,("<API key>: %s\n",
nt_errstr(status)));
}
TALLOC_FREE(ini_ctx);
talloc_free(gpo_cache_path);
return status;
}
static NTSTATUS <API key>(TALLOC_CTX *mem_ctx,
struct <API key> **reg_info)
{
NTSTATUS status;
struct <API key> *info = NULL;
struct <API key> table[] = {
/* FIXME: how can we store the "(Default)" value ??? */
/* { "", REG_SZ, "Security" }, */
{ "ProcessGroupPolicy", REG_SZ, "<API key>" },
{ "NoUserPolicy", REG_DWORD, "1" },
{ "ExtensionDebugLevel", REG_DWORD, "1" },
{ NULL, REG_NONE, NULL }
};
info = talloc_zero(mem_ctx, struct <API key>);
<API key>(info);
status = <API key>(mem_ctx, GP_EXT_NAME,
<API key>,
table, info);
<API key>(status);
*reg_info = info;
return NT_STATUS_OK;
}
static NTSTATUS security_initialize(TALLOC_CTX *mem_ctx)
{
return NT_STATUS_OK;
}
static NTSTATUS security_shutdown(void)
{
NTSTATUS status;
status = <API key>(GP_EXT_NAME);
if (NT_STATUS_IS_OK(status)) {
return status;
}
TALLOC_FREE(ctx);
return NT_STATUS_OK;
}
static struct <API key> security_methods = {
.initialize = security_initialize,
.<API key> = <API key>,
.get_reg_config = <API key>,
.shutdown = security_shutdown
};
NTSTATUS gpext_security_init(TALLOC_CTX *mem_ctx)
{
NTSTATUS status;
ctx = talloc_init("gpext_security_init");
<API key>(ctx);
status = <API key>(ctx, <API key>,
GP_EXT_NAME, <API key>,
&security_methods);
if (!NT_STATUS_IS_OK(status)) {
TALLOC_FREE(ctx);
}
return status;
}
|
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_20) on Wed Feb 09 11:31:29 EST 2011 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class net.sf.sketchel.Templates
</TITLE>
<META NAME="date" CONTENT="2011-02-09">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class net.sf.sketchel.Templates";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<A NAME="navbar_top"></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../net/sf/sketchel/Templates.html" title="class in net.sf.sketchel"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?net/sf/sketchel//class-useTemplates.html" target="_top"><B>FRAMES</B></A>
<A HREF="Templates.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>net.sf.sketchel.Templates</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../net/sf/sketchel/Templates.html" title="class in net.sf.sketchel">Templates</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#net.sf.sketchel"><B>net.sf.sketchel</B></A></TD>
<TD> </TD>
</TR>
</TABLE>
<P>
<A NAME="net.sf.sketchel"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../net/sf/sketchel/Templates.html" title="class in net.sf.sketchel">Templates</A> in <A HREF="../../../../net/sf/sketchel/package-summary.html">net.sf.sketchel</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="<API key>">
<TH ALIGN="left" COLSPAN="2">Constructors in <A HREF="../../../../net/sf/sketchel/package-summary.html">net.sf.sketchel</A> with parameters of type <A HREF="../../../../net/sf/sketchel/Templates.html" title="class in net.sf.sketchel">Templates</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../net/sf/sketchel/TemplateSelector.html#TemplateSelector(net.sf.sketchel.Templates, net.sf.sketchel.TemplSelectListener)">TemplateSelector</A></B>(<A HREF="../../../../net/sf/sketchel/Templates.html" title="class in net.sf.sketchel">Templates</A> templ,
<A HREF="../../../../net/sf/sketchel/TemplSelectListener.html" title="interface in net.sf.sketchel">TemplSelectListener</A> listen)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<HR>
<A NAME="navbar_bottom"></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="<API key>"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../net/sf/sketchel/Templates.html" title="class in net.sf.sketchel"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?net/sf/sketchel//class-useTemplates.html" target="_top"><B>FRAMES</B></A>
<A HREF="Templates.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<HR>
</BODY>
</HTML>
|
#ifndef __SUI_USER_LIST_H
#define __SUI_USER_LIST_H
#include <gtk/gtk.h>
#include "sui_user.h"
typedef struct _SuiUserList SuiUserList;
typedef struct _SuiUserListClass SuiUserListClass;
#define SUI_TYPE_USER_LIST (<API key>())
#define SUI_USER_LIST(obj) (<API key>((obj), SUI_TYPE_USER_LIST, SuiUserList))
GType <API key>(void);
SuiUserList *sui_user_list_new(void);
void <API key>(SuiUserList *list, SuiUser *user);
void <API key>(SuiUserList *list, SuiUser *user);
void <API key>(SuiUserList *list, SuiUser *user);
void sui_user_list_clear(SuiUserList *list);
GList* <API key>(SuiUserList *self, const char *prefix);
#endif /* __SUI_USER_LIST_H */
|
#pragma once
#include <glib.h>
#include <glib/gi18n.h>
#include <inttypes.h>
#include "common/metadata.h"
typedef enum <API key>
{
<API key> = 0, // a query with only select and where statement
<API key> = 1 << 0, // if query should include order by statement
<API key> = 1 << 1, // if query should include "limit ?1,?2" part
<API key> = 1 << 2, // if query should include extended where part
<API key> = 1 << 3 // if query should only use extended where part
} <API key>;
#define <API key> (<API key> | <API key>)
typedef enum <API key>
{
<API key> = 0,
<API key> = 1 << 0, // use film_id in filter
<API key> = 1 << 1, // show all stars including and above selected star filter
<API key> = 1 << 2, // show only selected star filter
<API key> = 1 << 3, // show only altered images
<API key> = 1 << 4, // show only unaltered images
<API key> = 1 << 5, // show only rejected images
<API key> = 1 << 6 // use the comparator defined in the comparator field to filter stars
} <API key>;
typedef enum <API key>
{
<API key> = 0,
<API key> = 1,
<API key> = 2,
<API key> = 3,
<API key> = 4,
<API key> = 5,
<API key> = 6,
<API key> = 7,
<API key> = 8
} <API key>;
typedef enum <API key>
{
<API key> = -1,
<API key> = 0,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>
} <API key>;
#define <API key> 0x8000
/* NOTE: any reordeing in this module require a legacy_preset entry in src/libs/collect.c */
typedef enum <API key>
{
<API key> = 0,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key> = <API key> + DT_METADATA_NUMBER,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>, // this one goes here as not used currently in collect.c
<API key>
} <API key>;
typedef enum <API key>
{
<API key> = 0,
<API key> = 1,
<API key> = 2,
<API key> = 3,
<API key> = 4,
<API key> = 5,
<API key> = 6
} <API key>;
typedef enum <API key>
{
<API key> = 0,
<API key> = 1, // a completly different query
<API key> = 2, // base query has been finetuned (filter, ...)
<API key> = 3 // we have just reload the collection after images changes (query is identical)
} <API key>;
typedef struct <API key>
{
/** flags for which query parts to use, see COLLECTION_QUERY_x defines... */
uint32_t query_flags;
/** flags for which filters to use, see COLLECTION_FILTER_x defines... */
uint32_t filter_flags;
/** current film id */
uint32_t film_id;
/** current filter */
uint32_t rating;
<API key> comparator;
/** sorting **/
<API key> sort; // Has to be changed to a dt_collection_sort struct
<API key> sort_second_order;
gint descending;
} <API key>;
typedef struct dt_collection_t
{
int clone;
gchar *query, *query_no_group;
gchar **where_ext;
unsigned int count, count_no_group;
unsigned int tagid;
<API key> params;
<API key> store;
} dt_collection_t;
/* returns the name for the given collection property */
const char *dt_collection_name(<API key> prop);
/** instantiates a collection context, if clone equals NULL default query is constructed. */
const dt_collection_t *dt_collection_new(const dt_collection_t *clone);
/** frees a collection context. */
void dt_collection_free(const dt_collection_t *collection);
/** fetch params for collection for storing. */
const <API key> *<API key>(const dt_collection_t *collection);
/** get the filtered map between sanitized makermodel and exif maker/model **/
void <API key>(const gchar *filter, GList **sanitized, GList **exif);
/** get the sanitized makermodel for exif maker/model **/
gchar *<API key>(const char *exif_maker, const char *exif_model);
/** get the generated query for collection */
const gchar *<API key>(const dt_collection_t *collection);
/** get the generated query for collection including the images hidden in groups */
const gchar *<API key>(const dt_collection_t *collection);
/** updates sql query for a collection. @return 1 if query changed. */
int <API key>(const dt_collection_t *collection);
/** reset collection to default dummy selection */
void dt_collection_reset(const dt_collection_t *collection);
/** gets an extended where part */
gchar *<API key>(const dt_collection_t *collection, int exclude);
/** sets an extended where part */
void <API key>(const dt_collection_t *collection, gchar **extended_where);
/** get filter flags for collection */
uint32_t <API key>(const dt_collection_t *collection);
/** set filter flags for collection */
void <API key>(const dt_collection_t *collection, uint32_t flags);
/** get filter flags for collection */
uint32_t <API key>(const dt_collection_t *collection);
/** set filter flags for collection */
void <API key>(const dt_collection_t *collection, uint32_t flags);
/** set the film_id of collection */
void <API key>(const dt_collection_t *collection, const int32_t film_id);
/** set the tagid of collection */
void <API key>(dt_collection_t *collection, const uint32_t tagid);
/** set the star level for filter */
void <API key>(const dt_collection_t *collection, uint32_t rating);
/** get the star level for filter. The value returned starts on 0 **/
uint32_t <API key>(const dt_collection_t *collection);
/** set the comparator for rating */
void <API key>(const dt_collection_t *collection,
const <API key> comparator);
/** get the comparator for rating */
<API key> <API key>(const dt_collection_t *collection);
/** set the sort fields and flags used to show the collection **/
void <API key>(const dt_collection_t *collection, <API key> sort, gint reverse);
/** get the sort field used **/
<API key> <API key>(const dt_collection_t *collection);
/** get if the collection must be shown in descending order **/
gboolean <API key>(const dt_collection_t *collection);
/** get the part of the query for sorting the collection **/
gchar *<API key>(const dt_collection_t *collection);
/** get the count of query */
uint32_t <API key>(const dt_collection_t *collection);
/** get the count of query including the images hidden in groups */
uint32_t <API key>(const dt_collection_t *collection);
/** get the nth image in the query */
int <API key>(const dt_collection_t *collection, int nth);
/** get all image ids order as current selection. no more than limit many images are returned, <0 ==
* unlimited */
GList *<API key>(const dt_collection_t *collection, int limit);
/** get selected image ids order as current selection. no more than limit many images are returned, <0 ==
* unlimited */
GList *<API key>(const dt_collection_t *collection, int limit);
/** get the count of selected images */
uint32_t <API key>(const dt_collection_t *collection);
/** update query by conf vars */
void <API key>(const dt_collection_t *collection, <API key> query_change,
<API key> changed_property, GList *list);
/** updates the hint message for collection */
void <API key>(const dt_collection_t *collection);
/** returns the image offset in the collection */
int <API key>(int imgid);
/* serialize and deserialize into a string. */
void <API key>(const char *buf);
int <API key>(char *buf, int bufsize);
/* splits an input string into a number part and an optional operator part */
void <API key>(const gchar *input, char **number1, char **number2, char **op);
void <API key>(const gchar *input, char **number1, char **number2, char **op);
void <API key>(const gchar *input, char **number1, char **number2, char **op);
int64_t <API key>(const int32_t image_id, const int32_t tagid);
void <API key>(const unsigned int length, const int64_t image_position,
const int32_t tagid);
/* move images with drag and drop */
void <API key>(const int32_t image_id, GList * selected_images);
/* initialize memory table */
void <API key>();
// modelines: These editor modelines have been set for all relevant files by tools/update_modelines.sh
// vim: shiftwidth=2 expandtab tabstop=2 cindent
// kate: tab-indents: off; indent-width 2; replace-tabs on; indent-mode cstyle; <API key> modified;
|
Copyright 2007-2017 The OpenRA Developers (see AUTHORS)
This file is part of OpenRA, which is free software. It is made
available to you under the terms of the GNU General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version. For more
information, see COPYING.
]]
HarkonnenBase = { HBarracks, HWindTrap1, HWindTrap2, HLightFactory, HOutpost, HConyard, HRefinery, HSilo1, HSilo2, HSilo3, HSilo4 }
<API key> = { CPos.New(2, 58), CPos.New(3, 58), CPos.New(4, 58), CPos.New(5, 58), CPos.New(6, 58), CPos.New(7, 58), CPos.New(8, 58), CPos.New(9, 58), CPos.New(10, 58), CPos.New(11, 58), CPos.New(12, 58), CPos.New(13, 58), CPos.New(14, 58), CPos.New(15, 58), CPos.New(16, 58), CPos.New(16, 59), CPos.New(16, 60) }
<API key> =
{
easy =
{
{ "light_inf", "trike", "trooper" },
{ "light_inf", "trike", "quad" },
{ "light_inf", "light_inf", "trooper", "trike", "trike", "quad" }
},
normal =
{
{ "light_inf", "trike", "trooper" },
{ "light_inf", "trike", "trike" },
{ "light_inf", "light_inf", "trooper", "trike", "trike", "quad" },
{ "light_inf", "light_inf", "trooper", "trooper" },
{ "light_inf", "light_inf", "light_inf", "light_inf" },
{ "light_inf", "trike", "quad", "quad" }
},
hard =
{
{ "trike", "trike", "quad" },
{ "light_inf", "trike", "trike" },
{ "trooper", "trooper", "light_inf", "trike" },
{ "light_inf", "light_inf", "light_inf", "trike", "trike" },
{ "light_inf", "light_inf", "trooper", "trooper" },
{ "trike", "trike", "quad", "quad", "quad", "trike" },
{ "light_inf", "light_inf", "light_inf", "trike", "trike" },
{ "light_inf", "trike", "light_inf", "trooper", "trooper", "quad" },
{ "trike", "trike", "quad", "quad", "quad", "trike" }
}
}
<API key> =
{
easy = DateTime.Minutes(5),
normal = DateTime.Minutes(2) + DateTime.Seconds(40),
hard = DateTime.Minutes(1) + DateTime.Seconds(20)
}
<API key> =
{
easy = 3,
normal = 6,
hard = 9
}
HarkonnenPaths =
{
{ HarkonnenEntry1.Location, HarkonnenRally1.Location },
{ HarkonnenEntry2.Location, HarkonnenRally2.Location },
{ HarkonnenEntry3.Location, HarkonnenRally3.Location }
}
HarkonnenHunters = { "light_inf", "light_inf", "trike", "quad" }
<API key> = { "light_inf", "light_inf", "quad", "quad", "trike", "trike", "trooper", "trooper" }
HarkonnenHunterPath = { HarkonnenEntry5.Location, HarkonnenRally5.Location }
<API key> = { HarkonnenEntry4.Location, HarkonnenRally4.Location }
OrdosReinforcements = { "quad", "raider" }
OrdosPath = { OrdosEntry.Location, OrdosRally.Location }
OrdosBaseBuildings = { "barracks", "light_factory" }
OrdosUpgrades = { "upgrade.barracks", "upgrade.light" }
MessageCheck = function(index)
return #player.GetActorsByType(OrdosBaseBuildings[index]) > 0 and not player.HasPrerequisites({ OrdosUpgrades[index] })
end
Tick = function()
if player.HasNoRequiredUnits() then
harkonnen.<API key>(KillOrdos)
end
if harkonnen.HasNoRequiredUnits() and not player.<API key>(KillHarkonnen) then
Media.DisplayMessage("The Harkonnen have been annihilated!", "Mentat")
player.<API key>(KillHarkonnen)
end
if DateTime.GameTime % DateTime.Seconds(10) == 0 and LastHarvesterEaten[harkonnen] then
local units = harkonnen.GetActorsByType("harvester")
if #units > 0 then
LastHarvesterEaten[harkonnen] = false
ProtectHarvester(units[1], harkonnen, AttackGroupSize[Difficulty])
end
end
if DateTime.GameTime % DateTime.Seconds(32) == 0 and (MessageCheck(1) or MessageCheck(2)) then
Media.DisplayMessage("Upgrade barracks and light factory to produce more advanced units.", "Mentat")
end
end
WorldLoaded = function()
harkonnen = Player.GetPlayer("Harkonnen")
player = Player.GetPlayer("Ordos")
InitObjectives(player)
KillOrdos = harkonnen.AddPrimaryObjective("Kill all Ordos units.")
KillHarkonnen = player.AddPrimaryObjective("Eliminate all Harkonnen units and reinforcements\nin the area.")
Camera.Position = OConyard.CenterPosition
Trigger.OnAllKilled(HarkonnenBase, function()
Utils.Do(harkonnen.GetGroundAttackers(), IdleHunt)
end)
local path = function() return Utils.Random(HarkonnenPaths) end
local waveCondition = function() return player.<API key>(KillHarkonnen) end
<API key>(harkonnen, 0, <API key>[Difficulty], <API key>[Difficulty], path, <API key>[Difficulty], waveCondition)
ActivateAI()
Trigger.AfterDelay(DateTime.Minutes(2) + DateTime.Seconds(30), function()
Reinforcements.<API key>(player, "carryall.reinforce", OrdosReinforcements, OrdosPath, { OrdosPath[1] })
end)
<API key>(player, harkonnen, <API key>, HarkonnenHunters, HarkonnenHunterPath)
end
|
<!DOCTYPE html PUBLIC "-
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta name='ocr-system' content='tesseract'/>
</head>
<body>
<div class='ocr_page' id='page_1' title='image "/tmp/scan.tif"; bbox 0 0 850 1173'>
<div class='ocr_carea' id='block_14_14' title="bbox 113 527 771 711">
<p class='ocr_par' dir='ltr' id='par_15' title="bbox 114 601 770 710">
<span class='ocr_line' id='line_19' title="bbox 114 601 770 617">
<span class='ocr_word' id='word_200' title="bbox 208 607 237 615">
<strong>Pße</strong>
</span>
</span>
</p>
</div>
</div>
</body>
</html>
|
package org.isoron.uhabits.models;
import android.support.annotation.*;
import org.isoron.uhabits.utils.*;
import java.util.*;
/**
* The collection of {@link Streak}s that belong to a habit.
* <p>
* This list is populated automatically from the list of repetitions.
*/
public abstract class StreakList
{
protected final Habit habit;
protected ModelObservable observable;
protected StreakList(Habit habit)
{
this.habit = habit;
observable = new ModelObservable();
}
public abstract List<Streak> getAll();
@NonNull
public List<Streak> getBest(int limit)
{
List<Streak> streaks = getAll();
Collections.sort(streaks, (s1, s2) -> s2.compareLonger(s1));
streaks = streaks.subList(0, Math.min(streaks.size(), limit));
Collections.sort(streaks, (s1, s2) -> s2.compareNewer(s1));
return streaks;
}
@Nullable
public abstract Streak getNewestComputed();
@NonNull
public ModelObservable getObservable()
{
return observable;
}
public abstract void invalidateNewerThan(long timestamp);
public synchronized void rebuild()
{
long today = DateUtils.getStartOfToday();
Long beginning = findBeginning();
if (beginning == null || beginning > today) return;
int checks[] = habit.getCheckmarks().getValues(beginning, today);
List<Streak> streaks = checkmarksToStreaks(beginning, checks);
<API key>();
add(streaks);
}
/**
* Converts a list of checkmark values to a list of streaks.
*
* @param beginning the timestamp corresponding to the first checkmark
* value.
* @param checks the checkmarks values, ordered by decreasing timestamp.
* @return the list of streaks.
*/
@NonNull
protected List<Streak> checkmarksToStreaks(long beginning, int[] checks)
{
ArrayList<Long> transitions = getTransitions(beginning, checks);
List<Streak> streaks = new LinkedList<>();
for (int i = 0; i < transitions.size(); i += 2)
{
long start = transitions.get(i);
long end = transitions.get(i + 1);
streaks.add(new Streak(start, end));
}
return streaks;
}
/**
* Finds the place where we should start when recomputing the streaks.
*
* @return
*/
@Nullable
protected Long findBeginning()
{
Streak newestStreak = getNewestComputed();
if (newestStreak != null) return newestStreak.getStart();
Repetition oldestRep = habit.getRepetitions().getOldest();
if (oldestRep != null) return oldestRep.getTimestamp();
return null;
}
/**
* Returns the timestamps where there was a transition from performing a
* habit to not performing a habit, and vice-versa.
*
* @param beginning the timestamp for the first checkmark
* @param checks the checkmarks, ordered by decresing timestamp
* @return the list of transitions
*/
@NonNull
protected ArrayList<Long> getTransitions(long beginning, int[] checks)
{
long day = DateUtils.<API key>;
long current = beginning;
ArrayList<Long> list = new ArrayList<>();
list.add(current);
for (int i = 1; i < checks.length; i++)
{
current += day;
int j = checks.length - i - 1;
if ((checks[j + 1] == 0 && checks[j] > 0)) list.add(current);
if ((checks[j + 1] > 0 && checks[j] == 0)) list.add(current - day);
}
if (list.size() % 2 == 1) list.add(current);
return list;
}
protected abstract void add(@NonNull List<Streak> streaks);
protected abstract void <API key>();
}
|
#include "qwt_scale_draw.h"
#include "qwt_scale_div.h"
#include "qwt_scale_map.h"
#include "qwt_math.h"
#include "qwt_painter.h"
#include <qpen.h>
#include <qpainter.h>
#include <qmath.h>
#if QT_VERSION < 0x040601
#define qFastSin(x) qSin(x)
#define qFastCos(x) qCos(x)
#endif
class QwtScaleDraw::PrivateData
{
public:
PrivateData():
len( 0 ),
alignment( QwtScaleDraw::BottomScale ),
labelAlignment( 0 ),
labelRotation( 0.0 )
{
}
QPointF pos;
double len;
Alignment alignment;
Qt::Alignment labelAlignment;
double labelRotation;
};
/*!
\brief Constructor
The range of the scale is initialized to [0, 100],
The position is at (0, 0) with a length of 100.
The orientation is <API key>::Bottom.
*/
QwtScaleDraw::QwtScaleDraw()
{
d_data = new QwtScaleDraw::PrivateData;
setLength( 100 );
}
//! Destructor
QwtScaleDraw::~QwtScaleDraw()
{
delete d_data;
}
/*!
Return alignment of the scale
\sa setAlignment()
\return Alignment of the scale
*/
QwtScaleDraw::Alignment QwtScaleDraw::alignment() const
{
return d_data->alignment;
}
/*!
Set the alignment of the scale
\param align Alignment of the scale
The default alignment is QwtScaleDraw::BottomScale
\sa alignment()
*/
void QwtScaleDraw::setAlignment( Alignment align )
{
d_data->alignment = align;
}
/*!
Return the orientation
TopScale, BottomScale are horizontal (Qt::Horizontal) scales,
LeftScale, RightScale are vertical (Qt::Vertical) scales.
\return Orientation of the scale
\sa alignment()
*/
Qt::Orientation QwtScaleDraw::orientation() const
{
switch ( d_data->alignment )
{
case TopScale:
case BottomScale:
return Qt::Horizontal;
case LeftScale:
case RightScale:
default:
return Qt::Vertical;
}
}
/*!
\brief Determine the minimum border distance
This member function returns the minimum space
needed to draw the mark labels at the scale's endpoints.
\param font Font
\param start Start border distance
\param end End border distance
*/
void QwtScaleDraw::getBorderDistHint(
const QFont &font, int &start, int &end ) const
{
start = 0;
end = 1.0;
if ( !hasComponent( <API key>::Labels ) )
return;
const QList<double> &ticks = scaleDiv().ticks( QwtScaleDiv::MajorTick );
if ( ticks.count() == 0 )
return;
// Find the ticks, that are mapped to the borders.
// minTick is the tick, that is mapped to the top/left-most position
// in widget coordinates.
double minTick = ticks[0];
double minPos = scaleMap().transform( minTick );
double maxTick = minTick;
double maxPos = minPos;
for ( int i = 1; i < ticks.count(); i++ )
{
const double tickPos = scaleMap().transform( ticks[i] );
if ( tickPos < minPos )
{
minTick = ticks[i];
minPos = tickPos;
}
if ( tickPos > scaleMap().transform( maxTick ) )
{
maxTick = ticks[i];
maxPos = tickPos;
}
}
double e = 0.0;
double s = 0.0;
if ( orientation() == Qt::Vertical )
{
s = -labelRect( font, minTick ).top();
s -= qAbs( minPos - qRound( scaleMap().p2() ) );
e = labelRect( font, maxTick ).bottom();
e -= qAbs( maxPos - scaleMap().p1() );
}
else
{
s = -labelRect( font, minTick ).left();
s -= qAbs( minPos - scaleMap().p1() );
e = labelRect( font, maxTick ).right();
e -= qAbs( maxPos - scaleMap().p2() );
}
if ( s < 0.0 )
s = 0.0;
if ( e < 0.0 )
e = 0.0;
start = qCeil( s );
end = qCeil( e );
}
/*!
Determine the minimum distance between two labels, that is necessary
that the texts don't overlap.
\param font Font
\return The maximum width of a label
\sa getBorderDistHint()
*/
int QwtScaleDraw::minLabelDist( const QFont &font ) const
{
if ( !hasComponent( <API key>::Labels ) )
return 0;
const QList<double> &ticks = scaleDiv().ticks( QwtScaleDiv::MajorTick );
if ( ticks.isEmpty() )
return 0;
const QFontMetrics fm( font );
const bool vertical = ( orientation() == Qt::Vertical );
QRectF bRect1;
QRectF bRect2 = labelRect( font, ticks[0] );
if ( vertical )
{
bRect2.setRect( -bRect2.bottom(), 0.0, bRect2.height(), bRect2.width() );
}
double maxDist = 0.0;
for ( int i = 1; i < ticks.count(); i++ )
{
bRect1 = bRect2;
bRect2 = labelRect( font, ticks[i] );
if ( vertical )
{
bRect2.setRect( -bRect2.bottom(), 0.0,
bRect2.height(), bRect2.width() );
}
double dist = fm.leading(); // space between the labels
if ( bRect1.right() > 0 )
dist += bRect1.right();
if ( bRect2.left() < 0 )
dist += -bRect2.left();
if ( dist > maxDist )
maxDist = dist;
}
double angle = qwtRadians( labelRotation() );
if ( vertical )
angle += M_PI / 2;
const double sinA = qFastSin( angle ); // qreal -> double
if ( qFuzzyCompare( sinA + 1.0, 1.0 ) )
return qCeil( maxDist );
const int fmHeight = fm.ascent() - 2;
// The distance we need until there is
// the height of the label font. This height is needed
// for the neighbored label.
double labelDist = fmHeight / qFastSin( angle ) * qFastCos( angle );
if ( labelDist < 0 )
labelDist = -labelDist;
// For text orientations close to the scale orientation
if ( labelDist > maxDist )
labelDist = maxDist;
// For text orientations close to the opposite of the
// scale orientation
if ( labelDist < fmHeight )
labelDist = fmHeight;
return qCeil( labelDist );
}
/*!
Calculate the width/height that is needed for a
vertical/horizontal scale.
The extent is calculated from the pen width of the backbone,
the major tick length, the spacing and the maximum width/height
of the labels.
\param font Font used for painting the labels
\return Extent
\sa minLength()
*/
double QwtScaleDraw::extent( const QFont &font ) const
{
double d = 0;
if ( hasComponent( <API key>::Labels ) )
{
if ( orientation() == Qt::Vertical )
d = maxLabelWidth( font );
else
d = maxLabelHeight( font );
if ( d > 0 )
d += spacing();
}
if ( hasComponent( <API key>::Ticks ) )
{
d += maxTickLength();
}
if ( hasComponent( <API key>::Backbone ) )
{
const double pw = qMax( 1, penWidth() ); // pen width can be zero
d += pw;
}
d = qMax( d, minimumExtent() );
return d;
}
/*!
Calculate the minimum length that is needed to draw the scale
\param font Font used for painting the labels
\return Minimum length that is needed to draw the scale
\sa extent()
*/
int QwtScaleDraw::minLength( const QFont &font ) const
{
int startDist, endDist;
getBorderDistHint( font, startDist, endDist );
const QwtScaleDiv &sd = scaleDiv();
const uint minorCount =
sd.ticks( QwtScaleDiv::MinorTick ).count() +
sd.ticks( QwtScaleDiv::MediumTick ).count();
const uint majorCount =
sd.ticks( QwtScaleDiv::MajorTick ).count();
int lengthForLabels = 0;
if ( hasComponent( <API key>::Labels ) )
lengthForLabels = minLabelDist( font ) * majorCount;
int lengthForTicks = 0;
if ( hasComponent( <API key>::Ticks ) )
{
const double pw = qMax( 1, penWidth() ); // penwidth can be zero
lengthForTicks = qCeil( ( majorCount + minorCount ) * ( pw + 1.0 ) );
}
return startDist + endDist + qMax( lengthForLabels, lengthForTicks );
}
/*!
Find the position, where to paint a label
The position has a distance that depends on the length of the ticks
in direction of the alignment().
\param value Value
\return Position, where to paint a label
*/
QPointF QwtScaleDraw::labelPosition( double value ) const
{
const double tval = scaleMap().transform( value );
double dist = spacing();
if ( hasComponent( <API key>::Backbone ) )
dist += qMax( 1, penWidth() );
if ( hasComponent( <API key>::Ticks ) )
dist += tickLength( QwtScaleDiv::MajorTick );
double px = 0;
double py = 0;
switch ( alignment() )
{
case RightScale:
{
px = d_data->pos.x() + dist;
py = tval;
break;
}
case LeftScale:
{
px = d_data->pos.x() - dist;
py = tval;
break;
}
case BottomScale:
{
px = tval;
py = d_data->pos.y() + dist;
break;
}
case TopScale:
{
px = tval;
py = d_data->pos.y() - dist;
break;
}
}
return QPointF( px, py );
}
/*!
Draw a tick
\param painter Painter
\param value Value of the tick
\param len Length of the tick
\sa drawBackbone(), drawLabel()
*/
void QwtScaleDraw::drawTick( QPainter *painter, double value, double len ) const
{
if ( len <= 0 )
return;
const bool roundingAlignment = QwtPainter::roundingAlignment( painter );
QPointF pos = d_data->pos;
double tval = scaleMap().transform( value );
if ( roundingAlignment )
tval = qRound( tval );
const int pw = penWidth();
int a = 0;
if ( pw > 1 && roundingAlignment )
a = 1;
switch ( alignment() )
{
case LeftScale:
{
double x1 = pos.x() + a;
double x2 = pos.x() + a - pw - len;
if ( roundingAlignment )
{
x1 = qRound( x1 );
x2 = qRound( x2 );
}
QwtPainter::drawLine( painter, x1, tval, x2, tval );
break;
}
case RightScale:
{
double x1 = pos.x();
double x2 = pos.x() + pw + len;
if ( roundingAlignment )
{
x1 = qRound( x1 );
x2 = qRound( x2 );
}
QwtPainter::drawLine( painter, x1, tval, x2, tval );
break;
}
case BottomScale:
{
double y1 = pos.y();
double y2 = pos.y() + pw + len;
if ( roundingAlignment )
{
y1 = qRound( y1 );
y2 = qRound( y2 );
}
QwtPainter::drawLine( painter, tval, y1, tval, y2 );
break;
}
case TopScale:
{
double y1 = pos.y() + a;
double y2 = pos.y() - pw - len + a;
if ( roundingAlignment )
{
y1 = qRound( y1 );
y2 = qRound( y2 );
}
QwtPainter::drawLine( painter, tval, y1, tval, y2 );
break;
}
}
}
/*!
Draws the baseline of the scale
\param painter Painter
\sa drawTick(), drawLabel()
*/
void QwtScaleDraw::drawBackbone( QPainter *painter ) const
{
const bool doAlign = QwtPainter::roundingAlignment( painter );
const QPointF &pos = d_data->pos;
const double len = d_data->len;
const int pw = qMax( penWidth(), 1 );
// pos indicates a border not the center of the backbone line
// so we need to shift its position depending on the pen width
// and the alignment of the scale
double off;
if ( doAlign )
{
if ( alignment() == LeftScale || alignment() == TopScale )
off = ( pw - 1 ) / 2;
else
off = pw / 2;
}
else
{
off = 0.5 * penWidth();
}
switch ( alignment() )
{
case LeftScale:
{
double x = pos.x() - off;
if ( doAlign )
x = qRound( x );
QwtPainter::drawLine( painter, x, pos.y(), x, pos.y() + len );
break;
}
case RightScale:
{
double x = pos.x() + off;
if ( doAlign )
x = qRound( x );
QwtPainter::drawLine( painter, x, pos.y(), x, pos.y() + len );
break;
}
case TopScale:
{
double y = pos.y() - off;
if ( doAlign )
y = qRound( y );
QwtPainter::drawLine( painter, pos.x(), y, pos.x() + len, y );
break;
}
case BottomScale:
{
double y = pos.y() + off;
if ( doAlign )
y = qRound( y );
QwtPainter::drawLine( painter, pos.x(), y, pos.x() + len, y );
break;
}
}
}
/*!
\brief Move the position of the scale
The meaning of the parameter pos depends on the alignment:
<dl>
<dt>QwtScaleDraw::LeftScale
<dd>The origin is the topmost point of the
backbone. The backbone is a vertical line.
Scale marks and labels are drawn
at the left of the backbone.
<dt>QwtScaleDraw::RightScale
<dd>The origin is the topmost point of the
backbone. The backbone is a vertical line.
Scale marks and labels are drawn
at the right of the backbone.
<dt>QwtScaleDraw::TopScale
<dd>The origin is the leftmost point of the
backbone. The backbone is a horizontal line.
Scale marks and labels are drawn
above the backbone.
<dt>QwtScaleDraw::BottomScale
<dd>The origin is the leftmost point of the
backbone. The backbone is a horizontal line
Scale marks and labels are drawn
below the backbone.
</dl>
\param pos Origin of the scale
\sa pos(), setLength()
*/
void QwtScaleDraw::move( const QPointF &pos )
{
d_data->pos = pos;
updateMap();
}
/*!
\return Origin of the scale
\sa move(), length()
*/
QPointF QwtScaleDraw::pos() const
{
return d_data->pos;
}
/*!
Set the length of the backbone.
The length doesn't include the space needed for
overlapping labels.
\param length Length of the backbone
\sa move(), minLabelDist()
*/
void QwtScaleDraw::setLength( double length )
{
#if 1
if ( length >= 0 && length < 10 )
length = 10;
// why should we accept negative lengths ???
if ( length < 0 && length > -10 )
length = -10;
#else
length = qMax( length, 10 );
#endif
d_data->len = length;
updateMap();
}
/*!
\return the length of the backbone
\sa setLength(), pos()
*/
double QwtScaleDraw::length() const
{
return d_data->len;
}
/*!
Draws the label for a major scale tick
\param painter Painter
\param value Value
\sa drawTick(), drawBackbone(), boundingLabelRect()
*/
void QwtScaleDraw::drawLabel( QPainter *painter, double value ) const
{
QwtText lbl = tickLabel( painter->font(), value );
if ( lbl.isEmpty() )
return;
QPointF pos = labelPosition( value );
QSizeF labelSize = lbl.textSize( painter->font() );
const QTransform transform = labelTransformation( pos, labelSize );
painter->save();
painter->setWorldTransform( transform, true );
lbl.draw ( painter, QRect( QPoint( 0, 0 ), labelSize.toSize() ) );
painter->restore();
}
/*!
\brief Find the bounding rectangle for the label.
The coordinates of the rectangle are absolute ( calculated from pos() ).
in direction of the tick.
\param font Font used for painting
\param value Value
\return Bounding rectangle
\sa labelRect()
*/
QRect QwtScaleDraw::boundingLabelRect( const QFont &font, double value ) const
{
QwtText lbl = tickLabel( font, value );
if ( lbl.isEmpty() )
return QRect();
const QPointF pos = labelPosition( value );
QSizeF labelSize = lbl.textSize( font );
const QTransform transform = labelTransformation( pos, labelSize );
return transform.mapRect( QRect( QPoint( 0, 0 ), labelSize.toSize() ) );
}
/*!
Calculate the transformation that is needed to paint a label
depending on its alignment and rotation.
\param pos Position where to paint the label
\param size Size of the label
\return Transformation matrix
\sa setLabelAlignment(), setLabelRotation()
*/
QTransform QwtScaleDraw::labelTransformation(
const QPointF &pos, const QSizeF &size ) const
{
QTransform transform;
transform.translate( pos.x(), pos.y() );
transform.rotate( labelRotation() );
int flags = labelAlignment();
if ( flags == 0 )
{
switch ( alignment() )
{
case RightScale:
{
if ( flags == 0 )
flags = Qt::AlignRight | Qt::AlignVCenter;
break;
}
case LeftScale:
{
if ( flags == 0 )
flags = Qt::AlignLeft | Qt::AlignVCenter;
break;
}
case BottomScale:
{
if ( flags == 0 )
flags = Qt::AlignHCenter | Qt::AlignBottom;
break;
}
case TopScale:
{
if ( flags == 0 )
flags = Qt::AlignHCenter | Qt::AlignTop;
break;
}
}
}
double x, y;
if ( flags & Qt::AlignLeft )
x = -size.width();
else if ( flags & Qt::AlignRight )
x = 0.0;
else // Qt::AlignHCenter
x = -( 0.5 * size.width() );
if ( flags & Qt::AlignTop )
y = -size.height();
else if ( flags & Qt::AlignBottom )
y = 0;
else // Qt::AlignVCenter
y = -( 0.5 * size.height() );
transform.translate( x, y );
return transform;
}
/*!
Find the bounding rectangle for the label. The coordinates of
the rectangle are relative to spacing + tick length from the backbone
in direction of the tick.
\param font Font used for painting
\param value Value
\return Bounding rectangle that is needed to draw a label
*/
QRectF QwtScaleDraw::labelRect( const QFont &font, double value ) const
{
QwtText lbl = tickLabel( font, value );
if ( lbl.isEmpty() )
return QRectF( 0.0, 0.0, 0.0, 0.0 );
const QPointF pos = labelPosition( value );
const QSizeF labelSize = lbl.textSize( font );
const QTransform transform = labelTransformation( pos, labelSize );
QRectF br = transform.mapRect( QRectF( QPointF( 0, 0 ), labelSize ) );
br.translate( -pos.x(), -pos.y() );
return br;
}
/*!
Calculate the size that is needed to draw a label
\param font Label font
\param value Value
\return Size that is needed to draw a label
*/
QSizeF QwtScaleDraw::labelSize( const QFont &font, double value ) const
{
return labelRect( font, value ).size();
}
/*!
Rotate all labels.
When changing the rotation, it might be necessary to
adjust the label flags too. Finding a useful combination is
often the result of try and error.
\param rotation Angle in degrees. When changing the label rotation,
the label flags often needs to be adjusted too.
\sa setLabelAlignment(), labelRotation(), labelAlignment().
*/
void QwtScaleDraw::setLabelRotation( double rotation )
{
d_data->labelRotation = rotation;
}
/*!
\return the label rotation
\sa setLabelRotation(), labelAlignment()
*/
double QwtScaleDraw::labelRotation() const
{
return d_data->labelRotation;
}
/*!
\brief Change the label flags
Labels are aligned to the point tick length + spacing away from the backbone.
The alignment is relative to the orientation of the label text.
In case of an flags of 0 the label will be aligned
depending on the orientation of the scale:
QwtScaleDraw::TopScale: Qt::AlignHCenter | Qt::AlignTop\n
QwtScaleDraw::BottomScale: Qt::AlignHCenter | Qt::AlignBottom\n
QwtScaleDraw::LeftScale: Qt::AlignLeft | Qt::AlignVCenter\n
QwtScaleDraw::RightScale: Qt::AlignRight | Qt::AlignVCenter\n
Changing the alignment is often necessary for rotated labels.
\param alignment Or'd Qt::AlignmentFlags see <qnamespace.h>
\sa setLabelRotation(), labelRotation(), labelAlignment()
\warning The various alignments might be confusing.
The alignment of the label is not the alignment
of the scale and is not the alignment of the flags
( QwtText::flags() ) returned from <API key>::label().
*/
void QwtScaleDraw::setLabelAlignment( Qt::Alignment alignment )
{
d_data->labelAlignment = alignment;
}
/*!
\return the label flags
\sa setLabelAlignment(), labelRotation()
*/
Qt::Alignment QwtScaleDraw::labelAlignment() const
{
return d_data->labelAlignment;
}
/*!
\param font Font
\return the maximum width of a label
*/
int QwtScaleDraw::maxLabelWidth( const QFont &font ) const
{
double maxWidth = 0.0;
const QList<double> &ticks = scaleDiv().ticks( QwtScaleDiv::MajorTick );
for ( int i = 0; i < ticks.count(); i++ )
{
const double v = ticks[i];
if ( scaleDiv().contains( v ) )
{
const double w = labelSize( font, ticks[i] ).width();
if ( w > maxWidth )
maxWidth = w;
}
}
return qCeil( maxWidth );
}
/*!
\param font Font
\return the maximum height of a label
*/
int QwtScaleDraw::maxLabelHeight( const QFont &font ) const
{
double maxHeight = 0.0;
const QList<double> &ticks = scaleDiv().ticks( QwtScaleDiv::MajorTick );
for ( int i = 0; i < ticks.count(); i++ )
{
const double v = ticks[i];
if ( scaleDiv().contains( v ) )
{
const double h = labelSize( font, ticks[i] ).height();
if ( h > maxHeight )
maxHeight = h;
}
}
return qCeil( maxHeight );
}
void QwtScaleDraw::updateMap()
{
const QPointF pos = d_data->pos;
double len = d_data->len;
QwtScaleMap &sm = scaleMap();
if ( orientation() == Qt::Vertical )
sm.setPaintInterval( pos.y() + len, pos.y() );
else
sm.setPaintInterval( pos.x(), pos.x() + len );
}
|
import time
from cloudbot import hook
@hook.command(autohelp=False)
def beats(text):
"""beats -- Gets the current time in .beats (Swatch Internet Time). """
if text.lower() == "wut":
return "Instead of hours and minutes, the mean solar day is divided " \
"up into 1000 parts called \".beats\". Each .beat lasts 1 minute and" \
" 26.4 seconds. Times are notated as a 3-digit number out of 1000 af" \
"ter midnight. So, @248 would indicate a time 248 .beats after midni" \
"ght representing 248/1000 of a day, just over 5 hours and 57 minute" \
"s. There are no timezones."
elif text.lower() == "guide":
return "1 day = 1000 .beats, 1 hour = 41.666 .beats, 1 min = 0.6944 .beats, 1 second = 0.01157 .beats"
t = time.gmtime()
h, m, s = t.tm_hour, t.tm_min, t.tm_sec
utc = 3600 * h + 60 * m + s
bmt = utc + 3600 # Biel Mean Time (BMT)
beat = bmt / 86.4
if beat > 1000:
beat -= 1000
return "Swatch Internet Time: @%06.2f" % beat
|
package com.khasang.forecast.sqlite;
import android.os.AsyncTask;
public class SQLiteExecAsyncTask extends AsyncTask<Void, Void, Void> {
private final String query;
private Object[] bindArgs;
public SQLiteExecAsyncTask(String query, Object[] bindArgs) {
this.query = query;
this.bindArgs = bindArgs;
this.execute();
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
try {
SQLiteWork.getInstance().queryExec(query, bindArgs);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
|
#ifndef <API key>
#define <API key>
#include <gnuradio/tags.h>
#include <vector>
namespace gr {
class tag_checker
{
private:
std::vector<tag_t> d_tags;
tag_t d_next_tag;
bool d_has_next_tag;
unsigned int d_next_tag_index;
public:
tag_checker(std::vector<tag_t>& tags) : d_has_next_tag(false), d_next_tag_index(0)
{
d_tags = tags;
std::sort(d_tags.begin(), d_tags.end(), &gr::tag_t::offset_compare);
if (!d_tags.empty()) {
d_has_next_tag = true;
d_next_tag = tags[0];
}
};
~tag_checker(){};
void get_tags(std::vector<tag_t>& tag_list, unsigned int offset)
{
while (d_has_next_tag && (offset >= d_next_tag.offset)) {
if (offset == d_next_tag.offset) {
tag_list.push_back(d_next_tag);
}
d_next_tag_index += 1;
if (d_next_tag_index >= d_tags.size()) {
d_has_next_tag = false;
} else {
d_next_tag = d_tags[d_next_tag_index];
}
}
};
};
} // namespace gr
#endif /* <API key> */
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.Cryptography;
using HaloSigner.Containers;
using HaloSigner.IO;
namespace HaloSigner.Reach
{
public class ReachGPD : GPD
{
public ReachGPD(string path)
: base(path)
{
try
{
ReadSettings();
}
catch
{
Close();
throw;
}
}
public ReachGPD(Stream stream)
: base(stream)
{
ReadSettings();
}
<summary>
The GPD's hash.
</summary>
public byte[] Hash
{
get { return _hash; }
}
<summary>
Updates and rehashes the GPD.
</summary>
public void Update()
{
// Not much to see here...
WriteHash();
}
private void ReadSettings()
{
if (TitleName != "Halo: Reach")
throw new ArgumentException("Not a valid Reach GPD");
// Title-specific data 1
_titleSpecific1 = FindSetting(TitleSpecific1ID) as GPDBinarySetting;
if (_titleSpecific1 == null || _titleSpecific1.Size != TitleSpecific1Size)
throw new ArgumentException("Not a valid Reach GPD - missing or invalid TitleSpecific1");
// Title-specific data 2
_titleSpecific2 = FindSetting(TitleSpecific2ID) as GPDBinarySetting;
if (_titleSpecific2 == null || _titleSpecific2.Size != TitleSpecific2Size)
throw new ArgumentException("Not a valid Reach GPD - missing or invalid TitleSpecific2");
// Title-specific data 3
_titleSpecific3 = FindSetting(TitleSpecific3ID) as GPDBinarySetting;
if (_titleSpecific3 == null || _titleSpecific3.Size != TitleSpecific3Size)
throw new ArgumentException("Not a valid Reach GPD - missing or invalid TitleSpecific3");
ReadHash();
}
private void ReadHash()
{
BigEndianStream stream = _titleSpecific3.GetStream();
stream.Position += HashOffset;
_hash = new byte[HashSize];
stream.ReadBlock(_hash, 0, HashSize);
}
private void WriteHash()
{
SHA1 sha1 = new <API key>();
const int LargestSettingSize = 0x3E8;
byte[] data = new byte[LargestSettingSize];
// Hash TitleSpecific1
BigEndianStream stream = _titleSpecific1.GetStream();
stream.ReadBlock(data, 0, TitleSpecific1Size);
sha1.TransformBlock(data, 0, TitleSpecific1Size, data, 0);
// Hash TitleSpecific2
stream = _titleSpecific2.GetStream();
stream.ReadBlock(data, 0, TitleSpecific2Size);
sha1.TransformBlock(data, 0, TitleSpecific2Size, data, 0);
// Read in TitleSpecific3
stream = _titleSpecific3.GetStream();
stream.ReadBlock(data, 0, TitleSpecific3Size);
// Fill the hash area with 0x99
for (int i = HashOffset; i < HashOffset + HashSize; i++)
data[i] = 0x99;
// Transform TitleSpecific3 and get the hash
sha1.TransformFinalBlock(data, 0, TitleSpecific3Size);
_hash = sha1.Hash;
// Write it back
stream.Position -= TitleSpecific3Size - HashOffset;
stream.WriteBlock(_hash);
}
private GPDBinarySetting _titleSpecific1;
private GPDBinarySetting _titleSpecific2;
private GPDBinarySetting _titleSpecific3;
private byte[] _hash;
const int HashOffset = 0x2E8;
const int HashSize = 0x14;
const uint TitleSpecific1ID = 0x63E83FFF;
const uint TitleSpecific2ID = 0x63E83FFE;
const uint TitleSpecific3ID = 0x63E83FFD;
const int TitleSpecific1Size = 0x3E8;
const int TitleSpecific2Size = 0x3E8;
const int TitleSpecific3Size = 0x300;
}
}
|
#ifndef <API key>
#define <API key>
#include <cxxtest/TestSuite.h>
#include <vector>
#include "MantidAPI/<API key>.h"
#include "MantidAPI/<API key>.h"
#include "MantidKernel/ConfigService.h"
#include "MantidKernel/WarningSuppressions.h"
#include <boost/shared_ptr.hpp>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
class <API key> : public CxxTest::TestSuite {
private:
class <API key>
: public Mantid::API::<API key> {
public:
<API key>
MOCK_CONST_METHOD0(getName, std::string());
MOCK_CONST_METHOD0(isValid, bool());
MOCK_CONST_METHOD0(toXMLString, std::string());
<API key>
protected:
<API key> *clone() const override {
return new <API key>;
}
};
// TODO, use mocking framework instead!
class <API key>
: public Mantid::API::<API key> {
public:
Mantid::API::<API key> *
createParameter(Poco::XML::Element *) override {
return new <API key>;
}
void setSuccessorParser(
Mantid::API::<API key> *) override {}
};
class <API key>
: public Mantid::API::<API key> {
public:
Mantid::API::<API key> *
createParameter(Poco::XML::Element *) override {
return new <API key>;
}
void setSuccessorParser(
Mantid::API::<API key> *) override {}
};
public:
void testSetup() {
Mantid::API::<API key>::Instance()
.subscribe<<API key>>(
"<API key>");
Mantid::API::<API key>::Instance()
.subscribe<<API key>>(
"<API key>");
}
void <API key>() {
Mantid::API::<API key> *parser =
Mantid::API::<API key>::Instance()
.createUnwrapped("<API key>");
<API key> *a =
dynamic_cast<<API key> *>(parser);
TSM_ASSERT("The correct implicit implicit function parameter parser type "
"has not been generated",
NULL != a);
delete parser;
}
void <API key>() {
Mantid::API::<API key> *parser =
Mantid::API::<API key>::Instance()
.createUnwrapped("<API key>");
<API key> *b =
dynamic_cast<<API key> *>(parser);
TSM_ASSERT("The correct implicit function parameter parser type has not "
"been generated",
NULL != b);
delete parser;
}
void testCreateThrows() {
TSM_ASSERT_THROWS(
"Should have thrown exception on use of create rather than "
"createunwrapped.",
Mantid::API::<API key>::Instance().create(
""),
std::runtime_error);
}
};
#endif
|
# This file is part of Iris.
# Iris is free software: you can redistribute it and/or modify it under
# (at your option) any later version.
# Iris is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# import iris tests first so that some things can be initialised before importing anything else
import iris.tests as tests
import os
import iris
import iris.fileformats.pp
import iris.fileformats.pp_rules
import iris.fileformats.rules
import iris.io
import iris.util
import iris.tests.stock
@iris.tests.skip_data
class TestPPLoadCustom(tests.IrisTest):
def setUp(self):
self.subcubes = iris.cube.CubeList()
filename = tests.get_data_path(('PP', 'aPPglob1', 'global.pp'))
self.template = iris.fileformats.pp.load(filename).next()
def _field_to_cube(self, field):
cube, _, _ = iris.fileformats.rules._make_cube(
field, iris.fileformats.pp_rules.convert)
return cube
def test_lbtim_2(self):
for delta in range(10):
field = self.template.copy()
field.lbtim = 2
field.lbdat += delta
cube = self._field_to_cube(field)
self.subcubes.append(cube)
cube = self.subcubes.merge()[0]
self.assertCML(cube, ('pp_rules', 'lbtim_2.cml'))
def _ocean_depth(self, bounded=False):
lbuser = list(self.template.lbuser)
lbuser[6] = 2
lbuser[3] = 101
lbuser = tuple(lbuser)
for level_and_depth in enumerate([5.0, 15.0, 25.0, 35.0, 45.0]):
field = self.template.copy()
field.lbuser = lbuser
field.lbvc = 2
field.lbfc = 601
field.lblev, field.blev = level_and_depth
if bounded:
brsvd = list(field.brsvd)
brsvd[0] = field.blev - 1
field.brsvd = tuple(brsvd)
field.brlev = field.blev + 1
cube = self._field_to_cube(field)
self.subcubes.append(cube)
def test_ocean_depth(self):
self._ocean_depth()
cube = self.subcubes.merge()[0]
self.assertCML(cube, ('pp_rules', 'ocean_depth.cml'))
def <API key>(self):
self._ocean_depth(bounded=True)
cube = self.subcubes.merge()[0]
self.assertCML(cube, ('pp_rules', 'ocean_depth_bounded.cml'))
def test_invalid_units(self):
# UM to CF rules are mapped to the invalid unit "1e3 psu @0.035"
# for the STASH code m02s00i102.
lbuser = list(self.template.lbuser)
lbuser[6] = 2
lbuser[3] = 102
self.template.lbuser = tuple(lbuser)
cube = self._field_to_cube(self.template)
self.assertCML(cube, ('pp_rules', 'invalid_units.cml'))
class TestReferences(tests.IrisTest):
def setUp(self):
target = iris.tests.stock.simple_2d()
target.data = target.data.astype('f4')
self.target = target
self.ref = target.copy()
def <API key>(self):
# If the target cube is missing one of the source dimension
# coords, ensure the re-grid fails nicely - i.e. returns None.
self.target.remove_coord('bar')
new_ref = iris.fileformats.rules._ensure_aligned({}, self.ref,
self.target)
self.assertIsNone(new_ref)
def <API key>(self):
# If the target cube has two of the source dimension coords
# sharing the same dimension (e.g. a trajectory) then ensure
# the re-grid fails nicely - i.e. returns None.
self.target.remove_coord('foo')
new_foo = self.target.coord('bar').copy()
new_foo.rename('foo')
self.target.add_aux_coord(new_foo, 0)
new_ref = iris.fileformats.rules._ensure_aligned({}, self.ref,
self.target)
self.assertIsNone(new_ref)
def <API key>(self):
new_ref = iris.fileformats.rules._ensure_aligned({}, self.ref,
self.target)
# Bounds don't make it through the re-grid process
self.ref.coord('bar').bounds = None
self.ref.coord('foo').bounds = None
self.assertEqual(new_ref, self.ref)
@iris.tests.skip_data
class TestPPLoading(tests.IrisTest):
def test_simple(self):
cube = iris.tests.stock.simple_pp()
self.assertCML(cube, ('cube_io', 'pp', 'load', 'global.cml'))
@iris.tests.skip_data
class TestPPLoadRules(tests.IrisTest):
def test_pp_load_rules(self):
# Test PP loading and rule evaluation.
cube = iris.tests.stock.simple_pp()
self.assertCML(cube, ('pp_rules', 'global.cml'))
data_path = tests.get_data_path(('PP', 'rotated_uk', 'rotated_uk.pp'))
cube = iris.load(data_path)[0]
self.assertCML(cube, ('pp_rules', 'rotated_uk.cml'))
def test_lbproc(self):
data_path = tests.get_data_path(('PP', 'meanMaxMin', '200806081200__qwpb.T24.pp'))
# Set up standard name and T+24 constraint
constraint = iris.Constraint('air_temperature', forecast_period=24)
cubes = iris.load(data_path, constraint)
cubes = iris.cube.CubeList([cubes[0], cubes[3], cubes[1], cubes[2], cubes[4]])
self.assertCML(cubes, ('pp_rules', 'lbproc_mean_max_min.cml'))
def test_custom_rules(self):
# Test custom rule evaluation.
# Default behaviour
data_path = tests.get_data_path(('PP', 'aPPglob1', 'global.pp'))
cube = iris.load_cube(data_path)
self.assertEqual(cube.standard_name, 'air_temperature')
# Custom behaviour
temp_path = iris.util.<API key>()
f = open(temp_path, 'w')
f.write('\n'.join((
'IF',
'f.lbuser[3] == 16203',
'THEN',
'CMAttribute("standard_name", None)',
'CMAttribute("long_name", "customised")')))
f.close()
iris.fileformats.pp.add_load_rules(temp_path)
cube = iris.load_cube(data_path)
self.assertEqual(cube.name(), 'customised')
os.remove(temp_path)
# Back to default
iris.fileformats.pp.reset_load_rules()
cube = iris.load_cube(data_path)
self.assertEqual(cube.standard_name, 'air_temperature')
def test_cell_methods(self):
# Test cell methods are created for correct values of lbproc
orig_file = tests.get_data_path(('PP', 'aPPglob1', 'global.pp'))
# Values that result in cell methods being created
cell_method_values = {128 : "mean", 4096 : "minimum", 8192 : "maximum"}
# Make test values as list of single bit values and some multiple bit values
single_bit_values = list(iris.fileformats.pp.LBPROC_PAIRS)
multiple_bit_values = [(128 + 64, ""), (4096 + 2096, ""), (8192 + 1024, "")]
test_values = list(single_bit_values) + multiple_bit_values
for value, _ in test_values:
f = iris.fileformats.pp.load(orig_file).next()
f.lbproc = value # set value
# Write out pp file
temp_filename = iris.util.<API key>(".pp")
f.save(open(temp_filename, 'wb'))
# Load pp file
cube = iris.load_cube(temp_filename)
if value in cell_method_values:
# Check for cell method on cube
self.assertEqual(cube.cell_methods[0].method, cell_method_values[value])
else:
# Check no cell method was created for values other than 128, 4096, 8192
self.assertEqual(len(cube.cell_methods), 0)
os.remove(temp_filename)
def test_process_flags(self):
# Test that process flags are created for correct values of lbproc
orig_file = tests.get_data_path(('PP', 'aPPglob1', 'global.pp'))
# Values that result in process flags attribute NOT being created
<API key> = (128, 4096, 8192)
# Test single flag values
for value, _ in iris.fileformats.pp.LBPROC_PAIRS:
f = iris.fileformats.pp.load(orig_file).next()
f.lbproc = value # set value
# Write out pp file
temp_filename = iris.util.<API key>(".pp")
f.save(open(temp_filename, 'wb'))
# Load pp file
cube = iris.load_cube(temp_filename)
if value in <API key>:
# Check ukmo__process_flags attribute not created
self.assertEqual(cube.attributes.get("ukmo__process_flags", None), None)
else:
# Check ukmo__process_flags attribute contains correct values
self.assertIn(iris.fileformats.pp.lbproc_map[value], cube.attributes["ukmo__process_flags"])
os.remove(temp_filename)
# Test multiple flag values
multiple_bit_values = ((128, 64), (4096, 1024), (8192, 1024))
# Maps lbproc value to the process flags that should be created
multiple_map = {sum(x) : [iris.fileformats.pp.lbproc_map[y] for y in x] for x in multiple_bit_values}
for bit_values in multiple_bit_values:
f = iris.fileformats.pp.load(orig_file).next()
f.lbproc = sum(bit_values) # set value
# Write out pp file
temp_filename = iris.util.<API key>(".pp")
f.save(open(temp_filename, 'wb'))
# Load pp file
cube = iris.load_cube(temp_filename)
# Check the process flags created
self.assertEquals(set(cube.attributes["ukmo__process_flags"]), set(multiple_map[sum(bit_values)]), "Mismatch between expected and actual process flags.")
os.remove(temp_filename)
@iris.tests.skip_data
class TestStdName(tests.IrisTest):
def test_no_std_name(self):
fname = tests.get_data_path(['PP', 'simple_pp', 'bad_global.pp'])
cube = iris.load_cube(fname)
self.assertCML([cube], ['cube_io', 'pp', 'no_std_name.cml'])
if __name__ == "__main__":
tests.main()
|
package org.mnode.coucou;
import java.util.Comparator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class <API key> implements Comparator<PathResult<?, ?>> {
private static final Logger LOGGER = LoggerFactory.getLogger(<API key>.class);
@Override
public int compare(PathResult<?, ?> o1, PathResult<?, ?> o2) {
int retVal = 0;
if (o1.isLeaf() && !o2.isLeaf()) {
retVal = Integer.MAX_VALUE;
}
else if (o2.isLeaf() && !o1.isLeaf()) {
retVal = Integer.MIN_VALUE;
}
else {
try {
retVal = o1.getName().compareToIgnoreCase(o2.getName());
}
catch (PathResultException pre) {
LOGGER.error(String.format("Error comparing o1: %s, and o2: %s", o1, o2), pre);
}
}
return retVal;
}
}
|
<?php
/**
* \file htdocs/core/lib/images.lib.php
* \brief Set of function for manipulating images
*/
// Define size of logo small and mini
$maxwidthsmall=270;$maxheightsmall=150;
$maxwidthmini=128;$maxheightmini=72;
$quality = 80;
/**
* Return if a filename is file name of a supported image format
*
* @param string $file Filename
* @return int -1=Not image filename, 0=Image filename but format not supported by PHP, 1=Image filename with format supported
*/
function <API key>($file)
{
// Case filename is not a format image
if (! preg_match('/(\.gif|\.jpg|\.jpeg|\.png|\.bmp)$/i',$file,$reg)) return -1;
// Case filename is a format image but not supported by this PHP
$imgfonction='';
if (strtolower($reg[1]) == '.gif') $imgfonction = 'imagecreatefromgif';
if (strtolower($reg[1]) == '.png') $imgfonction = 'imagecreatefrompng';
if (strtolower($reg[1]) == '.jpg') $imgfonction = 'imagecreatefromjpeg';
if (strtolower($reg[1]) == '.jpeg') $imgfonction = 'imagecreatefromjpeg';
if (strtolower($reg[1]) == '.bmp') $imgfonction = 'imagecreatefromwbmp';
if ($imgfonction)
{
if (! function_exists($imgfonction))
{
// Fonctions de conversion non presente dans ce PHP
return 0;
}
}
// Filename is a format image and supported by this PHP
return 1;
}
/**
* Return size of image file on disk (Supported extensions are gif, jpg, png and bmp)
*
* @param string $file Full path name of file
* @param bool $url Image with url (true or false)
* @return array array('width'=>width, 'height'=>height)
*/
function dol_getImageSize($file, $url = false)
{
$ret=array();
if (<API key>($file) < 0) return $ret;
$fichier = $file;
if (!$url)
{
$fichier = realpath($file); // Chemin canonique absolu de l'image
$dir = dirname($file); // Chemin du dossier contenant l'image
}
$infoImg = getimagesize($fichier); // Recuperation des infos de l'image
$ret['width']=$infoImg[0]; // Largeur de l'image
$ret['height']=$infoImg[1]; // Hauteur de l'image
return $ret;
}
/**
* Resize or crop an image file (Supported extensions are gif, jpg, png and bmp)
*
* @param string $file Path of file to resize/crop
* @param int $mode 0=Resize, 1=Crop
* @param int $newWidth Largeur maximum que dois faire l'image destination (0=keep ratio)
* @param int $newHeight Hauteur maximum que dois faire l'image destination (0=keep ratio)
* @param int $src_x Position of croping image in source image (not use if mode=0)
* @param int $src_y Position of croping image in source image (not use if mode=0)
* @return int File name if OK, error message if KO
*/
function <API key>($file, $mode, $newWidth, $newHeight, $src_x=0, $src_y=0)
{
require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
global $conf,$langs;
dol_syslog("<API key> file=".$file." mode=".$mode." newWidth=".$newWidth." newHeight=".$newHeight." src_x=".$src_x." src_y=".$src_y);
// Clean parameters
$file=trim($file);
// Check parameters
if (! $file)
{
// Si le fichier n'a pas ete indique
return 'Bad parameter file';
}
elseif (! file_exists($file))
{
// Si le fichier passe en parametre n'existe pas
return $langs->trans("ErrorFileNotFound",$file);
}
elseif(<API key>($file) < 0)
{
return 'This filename '.$file.' does not seem to be an image filename.';
}
elseif(!is_numeric($newWidth) && !is_numeric($newHeight))
{
return 'Wrong value for parameter newWidth or newHeight';
}
elseif ($mode == 0 && $newWidth <= 0 && $newHeight <= 0)
{
return 'At least newHeight or newWidth must be defined for resizing';
}
elseif ($mode == 1 && ($newWidth <= 0 || $newHeight <= 0))
{
return 'Both newHeight or newWidth must be defined for croping';
}
$fichier = realpath($file); // Chemin canonique absolu de l'image
$dir = dirname($file); // Chemin du dossier contenant l'image
$infoImg = getimagesize($fichier); // Recuperation des infos de l'image
$imgWidth = $infoImg[0]; // Largeur de l'image
$imgHeight = $infoImg[1]; // Hauteur de l'image
if ($mode == 0) // If resize, we check parameters
{
if ($newWidth <= 0)
{
$newWidth=intval(($newHeight / $imgHeight) * $imgWidth); // Keep ratio
}
if ($newHeight <= 0)
{
$newHeight=intval(($newWidth / $imgWidth) * $imgHeight); // Keep ratio
}
}
$imgfonction='';
switch($infoImg[2])
{
case 1: // IMG_GIF
$imgfonction = 'imagecreatefromgif';
break;
case 2: // IMG_JPG
$imgfonction = 'imagecreatefromjpeg';
break;
case 3: // IMG_PNG
$imgfonction = 'imagecreatefrompng';
break;
case 4: // IMG_WBMP
$imgfonction = 'imagecreatefromwbmp';
break;
}
if ($imgfonction)
{
if (! function_exists($imgfonction))
{
// Fonctions de conversion non presente dans ce PHP
return 'Resize not possible. This PHP does not support GD functions '.$imgfonction;
}
}
// Initialisation des variables selon l'extension de l'image
switch($infoImg[2])
{
case 1: // Gif
$img = imagecreatefromgif($fichier);
$extImg = '.gif'; // File name extension of image
$newquality='NU'; // Quality is not used for this format
break;
case 2: // Jpg
$img = imagecreatefromjpeg($fichier);
$extImg = '.jpg';
$newquality=100; // % quality maximum
break;
case 3: // Png
$img = imagecreatefrompng($fichier);
$extImg = '.png';
$newquality=0; // No compression (0-9)
break;
case 4: // Bmp
$img = imagecreatefromwbmp($fichier);
$extImg = '.bmp';
$newquality='NU'; // Quality is not used for this format
break;
}
// Create empty image
if ($infoImg[2] == 1)
{
// Compatibilite image GIF
$imgThumb = imagecreate($newWidth, $newHeight);
}
else
{
$imgThumb = <API key>($newWidth, $newHeight);
}
// Activate antialiasing for better quality
if (function_exists('imageantialias'))
{
imageantialias($imgThumb, true);
}
// This is to keep transparent alpha channel if exists (PHP >= 4.2)
if (function_exists('imagesavealpha'))
{
imagesavealpha($imgThumb, true);
}
// Initialisation des variables selon l'extension de l'image
switch($infoImg[2])
{
case 1: // Gif
$trans_colour = imagecolorallocate($imgThumb, 255, 255, 255); // On procede autrement pour le format GIF
<API key>($imgThumb,$trans_colour);
break;
case 2: // Jpg
$trans_colour = <API key>($imgThumb, 255, 255, 255, 0);
break;
case 3: // Png
imagealphablending($imgThumb,false); // Pour compatibilite sur certain systeme
$trans_colour = <API key>($imgThumb, 255, 255, 255, 127); // Keep transparent channel
break;
case 4: // Bmp
$trans_colour = <API key>($imgThumb, 255, 255, 255, 0);
break;
}
if (function_exists("imagefill")) imagefill($imgThumb, 0, 0, $trans_colour);
dol_syslog("<API key>: convert image from ($imgWidth x $imgHeight) at position ($src_x x $src_y) to ($newWidth x $newHeight) as $extImg, newquality=$newquality");
//imagecopyresized($imgThumb, $img, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $imgWidth, $imgHeight); // Insere l'image de base redimensionnee
imagecopyresampled($imgThumb, $img, 0, 0, $src_x, $src_y, $newWidth, $newHeight, ($mode==0?$imgWidth:$newWidth), ($mode==0?$imgHeight:$newHeight)); // Insere l'image de base redimensionnee
$imgThumbName = $file;
//$fp = fopen($imgThumbName, "w");
//fclose($fp);
// Create image on disk
switch($infoImg[2])
{
case 1: // Gif
imagegif($imgThumb, $imgThumbName);
break;
case 2: // Jpg
imagejpeg($imgThumb, $imgThumbName, $newquality);
break;
case 3: // Png
imagepng($imgThumb, $imgThumbName, $newquality);
break;
case 4: // Bmp
image2wbmp($imgThumb, $imgThumbName);
break;
}
if (! empty($conf->global->MAIN_UMASK)) @chmod($imgThumbName, octdec($conf->global->MAIN_UMASK));
// Free memory. This does not delete image.
imagedestroy($img);
imagedestroy($imgThumb);
clearstatcache();
return $imgThumbName;
}
/**
* Create a thumbnail from an image file (Supported extensions are gif, jpg, png and bmp).
* If file is myfile.jpg, new file may be myfile_small.jpg
*
* @param string $file Path of source file to resize
* @param int $maxWidth Largeur maximum que dois faire la miniature (-1=unchanged, 160 by default)
* @param int $maxHeight Hauteur maximum que dois faire l'image (-1=unchanged, 120 by default)
* @param string $extName Extension to differenciate thumb file name ('_small', '_mini')
* @param int $quality Quality of compression (0=worst, 100=best)
* @param string $outdir Directory where to store thumb
* @param int $targetformat New format of target (IMAGETYPE_GIF, IMAGETYPE_JPG, IMAGETYPE_PNG, IMAGETYPE_BMP, IMAGETYPE_WBMP ... or 0 to keep old format)
* @return string Full path of thumb or '' if it fails
*/
function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName='_small', $quality=50, $outdir='thumbs', $targetformat=0)
{
require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
global $conf,$langs;
dol_syslog("vignette file=".$file." extName=".$extName." maxWidth=".$maxWidth." maxHeight=".$maxHeight." quality=".$quality." outdir=".$outdir." targetformat=".$targetformat);
// Clean parameters
$file=trim($file);
// Check parameters
if (! $file)
{
// Si le fichier n'a pas ete indique
return 'ErrorBadParameters';
}
elseif (! file_exists($file))
{
// Si le fichier passe en parametre n'existe pas
dol_syslog($langs->trans("ErrorFileNotFound",$file),LOG_ERR);
return $langs->trans("ErrorFileNotFound",$file);
}
elseif(<API key>($file) < 0)
{
dol_syslog('This file '.$file.' does not seem to be an image format file name.',LOG_WARNING);
return 'ErrorBadImageFormat';
}
elseif(!is_numeric($maxWidth) || empty($maxWidth) || $maxWidth < -1){
// Si la largeur max est incorrecte (n'est pas numerique, est vide, ou est inferieure a 0)
dol_syslog('Wrong value for parameter maxWidth',LOG_ERR);
return 'Error: Wrong value for parameter maxWidth';
}
elseif(!is_numeric($maxHeight) || empty($maxHeight) || $maxHeight < -1){
// Si la hauteur max est incorrecte (n'est pas numerique, est vide, ou est inferieure a 0)
dol_syslog('Wrong value for parameter maxHeight',LOG_ERR);
return 'Error: Wrong value for parameter maxHeight';
}
$fichier = realpath($file); // Chemin canonique absolu de l'image
$dir = dirname($file); // Chemin du dossier contenant l'image
$infoImg = getimagesize($fichier); // Recuperation des infos de l'image
$imgWidth = $infoImg[0]; // Largeur de l'image
$imgHeight = $infoImg[1]; // Hauteur de l'image
if ($maxWidth == -1) $maxWidth=$infoImg[0]; // If size is -1, we keep unchanged
if ($maxHeight == -1) $maxHeight=$infoImg[1]; // If size is -1, we keep unchanged
// Si l'image est plus petite que la largeur et la hauteur max, on ne cree pas de vignette
if ($infoImg[0] < $maxWidth && $infoImg[1] < $maxHeight)
{
// On cree toujours les vignettes
dol_syslog("File size is smaller than thumb size",LOG_DEBUG);
//return 'Le fichier '.$file.' ne necessite pas de creation de vignette';
}
$imgfonction='';
switch($infoImg[2])
{
case IMAGETYPE_GIF:
$imgfonction = 'imagecreatefromgif';
break;
case IMAGETYPE_JPEG:
$imgfonction = 'imagecreatefromjpeg';
break;
case IMAGETYPE_PNG:
$imgfonction = 'imagecreatefrompng';
break;
case IMAGETYPE_BMP:
// Not supported by PHP GD
break;
case IMAGETYPE_WBMP:
$imgfonction = 'imagecreatefromwbmp';
break;
}
if ($imgfonction)
{
if (! function_exists($imgfonction))
{
// Fonctions de conversion non presente dans ce PHP
return 'Error: Creation of thumbs not possible. This PHP does not support GD function '.$imgfonction;
}
}
// On cree le repertoire contenant les vignettes
$dirthumb = $dir.($outdir?'/'.$outdir:''); // Chemin du dossier contenant les vignettes
dol_mkdir($dirthumb);
// Initialisation des variables selon l'extension de l'image
switch($infoImg[2])
{
case IMAGETYPE_GIF:
$img = imagecreatefromgif($fichier);
$extImg = '.gif'; // Extension de l'image
break;
case IMAGETYPE_JPEG:
$img = imagecreatefromjpeg($fichier);
$extImg = (preg_match('/\.jpeg$/',$file)?'.jpeg':'.jpg'); // Extension de l'image
break;
case IMAGETYPE_PNG:
$img = imagecreatefrompng($fichier);
$extImg = '.png';
break;
case IMAGETYPE_BMP:
// Not supported by PHP GD
$extImg = '.bmp';
break;
case IMAGETYPE_WBMP:
$img = imagecreatefromwbmp($fichier);
$extImg = '.bmp';
break;
}
if (! is_resource($img))
{
dol_syslog('Failed to detect type of image. We found infoImg[2]='.$infoImg[2], LOG_WARNING);
return 0;
}
// Initialisation des dimensions de la vignette si elles sont superieures a l'original
if($maxWidth > $imgWidth){ $maxWidth = $imgWidth; }
if($maxHeight > $imgHeight){ $maxHeight = $imgHeight; }
$whFact = $maxWidth/$maxHeight; // Facteur largeur/hauteur des dimensions max de la vignette
$imgWhFact = $imgWidth/$imgHeight; // Facteur largeur/hauteur de l'original
// Fixe les dimensions de la vignette
if($whFact < $imgWhFact)
{
// Si largeur determinante
$thumbWidth = $maxWidth;
$thumbHeight = $thumbWidth / $imgWhFact;
}
else
{
// Si hauteur determinante
$thumbHeight = $maxHeight;
$thumbWidth = $thumbHeight * $imgWhFact;
}
$thumbHeight=round($thumbHeight);
$thumbWidth=round($thumbWidth);
// Define target format
if (empty($targetformat)) $targetformat=$infoImg[2];
// Create empty image
if ($targetformat == IMAGETYPE_GIF)
{
// Compatibilite image GIF
$imgThumb = imagecreate($thumbWidth, $thumbHeight);
}
else
{
$imgThumb = <API key>($thumbWidth, $thumbHeight);
}
// Activate antialiasing for better quality
if (function_exists('imageantialias'))
{
imageantialias($imgThumb, true);
}
// This is to keep transparent alpha channel if exists (PHP >= 4.2)
if (function_exists('imagesavealpha'))
{
imagesavealpha($imgThumb, true);
}
// Initialisation des variables selon l'extension de l'image
// $targetformat is 0 by default, in such case, we keep original extension
switch($targetformat)
{
case IMAGETYPE_GIF:
$trans_colour = imagecolorallocate($imgThumb, 255, 255, 255); // On procede autrement pour le format GIF
<API key>($imgThumb,$trans_colour);
$extImgTarget = '.gif';
$newquality='NU';
break;
case IMAGETYPE_JPEG:
$trans_colour = <API key>($imgThumb, 255, 255, 255, 0);
$extImgTarget = (preg_match('/\.jpeg$/i',$file)?'.jpeg':'.jpg');
$newquality=$quality;
break;
case IMAGETYPE_PNG:
imagealphablending($imgThumb,false); // Pour compatibilite sur certain systeme
$trans_colour = <API key>($imgThumb, 255, 255, 255, 127); // Keep transparent channel
$extImgTarget = '.png';
$newquality=$quality-100;
$newquality=round(abs($quality-100)*9/100);
break;
case IMAGETYPE_BMP:
// Not supported by PHP GD
$extImgTarget = '.bmp';
$newquality='NU';
break;
case IMAGETYPE_WBMP:
$trans_colour = <API key>($imgThumb, 255, 255, 255, 0);
$extImgTarget = '.bmp';
$newquality='NU';
break;
}
if (function_exists("imagefill")) imagefill($imgThumb, 0, 0, $trans_colour);
dol_syslog("vignette: convert image from ($imgWidth x $imgHeight) to ($thumbWidth x $thumbHeight) as $extImg, newquality=$newquality");
//imagecopyresized($imgThumb, $img, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $imgWidth, $imgHeight); // Insere l'image de base redimensionnee
imagecopyresampled($imgThumb, $img, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $imgWidth, $imgHeight); // Insere l'image de base redimensionnee
$fileName = preg_replace('/(\.gif|\.jpeg|\.jpg|\.png|\.bmp)$/i','',$file); // On enleve extension quelquesoit la casse
$fileName = basename($fileName);
//$imgThumbName = $dirthumb.'/'.<API key>(basename($file), $extName, $extImgTarget); // Full path of thumb file
$imgThumbName = <API key>($file, $extName, $extImgTarget); // Full path of thumb file
//$fp = fopen($imgThumbName, "w");
//fclose($fp);
// Create image on disk
switch($targetformat)
{
case IMAGETYPE_GIF:
imagegif($imgThumb, $imgThumbName);
break;
case IMAGETYPE_JPEG:
imagejpeg($imgThumb, $imgThumbName, $newquality);
break;
case IMAGETYPE_PNG:
imagepng($imgThumb, $imgThumbName, $newquality);
break;
case IMAGETYPE_BMP:
// Not supported by PHP GD
break;
case IMAGETYPE_WBMP:
image2wbmp($imgThumb, $imgThumbName);
break;
}
if (! empty($conf->global->MAIN_UMASK)) @chmod($imgThumbName, octdec($conf->global->MAIN_UMASK));
// Free memory. This does not delete image.
imagedestroy($img);
imagedestroy($imgThumb);
return $imgThumbName;
}
|
#!/usr/bin/env bash
# Set default values of some useful variables
export VERSION="1.0-beta" # Latest released Dorsal version
export PREFIX=${HOME}/local # Default download/install location
export ORIG_DIR=`pwd` # Store original directory, so we can
# return to it when finished
# Colours for progress and error reporting
BAD="\033[1;31m"
GOOD="\033[1;32m"
BOLD="\033[1m"
Define helper functions
cecho() {
# Display messages in a specified colour
COL=$1; shift
echo -e "${COL}$@\033[0m"
}
default () {
# Export a variable, if it is not already set
VAR="${1%%=*}"
VALUE="${1
eval "[[ \$$VAR ]] || export $VAR='$VALUE'"
}
# Make a directory name more readable by replacing homedir with ~
prettify_dir() {
echo ${1/#$HOME\//~\/}
}
# Make a directory name entered with ~ for the homedir more portable
unprettify_dir() {
echo ${1/#~\//$HOME\/}
}
# Fetch the latest released version of Dorsal
fetch_dorsal() {
default TMPDIR=/tmp
cd ${TMPDIR}
cecho ${GOOD} "Fetching the FEniCS installer files"
wget -N http://launchpad.net/dorsal/trunk/${VERSION}/+download/dorsal-${VERSION}.tar.bz2
if [ -d "dorsal-${VERSION}" ]
then
rm -fr dorsal-${VERSION}
fi
tar -xjf dorsal-${VERSION}.tar.bz2
cd dorsal-${VERSION}
}
# Set up the build configuration (using some sensible defaults)
cfg_dorsal() {
echo "PROJECT=FEniCS" > dorsal.cfg
echo "DOWNLOAD_PATH=${PREFIX}/src" >> dorsal.cfg
echo "INSTALL_PATH=${PREFIX}" >> dorsal.cfg
echo "PROCS=2" >> dorsal.cfg
echo "STABLE_BUILD=true" >> dorsal.cfg
}
# Run the build script
run_dorsal() {
./dorsal.sh
cd ${ORIG_DIR}
}
while :
do
SELECTION1="Install FEniCS"
SELECTION2="Change installation path [$(prettify_dir ${PREFIX})]"
SELECTION3="Exit installer"
if [ -x /usr/bin/zenity ]; then
SELECTION=`/usr/bin/zenity \
--width 350 --height 225 \
--title "FEniCS Installer" \
--text "Welcome to the FEniCS Installer" \
--list --radiolist \
--column Select \
--column Action \
True "${SELECTION1}" \
False "${SELECTION2}" \
False "${SELECTION3}"`
case ${SELECTION} in
"${SELECTION1}")
fetch_dorsal
cfg_dorsal
run_dorsal
;;
"${SELECTION2}")
PREFIX=`zenity --title 'Select installation path' --file-selection --directory`
;;
"${SELECTION3}")
cd ${ORIG_DIR}
exit 0
;;
*)
echo "default"
;;
esac
else
clear
echo "
echo " Welcome to the FEniCS installer"
echo "
echo ""
echo " [1] ${SELECTION1}"
echo " [2] ${SELECTION2}"
echo " [3] ${SELECTION3}"
echo ""
echo "
echo ""
echo -n "What would you like to do? [1-3]: "
read OPTION
case ${OPTION} in
1) fetch_dorsal
cfg_dorsal
run_dorsal
;;
2) echo "Please enter your preferred installation path: ";
read PREFIX
PREFIX=$(unprettify_dir ${PREFIX})
;;
3) cd ${ORIG_DIR}
exit 0
;;
*) ;;
esac
echo ""
fi
done
|
package fr.skyforce77.arch3ds.api.listener;
import fr.skyforce77.arch3ds.api.input.ArchInput;
public interface InputListener {
/**
* Called when input status changed
*/
public void onInput(ArchInput input, byte status);
}
|
#include "pt_time.h"
#include "intel-pt.h"
#include <string.h>
#include <limits.h>
void pt_time_init(struct pt_time *time)
{
if (!time)
return;
memset(time, 0, sizeof(*time));
}
int pt_time_query_tsc(uint64_t *tsc, uint32_t *lost_mtc,
uint32_t *lost_cyc, const struct pt_time *time)
{
if (!tsc || !time)
return -pte_internal;
*tsc = time->tsc;
if (lost_mtc)
*lost_mtc = time->lost_mtc;
if (lost_cyc)
*lost_cyc = time->lost_cyc;
if (!time->have_tsc)
return -pte_no_time;
return 0;
}
int pt_time_query_cbr(uint32_t *cbr, const struct pt_time *time)
{
if (!cbr || !time)
return -pte_internal;
if (!time->have_cbr)
return -pte_no_cbr;
*cbr = time->cbr;
return 0;
}
/* Compute the distance between two CTC sources.
*
* We adjust a single wrap-around but fail if the distance is bigger than that.
*
* Returns zero on success, a negative error code otherwise.
*/
static int pt_time_ctc_delta(uint32_t *ctc_delta, uint32_t ctc,
uint32_t last_ctc, const struct pt_config *config)
{
if (!config || !ctc_delta)
return -pte_internal;
/* Correct a single wrap-around. If we lost enough MTCs to wrap
* around twice, timing will be wrong until the next TSC.
*/
if (ctc < last_ctc) {
ctc += 1u << (config->mtc_freq + pt_pl_mtc_bit_size);
/* Since we only store the CTC between TMA/MTC or MTC/TMC a
* single correction should suffice.
*/
if (ctc < last_ctc)
return -pte_bad_packet;
}
*ctc_delta = ctc - last_ctc;
return 0;
}
/* Translate CTC into the same unit as the FastCounter by multiplying with P.
*
* Returns zero on success, a negative error code otherwise.
*/
static int pt_time_ctc_fc(uint64_t *fc, uint64_t ctc,
const struct pt_config *config)
{
uint32_t eax, ebx;
if (!fc || !config)
return -pte_internal;
eax = config->cpuid_0x15_eax;
ebx = config->cpuid_0x15_ebx;
/* Neither multiply nor divide by zero. */
if (!eax || !ebx)
return -pte_bad_config;
*fc = (ctc * ebx) / eax;
return 0;
}
int pt_time_update_tsc(struct pt_time *time,
const struct pt_packet_tsc *packet,
const struct pt_config *config)
{
(void) config;
if (!time || !packet)
return -pte_internal;
time->have_tsc = 1;
time->have_tma = 0;
time->tsc = time->base = packet->tsc;
time->fc = 0ull;
/* We got the full time; we recover from previous losses. */
time->lost_mtc = 0;
time->lost_cyc = 0;
return 0;
}
int pt_time_update_cbr(struct pt_time *time,
const struct pt_packet_cbr *packet,
const struct pt_config *config)
{
(void) config;
if (!time || !packet)
return -pte_internal;
time->have_cbr = 1;
time->cbr = packet->ratio;
return 0;
}
int pt_time_update_tma(struct pt_time *time,
const struct pt_packet_tma *packet,
const struct pt_config *config)
{
uint32_t ctc, mtc_mask, mtc_offset, mtc_freq;
uint64_t fc;
if (!time || !packet || !config)
return -pte_internal;
/* Without a TSC something is seriously wrong. */
if (!time->have_tsc)
return -pte_bad_context;
ctc = packet->ctc;
fc = packet->fc;
mtc_freq = config->mtc_freq;
mtc_mask = (1u << mtc_freq) - 1u;
mtc_offset = ctc & mtc_mask;
/* Mask out the MTC offset and the high order bits. */
ctc &= pt_pl_mtc_mask << mtc_freq;
time->have_tma = 1;
time->base -= fc;
time->fc += fc;
time->mtc_offset = mtc_offset;
/* If the MTC frequency is low enough that TMA provides the full CTC
* value, we're fine.
*/
if ((mtc_freq + 8) <= <API key>) {
time->ctc = ctc;
time->ctc_cyc = ctc;
/* We can use the TMA instead of an MTC. */
time->have_mtc = 1;
}
/* Otherwise, we must rely on either having seen an MTC before or
* on heuristically approximating it later at the next MTC.
*/
return 0;
}
int pt_time_update_mtc(struct pt_time *time,
const struct pt_packet_mtc *packet,
const struct pt_config *config)
{
uint32_t last_ctc, mtc_offset, ctc, ctc_delta;
uint64_t tsc, base;
uint8_t mtc_freq;
int errcode, have_tsc, have_tma, have_mtc;
if (!time || !packet || !config)
return -pte_internal;
have_tsc = time->have_tsc;
have_tma = time->have_tma;
have_mtc = time->have_mtc;
/* We ignore MTCs between TSC and TMA to avoid apparent CTC overflows.
* Later MTCs will ensure that no time is lost.
*/
if (have_tsc && !have_tma)
return 0;
base = time->base;
last_ctc = time->ctc;
mtc_offset = time->mtc_offset;
mtc_freq = config->mtc_freq;
ctc = packet->ctc << mtc_freq;
/* Store our CTC value if we have or would have reset FC. */
if (time->fc || time->lost_cyc || !have_mtc)
time->ctc_cyc = ctc;
/* Prepare for the next packet in case we error out below. */
time->have_mtc = 1;
time->fc = 0ull;
time->mtc_offset = 0;
time->ctc = ctc;
/* We recover from previous CYC losses. */
time->lost_cyc = 0;
/* Avoid a big jump when we see the first MTC with an arbitrary CTC
* payload.
*/
if (!have_mtc) {
uint8_t shift;
/* If we have not seen a TMA, we ignore this first MTC.
*
* We have no idea where in this MTC period tracing started.
* We could lose an entire MTC period or just a tiny fraction.
*
* On the other hand, if we assumed a previous MTC value, we
* might make just the same error.
*/
if (!have_tma)
return 0;
/* The TMA we've seen provided an offset into the current
* MTC period. Let's assume the last CTC was just small
* enough to contain that offset.
*/
shift = <API key>;
if (shift < mtc_freq)
shift = mtc_freq;
ctc_delta = 1u << shift;
} else {
/* This is the normal case. We have seen an MTC before so we
* know the previous CTC value.
*/
errcode = pt_time_ctc_delta(&ctc_delta, ctc, last_ctc, config);
if (errcode < 0) {
time->lost_mtc += 1;
return errcode;
}
}
/* We don't want a wrap-around here. Something must be wrong. */
if (ctc_delta < mtc_offset) {
time->lost_mtc += 1;
return -pte_bad_packet;
}
ctc_delta -= mtc_offset;
errcode = pt_time_ctc_fc(&tsc, ctc_delta, config);
if (errcode < 0)
return errcode;
base += tsc;
time->tsc = time->base = base;
return 0;
}
/* Adjust a CYC packet's payload spanning multiple MTC periods.
*
* CYC packets measure the Fast Counter since the last CYC(-eligible) packet.
* Depending on the CYC threshold, we may not get a CYC for each MTC, so a CYC
* period may overlap with or even span multiple MTC periods.
*
* We can't do much about the overlap case without examining all packets in
* the respective periods. We leave this as expected imprecision.
*
* If we find a CYC packet to span multiple MTC packets, though, we try to
* approximate the portion for the current MTC period by subtracting the
* estimated portion for previous MTC periods using calibration information.
*
* We only consider MTC. For the first CYC after TSC, the corresponding TMA
* will contain the Fast Counter at TSC.
*
* Returns zero on success, a negative error code otherwise.
*/
static int pt_time_adjust_cyc(uint64_t *cyc, const struct pt_time *time,
const struct pt_config *config, uint64_t fcr)
{
uint32_t last_ctc, ctc, ctc_delta;
uint64_t fc, total_cyc, old_cyc;
int errcode;
if (!time || !config || !fcr)
return -pte_internal;
last_ctc = time->ctc_cyc;
ctc = time->ctc;
/* There is nothing to do if this is the current MTC period. */
if (ctc == last_ctc)
return 0;
/* Calibration computes
*
* fc = (ctc_delta * cpuid[0x15].ebx) / cpuid[0x15].eax.
* fcr = (fc << pt_tcal_fcr_shr) / cyc
*
* So cyc = (fc << pt_tcal_fcr_shr) / fcr.
*/
errcode = pt_time_ctc_delta(&ctc_delta, ctc, last_ctc, config);
if (errcode < 0)
return errcode;
errcode = pt_time_ctc_fc(&fc, ctc_delta, config);
if (errcode < 0)
return errcode;
old_cyc = (fc << pt_tcal_fcr_shr) / fcr;
total_cyc = *cyc;
/* Make sure we don't wrap around. If we would, attribute the entire
* CYC payload to any previous MTC period.
*
* We lost an unknown portion of the CYC payload for the current MTC
* period, but it's usually better to run too slow than too fast.
*/
if (total_cyc < old_cyc)
total_cyc = old_cyc;
*cyc = total_cyc - old_cyc;
return 0;
}
int pt_time_update_cyc(struct pt_time *time,
const struct pt_packet_cyc *packet,
const struct pt_config *config, uint64_t fcr)
{
uint64_t cyc, fc;
if (!time || !packet || !config)
return -pte_internal;
if (!fcr) {
time->lost_cyc += 1;
return 0;
}
cyc = packet->value;
fc = time->fc;
if (!fc) {
int errcode;
errcode = pt_time_adjust_cyc(&cyc, time, config, fcr);
if (errcode < 0)
return errcode;
}
fc += (cyc * fcr) >> pt_tcal_fcr_shr;
time->fc = fc;
time->tsc = time->base + fc;
return 0;
}
void pt_tcal_init(struct pt_time_cal *tcal)
{
if (!tcal)
return;
memset(tcal, 0, sizeof(*tcal));
tcal->min_fcr = UINT64_MAX;
}
static int pt_tcal_have_fcr(const struct pt_time_cal *tcal)
{
if (!tcal)
return 0;
return (tcal->min_fcr <= tcal->max_fcr);
}
int pt_tcal_fcr(uint64_t *fcr, const struct pt_time_cal *tcal)
{
if (!fcr || !tcal)
return -pte_internal;
if (!pt_tcal_have_fcr(tcal))
return -pte_no_time;
*fcr = tcal->fcr;
return 0;
}
int pt_tcal_set_fcr(struct pt_time_cal *tcal, uint64_t fcr)
{
if (!tcal)
return -pte_internal;
tcal->fcr = fcr;
if (fcr < tcal->min_fcr)
tcal->min_fcr = fcr;
if (fcr > tcal->max_fcr)
tcal->max_fcr = fcr;
return 0;
}
int pt_tcal_update_tsc(struct pt_time_cal *tcal,
const struct pt_packet_tsc *packet,
const struct pt_config *config)
{
(void) config;
if (!tcal || !packet)
return -pte_internal;
/* A TSC outside of PSB+ may indicate loss of time. We do not use it
* for calibration. We store the TSC value for calibration at the next
* TSC in PSB+, though.
*/
tcal->tsc = packet->tsc;
tcal->cyc_tsc = 0ull;
return 0;
}
int pt_tcal_header_tsc(struct pt_time_cal *tcal,
const struct pt_packet_tsc *packet,
const struct pt_config *config)
{
uint64_t tsc, last_tsc, tsc_delta, cyc, fcr;
(void) config;
if (!tcal || !packet)
return -pte_internal;
last_tsc = tcal->tsc;
cyc = tcal->cyc_tsc;
tsc = packet->tsc;
tcal->tsc = tsc;
tcal->cyc_tsc = 0ull;
if (!last_tsc || !cyc)
return 0;
/* Correct a single wrap-around. */
if (tsc < last_tsc) {
tsc += 1ull << pt_pl_tsc_bit_size;
if (tsc < last_tsc)
return -pte_bad_packet;
}
tsc_delta = tsc - last_tsc;
/* We shift the nominator to improve rounding precision.
*
* Since we're only collecting the CYCs between two TSC, we shouldn't
* overflow. Let's rather fail than overflow.
*/
if (tsc_delta & ~(~0ull >> pt_tcal_fcr_shr))
return -pte_internal;
fcr = (tsc_delta << pt_tcal_fcr_shr) / cyc;
return pt_tcal_set_fcr(tcal, fcr);
}
int pt_tcal_update_cbr(struct pt_time_cal *tcal,
const struct pt_packet_cbr *packet,
const struct pt_config *config)
{
/* A CBR outside of PSB+ indicates a frequency change. Reset our
* calibration state.
*/
pt_tcal_init(tcal);
return pt_tcal_header_cbr(tcal, packet, config);
}
int pt_tcal_header_cbr(struct pt_time_cal *tcal,
const struct pt_packet_cbr *packet,
const struct pt_config *config)
{
uint64_t cbr, p1, fcr;
if (!tcal || !packet || !config)
return -pte_internal;
p1 = config->nom_freq;
if (!p1)
return 0;
/* If we know the nominal frequency, we can use it for calibration. */
cbr = packet->ratio;
fcr = (p1 << pt_tcal_fcr_shr) / cbr;
return pt_tcal_set_fcr(tcal, fcr);
}
int pt_tcal_update_tma(struct pt_time_cal *tcal,
const struct pt_packet_tma *packet,
const struct pt_config *config)
{
(void) tcal;
(void) packet;
(void) config;
/* Nothing to do. */
return 0;
}
int pt_tcal_update_mtc(struct pt_time_cal *tcal,
const struct pt_packet_mtc *packet,
const struct pt_config *config)
{
uint32_t last_ctc, ctc, ctc_delta, have_mtc;
uint64_t cyc, fc, fcr;
int errcode;
if (!tcal || !packet || !config)
return -pte_internal;
last_ctc = tcal->ctc;
have_mtc = tcal->have_mtc;
cyc = tcal->cyc_mtc;
ctc = packet->ctc << config->mtc_freq;
/* We need at least two MTC (including this). */
if (!have_mtc) {
tcal->cyc_mtc = 0ull;
tcal->ctc = ctc;
tcal->have_mtc = 1;
return 0;
}
/* Without any cycles, we can't calibrate. Try again at the next
* MTC and distribute the cycles over the combined MTC period.
*/
if (!cyc)
return 0;
/* Prepare for the next packet in case we error out below. */
tcal->have_mtc = 1;
tcal->cyc_mtc = 0ull;
tcal->ctc = ctc;
/* Let's pretend we will fail. We'll correct it at the end. */
tcal->lost_mtc += 1;
errcode = pt_time_ctc_delta(&ctc_delta, ctc, last_ctc, config);
if (errcode < 0)
return errcode;
errcode = pt_time_ctc_fc(&fc, ctc_delta, config);
if (errcode < 0)
return errcode;
/* We shift the nominator to improve rounding precision.
*
* Since we're only collecting the CYCs between two MTC, we shouldn't
* overflow. Let's rather fail than overflow.
*/
if (fc & ~(~0ull >> pt_tcal_fcr_shr))
return -pte_internal;
fcr = (fc << pt_tcal_fcr_shr) / cyc;
errcode = pt_tcal_set_fcr(tcal, fcr);
if (errcode < 0)
return errcode;
/* We updated the FCR. This recovers from previous MTC losses. */
tcal->lost_mtc = 0;
return 0;
}
int pt_tcal_update_cyc(struct pt_time_cal *tcal,
const struct pt_packet_cyc *packet,
const struct pt_config *config)
{
uint64_t cyc;
(void) config;
if (!tcal || !packet)
return -pte_internal;
cyc = packet->value;
tcal->cyc_mtc += cyc;
tcal->cyc_tsc += cyc;
return 0;
}
|
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>ns-3 PLC model: ns3::PLC_Mac Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { searchBox.OnSelectItem(0); });
</script>
</head>
<body>
<div id="top"><!-- do not remove this div! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">ns-3 PLC model
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- Generated by Doxygen 1.7.6.1 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark"> </span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark"> </span>Enumerations</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="<API key>">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><b>ns3</b> </li>
<li class="navelem"><a class="el" href="<API key>.html">PLC_Mac</a> </li>
</ul>
</div>
</div>
<div class="header">
<div class="summary">
<a href="#pub-methods">Public Member Functions</a> |
<a href="#pub-static-methods">Static Public Member Functions</a> |
<a href="#pro-methods">Protected Member Functions</a> |
<a href="#pro-attribs">Protected Attributes</a> |
<a href="#pro-static-attribs">Static Protected Attributes</a> </div>
<div class="headertitle">
<div class="title">ns3::PLC_Mac Class Reference</div> </div>
</div><!--header
<div class="contents">
<!-- doxytag: class="ns3::PLC_Mac" -->
<p><code>#include <<a class="el" href="plc-mac_8h_source.html">plc-mac.h</a>></code></p>
<div class="dynheader">
Inheritance diagram for ns3::PLC_Mac:</div>
<div class="dyncontent">
<div class="center">
<img src="<API key>.png" usemap="#ns3::PLC_Mac_map" alt=""/>
<map id="ns3::PLC_Mac_map" name="ns3::PLC_Mac_map">
<area href="<API key>.html" alt="ns3::PLC_ArqMac" shape="rect" coords="0,56,114,80"/>
</map>
</div></div>
<p><a href="<API key>.html">List of all members.</a></p>
<table class="memberdecls">
<tr><td colspan="2"><h2><a name="pub-methods"></a>
Public Member Functions</h2></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::<API key>" ref="<API key>" args="(<API key> c)" -->
void </td><td class="memItemRight" valign="bottom"><b><API key></b> (<API key> c)</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::RequestCca" ref="<API key>" args="()" -->
void </td><td class="memItemRight" valign="bottom"><b>RequestCca</b> ()</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::InitializeCsmaCa" ref="<API key>" args="(void)" -->
void </td><td class="memItemRight" valign="bottom"><b>InitializeCsmaCa</b> (void)</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::RandomBackoffDelay" ref="<API key>" args="()" -->
void </td><td class="memItemRight" valign="bottom"><b>RandomBackoffDelay</b> ()</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::CcaConfirm" ref="<API key>" args="(PLC_PhyCcaResult status)" -->
void </td><td class="memItemRight" valign="bottom"><b>CcaConfirm</b> (PLC_PhyCcaResult status)</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::CsmaCaConfirm" ref="<API key>" args="(PLC_CsmaCaState state)" -->
void </td><td class="memItemRight" valign="bottom"><b>CsmaCaConfirm</b> (PLC_CsmaCaState state)</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::NotifyCcaConfirm" ref="<API key>" args="(PLC_PhyCcaResult status)=0" -->
virtual void </td><td class="memItemRight" valign="bottom"><b>NotifyCcaConfirm</b> (PLC_PhyCcaResult status)=0</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::NotifyCsmaCaConfirm" ref="<API key>" args="(PLC_CsmaCaState state)=0" -->
virtual void </td><td class="memItemRight" valign="bottom"><b>NotifyCsmaCaConfirm</b> (PLC_CsmaCaState state)=0</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">SetMacDataCallback</a> (PLC_MacDataCallback c)</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>"><API key></a> (<API key> c)</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>"><API key></a> (PLC_MacDataCallback c)</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>"><API key></a> (<API key> c)</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">SetAddress</a> (Mac48Address addr)</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">Mac48Address </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">GetAddress</a> (void)</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">SetBroadcastAddress</a> (Mac48Address addr)</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">Mac48Address </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">GetBroadcastAddress</a> (void)</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">SetMulticastAddress</a> (Mac48Address addr)</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">Mac48Address </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">GetMulticastAddress</a> (void)</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">bool </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">Send</a> (Ptr< Packet > p, Mac48Address dst)</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">bool </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">SendFrom</a> (Ptr< Packet > p, Mac48Address src, Mac48Address dst)</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::SetPhy" ref="<API key>" args="(Ptr< PLC_Phy > phy)" -->
void </td><td class="memItemRight" valign="bottom"><b>SetPhy</b> (Ptr< <a class="el" href="<API key>.html">PLC_Phy</a> > phy)</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::GetPhy" ref="<API key>" args="(void)" -->
Ptr< <a class="el" href="<API key>.html">PLC_Phy</a> > </td><td class="memItemRight" valign="bottom"><b>GetPhy</b> (void)</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">virtual void </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>"><API key></a> (void)=0</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>"><API key></a> (Ptr< const Packet > p)</td></tr>
<tr><td colspan="2"><h2><a name="pub-static-methods"></a>
Static Public Member Functions</h2></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::GetTypeId" ref="<API key>" args="(void)" -->
static TypeId </td><td class="memItemRight" valign="bottom"><b>GetTypeId</b> (void)</td></tr>
<tr><td colspan="2"><h2><a name="pro-methods"></a>
Protected Member Functions</h2></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::DoInitialize" ref="<API key>" args="(void)" -->
virtual void </td><td class="memItemRight" valign="bottom"><b>DoInitialize</b> (void)</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::DoDispose" ref="<API key>" args="(void)" -->
virtual void </td><td class="memItemRight" valign="bottom"><b>DoDispose</b> (void)</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::DoSendFrom" ref="<API key>" args="(Ptr< Packet > p, Mac48Address src, Mac48Address dst)=0" -->
virtual bool </td><td class="memItemRight" valign="bottom"><b>DoSendFrom</b> (Ptr< Packet > p, Mac48Address src, Mac48Address dst)=0</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::DoProcess" ref="<API key>" args="(Ptr< const Packet > p)=0" -->
virtual void </td><td class="memItemRight" valign="bottom"><b>DoProcess</b> (Ptr< const Packet > p)=0</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::DoSetPhy" ref="<API key>" args="(Ptr< PLC_Phy > phy)=0" -->
virtual void </td><td class="memItemRight" valign="bottom"><b>DoSetPhy</b> (Ptr< <a class="el" href="<API key>.html">PLC_Phy</a> > phy)=0</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::DoGetPhy" ref="<API key>" args="(void)=0" -->
virtual Ptr< <a class="el" href="<API key>.html">PLC_Phy</a> > </td><td class="memItemRight" valign="bottom"><b>DoGetPhy</b> (void)=0</td></tr>
<tr><td colspan="2"><h2><a name="pro-attribs"></a>
Protected Attributes</h2></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::m_address" ref="<API key>" args="" -->
Mac48Address </td><td class="memItemRight" valign="bottom"><b>m_address</b></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::m_broadcast_address" ref="<API key>" args="" -->
Mac48Address </td><td class="memItemRight" valign="bottom"><b>m_broadcast_address</b></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::m_multicast_address" ref="<API key>" args="" -->
Mac48Address </td><td class="memItemRight" valign="bottom"><b>m_multicast_address</b></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::m_csmaca_active" ref="<API key>" args="" -->
bool </td><td class="memItemRight" valign="bottom"><b>m_csmaca_active</b></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::m_promiscuous_mode" ref="<API key>" args="" -->
bool </td><td class="memItemRight" valign="bottom"><b>m_promiscuous_mode</b></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::m_csmaca_attempts" ref="<API key>" args="" -->
uint32_t </td><td class="memItemRight" valign="bottom"><b>m_csmaca_attempts</b></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::m_NB" ref="<API key>" args="" -->
uint8_t </td><td class="memItemRight" valign="bottom"><b>m_NB</b></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::m_BE" ref="<API key>" args="" -->
uint8_t </td><td class="memItemRight" valign="bottom"><b>m_BE</b></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::m_macMinBE" ref="<API key>" args="" -->
uint8_t </td><td class="memItemRight" valign="bottom"><b>m_macMinBE</b></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::m_macMaxBE" ref="<API key>" args="" -->
uint8_t </td><td class="memItemRight" valign="bottom"><b>m_macMaxBE</b></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::<API key>" ref="<API key>" args="" -->
uint8_t </td><td class="memItemRight" valign="bottom"><b><API key></b></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::<API key>" ref="<API key>" args="" -->
uint64_t </td><td class="memItemRight" valign="bottom"><b><API key></b></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::m_requestCCAEvent" ref="<API key>" args="" -->
EventId </td><td class="memItemRight" valign="bottom"><b>m_requestCCAEvent</b></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::m_backoffEndEvent" ref="<API key>" args="" -->
EventId </td><td class="memItemRight" valign="bottom"><b>m_backoffEndEvent</b></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::m_data_callback" ref="<API key>" args="" -->
PLC_MacDataCallback </td><td class="memItemRight" valign="bottom"><b>m_data_callback</b></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::<API key>" ref="<API key>" args="" -->
<API key> </td><td class="memItemRight" valign="bottom"><b><API key></b></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::<API key>" ref="<API key>" args="" -->
PLC_MacDataCallback </td><td class="memItemRight" valign="bottom"><b><API key></b></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::<API key>" ref="<API key>" args="" -->
<API key> </td><td class="memItemRight" valign="bottom"><b><API key></b></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::<API key>" ref="<API key>" args="" -->
<API key> </td><td class="memItemRight" valign="bottom"><b><API key></b></td></tr>
<tr><td colspan="2"><h2><a name="pro-static-attribs"></a>
Static Protected Attributes</h2></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::mac_list" ref="<API key>" args="" -->
static std::map< Mac48Address, <br class="typebreak"/>
Ptr< <a class="el" href="<API key>.html">PLC_Mac</a> > > </td><td class="memItemRight" valign="bottom"><b>mac_list</b> = std::map<Mac48Address, Ptr<<a class="el" href="<API key>.html">PLC_Mac</a>> > ()</td></tr>
</table>
<hr/><a name="details" id="details"></a><h2>Detailed Description</h2>
<div class="textblock"><p>Abstract base class for PLC MAC layers implementing 48 bit addressing and channel access via CSMA/CA algorithm </p>
</div><hr/><h2>Member Function Documentation</h2>
<a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::GetAddress" ref="<API key>" args="(void)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">Mac48Address <a class="el" href="<API key>.html#<API key>">ns3::PLC_Mac::GetAddress</a> </td>
<td>(</td>
<td class="paramtype">void </td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</div>
<div class="memdoc">
<dl class="return"><dt><b>Returns:</b></dt><dd>16bit MAC address </dd></dl>
</div>
</div>
<a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::GetBroadcastAddress" ref="<API key>" args="(void)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">Mac48Address <a class="el" href="<API key>.html#<API key>">ns3::PLC_Mac::GetBroadcastAddress</a> </td>
<td>(</td>
<td class="paramtype">void </td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</div>
<div class="memdoc">
<dl class="return"><dt><b>Returns:</b></dt><dd>16 bit broadcast address </dd></dl>
</div>
</div>
<a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::GetMulticastAddress" ref="<API key>" args="(void)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">Mac48Address <a class="el" href="<API key>.html#<API key>">ns3::PLC_Mac::GetMulticastAddress</a> </td>
<td>(</td>
<td class="paramtype">void </td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</div>
<div class="memdoc">
<dl class="return"><dt><b>Returns:</b></dt><dd>16 bit multicast address </dd></dl>
</div>
</div>
<a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::<API key>" ref="<API key>" args="(Ptr< const Packet > p)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void <a class="el" href="<API key>.html#<API key>">ns3::PLC_Mac::<API key></a> </td>
<td>(</td>
<td class="paramtype">Ptr< const Packet > </td>
<td class="paramname"><em>p</em></td><td>)</td>
<td></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Notify MAC that PHY successfully finished reception of packet p</p>
<dl class="params"><dt><b>Parameters:</b></dt><dd>
<table class="params">
<tr><td class="paramname">p</td><td>the received packet </td></tr>
</table>
</dd>
</dl>
</div>
</div>
<a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::<API key>" ref="<API key>" args="(void)=0" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">virtual void <a class="el" href="<API key>.html#<API key>">ns3::PLC_Mac::<API key></a> </td>
<td>(</td>
<td class="paramtype">void </td>
<td class="paramname"></td><td>)</td>
<td><code> [pure virtual]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Notify the MAC that the PHY has finished a previously started transmission </p>
<p>Implemented in <a class="el" href="<API key>.html#<API key>">ns3::PLC_ArqMac</a>.</p>
</div>
</div>
<a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::Send" ref="<API key>" args="(Ptr< Packet > p, Mac48Address dst)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">bool <a class="el" href="<API key>.html#<API key>">ns3::PLC_Mac::Send</a> </td>
<td>(</td>
<td class="paramtype">Ptr< Packet > </td>
<td class="paramname"><em>p</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">Mac48Address </td>
<td class="paramname"><em>dst</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Send packet p to dst </p>
<dl class="params"><dt><b>Parameters:</b></dt><dd>
<table class="params">
<tr><td class="paramname">p</td><td></td></tr>
<tr><td class="paramname">dst</td><td></td></tr>
</table>
</dd>
</dl>
<dl class="return"><dt><b>Returns:</b></dt><dd></dd></dl>
</div>
</div>
<a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::SendFrom" ref="<API key>" args="(Ptr< Packet > p, Mac48Address src, Mac48Address dst)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">bool <a class="el" href="<API key>.html#<API key>">ns3::PLC_Mac::SendFrom</a> </td>
<td>(</td>
<td class="paramtype">Ptr< Packet > </td>
<td class="paramname"><em>p</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">Mac48Address </td>
<td class="paramname"><em>src</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">Mac48Address </td>
<td class="paramname"><em>dst</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div>
<div class="memdoc">
<dl class="params"><dt><b>Parameters:</b></dt><dd>
<table class="params">
<tr><td class="paramname">p</td><td></td></tr>
<tr><td class="paramname">src</td><td></td></tr>
<tr><td class="paramname">dst</td><td></td></tr>
</table>
</dd>
</dl>
<dl class="return"><dt><b>Returns:</b></dt><dd></dd></dl>
</div>
</div>
<a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::SetAddress" ref="<API key>" args="(Mac48Address addr)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void <a class="el" href="<API key>.html#<API key>">ns3::PLC_Mac::SetAddress</a> </td>
<td>(</td>
<td class="paramtype">Mac48Address </td>
<td class="paramname"><em>addr</em></td><td>)</td>
<td></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Set MAC address</p>
<dl class="params"><dt><b>Parameters:</b></dt><dd>
<table class="params">
<tr><td class="paramname">addr</td><td>16 bit MAC address </td></tr>
</table>
</dd>
</dl>
</div>
</div>
<a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::SetBroadcastAddress" ref="<API key>" args="(Mac48Address addr)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void <a class="el" href="<API key>.html#<API key>">ns3::PLC_Mac::SetBroadcastAddress</a> </td>
<td>(</td>
<td class="paramtype">Mac48Address </td>
<td class="paramname"><em>addr</em></td><td>)</td>
<td></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Set broadcast address</p>
<dl class="params"><dt><b>Parameters:</b></dt><dd>
<table class="params">
<tr><td class="paramname">addr</td><td>16 bit broadcast address </td></tr>
</table>
</dd>
</dl>
</div>
</div>
<a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::<API key>" ref="<API key>" args="(<API key> c)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void <a class="el" href="<API key>.html#<API key>">ns3::PLC_Mac::<API key></a> </td>
<td>(</td>
<td class="paramtype"><API key> </td>
<td class="paramname"><em>c</em></td><td>)</td>
<td></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Callback indicating that acknowledgement for previously sent data has been received </p>
</div>
</div>
<a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::SetMacDataCallback" ref="<API key>" args="(PLC_MacDataCallback c)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void <a class="el" href="<API key>.html#<API key>">ns3::PLC_Mac::SetMacDataCallback</a> </td>
<td>(</td>
<td class="paramtype">PLC_MacDataCallback </td>
<td class="paramname"><em>c</em></td><td>)</td>
<td></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Callback for data delivery to higher layer </p>
</div>
</div>
<a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::SetMulticastAddress" ref="<API key>" args="(Mac48Address addr)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void <a class="el" href="<API key>.html#<API key>">ns3::PLC_Mac::SetMulticastAddress</a> </td>
<td>(</td>
<td class="paramtype">Mac48Address </td>
<td class="paramname"><em>addr</em></td><td>)</td>
<td></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Set multicast address</p>
<dl class="params"><dt><b>Parameters:</b></dt><dd>
<table class="params">
<tr><td class="paramname">addr</td><td>16 bit multicast address </td></tr>
</table>
</dd>
</dl>
</div>
</div>
<a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::<API key>" ref="<API key>" args="(PLC_MacDataCallback c)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void <a class="el" href="<API key>.html#<API key>">ns3::PLC_Mac::<API key></a> </td>
<td>(</td>
<td class="paramtype">PLC_MacDataCallback </td>
<td class="paramname"><em>c</em></td><td>)</td>
<td></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Callback for promiscuous data delivery to higher layer </p>
</div>
</div>
<a class="anchor" id="<API key>"></a><!-- doxytag: member="ns3::PLC_Mac::<API key>" ref="<API key>" args="(<API key> c)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void <a class="el" href="<API key>.html#<API key>">ns3::PLC_Mac::<API key></a> </td>
<td>(</td>
<td class="paramtype"><API key> </td>
<td class="paramname"><em>c</em></td><td>)</td>
<td></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Callback for failed data transmission </p>
</div>
</div>
<hr/>The documentation for this class was generated from the following files:<ul>
<li>model/<a class="el" href="plc-mac_8h_source.html">plc-mac.h</a></li>
<li>model/plc-mac.cc</li>
</ul>
</div><!-- contents -->
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark"> </span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark"> </span>Enumerations</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="<API key>">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<hr class="footer"/><address class="footer"><small>
Generated on Sat Mar 30 2013 21:36:39 for ns-3 PLC model by &
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.7.6.1
</small></address>
</body>
</html>
|
#ifndef __BAYES_H__
#define __BAYES_H__
#include "function.h"
#include <iostream>
template <class T> class BayesModel: public RealFunction<T>
{
public:
BayesModel() { logprior = NULL; loglikelihood = NULL; }
virtual ~BayesModel() { }
void SetPrior(const RealFunction<T> & lprior) { logprior = &lprior; }
void SetLikelihood(const RealFunction<T> & llikelihood) { loglikelihood = &llikelihood; }
double operator()(const T & x) const override
{
if (logprior == NULL) return (*loglikelihood)(x);
else return (*loglikelihood)(x)+(*logprior)(x);
}
private:
const RealFunction<T> * logprior;
const RealFunction<T> * loglikelihood;
};
#endif
|
-- 170
-- UCColumnA
-- Added UNIQUE to column ndb_no in table nut_data
CREATE TABLE "data_src" (
"datasrc_id" CHAR(6) NOT NULL,
"authors" VARCHAR(100),
"title" VARCHAR(100) NOT NULL,
"year" INT,
"journal" VARCHAR(100),
"vol_city" VARCHAR(100),
"issue_state" VARCHAR(100),
"start_page" VARCHAR(100),
"end_page" VARCHAR(100)
)
CREATE TABLE "datsrcln" (
"ndb_no" CHAR(5) NOT NULL,
"nutr_no" CHAR(3) NOT NULL,
"datasrc_id" CHAR(6) NOT NULL
)
CREATE TABLE "deriv_cd" (
"deriv_cd" VARCHAR(100) NOT NULL,
"derivcd_desc" VARCHAR(100) NOT NULL
)
CREATE TABLE "fd_group" (
"fdgrp_cd" CHAR(4) NOT NULL,
"fddrp_desc" VARCHAR(100) NOT NULL
)
CREATE TABLE "food_des" (
"ndb_no" CHAR(5) NOT NULL,
"fdgrp_cd" CHAR(4) NOT NULL,
"long_desc" VARCHAR(100) NOT NULL,
"shrt_desc" VARCHAR(100) NOT NULL,
"comname" VARCHAR(100),
"manufacname" VARCHAR(100),
"survey" CHAR(1),
"ref_desc" VARCHAR(100),
"refuse" INT,
"sciname" VARCHAR(100),
"n_factor" INT,
"pro_factor" INT,
"fat_factor" INT,
"cho_factor" INT
)
CREATE TABLE "footnote" (
"ndb_no" CHAR(5) NOT NULL,
"footnt_no" CHAR(4) NOT NULL,
"footnt_typ" CHAR(1) NOT NULL,
"nutr_no" CHAR(3),
"footnt_txt" VARCHAR(100) NOT NULL
)
CREATE TABLE "nut_data" (
"ndb_no" CHAR(5) UNIQUE NOT NULL,
"nutr_no" CHAR(3) NOT NULL,
"nutr_val" INT NOT NULL,
"num_data_pts" INT NOT NULL,
"std_error" INT,
"src_cd" INT NOT NULL,
"deriv_cd" VARCHAR(100),
"ref_ndb_no" CHAR(5),
"add_nutr_mark" CHAR(1),
"num_studies" INT,
"min" INT,
"max" INT,
"df" INT,
"low_eb" INT,
"up_eb" INT,
"stat_cmt" VARCHAR(100),
"cc" CHAR(1)
)
CREATE TABLE "nutr_def" (
"nutr_no" CHAR(3) NOT NULL,
"units" VARCHAR(100) NOT NULL,
"tagname" VARCHAR(100),
"nutrdesc" VARCHAR(100),
"num_dec" SMALLINT,
"sr_order" INT
)
CREATE TABLE "src_cd" (
"src_cd" INT NOT NULL,
"srccd_desc" VARCHAR(100) NOT NULL
)
CREATE TABLE "weight" (
"ndb_no" CHAR(5) NOT NULL,
"seq" CHAR(2) NOT NULL,
"amount" INT NOT NULL,
"msre_desc" VARCHAR(100) NOT NULL,
"gm_wgt" INT NOT NULL,
"num_data_pts" INT,
"std_dev" INT
)
|
WebJack.Profiles = {
// default SoftModem frequencies, no echo cancellation to avoid attenuation
SoftModem : {
baud : 1225,
freqLow : 4900,
freqHigh : 7350,
echoCancellation : false,
softmodem : true
},
// lower frequencies and echo cancellation: try this to reduce crosstalk for long cables
<API key> : {
baud : 1225,
freqLow : 2450,
freqHigh : 4900,
echoCancellation : true,
softmodem : true
},
// browser-to-browser, over-the-air transmission profile
Browser : {
baud : 1225,
freqLow : 19600,
freqHigh : 20825,
echoCancellation : false,
softmodem : false
}
}
|
# Don't edit this file! Your changes will be overwritten when you re-save the Projucer project!
# build with "V=1" for verbose builds
ifeq ($(V), 1)
V_AT =
else
V_AT = @
endif
# (this disables dependency generation if multiple architectures are set)
DEPFLAGS := $(if $(word 2, $(TARGET_ARCH)), , -MMD)
ifndef STRIP
STRIP=strip
endif
ifndef AR
AR=ar
endif
ifndef CONFIG
CONFIG=Debug
endif
ifeq ($(CONFIG),Debug)
JUCE_BINDIR := build
JUCE_LIBDIR := build
JUCE_OBJDIR := build/intermediate/Debug
JUCE_OUTDIR := build
ifeq ($(TARGET_ARCH),)
TARGET_ARCH := -march=native
endif
JUCE_CPPFLAGS := $(DEPFLAGS) -DLINUX=1 -DDEBUG=1 -D_DEBUG=1 -<API key>=1 -DJUCE_APP_VERSION=1.0.0 -<API key>=0x10000 $(shell pkg-config --cflags alsa freetype2 libcurl x11 xext xinerama webkit2gtk-4.0 gtk+-x11-3.0) -pthread -I../../JuceLibraryCode -I../../../../../modules $(CPPFLAGS)
JUCE_CPPFLAGS_APP := -<API key>=0 -<API key>=0 -<API key>=0 -<API key>=0 -<API key>=0 -<API key>=0 -<API key>=0
JUCE_TARGET_APP := BlocksMonitor
JUCE_CFLAGS += $(JUCE_CPPFLAGS) $(TARGET_ARCH) -g -ggdb -O0 $(CFLAGS)
JUCE_CXXFLAGS += $(JUCE_CFLAGS) -std=c++11 $(CXXFLAGS)
JUCE_LDFLAGS += $(TARGET_ARCH) -L$(JUCE_BINDIR) -L$(JUCE_LIBDIR) $(shell pkg-config --libs alsa freetype2 libcurl x11 xext xinerama webkit2gtk-4.0 gtk+-x11-3.0) -lGL -ldl -lpthread -lrt $(LDFLAGS)
CLEANCMD = rm -rf $(JUCE_OUTDIR)/$(TARGET) $(JUCE_OBJDIR)
endif
ifeq ($(CONFIG),Release)
JUCE_BINDIR := build
JUCE_LIBDIR := build
JUCE_OBJDIR := build/intermediate/Release
JUCE_OUTDIR := build
ifeq ($(TARGET_ARCH),)
TARGET_ARCH := -march=native
endif
JUCE_CPPFLAGS := $(DEPFLAGS) -DLINUX=1 -DNDEBUG=1 -<API key>=1 -DJUCE_APP_VERSION=1.0.0 -<API key>=0x10000 $(shell pkg-config --cflags alsa freetype2 libcurl x11 xext xinerama webkit2gtk-4.0 gtk+-x11-3.0) -pthread -I../../JuceLibraryCode -I../../../../../modules $(CPPFLAGS)
JUCE_CPPFLAGS_APP := -<API key>=0 -<API key>=0 -<API key>=0 -<API key>=0 -<API key>=0 -<API key>=0 -<API key>=0
JUCE_TARGET_APP := BlocksMonitor
JUCE_CFLAGS += $(JUCE_CPPFLAGS) $(TARGET_ARCH) -O3 $(CFLAGS)
JUCE_CXXFLAGS += $(JUCE_CFLAGS) -std=c++11 $(CXXFLAGS)
JUCE_LDFLAGS += $(TARGET_ARCH) -L$(JUCE_BINDIR) -L$(JUCE_LIBDIR) $(shell pkg-config --libs alsa freetype2 libcurl x11 xext xinerama webkit2gtk-4.0 gtk+-x11-3.0) -fvisibility=hidden -lGL -ldl -lpthread -lrt $(LDFLAGS)
CLEANCMD = rm -rf $(JUCE_OUTDIR)/$(TARGET) $(JUCE_OBJDIR)
endif
OBJECTS_APP := \
$(JUCE_OBJDIR)/Main_90ebc5c2.o \
$(JUCE_OBJDIR)/<API key>.o \
$(JUCE_OBJDIR)/<API key>.o \
$(JUCE_OBJDIR)/<API key>.o \
$(JUCE_OBJDIR)/<API key>.o \
$(JUCE_OBJDIR)/<API key>.o \
$(JUCE_OBJDIR)/<API key>.o \
$(JUCE_OBJDIR)/<API key>.o \
$(JUCE_OBJDIR)/<API key>.o \
$(JUCE_OBJDIR)/<API key>.o \
$(JUCE_OBJDIR)/<API key>.o \
$(JUCE_OBJDIR)/<API key>.o \
$(JUCE_OBJDIR)/<API key>.o \
$(JUCE_OBJDIR)/<API key>.o \
.PHONY: clean all
all : $(JUCE_OUTDIR)/$(JUCE_TARGET_APP)
$(JUCE_OUTDIR)/$(JUCE_TARGET_APP) : check-pkg-config $(OBJECTS_APP) $(RESOURCES)
@echo Linking "BlocksMonitor - App"
-$(V_AT)mkdir -p $(JUCE_BINDIR)
-$(V_AT)mkdir -p $(JUCE_LIBDIR)
-$(V_AT)mkdir -p $(JUCE_OUTDIR)
$(V_AT)$(CXX) -o $(JUCE_OUTDIR)/$(JUCE_TARGET_APP) $(OBJECTS_APP) $(JUCE_LDFLAGS) $(RESOURCES) $(TARGET_ARCH)
$(JUCE_OBJDIR)/Main_90ebc5c2.o: ../../Source/Main.cpp
-$(V_AT)mkdir -p $(JUCE_OBJDIR)
@echo "Compiling Main.cpp"
$(V_AT)$(CXX) $(JUCE_CXXFLAGS) $(JUCE_CPPFLAGS_APP) $(JUCE_CFLAGS_APP) -o "$@" -c "$<"
$(JUCE_OBJDIR)/<API key>.o: ../../JuceLibraryCode/<API key>.cpp
-$(V_AT)mkdir -p $(JUCE_OBJDIR)
@echo "Compiling <API key>.cpp"
$(V_AT)$(CXX) $(JUCE_CXXFLAGS) $(JUCE_CPPFLAGS_APP) $(JUCE_CFLAGS_APP) -o "$@" -c "$<"
$(JUCE_OBJDIR)/<API key>.o: ../../JuceLibraryCode/<API key>.cpp
-$(V_AT)mkdir -p $(JUCE_OBJDIR)
@echo "Compiling <API key>.cpp"
$(V_AT)$(CXX) $(JUCE_CXXFLAGS) $(JUCE_CPPFLAGS_APP) $(JUCE_CFLAGS_APP) -o "$@" -c "$<"
$(JUCE_OBJDIR)/<API key>.o: ../../JuceLibraryCode/<API key>.cpp
-$(V_AT)mkdir -p $(JUCE_OBJDIR)
@echo "Compiling <API key>.cpp"
$(V_AT)$(CXX) $(JUCE_CXXFLAGS) $(JUCE_CPPFLAGS_APP) $(JUCE_CFLAGS_APP) -o "$@" -c "$<"
$(JUCE_OBJDIR)/<API key>.o: ../../JuceLibraryCode/<API key>.cpp
-$(V_AT)mkdir -p $(JUCE_OBJDIR)
@echo "Compiling <API key>.cpp"
$(V_AT)$(CXX) $(JUCE_CXXFLAGS) $(JUCE_CPPFLAGS_APP) $(JUCE_CFLAGS_APP) -o "$@" -c "$<"
$(JUCE_OBJDIR)/<API key>.o: ../../JuceLibraryCode/<API key>.cpp
-$(V_AT)mkdir -p $(JUCE_OBJDIR)
@echo "Compiling <API key>.cpp"
$(V_AT)$(CXX) $(JUCE_CXXFLAGS) $(JUCE_CPPFLAGS_APP) $(JUCE_CFLAGS_APP) -o "$@" -c "$<"
$(JUCE_OBJDIR)/<API key>.o: ../../JuceLibraryCode/<API key>.cpp
-$(V_AT)mkdir -p $(JUCE_OBJDIR)
@echo "Compiling <API key>.cpp"
$(V_AT)$(CXX) $(JUCE_CXXFLAGS) $(JUCE_CPPFLAGS_APP) $(JUCE_CFLAGS_APP) -o "$@" -c "$<"
$(JUCE_OBJDIR)/<API key>.o: ../../JuceLibraryCode/include_juce_core.cpp
-$(V_AT)mkdir -p $(JUCE_OBJDIR)
@echo "Compiling include_juce_core.cpp"
$(V_AT)$(CXX) $(JUCE_CXXFLAGS) $(JUCE_CPPFLAGS_APP) $(JUCE_CFLAGS_APP) -o "$@" -c "$<"
$(JUCE_OBJDIR)/<API key>.o: ../../JuceLibraryCode/<API key>.cpp
-$(V_AT)mkdir -p $(JUCE_OBJDIR)
@echo "Compiling <API key>.cpp"
$(V_AT)$(CXX) $(JUCE_CXXFLAGS) $(JUCE_CPPFLAGS_APP) $(JUCE_CFLAGS_APP) -o "$@" -c "$<"
$(JUCE_OBJDIR)/<API key>.o: ../../JuceLibraryCode/include_juce_events.cpp
-$(V_AT)mkdir -p $(JUCE_OBJDIR)
@echo "Compiling include_juce_events.cpp"
$(V_AT)$(CXX) $(JUCE_CXXFLAGS) $(JUCE_CPPFLAGS_APP) $(JUCE_CFLAGS_APP) -o "$@" -c "$<"
$(JUCE_OBJDIR)/<API key>.o: ../../JuceLibraryCode/<API key>.cpp
-$(V_AT)mkdir -p $(JUCE_OBJDIR)
@echo "Compiling <API key>.cpp"
$(V_AT)$(CXX) $(JUCE_CXXFLAGS) $(JUCE_CPPFLAGS_APP) $(JUCE_CFLAGS_APP) -o "$@" -c "$<"
$(JUCE_OBJDIR)/<API key>.o: ../../JuceLibraryCode/<API key>.cpp
-$(V_AT)mkdir -p $(JUCE_OBJDIR)
@echo "Compiling <API key>.cpp"
$(V_AT)$(CXX) $(JUCE_CXXFLAGS) $(JUCE_CPPFLAGS_APP) $(JUCE_CFLAGS_APP) -o "$@" -c "$<"
$(JUCE_OBJDIR)/<API key>.o: ../../JuceLibraryCode/<API key>.cpp
-$(V_AT)mkdir -p $(JUCE_OBJDIR)
@echo "Compiling <API key>.cpp"
$(V_AT)$(CXX) $(JUCE_CXXFLAGS) $(JUCE_CPPFLAGS_APP) $(JUCE_CFLAGS_APP) -o "$@" -c "$<"
$(JUCE_OBJDIR)/<API key>.o: ../../JuceLibraryCode/include_juce_opengl.cpp
-$(V_AT)mkdir -p $(JUCE_OBJDIR)
@echo "Compiling include_juce_opengl.cpp"
$(V_AT)$(CXX) $(JUCE_CXXFLAGS) $(JUCE_CPPFLAGS_APP) $(JUCE_CFLAGS_APP) -o "$@" -c "$<"
check-pkg-config:
@command -v pkg-config >/dev/null 2>&1 || { echo >&2 "pkg-config not installed. Please, install it."; exit 1; }
@pkg-config --print-errors alsa freetype2 libcurl x11 xext xinerama webkit2gtk-4.0 gtk+-x11-3.0
clean:
@echo Cleaning BlocksMonitor
$(V_AT)$(CLEANCMD)
strip:
@echo Stripping BlocksMonitor
-$(V_AT)$(STRIP) --strip-unneeded $(JUCE_OUTDIR)/$(TARGET)
-include $(OBJECTS_APP:%.o=%.d)
|
/**
* Distance measure that takes into account the decrease of the Euclidean
* distance with increasing latitude of the reference point.
*
* @author Ralf Quast
*/
public final class SinusoidalDistance implements DistanceMeasure {
private final double lon0;
private final double lat0;
private final double lonFactor;
public SinusoidalDistance(double lon0, double lat0) {
this.lon0 = lon0;
this.lat0 = lat0;
this.lonFactor = Math.cos(Math.toRadians(lat0));
}
@Override
public double distance(double lon, double lat) {
double deltaLat = lat - lat0;
double deltaLon = lon - lon0;
if (deltaLon < 0.0) {
deltaLon = -deltaLon;
}
if (deltaLon > 180.0) {
deltaLon = 360.0 - deltaLon;
}
deltaLon *= lonFactor;
return deltaLat * deltaLat + deltaLon * deltaLon;
}
}
|
<?php
class <API key> extends <API key>
{
public function setUp()
{
$this->bootstrap = new Zend_Application(APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini');
parent::setUp();
}
public function testIndexAction()
{
$params = array('action' => 'index', 'controller' => 'DojoDndSource', 'module' => 'elements');
$urlParams = $this->urlizeOptions($params);
$url = $this->url($urlParams);
$this->dispatch($url);
// assertions
$this->assertModule($urlParams['module']);
$this->assertController($urlParams['controller']);
$this->assertAction($urlParams['action']);
$this-><API key>(
'div#view-content p',
'View script for controller <b>' . $params['controller'] . '</b> and script/action name <b>' . $params['action'] . '</b>'
);
}
}
|
<!-- Modal -->
<div class="modal fade" id="helpModal" tabindex="-1" role="dialog" aria-labelledby="helpModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="fa fa-times"></i></button>
<h4 class="modal-title" id="helpModalLabel">Instructions</h4>
</div>
<div class="modal-body">
<h1>Editing lane or task names</h1>
<p>Click on any text to start editing mode. The application will save your input automatically.</p>
<h1>Drag & Drop</h1>
<p>You are able to drag and sort tasks to every available lane in any order.</p>
<p><img src="@routes.Assets.at("images/help_dragndrop.jpg")" alt="drag and drop" /> </p>
<h1>Delete tasks</h1>
<p>You can delete task by hovering on a task and click the red cross.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
|
<?php
class <API key> implements <API key>
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(T_RETURN);
}//end register()
/**
* Processes this sniff, when one of its tokens is encountered.
*
* @param <API key> $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token in
* the stack passed in $tokens.
*
* @return void
*/
public function process(<API key> $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$functionName = $phpcsFile->findNext(T_STRING, ($stackPtr + 1), null, false, null, true);
while ($functionName !== false) {
// Check if this is really a function.
$bracket = $phpcsFile->findNext(T_WHITESPACE, ($functionName + 1), null, true);
if ($tokens[$bracket]['code'] !== T_OPEN_PARENTHESIS) {
// Not a function call.
$functionName = $phpcsFile->findNext(T_STRING, ($functionName + 1), null, false, null, true);
continue;
}
$error = 'The result of a function call should be assigned to a variable before being returned';
$phpcsFile->addWarning($error, $stackPtr, 'NotAssigned');
break;
}
}//end process()
}//end class
?>
|
package scavenger.app
import akka.actor.{ActorPath, ActorSystem}
import java.io.File
import com.typesafe.config._
/** Trait for programs with a `main`-function,
* that loads <API key>, creates actor system, starts actors.
*
* @since 2.1
* @author Andrey Tyukin
*/
private[app] trait ScavengerNode {
private var actorSystem: ActorSystem = _
/** Enables each type of node to provide a slightly different
* version of the configuration that is used to create the
* `ActorSystem`.
*/
private[app] def extractNodeConfig(generalConfig: Config): Config
/** Depending on the type of node, this method has to
* spawn a master/worker/seed actor in the `system`.
*
* The configuration is put together from the application configuration file
* and `reference.conf` in `resources` folder of Scavenger.
*/
private[app] def initializeActors(
system: ActorSystem,
nodeSpecificConfig: Config
): Unit
/** This method composes `ActorPath` of the seed node from various
* entries in the specified configuration.
*
* It makes use of the following entries in the `seed`-subconfig:
*
* {{{
* scavenger {
* seed {
* akka.remote.netty.tcp.hostname = "123.456.78.90"
* akka.remote.netty.tcp.port = "55555"
* }
* }
* }}}
*/
private[app] def extractSeedPath(generalConfig: Config): ActorPath = {
val seedConfig = generalConfig.getConfig("seed")
val seedIp = seedConfig.getString("akka.remote.netty.tcp.hostname")
val seedPort = seedConfig.getString("akka.remote.netty.tcp.port")
val seedPathStr = s"akka.tcp://scavenger@${seedIp}:${seedPort}/user/seed"
ActorPath.fromString(seedPathStr)
}
/** Loads configuration files and initializes an
* actor system, together with the right set of actors.
*
* TODO: this description is outdated
*
* The configuration files are loaded from the following paths:
*
* 1) /src/main/resources/reference.conf
* contains the default configuration for the framework. Works only
* for `<API key>`, because it does not contain an
* id of the seed node.
* This file is packaged inside the jar, and is therefore not accessible.
*
* 2) <API key> `scavenger.conf` file, that
* should be adjusted by the user. In particularly,
* IP and port of the seed node, as well as the directory for
* persisted intermediate results should be specified.
*
* 3) Following additional JVM-properties can be used to set the
* IP and port of worker nodes: -DnodeIp=123.456.0.78 -DnodePort=8765
*
* 4) All other parameters can be specified as JVM properties as well, but
* keep in mind that values in 'scavenger.conf' have higher precedence
* than anything else.
*
*/
def scavengerInit(): Unit = {
val conf = ConfigFactory.load()
// TODO: all this seemed to be a bad idea, just remove it completely
// use system property -Dconfig.file=/path/to/scavenger.conf instead
// of all this mess!
// val <API key> = System.getProperty("scavengerConfPath")
// val scavengerConfPath =
// if (<API key> == null) "scavenger.conf"
// else <API key>
// val scavengerConfFile = new File(scavengerConfPath)
// if (!scavengerConfFile.exists) {
// throw new <API key>("Could not find the user-modified " +
// "configuration file. Expected a path to this file passed as a " +
// "property to the jvm: " +
// "-DscavengerConfPath=/path/to/my/scavenger.conf"
// val userConf = ConfigFactory.parseFile(scavengerConfFile)
var generalConfig = ConfigFactory.empty()
try{
generalConfig =
conf.getConfig("scavenger") withFallback conf
} catch { // for backwards compatibility
case ex: ConfigException.Missing => {val userConf = ConfigFactory.parseFile(new File("scavenger.conf"))
generalConfig = userConf.getConfig("scavenger") withFallback conf
}
}
// referenceConf
val nodeSpecificConfig = extractNodeConfig(generalConfig)
actorSystem = ActorSystem("scavenger", nodeSpecificConfig)
initializeActors(actorSystem, nodeSpecificConfig)
}
def scavengerShutdown(): Unit = {
actorSystem.shutdown()
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace _213
{
public partial class frOrderConfirm : Form
{
public frOrderConfirm()
{
InitializeComponent();
}
private void frOrderConfirm_Load(object sender, EventArgs e)
{
gebruik util = new gebruik();
txtDayOrders.Text = util.getDayOrders(DateTime.Now.Date.ToString());
}
private void btnConfirmO_Click(object sender, EventArgs e)
{
gebruik util = new gebruik();
//verander net die voor toets
util.sendOrders(txtDayOrders.Text, "wiesupplieris", "supplier@gmail.com");
}
}
}
|
const glob = require('glob');
const path = require('path');
const merge = require('webpack-merge');
// Regular plugins
const pluginPattern1 = '../../graylog-plugin-*/webpack.config.js';
// Plugins where the web part is in a subdir
const pluginPattern2 = '../../graylog-plugin-*/*/webpack.config.js';
const pluginConfigs = process.env.disable_plugins == 'true' ? [] : glob.sync(pluginPattern1).concat(glob.sync(pluginPattern2));
process.env.web_src_path = path.resolve(__dirname);
module.exports = ['./webpack.config.js']
.concat(pluginConfigs)
.map(function(config) { return require(path.resolve(__dirname, config)); })
.reduce(function(config1, config2) {
return merge.smart(config2, config1);
});
|
#@+leo-ver=5-thin
#@+node:lee.20141223114246.40: * @file example2.py
#@@language python
#@@tabwidth -4
import cherrypy
import random
from std.asciisymbol import asciiImage
#@+others
#@+node:lee.20141223114246.41: ** class Application
class Application(object):
#@+others
#@+node:lee.20141223114246.42: *3* def init
def __init__(self):
self.name = ''
self.number = '40323208'
self.classes = ''
# github repository url
self.github_repo_url = 'https://github.com/40323208/<API key>.git'
# openshift app
self.openshift_url = 'http://b40323208-40323208.rhcloud.com/'
self.evaluation = [('', 80), ('', 78), ('', 80)]
# url
self.photo_url = 'https://copy.com/dKfcJJjroD1e'
self.my_remark = """
...TA
Github Openshift
: git pull git push
"""
#@+node:lee.20141223114246.43: *3* def use_template
def use_template(self, content):
return above + self.generate_nav(self.link()) + content + below
#@+node:lee.20141223114246.44: *3* def generate_nav
def generate_nav(self, anchors):
above_side = """
<div class="row">
<div class="nav twelve columns">
<input type="checkbox" id="toggle" />
<div>
<label for="toggle" class="toggle" data-open="Main Menu" data-close="Close Menu" onclick></label>
<ul class="menu">
"""
content = ''
for link, name in anchors:
content += '<li><a href="' + link + '">' + name + '</a></li>'
below_side = """
</ul>
</div>
</div>
</div>
"""
return above_side + content + below_side
#@+node:lee.20141223114246.45: *3* def generate_form_page
def generate_form_page(self, form='', output=''):
content = """
<div class="content">
<div class="row">
<div class="one-half column">
%s
</div>
<div class="one-half column">
<div class="output u-full-width">
<p>Output:</p>
<p>
%s
</p>
</div>
</div>
</div>
</div>
"""%(form, output)
return self.use_template(content)
#@+node:lee.20141223114246.55: *3* def <API key>
def <API key>(self, headline, output):
content = """
<div class="content">
<div class="row">
<div class="headline center">%s</div>
<div class="twelve columns">
<p>%s</p>
</div>
</div>
</div>
""" % (headline, output)
return self.use_template(content)
#@+node:lee.20141223114246.46: *3* def <API key>
def <API key>(self, data=None):
if data is None:
return ''
# check data have all we need, if the key not exist, use empty string
must_have_key = ('photo_url', 'name', 'ID', 'class', 'evaluation')
for key in must_have_key:
data[key] = data.get(key, '')
if 'evaluation' in data:
table_content = ''
for projectName, score in data['evaluation']:
table_content += """<tr><td>%s</td><td>%s</td>"""%(projectName, score)
data['evaluation'] = table_content
content = """
<div class="content">
<div class="row">
<div class="one-half column">
<div class="headline">
About Me
</div>
<div class="photo">
<img src="{photo_url:s}" alt="photo">
</div>
<div class="meta">
<ul>
<li>Name: {name:s}</li>
<li>ID NO. : {ID:s}</li>
<li>Class: {class:s}</li>
</ul>
</div>
</div>
<div class="one-half column">
<div class="headline">
Self Evaluation
</div>
<div>
<table class="u-full-width">
<thead>
<tr>
<th>Project Name</th>
<th>Score</th>
</tr>
</thead>
<tbody>
{evaluation:s}
</tbody>
</table>
</div>
</div>
</div>
</div>
""".format(**data)
return self.use_template(content)
#@+node:lee.20141223114246.47: *3* def link
def link(self):
aviable_link = [("index", "HOME"), ("remark", ""), (self.openshift_url, "openshift app"),(self.github_repo_url, "github repo"),]
return aviable_link
#@+node:lee.20141223114246.54: *3* def remark
@cherrypy.expose
def remark(self):
# <API key>(, )
return self.<API key>("REMARK", self.my_remark)
#@+node:lee.20141223114246.48: *3* def index
@cherrypy.expose
def index(self):
data = {
'name':self.name,
'ID':self.number,
'class':self.classes,
'evaluation': self.evaluation,
'photo_url':self.photo_url,
}
return self.<API key>(data)
#@-others
#@-others
#@-leo
|
#pragma once
#include "hal/abs_rxtx.h"
namespace rp{ namespace arch{ namespace net{
class raw_serial : public rp::hal::serial_rxtx
{
public:
enum{
<API key> = 512,
<API key> = 128,
};
raw_serial();
virtual ~raw_serial();
virtual bool bind(const char * portname, uint32_t baudrate, uint32_t flags = 0);
virtual bool open();
virtual void close();
virtual void flush( _u32 flags);
virtual int waitfordata(_word_size_t data_count,_u32 timeout = -1, _word_size_t * returned_size = NULL);
virtual int senddata(const unsigned char * data, _word_size_t size);
virtual int recvdata(unsigned char * data, _word_size_t size);
virtual int waitforsent(_u32 timeout = -1, _word_size_t * returned_size = NULL);
virtual int waitforrecv(_u32 timeout = -1, _word_size_t * returned_size = NULL);
virtual size_t rxqueue_count();
_u32 getTermBaudBitmap(_u32 baud);
protected:
bool open(const char * portname, uint32_t baudrate, uint32_t flags = 0);
void _init();
char _portName[200];
uint32_t _baudrate;
uint32_t _flags;
int serial_fd;
size_t required_tx_cnt;
size_t required_rx_cnt;
};
}}}
|
package org.thoughtcrime.securesms.database;
import android.app.Application;
import android.content.Context;
import android.database.Cursor;
import android.text.TextUtils;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.facebook.flipper.plugins.databases.DatabaseDescriptor;
import com.facebook.flipper.plugins.databases.DatabaseDriver;
import net.zetetic.database.DatabaseUtils;
import net.zetetic.database.sqlcipher.SQLiteDatabase;
import net.zetetic.database.sqlcipher.SQLiteStatement;
import org.signal.core.util.logging.Log;
import org.thoughtcrime.securesms.util.Hex;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* A lot of this code is taken from {@link com.facebook.flipper.plugins.databases.impl.<API key>}
* and made to work with SqlCipher. Unfortunately I couldn't use it directly, nor subclass it.
*/
public class <API key> extends DatabaseDriver<<API key>.Descriptor> {
private static final String TAG = Log.tag(<API key>.class);
public <API key>(Context context) {
super(context);
}
@Override
public List<Descriptor> getDatabases() {
try {
<API key> mainOpenHelper = Objects.requireNonNull(SignalDatabase.getInstance());
<API key> keyValueOpenHelper = KeyValueDatabase.getInstance((Application) getContext());
<API key> megaphoneOpenHelper = MegaphoneDatabase.getInstance((Application) getContext());
<API key> <API key> = JobDatabase.getInstance((Application) getContext());
<API key> metricsOpenHelper = <API key>.getInstance((Application) getContext());
return Arrays.asList(new Descriptor(mainOpenHelper),
new Descriptor(keyValueOpenHelper),
new Descriptor(megaphoneOpenHelper),
new Descriptor(<API key>),
new Descriptor(metricsOpenHelper));
} catch (Exception e) {
Log.i(TAG, "Unable to use reflection to access raw database.", e);
}
return Collections.emptyList();
}
@Override
public List<String> getTableNames(Descriptor descriptor) {
SQLiteDatabase db = descriptor.getReadable();
List<String> tableNames = new ArrayList<>();
try (Cursor cursor = db.rawQuery("SELECT name FROM sqlite_master WHERE type IN (?, ?)", new String[] { "table", "view" })) {
while (cursor != null && cursor.moveToNext()) {
tableNames.add(cursor.getString(0));
}
}
return tableNames;
}
@Override
public <API key> getTableData(Descriptor descriptor, String table, String order, boolean reverse, int start, int count) {
SQLiteDatabase db = descriptor.getReadable();
long total = DatabaseUtils.queryNumEntries(db, table);
String orderBy = order != null ? order + (reverse ? " DESC" : " ASC") : null;
String limitBy = start + ", " + count;
try (Cursor cursor = db.query(table, null, null, null, null, null, orderBy, limitBy)) {
String[] columnNames = cursor.getColumnNames();
List<List<Object>> rows = cursorToList(cursor);
return new <API key>(Arrays.asList(columnNames), rows, start, rows.size(), total);
}
}
@Override
public <API key> getTableStructure(Descriptor descriptor, String table) {
SQLiteDatabase db = descriptor.getReadable();
Map<String, String> foreignKeyValues = new HashMap<>();
try(Cursor cursor = db.rawQuery("PRAGMA foreign_key_list(" + table + ")", null)) {
while (cursor != null && cursor.moveToNext()) {
String from = cursor.getString(cursor.getColumnIndex("from"));
String to = cursor.getString(cursor.getColumnIndex("to"));
String tableName = cursor.getString(cursor.getColumnIndex("table")) + "(" + to + ")";
foreignKeyValues.put(from, tableName);
}
}
List<String> structureColumns = Arrays.asList("column_name", "data_type", "nullable", "default", "primary_key", "foreign_key");
List<List<Object>> structureValues = new ArrayList<>();
try (Cursor cursor = db.rawQuery("PRAGMA table_info(" + table + ")", null)) {
while (cursor != null && cursor.moveToNext()) {
String columnName = cursor.getString(cursor.getColumnIndex("name"));
String foreignKey = foreignKeyValues.containsKey(columnName) ? foreignKeyValues.get(columnName) : null;
structureValues.add(Arrays.asList(columnName,
cursor.getString(cursor.getColumnIndex("type")),
cursor.getInt(cursor.getColumnIndex("notnull")) == 0,
<API key>(cursor, cursor.getColumnIndex("dflt_value")),
cursor.getInt(cursor.getColumnIndex("pk")) == 1,
foreignKey));
}
}
List<String> indexesColumns = Arrays.asList("index_name", "unique", "indexed_column_name");
List<List<Object>> indexesValues = new ArrayList<>();
try (Cursor indexesCursor = db.rawQuery("PRAGMA index_list(" + table + ")", null)) {
List<String> indexedColumnNames = new ArrayList<>();
String indexName = indexesCursor.getString(indexesCursor.getColumnIndex("name"));
try(Cursor indexInfoCursor = db.rawQuery("PRAGMA index_info(" + indexName + ")", null)) {
while (indexInfoCursor.moveToNext()) {
indexedColumnNames.add(indexInfoCursor.getString(indexInfoCursor.getColumnIndex("name")));
}
}
indexesValues.add(Arrays.asList(indexName,
indexesCursor.getInt(indexesCursor.getColumnIndex("unique")) == 1,
TextUtils.join(",", indexedColumnNames)));
}
return new <API key>(structureColumns, structureValues, indexesColumns, indexesValues);
}
@Override
public <API key> getTableInfo(Descriptor databaseDescriptor, String table) {
SQLiteDatabase db = databaseDescriptor.getReadable();
try (Cursor cursor = db.rawQuery("SELECT sql FROM sqlite_master WHERE name = ?", new String[] { table })) {
cursor.moveToFirst();
return new <API key>(cursor.getString(cursor.getColumnIndex("sql")));
}
}
@Override
public <API key> executeSQL(Descriptor descriptor, String query) {
SQLiteDatabase db = descriptor.getWritable();
String firstWordUpperCase = getFirstWord(query).toUpperCase();
switch (firstWordUpperCase) {
case "UPDATE":
case "DELETE":
return executeUpdateDelete(db, query);
case "INSERT":
return executeInsert(db, query);
case "SELECT":
case "PRAGMA":
case "EXPLAIN":
return executeSelect(db, query);
default:
return executeRawQuery(db, query);
}
}
private static String getFirstWord(String s) {
s = s.trim();
int firstSpace = s.indexOf(' ');
return firstSpace >= 0 ? s.substring(0, firstSpace) : s;
}
private static <API key> executeUpdateDelete(SQLiteDatabase database, String query) {
SQLiteStatement statement = database.compileStatement(query);
int count = statement.executeUpdateDelete();
return <API key>.<API key>(count);
}
private static <API key> executeInsert(SQLiteDatabase database, String query) {
SQLiteStatement statement = database.compileStatement(query);
long insertedId = statement.executeInsert();
return <API key>.successfulInsert(insertedId);
}
private static <API key> executeSelect(SQLiteDatabase database, String query) {
try (Cursor cursor = database.rawQuery(query, null)) {
String[] columnNames = cursor.getColumnNames();
List<List<Object>> rows = cursorToList(cursor);
return <API key>.successfulSelect(Arrays.asList(columnNames), rows);
}
}
private static <API key> executeRawQuery(SQLiteDatabase database, String query) {
database.execSQL(query);
return <API key>.successfulRawQuery();
}
private static @NonNull List<List<Object>> cursorToList(Cursor cursor) {
List<List<Object>> rows = new ArrayList<>();
int numColumns = cursor.getColumnCount();
while (cursor.moveToNext()) {
List<Object> values = new ArrayList<>(numColumns);
for (int column = 0; column < numColumns; column++) {
values.add(<API key>(cursor, column));
}
rows.add(values);
}
return rows;
}
private static @Nullable Object <API key>(Cursor cursor, int column) {
switch (cursor.getType(column)) {
case Cursor.FIELD_TYPE_NULL:
return null;
case Cursor.FIELD_TYPE_INTEGER:
return cursor.getLong(column);
case Cursor.FIELD_TYPE_FLOAT:
return cursor.getDouble(column);
case Cursor.FIELD_TYPE_BLOB:
byte[] blob = cursor.getBlob(column);
String bytes = blob != null ? "(blob) " + Hex.toStringCondensed(Arrays.copyOf(blob, Math.min(blob.length, 32))) : null;
if (bytes != null && bytes.length() == 32 && blob.length > 32) {
bytes += "...";
}
return bytes;
case Cursor.FIELD_TYPE_STRING:
default:
return cursor.getString(column);
}
}
static class Descriptor implements DatabaseDescriptor {
private final <API key> sqlCipherOpenHelper;
Descriptor(@NonNull <API key> sqlCipherOpenHelper) {
this.sqlCipherOpenHelper = sqlCipherOpenHelper;
}
@Override
public String name() {
return sqlCipherOpenHelper.getDatabaseName();
}
public @NonNull SQLiteDatabase getReadable() {
return sqlCipherOpenHelper.<API key>();
}
public @NonNull SQLiteDatabase getWritable() {
return sqlCipherOpenHelper.<API key>();
}
}
}
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import matplotlib.pyplot as plt
def plot_diagram(plot_data, x, y, size='Size'):
fig, ax = plt.subplots()
ax = plot_data.plot.scatter(
x,
y,
s=plot_data[size] * 100,
alpha=0.7,
title="Portfolio-Analyse",
figsize=[10,7],
fontsize=14,
ax=ax
)
ax.title.set_size(24)
plt.xlabel(x, fontsize=18)
plt.ylabel(y, fontsize=18)
# plot vertical axis
ax.plot(
[plot_data[x].max()/2, plot_data[x].max()/2],
[0, plot_data[y].max()], color='k', linestyle='--', linewidth=0.6)
# plot horizonzal axis
ax.plot(
[0, plot_data[x].max()],
[plot_data[y].max()/2,plot_data[y].max()/2], color='k', linestyle='--', linewidth=0.6)
# plot fields' key words
ax.text(plot_data[x].max()*1/4, plot_data[y].max()*3/4, "Strengths", ha="center", fontsize=24)
ax.text(plot_data[x].max()*3/4, plot_data[y].max()*3/4, "Weaknesses", ha="center", fontsize=24)
ax.text(plot_data[x].max()*1/4, plot_data[y].max()*1/4, "Opportunities", ha="center", fontsize=24)
ax.text(plot_data[x].max()*3/4, plot_data[y].max()*1/4, "Threats", ha="center", fontsize=24)
for k, v in plot_data[[x, y]].iterrows():
ax.annotate(k, v, horizontalalignment='center', verticalalignment='middle', fontsize=14)
return ax
|
<!
title: "Icecast monitoring with Netdata"
custom_edit_url: https://github.com/netdata/netdata/edit/master/collectors/python.d.plugin/icecast/README.md
sidebar_label: "Icecast"
# Icecast monitoring with Netdata
Monitors the number of listeners for active sources.
## Requirements
- icecast version >= 2.4.0
It produces the following charts:
1. **Listeners** in listeners
- source number
## Configuration
Edit the `python.d/icecast.conf` configuration file using `edit-config` from the Netdata [config
directory](/docs/configure/nodes.md), which is typically at `/etc/netdata`.
bash
cd /etc/netdata # Replace this path with your Netdata config directory, if different
sudo ./edit-config python.d/icecast.conf
Needs only `url` to server's `/status-json.xsl`
Here is an example for remote server:
yaml
remote:
url : 'http://1.2.3.4:8443/status-json.xsl'
Without configuration, module attempts to connect to `http://localhost:8443/status-json.xsl`
[;
-- Vampiric Touch (Dispelled) Bonus Data
DELETE FROM `spell_bonus_data` WHERE `entry`=64085;
INSERT INTO `spell_bonus_data` VALUES
(64085,1.2,-1,-1,-1,'Priest - Vampiric Touch (Dispelled)');
|
package com.openmeap.model;
import java.sql.SQLException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.<API key>;
import javax.persistence.Query;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import com.openmeap.event.ProcessingEvent;
import com.openmeap.model.dto.Application;
import com.openmeap.model.dto.ApplicationArchive;
import com.openmeap.model.dto.ApplicationVersion;
import com.openmeap.model.dto.Deployment;
/**
* Intended to basically pass-through to the entity manager.
*
* Implemented with the idea that a different persistence
* mechanism might one day be used.
*
* @author schang
*/
@Transactional
public class ModelServiceImpl implements ModelService
{
private Logger logger = LoggerFactory.getLogger(ModelServiceImpl.class);
private EntityManager entityManager = null;
/**
* Number of times to retry refreshing a model entity before failing the operation.
* Using SQLite, sometimes the database file is locked by another process.
*/
private int <API key>=3;
/**
* Amount of time to wait between each refresh retry.
*/
private int <API key>=250;
public void <API key>() {
entityManager.clear();
}
@Override
public <T extends ModelEntity> T saveOrUpdate(T entity) throws <API key> {
T entityToReturn = entity;
try {
// if we haven't loaded this object yet,
// then attempt to do so
if( ! entityManager.contains(entity) ) {
entityToReturn = entityManager.merge(entity);
}
entityManager.persist(entityToReturn);
} catch( <API key> pe ) {
throw new <API key>(pe);
}
return entityToReturn;
}
@Override
public <T extends ModelEntity> void delete(T obj2Delete) throws <API key> {
_delete(obj2Delete,null);
}
@Override
public <T extends ModelEntity> void refresh(T entity) throws <API key> {
int numRetries = <API key>;
boolean notSuccessful = false;
do {
try{
if(entity!=null) {
this._refresh(entity);
}
} catch(Exception e) {
Throwable t = ExceptionUtils.getRootCause(e);
if(!(t instanceof SQLException)) {
throw new <API key>(e);
}
logger.warn("Unable to refresh model entity, "+numRetries+" left. "+t.getMessage());
numRetries
notSuccessful=true;
try {
Thread.sleep(<API key>);
} catch (<API key> e1) {
throw new <API key>("Thread sleep interrupted during the refresh retry interval: "+e1.getMessage(),e1);
}
}
} while(notSuccessful && numRetries!=0);
if(numRetries==0) {
throw new <API key>("Unable to refresh model entity. "+<API key>+" retries failed");
}
}
@SuppressWarnings("unchecked")
public <T extends ModelEntity> T findByPrimaryKey(Class<T> clazz, Object pk) {
try {
T obj = (T)entityManager.find(clazz, pk);
return obj;
} catch( NoResultException nre ) {
return null;
}
}
@SuppressWarnings("unchecked")
public <T extends ModelEntity> List<T> findAll(Class<T> clazz) {
Query q = entityManager.createQuery("select distinct a from "+clazz.getCanonicalName()+" a");
try {
return q.getResultList();
} catch( NoResultException nre ) {
return null;
}
}
@Override
public Application <API key>(String name) {
Query q = entityManager.createQuery("select distinct a "
+"from Application a "
+"where a.name=:name");
q.setParameter("name", name);
try {
return (Application)q.getSingleResult();
} catch( NoResultException nre ) {
return null;
}
}
@Override
public ApplicationVersion <API key>(String appName, String identifier) {
Query q = entityManager.createQuery("select distinct av "
+"from ApplicationVersion av "
+"inner join fetch av.application a "
+"where av.identifier=:identifier "
+"and a.name=:name");
q.setParameter("name", appName);
q.setParameter("identifier", identifier);
try {
ApplicationVersion ver = (ApplicationVersion)q.getSingleResult();
return ver;
} catch( NoResultException nre ) {
return null;
}
}
@Override
public List<Deployment> <API key>(Application app) {
Query q = entityManager.createQuery("select d "
+"from Deployment d "
+"inner join fetch d.applicationArchive aa "
+"inner join d.application a "
+"where a.name=:name");
q.setParameter("name", app.getName());
try {
@SuppressWarnings(value={"unchecked"})
List<Deployment> deployments = (List<Deployment>)q.getResultList();
return deployments;
} catch( NoResultException nre ) {
return null;
}
}
@Override
public List<Deployment> <API key>(ApplicationArchive archive) {
Query q = entityManager.createQuery("select distinct d "
+"from Deployment d "
+"inner join fetch d.applicationArchive aa "
+"where aa.id=:id" );
q.setParameter("id", archive.getId());
try {
@SuppressWarnings(value={"unchecked"})
List<Deployment> deployments = (List<Deployment>)q.getResultList();
return deployments;
} catch( NoResultException nre ) {
return null;
}
}
@Override
public List<ApplicationVersion> <API key>(ApplicationArchive archive) {
Query q = entityManager.createQuery("select distinct av "
+"from ApplicationVersion av "
+"inner join fetch av.archive aa "
+"where aa.id=:id " );
q.setParameter("id", archive.getId());
try {
@SuppressWarnings(value={"unchecked"})
List<ApplicationVersion> versions = (List<ApplicationVersion>)q.getResultList();
return versions;
} catch( NoResultException nre ) {
return null;
}
}
@Override
public Deployment getLastDeployment(Application app) {
Query q = entityManager.createQuery("select distinct d "
+"from Deployment d join d.application "
+"where d.application.id=:id "
+"order by d.createDate desc");
q.setParameter("id", app.getId());
q.setMaxResults(1);
try {
Object o = q.getSingleResult();
return (Deployment)o;
} catch( NoResultException nre ) {
return null;
}
}
@Override
public ApplicationArchive <API key>(Deployment depl) {
Query q = entityManager.createQuery("select distinct aa "
+"from ApplicationArchive aa, Deployment d "
+"where d.applicationArchive=aa and d.id=:id ");
q.setParameter("id", depl.getId());
q.setMaxResults(1);
try {
Object o = q.getSingleResult();
return ((ApplicationArchive)o);
} catch( NoResultException nre ) {
return null;
}
}
@Override
public ApplicationArchive <API key>(Application app, String hash, String hashAlgorithm) {
Query q = entityManager.createQuery("select distinct ar "
+"from ApplicationArchive ar "
+"join fetch ar.application app "
+"where ar.hash=:hash "
+"and ar.hashAlgorithm=:hashAlgorithm "
+"and app.id=:appId");
q.setParameter("hash", hash);
q.setParameter("hashAlgorithm", hashAlgorithm);
q.setParameter("appId",app.getId());
q.setMaxResults(1);
try {
ApplicationArchive o = (ApplicationArchive)q.getSingleResult();
return (ApplicationArchive)o;
} catch( NoResultException nre ) {
return null;
}
}
@Override
public int <API key>(String hash, String hashAlg) {
Query q = entityManager.createQuery("select count(d) "
+"from Deployment d "
+"left join d.applicationArchive aa "
+"where aa.hash=:hash "
+"and aa.hashAlgorithm=:hashAlgorithm");
q.setParameter("hash", hash);
q.setParameter("hashAlgorithm", hashAlg);
try {
Number ret = (Number)q.getSingleResult();
return ret.intValue();
} catch( NoResultException nre ) {
return 0;
}
}
@Override
public int <API key>(String hash, String hashAlg) {
Query q = entityManager.createQuery("select count(av) "
+"from ApplicationVersion av "
+"left join av.archive ar "
+"where ar.hash=:hash "
+"and ar.hashAlgorithm=:hashAlgorithm");
q.setParameter("hash", hash);
q.setParameter("hashAlgorithm", hashAlg);
try {
Number ret = (Number)q.getSingleResult();
return ret.intValue();
} catch( NoResultException nre ) {
return 0;
}
}
@Override
public int <API key>(String hash, String hashAlg) {
Query q = entityManager.createQuery("select count(ar) "
+"from ApplicationArchive ar "
+"where ar.hash=:hash "
+"and ar.hashAlgorithm=:hashAlgorithm ");
q.setParameter("hash", hash);
q.setParameter("hashAlgorithm", hashAlg);
try {
Number ret = (Number)q.getSingleResult();
return ret.intValue();
} catch( NoResultException nre ) {
return 0;
}
}
@Override
public <E extends ModelEntity, T extends ModelEntity> List<T> getOrdered(E entity, String listMethod, Comparator<T> comparator) {
EntityManager entityManager = getEntityManager();
entityManager.getTransaction().begin();
entityManager.merge(entity);
List<T> ents;
try {
ents = (List<T>) entity.getClass().getMethod(listMethod).invoke(entity);
} catch (Exception e) {
throw new <API key>(e);
}
Collections.sort( ents, comparator );
entityManager.getTransaction().commit();
return ents;
}
// ACCESSORS
public void setEntityManager(EntityManager manager) {
entityManager = manager;
}
public EntityManager getEntityManager() {
return entityManager;
}
/**
* Amount of time to wait between each refresh retry.
*/
public void <API key>(int <API key>) {
this.<API key> = <API key>;
}
/**
* Number of times to retry refreshing a model entity before failing the operation.
* Using SQLite, sometimes the database file is locked by another process.
*/
public void <API key>(int <API key>) {
this.<API key> = <API key>;
}
// PRIVATE METHODS
private <T extends ModelEntity> void _delete(T entity, List<ProcessingEvent> events) throws <API key> {
// give the event notifiers an opportunity to act, prior to deletion
entity.remove();
entityManager.remove(entity);
}
private void _refresh(ModelEntity obj2Refresh) {
if( !entityManager.contains(obj2Refresh) ) {
entityManager.merge(obj2Refresh);
}
entityManager.refresh(obj2Refresh);
}
@Override
public ModelService begin() {
entityManager.getTransaction().begin();
return this;
}
@Override
public ModelService commit() {
entityManager.getTransaction().commit();
return this;
}
@Override
public ModelService rollback() {
if( entityManager.isOpen() && entityManager.getTransaction().isActive() ) {
entityManager.getTransaction().rollback();
}
return this;
}
}
|
function loadText()
{
document.getElementById("txtLang").innerHTML = "\u78ba\u5b9a\u522a\u9664\u6b64\u8cc7\u6599\u593e ?";
document.getElementById("btnClose").value = "\u95dc\u9589 ";
document.getElementById("btnDelete").value = "\u522a\u9664 ";
}
function writeTitle()
{
document.write("<title>Delete Folder</title>")
}
|
// gameswf_jit_x86.h -- Julien Hamaide <julien.hamaide@gmail.com> 2008
// This source code has been donated to the Public Domain. Do
// whatever you want with it.
// Jit x86
#ifndef GAMESWF_JIT_X86_H
#define GAMESWF_JIT_X68_H
#include "gameswf_jit.h"
enum jit_register
{
jit_eax = 0,
jit_ebx = 3,
jit_ecx = 1,
jit_edx = 2,
jit_esi = 6,
jit_edi = 7,
jit_ebp = 5,
jit_esp = 4
};
template<typename T> void* cast_to_voidp( T value )
{
union
{
T _value;
void * _voidp;
} cast;
cast._value = value;
return cast._voidp;
}
struct <API key>
{
<API key>( jit_register reg, int offset ) : m_register( reg ), m_offset( offset ) {}
jit_register m_register;
int m_offset;
};
#define jit_this_pointer jit_ecx
#define jit_result jit_eax
#define jit_stack_pointer jit_esp
#define jit_push( _function_, _variable_ ) { jit_add_bytecode_u8( _function_, 0x50 | _variable_ ); }
#define jit_pop( _function_, _variable_ ) { jit_add_bytecode_u8( _function_, 0x50 | _variable_ + 8 ); }
#define jit_mov( _function_, _register1_, _register2_ ) <API key>( _function_, _register1_, _register2_ )
#define jit_load( _function_, _register_, _memory_ ) <API key>( _function_, _register_, _memory_ );
#define jit_store( _function_, _register_, _memory_ )
#define jit_subi( _function_, _register_, _value_ ) <API key>( _function_, _register_, _value_ )
#define jit_getarg( _index_ ) <API key>( jit_ebp, 4 * ( 2 + _index_ ) )
#define jit_pusharg( _function_, _arg_ ) jit_push( _function_, _arg_ )
#define jit_pushargi( _function_, _arg_ ) jit_pushi( _function_, _arg_ )
#define jit_popargs( _function_, _arg_ ) jit_subi( _function_, jit_esp, 4 * _arg_ )
#define jit_this_call( _function_, _address_ ) { jit_call( _function_, _address_);}
#define jit_call( _function_, _address_ ) { jit_add_bytecode_u8( _function_, 0xE8 ); _function_.add_address_patch( cast_to_voidp(_address_), 4 );}
#define jit_ret( _function_ ) jit_add_bytecode_u8( _function_, 0xC3 )
#define jit_add_bytecode_u8( _function_, _value_ ) { _function_.push_byte( static_cast<unsigned char>( _value_ ) ); }
#define <API key>( _function_, _value_ ) { _function_.push_integer( (unsigned int)( _value_ ) ); }
#define jit_getaddress( _function_, _destination_, _source_, _offset_ ) jit_lea( _function_, _destination_, <API key>( _source_, _offset_) )
// Implementations
void <API key>( jit_function & function, const jit_register destination, const jit_register source );
void <API key>( jit_function & function, const jit_register destination, const <API key> & address );
void <API key>( jit_function & function, const jit_register destination, const int value );
void jit_lea( jit_function & function, const jit_register destination, const <API key> & address );
void jit_pushi( jit_function & function, const void * pointer );
void jit_pushi( jit_function & function, int value );
void jit_pushi( jit_function & function, uint8 value );
void jit_pushi( jit_function & function, double value );
#endif
|
if SETTINGS[:noenv_enable]
before = 'model_name'
Deface::Override.new(
:virtual_path => 'hosts/_form',
:name => 'hosts_noenv',
:insert_before => "div##{before}",
:partial => 'hosts/noenv_field',
)
end
|
"use strict";
(function () {
var start = document.querySelector("#start");
if(start){
start.onclick = function(){
counter(25,0);
}
}
var stop = document.querySelector("#stop");
if(stop){
stop.onclick = function(){
counter(0,0);
}
}
function counter(minutes,seconds){
if(seconds==0){
if(minutes==0){
var clock = '0:0';
document.getElementById("clock").innerHTML = clock;
return;
}
seconds=59;
minutes
}
var clock = minutes+':'+seconds;
document.getElementById("clock").innerHTML=clock;
seconds
setTimeout(function(){counter(minutes,seconds)}, 50);
}
})();
//~ function counter(minutes,seconds){
//~ if(seconds==0){
//~ seconds=59;
//~ minutes--;
//~ var clock = minutes+':'+seconds;
//~ document.getElementBiId("clock").innerHTML=clock;
//~ seconds--;
|
<?php
require_once('includes/classes/logo_upload.php');
require_once('includes/classes/currencies.php');
require_once('../ext/tcpdf/config/lang/eng.php');
require_once('../ext/tcpdf/tcpdf.php');
define('TOC_PDF_POS_START_X', 70);
define('TOC_PDF_POS_START_Y', 50);
define('<API key>', 100);
define('<API key>', 10);
define('TOC_PDF_LOGO_WIDTH', 80);
define('TOC_PDF_LOGO_HEIGHT', 20);
define('<API key>', TOC_PDF_POS_START_Y);
define('<API key>', TOC_PDF_POS_START_Y);
define('<API key>', (TOC_PDF_POS_START_Y + 40));
define('<API key>', <API key>);
define('<API key>', <API key>);
define('<API key>', <API key>);
define('<API key>', (<API key> + 20));
define('<API key>', (<API key> + 6));
define('TOC_PDF_FONT', 'times');
define('<API key>', 11);
define('<API key>', 9);
define('<API key>', 8);
define('<API key>', 14);
define('<API key>', 9);
define('<API key>', 10);
define('<API key>', 9);
define('<API key>', 5);
define('<API key>', 8);
define('<API key>', 10);
define('<API key>', 11);
/*
* Class TOCPDF
*/
class TOCPDF extends TCPDF {
var $_customer_info = array();
function setCustomerInfo($customer_info) {
$this->_customer_info = $customer_info;
}
function Header() {
//Logo
$logo = toC_Logo_Upload::getOriginalLogo();
//verify whether the default logo is existed when the template logo isn't uploded yet
if ($logo === false) {
if (file_exists(DIR_FS_CATALOG . DIR_WS_IMAGES . 'store_logo.jpg')) {
$logo = DIR_FS_CATALOG . DIR_WS_IMAGES . 'store_logo.jpg';
}else if (file_exists(DIR_FS_CATALOG . DIR_WS_IMAGES . 'store_logo.png')){
$logo = DIR_FS_CATALOG . DIR_WS_IMAGES . 'store_logo.png';
}
}
$this->Image($logo, <API key>, <API key>, TOC_PDF_LOGO_WIDTH, TOC_PDF_LOGO_HEIGHT);
//Line
$this->line(10, 45, 98, 45);
//Customer Information
$this->SetFont(TOC_PDF_FONT, 'B', <API key>);
$this->SetY(<API key>);
$this->MultiCell(100, 4, $this->_customer_info['name'] . "\n" .
$this->_customer_info['street_address'] . " " . $this->_customer_info['suburb'] . "\n" .
$this->_customer_info['postcode'] . " " . $this->_customer_info['city'] . "\n" .
$this->_customer_info['country_title'] . "\n" .
$this->_customer_info['email_address'], 0, 'L');
//Store Information
$this->SetFont(TOC_PDF_FONT, 'B', <API key>);
$this->SetY(<API key>);
$this->Cell(100);
$this->MultiCell(80, 4, STORE_NAME_ADDRESS, 0 ,'R');
}
function Footer() {
// Position at 1.5 cm from bottom
$this->SetY(-15);
// Set font
$this->SetFont(TOC_PDF_FONT, 'I', <API key>);
// Page number
$this->Cell(0, 10, $this->getAliasNumPage() . '/' . $this->getAliasNbPages(), 0, 0, 'R');
}
}
?>
|
"""Config file for coverage.py"""
import os, re, sys
from .backward import string_class, iitems
# In py3, # ConfigParser was renamed to the more-standard configparser
try:
import configparser # pylint: disable=F0401
except ImportError:
import ConfigParser as configparser
class HandyConfigParser(configparser.RawConfigParser):
"""Our specialization of ConfigParser."""
def read(self, filename):
"""Read a filename as UTF-8 configuration data."""
kwargs = {}
if sys.version_info >= (3, 2):
kwargs['encoding'] = "utf-8"
return configparser.RawConfigParser.read(self, filename, **kwargs)
def get(self, *args, **kwargs):
v = configparser.RawConfigParser.get(self, *args, **kwargs)
def dollar_replace(m):
"""Called for each $replacement."""
# Only one of the groups will have matched, just get its text.
word = [w for w in m.groups() if w is not None][0]
if word == "$":
return "$"
else:
return os.environ.get(word, '')
dollar_pattern = r"""(?x) # Use extended regex syntax
\$(?: # A dollar sign, then
(?P<v1>\w+) | # a plain word,
{(?P<v2>\w+)} | # or a {-wrapped word,
(?P<char>[$]) # or a dollar sign.
)
"""
v = re.sub(dollar_pattern, dollar_replace, v)
return v
def getlist(self, section, option):
"""Read a list of strings.
The value of `section` and `option` is treated as a comma- and newline-
separated list of strings. Each value is stripped of whitespace.
Returns the list of strings.
"""
value_list = self.get(section, option)
values = []
for value_line in value_list.split('\n'):
for value in value_line.split(','):
value = value.strip()
if value:
values.append(value)
return values
def getlinelist(self, section, option):
"""Read a list of full-line strings.
The value of `section` and `option` is treated as a newline-separated
list of strings. Each value is stripped of whitespace.
Returns the list of strings.
"""
value_list = self.get(section, option)
return list(filter(None, value_list.split('\n')))
# The default line exclusion regexes
DEFAULT_EXCLUDE = [
'(?i)# *pragma[: ]*no *cover',
]
DEFAULT_PARTIAL = [
'(?i)# *pragma[: ]*no *branch',
]
# The default partial branch regexes, based on Python semantics.
# These are any Python branching constructs that can't actually execute all
# their branches.
<API key> = [
'while (True|1|False|0):',
'if (True|1|False|0):',
]
class CoverageConfig(object):
"""Coverage.py configuration.
The attributes of this class are the various settings that control the
operation of coverage.py.
"""
def __init__(self):
"""Initialize the configuration attributes to their defaults."""
# Metadata about the config.
self.<API key> = []
self.config_files = []
# Defaults for [run]
self.branch = False
self.cover_pylib = False
self.data_file = ".coverage"
self.parallel = False
self.timid = False
self.source = None
self.debug = []
# Defaults for [report]
self.exclude_list = DEFAULT_EXCLUDE[:]
self.ignore_errors = False
self.include = None
self.omit = None
self.partial_list = DEFAULT_PARTIAL[:]
self.partial_always_list = <API key>[:]
self.precision = 0
self.show_missing = False
# Defaults for [html]
self.html_dir = "htmlcov"
self.extra_css = None
self.html_title = "Coverage report"
# Defaults for [xml]
self.xml_output = "coverage.xml"
# Defaults for [paths]
self.paths = {}
def from_environment(self, env_var):
"""Read configuration from the `env_var` environment variable."""
# Timidity: for nose users, read an environment variable. This is a
# cheap hack, since the rest of the command line arguments aren't
# recognized, but it solves some users' problems.
env = os.environ.get(env_var, '')
if env:
self.timid = ('--timid' in env)
MUST_BE_LIST = ["omit", "include", "debug"]
def from_args(self, **kwargs):
"""Read config values from `kwargs`."""
for k, v in iitems(kwargs):
if v is not None:
if k in self.MUST_BE_LIST and isinstance(v, string_class):
v = [v]
setattr(self, k, v)
def from_file(self, filename):
"""Read configuration from a .rc file.
`filename` is a file name to read.
"""
self.<API key>.append(filename)
cp = HandyConfigParser()
files_read = cp.read(filename)
if files_read is not None: # return value changed in 2.4
self.config_files.extend(files_read)
for option_spec in self.CONFIG_FILE_OPTIONS:
self.<API key>(cp, *option_spec)
# [paths] is special
if cp.has_section('paths'):
for option in cp.options('paths'):
self.paths[option] = cp.getlist('paths', option)
CONFIG_FILE_OPTIONS = [
# [run]
('branch', 'run:branch', 'boolean'),
('cover_pylib', 'run:cover_pylib', 'boolean'),
('data_file', 'run:data_file'),
('debug', 'run:debug', 'list'),
('include', 'run:include', 'list'),
('omit', 'run:omit', 'list'),
('parallel', 'run:parallel', 'boolean'),
('source', 'run:source', 'list'),
('timid', 'run:timid', 'boolean'),
# [report]
('exclude_list', 'report:exclude_lines', 'linelist'),
('ignore_errors', 'report:ignore_errors', 'boolean'),
('include', 'report:include', 'list'),
('omit', 'report:omit', 'list'),
('partial_list', 'report:partial_branches', 'linelist'),
('partial_always_list', 'report:<API key>', 'linelist'),
('precision', 'report:precision', 'int'),
('show_missing', 'report:show_missing', 'boolean'),
# [html]
('html_dir', 'html:directory'),
('extra_css', 'html:extra_css'),
('html_title', 'html:title'),
# [xml]
('xml_output', 'xml:output'),
]
def <API key>(self, cp, attr, where, type_=''):
"""Set an attribute on self if it exists in the ConfigParser."""
section, option = where.split(":")
if cp.has_option(section, option):
method = getattr(cp, 'get'+type_)
setattr(self, attr, method(section, option))
# eflag: FileType = Python2
|
# -*- coding: utf-8 -*-
import os, sys, time, multiprocessing, re
from .processes import ForkedProcess
from .remoteproxy import ClosedError
from ..python2_3 import basestring, xrange
class CanceledError(Exception):
"""Raised when the progress dialog is canceled during a processing operation."""
pass
class Parallelize(object):
def __init__(self, tasks=None, workers=None, block=True, progressDialog=None, randomReseed=True, **kwds):
## Generate progress dialog.
## Note that we want to avoid letting forked child processes play with progress dialogs..
self.showProgress = False
if progressDialog is not None:
self.showProgress = True
if isinstance(progressDialog, basestring):
progressDialog = {'labelText': progressDialog}
from ..widgets.ProgressDialog import ProgressDialog
self.progressDlg = ProgressDialog(**progressDialog)
if workers is None:
workers = self.<API key>()
if not hasattr(os, 'fork'):
workers = 1
self.workers = workers
if tasks is None:
tasks = range(workers)
self.tasks = list(tasks)
self.reseed = randomReseed
self.kwds = kwds.copy()
self.kwds['_taskStarted'] = self._taskStarted
def __enter__(self):
self.proc = None
if self.workers == 1:
return self.runSerial()
else:
return self.runParallel()
def __exit__(self, *exc_info):
if self.proc is not None: ## worker
exceptOccurred = exc_info[0] is not None ## hit an exception during processing.
try:
if exceptOccurred:
sys.excepthook(*exc_info)
finally:
#print os.getpid(), 'exit'
os._exit(1 if exceptOccurred else 0)
else: ## parent
if self.showProgress:
try:
self.progressDlg.__exit__(None, None, None)
except Exception:
pass
def runSerial(self):
if self.showProgress:
self.progressDlg.__enter__()
self.progressDlg.setMaximum(len(self.tasks))
self.progress = {os.getpid(): []}
return Tasker(self, None, self.tasks, self.kwds)
def runParallel(self):
self.childs = []
## break up tasks into one set per worker
workers = self.workers
chunks = [[] for i in xrange(workers)]
i = 0
for i in range(len(self.tasks)):
chunks[i%workers].append(self.tasks[i])
## fork and assign tasks to each worker
for i in range(workers):
proc = ForkedProcess(target=None, preProxy=self.kwds, randomReseed=self.reseed)
if not proc.isParent:
self.proc = proc
return Tasker(self, proc, chunks[i], proc.forkedProxies)
else:
self.childs.append(proc)
## Keep track of the progress of each worker independently.
self.progress = dict([(ch.childPid, []) for ch in self.childs])
## for each child process, self.progress[pid] is a list
## of task indexes. The last index is the task currently being
## processed; all others are finished.
try:
if self.showProgress:
self.progressDlg.__enter__()
self.progressDlg.setMaximum(len(self.tasks))
## process events from workers until all have exited.
activeChilds = self.childs[:]
self.exitCodes = []
pollInterval = 0.01
while len(activeChilds) > 0:
waitingChildren = 0
rem = []
for ch in activeChilds:
try:
n = ch.processRequests()
if n > 0:
waitingChildren += 1
except ClosedError:
#print ch.childPid, 'process finished'
rem.append(ch)
if self.showProgress:
self.progressDlg += 1
#print "remove:", [ch.childPid for ch in rem]
for ch in rem:
activeChilds.remove(ch)
while True:
try:
pid, exitcode = os.waitpid(ch.childPid, 0)
self.exitCodes.append(exitcode)
break
except OSError as ex:
if ex.errno == 4: ## If we get this error, just try again
continue
#print "Ignored system call interruption"
else:
raise
#print [ch.childPid for ch in activeChilds]
if self.showProgress and self.progressDlg.wasCanceled():
for ch in activeChilds:
ch.kill()
raise CanceledError()
## adjust polling interval--prefer to get exactly 1 event per poll cycle.
if waitingChildren > 1:
pollInterval *= 0.7
elif waitingChildren == 0:
pollInterval /= 0.7
pollInterval = max(min(pollInterval, 0.5), 0.0005) ## but keep it within reasonable limits
time.sleep(pollInterval)
finally:
if self.showProgress:
self.progressDlg.__exit__(None, None, None)
for ch in self.childs:
ch.join()
if len(self.exitCodes) < len(self.childs):
raise Exception("Parallelizer started %d processes but only received exit codes from %d." % (len(self.childs), len(self.exitCodes)))
for code in self.exitCodes:
if code != 0:
raise Exception("Error occurred in parallel-executed subprocess (console output may have more information).")
return [] ## no tasks for parent process.
@staticmethod
def <API key>():
if 'linux' in sys.platform:
## I think we can do a little better here..
## cpu_count does not consider that there is little extra benefit to using hyperthreaded cores.
try:
cores = {}
pid = None
with open('/proc/cpuinfo') as fd:
for line in fd:
m = re.match(r'physical id\s+:\s+(\d+)', line)
if m is not None:
pid = m.groups()[0]
m = re.match(r'cpu cores\s+:\s+(\d+)', line)
if m is not None:
cores[pid] = int(m.groups()[0])
return sum(cores.values())
except:
return multiprocessing.cpu_count()
else:
return multiprocessing.cpu_count()
def _taskStarted(self, pid, i, **kwds):
## called remotely by tasker to indicate it has started working on task i
#print pid, 'reported starting task', i
if self.showProgress:
if len(self.progress[pid]) > 0:
self.progressDlg += 1
if pid == os.getpid(): ## single-worker process
if self.progressDlg.wasCanceled():
raise CanceledError()
self.progress[pid].append(i)
class Tasker(object):
def __init__(self, parallelizer, process, tasks, kwds):
self.proc = process
self.par = parallelizer
self.tasks = tasks
for k, v in kwds.items():
setattr(self, k, v)
def __iter__(self):
## we could fix this up such that tasks are retrieved from the parent process one at a time..
for i, task in enumerate(self.tasks):
self.index = i
#print os.getpid(), 'starting task', i
self._taskStarted(os.getpid(), i, _callSync='off')
yield task
if self.proc is not None:
#print os.getpid(), 'no more tasks'
self.proc.close()
def process(self):
"""
Process requests from parent.
Usually it is not necessary to call this unless you would like to
receive messages (such as exit requests) during an iteration.
"""
if self.proc is not None:
self.proc.processRequests()
def numWorkers(self):
"""
Return the number of parallel workers
"""
return self.par.workers
#class Parallelizer:
#"""
#Use::
#p = Parallelizer()
#with p(4) as i:
#p.finish(do_work(i))
#print p.results()
#"""
#def __init__(self):
#pass
#def __call__(self, n):
#self.replies = []
#self.conn = None ## indicates this is the parent process
#return Session(self, n)
#def finish(self, data):
#if self.conn is None:
#self.replies.append((self.i, data))
#else:
##print "send", self.i, data
#self.conn.send((self.i, data))
#os._exit(0)
#def result(self):
#print self.replies
#class Session:
#def __init__(self, par, n):
#self.par = par
#self.n = n
#def __enter__(self):
#self.childs = []
#for i in range(1, self.n):
#c1, c2 = multiprocessing.Pipe()
#pid = os.fork()
#if pid == 0: ## child
#self.par.i = i
#self.par.conn = c2
#self.childs = None
#c1.close()
#return i
#else:
#self.childs.append(c1)
#c2.close()
#self.par.i = 0
#return 0
#def __exit__(self, *exc_info):
#if exc_info[0] is not None:
#sys.excepthook(*exc_info)
#if self.childs is not None:
#self.par.replies.extend([conn.recv() for conn in self.childs])
#else:
#self.par.finish(None)
|
#ifndef <API key>
#define <API key>
#include <asn_application.h>
/* Including external dependencies */
#include <NativeInteger.h>
#include <constr_SEQUENCE.h>
#ifdef __cplusplus
extern "C"
{
#endif
/* <API key> */
typedef struct <API key>
{
long ai0;
long ai1;
long ai2;
/* Context for parsing across buffer boundaries */
asn_struct_ctx_t _asn_ctx;
} <API key>;
/* Implementation */
extern <API key> <API key>;
#ifdef __cplusplus
}
#endif
#endif /* <API key> */
#include <asn_internal.h>
|
<?php namespace Hideyo\Ecommerce\Backend\Controllers;
/**
* <API key>
*
* This is the controller of the content groups of the shop
* @author Matthijs Neijenhuijs <matthijs@hideyo.io>
* @version 0.1
*/
use App\Http\Controllers\Controller;
use Hideyo\Ecommerce\Backend\Repositories\<API key>;
use Illuminate\Http\Request;
use Notification;
use Datatables;
use Form;
class <API key> extends Controller
{
public function __construct(
Request $request,
<API key> $content
) {
$this->request = $request;
$this->content = $content;
}
public function index()
{
if ($this->request->wantsJson()) {
$query = $this->content->getGroupModel()
->select(['id', 'title'])
->where('shop_id', '=', \Auth::guard('hideyobackend')->user()->selected_shop_id);
$datatables = Datatables::of($query)
->addColumn('action', function ($query) {
$deleteLink = Form::deleteajax(url()->route('hideyo.content-group.destroy', $query->id), 'Delete', '', array('class'=>'btn btn-default btn-sm btn-danger'));
$links = '<a href="'.url()->route('hideyo.content-group.edit', $query->id).'" class="btn btn-default btn-sm btn-success"><i class="entypo-pencil"></i>Edit</a> '.$deleteLink;
return $links;
});
return $datatables->make(true);
}
return view('hideyo_backend::content_group.index')->with('contentGroup', $this->content->selectAll());
}
public function create()
{
return view('hideyo_backend::content_group.create')->with(array());
}
public function store()
{
$result = $this->content->createGroup($this->request->all());
if (isset($result->id)) {
Notification::success('The content was inserted.');
return redirect()->route('hideyo.content-group.index');
}
foreach ($result->errors()->all() as $error) {
Notification::error($error);
}
return redirect()->back()->withInput();
}
public function edit($contentGroupId)
{
return view('hideyo_backend::content_group.edit')->with(array('contentGroup' => $this->content->findGroup($contentGroupId)));
}
public function editSeo($contentGroupId)
{
return view('hideyo_backend::content_group.edit_seo')->with(array('contentGroup' => $this->content->find($contentGroupId)));
}
public function update($contentGroupId)
{
$result = $this->content->updateGroupById($this->request->all(), $contentGroupId);
if (isset($result->id)) {
if ($this->request->get('seo')) {
Notification::success('ContentGroup seo was updated.');
return redirect()->route('hideyo.content-group.edit_seo', $contentGroupId);
} elseif ($this->request->get('content-combination')) {
Notification::success('ContentGroup combination leading attribute group was updated.');
return redirect()->route('hideyo.content-group.{contentId}.content-combination.index', $contentGroupId);
} else {
Notification::success('ContentGroup was updated.');
return redirect()->route('hideyo.content-group.index');
}
}
foreach ($result->errors()->all() as $error) {
Notification::error($error);
}
return redirect()->back()->withInput();
}
/**
* Remove the specified resource from storage
* @param int $contentGroupId
* @return Redirect
*/
public function destroy($contentGroupId)
{
$result = $this->content->destroyGroup($contentGroupId);
if ($result) {
Notification::success('The content was deleted.');
return redirect()->route('hideyo.content-group.index');
}
}
}
|
#ifndef <API key>
#define <API key>
#include "IntRect.h"
#include "GraphicsContext.h"
#include "RenderSkinAndroid.h"
#include "<API key>.h"
#include "SkCanvas.h"
#include "SkPicture.h"
#include "SkTDArray.h"
#include <wtf/Vector.h>
class SkCanvas;
namespace WebCore {
class <API key> {
public:
class State;
<API key>();
virtual ~<API key>();
virtual bool isPaintingDisabled() = 0;
void setGraphicsContext(GraphicsContext* gc) { m_gc = gc; }
virtual bool deleteUs() const { return false; }
typedef enum { PaintingContext, RecordingContext } ContextType;
virtual ContextType type() = 0;
// State management
virtual void <API key>(float opacity) = 0;
virtual void <API key>() = 0;
virtual void save();
virtual void restore();
// State values
virtual void setAlpha(float alpha);
int getNormalizedAlpha() const;
virtual void <API key>(CompositeOperator op);
virtual bool setFillColor(const Color& c);
virtual bool setFillShader(SkShader* fillShader);
virtual void setLineCap(LineCap cap);
virtual void setLineDash(const DashArray& dashes, float dashOffset);
virtual void setLineJoin(LineJoin join);
virtual void setMiterLimit(float limit);
virtual void setShadow(int radius, int dx, int dy, SkColor c);
virtual void setShouldAntialias(bool useAA);
virtual bool setStrokeColor(const Color& c);
virtual bool setStrokeShader(SkShader* strokeShader);
virtual void setStrokeStyle(StrokeStyle style);
virtual void setStrokeThickness(float f);
// FIXME: These setupPaint* should be private, but
// they are used by FontAndroid currently
virtual void setupPaintFill(SkPaint* paint) const;
virtual bool setupPaintShadow(SkPaint* paint, SkPoint* offset) const;
// Sets up the paint for stroking. Returns true if the style is really
// just a dash of squares (the size of the paint's stroke-width.
virtual bool setupPaintStroke(SkPaint* paint, SkRect* rect, bool isHLine = false);
// Matrix operations
virtual void concatCTM(const AffineTransform& affine) = 0;
virtual void rotate(float angleInRadians) = 0;
virtual void scale(const FloatSize& size) = 0;
virtual void translate(float x, float y) = 0;
virtual const SkMatrix& getTotalMatrix() = 0;
// Clipping
virtual void <API key>(const IntRect& rect, int thickness) = 0;
virtual void canvasClip(const Path& path) = 0;
virtual bool clip(const FloatRect& rect) = 0;
virtual bool clip(const Path& path) = 0;
virtual bool clipConvexPolygon(size_t numPoints, const FloatPoint*, bool antialias) = 0;
virtual bool clipOut(const IntRect& r) = 0;
virtual bool clipOut(const Path& p) = 0;
virtual bool clipPath(const Path& pathToClip, WindRule clipRule) = 0;
virtual SkIRect getTotalClipBounds() = 0;
// Drawing
virtual void clearRect(const FloatRect& rect) = 0;
virtual void drawBitmapPattern(const SkBitmap& bitmap, const SkMatrix& matrix,
CompositeOperator compositeOp, const FloatRect& destRect) = 0;
virtual void drawBitmapRect(const SkBitmap& bitmap, const SkIRect* src,
const SkRect& dst, CompositeOperator op = CompositeSourceOver) = 0;
virtual void drawConvexPolygon(size_t numPoints, const FloatPoint* points,
bool shouldAntialias) = 0;
virtual void drawEllipse(const IntRect& rect) = 0;
virtual void drawFocusRing(const Vector<IntRect>& rects, int /* width */,
int /* offset */, const Color& color) = 0;
virtual void <API key>(const Font& font, const TextRun& run,
const FloatPoint& point, int h,
const Color& backgroundColor, ColorSpace colorSpace,
int from, int to, bool isActive) = 0;
virtual void drawLine(const IntPoint& point1, const IntPoint& point2) = 0;
virtual void drawLineForText(const FloatPoint& pt, float width) = 0;
virtual void <API key>(const FloatPoint& pt, float width,
GraphicsContext::<API key>) = 0;
virtual void drawRect(const IntRect& rect) = 0;
virtual void fillPath(const Path& pathToFill, WindRule fillRule) = 0;
virtual void fillRect(const FloatRect& rect) = 0;
void fillRect(const FloatRect& rect, const Color& color, ColorSpace) {
fillRect(rect, color);
}
virtual void fillRect(const FloatRect& rect, const Color& color) = 0;
void fillRoundedRect(const IntRect& rect, const IntSize& topLeft,
const IntSize& topRight, const IntSize& bottomLeft,
const IntSize& bottomRight, const Color& color,
ColorSpace) {
fillRoundedRect(rect, topLeft, topRight, bottomLeft, bottomRight, color);
}
virtual void fillRoundedRect(const IntRect& rect, const IntSize& topLeft,
const IntSize& topRight, const IntSize& bottomLeft,
const IntSize& bottomRight, const Color& color) = 0;
virtual void strokeArc(const IntRect& r, int startAngle, int angleSpan) = 0;
virtual void strokePath(const Path& pathToStroke) = 0;
virtual void strokeRect(const FloatRect& rect, float lineWidth) = 0;
virtual void drawPosText(const void* text, size_t byteLength,
const SkPoint pos[], const SkPaint& paint) = 0;
virtual void drawMediaButton(const IntRect& rect, <API key>::MediaButton buttonType,
bool translucent = false, bool drawBackground = true,
const IntRect& thumb = IntRect()) = 0;
virtual SkCanvas* recordingCanvas() = 0;
virtual void setTextOffset(FloatSize offset) = 0;
void setRawState(State* state) { m_state = state; }
virtual void <API key>() {}
virtual void clearRecording() {}
virtual SkPicture* getRecordingPicture() const { return NULL; }
virtual bool isDefault() const { return true; }
virtual bool isAnimating() const { return false; }
virtual bool isRecording() const { return false; }
virtual bool isDirty() const {return false; }
virtual void setIsAnimating() {}
struct ShadowRec {
SkScalar blur;
SkScalar dx;
SkScalar dy;
SkColor color; // alpha>0 means valid shadow
ShadowRec(SkScalar b = 0,
SkScalar x = 0,
SkScalar y = 0,
SkColor c = 0) // by default, alpha=0, so no shadow
: blur(b), dx(x), dy(y), color(c)
{};
};
class State {
public:
SkPathEffect* pathEffect;
float miterLimit;
float alpha;
float strokeThickness;
SkPaint::Cap lineCap;
SkPaint::Join lineJoin;
SkXfermode::Mode mode;
int dashRatio; // Ratio of the length of a dash to its width
ShadowRec shadow;
SkColor fillColor;
SkShader* fillShader;
SkColor strokeColor;
SkShader* strokeShader;
bool useAA;
StrokeStyle strokeStyle;
State();
State(const State& other);
~State();
void setShadow(int radius, int dx, int dy, SkColor c);
bool setupShadowPaint(SkPaint* paint, SkPoint* offset,
bool <API key>);
SkColor applyAlpha(SkColor c) const;
State <API key>();
private:
// Not supported.
void operator=(const State&);
friend class <API key>;
friend class <API key>;
};
protected:
virtual bool <API key>() const = 0;
void setupPaintCommon(SkPaint* paint) const;
GraphicsContext* m_gc; // Back-ptr to our parent
WTF::Vector<State> m_stateStack;
State* m_state;
};
}
#endif
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var <API key> = require("@esri/arcgis-rest-request");
var helpers_1 = require("./helpers");
function createFolder(requestOptions) {
var owner = helpers_1.determineOwner(requestOptions);
var baseUrl = <API key>.getPortalUrl(requestOptions) + "/content/users/" + owner;
var url = baseUrl + "/createFolder";
requestOptions.params = tslib_1.__assign({ title: requestOptions.title }, requestOptions.params);
return <API key>.request(url, requestOptions);
}
exports.createFolder = createFolder;
function createItemInFolder(requestOptions) {
var owner = helpers_1.determineOwner(requestOptions);
var baseUrl = <API key>.getPortalUrl(requestOptions) + "/content/users/" + owner;
var url = baseUrl + "/addItem";
if (requestOptions.folder) {
url = baseUrl + "/" + requestOptions.folder + "/addItem";
}
// serialize the item into something Portal will accept
requestOptions.params = tslib_1.__assign({}, requestOptions.params, helpers_1.serializeItem(requestOptions.item));
return <API key>.request(url, requestOptions);
}
exports.createItemInFolder = createItemInFolder;
function createItem(requestOptions) {
// delegate to createItemInFolder placing in the root of the filestore
var options = tslib_1.__assign({ folder: null }, requestOptions);
return createItemInFolder(options);
}
exports.createItem = createItem;
//# sourceMappingURL=create.js.map
|
export { default } from './<API key>';
export * from './<API key>';
export * from '../<API key>/<API key>';
export * from '../<API key>/<API key>';
export { useDetailedItems } from '../../hooks/useDetailedItems';
|
package com.amaze.filemanager.file_operations.filesystem.smbstreamer;
import static android.os.Build.VERSION_CODES.JELLY_BEAN;
import static android.os.Build.VERSION_CODES.KITKAT;
import static android.os.Build.VERSION_CODES.P;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.annotation.Config;
import org.robolectric.shadow.api.Shadow;
import com.amaze.filemanager.file_operations.filesystem.smbstreamer.StreamSource;
import com.amaze.filemanager.file_operations.shadows.ShadowMultiDex;
import com.amaze.filemanager.file_operations.shadows.jcifs.smb.ShadowSmbFile;
import android.os.Environment;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import jcifs.smb.SmbFile;
@RunWith(AndroidJUnit4.class)
@Config(
shadows = {ShadowMultiDex.class, ShadowSmbFile.class},
sdk = {JELLY_BEAN, KITKAT, P})
public class StreamSourceTest {
private SmbFile file;
private StreamSource ss;
private byte[] text;
@Before
public void setUp() throws IOException {
StringBuilder textInFile = new StringBuilder();
for (int i = 0; i < 20; i++) textInFile.append("a");
text = textInFile.toString().getBytes();
file = createFile();
ss = new StreamSource(file, file.length());
}
@After
public void tearDown() {
if (ss != null) ss.close();
}
private SmbFile createFile() throws IOException {
File testFile = new File(Environment.<API key>(), "Test.txt");
testFile.createNewFile();
OutputStream is = new FileOutputStream(testFile);
is.write(text);
is.flush();
is.close();
SmbFile file = new SmbFile("smb://127.0.0.1/Test.txt");
ShadowSmbFile shadowSmbFile = Shadow.extract(file);
shadowSmbFile.setFile(testFile);
return file;
}
/*
From now on ssEmpty will not be used since StreamSource()
constructor does not initialize any internal variables
*/
/** Purpose: Open an existing file Input: no Expected: cs.read() = 1 buff[0] = text[0] */
@Test
public void openExisting() throws IOException {
ss.open();
byte[] buff = new byte[1];
assertEquals(buff.length, ss.read(buff));
assertEquals(text[0], buff[0]);
}
/**
* Purpose: Read content of length equal to the buffer size from the file Input: read(buffer)
* Expected: buffer = text n = len(buffer)
*/
@Test
public void read() throws IOException {
ss.open();
byte[] buff = new byte[10];
int n = ss.read(buff);
byte[] temp = Arrays.copyOfRange(text, 0, buff.length);
assertArrayEquals(temp, buff);
assertEquals(buff.length, n);
}
/**
* Purpose: Read content from the file with the buffer size bigger than length of the text in the
* file Input: read(buffer) Expected: buffer = text n = len
*/
@Test
public void readExceed() throws IOException {
ss.open();
byte[] buff = new byte[100];
int n = ss.read(buff);
// erase dummy values in the end of buffer
byte[] buffer = Arrays.copyOfRange(buff, 0, n);
assertArrayEquals(text, buffer);
assertEquals(text.length, n);
}
/**
* Purpose: Throw an exception when reading happen on a closed file Input: read(buffer) Expected:
* IOException is thrown
*/
@Test(expected = IOException.class)
public void readClosedException() throws IOException {
ss.open();
ss.close();
byte[] buff = new byte[text.length];
int n = ss.read(buff);
}
/**
* Purpose: Read content in certain positions of the buffer from the file Input: read(buffer,
* startPosition, endPosition) Expected: buffer = text n = endPosition
*/
@Test
public void readStartEnd() throws IOException {
ss.open();
byte[] buff = new byte[100];
int start = 5;
int end = 10;
int n = ss.read(buff, start, end);
byte[] file = Arrays.copyOfRange(text, 0, end - start);
byte[] buffer = Arrays.copyOfRange(buff, start, end);
assertArrayEquals(file, buffer);
assertEquals(end, n);
}
/**
* Purpose: Throw an exception when start and/or end positions for writing in the buffer exceed
* size of the buffer Input: read(buffer, startPosition, endPosition) Expected:
* <API key> is thrown
*/
@Test(expected = <API key>.class)
public void <API key>() throws IOException {
ss.open();
byte[] buff = new byte[100];
int start = 95;
int end = 110;
ss.read(buff, start, end);
}
/**
* Purpose: Throw an exception when reading happen on a closed file Input: read(buffer,
* startPosition, endPosition) Expected: IOException is thrown
*/
@Test(expected = IOException.class)
public void <API key>() throws IOException {
ss.open();
ss.close();
byte[] buff = new byte[100];
int start = 5;
int end = 10;
int n = ss.read(buff, start, end);
}
/**
* Purpose: Read content of the file from a certain position Input: moveTo(readPosition),
* read(buff) Expected: buff = text[readPosition] n = buff.length
*/
@Test
public void moveTo() throws IOException {
int readPosition = text.length - 10;
byte[] buff = new byte[1];
ss.moveTo(readPosition);
ss.open();
int n = ss.read(buff);
assertEquals(text[readPosition], buff[0]);
assertEquals(buff.length, n);
}
/**
* Purpose: Throw an exception when a reading position in the file is incorrect Input:
* moveTo(wrongPosition) Expected: <API key> is thrown
*/
@Test(expected = <API key>.class)
public void moveToException() throws <API key>, IOException {
ss.open();
ss.moveTo(-1);
}
/**
* Purpose: Close file after successful reading Input: no Expected: Stream is closed and reading
* from the file is unavailable
*/
@Test
public void close() throws IOException {
ss.open();
ss.close();
int n = -1;
try {
byte[] buff = new byte[1];
n = ss.read(buff);
} catch (IOException ignored) {
}
assertEquals(-1, n);
}
/** Purpose: Get MIME type Input: no Expected: return "txt" */
@Test
public void getMimeType() {
assertEquals("txt", ss.getMimeType());
}
/** Purpose: Get length of the text from a file Input: no Expected: return len */
@Test
public void length() {
assertEquals(text.length, ss.length());
}
/** Purpose: Get name of a file Input: no Expected: return "Test.txt" */
@Test
public void getName() {
assertEquals(file.getName(), ss.getName());
}
/**
* Purpose: Get available to read remain amount of text from a file Input: no Expected: return
* amount
*/
@Test
public void available() throws IOException {
int amount = 12;
ss.moveTo(text.length - amount);
assertEquals(amount, ss.availableExact());
}
/** Purpose: Move reading position to the beginning of a file Input: no Expected: return len */
@Test
public void reset() throws IOException {
ss.moveTo(10);
assertEquals(text.length - 10, ss.availableExact());
ss.reset();
assertEquals(text.length, ss.availableExact());
}
/** Purpose: Get a file object Input: no Expected: return SmbFile */
@Test
public void getFile() {
assertEquals(file, ss.getFile());
}
}
|
#ifndef _ADDRESSES_H_
#define _ADDRESSES_H_
#pragma warning(disable : 4731)
#define RCT2_ADDRESS(address, type) ((type*)(address))
#define RCT2_GLOBAL(address, type) (*((type*)(address)))
#define RCT2_CALLPROC(address) (((void(*)())(address))())
#define RCT2_CALLFUNC(address, returnType) ((((returnType)(*)())(address))())
#define RCT2_CALLFUNC_1(address, returnType, a1, v1) (((returnType(*)(a1))(address))(v1))
#define RCT2_CALLFUNC_2(address, returnType, a1, a2, v1, v2) (((returnType(*)(a1, a2))(address))(v1, v2))
#define RCT2_CALLFUNC_3(address, returnType, a1, a2, a3, v1, v2, v3) (((returnType(*)(a1, a2, a3))(address))(v1, v2, v3))
#define RCT2_CALLFUNC_4(address, returnType, a1, a2, a3, a4, v1, v2, v3, v4) (((returnType(*)(a1, a2, a3, a4))(address))(v1, v2, v3, v4))
#define RCT2_CALLFUNC_5(address, returnType, a1, a2, a3, a4, a5, v1, v2, v3, v4, v5) (((returnType(*)(a1, a2, a3, a4, a5))(address))(v1, v2, v3, v4, v5))
#define RCT2_CALLPROC_1(address, a1, v1) RCT2_CALLFUNC_1(address, void, a1, v1)
#define RCT2_CALLPROC_2(address, a1, a2, v1, v2) RCT2_CALLFUNC_2(address, void, a1, a2, v1, v2)
#define RCT2_CALLPROC_3(address, a1, a2, a3, v1, v2, v3) RCT2_CALLFUNC_3(address, void, a1, a2, a3, v1, v2, v3)
#define RCT2_CALLPROC_4(address, a1, a2, a3, a4, v1, v2, v3, v4) RCT2_CALLFUNC_4(address, void, a1, a2, a3, a4, v1, v2, v3, v4)
#define RCT2_CALLPROC_5(address, a1, a2, a3, a4, a5, v1, v2, v3, v4, v5) RCT2_CALLFUNC_5(address, void, a1, a2, a3, a4, a5, v1, v2, v3, v4, v5)
#define <API key> 0x00997c9d
#define <API key> 0x009A9800
#define <API key> 0x009A9FF4
#define <API key> 0x009AA008
#define <API key> 0x009AA214
#define <API key> 0x009AAC74
#define <API key> 0x009AAC78
#define <API key> 0x009AAC79
#define <API key> 0x009AAC7A
#define <API key> 0x009AACBA
#define <API key> 0x009AB4C2
#define <API key> 0x009AB4C4
#define <API key> 0x009AB4D9
#define <API key> 0x009AB5DA
#define <API key> 0x009AB6E9
#define <API key> 0x009AB7FB
#define <API key> 0x009AB90E
#define <API key> 0x009ABA1E
#define <API key> 0x009ABB37
#define <API key> 0x009ABDC8
#define <API key> 0x009ABDD8
#define <API key> 0x009ABDDA
#define <API key> 0x009ABDE4
#define <API key> 0x009ABDE6
#define <API key> 0x009ABDE8
#define <API key> 0x009ABDEC
#define <API key> 0x009AC319
#define <API key> 0x009DE51D
#define <API key> 0x009DE51F
#define <API key> 0x009DE520
#define <API key> 0x009DE524
#define <API key> 0x009DE52A
#define <API key> 0x009DE52C
#define <API key> 0x009DE52E
#define <API key> 0x009DE530
#define <API key> 0x009DE533
#define <API key> 0x009DE534
#define <API key> 0x009DE536
#define <API key> 0x009DE538
#define <API key> 0x009DE53A
#define <API key> 0x009DE53C
#define <API key> 0x009DE53E
#define <API key> 0x009DE542
#define <API key> 0x009DE544
#define <API key> 0x009DE546
#define <API key> 0x009DE55C
#define <API key> 0x009DE55E
#define <API key> 0x009DE560
#define <API key> 0x009DEA68
#define <API key> 0x009DEA6D
#define <API key> 0x009DEA70
#define <API key> 0x009DEA71
#define <API key> 0x009DEA74
#define <API key> 0x009E2D98
#define <API key> 0x009E2E1C
#define <API key> 0x009E2E20
#define <API key> 0x009E2E24
#define <API key> 0x009E2E25
#define <API key> 0x009EBD28
#define <API key> 0x00F663A8
#define <API key> 0x00F663AA
#define <API key> 0x00F663B8
#define <API key> 0x010E63BC
#define <API key> 0x013573BC
#define <API key> 0x013573BE
#define <API key> 0x013573C0
#define <API key> 0x013573C2
#define <API key> 0x013573C4
#define <API key> 0x013573E0
#define <API key> 0x013573E4
#define <API key> 0x013573E8
#define <API key> 0x01357844
#define <API key> 0x01357CB0
#define <API key> 0x01357CB2
#define <API key> 0x01357CD2
#define <API key> 0x013580F8
#define <API key> 0x013580F9
#define <API key> 0x013580FC
#define <API key> 0x01358100
#define <API key> 0x01358330
#define <API key> 0x0135853C
#define <API key> 0x01358740
#define <API key> 0x01358744
#define <API key> 0x01358748
#define <API key> 0x0135874C
#define <API key> 0x01358760
#define <API key> 0x013587F8
#define <API key> 0x01358834
#define <API key> 0x0135924A
#define <API key> 0x01359350
#define <API key> 0x01359358
#define <API key> 0x01359360
#define <API key> 0x013628F4
#define <API key> 0x013628F8
#define <API key> 0x0138B60C
#define <API key> 0x013CA746
#define <API key> 0x013CA74A
#define <API key> 0x013CA74B
#define <API key> 0x013CA74C
#define <API key> 0x013CA754
#define <API key> 0x013CE950
#define <API key> 0x013CE9A4
#define <API key> 0x0141E9E0
#define <API key> 0x0141F5B8
#define <API key> 0x01420078
#define <API key> 0x014234B8
#define <API key> 0x014234BC
#define <API key> 0x01423570
#define <API key> 0x01423A04
#define <API key> 0x01423B5C
#define <API key> 0x01424304
#define <API key> 0x01424320
#define <API key> 0x01423B20
static void <API key>(int address)
{
__asm push ebp
__asm call address
__asm pop ebp
}
static void RCT2_CALLPROC_X(int address, int _eax, int _ebx, int _ecx, int _edx, int _esi, int _edi, int _ebp)
{
__asm {
push address
mov eax, _eax
mov ebx, _ebx
mov ecx, _ecx
mov edx, _edx
mov esi, _esi
mov edi, _edi
mov ebp, _ebp
call [esp]
add esp, 4
}
}
static void RCT2_CALLFUNC_X(int address, int *_eax, int *_ebx, int *_ecx, int *_edx, int *_esi, int *_edi, int *_ebp)
{
__asm {
// Store C's base pointer
push ebp
// Store address to call
push address
// Set all registers to the input values
mov eax, [_eax]
mov eax, [eax]
mov ebx, [_ebx]
mov ebx, [ebx]
mov ecx, [_ecx]
mov ecx, [ecx]
mov edx, [_edx]
mov edx, [edx]
mov esi, [_esi]
mov esi, [esi]
mov edi, [_edi]
mov edi, [edi]
mov ebp, [_ebp]
mov ebp, [ebp]
// Call function
call [esp]
add esp, 4
// Store output eax
push eax
// Put original C base pointer into eax
mov eax, [esp+4]
// Store output ebp
push ebp
// Set ebp to the original C base pointer
mov ebp, eax
// Put output ebp into ebp parameter
mov eax, [esp]
mov [_ebp], eax
add esp, 4
// Get resulting ebx, ecx, edx, esi, edi registers
mov eax, [_edi]
mov [eax], edi
mov eax, [_esi]
mov [eax], esi
mov eax, [_edx]
mov [eax], edx
mov eax, [_ecx]
mov [eax], ecx
mov eax, [_ebx]
mov [eax], ebx
pop eax
// Get resulting eax register
mov ebx, [_eax]
mov [ebx], eax
add esp, 4
}
}
#endif
|
/*
* <API key>: 2008 Till Harbaum <till@harbaum.org>
*
* <API key>: GPL-3.0-or-later
*/
#include <gps_state.h>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <gps.h>
#include <gtk/gtk.h>
#include <mutex>
#include <unistd.h>
#include <osm2go_cpp.h>
#include <osm2go_platform.h>
#include <osm2go_platform_gtk.h>
namespace {
/* setup for direct gpsd based communication */
class gpsd_state_t : public gps_state_t {
public:
gpsd_state_t(GpsCallback cb, void *context);
gpsd_state_t() <API key>;
gpsd_state_t(const gpsd_state_t &) <API key>;
gpsd_state_t &operator=(const gpsd_state_t &) <API key>;
#if __cplusplus >= 201103L
gpsd_state_t(gpsd_state_t &&) = delete;
gpsd_state_t &operator=(gpsd_state_t &&) = delete;
#endif
~gpsd_state_t() override;
pos_t get_pos(float *alt) override;
void setEnable(bool en) override;
bool runCallback()
{
return callback(cb_context);
}
osm2go_platform::Timer timer;
GThread * const thread_p;
std::mutex mutex;
bool enable;
bool terminate;
gps_data_t gpsdata;
};
bool
gps_connect(gps_data_t &gps)
{
memset(&gps, 0, sizeof(gps));
if(gps_open("localhost", DEFAULT_GPSD_PORT, &gps) != 0)
return false;
if(gps_stream(&gps, WATCH_ENABLE | WATCH_JSON, nullptr) < 0)
return false;
return true;
}
gboolean
gps_callback(gpointer data)
{
return static_cast<gpsd_state_t *>(data)->runCallback() ? TRUE : FALSE;
}
inline bool
hasGpsFix(gps_data_t &gpsdata)
{
#if <API key> < 10
return (gpsdata.status != STATUS_NO_FIX);
#elif defined STATUS_UNK
return (gpsdata.fix.status != STATUS_UNK);
#else
return (gpsdata.fix.status != STATUS_NO_FIX);
#endif
}
#if <API key> >= 7
inline int
gps_read(gps_data_t *gps)
{
return gps_read(gps, nullptr, 0);
}
#endif
} // namespace
pos_t gpsd_state_t::get_pos(float* alt)
{
pos_t pos(NAN, NAN);
if(enable) {
std::lock_guard<std::mutex> lock(mutex);
if(gpsdata.set & STATUS_SET) {
if(hasGpsFix(gpsdata)) {
if(gpsdata.set & LATLON_SET) {
pos.lat = gpsdata.fix.latitude;
pos.lon = gpsdata.fix.longitude;
}
if(alt != nullptr && gpsdata.set & ALTITUDE_SET)
*alt = gpsdata.fix.altitude;
}
}
}
return pos;
}
void gpsd_state_t::setEnable(bool en)
{
if(!en && timer.isActive())
timer.stop();
else if(en && !timer.isActive())
timer.restart(1, gps_callback, this);
enable = en;
}
gpointer gps_thread(gpointer data) {
gpsd_state_t * const gps_state = static_cast<gpsd_state_t *>(data);
gps_state->gpsdata.set = 0;
gps_data_t gps;
bool connected = false;
while(!gps_state->terminate) {
if(gps_state->enable) {
if(!connected) {
g_debug("trying to connect");
connected = gps_connect(gps);
if(!connected)
sleep(10);
} else {
/* update every second, wait here to make sure a complete */
/* reply is received */
if(gps_waiting(&gps, 1000000)) {
int r = gps_read(&gps);
std::lock_guard<std::mutex> lock(gps_state->mutex);
if(G_LIKELY(r > 0))
gps_state->gpsdata = gps;
else
gps_clear_fix(&gps_state->gpsdata.fix);
}
}
} else {
if(connected) {
g_debug("stopping GPS connection due to user request");
gps_stream(&gps, WATCH_DISABLE, nullptr);
connected = false;
} else
sleep(1);
}
}
g_debug("GPS thread ended");
return nullptr;
}
gps_state_t *gps_state_t::create(GpsCallback cb, void *context) {
return new gpsd_state_t(cb, context);
}
gpsd_state_t::gpsd_state_t(GpsCallback cb, void *context)
: gps_state_t(cb, context)
, thread_p(g_thread_try_new("gps", gps_thread, this, nullptr))
, enable(false)
, terminate(false)
{
g_debug("GPS init: Using gpsd");
/* start a new thread to listen to gpsd */
}
gpsd_state_t::~gpsd_state_t()
{
terminate = true;
if(thread_p != nullptr)
g_thread_join(thread_p);
}
|
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>Yate: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">Yate
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.9.1 -->
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="namespaceTelEngine.html">TelEngine</a></li><li class="navelem"><a class="el" href="<API key>.html">Math</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">Math Member List</div> </div>
</div><!--header
<div class="contents">
<p>This is the complete list of members for <a class="el" href="<API key>.html">Math</a>, including all inherited members.</p>
<table class="directory">
<tr class="even"><td class="entry"><a class="el" href="<API key>.html#<API key>">dumpComplex</a>(String &buf, const Complex &val, const char *sep=0, const char *fmt=0)</td><td class="entry"><a class="el" href="<API key>.html">Math</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr><td class="entry"><a class="el" href="<API key>.html#<API key>">dumpFloat</a>(String &buf, const float &val, const char *sep=0, const char *fmt=0)</td><td class="entry"><a class="el" href="<API key>.html">Math</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
</table></div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Wed Mar 30 2016 15:06:04 for Yate by &
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.9.1
</small></address>
</body>
</html>
|
<?php
namespace Hideyo\Ecommerce\Backend\Models;
use Hideyo\Ecommerce\Backend\Models\BaseModel;
class <API key> extends BaseModel
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = '<API key>';
// Add the 'avatar' attachment to the fillable array so that it's mass-assignable on this model.
protected $fillable = ['category_id', 'product_id'];
public function shop()
{
return $this->belongsTo('Hideyo\Ecommerce\Backend\Models\Shop');
}
public function product()
{
return $this->belongsTo('Hideyo\Ecommerce\Backend\Models\Product');
}
public function productCategory()
{
return $this->belongsTo('Hideyo\Ecommerce\Backend\Models\ProductCategory');
}
}
|
import os
from .utils import exec_cmd, get_frappe, <API key>, get_config, build_assets, <API key>, get_cmd_output, run_frappe_cmd
import logging
import requests
import semantic_version
import json
import re
import subprocess
logger = logging.getLogger(__name__)
class <API key>(Exception):
def __init__(self, message, upstream_version, local_version):
super(<API key>, self).__init__(message)
self.upstream_version = upstream_version
self.local_version = local_version
def get_apps(bench='.'):
try:
with open(os.path.join(bench, 'sites', 'apps.txt')) as f:
return f.read().strip().split('\n')
except IOError:
return []
def add_to_appstxt(app, bench='.'):
apps = get_apps(bench=bench)
if app not in apps:
apps.append(app)
return write_appstxt(apps, bench=bench)
def remove_from_appstxt(app, bench='.'):
apps = get_apps(bench=bench)
if app in apps:
apps.remove(app)
return write_appstxt(apps, bench=bench)
def write_appstxt(apps, bench='.'):
with open(os.path.join(bench, 'sites', 'apps.txt'), 'w') as f:
return f.write('\n'.join(apps))
def get_app(app, git_url, branch=None, bench='.', build_asset_files=True):
logger.info('getting app {}'.format(app))
shallow_clone = '--depth 1' if <API key>() and get_config().get('shallow_clone') else ''
branch = '--branch {branch}'.format(branch=branch) if branch else ''
exec_cmd("git clone {git_url} {branch} {shallow_clone} --origin upstream {app}".format(
git_url=git_url,
app=app,
shallow_clone=shallow_clone,
branch=branch),
cwd=os.path.join(bench, 'apps'))
print 'installing', app
install_app(app, bench=bench)
if build_asset_files:
build_assets(bench=bench)
conf = get_config()
if conf.get('<API key>'):
<API key>(bench=bench)
def new_app(app, bench='.'):
logger.info('creating new app {}'.format(app))
apps = os.path.abspath(os.path.join(bench, 'apps'))
if FRAPPE_VERSION == 4:
exec_cmd("{frappe} --make_app {apps} {app}".format(frappe=get_frappe(bench=bench),
apps=apps, app=app))
else:
run_frappe_cmd('make-app', apps, app, bench=bench)
install_app(app, bench=bench)
def install_app(app, bench='.'):
logger.info('installing {}'.format(app))
conf = get_config()
find_links = '--find-links={}'.format(conf.get('wheel_cache_dir')) if conf.get('wheel_cache_dir') else ''
exec_cmd("{pip} install -q {find_links} -e {app}".format(
pip=os.path.join(bench, 'env', 'bin', 'pip'),
app=os.path.join(bench, 'apps', app),
find_links=find_links))
add_to_appstxt(app, bench=bench)
def pull_all_apps(bench='.'):
apps_dir = os.path.join(bench, 'apps')
apps = [app for app in os.listdir(apps_dir) if os.path.isdir(os.path.join(apps_dir, app))]
rebase = '--rebase' if get_config().get('rebase_on_pull') else ''
frappe_dir = os.path.join(apps_dir, 'frappe')
for app in apps:
app_dir = os.path.join(apps_dir, app)
if os.path.exists(os.path.join(app_dir, '.git')):
logger.info('pulling {0}'.format(app))
exec_cmd("git pull {rebase} upstream {branch}".format(rebase=rebase, branch=get_current_branch(app_dir)), cwd=app_dir)
def is_version_upgrade(bench='.'):
apps_dir = os.path.join(bench, 'apps')
frappe_dir = os.path.join(apps_dir, 'frappe')
fetch_upstream(frappe_dir)
upstream_version = <API key>(frappe_dir)
if not upstream_version:
raise Exception("Current branch not in upstream")
local_version = get_major_version(get_current_version(frappe_dir))
upstream_version = get_major_version(upstream_version)
if upstream_version - local_version > 0:
return (local_version, upstream_version)
return False
def <API key>(bench='.'):
apps_dir = os.path.join(bench, 'apps')
frappe_dir = os.path.join(apps_dir, 'frappe')
try:
return get_major_version(get_current_version(frappe_dir))
except IOError:
return ''
def get_current_branch(repo_dir):
return get_cmd_output("basename $(git symbolic-ref -q HEAD)", cwd=repo_dir)
def fetch_upstream(repo_dir):
return exec_cmd("git fetch upstream", cwd=repo_dir)
def get_current_version(repo_dir):
with open(os.path.join(repo_dir, 'setup.py')) as f:
return <API key>(f.read())
def <API key>(repo_dir):
try:
contents = subprocess.check_output(['git', 'show', 'upstream/{branch}:setup.py'.format(branch=get_current_branch(repo_dir))], cwd=repo_dir, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError, e:
if "Invalid object" in e.output:
return None
else:
raise
return <API key>(contents)
def switch_branch(branch, apps=None, bench='.'):
apps_dir = os.path.join(bench, 'apps')
if not apps:
apps = ('frappe', 'erpnext', 'shopping_cart')
for app in apps:
app_dir = os.path.join(apps_dir, app)
if os.path.exists(app_dir):
exec_cmd("git fetch upstream", cwd=app_dir)
exec_cmd("git checkout {branch}".format(branch=branch), cwd=app_dir)
def switch_to_master(apps=None, bench='.'):
switch_branch('master', apps=apps, bench=bench)
def switch_to_develop(apps=None, bench='.'):
switch_branch('develop', apps=apps, bench=bench)
def switch_to_v4(apps=None, bench='.'):
switch_branch('v4.x.x', apps=apps, bench=bench)
def <API key>(contents):
match = re.search(r"^(\s*%s\s*=\s*['\\\"])(.+?)(['\"])(?sm)" % 'version',
contents)
return match.group(2)
def get_major_version(version):
return semantic_version.Version(version).major
def <API key>(path, bench='.'):
apps = get_apps_json(path)
for app in apps:
get_app(app['name'], app['url'], branch=app.get('branch'), bench=bench, build_asset_files=False)
def get_apps_json(path):
if path.startswith('http'):
r = requests.get(path)
return r.json()
else:
with open(path) as f:
return json.load(f)
FRAPPE_VERSION = <API key>()
|
/* -*- buffer-read-only: t -*- vi: set ro: */
/* DO NOT EDIT! GENERATED AUTOMATICALLY! */
#ifndef _UNIWIDTH_H
#define _UNIWIDTH_H
#include "unitypes.h"
/* Get size_t. */
#include <stddef.h>
/* Get locale_charset() declaration. */
#include "localcharset.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Display width. */
/* These functions are locale dependent. The encoding argument identifies
the encoding (e.g. "ISO-8859-2" for Polish). */
/* Determine number of column positions required for UC. */
extern int
uc_width (ucs4_t uc, const char *encoding)
_UC_ATTRIBUTE_PURE;
/* Determine number of column positions required for first N units
(or fewer if S ends before this) in S. */
extern int
u8_width (const uint8_t *s, size_t n, const char *encoding)
_UC_ATTRIBUTE_PURE;
extern int
u16_width (const uint16_t *s, size_t n, const char *encoding)
_UC_ATTRIBUTE_PURE;
extern int
u32_width (const uint32_t *s, size_t n, const char *encoding)
_UC_ATTRIBUTE_PURE;
/* Determine number of column positions required for S. */
extern int
u8_strwidth (const uint8_t *s, const char *encoding)
_UC_ATTRIBUTE_PURE;
extern int
u16_strwidth (const uint16_t *s, const char *encoding)
_UC_ATTRIBUTE_PURE;
extern int
u32_strwidth (const uint32_t *s, const char *encoding)
_UC_ATTRIBUTE_PURE;
#ifdef __cplusplus
}
#endif
#endif /* _UNIWIDTH_H */
|
package gov.noaa.pmel.util;
import javax.swing.filechooser.*;
import java.io.File;
public class SimpleFileFilter extends FileFilter {
private String[] extensions;
private String description;
public SimpleFileFilter(String ext) {
this(new String[] {ext}, null);
}
public SimpleFileFilter(String[] exts, String descr) {
extensions = new String[exts.length];
for(int i=exts.length -1; i >=0; i
extensions[i]= exts[i].toLowerCase();
}
description = (descr ==null? exts[0] + " files" : descr);
}
public boolean accept(File f) {
if(f.isDirectory()) {return true;}
String name = f.getName().toLowerCase();
for(int i=extensions.length-1; i>=0; i
if(name.endsWith(extensions[i])) {
return true;
}
}
return false;
}
public boolean hasExtension(String ext) {
for(int i=0; i < extensions.length; i++) {
if(extensions[i].equals(ext)) return true;
}
return false;
}
public String getExtension() {
return getExtension(0);
}
public String getExtension(int index) {
int idx = index;
if(idx < 0 || idx >= extensions.length) idx = 0;
return extensions[idx];
}
public String getDescription() {
return description;
}
}
|
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_04) on Sat Jul 28 16:42:18 BST 2012 -->
<title>org.opensourcedea.utils</title>
<meta name="date" content="2012-07-28">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="org.opensourcedea.utils";
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="topNav"><a name="navbar_top">
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../org/opensourcedea/test/package-summary.html">Prev Package</a></li>
<li>Next Package</li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?org/opensourcedea/utils/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip-navbar_top">
</a></div>
<div class="header">
<h1 title="Package" class="title">Package org.opensourcedea.utils</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="packageSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation">
<caption><span>Class Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Class</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../org/opensourcedea/utils/MathUtils.html" title="class in org.opensourcedea.utils">MathUtils</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<div class="bottomNav"><a name="navbar_bottom">
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../org/opensourcedea/test/package-summary.html">Prev Package</a></li>
<li>Next Package</li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?org/opensourcedea/utils/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip-navbar_bottom">
</a></div>
</body>
</html>
|
/**
* @file util/<API key>.c
* @brief a version of hash map implemented in <API key>.c but with
* uint32_t as keys
* @author Christian Grothoff
* @author Sree Harsha Totakura
*/
#include "platform.h"
#include "<API key>.h"
#define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
/**
* An entry in the hash map.
*/
struct MapEntry
{
/**
* Key for the entry.
*/
uint32_t key;
/**
* Value of the entry.
*/
void *value;
/**
* If there is a hash collision, we create a linked list.
*/
struct MapEntry *next;
};
/**
* Internal representation of the hash map.
*/
struct <API key>
{
/**
* All of our buckets.
*/
struct MapEntry **map;
/**
* Number of entries in the map.
*/
unsigned int size;
/**
* Length of the "map" array.
*/
unsigned int map_length;
/**
* Counts the destructive modifications (grow, remove)
* to the map, so that iterators can check if they are still valid.
*/
unsigned int <API key>;
};
/**
* Cursor into a multihashmap.
* Allows to enumerate elements asynchronously.
*/
struct <API key>
{
/**
* Position in the bucket 'idx'
*/
struct MapEntry *me;
/**
* Current bucket index.
*/
unsigned int idx;
/**
* Modification counter as observed on the map when the iterator
* was created.
*/
unsigned int <API key>;
/**
* Map that we are iterating over.
*/
const struct <API key> *map;
};
/**
* Create a multi hash map.
*
* @param len initial size (map will grow as needed)
* @return NULL on error
*/
struct <API key> *
<API key> (unsigned int len)
{
struct <API key> *ret;
GNUNET_assert (len > 0);
ret = GNUNET_new (struct <API key>);
ret->map = GNUNET_malloc (len * sizeof (struct MapEntry *));
ret->map_length = len;
return ret;
}
/**
* Destroy a hash map. Will not free any values
* stored in the hash map!
*
* @param map the map
*/
void
<API key> (struct <API key>
*map)
{
unsigned int i;
struct MapEntry *e;
for (i = 0; i < map->map_length; i++)
{
while (NULL != (e = map->map[i]))
{
map->map[i] = e->next;
GNUNET_free (e);
}
}
GNUNET_free (map->map);
GNUNET_free (map);
}
/**
* Compute the index of the bucket for the given key.
*
* @param m hash map for which to compute the index
* @param key what key should the index be computed for
* @return offset into the "map" array of "m"
*/
static unsigned int
idx_of (const struct <API key> *m,
const uint32_t key)
{
GNUNET_assert (m != NULL);
return ((unsigned int) key) % m->map_length;
}
/**
* Get the number of key-value pairs in the map.
*
* @param map the map
* @return the number of key value pairs
*/
unsigned int
<API key> (const struct
<API key> *map)
{
return map->size;
}
/**
* Given a key find a value in the map matching the key.
*
* @param map the map
* @param key what to look for
* @return NULL if no value was found; note that
* this is indistinguishable from values that just
* happen to be NULL; use "contains" to test for
* key-value pairs with value NULL
*/
void *
<API key> (const struct
<API key> *map,
uint32_t key)
{
struct MapEntry *e;
e = map->map[idx_of (map, key)];
while (e != NULL)
{
if (key == e->key)
return e->value;
e = e->next;
}
return NULL;
}
/**
* Iterate over all entries in the map.
*
* @param map the map
* @param it function to call on each entry
* @param it_cls extra argument to @a it
* @return the number of key value pairs processed,
* #GNUNET_SYSERR if it aborted iteration
*/
int
<API key> (const struct
<API key> *map,
<API key> it,
void *it_cls)
{
int count;
unsigned int i;
struct MapEntry *e;
struct MapEntry *n;
count = 0;
GNUNET_assert (NULL != map);
for (i = 0; i < map->map_length; i++)
{
n = map->map[i];
while (NULL != (e = n))
{
n = e->next;
if (NULL != it)
{
if (GNUNET_OK != it (it_cls, e->key, e->value))
return GNUNET_SYSERR;
}
count++;
}
}
return count;
}
/**
* Remove the given key-value pair from the map. Note that if the
* key-value pair is in the map multiple times, only one of the pairs
* will be removed.
*
* @param map the map
* @param key key of the key-value pair
* @param value value of the key-value pair
* @return GNUNET_YES on success, GNUNET_NO if the key-value pair
* is not in the map
*/
int
<API key> (struct <API key>
*map,
uint32_t key, const void *value)
{
struct MapEntry *e;
struct MapEntry *p;
unsigned int i;
map-><API key>++;
i = idx_of (map, key);
p = NULL;
e = map->map[i];
while (e != NULL)
{
if ( (key == e->key) && (value == e->value) )
{
if (p == NULL)
map->map[i] = e->next;
else
p->next = e->next;
GNUNET_free (e);
map->size
return GNUNET_YES;
}
p = e;
e = e->next;
}
return GNUNET_NO;
}
/**
* Remove all entries for the given key from the map.
* Note that the values would not be "freed".
*
* @param map the map
* @param key identifies values to be removed
* @return number of values removed
*/
int
<API key> (struct
<API key>
*map,
uint32_t key)
{
struct MapEntry *e;
struct MapEntry *p;
unsigned int i;
int ret;
map-><API key>++;
ret = 0;
i = idx_of (map, key);
p = NULL;
e = map->map[i];
while (e != NULL)
{
if (key == e->key)
{
if (p == NULL)
map->map[i] = e->next;
else
p->next = e->next;
GNUNET_free (e);
map->size
if (p == NULL)
e = map->map[i];
else
e = p->next;
ret++;
}
else
{
p = e;
e = e->next;
}
}
return ret;
}
/**
* Check if the map contains any value under the given
* key (including values that are NULL).
*
* @param map the map
* @param key the key to test if a value exists for it
* @return GNUNET_YES if such a value exists,
* GNUNET_NO if not
*/
int
<API key> (const struct
<API key> *map,
uint32_t key)
{
struct MapEntry *e;
e = map->map[idx_of (map, key)];
while (e != NULL)
{
if (key == e->key)
return GNUNET_YES;
e = e->next;
}
return GNUNET_NO;
}
/**
* Check if the map contains the given value under the given
* key.
*
* @param map the map
* @param key the key to test if a value exists for it
* @param value value to test for
* @return GNUNET_YES if such a value exists,
* GNUNET_NO if not
*/
int
<API key> (const struct
<API key>
*map,
uint32_t key,
const void *value)
{
struct MapEntry *e;
e = map->map[idx_of (map, key)];
while (e != NULL)
{
if ( (key == e->key) && (e->value == value) )
return GNUNET_YES;
e = e->next;
}
return GNUNET_NO;
}
/**
* Grow the given map to a more appropriate size.
*
* @param map the hash map to grow
*/
static void
grow (struct <API key> *map)
{
struct MapEntry **old_map;
struct MapEntry **new_map;
struct MapEntry *e;
unsigned int old_len;
unsigned int new_len;
unsigned int idx;
unsigned int i;
map-><API key>++;
old_map = map->map;
old_len = map->map_length;
new_len = old_len * 2;
new_map = GNUNET_malloc (sizeof (struct MapEntry *) * new_len);
map->map_length = new_len;
map->map = new_map;
for (i = 0; i < old_len; i++)
{
while (NULL != (e = old_map[i]))
{
old_map[i] = e->next;
idx = idx_of (map, e->key);
e->next = new_map[idx];
new_map[idx] = e;
}
}
GNUNET_free (old_map);
}
/**
* Store a key-value pair in the map.
*
* @param map the map
* @param key key to use
* @param value value to use
* @param opt options for put
* @return GNUNET_OK on success,
* GNUNET_NO if a value was replaced (with REPLACE)
* GNUNET_SYSERR if UNIQUE_ONLY was the option and the
* value already exists
*/
int
<API key> (struct <API key>
*map, uint32_t key, void *value,
enum <API key>
opt)
{
struct MapEntry *e;
unsigned int i;
i = idx_of (map, key);
if ((opt != <API key>) &&
(opt != <API key>))
{
e = map->map[i];
while (e != NULL)
{
if (key == e->key)
{
if (opt == <API key>)
return GNUNET_SYSERR;
e->value = value;
return GNUNET_NO;
}
e = e->next;
}
}
if (map->size / 3 >= map->map_length / 4)
{
grow (map);
i = idx_of (map, key);
}
e = GNUNET_new (struct MapEntry);
e->key = key;
e->value = value;
e->next = map->map[i];
map->map[i] = e;
map->size++;
return GNUNET_OK;
}
/**
* Iterate over all entries in the map that match a particular key.
*
* @param map the map
* @param key key that the entries must correspond to
* @param it function to call on each entry
* @param it_cls extra argument to it
* @return the number of key value pairs processed,
* GNUNET_SYSERR if it aborted iteration
*/
int
<API key> (const struct
<API key>
*map, uint32_t key,
<API key>
it, void *it_cls)
{
int count;
struct MapEntry *e;
struct MapEntry *n;
count = 0;
n = map->map[idx_of (map, key)];
while (NULL != (e = n))
{
n = e->next;
if (key != e->key)
continue;
if ((it != NULL) && (GNUNET_OK != it (it_cls, key, e->value)))
return GNUNET_SYSERR;
count++;
}
return count;
}
/**
* Create an iterator for a multihashmap.
* The iterator can be used to retrieve all the elements in the multihashmap
* one by one, without having to handle all elements at once (in contrast to
* <API key>()). Note that the iterator can not be
* used anymore if elements have been removed from 'map' after the creation of
* the iterator, or 'map' has been destroyed. Adding elements to 'map' may
* result in skipped or repeated elements.
*
* @param map the map to create an iterator for
* @return an iterator over the given multihashmap 'map'
*/
struct <API key> *
<API key> (const struct <API key> *map)
{
struct <API key> *iter;
iter = GNUNET_new (struct <API key>);
iter->map = map;
iter-><API key> = map-><API key>;
iter->me = map->map[0];
return iter;
}
/**
* Retrieve the next element from the hash map at the iterator's position.
* If there are no elements left, GNUNET_NO is returned, and 'key' and 'value'
* are not modified.
* This operation is only allowed if no elements have been removed from the
* multihashmap since the creation of 'iter', and the map has not been destroyed.
* Adding elements may result in repeating or skipping elements.
*
* @param iter the iterator to get the next element from
* @param key pointer to store the key in, can be NULL
* @param value pointer to store the value in, can be NULL
* @return #GNUNET_YES we returned an element,
* #GNUNET_NO if we are out of elements
*/
int
<API key> (struct <API key> *iter,
uint32_t *key,
const void **value)
{
/* make sure the map has not been modified */
GNUNET_assert (iter-><API key> == iter->map-><API key>);
/* look for the next entry, skipping empty buckets */
while (1)
{
if (iter->idx >= iter->map->map_length)
return GNUNET_NO;
if (NULL != iter->me)
{
if (NULL != key)
*key = iter->me->key;
if (NULL != value)
*value = iter->me->value;
iter->me = iter->me->next;
return GNUNET_YES;
}
iter->idx += 1;
if (iter->idx < iter->map->map_length)
iter->me = iter->map->map[iter->idx];
}
}
/**
* Destroy a multihashmap iterator.
*
* @param iter the iterator to destroy
*/
void
<API key> (struct <API key> *iter)
{
GNUNET_free (iter);
}
/* end of <API key>.c */
|
package com.sosnitzka.taiga.recipes;
import com.sosnitzka.taiga.Blocks;
import com.sosnitzka.taiga.Items;
import com.sosnitzka.taiga.TAIGA;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.common.registry.GameRegistry;
public class CraftingRegistry {
public static void register() {
convertion(Item.getItemFromBlock(Blocks.tiberiumBlock), Items.tiberiumIngot, Items.tiberiumNugget);
convertion(Item.getItemFromBlock(Blocks.auroriumBlock), Items.auroriumIngot, Items.auroriumNugget);
convertion(Item.getItemFromBlock(Blocks.prometheumBlock), Items.prometheumIngot, Items.prometheumNugget);
convertion(Item.getItemFromBlock(Blocks.duraniteBlock), Items.duraniteIngot, Items.duraniteNugget);
convertion(Item.getItemFromBlock(Blocks.valyriumBlock), Items.valyriumIngot, Items.valyriumNugget);
convertion(Item.getItemFromBlock(Blocks.vibraniumBlock), Items.vibraniumIngot, Items.vibraniumNugget);
convertion(Item.getItemFromBlock(Blocks.karmesineBlock), Items.karmesineIngot, Items.karmesineNugget);
convertion(Item.getItemFromBlock(Blocks.oviumBlock), Items.oviumIngot, Items.oviumNugget);
convertion(Item.getItemFromBlock(Blocks.jauxumBlock), Items.jauxumIngot, Items.jauxumNugget);
convertion(Item.getItemFromBlock(Blocks.palladiumBlock), Items.palladiumIngot, Items.palladiumNugget);
convertion(Item.getItemFromBlock(Blocks.uruBlock), Items.uruIngot, Items.uruNugget);
convertion(Item.getItemFromBlock(Blocks.osramBlock), Items.osramIngot, Items.osramNugget);
convertion(Item.getItemFromBlock(Blocks.eezoBlock), Items.eezoIngot, Items.eezoNugget);
convertion(Item.getItemFromBlock(Blocks.abyssumBlock), Items.abyssumIngot, Items.abyssumNugget);
convertion(Item.getItemFromBlock(Blocks.terraxBlock), Items.terraxIngot, Items.terraxNugget);
convertion(Item.getItemFromBlock(Blocks.triberiumBlock), Items.triberiumIngot, Items.triberiumNugget);
convertion(Item.getItemFromBlock(Blocks.fractumBlock), Items.fractumIngot, Items.fractumNugget);
convertion(Item.getItemFromBlock(Blocks.violiumBlock), Items.violiumIngot, Items.violiumNugget);
convertion(Item.getItemFromBlock(Blocks.proxiiBlock), Items.proxiiIngot, Items.proxiiNugget);
convertion(Item.getItemFromBlock(Blocks.tritoniteBlock), Items.tritoniteIngot, Items.tritoniteNugget);
convertion(Item.getItemFromBlock(Blocks.ignitzBlock), Items.ignitzIngot, Items.ignitzNugget);
convertion(Item.getItemFromBlock(Blocks.imperomiteBlock), Items.imperomiteIngot, Items.imperomiteNugget);
convertion(Item.getItemFromBlock(Blocks.solariumBlock), Items.solariumIngot, Items.solariumNugget);
convertion(Item.getItemFromBlock(Blocks.nihiliteBlock), Items.nihiliteIngot, Items.nihiliteNugget);
convertion(Item.getItemFromBlock(Blocks.adamantBlock), Items.adamantIngot, Items.adamantNugget);
convertion(Item.getItemFromBlock(Blocks.dyoniteBlock), Items.dyoniteIngot, Items.dyoniteNugget);
convertion(Item.getItemFromBlock(Blocks.nucleumBlock), Items.nucleumIngot, Items.nucleumNugget);
convertion(Item.getItemFromBlock(Blocks.lumixBlock), Items.lumixIngot, Items.lumixNugget);
convertion(Item.getItemFromBlock(Blocks.seismumBlock), Items.seismumIngot, Items.seismumNugget);
convertion(Item.getItemFromBlock(Blocks.astriumBlock), Items.astriumIngot, Items.astriumNugget);
convertion(Item.getItemFromBlock(Blocks.niobBlock), Items.niobIngot, Items.niobNugget);
convertion(Item.getItemFromBlock(Blocks.yrdeenBlock), Items.yrdeenIngot, Items.yrdeenNugget);
convertion(Item.getItemFromBlock(Blocks.ioxBlock), Items.ioxIngot, Items.ioxNugget);
convertion(Item.getItemFromBlock(Blocks.blockMeteorite), Items.meteoriteIngot, Items.meteoriteNugget);
convertion(Item.getItemFromBlock(Blocks.blockObsidiorite), Items.obsidioriteIngot, Items.obsidioriteNugget);
convertion(Item.getItemFromBlock(Blocks.dilithiumBlock), Items.dilithiumIngot, Items.dilithiumNugget);
//convertion(Item.getItemFromBlock(Blocks.), Items., Items.);
}
public static void convertion(Item block, Item ingot, Item nugget) {
//GameData.register_impl(new ShapedOreRecipe());
//GameData.register_impl(new ShapedOreRecipe(new ResourceLocation(""), new ItemStack(ingot), "
// "###", '#', new ItemStack(nugget)));
//GameRegistry.addShapedRecipe(new ResourceLocation(TAIGA.MODID + ":<API key>" + block.getUnlocalizedName()), new ResourceLocation(""), new ItemStack(block), "
GameRegistry.addShapelessRecipe(new ResourceLocation(TAIGA.MODID + ":<API key>" + block
.getUnlocalizedName()), new ResourceLocation(""), new ItemStack(ingot, 9), Ingredient.fromStacks(new
ItemStack(block)));
GameRegistry.addShapelessRecipe(new ResourceLocation(TAIGA.MODID + ":<API key>" + block
.getUnlocalizedName()), new ResourceLocation(""), new ItemStack(nugget, 9), Ingredient.fromStacks(new
ItemStack(ingot)));
}
}
|
#!/usr/bin/env python
# pylint: disable=C0103,W0622
# A library that provides a Python interface to the Telegram Bot API
# This program is free software: you can redistribute it and/or modify
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
"""This module contains a object that represents a Telegram User"""
from telegram import TelegramObject
class User(TelegramObject):
"""This object represents a Telegram User.
Attributes:
id (int):
first_name (str):
last_name (str):
username (str):
Args:
id (int):
first_name (str):
**kwargs: Arbitrary keyword arguments.
Keyword Args:
last_name (Optional[str]):
username (Optional[str]):
"""
def __init__(self,
id,
first_name,
**kwargs):
# Required
self.id = int(id)
self.first_name = first_name
# Optionals
self.last_name = kwargs.get('last_name', '')
self.username = kwargs.get('username', '')
@property
def name(self):
"""str: """
if self.username:
return '@%s' % self.username
if self.last_name:
return '%s %s' % (self.first_name, self.last_name)
return self.first_name
@staticmethod
def de_json(data):
"""
Args:
data (str):
Returns:
telegram.User:
"""
if not data:
return None
return User(**data)
|
<?php
/**
* The default page template
*
* @package Flint\Pistons
* @since 0.1.0
*/
get_header(); ?>
<?php flint_get_sidebar('header'); ?>
<?php while ( have_posts() ) : the_post(); ?>
<div id="prologue-wrap">
<section id="prologue" class="container">
<div class="row">
<header class="page-header col-xs-12">
<h1 class="page-title"><?php echo the_title(); ?></h1>
<?php if ( current_user_can('edit_posts') ) { ?><a class="btn btn-default btn-sm btn-edit hidden-xs" href="<?php echo get_edit_post_link(); ?>">Edit</a><?php } ?>
</header><!-- .page-header -->
</div><!-- .row -->
</section><!-- #prologue -->
</div><!-- #prologue-wrap -->
<div id="primary" class="content-area container">
<div class="row">
<?php
if ( function_exists( 'flint_post_margin' ) ) {
flint_post_margin( true );
} else {
flint_get_spacer( 'left' );
}
?>
<div id="content" role="main" <?php flint_content_class(); ?>>
<div class="row">
<article id="post-<?php the_ID(); ?>" <?php post_class('col-xs-12'); ?>>
<header class="entry-header">
<?php $type = get_post_type(); ?>
<?php do_action('<API key>'.$type); ?>
<div class="entry-meta">
<?php do_action('<API key>'.$type); ?>
</div><!-- .entry-meta -->
<?php do_action('<API key>'.$type); ?>
</header><!-- .entry-header -->
<?php if ( is_search() ) : ?>
<div class="entry-summary">
<?php the_excerpt(); ?>
</div><!-- .entry-summary -->
<?php else : ?>
<div class="entry-content">
<?php flint_the_content(); ?>
<?php
flint_link_pages( array(
'before' => '<ul class="pagination">',
'after' => '</ul>',
) ); ?>
</div><!-- .entry-content -->
<?php endif; ?>
</article><!-- #page-<?php the_ID(); ?> -->
</div><!-- .row -->
<?php if ( comments_open() || '0' != get_comments_number() ) { comments_template(); } ?>
</div><!-- #content -->
<?php
if ( function_exists( 'flint_post_margin' ) ) {
flint_post_margin();
} else {
flint_get_spacer( 'right' );
}
?>
</div><!-- .row -->
</div><!-- #primary -->
<?php endwhile; ?>
</div><!-- #page -->
<?php flint_get_sidebar('footer'); ?>
<?php get_footer(); ?>
|
// <API key>: GPL-2.0+
#include "exporterregistry.h"
#include "exporterinterface.h"
#include <algorithm>
#include "<API key>.h"
#include "post/ppresult.h"
#include "settings.h"
ExporterRegistry::ExporterRegistry(const Dso::<API key> *deviceSpecification, DsoSettings *settings,
QObject *parent)
: QObject(parent), deviceSpecification(deviceSpecification), settings(settings) {}
bool ExporterRegistry::processData(std::shared_ptr<PPresult> &data, ExporterInterface *const &exporter) {
if (!exporter->samples(data)) {
waitToSaveExporters.insert(exporter);
emit <API key>();
return true;
}
return false;
}
void ExporterRegistry::addRawSamples(PPresult *d) {
if (settings->exporting.useProcessedSamples) return;
std::shared_ptr<PPresult> data(d);
enabledExporters.remove_if([&data, this](ExporterInterface *const &i) { return processData(data, i); });
}
void ExporterRegistry::input(std::shared_ptr<PPresult> data) {
if (!settings->exporting.useProcessedSamples) return;
enabledExporters.remove_if([&data, this](ExporterInterface *const &i) { return processData(data, i); });
}
void ExporterRegistry::registerExporter(ExporterInterface *exporter) {
exporters.push_back(exporter);
exporter->create(this);
}
void ExporterRegistry::setExporterEnabled(ExporterInterface *exporter, bool enabled) {
bool wasInList = false;
enabledExporters.remove_if([exporter, &wasInList](ExporterInterface *inlist) {
if (inlist == exporter) {
wasInList = true;
return true;
} else
return false;
});
if (enabled) {
// If the exporter was waiting for the user save confirmation,
// reset it instead.
auto localFind = waitToSaveExporters.find(exporter);
if (localFind != waitToSaveExporters.end()) {
waitToSaveExporters.erase(localFind);
exporter->create(this);
}
enabledExporters.push_back(exporter);
} else if (wasInList) {
// If exporter made some progress: Add to waiting for GUI list
if (exporter->progress() > 0) {
waitToSaveExporters.insert(exporter);
emit <API key>();
} else // Reset exporter
exporter->create(this);
}
}
void ExporterRegistry::<API key>() {
for (ExporterInterface *exporter : waitToSaveExporters) {
if (exporter->save()) {
emit <API key>(exporter->name(), tr("Data saved"));
} else {
emit <API key>(exporter->name(), tr("No data exported"));
}
exporter->create(this);
}
waitToSaveExporters.clear();
}
std::vector<ExporterInterface *>::const_iterator ExporterRegistry::begin() { return exporters.begin(); }
std::vector<ExporterInterface *>::const_iterator ExporterRegistry::end() { return exporters.end(); }
|
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_24) on Sat Jul 09 05:08:30 CEST 2011 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
All Classes
</TITLE>
<META NAME="date" CONTENT="2011-07-09">
<LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">
</HEAD>
<BODY BGCOLOR="white">
<FONT size="+1" CLASS="FrameHeadingFont">
<B>All Classes</B></FONT>
<BR>
<TABLE BORDER="0" WIDTH="100%" SUMMARY="">
<TR>
<TD NOWRAP><FONT CLASS="FrameItemFont"><A HREF="kr/ac/kaist/swrc/jhannanum/plugin/MajorPlugin/MorphAnalyzer/ChartMorphAnalyzer/AnalyzedDic.html" title="class in kr.ac.kaist.swrc.jhannanum.plugin.MajorPlugin.MorphAnalyzer.ChartMorphAnalyzer">AnalyzedDic</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/plugin/MajorPlugin/MorphAnalyzer/ChartMorphAnalyzer/ChartMorphAnalyzer.html" title="class in kr.ac.kaist.swrc.jhannanum.plugin.MajorPlugin.MorphAnalyzer.ChartMorphAnalyzer">ChartMorphAnalyzer</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/share/Code.html" title="class in kr.ac.kaist.swrc.jhannanum.share">Code</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/comm/CommObject.html" title="class in kr.ac.kaist.swrc.jhannanum.comm">CommObject</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/plugin/MajorPlugin/MorphAnalyzer/ChartMorphAnalyzer/Connection.html" title="class in kr.ac.kaist.swrc.jhannanum.plugin.MajorPlugin.MorphAnalyzer.ChartMorphAnalyzer">Connection</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/plugin/MajorPlugin/MorphAnalyzer/ChartMorphAnalyzer/ConnectionNot.html" title="class in kr.ac.kaist.swrc.jhannanum.plugin.MajorPlugin.MorphAnalyzer.ChartMorphAnalyzer">ConnectionNot</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/comm/Eojeol.html" title="class in kr.ac.kaist.swrc.jhannanum.comm">Eojeol</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/plugin/MajorPlugin/MorphAnalyzer/ChartMorphAnalyzer/Exp.html" title="class in kr.ac.kaist.swrc.jhannanum.plugin.MajorPlugin.MorphAnalyzer.ChartMorphAnalyzer">Exp</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/demo/GUIDemo.html" title="class in kr.ac.kaist.swrc.jhannanum.demo">GUIDemo</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/plugin/MajorPlugin/PosTagger/HmmPosTagger/HMMTagger.html" title="class in kr.ac.kaist.swrc.jhannanum.plugin.MajorPlugin.PosTagger.HmmPosTagger">HMMTagger</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/plugin/SupplementPlugin/PlainTextProcessor/<API key>/<API key>.html" title="class in kr.ac.kaist.swrc.jhannanum.plugin.SupplementPlugin.PlainTextProcessor.<API key>"><API key></A>
<BR>
<A HREF="org/json/JSONArray.html" title="class in org.json">JSONArray</A>
<BR>
<A HREF="org/json/JSONException.html" title="class in org.json">JSONException</A>
<BR>
<A HREF="org/json/JSONObject.html" title="class in org.json">JSONObject</A>
<BR>
<A HREF="org/json/JSONObject.Null.html" title="class in org.json">JSONObject.Null</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/share/JSONReader.html" title="class in kr.ac.kaist.swrc.jhannanum.share">JSONReader</A>
<BR>
<A HREF="org/json/JSONString.html" title="interface in org.json"><I>JSONString</I></A>
<BR>
<A HREF="org/json/JSONStringer.html" title="class in org.json">JSONStringer</A>
<BR>
<A HREF="org/json/JSONTokener.html" title="class in org.json">JSONTokener</A>
<BR>
<A HREF="org/json/JSONWriter.html" title="class in org.json">JSONWriter</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/demo/ManualWorkflowSetUp.html" title="class in kr.ac.kaist.swrc.jhannanum.demo">ManualWorkflowSetUp</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/plugin/MajorPlugin/MorphAnalyzer/MorphAnalyzer.html" title="interface in kr.ac.kaist.swrc.jhannanum.plugin.MajorPlugin.MorphAnalyzer"><I>MorphAnalyzer</I></A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/thread/MorphAnalyzerThread.html" title="class in kr.ac.kaist.swrc.jhannanum.thread">MorphAnalyzerThread</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/plugin/MajorPlugin/MorphAnalyzer/ChartMorphAnalyzer/MorphemeChart.html" title="class in kr.ac.kaist.swrc.jhannanum.plugin.MajorPlugin.MorphAnalyzer.ChartMorphAnalyzer">MorphemeChart</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/plugin/SupplementPlugin/MorphemeProcessor/MorphemeProcessor.html" title="interface in kr.ac.kaist.swrc.jhannanum.plugin.SupplementPlugin.MorphemeProcessor"><I>MorphemeProcessor</I></A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/thread/MorphemeProcThread.html" title="class in kr.ac.kaist.swrc.jhannanum.thread">MorphemeProcThread</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/plugin/SupplementPlugin/PosProcessor/NounExtractor/NounExtractor.html" title="class in kr.ac.kaist.swrc.jhannanum.plugin.SupplementPlugin.PosProcessor.NounExtractor">NounExtractor</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/plugin/MajorPlugin/MorphAnalyzer/ChartMorphAnalyzer/NumberDic.html" title="class in kr.ac.kaist.swrc.jhannanum.plugin.MajorPlugin.MorphAnalyzer.ChartMorphAnalyzer">NumberDic</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/plugin/MajorPlugin/PosTagger/HmmPosTagger/PhraseTag.html" title="class in kr.ac.kaist.swrc.jhannanum.plugin.MajorPlugin.PosTagger.HmmPosTagger">PhraseTag</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/comm/PlainSentence.html" title="class in kr.ac.kaist.swrc.jhannanum.comm">PlainSentence</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/plugin/SupplementPlugin/PlainTextProcessor/PlainTextProcessor.html" title="interface in kr.ac.kaist.swrc.jhannanum.plugin.SupplementPlugin.PlainTextProcessor"><I>PlainTextProcessor</I></A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/thread/PlainTextProcThread.html" title="class in kr.ac.kaist.swrc.jhannanum.thread">PlainTextProcThread</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/plugin/Plugin.html" title="interface in kr.ac.kaist.swrc.jhannanum.plugin"><I>Plugin</I></A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/plugin/SupplementPlugin/PosProcessor/PosProcessor.html" title="interface in kr.ac.kaist.swrc.jhannanum.plugin.SupplementPlugin.PosProcessor"><I>PosProcessor</I></A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/thread/PosProcThread.html" title="class in kr.ac.kaist.swrc.jhannanum.thread">PosProcThread</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/plugin/MajorPlugin/PosTagger/PosTagger.html" title="interface in kr.ac.kaist.swrc.jhannanum.plugin.MajorPlugin.PosTagger"><I>PosTagger</I></A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/thread/PosTaggerThread.html" title="class in kr.ac.kaist.swrc.jhannanum.thread">PosTaggerThread</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/plugin/MajorPlugin/MorphAnalyzer/ChartMorphAnalyzer/PostProcessor.html" title="class in kr.ac.kaist.swrc.jhannanum.plugin.MajorPlugin.MorphAnalyzer.ChartMorphAnalyzer">PostProcessor</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/plugin/MajorPlugin/PosTagger/HmmPosTagger/ProbabilityDBM.html" title="class in kr.ac.kaist.swrc.jhannanum.plugin.MajorPlugin.PosTagger.HmmPosTagger">ProbabilityDBM</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/exception/ResultTypeException.html" title="class in kr.ac.kaist.swrc.jhannanum.exception">ResultTypeException</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/plugin/MajorPlugin/MorphAnalyzer/ChartMorphAnalyzer/SegmentPosition.html" title="class in kr.ac.kaist.swrc.jhannanum.plugin.MajorPlugin.MorphAnalyzer.ChartMorphAnalyzer">SegmentPosition</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/comm/Sentence.html" title="class in kr.ac.kaist.swrc.jhannanum.comm">Sentence</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/plugin/SupplementPlugin/PlainTextProcessor/SentenceSegmentor/SentenceSegmentor.html" title="class in kr.ac.kaist.swrc.jhannanum.plugin.SupplementPlugin.PlainTextProcessor.SentenceSegmentor">SentenceSegmentor</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/comm/SetOfSentences.html" title="class in kr.ac.kaist.swrc.jhannanum.comm">SetOfSentences</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/plugin/SupplementPlugin/MorphemeProcessor/SimpleMAResult09/SimpleMAResult09.html" title="class in kr.ac.kaist.swrc.jhannanum.plugin.SupplementPlugin.MorphemeProcessor.SimpleMAResult09">SimpleMAResult09</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/plugin/SupplementPlugin/MorphemeProcessor/SimpleMAResult22/SimpleMAResult22.html" title="class in kr.ac.kaist.swrc.jhannanum.plugin.SupplementPlugin.MorphemeProcessor.SimpleMAResult22">SimpleMAResult22</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/plugin/SupplementPlugin/PosProcessor/SimplePOSResult09/SimplePOSResult09.html" title="class in kr.ac.kaist.swrc.jhannanum.plugin.SupplementPlugin.PosProcessor.SimplePOSResult09">SimplePOSResult09</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/plugin/SupplementPlugin/PosProcessor/SimplePOSResult22/SimplePOSResult22.html" title="class in kr.ac.kaist.swrc.jhannanum.plugin.SupplementPlugin.PosProcessor.SimplePOSResult22">SimplePOSResult22</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/plugin/MajorPlugin/MorphAnalyzer/ChartMorphAnalyzer/Simti.html" title="class in kr.ac.kaist.swrc.jhannanum.plugin.MajorPlugin.MorphAnalyzer.ChartMorphAnalyzer">Simti</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/share/TagMapper.html" title="class in kr.ac.kaist.swrc.jhannanum.share">TagMapper</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/exception/TagMappingException.html" title="class in kr.ac.kaist.swrc.jhannanum.exception">TagMappingException</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/share/TagSet.html" title="class in kr.ac.kaist.swrc.jhannanum.share">TagSet</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/plugin/MajorPlugin/MorphAnalyzer/ChartMorphAnalyzer/Trie.html" title="class in kr.ac.kaist.swrc.jhannanum.plugin.MajorPlugin.MorphAnalyzer.ChartMorphAnalyzer">Trie</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/plugin/SupplementPlugin/MorphemeProcessor/<API key>/UnknownProcessor.html" title="class in kr.ac.kaist.swrc.jhannanum.plugin.SupplementPlugin.MorphemeProcessor.<API key>">UnknownProcessor</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/hannanum/Workflow.html" title="class in kr.ac.kaist.swrc.jhannanum.hannanum">Workflow</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/hannanum/WorkflowFactory.html" title="class in kr.ac.kaist.swrc.jhannanum.hannanum">WorkflowFactory</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/demo/<API key>.html" title="class in kr.ac.kaist.swrc.jhannanum.demo"><API key></A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/demo/<API key>.html" title="class in kr.ac.kaist.swrc.jhannanum.demo"><API key></A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/demo/<API key>.html" title="class in kr.ac.kaist.swrc.jhannanum.demo"><API key></A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/demo/WorkflowSimplePos09.html" title="class in kr.ac.kaist.swrc.jhannanum.demo">WorkflowSimplePos09</A>
<BR>
<A HREF="kr/ac/kaist/swrc/jhannanum/demo/WorkflowSimplePos22.html" title="class in kr.ac.kaist.swrc.jhannanum.demo">WorkflowSimplePos22</A>
<BR>
</FONT></TD>
</TR>
</TABLE>
</BODY>
</HTML>
|
# Name: errdlg.py #
# Purpose: Error Reporter Dialog #
"""
Editra Control Library: Error Reporter Dialog
Dialog for displaying exceptions and reporting errors to application maintainer.
This dialog is intended as a base class and should be subclassed to fit the
applications needs.
This dialog should be initiated inside of a sys.excepthook handler.
Example:
sys.excepthook = ExceptHook
def ExceptionHook(exctype, value, trace):
# Format the traceback
ftrace = ErrorDialog.FormatTrace(exctype, value, trace)
# Ensure that error gets raised to console as well
print ftrace
# If abort has been set and we get here again do a more forcefull shutdown
if ErrorDialog.ABORT:
os._exit(1)
# Prevent multiple reporter dialogs from opening at once
if not ErrorDialog.REPORTER_ACTIVE and not ErrorDialog.ABORT:
dlg = ErrorDialog(ftrace)
dlg.ShowModal()
dlg.Destroy()
@summary: Error Reporter Dialog
"""
__author__ = "Cody Precord <cprecord@editra.org>"
__svnid__ = "$Id: errdlg.py 62466 2009-10-21 23:35:41Z CJP $"
__revision__ = "$Revision: 62466 $"
__all__ = [# Classes
'ErrorDialog', 'ErrorReporter',
# Functions
'TimeStamp']
# Dependencies
import os
import sys
import platform
import time
import traceback
import wx
# Globals
#_ = wx.GetTranslation
from gettext import gettext as _
class ErrorReporter(object):
"""Crash/Error Reporter Service
@summary: Stores all errors caught during the current session.
@note: singleton class
"""
instance = None
_first = True
def __init__(self):
"""Initialize the reporter
@note: The ErrorReporter is a singleton.
"""
# Ensure init only happens once
if self._first:
object.__init__(self)
self._first = False
self._sessionerr = list()
else:
pass
def __new__(cls, *args, **kargs):
"""Maintain only a single instance of this object
@return: instance of this class
"""
if not cls.instance:
cls.instance = object.__new__(cls, *args, **kargs)
return cls.instance
def AddMessage(self, msg):
"""Adds a message to the reporters list of session errors
@param msg: The Error Message to save
"""
if msg not in self._sessionerr:
self._sessionerr.append(msg)
def GetErrorStack(self):
"""Returns all the errors caught during this session
@return: formatted log message of errors
"""
return (os.linesep * 2).join(self._sessionerr)
def GetLastError(self):
"""Gets the last error from the current session
@return: Error Message String
"""
if len(self._sessionerr):
return self._sessionerr[-1]
class ErrorDialog(wx.Dialog):
"""Dialog for showing errors and and notifying Editra.org should the
user choose so.
"""
ID_SEND = wx.NewId()
ABORT = False
REPORTER_ACTIVE = False
def __init__(self, parent, id=wx.ID_ANY, title=u'',
pos=wx.DefaultPosition, size=wx.DefaultSize,
style=wx.<API key> | wx.RESIZE_BORDER,
name="ErrorReporterDlg", message=u''):
"""Initialize the dialog
@param message: Error message to display
"""
ErrorDialog.REPORTER_ACTIVE = True
wx.Dialog.__init__(self, parent, id, title, pos, size, style, name)
# Give message to ErrorReporter
ErrorReporter().AddMessage(message)
# Attributes
self.err_msg = os.linesep.join((self.GetEnvironmentInfo(),
"
ErrorReporter().GetErrorStack(),
"
# Layout
self._panel = ErrorPanel(self, self.err_msg)
self._DoLayout()
self.SetMinSize(wx.Size(450, 300))
# Event Handlers
self.Bind(wx.EVT_BUTTON, self.OnButton)
self.Bind(wx.EVT_CLOSE, self.OnClose)
# Auto show at end of init
self.CenterOnParent()
def _DoLayout(self):
"""Layout the dialog and prepare it to be shown
@note: Do not call this method in your code
"""
msizer = wx.BoxSizer(wx.VERTICAL)
msizer.Add(self._panel, 1, wx.EXPAND)
self.SetSizer(msizer)
self.SetInitialSize()
def Abort(self):
"""Called to abort the application
@note: needs to be overidden in sublcasses
"""
raise NotImplementedError("Abort must be implemented!")
def GetEnvironmentInfo(self):
"""Get the enviromental info / Header of error report
@return: string
"""
info = list()
info.append("
info.append("Please provide additional information about the crash here")
info.extend(["", ""])
info.append("
info.append(self.GetProgramName())
info.append("Operating System: %s" % wx.GetOsDescription())
if sys.platform == 'darwin':
info.append("Mac OSX: %s" % platform.mac_ver()[0])
info.append("Python Version: %s" % sys.version)
info.append("wxPython Version: %s" % wx.version())
info.append("wxPython Info: (%s)" % ", ".join(wx.PlatformInfo))
info.append("Python Encoding: Default=%s File=%s" % \
(sys.getdefaultencoding(), sys.<API key>()))
info.append("wxPython Encoding: %s" % wx.<API key>())
info.append("System Architecture: %s %s" % (platform.architecture()[0], \
platform.machine()))
info.append("Byte order: %s" % sys.byteorder)
info.append("Frozen: %s" % str(getattr(sys, 'frozen', 'False')))
info.append("
info.append("")
return os.linesep.join(info)
def GetProgramName(self):
"""Get the program name/version info to include in error report
@return: string
"""
return wx.GetApp().GetAppName()
def Send(self):
"""Called to send error report
@note: needs to be overridden in subclasses
"""
raise NotImplementedError("Send must be implemented!")
@staticmethod
def FormatTrace(exctype, value, trace):
"""Format the traceback
@return: string
"""
exc = traceback.format_exception(exctype, value, trace)
exc.insert(0, u"*** %s ***%s" % (TimeStamp(), os.linesep))
ftrace = u"".join(exc)
return ftrace
def SetDescriptionLabel(self, label):
"""Set the dialogs main description text
@param label: string
"""
self._panel.SetDescriptionText(label)
def ShowAbortButton(self, show=True):
"""Show/Hide the Abort button
@keyword show: bool
"""
btn = self._panel.FindWindowById(wx.ID_ABORT)
if btn is not None:
btn.Show(show)
self._panel.Layout()
def ShowSendButton(self, show=True):
"""Show/Hide the Send button
@keyword show: bool
"""
btn = self._panel.FindWindowById(ErrorDialog.ID_SEND)
if btn is not None:
btn.Show(show)
self._panel.Layout()
def OnButton(self, evt):
"""Handles button events
@param evt: event that called this handler
@postcondition: Dialog is closed
@postcondition: If Report Event then email program is opened
"""
e_id = evt.GetId()
if e_id == wx.ID_CLOSE:
self.Close()
elif e_id == ErrorDialog.ID_SEND:
self.Send()
self.Close()
elif e_id == wx.ID_ABORT:
ErrorDialog.ABORT = True
self.Abort()
self.Close()
else:
evt.Skip()
def OnClose(self, evt):
"""Cleans up the dialog when it is closed
@param evt: Event that called this handler
"""
ErrorDialog.REPORTER_ACTIVE = False
evt.Skip()
class ErrorPanel(wx.Panel):
"""Error Reporter panel"""
def __init__(self, parent, msg):
"""Create the panel
@param parent: wx.Window
@param msg: Error message to display
"""
wx.Panel.__init__(self, parent)
# Attributes
self.err_msg = msg
self.desc = wx.StaticText(self, label=u'')
# Layout
self.__DoLayout()
def __DoLayout(self):
"""Layout the control"""
icon = wx.StaticBitmap(self,
bitmap=wx.ArtProvider.GetBitmap(wx.ART_ERROR))
t_lbl = wx.StaticText(self, label=_("Error Traceback:"))
tctrl = wx.TextCtrl(self, value=self.err_msg, style=wx.TE_MULTILINE |
wx.TE_READONLY)
abort_b = wx.Button(self, wx.ID_ABORT, _("Abort"))
abort_b.SetToolTipString(_("Exit the application"))
send_b = wx.Button(self, ErrorDialog.ID_SEND, _("Report Error"))
send_b.SetDefault()
close_b = wx.Button(self, wx.ID_CLOSE)
# Layout
vsizer = wx.BoxSizer(wx.VERTICAL)
hsizer1 = wx.BoxSizer(wx.HORIZONTAL)
hsizer1.AddMany([((5, 5), 0), (icon, 0, wx.<API key>),
((12, 5), 0), (self.desc, 0, wx.EXPAND), ((5, 5), 0)])
hsizer2 = wx.BoxSizer(wx.HORIZONTAL)
hsizer2.AddMany([((5, 5), 0), (tctrl, 1, wx.EXPAND), ((5, 5), 0)])
bsizer = wx.BoxSizer(wx.HORIZONTAL)
bsizer.AddMany([((5, 5), 0), (abort_b, 0), ((-1, -1), 1, wx.EXPAND),
(send_b, 0), ((5, 5), 0), (close_b, 0), ((5, 5), 0)])
vsizer.AddMany([((5, 5), 0),
(hsizer1, 0),
((10, 10), 0),
(t_lbl, 0, wx.ALIGN_LEFT|wx.LEFT, 5),
((3, 3), 0),
(hsizer2, 1, wx.EXPAND),
((8, 8), 0),
(bsizer, 0, wx.EXPAND),
((8, 8), 0)])
self.SetSizer(vsizer)
self.SetAutoLayout(True)
def SetDescriptionText(self, text):
"""Set the description label text
@param text: string
"""
self.desc.SetLabel(text)
self.Layout()
def TimeStamp():
"""Create a formatted time stamp of current time
@return: Time stamp of the current time (Day Month Date HH:MM:SS Year)
@rtype: string
"""
now = time.localtime(time.time())
now = time.asctime(now)
return now
|
# This file is part of Phobos.
# Phobos is free software: you can redistribute it and/or modify
# (at your option) any later version.
# Phobos is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
import json
import re
import sqlite3
from miner.base import BaseMiner
from util import cachedproperty
class FsdLiteMiner(BaseMiner):
"""Class, which fetches data from FSDLite format static cache files."""
name = 'fsd_lite'
def __init__(self, resbrowser, translator):
self._resbrowser = resbrowser
self._translator = translator
def contname_iter(self):
for container_name in sorted(self.<API key>):
yield container_name
def get_data(self, container_name, language=None, verbose=False, **kwargs):
try:
resource_path = self.<API key>[container_name]
except KeyError:
self.<API key>(container_name)
else:
rows = {}
file_path = self._resbrowser.get_file_info(resource_path).file_abspath
with sqlite3.connect(file_path) as dbconn:
c = dbconn.cursor()
c.execute(u'select key, value from cache')
for sqlite_row in c:
key = sqlite_row[0]
value = sqlite_row[1]
row = json.loads(value)
rows[key] = row
self._translator.translate_container(rows, language, verbose=verbose)
return rows
@cachedproperty
def <API key>(self):
"""
Map between container names and resource path names to static cache files.
Format: {container path: resource path to static cache}
"""
<API key> = {}
for resource_path in self._resbrowser.respath_iter():
# Filter by resource file path first
container_name = self.<API key>(resource_path)
if container_name is None:
continue
# Now, check if it's actually sqlite database and if it has cache table
if not self.__check_cache(resource_path):
continue
<API key>[container_name] = resource_path
return <API key>
def <API key>(self, resource_path):
"""
Validate resource path and return stripped resource
name if path is valid, return None otherwise.
"""
m = re.match(r'^res:/staticdata/(?P<fname>.+).static$', resource_path)
if not m:
return None
return m.group('fname')
def __check_cache(self, resource_path):
"""Check if file is actually SQLite database and has cache table."""
file_path = self._resbrowser.get_file_info(resource_path).file_abspath
try:
dbconn = sqlite3.connect(file_path)
c = dbconn.cursor()
c.execute('select count(*) from sqlite_master where type = \'table\' and name = \'cache\'')
except KeyboardInterrupt:
raise
except:
has_cache = False
else:
has_cache = False
for row in c:
has_cache = bool(row[0])
return has_cache
|
<?php
// POS-Tech API
// This file is part of POS-Tech.
// POS-Tech is free software: you can redistribute it and/or modify
// (at your option) any later version.
// POS-Tech is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
namespace Pasteque\Bundle\ServerBundle\Entity\Ticket;
/**
* SharedTicketLine.
*/
class SharedTicketLine
{
/**
* @var int
*/
private $id;
/**
* @var string
*/
private $displayId;
/**
* @var int
*/
private $sharedTicketId;
/**
* @var int
*/
private $line;
/**
* @var int
*/
private $productId;
/**
* @var int
*/
private $taxId;
/**
* @var float
*/
private $quantity;
/**
* @var float
*/
private $discountRate;
/**
* @var float
*/
private $price;
/**
* @var string
*/
private $attributes;
/**
* SharedTicketLine constructor.
*
* @param int $sharedTicketId
* @param int $line
* @param int $productId
* @param int $taxId
* @param float $quantity
* @param float $price
* @param float $discountRate
* @param string $attributes
* @param string $displayId
*/
public function __construct($sharedTicketId, $line, $productId, $taxId, $quantity, $price,
$discountRate = 0.0, $attributes = null, $displayId = null)
{
$this->displayId = ($displayId === null ? com_create_guid() : $displayId);
$this->sharedTicketId = $sharedTicketId;
$this->line = $line;
$this->productId = $productId;
$this->taxId = $taxId;
$this->quantity = $quantity;
$this->price = $price;
$this->discountRate = $discountRate;
$this->attributes = $attributes;
}
/**
* Get id.
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set displayId.
*
* @param string $displayId
*
* @return SharedTicketLine
*/
public function setDisplayId($displayId)
{
$this->displayId = $displayId;
return $this;
}
/**
* Get displayId.
*
* @return string
*/
public function getDisplayId()
{
return $this->displayId;
}
/**
* Set sharedTicketId.
*
* @param int $sharedTicketId
*
* @return SharedTicketLine
*/
public function setSharedTicketId($sharedTicketId)
{
$this->sharedTicketId = $sharedTicketId;
return $this;
}
/**
* Get sharedTicketId.
*
* @return int
*/
public function getSharedTicketId()
{
return $this->sharedTicketId;
}
/**
* Set line.
*
* @param int $line
*
* @return SharedTicketLine
*/
public function setLine($line)
{
$this->line = $line;
return $this;
}
/**
* Get line.
*
* @return int
*/
public function getLine()
{
return $this->line;
}
/**
* Set productId.
*
* @param int $productId
*
* @return SharedTicketLine
*/
public function setProductId($productId)
{
$this->productId = $productId;
return $this;
}
/**
* Get productId.
*
* @return int
*/
public function getProductId()
{
return $this->productId;
}
/**
* Set taxId.
*
* @param int $taxId
*
* @return SharedTicketLine
*/
public function setTaxId($taxId)
{
$this->taxId = $taxId;
return $this;
}
/**
* Get taxId.
*
* @return int
*/
public function getTaxId()
{
return $this->taxId;
}
/**
* Set quantity.
*
* @param float $quantity
*
* @return SharedTicketLine
*/
public function setQuantity($quantity)
{
$this->quantity = $quantity;
return $this;
}
/**
* Get quantity.
*
* @return float
*/
public function getQuantity()
{
return $this->quantity;
}
/**
* Set discountRate.
*
* @param float $discountRate
*
* @return SharedTicketLine
*/
public function setDiscountRate($discountRate)
{
$this->discountRate = $discountRate;
return $this;
}
/**
* Get discountRate.
*
* @return float
*/
public function getDiscountRate()
{
return $this->discountRate;
}
/**
* Set price.
*
* @param float $price
*
* @return SharedTicketLine
*/
public function setPrice($price)
{
$this->price = $price;
return $this;
}
/**
* Get price.
*
* @return float
*/
public function getPrice()
{
return $this->price;
}
/**
* Set attributes.
*
* @param string $attributes
*
* @return SharedTicketLine
*/
public function setAttributes($attributes)
{
$this->attributes = $attributes;
return $this;
}
/**
* Get attributes.
*
* @return string
*/
public function getAttributes()
{
return $this->attributes;
}
}
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http:
<html xmlns="http:
<head>
<meta name="Content-Type" content="text/html; charset=UTF-8" />
<title>Module: Ronin::Generators::Exploits</title>
<link rel="stylesheet" href="../../css/style.css" type="text/css" media="screen" charset="utf-8" />
<link rel="stylesheet" href="../../css/common.css" type="text/css" media="screen" charset="utf-8" />
<script type="text/javascript" charset="utf-8">
relpath = '../..';
if (relpath != '') relpath += '/';
</script>
<script type="text/javascript" charset="utf-8" src="../../js/jquery.js"></script>
<script type="text/javascript" charset="utf-8" src="../../js/app.js"></script>
</head>
<body>
<div id="header">
<div id="menu">
<a href="../../_index.html">Index (E)</a> »
<a href="../../Ronin.html" title="Ronin">Ronin</a> » <a href="../Generators.html" title="Generators">Generators</a>
»
<span class="title">Exploits</span>
</div>
<div id="search">
<a id="class_list_link" href="#">Namespace List</a>
<a id="method_list_link" href="#">Method List</a>
<a id ="file_list_link" href="#">File List</a>
</div>
<div class="clear"></div>
</div>
<iframe id="search_frame"></iframe>
<div id="content"><h1>Module: Ronin::Generators::Exploits
</h1>
<dl class="box">
<dt class="r1 last">Defined in:</dt>
<dd class="r1 last">lib/ronin/generators/exploits/web.rb<span class="defines">,<br />
lib/ronin/generators/exploits/ftp.rb,<br /> lib/ronin/generators/exploits/http.rb,<br /> lib/ronin/generators/exploits/local.rb,<br /> lib/ronin/generators/exploits/remote.rb,<br /> lib/ronin/generators/exploits/static.rb,<br /> lib/ronin/generators/exploits/exploit.rb,<br /> lib/ronin/generators/exploits/remote_udp.rb,<br /> lib/ronin/generators/exploits/remote_tcp.rb</span>
</dd>
</dl>
<div class="clear"></div>
<h2>Defined Under Namespace</h2>
<p class="children">
<strong class="classes">Classes:</strong> <a href="Exploits/Exploit.html" title="Exploit">Exploit</a>, <a href="Exploits/FTP.html" title="FTP">FTP</a>, <a href="Exploits/HTTP.html" title="HTTP">HTTP</a>, <a href="Exploits/Local.html" title="Local">Local</a>, <a href="Exploits/Remote.html" title="Remote">Remote</a>, <a href="Exploits/RemoteTCP.html" title="RemoteTCP">RemoteTCP</a>, <a href="Exploits/RemoteUDP.html" title="RemoteUDP">RemoteUDP</a>, <a href="Exploits/Web.html" title="Web">Web</a>
</p>
</div>
<div id="footer">
Generated on Sun Dec 27 01:09:44 2009 by
<a href="http://yardoc.org" title="Yay! A Ruby Documentation Tool">yard</a>
0.5.2 (ruby-1.8.7).
</div>
</body>
</html>
|
namespace NzbDrone.Core.Movies
{
public class AddMovieOptions : MonitoringOptions
{
public bool SearchForMovie { get; set; }
}
}
|
using WowPacketParser.Store.Objects.UpdateFields;
// This file is automatically generated, DO NOT EDIT
namespace <API key>.V9_0_1_36216.UpdateFields.V9_1_0_39185
{
public class Research : IResearch
{
public short ResearchProjectID { get; set; }
}
}
|
#include <QtWidgets>
#include "<API key>.h"
#include "metadata.h"
#include "utility.h"
QGroupBox *add_geog_cs_group(lemon::<API key> *geog_cs) {
QGroupBox *geog_cs_group = new QGroupBox(QObject::tr(""));
QVBoxLayout *main_layout = new QVBoxLayout();
QLabel *name_label = new QLabel(QObject::tr(""));
QLabel *name = new QLabel(lemon::to_qstring(geog_cs->name));
QHBoxLayout *name_layout = new QHBoxLayout();
name_layout->addWidget(name_label);
name_layout->addWidget(name);
main_layout->addLayout(name_layout);
if (!geog_cs->authority_name.empty() || !geog_cs->authority_code.empty()) {
QLabel *authority_name =
new QLabel(lemon::to_qstring(geog_cs->authority_name));
QLabel *authority_code =
new QLabel(lemon::to_qstring(geog_cs->authority_code));
QHBoxLayout *authority_layout = new QHBoxLayout();
authority_layout->addWidget(authority_name);
authority_layout->addWidget(authority_code);
main_layout->addLayout(authority_layout);
}
QLabel *datum_label = new QLabel(QObject::tr(""));
QLabel *datum = new QLabel(lemon::to_qstring(geog_cs->datum));
QHBoxLayout *datum_layout = new QHBoxLayout();
datum_layout->addWidget(datum_label);
datum_layout->addWidget(datum);
QLabel *spheroid_label = new QLabel(QObject::tr(""));
QLabel *spheroid = new QLabel(lemon::to_qstring(geog_cs->spheroid));
QHBoxLayout *spheroid_layout = new QHBoxLayout();
spheroid_layout->addWidget(spheroid_label);
spheroid_layout->addWidget(spheroid);
QLabel *semimajor_label = new QLabel(QObject::tr(""));
QLabel *semimajor = new QLabel(QString::number(geog_cs->semimajor));
QHBoxLayout *semimajor_layout = new QHBoxLayout();
semimajor_layout->addWidget(semimajor_label);
semimajor_layout->addWidget(semimajor);
QLabel *semiminor_label = new QLabel(QObject::tr(""));
QLabel *semiminor = new QLabel(QString::number(geog_cs->semiminor));
QHBoxLayout *semiminor_layout = new QHBoxLayout();
semiminor_layout->addWidget(semiminor_label);
semiminor_layout->addWidget(semiminor);
QLabel *<API key> = new QLabel(QObject::tr(""));
QLabel *inverse_flattening =
new QLabel(QString::number(geog_cs->inverse_flattening));
QHBoxLayout *<API key> = new QHBoxLayout();
<API key>->addWidget(<API key>);
<API key>->addWidget(inverse_flattening);
QLabel *angular_unit_label = new QLabel(QObject::tr(""));
QLabel *angular_unit = new QLabel(lemon::to_qstring(geog_cs->angular_unit));
QHBoxLayout *angular_unit_layout = new QHBoxLayout();
angular_unit_layout->addWidget(angular_unit_label);
angular_unit_layout->addWidget(angular_unit);
QLabel *<API key> = new QLabel(QObject::tr("/"));
QLabel *radians_per_unit =
new QLabel(QString::number(geog_cs->radians_per_unit));
QHBoxLayout *<API key> = new QHBoxLayout();
<API key>->addWidget(<API key>);
<API key>->addWidget(radians_per_unit);
QLabel *<API key> = new QLabel(QObject::tr(""));
QLabel *prime_meridian =
new QLabel(lemon::to_qstring(geog_cs->prime_meridian));
QHBoxLayout *<API key> = new QHBoxLayout();
<API key>->addWidget(<API key>);
<API key>->addWidget(prime_meridian);
QLabel *<API key> = new QLabel(QObject::tr(""));
QLabel *meridian_longitude =
new QLabel(QString::number(geog_cs->meridian_longitude));
QHBoxLayout *<API key> = new QHBoxLayout();
<API key>->addWidget(<API key>);
<API key>->addWidget(meridian_longitude);
main_layout->addLayout(datum_layout);
main_layout->addLayout(spheroid_layout);
main_layout->addLayout(semimajor_layout);
main_layout->addLayout(semiminor_layout);
main_layout->addLayout(<API key>);
main_layout->addLayout(angular_unit_layout);
main_layout->addLayout(<API key>);
main_layout->addLayout(<API key>);
main_layout->addLayout(<API key>);
if (geog_cs->have_towgs84_node) {
QLabel *<API key> = new QLabel(QObject::tr("TOWGS84"));
QString params;
for (int i = 0; i < 6; ++i)
params.append(QString::number(geog_cs->towgs84_params[i])).append(", ");
params.append(QString::number(geog_cs->towgs84_params[6]));
QLabel *towgs84_params = new QLabel(params);
QHBoxLayout *<API key> = new QHBoxLayout();
<API key>->addWidget(<API key>);
<API key>->addWidget(towgs84_params);
main_layout->addLayout(<API key>);
}
geog_cs_group->setLayout(main_layout);
return geog_cs_group;
}
QGroupBox *add_proj_cs_group(lemon::<API key> *proj_cs) {
QGroupBox *proj_cs_group = new QGroupBox(QObject::tr(""));
QVBoxLayout *main_layout = new QVBoxLayout();
QLabel *name_label = new QLabel(QObject::tr(""));
QLabel *name = new QLabel(lemon::to_qstring(proj_cs->name));
QHBoxLayout *name_layout = new QHBoxLayout();
name_layout->addWidget(name_label);
name_layout->addWidget(name);
QLabel *projection_label = new QLabel(QObject::tr(""));
QLabel *projection = new QLabel(lemon::to_qstring(proj_cs->projection_name));
QHBoxLayout *projection_layout = new QHBoxLayout();
projection_layout->addWidget(projection_label);
projection_layout->addWidget(projection);
main_layout->addLayout(name_layout);
main_layout->addLayout(projection_layout);
if (!proj_cs->authority_name.empty() || !proj_cs->authority_code.empty()) {
QLabel *authority_name =
new QLabel(lemon::to_qstring(proj_cs->authority_name));
QLabel *authority_code =
new QLabel(lemon::to_qstring(proj_cs->authority_code));
QHBoxLayout *authority_layout = new QHBoxLayout();
authority_layout->addWidget(authority_name);
authority_layout->addWidget(authority_code);
main_layout->addLayout(authority_layout);
}
QLabel *linear_unit_label = new QLabel(QObject::tr(""));
QLabel *linear_unit = new QLabel(lemon::to_qstring(proj_cs->linear_unit));
QHBoxLayout *linear_unit_layout = new QHBoxLayout();
linear_unit_layout->addWidget(linear_unit_label);
linear_unit_layout->addWidget(linear_unit);
QLabel *<API key> = new QLabel(QObject::tr("/"));
QLabel *meters_per_unit =
new QLabel(QString::number(proj_cs->meters_per_unit));
QHBoxLayout *<API key> = new QHBoxLayout();
<API key>->addWidget(<API key>);
<API key>->addWidget(meters_per_unit);
main_layout->addLayout(linear_unit_layout);
main_layout->addLayout(<API key>);
if (!proj_cs->projection_params.empty()) {
main_layout->addWidget(new QLabel(QObject::tr("")));
QTableWidget *params = new QTableWidget(
static_cast<int>(proj_cs->projection_params.size()), 2);
params->horizontalHeader()->setVisible(false);
params->verticalHeader()->setVisible(false);
params->setEditTriggers(QAbstractItemView::NoEditTriggers);
params->setSelectionMode(QAbstractItemView::NoSelection);
int row_index = 0;
for (auto &e : proj_cs->projection_params) {
params->setItem(row_index, 0,
new QTableWidgetItem(lemon::to_qstring(e.first)));
params->setItem(row_index, 1,
new QTableWidgetItem(QString::number(e.second)));
++row_index;
}
params-><API key>();
main_layout->addWidget(params);
}
main_layout->addWidget(add_geog_cs_group(&proj_cs->geog_cs));
proj_cs_group->setLayout(main_layout);
return proj_cs_group;
}
QGroupBox *add_local_cs_group(lemon::<API key> *local_cs) {
QGroupBox *local_cs_group = new QGroupBox(QObject::tr(""));
return local_cs_group;
}
QGroupBox *add_vert_cs_group(lemon::<API key> *vert_cs) {
QGroupBox *vert_cs_group = new QGroupBox(QObject::tr(""));
QVBoxLayout *main_layout = new QVBoxLayout();
QLabel *name_label = new QLabel(QObject::tr(""));
QLabel *name = new QLabel(lemon::to_qstring(vert_cs->name));
QHBoxLayout *name_layout = new QHBoxLayout();
name_layout->addWidget(name_label);
name_layout->addWidget(name);
main_layout->addLayout(name_layout);
if (!vert_cs->authority_name.empty() || !vert_cs->authority_code.empty()) {
QLabel *authority_name =
new QLabel(lemon::to_qstring(vert_cs->authority_name));
QLabel *authority_code =
new QLabel(lemon::to_qstring(vert_cs->authority_code));
QHBoxLayout *authority_layout = new QHBoxLayout();
authority_layout->addWidget(authority_name);
authority_layout->addWidget(authority_code);
main_layout->addLayout(authority_layout);
}
QLabel *vert_datum_label = new QLabel(QObject::tr(""));
QLabel *vert_datum = new QLabel(lemon::to_qstring(vert_cs->name));
QHBoxLayout *vert_datum_layout = new QHBoxLayout();
vert_datum_layout->addWidget(vert_datum_label);
vert_datum_layout->addWidget(vert_datum);
QLabel *linear_unit_label = new QLabel(QObject::tr(""));
QLabel *linear_unit = new QLabel(lemon::to_qstring(vert_cs->linear_unit));
QHBoxLayout *linear_unit_layout = new QHBoxLayout();
linear_unit_layout->addWidget(linear_unit_label);
linear_unit_layout->addWidget(linear_unit);
QLabel *<API key> = new QLabel(QObject::tr("/"));
QLabel *meters_per_unit =
new QLabel(QString::number(vert_cs->meters_per_unit));
QHBoxLayout *<API key> = new QHBoxLayout();
<API key>->addWidget(<API key>);
<API key>->addWidget(meters_per_unit);
main_layout->addLayout(vert_datum_layout);
main_layout->addLayout(linear_unit_layout);
main_layout->addLayout(<API key>);
if (!vert_cs->axis_name.empty()) {
QLabel *axis_name_label = new QLabel(QObject::tr(""));
QLabel *axis_name = new QLabel(lemon::to_qstring(vert_cs->axis_name));
QHBoxLayout *axis_name_layout = new QHBoxLayout();
axis_name_layout->addWidget(axis_name_label);
axis_name_layout->addWidget(axis_name);
QLabel *<API key> = new QLabel(QObject::tr(""));
QLabel *axis_orientation =
new QLabel(lemon::to_qstring(vert_cs->axis_orientation));
QHBoxLayout *<API key> = new QHBoxLayout();
<API key>->addWidget(<API key>);
<API key>->addWidget(axis_orientation);
main_layout->addLayout(axis_name_layout);
main_layout->addLayout(<API key>);
}
vert_cs_group->setLayout(main_layout);
return vert_cs_group;
}
<API key>::<API key>(const lemon::metadata *metadata,
QWidget *parent)
: QWidget(parent) {
QVBoxLayout *main_layout = new QVBoxLayout();
if (metadata->proj_cs)
main_layout->addWidget(add_proj_cs_group(metadata->proj_cs.get()));
if (metadata->geog_cs)
main_layout->addWidget(add_geog_cs_group(metadata->geog_cs.get()));
if (metadata->local_cs)
main_layout->addWidget(add_local_cs_group(metadata->local_cs.get()));
if (metadata->vert_cs)
main_layout->addWidget(add_vert_cs_group(metadata->vert_cs.get()));
setLayout(main_layout);
}
|
package nz.ac.waikato.cms.gui;
import nz.ac.waikato.cms.core.FileUtils;
import nz.ac.waikato.cms.core.Project;
import nz.ac.waikato.cms.doc.HyperLinkGrades;
import nz.ac.waikato.cms.doc.HyperLinkGrades.Location;
import nz.ac.waikato.cms.gui.core.<API key>;
import nz.ac.waikato.cms.gui.core.BaseFileChooser;
import nz.ac.waikato.cms.gui.core.BaseFrame;
import nz.ac.waikato.cms.gui.core.BaseScrollPane;
import nz.ac.waikato.cms.gui.core.ExtensionFileFilter;
import nz.ac.waikato.cms.gui.core.GUIHelper;
import nz.ac.waikato.cms.gui.core.SetupPanel;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.<API key>;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.regex.Pattern;
/**
* For hyperlinking pages in PDFs where Grades were found that matched a
* regular expression.
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class HyperLinkGradesGUI
extends SetupPanel {
public static final String EXPRESSION = "Expression";
public static final String OUTPUT_DIR = "OutputDir";
public static final String CSV_OUTPUT = "CsvOutput";
public static final String SUFFIX = "Suffix";
public static final String CASE_SENSITIVE = "CaseSensitive";
public static final String EXCLUDE_COMPLETIONS = "ExcludeCompletions";
/** the file chooser to use for PDFs. */
protected BaseFileChooser m_FileChooserPDF;
/** the file chooser to use for CSVs. */
protected BaseFileChooser m_FileChooserCSV;
/** the directory chooser to use. */
protected <API key> m_DirChooser;
/** the input files. */
protected JList m_ListInputFiles;
/** the model for the input files. */
protected DefaultListModel<File> m_ModelInputFiles;
/** the button for adding files. */
protected JButton m_ButtonAddFiles;
/** the button for selecting the CSV output file. */
protected JButton <API key>;
/** the button for removing selected files. */
protected JButton m_ButtonRemoveFiles;
/** the button for removing all files. */
protected JButton <API key>;
/** the expression. */
protected JTextField m_TextExpression;
/** the output directory. */
protected JTextField m_TextOutputDir;
/** the CSV output file. */
protected JTextField m_TextCSVOutput;
/** the button for selecting the output directory. */
protected JButton m_ButtonOutputDir;
/** the suffix. */
protected JTextField m_TextSuffix;
/** the checkbox for case-sensitive search. */
protected JCheckBox <API key>;
/** the checkbox for excluding completions. */
protected JCheckBox <API key>;
/** the button for indexing the files. */
protected JButton m_ButtonIndex;
/** the button for closing the frame. */
protected JButton m_ButtonClose;
/** the label for the progress. */
protected JLabel m_LabelProgress;
/** whether files are being processed. */
protected boolean m_Processing;
/**
* Initializes the members.
*/
protected void initialize() {
m_FileChooserPDF = new BaseFileChooser();
m_FileChooserPDF.<API key>(ExtensionFileFilter.getPdfFileFilter());
m_FileChooserPDF.<API key>(false);
m_FileChooserPDF.<API key>(true);
m_FileChooserCSV = new BaseFileChooser();
m_FileChooserCSV.<API key>(ExtensionFileFilter.getCsvFileFilter());
m_FileChooserCSV.<API key>(false);
m_FileChooserCSV.<API key>(true);
m_DirChooser = new <API key>();
m_Processing = false;
}
/**
* Initializes the widgets.
*/
protected void initGUI() {
JPanel panelFiles;
JPanel panelParams;
List<JLabel> labels;
setLayout(new BorderLayout());
panelFiles = new JPanel(new BorderLayout());
panelFiles.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
add(panelFiles, BorderLayout.CENTER);
// input files
{
JLabel label = new JLabel("Input files");
panelFiles.add(label, BorderLayout.NORTH);
JPanel panel = new JPanel(new BorderLayout());
panelFiles.add(panel, BorderLayout.CENTER);
m_ModelInputFiles = new DefaultListModel<>();
m_ListInputFiles = new JList(m_ModelInputFiles);
m_ListInputFiles.<API key>(new <API key>() {
@Override
public void valueChanged(ListSelectionEvent e) {
updateButtons();
}
});
panel.add(new BaseScrollPane(m_ListInputFiles), BorderLayout.CENTER);
JPanel panelRight = new JPanel(new BorderLayout());
panel.add(panelRight, BorderLayout.EAST);
JPanel panelButtons = new JPanel(new GridLayout(3, 1));
panelButtons.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0));
panelRight.add(panelButtons, BorderLayout.NORTH);
m_ButtonAddFiles = new JButton("Add...");
m_ButtonAddFiles.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int retVal = m_FileChooserPDF.showOpenDialog(HyperLinkGradesGUI.this);
if (retVal != BaseFileChooser.APPROVE_OPTION)
return;
File[] files = m_FileChooserPDF.getSelectedFiles();
for (File file: files)
m_ModelInputFiles.addElement(file);
updateButtons();
}
});
panelButtons.add(m_ButtonAddFiles);
m_ButtonRemoveFiles = new JButton("Remove");
m_ButtonRemoveFiles.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int[] indices = m_ListInputFiles.getSelectedIndices();
for (int i = indices.length - 1; i >= 0; i
m_ModelInputFiles.remove(indices[i]);
updateButtons();
}
});
panelButtons.add(m_ButtonRemoveFiles);
<API key> = new JButton("Remove all");
<API key>.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
m_ModelInputFiles.removeAllElements();
updateButtons();
}
});
panelButtons.add(<API key>);
}
// the parameters
labels = new ArrayList<>();
panelParams = new JPanel(new GridLayout(6, 1));
panelFiles.add(panelParams, BorderLayout.SOUTH);
// expression
{
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 5));
panelParams.add(panel);
m_TextExpression = new JTextField(30);
m_TextExpression.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
checkExpression();
}
@Override
public void removeUpdate(DocumentEvent e) {
checkExpression();
}
@Override
public void changedUpdate(DocumentEvent e) {
checkExpression();
}
protected void checkExpression() {
if (m_TextExpression.getText().trim().isEmpty() || isValidExpression())
m_TextExpression.setForeground(Color.BLACK);
else
m_TextExpression.setForeground(Color.RED);
updateButtons();
}
});
JLabel label = new JLabel(EXPRESSION);
label.<API key>('x');
label.setLabelFor(m_TextExpression);
panel.add(label);
panel.add(m_TextExpression);
labels.add(label);
}
// output dir
{
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 5));
panelParams.add(panel);
m_TextOutputDir = new JTextField(30);
m_TextOutputDir.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
checkDir();
}
@Override
public void removeUpdate(DocumentEvent e) {
checkDir();
}
@Override
public void changedUpdate(DocumentEvent e) {
checkDir();
}
protected void checkDir() {
if (m_TextOutputDir.getText().trim().isEmpty() || isValidOutputDir())
m_TextOutputDir.setForeground(Color.BLACK);
else
m_TextOutputDir.setForeground(Color.RED);
updateButtons();
}
});
JLabel label = new JLabel("Output directory");
label.<API key>('O');
label.setLabelFor(m_TextOutputDir);
m_ButtonOutputDir = new JButton("...");
m_ButtonOutputDir.setPreferredSize(new Dimension((int) m_ButtonOutputDir.getPreferredSize().getWidth(), (int) m_TextOutputDir.getPreferredSize().getHeight()));
m_ButtonOutputDir.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!m_TextOutputDir.getText().isEmpty())
m_DirChooser.setCurrentDirectory(new File(m_TextOutputDir.getText()));
int retVal = m_DirChooser.showOpenDialog(HyperLinkGradesGUI.this);
if (retVal != <API key>.APPROVE_OPTION)
return;
m_TextOutputDir.setText(m_DirChooser.getSelectedFile().getAbsolutePath());
}
});
panel.add(label);
panel.add(m_TextOutputDir);
panel.add(m_ButtonOutputDir);
labels.add(label);
}
// csv output
{
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 5));
panelParams.add(panel);
m_TextCSVOutput = new JTextField(30);
m_TextCSVOutput.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
checkDir();
}
@Override
public void removeUpdate(DocumentEvent e) {
checkDir();
}
@Override
public void changedUpdate(DocumentEvent e) {
checkDir();
}
protected void checkDir() {
if (m_TextCSVOutput.getText().trim().isEmpty() || isValidOutputDir())
m_TextCSVOutput.setForeground(Color.BLACK);
else
m_TextCSVOutput.setForeground(Color.RED);
updateButtons();
}
});
JLabel label = new JLabel("CSV Output");
label.<API key>('V');
label.setLabelFor(m_TextCSVOutput);
<API key> = new JButton("...");
<API key>.setPreferredSize(new Dimension((int) m_ButtonOutputDir.getPreferredSize().getWidth(), (int) m_TextCSVOutput.getPreferredSize().getHeight()));
<API key>.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!m_TextCSVOutput.getText().isEmpty())
m_FileChooserCSV.setSelectedFile(new File(m_TextCSVOutput.getText()));
int retVal = m_FileChooserCSV.showSaveDialog(HyperLinkGradesGUI.this);
if (retVal != BaseFileChooser.APPROVE_OPTION)
return;
m_TextCSVOutput.setText(m_FileChooserCSV.getSelectedFile().getAbsolutePath());
}
});
panel.add(label);
panel.add(m_TextCSVOutput);
panel.add(<API key>);
labels.add(label);
}
// suffix
{
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 5));
panelParams.add(panel);
m_TextSuffix = new JTextField(30);
JLabel label = new JLabel(SUFFIX);
label.<API key>('S');
label.setLabelFor(m_TextSuffix);
panel.add(label);
panel.add(m_TextSuffix);
labels.add(label);
}
// case sensitive
{
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 5));
panelParams.add(panel);
<API key> = new JCheckBox("");
JLabel label = new JLabel("Case-sensitive matching");
label.<API key>('m');
label.setLabelFor(<API key>);
panel.add(label);
panel.add(<API key>);
labels.add(label);
}
// no completions
{
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 5));
panelParams.add(panel);
<API key> = new JCheckBox("");
JLabel label = new JLabel("Exclude completions");
label.<API key>('p');
label.setLabelFor(<API key>);
panel.add(label);
panel.add(<API key>);
labels.add(label);
}
// the buttons at the bottom
{
JPanel panelBottom = new JPanel(new BorderLayout());
add(panelBottom, BorderLayout.SOUTH);
JPanel panelLeft = new JPanel(new FlowLayout(FlowLayout.LEFT));
panelBottom.add(panelLeft, BorderLayout.WEST);
m_LabelProgress = new JLabel("");
panelLeft.add(m_LabelProgress);
JPanel panelRight = new JPanel(new FlowLayout(FlowLayout.RIGHT));
panelBottom.add(panelRight, BorderLayout.EAST);
m_ButtonIndex = new JButton("Index", GUIHelper.getIcon("run.gif"));
m_ButtonIndex.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
process();
}
});
panelRight.add(m_ButtonIndex);
m_ButtonClose = new JButton("Close", GUIHelper.getIcon("stop.gif"));
m_ButtonClose.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
GUIHelper.closeParent(HyperLinkGradesGUI.this);
}
});
panelRight.add(m_ButtonClose);
}
// adjust labels
validate();
int max = 0;
for (JLabel label: labels) {
if (label.getPreferredSize().getWidth() > max)
max = (int) label.getPreferredSize().getWidth();
}
max += 5;
for (JLabel label: labels)
label.setPreferredSize(new Dimension(max, (int) label.getPreferredSize().getHeight()));
}
/**
* Finishes up the initialization.
*/
@Override
protected void finishInit() {
super.finishInit();
updateButtons();
}
/**
* Indexes the files.
*/
protected void process() {
SwingWorker worker;
m_Processing = true;
updateButtons();
worker = new SwingWorker() {
protected StringBuilder m_Errors;
@Override
protected Object doInBackground() throws Exception {
saveSetup();
m_Errors = new StringBuilder();
for (int i = 0; i < m_ModelInputFiles.getSize(); i++) {
File fileIn = m_ModelInputFiles.get(i);
File fileOut = FileUtils.replaceExtension(new File(m_TextOutputDir.getText() + File.separator + fileIn.getName()), m_TextSuffix.getText() + ".pdf");
m_LabelProgress.setText("Processing " + (i+1) + "/" + m_ModelInputFiles.getSize() + "...");
try {
List<Location> locations = HyperLinkGrades.locate(
fileIn,
m_TextExpression.getText(),
<API key>.isSelected(),
<API key>.isSelected());
if (!HyperLinkGrades.addIndex(
locations,
fileIn,
fileOut)) {
throw new Exception("Failed to add index!");
}
if (!m_TextCSVOutput.getText().trim().isEmpty()) {
File csv = new File(m_TextCSVOutput.getText());
if (!csv.isDirectory()) {
if (!HyperLinkGrades.generateCSV(locations, csv))
throw new Exception("Failed to generate CSV: " + csv);
}
}
}
catch (Exception e) {
m_Errors.append("Failed to process: " + fileIn + "\n");
System.err.println("Failed to process: " + fileIn);
e.printStackTrace();
}
}
return null;
}
@Override
protected void done() {
m_LabelProgress.setText("");
m_Processing = false;
updateButtons();
if (m_Errors.length() > 0) {
JOptionPane.showMessageDialog(
HyperLinkGradesGUI.this,
m_Errors.toString(),
"Error",
JOptionPane.ERROR_MESSAGE);
}
super.done();
}
};
worker.execute();
}
/**
* Returns whether the expression is valid.
*
* @return true if valid
*/
protected boolean isValidExpression() {
if (m_TextExpression.getText().trim().isEmpty())
return false;
try {
Pattern.compile(m_TextExpression.getText());
return true;
}
catch (Exception e) {
return false;
}
}
/**
* Returns whether the output dir is valid.
*
* @return true if valid
*/
protected boolean isValidOutputDir() {
File file;
if (m_TextOutputDir.getText().trim().isEmpty())
return false;
try {
file = new File(m_TextOutputDir.getText());
return file.exists() && file.isDirectory();
}
catch (Exception e) {
return false;
}
}
/**
* Returns whether files can be indexed.
*
* @return true if possible
*/
protected boolean canIndexFiles() {
boolean result;
result = !m_Processing
&& (m_ModelInputFiles.getSize() > 0)
&& isValidExpression()
&& isValidOutputDir();
return result;
}
/**
* Updates the state of the buttons.
*/
protected void updateButtons() {
m_ButtonAddFiles.setEnabled(!m_Processing);
m_ButtonRemoveFiles.setEnabled(!m_Processing && (m_ListInputFiles.getSelectedIndices().length > 0));
<API key>.setEnabled(!m_Processing && (m_ModelInputFiles.getSize() > 0));
m_ButtonClose.setEnabled(!m_Processing);
m_ButtonIndex.setEnabled(canIndexFiles());
}
/**
* Maps the properties back to the GUI.
*
* @param props the properties to use
*/
protected void propsToGUI(Properties props) {
m_TextExpression.setText(props.getProperty(EXPRESSION, ""));
m_TextOutputDir.setText(props.getProperty(OUTPUT_DIR, ""));
m_TextCSVOutput.setText(props.getProperty(CSV_OUTPUT, ""));
m_TextSuffix.setText(props.getProperty(SUFFIX, ""));
<API key>.setSelected(props.getProperty(CASE_SENSITIVE, "false").equals("true"));
<API key>.setSelected(props.getProperty(EXCLUDE_COMPLETIONS, "false").equals("true"));
}
/**
* Maps the GUI to a properties object.
*
* @return the properties
*/
protected Properties guiToProps() {
Properties result;
result = new Properties();
result.setProperty(EXPRESSION, m_TextExpression.getText());
result.setProperty(OUTPUT_DIR, m_TextOutputDir.getText());
result.setProperty(CSV_OUTPUT, m_TextCSVOutput.getText());
result.setProperty(SUFFIX, m_TextSuffix.getText());
result.setProperty(CASE_SENSITIVE, "" + <API key>.isSelected());
result.setProperty(EXCLUDE_COMPLETIONS, "" + <API key>.isSelected());
return result;
}
/**
* Creates a frame with the GUI.
*
* @return the frame
*/
public static BaseFrame createFrame() {
BaseFrame result;
result = new BaseFrame("Hyperlink Grades");
HyperLinkGradesGUI panel = new HyperLinkGradesGUI();
result.getRootPane().setLayout(new BorderLayout());
result.getRootPane().add(panel);
result.setSize(600, 400);
return result;
}
/**
* Starts the GUI.
*
* @param args ignored
*/
public static void main(String[] args) {
Project.initialize();
BaseFrame frame = createFrame();
frame.<API key>(BaseFrame.EXIT_ON_CLOSE);
frame.<API key>(null);
frame.setVisible(true);
}
}
|
package cc.fooledit.editor.text.mode.sql;
import org.osgi.framework.*;
/**
*
* @author Chan Chung Kwong
*/
public class Activator implements BundleActivator{
public static final String NAME=Activator.class.getPackage().getName();
public static final String CONTENT_TYPE="application/sql";
@Override
public void start(BundleContext bc) throws Exception{
}
@Override
public void stop(BundleContext bc) throws Exception{
}
}
|
namespace ShareX.UploadersLib
{
partial class JiraUpload
{
<summary>
Required designer variable.
</summary>
private System.ComponentModel.IContainer components = null;
<summary>
Clean up any resources being used.
</summary>
<param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
<summary>
Required method for Designer support - do not modify
the contents of this method with the code editor.
</summary>
private void InitializeComponent()
{
System.ComponentModel.<API key> resources = new System.ComponentModel.<API key>(typeof(JiraUpload));
this.lblIssueId = new System.Windows.Forms.Label();
this.txtIssueId = new System.Windows.Forms.TextBox();
this.lblSummary = new System.Windows.Forms.Label();
this.btnUpload = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.gpSummary = new System.Windows.Forms.GroupBox();
this.gpSummary.SuspendLayout();
this.SuspendLayout();
// lblIssueId
resources.ApplyResources(this.lblIssueId, "lblIssueId");
this.lblIssueId.Name = "lblIssueId";
// txtIssueId
resources.ApplyResources(this.txtIssueId, "txtIssueId");
this.txtIssueId.Name = "txtIssueId";
this.txtIssueId.TextChanged += new System.EventHandler(this.<API key>);
// lblSummary
resources.ApplyResources(this.lblSummary, "lblSummary");
this.lblSummary.Name = "lblSummary";
// btnUpload
resources.ApplyResources(this.btnUpload, "btnUpload");
this.btnUpload.Name = "btnUpload";
this.btnUpload.<API key> = true;
this.btnUpload.Click += new System.EventHandler(this.btnSend_Click);
// btnCancel
resources.ApplyResources(this.btnCancel, "btnCancel");
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Name = "btnCancel";
this.btnCancel.<API key> = true;
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
// gpSummary
resources.ApplyResources(this.gpSummary, "gpSummary");
this.gpSummary.Controls.Add(this.lblSummary);
this.gpSummary.Name = "gpSummary";
this.gpSummary.TabStop = false;
// JiraUpload
this.AcceptButton = this.btnUpload;
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.btnCancel;
this.Controls.Add(this.txtIssueId);
this.Controls.Add(this.lblIssueId);
this.Controls.Add(this.gpSummary);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnUpload);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "JiraUpload";
this.Load += new System.EventHandler(this.JiraUpload_Load);
this.gpSummary.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label lblIssueId;
private System.Windows.Forms.Label lblSummary;
private System.Windows.Forms.Button btnUpload;
private System.Windows.Forms.TextBox txtIssueId;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.GroupBox gpSummary;
}
}
|
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - <API key></title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="">
<div ng-controller="FetchCtrl">
<select ng-model="method">
<option>GET</option>
<option>JSONP</option>
</select>
<input type="text" ng-model="url" size="80"/>
<button id="fetchbtn" ng-click="fetch()">fetch</button><br>
<button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
<button id="samplejsonpbtn"
ng-click="updateModel('JSONP',
'http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
Sample JSONP
</button>
<button id="invalidjsonpbtn"
ng-click="updateModel('JSONP', 'http://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
Invalid JSONP
</button>
<pre>http status code: {{status}}</pre>
<pre>http response data: {{data}}</pre>
</div>
</body>
</html>
|
# - Try to find Mathematica installation and provide CMake functions for its C/C++ interface
# See the FindMathematica manual for usage hints.
# obtaining a copy of this software and associated documentation)
# files (the "Software"), to deal in the Software without)
# restriction, including without limitation the rights to use,)
# copies of the Software, and to permit persons to whom the)
# Software is furnished to do so, subject to the following)
# conditions:)
# included in all copies or substantial portions of the Software.)
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES)
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND)
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,)
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING)
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR)
# OTHER DEALINGS IN THE SOFTWARE.)
# we need the CMakeParseArguments module
# call <API key>, but prevent modification of the CMake policy stack
cmake_policy(PUSH)
<API key>(VERSION 2.8.12)
cmake_policy(POP)
set (<API key> "${<API key>}")
set (<API key> "3.4.0")
# activate select policies
if (POLICY CMP0025)
# Compiler id for Apple Clang is now AppleClang
cmake_policy(SET CMP0025 NEW)
endif()
if (POLICY CMP0026)
# disallow use of the LOCATION target property
if (CYGWIN OR MSYS)
# Cygwin and MSYS do not produce workable Mathematica paths using
# the $<TARGET_FILE:...> notation
cmake_policy(SET CMP0026 OLD)
else()
cmake_policy(SET CMP0026 NEW)
endif()
endif()
if (POLICY CMP0038)
# targets may not link directly to themselves
cmake_policy(SET CMP0038 NEW)
endif()
if (POLICY CMP0039)
# utility targets may not have link dependencies
cmake_policy(SET CMP0039 NEW)
endif()
if (POLICY CMP0040)
# target in the TARGET signature of add_custom_command() must exist
cmake_policy(SET CMP0040 NEW)
endif()
if (POLICY CMP0045)
# error on non-existent target in get_target_property
cmake_policy(SET CMP0045 NEW)
endif()
if (POLICY CMP0046)
# error on non-existent dependency in add_dependencies
cmake_policy(SET CMP0046 NEW)
endif()
if (POLICY CMP0049)
# do not expand variables in target source entries
cmake_policy(SET CMP0049 NEW)
endif()
if (POLICY CMP0050)
# disallow add_custom_command SOURCE signatures
cmake_policy(SET CMP0050 NEW)
endif()
if (POLICY CMP0051)
# include TARGET_OBJECTS expressions in a target's SOURCES property
cmake_policy(SET CMP0051 NEW)
endif()
if (POLICY CMP0053)
# simplify variable reference and escape sequence evaluation
cmake_policy(SET CMP0053 NEW)
endif()
if (POLICY CMP0054)
# only interpret if() arguments as variables or keywords when unquoted
cmake_policy(SET CMP0054 NEW)
endif()
include(TestBigEndian)
include(CMakeParseArguments)
include(<API key>)
include(CMakeFindFrameworks)
# internal function to convert Windows path to Cygwin workable CMake path
# E.g., "C:\Program Files" is converted to "/cygdrive/c/Program Files"
# file(TO_CMAKE_PATH "C:\Program Files" ...) would result in unworkable "C;/Program Files"
function (_to_cmake_path _inPath _outPathVariable)
if (CYGWIN)
find_program(<API key> "cygpath")
mark_as_advanced(<API key>)
execute_process(
COMMAND "${<API key>}" "--unix" "${_inPath}" TIMEOUT 5
OUTPUT_VARIABLE ${_outPathVariable} <API key>)
else()
file(TO_CMAKE_PATH "${_inPath}" ${_outPathVariable})
endif()
set (${_outPathVariable} "${${_outPathVariable}}" PARENT_SCOPE)
endfunction()
# internal function to convert CMake path to "pure" native path without escapes
function (_to_native_path _inPath _outPathVariable)
# do not use the built-in function file (TO_NATIVE_PATH ...),
# which does too much or the wrong thing:
# it converts a CMake path to a native path but then also escapes all blanks
# and special characters
# under MinGW it produces unworkable paths with forward slashes
if (CYGWIN)
find_program(<API key> "cygpath")
mark_as_advanced(<API key>)
execute_process(
COMMAND "${<API key>}" "--mixed" "${_inPath}" TIMEOUT 5
OUTPUT_VARIABLE ${_outPathVariable} <API key>)
elseif (CMAKE_HOST_UNIX)
# use CMake path literally under UNIX
set (${_outPathVariable} "${_inPath}")
elseif (CMAKE_HOST_WIN32)
string (REPLACE "/" "\\" ${_outPathVariable} "${_inPath}")
else()
message (FATAL_ERROR "Unsupported host platform ${<API key>}")
endif()
set (${_outPathVariable} "${${_outPathVariable}}" PARENT_SCOPE)
endfunction()
# internal macro to set a file's executable bit under UNIX
macro (<API key> _inPath)
if (CMAKE_HOST_UNIX)
_to_native_path ("${_inPath}" _nativePath)
execute_process(
COMMAND chmod "-f" "+x" "${_nativePath}" TIMEOUT 5)
endif()
endmacro()
# internal macro to convert list to command string with quoting
macro (_list_to_cmd_str _outCmd)
set (_str "")
foreach (_arg ${ARGN})
if ("${_arg}" MATCHES " ")
set (_arg "\"${_arg}\"")
endif()
if (_str)
set (_str "${_str} ${_arg}")
else()
set (_str "${_arg}")
endif()
endforeach()
set (${_outCmd} "${_str}")
endmacro()
# internal macro to compute kernel paths (relative to installation directory)
macro (<API key> _outKernelNames)
if (<API key> AND <API key>)
if (<API key> VERSION_LESS "10.0.0")
if (CMAKE_HOST_WIN32 OR CYGWIN)
set (${_outKernelNames} "math.exe")
elseif (CMAKE_HOST_APPLE)
set (${_outKernelNames} "Contents/MacOS/MathKernel")
elseif (CMAKE_HOST_UNIX)
set (${_outKernelNames} "Executables/MathKernel" "Executables/math")
endif()
else()
if (CMAKE_HOST_WIN32 OR CYGWIN)
set (${_outKernelNames} "wolfram.exe")
elseif (CMAKE_HOST_APPLE)
set (${_outKernelNames} "Contents/MacOS/WolframKernel")
elseif (CMAKE_HOST_UNIX)
set (${_outKernelNames} "Executables/WolframKernel")
endif()
endif()
else()
if (CMAKE_HOST_WIN32 OR CYGWIN)
set (${_outKernelNames} "wolfram.exe" "math.exe")
elseif (CMAKE_HOST_APPLE)
set (${_outKernelNames} "Contents/MacOS/WolframKernel" "Contents/MacOS/MathKernel")
elseif (CMAKE_HOST_UNIX)
set (${_outKernelNames} "Executables/WolframKernel" "Executables/MathKernel" "Executables/math")
endif()
endif()
endmacro()
# internal macro to to compute front end paths (relative to installation directory)
macro (<API key> _outFrontEndNames)
if (CMAKE_HOST_WIN32 OR CYGWIN)
set (${_outFrontEndNames} "Mathematica.exe")
elseif (CMAKE_HOST_APPLE)
set (${_outFrontEndNames} "Contents/MacOS/Mathematica")
elseif (CMAKE_HOST_UNIX)
set (${_outFrontEndNames}
"Executables/mathematica" "Executables/Mathematica")
endif()
endmacro()
# internal macro to compute program name from product name and version
# E.g., "Mathematica" and "7.0" gives "Mathematica 7.0.app" for Mac OS X
macro (<API key> _product _version _outProgramNames)
string (REPLACE " " "" <API key> "${_product}")
if (CMAKE_HOST_APPLE)
if (${_version})
# under Mac OS X the application name may contain the version number as a suffix
list (APPEND ${_outProgramNames} "${_product} ${_version}.app")
list (APPEND ${_outProgramNames} "${<API key>} ${_version}.app")
else()
list (APPEND ${_outProgramNames} "${_product}.app")
list (APPEND ${_outProgramNames} "${<API key>}.app")
endif()
else()
if (${_version})
# other platforms have a sub-directory named after the version number
list (APPEND ${_outProgramNames} "${_product}/${_version}")
list (APPEND ${_outProgramNames} "${<API key>}/${_version}")
endif()
endif()
endmacro()
# internal macro to determine search order for different versions of Mathematica
macro (_get_program_names _outProgramNames)
set (${_outProgramNames} "")
# Mathematica products in order of preference
set (_MathematicaApps "Mathematica" "Wolfram Desktop" "Wolfram Engine" "gridMathematica Server")
# Mathematica product versions in order of preference
set (<API key>
"12.2" "12.1" "12.0"
"11.3" "11.2" "11.1" "11.0"
"10.4" "10.3" "10.2" "10.1" "10.0"
"9.0" "8.0" "7.0" "6.0" "5.2")
# search for explicitly requested application version first
if (<API key> AND <API key>)
foreach (_product IN LISTS _MathematicaApps)
<API key>("${_product}"
"${<API key>}.${<API key>}"
${_outProgramNames})
endforeach()
endif()
# then try all qualified application names
foreach (_product IN LISTS _MathematicaApps)
foreach (_version IN LISTS <API key>)
<API key>("${_product}" "${_version}" ${_outProgramNames})
endforeach()
endforeach()
# then try unqualified application names
foreach (_product IN LISTS _MathematicaApps)
<API key>("${_product}" "" ${_outProgramNames})
endforeach()
list (REMOVE_DUPLICATES ${_outProgramNames})
endmacro()
# internal function to get Mathematica Windows installation directory for a registry entry
function (<API key> _registryKey _outSearchPaths)
set (<API key>
"Wolfram Mathematica [0-9.]+" "Wolfram Desktop [0-9.]+"
"Wolfram Engine [0-9.]+" "Wolfram Finance Platform")
<API key> (
_productName "[${_registryKey};ProductName]" NAME)
<API key> (
_productVersion "[${_registryKey};ProductVersion]" NAME)
<API key> (
_productPath "[${_registryKey};ExecutablePath]" PATH)
if (Mathematica_DEBUG)
message (STATUS "[${_registryKey};ProductName]=${_productName}")
message (STATUS "[${_registryKey};ProductVersion]=${_productVersion}")
message (STATUS "[${_registryKey};ExecutablePath]=${_productPath}")
endif()
set (_qualified False)
foreach (_Pattern IN LISTS <API key>)
if ("${_productName}" MATCHES "${_Pattern}")
set (_qualified True)
break()
endif()
endforeach()
if (_qualified)
if (EXISTS "${_productPath}")
_to_cmake_path("${_productPath}" _path)
if (<API key> AND <API key>)
if ("${_productVersion}" MATCHES "${<API key>}")
# prepend if version matches requested one
list (INSERT ${_outSearchPaths} 0 "${_path}")
else()
list (APPEND ${_outSearchPaths} "${_path}")
endif()
else()
list (APPEND ${_outSearchPaths} "${_path}")
endif()
endif()
endif()
set (${_outSearchPaths} ${${_outSearchPaths}} PARENT_SCOPE)
endfunction()
# internal function to determine Mathematica installation paths from Windows registry
function (<API key> _outSearchPaths)
if (CMAKE_HOST_WIN32)
foreach (_registryKey IN ITEMS ${ARGN})
set (_regExe "reg.exe")
if (DEFINED ENV{windir})
# use 64-bit reg.exe under WoW64 to make sure we search all keys
if (EXISTS "$ENV{windir}/sysnative/reg.exe")
set (_regExe "$ENV{windir}/sysnative/reg.exe")
endif()
endif()
execute_process(
COMMAND "${_regExe}" query "${_registryKey}" "/s"
COMMAND findstr "${_registryKey}"
TIMEOUT 5 OUTPUT_VARIABLE _queryResult ERROR_QUIET)
string (REGEX MATCHALL "[0-9]+" _installIDs "${_queryResult}")
if (_installIDs)
# _installIDs sorted from oldest to newest version
list (REVERSE _installIDs)
set (_paths "")
foreach (_installID IN LISTS _installIDs)
<API key>("${_registryKey}\\${_installID}" _paths)
endforeach()
list (APPEND ${_outSearchPaths} ${_paths})
endif()
endforeach()
set (${_outSearchPaths} ${${_outSearchPaths}} PARENT_SCOPE)
endif()
endfunction()
# internal function to determine Mathematica installation paths from Mac OS X LaunchServices database
function (<API key> _outSearchPaths)
if (CMAKE_HOST_APPLE)
# the lsregister executable is needed to search the LaunchServices database
# the executable usually resides in the LaunchServices framework Support directory
# The LaunchServices framework is a sub-framework of the CoreServices umbrella framework
<API key>(CoreServices)
find_program (<API key> NAMES "lsregister" PATH_SUFFIXES "Support"
HINTS "${<API key>}/Frameworks/LaunchServices.framework")
mark_as_advanced(
<API key>
<API key>
<API key>)
if (NOT <API key>)
message (STATUS "Skipping search of the LaunchServices database, because the lsregister executable could not be found.")
return()
endif()
foreach (_bundleID IN ITEMS ${ARGN})
execute_process(
COMMAND "${<API key>}" "-dump"
COMMAND "grep" "--before-context=20" "--after-context=20" " ${_bundleID} "
COMMAND "grep" "--only-matching" "/.*\\.app"
TIMEOUT 10 OUTPUT_VARIABLE _queryResult ERROR_QUIET)
string (REPLACE ";" "\\;" _queryResult "${_queryResult}")
string (REPLACE "\n" ";" _appPaths "${_queryResult}")
if (_appPaths)
# put paths into canonical order
list (SORT _appPaths)
list (REVERSE _appPaths)
else()
message (STATUS "No Mathematica apps registered in Mac OS X LaunchServices database.")
endif()
if (Mathematica_DEBUG)
message (STATUS "Mac OS X LaunchServices database registered apps=${_appPaths}")
endif()
if (_appPaths)
set (_paths "")
set (_insertIndex 0)
foreach (_appPath IN LISTS _appPaths)
# ignore paths that no longer exist
if (EXISTS "${_appPath}")
_to_cmake_path("${_appPath}" _appPath)
if (<API key> AND <API key>)
if ("${_appPath}" MATCHES "${<API key>}.${<API key>}")
# insert in front of other versions if version matches requested one
list (LENGTH _paths _len)
if (_len EQUAL _insertIndex)
list (APPEND _paths "${_appPath}")
else()
list (INSERT _paths ${_insertIndex} "${_appPath}")
endif()
math(EXPR _insertIndex "${_insertIndex} + 1")
else()
list (APPEND _paths "${_appPath}")
endif()
else()
list (APPEND _paths "${_appPath}")
endif()
endif()
endforeach()
list (APPEND ${_outSearchPaths} ${_paths})
endif()
endforeach()
set (${_outSearchPaths} ${${_outSearchPaths}} PARENT_SCOPE)
endif()
endfunction()
# internal macro to determine default Mathematica installation (the one which is on the system search path)
macro (<API key> _outSearchPaths)
set (_searchPaths "")
if (DEFINED ENV{PATH})
file (TO_CMAKE_PATH "$ENV{PATH}" _searchPaths)
endif()
<API key>(_kernelNames)
foreach (_searchPath IN LISTS _searchPaths)
if (CMAKE_HOST_WIN32 OR CYGWIN)
set (_executable "${_searchPath}/math.exe")
else()
set (_executable "${_searchPath}/math")
endif()
if (EXISTS "${_executable}")
# resolve symlinks
<API key> (_executable "${_executable}" REALPATH)
foreach (_kernelName IN LISTS _kernelNames)
string (REPLACE "${_kernelName}" "" _executableDir "${_executable}")
if (NOT "${_executable}" STREQUAL "${_executableDir}" AND
IS_DIRECTORY ${_executableDir})
if (<API key>)
list (APPEND ${_outSearchPaths} "${_executableDir}")
else()
# prefer default installation if not searching for version explicitly
list (INSERT ${_outSearchPaths} 0 "${_executableDir}")
endif()
endif()
endforeach()
endif()
endforeach()
endmacro()
# internal macro to determine platform specific Mathematica installation search paths
macro (_get_search_paths _outSearchPaths)
set (${_outSearchPaths} "")
if (CMAKE_HOST_WIN32 OR CYGWIN)
# add non-standard installation paths from Windows registry
<API key>(${_outSearchPaths}
"HKEY_LOCAL_MACHINE\\SOFTWARE\\Wolfram Research\\Installations"
"HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Wolfram Research\\Installations")
# environment variable locations where Mathematica may be installed
set (<API key> to "ProgramW6432" "ProgramFiles(x86)" "ProgramFiles" )
if (CYGWIN)
# Cygwin may be configured to convert all environment variables to all-uppercase
list (APPEND <API key> "PROGRAMW6432" "PROGRAMFILES(X86)" "PROGRAMFILES")
endif()
# add standard Mathematica Windows installation paths
foreach (_envVar IN LISTS <API key>)
if (DEFINED ENV{${_envVar})
_to_cmake_path("$ENV{${_envVar}}" _unixPath)
list (APPEND ${_outSearchPaths} "${_unixPath}/Wolfram Research" )
endif()
endforeach()
elseif (CMAKE_HOST_APPLE)
# add standard Mathematica Mac OS X installation paths
list (APPEND ${_outSearchPaths} "~/Applications;/Applications")
if (<API key>)
list (APPEND ${_outSearchPaths} ${<API key>})
endif()
# add non-standard installation paths from Mac OS X LaunchServices database
<API key>(${_outSearchPaths} "com.wolfram.Mathematica")
elseif (CMAKE_HOST_UNIX)
# add standard Mathematica Unix installation paths
list (APPEND ${_outSearchPaths} "/usr/local/Wolfram" "/opt/Wolfram")
endif()
<API key>(${_outSearchPaths})
if (${_outSearchPaths})
list (REMOVE_DUPLICATES ${_outSearchPaths})
endif()
endmacro()
# internal macro to compute Mathematica SystemIDs from system name
macro (<API key> _systemName _systemProcessor _outSystemIDs)
if ("${_systemName}" STREQUAL "Windows")
if ("${_systemProcessor}" STREQUAL "AMD64")
set (${_outSystemIDs} "Windows-x86-64")
else()
# default to 32-bit Windows
set (${_outSystemIDs} "Windows")
endif()
elseif ("${_systemName}" STREQUAL "CYGWIN")
if ("${_systemProcessor}" STREQUAL "x86_64")
set (${_outSystemIDs} "Windows-x86-64")
else()
# default to 32-bit Windows
set (${_outSystemIDs} "Windows")
endif()
elseif ("${_systemName}" STREQUAL "Darwin")
if ("${_systemProcessor}" STREQUAL "i386")
set (${_outSystemIDs} "MacOSX-x86")
elseif ("${_systemProcessor}" STREQUAL "x86_64")
set (${_outSystemIDs} "MacOSX-x86-64")
elseif ("${_systemProcessor}" MATCHES "ppc64|powerpc64")
set (${_outSystemIDs} "Darwin-PowerPC64")
elseif ("${_systemProcessor}" MATCHES "ppc|powerpc")
if (Mathematica_VERSION)
# Mathematica versions before 6 used "Darwin" as system ID for ppc32
if (NOT "${Mathematica_VERSION}" VERSION_LESS "6.0")
set (${_outSystemIDs} "MacOSX")
else()
set (${_outSystemIDs} "Darwin")
endif()
else ()
set (${_outSystemIDs} "MacOSX" "Darwin")
endif()
endif()
elseif ("${_systemName}" STREQUAL "Linux")
if ("${_systemProcessor}" MATCHES "^i.86$")
set (${_outSystemIDs} "Linux")
elseif ("${_systemProcessor}" MATCHES "x86_64|amd64")
set (${_outSystemIDs} "Linux-x86-64")
elseif ("${_systemProcessor}" STREQUAL "ia64")
set (${_outSystemIDs} "Linux-IA64")
elseif ("${_systemProcessor}" MATCHES "^arm")
set (${_outSystemIDs} "Linux-ARM")
endif()
elseif ("${_systemName}" STREQUAL "SunOS")
if ("${_systemProcessor}" MATCHES "^sparc")
if (Mathematica_VERSION)
# Mathematica versions before 6 used "UltraSPARC" as system ID for Solaris
if (NOT "${Mathematica_VERSION}" VERSION_LESS "6.0")
set (${_outSystemIDs} "Solaris-SPARC")
else()
set (${_outSystemIDs} "UltraSPARC")
endif()
else ()
set (${_outSystemIDs} "Solaris-SPARC" "UltraSPARC")
endif()
elseif ("${_systemProcessor}" STREQUAL "x86_64")
set (${_outSystemIDs} "Solaris-x86-64")
endif()
elseif ("${_systemName}" STREQUAL "AIX")
set (${_outSystemIDs} "AIX-Power64")
elseif ("${_systemName}" STREQUAL "HP-UX")
set (${_outSystemIDs} "HPUX-PA64")
elseif ("${_systemName}" STREQUAL "IRIX")
set (${_outSystemIDs} "IRIX-MIPS64")
endif()
endmacro(<API key>)
# internal macro to compute target Mathematica SystemIDs
macro (_get_system_IDs _outSystemIDs)
if (WIN32 OR CYGWIN)
# pointer size check is more reliable than <API key>
if (CMAKE_SIZEOF_VOID_P EQUAL 8)
set (${_outSystemIDs} "Windows-x86-64")
else()
set (${_outSystemIDs} "Windows")
endif()
elseif (APPLE)
set (${_outSystemIDs} "")
if (<API key>)
# determine System ID from specified architectures
foreach (_arch ${<API key>})
set (_systemID "")
<API key>("${CMAKE_SYSTEM_NAME}" "${_arch}" _systemID)
if (_systemID)
list (APPEND ${_outSystemIDs} ${_systemID})
else()
message (FATAL_ERROR "Unsupported Mac OS X architecture ${_arch}")
endif()
endforeach()
else()
# determine System ID by checking endianness and pointer size
TEST_BIG_ENDIAN(_isBigEndian)
if (_isBigEndian)
if (CMAKE_SIZEOF_VOID_P EQUAL 8)
set (${_outSystemIDs} "Darwin-PowerPC64")
else()
if (Mathematica_VERSION)
# Mathematica versions before 6 used "Darwin" as system ID for ppc32
if (NOT "${Mathematica_VERSION}" VERSION_LESS "6.0")
set (${_outSystemIDs} "MacOSX")
else()
set (${_outSystemIDs} "Darwin")
endif()
else ()
set (${_outSystemIDs} "MacOSX" "Darwin")
endif()
endif()
else()
if (CMAKE_SIZEOF_VOID_P EQUAL 8)
set (${_outSystemIDs} "MacOSX-x86-64")
else()
set (${_outSystemIDs} "MacOSX-x86")
endif()
endif()
endif()
elseif (UNIX)
if ("${CMAKE_SYSTEM_NAME}" STREQUAL "Linux")
# pointer size check is more reliable than <API key>
if (CMAKE_SIZEOF_VOID_P EQUAL 8)
set (${_outSystemIDs} "Linux-x86-64")
else()
set (${_outSystemIDs} "Linux")
endif()
else()
<API key>("${CMAKE_SYSTEM_NAME}" "${<API key>}" ${_outSystemIDs})
endif()
else()
set (${_outSystemIDs} "Generic")
endif()
list (REMOVE_DUPLICATES ${_outSystemIDs})
endmacro(_get_system_IDs)
# internal macro to compute host Mathematica SystemIDs
macro (<API key> _outSystemIDs)
if (CMAKE_HOST_WIN32)
set (${_outSystemIDs} "Windows")
if (DEFINED ENV{<API key>})
if ("$ENV{<API key>}" STREQUAL "AMD64")
# running of WoW64, host is native 64-bit Windows
set (${_outSystemIDs} "Windows-x86-64")
endif()
elseif (DEFINED ENV{<API key>})
if ("$ENV{<API key>}" STREQUAL "AMD64")
# host is native 64-bit Windows
set (${_outSystemIDs} "Windows-x86-64")
endif()
endif()
else()
# always determine host system ID from
# <API key> and <API key>
if (_CMAKE_OSX_MACHINE)
# work-around for Mac OS X, where <API key> is not always accurate
set (<API key> "${_CMAKE_OSX_MACHINE}")
else()
set (<API key> "${<API key>}")
endif()
<API key>(
"${<API key>}" "${<API key>}"
_hostSystemID)
if (NOT DEFINED _hostSystemID)
message (FATAL_ERROR "Unsupported host platform ${<API key>}")
endif()
<API key>(${_hostSystemID} ${_outSystemIDs})
endif()
endmacro()
macro (<API key> _version _outSystemIDs)
if (NOT "${_version}" VERSION_LESS "12.1")
set (${_outSystemIDs}
"Windows-x86-64"
"Linux-x86-64" "Linux-ARM"
"MacOSX-x86-64")
elseif (NOT "${_version}" VERSION_LESS "11.3")
set (${_outSystemIDs}
"Windows" "Windows-x86-64"
"Linux-x86-64" "Linux-ARM"
"MacOSX-x86-64")
elseif (NOT "${_version}" VERSION_LESS "10.0")
set (${_outSystemIDs}
"Windows" "Windows-x86-64"
"Linux" "Linux-x86-64" "Linux-ARM"
"MacOSX-x86-64")
elseif (NOT "${_version}" VERSION_LESS "9.0")
set (${_outSystemIDs}
"Windows" "Windows-x86-64"
"Linux" "Linux-x86-64"
"MacOSX-x86-64")
elseif (NOT "${_version}" VERSION_LESS "8.0")
set (${_outSystemIDs}
"Windows" "Windows-x86-64"
"Linux" "Linux-x86-64"
"MacOSX-x86" "MacOSX-x86-64")
elseif (NOT "${_version}" VERSION_LESS "7.0")
set (${_outSystemIDs}
"Windows" "Windows-x86-64"
"Linux" "Linux-x86-64"
"MacOSX-x86" "MacOSX-x86-64" "MacOSX"
"Solaris-SPARC" "Solaris-x86-64")
elseif (NOT "${_version}" VERSION_LESS "6.0")
set (${_outSystemIDs}
"Windows" "Windows-x86-64"
"Linux" "Linux-x86-64" "Linux-IA64"
"MacOSX-x86" "MacOSX-x86-64" "MacOSX"
"Solaris-SPARC" "Solaris-x86-64"
"AIX-Power64")
elseif (NOT "${_version}" VERSION_LESS "5.2")
set (${_outSystemIDs}
"Windows" "Windows-x86-64"
"Linux" "Linux-x86-64" "Linux-IA64"
"MacOSX-x86" "Darwin-PowerPC64" "Darwin"
"UltraSPARC" "Solaris-x86-64"
"AIX-Power64" "DEC-AXP" "HPUX-PA64" "IRIX-MIPS64")
else()
# platforms probably supported before 5.2?
set (${_outSystemIDs}
"Windows"
"Linux" "Linux-x86-64" "Linux-IA64" "Linux-PPC"
"Darwin"
"Solaris" "SGI"
"IBM-RISC" "DEC-AXP" "HP-RISC" "IRIX-MIPS32" "IRIX-MIPS64")
endif()
endmacro()
macro (<API key> _systemID _outSystemIDs)
set (${_outSystemIDs} "")
if ("${_systemID}" STREQUAL "Windows-x86-64")
if (Mathematica_VERSION)
if (NOT "${Mathematica_VERSION}" VERSION_LESS "5.2")
# Mathematica 5.2 added support for Windows-x86-64
list (APPEND ${_outSystemIDs} "Windows-x86-64")
endif()
else()
list (APPEND ${_outSystemIDs} "Windows-x86-64")
endif()
if (Mathematica_VERSION)
# Mathematica 12.1 dropped support for x86
if ("${Mathematica_VERSION}" VERSION_LESS "12.1")
# Windows x64 can run x86 through WoW64
list (APPEND ${_outSystemIDs} "Windows")
endif()
else()
# Windows x64 can run x86 through WoW64
list (APPEND ${_outSystemIDs} "Windows")
endif()
elseif ("${_systemID}" MATCHES "MacOSX|Darwin")
if ("${_systemID}" MATCHES "MacOSX-x86")
if (Mathematica_VERSION)
# Mathematica 6 added support for MacOSX-x86-64
if (NOT "${Mathematica_VERSION}" VERSION_LESS "6.0")
list (APPEND ${_outSystemIDs} "MacOSX-x86-64")
endif()
# Mathematica 5.2 added support for MacOSX-x86
# Mathematica 9.0 dropped support for MacOSX-x86
if (NOT "${Mathematica_VERSION}" VERSION_LESS "5.2" AND
"${Mathematica_VERSION}" VERSION_LESS "9.0")
list (APPEND ${_outSystemIDs} "MacOSX-x86")
endif()
else()
list (APPEND ${_outSystemIDs} "MacOSX-x86-64" "MacOSX-x86")
endif()
elseif ("${_systemID}" STREQUAL "Darwin-PowerPC64")
if (Mathematica_VERSION)
if (NOT "${Mathematica_VERSION}" VERSION_LESS "5.2" AND
"${Mathematica_VERSION}" VERSION_LESS "6.0")
# Only Mathematica 5.2 supports Darwin-PowerPC64
list (APPEND ${_outSystemIDs} "Darwin-PowerPC64")
endif()
else()
list (APPEND ${_outSystemIDs} "Darwin-PowerPC64")
endif()
endif()
# handle ppc32 (Darwin or MacOSX)
# Mac OS X versions before Lion support ppc32 natively or through Rosetta
# (Mac OS X 10.7.0 is Darwin 11.0.0)
if ("${<API key>}" VERSION_LESS "11.0.0")
if (Mathematica_VERSION)
if ("${Mathematica_VERSION}" VERSION_LESS "6.0")
# Mathematica versions before 6 used "Darwin" as system ID for ppc32
list (APPEND ${_outSystemIDs} "Darwin")
elseif ("${Mathematica_VERSION}" VERSION_LESS "8.0")
# Mathematica 8 dropped support for ppc32
list (APPEND ${_outSystemIDs} "MacOSX")
endif()
else()
list (APPEND ${_outSystemIDs} "MacOSX" "Darwin")
endif()
endif()
elseif ("${_systemID}" MATCHES "Linux-x86-64|Linux-IA64")
if (Mathematica_VERSION)
if (NOT "${Mathematica_VERSION}" VERSION_LESS "5.2")
# Mathematica 5.2 added support for 64-bit
list (APPEND ${_outSystemIDs} ${_systemID})
endif()
else()
list (APPEND ${_outSystemIDs} ${_systemID})
endif()
# Linux 64-bit can run x86 through ia32-libs package
if (Mathematica_VERSION)
if ("${Mathematica_VERSION}" VERSION_LESS "11.3")
# Mathematica 11.3 dropped support for 32-bit Linux
list (APPEND ${_outSystemIDs} "Linux")
endif()
else()
list (APPEND ${_outSystemIDs} "Linux")
endif()
else()
list (APPEND ${_outSystemIDs} ${_systemID})
endif()
list (REMOVE_DUPLICATES ${_outSystemIDs})
endmacro()
# internal macro to compute target MathLink / WSTP DeveloperKit system ID
macro(<API key> _outSystemIDs)
if (APPLE)
if (Mathematica_VERSION)
if ("${Mathematica_VERSION}" VERSION_LESS "9.0")
# Mathematica versions before 9 did not have a system ID subdirectory
set (${_outSystemIDs} "")
else()
# Mathematica versions after 9 have a system ID subdirectory
set (${_outSystemIDs} "MacOSX-x86-64")
endif()
else()
_get_system_IDs(${_outSystemIDs})
endif()
else()
_get_system_IDs(${_outSystemIDs})
endif()
endmacro()
# internal macro to compute host MathLink / WSTP DeveloperKit system ID
macro(<API key> _outSystemIDs)
if (CMAKE_HOST_APPLE)
if (Mathematica_VERSION)
# Mathematica versions before 9 did not have a system ID subdirectory
if ("${Mathematica_VERSION}" VERSION_LESS "9.0")
set (${_outSystemIDs} "")
else()
# The MacOSX-x86-64 DeveloperKit is a universal binary with architectures i386 and x86_64
set (${_outSystemIDs} "MacOSX-x86-64")
endif()
else()
<API key>(${_outSystemIDs})
endif()
else()
<API key>(${_outSystemIDs})
endif()
endmacro()
# internal macro to compute target development flavor
macro (_get_target_flavor _outFlavor)
if (CYGWIN)
set (${_outFlavor} "cygwin")
elseif (WIN32)
if (CMAKE_SIZEOF_VOID_P EQUAL 8)
set (${_outFlavor} "mldev64")
else()
set (${_outFlavor} "mldev32")
endif()
elseif (APPLE)
set (${_outFlavor} "")
if (Mathematica_VERSION)
if (<API key> AND
NOT "${Mathematica_VERSION}" VERSION_LESS "10.0" AND
"${Mathematica_VERSION}" VERSION_LESS "10.4")
# Mathematica 10 added LLVM libc++ compiled version in <API key> directory
# Mathematica 10.4 and later only ship with LLVM libc++ compiled version
set (${_outFlavor} "<API key>")
endif()
endif()
else()
# no flavors on non-Windows platforms
set (${_outFlavor} "")
endif()
endmacro()
# internal macro to compute host development flavor
macro (_get_host_flavor _outFlavor)
if (CYGWIN)
set (${_outFlavor} "cygwin")
elseif (CMAKE_HOST_WIN32)
set (${_outFlavor} "mldev32")
if (DEFINED ENV{<API key>})
if ("$ENV{<API key>}" STREQUAL "AMD64")
# running of WoW64, host is native 64-bit Windows
set (${_outFlavor} "mldev64")
endif()
elseif (DEFINED ENV{<API key>})
if ("$ENV{<API key>}" STREQUAL "AMD64")
# host is native 64-bit Windows
set (${_outFlavor} "mldev64")
endif()
endif()
elseif (CMAKE_HOST_APPLE)
set (${_outFlavor} "")
if (Mathematica_VERSION)
if (<API key> AND
NOT "${Mathematica_VERSION}" VERSION_LESS "10.0" AND
"${Mathematica_VERSION}" VERSION_LESS "10.4")
# Mathematica 10 added LLVM libc++ compiled version in <API key> directory
# Mathematica 10.4 and later only ship with LLVM libc++ compiled version
set (${_outFlavor} "<API key>")
endif()
endif()
else()
# no flavors on non-Windows platforms
set (${_outFlavor} "")
endif()
endmacro()
# internal macro to compute WolframRTL library names
macro (<API key> _outLibraryNames)
if (<API key>)
set (${_outLibraryNames} "<API key>" )
else()
if (<API key>)
set (${_outLibraryNames} "WolframRTL_Minimal" )
else()
set (${_outLibraryNames} "WolframRTL" )
endif()
endif()
endmacro()
# internal macro to compute MathLink library names
macro (<API key> _outLibraryNames)
if (CYGWIN)
if (DEFINED <API key>)
set (${_outLibraryNames} "ML32i${<API key>}")
else()
set (${_outLibraryNames} "ML32i4" "ML32i3" "ML32i2" "ML32i1")
endif()
elseif (WIN32)
if (CMAKE_SIZEOF_VOID_P EQUAL 8)
if (BORLAND)
set (${_outLibraryNames} "ml64i3b" "ml64i2b")
elseif (WATCOM)
set (${_outLibraryNames} "ml64i3w" "ml64i2w")
endif()
# always add default Microsoft 64-bit PE libraries
if (DEFINED <API key>)
if (<API key>)
list (APPEND ${_outLibraryNames} "ml64i${<API key>}s")
else()
list (APPEND ${_outLibraryNames} "ml64i${<API key>}m")
endif()
else()
if (<API key>)
list (APPEND ${_outLibraryNames} "ml64i4s" "ml64i3s")
else()
list (APPEND ${_outLibraryNames} "ml64i4m" "ml64i3m" "ml64i2m")
endif()
endif()
else()
if (BORLAND)
set (${_outLibraryNames} "ml32i3b" "ml32i2b" "ml32i1b")
elseif (WATCOM)
set (${_outLibraryNames} "ml32i3w" "ml32i2w" "ml32i1w")
endif()
# always add default Microsoft 32-bit PE libraries
if (DEFINED <API key>)
if (<API key>)
list (APPEND ${_outLibraryNames} "ml32i${<API key>}s")
else()
list (APPEND ${_outLibraryNames} "ml32i${<API key>}m")
endif()
else()
if (<API key>)
list (APPEND ${_outLibraryNames} "ml32i4s" "ml32i3s")
else()
list (APPEND ${_outLibraryNames} "ml32i4m" "ml32i3m" "ml32i2m" "ml32i1m")
endif()
endif()
endif()
elseif (APPLE)
if (<API key>)
if (DEFINED <API key> AND DEFINED <API key>)
set (${_outLibraryNames} "libMLi${<API key>}.${<API key>}.a")
elseif (DEFINED <API key>)
set (${_outLibraryNames} "libMLi${<API key>}.a")
else()
set (${_outLibraryNames} "libMLi4.a" "libMLi3.a" "libML.a")
endif()
else()
# search for mathlink.framework
set (${_outLibraryNames} "mathlink" "ML")
endif()
elseif (UNIX)
if (<API key>)
set (_ext ".a")
else()
set (_ext ".so")
endif()
if (CMAKE_SIZEOF_VOID_P EQUAL 8)
set (_arch "64")
else()
set (_arch "32")
endif()
if (DEFINED <API key>)
set (${_outLibraryNames} "libML${_arch}i${<API key>}${_ext}")
else()
set (${_outLibraryNames} "libML${_arch}i4${_ext}" "libML${_arch}i3${_ext}" "libML${_ext}")
endif()
endif()
endmacro(<API key>)
function (<API key> _templateFile _outfile)
<API key>(_templateFile_name ${_templateFile} NAME)
<API key>(_templateFile_ext "${_templateFile}" EXT)
if (_templateFile_ext STREQUAL ".tmpp")
set (${_outfile} "${_templateFile_name}.cpp" PARENT_SCOPE)
elseif (_templateFile_ext STREQUAL ".tm++")
set (${_outfile} "${_templateFile_name}.c++" PARENT_SCOPE)
elseif (_templateFile_ext STREQUAL ".tmxx")
set (${_outfile} "${_templateFile_name}.cxx" PARENT_SCOPE)
else()
set (${_outfile} "${_templateFile_name}.c" PARENT_SCOPE)
endif()
endfunction()
# internal macro to compute WSTP library names
macro (<API key> _outLibraryNames)
if (CYGWIN)
if (DEFINED <API key>)
set (${_outLibraryNames} "WSTP32i${<API key>}")
else()
set (${_outLibraryNames} "WSTP32i4" "WSTP32i3" "WSTP32i2" "WSTP32i1")
endif()
elseif (WIN32)
if (CMAKE_SIZEOF_VOID_P EQUAL 8)
set (_arch "64")
else()
set (_arch "32")
endif()
if (DEFINED <API key>)
if (<API key>)
list (APPEND ${_outLibraryNames} "wstp${_arch}i${<API key>}s")
else()
list (APPEND ${_outLibraryNames} "wstp${_arch}i${<API key>}m")
endif()
else()
if (<API key>)
list (APPEND ${_outLibraryNames} "wstp${_arch}i4s" "wstp${_arch}i3s")
else()
list (APPEND ${_outLibraryNames} "wstp${_arch}i4m" "wstp${_arch}i3m" "wstp${_arch}i2m" "wstp${_arch}i1m")
endif()
endif()
elseif (APPLE)
if (<API key>)
if (DEFINED <API key> AND DEFINED <API key>)
set (${_outLibraryNames} "libWSTPi${<API key>}.${<API key>}.a")
elseif (DEFINED <API key>)
set (${_outLibraryNames} "libWSTPi${<API key>}.a")
else()
set (${_outLibraryNames} "libWSTPi4.a" "libWSTPi3.a")
endif()
else()
# search for wstp.framework
set (${_outLibraryNames} "wstp")
endif()
elseif (UNIX)
if (<API key>)
set (_ext ".a")
else()
set (_ext ".so")
endif()
if (CMAKE_SIZEOF_VOID_P EQUAL 8)
set (_arch "64")
else()
set (_arch "32")
endif()
if (DEFINED <API key>)
set (${_outLibraryNames} "libWSTP${_arch}i${<API key>}${_ext}")
else()
set (${_outLibraryNames} "libWSTP${_arch}i4${_ext}" "libWSTP${_arch}i3${_ext}")
endif()
endif()
endmacro(<API key>)
# internal macro to compute Java launcher name
macro (<API key> _outExecutabeName)
if (CMAKE_HOST_WIN32)
set (${_outExecutabeName} "java.exe")
elseif (CMAKE_HOST_UNIX)
set (${_outExecutabeName} "java")
endif()
endmacro()
# internal macro to compute required WolframRTL system libraries
macro (<API key> _outLibraries)
if (UNIX)
if (CMAKE_SYSTEM_NAME STREQUAL "Linux")
list (APPEND ${_outLibraries} pthread m )
endif()
endif()
endmacro()
# internal macro to compute required MathLink system libraries
macro (<API key> _outLibraries)
if (APPLE)
if (DEFINED <API key>)
if ("${<API key>}" GREATER 18)
# OS X MathLink API revision >= 19 has dependency on C++ standard library
if (<API key>)
# LLVM libc++
list (APPEND ${_outLibraries} c++ )
else()
# GNU libstdc++
list (APPEND ${_outLibraries} stdc++ )
endif()
endif()
if ("${<API key>}" GREATER 20)
# Mac OS X MathLink API revision >= 21 has dependency on Core Foundation framework
list (APPEND ${_outLibraries} "-framework Foundation" )
endif()
endif()
elseif (UNIX)
if (DEFINED <API key>)
if ("${<API key>}" GREATER 18)
# UNIX MathLink API revision >= 19 has dependency on GNU libstdc++
list (APPEND ${_outLibraries} stdc++ )
endif()
endif()
if (CMAKE_SYSTEM_NAME STREQUAL "Linux")
list (APPEND ${_outLibraries} m)
set (<API key> TRUE)
find_package(Threads REQUIRED)
list (APPEND ${_outLibraries} "${<API key>}")
find_library(<API key> rt)
mark_as_advanced(<API key>)
list (APPEND ${_outLibraries} ${<API key>})
if (DEFINED <API key>)
if ("${<API key>}" GREATER 24)
# Linux MathLink API revision >= 25 has dependency on libdl and libuuid
list (APPEND ${_outLibraries} ${CMAKE_DL_LIBS})
find_library (<API key> uuid)
mark_as_advanced(<API key>)
list (APPEND ${_outLibraries} ${<API key>})
endif()
endif()
elseif (CMAKE_SYSTEM_NAME STREQUAL "SunOS")
list (APPEND ${_outLibraries} m socket nsl rt )
elseif (CMAKE_SYSTEM_NAME STREQUAL "AIX")
list (APPEND ${_outLibraries} m pthread )
elseif (CMAKE_SYSTEM_NAME STREQUAL "HP-UX")
list (APPEND ${_outLibraries}
m /usr/lib/pa20_64/libdld.sl /usr/lib/pa20_64/libm.a pthread rt )
elseif (CMAKE_SYSTEM_NAME STREQUAL "IRIX")
list (APPEND ${_outLibraries} m pthread )
endif()
elseif (WIN32)
if (DEFINED <API key>)
if ("${<API key>}" GREATER 19)
# Windows MathLink API revision >= 20 has dependency on Winsock 2
list (APPEND ${_outLibraries} Ws2_32.lib )
endif()
if ("${<API key>}" GREATER 24)
# Windows MathLink API interface >= 25 has dependency on RPC
list (APPEND ${_outLibraries} Rpcrt4.lib )
endif()
endif()
endif()
endmacro()
# internal macro to compute required WSTP system libraries
macro (<API key> _outLibraries)
if (APPLE)
if (DEFINED <API key>)
if ("${<API key>}" GREATER 18)
# OS X WSTP API revision >= 19 has dependency on C++ standard library
if (<API key>)
# LLVM libc++
list (APPEND ${_outLibraries} c++ )
else()
# GNU libstdc++
list (APPEND ${_outLibraries} stdc++ )
endif()
endif()
if ("${<API key>}" GREATER 20)
# Mac OS X WSTP API revision >= 21 has dependency on Core Foundation framework
list (APPEND ${_outLibraries} "-framework Foundation" )
endif()
endif()
elseif (UNIX)
if (CMAKE_SYSTEM_NAME STREQUAL "Linux")
if (DEFINED <API key>)
if ("${<API key>}" GREATER 18)
# UNIX WSTP API revision >= 19 has dependency on GNU libstdc++
list (APPEND ${_outLibraries} stdc++ )
endif()
endif()
list (APPEND ${_outLibraries} m pthread rt )
if (DEFINED <API key>)
if ("${<API key>}" GREATER 24)
# Linux WSTP API revision >= 25 has dependency on libdl and libuuid
list (APPEND ${_outLibraries} dl uuid)
endif()
endif()
endif()
elseif (WIN32)
if (DEFINED <API key>)
if ("${<API key>}" GREATER 19)
# Windows WSTP API revision >= 20 has dependency on Winsock 2
list (APPEND ${_outLibraries} Ws2_32.lib )
endif()
if ("${<API key>}" GREATER 24)
# Windows WSTP API interface >= 25 has dependency on RPC
list (APPEND ${_outLibraries} Rpcrt4.lib )
endif()
endif()
endif()
endmacro()
# internal macro to return dynamic library search path environment variables on host platform
macro (<API key> _outVariableNames)
set (${_outVariableNames} "")
if (CMAKE_HOST_APPLE)
list (APPEND ${_outVariableNames} "DYLD_FRAMEWORK_PATH" "DYLD_LIBRARY_PATH")
elseif (CYGWIN)
list (APPEND ${_outVariableNames} "PATH" "LD_LIBRARY_PATH")
elseif (CMAKE_HOST_WIN32)
list (APPEND ${_outVariableNames} "PATH")
elseif (CMAKE_HOST_UNIX)
if ("${<API key>}" STREQUAL "SunOS")
list (APPEND ${_outVariableNames} "LD_LIBRARY_PATH_64")
elseif ("${<API key>}" STREQUAL "AIX")
list (APPEND ${_outVariableNames} "LIBPATH")
elseif ("${<API key>}" STREQUAL "HP-UX")
list (APPEND ${_outVariableNames} "SHLIB_PATH")
elseif ("${<API key>}" STREQUAL "IRIX")
list (APPEND ${_outVariableNames} "LD_LIBRARY64_PATH")
endif()
list (APPEND ${_outVariableNames} "LD_LIBRARY_PATH")
endif()
endmacro()
# internal macro to convert list to a search path list for host platform
function (<API key> _outPathList)
set (_nativePathList "")
foreach (_path ${ARGN})
_to_native_path("${_path}" _nativePath)
list (APPEND _nativePathList "${_nativePath}")
endforeach()
if (CMAKE_HOST_UNIX)
string (REPLACE ";" ":" _nativePathList "${_nativePathList}")
elseif (CMAKE_HOST_WIN32)
# prevent CMake from interpreting ; as a list separator
string (REPLACE ";" "\\;" _nativePathList "${_nativePathList}")
endif()
set (${_outPathList} "${_nativePathList}" PARENT_SCOPE)
endfunction()
function (_to_cmake_path_list _outPathList)
set (_cmakePathList "")
foreach (_path ${ARGN})
_to_cmake_path("${_path}" _cmakePath)
list (APPEND _cmakePathList "${_cmakePath}")
endforeach()
if (CMAKE_HOST_UNIX)
string (REPLACE ";" ":" _cmakePathList "${_cmakePathList}")
elseif (CMAKE_HOST_WIN32)
# prevent CMake from interpreting ; as a list separator
string (REPLACE ";" "\\;" _cmakePathList "${_cmakePathList}")
endif()
set (${_outPathList} "${_cmakePathList}" PARENT_SCOPE)
endfunction()
# internal macro to select runtime libraries according to build type
macro (<API key> _outRuntimeDirs)
set (${_outRuntimeDirs} ${<API key>})
if (DEFINED CMAKE_BUILD_TYPE)
if ("${CMAKE_BUILD_TYPE}" STREQUAL "Debug")
set (${_outRuntimeDirs} ${<API key>})
endif()
endif()
endmacro()
# internal macro to set up Mathematica host system IDs
macro (<API key>)
_get_system_IDs(<API key>)
# default target platform system ID is first one in <API key>
list(GET <API key> 0 <API key>)
if (<API key> AND COMMAND Mathematica_EXECUTE)
# determine true host system ID which depends on both Mathematica version
# and OS variant by running Mathematica kernel
Mathematica_EXECUTE(
CODE "Print[StandardForm[$SystemID]]"
OUTPUT_VARIABLE <API key>
CACHE DOC "Actual Mathematica host system ID."
TIMEOUT 10)
if (NOT <API key>)
message (WARNING "Cannot accurately determine Mathematica host system ID.")
endif()
endif()
if (<API key>)
if (<API key> MATCHES "[a-zA-Z0-9_-]+")
set (<API key> "${<API key>}")
else()
unset (<API key> CACHE)
endif()
else()
# guess host system ID from the environment
<API key>(_HostSystemIDs)
# default to first ID in _HostSystemIDs
list (GET _HostSystemIDs 0 <API key>)
endif()
<API key>(${<API key>} <API key>)
endmacro()
# internal macro to set up Mathematica creation ID
macro (<API key>)
if (DEFINED <API key>)
if (EXISTS "${<API key>}/.CreationID")
# parse hidden CreationID file
file (STRINGS "${<API key>}/.CreationID" <API key> REGEX "[0-9]+")
elseif (CMAKE_HOST_APPLE AND EXISTS "${<API key>}/Contents/Info.plist")
execute_process(
COMMAND "grep" "--after-context=1" "<API key>"
"${<API key>}/Contents/Info.plist"
TIMEOUT 10 OUTPUT_VARIABLE _versionStr ERROR_QUIET)
if (_versionStr MATCHES "\\.([0-9]+)</string>")
# OS X Info.plist <API key> has Creation ID as last version component
set (<API key> "${CMAKE_MATCH_1}")
else()
set (_versionLine "")
endif()
endif()
endif()
if (NOT DEFINED <API key> AND DEFINED <API key>)
set (<API key> ${<API key>})
endif()
endmacro()
# internal macro to set up Mathematica base directory variable
macro (<API key>)
if (<API key> AND COMMAND Mathematica_EXECUTE)
# determine true $BaseDirectory
Mathematica_EXECUTE(
CODE "Print[StandardForm[$BaseDirectory]]"
OUTPUT_VARIABLE <API key>
CACHE DOC "Actual Mathematica $BaseDirectory."
TIMEOUT 10)
if (NOT <API key>)
message (WARNING "Cannot accurately determine Mathematica $BaseDirectory.")
endif()
endif()
if (<API key>)
if (IS_ABSOLUTE "${<API key>}")
set (<API key> "${<API key>}")
else()
unset (<API key> CACHE)
endif()
else ()
# guess <API key> from environment
# environment variable MATHEMATICA_BASE may override default
# $BaseDirectory, see
if (DEFINED ENV{MATHEMATICA_BASE})
set (<API key> "$ENV{MATHEMATICA_BASE}")
elseif (CMAKE_HOST_WIN32 OR CYGWIN)
if (DEFINED $ENV{PROGRAMDATA})
set (<API key> "$ENV{PROGRAMDATA}\\Mathematica")
elseif (DEFINED ENV{ALLUSERSAPPDATA})
set (<API key> "$ENV{ALLUSERSAPPDATA}\\Mathematica")
elseif (DEFINED ENV{USERPROFILE} AND
DEFINED ENV{ALLUSERSPROFILE} AND
DEFINED ENV{APPDATA})
string (REPLACE "$ENV{USERPROFILE}" "$ENV{ALLUSERSPROFILE}"
<API key> "$ENV{APPDATA}\\Mathematica")
endif()
elseif (CMAKE_HOST_APPLE)
set (<API key> "/Library/Mathematica")
elseif (CMAKE_HOST_UNIX)
set (<API key> "/usr/share/Mathematica")
endif()
endif()
if (<API key>)
<API key>(<API key> "${<API key>}" ABSOLUTE)
_to_cmake_path("${<API key>}" <API key>)
else()
set (<API key> "<API key>")
message (WARNING "Cannot determine Mathematica base directory.")
endif()
endmacro()
# internal macro to set up Mathematica user base directory variable
macro (<API key>)
if (<API key> AND COMMAND Mathematica_EXECUTE)
# determine true $UserBaseDirectory
Mathematica_EXECUTE(
CODE "Print[StandardForm[$UserBaseDirectory]]"
OUTPUT_VARIABLE <API key>
CACHE DOC "Actual Mathematica $UserBaseDirectory."
TIMEOUT 10)
if (NOT <API key>)
message (WARNING "Cannot accurately determine Mathematica $UserBaseDirectory.")
endif()
endif()
if (<API key>)
if (IS_ABSOLUTE "${<API key>}")
set (<API key> "${<API key>}")
else()
unset (<API key> CACHE)
endif()
else ()
# guess <API key> from environment
# environment variable <API key> may override default
# $UserBaseDirectory, see
if (DEFINED ENV{<API key>})
set (<API key> "$ENV{<API key>}")
elseif (CMAKE_HOST_WIN32 OR CYGWIN)
if (DEFINED ENV{APPDATA})
set (<API key> "$ENV{APPDATA}\\Mathematica")
endif()
elseif (CMAKE_HOST_APPLE)
if (DEFINED ENV{HOME})
set (<API key> "$ENV{HOME}/Library/Mathematica")
endif()
elseif (CMAKE_HOST_UNIX)
if (DEFINED ENV{HOME})
set (<API key> "$ENV{HOME}/.Mathematica")
endif()
endif()
endif()
if (<API key>)
<API key>(<API key> "${<API key>}" ABSOLUTE)
_to_cmake_path("${<API key>}" <API key>)
else()
set (<API key> "<API key>")
message (WARNING "Cannot determine Mathematica user base directory.")
endif()
endmacro()
# internal macro to setup FindMathematica option variables
macro (<API key>)
if (NOT DEFINED <API key>)
if (DEFINED <API key>)
set (<API key> ${<API key>})
else()
set (<API key> FALSE)
endif()
endif()
option (<API key>
"prefer static Mathematica libraries to dynamic libraries?"
${<API key>})
if (NOT DEFINED <API key>)
if (DEFINED <API key>)
set (<API key> ${<API key>})
else()
set (<API key> FALSE)
endif()
endif()
option (<API key>
"prefer minimal Mathematica libraries to full libraries?"
${<API key>})
if (NOT DEFINED <API key>)
if (DEFINED <API key>)
set (<API key> ${<API key>})
else()
# starting with OS X 10.9, Clang uses libc++ by default
if (APPLE AND NOT "${<API key>}" VERSION_LESS "13.0.0" AND "${<API key>}" MATCHES "Clang")
set (<API key> TRUE)
else()
set (<API key> FALSE)
endif()
endif()
endif()
option (<API key>
"prefer Mathematica libraries linked with LLVM libc++ to those linked with GNU libstdc++?"
${<API key>})
if (NOT DEFINED <API key>)
if (DEFINED Mathematica_DEBUG)
set (<API key> ${Mathematica_DEBUG})
else()
set (<API key> FALSE)
endif()
endif()
option (Mathematica_DEBUG
"enable FindMathematica debugging output?"
${<API key>})
if (NOT DEFINED <API key>)
if (DEFINED <API key>)
set (<API key> ${<API key>})
else()
set (<API key> TRUE)
endif()
endif()
option (<API key>
"allow FindMathematica to implicitly run the Mathematica kernel at CMake configure time?"
${<API key>})
endmacro()
# internal macro to find Mathematica installation
macro (_find_mathematica)
<API key>(<API key>)
<API key>(_KernelExecutables)
if (Mathematica_DEBUG)
message (STATUS "FrontEndExecutables ${<API key>}")
message (STATUS "KernelExecutables ${_KernelExecutables}")
endif()
set (_helpStr "Mathematica host installation root directory.")
if (NOT DEFINED <API key>)
set (_doSearch TRUE)
elseif (NOT EXISTS "${<API key>}")
set (_doSearch TRUE)
else()
set (_doSearch FALSE)
endif()
if (_doSearch)
_get_search_paths(_SearchPaths)
_get_program_names(_ProgramNames)
if (Mathematica_DEBUG)
message (STATUS "SearchPaths ${_SearchPaths}")
message (STATUS "ProgramNames ${_ProgramNames}")
message (STATUS "KernelExecutables ${_KernelExecutables}")
endif()
find_path (<API key>
NAMES ${_KernelExecutables}
PATH_SUFFIXES ${_ProgramNames}
PATHS ${_SearchPaths} ENV MATHEMATICA_HOME
DOC "${_helpStr}"
NO_DEFAULT_PATH <API key>
)
else()
# preserve pre-defined value, but set correct type and help string
set_property(CACHE <API key> PROPERTY TYPE PATH)
set_property(CACHE <API key> PROPERTY HELPSTRING "${_helpStr}")
endif()
# <API key> is initialized to <API key> by default
# upon cross-compiling <API key> needs to be manually set to the correct
# Mathematica installation folder for the target platform
set (_helpStr "Mathematica target installation root directory.")
if (NOT DEFINED <API key>)
set (<API key> ${<API key>} CACHE PATH "${_helpStr}")
elseif (NOT EXISTS "${<API key>}")
set (<API key> ${<API key>} CACHE PATH "${_helpStr}")
else()
# preserve pre-defined value, but set correct type and help string
set_property(CACHE <API key> PROPERTY TYPE PATH)
set_property(CACHE <API key> PROPERTY HELPSTRING "${_helpStr}")
endif()
find_program (<API key>
NAMES ${_KernelExecutables}
HINTS ${<API key>}
DOC "Mathematica kernel executable."
NO_DEFAULT_PATH <API key>
)
find_program (<API key>
NAMES ${<API key>}
HINTS ${<API key>}
DOC "Mathematica front end executable."
NO_DEFAULT_PATH <API key>
)
find_path (<API key>
NAMES "mdefs.h"
HINTS
"${<API key>}/SystemFiles/IncludeFiles"
"${<API key>}/Contents/SystemFiles/IncludeFiles"
"${<API key>}/Contents/Resources/Wolfram Player.app/Contents/SystemFiles/IncludeFiles"
PATH_SUFFIXES "C"
DOC "Mathematica C language definitions include directory."
NO_DEFAULT_PATH <API key>
)
if (<API key>)
set (<API key> ${<API key>})
else()
set (<API key> "")
endif()
set (<API key> "")
set (<API key> "")
set (<API key> "")
set (<API key> "")
endmacro(_find_mathematica)
# internal macro to init _LIBRARIES variable from given _LIBRARY variable
macro (<API key> _library_var _libraries_var)
if (APPLE)
# handle universal builds under Mac OS X
# we need to add a library for each architecture
_get_system_IDs(_SystemIDs)
foreach (_systemID IN LISTS _SystemIDs)
if ("${${_library_var}}" MATCHES "/${_systemID}/")
set (_primarySystemID "${_systemID}")
endif()
endforeach()
if (_primarySystemID)
set (${_libraries_var} "")
foreach (_systemID IN LISTS _SystemIDs)
string (REPLACE "/${_primarySystemID}/" "/${_systemID}/" _library
"${${_library_var}}")
if (EXISTS "${_library}")
list (APPEND ${_libraries_var} "${_library}")
endif()
endforeach()
else()
set (${_libraries_var} ${${_library_var}})
endif()
else()
set (${_libraries_var} ${${_library_var}})
endif()
endmacro()
# internal macro to find Wolfram Library inside Mathematica installation
macro (<API key>)
if (NOT DEFINED <API key>)
_find_mathematica()
endif()
_get_system_IDs(_SystemIDs)
<API key>(<API key>)
if (Mathematica_DEBUG)
message (STATUS "WolframLibrary SystemID ${_SystemIDs}")
message (STATUS "<API key> ${<API key>}")
endif()
set (<API key> "${<API key>}")
set (<API key> "${<API key>}")
if (CYGWIN)
# Wolfram RTL library names do not follow UNIX conventions under Cygwin
set (<API key> "")
set (<API key> ".lib")
endif()
find_library (<API key>
NAMES ${<API key>}
HINTS
"${<API key>}/SystemFiles/Libraries"
"${<API key>}/Contents/SystemFiles/Libraries"
"${<API key>}/Contents/Resources/Wolfram Player.app/Contents/SystemFiles/Libraries"
PATH_SUFFIXES ${_SystemIDs}
DOC "Mathematica Wolfram Runtime Library."
NO_DEFAULT_PATH <API key>
)
find_path (<API key>
NAMES "WolframLibrary.h" "WolframRTL.h"
HINTS
"${<API key>}/SystemFiles/IncludeFiles"
"${<API key>}/Contents/SystemFiles/IncludeFiles"
"${<API key>}/Contents/Resources/Wolfram Player.app/Contents/SystemFiles/IncludeFiles"
PATH_SUFFIXES "C"
DOC "Mathematica WolframLibrary include directory."
NO_DEFAULT_PATH <API key>
)
if (<API key>)
list (APPEND <API key> ${<API key>})
endif()
set (<API key> "${<API key>}")
set (<API key> "${<API key>}")
endmacro()
# internal macro to find MathLink SDK inside Mathematica installation
macro (_find_mathlink)
<API key>(_SystemIDs)
<API key>(_HostSystemIDs)
_get_target_flavor(_MathLinkFlavor)
_get_host_flavor(_HostMathLinkFlavor)
<API key>(<API key>)
if (NOT DEFINED <API key> OR
NOT DEFINED <API key>)
_find_mathematica()
endif()
if (Mathematica_DEBUG)
message (STATUS "MathLink Target DeveloperKit SystemID ${_SystemIDs} ${_MathLinkFlavor}")
message (STATUS "MathLink Host DeveloperKit SystemID ${_HostSystemIDs} ${_HostMathLinkFlavor}")
message (STATUS "MathLink Library Names ${<API key>}")
endif()
find_path (<API key>
NAMES "CompilerAdditions"
HINTS
"${<API key>}/SystemFiles/Links/MathLink/DeveloperKit"
"${<API key>}/Contents/SystemFiles/Links/MathLink/DeveloperKit"
"${<API key>}/Contents/Resources/Wolfram Player.app/Contents/SystemFiles/Links/MathLink/DeveloperKit"
"${<API key>}/AddOns/MathLink/DeveloperKit"
PATH_SUFFIXES ${_SystemIDs}
DOC "MathLink target SDK root directory."
NO_DEFAULT_PATH <API key>
)
if (_MathLinkFlavor)
set (_CompilerAdditions
"${<API key>}/CompilerAdditions/${_MathLinkFlavor}"
"${<API key>}/CompilerAdditions")
else()
set (_CompilerAdditions "${<API key>}/CompilerAdditions")
endif()
find_path (<API key>
NAMES "CompilerAdditions"
HINTS
"${<API key>}/SystemFiles/Links/MathLink/DeveloperKit"
"${<API key>}/Contents/SystemFiles/Links/MathLink/DeveloperKit"
"${<API key>}/Contents/Resources/Wolfram Player.app/Contents/SystemFiles/Links/MathLink/DeveloperKit"
"${<API key>}/AddOns/MathLink/DeveloperKit"
PATH_SUFFIXES ${_HostSystemIDs}
DOC "MathLink host SDK root directory."
NO_DEFAULT_PATH <API key>
)
if (_HostMathLinkFlavor)
set (<API key>
"${<API key>}/CompilerAdditions/${_HostMathLinkFlavor}"
"${<API key>}/CompilerAdditions")
else()
set (<API key> "${<API key>}/CompilerAdditions")
endif()
if (Mathematica_DEBUG)
message (STATUS "MathLink CompilerAdditions ${_CompilerAdditions}")
message (STATUS "MathLink <API key> ${<API key>}")
endif()
if (APPLE)
set (_findFrameWorkSave "${<API key>}")
if (<API key>)
set (<API key> "LAST")
else()
set (<API key> "FIRST")
endif()
endif()
find_program (<API key>
NAMES "mprep"
HINTS ${<API key>}
PATH_SUFFIXES "bin"
DOC "MathLink template file preprocessor executable."
NO_DEFAULT_PATH <API key>
)
find_library (<API key>
NAMES ${<API key>}
HINTS ${_CompilerAdditions}
PATH_SUFFIXES "lib"
DOC "MathLink library to link against."
NO_DEFAULT_PATH <API key>
)
find_path (<API key>
NAMES "mathlink.h"
HINTS ${_CompilerAdditions}
PATH_SUFFIXES "include"
DOC "Path to the MathLink include directory."
NO_DEFAULT_PATH <API key>
)
if (APPLE AND DEFINED <API key> AND IS_DIRECTORY "${<API key>}")
if (DEFINED <API key>)
set (<API key> "${<API key>}/Versions/${<API key>}.${<API key>}")
else()
set (<API key> "${<API key>}/Versions/${<API key>}.[0-9]+")
endif()
file (GLOB _versionedLibrary "${<API key>}/mathlink")
if (_versionedLibrary)
# use last if there are multiple
list (GET _versionedLibrary -1 _versionedLibrary)
set (<API key> "${_versionedLibrary}" CACHE FILEPATH "MathLink library to link against." FORCE)
endif()
file (GLOB _versionedHeaderDir "${<API key>}/Headers")
if (_versionedHeaderDir)
set (<API key> "${_versionedHeaderDir}" CACHE FILEPATH "Path to the MathLink include directory." FORCE)
endif()
endif()
find_path (<API key>
NAMES "mathlink.h"
HINTS ${<API key>}
PATH_SUFFIXES "include"
DOC "Path to the MathLink host include directory."
NO_DEFAULT_PATH <API key>
)
if (APPLE)
set (<API key> "${_findFrameWorkSave}")
endif()
if (<API key>)
list (APPEND <API key> ${<API key>})
endif()
endmacro(_find_mathlink)
# internal macro to find WSTP SDK inside Mathematica installation
macro (_find_WSTP)
<API key>(_SystemIDs)
<API key>(_HostSystemIDs)
_get_target_flavor(_WSTPFlavor)
_get_host_flavor(_HostWSTPFlavor)
<API key>(_WSTPLibraryNames)
if (NOT DEFINED <API key> OR
NOT DEFINED <API key>)
_find_mathematica()
endif()
if (Mathematica_DEBUG)
message (STATUS "WSTP Target DeveloperKit SystemID ${_SystemIDs} ${_WSTPFlavor}")
message (STATUS "WSTP Host DeveloperKit SystemID ${_HostSystemIDs} ${_HostWSTPFlavor}")
message (STATUS "WSTP Library Names ${_WSTPLibraryNames}")
endif()
find_path (<API key>
NAMES "CompilerAdditions"
HINTS
"${<API key>}/SystemFiles/Links/WSTP/DeveloperKit"
"${<API key>}/Contents/SystemFiles/Links/WSTP/DeveloperKit"
"${<API key>}/Contents/Resources/Wolfram Player.app/Contents/SystemFiles/Links/WSTP/DeveloperKit"
PATH_SUFFIXES ${_SystemIDs}
DOC "WSTP target SDK root directory."
NO_DEFAULT_PATH <API key>
)
if (_WSTPFlavor)
set (_CompilerAdditions
"${<API key>}/CompilerAdditions/${_WSTPFlavor}"
"${<API key>}/CompilerAdditions")
else()
set (_CompilerAdditions "${<API key>}/CompilerAdditions")
endif()
find_path (<API key>
NAMES "CompilerAdditions"
HINTS
"${<API key>}/SystemFiles/Links/WSTP/DeveloperKit"
"${<API key>}/Contents/SystemFiles/Links/WSTP/DeveloperKit"
"${<API key>}/Contents/Resources/Wolfram Player.app/Contents/SystemFiles/Links/WSTP/DeveloperKit"
PATH_SUFFIXES ${_HostSystemIDs}
DOC "WSTP host SDK root directory."
NO_DEFAULT_PATH <API key>
)
if (_HostWSTPFlavor)
set (<API key>
"${<API key>}/CompilerAdditions/${_HostWSTPFlavor}"
"${<API key>}/CompilerAdditions")
else()
set (<API key> "${<API key>}/CompilerAdditions")
endif()
if (Mathematica_DEBUG)
message (STATUS "WSTP CompilerAdditions ${_CompilerAdditions}")
message (STATUS "WSTP <API key> ${<API key>}")
endif()
if (APPLE)
set (_findFrameWorkSave "${<API key>}")
if (<API key>)
set (<API key> "LAST")
else()
set (<API key> "FIRST")
endif()
endif()
find_program (<API key>
NAMES "wsprep"
HINTS ${<API key>}
PATH_SUFFIXES "bin"
DOC "WSTP template file preprocessor executable."
NO_DEFAULT_PATH <API key>
)
find_library (<API key>
NAMES ${_WSTPLibraryNames}
HINTS ${_CompilerAdditions}
PATH_SUFFIXES "lib"
DOC "WSTP library to link against."
NO_DEFAULT_PATH <API key>
)
find_path (<API key>
NAMES "wstp.h"
HINTS ${_CompilerAdditions}
PATH_SUFFIXES "include"
DOC "Path to the WSTP include directory."
NO_DEFAULT_PATH <API key>
)
if (APPLE AND DEFINED <API key> AND IS_DIRECTORY "${<API key>}")
if (DEFINED <API key>)
set (<API key> "${<API key>}/Versions/${<API key>}.${<API key>}")
else()
set (<API key> "${<API key>}/Versions/${<API key>}.[0-9]+")
endif()
file (GLOB _versionedLibrary "${<API key>}/wstp")
if (_versionedLibrary)
# use last if there are multiple
list (GET _versionedLibrary -1 _versionedLibrary)
set (<API key> "${_versionedLibrary}" CACHE FILEPATH "WSTP library to link against." FORCE)
endif()
file (GLOB _versionedHeaderDir "${<API key>}/Headers")
if (_versionedHeaderDir)
set (<API key> "${_versionedHeaderDir}" CACHE FILEPATH "Path to the WSTP include directory." FORCE)
endif()
endif()
find_path (<API key>
NAMES "wstp.h"
HINTS ${<API key>}
PATH_SUFFIXES "include"
DOC "Path to the WSTP host include directory."
NO_DEFAULT_PATH <API key>
)
if (APPLE)
set (<API key> "${_findFrameWorkSave}")
endif()
if (<API key>)
list (APPEND <API key> ${<API key>})
endif()
endmacro(_find_WSTP)
# internal macro to find J/Link SDK inside Mathematica installation
macro (_find_jlink)
if (NOT DEFINED <API key>)
_find_mathematica()
endif()
_get_system_IDs(_SystemIDs)
<API key>(_HostSystemIDs)
<API key>(_JLinkJavaNames)
if (Mathematica_DEBUG)
message (STATUS "J/Link Target SystemID ${_SystemIDs}")
message (STATUS "J/Link Host SystemID ${_HostSystemIDs}")
message (STATUS "JLinkJavaName ${_JLinkJavaNames}")
endif()
find_path (<API key>
NAMES "JLink.jar"
HINTS
"${<API key>}/SystemFiles/Links/JLink"
"${<API key>}/Contents/SystemFiles/Links/JLink"
"${<API key>}/Contents/Resources/Wolfram Player.app/Contents/SystemFiles/Links/JLink"
"${<API key>}/AddOns/JLink"
DOC "J/Link SDK root directory."
NO_DEFAULT_PATH <API key>
)
if (EXISTS "${<API key>}")
set (<API key> "${<API key>}/JLink.jar")
else()
set (<API key> "<API key>")
endif()
set (<API key> "${<API key>}")
set (<API key> "${<API key>}")
if (APPLE)
set (<API key> "lib")
set (<API key> ".jnilib")
elseif (WIN32)
set (<API key> "")
set (<API key> ".dll")
endif()
find_library (<API key>
NAMES "JLinkNativeLibrary"
HINTS "${<API key>}/SystemFiles/Libraries"
PATHS ENV JLINK_LIB_DIR
PATH_SUFFIXES ${_SystemIDs}
DOC "J/Link native library."
NO_DEFAULT_PATH <API key>
)
set (<API key> "${<API key>}")
set (<API key> "${<API key>}")
if (CMAKE_HOST_APPLE)
if (EXISTS "${<API key>}/Contents/SystemFiles/Java")
set (_mmaJavaHome "${<API key>}/Contents/SystemFiles/Java")
elseif (EXISTS "${<API key>}/Contents/Resources/Wolfram Player.app/Contents/SystemFiles/Java")
set (_mmaJavaHome "${<API key>}/Contents/Resources/Wolfram Player.app/Contents/SystemFiles/Java")
else()
# OS X versions of Mathematica earlier than 10 did not have a JVM bundled
# but used the Java JVM pre-installed on system
set (_mmaJavaHome "${<API key>}/SystemFiles/Java")
if (DEFINED Mathematica_VERSION)
if ("${Mathematica_VERSION}" VERSION_LESS "10.0")
# use java_home to find path to JVM installed on system
find_program(<API key> "java_home" PATHS "/usr/libexec/")
mark_as_advanced(<API key>)
if (<API key>)
execute_process(
COMMAND "${<API key>}" "--version" "1.6"
TIMEOUT 10 OUTPUT_VARIABLE _mmaJavaHome ERROR_QUIET <API key>)
endif()
endif()
endif()
endif()
else()
set (_mmaJavaHome "${<API key>}/SystemFiles/Java")
endif()
find_program (<API key>
NAMES "bin/${_JLinkJavaNames}"
HINTS "${_mmaJavaHome}"
PATH_SUFFIXES ${_HostSystemIDs}
DOC "J/Link Java launcher."
NO_DEFAULT_PATH <API key>
)
find_path (<API key>
NAMES "bin/${_JLinkJavaNames}"
HINTS "${_mmaJavaHome}"
PATH_SUFFIXES ${_HostSystemIDs}
DOC "J/Link Java home directory."
NO_DEFAULT_PATH <API key>
)
endmacro()
# internal macro to find MUnit package
macro (_find_munit_package)
if (<API key> AND COMMAND <API key>)
<API key>(<API key> "MUnit`MUnit`")
# determine enclosing MUnit package directory
if (<API key>)
<API key>(<API key> "${<API key>}")
endif()
endif()
if (NOT DEFINED <API key>)
set (<API key> "<API key>")
endif()
endmacro()
# internal macro to find LibaryLink package
macro (<API key>)
if (<API key> AND COMMAND <API key>)
<API key>(<API key> "LibraryLink`LibraryLink`")
# determine enclosing LibraryLink package directory
if (<API key>)
<API key>(<API key> "${<API key>}")
endif()
endif()
if (NOT DEFINED <API key>)
set (<API key> "<API key>")
endif()
endmacro()
# internal helper macro to setup version related variables from existing _VERSION variable
macro (<API key> _packageName)
if (DEFINED ${_packageName}_VERSION)
string (REGEX MATCHALL "[0-9]+" _versionComponents "${${_packageName}_VERSION}")
list (LENGTH _versionComponents _len)
if (_len GREATER 0)
list(GET _versionComponents 0 ${_packageName}_VERSION_MAJOR)
endif()
if (_len GREATER 1)
list(GET _versionComponents 1 ${_packageName}_VERSION_MINOR)
endif()
if (_len GREATER 2)
list(GET _versionComponents 2 ${_packageName}_VERSION_PATCH)
endif()
if (_len GREATER 3)
list(GET _versionComponents 3 ${_packageName}_VERSION_TWEAK)
endif()
set (${_packageName}_VERSION_COUNT ${_len})
if (NOT DEFINED ${_packageName}_VERSION_STRING)
set (${_packageName}_VERSION_STRING ${${_packageName}_VERSION})
endif()
endif()
endmacro()
# internal macro to setup Mathematica version related variables
macro (<API key>)
if (NOT Mathematica_VERSION)
set (_versionLine "")
if (DEFINED <API key>)
if (<API key> AND EXISTS "${<API key>}/.VersionID")
# parse version number from hidden VersionID and PatchLevel files
file (STRINGS "${<API key>}/.VersionID" _versionLine)
if (EXISTS "${<API key>}/.PatchLevel")
file (STRINGS "${<API key>}/.PatchLevel" _patchLevel)
if (_versionLine MATCHES ".+" AND _patchLevel MATCHES ".+")
set (_versionLine "${_versionLine}.${_patchLevel}")
endif()
endif()
elseif (CMAKE_HOST_APPLE AND <API key> AND
EXISTS "${<API key>}/Contents/Info.plist")
execute_process(
COMMAND "grep" "--after-context=1" "<API key>"
"${<API key>}/Contents/Info.plist"
TIMEOUT 10 OUTPUT_VARIABLE _versionStr ERROR_QUIET)
if (_versionStr MATCHES "<string>([0-9]+\\.[0-9]+\\.[0-9]+)")
set (_versionLine "${CMAKE_MATCH_1}")
else()
set (_versionLine "")
endif()
endif()
endif()
if (NOT _versionLine AND DEFINED <API key>)
if (<API key> AND
EXISTS "${<API key>}/mathlink.h")
# parse version number from mathlink.h
file (STRINGS "${<API key>}/mathlink.h" _versionLine
REGEX ".*define.*MLMATHVERSION.*")
endif()
endif()
if (NOT _versionLine AND DEFINED <API key>)
if (<API key> AND
EXISTS "${<API key>}/mathlink.h")
# parse version number from mathlink.h
file (STRINGS "${<API key>}/mathlink.h" _versionLine
REGEX ".*define.*MLMATHVERSION.*")
endif()
endif()
if (_versionLine MATCHES ".+")
string (REGEX REPLACE "[^0-9]*([0-9]+(\\.[0-9]+)*).*" "\\1" _versionStr "${_versionLine}")
if (DEFINED _versionStr)
set (Mathematica_VERSION "${_versionStr}"
CACHE INTERNAL "Mathematica version." FORCE)
endif()
endif()
endif()
<API key>(Mathematica)
endmacro()
# internal macro to setup WolframLibrary version related variables
macro (<API key>)
if (NOT <API key> AND <API key>)
set (_file "${<API key>}/WolframLibrary.h")
if (EXISTS "${_file}")
file (STRINGS "${_file}" _versionLine REGEX ".*define.*<API key>.*")
if (_versionLine)
string (REGEX REPLACE "[^0-9]*([0-9]+(\\.[0-9]+)*).*" "\\1" _versionStr "${_versionLine}")
if (DEFINED _versionStr)
set (<API key> "${_versionStr}"
CACHE INTERNAL "WolframLibrary version." FORCE)
endif()
endif()
endif()
endif()
<API key>(<API key>)
endmacro()
# internal macro to setup MathLink version related variables
macro (<API key>)
if (NOT <API key> AND <API key>)
set (_file "${<API key>}/mathlink.h")
if (EXISTS "${_file}")
if (DEFINED <API key>)
set (_mlInterface "${<API key>}")
else()
file (STRINGS "${_file}" _mlInterfaceLine REGEX ".*define.*MLINTERFACE.*")
string (REGEX REPLACE "[^0-9]*([0-9]+).*" "\\1" _mlInterface
${_mlInterfaceLine})
endif()
file (STRINGS "${_file}" _mlRevisionLine REGEX ".*define.*MLREVISION.*")
string (REGEX REPLACE "[^0-9]*([0-9]+).*" "\\1" _mlRevision
${_mlRevisionLine})
if (DEFINED _mlInterface AND DEFINED _mlRevision)
set (_versionStr "${_mlInterface}.${_mlRevision}")
set (<API key> "${_versionStr}"
CACHE INTERNAL "MathLink version." FORCE)
endif()
endif()
endif()
<API key>(<API key>)
endmacro()
# internal macro to setup WSTP version related variables
macro (<API key>)
if (NOT <API key> AND <API key>)
set (_file "${<API key>}/wstp.h")
if (EXISTS "${_file}")
if (DEFINED <API key>)
set (_wstpInterface "${<API key>}")
else()
file (STRINGS "${_file}" _wstpInterfaceLine REGEX ".*define.*(WS|ML)INTERFACE.*")
if (_wstpInterfaceLine)
string (REGEX REPLACE "[^0-9]*([0-9]+).*" "\\1" _wstpInterface
${_wstpInterfaceLine})
endif()
endif()
file (STRINGS "${_file}" _wstpRevisionLine REGEX ".*define.*(WS|ML)REVISION.*")
string (REGEX REPLACE "[^0-9]*([0-9]+).*" "\\1" _wstpRevision
${_wstpRevisionLine})
if (DEFINED _wstpInterface AND DEFINED _wstpRevision)
set (_versionStr "${_wstpInterface}.${_wstpRevision}")
set (<API key> "${_versionStr}"
CACHE INTERNAL "WSTP version." FORCE)
endif()
endif()
endif()
<API key>(Mathematica_WSTP)
endmacro()
# internal macro to setup J/Link version related variables
macro (<API key>)
if (NOT <API key> AND <API key>)
set (_file "${<API key>}/Source/Java/com/wolfram/jlink/KernelLink.java")
if (EXISTS "${_file}")
file (STRINGS "${_file}" _versionLine REGEX ".*String.*VERSION.*")
string (REGEX REPLACE "[^0-9]*([0-9]+(\\.[0-9]+)*).*" "\\1" _versionStr "${_versionLine}")
if (DEFINED _versionStr)
set (<API key> "${_versionStr}"
CACHE INTERNAL "J/Link version." FORCE)
endif()
endif()
endif()
<API key>(Mathematica_JLink)
endmacro()
# internal macro to setup MUnit version related variables
macro (<API key>)
if (NOT <API key> AND <API key>)
set (_file "${<API key>}")
if (EXISTS "${_file}")
file (STRINGS "${_file}" <API key> REGEX ".*`\\$VersionNumber.*")
file (STRINGS "${_file}" <API key> REGEX ".*`\\$ReleaseNumber.*")
file (STRINGS "${_file}" _mUnitVersionLine REGEX ".*`\\$Version.*")
string (REGEX REPLACE "[^0-9]*([0-9]+\\.[0-9]+).*" "\\1" _mUnitVersionNumber
${<API key>})
string (REGEX REPLACE "[^0-9]*([0-9]+).*" "\\1" _mUnitReleaseNumber
${<API key>})
if (DEFINED _mUnitVersionNumber AND DEFINED _mUnitReleaseNumber)
set (_versionStr "${_mUnitVersionNumber}.${_mUnitReleaseNumber}")
set (<API key> "${_versionStr}"
CACHE INTERNAL "MUnit version." FORCE)
endif()
endif()
endif()
<API key>(Mathematica_MUnit)
endmacro()
# internal macro to setup WolframLibrary library related variables
macro (<API key>)
if (<API key>)
set (<API key> "")
set (<API key> "")
<API key>(<API key> <API key>)
foreach (_library ${<API key>})
<API key> (_libraryDir ${_library} DIRECTORY)
list (APPEND <API key> ${_libraryDir})
if (NOT <API key>)
list (APPEND <API key> ${_libraryDir})
list (APPEND <API key> ${_libraryDir})
list (APPEND <API key> ${_libraryDir})
list (APPEND <API key> ${_libraryDir})
endif()
endforeach()
if (NOT APPLE)
# kernel binaries dir on Windows and Linux contains additional runtime libraries (e.g., Intel MKL)
foreach (_systemID ${<API key>})
set (_kernelBinariesDir "${<API key>}/SystemFiles/Kernel/Binaries/${_systemID}")
if (EXISTS "${_kernelBinariesDir}")
list (APPEND <API key> ${_kernelBinariesDir})
if (NOT <API key>)
list (APPEND <API key> "${_kernelBinariesDir}")
list (APPEND <API key> "${_kernelBinariesDir}")
list (APPEND <API key> "${_kernelBinariesDir}")
list (APPEND <API key> "${_kernelBinariesDir}")
endif()
endif()
endforeach()
endif()
<API key>(<API key>)
list (REMOVE_DUPLICATES <API key>)
list (REMOVE_DUPLICATES <API key>)
list (APPEND <API key> ${<API key>})
endif()
endmacro()
# internal macro to setup MathLink library related variables
macro (<API key>)
if (<API key>)
<API key>(<API key> <API key>)
if (DEFINED <API key>)
set (<API key> "-DMLINTERFACE=${<API key>}")
elseif (DEFINED <API key>)
set (<API key> "-DMLINTERFACE=${<API key>}")
else()
set (<API key> "")
endif()
set (<API key> "")
set (<API key> "")
if (APPLE)
set (<API key> "")
foreach (_library ${<API key>})
<API key> (_libraryDir ${_library} DIRECTORY)
list (APPEND <API key> ${_libraryDir})
endforeach()
# for OS X we have to add the MathLink CompilerAdditions directory which contains the MathLink framework
_get_target_flavor(_MathLinkFlavor)
if (_MathLinkFlavor)
set (_CompilerAdditions "${<API key>}/CompilerAdditions/${_MathLinkFlavor}")
else()
set (_CompilerAdditions "${<API key>}/CompilerAdditions")
endif()
if (IS_DIRECTORY "${_CompilerAdditions}")
list (APPEND <API key> "${_CompilerAdditions}")
list (APPEND <API key> "${_CompilerAdditions}")
list (APPEND <API key> "${_CompilerAdditions}")
list (APPEND <API key> "${_CompilerAdditions}")
endif()
elseif (UNIX)
set (<API key> "")
foreach (_library ${<API key>})
<API key> (_libraryDir ${_library} DIRECTORY)
list (APPEND <API key> ${_libraryDir})
if (NOT <API key>)
list (APPEND <API key> ${_libraryDir})
list (APPEND <API key> ${_libraryDir})
list (APPEND <API key> ${_libraryDir})
list (APPEND <API key> ${_libraryDir})
endif()
endforeach()
elseif (WIN32)
set (<API key> "")
foreach (_library ${<API key>})
<API key> (_libraryDir ${_library} DIRECTORY)
list (APPEND <API key> ${_libraryDir})
endforeach()
# Windows MathLink SDK has runtime DLLs in a separate directory
set (_runtimeDir "${<API key>}/SystemAdditions")
if (IS_DIRECTORY "${_runtimeDir}")
list (APPEND <API key> "${_runtimeDir}")
list (APPEND <API key> "${_runtimeDir}")
endif()
# Windows MathLink SDK also ships with debug DLLs in <API key>
set (_runtimeDir "${<API key>}/<API key>/DebugLibraries")
if (IS_DIRECTORY "${_runtimeDir}")
list (APPEND <API key> "${_runtimeDir}")
list (APPEND <API key> "${_runtimeDir}")
endif()
endif()
<API key>(<API key>)
list (REMOVE_DUPLICATES <API key>)
list (REMOVE_DUPLICATES <API key>)
list (APPEND <API key> ${<API key>})
endif()
endmacro()
# internal macro to setup WSTP library related variables
macro (<API key>)
if (<API key>)
<API key>(<API key> <API key>)
if (DEFINED <API key>)
set (<API key> "-DWSINTERFACE=${<API key>}")
elseif (DEFINED <API key>)
set (<API key> "-DWSINTERFACE=${<API key>}")
else()
set (<API key> "")
endif()
set (<API key> "")
set (<API key> "")
if (APPLE)
set (<API key> "")
foreach (_library ${<API key>})
<API key> (_libraryDir ${_library} DIRECTORY)
list (APPEND <API key> ${_libraryDir})
endforeach()
# for OS X we have to add the WSTP CompilerAdditions directory which contains the WSTP framework
_get_target_flavor(_WSTPFlavor)
if (_WSTPFlavor)
set (_CompilerAdditions "${<API key>}/CompilerAdditions/${_WSTPFlavor}")
else()
set (_CompilerAdditions "${<API key>}/CompilerAdditions")
endif()
if (IS_DIRECTORY "${_CompilerAdditions}")
list (APPEND <API key> ${_libraryDir})
list (APPEND <API key> ${_libraryDir})
list (APPEND <API key> "${_CompilerAdditions}")
list (APPEND <API key> "${_CompilerAdditions}")
endif()
elseif (UNIX)
set (<API key> "")
foreach (_library ${<API key>})
<API key> (_libraryDir ${_library} DIRECTORY)
list (APPEND <API key> ${_libraryDir})
if (NOT <API key>)
list (APPEND <API key> ${_libraryDir})
list (APPEND <API key> ${_libraryDir})
list (APPEND <API key> ${_libraryDir})
list (APPEND <API key> ${_libraryDir})
endif()
endforeach()
elseif (WIN32)
set (<API key> "")
foreach (_library ${<API key>})
<API key> (_libraryDir ${_library} DIRECTORY)
list (APPEND <API key> ${_libraryDir})
endforeach()
# Windows WSTP SDK has runtime DLLs in a separate directory
set (_runtimeDir "${<API key>}/SystemAdditions")
if (IS_DIRECTORY "${_runtimeDir}")
list (APPEND <API key> "${_runtimeDir}")
list (APPEND <API key> "${_runtimeDir}")
endif()
# Windows WSTP SDK also ships with debug DLLs in <API key>
set (_runtimeDir "${<API key>}/<API key>/DebugLibraries")
if (IS_DIRECTORY "${_runtimeDir}")
list (APPEND <API key> "${_runtimeDir}")
list (APPEND <API key> "${_runtimeDir}")
endif()
endif()
<API key>(<API key>)
list (REMOVE_DUPLICATES <API key>)
list (REMOVE_DUPLICATES <API key>)
list (APPEND <API key> ${<API key>})
endif()
endmacro()
# internal macro to log used variables
macro (_log_used_variables)
if (Mathematica_DEBUG)
message (STATUS "Executing on ${CMAKE_HOST_SYSTEM}, ${<API key>}, ${<API key>}, ${<API key>}")
message (STATUS "Compiling for ${CMAKE_SYSTEM}, ${CMAKE_SYSTEM_NAME}, ${<API key>}, ${<API key>}")
message (STATUS "Configuration: ${CMAKE_BUILD_TYPE}, ${<API key>}")
message (STATUS "Configuration directory: ${CMAKE_CFG_INTDIR}")
message (STATUS "Project source dir: ${PROJECT_SOURCE_DIR}")
message (STATUS "Project binary dir: ${PROJECT_BINARY_DIR}")
message (STATUS "Cross compiling: ${<API key>}")
message (STATUS "Library prefixes: ${<API key>}")
message (STATUS "Library suffixes: ${<API key>}")
message (STATUS "Current file: ${<API key>}:${<API key>}")
message (STATUS "Parent file: ${<API key>}")
message (STATUS "Find version: ${<API key>}")
message (STATUS "Find exact: ${<API key>}")
message (STATUS "Find quietly: ${<API key>}")
message (STATUS "Find required: ${<API key>}")
message (STATUS "Find components: ${<API key>}")
message (STATUS "Find required MathLink: ${<API key>}")
message (STATUS "Find MathLink interface version: ${<API key>}")
message (STATUS "Find MathLink revision number: ${<API key>}")
message (STATUS "Find required WSTP: ${<API key>}")
message (STATUS "Find WSTP interface version: ${<API key>}")
message (STATUS "Find WSTP revision number: ${<API key>}")
message (STATUS "Find required WolframLibrary: ${<API key>}")
message (STATUS "Find required J/Link: ${<API key>}")
message (STATUS "Find required MUnit: ${<API key>}")
message (STATUS "Use static libraries: ${<API key>}")
message (STATUS "Use minimal libraries: ${<API key>}")
endif()
endmacro()
# internal macro to log found variables
macro (<API key>)
if (Mathematica_DEBUG)
message (STATUS "Mathematica CMake module dir ${<API key>}")
if (Mathematica_FOUND)
message (STATUS "Mathematica ${Mathematica_VERSION} found")
message (STATUS "Mathematica creation ID ${<API key>}")
message (STATUS "Mathematica target root dir ${<API key>}")
message (STATUS "Mathematica host root dir ${<API key>}")
message (STATUS "Mathematica host MathLink include dir ${<API key>}")
message (STATUS "Mathematica host WSTP include dir ${<API key>}")
message (STATUS "Mathematica kernel executable ${<API key>}")
message (STATUS "Mathematica frontend executable ${<API key>}")
message (STATUS "Mathematica target system ID ${<API key>}")
message (STATUS "Mathematica target system IDs ${<API key>}")
message (STATUS "Mathematica host system ID ${<API key>}")
message (STATUS "Mathematica host system IDs ${<API key>}")
message (STATUS "Mathematica base directory ${<API key>}")
message (STATUS "Mathematica user base directory ${<API key>}")
message (STATUS "Mathematica include dir ${<API key>}")
message (STATUS "Mathematica include dirs ${<API key>}")
message (STATUS "Mathematica libraries ${<API key>}")
message (STATUS "Mathematica library dirs ${<API key>}")
message (STATUS "Mathematica runtime library dirs ${<API key>}")
message (STATUS "Mathematica runtime debug library dirs ${<API key>}")
else()
message (STATUS "Mathematica not found")
endif()
if (<API key>)
message (STATUS "WolframLibrary ${<API key>} found")
message (STATUS "WolframLibrary include dir ${<API key>}")
message (STATUS "WolframLibrary library ${<API key>}")
message (STATUS "WolframLibrary libraries ${<API key>}")
message (STATUS "WolframLibrary runtime library dirs ${<API key>}")
message (STATUS "WolframLibrary runtime debug library dirs ${<API key>}")
message (STATUS "LibraryLink package dir ${<API key>}")
else()
message (STATUS "WolframLibrary not found")
endif()
if (<API key>)
message (STATUS "MathLink ${<API key>} found")
message (STATUS "MathLink target root dir ${<API key>}")
message (STATUS "MathLink host root dir ${<API key>}")
message (STATUS "MathLink include dir ${<API key>}")
message (STATUS "MathLink library ${<API key>}")
message (STATUS "MathLink libraries ${<API key>}")
message (STATUS "MathLink mprep executable ${<API key>}")
message (STATUS "MathLink definitions ${<API key>}")
message (STATUS "MathLink linker flags ${<API key>}")
message (STATUS "MathLink runtime library dirs ${<API key>}")
message (STATUS "MathLink runtime debug library dirs ${<API key>}")
else()
message (STATUS "MathLink not found")
endif()
if (<API key>)
message (STATUS "WSTP ${<API key>} found")
message (STATUS "WSTP target root dir ${<API key>}")
message (STATUS "WSTP host root dir ${<API key>}")
message (STATUS "WSTP include dir ${<API key>}")
message (STATUS "WSTP library ${<API key>}")
message (STATUS "WSTP libraries ${<API key>}")
message (STATUS "WSTP wsprep executable ${<API key>}")
message (STATUS "WSTP definitions ${<API key>}")
message (STATUS "WSTP linker flags ${<API key>}")
message (STATUS "WSTP runtime library dirs ${<API key>}")
message (STATUS "WSTP runtime debug library dirs ${<API key>}")
else()
message (STATUS "WSTP not found")
endif()
if (<API key>)
message (STATUS "J/Link ${<API key>} found")
message (STATUS "J/Link package dir ${<API key>}")
message (STATUS "J/Link JAR file ${<API key>}")
message (STATUS "J/Link native library ${<API key>}")
message (STATUS "J/Link java launcher ${<API key>}")
message (STATUS "J/Link java home directory ${<API key>}")
else()
message (STATUS "J/Link not found")
endif()
if (<API key>)
message (STATUS "MUnit ${<API key>} found")
message (STATUS "MUnit package dir ${<API key>}")
else()
message (STATUS "MUnit not found")
endif()
endif()
if (DEFINED <API key> AND
DEFINED <API key> AND
DEFINED <API key>)
if (APPLE AND "${<API key>}" EQUAL 5 AND "${<API key>}" EQUAL 2)
foreach (_systemID ${<API key>})
if ("${_systemID}" STREQUAL "MacOSX-x86-64")
message (WARNING "Mathematica 5.2 for Mac OS X does not support x86_64, run cmake with option -<API key>=i386.")
endif()
endforeach()
endif()
endif()
if (CYGWIN AND <API key> AND <API key>)
if ("${<API key>}" VERSION_LESS "3.0.0" OR NOT "${<API key>}" VERSION_LESS "4.0.0")
message (WARNING
"LibraryLink DLL generation requires the -mno-cygwin compiler flag, which is not supported by gcc ${<API key>}."
" Run cmake with options -DCMAKE_CXX_COMPILER=/usr/bin/g++-3.exe -DCMAKE_C_COMPILER=/usr/bin/gcc-3.exe.")
endif()
endif()
endmacro(<API key>)
# internal macro returns cache variables that determine search result
macro (<API key> _CacheVariables)
set (${_CacheVariables}
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>)
endmacro()
# internal macro returns cache variables that are dependent on the given variable
macro (<API key> _var _outDependentVars)
# do comparisons with an underscore prefix to prevent CMake from automatically
# resolving the left and right hand arguments to STREQUAL
if ("_${_var}" STREQUAL "<API key>" OR
"_${_var}" STREQUAL "<API key>")
list (APPEND ${_outDependentVars}
<API key> <API key> Mathematica_VERSION)
<API key>("<API key>" ${_outDependentVars})
<API key>("<API key>" ${_outDependentVars})
elseif ("_${_var}" STREQUAL "<API key>" OR
"_${_var}" STREQUAL "<API key>")
list (APPEND ${_outDependentVars}
Mathematica_VERSION
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>)
<API key>("<API key>" ${_outDependentVars})
<API key>("<API key>" ${_outDependentVars})
elseif ("_${_var}" STREQUAL "<API key>")
# all cached Mathematica version variables are dependent on the cached creation ID
list (APPEND ${_outDependentVars}
Mathematica_VERSION
<API key>
<API key>
<API key>
<API key>
<API key>)
elseif ("_${_var}" STREQUAL "<API key>" OR
"_${_var}" STREQUAL "<API key>")
list (APPEND ${_outDependentVars}
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>)
<API key>("<API key>" ${_outDependentVars})
<API key>("<API key>" ${_outDependentVars})
<API key>("<API key>" ${_outDependentVars})
<API key>("<API key>" ${_outDependentVars})
elseif ("_${_var}" STREQUAL "<API key>")
list (APPEND ${_outDependentVars}
<API key>
<API key>
<API key>)
elseif ("_${_var}" STREQUAL "<API key>")
list (APPEND ${_outDependentVars}
<API key>
<API key>)
elseif ("_${_var}" STREQUAL "<API key>" OR
"_${_var}" STREQUAL "<API key>")
list (APPEND ${_outDependentVars}
<API key>
<API key>
<API key>
<API key>
<API key>)
elseif ("_${_var}" STREQUAL "<API key>")
list (APPEND ${_outDependentVars}
<API key>
<API key>
<API key>)
elseif ("_${_var}" STREQUAL "<API key>")
list (APPEND ${_outDependentVars}
<API key>
<API key>)
elseif ("_${_var}" STREQUAL "<API key>" OR
"_${_var}" STREQUAL "<API key>")
list (APPEND ${_outDependentVars}
<API key>
<API key>
<API key>
<API key>
<API key>)
elseif ("_${_var}" STREQUAL "<API key>")
list (APPEND ${_outDependentVars}
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>)
elseif ("_${_var}" STREQUAL "<API key>")
list (APPEND ${_outDependentVars}
<API key>)
elseif ("_${_var}" STREQUAL "<API key>")
list (APPEND ${_outDependentVars}
<API key>
<API key>)
elseif ("_${_var}" STREQUAL "<API key>")
list (APPEND ${_outDependentVars}
<API key> <API key>)
elseif ("_${_var}" STREQUAL "<API key>")
list (APPEND ${_outDependentVars}
<API key>)
endif()
endmacro(<API key>)
# internal macro to cleanup outdated cache variables
macro (_cleanup_cache)
<API key>(_CacheVariables)
set (_vars_to_clean "")
foreach (_CacheVariable IN LISTS _CacheVariables)
get_property(_cacheVariableType CACHE "${_CacheVariable}" PROPERTY TYPE)
if (DEFINED ${_CacheVariable} AND DEFINED ${_CacheVariable}_LAST)
if (NOT "${${_CacheVariable}}" STREQUAL "${${_CacheVariable}_LAST}")
# search var has changed
<API key>(${_CacheVariable} _vars_to_clean)
if (Mathematica_DEBUG)
message (STATUS "${_CacheVariable} changed from ${${_CacheVariable}_LAST} to ${${_CacheVariable}}")
endif()
elseif ("${_cacheVariableType}" MATCHES "PATH" AND
NOT "${${_CacheVariable}}" MATCHES "-NOTFOUND$" AND
NOT EXISTS "${${_CacheVariable}}")
# original var path no longer exists
list (APPEND _vars_to_clean "${_CacheVariable}")
<API key>(${_CacheVariable} _vars_to_clean)
if (Mathematica_DEBUG)
message (STATUS "${_CacheVariable} path ${${_CacheVariable}} no longer exists")
endif()
elseif ("${_cacheVariableType}" MATCHES "PATH" AND
EXISTS "${${_CacheVariable}}" AND
"${${_CacheVariable}}" IS_NEWER_THAN "${CMAKE_CACHEFILE_DIR}/CMakeCache.txt")
# search var path has changed
<API key>(${_CacheVariable} _vars_to_clean)
if (Mathematica_DEBUG)
message (STATUS "${_CacheVariable} path ${${_CacheVariable}} modified since last CMake run")
endif()
endif()
elseif (DEFINED ${_CacheVariable} OR DEFINED ${_CacheVariable}_LAST)
# search var presence changed
<API key>(${_CacheVariable} _vars_to_clean)
if (Mathematica_DEBUG)
message (STATUS "${_CacheVariable} presence changed")
endif()
endif()
endforeach()
if (_vars_to_clean)
list (REMOVE_DUPLICATES _vars_to_clean)
message (STATUS "Mathematica environment changed, restart search ...")
if (Mathematica_DEBUG)
message (STATUS "Unset ${_vars_to_clean}")
endif()
foreach (_CacheVariable IN LISTS _vars_to_clean)
unset(${_CacheVariable} CACHE)
unset(${_CacheVariable})
endforeach()
endif()
endmacro()
# internal macro to update cache variables
macro (_update_cache)
mark_as_advanced(
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
)
<API key>(_CacheVariables)
foreach (_CacheVariable IN LISTS _CacheVariables)
if (DEFINED ${_CacheVariable})
set (${_CacheVariable}_LAST ${${_CacheVariable}}
CACHE INTERNAL "Last value of ${_CacheVariable}." FORCE)
else()
unset(${_CacheVariable}_LAST CACHE)
endif()
endforeach()
endmacro()
# internal macro to return variables that need to exist in order for component
# to be considered found successfully
macro (_get_required_vars _component _outVars)
if ("${_component}" STREQUAL "Mathematica")
set (${_outVars}
<API key>
<API key>)
elseif ("${_component}" STREQUAL "MathLink")
set (${_outVars}
<API key> <API key>)
elseif ("${_component}" STREQUAL "WSTP")
set (${_outVars}
<API key> <API key>)
elseif ("${_component}" STREQUAL "WolframLibrary")
set (${_outVars}
<API key> <API key>)
elseif ("${_component}" STREQUAL "JLink")
set (${_outVars}
<API key> <API key>)
elseif ("${_component}" STREQUAL "MUnit")
set (${_outVars}
<API key>)
endif()
endmacro()
macro (<API key> _outComponents)
if (<API key>)
list (APPEND ${_outComponents} ${<API key>})
else()
if (DEFINED <API key>)
set (_versionMajor "${<API key>}")
elseif (DEFINED <API key>)
set (_versionMajor "${<API key>}")
else()
set (_versionMajor "")
endif()
if (_versionMajor)
if (_versionMajor GREATER 9)
list (APPEND ${_outComponents} "WSTP" "MathLink" "WolframLibrary" "JLink" "MUnit")
elseif (_versionMajor GREATER 7)
list (APPEND ${_outComponents} "MathLink" "WolframLibrary" "JLink" "MUnit")
else()
list (APPEND ${_outComponents} "MathLink" "JLink" "MUnit")
endif()
else()
list (APPEND ${_outComponents} "WSTP" "MathLink" "WolframLibrary" "JLink" "MUnit")
endif()
endif()
list (REMOVE_DUPLICATES ${_outComponents})
endmacro()
# internal macro to handle the QUIETLY and REQUIRED arguments and set *_FOUND variables
macro (<API key>)
# determine required Mathematica components
_get_required_vars("Mathematica" _requiredVars)
<API key>(_components)
foreach(_component IN LISTS _components)
_get_required_vars(${_component} <API key>)
# suppress <API key> warning on mismatching names
set (<API key> On)
<API key>(
Mathematica_${_component}
REQUIRED_VARS ${<API key>}
VERSION_VAR Mathematica_${_component}_VERSION)
string(TOUPPER ${_component} _UpperCaseComponent)
# <API key> only sets upper case _FOUND variable
set (Mathematica_${_component}_FOUND ${MATHEMATICA_${_UpperCaseComponent}_FOUND})
if (<API key>${_component})
list (APPEND _requiredVars ${<API key>} )
endif()
endforeach()
<API key>(
Mathematica
REQUIRED_VARS ${_requiredVars}
VERSION_VAR Mathematica_VERSION)
# <API key> only sets upper case _FOUND variable
set (Mathematica_FOUND ${MATHEMATICA_FOUND})
endmacro()
# internal macro that searches for requested components
macro (_find_components)
<API key>(_components)
foreach(_component IN LISTS _components)
if ("${_component}" STREQUAL "MathLink")
_find_mathlink()
<API key>()
<API key>()
elseif ("${_component}" STREQUAL "WSTP")
_find_wstp()
<API key>()
<API key>()
elseif ("${_component}" STREQUAL "WolframLibrary")
<API key>()
<API key>()
<API key>()
<API key>()
elseif ("${_component}" STREQUAL "JLink")
_find_jlink()
<API key>()
elseif ("${_component}" STREQUAL "MUnit")
_find_munit_package()
<API key>()
else()
message (FATAL_ERROR "Unknown Mathematica component ${_component}")
endif()
endforeach()
list (REMOVE_DUPLICATES <API key>)
list (REMOVE_DUPLICATES <API key>)
list (REMOVE_DUPLICATES <API key>)
list (REMOVE_DUPLICATES <API key>)
list (REMOVE_DUPLICATES <API key>)
endmacro()
# internal helper function to compute the install name of a shared library under Mac OS X
macro (_get_install_name _libraryPath _libraryInstallName _libraryAbsPath)
if (APPLE)
set (${_libraryInstallName} "")
set (${_libraryAbsPath} "")
if (IS_DIRECTORY "${_libraryPath}")
# framework folder
<API key>(_name "${_libraryPath}" NAME_WE)
set (_path "${_libraryPath}/${_name}")
else()
set (_path "${_libraryPath}")
endif()
if (EXISTS "${_path}")
find_program(<API key> "otool")
mark_as_advanced(<API key>)
<API key>(${_libraryAbsPath} ${_path} ABSOLUTE)
set (_otoolOutput "")
if (<API key>)
execute_process(
COMMAND "${<API key>}" "-D" "-X" "${${_libraryAbsPath}}" TIMEOUT 5
OUTPUT_VARIABLE _otoolOutput <API key>)
# install name is in last line of otool output
string (REPLACE "\n" ";" _otoolOutput "${_otoolOutput}")
endif()
if (_otoolOutput)
list (GET _otoolOutput -1 ${_libraryInstallName})
else()
set (${_libraryInstallName} "")
endif()
endif()
endif()
endmacro()
# FindMathematica "main" starts here
<API key>()
_log_used_variables()
<API key>()
<API key>()
if (DEFINED <API key>)
# not the initial find invocation
_cleanup_cache()
endif()
<API key>()
<API key>()
_find_mathematica()
<API key>()
# now setup public functions based on found components
# public function to convert a CMake string to a Mathematica string
function (<API key> _inStr _outStr)
string (REPLACE "\\" "\\\\" _str ${_inStr})
string (REPLACE "\"" "\\\"" _str ${_str})
set (${_outStr} "\"${_str}\"" PARENT_SCOPE)
endfunction()
# public function to convert a CMake list to a Mathematica list
function (<API key> _outList)
set (_list "{")
foreach (_elem ${ARGN})
<API key>(${_elem} _elemStr)
if ("${_list}" STREQUAL "{")
set (_list "{${_elemStr}")
else()
set (_list "${_list},${_elemStr}")
endif()
endforeach()
set (${_outList} "${_list}}" PARENT_SCOPE)
endfunction()
# public function to convert CMake paths to Mathematica paths
function (<API key> _inPathStr _outPathStr)
list (LENGTH _inPathStr _len)
if (_len EQUAL 0)
set (${_outPathStr} "" PARENT_SCOPE)
elseif (_len EQUAL 1)
_to_native_path("${_inPathStr}" _nativePath)
<API key>("${_nativePath}" _pathMma)
set (${_outPathStr} "${_pathMma}" PARENT_SCOPE)
else()
set (_lastDir "")
set (_names "")
set (_nativePathsMma "")
set (_hasMapPaths FALSE)
set (_requiresList FALSE)
foreach (_path IN LISTS _inPathStr ITEMS "")
<API key>(_dir "${_path}" DIRECTORY)
<API key>(_name "${_path}" NAME)
if (_lastDir AND NOT "${_dir}" STREQUAL "${_lastDir}")
list (LENGTH _names _nameCount)
if (_nameCount GREATER 1)
<API key>("${_lastDir}" _commonDirMma)
<API key>(_namesMma ${_names})
set (_code "Map[ToFileName[${_commonDirMma},#]&,${_namesMma}]")
set (_hasMapPaths TRUE)
else()
<API key>("${_lastDir}/${_names}" _code)
endif()
if (_nativePathsMma)
set (_nativePathsMma "${_nativePathsMma},${_code}")
set (_requiresList TRUE)
else()
set (_nativePathsMma "${_code}")
endif()
set (_names "")
endif()
set (_lastDir "${_dir}")
list (APPEND _names "${_name}")
endforeach()
if (_requiresList AND _hasMapPaths)
set (_nativePathsMma "Flatten[{${_nativePathsMma}}]")
elseif (_requiresList)
set (_nativePathsMma "{${_nativePathsMma}}")
endif()
set (${_outPathStr} "${_nativePathsMma}" PARENT_SCOPE)
endif()
endfunction()
# public function to initialize Mathematica test properties
function (<API key>)
<API key>(_configRuntimeDirs)
<API key>(_envVars)
foreach (_envVar IN LISTS _envVars)
if (DEFINED ENV{${_envVar}})
file (TO_CMAKE_PATH "$ENV{${_envVar}}" _envRuntimeDirs)
# prepend Mathematica runtime directories to system ones
set (_runtimeDirs ${_configRuntimeDirs} ${_envRuntimeDirs})
else()
set (_runtimeDirs ${_configRuntimeDirs})
endif()
if (_runtimeDirs)
list (REMOVE_DUPLICATES _runtimeDirs)
if (CYGWIN)
# CYGWIN path list requires UNIX syntax
_to_cmake_path_list(_nativeRuntimeDirs ${_runtimeDirs})
else()
<API key>(_nativeRuntimeDirs ${_runtimeDirs})
endif()
foreach (_testName ${ARGV})
if ("${_testName}" STREQUAL "PROPERTIES")
break()
endif()
set_property (TEST ${_testName} APPEND PROPERTY
ENVIRONMENT "${_envVar}=${_nativeRuntimeDirs}" )
endforeach()
endif()
endforeach()
set (_haveProperties False)
foreach (_testName IN ITEMS ${ARGV})
if ("${_testName}" STREQUAL "PROPERTIES")
set (_haveProperties True)
break()
endif()
set_property (TEST ${_testName} APPEND PROPERTY LABELS "Mathematica")
endforeach()
if (_haveProperties)
<API key> (${ARGV})
endif()
endfunction(<API key>)
# internal macro to return test driver for host platform
function (_add_test_driver _cmdVar _testName _inputVar _inputFileVar)
if (CMAKE_HOST_UNIX)
set (_testDriver "${<API key>}/<API key>.sh")
elseif (CMAKE_HOST_WIN32)
set (_testDriver "${<API key>}/<API key>.cmd")
endif()
if (NOT EXISTS "${_testDriver}")
message (FATAL_ERROR "FindMathematica test driver script ${_testDriver} is missing.")
endif()
<API key>(${_testDriver})
if (CYGWIN)
_to_cmake_path("${_testDriver}" _testDriver)
else()
_to_native_path("${_testDriver}" _testDriver)
endif()
list (APPEND ${_cmdVar} "${_testDriver}" "${_testName}" "$<CONFIGURATION>")
if (DEFINED ${_inputVar})
list (APPEND ${_cmdVar} "input" "${${_inputVar}}")
elseif (DEFINED ${_inputFileVar})
list (APPEND ${_cmdVar} "inputfile" "${${_inputFileVar}}")
else()
list (APPEND ${_cmdVar} "noinput")
endif()
set (${_cmdVar} ${${_cmdVar}} PARENT_SCOPE)
endfunction()
# internal macro to add platform specific executable launch prefix
macro (_add_launch_prefix _cmdVar _systemIDVar)
if (DEFINED ${_systemIDVar})
if (CMAKE_HOST_APPLE)
if (NOT "${${_systemIDVar}}" STREQUAL "${<API key>}")
# under Mac OS X, run appropriate target architecture of executable universal binary
# by using the the /usr/bin/arch tool which is available since Leopard
# (Mac OS X 10.5.0 is Darwin 9.0.0)
if ("${<API key>}" VERSION_LESS "9.0.0")
message (STATUS "Executable system ID selection of ${${_systemIDVar}} is not supported, running default.")
elseif ("${${_systemIDVar}}" STREQUAL "MacOSX-x86")
list (APPEND ${_cmdVar} "/usr/bin/arch" "-i386")
elseif("${${_systemIDVar}}" STREQUAL "MacOSX-x86-64")
list (APPEND ${_cmdVar} "/usr/bin/arch" "-x86_64")
elseif("${${_systemIDVar}}" MATCHES "Darwin|MacOSX")
list (APPEND ${_cmdVar} "/usr/bin/arch" "-ppc")
elseif("${${_systemIDVar}}" STREQUAL "Darwin-PowerPC64")
list (APPEND ${_cmdVar} "/usr/bin/arch" "-ppc64")
else()
message (STATUS "Executable system ID ${${_systemIDVar}} is not supported, running default.")
endif()
endif()
endif()
endif()
endmacro()
# internal macro to set up kernel launch command
macro (<API key> _cmdVar _systemIDVar _kernelOptionsVar)
if (CMAKE_HOST_WIN32 OR CYGWIN)
set (_kernelExecutable "${<API key>}")
if (DEFINED ${_systemIDVar})
# under Windows, run alternate binary for given system ID
<API key>(_kernelName "${_kernelExecutable}" NAME)
set (_kernelExecutable
"${<API key>}/SystemFiles/Kernel/Binaries/${${_systemIDVar}}/${_kernelName}")
if (NOT EXISTS "${_kernelExecutable}")
set (_kernelExecutable "${<API key>}")
if (NOT "${_systemIDVar}" STREQUAL "${<API key>}")
message (STATUS "Kernel executable for ${${_systemIDVar}} is not available, running default ${<API key>}.")
endif()
endif()
endif()
_to_native_path("${_kernelExecutable}" _kernelExecutable)
list (APPEND ${_cmdVar} "${_kernelExecutable}")
elseif (CMAKE_HOST_APPLE)
_add_launch_prefix(${_cmdVar} ${_systemIDVar})
_to_native_path("${<API key>}" _kernelExecutable)
list (APPEND ${_cmdVar} "${_kernelExecutable}")
elseif (CMAKE_HOST_UNIX)
_to_native_path("${<API key>}" _kernelExecutable)
list (APPEND ${_cmdVar} "${_kernelExecutable}")
if (DEFINED ${_systemIDVar})
if (Mathematica_VERSION)
if (NOT "${Mathematica_VERSION}" VERSION_LESS "8.0")
# Mathematica 8 kernel wrapper shell script supports option -SystemID
list (APPEND ${_cmdVar} "-SystemID" "${${_systemIDVar}}")
elseif (NOT "${_systemIDVar}" STREQUAL "${<API key>}")
message (STATUS "Kernel system ID selection of ${${_systemIDVar}} is not supported, running default ${<API key>}.")
endif()
endif()
endif()
else()
message (FATAL_ERROR "Unsupported host platform ${<API key>}")
endif()
if (DEFINED ${_kernelOptionsVar})
list (APPEND ${_cmdVar} ${${_kernelOptionsVar}})
else()
list (APPEND ${_cmdVar} "-noinit" "-noprompt")
endif()
endmacro(<API key>)
macro (<API key> _codeVar _useTempFileVar)
set (_codeLength 0)
set (_codeSegmentCount 1)
set (_usesReservedChars FALSE)
foreach (_codeSegment IN LISTS ${_codeVar})
string (LENGTH "${_codeSegment}" _codeSegmentLength)
math (EXPR _codeLength "${_codeLength} + ${_codeSegmentLength}")
if (_codeSegment MATCHES "(Get|Needs|Install|Sequence)\\[[^]]*\\]")
# start new code segment
math (EXPR _codeSegmentCount "${_codeSegmentCount} + 1")
endif()
if (NOT _usesReservedChars)
if (_codeSegment MATCHES "[<>|&!%^]")
set (_usesReservedChars TRUE)
endif()
endif()
endforeach()
if (CMAKE_HOST_WIN32 AND (_usesReservedChars OR _codeLength GREATER 1000 OR _codeSegmentCount GREATER 3))
# under Windows XP or later cmd.exe has a command line length limit of 8191 characters.
# we do not use inline statements if the approximate command line length
# might exceed that limit or there are too many individual arguments.
# we write the inline statements to a temporary script instead
set (${_useTempFileVar} TRUE)
elseif (CMAKE_HOST_UNIX AND (_codeLength GREATER 10000 OR _codeSegmentCount GREATER 10))
# for UNIX use a temp file if command line becomes confusing
set (${_useTempFileVar} TRUE)
else()
set (${_useTempFileVar} FALSE)
endif()
endmacro()
macro (<API key> _codeVar _codeSegments)
# collect all CODE sections into CompoundExpressions
set (${_codeSegments} "")
set (_currentCodeSegment "")
set (<API key> False)
foreach (_codeSegment IN LISTS ${_codeVar} ITEMS "Sequence[]")
if (_codeSegment MATCHES "\n")
# remove indentation with tabs
string (REGEX REPLACE "\t+" "" _codeSegment "${_codeSegment}")
# separate multiple lines via commas
string (REPLACE "\n" "," _codeSegment "${_codeSegment}")
endif()
# prevent CMake from interpreting ; as a list separator
string (REPLACE ";" "\\;" _codeSegment "${_codeSegment}")
if (_currentCodeSegment)
if (NOT _codeSegment STREQUAL "Sequence[]")
set (<API key> True)
set (_currentCodeSegment "${_currentCodeSegment},${_codeSegment}")
endif()
else()
set (_currentCodeSegment "${_codeSegment}")
endif()
# flush current CompoundExpression when a Get[...], Needs[...] or Install[...]
# expression is encountered, so that new context definitions become effective
# immediately for subsequent commands
# Sequence[] can be used to explicitly flush the current CompoundExpression
if (_codeSegment MATCHES "(Get|Needs|Install|Sequence)\\[[^]]*\\]")
if (<API key> OR
(CMAKE_HOST_WIN32 AND NOT _currentCodeSegment MATCHES " "))
# note that the blanks around the CompoundExpression argument below are necessary
# to force CMake to do proper cmd.exe quoting of the resulting parameter under Windows
# (a comma in the parameter may be misinterpreted as a separator otherwise)
list (APPEND ${_codeSegments} "-run" "CompoundExpression[ ${_currentCodeSegment} ]")
elseif (NOT _currentCodeSegment STREQUAL "Sequence[]")
# flush single code segment, but only if it is not a NOP
list (APPEND ${_codeSegments} "-run" "${_currentCodeSegment}")
endif()
set (_currentCodeSegment "")
set (<API key> False)
endif()
endforeach()
endmacro(<API key>)
macro (<API key> _codeVar _tempScriptFile)
# check for use of CMake generator expressions in inline code
set (<API key> FALSE)
set (_contents "")
foreach (_codeSegment IN LISTS ${_codeVar})
string (REPLACE ";" "\\;" _line "${_codeSegment}")
list (APPEND _contents "${_line}")
if (NOT <API key>)
if ("${_line}" MATCHES "\\$<.*>")
set (<API key> TRUE)
endif()
endif()
endforeach()
string (REPLACE ";" "\n" _contents "${_contents}")
# use script content MD5 as temporary file name
string (MD5 _scriptName "${_contents}")
set (_tempScript "${<API key>}/FindMathematica/${_scriptName}.m")
file (WRITE "${_tempScript}" "${_contents}")
if (<API key>)
set (<API key> "$<$<CONFIG:>:None>$<$<NOT:$<CONFIG:>>:$<CONFIGURATION>>")
set (_tempConfigScript "${<API key>}/FindMathematica/${_scriptName}_${<API key>}.m")
file (GENERATE OUTPUT "${_tempConfigScript}" INPUT "${_tempScript}")
else()
set (_tempConfigScript "${_tempScript}")
endif()
set (${_tempScriptFile} "${_tempConfigScript}")
endmacro(<API key>)
# internal macro to translate CODE or SCRIPT option to Mathematica launch command
macro (_add_script_or_code _cmdVar _scriptVar _codeVar)
if (DEFINED ${_codeVar} OR DEFINED ${_scriptVar})
# start with code to prepend the FindMathematica module directory to the Mathematica $Path
<API key>("${<API key>}" _cmakeModuleDirMma)
set (_code "PrependTo[$Path, ${_cmakeModuleDirMma}]")
# add given inline code statements
if (DEFINED ${_codeVar})
list (APPEND _code ${${_codeVar}})
endif()
# compute absolute path to given script
if (DEFINED ${_scriptVar})
if (IS_ABSOLUTE "${${_scriptVar}}")
_to_cmake_path("${${_scriptVar}}" _scriptFileAbs)
else()
_to_cmake_path("${<API key>}/${${_scriptVar}}" _scriptFileAbs)
endif()
endif()
if (NOT DEFINED ${_scriptVar})
# no given script, quit kernel explicitly unless last code statement already does it
list (GET _code -1 _lastStatement)
if (NOT _lastStatement MATCHES "^(Quit|Exit)\\[")
list (APPEND _code "Quit[]")
endif()
elseif ("${Mathematica_VERSION}" VERSION_LESS "10.0")
# Although the -script option is supported since Mathematica 8, under Mathematica 9
# using the -script option does not work as expected, if it is preceded by multiple inline
# Mathematica commands using the -run option.
# Thus we use the Get function instead, which should work with all versions.
# running the kernel with the -script option is equivalent to reading the file using the Get function
# with a single difference: after the last command in the file is evaluated, the kernel terminates
<API key>("${_scriptFileAbs}" _scriptFileMma)
list (APPEND _code "Get[${_scriptFileMma}]" "Quit[]")
endif()
# convert resulting code to kernel inline code segments or if necessary to a temporary script file
<API key>(_code _useTempFile)
if (_useTempFile)
<API key>(_code _tempScriptFile)
<API key>("${_tempScriptFile}" _tempScriptFileMma)
list (APPEND ${_cmdVar} "-run" "Get[${_tempScriptFileMma}]")
else()
<API key>(_code _codeSegments)
list (APPEND ${_cmdVar} ${_codeSegments})
endif()
# finally, run given script with -script option if using Mathematica 10 or later
if (DEFINED ${_scriptVar})
if (NOT "${Mathematica_VERSION}" VERSION_LESS "10.0")
list (APPEND ${_cmdVar} "-script" "${_scriptFileAbs}")
# after the last command in the script file is evaluated, the kernel terminates automatically
endif()
endif()
endif()
endmacro(_add_script_or_code)
# internal macro to set up linkmode launch command
macro (<API key> _cmdVar _protocolKind _systemIDVar _kernelOptionsVar _linkProtocolVar _scriptVar _codeVar)
list (APPEND ${_cmdVar} "-linkmode" "launch")
if (DEFINED ${_linkProtocolVar})
list (APPEND ${_cmdVar} "-linkprotocol" "${${_linkProtocolVar}}")
endif()
list (APPEND ${_cmdVar} "-linkname")
if (UNIX AND NOT CYGWIN)
# UNIX (except for Cygwin) requires quoted link name path and -mathlink or -wstp
set (_kernelLaunchArgs "")
<API key>(_kernelLaunchArgs ${_systemIDVar} ${_kernelOptionsVar})
_add_script_or_code(_kernelLaunchArgs ${_scriptVar} ${_codeVar})
_list_to_cmd_str(_kernelLaunchStr ${_kernelLaunchArgs})
list (APPEND ${_cmdVar} "${_kernelLaunchStr} ${_protocolKind}")
else ()
<API key>(${_cmdVar} ${_systemIDVar} ${_kernelOptionsVar})
endif()
endmacro()
if (<API key>)
# public function for executing Mathematica code file at configuration time
function (Mathematica_EXECUTE)
set(_options "")
list(APPEND _options CACHE)
set(_oneValueArgs
SCRIPT SYSTEM_ID
INPUT_FILE OUTPUT_FILE ERROR_FILE
RESULT_VARIABLE OUTPUT_VARIABLE ERROR_VARIABLE
TIMEOUT DOC)
set(_multiValueArgs CODE KERNEL_OPTIONS)
<API key>(_option "${_options}" "${_oneValueArgs}" "${_multiValueArgs}" ${ARGN})
if(<API key>)
message (FATAL_ERROR "Unknown keywords: ${<API key>}")
elseif (NOT _option_CODE AND NOT _option_SCRIPT)
message (FATAL_ERROR "Either the keyword CODE or SCRIPT must be present.")
endif()
if (_option_CACHE AND <API key>)
if (DEFINED "${<API key>}")
set (_var "${${<API key>}}")
if (_var AND NOT "${_var}" MATCHES "\\$Failed|\\$Aborted|Mathematica cannot find a valid password")
# use result from cache if is not a false constant, $Failed, $Aborted or not properly registered
return()
endif()
endif()
endif()
set (_cmd COMMAND)
<API key>(_cmd _option_SYSTEM_ID <API key>)
_add_script_or_code(_cmd _option_SCRIPT _option_CODE)
if (_option_CODE)
list (APPEND _cmd <API key>)
list (APPEND _cmd <API key>)
endif()
foreach (_key IN LISTS _oneValueArgs)
set (_value "_option_${_key}")
if (DEFINED ${_value})
if (_key MATCHES "_VARIABLE$")
list (APPEND _cmd ${_key} "${${_value}}")
list (APPEND _variables "${${_value}}")
elseif (NOT _key MATCHES "SCRIPT|CODE|SYSTEM_ID|DOC")
list (APPEND _cmd ${_key} "${${_value}}")
endif()
endif()
endforeach()
list (APPEND _cmd WORKING_DIRECTORY "${<API key>}")
if (Mathematica_DEBUG)
message (STATUS "execute_process: ${_cmd}")
endif()
execute_process (${_cmd})
# put result to cache
if (<API key>)
# if Mathematica is not registered properly, print a warning
if ("${${<API key>}}" MATCHES "Mathematica cannot find a valid password")
message (WARNING "${${<API key>}}")
return()
endif()
endif()
if (_option_CACHE AND <API key>)
if (NOT _option_DOC)
set (_option_DOC "Mathematica_EXECUTE kernel output.")
endif()
set (${<API key>}
"${${<API key>}}" CACHE STRING "${_option_DOC}" FORCE)
endif()
# propagate variables to parent scope
foreach (_var IN LISTS _variables)
if (DEFINED ${_var})
set (${_var} ${${_var}} PARENT_SCOPE)
endif()
endforeach()
endfunction(Mathematica_EXECUTE)
# public function for executing Mathematica code at build time as a standalone target
function (<API key> _targetName)
set(_options ALL)
set(_oneValueArgs SCRIPT COMMENT SYSTEM_ID)
set(_multiValueArgs CODE DEPENDS SOURCES KERNEL_OPTIONS)
<API key>(_option "${_options}" "${_oneValueArgs}" "${_multiValueArgs}" ${ARGN})
if(<API key>)
message (FATAL_ERROR "Unknown keywords: ${<API key>}")
elseif (NOT _option_CODE AND NOT _option_SCRIPT)
message (FATAL_ERROR "Either the keyword CODE or SCRIPT must be present.")
endif()
set (_cmd "${_targetName}")
if (_option_ALL)
list(APPEND _cmd "ALL")
endif()
list(APPEND _cmd COMMAND)
<API key>(_cmd _option_SYSTEM_ID <API key>)
_add_script_or_code(_cmd _option_SCRIPT _option_CODE)
if (_option_SCRIPT)
list (APPEND _option_DEPENDS ${_option_SCRIPT})
endif()
if (_option_DEPENDS)
list (APPEND _cmd DEPENDS ${_option_DEPENDS})
endif()
if (_option_COMMENT)
list(APPEND _cmd COMMENT ${_option_COMMENT})
endif()
if (_option_SOURCES)
list(APPEND _cmd SOURCES ${_option_SOURCES})
endif()
list (APPEND _cmd WORKING_DIRECTORY "${<API key>}" VERBATIM)
if (Mathematica_DEBUG)
message (STATUS "add_custom_target: ${_cmd}")
endif()
add_custom_target(${_cmd})
endfunction(<API key>)
# public function for executing Mathematica code at build time to produce output files
function (<API key>)
set(_options PRE_BUILD PRE_LINK POST_BUILD APPEND)
set(_oneValueArgs SCRIPT COMMENT MAIN_DEPENDENCY TARGET SYSTEM_ID)
set(_multiValueArgs CODE OUTPUT DEPENDS KERNEL_OPTIONS)
<API key>(_option "${_options}" "${_oneValueArgs}" "${_multiValueArgs}" ${ARGN})
if(<API key>)
message (FATAL_ERROR "Unknown keywords: ${<API key>}")
elseif (NOT _option_CODE AND NOT _option_SCRIPT)
message (FATAL_ERROR "Either the keyword CODE or SCRIPT must be present.")
elseif (NOT _option_OUTPUT AND NOT _option_TARGET)
message (FATAL_ERROR "Either the keyword OUTPUT or TARGET must be present.")
elseif (_option_OUTPUT AND _option_TARGET)
message (FATAL_ERROR "Keywords OUTPUT and TARGET are mutually exclusive.")
endif()
if (_option_OUTPUT)
set (_cmd OUTPUT ${_option_OUTPUT})
endif()
if (_option_TARGET)
set (_cmd TARGET ${_option_TARGET})
endif()
if (_option_PRE_BUILD)
list(APPEND _cmd PRE_BUILD)
endif()
if (_option_PRE_LINK)
list(APPEND _cmd PRE_LINK)
endif()
if (_option_POST_BUILD)
list(APPEND _cmd POST_BUILD)
endif()
list(APPEND _cmd COMMAND)
<API key>(_cmd _option_SYSTEM_ID <API key>)
_add_script_or_code(_cmd _option_SCRIPT _option_CODE)
if (<API key>)
list(APPEND _cmd MAIN_DEPENDENCY ${<API key>})
endif()
if (_option_SCRIPT AND _option_OUTPUT)
list (APPEND _option_DEPENDS ${_option_SCRIPT})
endif()
if (_option_DEPENDS)
list(APPEND _cmd DEPENDS ${_option_DEPENDS})
endif()
if (_option_COMMENT)
list(APPEND _cmd COMMENT ${_option_COMMENT})
endif()
list (APPEND _cmd WORKING_DIRECTORY "${<API key>}" VERBATIM)
if (_option_APPEND)
list(APPEND _cmd APPEND)
endif()
if (Mathematica_DEBUG)
message (STATUS "add_custom_command: ${_cmd}")
endif()
add_custom_command(${_cmd})
endfunction(<API key>)
# public function to simplify testing Mathematica commands
function (<API key>)
set(_options "")
set(_oneValueArgs NAME SCRIPT INPUT INPUT_FILE SYSTEM_ID)
set(_multiValueArgs CODE CONFIGURATIONS COMMAND KERNEL_OPTIONS)
<API key>(_option "${_options}" "${_oneValueArgs}" "${_multiValueArgs}" ${ARGN})
if(<API key>)
message (FATAL_ERROR "Unknown keywords: ${<API key>}")
elseif (NOT _option_NAME)
message (FATAL_ERROR "Mandatory parameter NAME is missing.")
elseif (NOT _option_CODE AND NOT _option_SCRIPT AND NOT _option_COMMAND)
message (FATAL_ERROR "Either the keyword CODE, SCRIPT or COMMAND must be present.")
endif()
set (_cmd NAME "${_option_NAME}" COMMAND)
_add_test_driver(_cmd "${_option_NAME}" _option_INPUT _option_INPUT_FILE)
if (_option_COMMAND)
_add_launch_prefix(_cmd _option_SYSTEM_ID)
list (APPEND _cmd ${_option_COMMAND})
else()
<API key>(_cmd _option_SYSTEM_ID <API key>)
_add_script_or_code(_cmd _option_SCRIPT _option_CODE)
endif()
if (<API key>)
list (APPEND _cmd CONFIGURATIONS ${<API key>})
endif()
if (Mathematica_DEBUG)
message (STATUS "add_test: ${_cmd}")
endif()
add_test (${_cmd})
endfunction (<API key>)
# public function to add target that runs Mathematica Encode function on input files
function (Mathematica_ENCODE)
set(_options "CHECK_TIMESTAMPS")
set(_oneValueArgs "COMMENT" "KEY" "MACHINE_ID")
set(_multiValueArgs "OUTPUT")
<API key>(_option "${_options}" "${_oneValueArgs}" "${_multiValueArgs}" ${ARGN})
set (_inputFiles ${<API key>})
list (LENGTH _inputFiles _inputFileCount)
if (_inputFileCount EQUAL 0)
message (WARNING "No input files to encode given.")
return()
endif()
if (_option_OUTPUT)
set (_outputFiles ${_option_OUTPUT})
else()
# no output option given, write encoded files to <API key>
set (_outputFiles ${<API key>})
endif()
list (LENGTH _outputFiles _outputFileCount)
if (_outputFileCount EQUAL 1 AND _inputFileCount GREATER 1 AND IS_DIRECTORY "${_outputFiles}")
# OUTPUT option is a single existing directory, write encoded files to it
set (_outputDir "${_outputFiles}")
math(EXPR _lastIndex "${_inputFileCount} - 2")
foreach(_index RANGE ${_lastIndex})
list (APPEND _outputFiles "${_outputDir}")
endforeach()
set (_outputFileCount ${_inputFileCount})
endif()
set (_outputFilesAbs "")
set (_inputFilesAbs "")
set (_outputDirs "")
if (_outputFileCount EQUAL _inputFileCount)
math(EXPR _lastIndex "${_inputFileCount} - 1")
foreach(_index RANGE ${_lastIndex})
list (GET _inputFiles ${_index} _inputFile)
<API key>(_inputFileAbs "${_inputFile}" ABSOLUTE)
list (APPEND _inputFilesAbs "${_inputFileAbs}")
list (GET _outputFiles ${_index} _outputFile)
if (IS_DIRECTORY "${_outputFile}")
file (RELATIVE_PATH _inputFileRel ${<API key>} "${_inputFileAbs}")
if (NOT IS_ABSOLUTE "${_inputFileRel}" AND NOT "${_inputFileRel}" MATCHES "^\\.\\.")
set (_outputFile "${_outputFile}/${_inputFileRel}")
else()
<API key>(_inputFileName "${_inputFile}" NAME)
set (_outputFile "${_outputFile}/${_inputFileName}")
endif()
endif()
if (IS_ABSOLUTE "${_outputFile}")
list (APPEND _outputFilesAbs "${_outputFile}")
else()
list (APPEND _outputFilesAbs "${<API key>}/${_outputFile}")
endif()
<API key>(_outputFileDir "${_outputFile}" DIRECTORY)
if (NOT _outputFileDir STREQUAL "${<API key>}")
list (APPEND _outputDirs "${_outputFileDir}")
endif()
endforeach()
else()
# OUTPUT option must have exactly one entry for each input file
message (FATAL_ERROR
"Number of output files (${_outputFileCount}) does not match number of input files (${_inputFileCount}).")
endif()
<API key>("${_inputFilesAbs}" _inputFilesAbsMma)
<API key>("${_outputFilesAbs}" _outputFilesAbsMma)
set (_cmdOptionsMma "")
if (_option_KEY)
<API key>("${_option_KEY}" _keyMma)
set (_cmdOptionsMma "${_cmdOptionsMma},${_keyMma}")
endif()
if (_option_MACHINE_ID)
<API key>("${_option_MACHINE_ID}" _machineIDMma)
set (_cmdOptionsMma "${_cmdOptionsMma},MachineID->${_machineIDMma}")
endif()
if (<API key>)
set (_encodeFunc "If[FileType[#2]==None||OrderedQ[{FileDate[#2],FileDate[#1]}],Encode[#1,#2${_cmdOptionsMma}]]&")
else()
set (_encodeFunc "Encode[#1,#2${_cmdOptionsMma}]&")
endif()
if (_inputFileCount EQUAL 1)
set (_func "Apply")
else()
set (_func "MapThread")
endif()
set (_cmds "")
if (_outputDirs)
list (SORT _outputDirs)
list (REMOVE_DUPLICATES _outputDirs)
<API key>("${_outputDirs}" _outputDirsMma)
list (APPEND _cmds "Quiet[CreateDirectory[${_outputDirsMma}]]")
endif()
list (APPEND _cmds "${_func}[${_encodeFunc},{${_inputFilesAbsMma},${_outputFilesAbsMma}}]")
if (NOT _option_COMMENT)
if (_inputFileCount EQUAL 1)
set (_option_COMMENT "Encoding ${_inputFiles}")
else()
set (_option_COMMENT "Encoding ${_inputFileCount} Mathematica files")
endif()
endif()
<API key>(
CODE ${_cmds}
OUTPUT ${_outputFilesAbs}
DEPENDS ${_inputFilesAbs}
COMMENT "${_option_COMMENT}")
<API key>(${_outputFilesAbs} PROPERTIES GENERATED TRUE LABELS "Mathematica")
endfunction(Mathematica_ENCODE)
# public function to find Mathematica package
function (<API key> _var _packageName)
set(_options "")
set(_oneValueArgs DOC SYSTEM_ID)
set(_multiValueArgs KERNEL_OPTIONS)
<API key>(_option "${_options}" "${_oneValueArgs}" "${_multiValueArgs}" ${ARGN})
if(<API key>)
message (FATAL_ERROR "Unknown keywords: ${<API key>}")
endif()
# determine MUnit package directory
<API key>("${_packageName}" _packageNameMma)
# default to using FileNames function
set (_findPackage "Print[StandardForm[Check[First[FileNames[ContextToFileName[${_packageNameMma}],$Path]],$Failed]]]")
if (DEFINED Mathematica_VERSION)
if (NOT "${Mathematica_VERSION}" VERSION_LESS "7.0")
# function FindFile available since Mathematica 7
set (_findPackage "Print[StandardForm[FindFile[${_packageNameMma}]]]")
endif()
endif()
if (NOT _option_DOC)
set (_option_DOC "Mathematica package file path.")
endif()
set (_cmd
CODE "${_findPackage}"
OUTPUT_VARIABLE ${_var}
CACHE DOC "${_option_DOC}"
TIMEOUT 10)
if (<API key>)
list (APPEND _cmd KERNEL_OPTIONS ${<API key>})
endif()
if (_option_SYSTEM_ID)
list (APPEND _cmd SYSTEM_ID ${_option_SYSTEM_ID})
endif()
# if package file variable already defined, verify package file existence
if (DEFINED ${_var})
if (NOT EXISTS "${${_var}}")
unset(${_var} CACHE)
unset(${_var})
endif()
endif()
Mathematica_EXECUTE(${_cmd})
# verify package file existence
if (DEFINED ${_var})
if (EXISTS "${${_var}}")
_to_cmake_path("${${_var}}" ${_var})
else()
set (${_var} "${_var}-NOTFOUND")
endif()
else()
set (${_var} "${_var}-NOTFOUND")
endif()
set (${_var} "${${_var}}" CACHE FILEPATH "${_option_DOC}" FORCE)
set (${_var} "${${_var}}" PARENT_SCOPE)
endfunction()
# public function to get root Mathematica package directory from a package file
function (<API key> _var _packageFile)
<API key>("${Mathematica_VERSION}" _intermediateDirs)
list (APPEND _intermediateDirs
"Kernel" "SystemResources" "SystemFiles" "Binaries"
"Libraries" "LibraryResources" "Java" "CSource")
if (NOT EXISTS "${_packageFile}")
set (${_var} "${_var}-NOTFOUND" PARENT_SCOPE)
return()
endif()
# walk up directory tree until we find package root dir
set (_packageFileDir "${_packageFile}")
set (_index 0)
while (NOT ${_index} EQUAL -1)
<API key>(_packageFileDir "${_packageFileDir}" DIRECTORY)
<API key>(_name "${_packageFileDir}" NAME)
list (FIND _intermediateDirs "${_name}" _index)
endwhile()
set (${_var} ${_packageFileDir} PARENT_SCOPE)
endfunction()
endif (<API key>)
# re-compute system IDs and base directories, now that we can query the kernel
<API key>()
<API key>()
<API key>()
<API key>()
# find Mathematica components
_find_components()
<API key>()
_update_cache()
<API key>()
<API key>()
# public function for fixing shared library references to dynamic Mathematica runtime libraries under Mac OS X
function (<API key>)
if (APPLE)
foreach(_target ${ARGV})
get_target_property(_targetType ${_target} TYPE)
if (_targetType MATCHES "MODULE_LIBRARY|SHARED_LIBRARY|EXECUTABLE")
foreach(_library <API key> <API key> <API key>)
if (DEFINED ${_library})
_get_install_name("${${_library}}" _libraryInstallName _libraryAbsPath)
if (_libraryInstallName)
add_custom_command (TARGET ${_target}
POST_BUILD COMMAND "${<API key>}"
"-change" "${_libraryInstallName}" "${_libraryAbsPath}"
"$<TARGET_FILE:${_target}>" VERBATIM)
endif()
endif()
endforeach()
endif()
endforeach()
endif()
endfunction()
if (<API key> AND <API key>)
# public function to simplify testing MathLink programs
function (<API key>)
set(_options "")
set(_oneValueArgs NAME SCRIPT TARGET INPUT INPUT_FILE SYSTEM_ID LINK_PROTOCOL LINK_MODE)
set(_multiValueArgs CODE CONFIGURATIONS KERNEL_OPTIONS)
<API key>(_option "${_options}" "${_oneValueArgs}" "${_multiValueArgs}" ${ARGN})
if(<API key>)
message (FATAL_ERROR "Unknown keywords: ${<API key>}")
elseif (NOT _option_TARGET)
message (FATAL_ERROR "Mandatory parameter TARGET is missing.")
elseif (NOT _option_NAME)
message (FATAL_ERROR "Mandatory parameter NAME is missing.")
endif()
if (NOT _option_LINK_MODE)
if (_option_CODE OR _option_SCRIPT)
set (_option_LINK_MODE "ParentConnect")
else()
set (_option_LINK_MODE "Launch")
endif()
endif()
set (_cmd NAME "${_option_NAME}" COMMAND)
_add_test_driver(_cmd "${_option_NAME}" _option_INPUT _option_INPUT_FILE)
if (_option_LINK_MODE MATCHES "^ParentConnect$")
# run Mathematica kernel and launch MathLink executable as a child process that connects with ParentConnect
if (CYGWIN OR MSYS)
get_target_property (_targetFile ${_option_TARGET} LOCATION)
<API key>("${_targetFile}" _installCmdMma)
else()
set (_installCmdMma "\"$<TARGET_FILE:${_option_TARGET}>\"")
endif()
set (_launch_prefix "")
_add_launch_prefix(_launch_prefix _option_SYSTEM_ID)
if (_launch_prefix)
<API key>(_launch_prefixMma ${_launch_prefix})
set (_installCmdMma
"StringJoin[StringInsert[${_launch_prefixMma},\" \",-1],StringInsert[${_installCmdMma},\"\\\"\",{1,-1}]]" )
endif()
if (<API key>)
set (_installCmd "link=Install[${_installCmdMma},LinkProtocol->\"${<API key>}\"]")
else()
set (_installCmd "link=Install[${_installCmdMma}]")
endif()
if (_option_CODE)
list (APPEND _installCmd ${_option_CODE})
endif()
if (NOT _option_SCRIPT)
list (APPEND _installCmd "Uninstall[link]")
endif()
<API key>(_cmd _option_SYSTEM_ID <API key>)
_add_script_or_code(_cmd _option_SCRIPT _installCmd)
elseif (_option_LINK_MODE MATCHES "^Launch$")
# run MathLink executable as front-end to Mathematica kernel
_add_launch_prefix(_cmd _option_SYSTEM_ID)
list (APPEND _cmd "$<TARGET_FILE:${_option_TARGET}>")
<API key>(_cmd "-mathlink"
_option_SYSTEM_ID <API key> <API key>
_option_SCRIPT _option_CODE)
else()
message (FATAL_ERROR "Parameter LINK_MODE must be either \"Launch\" or \"ParentConnect\".")
endif()
if (<API key>)
list (APPEND _cmd CONFIGURATIONS ${<API key>})
endif()
if (Mathematica_DEBUG)
message (STATUS "add_test: ${_cmd}")
endif()
add_test (${_cmd})
endfunction(<API key>)
endif (<API key> AND <API key>)
if (<API key> AND <API key>)
# public function to simplify testing WSTP programs
function (<API key>)
set(_options "")
set(_oneValueArgs NAME SCRIPT TARGET INPUT INPUT_FILE SYSTEM_ID LINK_PROTOCOL)
set(_multiValueArgs CODE CONFIGURATIONS KERNEL_OPTIONS)
<API key>(_option "${_options}" "${_oneValueArgs}" "${_multiValueArgs}" ${ARGN})
if(<API key>)
message (FATAL_ERROR "Unknown keywords: ${<API key>}")
elseif (NOT _option_TARGET)
message (FATAL_ERROR "Mandatory parameter TARGET is missing.")
elseif (NOT _option_NAME)
message (FATAL_ERROR "Mandatory parameter NAME is missing.")
endif()
set (_cmd NAME "${_option_NAME}" COMMAND)
_add_test_driver(_cmd "${_option_NAME}" _option_INPUT _option_INPUT_FILE)
if (_option_CODE OR _option_SCRIPT)
# run Mathematica kernel and install WSTP executable
if (CYGWIN OR MSYS)
get_target_property (_targetFile ${_option_TARGET} LOCATION)
<API key>("${_targetFile}" _installCmdMma)
else()
set (_installCmdMma "\"$<TARGET_FILE:${_option_TARGET}>\"")
endif()
set (_launch_prefix "")
_add_launch_prefix(_launch_prefix _option_SYSTEM_ID)
if (_launch_prefix)
<API key>(_launch_prefixMma ${_launch_prefix})
set (_installCmdMma
"StringJoin[StringInsert[${_launch_prefixMma},\" \",-1],StringInsert[${_installCmdMma},\"\\\"\",{1,-1}]]" )
endif()
if (<API key>)
set (_installCmd "link=Install[${_installCmdMma},LinkProtocol->\"${<API key>}\"]")
else()
set (_installCmd "link=Install[${_installCmdMma}]")
endif()
if (_option_CODE)
list (APPEND _installCmd ${_option_CODE})
endif()
if (NOT _option_SCRIPT)
list (APPEND _installCmd "Uninstall[link]")
endif()
<API key>(_cmd _option_SYSTEM_ID <API key>)
_add_script_or_code(_cmd _option_SCRIPT _installCmd)
else()
# run WSTP executable as front-end to Mathematica kernel
_add_launch_prefix(_cmd _option_SYSTEM_ID)
list (APPEND _cmd "$<TARGET_FILE:${_option_TARGET}>")
<API key>(_cmd "-wstp"
_option_SYSTEM_ID <API key> <API key>
_option_SCRIPT _option_CODE)
endif()
if (<API key>)
list (APPEND _cmd CONFIGURATIONS ${<API key>})
endif()
if (Mathematica_DEBUG)
message (STATUS "add_test: ${_cmd}")
endif()
add_test (${_cmd})
endfunction(<API key>)
endif (<API key> AND <API key>)
if (<API key> AND <API key>)
# public function to add target that creates C code from Mathematica code
function (<API key> _packageFile)
<API key>(<API key> ${_packageFile} NAME_WE)
<API key>(_packageFileName ${_packageFile} NAME)
<API key>(_packageFileAbs ${_packageFile} ABSOLUTE)
set(_options "")
set(_oneValueArgs "OUTPUT")
set(_multiValueArgs "DEPENDS")
<API key>(_option "${_options}" "${_oneValueArgs}" "${_multiValueArgs}" ${ARGN})
if(<API key>)
message (FATAL_ERROR "Unknown keywords: ${<API key>}")
endif()
if (_option_OUTPUT)
set (_cSource "${_option_OUTPUT}")
<API key>(_cHeaderBaseName ${_cSource} NAME_WE)
set (_cHeader "${_cHeaderBaseName}.h")
else()
set (_cSource "${_packageFileName}.c")
set (_cHeader "${_packageFileName}.h")
set (_cHeaderBaseName "${_packageFileName}")
endif()
<API key>(${_packageFileAbs} _packageFileAbsMma)
<API key>(${_cSource} _cSourceMma)
<API key>(${_cHeader} _cHeaderMma)
<API key>(${_cHeaderBaseName} _cHeaderBaseNameMma)
<API key>(${<API key>} <API key>)
string (REGEX REPLACE "\n|\t" "" _codeGenerate
"Module[{functions=Get[${_packageFileAbsMma}]},
If[ListQ[functions],
CompoundExpression[
CCodeGenerate[Sequence@@functions,${_cSourceMma},
\"CodeTarget\"->\"WolframRTL\",
\"HeaderName\"->${_cHeaderBaseNameMma},
\"<API key>\"->${<API key>}],
CCodeGenerate[Sequence@@functions,${_cHeaderMma},
\"CodeTarget\"->\"WolframRTLHeader\",
\"<API key>\"->${<API key>}]
]
]
]")
list (INSERT _codeGenerate 0 "Needs[\"CCodeGenerator`\"]")
set (_msg "Generating source ${_cSource} and header ${_cHeader} from ${_packageFile}")
list (INSERT _option_DEPENDS 0 "${_packageFileAbs}")
<API key>(
OUTPUT "${_cSource}" "${_cHeader}"
CODE ${_codeGenerate}
DEPENDS ${_option_DEPENDS}
COMMENT "${_msg}")
<API key>("${_cSource}" "${_cHeader}"
PROPERTIES GENERATED TRUE LABELS "Mathematica")
endfunction(<API key>)
# public function to simplify testing WolframLibrary targets
function (<API key>)
set(_options "")
set(_oneValueArgs NAME SCRIPT TARGET INPUT INPUT_FILE SYSTEM_ID)
set(_multiValueArgs CODE CONFIGURATIONS KERNEL_OPTIONS)
<API key>(_option "${_options}" "${_oneValueArgs}" "${_multiValueArgs}" ${ARGN})
if(<API key>)
message (FATAL_ERROR "Unknown keywords: ${<API key>}")
elseif (NOT _option_TARGET)
message (FATAL_ERROR "Mandatory parameter TARGET is missing.")
elseif (NOT _option_NAME)
message (FATAL_ERROR "Mandatory parameter NAME is missing.")
elseif (NOT _option_CODE AND NOT _option_SCRIPT)
message (FATAL_ERROR "Either the keyword CODE or SCRIPT must be present.")
endif()
set (_cmd NAME "${_option_NAME}" COMMAND)
_add_test_driver(_cmd "${_option_NAME}" _option_INPUT _option_INPUT_FILE)
# run Mathematica kernel and load Wolfram library
if (CYGWIN OR MSYS)
get_target_property (_targetFile ${_option_TARGET} LOCATION)
<API key>("${_targetFile}" _targetFileMma)
else()
set (_targetFileMma "\"$<TARGET_FILE:${_option_TARGET}>\"")
endif()
set (_installCmd
"libPath = ${_targetFileMma}"
"LibraryLoad[libPath]"
"Print[LibraryLink`$LibraryError]" )
if (_option_CODE)
list (APPEND _installCmd ${_option_CODE})
endif()
if (NOT _option_SCRIPT)
list (APPEND _installCmd "LibraryUnload[libPath]")
endif()
<API key>(_cmd _option_SYSTEM_ID <API key>)
_add_script_or_code(_cmd _option_SCRIPT _installCmd)
if (<API key>)
list (APPEND _cmd CONFIGURATIONS ${<API key>})
endif()
if (Mathematica_DEBUG)
message (STATUS "add_test: ${_cmd}")
endif()
add_test (${_cmd})
endfunction(<API key>)
endif (<API key> AND <API key>)
if (<API key>)
# public function that sets dynamic library names according to LibraryLink naming conventions
function (<API key>)
set (_haveProperties False)
foreach (_libraryName ${ARGV})
if ("${_libraryName}" STREQUAL "PROPERTIES")
set (_haveProperties True)
break()
endif()
<API key> (${_libraryName} PROPERTIES PREFIX "")
if (WIN32 OR CYGWIN)
<API key> (${_libraryName} PROPERTIES SUFFIX ".dll")
elseif (APPLE)
<API key> (${_libraryName} PROPERTIES SUFFIX ".dylib")
elseif (UNIX)
<API key> (${_libraryName} PROPERTIES SUFFIX ".so")
endif()
<API key> (${_libraryName} PROPERTIES LABELS "Mathematica")
if (CYGWIN AND <API key>)
# Mathematica kernel cannot load Cygwin generated libraries linked with Cygwin runtime DLL
# a work-around is to use the -mno-cygwin flag, which is only supported by gcc 3.x, not by gcc 4.x
if (NOT "${<API key>}" VERSION_LESS "3.0.0" AND "${<API key>}" VERSION_LESS "4.0.0")
<API key> (${_libraryName} PROPERTIES COMPILE_OPTIONS "-mno-cygwin")
<API key> (${_libraryName} PROPERTIES LINK_FLAGS "-mno-cygwin")
endif()
endif()
endforeach()
if (_haveProperties)
<API key> (${ARGV})
endif()
endfunction(<API key>)
# public function for creating dynamic library loadable with LibraryLink
function (<API key> _libraryName)
add_library (${_libraryName} MODULE ${ARGN})
<API key>(${_libraryName})
endfunction()
endif (<API key>)
if (<API key>)
# public function for creating source file from template file using mprep
function (<API key> _templateFile)
<API key>(_templateFileName ${_templateFile} NAME)
<API key>(_templateFileAbs ${_templateFile} ABSOLUTE)
set(_options LINE_DIRECTIVES)
set(_oneValueArgs OUTPUT CUSTOM_HEADER CUSTOM_TRAILER)
set(_multiValueArgs "")
<API key>(_option "${_options}" "${_oneValueArgs}" "${_multiValueArgs}" ${ARGN})
if(<API key>)
message (FATAL_ERROR "Unknown keywords: ${<API key>}")
endif()
if (_option_OUTPUT)
set (_outfile ${_option_OUTPUT})
else()
<API key>("${_templateFile}" _outfile)
endif()
_to_native_path ("${<API key>}" _mprepExeNative)
_to_native_path ("${_outfile}" _outfileNative)
set (_command "${_mprepExeNative}" "-o" "${_outfileNative}")
set (_dependencies "${<API key>}")
if (<API key>)
_to_native_path ("${<API key>}" _customHeaderNative)
list (APPEND _command "-h" "${_customHeaderNative}")
list (APPEND _dependencies "${<API key>}")
endif()
if (<API key>)
_to_native_path ("${<API key>}" <API key>)
list (APPEND _command "-t" "${<API key>}")
list (APPEND _dependencies "${<API key>}")
endif()
if (<API key>)
list (APPEND _command "-lines")
else()
list (APPEND _command "-nolines")
endif()
if (CYGWIN)
# under Cygwin invoke mprep.exe with template file argument specified as
# a relative path because it cannot handle absolute Cygwin UNIX paths
file (RELATIVE_PATH _templateFileRel ${<API key>} ${_templateFileAbs})
list (APPEND _command "${_templateFileRel}")
else()
_to_native_path ("${_templateFileAbs}" <API key>)
list (APPEND _command "${<API key>}")
endif()
set (_msg "Generating MathLink source ${_outfile} from ${_templateFileName}")
add_custom_command(
OUTPUT ${_outfile}
COMMAND ${_command}
MAIN_DEPENDENCY ${_templateFileAbs}
DEPENDS ${_dependencies}
WORKING_DIRECTORY ${<API key>}
COMMENT ${_msg}
VERBATIM)
<API key>(${_outfile} PROPERTIES GENERATED TRUE LABELS "Mathematica")
endfunction(<API key>)
# public function for creating MathLink executable from template file and source files
function (<API key> _executableName _templateFile)
<API key>(${_templateFile} _outfile)
<API key>(${_templateFile} OUTPUT ${_outfile})
add_executable (${_executableName} WIN32 ${_outfile} ${ARGN})
<API key>(${_executableName} PRIVATE ${<API key>})
if (<API key>)
<API key>(${_executableName} PROPERTIES LINK_FLAGS "${<API key>}")
endif()
<API key> (${_executableName} PROPERTIES LABELS "Mathematica")
endfunction()
# public function for exporting standard mprep header and trailer code
function (<API key>)
set(_options FORCE)
set(_oneValueArgs OUTPUT_DIRECTORY SYSTEM_ID)
set(_multiValueArgs "")
<API key>(_option "${_options}" "${_oneValueArgs}" "${_multiValueArgs}" ${ARGN})
if (NOT <API key>)
set (<API key> "${<API key>}")
endif()
if (NOT _option_SYSTEM_ID)
set (_option_SYSTEM_ID "${<API key>}")
endif()
set (_headerFileName "${<API key>}/mprep_header_${_option_SYSTEM_ID}.txt")
set (_trailerFileName "${<API key>}/mprep_trailer_${_option_SYSTEM_ID}.txt")
if (NOT _option_FORCE AND
EXISTS "${_headerFileName}" AND EXISTS "${_trailerFileName}")
message (STATUS "Mprep header file mprep_header_${_option_SYSTEM_ID}.txt already exists")
message (STATUS "Mprep trailer file mprep_trailer_${_option_SYSTEM_ID}.txt already exists")
return()
endif()
if (WIN32)
set (_input_file "NUL")
else()
set (_input_file "/dev/null")
endif()
execute_process(
COMMAND "${<API key>}"
WORKING_DIRECTORY ${<API key>}
INPUT_FILE "${_input_file}"
OUTPUT_VARIABLE _mprep_frame
<API key>)
# prevent CMake from interpreting ; as a list separator
string (REPLACE ";" "\\;" _mprep_frame "${_mprep_frame}")
string (REPLACE "\n" ";" _mprep_frame "${_mprep_frame}")
set (_header "")
set (_trailer "")
foreach (_line IN LISTS _mprep_frame)
if ("${_line}" MATCHES "MPREP_REVISION ([0-9]+)")
set (_mprep_revision "${CMAKE_MATCH_1}")
set (_appendToVar _header)
elseif ("${_line}" MATCHES "/.*end header.*/")
unset (_appendToVar)
elseif ("${_line}" MATCHES "/.*begin trailer.*/")
set (_appendToVar _trailer)
elseif (DEFINED _appendToVar)
set (${_appendToVar} "${${_appendToVar}}${_line}\n")
endif()
endforeach()
if ("${_header}" MATCHES ".+")
message (STATUS "Mprep header revision ${_mprep_revision} exported to ${_headerFileName}")
file (WRITE "${_headerFileName}" "${_header}")
endif()
if ("${_trailer}" MATCHES ".+")
message (STATUS "Mprep trailer revision ${_mprep_revision} exported to ${_trailerFileName}")
file (WRITE "${_trailerFileName}" "${_trailer}")
endif()
endfunction(<API key>)
endif (<API key>)
if (<API key>)
# public function for creating source file from template file using mprep
function (<API key> _templateFile)
<API key>(_templateFileName ${_templateFile} NAME)
<API key>(_templateFileAbs ${_templateFile} ABSOLUTE)
set(_options LINE_DIRECTIVES)
set(_oneValueArgs OUTPUT CUSTOM_HEADER CUSTOM_TRAILER)
set(_multiValueArgs "")
<API key>(_option "${_options}" "${_oneValueArgs}" "${_multiValueArgs}" ${ARGN})
if(<API key>)
message (FATAL_ERROR "Unknown keywords: ${<API key>}")
endif()
if (_option_OUTPUT)
set (_outfile ${_option_OUTPUT})
else()
<API key>("${_templateFile}" _outfile)
endif()
_to_native_path ("${<API key>}" _mprepExeNative)
_to_native_path ("${_outfile}" _outfileNative)
set (_command "${_mprepExeNative}" "-o" "${_outfileNative}")
set (_dependencies "${<API key>}")
if (<API key>)
_to_native_path ("${<API key>}" _customHeaderNative)
list (APPEND _command "-h" "${_customHeaderNative}")
list (APPEND _dependencies "${<API key>}")
endif()
if (<API key>)
_to_native_path ("${<API key>}" <API key>)
list (APPEND _command "-t" "${<API key>}")
list (APPEND _dependencies "${<API key>}")
endif()
if (<API key>)
list (APPEND _command "-lines")
else()
list (APPEND _command "-nolines")
endif()
if (CYGWIN)
# under Cygwin invoke mprep.exe with template file argument specified as
# a relative path because it cannot handle absolute Cygwin UNIX paths
file (RELATIVE_PATH _templateFileRel ${<API key>} ${_templateFileAbs})
list (APPEND _command "${_templateFileRel}")
else()
_to_native_path ("${_templateFileAbs}" <API key>)
list (APPEND _command "${<API key>}")
endif()
set (_msg "Generating WSTP source ${_outfile} from ${_templateFileName}")
add_custom_command(
OUTPUT ${_outfile}
COMMAND ${_command}
MAIN_DEPENDENCY ${_templateFileAbs}
DEPENDS ${_dependencies}
WORKING_DIRECTORY ${<API key>}
COMMENT ${_msg}
VERBATIM)
<API key>(${_outfile} PROPERTIES GENERATED TRUE LABELS "Mathematica")
endfunction(<API key>)
# public function for creating WSTP executable from template file and source files
function (<API key> _executableName _templateFile)
<API key>("${_templateFile}" _outfile)
<API key>(${_templateFile} OUTPUT ${_outfile})
add_executable (${_executableName} WIN32 ${_outfile} ${ARGN})
<API key>(${_executableName} PRIVATE ${<API key>})
if (<API key>)
<API key>(${_executableName} PROPERTIES LINK_FLAGS "${<API key>}")
endif()
<API key> (${_executableName} PROPERTIES LABELS "Mathematica")
endfunction()
# public function for exporting standard mprep header and trailer code
function (<API key>)
set(_options FORCE)
set(_oneValueArgs OUTPUT_DIRECTORY SYSTEM_ID)
set(_multiValueArgs "")
<API key>(_option "${_options}" "${_oneValueArgs}" "${_multiValueArgs}" ${ARGN})
if (NOT <API key>)
set (<API key> "${<API key>}")
endif()
if (NOT _option_SYSTEM_ID)
set (_option_SYSTEM_ID "${<API key>}")
endif()
set (_headerFileName "${<API key>}/wsprep_header_${_option_SYSTEM_ID}.txt")
set (_trailerFileName "${<API key>}/wsprep_trailer_${_option_SYSTEM_ID}.txt")
if (NOT _option_FORCE AND
EXISTS "${_headerFileName}" AND EXISTS "${_trailerFileName}")
message (STATUS "wsprep header file wsprep_header_${_option_SYSTEM_ID}.txt already exists")
message (STATUS "wsprep trailer file wsprep_trailer_${_option_SYSTEM_ID}.txt already exists")
return()
endif()
if (WIN32)
set (_input_file "NUL")
else()
set (_input_file "/dev/null")
endif()
execute_process(
COMMAND "${<API key>}"
WORKING_DIRECTORY ${<API key>}
INPUT_FILE "${_input_file}"
OUTPUT_VARIABLE _wsprep_frame
<API key>)
# prevent CMake from interpreting ; as a list separator
string (REPLACE ";" "\\;" _wsprep_frame "${_wsprep_frame}")
string (REPLACE "\n" ";" _wsprep_frame "${_wsprep_frame}")
set (_header "")
set (_trailer "")
foreach (_line IN LISTS _wsprep_frame)
if ("${_line}" MATCHES "PREP_REVISION ([0-9]+)")
set (_wsprep_revision "${CMAKE_MATCH_1}")
set (_appendToVar _header)
elseif ("${_line}" MATCHES "/.*end header.*/")
unset (_appendToVar)
elseif ("${_line}" MATCHES "/.*begin trailer.*/")
set (_appendToVar _trailer)
elseif (DEFINED _appendToVar)
set (${_appendToVar} "${${_appendToVar}}${_line}\n")
endif()
endforeach()
if ("${_header}" MATCHES ".+")
message (STATUS "wsprep header revision ${_wsprep_revision} exported to ${_headerFileName}")
file (WRITE "${_headerFileName}" "${_header}")
endif()
if ("${_trailer}" MATCHES ".+")
message (STATUS "wsprep trailer revision ${_wsprep_revision} exported to ${_trailerFileName}")
file (WRITE "${_trailerFileName}" "${_trailer}")
endif()
endfunction(<API key>)
endif (<API key>)
if (<API key>)
# public function for resolving a TestSuite declaration in a Mathematica unit test file
function (<API key> _var)
set(_options "")
set(_oneValueArgs RELATIVE)
set(_multiValueArgs "")
<API key>(_option "${_options}" "${_oneValueArgs}" "${_multiValueArgs}" ${ARGN})
set (${_var} "")
foreach (_testSuiteFile IN LISTS <API key>)
# parse test file names from TestSuite[{ ... }]
file (STRINGS "${_testSuiteFile}" _testSuite NEWLINE_CONSUME)
if ("${_testSuite}" MATCHES "TestSuite\\[")
string (REPLACE "\n" "" _testSuite "${_testSuite}")
string (REGEX REPLACE ".*TestSuite\\[.*{(.*)}.*\\].*" "\\1" _testSuite "${_testSuite}")
string (REPLACE "," ";" _testSuite "${_testSuite}")
<API key>(_testSuiteDir "${_testSuiteFile}" DIRECTORY)
foreach (_testSuiteItem IN LISTS _testSuite)
# parse quoted test file name
string (REGEX REPLACE "[^\"]*\"(.*)\"[^\"]*" "\\1" _testSuiteItem "${_testSuiteItem}")
_to_cmake_path("${_testSuiteDir}/${_testSuiteItem}" _testFile)
if (_option_RELATIVE)
file (RELATIVE_PATH _testFile "${_option_RELATIVE}" "${_testFile}")
endif()
list (APPEND ${_var} "${_testFile}")
endforeach()
else()
# not a test suite file, return test suite file path itself
<API key>(_testSuiteFile "${_testSuiteFile}" ABSOLUTE)
if (_option_RELATIVE)
file (RELATIVE_PATH _testSuiteFile "${_option_RELATIVE}" "${_testSuiteFile}")
endif()
list (APPEND ${_var} "${_testSuiteFile}")
endif()
endforeach()
list (REMOVE_DUPLICATES ${_var})
set (${_var} "${${_var}}" PARENT_SCOPE)
endfunction()
# public function for adding a CMake test that runs a Mathematica MUnit test file or notebook
function (<API key>)
set(_options "")
set(_oneValueArgs NAME LOGGERS SCRIPT INPUT INPUT_FILE TIMEOUT SYSTEM_ID)
set(_multiValueArgs CODE CONFIGURATIONS KERNEL_OPTIONS)
<API key>(_option "${_options}" "${_oneValueArgs}" "${_multiValueArgs}" ${ARGN})
if(<API key>)
message (FATAL_ERROR "Unknown keywords: ${<API key>}")
elseif (NOT _option_NAME)
message (FATAL_ERROR "Mandatory parameter NAME is missing.")
elseif (NOT _option_SCRIPT)
message (FATAL_ERROR "Mandatory parameter SCRIPT is missing.")
endif()
set (_cmd NAME "${_option_NAME}" COMMAND)
_add_test_driver(_cmd "${_option_NAME}" _option_INPUT _option_INPUT_FILE)
if (NOT _option_LOGGERS)
# default to VerbosePrintLogger which prints detailed information for failed tests
set (_option_LOGGERS "{VerbosePrintLogger[]}")
endif()
set (_testCmds "If[Needs[\"MUnit`\"]===$Failed,Exit[]]")
if (_option_CODE)
list (APPEND _testCmds ${_option_CODE})
endif()
if (IS_ABSOLUTE "${_option_SCRIPT}")
_to_cmake_path("${_option_SCRIPT}" _testScript)
else()
_to_cmake_path("${<API key>}/${_option_SCRIPT}" _testScript)
endif()
<API key>(_testScriptExt "${_testScript}" EXT)
<API key>(_testScriptDir "${_testScript}" DIRECTORY)
<API key>("${_option_NAME}" _testNameMma)
if ("${_testScriptExt}" MATCHES "\\.(nb|cdf)$")
# notebook test run requires Mathematica front end
if (DEFINED Mathematica_VERSION)
if ("${Mathematica_VERSION}" VERSION_LESS "7.0")
# default to using undocumented function Developer`UseFrontEnd
# available in Mathematica 5.1 and newer
set (_useFrontEndFunc "Developer`UseFrontEnd")
else()
# documented function UsingFrontEnd available since Mathematica 7
set (_useFrontEndFunc "UsingFrontEnd")
endif()
endif()
<API key>("${_testScript}" _testScriptMma)
string (REGEX REPLACE "\n|\t" "" _testCmd
"${_useFrontEndFunc}[
CompoundExpression[
nb=NotebookOpen[${_testScriptMma},Visible->False],
mUnitResult=TestRun[nb,TestRunTitle->${_testNameMma},Loggers:>${_option_LOGGERS}],
NotebookClose[nb]]]")
list (APPEND _testCmds "${_testCmd}")
else()
<API key>(_testFiles "${_testScript}")
<API key>("${_testFiles}" _testFilesMma)
list (LENGTH _testFiles _fileCount)
if (_fileCount GREATER 1)
if (DEFINED Mathematica_VERSION)
if ("${Mathematica_VERSION}" VERSION_LESS "7.0")
# default to using DirectoryName
set (_titleExtractFunc "StringDrop[#,StringLength[DirectoryName[#]]]")
else()
# function FileNameTake available since Mathematica 7
set (_titleExtractFunc "FileNameTake[
endif()
endif()
<API key>("${_testScriptDir}" _testScriptDirMma)
string (REGEX REPLACE "\n|\t" "" _testCmd
"mUnitResult=And@@Map[
TestRun[#,TestRunTitle->${_titleExtractFunc},Loggers:>${_option_LOGGERS}]&,
${_testFilesMma}]")
else()
string (REGEX REPLACE "\n|\t" "" _testCmd
"mUnitResult=TestRun[
${_testFilesMma},TestRunTitle->${_testNameMma},Loggers:>${_option_LOGGERS}]")
endif()
list (APPEND _testCmds "${_testCmd}")
endif()
# use MUnit TestRun result as exit code to signal CTest success or failure
list (APPEND _testCmds "Exit[Boole[Not[mUnitResult]]]")
<API key>(_cmd _option_SYSTEM_ID <API key>)
_add_script_or_code(_cmd _noScript _testCmds)
if (<API key>)
list (APPEND _cmd CONFIGURATIONS ${<API key>})
endif()
if (Mathematica_DEBUG)
message (STATUS "add_test: ${_cmd}")
endif()
add_test (${_cmd})
set_property (TEST ${_option_NAME} PROPERTY LABELS "Mathematica")
if (_option_TIMEOUT)
<API key> (${_option_NAME} PROPERTIES TIMEOUT ${_option_TIMEOUT})
endif()
endfunction (<API key>)
endif (<API key>)
if (<API key> AND <API key>)
# public function for adding a target which builds Mathematica documentation
function (<API key> _targetName)
# documentation build requires Apache Ant
if (CMAKE_HOST_WIN32)
set (_antExecutableName "ant.bat")
else()
set (_antExecutableName "ant")
endif()
find_program(<API key> "${_antExecutableName}" PATHS ENV ANT_HOME PATH_SUFFIXES "bin")
if (NOT <API key>)
message (WARNING "Mathematica documentation build required Apache Ant executable \"ant\" cannot be found.")
endif()
# find DocumentationBuild package
<API key>(<API key> "DocumentationBuild`"
DOC "Mathematica DocumentationBuild package.")
if (NOT <API key>)
message (STATUS "Mathematica documentation build required package \"DocumentationBuild`\" cannot be found.")
endif()
<API key>(<API key>
"${<API key>}")
# find Transmogrify package required by DocumentationBuild package
<API key>(<API key> "Transmogrify`"
DOC "Mathematica Transmogrify package.")
if (NOT <API key>)
message (STATUS "Mathematica documentation build required package \"Transmogrify`\" cannot be found.")
endif()
mark_as_advanced(
<API key>
<API key>
<API key>
)
# build command from options
set(_options "ALL" "CHECK_TIMESTAMPS" "INCLUDE_NOTEBOOKS")
set(_oneValueArgs DOCUMENTATION_TYPE INPUT_DIRECTORY OUTPUT_DIRECTORY APPLICATION_NAME LANGUAGE COMMENT JAVACMD)
set(_multiValueArgs SOURCES)
<API key>(_option "${_options}" "${_oneValueArgs}" "${_multiValueArgs}" ${ARGN})
if(<API key>)
message (FATAL_ERROR "Unknown keywords: ${<API key>}")
endif()
if (NOT <API key>)
set (<API key> "Notebook")
endif()
if (NOT <API key>)
set (<API key> "${PROJECT_NAME}")
endif()
if (NOT _option_LANGUAGE)
set (_option_LANGUAGE "English")
endif()
if (NOT <API key>)
set (<API key> "${<API key>}")
endif()
if (NOT _option_JAVACMD)
if (<API key>)
set (_option_JAVACMD "${<API key>}")
elseif (<API key>)
set (_option_JAVACMD "${<API key>}")
else()
if (CMAKE_HOST_WIN32)
set (_option_JAVACMD "java.exe")
else()
set (_option_JAVACMD "java")
endif()
endif()
endif()
if (NOT <API key>)
if (<API key> STREQUAL "Notebook")
set (<API key>
"${<API key>}/${<API key>}/Documentation")
else()
set (<API key>
"${<API key>}/${<API key>}-${<API key>}")
endif()
endif()
if (NOT _option_COMMENT)
set (_option_COMMENT
"Building ${<API key>} Mathematica ${<API key>} documentation")
endif()
# set up custom target
set (_cmd "${_targetName}")
if (_option_ALL)
list (APPEND _cmd ALL)
endif()
if (<API key> AND
<API key> AND
<API key>)
# set up documentation generation script if all requirements are met
set (<API key> "${<API key>}/<API key>.cmake.in")
set (_buildScriptName "${<API key>}Mathematica${<API key>}DocumentationBuild.cmake")
if (NOT EXISTS "${<API key>}")
message (FATAL_ERROR "FindMathematica documentation build script template ${<API key>} is missing.")
endif()
configure_file("${<API key>}" "${_buildScriptName}" @ONLY)
list (APPEND _cmd COMMAND "${CMAKE_COMMAND}" "-P" "${<API key>}/${_buildScriptName}")
list (APPEND _cmd DEPENDS "${<API key>}/${_buildScriptName}")
else()
# just generate empty documentation directory and print message
list (APPEND _cmd COMMAND "${CMAKE_COMMAND}" "-E" "make_directory" "${<API key>}")
list (APPEND _cmd COMMAND "${CMAKE_COMMAND}" "-E" "echo" "Required Mathematica packages for documentation building are not available.")
endif()
list (APPEND _cmd WORKING_DIRECTORY "${<API key>}")
list (APPEND _cmd COMMENT ${_option_COMMENT} VERBATIM)
if (_option_SOURCES)
list (APPEND _cmd SOURCES ${_option_SOURCES})
endif()
if (<API key>)
|
/* Atmel Microcontroller Software Support */
/* modification, are permitted provided that the following condition is met: */
/* Atmel's name may not be used to endorse or promote products derived from */
/* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE */
/* DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT, */
/* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT */
/* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, */
/* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF */
/* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING */
/* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, */
/* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
#ifndef <API key>
#define <API key>
#if (defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__))
#define REG_RTC_CR (0x400E1860U) /**< \brief (RTC) Control Register */
#define REG_RTC_MR (0x400E1864U) /**< \brief (RTC) Mode Register */
#define REG_RTC_TIMR (0x400E1868U) /**< \brief (RTC) Time Register */
#define REG_RTC_CALR (0x400E186CU) /**< \brief (RTC) Calendar Register */
#define REG_RTC_TIMALR (0x400E1870U) /**< \brief (RTC) Time Alarm Register */
#define REG_RTC_CALALR (0x400E1874U) /**< \brief (RTC) Calendar Alarm Register */
#define REG_RTC_SR (0x400E1878U) /**< \brief (RTC) Status Register */
#define REG_RTC_SCCR (0x400E187CU) /**< \brief (RTC) Status Clear Command Register */
#define REG_RTC_IER (0x400E1880U) /**< \brief (RTC) Interrupt Enable Register */
#define REG_RTC_IDR (0x400E1884U) /**< \brief (RTC) Interrupt Disable Register */
#define REG_RTC_IMR (0x400E1888U) /**< \brief (RTC) Interrupt Mask Register */
#define REG_RTC_VER (0x400E188CU) /**< \brief (RTC) Valid Entry Register */
#else
#define REG_RTC_CR (*(RwReg*)0x400E1860U) /**< \brief (RTC) Control Register */
#define REG_RTC_MR (*(RwReg*)0x400E1864U) /**< \brief (RTC) Mode Register */
#define REG_RTC_TIMR (*(RwReg*)0x400E1868U) /**< \brief (RTC) Time Register */
#define REG_RTC_CALR (*(RwReg*)0x400E186CU) /**< \brief (RTC) Calendar Register */
#define REG_RTC_TIMALR (*(RwReg*)0x400E1870U) /**< \brief (RTC) Time Alarm Register */
#define REG_RTC_CALALR (*(RwReg*)0x400E1874U) /**< \brief (RTC) Calendar Alarm Register */
#define REG_RTC_SR (*(RoReg*)0x400E1878U) /**< \brief (RTC) Status Register */
#define REG_RTC_SCCR (*(WoReg*)0x400E187CU) /**< \brief (RTC) Status Clear Command Register */
#define REG_RTC_IER (*(WoReg*)0x400E1880U) /**< \brief (RTC) Interrupt Enable Register */
#define REG_RTC_IDR (*(WoReg*)0x400E1884U) /**< \brief (RTC) Interrupt Disable Register */
#define REG_RTC_IMR (*(RoReg*)0x400E1888U) /**< \brief (RTC) Interrupt Mask Register */
#define REG_RTC_VER (*(RoReg*)0x400E188CU) /**< \brief (RTC) Valid Entry Register */
#endif /* (defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */
#endif /* <API key> */
|
#ifndef MYENGINE_PLUGIN_H
#define MYENGINE_PLUGIN_H
#include "LibExport.hpp"
#include <string>
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
namespace MyEngine
{
class Kernel;
Representation of a plugin
class Plugin
{
public:
Initialize and load plugin
DEF_Export Plugin(const std::string &sFilename);
Copy existing plugin instance
DEF_Export Plugin(const Plugin &Other);
Unload a plugin
DEF_Export ~Plugin();
// Plugin implementation
public:
Query the plugin for its expected engine version
DEF_Export int getEngineVersion() const {
return <API key>();
}
Register the plugin to a kernel
DEF_Export void registerPlugin(Kernel &K) {
m_pfnRegisterPlugin(K);
}
private:
Too lazy to this now...
Plugin &operator =(const Plugin &Other);
Signature for the version query function
typedef int fnGetEngineVersion();
Signature for the plugin's registration function
typedef void fnRegisterPlugin(Kernel &);
#ifdef _WIN32
HMODULE m_hDLL; ///< Win32 DLL handle
#else
void *m_hDLL;
#endif
size_t *m_pDLLRefCount; ///< Number of references to the DLL
fnGetEngineVersion *<API key>; ///< Version query function
fnRegisterPlugin *m_pfnRegisterPlugin; ///< Plugin registration function
};
} // namespace MyEngine
#endif // MYENGINE_PLUGIN_H
|
/**@file
*
* @defgroup <API key> Types definitions for BLE support in SoftDevice handler.
* @{
* @ingroup softdevice_handler
* @brief This file contains the declarations of types required for BLE stack support. These
* types will be defined when the preprocessor define <API key> is defined.
*/
#ifndef <API key>
#define <API key>
#ifdef <API key>
#include <stdlib.h>
#include "nrf_ble.h"
#include "nrf_sdm.h"
#include "app_error.h"
#include "app_util.h"
#define <API key> (sizeof(ble_evt_t) + (<API key>)) /**< Size of BLE event message buffer. This will be provided to the SoftDevice while fetching an event. */
#define <API key> 0 /**< The size of the scheduler event used by SoftDevice handler when passing BLE events using the @ref app_scheduler. */
/**@brief Application stack event handler type. */
typedef void (*ble_evt_handler_t) (ble_evt_t * p_ble_evt);
/**@brief Function for registering for BLE events.
*
* @details The application should use this function to register for receiving BLE events from
* the SoftDevice. If the application does not call this function, then any BLE event
* that may be generated by the SoftDevice will NOT be fetched. Once the application has
* registered for the events, it is not possible to cancel the registration.
* However, it is possible to register a different function for handling the events at
* any point of time.
*
* @param[in] ble_evt_handler Function to be called for each received BLE event.
*
* @retval NRF_SUCCESS Successful registration.
* @retval NRF_ERROR_NULL Null pointer provided as input.
*/
uint32_t <API key>(ble_evt_handler_t ble_evt_handler);
#else
#define <API key> 0 /**< Since the BLE stack support is not required, this is equated to 0, so that the @ref softdevice_handler.h can compute the internal event buffer size without having to care for BLE events.*/
#define <API key> 0
#endif // <API key>
#endif // <API key>
|
package com.redhat.lightblue.migrator;
import java.util.Map;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.io.IOException;
import java.sql.SQLException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeType;
import com.fasterxml.jackson.databind.node.ArrayNode;
import org.apache.commons.lang.StringUtils;
import com.redhat.lightblue.client.LightblueClient;
import com.redhat.lightblue.client.request.data.DataFindRequest;
import com.redhat.lightblue.client.request.data.DataSaveRequest;
import com.redhat.lightblue.client.request.SortCondition;
import com.redhat.lightblue.client.response.LightblueResponse;
import com.redhat.lightblue.client.enums.SortDirection;
import com.redhat.lightblue.client.enums.ExpressionOperation;
import com.redhat.lightblue.client.expression.query.Query;
import com.redhat.lightblue.client.expression.query.ValueQuery;
import com.redhat.lightblue.client.projection.Projection;
import com.redhat.lightblue.client.projection.FieldProjection;
import static com.redhat.lightblue.client.projection.FieldProjection.<API key>;
import static com.redhat.lightblue.client.projection.FieldProjection.excludeField;
import static com.redhat.lightblue.client.expression.query.NaryLogicalQuery.and;
import static com.redhat.lightblue.client.expression.query.NaryLogicalQuery.or;
public class DefaultMigrator extends Migrator {
private static final Logger LOGGER=LoggerFactory.getLogger(DefaultMigrator.class);
protected static final int BATCH_SIZE = 64;
private LightblueClient sourceCli;
private LightblueClient destCli;
public DefaultMigrator(ThreadGroup grp) {
super(grp);
}
private LightblueClient getSourceCli() {
try {
if(sourceCli==null)
sourceCli=getLightblueClient(<API key>().getSourceConfigPath());
return sourceCli;
} catch (Exception e) {
LOGGER.error("Cannot get source cli:{}",e);
throw new RuntimeException("Cannot get source client:"+e);
}
}
private LightblueClient getDestCli() {
try {
if(destCli==null)
destCli=getLightblueClient(<API key>().<API key>());
return destCli;
} catch (Exception e) {
LOGGER.error("Cannot get dest cli:{}",e);
throw new RuntimeException("Cannot get dest client:"+e);
}
}
public List<JsonNode> getSourceDocuments() {
LOGGER.debug("Retrieving source docs");
try {
DataFindRequest sourceRequest = new DataFindRequest(<API key>().getSourceEntityName(),
<API key>().<API key>());
sourceRequest.where(new Query() {
public String toJson() {
return getMigrationJob().getQuery();
}
});
sourceRequest.select(<API key>("*"), excludeField("objectType"));
LOGGER.debug("Source docs retrieval req: {}",sourceRequest.getBody());
JsonNode[] results=getSourceCli().data(sourceRequest,JsonNode[].class);
LOGGER.debug("There are {} source docs",results.length);
return Arrays.asList(results);
} catch (Exception e) {
LOGGER.error("Error while retrieving source documents:{}",e);
throw new RuntimeException("Cannot retrieve source documents:"+e);
}
}
public List<JsonNode> <API key>(Collection<Identity> ids) {
try {
List<JsonNode> <API key> = new ArrayList<>();
if (ids == null || ids.isEmpty()) {
LOGGER.debug("Unable to fetch any destination documents as there are no source documents");
return <API key>;
}
List<Identity> batch=new ArrayList<>();
for(Identity id:ids) {
batch.add(id);
if(batch.size()>=BATCH_SIZE) {
<API key>(batch,<API key>);
batch.clear();
}
}
if(!batch.isEmpty()) {
<API key>(batch,<API key>);
}
return <API key>;
} catch (Exception e) {
LOGGER.error("Error while retrieving destination documents:{}",e);
throw new RuntimeException("Cannot retrieve destination documents:"+e);
}
}
private void <API key>(List<Identity> ids,List<JsonNode> dest)
throws Exception {
if(ids!=null&&!ids.isEmpty()) {
DataFindRequest destinationRequest = new DataFindRequest(<API key>().<API key>(),
<API key>().<API key>());
List<Query> requestConditions = new ArrayList<>();
for (Identity id:ids) {
List<Query> docConditions = new ArrayList<>();
int i=0;
for (String keyField : <API key>().<API key>()) {
Object v=id.get(i);
ValueQuery docQuery = new ValueQuery(keyField,ExpressionOperation.EQ,v==null?null:v.toString());
docConditions.add(docQuery);
i++;
}
requestConditions.add(and(docConditions));
}
destinationRequest.where(or(requestConditions));
destinationRequest.select(<API key>("*"), excludeField("objectType"));
LOGGER.debug("Fetching destination docs {}",destinationRequest.getBody());
JsonNode[] nodes=getDestCli().data(destinationRequest, JsonNode[].class);
if(nodes!=null) {
LOGGER.debug("There are {} destination docs",nodes.length);
for(JsonNode node:nodes)
dest.add(node);
}
}
}
/**
*
* @param sourceDocument
* @param destinationDocument
* @return list of inconsistent paths
*/
public List<String> compareDocs(JsonNode sourceDocument, JsonNode destinationDocument) {
List<String> inconsistentPaths = new ArrayList<>();
compareDocs(inconsistentPaths, sourceDocument, destinationDocument, null);
return inconsistentPaths;
}
//Recursive method
private void compareDocs(List<String> inconsistentPaths,
final JsonNode sourceDocument,
final JsonNode destinationDocument,
final String path) {
List<String> excludes = <API key>().<API key>();
if (excludes != null && excludes.contains(path)) {
return;
}
if (sourceDocument == null && destinationDocument == null) {
return;
} else if (sourceDocument == null || destinationDocument == null) {
inconsistentPaths.add(StringUtils.isEmpty(path) ? "*" : path);
return;
}
// for each field compare to destination
if (JsonNodeType.ARRAY.equals(sourceDocument.getNodeType())) {
if (!JsonNodeType.ARRAY.equals(destinationDocument.getNodeType())) {
inconsistentPaths.add(StringUtils.isEmpty(path) ? "*" : path);
return;
}
ArrayNode sourceArray = (ArrayNode) sourceDocument;
ArrayNode destinationArray = (ArrayNode) destinationDocument;
if (sourceArray.size() != destinationArray.size()) {
inconsistentPaths.add(StringUtils.isEmpty(path) ? "*" : path);
return;
}
// compare array contents
for (int x = 0; x < sourceArray.size(); x++) {
compareDocs(inconsistentPaths, sourceArray.get(x), destinationArray.get(x), path);
}
} else if (JsonNodeType.OBJECT.equals(sourceDocument.getNodeType())) {
if (!JsonNodeType.OBJECT.equals(destinationDocument.getNodeType())) {
inconsistentPaths.add(StringUtils.isEmpty(path) ? "*" : path);
return;
}
// compare object contents
Iterator<Map.Entry<String, JsonNode>> itr = sourceDocument.fields();
while (itr.hasNext()) {
Map.Entry<String, JsonNode> entry = itr.next();
compareDocs(inconsistentPaths, entry.getValue(), destinationDocument.get(entry.getKey()),
StringUtils.isEmpty(path) ? entry.getKey() : path + "." + entry.getKey());
}
} else if (!sourceDocument.asText().equals(destinationDocument.asText())) {
inconsistentPaths.add(StringUtils.isEmpty(path) ? "*" : path);
}
}
public List<LightblueResponse> save(List<JsonNode> docs) {
List<LightblueResponse> responses = new ArrayList<>();
List<JsonNode> batch=new ArrayList<>();
for(JsonNode doc:docs) {
batch.add(doc);
if(batch.size()>=BATCH_SIZE) {
responses.add(saveBatch(batch));
batch.clear();
}
}
if(!batch.isEmpty()) {
responses.add(saveBatch(batch));
}
return responses;
}
private LightblueResponse saveBatch(List<JsonNode> <API key>) {
// LightblueClient - save & overwrite documents
DataSaveRequest saveRequest = new DataSaveRequest(<API key>().<API key>(),
<API key>().<API key>());
saveRequest.create(<API key>.toArray());
List<Projection> projections = new ArrayList<>();
projections.add(new FieldProjection("*", false, true));
saveRequest.returns(projections);
return getDestCli().data(saveRequest);
}
}
|
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_20) on Wed Feb 09 11:30:56 EST 2011 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
ConfigData
</TITLE>
<META NAME="date" CONTENT="2011-02-09">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="ConfigData";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<A NAME="navbar_top"></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/ConfigData.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../net/sf/sketchel/ClipboardMolecule.html" title="class in net.sf.sketchel"><B>PREV CLASS</B></A>
<A HREF="../../../net/sf/sketchel/<API key>.html" title="class in net.sf.sketchel"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?net/sf/sketchel/ConfigData.html" target="_top"><B>FRAMES</B></A>
<A HREF="ConfigData.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<HR>
<H2>
<FONT SIZE="-1">
net.sf.sketchel</FONT>
<BR>
Class ConfigData</H2>
<PRE>
java.lang.Object
<IMG SRC="../../../resources/inherit.gif" ALT="extended by "><B>net.sf.sketchel.ConfigData</B>
</PRE>
<HR>
<DL>
<DT><PRE>public class <B>ConfigData</B><DT>extends java.lang.Object</DL>
</PRE>
<P>
<HR>
<P>
<A NAME="constructor_summary"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../net/sf/sketchel/ConfigData.html#ConfigData()">ConfigData</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../net/sf/sketchel/ConfigData.html#ConfigData(net.sf.sketchel.ConfigData)">ConfigData</A></B>(<A HREF="../../../net/sf/sketchel/ConfigData.html" title="class in net.sf.sketchel">ConfigData</A> cpy)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../net/sf/sketchel/ConfigData.html#ConfigData(java.lang.String)">ConfigData</A></B>(java.lang.String fn)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<A NAME="method_summary"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../net/sf/sketchel/ConfigData.html#addPolicy(net.sf.sketchel.RenderPolicy)">addPolicy</A></B>(<A HREF="../../../net/sf/sketchel/RenderPolicy.html" title="class in net.sf.sketchel">RenderPolicy</A> p)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../net/sf/sketchel/ConfigData.html#deletePolicy(int)">deletePolicy</A></B>(int N)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> boolean</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../net/sf/sketchel/ConfigData.html#fileExists()">fileExists</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../net/sf/sketchel/ConfigData.html#fullFN()">fullFN</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../net/sf/sketchel/RenderPolicy.html" title="class in net.sf.sketchel">RenderPolicy</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../net/sf/sketchel/ConfigData.html#getPolicy(int)">getPolicy</A></B>(int N)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../net/sf/sketchel/ConfigData.html#loadFile()">loadFile</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../net/sf/sketchel/ConfigData.html#numPolicies()">numPolicies</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../net/sf/sketchel/ConfigData.html#<API key>(java.awt.Color, java.awt.Color[], java.lang.String)"><API key></A></B>(java.awt.Color foreground,
java.awt.Color[] atomCols,
java.lang.String text)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../net/sf/sketchel/ConfigData.html#parseContent(net.sf.sketchel.TrivialDOM)">parseContent</A></B>(<A HREF="../../../net/sf/sketchel/TrivialDOM.html" title="class in net.sf.sketchel">TrivialDOM</A> xml)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../net/sf/sketchel/ConfigData.html#produceContent(net.sf.sketchel.TrivialDOM)">produceContent</A></B>(<A HREF="../../../net/sf/sketchel/TrivialDOM.html" title="class in net.sf.sketchel">TrivialDOM</A> xml)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../net/sf/sketchel/ConfigData.html#refresh()">refresh</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../net/sf/sketchel/ConfigData.html#saveFile()">saveFile</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../net/sf/sketchel/ConfigData.html#setPolicy(int, net.sf.sketchel.RenderPolicy)">setPolicy</A></B>(int N,
<A HREF="../../../net/sf/sketchel/RenderPolicy.html" title="class in net.sf.sketchel">RenderPolicy</A> p)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../net/sf/sketchel/ConfigData.html#useDefaults()">useDefaults</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<A NAME="<API key>.lang.Object"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="<API key>">
<TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD>
</TR>
</TABLE>
<P>
<A NAME="constructor_detail"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="ConfigData()"></A><H3>
ConfigData</H3>
<PRE>
public <B>ConfigData</B>()</PRE>
<DL>
</DL>
<HR>
<A NAME="ConfigData(java.lang.String)"></A><H3>
ConfigData</H3>
<PRE>
public <B>ConfigData</B>(java.lang.String fn)</PRE>
<DL>
</DL>
<HR>
<A NAME="ConfigData(net.sf.sketchel.ConfigData)"></A><H3>
ConfigData</H3>
<PRE>
public <B>ConfigData</B>(<A HREF="../../../net/sf/sketchel/ConfigData.html" title="class in net.sf.sketchel">ConfigData</A> cpy)</PRE>
<DL>
</DL>
<A NAME="method_detail"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="fullFN()"></A><H3>
fullFN</H3>
<PRE>
public java.lang.String <B>fullFN</B>()</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="fileExists()"></A><H3>
fileExists</H3>
<PRE>
public boolean <B>fileExists</B>()</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="numPolicies()"></A><H3>
numPolicies</H3>
<PRE>
public int <B>numPolicies</B>()</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getPolicy(int)"></A><H3>
getPolicy</H3>
<PRE>
public <A HREF="../../../net/sf/sketchel/RenderPolicy.html" title="class in net.sf.sketchel">RenderPolicy</A> <B>getPolicy</B>(int N)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="setPolicy(int, net.sf.sketchel.RenderPolicy)"></A><H3>
setPolicy</H3>
<PRE>
public void <B>setPolicy</B>(int N,
<A HREF="../../../net/sf/sketchel/RenderPolicy.html" title="class in net.sf.sketchel">RenderPolicy</A> p)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="addPolicy(net.sf.sketchel.RenderPolicy)"></A><H3>
addPolicy</H3>
<PRE>
public void <B>addPolicy</B>(<A HREF="../../../net/sf/sketchel/RenderPolicy.html" title="class in net.sf.sketchel">RenderPolicy</A> p)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="deletePolicy(int)"></A><H3>
deletePolicy</H3>
<PRE>
public void <B>deletePolicy</B>(int N)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="refresh()"></A><H3>
refresh</H3>
<PRE>
public void <B>refresh</B>()</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="loadFile()"></A><H3>
loadFile</H3>
<PRE>
public void <B>loadFile</B>()
throws java.io.IOException</PRE>
<DL>
<DD><DL>
<DT><B>Throws:</B>
<DD><CODE>java.io.IOException</CODE></DL>
</DD>
</DL>
<HR>
<A NAME="parseContent(net.sf.sketchel.TrivialDOM)"></A><H3>
parseContent</H3>
<PRE>
protected void <B>parseContent</B>(<A HREF="../../../net/sf/sketchel/TrivialDOM.html" title="class in net.sf.sketchel">TrivialDOM</A> xml)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="saveFile()"></A><H3>
saveFile</H3>
<PRE>
public void <B>saveFile</B>()
throws java.io.IOException</PRE>
<DL>
<DD><DL>
<DT><B>Throws:</B>
<DD><CODE>java.io.IOException</CODE></DL>
</DD>
</DL>
<HR>
<A NAME="produceContent(net.sf.sketchel.TrivialDOM)"></A><H3>
produceContent</H3>
<PRE>
protected void <B>produceContent</B>(<A HREF="../../../net/sf/sketchel/TrivialDOM.html" title="class in net.sf.sketchel">TrivialDOM</A> xml)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="useDefaults()"></A><H3>
useDefaults</H3>
<PRE>
public void <B>useDefaults</B>()</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="<API key>(java.awt.Color, java.awt.Color[], java.lang.String)"></A><H3>
<API key></H3>
<PRE>
public static void <B><API key></B>(java.awt.Color foreground,
java.awt.Color[] atomCols,
java.lang.String text)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="navbar_bottom"></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="<API key>"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/ConfigData.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../net/sf/sketchel/ClipboardMolecule.html" title="class in net.sf.sketchel"><B>PREV CLASS</B></A>
<A HREF="../../../net/sf/sketchel/<API key>.html" title="class in net.sf.sketchel"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?net/sf/sketchel/ConfigData.html" target="_top"><B>FRAMES</B></A>
<A HREF="ConfigData.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<HR>
</BODY>
</HTML>
|
from entity_reader import EntityReader
import textract
from dataset_importer.utils import <API key>
class RTFReader(EntityReader):
@staticmethod
def get_features(**kwargs):
directory = kwargs['directory']
for file_path in RTFReader.get_file_list(directory, 'rtf'):
try:
features = RTFReader.get_meta_features(file_path=file_path)
features['text'] = textract.process(file_path).decode('utf8')
features['_texta_id'] = file_path
yield features
except Exception as e:
<API key>(kwargs, e, file_path=file_path)
@staticmethod
def <API key>(**kwargs):
directory = kwargs['directory']
return RTFReader.count_documents(root_directory=directory, extension='rtf')
|
#include "<API key>.H"
#include "dictionary.H"
#include "specie.H"
// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //
const Foam::scalar Foam::<API key>::TrMax = 0.999;
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
Foam::<API key>::<API key>
(
const dictionary& dict
)
:
components_(),
properties_()
{
components_ = dict.toc();
properties_.setSize(components_.size());
forAll(components_, i)
{
if (dict.isDict(components_[i]))
{
properties_.set
(
i,
liquidProperties::New(dict.subDict(components_[i]))
);
}
else
{
properties_.set
(
i,
liquidProperties::New(components_[i])
);
}
}
}
Foam::<API key>::<API key>
(
const <API key>& lm
)
:
components_(lm.components_),
properties_(lm.properties_.size())
{
forAll(properties_, i)
{
properties_.set(i, lm.properties_(i)->clone());
}
}
// * * * * * * * * * * * * * * * * Selectors * * * * * * * * * * * * * * * * //
Foam::autoPtr<Foam::<API key>>
Foam::<API key>::New
(
const dictionary& <API key>
)
{
return autoPtr<<API key>>
(
new <API key>(<API key>)
);
}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
Foam::scalar Foam::<API key>::Tc(const scalarField& X) const
{
scalar vTc = 0.0;
scalar vc = 0.0;
forAll(properties_, i)
{
scalar x1 = X[i]*properties_[i].Vc();
vc += x1;
vTc += x1*properties_[i].Tc();
}
return vTc/vc;
}
Foam::scalar Foam::<API key>::Tpt(const scalarField& X) const
{
scalar Tpt = 0.0;
forAll(properties_, i)
{
Tpt += X[i]*properties_[i].Tt();
}
return Tpt;
}
Foam::scalar Foam::<API key>::pvInvert
(
const scalar p,
const scalarField& X
) const
{
// Set upper and lower bounds
scalar Thi = Tc(X);
scalar Tlo = Tpt(X);
// Check for critical and solid phase conditions
if (p >= pv(p, Thi, X))
{
return Thi;
}
else if (p < pv(p, Tlo, X))
{
WarningInFunction
<< "Pressure below triple point pressure: "
<< "p = " << p << " < Pt = " << pv(p, Tlo, X) << nl << endl;
return -1;
}
// Set initial guess
scalar T = (Thi + Tlo)*0.5;
while ((Thi - Tlo) > 1.0e-4)
{
if ((pv(p, T, X) - p) <= 0.0)
{
Tlo = T;
}
else
{
Thi = T;
}
T = (Thi + Tlo)*0.5;
}
return T;
}
Foam::scalar Foam::<API key>::Tpc(const scalarField& X) const
{
scalar Tpc = 0.0;
forAll(properties_, i)
{
Tpc += X[i]*properties_[i].Tc();
}
return Tpc;
}
Foam::scalar Foam::<API key>::Ppc(const scalarField& X) const
{
scalar Vc = 0.0;
scalar Zc = 0.0;
forAll(properties_, i)
{
Vc += X[i]*properties_[i].Vc();
Zc += X[i]*properties_[i].Zc();
}
return RR*Zc*Tpc(X)/Vc;
}
Foam::scalar Foam::<API key>::omega(const scalarField& X) const
{
scalar omega = 0.0;
forAll(properties_, i)
{
omega += X[i]*properties_[i].omega();
}
return omega;
}
Foam::scalarField Foam::<API key>::Xs
(
const scalar p,
const scalar Tg,
const scalar Tl,
const scalarField& Xg,
const scalarField& Xl
) const
{
scalarField Xs(Xl.size());
// Raoult's Law
forAll(Xs, i)
{
scalar Ti = min(TrMax*properties_[i].Tc(), Tl);
Xs[i] = properties_[i].pv(p, Ti)*Xl[i]/p;
}
return Xs;
}
Foam::scalar Foam::<API key>::W(const scalarField& X) const
{
scalar W = 0.0;
forAll(properties_, i)
{
W += X[i]*properties_[i].W();
}
return W;
}
Foam::scalarField Foam::<API key>::Y(const scalarField& X) const
{
scalarField Y(X.size());
scalar sumY = 0.0;
forAll(Y, i)
{
Y[i] = X[i]*properties_[i].W();
sumY += Y[i];
}
Y /= sumY;
return Y;
}
Foam::scalarField Foam::<API key>::X(const scalarField& Y) const
{
scalarField X(Y.size());
scalar sumX = 0.0;
forAll(X, i)
{
X[i] = Y[i]/properties_[i].W();
sumX += X[i];
}
X /= sumX;
return X;
}
Foam::scalar Foam::<API key>::rho
(
const scalar p,
const scalar T,
const scalarField& X
) const
{
scalar sumY = 0.0;
scalar v = 0.0;
forAll(properties_, i)
{
if (X[i] > small)
{
scalar Ti = min(TrMax*properties_[i].Tc(), T);
scalar rho = properties_[i].rho(p, Ti);
if (rho > small)
{
scalar Yi = X[i]*properties_[i].W();
sumY += Yi;
v += Yi/rho;
}
}
}
return sumY/v;
}
Foam::scalar Foam::<API key>::pv
(
const scalar p,
const scalar T,
const scalarField& X
) const
{
scalar sumY = 0.0;
scalar pv = 0.0;
forAll(properties_, i)
{
if (X[i] > small)
{
scalar Yi = X[i]*properties_[i].W();
sumY += Yi;
scalar Ti = min(TrMax*properties_[i].Tc(), T);
pv += Yi*properties_[i].pv(p, Ti);
}
}
return pv/sumY;
}
Foam::scalar Foam::<API key>::hl
(
const scalar p,
const scalar T,
const scalarField& X
) const
{
scalar sumY = 0.0;
scalar hl = 0.0;
forAll(properties_, i)
{
if (X[i] > small)
{
scalar Yi = X[i]*properties_[i].W();
sumY += Yi;
scalar Ti = min(TrMax*properties_[i].Tc(), T);
hl += Yi*properties_[i].hl(p, Ti);
}
}
return hl/sumY;
}
Foam::scalar Foam::<API key>::Cp
(
const scalar p,
const scalar T,
const scalarField& X
) const
{
scalar sumY = 0.0;
scalar Cp = 0.0;
forAll(properties_, i)
{
if (X[i] > small)
{
scalar Yi = X[i]*properties_[i].W();
sumY += Yi;
scalar Ti = min(TrMax*properties_[i].Tc(), T);
Cp += Yi*properties_[i].Cp(p, Ti);
}
}
return Cp/sumY;
}
Foam::scalar Foam::<API key>::sigma
(
const scalar p,
const scalar T,
const scalarField& X
) const
{
// sigma is based on surface mole fractions
// which are estimated from Raoult's Law
scalar sigma = 0.0;
scalarField Xs(X.size());
scalar XsSum = 0.0;
forAll(properties_, i)
{
scalar Ti = min(TrMax*properties_[i].Tc(), T);
scalar Pvs = properties_[i].pv(p, Ti);
Xs[i] = X[i]*Pvs/p;
XsSum += Xs[i];
}
Xs /= XsSum;
forAll(properties_, i)
{
if (Xs[i] > small)
{
scalar Ti = min(TrMax*properties_[i].Tc(), T);
sigma += Xs[i]*properties_[i].sigma(p, Ti);
}
}
return sigma;
}
Foam::scalar Foam::<API key>::mu
(
const scalar p,
const scalar T,
const scalarField& X
) const
{
scalar mu = 0.0;
forAll(properties_, i)
{
if (X[i] > small)
{
scalar Ti = min(TrMax*properties_[i].Tc(), T);
mu += X[i]*log(properties_[i].mu(p, Ti));
}
}
return exp(mu);
}
Foam::scalar Foam::<API key>::kappa
(
const scalar p,
const scalar T,
const scalarField& X
) const
{
// Calculate superficial volume fractions phii
scalarField phii(X.size());
scalar pSum = 0.0;
forAll(properties_, i)
{
scalar Ti = min(TrMax*properties_[i].Tc(), T);
scalar Vi = properties_[i].W()/properties_[i].rho(p, Ti);
phii[i] = X[i]*Vi;
pSum += phii[i];
}
phii /= pSum;
scalar K = 0.0;
forAll(properties_, i)
{
scalar Ti = min(TrMax*properties_[i].Tc(), T);
forAll(properties_, j)
{
scalar Tj = min(TrMax*properties_[j].Tc(), T);
scalar Kij =
2.0
/(
1.0/properties_[i].kappa(p, Ti)
+ 1.0/properties_[j].kappa(p, Tj)
);
K += phii[i]*phii[j]*Kij;
}
}
return K;
}
Foam::scalar Foam::<API key>::D
(
const scalar p,
const scalar T,
const scalarField& X
) const
{
// Blanc's law
scalar Dinv = 0.0;
forAll(properties_, i)
{
if (X[i] > small)
{
scalar Ti = min(TrMax*properties_[i].Tc(), T);
Dinv += X[i]/properties_[i].D(p, Ti);
}
}
return 1.0/Dinv;
}
|
package org.tomahawk.tomahawk_android.fragments;
import org.tomahawk.libtomahawk.collection.Album;
import org.tomahawk.libtomahawk.collection.Artist;
import org.tomahawk.libtomahawk.collection.Image;
import org.tomahawk.libtomahawk.collection.Playlist;
import org.tomahawk.libtomahawk.infosystem.InfoRequestData;
import org.tomahawk.libtomahawk.infosystem.InfoSystem;
import org.tomahawk.libtomahawk.infosystem.User;
import org.tomahawk.libtomahawk.infosystem.hatchet.Search;
import org.tomahawk.libtomahawk.infosystem.hatchet.SearchResult;
import org.tomahawk.libtomahawk.resolver.PipeLine;
import org.tomahawk.libtomahawk.resolver.Query;
import org.tomahawk.tomahawk_android.R;
import org.tomahawk.tomahawk_android.activities.<API key>;
import org.tomahawk.tomahawk_android.utils.FragmentInfo;
import org.tomahawk.tomahawk_android.utils.ThreadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.view.View;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public class SearchPagerFragment extends PagerFragment {
private String mCurrentQueryString;
protected final Set<Query> <API key>
= Collections.newSetFromMap(new ConcurrentHashMap<Query, Boolean>());
private final ArrayList<String> mAlbumIds = new ArrayList<>();
private final ArrayList<String> mArtistIds = new ArrayList<>();
private final ArrayList<String> mUserIds = new ArrayList<>();
private Playlist <API key>;
private <API key> <API key>;
private boolean mIsFirstBroadcast;
/**
* Handles incoming broadcasts.
*/
private class <API key> extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
boolean noConnectivity =
intent.getBooleanExtra(ConnectivityManager.<API key>, false);
if (!noConnectivity && !mIsFirstBroadcast) {
<API key>(mCurrentQueryString);
}
mIsFirstBroadcast = false;
}
}
}
@SuppressWarnings("unused")
public void onEventMainThread(PipeLine.ResultsEvent event) {
if (<API key>.contains(event.mQuery)) {
<API key> = event.mQuery.getResultPlaylist();
updatePager();
}
}
/**
* Restore the {@link String} inside the search {@link android.widget.TextView}. Either through
* the savedInstanceState {@link Bundle} or through the a {@link Bundle} provided in the
* Arguments.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null
&& savedInstanceState.containsKey(TomahawkFragment.QUERY_STRING)
&& savedInstanceState.getString(TomahawkFragment.QUERY_STRING) != null) {
mCurrentQueryString = savedInstanceState.getString(
TomahawkFragment.QUERY_STRING);
}
}
/**
* Called, when this {@link SearchPagerFragment}'s {@link android.view.View} has been created
*/
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
int initialPage = -1;
if (getArguments() != null) {
if (getArguments().containsKey(TomahawkFragment.<API key>)) {
initialPage = getArguments().getInt(TomahawkFragment.<API key>);
}
if (getArguments().containsKey(TomahawkFragment.QUERY_STRING)
&& getArguments().getString(TomahawkFragment.QUERY_STRING) != null) {
mCurrentQueryString = getArguments().getString(
TomahawkFragment.QUERY_STRING);
}
}
// If we have restored a CurrentQueryString, start searching, so that we show the proper
// results again
if (mCurrentQueryString != null) {
<API key>(mCurrentQueryString);
getActivity().setTitle(mCurrentQueryString);
}
showContentHeader(null);
updatePager(initialPage);
}
@Override
public void onStart() {
super.onStart();
// Initialize and register Receiver
if (<API key> == null) {
mIsFirstBroadcast = true;
<API key> = new <API key>();
IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
getActivity().registerReceiver(<API key>, intentFilter);
}
}
@Override
public void onPause() {
super.onPause();
for (Query query : <API key>) {
if (ThreadManager.get().stop(query)) {
<API key>.remove(query);
}
}
}
@Override
public void onStop() {
super.onStop();
if (<API key> != null) {
getActivity().unregisterReceiver(<API key>);
<API key> = null;
}
}
/**
* Save the {@link String} inside the search {@link android.widget.TextView}.
*/
@Override
public void onSaveInstanceState(Bundle out) {
out.putString(TomahawkFragment.QUERY_STRING, mCurrentQueryString);
super.onSaveInstanceState(out);
}
private void updatePager() {
updatePager(-1);
}
private void updatePager(int initialPage) {
List<FragmentInfoList> fragmentInfoLists = new ArrayList<>();
FragmentInfoList fragmentInfoList = new FragmentInfoList();
FragmentInfo fragmentInfo = new FragmentInfo();
fragmentInfo.mClass = ArtistsFragment.class;
fragmentInfo.mTitle = getString(R.string.artists);
fragmentInfo.mBundle = <API key>();
if (mArtistIds != null) {
fragmentInfo.mBundle
.putStringArrayList(TomahawkFragment.ARTISTARRAY, mArtistIds);
}
fragmentInfoList.addFragmentInfo(fragmentInfo);
fragmentInfoLists.add(fragmentInfoList);
fragmentInfoList = new FragmentInfoList();
fragmentInfo = new FragmentInfo();
fragmentInfo.mClass = AlbumsFragment.class;
fragmentInfo.mTitle = getString(R.string.albums);
fragmentInfo.mBundle = <API key>();
if (mAlbumIds != null) {
fragmentInfo.mBundle
.putStringArrayList(TomahawkFragment.ALBUMARRAY, mAlbumIds);
}
fragmentInfoList.addFragmentInfo(fragmentInfo);
fragmentInfoLists.add(fragmentInfoList);
fragmentInfoList = new FragmentInfoList();
fragmentInfo = new FragmentInfo();
fragmentInfo.mClass = <API key>.class;
fragmentInfo.mTitle = getString(R.string.songs);
fragmentInfo.mBundle = <API key>();
if (<API key> != null) {
fragmentInfo.mBundle
.putString(TomahawkFragment.PLAYLIST, <API key>.getId());
}
fragmentInfoList.addFragmentInfo(fragmentInfo);
fragmentInfoLists.add(fragmentInfoList);
fragmentInfoList = new FragmentInfoList();
fragmentInfo = new FragmentInfo();
fragmentInfo.mClass = UsersFragment.class;
fragmentInfo.mTitle = getString(R.string.users);
fragmentInfo.mBundle = <API key>();
if (mUserIds != null) {
fragmentInfo.mBundle
.putStringArrayList(TomahawkFragment.USERARRAY, mUserIds);
}
fragmentInfoList.addFragmentInfo(fragmentInfo);
fragmentInfoLists.add(fragmentInfoList);
setupPager(fragmentInfoLists, initialPage, null, 1);
}
/**
* Invoke the resolving process with the given fullTextQuery {@link String}
*/
public void <API key>(String fullTextQuery) {
((<API key>) getActivity()).closeDrawer();
<API key> = null;
mAlbumIds.clear();
mArtistIds.clear();
mUserIds.clear();
mCurrentQueryString = fullTextQuery;
<API key>.clear();
<API key>.add(InfoSystem.get().resolve(fullTextQuery));
Query query = PipeLine.get().resolve(fullTextQuery, false);
if (query != null) {
<API key>.clear();
<API key>.add(query);
}
}
@Override
protected void <API key>(InfoRequestData infoRequestData) {
List<Search> results = infoRequestData.getResultList(Search.class);
if (results != null && results.size() > 0) {
Search search = results.get(0);
float maxScore = 0f;
Image contentHeaderImage = null;
for (SearchResult result : search.getSearchResults()) {
Object resultObject = result.getResult();
if (resultObject instanceof Artist) {
Artist artist = (Artist) resultObject;
mArtistIds.add(artist.getCacheKey());
if (artist.getImage() != null && result.getScore() > maxScore) {
maxScore = result.getScore();
contentHeaderImage = artist.getImage();
}
} else if (resultObject instanceof Album) {
Album album = (Album) resultObject;
mAlbumIds.add(album.getCacheKey());
if (album.getImage() != null && result.getScore() > maxScore) {
maxScore = result.getScore();
contentHeaderImage = album.getImage();
}
} else if (resultObject instanceof User) {
User user = (User) resultObject;
mUserIds.add(user.getCacheKey());
if (user.getImage() != null && result.getScore() > maxScore) {
maxScore = result.getScore();
contentHeaderImage = user.getImage();
}
}
}
showContentHeader(contentHeaderImage);
}
updatePager();
}
}
|
#endregion
namespace WebSocketSharp.Frame
{
public enum Rsv : byte
{
OFF = 0x0,
ON = 0x1
}
}
|
<?php if (!defined ('ABSPATH')) die ('No direct access allowed'); ?>
<ul <?php echo $class ?>>
<li><a <?php if ($sub == '') echo 'class="current"'; ?>href="<?php echo $url ?>"><?php _e ('Forms', 'filled-in') ?></a><?php echo $trail; ?></li>
<li><a <?php if ($sub == 'templates') echo 'class="current"'; ?>href="<?php echo $url ?>&sub=templates"><?php _e ('Email Templates', 'filled-in') ?></a></li>
<?php if (current_user_can ('activate_plugins')) : ?>
<li><?php echo $trail; ?><a <?php if ($sub == 'reports') echo 'class="current"'; ?>href="<?php echo $url ?>&sub=reports"><?php _e ('Batch Processing', 'filled-in') ?></a><?php echo $trail; ?></li>
<li><a <?php if ($sub == 'options') echo 'class="current"'; ?>href="<?php echo $url ?>&sub=options"><?php _e ('Options', 'filled-in') ?></a></li>
<?php endif; ?>
</ul>
|
#include "StdInc.h"
char szVehicleName[50] = {'\0'};
char szZoneName[50] = {'\0'};
CHudSA::CHudSA(void)
{
InitComponentList();
// Set the default values
<API key> = 210.0f;
<API key> = (float*)<API key>;
MemPut<float>(<API key>, 192.0f);
<API key> = (float*)VAR_AspectRatioMult;
MemPut<float>(<API key>, 0.002232143f);
// Patch xrefs to 0x863B34, because this variable seems to be shared (2 other functions without any context access to it; probably a compiler optimization)
MemPut<DWORD>(0x58E7D4 + 2, (DWORD)&<API key>);
MemPut<DWORD>(0x58E7EA + 2, (DWORD)&<API key>);
MemPut<DWORD>(0x53E3ED + 2, (DWORD)&<API key>);
MemPut<DWORD>(0x53E41A + 2, (DWORD)&<API key>);
MemPut<DWORD>(0x53E488 + 2, (DWORD)&<API key>);
MemPut<DWORD>(0x53E4BF + 2, (DWORD)&<API key>);
}
VOID CHudSA::SetHelpMessage(char* szMessage)
{
DEBUG_TRACE("VOID CHudSA::SetHelpMessage( char * szMessage )");
wchar_t szHelp[255] = {'\0'};
MultiByteToWideChar(CP_ACP, 0, szMessage, -1, szHelp, 255);
DWORD dwFunction = FUNC_SetHelpMessage;
_asm
{
push 0
push 1
lea eax, szHelp
push eax
call dwFunction
add esp, 0xC
}
}
/**
* \todo Find out what param 2 is
*/
VOID CHudSA::SetBigMessage(char* szBigMessage)
{
DEBUG_TRACE("VOID CHudSA::SetBigMessage( char * szBigMessage )");
wchar_t wszBigMessage[255] = {'\0'};
MultiByteToWideChar(CP_ACP, 0, szBigMessage, -1, wszBigMessage, 255);
DWORD dwFunction = FUNC_SetBigMessage;
_asm
{
push 10 // what is this param?
lea eax, wszBigMessage
push eax
call dwFunction
add esp, 8
}
}
/**
* \todo Fix: doesn't work
*/
VOID CHudSA::SetVehicleName(char* szName)
{
DEBUG_TRACE("VOID CHudSA::SetVehicleName( char * szName )");
char* szVehicleNamePtr = (char*)VAR_VehicleNamePtr;
if (szName != 0)
{
// wchar_t szHelp[255] = {'\0'};
// MultiByteToWideChar(CP_ACP, 0, szMessage, -1, szHelp, 255);
if (strlen(szName) < 50)
{
strcpy(szVehicleName, szName);
szVehicleNamePtr = szVehicleName;
}
}
else
{
MemPutFast<DWORD>(VAR_VehicleNamePtr, 0);
}
}
/**
* \todo Fix: doesn't work
*/
VOID CHudSA::SetZoneName(char* szName)
{
DEBUG_TRACE("VOID CHudSA::SetZoneName( char * szName )");
char* szZoneNamePtr = (char*)VAR_ZoneNamePtr;
if (szName != 0)
{
if (strlen(szName) < 50)
{
strcpy(szZoneName, szName);
szZoneNamePtr = szZoneName;
}
}
else
{
MemPutFast<DWORD>(VAR_ZoneNamePtr, 0);
}
}
VOID CHudSA::Disable(bool bDisabled)
{
DEBUG_TRACE("VOID CHudSA::Disable ( bool bDisabled )");
if (bDisabled)
MemPut<BYTE>(FUNC_Draw, 0xC3);
else
MemPut<BYTE>(FUNC_Draw, 0x80);
// Also disable the radar as the above code will not hide it before the local player has spawned
if (bDisabled)
MemPut<BYTE>(FUNC_DrawRadarPlanB, 0xC3);
else
MemPut<BYTE>(FUNC_DrawRadarPlanB, 0x83);
}
bool CHudSA::IsDisabled(void)
{
return *(BYTE*)FUNC_Draw == 0xC3;
}
VOID CHudSA::DrawBarChart(float fX, float fY, DWORD dwWidth, DWORD dwHeight, float fPercentage, DWORD dwForeColor, DWORD dwBorderColor)
{
DWORD dwFunc = FUNC_DrawBarChart;
_asm
{
push dwBorderColor
push dwForeColor
push 1
push 0
push 0
push fPercentage
push dwHeight
push dwWidth
push fY
push fX
call dwFunc
add esp, 0x28
}
}
bool CHudSA::CalcScreenCoors(CVector* vecPosition1, CVector* vecPosition2, float* fX, float* fY, bool bSetting1, bool bSetting2)
{
DWORD dwFunc = 0x71DA00;
bool bReturn = false;
_asm
{
//push bSetting2
//push bSetting1
push fY
push fX
push vecPosition2
push vecPosition1
call dwFunc
add esp, 0x18
sub esp, 8
mov bReturn, al
}
return bReturn;
}
void CHudSA::Draw2DPolygon(float fX1, float fY1, float fX2, float fY2, float fX3, float fY3, float fX4, float fY4, DWORD dwColor)
{
DWORD dwFunc = FUNC_Draw2DPolygon;
_asm
{
lea eax, dwColor
push eax
push fY4
push fX4
push fY3
push fX3
push fY2
push fX2
push fY1
push fX1
call dwFunc
add esp, 36
}
}
// CHudSA::InitComponentList
void CHudSA::InitComponentList(void)
{
SHudComponent componentList[] = {
{1, HUD_AMMO, 1, FUNC_DrawAmmo, 1, 0xCC, 0xC3},
{1, HUD_WEAPON, 1, FUNC_DrawWeaponIcon, 1, 0xCC, 0xC3},
{1, HUD_HEALTH, 1, <API key>, 1, 0xCC, 0xC3},
{1, HUD_BREATH, 1, <API key>, 1, 0xCC, 0xC3},
{1, HUD_ARMOUR, 1, <API key>, 1, 0xCC, 0xC3},
{1, HUD_MONEY, 1, CODE_ShowMoney, 2, 0xCCCC, 0xE990},
{1, HUD_VEHICLE_NAME, 1, <API key>, 1, 0xCC, 0xC3},
{1, HUD_AREA_NAME, 1, FUNC_DrawAreaName, 1, 0xCC, 0xC3},
{1, HUD_RADAR, 1, FUNC_DrawRadar, 1, 0xCC, 0xC3},
{1, HUD_CLOCK, 0, VAR_DisableClock, 1, 1, 0},
{1, HUD_RADIO, 1, FUNC_DrawRadioName, 1, 0xCC, 0xC3},
{1, HUD_WANTED, 1, <API key>, 1, 0xCC, 0xC3},
{1, HUD_CROSSHAIR, 1, FUNC_DrawCrosshair, 1, 0xCC, 0xC3},
{1, HUD_VITAL_STATS, 1, FUNC_DrawVitalStats, 1, 0xCC, 0xC3},
{0, HUD_HELP_TEXT, 1, FUNC_DrawHelpText, 1, 0xCC, 0xC3},
};
for (uint i = 0; i < NUMELMS(componentList); i++)
{
const SHudComponent& component = componentList[i];
MapSet(m_HudComponentMap, component.type, component);
}
}
// CHudSA::SetComponentVisible
void CHudSA::SetComponentVisible(eHudComponent component, bool bVisible)
{
// Handle ALL option
if (component == HUD_ALL)
{
for (std::map<eHudComponent, SHudComponent>::iterator iter = m_HudComponentMap.begin(); iter != m_HudComponentMap.end(); ++iter)
{
const SHudComponent& component = iter->second;
if (component.bIsPartOfAll)
SetComponentVisible(component.type, bVisible);
}
return;
}
// Set visiblity of one component
SHudComponent* pComponent = MapFind(m_HudComponentMap, component);
if (pComponent)
{
// Save original bytes if requred
if (pComponent->bSaveOriginalBytes)
{
pComponent->origData = *(DWORD*)pComponent->uiDataAddr;
pComponent->bSaveOriginalBytes = false;
}
// Poke bytes
uchar* pSrc = (uchar*)(bVisible ? &pComponent->origData : &pComponent->disabledData);
uchar* pDest = (uchar*)(pComponent->uiDataAddr);
for (uint i = 0; i < pComponent->uiDataSize; i++)
{
if (pComponent->type != HUD_CLOCK)
MemPut<BYTE>(pDest + i, pSrc[i]);
else
MemPutFast<BYTE>(pDest + i, pSrc[i]);
}
}
}
// CHudSA::IsComponentVisible
bool CHudSA::IsComponentVisible(eHudComponent component)
{
SHudComponent* pComponent = MapFind(m_HudComponentMap, component);
if (pComponent)
{
// Determine if invisible by matching data with disabled values
uchar* pSrc = (uchar*)(&pComponent->disabledData);
uchar* pDest = (uchar*)(pComponent->uiDataAddr);
if (memcmp(pDest, pSrc, pComponent->uiDataSize) == 0)
return false; // Matches disabled bytes
return true;
}
return false;
}
// CHudSA::AdjustComponents
void CHudSA::AdjustComponents(float fAspectRatio)
{
// Fix for #7400 (HUD elements do not scale correctly for widescreen)
// 0x859524: GTA multiplies all HUD and menu transformation variables by this floating point value. It is equal to 1/448, so just translate it to 16/10 /
// 16/9
MemPut<float>(<API key>, 0.002232143f / (4.0f / 3.0f) * fAspectRatio);
// Set the sniper crosshair scale (fix for #7659)
<API key> = 210.0f * (4.0f / 3.0f) / fAspectRatio;
// Set the camera crosshair scale (same display flaw as in #7659)
MemPut<float>(<API key>, 192.0f * (4.0f / 3.0f) / fAspectRatio);
}
// CHudSA::<API key>
void CHudSA::<API key>(void)
{
// Restore default values (4:3 aspect ratio)
MemPut<float>(<API key>, 0.002232143f);
MemPut<float>(<API key>, 192.0f);
<API key> = 210.0f;
}
|
/**
* \file sha256.h
*
* \brief This file contains SHA-224 and SHA-256 definitions and functions.
*
* The Secure Hash Algorithms 224 and 256 (SHA-224 and SHA-256) cryptographic
* hash functions are defined in <em>FIPS 180-4: Secure Hash Standard (SHS)</em>.
*/
#ifndef MBEDTLS_SHA256_H
#define MBEDTLS_SHA256_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include <stddef.h>
#include <stdint.h>
/* <API key> is deprecated and should not be used. */
#define <API key> -0x0037 /**< SHA-256 hardware accelerator failed */
#define <API key> -0x0074 /**< SHA-256 input data was malformed. */
#ifdef __cplusplus
extern "C" {
#endif
#if !defined(MBEDTLS_SHA256_ALT)
// Regular implementation
/**
* \brief The SHA-256 context structure.
*
* The structure is used both for SHA-256 and for SHA-224
* checksum calculations. The choice between these two is
* made in the call to <API key>().
*/
typedef struct <API key>
{
uint32_t total[2]; /*!< The number of Bytes processed. */
uint32_t state[8]; /*!< The intermediate digest state. */
unsigned char buffer[64]; /*!< The data block being processed. */
int is224; /*!< Determines which function to use:
0: Use SHA-256, or 1: Use SHA-224. */
}
<API key>;
#else /* MBEDTLS_SHA256_ALT */
#include "sha256_alt.h"
#endif /* MBEDTLS_SHA256_ALT */
/**
* \brief This function initializes a SHA-256 context.
*
* \param ctx The SHA-256 context to initialize. This must not be \c NULL.
*/
void mbedtls_sha256_init( <API key> *ctx );
/**
* \brief This function clears a SHA-256 context.
*
* \param ctx The SHA-256 context to clear. This may be \c NULL, in which
* case this function returns immediately. If it is not \c NULL,
* it must point to an initialized SHA-256 context.
*/
void mbedtls_sha256_free( <API key> *ctx );
/**
* \brief This function clones the state of a SHA-256 context.
*
* \param dst The destination context. This must be initialized.
* \param src The context to clone. This must be initialized.
*/
void <API key>( <API key> *dst,
const <API key> *src );
/**
* \brief This function starts a SHA-224 or SHA-256 checksum
* calculation.
*
* \param ctx The context to use. This must be initialized.
* \param is224 This determines which function to use. This must be
* either \c 0 for SHA-256, or \c 1 for SHA-224.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int <API key>( <API key> *ctx, int is224 );
/**
* \brief This function feeds an input buffer into an ongoing
* SHA-256 checksum calculation.
*
* \param ctx The SHA-256 context. This must be initialized
* and have a hash operation started.
* \param input The buffer holding the data. This must be a readable
* buffer of length \p ilen Bytes.
* \param ilen The length of the input data in Bytes.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int <API key>( <API key> *ctx,
const unsigned char *input,
size_t ilen );
/**
* \brief This function finishes the SHA-256 operation, and writes
* the result to the output buffer.
*
* \param ctx The SHA-256 context. This must be initialized
* and have a hash operation started.
* \param output The SHA-224 or SHA-256 checksum result.
* This must be a writable buffer of length \c 32 Bytes.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int <API key>( <API key> *ctx,
unsigned char output[32] );
/**
* \brief This function processes a single data block within
* the ongoing SHA-256 computation. This function is for
* internal use only.
*
* \param ctx The SHA-256 context. This must be initialized.
* \param data The buffer holding one block of data. This must
* be a readable buffer of length \c 64 Bytes.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int <API key>( <API key> *ctx,
const unsigned char data[64] );
#if !defined(<API key>)
#if defined(<API key>)
#define MBEDTLS_DEPRECATED __attribute__((deprecated))
#else
#define MBEDTLS_DEPRECATED
#endif
/**
* \brief This function starts a SHA-224 or SHA-256 checksum
* calculation.
*
* \deprecated Superseded by <API key>() in 2.7.0.
*
* \param ctx The context to use. This must be initialized.
* \param is224 Determines which function to use. This must be
* either \c 0 for SHA-256, or \c 1 for SHA-224.
*/
MBEDTLS_DEPRECATED void <API key>( <API key> *ctx,
int is224 );
/**
* \brief This function feeds an input buffer into an ongoing
* SHA-256 checksum calculation.
*
* \deprecated Superseded by <API key>() in 2.7.0.
*
* \param ctx The SHA-256 context to use. This must be
* initialized and have a hash operation started.
* \param input The buffer holding the data. This must be a readable
* buffer of length \p ilen Bytes.
* \param ilen The length of the input data in Bytes.
*/
MBEDTLS_DEPRECATED void <API key>( <API key> *ctx,
const unsigned char *input,
size_t ilen );
/**
* \brief This function finishes the SHA-256 operation, and writes
* the result to the output buffer.
*
* \deprecated Superseded by <API key>() in 2.7.0.
*
* \param ctx The SHA-256 context. This must be initialized and
* have a hash operation started.
* \param output The SHA-224 or SHA-256 checksum result. This must be
* a writable buffer of length \c 32 Bytes.
*/
MBEDTLS_DEPRECATED void <API key>( <API key> *ctx,
unsigned char output[32] );
/**
* \brief This function processes a single data block within
* the ongoing SHA-256 computation. This function is for
* internal use only.
*
* \deprecated Superseded by <API key>() in 2.7.0.
*
* \param ctx The SHA-256 context. This must be initialized.
* \param data The buffer holding one block of data. This must be
* a readable buffer of size \c 64 Bytes.
*/
MBEDTLS_DEPRECATED void <API key>( <API key> *ctx,
const unsigned char data[64] );
#undef MBEDTLS_DEPRECATED
#endif /* !<API key> */
/**
* \brief This function calculates the SHA-224 or SHA-256
* checksum of a buffer.
*
* The function allocates the context, performs the
* calculation, and frees the context.
*
* The SHA-256 result is calculated as
* output = SHA-256(input buffer).
*
* \param input The buffer holding the data. This must be a readable
* buffer of length \p ilen Bytes.
* \param ilen The length of the input data in Bytes.
* \param output The SHA-224 or SHA-256 checksum result. This must
* be a writable buffer of length \c 32 Bytes.
* \param is224 Determines which function to use. This must be
* either \c 0 for SHA-256, or \c 1 for SHA-224.
*/
int mbedtls_sha256_ret( const unsigned char *input,
size_t ilen,
unsigned char output[32],
int is224 );
#if !defined(<API key>)
#if defined(<API key>)
#define MBEDTLS_DEPRECATED __attribute__((deprecated))
#else
#define MBEDTLS_DEPRECATED
#endif
/**
* \brief This function calculates the SHA-224 or SHA-256 checksum
* of a buffer.
*
* The function allocates the context, performs the
* calculation, and frees the context.
*
* The SHA-256 result is calculated as
* output = SHA-256(input buffer).
*
* \deprecated Superseded by mbedtls_sha256_ret() in 2.7.0.
*
* \param input The buffer holding the data. This must be a readable
* buffer of length \p ilen Bytes.
* \param ilen The length of the input data in Bytes.
* \param output The SHA-224 or SHA-256 checksum result. This must be
* a writable buffer of length \c 32 Bytes.
* \param is224 Determines which function to use. This must be either
* \c 0 for SHA-256, or \c 1 for SHA-224.
*/
MBEDTLS_DEPRECATED void mbedtls_sha256( const unsigned char *input,
size_t ilen,
unsigned char output[32],
int is224 );
#undef MBEDTLS_DEPRECATED
#endif /* !<API key> */
/**
* \brief The SHA-224 and SHA-256 checkup routine.
*
* \return \c 0 on success.
* \return \c 1 on failure.
*/
int <API key>( int verbose );
#ifdef __cplusplus
}
#endif
#endif /* mbedtls_sha256.h */
|
package com.mucommander.command;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.<API key>;
import javax.xml.parsers.SAXParserFactory;
import java.io.IOException;
import java.io.InputStream;
/**
* Class used to parse custom associations XML files.
* <p>
* Association file parsing is done through the {@link #read(InputStream,AssociationBuilder) read} method, which is
* the only way to interact with this class.
* </p>
* <p>
* Note that while this class knows how to read the content of an association XML file, its role is not to interpret it. This
* is done by instances of {@link AssociationBuilder}.
* </p>
* @see <API key>
* @see AssociationBuilder
* @see AssociationWriter
* @author Nicolas Rinaudo
*/
public class AssociationReader extends DefaultHandler implements <API key> {
/** Where to send building messages. */
private AssociationBuilder builder;
private boolean isInAssociation;
/**
* Creates a new command reader.
* @param b where to send custom command events.
*/
private AssociationReader(AssociationBuilder b) {builder = b;}
/**
* Parses the content of the specified input stream.
* <p>
* This method will go through the specified input stream and notify the builder of any new association declaration it
* encounters. Note that parsing is done in a very lenient fashion, and perfectly invalid XML files might not raise
* an exception. This is not a flaw in the parser, and both allows muCommander to be error resilient and the associations
* file format to be extended without having to rewrite most of this code.
* </p>
* <p>
* Note that even if an error occurs, both of the builder's {@link AssociationBuilder#startBuilding()} and
* {@link AssociationBuilder#endBuilding()} methods will still be called. Parsing will stop at the first error
* however, so while the builder is guaranteed to receive correct messages, it might not receive all declared
* associations.
* </p>
* @param in where to read association data from.
* @param b where to send building events to.
* @throws IOException if any IO error occurs.
* @see #read(InputStream,AssociationBuilder)
*/
public static void read(InputStream in, AssociationBuilder b) throws IOException, CommandException {
b.startBuilding();
try {SAXParserFactory.newInstance().newSAXParser().parse(in, new AssociationReader(b));}
catch(<API key> e) {throw new CommandException(e);}
catch(SAXException e) {throw new CommandException(e);}
finally {b.endBuilding();}
}
/**
* This method is public as an implementation side effect and should not be called directly.
*/
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
String buffer;
try {
if(!isInAssociation) {
if(qName.equals(ELEMENT_ASSOCIATION)) {
// Makes sure the required attributes are present.
if((buffer = attributes.getValue(ATTRIBUTE_COMMAND)) == null)
return;
isInAssociation = true;
builder.startAssociation(buffer);
}
}
else {
if(qName.equals(ELEMENT_MASK)) {
String caseSensitive;
if((buffer = attributes.getValue(ATTRIBUTE_VALUE)) == null)
return;
if((caseSensitive = attributes.getValue(<API key>)) != null)
builder.setMask(buffer, caseSensitive.equals(VALUE_TRUE));
else
builder.setMask(buffer, true);
}
else if(qName.equals(ELEMENT_IS_HIDDEN)) {
if((buffer = attributes.getValue(ATTRIBUTE_VALUE)) == null)
return;
builder.setIsHidden(buffer.equals(VALUE_TRUE));
}
else if(qName.equals(ELEMENT_IS_SYMLINK)) {
if((buffer = attributes.getValue(ATTRIBUTE_VALUE)) == null)
return;
builder.setIsSymlink(buffer.equals(VALUE_TRUE));
}
else if(qName.equals(ELEMENT_IS_READABLE)) {
if((buffer = attributes.getValue(ATTRIBUTE_VALUE)) == null)
return;
builder.setIsReadable(buffer.equals(VALUE_TRUE));
}
else if(qName.equals(ELEMENT_IS_WRITABLE)) {
if((buffer = attributes.getValue(ATTRIBUTE_VALUE)) == null)
return;
builder.setIsWritable(buffer.equals(VALUE_TRUE));
}
else if(qName.equals(<API key>)) {
if((buffer = attributes.getValue(ATTRIBUTE_VALUE)) == null)
return;
builder.setIsExecutable(buffer.equals(VALUE_TRUE));
}
}
}
catch(CommandException e) {throw new SAXException(e);}
}
/**
* This method is public as an implementation side effect, but should not be called directly.
*/
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if(qName.equals(ELEMENT_ASSOCIATION) && isInAssociation) {
try {builder.endAssociation();}
catch(CommandException e) {throw new SAXException(e);}
isInAssociation = false;
}
}
}
|
<html><body>Ghost of Wigoth:<br>
I already gathered three glasses. You did good too. I'm not brave enough to face those women.<br>
<Button ALIGN=LEFT ICON="NORMAL" action="bypass -h Quest Q00620_FourGoblets 18">"Do you know them?"</button>
</body></html>
|
package org.sigmah.client.ui.view.admin.models.project;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.sigmah.client.i18n.I18N;
import org.sigmah.client.ui.widget.HasGrid.GridEventHandler;
import org.sigmah.client.util.ClientUtils;
import org.sigmah.client.util.ColumnProviders;
import org.sigmah.shared.dto.PhaseModelDTO;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnData;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridCellRenderer;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
/**
* Provides phase models admin grid columns configuration.
*
* @author Denis Colliot (dcolliot@ideia.fr)
*/
abstract class <API key> {
/**
* Returns the {@link GridEventHandler} implementation.
*
* @return The {@link GridEventHandler} implementation.
*/
protected abstract GridEventHandler<PhaseModelDTO> getGridEventHandler();
/**
* Gets the columns model for the phases admin grid.
*
* @return The columns model for the phases admin grid.
*/
public ColumnModel getColumnModel() {
final List<ColumnConfig> configs = new ArrayList<ColumnConfig>();
// Display order column.
configs.add(new ColumnConfig(PhaseModelDTO.DISPLAY_ORDER, I18N.CONSTANTS.adminPhaseOrder(), 50));
// Name column.
ColumnConfig column = new ColumnConfig(PhaseModelDTO.NAME, I18N.CONSTANTS.adminPhaseName(), 200);
column.setRenderer(new GridCellRenderer<PhaseModelDTO>() {
@Override
public Object render(final PhaseModelDTO model, final String property, final ColumnData config, final int rowIndex, final int colIndex,
final ListStore<PhaseModelDTO> store, final Grid<PhaseModelDTO> grid) {
return ColumnProviders.renderLink(model.getName(), new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
getGridEventHandler().onRowClickEvent(model);
}
});
}
});
configs.add(column);
// Successors column.
column = new ColumnConfig(PhaseModelDTO.SUCCESSORS, I18N.CONSTANTS.<API key>(), 400);
column.setRenderer(new GridCellRenderer<PhaseModelDTO>() {
@Override
public Object render(final PhaseModelDTO model, final String property, final ColumnData config, final int rowIndex, final int colIndex,
final ListStore<PhaseModelDTO> store, final Grid<PhaseModelDTO> grid) {
final Collection<String> successors = new ArrayList<String>();
for (final PhaseModelDTO phase : model.getSuccessors()) {
successors.add(phase.getName());
}
return renderCollection(successors, "");
}
});
configs.add(column);
// Guide URL column.
configs.add(new ColumnConfig(PhaseModelDTO.GUIDE, I18N.CONSTANTS.<API key>(), 250));
return new ColumnModel(configs);
}
/**
* Renders a collection of string values.
*
* @param values
* The values.
* @param defaultLabel
* The default label rendered if the {@code values} collection is {@code null} or empty.
* @return The rendering of the given {@code values}.
*/
private static Object renderCollection(final Collection<String> values, final String defaultLabel) {
final StringBuilder builder = new StringBuilder();
if (ClientUtils.isNotEmpty(values)) {
for (final Object value : values) {
if (builder.length() > 0) {
builder.append(", ");
}
builder.append(value);
}
} else {
builder.append(defaultLabel);
}
return ColumnProviders.renderText(builder.toString());
}
}
|
<?php //## NextScripts Yo Connection Class
$nxs_snapAvNts[] = array('code'=>'YO', 'lcode'=>'yo', 'name'=>'Yo', 'type'=>'Messengers');
if (!class_exists("nxs_snapClassYO")) { class nxs_snapClassYO extends nxs_snapClassNT {
var $ntInfo = array('code'=>'YO', 'lcode'=>'yo', 'name'=>'Yo', 'defNName'=>'', 'tstReq' => false, 'instrURL'=>'http:
//
function showGenNTSettings($ntOpts){ $this->nt = $ntOpts; $this->showNTGroup(); }
//
function showNewNTSettings($ii){ $defO = array('nName'=>'', 'do'=>'1', 'apiKey'=>'', 'msgFormat'=>'%TITLE%'); $this->showGNewNTSettings($ii, $defO); }
//
function <API key>($options) { return !empty($options['apiKey']); }
function doAuth() { }
function accTab($ii, $options, $isNew=false){ global $nxs_snapSetPgURL; $ntInfo = $this->ntInfo; $nt = $ntInfo['lcode']; ?><div id="altFormat" style="">
<div style="width:100%;"><strong id="altFormatText">Yo API Key:</strong> <span style="font-size: 11px; margin: 0px;">Get it from <a target="_blank" href="http:
<input name="<?php echo $nt; ?>[<?php echo $ii; ?>][apiKey]" style="width: 60%;" value="<?php _e(apply_filters('format_to_edit', htmlentities($options['apiKey'], ENT_COMPAT, "UTF-8")), '<API key>') ?>" /> <br/>
</div><br/><?php $this->elemMsgFormat($ii,'Message Text Format','msgFormat',$options['msgFormat']);
}
function advTab($ii, $options){}
//
function setNTSettings($post, $options){
foreach ($post as $ii => $pval){
if (!empty($pval['apiKey']) && !empty($pval['apiKey'])){ if (!isset($options[$ii])) $options[$ii] = array(); $options[$ii] = $this-><API key>($pval,$options[$ii]);
//## Uniqe Items
if (isset($pval['apiKey'])) $options[$ii]['apiKey'] = trim($pval['apiKey']);
} elseif ( count($pval)==1 ) if (isset($pval['do'])) $options[$ii]['do'] = $pval['do']; else $options[$ii]['do'] = 0;
} return $options;
}
//
function <API key>($ntOpts, $post){ $post_id = $post->ID; $nt = $this->ntInfo['lcode']; $ntU = $this->ntInfo['code'];
foreach($ntOpts as $ii=>$ntOpt) { $isFin = $this-><API key>($ntOpt); if (!$isFin) continue;
$pMeta = maybe_unserialize(get_post_meta($post_id, 'snap'.$ntU, true)); if (is_array($pMeta) && !empty($pMeta[$ii])) $ntOpt = $this->adjMetaOpt($ntOpt, $pMeta[$ii]);
if (empty($ntOpt['imgToUse'])) $ntOpt['imgToUse'] = ''; if (empty($ntOpt['urlToUse'])) $ntOpt['urlToUse'] = ''; $postType = isset($ntOpt['postType'])?$ntOpt['postType']:'';
$msgFormat = !empty($ntOpt['msgFormat'])?htmlentities($ntOpt['msgFormat'], ENT_COMPAT, "UTF-8"):''; $msgTFormat = !empty($ntOpt['msgTFormat'])?htmlentities($ntOpt['msgTFormat'], ENT_COMPAT, "UTF-8"):'';
$imgToUse = $ntOpt['imgToUse']; $urlToUse = $ntOpt['urlToUse']; $ntOpt['ii']=$ii;
$this-><API key>($post, $ntOpt, $pMeta); ?>
<?php $this->elemEdTitleFormat($ii, __('Title Format:', '<API key>'),$msgTFormat); $this->elemEdMsgFormat($ii, __('Message Format:', '<API key>'),$msgFormat);
/* ## Select Image & URL ## */ nxs_showURLToUseDlg($nt, $ii, $urlToUse); $this-><API key>($ii);
}
}
//
function adjMetaOpt($optMt, $pMeta){ $optMt = $this->adjMetaOptG($optMt, $pMeta);
//if (!empty($pMeta['tgBoard'])) $optMt['tgBoard'] = $pMeta['tgBoard'];
return $optMt;
}
function adjPublishWP(&$options, &$message, $postID){ //prr($message); prr($options);
}
}}
if (!function_exists("nxs_doPublishToYO")) { function nxs_doPublishToYO($postID, $options){
if (!is_array($options)) $options = maybe_unserialize(get_post_meta($postID, $options, true)); $cl = new nxs_snapClassYO(); $cl->nt[$options['ii']] = $options; return $cl->publishWP($options['ii'], $postID);
}}
?>
|
#include "mainwindow.h"
#include "userwindow.h"
#include <QApplication>
#include <QTranslator>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QTranslator qtTranslator;
if (qtTranslator.load("translations/qt_" + QLocale::system().name()))
a.installTranslator(&qtTranslator);
UserWindow uw;
MainWindow w(&uw);
w.show();
uw.show();
return a.exec();
}
|
# coding: utf8
# terms of the GNU General Public Licence version 3 (GPL Version 3),
# copied verbatim in the file LICENCE.md.
# In applying this licence, CERN does not waive the privileges and immunities
# granted to it by virtue of its status as an Intergovernmental Organization or
# submit itself to any jurisdiction.
'''
Example input for simulation of ion dynamics
No intensity effects
:Authors: **Alexandre Lasheen**
'''
from __future__ import division, print_function
from builtins import range
from scipy.constants import physical_constants
# Atomic Mass Unit [eV]
u = physical_constants['atomic mass unit-electron volt relationship'][0]
import numpy as np
from blond.input_parameters.ring import Ring
from blond.input_parameters.rf_parameters import RFStation
from blond.trackers.tracker import RingAndRFTracker
from blond.beam.distributions import bigaussian
from blond.monitors.monitors import BunchMonitor
from blond.beam.profile import Profile, CutOptions
from blond.beam.beam import Beam, Particle
from blond.plots.plot import Plot
import os
this_directory = os.path.dirname(os.path.realpath(__file__)) + '/'
try:
os.mkdir(this_directory + '../output_files')
except:
pass
try:
os.mkdir(this_directory + '../output_files/EX_07_fig')
except:
pass
# Bunch parameters
N_b = 5.0e11 # Design Intensity in SIS100
N_p = 50000 # Macro-particles
tau_0 = 100.0e-9 # Initial bunch length, 4 sigma [s]
Z = 28. # Charge state of Uranium
m_p = 238.05078826*u # Isotope mass of U-238
# Machine and RF parameters
C = 1083.6 # Machine circumference [m]
p_i = 153.37e9 # Synchronous momentum [eV/c]
p_f = 535.62e9 # Synchronous momentum, final 535.62e9
h = 10 # Harmonic number
V = 280.e3 # RF voltage [V]
dphi = np.pi # Phase modulation/offset
gamma_t = 15.59 # Transition gamma
alpha = 1./gamma_t/gamma_t # First order mom. comp. factor
# Tracking details
N_t = 45500 # Number of turns to track
dt_plt = 5000 # Time steps between plots
print("Setting up the simulation...")
print("")
# Define general parameters
general_params = Ring(C, alpha, np.linspace(p_i, p_f, N_t+1),
Particle(m_p, Z), n_turns=N_t)
# Define beam and distribution
beam = Beam(general_params, N_p, N_b)
print("Particle mass is %.3e eV" %general_params.Particle.mass)
print("Particle charge is %d e" %general_params.Particle.charge)
linspace_test = np.linspace(p_i, p_f, N_t+1)
momentum_test = general_params.momentum
beta_test = general_params.beta
gamma_test = general_params.gamma
energy_test = general_params.energy
mass_test = general_params.Particle.mass
charge_test = general_params.Particle.charge
# Define RF station parameters and corresponding tracker
rf_params = RFStation(general_params, [h], [V], [dphi])
print("Initial bucket length is %.3e s" %(2.*np.pi/rf_params.omega_rf[0,0]))
print("Final bucket length is %.3e s" %(2.*np.pi/rf_params.omega_rf[0,N_t]))
phi_s_test = rf_params.phi_s #: *Synchronous phase
omega_RF_d_test = rf_params.omega_rf_d #: *Design RF frequency of the RF systems in the station [GHz]*
omega_RF_test = rf_params.omega_rf #: *Initial, actual RF frequency of the RF systems in the station [GHz]*
phi_RF_test = rf_params.omega_rf #: *Initial, actual RF phase of each harmonic system*
E_increment_test = rf_params.delta_E #Energy increment (acceleration/deceleration) between two turns,
long_tracker = RingAndRFTracker(rf_params, beam)
eta_0_test = rf_params.eta_0 #: *Slippage factor (0th order) for the given RF section*
eta_1_test = rf_params.eta_1 #: *Slippage factor (1st order) for the given RF section*
eta_2_test = rf_params.eta_2 #: *Slippage factor (2nd order) for the given RF section*
alpha_order_test = rf_params.alpha_order
bigaussian(general_params, rf_params, beam, tau_0/4,
reinsertion = 'on', seed=1)
# Need slices for the Gaussian fit
slice_beam = Profile(beam, CutOptions(n_slices=100))
# Define what to save in file
bunchmonitor = BunchMonitor(general_params, rf_params, beam,
this_directory + '../output_files/EX_07_output_data',
Profile=slice_beam)
format_options = {'dirname': this_directory + '../output_files/EX_07_fig'}
plots = Plot(general_params, rf_params, beam, dt_plt, N_t, 0, 8.e-7,
-400e6, 400e6, separatrix_plot=True, Profile=slice_beam,
h5file=this_directory + '../output_files/EX_07_output_data',
format_options=format_options)
# For testing purposes
test_string = ''
test_string += '{:<17}\t{:<17}\t{:<17}\t{:<17}\n'.format(
'mean_dE', 'std_dE', 'mean_dt', 'std_dt')
test_string += '{:+10.10e}\t{:+10.10e}\t{:+10.10e}\t{:+10.10e}\n'.format(
np.mean(beam.dE), np.std(beam.dE), np.mean(beam.dt), np.std(beam.dt))
# Accelerator map
map_ = [long_tracker] + [slice_beam] + [bunchmonitor] + [plots]
print("Map set")
print("")
for i in range(1, N_t+1):
# Plot has to be done before tracking (at least for cases with separatrix)
if (i % dt_plt) == 0:
print("Outputting at time step %d..." %i)
print(" Beam momentum %.6e eV" %beam.momentum)
print(" Beam gamma %3.3f" %beam.gamma)
print(" Beam beta %3.3f" %beam.beta)
print(" Beam energy %.6e eV" %beam.energy)
print(" Four-times r.m.s. bunch length %.4e s" %(4.*beam.sigma_dt))
print("")
# Track
for m in map_:
m.track()
# Define losses according to separatrix
beam.losses_separatrix(general_params, rf_params)
# For testing purposes
test_string += '{:+10.10e}\t{:+10.10e}\t{:+10.10e}\t{:+10.10e}\n'.format(
np.mean(beam.dE), np.std(beam.dE), np.mean(beam.dt), np.std(beam.dt))
with open(this_directory + '../output_files/EX_07_test_data.txt', 'w') as f:
f.write(test_string)
print("Done!")
|
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'OutboundMessage.status'
db.alter_column(u'<API key>', 'status', self.gf('django.db.models.fields.CharField')(max_length='10'))
def backwards(self, orm):
# Changing field 'OutboundMessage.status'
db.alter_column(u'<API key>', 'status', self.gf('django.db.models.fields.CharField')(max_length='4'))
models = {
u'contactos.contact': {
'Meta': {'object_name': 'Contact'},
'contact_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contactos.ContactType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'person': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['popit.Person']"}),
'value': ('django.db.models.fields.CharField', [], {'max_length': '512'})
},
u'contactos.contacttype': {
'Meta': {'object_name': 'ContactType'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'label_name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'nuntium.message': {
'Meta': {'object_name': 'Message'},
'content': ('django.db.models.fields.TextField', [], {}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'subject': ('django.db.models.fields.CharField', [], {'max_length': '512'}),
'writeitinstance': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['nuntium.WriteItInstance']"})
},
u'nuntium.messagerecord': {
'Meta': {'object_name': 'MessageRecord'},
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
'datetime': ('django.db.models.fields.DateField', [], {'default': 'datetime.datetime(2013, 5, 2, 0, 0)'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'object_id': ('django.db.models.fields.<API key>', [], {}),
'status': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
u'nuntium.outboundmessage': {
'Meta': {'object_name': 'OutboundMessage'},
'contact': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contactos.Contact']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'message': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['nuntium.Message']"}),
'status': ('django.db.models.fields.CharField', [], {'default': "'ready'", 'max_length': "'10'"})
},
u'nuntium.writeitinstance': {
'Meta': {'object_name': 'WriteItInstance'},
'api_instance': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['popit.ApiInstance']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
u'popit.apiinstance': {
'Meta': {'object_name': 'ApiInstance'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'url': ('popit.fields.ApiInstanceURLField', [], {'unique': 'True', 'max_length': '200'})
},
u'popit.person': {
'Meta': {'object_name': 'Person'},
'api_instance': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['popit.ApiInstance']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'popit_url': ('popit.fields.PopItURLField', [], {'default': "''", 'max_length': '200', 'unique': 'True', 'null': 'True', 'blank': 'True'})
}
}
complete_apps = ['nuntium']
|
from __future__ import division
import StringIO
import json
import random
import sys
from twisted.internet import defer
import p2pool
from p2pool.bitcoin import getwork
from p2pool.util import expiring_dict, jsonrpc, variable
class _Provider(object):
def __init__(self, parent, long_poll):
self.parent = parent
self.long_poll = long_poll
def rpc_getwork(self, request, data=None):
return self.parent._getwork(request, data, long_poll=self.long_poll)
class _GETableServer(jsonrpc.Server):
def __init__(self, provider, render_get_func):
jsonrpc.Server.__init__(self, provider)
self.render_GET = render_get_func
class WorkerBridge(object):
def __init__(self):
self.new_work_event = variable.Event()
def preprocess_request(self, request):
return request, # *args to self.compute
def get_work(self, request):
raise NotImplementedError()
class WorkerInterface(object):
def __init__(self, worker_bridge):
self.worker_bridge = worker_bridge
self.worker_views = {}
self.work_cache = {}
self.work_cache_times = self.worker_bridge.new_work_event.times
self.<API key> = expiring_dict.ExpiringDict(300)
def attach_to(self, res, get_handler=None):
res.putChild('', _GETableServer(_Provider(self, long_poll=False), get_handler))
def repost(request):
request.content = StringIO.StringIO(json.dumps(dict(id=0, method='getwork')))
return s.render_POST(request)
s = _GETableServer(_Provider(self, long_poll=True), repost)
res.putChild('long-polling', s)
@defer.inlineCallbacks
def _getwork(self, request, data, long_poll):
request.setHeader('X-Long-Polling', '/long-polling')
request.setHeader('X-Roll-NTime', 'expire=10')
request.setHeader('X-Is-P2Pool', 'true')
if data is not None:
header = getwork.decode_data(data)
if header['merkle_root'] not in self.<API key>:
print >>sys.stderr, '''Couldn't link returned work's merkle root with its handler. This should only happen if this process was recently restarted!'''
defer.returnValue(False)
defer.returnValue(self.<API key>[header['merkle_root']](header, request))
if p2pool.DEBUG:
id = random.randrange(1000, 10000)
print 'POLL %i START is_long_poll=%r user_agent=%r user=%r' % (id, long_poll, request.getHeader('User-Agent'), request.getUser())
if long_poll:
request_id = request.getClientIP(), request.getHeader('Authorization')
if self.worker_views.get(request_id, self.worker_bridge.new_work_event.times) != self.worker_bridge.new_work_event.times:
if p2pool.DEBUG:
print 'POLL %i PUSH' % (id,)
else:
if p2pool.DEBUG:
print 'POLL %i WAITING' % (id,)
yield self.worker_bridge.new_work_event.get_deferred()
self.worker_views[request_id] = self.worker_bridge.new_work_event.times
key = self.worker_bridge.preprocess_request(request)
if self.work_cache_times != self.worker_bridge.new_work_event.times:
self.work_cache = {}
self.work_cache_times = self.worker_bridge.new_work_event.times
if key in self.work_cache:
res, orig_timestamp, handler = self.work_cache.pop(key)
else:
res, handler = self.worker_bridge.get_work(*key)
assert res.merkle_root not in self.<API key>
orig_timestamp = res.timestamp
self.<API key>[res.merkle_root] = handler
if res.timestamp + 12 < orig_timestamp + 600:
self.work_cache[key] = res.update(timestamp=res.timestamp + 12), orig_timestamp, handler
if p2pool.DEBUG:
print 'POLL %i END identifier=%i' % (id, self.worker_bridge.new_work_event.times)
defer.returnValue(res.getwork(identifier=str(self.worker_bridge.new_work_event.times), submitold=True))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.