answer
stringlengths 15
1.25M
|
|---|
#pragma once
#include <d3dx9shader.h>
class <API key>
{
typedef HRESULT(WINAPI* <API key>)(
LPCSTR pSrcData,
UINT SrcDataLen,
CONST D3DXMACRO* pDefines,
LPD3DXINCLUDE pInclude,
LPCSTR pFunctionName,
LPCSTR pProfile,
DWORD Flags,
LPD3DXBUFFER* ppShader,
LPD3DXBUFFER* ppErrorMsgs,
LPD3DXCONSTANTTABLE* ppConstantTable);
typedef HRESULT(WINAPI* <API key>)(
CONST DWORD* pShader,
bool EnableColorCode,
LPCSTR pComments,
LPD3DXBUFFER* ppDisassembly);
<API key> <API key>;
<API key> <API key>;
CComPtr<IDirect3DDevice9> m_pD3DDev;
public:
<API key>(IDirect3DDevice9* pD3DDev, bool fStaySilent = false);
virtual ~<API key>();
HRESULT CompileShader(
LPCSTR pSrcData,
LPCSTR pFunctionName,
LPCSTR pProfile,
DWORD Flags,
<API key>** ppPixelShader,
CString* disasm = nullptr,
CString* errmsg = nullptr);
};
|
<!doctype html>
<html>
<title>npm-rm</title>
<meta http-equiv="content-type" value="text/html;utf-8">
<link rel="stylesheet" type="text/css" href="../../static/style.css">
<link rel="canonical" href="https:
<script async=true src="../../static/toc.js"></script>
<body>
<div id="wrapper">
<h1><a href="../cli/npm-rm.html">npm-rm</a></h1> <p>Remove a package</p>
<h2 id="synopsis">SYNOPSIS</h2>
<pre><code>npm rm <name>
npm r <name>
npm uninstall <name>
npm un <name>
</code></pre><h2 id="description">DESCRIPTION</h2>
<p>This uninstalls a package, completely removing everything npm installed
on its behalf.</p>
<h2 id="see-also">SEE ALSO</h2>
<ul>
<li><a href="../cli/npm-prune.html">npm-prune(1)</a></li>
<li><a href="../cli/npm-install.html">npm-install(1)</a></li>
<li><a href="../files/npm-folders.html">npm-folders(5)</a></li>
<li><a href="../cli/npm-config.html">npm-config(1)</a></li>
<li><a href="../misc/npm-config.html">npm-config(7)</a></li>
<li><a href="../files/npmrc.html">npmrc(5)</a></li>
</ul>
</div>
<table border=0 cellspacing=0 cellpadding=0 id=npmlogo>
<tr><td style="width:180px;height:10px;background:rgb(237,127,127)" colspan=18> </td></tr>
<tr><td rowspan=4 style="width:10px;height:10px;background:rgb(237,127,127)"> </td><td style="width:40px;height:10px;background:#fff" colspan=4> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=4> </td><td style="width:40px;height:10px;background:#fff" colspan=4> </td><td rowspan=4 style="width:10px;height:10px;background:rgb(237,127,127)"> </td><td colspan=6 style="width:60px;height:10px;background:#fff"> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=4> </td></tr>
<tr><td colspan=2 style="width:20px;height:30px;background:#fff" rowspan=3> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3> </td><td style="width:10px;height:10px;background:#fff" rowspan=3> </td><td style="width:20px;height:10px;background:#fff" rowspan=4 colspan=2> </td><td style="width:10px;height:20px;background:rgb(237,127,127)" rowspan=2> </td><td style="width:10px;height:10px;background:#fff" rowspan=3> </td><td style="width:20px;height:10px;background:#fff" rowspan=3 colspan=2> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3> </td><td style="width:10px;height:10px;background:#fff" rowspan=3> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3> </td></tr>
<tr><td style="width:10px;height:10px;background:#fff" rowspan=2> </td></tr>
<tr><td style="width:10px;height:10px;background:#fff"> </td></tr>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
<p id="footer">npm-rm — npm@2.14.18</p>
|
#!/bin/bash
cd output_tfi
rm "h_mz_E_D=2_chi=20.dat"
rm "h_mz_E_D=2_chi=20_pm.dat"
rm "h_mz_E_D=3_chi=30.dat"
rm "h_mz_E_D=3_chi=30_pm.dat"
for f in `ls D=2_chi=20_*_trotter2_itebd.dat`
do
h=`echo $f | cut -f 3 -d "_" | cut -f 2 -d "="`
mz=`tail -n 1 $f | cut -f 3 -d " "`
E=`tail -n 1 $f | cut -f 5 -d " "`
tau=`echo $f | cut -f 4 -d "_" | cut -f 2 -d "="`
echo $h $mz $E $tau >> "h_mz_E_D=2_chi=20.dat"
done
for f in `ls D=2_chi=20_*_trotter2_pm_itebd.dat`
do
h=`echo $f | cut -f 3 -d "_" | cut -f 2 -d "="`
mz=`tail -n 1 $f | cut -f 3 -d " "`
E=`tail -n 1 $f | cut -f 5 -d " "`
tau=`echo $f | cut -f 4 -d "_" | cut -f 2 -d "="`
echo $h $mz $E $tau >> "h_mz_E_D=2_chi=20_pm.dat"
done
for f in `ls D=3_chi=30_*_trotter2_itebd.dat`
do
h=`echo $f | cut -f 3 -d "_" | cut -f 2 -d "="`
mz=`tail -n 1 $f | cut -f 3 -d " "`
E=`tail -n 1 $f | cut -f 5 -d " "`
tau=`echo $f | cut -f 4 -d "_" | cut -f 2 -d "="`
echo $h $mz $E $tau >> "h_mz_E_D=3_chi=30.dat"
done
for f in `ls D=3_chi=30_*_trotter2_pm_itebd.dat`
do
h=`echo $f | cut -f 3 -d "_" | cut -f 2 -d "="`
mz=`tail -n 1 $f | cut -f 3 -d " "`
E=`tail -n 1 $f | cut -f 5 -d " "`
tau=`echo $f | cut -f 4 -d "_" | cut -f 2 -d "="`
echo $h $mz $E $tau >> "h_mz_E_D=3_chi=30_pm.dat"
done
cd ..
exit 0
|
# htspan
## Dependencies
* gcc >= 4.8
* gsl >= 2.4.1
Included dependencies
* htslib >= 1.8
* mlat >= 0.1
## Install
{bash}
make
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# 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
from __future__ import absolute_import, division, print_function
__metaclass__ = type
RETURN =
from ansible_collections.theforeman.foreman.plugins.module_utils.foreman_helper import <API key>
def main():
module = <API key>(
argument_spec=dict(
manifest_path=dict(type='path'),
state=dict(default='present', choices=['absent', 'present', 'refreshed']),
repository_url=dict(aliases=['<API key>']),
),
foreman_spec=dict(
organization=dict(type='entity', required=True, thin=False),
),
required_if=[
['state', 'present', ['manifest_path']],
],
supports_check_mode=False,
)
module.task_timeout = 5 * 60
with module.api_connection():
organization = module.lookup_entity('organization')
scope = module.scope_for('organization')
try:
existing_manifest = organization['owner_details']['upstreamConsumer']
except KeyError:
existing_manifest = None
if module.state == 'present':
if 'repository_url' in module.foreman_params:
payload = {'<API key>': module.foreman_params['repository_url']}
org_spec = dict(id=dict(), <API key>=dict())
organization = module.ensure_entity('organizations', payload, organization, state='present', foreman_spec=org_spec)
try:
with open(module.foreman_params['manifest_path'], 'rb') as manifest_file:
files = {'content': (module.foreman_params['manifest_path'], manifest_file, 'application/zip')}
params = {}
if 'repository_url' in module.foreman_params:
params['repository_url'] = module.foreman_params['repository_url']
params.update(scope)
result = module.resource_action('subscriptions', 'upload', params, files=files, record_change=False, ignore_task_errors=True)
for error in result['humanized']['errors']:
if "same as existing data" in error:
# Nothing changed, but everything ok
break
if "older than existing data" in error:
module.fail_json(msg="Manifest is older than existing data.")
else:
module.fail_json(msg="Upload of the manifest failed: %s" % error)
else:
module.set_changed()
except IOError as e:
module.fail_json(msg="Unable to read the manifest file: %s" % e)
elif module.desired_absent and existing_manifest:
module.resource_action('subscriptions', 'delete_manifest', scope)
elif module.state == 'refreshed':
if existing_manifest:
module.resource_action('subscriptions', 'refresh_manifest', scope)
else:
module.fail_json(msg="No manifest found to refresh.")
if __name__ == '__main__':
main()
|
#!/usr/bin/env bash
# This file is part of qTox, a Qt-based graphical interface for Tox.
# qTox is libre software: you can redistribute it and/or modify
# (at your option) any later version.
# qTox is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# This script's purpose is to ease compiling qTox for users.
# NO AUTOMATED BUILDS SHOULD DEPEND ON IT.
# This script is and will be a subject to breaking changes, and at no time one
# should expect it to work - it's something that you could try to use but
# don't expect that it will work for sure.
# If script doesn't work, you should use instructions provided in INSTALL.md
# With that being said, reporting that this script doesn't work would be nice.
# If you are contributing code to qTox that change its dependencies / the way
# it's being build, please keep in mind that changing just bootstrap.sh
# *IS NOT* and will not be sufficient - you should update INSTALL.md first.
set -eu -o pipefail
# directory where the script is located
readonly SCRIPT_DIR=$( cd $(dirname $0); pwd -P)
# directory where dependencies will be installed
readonly INSTALL_DIR=libs
# just for convenience
readonly BASE_DIR="${SCRIPT_DIR}/${INSTALL_DIR}"
# versions of libs to checkout
readonly TOXCORE_VERSION="v0.2.10"
readonly SQLCIPHER_VERSION="v3.4.2"
# directory names of cloned repositories
readonly TOXCORE_DIR="libtoxcore-$TOXCORE_VERSION"
readonly SQLCIPHER_DIR="sqlcipher-$SQLCIPHER_VERSION"
# default values for user given parameters
INSTALL_TOX=true
INSTALL_SQLCIPHER=false
SYSTEM_WIDE=true
KEEP_BUILD_FILES=false
# if Fedora, by default install sqlcipher
if which dnf &> /dev/null
then
INSTALL_SQLCIPHER=true
fi
print_help() {
echo "Use this script to install/update libtoxcore"
echo ""
echo "usage:"
echo " ${0} PARAMETERS"
echo ""
echo "parameters:"
echo " --with-tox : install/update libtoxcore"
echo " --without-tox : do not install/update libtoxcore"
echo " --with-sqlcipher : install/update sqlcipher"
echo " --without-sqlcipher : do not install/update sqlcipher"
echo " -h|--help : displays this help"
echo " -l|--local : install packages into ${INSTALL_DIR}"
echo " -k|--keep : keep build files after installation/update"
echo ""
echo "example usages:"
echo " ${0} -- install libtoxcore"
}
print_debug_output() {
echo "with tox : ${INSTALL_TOX}"
echo "with sqlcipher : ${INSTALL_SQLCIPHER}"
echo "install system-wide : ${SYSTEM_WIDE}"
echo "keep build files : ${KEEP_BUILD_FILES}"
}
# remove not needed dirs
remove_build_dirs() {
rm -rf "${BASE_DIR}/${TOXCORE_DIR}"
rm -rf "${BASE_DIR}/${SQLCIPHER_DIR}"
}
install_toxcore() {
if [[ $INSTALL_TOX = "true" ]]
then
git clone https://github.com/toktok/c-toxcore.git \
--branch $TOXCORE_VERSION \
--depth 1 \
"${BASE_DIR}/${TOXCORE_DIR}"
pushd ${BASE_DIR}/${TOXCORE_DIR}
# compile and install
if [[ $SYSTEM_WIDE = "false" ]]
then
cmake . -<API key>=${BASE_DIR}
make -j $(nproc)
make install
else
cmake .
make -j $(nproc)
sudo make install
sudo ldconfig
fi
popd
fi
}
install_sqlcipher() {
if [[ $INSTALL_SQLCIPHER = "true" ]]
then
git clone https://github.com/sqlcipher/sqlcipher.git \
"${BASE_DIR}/${SQLCIPHER_DIR}" \
--branch $SQLCIPHER_VERSION \
--depth 1
pushd "${BASE_DIR}/${SQLCIPHER_DIR}"
autoreconf -if
if [[ $SYSTEM_WIDE = "false" ]]
then
./configure --prefix="${BASE_DIR}" \
--enable-tempstore=yes \
CFLAGS="-DSQLITE_HAS_CODEC"
make -j$(nproc)
make install || \
echo "" && \
echo "Sqlcipher failed to install locally." && \
echo "" && \
echo "Try without \"-l|--local\"" && \
exit 1
else
./configure \
--enable-tempstore=yes \
CFLAGS="-DSQLITE_HAS_CODEC"
make -j$(nproc)
sudo make install
sudo ldconfig
fi
popd
fi
}
main() {
while [ $# -ge 1 ]
do
if [ ${1} = "--with-tox" ]
then
INSTALL_TOX=true
shift
elif [ ${1} = "--without-tox" ]
then
INSTALL_TOX=false
shift
elif [ ${1} = "--with-sqlcipher" ]
then
INSTALL_SQLCIPHER=true
shift
elif [ ${1} = "--without-sqlcipher" ]
then
INSTALL_SQLCIPHER=false
shift
elif [ ${1} = "-l" -o ${1} = "--local" ]
then
SYSTEM_WIDE=false
shift
elif [ ${1} = "-k" -o ${1} = "--keep" ]
then
KEEP_BUILD_FILES=true
shift
else
if [ ${1} != "-h" -a ${1} != "--help" ]
then
echo "[ERROR] Unknown parameter \"${1}\""
echo ""
print_help
exit 1
fi
print_help
exit 0
fi
done
print_debug_output
# create BASE_DIR directory if necessary
mkdir -p "${BASE_DIR}"
# maybe an earlier run of this script failed
# thus we should remove the cloned repositories
# if they exist, otherwise cloning them may fail
remove_build_dirs
install_toxcore
install_sqlcipher
# remove cloned repositories
if [[ $KEEP_BUILD_FILES = "false" ]]
then
remove_build_dirs
fi
}
main $@
|
import moment from 'moment';
import <API key> from './controller/publications.controller.js';
import AuthorsController from './controller/authors.controller.js';
import <API key> from './controller/publishers.controller.js';
/*
* Application routing
*/
function routing($routeProvider) {
$routeProvider
.when('/publications', {
template: require('./view/publications.html'),
controller: <API key>,
controllerAs: 'vm'
})
.when('/authors', {
template: require('./view/authors.html'),
controller: AuthorsController,
controllerAs: 'vm'
})
.when('/publishers', {
template: require('./view/publishers.html'),
controller: <API key>,
controllerAs: 'vm'
})
.otherwise({ redirectTo: '/publications' });
}
routing.$inject = ['$routeProvider'];
/*
* Theming configuration for Material AngularJS
*/
function theming($mdThemingProvider) {
$mdThemingProvider
.theme('default')
.primaryPalette('indigo')
.accentPalette('red');
}
theming.$inject = ['$mdThemingProvider'];
/*
* Date localization configuration
*/
function dateLocalization($<API key>) {
const dateFmt = 'YYYY-MM-DD';
$<API key>.formatDate = (date) => {
return moment(date).format(dateFmt);
};
$<API key>.parseDate = (str) => {
const m = moment(str, dateFmt);
return m.isValid() ? m.toDate() : new Date(NaN);
};
}
dateLocalization.$inject = ['$<API key>'];
export { routing, theming, dateLocalization };
|
#include "<API key>.h"
#include "wololo/datPatch.h"
namespace wololo {
void <API key>(genie::DatFile *aocDat, std::map<int, std::string> *langReplacement) {
/*
* Disabling units that are not supposed to show in the scenario editor
*/
for (size_t civIndex = 0; civIndex < aocDat->Civs.size(); civIndex++) {
aocDat->Civs[civIndex].Units[1119].HideInEditor = 1;
aocDat->Civs[civIndex].Units[1145].HideInEditor = 1;
aocDat->Civs[civIndex].Units[1147].HideInEditor = 1;
aocDat->Civs[civIndex].Units[1221].HideInEditor = 1;
aocDat->Civs[civIndex].Units[1401].HideInEditor = 1;
for (size_t unitIndex = 1224; unitIndex <= 1390; unitIndex++) {
aocDat->Civs[civIndex].Units[unitIndex].HideInEditor = 1;
}
}
}
DatPatch <API key> = {
&<API key>,
"Hide units in the scenario editor"
};
}
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name='viewport' content='width=device-width, initial-scale=1.0, user-scalable=yes'>
<title>Video Poker</title>
<style>
@import url('https://fonts.googleapis.com/css?family=Luckiest+Guy');
body { background-color:#0032b4; color:#fff; font-family:"Helvetica Neue",Helvetica,sans-serif; font-size:1vw; }
#main { perspective:1000px; position:absolute; top:0px; right:0px; bottom:0px; left:0px; text-align:center; }
#paytable {
display:none;
width:90%;
color:#ffffff;
border: 4px outset #0df;
margin:.5em auto 0px;
background-color:#142850;
border-collapse:collapse;
line-height:1em;
font-weight: 700; font-size:130%;text-transform: uppercase;
}
#paybet { background-color:#0af; color:#ff0;border-bottom: 2px solid #fff; }
#paytable td#paybet1, #paytable td#paybet2,#paytable td#paybet3,#paytable td#paybet4,#paytable td#paybet5 { background-color:#0af; color:#ff0; text-align:center; border-bottom: 2px solid #fff; }
table#paytable .paybet { background-color:#c00; color:#ff0; }
#paytable td { text-align:left; border-left:3px solid #0af; white-space:nowrap; padding:.125em .25em .125em .25em;}
#paytable td.right { text-align:right; }
.paybet { background-color:#ff0; }
#toolbar { display:inline-block; position:absolute; left:0px; bottom:0px; right:0px; height:15%; text-align:center; background-color:rgba(0,0,0,.5); }
button { z-index:999; margin-top:1em; font-size:200%; color:#000; background-color:#cccc00; border:.25em outset #ffff00; width:7em; height 3em; text-transform:uppercase; height:3em; font-weight:bold; position:relative; text-shadow: 2px 2px 1px rgba(255,255,255,.5);}
button.disabled { color: #cccc00; text-shadow: none; }
.right { text-align:right; }
.left { text-align:left; }
h2 { width:3.3vw; height:6.1vh; margin:0; padding:1.3vw 1.6vw 1.1vw 0.7vw; color:#fff; z-index:9999; border-radius:5vw; display:inline-block; border:0.6vw dashed #fff; font-size:3vw; top:-1vh; position:relative; letter-spacing:-4px; text-shadow:-1px -2px 0px #000; }
.status { display:inline-block; }
#bet { width:30%; color:#eee; position:absolute; left:2vw; height:8vh; font-size:3vw; top:5vh; text-align:left; }
#bet:before { content: "BET: "; }
#credit { width:30vw; color:#eef; position:absolute; right:2vw; height:8vh; font-size:3vw; top:5vh; text-align:right; }
#credit:before { content: "CREDITS: "; }
#win { width:33%; color:#eee; position:absolute; left:33%; height:9vh; top:5vh; font-size:3vw;z-index:9999; }
@keyframes bounce {
0% { transform: rotate(0deg) scale(1); }
10% { transform: rotate(-15deg) scale(1.5); }
20% { transform: rotate(15deg) scale(1); }
30% { transform: rotate(-10deg) scale(1.5); }
40% { transform: rotate(10deg) scale(1); }
50% { transform: rotate(-5deg) scale(1.5); }
60% { transform: rotate(5deg) scale(1); }
70% { transform: scale(1.5); }
80% { transform: scale(1); }
90% { transform: scale(1.5); }
100% { transform: scale(1); }
}
.handresult {
font-size:2em;
background-color:rgba(174,84,231,1);
color:#fff;
border:.25vw solid rgba(107,36,154,1);
<API key>:1vw;
<API key>:1vw;
font-weight:bold;
text-shadow:2px 2px 2px #000;
z-index:99999;
width:100%;
position:absolute;
bottom:-0.2vh;
left:0;
display:none;
overflow:hidden;
transition:all 300ms cubic-bezier(.25, .99, .71, 1.23);
height:5vh;
text-transform:uppercase;
}
#cards .handresult {
font-size:3vw;
bottom:-1.5vh;
height:7vh;
}
#won {
position: absolute;
display: inline-block;
width:50vw;
top: 22%;
left: 20%;
font-size: 1.5vw;
color: #f9e945;
text-shadow: 2px 2px 0px #000;
font-weight: bold;
background-color: rgba(0,0,0,.5);
padding: 2vh 4vw 2vh;
border-radius: 4vw;
border: 1vw solid rgb(249, 233, 69);
transform: scale(1);
z-index: 99999;
box-shadow: 0 0.5vw 0.5vw rgba(0,0,0,.4);
animation: bounce 2s 2;
display:none;
animation: win 2000ms 2;
}
#won button { border-radius:4vw; }
@keyframes win {
0% { text-shadow:0 0 0 #fff; transform:scale(1); }
10% { transform:scale(1.25); }
20% { transform:scale(1.0); }
30% { transform:scale(1.25); }
40% { transform:scale(1.0); }
50% { text-shadow:0 0 6vw #fff; }
60% { text-shadow:0 0 0vw #fff; }
70% { text-shadow:0 0 6vw #fff; }
80% { text-shadow:0 0 0vw #fff; }
90% { text-shadow:0 0 6vw #fff; transform:scale(1.25); }
100% { text-shadow:0 0 0vw #fff; transform:scale(1.0); }
}
table#paytable tr.winner { background-color:#00d8ff; color:#000;}
td.winner { background-color:#fff; transform:scale(1); text-align:center; animation: throb 2s; }
#results { margin-top:-2em; display:none;}
.status { height: 10vh; position: absolute; font-weight: bold; bottom:16vh; text-shadow: 2px 2px 1px rgba(0,0,0,.5); left: 0px; width:100%; z-index:99; }
@keyframes throb {
0% { transform: scale(2); }
20% { transform: scale(1); }
40% { transform: scale(2); }
60% { transform: scale(1); }
80% { transform: scale(2); }
100% { transform: scale(1); }
}
th { border-bottom:3px solid #0df; border-right:3px solid #0df; }
#payleft, #payright {
position:absolute;
line-height:1.4vw;
bottom:15vh;
width:16vw;
height:42vh;
}
#payleft { left:0px; }
#payright { right:0px; }
.payline {
background-color: #f00;
margin: 0.2vh .5vw;
font-size: 1.25vw;
text-transform: uppercase;
text-align: center;
text-shadow: 1.5px 1.5px 0px #000;
border-radius: 1.5vw;
border: 0.2vw outset;
font-weight: bold;
padding-bottom: 0.3vh;
}
.pay {
background-color: #000;
display: block;
width: 10vw;
margin: 0 auto 0vh;
border: 2px inset #ff0;
padding:0.4vh 2vw;
<API key>:1.2vw;
<API key>:1.2vw;
}
#gameselect {
position:absolute;
display:inline-block;
bottom:11vh;
left:18vw;
width:24vw;
height:0vh;
background:linear-gradient(to top, #f4e130 0%,#fff460 100%);
z-index:999;
font-size:2.4vw;
color:#000;
text-shadow:1px 1px 0px #fff;
box-shadow:.25vw -.25vw .25vw rgba(0,0,0,.4), -.25vw 0 .25vw rgba(0,0,0,.4);
overflow:hidden;
font-weight:500;
text-transform:uppercase;
transition:all 300ms cubic-bezier(.25, .99, .71, 1.23);
text-align:left;
}
#handselect {
position:absolute;
display:inline-block;
bottom:11vh;
left:32.3vw;
width:14vw;
height:0vh;
background:linear-gradient(to top, #f4e130 0%,#fff460 100%);
z-index:999;
text-align:center;
font-size:3vw;
color:#000;
text-shadow:1px 1px 0px #fff;
box-shadow:.25vw -.25vw .25vw rgba(0,0,0,.4), -.25vw 0 .25vw rgba(0,0,0,.4);
overflow:hidden;
font-weight:500;
text-transform:uppercase;
transition:all 300ms cubic-bezier(.25, .99, .71, 1.23);
}
div#handselect.open { height:33vh; }
div#gameselect.open { height:36vh; }
#handselect input { display:none; }
#handcount { margin:0; padding:0; }
#gameslist { margin:0; padding:0; }
#gameslist li { list-style-type:none; border-bottom:1px solid #660; cursor:pointer; padding:1vh;}
.gameslistSelected { background-color:#660; color:#fff; }
#handcount li {
list-style-type:none;
border-bottom: 1px solid #660;
cursor:pointer;
}
.handcountSelected {
background-color:#660;
color:#fff;
}
#doubleup {
position:absolute;
display:none;
top:0;
left:0;
right:0;
bottom:0;
background-color:#0032b4;
z-index:99999;
width:100%;
}
#doubleup .cardwrap .card { width:90%; height:90%; }
#doubleup .cardwrap { padding-left:2.5vw; }
#doubleheader { font-size:2vw; font-family:"Luckiest Guy", cursive; }
#doubleheader h1 { color:#c00; -webkit-text-stroke: .125vw #ff0; font-size:2em; }
#doubleheader button {font-size:1.5vw;margin-left:2vw; }
.dealercardlabel { display: inline-block; position: relative; top: -2.2vh; background-color: #0032b4; color: #ff0; font-size: 1.5em; padding: 0px 0.25vw; left: -1.6vw; font-weight: bold; text-shadow: 2px 2px 0px #000; white-space: nowrap;}
#doubledealer { display: inline-block; width: 12vw; margin-right: 4vw; border: .25vw solid #ff0; border-radius: 1vw; padding-left: 3vw; height: 38vh; }
</style>
<link rel='manifest' href='manifest.json'>
<link rel='stylesheet' type='text/css' href='poker5.css'>
<script src="pokersolver.js"></script>
<script src="https:
<script>
// Initialize Firebase
var config = {
apiKey: "<Google Api>",
authDomain: "crblackjack-9e220.firebaseapp.com",
databaseURL: "https://crblackjack-9e220.firebaseio.com",
projectId: "crblackjack-9e220",
storageBucket: "crblackjack-9e220.appspot.com",
messagingSenderId: "32143422101"
};
firebase.initializeApp(config);
</script>
</head>
<body>
<div id='main'>
<table id='paytable'>
<colgroup>
<col>
<col id='bet1pay'>
<col id='bet2pay'>
<col id='bet3pay'>
<col id='bet4pay'>
<col id='bet5pay'>
</colgroup>
</table>
<div id='holds'>
<div id='card0-hold' class='hold'></div>
<div id='card1-hold' class='hold'></div>
<div id='card2-hold' class='hold'></div>
<div id='card3-hold' class='hold'></div>
<div id='card4-hold' class='hold'></div>
</div>
<div id='hands'>
</div>
<div id='payleft'></div>
<div id='cards'>
<div id='card0' class='cardwrap'><div class='card card1H'><figure class='pic'> </figure></div><div class='cardback'><figure class='pic'> </figure></div></div>
<div id='card1' class='cardwrap'><div class='card card13H'><figure class='pic'> </figure></div><div class='cardback'><figure class='pic'> </figure></div></div>
<div id='card2' class='cardwrap'><div class='card card12H'><figure class='pic'> </figure></div><div class='cardback'><figure class='pic'> </figure></div></div>
<div id='card3' class='cardwrap'><div class='card card11H'><figure class='pic'> </figure></div><div class='cardback'><figure class='pic'> </figure></div></div>
<div id='card4' class='cardwrap'><div class='card card10H'><figure class='pic'> </figure></div><div class='cardback'><figure class='pic'> </figure></div></div>
<div id='result' class='handresult'></div>
</div>
<div id='payright'></div>
<div id='status' class='status'>
<div id='bet'>0</div>
<div id='win'></div>
<div id='credit'></div>
</div>
<div id='won'></div>
<div id='gameover'>PLAY 5 CREDITS</div>
<div id='gameselect'>
<ul id='gameslist'>
<li id='game_poker'>Jacks or Better</li>
<li id='game_bonus'>Bonus Poker</li>
<li id='game_doublebonus'>Double Bonus</li>
<li id='game_dueces'>Dueces Wild</li>
<li id='game_joker'>Joker Poker</li>
</ul>
</div>
<div id='handselect'>
<ul id='handcount'>
<li id='handcount5'>5</li>
<li id='handcount10'>10</li>
<li id='handcount25'>25</li>
<li id='handcount50'>50</li>
<li id='handcount100'>100</li>
</ul>
</div>
<div id='toolbar'>
<span class='left'>
<button onclick='cdr.login()' class='leftButton' id='loginButton'>Login</button>
<button onclick='cdr.changeGames()' id='gamesButton'>Games</button>
<button onclick='cdr.changeHands()' id='handsButton'>Hands</button>
</span>
<h2 id='denom'>$1</h2>
<span class='right'>
<button onclick='cdr.betone()' id='betOne'>Bet 1</button>
<button onclick='cdr.betmax()' id='betMax'>Bet 5</button>
<button id='dealdrawButton' onclick='cdr.dealdraw()' disabled='true' class='rightButton disabled'>Deal</button>
</span>
</div>
<div id='doubleup'>
<div id='doubleheader'>
<h1>Double Up?</h1>
<p>YOU WON $<span id='doublewin'>0</span></p>
<p>DOUBLE UP TO $<span id='doubledouble'>0</span></p>
<p>
<button id='doubleButton'>Double</button>
<button id='collectButton'>Collect</button>
</p>
</div>
<div id='doublecards'>
<div id='doubledealer'><span class='dealercardlabel'>DEALERS CARD</span><br><div id='doublecard0' class='cardwrap flipped' ><div class='card card1S'><figure class='pic'> </figure></div><div class='cardback'><figure class='pic'> </figure></div></div></div>
<div id='doublecard1' class='cardwrap flipped'><br><div class='card card3H'><figure class='pic'> </figure></div><div class='cardback'><figure class='pic'> </figure></div></div>
<div id='doublecard2' class='cardwrap flipped'><br><div class='card card8D'><figure class='pic'> </figure></div><div class='cardback'><figure class='pic'> </figure></div></div>
<div id='doublecard3' class='cardwrap flipped'><br><div class='card card11C'><figure class='pic'> </figure></div><div class='cardback'><figure class='pic'> </figure></div></div>
<div id='doublecard4' class='cardwrap flipped'><br><div class='card card10H'><figure class='pic'> </figure></div><div class='cardback'><figure class='pic'> </figure></div></div>
</div>
</div>
</div>
<script>
(function() {
window.cdr = {
game: {
endpoint: "https://<API key>.cloudfunctions.net/",
hands: 10,
type: "poker",
wilds: "",
chipColors: ["#dd0", "#0c0", "#c00", "#c0c", "#000", "#0be", "#fa0", "#999", "#0a6", "#69a", "#333", "#000"],
creditValues: [ 1, 2, 5, 10, 25, 100, 250, 500, 1000, 2000, 5000, 10000, 50000 ],
creditValueIdx:0,
creditValue:1,
cards: [],
discards: {},
holds: {},
bet: 0,
credit: 1000,
uid:"",
stage:0
},
paytable: {
"RoyalFlush": { hand: 'Royal Flush', win: [ 250, 500, 750, 1000, 4000]},
"StraightFlush": { hand: 'Straight Flush', win: [ 50, 100, 150, 200, 250]},
"FourOfAKind": { hand: 'Four of a Kind', win: [ 25, 50, 75, 100, 125]},
"FullHouse": { hand: 'Full House', win: [ 9, 18, 27, 36, 45]},
"Flush": { hand: 'Flush', win: [ 6, 12, 18, 24, 30]},
"Straight": { hand: 'Straight', win: [ 4, 8, 12, 16, 20]},
"ThreeOfAKind": { hand: 'Three of a Kind', win: [ 3, 6, 9, 12, 15]},
"TwoPair": { hand: 'Two Pair', win: [ 2, 4, 6, 8, 10]},
"OnePair": { hand: 'Jacks or Better', win: [ 1, 2, 3, 4, 5]}
},
games: {
"poker": "Jacks or Better",
"bonus": "Bonus Poker",
"doublebonus": "Double Bonus Poker",
"dueces": "Dueces Wild",
"joker": "Joker Poker"
},
addListener: function(i) {
$$("card" + i).addEventListener("click", function(e) { cdr.toggleCard("card" + i, 0); });
},
changeGames: function() {
$$("game_"+cdr.game.type).classList.add('gameslistSelected');
$$("gameselect").classList.toggle("open");
$$("handselect").classList.remove("open");
},
changeHands: function() {
$$("handcount"+cdr.game.hands).classList.add('handcountSelected');
$$("handselect").classList.toggle("open");
$$("gameselect").classList.remove("open");
},
betone: function() {
$$("handselect").classList.remove("open");
$$("gameselect").classList.remove("open");
if (cdr.game.bet > 0) $(".paybet").classList.remove('paybet');
cdr.game.bet++;
if (cdr.game.bet > 5) {
cdr.game.bet = 0;
$$("dealdrawButton").setAttribute("disabled", true);
$$("dealdrawButton").classList.add("disabled");
}
if (cdr.game.bet > 0) {
$$("dealdrawButton").removeAttribute("disabled");
$$("dealdrawButton").classList.remove("disabled");
$$("paytable").className = "paybet" + cdr.game.bet;
if ($(".paybet")) $(".paybet").classList.remove('paybet');
$$("bet"+cdr.game.bet+"pay").classList.add('paybet');
}
$$("bet").innerHTML = cdr.game.bet + "x"+cdr.game.hands;
cdr.genPaytable();
},
betmax: function() {
$$("handselect").classList.remove("open");
$$("gameselect").classList.remove("open");
cdr.game.bet = 5;
if (cdr.game.bet > 0) {
$$("dealdrawButton").removeAttribute("disabled");
$$("dealdrawButton").classList.remove("disabled");
$$("dealdrawButton").innerHTML = "DEAL";
$$("paytable").className = "paybet" + cdr.game.bet;
if ($(".paybet")) $(".paybet").classList.remove('paybet');
$$("bet"+cdr.game.bet+"pay").classList.add('paybet');
} else {
$$("dealdrawButton").setAttribute("disabled");
$$("dealdrawButton").classList.add("disabled");
}
$$("bet").innerHTML = cdr.game.bet + "x" + cdr.game.hands + "(" + (cdr.game.bet * cdr.game.hands) + ")";
cdr.genPaytable();
cdr.deal();
},
dealdraw: function() {
$$("handselect").classList.remove("open");
$$("gameselect").classList.remove("open");
if (cdr.game.stage === 0) {
cdr.deal();
} else if (cdr.game.stage === 1) {
cdr.draw();
}
},
addListeners: function() {
$$("cards").addEventListener("mousedown", function(e) {
var tgt = e.target;
if (tgt.classList.contains('card')) {
cdr.toggleCard(tgt.parentNode.id, 0, 0);
} else if (tgt.classList.contains('cardwrap')) {
cdr.toggleCard(tgt.id, 0, 0);
}
});
$$("gameslist").addEventListener("click", function(e) {
$(".gameslistSelected").classList.remove("gameslistSelected");
var tgt = e.target;
var matches = tgt.id.match(/game_(\w+)/);
if (matches[1]) {
cdr.game.type = matches[1];
tgt.classList.add('gameslistSelected');
var url = document.location.href.replace(/
document.location.href = url + "#" + cdr.game.type;
$$("gameselect").classList.remove('open');
cdr.init();
$$('win').innerHTML = tgt.innerHTML;
cdr.settings.type = matches[1];
localStorage.setItem("settings", JSON.stringify(cdr.settings));
}
});
$$("handcount").addEventListener("click", function(e) {
var tgt = e.target;
var matches = tgt.id.match(/handcount(\d+)/);
if (matches[1]) {
var newcount = parseInt(matches[1]);
cdr.switchHands(newcount);
cdr.settings.hands = newcount;
localStorage.setItem("settings", JSON.stringify(cdr.settings));
}
});
$$("denom").addEventListener("click", function(e) {
cdr.game.creditValueIdx++;
if (cdr.game.creditValueIdx > cdr.game.creditValues.length - 1) cdr.game.creditValueIdx = 0;
if (cdr.game.balance / cdr.game.creditValues[cdr.game.creditValueIdx] < 0) cdr.game.creditValueIdx = 0;
cdr.game.creditValue = cdr.game.creditValues[cdr.game.creditValueIdx];
cdr.updateChip();
cdr.updateCredits();
cdr.settings.creditValue = cdr.game.creditValue;
cdr.settings.creditValueIdx = cdr.game.creditValueIdx;
localStorage.setItem("settings", JSON.stringify(cdr.settings));
});
},
init: function() {
if (document.location.hash) {
cdr.game.type = document.location.hash.replace(/^
if (cdr.game.type==="dueces") {
$$("main").classList.add('wilds');
cdr.game.wilds = "wilds";
} else {
cdr.game.wilds = "";
}
}
var savedJS = localStorage.getItem("settings");
if (savedJS) {
cdr.settings = JSON.parse(savedJS);
for (var i in cdr.settings) {
if (cdr.settings.hasOwnProperty(i)) {
cdr.game[i] = cdr.settings[i];
}
}
}
cdr.updateChip();
cdr.genPaytable();
cdr.makeHands();
//var cards = cdr.newDeck();
$$("main").classList.add("hands"+cdr.game.hands);
$$("gameover").style.transform = "scale(1)";
$$("gameover").innerHTML = cdr.games[cdr.game.type];
if (!cdr.game.listening) {
cdr.addListeners();
cdr.game.listening = true;
}
},
switchHands: function(handcount) {
$$("handcount"+cdr.game.hands).className = "";
$$("handcount"+handcount).className = "handcountSelected";
cdr.game.hands = handcount;
setTimeout(function() { $$("handselect").classList.remove("open"); }, 250);
setTimeout(function() {
cdr.makeHands();
$$("main").className = "hands"+cdr.game.hands + " " + cdr.game.wilds;
}, 250);
},
updateChip: function() {
$$("denom").className = "chip" + cdr.game.creditValue;
$$("denom").style.backgroundColor = cdr.game.chipColors[cdr.game.creditValueIdx];
var show = (cdr.game.creditValue>999) ? (cdr.game.creditValue / 1000) + "K" : cdr.game.creditValue;
$$("denom").innerHTML = "$" + show;
},
updateCredits: function() {
var uid = cdr.game.uid;
firebase.database().ref("bank/"+uid+"/balance").on("value", function(snapshot) {
var balance = snapshot.val();
cdr.game.balance = balance;
cdr.game.credit = Math.floor(balance / cdr.game.creditValue);
var showCredit = cdr.game.credit;
if (showCredit > 1000000000) {
showCredit = Math.floor(showCredit / 1000000) / 100 + "B";
} else if (showCredit > 1000000) {
showCredit = Math.floor(showCredit / 1000) / 100 + "M";
} else if (showCredit > 1000) {
showCredit = Math.floor(showCredit / 100) / 10 + "K";
}
$$("credit").innerHTML = showCredit;
if ((cdr.game.credit < 1) || cdr.game.active) {
cdr.disable("betOne");
cdr.disable("betMax");
} else if (cdr.game.credit < 5) {
cdr.enable("betOne");
cdr.disable("betMax");
} else {
cdr.enable("betOne");
cdr.enable("betMax");
}
});
},
disable: function(item) {
$$(item).setAttribute("disabled",true);
$$(item).classList.add('disabled');
},
enable: function(item) {
$$(item).removeAttribute("disabled");
$$(item).classList.remove('disabled');
},
toggleCard: function(card, delay) {
// setTimeout(function() { $$(card).classList.toggle('flipped'); }, delay * 100);
var current = $$(card + '-hold').style.visibility;
if (current==="hidden") {
$$(card + '-hold').style.visibility = "";
cdr.game.holds[card] = true;
for (var i=1; i < cdr.game.hands; i++) {
$("#hand"+i+card+" .card").className = $("#"+card+" .card").className;
// $$("hand"+i+card).classList.remove('flipped');
cdr.showCard("hand"+i+card, 0, 0);
}
} else {
$$(card + '-hold').style.visibility = "hidden";
for (var i=1; i < cdr.game.hands; i++) {
// $$("hand"+i+card).classList.add('flipped');
cdr.hideCard("hand"+i+card, 0, 0);
}
delete cdr.game.holds[card];
}
// if (cdr.game.discards[card]) { delete cdr.game.discards[card]; } else { cdr.game.discards[card] = true; }
},
hideCard: function(card, delay) {
setTimeout(function() { $$(card).classList.add('flipped'); setTimeout(function() { $("#"+card+" .card").style.visibility='hidden';}, 100); }, delay * 10);
},
showCard: function(card, delay, wait=500) {
setTimeout(function() { $("#"+card+" .card").style.visibility='visible'; $$(card).classList.remove('flipped'); }, (delay * 10) + wait);
},
setCard: function(i, draw, delay) {
setTimeout(function() { $("#card" + i + " .card").className = 'card card' + draw; }, (delay * 100));
},
clearHolds: function() {
for (var i=0; i<5; i++) {
$$("card"+i+"-hold").style.visibility = "hidden";
}
cdr.game.holds = [];
},
newCard: function(card, newcard, delay) {
var match = card.match(/card(\d)/);
cdr.game.cards[match[1]] = newcard;
setTimeout(function() {
$("#" + card + " .card").className = "card card" + newcard;
}, delay * 75);
},
draw: function() {
var cnt = 0;
var needcards = [];
$$("dealdrawButton").setAttribute("disabled", true);
$$("dealdrawButton").classList.add('disabled');
$$("dealdrawButton").innerHTML = "DEAL";
for (var i=0; i<5; i++) {
if (!cdr.game.holds["card"+i]) {
cdr.hideCard('card' + i, cnt);
cnt++;
cdr.game.discards["card"+i] = true;
needcards.push(i);
}
}
var scr = document.createElement('script');
scr.src = cdr.game.endpoint + "exchangeCards?game="+cdr.game.type+"&callback=cdr.newCards&hands=" + cdr.game.hands + "&uid=" + firebase.auth().currentUser.uid + "&discard=" + needcards.join(',');
document.body.appendChild(scr);
},
newCards: function(cards) {
console.log("cards: "+JSON.stringify(cards));
console.dir(cards);
cdr.game.results = cards;
cdr.game.resultCounts = {};
cdr.game.stage = 2;
var cnt = 0;
var wintot = 0;
var c = cards.hands[0];
for (var j=0; j < c.length; j++) {
if ($$("card"+j).classList.contains('flipped')) {
$("#card"+j+" .card").className = "card card" + c[j];
$("#card"+j+" .card").style.visibility = "visible";
cdr.showCard("card"+j, cnt, 0);
cnt++;
}
}
if (cards.results[0]) {
cdr.showResult(0, cards);
wintot += cards.wins[0];
if (!cdr.game.resultCounts[cards.results[0]]) cdr.game.resultCounts[cards.results[0]] = 0;
cdr.game.resultCounts[cards.results[0]]++;
cdr.genPaytable(cdr.game.resultCounts);
}
var discards = 0;
for (var i=1; i < cards.hands.length; i++) {
var c = cards.hands[i];
for (var j=0; j < c.length; j++) {
if ($$("hand"+i+"card"+j).classList.contains('flipped')) {
$("#hand"+i+"card"+j+" .card").className = "card card" + c[j];
cdr.showCard("hand"+i+"card"+j, cnt, 0);
}
}
cnt++;
if (!discards) discards = cnt;
if (cards.results[i]) {
cdr.showResult(i, cards);
wintot += cards.wins[i];
if (!cdr.game.resultCounts[cards.results[i]]) cdr.game.resultCounts[cards.results[i]] = 0;
cdr.updatePaytable(i, cards.results[i]);
}
}
if (wintot > 0) {
setTimeout(function() {
$$("won").innerHTML = "<h1>YOU'VE WON "+Math.floor(wintot / cdr.game.creditValue)+" CREDITS!</h1><h1>\"DOUBLE IT\" TO "+Math.floor(wintot / cdr.game.creditValue) * 2 +"?</h1><button onclick='cdr.doubleup()'>DOUBLE IT</button> <button onclick='$$(\"won\").style.display = \"none\"'>COLLECT</button>";
$$("won").style.display = "inline-block";
$$("win").innerHTML = "WIN: "+Math.floor(wintot / cdr.game.creditValue);
cdr.resetButtons();
cdr.game.active = false;
cdr.game.stage = 0;
/*setTimeout(function() {
$$("doublewin").innerHTML = Math.floor(wintot / cdr.game.creditValue);
$$("doubledouble").innerHTML = Math.floor(wintot / cdr.game.creditValue) * 2;
$$("doubleup").style.display = "inline-block";
}, 2000);*/
}, cnt * 25);
} else {
cdr.gameoverTimeout = setTimeout(function() { $$("gameover").innerHTML = "GAME OVER"; $$("gameover").style.transform = "scale(1)"; }, 1000);
cdr.game.active = false;
cdr.resetButtons();
cdr.game.stage = 0;
}
},
updatePaytable: function(cnt, hand) {
setTimeout(function() {
cdr.game.resultCounts[hand]++;
cdr.genPaytable(cdr.game.resultCounts);
}, cnt * 10);
},
showResult: function(i, cards) {
var el = (i > 0) ? $$("hand"+i+"result") : $$("result");
setTimeout(function() {
el.innerHTML = cards.results[i].replace(/([a-z0-9])([A-Z0-9])/g, '$1 $2').replace(/([A-Z])([A-Z])/g, '$1 $2');
el.style.display = "inline-block";
el.style.height = "";
}, 10 * i);
},
checkWin: function() {
var scr = document.createElement('script');
scr.src = cdr.game.endpoint + "checkHand?callback=cdr.gotWin&game="+cdr.game.type+"&uid=" + firebase.auth().currentUser.uid;
document.body.appendChild(scr);
},
gotWin: function(hand, won) {
if (hand && won) {
var win = cdr.paytable[hand];
if (win) {
$$("win").innerHTML = win.hand;
$$("won").style.display = "inline-block";
$$("won").innerHTML = "WON " + win.win[cdr.game.bet - 1];
cdr.clearWinners();
$$(hand).classList.add('winner');
$$(hand + (cdr.game.bet - 1)).classList.add('winner');
cdr.gameoverTimeout = setTimeout(function() { $$("gameover").innerHTML = "GAME OVER"; $$("gameover").style.transform = "scale(1)"; }, 10000);
}
} else {
$$("gameover").innerHTML = "GAME OVER";
$$("gameover").style.transform = "scale(1)";
}
cdr.resetButtons();
cdr.game.active = false;
},
resetButtons: function() {
$$("gamesButton").classList.remove('disabled');
$$("gamesButton").removeAttribute('disabled');
$$("handsButton").classList.remove('disabled');
$$("handsButton").removeAttribute('disabled');
$$("handselect").classList.remove("open");
$$("gameselect").classList.remove("open");
$$("betOne").classList.remove('disabled');
$$("betOne").removeAttribute('disabled');
$$("betMax").classList.remove('disabled');
$$("betMax").removeAttribute('disabled');
if (cdr.game.bet) {
$$("dealdrawButton").classList.remove('disabled');
$$("dealdrawButton").removeAttribute('disabled');
} else {
$$("dealdrawButton").classList.add('disabled');
$$("dealdrawButton").setAttribute('disabled');
}
$$("dealdrawButton").innerHTML = "DEAL";
},
clearWinners: function() {
var els = $$$('.winner');
for (var i=0; i<els.length; i++) {
els[i].classList.remove('winner');
}
$$("result").style.display = "none";
for (var i=1; i<5; i++) {
$$("hand"+i+"result").style.display = "none";
}
},
resetCards: function() {
for (var h=1; h < cdr.game.hands; h++) {
for (var c=0; c < 5; c++) {
$$("hand"+h+"card"+c).classList.add('flipped');
}
$$("hand"+h+"result").style.height = "0";
}
setTimeout(function() {
var els = $$$(".handresult");
for (var i in els) {
if (els.hasOwnProperty(i)) {
els[i].style.display = "none";
}
}
}, 150);
},
deal: function() {
if (cdr.game.bet == 0) {
$$("gameover").innerHTML = "ADD CREDITS TO PLAY";
return false;
}
if (cdr.gameoverTimeout) {
clearTimeout(cdr.gameoverTimeout);
cdr.gameoverTimeout = 0;
}
$$("gameover").style.transform = "scale(0)";
$$("won").style.display = "none";
cdr.game.active = true;
cdr.game.stage = 1;
cdr.clearHolds();
cdr.clearWinners();
cdr.resetCards();
$$("win").innerHTML = "";
$$("won").innerHTML = "";
$$("won").style.display = "none";
$$("gamesButton").classList.add("disabled");
$$("gamesButton").setAttribute("disabled", true);
$$("handsButton").classList.add("disabled");
$$("handsButton").setAttribute("disabled", true);
$$("dealdrawButton").innerHTML = "DRAW";
$$("betOne").classList.add("disabled");
$$("betOne").setAttribute("disabled", true);
$$("betMax").classList.add("disabled");
$$("betMax").setAttribute("disabled", true);
cdr.game.cards = [];
cdr.game.discards = [];
cdr.newDeck();
var func = document.createElement('script');
func.src = cdr.game.endpoint + "newGame?game="+cdr.game.type+"&hands="+cdr.game.hands+"&callback=cdr.gotGame&uid=" + firebase.auth().currentUser.uid + "&bet=" + cdr.game.bet * cdr.game.creditValue;
document.body.appendChild(func);
},
gotGame: function(cards) {
for (var i=0; i<5; i++) {
draw = cards[i];
cards.push(draw);
cdr.hideCard("card" + i, i);
cdr.setCard(i, draw, i);
cdr.showCard("card" + i, i + 1);
}
cdr.game.cards = cards;
cdr.game.active = true;
cdr.game.draws = 1;
},
solve: function() {
var hand = [];
for (var i=0; i<cdr.game.cards.length; i++) {
var card = cdr.game.cards[i].toLowerCase();
var match = card.match(/(\d*)([cdsh])/i);
var num = parseInt(match[1]);
var suit = match[2];
if ((num > 9) || (num==1)) {
switch (num) {
case 1:
num = "A";
break;
case 10:
num = "T";
break;
case 11:
num = "J";
break;
case 12:
num = "Q";
break;
case 13:
num = "K";
break;
}
}
hand.push(num + suit);
}
console.log("hand:");
console.dir(hand);
var result = Hand.solve(hand, "jacksbetter", true);
cdr.game.result = result.constructor.name;
console.dir(result);
return result;
},
solveHand: function(hand) {
var suits = [];
var cards = [];
var seen = {};
var suit = '';
var canFlush = 1;
var haveAce = 0;
for (var i=0; i<hand.length; i++) {
var match = hand[i].match(/^(\d+)([HDSC])/i);
if (match[1] && match[2]) {
if (suit === '') suit = match[2];
if (match[1] == 1) {
haveAce++;
}
if (suit && (suit !== match[2])) {
canFlush = 0;
}
if (!seen[match[1]]) {
seen[match[1]] = 1;
} else {
seen[match[1]]++;
}
cards.push(parseInt(match[1]));
suits.push(match[2]);
}
}
var isFlush = canFlush;
cards = cards.sort(function(a, b) { return a - b; });
var lastCard, isStraight = true;
for (var i=0; i<cards.length - 1; i++) {
if (!lastCard) {
lastCard = parseInt(cards[i]);
} else if ((lastCard + 1) !== parseInt(cards[i])) {
if (isStraight!==false && (lastCard===1) && (cards[i]===10)) {
isStraight = true;
} else {
isStraight = false;
}
}
lastCard = parseInt(cards[i]);
}
var isPair = false;
var isTwoPair = false;
var isQualifiedPair = false;
var isThreeOfAKind = false;
var isFourOfAKind = false;
for (var i in seen) {
if (seen.hasOwnProperty(i)) {
if (seen[i] > 1) {
switch (seen[i]) {
case 2:
if ((i > 10) || (i == 1)) {
isQualifiedPair = true;
}
if (isPair===true) isTwoPair = true;
isPair = true;
break;
case 3:
isThreeOfAKind = true;
break;
case 4:
isFourOfAKind = true;
break;
}
}
}
}
if (isStraight && isFlush && (cards[0] === 10)) return "RoyalFlush";
if (isStraight && isFlush) return "StraightFlush";
if (isFourOfAKind) return "FourOfAKind";
if (isThreeOfAKind && isPair) return "FullHouse";
if (isFlush) return "Flush";
if (isStraight) return "Straight";
if (isThreeOfAKind) return "ThreeOfAKind";
if (isTwoPair) return "TwoPair";
if (isQualifiedPair) return "OnePair";
return false;
},
shuffle: function(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
},
genPaytable: function(counts) {
firebase.database().ref("payouts/"+cdr.game.type).once("value", function(snap) {
var pt = snap.val();
var hands = Object.keys(pt.hands);
var newpaytable = {};
var sortable = [];
for (var i=0; i<hands.length; i++) {
var name = hands[i];
var displayName = name.replace(/([a-z0-9])([A-Z0-9])/g, "$1 $2").replace(/([A-Z0-9])([A-Z0-9])/g, "$1 $2");
sortable.push([name, pt.hands[name]]);
var pay = [];
for (var j=1; j<6; j++) {
pay.push(parseInt(pt.hands[name]) * j);
}
newpaytable[name] = { "hand": displayName, win: pay };
}
cdr.paytable = newpaytable;
sortable.sort(function(a, b) {
return b[1] - a[1];
});
cdr.paytable[sortable[0][0]].win[4] = parseInt(pt.jackpot);
console.dir(newpaytable);
console.log("New pay table: " + JSON.stringify(newpaytable));
var payleft = $('#payleft');
var payright = $('#payright');
payleft.innerHTML = "";
payright.innerHTML = "";
var keys = Object.keys(cdr.paytable);
var half = Math.floor(keys.length / 2);
var entry, mypt, win, cnt;
for (var i=0; i < half; i++) {
mypt = cdr.paytable[sortable[i][0]];
win = mypt.win[cdr.game.bet - 1] || 0;
cnt = (counts && counts[sortable[i][0]]!=undefined) ? " X " + counts[sortable[i][0]] : "";
if (counts && cnt==="") win = 0;
entry = el('div', 'payline'+i, 'payline', mypt.hand + " <div class='pay'>" + win + cnt + "</"+"div>");
payleft.appendChild(entry);
}
for (var i=half; i < sortable.length; i++) {
mypt = cdr.paytable[sortable[i][0]];
win = mypt.win[cdr.game.bet - 1] || 0;
cnt = (counts && counts[sortable[i][0]]!=undefined) ? " X " + counts[sortable[i][0]] : "";
if (counts && cnt==="") win = 0;
entry = el('div', 'payline'+i, 'payline', mypt.hand + " <div class='pay'>"+win + cnt+"<"+"/div>");
payright.appendChild(entry);
}
});
},
newDeck: function() {
cdr.deck = [];
var suits = ['S', 'C', 'D', 'H'];
for (var s=0; s<4; s++) {
for (var i=1; i<14; i++) {
cdr.deck.push(i + suits[s]);
}
}
var scnt = Math.floor(Math.random() * 10) + 4;
for (var i=0; i<scnt; i++) {
cdr.deck = cdr.shuffle(cdr.deck);
}
return cdr.deck;
},
login: function(who) {
var provider;
provider = new firebase.auth.<API key>();
db = firebase.database();
firebase.auth().signInWithPopup(provider).then(function(result) {
var token = result.credential.accessToken;
var user = result.user;
console.dir(user);
writeUserData(user.uid, user.displayName, user.email, user.photoURL);
db.ref("bank/" + firebase.auth().currentUser.uid).on("value", function(snapshot) {
var bank = snapshot.val();
$$("credit").innerHTML = bank.balance;
});
}).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
var email = error.email;
var credential = error.credential;
});
},
writeUserData: function(userId, name, email, imageUrl) {
firebase.database().ref('users/' + userId).set({
name: name,
email: email,
profile_picture : imageUrl
});
setCookie("uid", userId);
},
makeHands: function() {
var hands = $$("hands");
hands.innerHTML = "";
for (var i=1; i<cdr.game.hands; i++) {
hands.appendChild(cdr.makeHand(i));
}
},
makeHand: function(id) {
var suits = ['S', 'C', 'D', 'H'];
var hand = el('div', 'hand'+id, 'hand');
var nums = 1, snum = 0;
for (var i=0; i<5; i++) {
var cnum = i + 1;
var suit = suits[3];
var card = el('div', '', 'card card' + cnum + suit, '<figure class="pic"> </figure>');
var cardback = el('div', '', 'cardback', '<figure class="pic"> </figure>');
var cardwrap = el('div', 'hand'+id+'card'+i, 'cardwrap flipped');
cardwrap.appendChild(card);
cardwrap.appendChild(cardback);
hand.appendChild(cardwrap);
nums++;
if (nums > 13) {
nums = 1;
snum++;
if (snum > 3) {
snum = 0;
}
}
}
hand.appendChild(el('div', 'hand'+id+'result', 'handresult'));
return hand;
}
};
cdr.init();
})();
function el(tag, id, classname, content) {
var el = document.createElement(tag);
if (id) el.id = id;
if (classname) el.className = classname;
if (content) el.innerHTML = content;
return el;
}
function $(str) { return document.querySelector(str); }
function $$(str) { return document.getElementById(str); }
function $$$(str) { return document.querySelectorAll(str); }
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
console.dir(user);
// User is signed in.
var displayName = user.displayName;
var email = user.email;
var emailVerified = user.emailVerified;
var photoURL = user.photoURL;
var isAnonymous = user.isAnonymous;
var uid = user.uid;
var providerData = user.providerData;
$$("loginButton").innerHTML = "LOGOUT";
cdr.game.uid = user.uid;
cdr.updateCredits();
} else {
// User is signed out.
$$("loginButton").innerHTML = "LOGIN";
}
});
</script>
</body>
</html>
|
import styled from "./Theme";
export const Content = styled.div`
margin: 2rem 0;
padding: 5px;
`;
|
<?php
namespace Chamilo\Core\Repository\Selector;
/**
* A category of options in a <API key>
*
* @author Hans De Bisschop <hans.de.bisschop@ehb.be>
*/
class <API key>
{
/**
*
* @var string
*/
private $type;
/**
*
* @var string
*/
private $name;
/**
*
* @var \core\repository\<API key>[]
*/
private $options;
/**
*
* @param string $type
* @param string $name
* @param \core\repository\<API key>[] $options
*/
public function __construct($type, $name, $options = array())
{
$this->type = $type;
$this->name = $name;
$this->options = $options;
}
/**
*
* @return string
*/
public function get_type()
{
return $this->type;
}
/**
*
* @param string $type
*/
public function set_type($type)
{
$this->type = $type;
}
/**
*
* @return string
*/
public function get_name()
{
return $this->name;
}
/**
*
* @param string $name
*/
public function set_name($name)
{
$this->name = $name;
}
/**
*
* @return \Chamilo\Core\Repository\Selector\TypeSelectorOption[]
*/
public function get_options()
{
return $this->options;
}
/**
*
* @param \core\repository\<API key>[]
*/
public function set_options($options)
{
$this->options = $options;
}
/**
*
* @param \core\repository\<API key> $option
*/
public function add_option($option)
{
$this->options[] = $option;
}
/**
* Sort the <API key> instances by name
*/
public function sort()
{
usort(
$this->options,
function ($option_a, $option_b)
{
return strcmp($option_a->get_name(), $option_b->get_name());
});
}
/**
*
* @return int
*/
public function count()
{
return count($this->get_options());
}
/**
*
* @return int[]
*/
public function <API key>()
{
$types = array();
foreach ($this->get_options() as $option)
{
if (! in_array($option-><API key>(), $types))
{
$types[] = $option-><API key>();
}
}
return $types;
}
}
|
# coding: utf-8
# 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
# Contributors: Benjamin BERNARD <benjamin.bernard@openpathview.fr>
# Email: team@openpathview.fr
# Description: Camera Set Partition, represent a partition of ImagesSets.
from typing import NamedTuple, List
from opv_import.model import ImageSet
CameraSetPartition = NamedTuple(
'CameraSetPartition',
[
('ref_set', ImageSet),
('images_sets', List[ImageSet]),
('start_indexes', List[int]),
('<API key>', List[int]),
('break_reason', str),
('<API key>', int),
('<API key>', int),
('<API key>', int)
]
)
|
<?php
class search
{
var $_searchtype;
var $_searchsql = '';
var $_basetable;
var $_limit = '';
/**
* hash
*/
var $_cacheHash = '';
var $_resultNum;
var $_mult = '';
var $_pattern = array('%','_','*');
var $_replace = array('\%','\_','%');
var $DB = null;
var $db_prefix = '';
var $_ifcache;
var $_cacheTime = 600;
function search($type, $cache = false)
{
$this->__construct($type, $cache);
}
function __construct($type, $cache = false)
{
if (in_array($type, array('article', 'comment', 'attachment', 'author')))
{
global $page, $pagesize, $DB, $db_prefix;
$this->DB = $DB;
$this->db_prefix = $db_prefix;
$this->_searchtype = $type;
$this->_ifcache = $cache ? true : false;
$this->_limit = sqlLimit($page, $pagesize);
switch ($this->_searchtype)
{
case 'article':
$this->_basetable = 't';
break;
case 'comment':
$this->_basetable = 'c';
break;
case 'attachment':
$this->_basetable = 'a';
break;
case 'author':
$this->_basetable = 'm';
break;
}
}
}
function getMult()
{
return $this->_mult;
}
function getResultNum()
{
return intval($this->_resultNum);
}
function exportResults($condition)
{
global $searchhash;
if (!is_array($condition)) return;
$cached = false;
if ($this->_ifcache && isset($searchhash) && preg_match('~^[a-z0-9]{32}$~', $searchhash))
{
$cached = $this->getCache($searchhash);
}
if (!$cached)
{
foreach ($condition as $k => $v)
{
$this->$k($v);
}
$this->_cacheHash = md5(md5($this->_searchsql).$this->_searchtype);
$this->_ifcache && $cached = $this->getCache($this->_cacheHash);
}
$this->_searchsql && $this->_searchsql = ' WHERE '.substr($this->_searchsql, 4);
return $this->{$this->_searchtype}($cached);
}
function getCache($searchhash)
{
global $timestamp;
$cacheData = $this->DB->fetch_one("SELECT num, ids, exptime FROM {$this->db_prefix}scaches WHERE hash = '$searchhash' AND exptime > '$timestamp'");
if ($cacheData && $cacheData['ids'])
{
$this->_resultNum = (int)$cacheData['num'];
$newids = '';
$ids = explode(',', $cacheData['ids']);
foreach ($ids as $v)
{
$newids .= (int)$v.',';
}
$newids && $newids = substr($newids, 0, -1);
switch ($this->_searchtype)
{
case 'article':
$this->_searchsql = " AND t.tid IN ($newids)";
break;
case 'comment':
$this->_searchsql = " AND c.rid IN ($newids)";
break;
case 'attachment':
$this->_searchsql = " AND a.aid IN ($newids)";
break;
case 'author':
$this->_searchsql = " AND m.uid IN ($newids)";
break;
}
$newids != $cacheData['ids'] && $this->DB->db_exec("UPDATE {$this->db_prefix}scaches SET ids = '".addslashes($newids)."' WHERE hash = '$searchhash' AND exptime = '".$cacheData['exptime']."'");
$this->_mult = '&searchhash='.$searchhash;
return true;
}
}
function buildCache($ids)
{
global $timestamp;
$this->DB->db_exec("DELETE FROM {$this->db_prefix}scaches WHERE exptime <= '$timestamp'");
$this->DB->db_exec("INSERT INTO {$this->db_prefix}scaches (hash,keywords,num,ids,searchip,searchtime,exptime) VALUES ('".$this->_cacheHash."','','".$this->_resultNum."','$ids','','','".($timestamp + $this->_cacheTime)."')");
$this->_mult = '&searchhash='.$this->_cacheHash;
}
function article($cached)
{
$anonymity = getSingleLang('common', 'common_anonymity');
if ($this->_ifcache && !$cached)
{
$query = $this->DB->db_query("SELECT t.tid FROM {$this->db_prefix}threads t ".$this->_searchsql);
$ids = '';
$num = 0;
while ($rs = $this->DB->fetch_all($query))
{
$ids .= (int)$rs['tid'].',';
$num++;
}
if ($ids)
{
$this->_resultNum = (int)$num;
$ids = substr($ids, 0, -1);
$this->buildCache($ids);
$this->_searchsql = " WHERE t.tid IN ($ids)";
unset($ids, $num);
}
}
if (!isset($this->_resultNum))
{
$rs = $this->DB->fetch_one("SELECT COUNT(*) num FROM {$this->db_prefix}threads t ".$this->_searchsql);
$this->_resultNum = (int)$rs['num'];
}
$query = $this->DB->db_query("SELECT t.tid, t.subject, t.author, t.postdate, t.postip FROM {$this->db_prefix}threads t ".$this->_searchsql.$this->_limit);
$article = array();
while ($rs = $this->DB->fetch_all($query))
{
$rs['postdate'] = gdate($rs['postdate'], 'Y-m-d H:i');
!$rs['author'] && $rs['author'] = $anonymity;
$article[] = $rs;
}
return $article;
}
function comment($cached)
{
$anonymity = getSingleLang('common', 'common_anonymity');
if ($this->_ifcache && !$cached)
{
$query = $this->DB->db_query("SELECT c.rid FROM {$this->db_prefix}comments c ".$this->_searchsql);
$ids = '';
$num = 0;
while ($rs = $this->DB->fetch_all($query))
{
$ids .= (int)$rs['rid'].',';
$num++;
}
if ($ids)
{
$this->_resultNum = (int)$num;
$ids = substr($ids, 0, -1);
$this->buildCache($ids);
$this->_searchsql = " WHERE c.rid IN ($ids)";
unset($ids, $num);
}
}
if (!isset($this->_resultNum))
{
$rs = $this->DB->fetch_one("SELECT COUNT(*) num FROM {$this->db_prefix}comments c ".$this->_searchsql);
$this->_resultNum = (int)$rs['num'];
}
$query = $this->DB->db_query("SELECT c.rid, c.content, c.author, c.postdate, c.postip FROM {$this->db_prefix}comments c ".$this->_searchsql.$this->_limit);
$comment = array();
while ($rs = $this->DB->fetch_all($query))
{
$rs['postdate'] = gdate($rs['postdate'], 'Y-m-d H:i');
$rs['content'] = PBSubStr($rs['content'], 50);
!$rs['author'] && $rs['author'] = $anonymity;
$comment[] = $rs;
}
return $comment;
}
// function author()
// $this->_sql = "SELECT * FROM {$this->db_prefix}threads t";
function attachment($cached)
{
$anonymity = getSingleLang('common', 'common_anonymity');
if ($this->_ifcache && !$cached)
{
$query = $this->DB->db_query("SELECT a.aid FROM {$this->db_prefix}attachments a ".$this->_searchsql);
$ids = '';
$num = 0;
while ($rs = $this->DB->fetch_all($query))
{
$ids .= (int)$rs['aid'].',';
$num++;
}
if ($ids)
{
$this->_resultNum = (int)$num;
$ids = substr($ids, 0, -1);
$this->buildCache($ids);
$this->_searchsql = " WHERE a.aid IN ($ids)";
unset($ids, $num);
}
}
if (!isset($this->_resultNum))
{
$rs = $this->DB->fetch_one("SELECT COUNT(*) num FROM {$this->db_prefix}attachments a ".$this->_searchsql);
$this->_resultNum = (int)$rs['num'];
}
$query = $this->DB->db_query("SELECT a.aid, a.tid, a.uid, a.filename, a.filesize, a.uploaddate, a.downloads FROM {$this->db_prefix}attachments a ".$this->_searchsql.$this->_limit);
$attachment = array();
while ($rs = $this->DB->fetch_all($query))
{
$rs['uploaddate'] = gdate($rs['uploaddate'], 'Y-m-d H:i');
$rs['filename'] = htmlspecialchars($rs['filename']);
$rs['filesize'] = getRealSize($rs['filesize']);
$attachment[] = $rs;
}
return $attachment;
}
function cid($cid)
{
!is_array($cid) && $cid = explode(',', $cid);
$newcid = '';
foreach ($cid as $v)
{
$v && is_numeric($v) && $newcid .= $newcid ? ',' : '' . (int)$v;
}
if ($newcid)
{
$this->_searchsql .= " AND ".$this->_basetable.".cid IN ($newcid)";
$this->_mult .= '&cid='.$newcid;
}
}
function mid($mid)
{
global $module;
!is_array($mid) && $mid = explode(',', $mid);
$newmid = '';
if (!is_object($module))
{
require_once PBDIGG_ROOT.'include/module.class.php';
$module = new module();
}
foreach ($mid as $v)
{
$v && is_numeric($v) && in_array($mid, $module->getModuleId()) && $newmid .= $newmid ? ',' : '' . (int)$v;
}
if ($newmid)
{
$this->_searchsql .= " AND ".$this->_basetable.".module IN ($newmid)";
$this->_mult .= '&mid='.$newmid;
}
}
function uid($uid)
{
!is_array($uid) && $uid = explode(',', $uid);
$newuid = '';
foreach ($uid as $v)
{
$v && is_numeric($v) && $newuid .= $newuid ? ',' : '' . (int)$v;
}
if ($newuid)
{
$this->_searchsql .= " AND ".$this->_basetable.".uid IN ($newuid)";
$this->_mult .= '&uid='.$newuid;
}
}
function authors($author)
{
$author = strip_tags(trim($author));
$_author = explode(',', $author);
$authorCondition = '';
foreach ($_author as $value)
{
if (trim($value) && (strlen($value) <= 20))
{
$authorCondition .= " OR username LIKE '".str_replace($this->_pattern, $this->_replace, preg_replace('~\*{2,}~i', '*', $value))."'";
}
}
if ($authorCondition)
{
$query = $this->DB->db_query("SELECT uid FROM {$this->db_prefix}members WHERE ".substr($authorCondition, 3));
$uids = '';
while ($rs = $this->DB->fetch_all($query))
{
$uids .= ",".(int)$rs['uid'];
}
$this->_searchsql .= $uids ? ' AND '.$this->_basetable.'.uid IN ('.substr($uids, 1).')' : ' AND 0';
$this->_mult .= '&authors='.rawurlencode($author);
}
}
function tags($tags)
{
$tags = strip_tags(trim($tags));
$_tags = explode(',', $tags);
$tagCondition = '';
foreach ($_tags as $value)
{
if (trim($value) && (strlen($value) <= 30))
{
$tagCondition .= " OR tg.tagname LIKE '".str_replace($this->_pattern, $this->_replace, preg_replace('/\*{2,}/i', '*', $value))."'";
}
}
if ($tagCondition)
{
$query = $this->DB->db_query("SELECT tc.tid FROM {$this->db_prefix}tagcache tc INNER JOIN {$this->db_prefix}tags tg USING (tagid) WHERE ".substr($tagCondition, 3));
$tids = '';
while ($rs = $this->DB->fetch_all($query))
{
$tids .= ",".(int)$rs['tid'];
}
$this->_searchsql .= $tids ? ' AND '.$this->_basetable.'.tid IN ('.substr($tids, 1).')' : ' AND 0';
$this->_mult .= '&tags='.rawurlencode($tags);
}
}
/**
* @param string $datefield
*/
function searchdate($params)
{
foreach ($params as $k => $v)
{
if (preg_replace('~[a-z]~i', '', $k)) return;
list ($more, $less) = $v;
if ($more && preg_match('~^\d{4}-\d{1,2}-\d{1,2}$~i', $more))
{
$this->_searchsql .= " AND {$this->_basetable}.$k >= ".pStrToTime($more.' 0:0:0');
$this->_mult .= '&'.$k.'more='.$more;
}
if ($less && preg_match('~^\d{4}-\d{1,2}-\d{1,2}$~i', $less))
{
$this->_searchsql .= " AND {$this->_basetable}.$k < ".pStrToTime($less.' 0:0:0');
$this->_mult .= '&'.$k.'less='.$less;
}
}
}
function searchscope($params)
{
foreach ($params as $k => $v)
{
if (preg_replace('~[a-z]~i', '', $k)) return;
list ($more, $less) = $v;
if (is_numeric($more) && $more != -1)
{
$more = (int)$more;
$this->_searchsql .= " AND {$this->_basetable}.$k >= $more";
$this->_mult .= '&'.$k.'more='.$more;
}
if (is_numeric($less) && $less != -1)
{
$less = (int)$less;
$this->_searchsql .= " AND {$this->_basetable}.$k < $less";
$this->_mult .= '&'.$k.'less='.$less;
}
}
}
function postip($ip)
{
if ($ip && preg_match('~^[0-9\*\.]+$~i', $ip))
{
$this->_searchsql .= " AND ".$this->_basetable.".postip ".((strpos($ip, '*') === FALSE) ? (" = '$ip'") : " LIKE '".str_replace('*', '%', preg_replace('~\*{2,}~i', '*', $ip))."'");
$this->_mult .= '&postip='.rawurlencode($ip);
}
}
function isimg($bool)
{
if ($bool)
{
$this->_searchsql .= ' AND '.$this->_basetable.'.isimg = 1';
$this->_mult .= '&isimg=1';
}
}
function linkhost($linkhost)
{
if ($linkhost && preg_match('~^[-_a-z0-9\.\~!\$&\'\(\)\*\+,;=:@\|/]+$~i', $linkhost))
{
$this->_searchsql .= " AND ".$this->_basetable.".linkhost ".(strpos($linkhost, '*') === FALSE ? " = '$linkhost'" : " LIKE '".str_replace('*', '%', preg_replace('~\*{2,}~i', '*', $linkhost))."'");
$this->_mult .= '&linkhost='.rawurlencode($linkhost);;
}
}
}
?>
|
using System;
namespace ForumSystem.Data.Models.BaseEntities
{
public interface IDeletableEntity
{
bool IsDeleted { get; set; }
DateTime? DeletedOn { get; set; }
}
}
|
#ifndef <API key>
#define <API key>
#include <list>
#include <map>
#include "goap/iplanner.h"
#include "goap/istate.h"
#include "goap/iscopetimer.h"
#include "goap/ifunctionstatemeter.h"
#include "goap/<API key>.h"
#include "newptr.h"
#include "log_hook.h"
#include "goaplibrary.h"
namespace goap
{
using namespace std;
/**
* Plan Formulation
*
* A character generates a plan in real-time by supplying some goal to satisfy to a system
* called a planner. The planner searches the space of actions for a sequence that will take
* the character from his starting state to his goal state. This process is referred to as
* formulatinga plan. If the planner is successful, it returns a plan for the character to follow
* to direct his behavior. The character follows this plan to completion, invalidation, or until
* another goal becomes more relevant. If another goal activates, or the plan in-progress
* becomes invalid for any reason, the character aborts the current plan and formulates a
* new one.
*/
class hanoi_tower_solver
{
IPlanner::Ptr _planner;
IState::CPtr _initialState;
IState::CPtr _goalState;
int _n = 0;
list<IPlanningAction::CPtr> _plan;
IPlanningStateMeter::CPtr _planningStateMeter;
public:
hanoi_tower_solver() {
}
hanoi_tower_solver(const hanoi_tower_solver& other) :
_planner(other._planner),
_initialState(other._initialState),
_goalState(other._goalState),
_n(other._n),
_plan(other._plan),
_planningStateMeter(other._planningStateMeter) {
}
list<IPlanningAction::CPtr> makePlan(const IState::New& initial, const IState::New& goal, int n = 3) {
tower_plan(initial, goal, n);
return makePlan();
}
private:
void tower_plan(const IState::New& initial, const IState::New& goal, int n = 3) {
_n = n;
_initialState = NewPtr<IState>()->assign(initial);
_goalState = NewPtr<IState>()->assign(goal);
_planner = planning_actions(n);
}
IPlanner::Ptr planning_actions(int n = 3) {
list<IPlanningAction::CPtr> planningActions {
Goap::newPlanningAction("Move from A to B",
[=](IState::CPtr state) -> bool { return validate(state, "A", "B", n); },
[=](IState::Ptr state) -> void { move(state, "A", "B", n); }),
Goap::newPlanningAction("Move from A to C",
[=](IState::CPtr state) -> bool { return validate(state, "A", "C", n); },
[=](IState::Ptr state) -> void { move(state, "A", "C", n); }),
Goap::newPlanningAction("Move from B to A",
[=](IState::CPtr state) -> bool { return validate(state, "B", "A", n); },
[=](IState::Ptr state) -> void { move(state, "B", "A", n); }),
Goap::newPlanningAction("Move from B to C",
[=](IState::CPtr state) -> bool { return validate(state, "B", "C", n); },
[=](IState::Ptr state) -> void { move(state, "B", "C", n); }),
Goap::newPlanningAction("Move from C to A",
[=](IState::CPtr state) -> bool { return validate(state, "C", "A", n); },
[=](IState::Ptr state) -> void { move(state, "C", "A", n); }),
Goap::newPlanningAction("Move from C to B",
[=](IState::CPtr state) -> bool { return validate(state, "C", "B", n); },
[=](IState::Ptr state) -> void { move(state, "C", "B", n); })
};
IPlanner::Ptr planner = Goap::newPlanner(IPlanner::BreadthFirst, planningActions);
return planner;
}
list<IPlanningAction::CPtr> makePlan() {
<API key>::Ptr comparer = NewPtr<<API key>>(<API key>);
if (!_planningStateMeter || *_planningStateMeter->goalState() != *_goalState) {
auto functionStateMeter = Goap::<API key>(_goalState);
functionStateMeter->monotonic(true);
functionStateMeter->fnDistance([=](IState::CPtr state, IFunctionStateMeter::CPtr stateMeter) {
float distanceToGoal = 1;
distanceToGoal = stateMeter->exactStateMeter()->distance(state); // Distance to goal
int an = state->atRef(concatStringInt("A", _n));
if (an == _n) {
// A conditional suggestion: First remove all elements from the tower 'A'
float distance = comparer->distance(state, _initialState);
//float distance2 = numericalComparer->distance(state, _restHelper) * 0.8 + 0.2;
distance = 1.0f - distance / (2 * _n + 1.0f);
if (distanceToGoal > distance)
distanceToGoal = distance;
}
return distanceToGoal;
});
functionStateMeter->fnEnough([](IState::CPtr state, IFunctionStateMeter::CPtr stateMeter) -> bool {
return stateMeter->exactStateMeter()->enough(state);
});
_planningStateMeter = functionStateMeter;
}
auto scopeTimer = Goap::newScopeTime("makePlan: ", [](const char *szMessage, double time, const char *szUnits) {
LOG(DEBUG) << szMessage << " " << " actions, " << time << " " << szUnits;
});
list<IPlanningAction::CPtr> actionsArray;
_planner->makePlanCached(_initialState, _planningStateMeter, actionsArray);
LOG(DEBUG) << "Goal length=" << _goalState->size() << " deep, " << pow(2, _goalState->size() - 1) << " optimus, " << actionsArray.size() << " actions:\n " << actionsArray;
_plan = actionsArray;
IPlanningAction::planToOstream(cerr, actionsArray, _initialState);
return actionsArray;
}
// public function run2():void
// var Plan:Vector.<IPlanningAction>;
// tower_plan( { {"A1", 1}, {"A2", 2}, {"A3", 3}, "C1":null, "C2":null, "C3":null }, { {"C1", 1}, {"C2", 2}, {"C3", 3} }, 3);
// plan = makePlan();
// tower_plan( { {"A1", 1}, {"A2", 2}, {"A3", 3}, {"A4", 4}, {"A5", 5}, {"A6", 6}, {"A7", 7}, {"A8", 8} }, { {"C1", 1}, {"C2", 2}, {"C3", 3}, {"C4", 4}, {"C5", 5}, {"C6", 6}, {"C7", 7}, {"C8", 8} }, 8);
// plan = makePlan();
// A1 1 B1 | C1 |
// A2 2 B2 | C2 |
// A3 3 B3 | C3 |
public:
void run()
{
list<IPlanningAction::CPtr> plan;
plan = makePlan( { {"A1", 1}, {"A2", 2}, {"A3", 3} }, { {"C1", 1}, {"C2", 2}, {"C3", 3} }, 3);
plan = makePlan( { {"A1", 1}, {"A2", 2}, {"A3", 3}, {"A4", 4} }, { {"C1", 1}, {"C2", 2}, {"C3", 3}, {"C4", 4} }, 4);
plan = makePlan( { {"A1", 1}, {"A2", 2}, {"A3", 3}, {"A4", 4}, {"A5", 5} }, { {"C1", 1}, {"C2", 2}, {"C3", 3}, {"C4", 4}, {"C5", 5} }, 5);
plan = makePlan( { {"A1", 1}, {"A2", 2}, {"A3", 3}, {"A4", 4}, {"A5", 5}, {"A6", 6} }, { {"C1", 1}, {"C2", 2}, {"C3", 3}, {"C4", 4}, {"C5", 5}, {"C6", 6} }, 6);
plan = makePlan( { {"A1", 1}, {"A2", 2}, {"A3", 3}, {"A4", 4}, {"A5", 5}, {"A6", 6}, {"A7", 7} }, { {"C1", 1}, {"C2", 2}, {"C3", 3}, {"C4", 4}, {"C5", 5}, {"C6", 6}, {"C7", 7} }, 7);
plan = makePlan( { {"A1", 1}, {"A2", 2}, {"A3", 3}, {"A4", 4}, {"A5", 5}, {"A6", 6}, {"A7", 7}, {"A8", 8} }, { {"C1", 1}, {"C2", 2}, {"C3", 3}, {"C4", 4}, {"C5", 5}, {"C6", 6}, {"C7", 7}, {"C8", 8} }, 8);
plan = makePlan( { {"A3", 1}, {"A4", 2}, {"A5", 3}, {"A6", 4}, {"A7", 5}, {"B6", 6}, {"B7", 7} }, { {"C1", 1}, {"C2", 2}, {"C3", 3}, {"C4", 4}, {"C5", 5}, {"C6", 6}, {"C7", 7} }, 7);
}
list<IPlanningAction::CPtr> plan() const {
return _plan;
}
IState::CPtr initialState() const {
return _initialState;
}
//private var _stringBuffer:StringBuffer = new StringBuffer;
/**
* Test if an action is posible given a state
* Validates that the state can change in the way it is specified in the 'from' 'to' strnigs.
* @param n The max tower height.
*/
static bool validate(IState::CPtr state, const string &from, const string &to, int n = 3)
{
int i = 0;
IStateValue::CPtr val;
int onFromTop = 0;
for (i = 1; i <= n; ++i) {
val = state->at(concatStringInt(from, i));
if (val && !val->empty()) {
break;
}
}
if (!val || !val->isInt())
return false;
onFromTop = static_cast<int>(*val);
int onToTop = 0;
bool trigerTo = false;
val.reset();
for (i = 1; i <= n; ++i) {
val = state->at(concatStringInt(to, i));
if (val && !val->empty())
break;
}
if (val && val->isInt()) {
trigerTo = true;
onToTop = static_cast<int>(*val);
}
return !trigerTo || onToTop > onFromTop;
}
//private static var _strCache:Object = { };
/**
* Helper function to cache strings in the form: 'String' + 'int'
* This is a way of lowering pression from the GC.
* The integger must be a low number.
*/
static const string& concatStringInt(const string &str, int n)
{
static map<int, map<string, string>> mapStr;
auto &val = mapStr[n][str];
if (val.empty()) {
val = str + to_string(n);
}
return val;
}
// The 'executor' function
static void move(IState::Ptr state, const string &from, const string &to, int n = 3)
{
int i = 0;
IStateValue::CPtr val;
const string* a = nullptr;
for (i = 1; i <= n; ++i) {
const string& astr = concatStringInt(from, i);
val = state->at(astr);
if (val && !val->empty()) {
a = &astr;
break;
}
}
if (!a) {
throw runtime_error("Can't trig from '" + from + "' to '" + to + "'");
}
const string* b = nullptr;
bool trigerTo = false;
for (i = 1; i <= n; ++i) {
val = state->at(concatStringInt(to, i));
if (val && !val->empty()) {
if (i
throw runtime_error("Can't put to '" + to + "'"); // Tower is full
} else {
b = &concatStringInt(to, i);
}
trigerTo = true;
break;
}
}
if (!trigerTo) {
b = &concatStringInt(to, n);
}
// Update the source state
state->put(*b, state->at(*a));
state->remove(*a);
}
};
}
#endif // <API key>
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\region_sica;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class <API key> extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function fnc_obtener_id($param){
$id_region_sica=0;
$obj_region_sica= region_sica::all();
foreach ($obj_region_sica as $paises){
if($paises->nombre_pais==$param){
$id_region_sica=$paises->id_region_sica;
}
}
return $id_region_sica;
}
public function index()
{
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
}
}
|
var model = function(name, config) {
"use strict";
var _model = {name: name},
_appendix = {};
// ## Data invariant and initialization
// This model describes a dynamic phenomenon in terms of changing
// quantities over time.
// This description starts at `T_START` milliseconds
// (ms), defaulting to 0 ms and ends at `T_END` ms. If no end is specified
// it is assumed that the phenomenon does not end or is still ongoing in
// the real world (RW). The phenomenon's change is tracked by "measuring"
// the changing quantities at consecutive moments in time. These moments
// are `T_STEP` apart, defaulting to 1 ms, and are tracked by order
// number.
var T_START = config.time.start || 0,
T_END = config.time.end || Infinity,
T_STEP = config.time.step || 1;
function set_end(seconds) {
T_END = seconds*1000;
}
_model.set_end = set_end;
// To translate from a moment's order number to its corresponding time in
// ms and vice versa, two helper functions are defined, `time_to_moment`
// and `moment_to_time`, as well as a shorthand name for these two helper
// functions, respectively, `t2m` and `m2t`.
_model.time_to_moment = function(time) {
return Math.floor(time / T_STEP);
};
var t2m = _model.time_to_moment;
_model.moment_to_time = function(moment) {
return moment * T_STEP;
};
var m2t = _model.moment_to_time;
// When I use "measured" I mean to denote that the values of the
// quantities describing the phenomenon have been captured, computed,
// downloaded, measured, or otherwise obtained. This `model` function is
// intended to be applicable for describing purely theoretical models of a
// phenomenon as well as real-time measurements of a phenomenon.
// "Measuring" a moment is left to the `measure_moment` function. Each
// model has to (re)implement this function to specify the relationship
// between the phenomenon's quantities of interest at each moment during
// the phenomenon.
_model.measure_moment = function(moment) {
// to be implemented in an object implementing model
};
// The model has the following data invariant:
// stating that the phenomenon has been described quantitatively for all
// moments. These "measurements" are stored in a list of `moments` and can
// be accessed through a moment's order number.
var moments = [];
_model.get_moment = function(moment) {
return moments[moment];
};
_model.number_of_moments = function() {
return moments.length;
};
// A moment can only be inspected if it already has been "measured".
// Following the data invariant, a moment has been measured when its order
// number is smaller or equal to the number of measured moments.
_model.moment_measured = function(moment) {
return (moment <= (moments.length - 1));
};
// Furthermore, the current moment of interest, or `now`, points to an
// already "measured" moment during the phenomenon's duration. Hence, the
// data invariant is extended as follows:
var now;
// To ensure this data invariant, `now` is set to a moment before the
// phenomenon started.
now = t2m(T_START) - 1;
// ## Inspecting and running a model
// Inspection through registerd views
var views = [];
var update_views = function() {
var update_view = function(view) {
view.update(_model.name);
};
views.forEach(update_view);
};
_model.update_views = update_views;
var update_all_views = function() {
var update_view = function(view) {
if (view.update_all) {
view.update_all();
} else {
view.update(_model.name);
}
};
views.forEach(update_view);
};
_model.update_all_views = update_all_views;
_model.register = function(view) {
var view_found = views.indexOf(view);
if (view_found === -1) {
views.push(view);
views.forEach(function(v) { if(v.update_all) v.update_all();});
}
};
_model.get_views_of_type = function(view_type) {
return views.filter(function(v) {
return v.type === view_type;
});
};
_model.unregister = function(view) {
if (arguments.length === 0) {
var unregister = function(view) {
view.unregister(_model.name);
};
views.forEach(unregister);
} else {
var view_found = views.indexOf(view);
if (view_found !== -1) {
views.slice(view_found, 1);
}
}
};
// As a model can be inspected repeatedly, as is one
// of the reasons to model a phenomenon using a computer, we introduce a
// `reset` function to resets `now` to a moment before the phenomenon
// started.
_model.reset = function() {
now = t2m(T_START) - 1;
_model.step();
update_views();
};
// Once a model has been started, the current moment will be measured as
// well as all moments before since the start. These moments can be
// inspected.
_model.has_started = function() {
return now >= 0;
};
// The `step` function will advance `now` to the next moment if the end of
// the phenomenon has not been reached yet. If that moment has not been
// "measured" earlier, "measure" it now.
_model.step = function(do_not_update_views) {
if (m2t(now) + T_STEP <= T_END) {
now++;
if (!_model.moment_measured(now)) {
var moment = _model.measure_moment(now);
moment._time_ = m2t(now);
moments.push(moment);
}
}
if (!do_not_update_views) {
update_views();
}
return now;
};
// If the phenomenon is a finite process or the "measuring" process cannot
// go further `T_END` will have a value that is not `Infinity`.
_model.can_finish = function() {
return Math.abs(T_END) !== Infinity;
};
// To inspect the whole phenomenon at once or inspect the last moment,
// `finish`ing the model will ensure that all moments during the
// phenomenon have been "measured".
_model.finish = function() {
var DO_NOT_UPDATE_VIEWS = true;
if (_model.can_finish()) {
while ((moments.length - 1) < t2m(T_END)) {
_model.step(DO_NOT_UPDATE_VIEWS);
}
}
now = moments.length - 1;
_model.update_views();
return now;
};
// We call the model finished if the current moment, or `now`, is the
// phenomenon's last moment.
_model.is_finished = function() {
return _model.can_finish() && m2t(now) >= T_END;
};
function reset_model() {
moments = [];
_model.action("reset").callback(_model)();
// _model.reset();
}
_model.reset_model = reset_model;
/**
* ## Actions on the model
*
*/
_model.actions = {};
_model.add_action = function( action ) {
_model.actions[action.name] = action;
_model.actions[action.name].install = function() {
return action.callback(_model);
};
};
if (config.actions) {
var add_action = function(action_name) {
_model.add_action(config.actions[action_name]);
};
Object.keys(config.actions).forEach(add_action);
}
_model.action = function( action_name ) {
if (_model.actions[action_name]) {
return _model.actions[action_name];
}
};
_model.remove_action = function( action ) {
if (_model.actions[action.name]) {
delete _model.actions[action.name];
}
};
_model.disable_action = function( action_name ) {
if (_model.actions[action_name]) {
_model.actions[action_name].enabled = false;
}
};
_model.enable_action = function( action_name ) {
if (_model.actions[action_name]) {
_model.actions[action_name].enabled = true;
}
};
_model.toggle_action = function( action_name ) {
if (_model.actions[action_name]) {
_model.actions[action_name].enabled =
!_model.action[action_name].enabled;
}
};
// ## Coordinating quantities
// All quantities that describe the phenomenon being modeled change in
// coordination with time's change. Add the model's time as a quantity to
// the list with quantities. To allow people to model time as part of
// their model, for example to describe the phenomenon accelerated, the
// internal time is added as quantity `_time_` and, as a result, "_time_"
// is not allowed as a quantity name.
_model.quantities = config.quantities || {};
_model.quantities._time_ = {
hidden: true,
minimum: T_START,
maximum: T_END,
value: m2t(now),
stepsize: T_STEP,
unit: "ms",
label: "internal time",
monotone: true
};
_model.get_minimum = function(quantity) {
if (arguments.length===0) {
// called without any arguments: return all minima
var minima = {},
add_minimum = function(quantity) {
minima[quantity] = parseFloat(_model.quantities[quantity].minimum);
};
Object.keys(_model.quantities).forEach(add_minimum);
return minima;
} else {
// return quantity's minimum
return parseFloat(_model.quantities[quantity].minimum);
}
};
_model.get_maximum = function(quantity) {
if (arguments.length===0) {
// called without any arguments: return all minima
var maxima = {},
add_maximum = function(quantity) {
maxima[quantity] = parseFloat(_model.quantities[quantity].maximum);
};
Object.keys(_model.quantities).forEach(add_maximum);
return maxima;
} else {
// return quantity's minimum
return parseFloat(_model.quantities[quantity].maximum);
}
};
_model.find_moment = function(quantity, value, EPSILON) {
if (moments.length === 0) {
// no moment are measured yet, so there is nothing to be found
return -1;
} else {
var val = _appendix.quantity_value(quantity);
// pre: quantity is monotone
// determine if it is increasing or decreasing
// determine type of monotone
// As the first moment has been measured and we do know the
// minimum of this quantity, type of monotone follows.
var start = val(0),
INCREASING = (start !== _model.get_maximum(quantity));
// Use a stupid linear search to find the moment that approaches the
// value best
var m = 0,
n = moments.length - 1,
lowerbound,
upperbound;
if (INCREASING) {
lowerbound = function(moment) {
return val(moment) < value;
};
upperbound = function(moment) {
return val(moment) > value;
};
} else {
lowerbound = function(moment) {
return val(moment) > value;
};
upperbound = function(moment) {
return val(moment) < value;
};
}
// Increasing "function", meaning
// Therefore,
// `find_moment` finds those moments m and n and returns the
// one closest to value or, when even close, the last moment
// decreasing is reverse.
while (lowerbound(m)) {
m++;
if (m>n) {
return -1;
}
}
return m;
/*
while (upperbound(n)) {
n--;
if (n<m) {
return -1;
}
}
//n++;
return (Math.abs(val(n)-value) < Math.abs(val(m)-value))?n:m;
*/
}
};
_model.get = function(quantity) {
if (now < 0) {
return undefined;
} else {
return moments[now][quantity];
}
};
_model.set = function(quantity, value) {
var q = _model.quantities[quantity];
if (value < parseFloat(q.minimum)) {
value = parseFloat(q.minimum);
} else if (value > parseFloat(q.maximum)) {
value = parseFloat(q.maximum);
}
// has value already been "measured"?
// As some quantities can have the same value more often, there are
// potentially many moments that fit the bill. There can be an unknown
// amount of moments that aren't measured as well.
// However, some quantities will be strictly increasing or decreasing
// and no value will appear twice. For example, the internal time will
// only increase. Those quantities with property `monotone`
// `true`, only one value will be searched for
var approx = _appendix.approximates(),
moment = -1;
if (q.monotone) {
moment = _model.find_moment(quantity, value);
if (moment === -1) {
// not yet "measured"
var DO_NOT_UPDATE_VIEWS = true;
_model.step(DO_NOT_UPDATE_VIEWS);
// THIS DOES WORK ONLY FOR INCREASING QUANTITIES. CHANGE THIS
// ALTER WITH FIND FUNCTION !!!!
while((moments[now][quantity] < value) && !_model.is_finished()) {
_model.step(DO_NOT_UPDATE_VIEWS);
}
} else {
now = moment;
}
update_views();
return moments[now];
}
};
_model.data = function() {
return moments.slice(0, now + 1);
};
_model.current_moment = function(moment_only) {
if (moment_only) {
return now;
} else {
return moments[now];
}
};
_model.graphs_shown = {
tailpoints: false,
line: false,
arrows: false
};
_model.show_graph = function(kind) {
var graphs = _model.get_views_of_type("graph");
function show_this_graph(g) {
switch(kind) {
case "line":
g.show_line(_model.name);
break;
case "tailpoints":
g.show_tailpoints(_model.name);
break;
case "arrows":
g.show_arrows(_model.name);
break;
}
}
graphs.forEach(show_this_graph);
_model.graphs_shown[kind] = true;
};
_model.hide_graph = function(kind) {
var graphs = _model.get_views_of_type("graph");
function hide_this_graph(g) {
switch(kind) {
case "line":
g.hide_line(_model.name);
break;
case "tailpoints":
g.hide_tailpoints(_model.name);
break;
case "arrows":
g.hide_arrows(_model.name);
break;
}
}
graphs.forEach(hide_this_graph);
_model.graphs_shown[kind] = false;
};
_model.graph_is_shown = function(kind) {
return _model.graphs_shown[kind];
};
// ## _appendix H: helper functions
_appendix.approximates = function(epsilon) {
var EPSILON = epsilon || 0.001,
fn = function(a, b) {
return Math.abs(a - b) <= EPSILON;
};
fn.EPSILON = EPSILON;
return fn;
};
_appendix.quantity_value = function(quantity) {
return function(moment) {
return moments[moment][quantity];
};
};
var step = (config.step_size || T_STEP)*5 ;
function step_size(size) {
if (arguments.length === 1) {
step = size;
}
return step;
}
_model.step_size = step_size;
function random_color() {
var hexes = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'],
colors = [],
i = 0;
while (i < 6) {
colors.push(hexes[Math.round(Math.random()*(hexes.length - 1))]);
i++;
}
return "#"+ colors.join("");
}
var color = random_color();
_model.color = function(c) {
if (arguments.length === 1) {
if (c === "random") {
color = random_color();
} else {
color = c;
}
}
return color;
};
return _model;
};
module.exports = model;
|
// C
// CenterSpace Software //
// 2098 NW Myrtlewood Way //
// Corvallis, Oregon, 97330 //
// USA //
using System;
namespace CenterSpace.Free
{
<summary>
Class MersenneTwister generates random numbers from a uniform distribution using
the Mersenne Twister algorithm.
</summary>
<remarks>Caution: MT is for MonteCarlo, and is NOT SECURE for CRYPTOGRAPHY
as it is.</remarks>
public class MersenneTwister
{
// Period parameters.
private const int N = 624;
private const int M = 397;
private const uint MATRIX_A = 0x9908b0dfU; // constant vector a
private const uint UPPER_MASK = 0x80000000U; // most significant w-r bits
private const uint LOWER_MASK = 0x7fffffffU; // least significant r bits
private const int MAX_RAND_INT = 0x7fffffff;
#endregion Constants
// mag01[x] = x * MATRIX_A for x=0,1
private uint[] mag01 = {0x0U, MATRIX_A};
// the array for the state vector
private uint[] mt = new uint[N];
// mti==N+1 means mt[N] is not initialized
private int mti = N+1;
#endregion Instance Variables
<summary>
Creates a random number generator using the time of day in milliseconds as
the seed.
</summary>
public MersenneTwister()
{
init_genrand( (uint)DateTime.Now.Millisecond );
}
<summary>
Creates a random number generator initialized with the given seed.
</summary>
<param name="seed">The seed.</param>
public MersenneTwister( int seed )
{
init_genrand( (uint)seed );
}
<summary>
Creates a random number generator initialized with the given array.
</summary>
<param name="init">The array for initializing keys.</param>
public MersenneTwister( int[] init )
{
uint[] initArray = new uint[init.Length];
for ( int i = 0; i < init.Length; ++i )
initArray[i] = (uint)init[i];
init_by_array( initArray, (uint)initArray.Length );
}
#endregion Constructors
<summary>
Gets the maximum random integer value. All random integers generated
by instances of this class are less than or equal to this value. This
value is <c>0x7fffffff</c> (<c>2,147,483,647</c>).
</summary>
public static int MaxRandomInt
{
get
{
return 0x7fffffff;
}
}
#endregion Properties
<summary>
Returns a random integer greater than or equal to zero and
less than or equal to <c>MaxRandomInt</c>.
</summary>
<returns>The next random integer.</returns>
public int Next()
{
return genrand_int31();
}
<summary>
Returns a positive random integer less than the specified maximum.
</summary>
<param name="maxValue">The maximum value. Must be greater than zero.</param>
<returns>A positive random integer less than or equal to <c>maxValue</c>.</returns>
public int Next( int maxValue )
{
return Next( 0, maxValue );
}
<summary>
Returns a random integer within the specified range.
</summary>
<param name="minValue">The lower bound.</param>
<param name="maxValue">The upper bound.</param>
<returns>A random integer greater than or equal to <c>minValue</c>, and less than
or equal to <c>maxValue</c>.</returns>
public int Next( int minValue, int maxValue )
{
if ( minValue > maxValue )
{
int tmp = maxValue;
maxValue = minValue;
minValue = tmp;
}
return (int)( Math.Floor((maxValue-minValue+1)*genrand_real1() + minValue) );
}
<summary>
Returns a random number between 0.0 and 1.0.
</summary>
<returns>A single-precision floating point number greater than or equal to 0.0,
and less than 1.0.</returns>
public float NextFloat()
{
return (float) genrand_real2();
}
<summary>
Returns a random number greater than or equal to zero, and either strictly
less than one, or less than or equal to one, depending on the value of the
given boolean parameter.
</summary>
<param name="includeOne">
If <c>true</c>, the random number returned will be
less than or equal to one; otherwise, the random number returned will
be strictly less than one.
</param>
<returns>
If <c>includeOne</c> is <c>true</c>, this method returns a
single-precision random number greater than or equal to zero, and less
than or equal to one. If <c>includeOne</c> is <c>false</c>, this method
returns a single-precision random number greater than or equal to zero and
strictly less than one.
</returns>
public float NextFloat( bool includeOne )
{
if ( includeOne )
{
return (float) genrand_real1();
}
return (float) genrand_real2();
}
<summary>
Returns a random number greater than 0.0 and less than 1.0.
</summary>
<returns>A random number greater than 0.0 and less than 1.0.</returns>
public float NextFloatPositive()
{
return (float) genrand_real3();
}
<summary>
Returns a random number between 0.0 and 1.0.
</summary>
<returns>A double-precision floating point number greater than or equal to 0.0,
and less than 1.0.</returns>
public double NextDouble()
{
return genrand_real2();
}
<summary>
Returns a random number greater than or equal to zero, and either strictly
less than one, or less than or equal to one, depending on the value of the
given boolean parameter.
</summary>
<param name="includeOne">
If <c>true</c>, the random number returned will be
less than or equal to one; otherwise, the random number returned will
be strictly less than one.
</param>
<returns>
If <c>includeOne</c> is <c>true</c>, this method returns a
single-precision random number greater than or equal to zero, and less
than or equal to one. If <c>includeOne</c> is <c>false</c>, this method
returns a single-precision random number greater than or equal to zero and
strictly less than one.
</returns>
public double NextDouble( bool includeOne )
{
if ( includeOne )
{
return genrand_real1();
}
return genrand_real2();
}
<summary>
Returns a random number greater than 0.0 and less than 1.0.
</summary>
<returns>A random number greater than 0.0 and less than 1.0.</returns>
public double NextDoublePositive()
{
return genrand_real3();
}
<summary>
Generates a random number on <c>[0,1)</c> with 53-bit resolution.
</summary>
<returns>A random number on <c>[0,1)</c> with 53-bit resolution</returns>
public double Next53BitRes()
{
return genrand_res53();
}
<summary>
Reinitializes the random number generator using the time of day in
milliseconds as the seed.
</summary>
public void Initialize()
{
init_genrand( (uint)DateTime.Now.Millisecond );
}
<summary>
Reinitializes the random number generator with the given seed.
</summary>
<param name="seed">The seed.</param>
public void Initialize( int seed )
{
init_genrand( (uint)seed );
}
<summary>
Reinitializes the random number generator with the given array.
</summary>
<param name="init">The array for initializing keys.</param>
public void Initialize( int[] init )
{
uint[] initArray = new uint[init.Length];
for ( int i = 0; i < init.Length; ++i )
initArray[i] = (uint)init[i];
init_by_array( initArray, (uint)initArray.Length );
}
// initializes mt[N] with a seed
private void init_genrand( uint s)
{
mt[0]= s & 0xffffffffU;
for (mti=1; mti<N; mti++)
{
mt[mti] =
(uint)(1812433253U * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti);
// See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier.
// In the previous versions, MSBs of the seed affect
// only MSBs of the array mt[].
mt[mti] &= 0xffffffffU;
// for >32 bit machines
}
}
// initialize by an array with array-length
// init_key is the array for initializing keys
// key_length is its length
private void init_by_array(uint[] init_key, uint key_length)
{
int i, j, k;
init_genrand(19650218U);
i=1; j=0;
k = (int)(N>key_length ? N : key_length);
for (; k>0; k
{
mt[i] = (uint)((uint)(mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525U)) + init_key[j] + j); /* non linear */
mt[i] &= 0xffffffffU; // for WORDSIZE > 32 machines
i++; j++;
if (i>=N) { mt[0] = mt[N-1]; i=1; }
if (j>=key_length) j=0;
}
for (k=N-1; k>0; k
{
mt[i] = (uint)((uint)(mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941U))- i); /* non linear */
mt[i] &= 0xffffffffU; // for WORDSIZE > 32 machines
i++;
if (i>=N) { mt[0] = mt[N-1]; i=1; }
}
mt[0] = 0x80000000U; // MSB is 1; assuring non-zero initial array
}
// generates a random number on [0,0xffffffff]-interval
uint genrand_int32()
{
uint y;
if (mti >= N)
{ /* generate N words at one time */
int kk;
if (mti == N+1) /* if init_genrand() has not been called, */
init_genrand(5489U); /* a default initial seed is used */
for (kk=0;kk<N-M;kk++)
{
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1U];
}
for (;kk<N-1;kk++)
{
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1U];
}
y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1U];
mti = 0;
}
y = mt[mti++];
// Tempering
y ^= (y >> 11);
y ^= (y << 7) & 0x9d2c5680U;
y ^= (y << 15) & 0xefc60000U;
y ^= (y >> 18);
return y;
}
// generates a random number on [0,0x7fffffff]-interval
private int genrand_int31()
{
return (int)(genrand_int32()>>1);
}
// generates a random number on [0,1]-real-interval
double genrand_real1()
{
return genrand_int32()*(1.0/4294967295.0);
// divided by 2^32-1
}
// generates a random number on [0,1)-real-interval
double genrand_real2()
{
return genrand_int32()*(1.0/4294967296.0);
// divided by 2^32
}
// generates a random number on (0,1)-real-interval
double genrand_real3()
{
return (((double)genrand_int32()) + 0.5)*(1.0/4294967296.0);
// divided by 2^32
}
// generates a random number on [0,1) with 53-bit resolution
double genrand_res53()
{
uint a=genrand_int32()>>5, b=genrand_int32()>>6;
return(a*67108864.0+b)*(1.0/9007199254740992.0);
}
// These real versions are due to Isaku Wada, 2002/01/09 added
#endregion Methods ported from C
#endregion Member Functions
}
}
|
package main
import (
"net/http"
"os"
"path"
"strings"
"github.com/zenazn/goji/web"
)
func fileServeHandler(c web.C, w http.ResponseWriter, r *http.Request) {
fileName := c.URLParams["name"]
filePath := path.Join(Config.filesDir, fileName)
if !<API key>(fileName) {
notFoundHandler(c, w, r)
return
}
if !Config.allowHotlink {
referer := r.Header.Get("Referer")
if referer != "" && !strings.HasPrefix(referer, Config.siteURL) {
w.WriteHeader(403)
return
}
}
w.Header().Set("<API key>", Config.<API key>)
http.ServeFile(w, r, filePath)
}
func staticHandler(c web.C, w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
if path[len(path)-1:] == "/" {
notFoundHandler(c, w, r)
return
} else {
if path == "/favicon.ico" {
path = "/static/images/favicon.gif"
}
filePath := strings.TrimPrefix(path, "/static/")
file, err := staticBox.Open(filePath)
if err != nil {
notFoundHandler(c, w, r)
return
}
w.Header().Set("Etag", timeStartedStr)
w.Header().Set("Cache-Control", "max-age=86400")
http.ServeContent(w, r, filePath, timeStarted, file)
return
}
}
func <API key>(filename string) bool {
filePath := path.Join(Config.filesDir, filename)
_, err := os.Stat(filePath)
if err != nil {
return false
}
if isFileExpired(filename) {
os.Remove(path.Join(Config.filesDir, filename))
os.Remove(path.Join(Config.metaDir, filename))
return false
}
return true
}
|
// This file is part of Return To The Roots.
// Return To The Roots is free software: you can redistribute it and/or modify
// (at your option) any later version.
// Return To The Roots is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#include "rttrDefines.h" // IWYU pragma: keep
#include "LanGameInfo.h"
#include "s25util/Serializer.h"
bool LanGameInfo::Serialize(Serializer& serializer)
{
if(name.size() > 64)
name.resize(64);
if(map.size() > 64)
map.resize(64);
if(version.size() > 16)
version.resize(16);
serializer.PushString(name);
serializer.PushBool(hasPwd);
serializer.PushString(map);
serializer.PushUnsignedChar(curNumPlayers);
serializer.PushUnsignedChar(maxNumPlayers);
serializer.PushUnsignedShort(port);
serializer.PushBool(isIPv6);
serializer.PushString(version);
serializer.PushString(revision);
return true;
}
bool LanGameInfo::Deserialize(Serializer& serializer)
{
name = serializer.PopString();
hasPwd = serializer.PopBool();
map = serializer.PopString();
curNumPlayers = serializer.PopUnsignedChar();
maxNumPlayers = serializer.PopUnsignedChar();
port = serializer.PopUnsignedShort();
isIPv6 = serializer.PopBool();
version = serializer.PopString();
revision = serializer.PopString();
return true;
}
|
<?php
/*
<API key>.php
Una publicacion en miniatura
*/
?>
<div class="<API key>">
<h2><?php print $producto->getDescripcion(); ?></h2>
<p>
<?php
$img = $producto->getImagenes();
for ($index = 0; $index < 3; $index++) {
if (!empty($img[$index]['imagen'])) {
break;
}
}
print getImagen($img[$index]['imagen'], 'img_preview img_preview_left');
print extractoTexto($producto->getResumen());
?>
</p>
</div>
|
require 'package'
class Aspell_fr < Package
description 'French Aspell Dictionary'
homepage 'https://ftpmirror.gnu.org/aspell/dict/0index.html'
version '0.50-3'
source_url 'https://ftpmirror.gnu.org/aspell/dict/fr/aspell-fr-0.50-3.tar.bz2'
source_sha256 '<SHA256-like>'
binary_url ({
aarch64: 'https://dl.bintray.com/chromebrew/chromebrew/aspell_fr-0.<API key>.tar.xz',
armv7l: 'https://dl.bintray.com/chromebrew/chromebrew/aspell_fr-0.<API key>.tar.xz',
i686: 'https://dl.bintray.com/chromebrew/chromebrew/aspell_fr-0.50-3-chromeos-i686.tar.xz',
x86_64: 'https://dl.bintray.com/chromebrew/chromebrew/aspell_fr-0.<API key>.tar.xz',
})
binary_sha256 ({
aarch64: '<SHA256-like>',
armv7l: '<SHA256-like>',
i686: '<SHA256-like>',
x86_64: '<SHA256-like>',
})
depends_on 'aspell'
def self.build
system './configure'
system 'make'
end
def self.install
system "make", "DESTDIR=#{CREW_DEST_DIR}", "install"
end
end
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
add word counts to Cornetto lexical units database file
The word count file should have three columns, delimited by white space,
containing (1) the count, (2) the lemma, (3) the main POS tag.
The tagset is assumed to be the Spoken Dutch Corpus tagset,
and the character encoding must be ISO-8859-1.
The counts appear as the value of the feature "count" on <form> elements.
The updated lexical units xml database is written to standard output.
Since we have only the lemma and the POS, and no word sense, the frequency
information is added to each matching lexical unit regardless of its sense
(i.e. the value of the "c_seq_nr" attribute).
"""
# TODO:
# - deal with multiword counts
__author__ = 'Erwin Marsi <e.marsi@gmail.com>'
__version__ = '0.6'
from sys import stderr, stdout
from xml.etree.cElementTree import iterparse, SubElement, tostring, ElementTree
from cornetto.argparse import ArgumentParser, <API key>
def read_counts(file):
if not hasattr(file, "read"):
file = open(file)
counts = {}
totals = dict(noun=0, verb=0, adj=0, other=0)
for l in file:
try:
count, form, tag = l.strip().split()
except ValueError:
stderr.write("Warning; ill-formed line: %s\n" % repr(l))
continue
# translate CGN tagset to word category
if tag in ("N", "VNW", "TW", "SPEC"):
cat = "noun"
elif tag in ("WW"):
cat = "verb"
elif tag in ("ADJ", "BW"):
cat = "adj"
else:
# LET LID TSW VG VZ
cat = "other"
# Cornetto word forms are stored in unicode
form = form.decode("iso-8859-1")
count = int(count)
if form not in counts:
counts[form] = dict(noun=0, verb=0, adj=0, other=0)
counts[form][cat] += count
totals[cat] += count
return counts, totals
def add_count_attrib(counts, totals, cdb_lu_file):
parser = iterparse(cdb_lu_file)
for event, elem in parser:
if elem.tag == "form":
# following the ElementTree conventions,
# word form will be ascii or unicode
form = elem.get("form-spelling")
# lower case because Cornette is not consistent
cat = elem.get("form-cat").lower()
# fix category flaws in current release of Cornetto
if cat == "adjective":
cat = "adj"
elif cat == "adverb":
cat = "other"
try:
count = counts[form][cat]
except KeyError:
# form not found
count = 0
elem.set("count", str(count))
# Finally, add totals, per category and overall, to the doc root
# Note that all words _not_ in Cornetto are not included in these totals
totals["all"] = sum(totals.values())
for cat, count in totals.items():
parser.root.set("count-total-%s" % cat, str(count))
return ElementTree(parser.root)
parser = ArgumentParser(description=__doc__,
version="%(prog)s version " + __version__,
formatter_class=<API key>)
parser.add_argument("cdb_lu", type=file,
help="xml file containing the lexical units")
parser.add_argument("word_counts", type=file,
help="tabular file containing the word counts")
args = parser.parse_args()
counts, totals = read_counts(args.word_counts)
etree = add_count_attrib(counts, totals, args.cdb_lu)
etree.write(stdout, encoding="utf-8")
#def add_statistics_elem(counts, cdb_lu_file):
#"""
#adds a separate <statistics> element,
#which accomodates for other counts for other sources
#"""
#parser = iterparse(cdb_lu_file)
#for event, elem in parser:
#if elem.tag == "cdb_lu":
#try:
#count = counts[form][cat]
#except KeyError:
#count = 0
#freq_el = SubElement(elem, "statistics")
#SubElement(freq_el, "count", scr="uvt").text = str(count)
#elif elem.tag == "form":
## following the ElementTree conventions,
## word form will be ascii or unicode
#form = elem.get("form-spelling")
#cat = elem.get("form-cat")
#return ElementTree(parser.root)
|
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>png++: index_pixel.hpp Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<!-- Generated by Doxygen 1.7.4 -->
<div id="top">
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">png++ <span id="projectnumber">0.2.1</span></div>
</td>
</tr>
</tbody>
</table>
</div>
<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><a href="annotated.html"><span>Classes</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="files.html"><span>File List</span></a></li>
</ul>
</div>
<div class="header">
<div class="headertitle">
<div class="title">index_pixel.hpp</div> </div>
</div>
<div class="contents">
<a name="l00031"></a>00031 <span class="preprocessor">#ifndef <API key></span>
<a name="l00032"></a>00032 <span class="preprocessor"></span><span class="preprocessor">#define <API key></span>
<a name="l00033"></a>00033 <span class="preprocessor"></span>
<a name="l00034"></a>00034 <span class="preprocessor">#include "<a class="code" href="types_8hpp.html">types.hpp</a>"</span>
<a name="l00035"></a>00035 <span class="preprocessor">#include "<a class="code" href="packed__pixel_8hpp.html">packed_pixel.hpp</a>"</span>
<a name="l00036"></a>00036 <span class="preprocessor">#include "<a class="code" href="pixel__traits_8hpp.html">pixel_traits.hpp</a>"</span>
<a name="l00037"></a>00037
<a name="l00038"></a>00038 <span class="keyword">namespace </span>png
<a name="l00039"></a>00039 {
<a name="l00040"></a>00040
<a name="l00044"></a><a class="code" href="<API key>.html">00044</a> <span class="keyword">class </span><a class="code" href="<API key>.html" title="The 8-bit Indexed (colormap) pixel type.">index_pixel</a>
<a name="l00045"></a>00045 {
<a name="l00046"></a>00046 <span class="keyword">public</span>:
<a name="l00047"></a><a class="code" href="<API key>.html#<API key>">00047</a> <a class="code" href="<API key>.html#<API key>">index_pixel</a>(<a class="code" href="namespacepng.html#<API key>">byte</a> index = 0)
<a name="l00048"></a>00048 : m_index(index)
<a name="l00049"></a>00049 {
<a name="l00050"></a>00050 }
<a name="l00051"></a>00051
<a name="l00052"></a><a class="code" href="<API key>.html#<API key>">00052</a> <a class="code" href="<API key>.html#<API key>">operator byte</a>()<span class="keyword"> const</span>
<a name="l00053"></a>00053 <span class="keyword"> </span>{
<a name="l00054"></a>00054 <span class="keywordflow">return</span> m_index;
<a name="l00055"></a>00055 }
<a name="l00056"></a>00056
<a name="l00057"></a>00057 <span class="keyword">private</span>:
<a name="l00058"></a>00058 <a class="code" href="namespacepng.html#<API key>">byte</a> m_index;
<a name="l00059"></a>00059 };
<a name="l00060"></a>00060
<a name="l00065"></a>00065 <span class="keyword">template</span>< <span class="keywordtype">size_t</span> bits >
<a name="l00066"></a><a class="code" href="<API key>.html">00066</a> <span class="keyword">class </span><a class="code" href="<API key>.html" title="The packed indexed pixel class template. The available specializations are for 1-, 2- and 4-bit pixels.">packed_index_pixel</a>
<a name="l00067"></a>00067 : <span class="keyword">public</span> <a class="code" href="<API key>.html" title="The packed pixel class template.">packed_pixel</a>< bits >
<a name="l00068"></a>00068 {
<a name="l00069"></a>00069 <span class="keyword">public</span>:
<a name="l00070"></a><a class="code" href="<API key>.html#<API key>">00070</a> <a class="code" href="<API key>.html#<API key>">packed_index_pixel</a>(<a class="code" href="namespacepng.html#<API key>">byte</a> value = 0)
<a name="l00071"></a>00071 : <a class="code" href="<API key>.html" title="The packed pixel class template.">packed_pixel</a>< bits >(value)
<a name="l00072"></a>00072 {
<a name="l00073"></a>00073 }
<a name="l00074"></a>00074 };
<a name="l00075"></a>00075
<a name="l00079"></a><a class="code" href="namespacepng.html#<API key>">00079</a> <span class="keyword">typedef</span> <a class="code" href="<API key>.html" title="The packed indexed pixel class template. The available specializations are for 1-, 2- and 4-bit pixels.">packed_index_pixel< 1 ></a> <a class="code" href="namespacepng.html#<API key>" title="The 1-bit Indexed pixel type.">index_pixel_1</a>;
<a name="l00080"></a>00080
<a name="l00084"></a><a class="code" href="namespacepng.html#<API key>">00084</a> <span class="keyword">typedef</span> <a class="code" href="<API key>.html" title="The packed indexed pixel class template. The available specializations are for 1-, 2- and 4-bit pixels.">packed_index_pixel< 2 ></a> <a class="code" href="namespacepng.html#<API key>" title="The 1-bit Indexed pixel type.">index_pixel_2</a>;
<a name="l00085"></a>00085
<a name="l00089"></a><a class="code" href="namespacepng.html#<API key>">00089</a> <span class="keyword">typedef</span> <a class="code" href="<API key>.html" title="The packed indexed pixel class template. The available specializations are for 1-, 2- and 4-bit pixels.">packed_index_pixel< 4 ></a> <a class="code" href="namespacepng.html#<API key>" title="The 1-bit Indexed pixel type.">index_pixel_4</a>;
<a name="l00090"></a>00090
<a name="l00094"></a>00094 <span class="keyword">template</span><>
<a name="l00095"></a><a class="code" href="<API key>.html">00095</a> <span class="keyword">struct </span>pixel_traits< <a class="code" href="<API key>.html" title="The 8-bit Indexed (colormap) pixel type.">index_pixel</a> >
<a name="l00096"></a>00096 : <a class="code" href="<API key>.html" title="Basic pixel traits class template.">basic_pixel_traits</a>< index_pixel, byte, color_type_palette >
<a name="l00097"></a>00097 {
<a name="l00098"></a>00098 };
<a name="l00099"></a>00099
<a name="l00103"></a>00103 <span class="keyword">template</span>< <span class="keywordtype">size_t</span> bits >
<a name="l00104"></a><a class="code" href="<API key>.html">00104</a> <span class="keyword">struct </span>pixel_traits< <a class="code" href="<API key>.html" title="The packed indexed pixel class template. The available specializations are for 1-, 2- and 4-bit pixels.">packed_index_pixel</a>< bits > >
<a name="l00105"></a>00105 : <a class="code" href="<API key>.html" title="Basic pixel traits class template.">basic_pixel_traits</a>< packed_index_pixel< bits >, byte,
<a name="l00106"></a>00106 color_type_palette, <span class="comment">/* channels = */</span> 1, bits >
<a name="l00107"></a>00107 {
<a name="l00108"></a>00108 };
<a name="l00109"></a>00109
<a name="l00110"></a>00110 } <span class="comment">// namespace png</span>
<a name="l00111"></a>00111
<a name="l00112"></a>00112 <span class="preprocessor">#endif // <API key></span>
</pre></div></div>
</div>
<hr class="footer"/><address class="footer"><small>Generated on Thu Apr 21 2011 22:55:12 for png++ by 
<a href="http:
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.4 </small></address>
</body>
</html>
|
# This file is part of Shanghai, an asynchronous multi-server IRC bot.
# Shanghai is free software: you can redistribute it and/or modify
# (at your option) any later version.
# Shanghai is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
import asyncio
from unittest import mock
import pytest
from shanghai import event
from shanghai.logging import Logger, get_logger, LogLevels
# use this when debug log output is desired
debug_logger = get_logger('logging', 'debug')
debug_logger.setLevel(LogLevels.DDEBUG)
@pytest.fixture
def loop():
return asyncio.get_event_loop()
@pytest.fixture
def evt():
return event.build_event("event")
# base class to subclass for an actual plugin
class BasePlugin:
pass
@pytest.fixture
def sample_plugin():
class TestPlugin(BasePlugin):
@event.event
def on_test(self):
pass
return TestPlugin
class TestPriority:
def test_type(self):
assert isinstance(event.Priority.DEFAULT, int)
def test_order(self):
assert (event.Priority.PRE_CORE
> event.Priority.CORE
> event.Priority.POST_CORE
> event.Priority.PRE_DEFAULT
> event.Priority.DEFAULT
> event.Priority.POST_DEFAULT)
def test_lookup(self):
assert event.Priority.lookup(event.Priority.CORE) is event.Priority.CORE
assert event.Priority.lookup(event.Priority.CORE.value) is event.Priority.CORE
assert event.Priority.lookup(-12312412) == -12312412
class TestEvent:
def test_build_event(self):
evt = event.build_event("evt_name", arg1="val1", arg2=None)
assert evt.name == "evt_name"
assert evt.args == {'arg1': "val1", 'arg2': None}
class <API key>:
def test_bool(self):
prio_set_list = event._PrioritizedSetList()
assert bool(prio_set_list) is False
prio_set_list.add(0, None)
assert bool(prio_set_list) is True
def test_add(self):
prio_set_list = event._PrioritizedSetList()
objs = [(i,) for i in range(5)]
prio_set_list.add(0, objs[0])
assert prio_set_list.list == [(0, {objs[0]})]
prio_set_list.add(0, objs[1])
assert prio_set_list.list == [(0, {objs[0], objs[1]})]
prio_set_list.add(10, objs[2])
assert prio_set_list.list == [(10, {objs[2]}),
(0, {objs[0], objs[1]})]
prio_set_list.add(-10, objs[3])
assert prio_set_list.list == [( 10, {objs[2]}), # noqa: E201
( 0, {objs[0], objs[1]}), # noqa: E201
(-10, {objs[3]})]
prio_set_list.add(-1, objs[4])
assert prio_set_list.list == [( 10, {objs[2]}), # noqa: E201
( 0, {objs[0], objs[1]}), # noqa: E201
( -1, {objs[4]}), # noqa: E201
(-10, {objs[3]})]
def <API key>(self):
prio_set_list = event._PrioritizedSetList()
obj = object()
prio_set_list.add(0, obj)
with pytest.raises(ValueError) as excinfo:
prio_set_list.add(0, obj)
excinfo.match(r"has already been added")
with pytest.raises(ValueError) as excinfo:
prio_set_list.add(1, obj)
excinfo.match(r"has already been added")
def test_contains(self):
prio_set_list = event._PrioritizedSetList()
obj = object()
prio_set_list.add(0, obj)
assert obj in prio_set_list
def test_iter(self):
prio_set_list = event._PrioritizedSetList()
objs = [(i,) for i in range(5)]
for i, obj in enumerate(objs):
prio_set_list.add(-i, obj)
for i, set_ in enumerate(prio_set_list):
assert set_ == (-i, {objs[i]})
def test_remove(self):
prio_set_list = event._PrioritizedSetList()
obj = (1,)
prio_set_list.add(1, obj)
assert prio_set_list
prio_set_list.remove(obj)
assert not prio_set_list
with pytest.raises(ValueError) as excinfo:
prio_set_list.remove(obj)
excinfo.match(r"can not be found")
# Skipping HandlerInfo tests
# since that is only to be used with the `event` decorator anyway.
class TestEventDecorator:
def test_no_param_usage(self):
@event.event
def func_name(self):
pass
@event.event
def on_test(self):
pass
assert hasattr(on_test, '_h_info')
h_info = on_test._h_info
assert h_info.event_name == "test"
assert func_name._h_info.event_name == "func_name"
assert h_info.handler is on_test
assert h_info.priority is event.Priority.DEFAULT
assert h_info.should_enable
assert not h_info.is_async
def test_param_usage(self):
@event.event('evt_test', priority=-12, enable=False)
def on_test(self):
pass
assert hasattr(on_test, '_h_info')
h_info = on_test._h_info
assert h_info.event_name == 'evt_test'
assert h_info.handler is on_test
assert h_info.priority == -12
assert not h_info.should_enable
assert not h_info.is_async
def test_async_handler(self):
@event.event(enable=False)
async def on_async_test(self):
pass
assert hasattr(on_async_test, '_h_info')
h_info = on_async_test._h_info
assert h_info.event_name == 'async_test'
assert h_info.handler is on_async_test
assert h_info.priority is event.Priority.DEFAULT
assert not h_info.should_enable
assert h_info.is_async
def test_prefix(self):
import functools
other_event_deco = functools.partial(event.event, _prefix="__test_")
@other_event_deco
def on_test(self):
pass
assert hasattr(on_test, '_h_info')
h_info = on_test._h_info
assert h_info.event_name == '__test_test'
def <API key>(self):
@event.core_event
def on_test(self):
pass
assert hasattr(on_test, '_h_info')
h_info = on_test._h_info
assert h_info.priority is event.Priority.CORE
def test_non_callable(self):
with pytest.raises(TypeError) as excinfo:
event.event(123)
excinfo.match(r"Expected string, callable or None as first argument")
with pytest.raises(TypeError) as excinfo:
event.event("name")([])
excinfo.match(r"Callable must be a function \(`def`\)"
r" or coroutine function \(`async def`\)")
class TestHandlerInstance:
def test_from_handler(self):
@event.event
def handler():
pass
h_inst = event.HandlerInstance.from_handler(handler)
assert h_inst.info is handler._h_info
assert h_inst.enabled
assert h_inst.handler is handler._h_info.handler
def <API key>(self):
def func():
pass
with pytest.raises(ValueError) as excinfo:
event.HandlerInstance.from_handler(func)
excinfo.match(r"Event handler must be decorated with `@event`")
def test_hash(self):
@event.event
def handler():
pass
h_inst = event.HandlerInstance.from_handler(handler)
h_inst2 = event.HandlerInstance.from_handler(handler)
assert h_inst is not h_inst2
assert hash(h_inst) == hash(h_inst2)
assert h_inst != h_inst2
class TestResultSet:
def test_extend(self, evt, loop):
async def corofunc():
pass
coro = corofunc()
coro2 = corofunc()
# silence "coroutine never awaited" warnings
loop.run_until_complete(coro)
loop.run_until_complete(coro2)
rval = event.ReturnValue(append_events=[evt])
rval2 = event.ReturnValue(eat=True, schedule={coro})
rval3 = event.ReturnValue(append_events=[evt], insert_events=[evt],
schedule={coro, coro2})
rset = event.ResultSet()
rset2 = event.ResultSet()
rset.extend(rval)
assert not rset.eat
assert rset.append_events == [evt]
rset.extend(rval2)
assert rset.eat
assert rset.schedule == {coro}
rset2.extend(rval3)
rset.extend(rset2)
rset.extend(None)
assert rset.eat
assert rset.append_events == [evt, evt]
assert rset.insert_events == [evt]
assert rset.schedule == {coro, coro2}
def test_iadd(self, evt):
rval = event.ReturnValue(append_events=[evt])
rval2 = event.ReturnValue(eat=True, append_events=[evt])
rset = event.ResultSet()
rset += rval
rset += rval2
rset += None
assert rset.eat
assert rset.append_events == [evt, evt]
def test_type(self):
rset = event.ResultSet()
with pytest.raises(NotImplementedError):
rset.extend([])
with pytest.raises(NotImplementedError):
rset.extend(False)
class TestEventDispatcher:
@pytest.fixture
def dispatcher(self):
return event.EventDispatcher()
def test_register(self, dispatcher):
name = "some_name"
@event.event(name)
async def corofunc(*args):
return True
h_inst = event.HandlerInstance.from_handler(corofunc)
dispatcher.register(h_inst)
assert h_inst in dispatcher.event_map["some_name"]
def <API key>(self, dispatcher):
name = "some_name"
class AClass:
@event.event(name)
def handler(self):
pass
@event.event(name)
async def hander(self):
pass
obj = AClass()
h_insts = dispatcher.register_plugin(obj)
assert len(dispatcher.event_map) == 1
assert len(h_insts) == 2
for h_inst in h_insts:
assert h_inst in dispatcher.event_map[name]
def test_dispatch(self, dispatcher, loop):
name = "some_name"
args = dict(zip(map(str, range(10)), range(10, 20)))
called = 0
@event.event(name)
async def corofunc(**local_args):
nonlocal called
assert local_args == args
called += 1
h_inst = event.HandlerInstance.from_handler(corofunc)
dispatcher.register(h_inst)
evt = event.Event(name, args)
evt2 = evt._replace(name=evt.name + "_")
loop.run_until_complete(dispatcher.dispatch(evt))
loop.run_until_complete(dispatcher.dispatch(evt2))
assert called == 1
def <API key>(self, dispatcher, loop, evt):
called = list()
@event.event(evt.name, priority=0)
async def corofunc():
called.append(corofunc)
@event.event(evt.name, priority=1)
def corofunc2():
called.append(corofunc2)
h_inst = event.HandlerInstance.from_handler(corofunc)
h_inst2 = event.HandlerInstance.from_handler(corofunc2)
dispatcher.register(h_inst)
dispatcher.register(h_inst2)
loop.run_until_complete(dispatcher.dispatch(evt))
assert called == [corofunc2, corofunc]
def <API key>(self, dispatcher, loop, evt):
called = 0
@event.event(evt.name, enable=False)
async def corofunc():
nonlocal called
called += 1
h_inst = event.HandlerInstance.from_handler(corofunc)
dispatcher.register(h_inst)
loop.run_until_complete(dispatcher.dispatch(evt))
assert called == 0
# TODO test disabled
def <API key>(self, loop, evt):
logger = mock.Mock(Logger)
dispatcher = event.EventDispatcher(logger=logger)
called = 0
@event.event(evt.name)
async def corofunc():
nonlocal called
called += 1
raise ValueError("yeah async")
@event.event(evt.name)
def handler():
nonlocal called
called += 1
raise ValueError("yeah sync")
dispatcher.register(event.HandlerInstance.from_handler(corofunc))
dispatcher.register(event.HandlerInstance.from_handler(handler))
assert not logger.exception.called
loop.run_until_complete(dispatcher.dispatch(evt))
assert called == 2
assert logger.exception.call_count == 2
def <API key>(self, loop, evt):
logger = mock.Mock(Logger)
dispatcher = event.EventDispatcher(logger=logger)
called = False
@event.event(evt.name)
async def corofunc():
nonlocal called
called = True
return "some arbitrary value"
dispatcher.register(event.HandlerInstance.from_handler(corofunc))
assert not logger.warning.called
loop.run_until_complete(dispatcher.dispatch(evt))
assert called
assert logger.warning.call_count == 1
def test_dispatch_eat(self, loop, evt):
dispatcher = event.EventDispatcher()
called = [False] * 3
@event.event(evt.name, priority=1)
def corofunc():
called[0] = True
@event.event(evt.name, priority=0)
async def corofunc2():
called[1] = True
return event.ReturnValue(eat=True)
@event.event(evt.name, priority=-1)
async def corofunc3():
called[2] = True
dispatcher.register(event.HandlerInstance.from_handler(corofunc))
dispatcher.register(event.HandlerInstance.from_handler(corofunc2))
dispatcher.register(event.HandlerInstance.from_handler(corofunc3))
result = loop.run_until_complete(dispatcher.dispatch(evt))
assert result.eat
assert called == [True, True, False]
def <API key>(self, loop, evt):
dispatcher = event.EventDispatcher()
called = [0] * 3
evt1 = evt
evt2 = evt._replace(name=evt.name + "_")
evt3 = evt._replace(name=evt.name + "__")
@event.event(evt.name)
def corofunc1():
called[0] += 1
return event.ReturnValue(insert_events=[evt2], append_events=[evt])
@event.event(evt2.name)
def corofunc2():
called[1] += 1
return event.ReturnValue(insert_events=[evt3], append_events=[evt2])
@event.event(evt3.name)
def corofunc3():
called[2] += 1
async def corofunc():
pass
return event.ReturnValue(append_events=[evt3], schedule={corofunc()})
dispatcher.register(event.HandlerInstance.from_handler(corofunc1))
dispatcher.register(event.HandlerInstance.from_handler(corofunc2))
dispatcher.register(event.HandlerInstance.from_handler(corofunc3))
result = loop.run_until_complete(dispatcher.dispatch(evt))
assert called == [1, 1, 1]
assert result.append_events == [evt1, evt2, evt3]
assert len(result.schedule) == 1
# prevent warnings again
loop.run_until_complete(next(iter(result.schedule)))
# TODO other ReturnValue tests
|
#include <Action/<API key>.h>
#include <FaceModelViewer.h>
#include <FaceModel.h>
using FaceTools::Action::<API key>;
using FaceTools::Interactor::ActorMoveNotifier;
using FaceTools::Action::FaceAction;
using FaceTools::Action::Event;
using FaceTools::FaceModelViewer;
using FaceTools::ModelViewer;
using FaceTools::FM;
using FaceTools::FVS;
using FaceTools::Vis::FV;
using MS = FaceTools::Action::ModelSelector;
<API key>::<API key>( const QString& dn, const QIcon& ico, const QKeySequence& ks)
: FaceAction( dn, ico, ks), _dblClickDrag(false)
{
const Interactor::SelectNotifier *sn = MS::selector();
connect( sn, &Interactor::SelectNotifier::<API key>, this, &<API key>::_doDoubleClicked);
connect( sn, &Interactor::SelectNotifier::onLeftButtonUp, this, &<API key>::_doLeftButtonUp);
_moveNotifier = std::shared_ptr<ActorMoveNotifier>( new ActorMoveNotifier);
connect( &*_moveNotifier, &ActorMoveNotifier::onActorStart, this, &<API key>::_doOnActorStart);
connect( &*_moveNotifier, &ActorMoveNotifier::onActorStop, this, &<API key>::_doOnActorStop);
setCheckable( true, false);
} // end ctor
QString <API key>::toolTip() const
{
return "When on, click and drag the selected model to change its position or orientation.";
} // end toolTip
QString <API key>::whatsThis() const
{
QStringList htext;
htext << "With this option toggled off, mouse clicking and dragging causes the camera to move around.";
htext << "When this option is toggled on, clicking and dragging on a model will reposition or reorient it in space.";
htext << "Click and drag with the left mouse button to rotate the model in place.";
htext << "Click and drag with the right mouse button (or hold down the SHIFT key while left clicking and dragging)";
htext << "to shift the model laterally. Click and drag with the middle mouse button (or hold down the CTRL key while";
htext << "left or right clicking and dragging) to move the model towards or away from you.";
htext << "Note that clicking and dragging off the model's surface will still move the camera around, but that this also";
htext << "toggles this option off (any camera action from the menu/toolbar will also toggle this option off).";
return tr( htext.join(" ").toStdString().c_str());
} // end whatsThis
bool <API key>::checkState( Event)
{
return MS::interactionMode() == IMode::ACTOR_INTERACTION;
} // end checkState
bool <API key>::checkEnable( Event)
{
const FM* fm = MS::selectedModel();
return fm || isChecked();
} // end checkEnabled
void <API key>::doAction( Event)
{
if ( isChecked())
{
MS::showStatus( "Model interaction ACTIVE");
MS::setInteractionMode( IMode::ACTOR_INTERACTION, true);
} // end if
else
{
MS::showStatus( "Camera interaction ACTIVE", 5000);
MS::setInteractionMode( IMode::CAMERA_INTERACTION);
} // end else
} // end doAction
void <API key>::_doOnActorStart()
{
storeUndo( this, Event::AFFINE_CHANGE);
} // end _doOnActorStart
void <API key>::_doOnActorStop()
{
emit onEvent( Event::AFFINE_CHANGE);
} // end _doOnActorStop
// Called only when user double clicks on an already selected model.
void <API key>::_doDoubleClicked()
{
_dblClickDrag = true;
setChecked( true);
execute( Event::USER);
} // end _doDoubleClicked
void <API key>::_doLeftButtonUp()
{
if ( _dblClickDrag)
{
_dblClickDrag = false;
setChecked( false);
execute( Event::USER);
} // end if
} // end _doLeftButtonUp
|
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Geotagger Map</title>
<style type="text/css">
v\:* {
behavior:url(#default#VML);
}
</style>
<!-- Make the document body take up the full screen -->
<style type="text/css">
html, body {width: 100%; height: 100%}
body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
</style>
<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.2"></script>
<!-- Include GeoTaggerMap (GTM) scripting interface functions -->
<script src="gtminterface.js" type="text/javascript"></script>
<!-- Include Bing map (BMap) scripting interface functions -->
<script src="bmapinterface.js" type="text/javascript"></script>
<!-- Include offline map scripting interface functions -->
<script src="nomapinterface.js" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
function onLoad()
{
if (BMapInterface.IsAvailable())
{
// Initialize Google Maps implementation of callback interface
BMapInterface.Initialize("map");
// Initialize generic callback interface
GTMInterface.Initialize(BMapInterface);
}
else
{
NoMapInterface.Initialize(document.getElementById("map"));
GTMInterface.Initialize(NoMapInterface);
}
}
</script>
</head>
<body onload="onLoad()">
<div id="map" style="width: 100%; height: 100%;">Loading...</div>
</body>
</html>
|
#!/usr/bin/env python3
from heapq import heapify, heappop, heappush
with open('NUOC.INP') as f:
m, n = map(int, f.readline().split())
height = [[int(i) for i in line.split()] for line in f]
queue = ([(h, 0, i) for i, h in enumerate(height[0])]
+ [(h, m - 1, i) for i, h in enumerate(height[-1])]
+ [(height[i][0], i, 0) for i in range(m)]
+ [(height[i][-1], i, n - 1) for i in range(m)])
heapify(queue)
visited = ([[True] * n]
+ [[True] + [False] * (n - 2) + [True] for _ in range(m - 2)]
+ [[True] * n])
result = 0
while queue:
h, i, j = heappop(queue)
for x, y in (i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1):
if 0 <= x < m and 0 <= y < n and not visited[x][y]:
result += max(0, h - height[x][y])
heappush(queue, (max(height[x][y], h), x, y))
visited[x][y] = True
with open('NUOC.OUT', 'w') as f: print(result, file=f)
|
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#define BUFFER_SIZE 1024
int main()
{
int socketfd;
int port = 2047;
struct sockaddr_in server_in;
struct sockaddr_in client_in;
int client_in_length = sizeof(client_in);
char buffer[BUFFER_SIZE];
//Create a socket
socketfd = socket(AF_INET, SOCK_DGRAM, 0);
if (socketfd < 0)
{
perror("Creating a socket failed!");
return -1;
}
// Set the server address, by defaulting server_in to 0
// then setting it to the port, before binding
memset((char *) &server_in, 0, sizeof(server_in));
server_in.sin_family = AF_INET; //IPV4
server_in.sin_port = htons(port);
server_in.sin_addr.s_addr = htons(INADDR_ANY); //Any interface
//Bind, Note the second parameter needs to be a sockaddr
if (bind(socketfd, (struct sockaddr *) &server_in, sizeof(server_in)) == -1)
{
perror("Binding Failed, ec set to errno!");
return -2;
}
//Keep listening, for stuff
while (true)
{
memset(buffer, 0, sizeof(buffer));
if (recvfrom(socketfd, buffer, BUFFER_SIZE, 0, (struct sockaddr *) &client_in, (socklen_t *)&client_in_length) == -1)
{
perror("Recieving from client failed");
return -3;
}
if (sendto(socketfd, "OK\n", 3, 0, (struct sockaddr *) &client_in, client_in_length) == -1)
perror("Sending to client failed");
//Make sure its not empty lines
printf("Message: %s", buffer);
}
printf("Hello to the world of tomrow");
return 0;
}
|
#include "derivative.h"
#define MCU_XTAL_CLK 8192000
#define MCU_REF_CLK_DIVIDER 256
#define MCU_REF_CLK (MCU_XTAL_CLK/MCU_REF_CLK_DIVIDER)
#define MCU_FLL_OUT (MCU_REF_CLK*1536)
#define MCU_BUSCLK (MCU_FLL_OUT/2)
#define RTI_TICK 1 /* Real Time Interrupt [ms] */
#define RTI_MS(x) (x/RTI_TICK) /* Tick Base to ms */
#define reset_now() asm( "HALT" )
void mcu_init( unsigned char tick_ms );
unsigned long get_ts( void );
|
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//! Eth rpc implementation.
use std::thread;
use std::time::{Instant, Duration};
use std::sync::Arc;
use rlp::{self, UntrustedRlp};
use time::get_time;
use bigint::prelude::U256;
use bigint::hash::{H64, H160, H256};
use util::Address;
use parking_lot::Mutex;
use ethash::SeedHashCompute;
use ethcore::account_provider::{AccountProvider, DappId};
use ethcore::block::IsBlock;
use ethcore::client::{<API key>, BlockId, TransactionId, UncleId};
use ethcore::ethereum::Ethash;
use ethcore::filter::Filter as EthcoreFilter;
use ethcore::header::{Header as BlockHeader, BlockNumber as EthBlockNumber};
use ethcore::log_entry::LogEntry;
use ethcore::miner::{MinerService, <API key>};
use ethcore::transaction::SignedTransaction;
use ethcore::snapshot::SnapshotService;
use ethsync::{SyncProvider};
use jsonrpc_core::{BoxFuture, Result};
use jsonrpc_core::futures::future;
use jsonrpc_macros::Trailing;
use v1::helpers::{errors, limit_logs, fake_sign};
use v1::helpers::dispatch::{FullDispatcher, default_gas_price};
use v1::helpers::block_import::is_major_importing;
use v1::helpers::accounts::unwrap_provider;
use v1::traits::Eth;
use v1::types::{
RichBlock, Block, BlockTransactions, BlockNumber, Bytes, SyncStatus, SyncInfo,
Transaction, CallRequest, Index, Filter, Log, Receipt, Work,
H64 as RpcH64, H256 as RpcH256, H160 as RpcH160, U256 as RpcU256,
};
use v1::metadata::Metadata;
const EXTRA_INFO_PROOF: &'static str = "Object exists in in blockchain (fetched earlier), extra_info is always available if object exists; qed";
Eth RPC options
pub struct EthClientOptions {
Return nonce from transaction queue when pending block not available.
pub <API key>: bool,
Returns receipt from pending blocks
pub <API key>: bool,
Send additional block number when asking for work
pub <API key>: bool,
}
impl EthClientOptions {
Creates new default `EthClientOptions` and allows alterations
by provided function.
pub fn with<F: Fn(&mut Self)>(fun: F) -> Self {
let mut options = Self::default();
fun(&mut options);
options
}
}
impl Default for EthClientOptions {
fn default() -> Self {
EthClientOptions {
<API key>: false,
<API key>: true,
<API key>: true,
}
}
}
Eth rpc implementation.
pub struct EthClient<C, SN: ?Sized, S: ?Sized, M, EM> where
C: <API key>,
SN: SnapshotService,
S: SyncProvider,
M: MinerService,
EM: <API key> {
client: Arc<C>,
snapshot: Arc<SN>,
sync: Arc<S>,
accounts: Option<Arc<AccountProvider>>,
miner: Arc<M>,
external_miner: Arc<EM>,
seed_compute: Mutex<SeedHashCompute>,
options: EthClientOptions,
eip86_transition: u64,
}
impl<C, SN: ?Sized, S: ?Sized, M, EM> EthClient<C, SN, S, M, EM> where
C: <API key>,
SN: SnapshotService,
S: SyncProvider,
M: MinerService,
EM: <API key> {
Creates new EthClient.
pub fn new(
client: &Arc<C>,
snapshot: &Arc<SN>,
sync: &Arc<S>,
accounts: &Option<Arc<AccountProvider>>,
miner: &Arc<M>,
em: &Arc<EM>,
options: EthClientOptions
) -> Self {
EthClient {
client: client.clone(),
snapshot: snapshot.clone(),
sync: sync.clone(),
miner: miner.clone(),
accounts: accounts.clone(),
external_miner: em.clone(),
seed_compute: Mutex::new(SeedHashCompute::new()),
options: options,
eip86_transition: client.eip86_transition(),
}
}
Attempt to get the `Arc<AccountProvider>`, errors if provider was not
set.
fn account_provider(&self) -> Result<Arc<AccountProvider>> {
unwrap_provider(&self.accounts)
}
fn block(&self, id: BlockId, include_txs: bool) -> Result<Option<RichBlock>> {
let client = &self.client;
match (client.block(id.clone()), client.<API key>(id)) {
(Some(block), Some(total_difficulty)) => {
let view = block.header_view();
Ok(Some(RichBlock {
inner: Block {
hash: Some(view.hash().into()),
size: Some(block.rlp().as_raw().len().into()),
parent_hash: view.parent_hash().into(),
uncles_hash: view.uncles_hash().into(),
author: view.author().into(),
miner: view.author().into(),
state_root: view.state_root().into(),
transactions_root: view.transactions_root().into(),
receipts_root: view.receipts_root().into(),
number: Some(view.number().into()),
gas_used: view.gas_used().into(),
gas_limit: view.gas_limit().into(),
logs_bloom: view.log_bloom().into(),
timestamp: view.timestamp().into(),
difficulty: view.difficulty().into(),
total_difficulty: Some(total_difficulty.into()),
seal_fields: view.seal().into_iter().map(Into::into).collect(),
uncles: block.uncle_hashes().into_iter().map(Into::into).collect(),
transactions: match include_txs {
true => BlockTransactions::Full(block.view().<API key>().into_iter().map(|t| Transaction::from_localized(t, self.eip86_transition)).collect()),
false => BlockTransactions::Hashes(block.transaction_hashes().into_iter().map(Into::into).collect()),
},
extra_data: Bytes::new(view.extra_data()),
},
extra_info: client.block_extra_info(id.clone()).expect(EXTRA_INFO_PROOF),
}))
},
_ => Ok(None)
}
}
fn transaction(&self, id: TransactionId) -> Result<Option<Transaction>> {
match self.client.transaction(id) {
Some(t) => Ok(Some(Transaction::from_localized(t, self.eip86_transition))),
None => Ok(None),
}
}
fn uncle(&self, id: UncleId) -> Result<Option<RichBlock>> {
let client = &self.client;
let uncle: BlockHeader = match client.uncle(id) {
Some(hdr) => hdr.decode(),
None => { return Ok(None); }
};
let parent_difficulty = match client.<API key>(BlockId::Hash(uncle.parent_hash().clone())) {
Some(difficulty) => difficulty,
None => { return Ok(None); }
};
let size = client.block(BlockId::Hash(uncle.hash()))
.map(|block| block.into_inner().len())
.map(U256::from)
.map(Into::into);
let block = RichBlock {
inner: Block {
hash: Some(uncle.hash().into()),
size: size,
parent_hash: uncle.parent_hash().clone().into(),
uncles_hash: uncle.uncles_hash().clone().into(),
author: uncle.author().clone().into(),
miner: uncle.author().clone().into(),
state_root: uncle.state_root().clone().into(),
transactions_root: uncle.transactions_root().clone().into(),
number: Some(uncle.number().into()),
gas_used: uncle.gas_used().clone().into(),
gas_limit: uncle.gas_limit().clone().into(),
logs_bloom: uncle.log_bloom().clone().into(),
timestamp: uncle.timestamp().into(),
difficulty: uncle.difficulty().clone().into(),
total_difficulty: Some((uncle.difficulty().clone() + parent_difficulty).into()),
receipts_root: uncle.receipts_root().clone().into(),
extra_data: uncle.extra_data().clone().into(),
seal_fields: uncle.seal().into_iter().cloned().map(Into::into).collect(),
uncles: vec![],
transactions: BlockTransactions::Hashes(vec![]),
},
extra_info: client.uncle_extra_info(id).expect(EXTRA_INFO_PROOF),
};
Ok(Some(block))
}
fn dapp_accounts(&self, dapp: DappId) -> Result<Vec<H160>> {
let store = self.account_provider()?;
store
.note_dapp_used(dapp.clone())
.and_then(|_| store.dapp_addresses(dapp))
.map_err(|e| errors::account("Could not fetch accounts.", e))
}
}
pub fn pending_logs<M>(miner: &M, best_block: EthBlockNumber, filter: &EthcoreFilter) -> Vec<Log> where M: MinerService {
let receipts = miner.pending_receipts(best_block);
let pending_logs = receipts.into_iter()
.flat_map(|(hash, r)| r.logs.into_iter().map(|l| (hash.clone(), l)).collect::<Vec<(H256, LogEntry)>>())
.collect::<Vec<(H256, LogEntry)>>();
let result = pending_logs.into_iter()
.filter(|pair| filter.matches(&pair.1))
.map(|pair| {
let mut log = Log::from(pair.1);
log.transaction_hash = Some(pair.0.into());
log
})
.collect();
result
}
fn check_known<C>(client: &C, number: BlockNumber) -> Result<()> where C: <API key> {
use ethcore::block_status::BlockStatus;
match client.block_status(number.into()) {
BlockStatus::InChain => Ok(()),
BlockStatus::Pending => Ok(()),
_ => Err(errors::unknown_block()),
}
}
const <API key>: usize = 4; // because uncles go back 6.
impl<C, SN: ?Sized, S: ?Sized, M, EM> Eth for EthClient<C, SN, S, M, EM> where
C: <API key> + 'static,
SN: SnapshotService + 'static,
S: SyncProvider + 'static,
M: MinerService + 'static,
EM: <API key> + 'static,
{
type Metadata = Metadata;
fn protocol_version(&self) -> Result<String> {
let version = self.sync.status().protocol_version.to_owned();
Ok(format!("{}", version))
}
fn syncing(&self) -> Result<SyncStatus> {
use ethcore::snapshot::RestorationStatus;
let status = self.sync.status();
let client = &self.client;
let snapshot_status = self.snapshot.status();
let (warping, warp_chunks_amount, <API key>) = match snapshot_status {
RestorationStatus::Ongoing { state_chunks, block_chunks, state_chunks_done, block_chunks_done } =>
(true, Some(block_chunks + state_chunks), Some(block_chunks_done + state_chunks_done)),
_ => (false, None, None),
};
if warping || is_major_importing(Some(status.state), client.queue_info()) {
let chain_info = client.chain_info();
let current_block = U256::from(chain_info.best_block_number);
let highest_block = U256::from(status.<API key>.unwrap_or(status.start_block_number));
let info = SyncInfo {
starting_block: status.start_block_number.into(),
current_block: current_block.into(),
highest_block: highest_block.into(),
warp_chunks_amount: warp_chunks_amount.map(|x| U256::from(x as u64)).map(Into::into),
<API key>: <API key>.map(|x| U256::from(x as u64)).map(Into::into),
};
Ok(SyncStatus::Info(info))
} else {
Ok(SyncStatus::None)
}
}
fn author(&self, meta: Metadata) -> Result<RpcH160> {
let dapp = meta.dapp_id();
let mut miner = self.miner.author();
if miner == 0.into() {
miner = self.dapp_accounts(dapp.into())?.get(0).cloned().unwrap_or_default();
}
Ok(RpcH160::from(miner))
}
fn is_mining(&self) -> Result<bool> {
Ok(self.miner.<API key>())
}
fn hashrate(&self) -> Result<RpcU256> {
Ok(RpcU256::from(self.external_miner.hashrate()))
}
fn gas_price(&self) -> Result<RpcU256> {
Ok(RpcU256::from(default_gas_price(&*self.client, &*self.miner)))
}
fn accounts(&self, meta: Metadata) -> Result<Vec<RpcH160>> {
let dapp = meta.dapp_id();
let accounts = self.dapp_accounts(dapp.into())?;
Ok(accounts.into_iter().map(Into::into).collect())
}
fn block_number(&self) -> Result<RpcU256> {
Ok(RpcU256::from(self.client.chain_info().best_block_number))
}
fn balance(&self, address: RpcH160, num: Trailing<BlockNumber>) -> BoxFuture<RpcU256> {
let address = address.into();
let id = num.unwrap_or_default();
try_bf!(check_known(&*self.client, id.clone()));
let res = match self.client.balance(&address, id.into()) {
Some(balance) => Ok(balance.into()),
None => Err(errors::state_pruned()),
};
Box::new(future::done(res))
}
fn storage_at(&self, address: RpcH160, pos: RpcU256, num: Trailing<BlockNumber>) -> BoxFuture<RpcH256> {
let address: Address = RpcH160::into(address);
let position: U256 = RpcU256::into(pos);
let id = num.unwrap_or_default();
try_bf!(check_known(&*self.client, id.clone()));
let res = match self.client.storage_at(&address, &H256::from(position), id.into()) {
Some(s) => Ok(s.into()),
None => Err(errors::state_pruned()),
};
Box::new(future::done(res))
}
fn transaction_count(&self, address: RpcH160, num: Trailing<BlockNumber>) -> BoxFuture<RpcU256> {
let address: Address = RpcH160::into(address);
let res = match num.unwrap_or_default() {
BlockNumber::Pending if self.options.<API key> => {
let nonce = self.miner.last_nonce(&address)
.map(|n| n + 1.into())
.or_else(|| self.client.nonce(&address, BlockNumber::Pending.into()));
match nonce {
Some(nonce) => Ok(nonce.into()),
None => Err(errors::database("latest nonce missing"))
}
}
id => {
try_bf!(check_known(&*self.client, id.clone()));
match self.client.nonce(&address, id.into()) {
Some(nonce) => Ok(nonce.into()),
None => Err(errors::state_pruned()),
}
}
};
Box::new(future::done(res))
}
fn <API key>(&self, hash: RpcH256) -> BoxFuture<Option<RpcU256>> {
Box::new(future::ok(self.client.block(BlockId::Hash(hash.into()))
.map(|block| block.transactions_count().into())))
}
fn <API key>(&self, num: BlockNumber) -> BoxFuture<Option<RpcU256>> {
Box::new(future::ok(match num {
BlockNumber::Pending => Some(
self.miner.status().<API key>.into()
),
_ =>
self.client.block(num.into())
.map(|block| block.transactions_count().into())
}))
}
fn <API key>(&self, hash: RpcH256) -> BoxFuture<Option<RpcU256>> {
Box::new(future::ok(self.client.block(BlockId::Hash(hash.into()))
.map(|block| block.uncles_count().into())))
}
fn <API key>(&self, num: BlockNumber) -> BoxFuture<Option<RpcU256>> {
Box::new(future::ok(match num {
BlockNumber::Pending => Some(0.into()),
_ => self.client.block(num.into())
.map(|block| block.uncles_count().into()
),
}))
}
fn code_at(&self, address: RpcH160, num: Trailing<BlockNumber>) -> BoxFuture<Bytes> {
let address: Address = RpcH160::into(address);
let id = num.unwrap_or_default();
try_bf!(check_known(&*self.client, id.clone()));
let res = match self.client.code(&address, id.into()) {
Some(code) => Ok(code.map_or_else(Bytes::default, Bytes::new)),
None => Err(errors::state_pruned()),
};
Box::new(future::done(res))
}
fn block_by_hash(&self, hash: RpcH256, include_txs: bool) -> BoxFuture<Option<RichBlock>> {
Box::new(future::done(self.block(BlockId::Hash(hash.into()), include_txs)))
}
fn block_by_number(&self, num: BlockNumber, include_txs: bool) -> BoxFuture<Option<RichBlock>> {
Box::new(future::done(self.block(num.into(), include_txs)))
}
fn transaction_by_hash(&self, hash: RpcH256) -> BoxFuture<Option<Transaction>> {
let hash: H256 = hash.into();
let block_number = self.client.chain_info().best_block_number;
let tx = try_bf!(self.transaction(TransactionId::Hash(hash))).or_else(|| {
self.miner.transaction(block_number, &hash)
.map(|t| Transaction::from_pending(t, block_number, self.eip86_transition))
});
Box::new(future::ok(tx))
}
fn <API key>(&self, hash: RpcH256, index: Index) -> BoxFuture<Option<Transaction>> {
Box::new(future::done(
self.transaction(TransactionId::Location(BlockId::Hash(hash.into()), index.value()))
))
}
fn <API key>(&self, num: BlockNumber, index: Index) -> BoxFuture<Option<Transaction>> {
Box::new(future::done(
self.transaction(TransactionId::Location(num.into(), index.value()))
))
}
fn transaction_receipt(&self, hash: RpcH256) -> BoxFuture<Option<Receipt>> {
let best_block = self.client.chain_info().best_block_number;
let hash: H256 = hash.into();
match (self.miner.pending_receipt(best_block, &hash), self.options.<API key>) {
(Some(receipt), true) => Box::new(future::ok(Some(receipt.into()))),
_ => {
let receipt = self.client.transaction_receipt(TransactionId::Hash(hash));
Box::new(future::ok(receipt.map(Into::into)))
}
}
}
fn <API key>(&self, hash: RpcH256, index: Index) -> BoxFuture<Option<RichBlock>> {
Box::new(future::done(self.uncle(UncleId {
block: BlockId::Hash(hash.into()),
position: index.value()
})))
}
fn <API key>(&self, num: BlockNumber, index: Index) -> BoxFuture<Option<RichBlock>> {
Box::new(future::done(self.uncle(UncleId {
block: num.into(),
position: index.value()
})))
}
fn compilers(&self) -> Result<Vec<String>> {
Err(errors::deprecated("Compilation functionality is deprecated.".to_string()))
}
fn logs(&self, filter: Filter) -> BoxFuture<Vec<Log>> {
let include_pending = filter.to_block == Some(BlockNumber::Pending);
let filter: EthcoreFilter = filter.into();
let mut logs = self.client.logs(filter.clone())
.into_iter()
.map(From::from)
.collect::<Vec<Log>>();
if include_pending {
let best_block = self.client.chain_info().best_block_number;
let pending = pending_logs(&*self.miner, best_block, &filter);
logs.extend(pending);
}
let logs = limit_logs(logs, filter.limit);
Box::new(future::ok(logs))
}
fn work(&self, no_new_work_timeout: Trailing<u64>) -> Result<Work> {
if !self.miner.<API key>() {
warn!(target: "miner", "Cannot give work package - engine seals internally.");
return Err(errors::no_work_required())
}
let no_new_work_timeout = no_new_work_timeout.unwrap_or_default();
// check if we're still syncing and return empty strings in that case
{
//TODO: check if initial sync is complete here
//let sync = self.sync;
if /*sync.status().state != SyncState::Idle ||*/ self.client.queue_info().total_queue_size() > <API key> {
trace!(target: "miner", "Syncing. Cannot give any work.");
return Err(errors::no_work());
}
// Otherwise spin until our submitted block has been included.
let timeout = Instant::now() + Duration::from_millis(1000);
while Instant::now() < timeout && self.client.queue_info().total_queue_size() > 0 {
thread::sleep(Duration::from_millis(1));
}
}
if self.miner.author().is_zero() {
warn!(target: "miner", "Cannot give work package - no author is configured. Use --author to configure!");
return Err(errors::no_author())
}
self.miner.map_sealing_work(&*self.client, |b| {
let pow_hash = b.hash();
let target = Ethash::<API key>(b.block().header().difficulty());
let seed_hash = self.seed_compute.lock().hash_block_number(b.block().header().number());
if no_new_work_timeout > 0 && b.block().header().timestamp() + no_new_work_timeout < get_time().sec as u64 {
Err(errors::no_new_work())
} else if self.options.<API key> {
let block_number = b.block().header().number();
Ok(Work {
pow_hash: pow_hash.into(),
seed_hash: seed_hash.into(),
target: target.into(),
number: Some(block_number),
})
} else {
Ok(Work {
pow_hash: pow_hash.into(),
seed_hash: seed_hash.into(),
target: target.into(),
number: None
})
}
}).unwrap_or(Err(errors::internal("No work found.", "")))
}
fn submit_work(&self, nonce: RpcH64, pow_hash: RpcH256, mix_hash: RpcH256) -> Result<bool> {
if !self.miner.<API key>() {
warn!(target: "miner", "Cannot submit work - engine seals internally.");
return Err(errors::no_work_required())
}
let nonce: H64 = nonce.into();
let pow_hash: H256 = pow_hash.into();
let mix_hash: H256 = mix_hash.into();
trace!(target: "miner", "submit_work: Decoded: nonce={}, pow_hash={}, mix_hash={}", nonce, pow_hash, mix_hash);
let seal = vec![rlp::encode(&mix_hash).into_vec(), rlp::encode(&nonce).into_vec()];
Ok(self.miner.submit_seal(&*self.client, pow_hash, seal).is_ok())
}
fn submit_hashrate(&self, rate: RpcU256, id: RpcH256) -> Result<bool> {
self.external_miner.submit_hashrate(rate.into(), id.into());
Ok(true)
}
fn <API key>(&self, raw: Bytes) -> Result<RpcH256> {
UntrustedRlp::new(&raw.into_vec()).as_val()
.map_err(errors::rlp)
.and_then(|tx| SignedTransaction::new(tx).map_err(errors::transaction))
.and_then(|signed_transaction| {
FullDispatcher::<API key>(
&*self.client,
&*self.miner,
signed_transaction.into(),
)
})
.map(Into::into)
}
fn submit_transaction(&self, raw: Bytes) -> Result<RpcH256> {
self.<API key>(raw)
}
fn call(&self, meta: Self::Metadata, request: CallRequest, num: Trailing<BlockNumber>) -> BoxFuture<Bytes> {
let request = CallRequest::into(request);
let signed = try_bf!(fake_sign::sign_call(request, meta.is_dapp()));
let num = num.unwrap_or_default();
let result = self.client.call(&signed, Default::default(), num.into());
Box::new(future::done(result
.map(|b| b.output.into())
.map_err(errors::call)
))
}
fn estimate_gas(&self, meta: Self::Metadata, request: CallRequest, num: Trailing<BlockNumber>) -> BoxFuture<RpcU256> {
let request = CallRequest::into(request);
let signed = try_bf!(fake_sign::sign_call(request, meta.is_dapp()));
Box::new(future::done(self.client.estimate_gas(&signed, num.unwrap_or_default().into())
.map(Into::into)
.map_err(errors::call)
))
}
fn compile_lll(&self, _: String) -> Result<Bytes> {
Err(errors::deprecated("Compilation of LLL via RPC is deprecated".to_string()))
}
fn compile_serpent(&self, _: String) -> Result<Bytes> {
Err(errors::deprecated("Compilation of Serpent via RPC is deprecated".to_string()))
}
fn compile_solidity(&self, _: String) -> Result<Bytes> {
Err(errors::deprecated("Compilation of Solidity via RPC is deprecated".to_string()))
}
}
|
#ifndef <API key>
#define <API key>
#include "caditem.h"
#include "items/cad_basic_box.h"
class <API key> : public CADitem
{
public:
<API key>();
virtual ~<API key>();
virtual QList<CADitemTypes::ItemType> flangable_items(int flangeIndex);
virtual QImage wizardImage();
virtual QString iconPath();
virtual QString domain();
virtual QString description();
virtual void calculate();
virtual void processWizardInput();
virtual QMatrix4x4 rotationOfFlange(quint8 num);
// virtual void paint(GLWidget* glwidget);
// QOpenGLBuffer arrayBufVertices;
// QOpenGLBuffer indexBufFaces;
// QOpenGLBuffer indexBufLines;
qreal a, a2, l, l2, b;
CAD_basic_box *radiator;
};
#endif // <API key>
|
package net.joaopms.PvPUtilities.helper;
import net.minecraftforge.common.config.Configuration;
import java.io.File;
public class ConfigHelper {
private static Configuration config;
public static void init(File file) {
config = new Configuration(file, true);
config.load();
initConfig();
config.save();
}
public static Configuration getConfig() {
return config;
}
private static void initConfig() {
config.get("overcastStatistics", "showOvercastLogo", true);
config.get("overcastStatistics", "showKills", true);
config.get("overcastStatistics", "showDeaths", true);
config.get("overcastStatistics", "showFriends", false);
config.get("overcastStatistics", "showKD", true);
config.get("overcastStatistics", "showKK", false);
config.get("overcastStatistics", "showServerJoins", false);
config.get("overcastStatistics", "showDaysPlayed", false);
config.get("overcastStatistics", "showRaindrops", false);
config.get("overcastStatistics", "overlayOpacity", 0.5F);
}
}
|
""" Loads hyperspy as a regular python library, creates a spectrum with random numbers and plots it to a file"""
import hyperspy.api as hs
import numpy as np
import matplotlib.pyplot as plt
s = hs.signals.Spectrum(np.random.rand(1024))
s.plot()
plt.savefig("testSpectrum.png")
|
# Makefile.in generated by automake 1.14.1 from Makefile.am.
# compat/jansson/Makefile. Generated from Makefile.in by configure.
# This Makefile.in is free software; the Free Software Foundation
# with or without modifications, as long as this notice is preserved.
# This program is distributed in the hope that it will be useful,
# PARTICULAR PURPOSE.
am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)'
<API key> = \
case $${target_option-} in \
?) ;; \
*) echo "<API key>: internal error: invalid" \
"target option '$${target_option-}' specified" >&2; \
exit 1;; \
esac; \
has_opt=no; \
sane_makeflags=$$MAKEFLAGS; \
if $(am__is_gnu_make); then \
sane_makeflags=$$MFLAGS; \
else \
case $$MAKEFLAGS in \
*\\[\ \ ]*) \
bs=\\; \
sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \
| sed "s/$$bs$$bs[$$bs $$bs ]*
esac; \
fi; \
skip_next=no; \
strip_trailopt () \
{ \
flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$
}; \
for flg in $$sane_makeflags; do \
test $$skip_next = yes && { skip_next=no; continue; }; \
case $$flg in \
*=*|--*) continue;; \
-*I) strip_trailopt 'I'; skip_next=yes;; \
-*I?*) strip_trailopt 'I';; \
-*O) strip_trailopt 'O'; skip_next=yes;; \
-*O?*) strip_trailopt 'O';; \
-*l) strip_trailopt 'l'; skip_next=yes;; \
-*l?*) strip_trailopt 'l';; \
-[dEDm]) skip_next=yes;; \
-[JT]) skip_next=yes;; \
esac; \
case $$flg in \
*$$target_option*) has_opt=yes; break;; \
esac; \
done; \
test $$has_opt = yes
am__make_dryrun = (target_option=n; $(<API key>))
am__make_keepgoing = (target_option=k; $(<API key>))
pkgdatadir = $(datadir)/ccminer
pkgincludedir = $(includedir)/ccminer
pkglibdir = $(libdir)/ccminer
pkglibexecdir = $(libexecdir)/ccminer
am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
install_sh_DATA = $(install_sh) -c -m 644
install_sh_PROGRAM = $(install_sh) -c
install_sh_SCRIPT = $(install_sh) -c
INSTALL_HEADER = $(INSTALL_DATA)
transform = $(<API key>)
NORMAL_INSTALL = :
PRE_INSTALL = :
POST_INSTALL = :
NORMAL_UNINSTALL = :
PRE_UNINSTALL = :
POST_UNINSTALL = :
build_triplet = <API key>
host_triplet = <API key>
target_triplet = <API key>
subdir = compat/jansson
DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \
$(top_srcdir)/depcomp
ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
am__aclocal_m4_deps = $(top_srcdir)/configure.ac
am__configure_deps = $(am__aclocal_m4_deps) $(<API key>) \
$(ACLOCAL_M4)
mkinstalldirs = $(install_sh) -d
CONFIG_HEADER = $(top_builddir)/ccminer-config.h
CONFIG_CLEAN_FILES =
<API key> =
LIBRARIES = $(noinst_LIBRARIES)
AR = ar
ARFLAGS = cru
AM_V_AR = $(am__v_AR_$(V))
am__v_AR_ = $(am__v_AR_$(<API key>))
am__v_AR_0 = @echo " AR " $@;
am__v_AR_1 =
libjansson_a_AR = $(AR) $(ARFLAGS)
libjansson_a_LIBADD =
<API key> = dump.$(OBJEXT) error.$(OBJEXT) \
hashtable.$(OBJEXT) load.$(OBJEXT) memory.$(OBJEXT) \
pack_unpack.$(OBJEXT) strbuffer.$(OBJEXT) strconv.$(OBJEXT) \
utf.$(OBJEXT) value.$(OBJEXT)
<API key> = $(<API key>)
AM_V_P = $(am__v_P_$(V))
am__v_P_ = $(am__v_P_$(<API key>))
am__v_P_0 = false
am__v_P_1 = :
AM_V_GEN = $(am__v_GEN_$(V))
am__v_GEN_ = $(am__v_GEN_$(<API key>))
am__v_GEN_0 = @echo " GEN " $@;
am__v_GEN_1 =
AM_V_at = $(am__v_at_$(V))
am__v_at_ = $(am__v_at_$(<API key>))
am__v_at_0 = @
am__v_at_1 =
DEFAULT_INCLUDES = -I. -I$(top_builddir)
depcomp = $(SHELL) $(top_srcdir)/depcomp
am__depfiles_maybe = depfiles
am__mv = mv -f
COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
AM_V_CC = $(am__v_CC_$(V))
am__v_CC_ = $(am__v_CC_$(<API key>))
am__v_CC_0 = @echo " CC " $@;
am__v_CC_1 =
CCLD = $(CC)
LINK = $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@
AM_V_CCLD = $(am__v_CCLD_$(V))
am__v_CCLD_ = $(am__v_CCLD_$(<API key>))
am__v_CCLD_0 = @echo " CCLD " $@;
am__v_CCLD_1 =
SOURCES = $(<API key>)
DIST_SOURCES = $(<API key>)
<API key> = \
case $$AM_UPDATE_INFO_DIR in \
n|no|NO) false;; \
*) (install-info --version) >/dev/null 2>&1;; \
esac
am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP)
# Read a list of newline-separated strings from the standard input,
# and print each of them once, without duplicates. Input order is
# *not* preserved.
am__uniquify_input = $(AWK) '\
BEGIN { nonempty = 0; } \
{ items[$$0] = 1; nonempty = 1; } \
END { if (nonempty) { for (i in items) print i; }; } \
'
# Make sure the list of sources is unique. This is necessary because,
# e.g., the same source file might be shared among _SOURCES variables
# for different programs/libraries.
<API key> = \
list='$(am__tagged_files)'; \
unique=`for i in $$list; do \
if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
done | $(am__uniquify_input)`
ETAGS = etags
CTAGS = ctags
DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
ACLOCAL = ${SHELL} /home/revolux/Desktop/ccminer/missing aclocal-1.14
ALLOCA =
AMTAR = $${TAR-tar}
<API key> = 1
AUTOCONF = ${SHELL} /home/revolux/Desktop/ccminer/missing autoconf
AUTOHEADER = ${SHELL} /home/revolux/Desktop/ccminer/missing autoheader
AUTOMAKE = ${SHELL} /home/revolux/Desktop/ccminer/missing automake-1.14
AWK = gawk
CC = gcc -std=gnu99
CCAS = gcc -std=gnu99
CCASDEPMODE = depmode=gcc3
CCASFLAGS = -g -O2
CCDEPMODE = depmode=gcc3
CFLAGS = -g -O2
CPP = gcc -std=gnu99 -E
CPPFLAGS =
CUDA_CFLAGS = -O3 -lineno -Xcompiler -Wall -D_FORCE_INLINES
CUDA_INCLUDES = -I/usr/local/cuda/include
CUDA_LDFLAGS = -L/usr/local/cuda/lib64 -ldl
CUDA_LIBS = -lcudart
CXX = g++
CXXDEPMODE = depmode=gcc3
CXXFLAGS = -O3 -march=native -D_REENTRANT -falign-functions=16 -falign-jumps=16 -falign-labels=16
CYGPATH_W = echo
DEFS = -DHAVE_CONFIG_H
DEPDIR = .deps
ECHO_C =
ECHO_N = -n
ECHO_T =
EGREP = /bin/grep -E
EXEEXT =
GREP = /bin/grep
INSTALL = /usr/bin/install -c
INSTALL_DATA = ${INSTALL} -m 644
INSTALL_PROGRAM = ${INSTALL}
INSTALL_SCRIPT = ${INSTALL}
<API key> = $(install_sh) -c -s
JANSSON_LIBS = -ljansson
LDFLAGS =
LIBCURL = -L/usr/lib/x86_64-linux-gnu -lcurl
LIBCURL_CPPFLAGS =
LIBOBJS =
LIBS = -lcrypto -lssl -lz
LTLIBOBJS =
MAINT =
MAKEINFO = ${SHELL} /home/revolux/Desktop/ccminer/missing makeinfo
MKDIR_P = /bin/mkdir -p
NVCC = /usr/local/cuda/bin/nvcc
NVML_LIBPATH = libnvidia-ml.so
OBJEXT = o
OPENMP_CFLAGS = -fopenmp
PACKAGE = ccminer
PACKAGE_BUGREPORT =
PACKAGE_NAME = ccminer
PACKAGE_STRING = ccminer 2.2.1
PACKAGE_TARNAME = ccminer
PACKAGE_URL = http://github.com/tpruvot/ccminer
PACKAGE_VERSION = 2.2.1
PATH_SEPARATOR = :
PTHREAD_FLAGS = -pthread
PTHREAD_LIBS = -lpthread
RANLIB = ranlib
SET_MAKE =
SHELL = /bin/bash
STRIP =
VERSION = 2.2.1
WS2_LIBS =
_libcurl_config =
abs_builddir = /home/revolux/Desktop/ccminer/compat/jansson
abs_srcdir = /home/revolux/Desktop/ccminer/compat/jansson
abs_top_builddir = /home/revolux/Desktop/ccminer
abs_top_srcdir = /home/revolux/Desktop/ccminer
ac_ct_CC = gcc
ac_ct_CXX = g++
am__include = include
am__leading_dot = .
am__quote =
am__tar = $${TAR-tar} chof - "$$tardir"
am__untar = $${TAR-tar} xf -
bindir = ${exec_prefix}/bin
build = <API key>
build_alias =
build_cpu = x86_64
build_os = linux-gnu
build_vendor = unknown
builddir = .
datadir = ${datarootdir}
datarootdir = ${prefix}/share
docdir = ${datarootdir}/doc/${PACKAGE_TARNAME}
dvidir = ${docdir}
exec_prefix = ${prefix}
host = <API key>
host_alias =
host_cpu = x86_64
host_os = linux-gnu
host_vendor = unknown
htmldir = ${docdir}
includedir = ${prefix}/include
infodir = ${datarootdir}/info
install_sh = ${SHELL} /home/revolux/Desktop/ccminer/install-sh
libdir = ${exec_prefix}/lib
libexecdir = ${exec_prefix}/libexec
localedir = ${datarootdir}/locale
localstatedir = ${prefix}/var
mandir = ${datarootdir}/man
mkdir_p = $(MKDIR_P)
oldincludedir = /usr/include
pdfdir = ${docdir}
prefix = /usr/local
<API key> = s,x,x,
psdir = ${docdir}
sbindir = ${exec_prefix}/sbin
sharedstatedir = ${prefix}/com
srcdir = .
sysconfdir = ${prefix}/etc
target = <API key>
target_alias =
target_cpu = x86_64
target_os = linux-gnu
target_vendor = unknown
top_build_prefix = ../../
top_builddir = ../..
top_srcdir = ../..
noinst_LIBRARIES = libjansson.a
<API key> = \
<API key>.h \
dump.c \
error.c \
hashtable.c hashtable.h \
jansson.h \
jansson_config.h \
jansson_private.h \
load.c \
memory.c \
pack_unpack.c \
strbuffer.c strbuffer.h \
strconv.c \
utf.c utf.h \
util.h \
value.c
all: all-am
.SUFFIXES:
.SUFFIXES: .c .o .obj
$(srcdir)/Makefile.in: # $(srcdir)/Makefile.am $(am__configure_deps)
@for dep in $?; do \
case '$(am__configure_deps)' in \
*$$dep*) \
( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
&& { if test -f $@; then exit 0; else break; fi; }; \
exit 1;; \
esac; \
done; \
echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign compat/jansson/Makefile'; \
$(am__cd) $(top_srcdir) && \
$(AUTOMAKE) --foreign compat/jansson/Makefile
.PRECIOUS: Makefile
Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
@case '$?' in \
*config.status*) \
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
*) \
echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
esac;
$(top_builddir)/config.status: $(top_srcdir)/configure $(<API key>)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(top_srcdir)/configure: # $(am__configure_deps)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(ACLOCAL_M4): # $(am__aclocal_m4_deps)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(am__aclocal_m4_deps):
<API key>:
-test -z "$(noinst_LIBRARIES)" || rm -f $(noinst_LIBRARIES)
libjansson.a: $(<API key>) $(<API key>) $(<API key>)
$(AM_V_at)-rm -f libjansson.a
$(AM_V_AR)$(libjansson_a_AR) libjansson.a $(<API key>) $(libjansson_a_LIBADD)
$(AM_V_at)$(RANLIB) libjansson.a
mostlyclean-compile:
-rm -f *.$(OBJEXT)
distclean-compile:
-rm -f *.tab.c
include ./$(DEPDIR)/dump.Po
include ./$(DEPDIR)/error.Po
include ./$(DEPDIR)/hashtable.Po
include ./$(DEPDIR)/load.Po
include ./$(DEPDIR)/memory.Po
include ./$(DEPDIR)/pack_unpack.Po
include ./$(DEPDIR)/strbuffer.Po
include ./$(DEPDIR)/strconv.Po
include ./$(DEPDIR)/utf.Po
include ./$(DEPDIR)/value.Po
.c.o:
$(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\
$(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\
$(am__mv) $$depbase.Tpo $$depbase.Po
# $(AM_V_CC)source='$<' object='$@' libtool=no \
# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
# $(AM_V_CC_no)$(COMPILE) -c -o $@ $<
.c.obj:
$(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\
$(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\
$(am__mv) $$depbase.Tpo $$depbase.Po
# $(AM_V_CC)source='$<' object='$@' libtool=no \
# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
# $(AM_V_CC_no)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'`
ID: $(am__tagged_files)
$(<API key>); mkid -fID $$unique
tags: tags-am
TAGS: tags
tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
set x; \
here=`pwd`; \
$(<API key>); \
shift; \
if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
test -n "$$unique" || unique=$$empty_fix; \
if test $$# -gt 0; then \
$(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
"$$@" $$unique; \
else \
$(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
$$unique; \
fi; \
fi
ctags: ctags-am
CTAGS: ctags
ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
$(<API key>); \
test -z "$(CTAGS_ARGS)$$unique" \
|| $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
$$unique
GTAGS:
here=`$(am__cd) $(top_builddir) && pwd` \
&& $(am__cd) $(top_srcdir) \
&& gtags -i $(GTAGS_ARGS) "$$here"
cscopelist: cscopelist-am
cscopelist-am: $(am__tagged_files)
list='$(am__tagged_files)'; \
case "$(srcdir)" in \
[\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \
*) sdir=$(subdir)/$(srcdir) ;; \
esac; \
for i in $$list; do \
if test -f "$$i"; then \
echo "$(subdir)/$$i"; \
else \
echo "$$sdir/$$i"; \
fi; \
done >> $(top_builddir)/cscope.files
distclean-tags:
-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
distdir: $(DISTFILES)
@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
list='$(DISTFILES)'; \
dist_files=`for file in $$list; do echo $$file; done | \
sed -e "s|^$$srcdirstrip/||;t" \
-e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
case $$dist_files in \
*/*) $(MKDIR_P) `echo "$$dist_files" | \
sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
sort -u` ;; \
esac; \
for file in $$dist_files; do \
if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
if test -d $$d/$$file; then \
dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
if test -d "$(distdir)/$$file"; then \
find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
fi; \
if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
fi; \
cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
else \
test -f "$(distdir)/$$file" \
|| cp -p $$d/$$file "$(distdir)/$$file" \
|| exit 1; \
fi; \
done
check-am: all-am
check: check-am
all-am: Makefile $(LIBRARIES)
installdirs:
install: install-am
install-exec: install-exec-am
install-data: install-data-am
uninstall: uninstall-am
install-am: all-am
@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
installcheck: installcheck-am
install-strip:
if test -z '$(STRIP)'; then \
$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(<API key>)" \
install_sh_PROGRAM="$(<API key>)" INSTALL_STRIP_FLAG=-s \
install; \
else \
$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(<API key>)" \
install_sh_PROGRAM="$(<API key>)" INSTALL_STRIP_FLAG=-s \
"INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
fi
mostlyclean-generic:
clean-generic:
distclean-generic:
-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-test . = "$(srcdir)" || test -z "$(<API key>)" || rm -f $(<API key>)
<API key>:
@echo "This command is intended for maintainers to use"
@echo "it deletes files that may require special tools to rebuild."
clean: clean-am
clean-am: clean-generic <API key> mostlyclean-am
distclean: distclean-am
-rm -rf ./$(DEPDIR)
-rm -f Makefile
distclean-am: clean-am distclean-compile distclean-generic \
distclean-tags
dvi: dvi-am
dvi-am:
html: html-am
html-am:
info: info-am
info-am:
install-data-am:
install-dvi: install-dvi-am
install-dvi-am:
install-exec-am:
install-html: install-html-am
install-html-am:
install-info: install-info-am
install-info-am:
install-man:
install-pdf: install-pdf-am
install-pdf-am:
install-ps: install-ps-am
install-ps-am:
installcheck-am:
maintainer-clean: maintainer-clean-am
-rm -rf ./$(DEPDIR)
-rm -f Makefile
maintainer-clean-am: distclean-am <API key>
mostlyclean: mostlyclean-am
mostlyclean-am: mostlyclean-compile mostlyclean-generic
pdf: pdf-am
pdf-am:
ps: ps-am
ps-am:
uninstall-am:
.MAKE: install-am install-strip
.PHONY: CTAGS GTAGS TAGS all all-am check check-am clean clean-generic \
<API key> cscopelist-am ctags ctags-am distclean \
distclean-compile distclean-generic distclean-tags distdir dvi \
dvi-am html html-am info info-am install install-am \
install-data install-data-am install-dvi install-dvi-am \
install-exec install-exec-am install-html install-html-am \
install-info install-info-am install-man install-pdf \
install-pdf-am install-ps install-ps-am install-strip \
installcheck installcheck-am installdirs maintainer-clean \
<API key> mostlyclean mostlyclean-compile \
mostlyclean-generic pdf pdf-am ps ps-am tags tags-am uninstall \
uninstall-am
# Tell versions [3.59,3.63) of GNU make to not export all variables.
# Otherwise a system limit (for SysV at least) may be exceeded.
.NOEXPORT:
|
/* $OpenBSD: stdlib.h,v 1.10 1999/06/11 22:47:48 espie Exp $ */
/* $NetBSD: stdlib.h,v 1.25 1995/12/27 21:19:08 jtc Exp $ */
#ifndef _STDLIB_H_
#define _STDLIB_H_
#include <machine/ansi.h>
#if !defined(_ANSI_SOURCE) /* for quad_t, etc. */
#include <sys/types.h>
#endif
#ifdef _BSD_SIZE_T_
typedef _BSD_SIZE_T_ size_t;
#undef _BSD_SIZE_T_
#endif
#ifdef _BSD_WCHAR_T_
typedef _BSD_WCHAR_T_ wchar_t;
#undef _BSD_WCHAR_T_
#endif
typedef struct {
int quot; /* quotient */
int rem; /* remainder */
} div_t;
typedef struct {
long quot; /* quotient */
long rem; /* remainder */
} ldiv_t;
#if !defined(_ANSI_SOURCE)
typedef struct {
quad_t quot; /* quotient */
quad_t rem; /* remainder */
} qdiv_t;
#endif
#ifndef NULL
#ifdef __GNUG__
#define NULL __null
#else
#define NULL 0
#endif
#endif
#define EXIT_FAILURE 1
#define EXIT_SUCCESS 0
#define RAND_MAX 0x7fffffff
#define MB_CUR_MAX 1 /* XXX */
#include <sys/cdefs.h>
__BEGIN_DECLS
__dead void abort __P((void));
int abs __P((int));
int atexit __P((void (*)(void)));
double atof __P((const char *));
int atoi __P((const char *));
long atol __P((const char *));
void *bsearch __P((const void *, const void *, size_t,
size_t, int (*)(const void *, const void *)));
void *calloc __P((size_t, size_t));
div_t div __P((int, int));
__dead void exit __P((int));
void free __P((void *));
char *getenv __P((const char *));
long labs __P((long));
ldiv_t ldiv __P((long, long));
void *malloc __P((size_t));
void qsort __P((void *, size_t, size_t,
int (*)(const void *, const void *)));
int rand __P((void));
int rand_r __P((unsigned int *));
void *realloc __P((void *, size_t));
void srand __P((unsigned));
double strtod __P((const char *, char **));
long strtol __P((const char *, char **, int));
unsigned long
strtoul __P((const char *, char **, int));
int system __P((const char *));
/* these are currently just stubs */
int mblen __P((const char *, size_t));
size_t mbstowcs __P((wchar_t *, const char *, size_t));
int wctomb __P((char *, wchar_t));
int mbtowc __P((wchar_t *, const char *, size_t));
size_t wcstombs __P((char *, const wchar_t *, size_t));
#if !defined(_ANSI_SOURCE) && !defined(_POSIX_SOURCE)
#if defined(alloca) && (alloca == __builtin_alloca) && (__GNUC__ < 2)
void *alloca __P((int)); /* built-in for gcc */
#else
void *alloca __P((size_t));
#endif /* __GNUC__ */
char *getbsize __P((int *, long *));
char *cgetcap __P((char *, const char *, int));
int cgetclose __P((void));
int cgetent __P((char **, char **, const char *));
int cgetfirst __P((char **, char **));
int cgetmatch __P((char *, const char *));
int cgetnext __P((char **, char **));
int cgetnum __P((char *, const char *, long *));
int cgetset __P((const char *));
int cgetstr __P((char *, const char *, char **));
int cgetustr __P((char *, const char *, char **));
int daemon __P((int, int));
char *devname __P((int, int));
int getloadavg __P((double [], int));
long a64l __P((const char *));
char *l64a __P((long));
void cfree __P((void *));
int getopt __P((int, char * const *, const char *));
extern char *optarg; /* getopt(3) external variables */
extern int opterr;
extern int optind;
extern int optopt;
extern int optreset;
int getsubopt __P((char **, char * const *, char **));
extern char *suboptarg; /* getsubopt(3) external variable */
int heapsort __P((void *, size_t, size_t,
int (*)(const void *, const void *)));
int mergesort __P((void *, size_t, size_t,
int (*)(const void *, const void *)));
int radixsort __P((const unsigned char **, int, const unsigned char *,
unsigned));
int sradixsort __P((const unsigned char **, int, const unsigned char *,
unsigned));
char *initstate __P((unsigned int, char *, size_t));
long random __P((void));
char *realpath __P((const char *, char *));
char *setstate __P((const char *));
void srandom __P((unsigned int));
int putenv __P((const char *));
#ifdef NOTUSED_BY_PMON
int setenv __P((const char *, const char *, int));
#endif
void unsetenv __P((const char *));
void setproctitle __P((const char *, ...));
quad_t qabs __P((quad_t));
qdiv_t qdiv __P((quad_t, quad_t));
quad_t strtoq __P((const char *, char **, int));
u_quad_t strtouq __P((const char *, char **, int));
double drand48 __P((void));
double erand48 __P((unsigned short[3]));
long jrand48 __P((unsigned short[3]));
void lcong48 __P((unsigned short[7]));
long lrand48 __P((void));
long mrand48 __P((void));
long nrand48 __P((unsigned short[3]));
unsigned short *seed48 __P((unsigned short[3]));
void srand48 __P((long));
u_int32_t arc4random __P((void));
void arc4random_stir __P((void));
void <API key> __P((unsigned char *, int));
int getbaudval __P((int ));
int getbaudrate __P((char *));
#endif /* !_ANSI_SOURCE && !_POSIX_SOURCE */
__END_DECLS
#endif /* _STDLIB_H_ */
|
package com.bruce.android.knowledge.custom_view.scanAnimation;
/**
* @author zhenghao.qi
* @version 1.0
* @time 2015110914:45:32
*/
public class <API key> implements IAnimationStrategy {
private int startX;
private int startY;
private int shift;
/**
* X Y
*/
private double currentX, currentY;
private long startTime;
private long cyclePeriod;
/**
* truefalse
*/
private boolean doing;
/**
* view
*/
private <API key> <API key>;
public <API key>(<API key> <API key>, int shift, long cyclePeriod) {
this.<API key> = <API key>;
this.shift = shift;
this.cyclePeriod = cyclePeriod;
initParams();
}
public void start() {
startTime = System.currentTimeMillis();
doing = true;
}
private void initParams() {
int[] position = new int[2];
<API key>.getLocationInWindow(position);
this.startX = position[0];
this.startY = position[1];
}
public void compute() {
long intervalTime = (System.currentTimeMillis() - startTime) % cyclePeriod;
double angle = Math.toRadians(360 * 1.0d * intervalTime / cyclePeriod);
int y = (int) (shift / 2 * Math.cos(angle));
y = Math.abs(y - shift/2);
currentY = startY + y;
doing = true;
}
@Override
public boolean doing() {
return doing;
}
public double getX() {
return currentX;
}
public double getY() {
return currentY;
}
public void cancel() {
doing = false;
}
}
|
Wordpress 4.5.3 = <API key>
Wordpress 4.1.13 = <API key>
Wordpress 3.8.16 = <API key>
Wordpress 3.4.2 = <API key>
Wordpress 5.1.1 = <API key>
Wordpress 5.3.1 = <API key>
|
// needs Markdown.Converter.js at the moment
(function () {
var util = {},
position = {},
ui = {},
doc = window.document,
re = window.RegExp,
nav = window.navigator,
SETTINGS = { lineLength: 72 },
// Used to work around some browser bugs where we can't use feature testing.
uaSniffed = {
isIE: /msie/.test(nav.userAgent.toLowerCase()),
isIE_5or6: /msie 6/.test(nav.userAgent.toLowerCase()) || /msie 5/.test(nav.userAgent.toLowerCase()),
isOpera: /opera/.test(nav.userAgent.toLowerCase())
};
// YOUR CHANGES GO HERE
// I've tried to localize the things you are likely to change to
// this area.
// The text that appears on the upper part of the dialog box when
// entering links.
var linkDialogText = "<p><b>Insert Hyperlink</b></p><p>http://example.com/ \"optional title\"</p>";
var imageDialogText = "<p><b>Insert Image</b></p><p>http://example.com/images/diagram.jpg \"optional title\"<br></p>";
// The default text that appears in the dialog input box when entering
// links.
var imageDefaultText = "http:
var linkDefaultText = "http:
var <API key> = "Markdown Editing Help";
// END OF YOUR CHANGES
// help, if given, should have a property "handler", the click handler for the help button,
// and can have an optional property "title" for the button's tooltip (defaults to "Markdown Editing Help").
// If help isn't given, not help button is created.
// The constructed editor object has the methods:
// - getConverter() returns the markdown converter object that was passed to the constructor
// - run() actually starts the editor; should be called after all necessary plugins are registered. Calling this more than once is a no-op.
// - refreshPreview() forces the preview to be updated. This method is only available after run() was called.
Markdown.Editor = function (markdownConverter, idPostfix, help) {
idPostfix = idPostfix || "";
var hooks = this.hooks = new Markdown.HookCollection();
hooks.addNoop("onPreviewRefresh"); // called with no arguments after the preview has been refreshed
hooks.addNoop("<API key>"); // called with the user's selection *after* the blockquote was created; should return the actual to-be-inserted text
hooks.addFalse("insertImageDialog"); /* called with one parameter: a callback to be called with the URL of the image. If the application creates
* its own image insertion dialog, this hook should return true, and the callback should be called with the chosen
* image url (or null if the user cancelled). If this hook returns false, the default dialog will be used.
*/
this.getConverter = function () { return markdownConverter; }
var that = this,
panels;
this.run = function () {
if (panels)
return; // already initialized
panels = new PanelCollection(idPostfix);
var commandManager = new CommandManager(hooks);
var previewManager = new PreviewManager(markdownConverter, panels, function () { hooks.onPreviewRefresh(); });
var undoManager, uiManager;
if (!/\?noundo/.test(doc.location.href)) {
undoManager = new UndoManager(function () {
previewManager.refresh();
if (uiManager) // not available on the first call
uiManager.<API key>();
}, panels);
this.textOperation = function (f) {
undoManager.setCommandMode();
f();
that.refreshPreview();
}
}
uiManager = new UIManager(idPostfix, panels, undoManager, previewManager, commandManager, help);
uiManager.<API key>();
var forceRefresh = that.refreshPreview = function () { previewManager.refresh(true); };
forceRefresh();
};
}
// before: contains all the text in the input box BEFORE the selection.
// after: contains all the text in the input box AFTER the selection.
function Chunks() { }
// startRegex: a regular expression to find the start tag
// endRegex: a regular expresssion to find the end tag
Chunks.prototype.findTags = function (startRegex, endRegex) {
var chunkObj = this;
var regex;
if (startRegex) {
regex = util.extendRegExp(startRegex, "", "$");
this.before = this.before.replace(regex,
function (match) {
chunkObj.startTag = chunkObj.startTag + match;
return "";
});
regex = util.extendRegExp(startRegex, "^", "");
this.selection = this.selection.replace(regex,
function (match) {
chunkObj.startTag = chunkObj.startTag + match;
return "";
});
}
if (endRegex) {
regex = util.extendRegExp(endRegex, "", "$");
this.selection = this.selection.replace(regex,
function (match) {
chunkObj.endTag = match + chunkObj.endTag;
return "";
});
regex = util.extendRegExp(endRegex, "^", "");
this.after = this.after.replace(regex,
function (match) {
chunkObj.endTag = match + chunkObj.endTag;
return "";
});
}
};
// If remove is false, the whitespace is transferred
// to the before/after regions.
// If remove is true, the whitespace disappears.
Chunks.prototype.trimWhitespace = function (remove) {
var beforeReplacer, afterReplacer, that = this;
if (remove) {
beforeReplacer = afterReplacer = "";
} else {
beforeReplacer = function (s) { that.before += s; return ""; }
afterReplacer = function (s) { that.after = s + that.after; return ""; }
}
this.selection = this.selection.replace(/^(\s*)/, beforeReplacer).replace(/(\s*)$/, afterReplacer);
};
Chunks.prototype.skipLines = function (nLinesBefore, nLinesAfter, findExtraNewlines) {
if (nLinesBefore === undefined) {
nLinesBefore = 1;
}
if (nLinesAfter === undefined) {
nLinesAfter = 1;
}
nLinesBefore++;
nLinesAfter++;
var regexText;
var replacementText;
// chrome bug ... documented at: http://meta.stackoverflow.com/questions/63307/<API key>/65985#65985
if (navigator.userAgent.match(/Chrome/)) {
"X".match(/()./);
}
this.selection = this.selection.replace(/(^\n*)/, "");
this.startTag = this.startTag + re.$1;
this.selection = this.selection.replace(/(\n*$)/, "");
this.endTag = this.endTag + re.$1;
this.startTag = this.startTag.replace(/(^\n*)/, "");
this.before = this.before + re.$1;
this.endTag = this.endTag.replace(/(\n*$)/, "");
this.after = this.after + re.$1;
if (this.before) {
regexText = replacementText = "";
while (nLinesBefore
regexText += "\\n?";
replacementText += "\n";
}
if (findExtraNewlines) {
regexText = "\\n*";
}
this.before = this.before.replace(new re(regexText + "$", ""), replacementText);
}
if (this.after) {
regexText = replacementText = "";
while (nLinesAfter
regexText += "\\n?";
replacementText += "\n";
}
if (findExtraNewlines) {
regexText = "\\n*";
}
this.after = this.after.replace(new re(regexText, ""), replacementText);
}
};
// end of Chunks
// A collection of the important regions on the page.
// Cached so we don't have to keep traversing the DOM.
// Also holds ieCachedRange and ieCachedScrollTop, where necessary; working around
// this issue:
// Internet explorer has problems with CSS sprite buttons that use HTML
// lists. When you click on the background image "button", IE will
// select the non-existent link text and discard the selection in the
// textarea. The solution to this is to cache the textarea selection
// on the button's mousedown event and set a flag. In the part of the
// code where we need to grab the selection, we check for the flag
// and, if it's set, use the cached area instead of querying the
// textarea.
// This ONLY affects Internet Explorer (tested on versions 6, 7
// and 8) and ONLY on button clicks. Keyboard shortcuts work
// normally since the focus never leaves the textarea.
function PanelCollection(postfix) {
this.buttonBar = doc.getElementById("wmd-button-bar" + postfix);
this.preview = doc.getElementById("wmd-preview" + postfix);
this.input = doc.getElementById("wmd-input" + postfix);
};
// Returns true if the DOM element is visible, false if it's hidden.
// Checks if display is anything other than none.
util.isVisible = function (elem) {
if (window.getComputedStyle) {
// Most browsers
return window.getComputedStyle(elem, null).getPropertyValue("display") !== "none";
}
else if (elem.currentStyle) {
return elem.currentStyle["display"] !== "none";
}
};
// Adds a listener callback to a DOM element which is fired on a specified
// event.
util.addEvent = function (elem, event, listener) {
if (elem.attachEvent) {
// IE only. The "on" is mandatory.
elem.attachEvent("on" + event, listener);
}
else {
// Other browsers.
elem.addEventListener(event, listener, false);
}
};
// Removes a listener callback from a DOM element which is fired on a specified
// event.
util.removeEvent = function (elem, event, listener) {
if (elem.detachEvent) {
// IE only. The "on" is mandatory.
elem.detachEvent("on" + event, listener);
}
else {
// Other browsers.
elem.removeEventListener(event, listener, false);
}
};
// Converts \r\n and \r to \n.
util.fixEolChars = function (text) {
text = text.replace(/\r\n/g, "\n");
text = text.replace(/\r/g, "\n");
return text;
};
// Extends a regular expression. Returns a new RegExp
// using pre + regex + post as the expression.
// Used in a few functions where we have a base
// expression and we want to pre- or append some
// conditions to it (e.g. adding "$" to the end).
// The flags are unchanged.
// regex is a RegExp, pre and post are strings.
util.extendRegExp = function (regex, pre, post) {
if (pre === null || pre === undefined) {
pre = "";
}
if (post === null || post === undefined) {
post = "";
}
var pattern = regex.toString();
var flags;
// Replace the flags with empty space and store them.
pattern = pattern.replace(/\/([gim]*)$/, function (wholeMatch, flagsPart) {
flags = flagsPart;
return "";
});
// Remove the slash delimiters on the regular expression.
pattern = pattern.replace(/(^\/|\/$)/g, "");
pattern = pre + pattern + post;
return new re(pattern, flags);
}
// UNFINISHED
// The assignment in the while loop makes jslint cranky.
// I'll change it to a better loop later.
position.getTop = function (elem, isInner) {
var result = elem.offsetTop;
if (!isInner) {
while (elem = elem.offsetParent) {
result += elem.offsetTop;
}
}
return result;
};
position.getHeight = function (elem) {
return elem.offsetHeight || elem.scrollHeight;
};
position.getWidth = function (elem) {
return elem.offsetWidth || elem.scrollWidth;
};
position.getPageSize = function () {
var scrollWidth, scrollHeight;
var innerWidth, innerHeight;
// It's not very clear which blocks work with which browsers.
if (self.innerHeight && self.scrollMaxY) {
scrollWidth = doc.body.scrollWidth;
scrollHeight = self.innerHeight + self.scrollMaxY;
}
else if (doc.body.scrollHeight > doc.body.offsetHeight) {
scrollWidth = doc.body.scrollWidth;
scrollHeight = doc.body.scrollHeight;
}
else {
scrollWidth = doc.body.offsetWidth;
scrollHeight = doc.body.offsetHeight;
}
if (self.innerHeight) {
// Non-IE browser
innerWidth = self.innerWidth;
innerHeight = self.innerHeight;
}
else if (doc.documentElement && doc.documentElement.clientHeight) {
// Some versions of IE (IE 6 w/ a DOCTYPE declaration)
innerWidth = doc.documentElement.clientWidth;
innerHeight = doc.documentElement.clientHeight;
}
else if (doc.body) {
// Other versions of IE
innerWidth = doc.body.clientWidth;
innerHeight = doc.body.clientHeight;
}
var maxWidth = Math.max(scrollWidth, innerWidth);
var maxHeight = Math.max(scrollHeight, innerHeight);
return [maxWidth, maxHeight, innerWidth, innerHeight];
};
// Handles pushing and popping TextareaStates for undo/redo commands.
// I should rename the stack variables to list.
function UndoManager(callback, panels) {
var undoObj = this;
var undoStack = []; // A stack of undo states
var stackPtr = 0; // The index of the current state
var mode = "none";
var lastState; // The last state
var timer; // The setTimeout handle for cancelling the timer
var inputStateObj;
// Set the mode for later logic steps.
var setMode = function (newMode, noSave) {
if (mode != newMode) {
mode = newMode;
if (!noSave) {
saveState();
}
}
if (!uaSniffed.isIE || mode != "moving") {
timer = setTimeout(refreshState, 1);
}
else {
inputStateObj = null;
}
};
var refreshState = function (isInitialState) {
inputStateObj = new TextareaState(panels, isInitialState);
timer = undefined;
};
this.setCommandMode = function () {
mode = "command";
saveState();
timer = setTimeout(refreshState, 0);
};
this.canUndo = function () {
return stackPtr > 1;
};
this.canRedo = function () {
if (undoStack[stackPtr + 1]) {
return true;
}
return false;
};
// Removes the last state and restores it.
this.undo = function () {
if (undoObj.canUndo()) {
if (lastState) {
// What about setting state -1 to null or checking for undefined?
lastState.restore();
lastState = null;
}
else {
undoStack[stackPtr] = new TextareaState(panels);
undoStack[--stackPtr].restore();
if (callback) {
callback();
}
}
}
mode = "none";
panels.input.focus();
refreshState();
};
// Redo an action.
this.redo = function () {
if (undoObj.canRedo()) {
undoStack[++stackPtr].restore();
if (callback) {
callback();
}
}
mode = "none";
panels.input.focus();
refreshState();
};
// Push the input area state to the stack.
var saveState = function () {
var currState = inputStateObj || new TextareaState(panels);
if (!currState) {
return false;
}
if (mode == "moving") {
if (!lastState) {
lastState = currState;
}
return;
}
if (lastState) {
if (undoStack[stackPtr - 1].text != lastState.text) {
undoStack[stackPtr++] = lastState;
}
lastState = null;
}
undoStack[stackPtr++] = currState;
undoStack[stackPtr + 1] = null;
if (callback) {
callback();
}
};
var handleCtrlYZ = function (event) {
var handled = false;
if (event.ctrlKey || event.metaKey) {
// IE and Opera do not support charCode.
var keyCode = event.charCode || event.keyCode;
var keyCodeChar = String.fromCharCode(keyCode);
switch (keyCodeChar) {
case "y":
undoObj.redo();
handled = true;
break;
case "z":
if (!event.shiftKey) {
undoObj.undo();
}
else {
undoObj.redo();
}
handled = true;
break;
}
}
if (handled) {
if (event.preventDefault) {
event.preventDefault();
}
if (window.event) {
window.event.returnValue = false;
}
return;
}
};
// Set the mode depending on what is going on in the input area.
var handleModeChange = function (event) {
if (!event.ctrlKey && !event.metaKey) {
var keyCode = event.keyCode;
if ((keyCode >= 33 && keyCode <= 40) || (keyCode >= 63232 && keyCode <= 63235)) {
// 33 - 40: page up/dn and arrow keys
// 63232 - 63235: page up/dn and arrow keys on safari
setMode("moving");
}
else if (keyCode == 8 || keyCode == 46 || keyCode == 127) {
// 8: backspace
// 46: delete
// 127: delete
setMode("deleting");
}
else if (keyCode == 13) {
// 13: Enter
setMode("newlines");
}
else if (keyCode == 27) {
// 27: escape
setMode("escape");
}
else if ((keyCode < 16 || keyCode > 20) && keyCode != 91) {
// 16-20 are shift, etc.
// 91: left window key
// I think this might be a little messed up since there are
// a lot of nonprinting keys above 20.
setMode("typing");
}
}
};
var setEventHandlers = function () {
util.addEvent(panels.input, "keypress", function (event) {
// keyCode 89: y
// keyCode 90: z
if ((event.ctrlKey || event.metaKey) && (event.keyCode == 89 || event.keyCode == 90)) {
event.preventDefault();
}
});
var handlePaste = function () {
if (uaSniffed.isIE || (inputStateObj && inputStateObj.text != panels.input.value)) {
if (timer == undefined) {
mode = "paste";
saveState();
refreshState();
}
}
};
util.addEvent(panels.input, "keydown", handleCtrlYZ);
util.addEvent(panels.input, "keydown", handleModeChange);
util.addEvent(panels.input, "mousedown", function () {
setMode("moving");
});
panels.input.onpaste = handlePaste;
panels.input.ondrop = handlePaste;
};
var init = function () {
setEventHandlers();
refreshState(true);
saveState();
};
init();
}
// end of UndoManager
// The input textarea state/contents.
// This is used to implement undo/redo by the undo manager.
function TextareaState(panels, isInitialState) {
// Aliases
var stateObj = this;
var inputArea = panels.input;
this.init = function () {
if (!util.isVisible(inputArea)) {
return;
}
if (!isInitialState && doc.activeElement && doc.activeElement !== inputArea) { // this happens when tabbing out of the input box
return;
}
this.<API key>();
this.scrollTop = inputArea.scrollTop;
if (!this.text && inputArea.selectionStart || inputArea.selectionStart === 0) {
this.text = inputArea.value;
}
}
// Sets the selected text in the input box after we've performed an
// operation.
this.<API key> = function () {
if (!util.isVisible(inputArea)) {
return;
}
if (inputArea.selectionStart !== undefined && !uaSniffed.isOpera) {
inputArea.focus();
inputArea.selectionStart = stateObj.start;
inputArea.selectionEnd = stateObj.end;
inputArea.scrollTop = stateObj.scrollTop;
}
else if (doc.selection) {
if (doc.activeElement && doc.activeElement !== inputArea) {
return;
}
inputArea.focus();
var range = inputArea.createTextRange();
range.moveStart("character", -inputArea.value.length);
range.moveEnd("character", -inputArea.value.length);
range.moveEnd("character", stateObj.end);
range.moveStart("character", stateObj.start);
range.select();
}
};
this.<API key> = function () {
if (!panels.ieCachedRange && (inputArea.selectionStart || inputArea.selectionStart === 0)) {
stateObj.start = inputArea.selectionStart;
stateObj.end = inputArea.selectionEnd;
}
else if (doc.selection) {
stateObj.text = util.fixEolChars(inputArea.value);
// IE loses the selection in the textarea when buttons are
// clicked. On IE we cache the selection. Here, if something is cached,
// we take it.
var range = panels.ieCachedRange || doc.selection.createRange();
var fixedRange = util.fixEolChars(range.text);
var marker = "\x07";
var markedRange = marker + fixedRange + marker;
range.text = markedRange;
var inputText = util.fixEolChars(inputArea.value);
range.moveStart("character", -markedRange.length);
range.text = fixedRange;
stateObj.start = inputText.indexOf(marker);
stateObj.end = inputText.lastIndexOf(marker) - marker.length;
var len = stateObj.text.length - util.fixEolChars(inputArea.value).length;
if (len) {
range.moveStart("character", -fixedRange.length);
while (len
fixedRange += "\n";
stateObj.end += 1;
}
range.text = fixedRange;
}
if (panels.ieCachedRange)
stateObj.scrollTop = panels.ieCachedScrollTop; // this is set alongside with ieCachedRange
panels.ieCachedRange = null;
this.<API key>();
}
};
// Restore this state into the input area.
this.restore = function () {
if (stateObj.text != undefined && stateObj.text != inputArea.value) {
inputArea.value = stateObj.text;
}
this.<API key>();
inputArea.scrollTop = stateObj.scrollTop;
};
// Gets a collection of HTML chunks from the inptut textarea.
this.getChunks = function () {
var chunk = new Chunks();
chunk.before = util.fixEolChars(stateObj.text.substring(0, stateObj.start));
chunk.startTag = "";
chunk.selection = util.fixEolChars(stateObj.text.substring(stateObj.start, stateObj.end));
chunk.endTag = "";
chunk.after = util.fixEolChars(stateObj.text.substring(stateObj.end));
chunk.scrollTop = stateObj.scrollTop;
return chunk;
};
// Sets the TextareaState properties given a chunk of markdown.
this.setChunks = function (chunk) {
chunk.before = chunk.before + chunk.startTag;
chunk.after = chunk.endTag + chunk.after;
this.start = chunk.before.length;
this.end = chunk.before.length + chunk.selection.length;
this.text = chunk.before + chunk.selection + chunk.after;
this.scrollTop = chunk.scrollTop;
};
this.init();
};
function PreviewManager(converter, panels, <API key>) {
var managerObj = this;
var timeout;
var elapsedTime;
var oldInputText;
var maxDelay = 3000;
var startType = "delayed";
// Adds event listeners to elements
var setupEvents = function (inputElem, listener) {
util.addEvent(inputElem, "input", listener);
inputElem.onpaste = listener;
inputElem.ondrop = listener;
util.addEvent(inputElem, "keypress", listener);
util.addEvent(inputElem, "keydown", listener);
};
var getDocScrollTop = function () {
var result = 0;
if (window.innerHeight) {
result = window.pageYOffset;
}
else
if (doc.documentElement && doc.documentElement.scrollTop) {
result = doc.documentElement.scrollTop;
}
else
if (doc.body) {
result = doc.body.scrollTop;
}
return result;
};
var makePreviewHtml = function () {
// If there is no registered preview panel
// there is nothing to do.
if (!panels.preview)
return;
var text = panels.input.value;
if (text && text == oldInputText) {
return; // Input text hasn't changed.
}
else {
oldInputText = text;
}
var prevTime = new Date().getTime();
text = converter.makeHtml(text);
// Calculate the processing time of the HTML creation.
// It's used as the delay time in the event listener.
var currTime = new Date().getTime();
elapsedTime = currTime - prevTime;
pushPreviewHtml(text);
};
// setTimeout is already used. Used as an event listener.
var applyTimeout = function () {
if (timeout) {
clearTimeout(timeout);
timeout = undefined;
}
if (startType !== "manual") {
var delay = 0;
if (startType === "delayed") {
delay = elapsedTime;
}
if (delay > maxDelay) {
delay = maxDelay;
}
timeout = setTimeout(makePreviewHtml, delay);
}
};
var getScaleFactor = function (panel) {
if (panel.scrollHeight <= panel.clientHeight) {
return 1;
}
return panel.scrollTop / (panel.scrollHeight - panel.clientHeight);
};
var setPanelScrollTops = function () {
if (panels.preview) {
panels.preview.scrollTop = (panels.preview.scrollHeight - panels.preview.clientHeight) * getScaleFactor(panels.preview);
}
};
this.refresh = function (requiresRefresh) {
if (requiresRefresh) {
oldInputText = "";
makePreviewHtml();
}
else {
applyTimeout();
}
};
this.processingTime = function () {
return elapsedTime;
};
var isFirstTimeFilled = true;
// IE doesn't let you use innerHTML if the element is contained somewhere in a table
// (which is the case for inline editing) -- in that case, detach the element, set the
// value, and reattach. Yes, that *is* ridiculous.
var ieSafePreviewSet = function (text) {
var preview = panels.preview;
var parent = preview.parentNode;
var sibling = preview.nextSibling;
parent.removeChild(preview);
preview.innerHTML = text;
if (!sibling)
parent.appendChild(preview);
else
parent.insertBefore(preview, sibling);
}
var <API key> = function (text) {
panels.preview.innerHTML = text;
}
var previewSetter;
var previewSet = function (text) {
if (previewSetter)
return previewSetter(text);
try {
<API key>(text);
previewSetter = <API key>;
} catch (e) {
previewSetter = ieSafePreviewSet;
previewSetter(text);
}
};
var pushPreviewHtml = function (text) {
var emptyTop = position.getTop(panels.input) - getDocScrollTop();
if (panels.preview) {
previewSet(text);
<API key>();
}
setPanelScrollTops();
if (isFirstTimeFilled) {
isFirstTimeFilled = false;
return;
}
var fullTop = position.getTop(panels.input) - getDocScrollTop();
if (uaSniffed.isIE) {
setTimeout(function () {
window.scrollBy(0, fullTop - emptyTop);
}, 0);
}
else {
window.scrollBy(0, fullTop - emptyTop);
}
};
var init = function () {
setupEvents(panels.input, applyTimeout);
makePreviewHtml();
if (panels.preview) {
panels.preview.scrollTop = 0;
}
};
init();
};
// Creates the background behind the hyperlink text entry box.
// And download dialog
// Most of this has been moved to CSS but the div creation and
// browser-specific hacks remain here.
ui.createBackground = function () {
var background = doc.createElement("div"),
style = background.style;
background.className = "<API key>";
style.position = "absolute";
style.top = "0";
style.zIndex = "1000";
if (uaSniffed.isIE) {
style.filter = "alpha(opacity=50)";
}
else {
style.opacity = "0.5";
}
var pageSize = position.getPageSize();
style.height = pageSize[1] + "px";
if (uaSniffed.isIE) {
style.left = doc.documentElement.scrollLeft;
style.width = doc.documentElement.clientWidth;
}
else {
style.left = "0";
style.width = "100%";
}
doc.body.appendChild(background);
return background;
};
// This simulates a modal dialog box and asks for the URL when you
// click the hyperlink or image buttons.
// text: The html for the input box.
// defaultInputText: The default value that appears in the input box.
// callback: The function which is executed when the prompt is dismissed, either via OK or Cancel.
// It receives a single argument; either the entered text (if OK was chosen) or null (if Cancel
// was chosen).
ui.prompt = function (text, defaultInputText, callback) {
// These variables need to be declared at this level since they are used
// in multiple functions.
var dialog; // The dialog box.
var input; // The text box where you enter the hyperlink.
if (defaultInputText === undefined) {
defaultInputText = "";
}
// Used as a keydown event handler. Esc dismisses the prompt.
// Key code 27 is ESC.
var checkEscape = function (key) {
var code = (key.charCode || key.keyCode);
if (code === 27) {
close(true);
}
};
// Dismisses the hyperlink input box.
// isCancel is true if we don't care about the input text.
// isCancel is false if we are going to keep the text.
var close = function (isCancel) {
util.removeEvent(doc.body, "keydown", checkEscape);
var text = input.value;
if (isCancel) {
text = null;
}
else {
// Fixes common pasting errors.
text = text.replace(/^http:\/\/(https?|ftp):\/\
if (!/^(?:https?|ftp):\/\//.test(text))
text = 'http://' + text;
}
dialog.parentNode.removeChild(dialog);
callback(text);
return false;
};
// Create the text input box form/window.
var createDialog = function () {
// The main dialog box.
dialog = doc.createElement("div");
dialog.className = "wmd-prompt-dialog";
dialog.style.padding = "10px;";
dialog.style.position = "fixed";
dialog.style.width = "400px";
dialog.style.zIndex = "1001";
// The dialog text.
var question = doc.createElement("div");
question.innerHTML = text;
question.style.padding = "5px";
dialog.appendChild(question);
// The web form container for the text box and buttons.
var form = doc.createElement("form"),
style = form.style;
form.onsubmit = function () { return close(false); };
style.padding = "0";
style.margin = "0";
style.cssFloat = "left";
style.width = "100%";
style.textAlign = "center";
style.position = "relative";
dialog.appendChild(form);
// The input text box
input = doc.createElement("input");
input.type = "text";
input.value = defaultInputText;
style = input.style;
style.display = "block";
style.width = "80%";
style.marginLeft = style.marginRight = "auto";
form.appendChild(input);
// The ok button
var okButton = doc.createElement("input");
okButton.type = "button";
okButton.onclick = function () { return close(false); };
okButton.value = "OK";
style = okButton.style;
style.margin = "10px";
style.display = "inline";
style.width = "7em";
// The cancel button
var cancelButton = doc.createElement("input");
cancelButton.type = "button";
cancelButton.onclick = function () { return close(true); };
cancelButton.value = "Cancel";
style = cancelButton.style;
style.margin = "10px";
style.display = "inline";
style.width = "7em";
form.appendChild(okButton);
form.appendChild(cancelButton);
util.addEvent(doc.body, "keydown", checkEscape);
dialog.style.top = "50%";
dialog.style.left = "50%";
dialog.style.display = "block";
if (uaSniffed.isIE_5or6) {
dialog.style.position = "absolute";
dialog.style.top = doc.documentElement.scrollTop + 200 + "px";
dialog.style.left = "50%";
}
doc.body.appendChild(dialog);
// This has to be done AFTER adding the dialog to the form if you
// want it to be centered.
dialog.style.marginTop = -(position.getHeight(dialog) / 2) + "px";
dialog.style.marginLeft = -(position.getWidth(dialog) / 2) + "px";
};
// Why is this in a zero-length timeout?
// Is it working around a browser bug?
setTimeout(function () {
createDialog();
var defTextLen = defaultInputText.length;
if (input.selectionStart !== undefined) {
input.selectionStart = 0;
input.selectionEnd = defTextLen;
}
else if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(false);
range.moveStart("character", -defTextLen);
range.moveEnd("character", defTextLen);
range.select();
}
input.focus();
}, 0);
};
function UIManager(postfix, panels, undoManager, previewManager, commandManager, helpOptions) {
var inputBox = panels.input,
buttons = {}; // buttons.undo, buttons.link, etc. The actual DOM elements.
<API key>();
var keyEvent = "keydown";
if (uaSniffed.isOpera) {
keyEvent = "keypress";
}
util.addEvent(inputBox, keyEvent, function (key) {
// Check to see if we have a button key and, if so execute the callback.
if ((key.ctrlKey || key.metaKey) && !key.altKey && !key.shiftKey) {
var keyCode = key.charCode || key.keyCode;
var keyCodeStr = String.fromCharCode(keyCode).toLowerCase();
switch (keyCodeStr) {
case "b":
doClick(buttons.bold);
break;
case "i":
doClick(buttons.italic);
break;
case "l":
doClick(buttons.link);
break;
case "q":
doClick(buttons.quote);
break;
case "k":
doClick(buttons.code);
break;
case "g":
doClick(buttons.image);
break;
case "o":
doClick(buttons.olist);
break;
case "u":
doClick(buttons.ulist);
break;
case "h":
doClick(buttons.heading);
break;
case "r":
doClick(buttons.hr);
break;
case "y":
doClick(buttons.redo);
break;
case "z":
if (key.shiftKey) {
doClick(buttons.redo);
}
else {
doClick(buttons.undo);
}
break;
default:
return;
}
if (key.preventDefault) {
key.preventDefault();
}
if (window.event) {
window.event.returnValue = false;
}
}
});
// Auto-indent on shift-enter
util.addEvent(inputBox, "keyup", function (key) {
if (key.shiftKey && !key.ctrlKey && !key.metaKey) {
var keyCode = key.charCode || key.keyCode;
// Character 13 is Enter
if (keyCode === 13) {
var fakeButton = {};
fakeButton.textOp = bindCommand("doAutoindent");
doClick(fakeButton);
}
}
});
// special handler because IE clears the context of the textbox on ESC
if (uaSniffed.isIE) {
util.addEvent(inputBox, "keydown", function (key) {
var code = key.keyCode;
if (code === 27) {
return false;
}
});
}
// Perform the button's action.
function doClick(button) {
inputBox.focus();
if (button.textOp) {
if (undoManager) {
undoManager.setCommandMode();
}
var state = new TextareaState(panels);
if (!state) {
return;
}
var chunks = state.getChunks();
// Some commands launch a "modal" prompt dialog. Javascript
// can't really make a modal dialog box and the WMD code
// will continue to execute while the dialog is displayed.
// This prevents the dialog pattern I'm used to and means
// I can't do something like this:
// var link = CreateLinkDialog();
// makeMarkdownLink(link);
// Instead of this straightforward method of handling a
// dialog I have to pass any code which would execute
// after the dialog is dismissed (e.g. link creation)
// in a function parameter.
// Yes this is awkward and I think it sucks, but there's
// no real workaround. Only the image and link code
// create dialogs and require the function pointers.
var fixupInputArea = function () {
inputBox.focus();
if (chunks) {
state.setChunks(chunks);
}
state.restore();
previewManager.refresh();
};
var noCleanup = button.textOp(chunks, fixupInputArea);
if (!noCleanup) {
fixupInputArea();
}
}
if (button.execute) {
button.execute(undoManager);
}
};
function setupButton(button, isEnabled) {
var normalYShift = "0px";
var disabledYShift = "-20px";
var highlightYShift = "-40px";
var image = button.<API key>("span")[0];
if (isEnabled) {
image.style.backgroundPosition = button.XShift + " " + normalYShift;
button.onmouseover = function () {
image.style.backgroundPosition = this.XShift + " " + highlightYShift;
};
button.onmouseout = function () {
image.style.backgroundPosition = this.XShift + " " + normalYShift;
};
// IE tries to select the background image "button" text (it's
// implemented in a list item) so we have to cache the selection
// on mousedown.
if (uaSniffed.isIE) {
button.onmousedown = function () {
if (doc.activeElement && doc.activeElement !== panels.input) { // we're not even in the input box, so there's no selection
return;
}
panels.ieCachedRange = document.selection.createRange();
panels.ieCachedScrollTop = panels.input.scrollTop;
};
}
if (!button.isHelp) {
button.onclick = function () {
if (this.onmouseout) {
this.onmouseout();
}
doClick(this);
return false;
}
}
}
else {
image.style.backgroundPosition = button.XShift + " " + disabledYShift;
button.onmouseover = button.onmouseout = button.onclick = function () { };
}
}
function bindCommand(method) {
if (typeof method === "string")
method = commandManager[method];
return function () { method.apply(commandManager, arguments); }
}
function <API key>() {
var buttonBar = panels.buttonBar;
var normalYShift = "0px";
var disabledYShift = "-20px";
var highlightYShift = "-40px";
var buttonRow = document.createElement("ul");
buttonRow.id = "wmd-button-row" + postfix;
buttonRow.className = 'wmd-button-row';
buttonRow = buttonBar.appendChild(buttonRow);
var xPosition = 0;
var makeButton = function (id, title, XShift, textOp) {
var button = document.createElement("li");
button.className = "wmd-button";
button.style.left = xPosition + "px";
xPosition += 25;
var buttonImage = document.createElement("span");
button.id = id + postfix;
button.appendChild(buttonImage);
button.title = title;
button.XShift = XShift;
if (textOp)
button.textOp = textOp;
setupButton(button, true);
buttonRow.appendChild(button);
return button;
};
var makeSpacer = function (num) {
var spacer = document.createElement("li");
spacer.className = "wmd-spacer wmd-spacer" + num;
spacer.id = "wmd-spacer" + num + postfix;
buttonRow.appendChild(spacer);
xPosition += 25;
}
buttons.bold = makeButton("wmd-bold-button", "Strong <strong> Ctrl+B", "0px", bindCommand("doBold"));
buttons.italic = makeButton("wmd-italic-button", "Emphasis <em> Ctrl+I", "-20px", bindCommand("doItalic"));
makeSpacer(1);
buttons.link = makeButton("wmd-link-button", "Hyperlink <a> Ctrl+L", "-40px", bindCommand(function (chunk, postProcessing) {
return this.doLinkOrImage(chunk, postProcessing, false);
}));
buttons.quote = makeButton("wmd-quote-button", "Blockquote <blockquote> Ctrl+Q", "-60px", bindCommand("doBlockquote"));
buttons.code = makeButton("wmd-code-button", "Code Sample <pre><code> Ctrl+K", "-80px", bindCommand("doCode"));
buttons.image = makeButton("wmd-image-button", "Image <img> Ctrl+G", "-100px", bindCommand(function (chunk, postProcessing) {
return this.doLinkOrImage(chunk, postProcessing, true);
}));
makeSpacer(2);
buttons.olist = makeButton("wmd-olist-button", "Numbered List <ol> Ctrl+O", "-120px", bindCommand(function (chunk, postProcessing) {
this.doList(chunk, postProcessing, true);
}));
buttons.ulist = makeButton("wmd-ulist-button", "Bulleted List <ul> Ctrl+U", "-140px", bindCommand(function (chunk, postProcessing) {
this.doList(chunk, postProcessing, false);
}));
buttons.heading = makeButton("wmd-heading-button", "Heading <h1>/<h2> Ctrl+H", "-160px", bindCommand("doHeading"));
buttons.hr = makeButton("wmd-hr-button", "Horizontal Rule <hr> Ctrl+R", "-180px", bindCommand("doHorizontalRule"));
makeSpacer(3);
buttons.undo = makeButton("wmd-undo-button", "Undo - Ctrl+Z", "-200px", null);
buttons.undo.execute = function (manager) { if (manager) manager.undo(); };
var redoTitle = /win/.test(nav.platform.toLowerCase()) ?
"Redo - Ctrl+Y" :
"Redo - Ctrl+Shift+Z"; // mac and other non-Windows platforms
buttons.redo = makeButton("wmd-redo-button", redoTitle, "-220px", null);
buttons.redo.execute = function (manager) { if (manager) manager.redo(); };
if (helpOptions) {
var helpButton = document.createElement("li");
var helpButtonImage = document.createElement("span");
helpButton.appendChild(helpButtonImage);
helpButton.className = "wmd-button wmd-help-button";
helpButton.id = "wmd-help-button" + postfix;
helpButton.XShift = "-240px";
helpButton.isHelp = true;
helpButton.style.right = "0px";
helpButton.title = helpOptions.title || <API key>;
helpButton.onclick = helpOptions.handler;
setupButton(helpButton, true);
buttonRow.appendChild(helpButton);
buttons.help = helpButton;
}
<API key>();
}
function <API key>() {
if (undoManager) {
setupButton(buttons.undo, undoManager.canUndo());
setupButton(buttons.redo, undoManager.canRedo());
}
};
this.<API key> = <API key>;
}
function CommandManager(pluginHooks) {
this.hooks = pluginHooks;
}
var commandProto = CommandManager.prototype;
// The markdown symbols - 4 spaces = code, > = blockquote, etc.
commandProto.prefixes = "(?:\\s{4,}|\\s*>|\\s*-\\s+|\\s*\\d+\\.|=|\\+|-|_|\\*|
// Remove markdown symbols from the chunk selection.
commandProto.unwrap = function (chunk) {
var txt = new re("([^\\n])\\n(?!(\\n|" + this.prefixes + "))", "g");
chunk.selection = chunk.selection.replace(txt, "$1 $2");
};
commandProto.wrap = function (chunk, len) {
this.unwrap(chunk);
var regex = new re("(.{1," + len + "})( +|$\\n?)", "gm"),
that = this;
chunk.selection = chunk.selection.replace(regex, function (line, marked) {
if (new re("^" + that.prefixes, "").test(line)) {
return line;
}
return marked + "\n";
});
chunk.selection = chunk.selection.replace(/\s+$/, "");
};
commandProto.doBold = function (chunk, postProcessing) {
return this.doBorI(chunk, postProcessing, 2, "strong text");
};
commandProto.doItalic = function (chunk, postProcessing) {
return this.doBorI(chunk, postProcessing, 1, "emphasized text");
};
// chunk: The selected region that will be enclosed with */**
// nStars: 1 for italics, 2 for bold
// insertText: If you just click the button without highlighting text, this gets inserted
commandProto.doBorI = function (chunk, postProcessing, nStars, insertText) {
// Get rid of whitespace and fixup newlines.
chunk.trimWhitespace();
chunk.selection = chunk.selection.replace(/\n{2,}/g, "\n");
// Look for stars before and after. Is the chunk already marked up?
// note that these regex matches cannot fail
var starsBefore = /(\**$)/.exec(chunk.before)[0];
var starsAfter = /(^\**)/.exec(chunk.after)[0];
var prevStars = Math.min(starsBefore.length, starsAfter.length);
// Remove stars if we have to since the button acts as a toggle.
if ((prevStars >= nStars) && (prevStars != 2 || nStars != 1)) {
chunk.before = chunk.before.replace(re("[*]{" + nStars + "}$", ""), "");
chunk.after = chunk.after.replace(re("^[*]{" + nStars + "}", ""), "");
}
else if (!chunk.selection && starsAfter) {
// It's not really clear why this code is necessary. It just moves
// some arbitrary stuff around.
chunk.after = chunk.after.replace(/^([*_]*)/, "");
chunk.before = chunk.before.replace(/(\s?)$/, "");
var whitespace = re.$1;
chunk.before = chunk.before + starsAfter + whitespace;
}
else {
// In most cases, if you don't have any selected text and click the button
// you'll get a selected, marked up region with the default text inserted.
if (!chunk.selection && !starsAfter) {
chunk.selection = insertText;
}
// Add the true markup.
var markup = nStars <= 1 ? "*" : "**"; // shouldn't the test be = ?
chunk.before = chunk.before + markup;
chunk.after = markup + chunk.after;
}
return;
};
commandProto.stripLinkDefs = function (text, defsToAdd) {
text = text.replace(/^[ ]{0,3}\[(\d+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?[ \t]*\n?[ \t]*(?:(\n*)["(](.+?)[")][ \t]*)?(?:\n+|$)/gm,
function (totalMatch, id, link, newlines, title) {
defsToAdd[id] = totalMatch.replace(/\s*$/, "");
if (newlines) {
// Strip the title and return that separately.
defsToAdd[id] = totalMatch.replace(/["(](.+?)[")]$/, "");
return newlines + title;
}
return "";
});
return text;
};
commandProto.addLinkDef = function (chunk, linkDef) {
var refNumber = 0; // The current reference number
var defsToAdd = {};
// Start with a clean slate by removing all previous link definitions.
chunk.before = this.stripLinkDefs(chunk.before, defsToAdd);
chunk.selection = this.stripLinkDefs(chunk.selection, defsToAdd);
chunk.after = this.stripLinkDefs(chunk.after, defsToAdd);
var defs = "";
var regex = /(\[)((?:\[[^\]]*\]|[^\[\]])*)(\][ ]?(?:\n[ ]*)?\[)(\d+)(\])/g;
var addDefNumber = function (def) {
refNumber++;
def = def.replace(/^[ ]{0,3}\[(\d+)\]:/, " [" + refNumber + "]:");
defs += "\n" + def;
};
// note that
// a) the recursive call to getLink cannot go infinite, because by definition
// of regex, inner is always a proper substring of wholeMatch, and
// b) more than one level of nesting is neither supported by the regex
// nor making a lot of sense (the only use case for nesting is a linked image)
var getLink = function (wholeMatch, before, inner, afterInner, id, end) {
inner = inner.replace(regex, getLink);
if (defsToAdd[id]) {
addDefNumber(defsToAdd[id]);
return before + inner + afterInner + refNumber + end;
}
return wholeMatch;
};
chunk.before = chunk.before.replace(regex, getLink);
if (linkDef) {
addDefNumber(linkDef);
}
else {
chunk.selection = chunk.selection.replace(regex, getLink);
}
var refOut = refNumber;
chunk.after = chunk.after.replace(regex, getLink);
if (chunk.after) {
chunk.after = chunk.after.replace(/\n*$/, "");
}
if (!chunk.after) {
chunk.selection = chunk.selection.replace(/\n*$/, "");
}
chunk.after += "\n\n" + defs;
return refOut;
};
// takes the line as entered into the add link/as image dialog and makes
// sure the URL and the optinal title are "nice".
function properlyEncoded(linkdef) {
return linkdef.replace(/^\s*(.*?)(?:\s+"(.+)")?\s*$/, function (wholematch, link, title) {
link = link.replace(/\?.*$/, function (querypart) {
return querypart.replace(/\+/g, " "); // in the query string, a plus and a space are identical
});
link = decodeURIComponent(link); // unencode first, to prevent double encoding
link = encodeURI(link).replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29');
link = link.replace(/\?.*$/, function (querypart) {
return querypart.replace(/\+/g, "%2b"); // since we replaced plus with spaces in the query part, all pluses that now appear where originally encoded
});
if (title) {
title = title.trim ? title.trim() : title.replace(/^\s*/, "").replace(/\s*$/, "");
title = $.trim(title).replace(/"/g, "quot;").replace(/\(/g, "(").replace(/\)/g, ")").replace(/</g, "<").replace(/>/g, ">");
}
return title ? link + ' "' + title + '"' : link;
});
}
commandProto.doLinkOrImage = function (chunk, postProcessing, isImage) {
chunk.trimWhitespace();
chunk.findTags(/\s*!?\[/, /\][ ]?(?:\n[ ]*)?(\[.*?\])?/);
var background;
if (chunk.endTag.length > 1 && chunk.startTag.length > 0) {
chunk.startTag = chunk.startTag.replace(/!?\[/, "");
chunk.endTag = "";
this.addLinkDef(chunk, null);
}
else {
// We're moving start and end tag back into the selection, since (as we're in the else block) we're not
// *removing* a link, but *adding* one, so whatever findTags() found is now back to being part of the
// link text. linkEnteredCallback takes care of escaping any brackets.
chunk.selection = chunk.startTag + chunk.selection + chunk.endTag;
chunk.startTag = chunk.endTag = "";
if (/\n\n/.test(chunk.selection)) {
this.addLinkDef(chunk, null);
return;
}
var that = this;
// The function to be executed when you enter a link and press OK or Cancel.
// Marks up the link and adds the ref.
var linkEnteredCallback = function (link) {
background.parentNode.removeChild(background);
if (link !== null) {
// [^\\] anything that's not a backslash
// (?:\\\\)* an even number (this includes zero) of backslashes
// (?= followed by
// [[\]] an opening or closing bracket
// In other words, a non-escaped bracket. These have to be escaped now to make sure they
// don't count as the end of the link or similar.
// Note that the actual bracket has to be a lookahead, because (in case of to subsequent brackets),
// the bracket in one match may be the "not a backslash" character in the next match, so it
// should not be consumed by the first match.
// The "prepend a space and finally remove it" steps makes sure there is a "not a backslash" at the
// start of the string, so this also works if the selection begins with a bracket. We cannot solve
// this by anchoring with ^, because in the case that the selection starts with two brackets, this
// would mean a zero-width match at the start. Since zero-width matches advance the string position,
// the first bracket could then not act as the "not a backslash" for the second.
chunk.selection = (" " + chunk.selection).replace(/([^\\](?:\\\\)*)(?=[[\]])/g, "$1\\").substr(1);
var linkDef = " [999]: " + properlyEncoded(link);
var num = that.addLinkDef(chunk, linkDef);
chunk.startTag = isImage ? "![" : "[";
chunk.endTag = "][" + num + "]";
if (!chunk.selection) {
if (isImage) {
chunk.selection = "enter image description here";
}
else {
chunk.selection = "enter link description here";
}
}
}
postProcessing();
};
background = ui.createBackground();
if (isImage) {
if (!this.hooks.insertImageDialog(linkEnteredCallback))
ui.prompt(imageDialogText, imageDefaultText, linkEnteredCallback);
}
else {
ui.prompt(linkDialogText, linkDefaultText, linkEnteredCallback);
}
return true;
}
};
// When making a list, hitting shift-enter will put your cursor on the next line
// at the current indent level.
commandProto.doAutoindent = function (chunk, postProcessing) {
var commandMgr = this,
fakeSelection = false;
chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}([*+-]|\d+[.])[ \t]*\n$/, "\n\n");
chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}>[ \t]*\n$/, "\n\n");
chunk.before = chunk.before.replace(/(\n|^)[ \t]+\n$/, "\n\n");
// There's no selection, end the cursor wasn't at the end of the line:
// The user wants to split the current list item / code line / blockquote line
// (for the latter it doesn't really matter) in two. Temporarily select the
// (rest of the) line to achieve this.
if (!chunk.selection && !/^[ \t]*(?:\n|$)/.test(chunk.after)) {
chunk.after = chunk.after.replace(/^[^\n]*/, function (wholeMatch) {
chunk.selection = wholeMatch;
return "";
});
fakeSelection = true;
}
if (/(\n|^)[ ]{0,3}([*+-]|\d+[.])[ \t]+.*\n$/.test(chunk.before)) {
if (commandMgr.doList) {
commandMgr.doList(chunk);
}
}
if (/(\n|^)[ ]{0,3}>[ \t]+.*\n$/.test(chunk.before)) {
if (commandMgr.doBlockquote) {
commandMgr.doBlockquote(chunk);
}
}
if (/(\n|^)(\t|[ ]{4,}).*\n$/.test(chunk.before)) {
if (commandMgr.doCode) {
commandMgr.doCode(chunk);
}
}
if (fakeSelection) {
chunk.after = chunk.selection + chunk.after;
chunk.selection = "";
}
};
commandProto.doBlockquote = function (chunk, postProcessing) {
chunk.selection = chunk.selection.replace(/^(\n*)([^\r]+?)(\n*)$/,
function (totalMatch, newlinesBefore, text, newlinesAfter) {
chunk.before += newlinesBefore;
chunk.after = newlinesAfter + chunk.after;
return text;
});
chunk.before = chunk.before.replace(/(>[ \t]*)$/,
function (totalMatch, blankLine) {
chunk.selection = blankLine + chunk.selection;
return "";
});
chunk.selection = chunk.selection.replace(/^(\s|>)+$/, "");
chunk.selection = chunk.selection || "Blockquote";
// The original code uses a regular expression to find out how much of the
// text *directly before* the selection already was a blockquote:
/*
if (chunk.before) {
chunk.before = chunk.before.replace(/\n?$/, "\n");
}
chunk.before = chunk.before.replace(/(((\n|^)(\n[ \t]*)*>(.+\n)*.*)+(\n[ \t]*)*$)/,
function (totalMatch) {
chunk.startTag = totalMatch;
return "";
});
*/
// This comes down to:
// Go backwards as many lines a possible, such that each line
// a) starts with ">", or
// b) is almost empty, except for whitespace, or
// c) is preceeded by an unbroken chain of non-empty lines
// leading up to a line that starts with ">" and at least one more character
// and in addition
// d) at least one line fulfills a)
// Since this is essentially a backwards-moving regex, it's susceptible to
// catstrophic backtracking and can cause the browser to hang;
// Hence we replaced this by a simple state machine that just goes through the
// lines and checks for a), b), and c).
var match = "",
leftOver = "",
line;
if (chunk.before) {
var lines = chunk.before.replace(/\n$/, "").split("\n");
var inChain = false;
for (var i = 0; i < lines.length; i++) {
var good = false;
line = lines[i];
inChain = inChain && line.length > 0; // c) any non-empty line continues the chain
if (/^>/.test(line)) {
good = true;
if (!inChain && line.length > 1) // c) any line that starts with ">" and has at least one more character starts the chain
inChain = true;
} else if (/^[ \t]*$/.test(line)) {
good = true;
} else {
good = inChain; // c) the line is not empty and does not start with ">", so it matches if and only if we're in the chain
}
if (good) {
match += line + "\n";
} else {
leftOver += match + line;
match = "\n";
}
}
if (!/(^|\n)>/.test(match)) {
leftOver += match;
match = "";
}
}
chunk.startTag = match;
chunk.before = leftOver;
// end of change
if (chunk.after) {
chunk.after = chunk.after.replace(/^\n?/, "\n");
}
chunk.after = chunk.after.replace(/^(((\n|^)(\n[ \t]*)*>(.+\n)*.*)+(\n[ \t]*)*)/,
function (totalMatch) {
chunk.endTag = totalMatch;
return "";
}
);
var replaceBlanksInTags = function (useBracket) {
var replacement = useBracket ? "> " : "";
if (chunk.startTag) {
chunk.startTag = chunk.startTag.replace(/\n((>|\s)*)\n$/,
function (totalMatch, markdown) {
return "\n" + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + "\n";
});
}
if (chunk.endTag) {
chunk.endTag = chunk.endTag.replace(/^\n((>|\s)*)\n/,
function (totalMatch, markdown) {
return "\n" + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + "\n";
});
}
};
if (/^(?![ ]{0,3}>)/m.test(chunk.selection)) {
this.wrap(chunk, SETTINGS.lineLength - 2);
chunk.selection = chunk.selection.replace(/^/gm, "> ");
replaceBlanksInTags(true);
chunk.skipLines();
} else {
chunk.selection = chunk.selection.replace(/^[ ]{0,3}> ?/gm, "");
this.unwrap(chunk);
replaceBlanksInTags(false);
if (!/^(\n|^)[ ]{0,3}>/.test(chunk.selection) && chunk.startTag) {
chunk.startTag = chunk.startTag.replace(/\n{0,2}$/, "\n\n");
}
if (!/(\n|^)[ ]{0,3}>.*$/.test(chunk.selection) && chunk.endTag) {
chunk.endTag = chunk.endTag.replace(/^\n{0,2}/, "\n\n");
}
}
chunk.selection = this.hooks.<API key>(chunk.selection);
if (!/\n/.test(chunk.selection)) {
chunk.selection = chunk.selection.replace(/^(> *)/,
function (wholeMatch, blanks) {
chunk.startTag += blanks;
return "";
});
}
};
commandProto.doCode = function (chunk, postProcessing) {
var hasTextBefore = /\S[ ]*$/.test(chunk.before);
var hasTextAfter = /^[ ]*\S/.test(chunk.after);
// Use 'four space' markdown if the selection is on its own
// line or is multiline.
if ((!hasTextAfter && !hasTextBefore) || /\n/.test(chunk.selection)) {
chunk.before = chunk.before.replace(/[ ]{4}$/,
function (totalMatch) {
chunk.selection = totalMatch + chunk.selection;
return "";
});
var nLinesBack = 1;
var nLinesForward = 1;
if (/(\n|^)(\t|[ ]{4,}).*\n$/.test(chunk.before)) {
nLinesBack = 0;
}
if (/^\n(\t|[ ]{4,})/.test(chunk.after)) {
nLinesForward = 0;
}
chunk.skipLines(nLinesBack, nLinesForward);
if (!chunk.selection) {
chunk.startTag = " ";
chunk.selection = "enter code here";
}
else {
if (/^[ ]{0,3}\S/m.test(chunk.selection)) {
if (/\n/.test(chunk.selection))
chunk.selection = chunk.selection.replace(/^/gm, " ");
else // if it's not multiline, do not select the four added spaces; this is more consistent with the doList behavior
chunk.before += " ";
}
else {
chunk.selection = chunk.selection.replace(/^[ ]{4}/gm, "");
}
}
}
else {
// Use backticks (`) to delimit the code block.
chunk.trimWhitespace();
chunk.findTags(/`/, /`/);
if (!chunk.startTag && !chunk.endTag) {
chunk.startTag = chunk.endTag = "`";
if (!chunk.selection) {
chunk.selection = "enter code here";
}
}
else if (chunk.endTag && !chunk.startTag) {
chunk.before += chunk.endTag;
chunk.endTag = "";
}
else {
chunk.startTag = chunk.endTag = "";
}
}
};
commandProto.doList = function (chunk, postProcessing, isNumberedList) {
// These are identical except at the very beginning and end.
// Should probably use the regex extension function to make this clearer.
var previousItemsRegex = /(\n|^)(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*$/;
var nextItemsRegex = /^\n*(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*/;
// The default bullet is a dash but others are possible.
// This has nothing to do with the particular HTML bullet,
// it's just a markdown bullet.
var bullet = "-";
// The number in a numbered list.
var num = 1;
// Get the item prefix - e.g. " 1. " for a numbered list, " - " for a bulleted list.
var getItemPrefix = function () {
var prefix;
if (isNumberedList) {
prefix = " " + num + ". ";
num++;
}
else {
prefix = " " + bullet + " ";
}
return prefix;
};
// Fixes the prefixes of the other list items.
var getPrefixedItem = function (itemText) {
// The numbering flag is unset when called by autoindent.
if (isNumberedList === undefined) {
isNumberedList = /^\s*\d/.test(itemText);
}
// Renumber/bullet the list element.
itemText = itemText.replace(/^[ ]{0,3}([*+-]|\d+[.])\s/gm,
function (_) {
return getItemPrefix();
});
return itemText;
};
chunk.findTags(/(\n|^)*[ ]{0,3}([*+-]|\d+[.])\s+/, null);
if (chunk.before && !/\n$/.test(chunk.before) && !/^\n/.test(chunk.startTag)) {
chunk.before += chunk.startTag;
chunk.startTag = "";
}
if (chunk.startTag) {
var hasDigits = /\d+[.]/.test(chunk.startTag);
chunk.startTag = "";
chunk.selection = chunk.selection.replace(/\n[ ]{4}/g, "\n");
this.unwrap(chunk);
chunk.skipLines();
if (hasDigits) {
// Have to renumber the bullet points if this is a numbered list.
chunk.after = chunk.after.replace(nextItemsRegex, getPrefixedItem);
}
if (isNumberedList == hasDigits) {
return;
}
}
var nLinesUp = 1;
chunk.before = chunk.before.replace(previousItemsRegex,
function (itemText) {
if (/^\s*([*+-])/.test(itemText)) {
bullet = re.$1;
}
nLinesUp = /[^\n]\n\n[^\n]/.test(itemText) ? 1 : 0;
return getPrefixedItem(itemText);
});
if (!chunk.selection) {
chunk.selection = "List item";
}
var prefix = getItemPrefix();
var nLinesDown = 1;
chunk.after = chunk.after.replace(nextItemsRegex,
function (itemText) {
nLinesDown = /[^\n]\n\n[^\n]/.test(itemText) ? 1 : 0;
return getPrefixedItem(itemText);
});
chunk.trimWhitespace(true);
chunk.skipLines(nLinesUp, nLinesDown, true);
chunk.startTag = prefix;
var spaces = prefix.replace(/./g, " ");
this.wrap(chunk, SETTINGS.lineLength - spaces.length);
chunk.selection = chunk.selection.replace(/\n/g, "\n" + spaces);
};
commandProto.doHeading = function (chunk, postProcessing) {
// Remove leading/trailing whitespace and reduce internal spaces to single spaces.
chunk.selection = chunk.selection.replace(/\s+/g, " ");
chunk.selection = chunk.selection.replace(/(^\s+|\s+$)/g, "");
// If we clicked the button with no selected text, we just
// make a level 2 hash header around some default text.
if (!chunk.selection) {
chunk.startTag = "
chunk.selection = "Heading";
chunk.endTag = "
return;
}
var headerLevel = 0; // The existing header level of the selected text.
// Remove any existing hash heading markdown and save the header level.
chunk.findTags(/
if (/#+/.test(chunk.startTag)) {
headerLevel = re.lastMatch.length;
}
chunk.startTag = chunk.endTag = "";
// Try to get the current header level by looking for - and = in the line
// below the selection.
chunk.findTags(null, /\s?(-+|=+)/);
if (/=+/.test(chunk.endTag)) {
headerLevel = 1;
}
if (/-+/.test(chunk.endTag)) {
headerLevel = 2;
}
// Skip to the next line so we can create the header markdown.
chunk.startTag = chunk.endTag = "";
chunk.skipLines(1, 1);
// We make a level 2 header if there is no current header.
// If there is a header level, we substract one from the header level.
// If it's already a level 1 header, it's removed.
var headerLevelToCreate = headerLevel == 0 ? 2 : headerLevel - 1;
if (headerLevelToCreate > 0) {
// The button only creates level 1 and 2 underline headers.
// Why not have it iterate over hash header levels? Wouldn't that be easier and cleaner?
var headerChar = headerLevelToCreate >= 2 ? "-" : "=";
var len = chunk.selection.length;
if (len > SETTINGS.lineLength) {
len = SETTINGS.lineLength;
}
chunk.endTag = "\n";
while (len
chunk.endTag += headerChar;
}
}
};
commandProto.doHorizontalRule = function (chunk, postProcessing) {
chunk.startTag = "
chunk.selection = "";
chunk.skipLines(2, 1, true);
}
})();
|
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_11) on Tue Feb 24 12:30:37 EET 2015 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Package jtodo.domain (jTODO R1.0 API)</title>
<meta name="date" content="2015-02-24">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Package jtodo.domain (jTODO R1.0 API)";
}
}
catch(err) {
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="topNav"><a name="navbar.top">
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Use</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../index-all.html">Index</a></li>
<li><a href="../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../index.html?jtodo/domain/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.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="Uses of Package jtodo.domain" class="title">Uses of Package<br>jtodo.domain</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../jtodo/domain/package-summary.html">jtodo.domain</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#jtodo.domain">jtodo.domain</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#jtodo.managers">jtodo.managers</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="#jtodo.ui">jtodo.ui</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="jtodo.domain">
</a>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../jtodo/domain/package-summary.html">jtodo.domain</a> used by <a href="../../jtodo/domain/package-summary.html">jtodo.domain</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../../jtodo/domain/class-use/AbstractListItem.html#jtodo.domain">AbstractListItem</a>
<div class="block">Defines items (Task/Category) in a a TaskList</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="../../jtodo/domain/class-use/Category.html#jtodo.domain">Category</a>
<div class="block">Category used to separate different Tasks</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="../../jtodo/domain/class-use/Deadline.html#jtodo.domain">Deadline</a>
<div class="block">Defines a deadline for a Task</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="../../jtodo/domain/class-use/ListItemColor.html#jtodo.domain">ListItemColor</a>
<div class="block">Defines a highlight color for AbstractListItem.</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="../../jtodo/domain/class-use/Month.html#jtodo.domain">Month</a>
<div class="block">Defines a month.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="../../jtodo/domain/class-use/Priority.html#jtodo.domain">Priority</a>
<div class="block">Priority given to a Task</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="../../jtodo/domain/class-use/Task.html#jtodo.domain">Task</a>
<div class="block">Defines a Task that the user wants to accomplish.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="jtodo.managers">
</a>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../jtodo/domain/package-summary.html">jtodo.domain</a> used by <a href="../../jtodo/managers/package-summary.html">jtodo.managers</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../../jtodo/domain/class-use/Category.html#jtodo.managers">Category</a>
<div class="block">Category used to separate different Tasks</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="../../jtodo/domain/class-use/Task.html#jtodo.managers">Task</a>
<div class="block">Defines a Task that the user wants to accomplish.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="jtodo.ui">
</a>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../jtodo/domain/package-summary.html">jtodo.domain</a> used by <a href="../../jtodo/ui/package-summary.html">jtodo.ui</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../../jtodo/domain/class-use/Category.html#jtodo.ui">Category</a>
<div class="block">Category used to separate different Tasks</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="../../jtodo/domain/class-use/Task.html#jtodo.ui">Task</a>
<div class="block">Defines a Task that the user wants to accomplish.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<div class="bottomNav"><a name="navbar.bottom">
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Use</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../index-all.html">Index</a></li>
<li><a href="../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../index.html?jtodo/domain/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.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>
<p class="legalCopy"><small>Copyright &
</body>
</html>
|
package de.jdellert.iwsa.sequence;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* Symbol table for mapping IPA segments to integers for efficient internal
* representation. The first two integers are always used for special symbols: 0
* ~ #: the word boundary symbol 1 ~ -: the gap symbol
*
*/
public class PhoneticSymbolTable implements Serializable {
private static final long serialVersionUID = -<API key>;
private String[] idToSymbol;
private Map<String, Integer> symbolToID;
public PhoneticSymbolTable(Collection<String> symbols) {
this.idToSymbol = new String[symbols.size() + 2];
this.symbolToID = new TreeMap<String, Integer>();
idToSymbol[0] = "
idToSymbol[1] = "-";
symbolToID.put("
symbolToID.put("-", 1);
int nextID = 2;
for (String symbol : symbols) {
idToSymbol[nextID] = symbol;
symbolToID.put(symbol, nextID);
nextID++;
}
}
public Integer toInt(String symbol) {
return symbolToID.get(symbol);
}
public String toSymbol(int id) {
return idToSymbol[id];
}
public int[] encode(String[] segments) {
int[] segmentIDs = new int[segments.length];
for (int idx = 0; idx < segments.length; idx++) {
segmentIDs[idx] = symbolToID.get(segments[idx]);
}
return segmentIDs;
}
public String[] decode(int[] segmentIDs) {
String[] segments = new String[segmentIDs.length];
for (int idx = 0; idx < segmentIDs.length; idx++) {
segments[idx] = idToSymbol[segmentIDs[idx]];
}
return segments;
}
public Set<String> getDefinedSymbols()
{
return new TreeSet<String>(symbolToID.keySet());
}
public int getSize() {
return idToSymbol.length;
}
public String toSymbolPair(int symbolPairID) {
return "(" + toSymbol(symbolPairID / idToSymbol.length) + "," + toSymbol(symbolPairID % idToSymbol.length) + ")";
}
public String toString()
{
StringBuilder line1 = new StringBuilder();
StringBuilder line2 = new StringBuilder();
for (int i = 0; i < idToSymbol.length; i++)
{
line1.append(i + "\t");
line2.append(idToSymbol[i] + "\t");
}
return line1 + "\n" + line2;
}
}
|
import {
moduleForComponent,
test
} from 'ember-qunit';
moduleForComponent('hq-category', {
// Specify the other units that are required for this test
// needs: ['component:foo', 'helper:bar']
});
test('it renders', function(assert) {
assert.expect(2);
// Creates the component instance
var component = this.subject();
assert.equal(component._state, 'preRender');
// Renders the component to the page
this.render();
assert.equal(component._state, 'inDOM');
});
|
package org.dragonet.proxy.network.translator;
import java.util.Iterator;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.spacehq.mc.protocol.data.message.Message;
public final class MessageTranslator {
public static String translate(Message message) {
String ret = message.getFullText();
/*
* It is a JSON message?
*/
try {
/*
* Do not ask me why, but json strings has colors.
* Changing this allows colors in plain texts! yay!
*/
JSONObject jObject = null;
if (message.getFullText().startsWith("{") && message.getFullText().endsWith("}")) {
jObject = new JSONObject(message.getFullText());
} else {
jObject = new JSONObject(message.toJsonString());
}
/*
* Let's iterate!
*/
ret = handleKeyObject(jObject);
} catch (JSONException e) {
/*
* If any exceptions happens, then:
* * The JSON message is buggy or
* * It isn't a JSON message
*
* So, if any exceptions happens, we send the original message
*/
}
return ret;
}
public static String handleKeyObject(JSONObject jObject) throws JSONException {
String chatMessage = "";
Iterator<String> iter = jObject.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
if (key.equals("color")) {
String color = jObject.getString(key);
if (color.equals("light_purple")) {
chatMessage = chatMessage + "§d";
}
if (color.equals("blue")) {
chatMessage = chatMessage + "§9";
}
if (color.equals("aqua")) {
chatMessage = chatMessage + "§b";
}
if (color.equals("gold")) {
chatMessage = chatMessage + "§6";
}
if (color.equals("green")) {
chatMessage = chatMessage + "§a";
}
if (color.equals("white")) {
chatMessage = chatMessage + "§f";
}
if (color.equals("yellow")) {
chatMessage = chatMessage + "§e";
}
if (color.equals("gray")) {
chatMessage = chatMessage + "§7";
}
if (color.equals("red")) {
chatMessage = chatMessage + "§c";
}
if (color.equals("black")) {
chatMessage = chatMessage + "§0";
}
if (color.equals("dark_green")) {
chatMessage = chatMessage + "§2";
}
if (color.equals("dark_gray")) {
chatMessage = chatMessage + "§8";
}
if (color.equals("dark_red")) {
chatMessage = chatMessage + "§4";
}
if (color.equals("dark_blue")) {
chatMessage = chatMessage + "§1";
}
if (color.equals("dark_aqua")) {
chatMessage = chatMessage + "§3";
}
if (color.equals("dark_purple")) {
chatMessage = chatMessage + "§5";
}
}
if (key.equals("bold")) {
String bold = jObject.getString(key);
if (bold.equals("true")) {
chatMessage = chatMessage + "§l";
}
}
if (key.equals("italic")) {
String bold = jObject.getString(key);
if (bold.equals("true")) {
chatMessage = chatMessage + "§o";
}
}
if (key.equals("underlined")) {
String bold = jObject.getString(key);
if (bold.equals("true")) {
chatMessage = chatMessage + "§n";
}
}
if (key.equals("strikethrough")) {
String bold = jObject.getString(key);
if (bold.equals("true")) {
chatMessage = chatMessage + "§m";
}
}
if (key.equals("obfuscated")) {
String bold = jObject.getString(key);
if (bold.equals("true")) {
chatMessage = chatMessage + "§k";
}
}
if (key.equals("text")) {
/*
* We only need the text message from the JSON.
*/
String jsonMessage = jObject.getString(key);
chatMessage = chatMessage + jsonMessage;
continue;
}
if (jObject.get(key) instanceof JSONArray) {
chatMessage += handleKeyArray(jObject.getJSONArray(key));
}
if (jObject.get(key) instanceof JSONObject) {
chatMessage += handleKeyObject(jObject.getJSONObject(key));
}
} catch (JSONException e) {
}
}
return chatMessage;
}
public static String handleKeyArray(JSONArray jObject) throws JSONException {
String chatMessage = "";
JSONObject jsonObject = jObject.toJSONObject(jObject);
Iterator<String> iter = jsonObject.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
/*
* We only need the text message from the JSON.
*/
if (key.equals("text")) {
String jsonMessage = jsonObject.getString(key);
chatMessage = chatMessage + jsonMessage;
continue;
}
if (jsonObject.get(key) instanceof JSONArray) {
handleKeyArray(jsonObject.getJSONArray(key));
}
if (jsonObject.get(key) instanceof JSONObject) {
handleKeyObject(jsonObject.getJSONObject(key));
}
} catch (JSONException e) {
}
}
return chatMessage;
}
}
|
// BOINC Sentinels.
// BOINC Sentinels is free software; you can redistribute it and/or modify it
// as published by the Free Software Foundation,
// BOINC Sentinels is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#ifndef <API key>
#define <API key>
class <API key>: public wxObject
{
<API key>(<API key>)
public:
<API key>();
virtual ~<API key>();
bool IsRead(CBSLNotification& bslNotification);
bool IsDeleted(CBSLNotification& bslNotification);
bool MarkRead(CBSLNotification& bslNotification, bool bValue);
bool MarkDeleted(CBSLNotification& bslNotification, bool bValue);
private:
wxString DeterminePath(CBSLNotification& bslNotification);
bool GetConfigValue(wxString strSubComponent, wxString strValueName, long dwDefaultValue, long* pdwValue);
bool SetConfigValue(wxString strSubComponent, wxString strValueName, long dwValue);
};
#endif
|
package org.interactiverobotics.ml.optimization;
import static org.interactiverobotics.ml.optimization.OptimizationResult.Status.*;
import org.apache.log4j.Logger;
import org.interactiverobotics.math.Vector;
import java.util.Objects;
public final class LBFGS extends AbstractOptimizer implements Optimizer {
private static final Logger LOG = Logger.getLogger(LBFGS.class);
public LBFGS(final OptimizableFunction function) {
this.function = Objects.requireNonNull(function);
}
private final OptimizableFunction function;
/**
* Maximum number of iterations.
*/
private int maxIterations = 100;
/**
* The number of corrections to approximate the inverse Hessian matrix.
*/
private int m = 6;
/**
* Epsilon for convergence test.
* Controls the accuracy of with which the solution is to be found.
*/
private double epsilon = 1.0E-5;
/**
* Distance (in iterations) to calculate the rate of decrease of the function.
* Used in delta convergence test.
*/
private int past = 3;
/**
* Minimum rate of decrease of the function.
* Used in delta convergence test.
*/
private double delta = 1.0E-5;
/**
* Maximum number of line search iterations.
*/
private int <API key> = 100;
/**
* Continue optimization if line search returns {@code <API key>}.
*/
private boolean <API key> = false;
public int getMaxIterations() {
return maxIterations;
}
public void setMaxIterations(int maxIterations) {
this.maxIterations = maxIterations;
}
public int getM() {
return m;
}
public void setM(int m) {
this.m = m;
}
public double getEpsilon() {
return epsilon;
}
public void setEpsilon(double epsilon) {
this.epsilon = epsilon;
}
public int getPast() {
return past;
}
public void setPast(int past) {
this.past = past;
}
public double getDelta() {
return delta;
}
public void setDelta(double delta) {
this.delta = delta;
}
public int <API key>() {
return <API key>;
}
public void <API key>(int <API key>) {
this.<API key> = <API key>;
}
public boolean <API key>() {
return <API key>;
}
public void <API key>(boolean <API key>) {
this.<API key> = <API key>;
}
@Override
public OptimizationResult optimize() {
LOG.debug("Limited-memory BFGS optimize...");
final <API key> lineSearch = new <API key>(function);
lineSearch.setMaxIterations(<API key>);
final State[] states = new State[m];
for (int i = 0; i < m; i ++) {
states[i] = new State();
}
int currentStateIndex = 0;
final double[] pastValues;
if (past > 0) {
pastValues = new double[past];
pastValues[0] = function.getValue();
} else {
pastValues = null;
}
Vector parameters = function.getParameters();
Vector gradient = function.getValueGradient();
final double initialGradientNorm = gradient.getLength() / Math.max(parameters.getLength(), 1.0);
LOG.debug("Initial gradient norm = " + initialGradientNorm);
if (initialGradientNorm <= epsilon) {
LOG.debug("Already minimized");
return new OptimizationResult(ALREADY_MINIMIZED, parameters, function.getValue(), 0);
}
Vector direction = gradient.copy().neg();
double step = Vector.dotProduct(direction, direction);
Vector prevParameters, prevGradient;
OptimizationResult.Status status = <API key>;
int iteration;
for (iteration = 1; iteration <= maxIterations; iteration ++) {
LOG.debug("Iteration " + iteration);
// save previous Parameters and Gradient
prevParameters = parameters.copy();
prevGradient = gradient.copy();
// search for optimal Step
LOG.debug("Direction: " + direction + " Step = " + step);
lineSearch.setDirection(direction);
lineSearch.setInitialStep(step);
final OptimizationResult lineSearchResult = lineSearch.optimize();
if (!lineSearchResult.hasConverged()) {
LOG.error("Line search not converged: " + lineSearchResult.getStatus());
final boolean <API key> =
(lineSearchResult.getStatus() == <API key>) && <API key>;
if (!<API key>) {
// step back
function.setParameters(prevParameters);
status = lineSearchResult.getStatus();
break;
}
}
parameters = function.getParameters();
gradient = function.getValueGradient();
final double value = function.getValue();
final boolean stop = fireOptimizerStep(parameters, value, direction, iteration);
if (stop) {
LOG.debug("Stop");
status = STOP;
break;
}
// test for convergence
final double gradientNorm = gradient.getLength() / Math.max(parameters.getLength(), 1.0);
LOG.debug("Gradient norm = " + gradientNorm);
if (gradientNorm <= epsilon) {
LOG.debug("Success");
status = SUCCESS;
break;
}
// delta convergence test
if (past > 0) {
if (iteration > past) {
// relative improvement from the past
final double rate = (pastValues[iteration % past] - value) / value;
if (rate < delta) {
status = STOP;
break;
}
}
pastValues[iteration % past] = value;
}
// update S and Y
final State currentState = states[currentStateIndex];
currentState.s = parameters.copy().sub(prevParameters);
currentState.y = gradient.copy().sub(prevGradient);
final double ys = Vector.dotProduct(currentState.y, currentState.s);
final double yy = Vector.dotProduct(currentState.y, currentState.y);
currentState.ys = ys;
currentStateIndex = (currentStateIndex + 1) % m;
// update Direction
direction = gradient.copy();
int availableStates = Math.min(iteration, m);
LOG.debug("Available states = " + availableStates);
int j = currentStateIndex;
for (int i = 0; i < availableStates; i ++) {
j = (j + m - 1) % m;
final State t = states[j];
t.alpha = Vector.dotProduct(t.s, direction) / t.ys;
direction.sub(t.y.copy().scale(t.alpha));
}
direction.scale(ys / yy);
for (int i = 0; i < availableStates; i ++) {
final State t = states[j];
final double beta = Vector.dotProduct(t.y, direction) / t.ys;
direction.add(t.s.copy().scale(t.alpha - beta));
j = (j + 1) % m;
}
direction.neg();
step = 1.0;
}
final Vector finalParameters = function.getParameters();
final double finalValue = function.getValue();
LOG.debug("Status = " + status + " Final Value = " + finalValue + " Parameters: " + finalParameters
+ " Iteration = " + iteration);
return new OptimizationResult(status, finalParameters, finalValue, iteration);
}
private static class State {
public double alpha;
public Vector s;
public Vector y;
public double ys;
}
}
|
package cn.bjsxt.oop.staticInitBlock;
public class Parent001 /*extends Object*/ {
static int aa;
static {
System.out.println(" Parent001");
aa=200;
}
}
|
using Fallout4Checklist.Entities;
namespace Fallout4Checklist.ViewModels
{
public class <API key>
{
public <API key>(Weapon weapon)
{
Weapon = weapon;
}
public Weapon Weapon { get; set; }
}
}
|
import inspect
import re
import pytest
from robottelo.logging import collection_logger as logger
IMPORTANCE_LEVELS = []
def pytest_addoption(parser):
"""Add CLI options related to Testimony token based mark collection"""
parser.addoption(
'--importance',
help='Comma separated list of importance levels to include in test collection',
)
parser.addoption(
'--component',
help='Comma separated list of component names to include in test collection',
)
parser.addoption(
'--assignee',
help='Comma separated list of assignees to include in test collection',
)
def pytest_configure(config):
"""Register markers related to testimony tokens"""
for marker in [
'importance: CaseImportance testimony token, use --importance to filter',
'component: Component testimony token, use --component to filter',
'assignee: Assignee testimony token, use --assignee to filter',
]:
config.addinivalue_line("markers", marker)
component_regex = re.compile(
# To match :CaseComponent: FooBar
r'\s*:CaseComponent:\s*(?P<component>\S*)',
re.IGNORECASE,
)
importance_regex = re.compile(
# To match :CaseImportance: Critical
r'\s*:CaseImportance:\s*(?P<importance>\S*)',
re.IGNORECASE,
)
assignee_regex = re.compile(
# To match :Assignee: jsmith
r'\s*:Assignee:\s*(?P<assignee>\S*)',
re.IGNORECASE,
)
@pytest.hookimpl(tryfirst=True)
def <API key>(session, items, config):
"""Add markers for testimony tokens"""
# split the option string and handle no option, single option, multiple
# config.getoption(default) doesn't work like you think it does, hence or ''
importance = [i for i in (config.getoption('importance') or '').split(',') if i != '']
component = [c for c in (config.getoption('component') or '').split(',') if c != '']
assignee = [a for a in (config.getoption('assignee') or '').split(',') if a != '']
selected = []
deselected = []
logger.info('Processing test items to add testimony token markers')
for item in items:
if item.nodeid.startswith('tests/robottelo/'):
# Unit test, no testimony markers
continue
# apply the marks for importance, component, and assignee
# Find matches from docstrings starting at smallest scope
item_docstrings = [
d
for d in map(inspect.getdoc, (item.function, getattr(item, 'cls', None), item.module))
if d is not None
]
item_mark_names = [m.name for m in item.iter_markers()]
for docstring in item_docstrings:
# Add marker starting at smallest docstring scope
# only add the mark if it hasn't already been applied at a lower scope
doc_component = component_regex.findall(docstring)
if doc_component and 'component' not in item_mark_names:
item.add_marker(pytest.mark.component(doc_component[0]))
doc_importance = importance_regex.findall(docstring)
if doc_importance and 'importance' not in item_mark_names:
item.add_marker(pytest.mark.importance(doc_importance[0]))
doc_assignee = assignee_regex.findall(docstring)
if doc_assignee and 'assignee' not in item_mark_names:
item.add_marker(pytest.mark.assignee(doc_assignee[0]))
# exit early if no filters were passed
if importance or component or assignee:
# Filter test collection based on CLI options for filtering
# filters should be applied together
# such that --component Repository --importance Critical --assignee jsmith
# only collects tests which have all three of these marks
# testimony requires both importance and component, this will blow up if its forgotten
importance_marker = item.get_closest_marker('importance').args[0]
if importance and importance_marker not in importance:
logger.debug(
f'Deselected test {item.nodeid} due to "--importance {importance}",'
f'test has importance mark: {importance_marker}'
)
deselected.append(item)
continue
component_marker = item.get_closest_marker('component').args[0]
if component and component_marker not in component:
logger.debug(
f'Deselected test {item.nodeid} due to "--component {component}",'
f'test has component mark: {component_marker}'
)
deselected.append(item)
continue
assignee_marker = item.get_closest_marker('assignee').args[0]
if assignee and assignee_marker not in assignee:
logger.debug(
f'Deselected test {item.nodeid} due to "--assignee {assignee}",'
f'test has assignee mark: {assignee_marker}'
)
deselected.append(item)
continue
selected.append(item)
# selected will be empty if no filter option was passed, defaulting to full items list
items[:] = selected if deselected else items
config.hook.pytest_deselected(items=deselected)
|
package se.dykstrom.jcc.common.ast;
import java.util.Objects;
/**
* Abstract base class for different types of jump statements, such as GOTO or GOSUB.
*
* @author Johan Dykstrom
*/
public abstract class <API key> extends AbstractNode implements Statement {
private final String jumpLabel;
protected <API key>(int line, int column, String jumpLabel) {
super(line, column);
this.jumpLabel = jumpLabel;
}
/**
* Returns the label to jump to.
*/
public String getJumpLabel() {
return jumpLabel;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
<API key> that = (<API key>) o;
return Objects.equals(jumpLabel, that.jumpLabel);
}
@Override
public int hashCode() {
return Objects.hash(jumpLabel);
}
}
|
class Block {
constructor(x, y, width, colour) {
this.x = x;
this.y = y;
this.width = width;
this.colour = colour;
this.occupied = false;
}
draw() {
fill(this.colour);
rect(this.x, this.y, this.width, this.width);
}
}
|
package de.minestar.contao.manager;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.bukkit.entity.Player;
import de.minestar.contao.core.Settings;
import de.minestar.contao.data.ContaoGroup;
import de.minestar.contao.data.User;
import de.minestar.core.MinestarCore;
import de.minestar.core.units.MinestarPlayer;
public class PlayerManager {
private Map<String, User> onlineUserMap = new HashMap<String, User>();
private Map<ContaoGroup, TreeSet<User>> groupMap = new HashMap<ContaoGroup, TreeSet<User>>();
public PlayerManager() {
for (ContaoGroup cGroup : ContaoGroup.values()) {
groupMap.put(cGroup, new TreeSet<User>());
}
}
public void addUser(User user) {
onlineUserMap.put(user.<API key>().toLowerCase(), user);
groupMap.get(user.getGroup()).add(user);
}
public void removeUser(String userName) {
User user = onlineUserMap.remove(userName.toLowerCase());
groupMap.get(user.getGroup()).remove(user);
}
public User getUser(Player player) {
return getUser(player.getName());
}
public User getUser(String userName) {
return onlineUserMap.get(userName.toLowerCase());
}
public String getGroupAsString(ContaoGroup contaoGroup) {
Set<User> groupMember = groupMap.get(contaoGroup);
if (groupMember.isEmpty())
return null;
StringBuilder sBuilder = new StringBuilder();
// BUILD HEAD
sBuilder.append(Settings.getColor(contaoGroup));
sBuilder.append(contaoGroup.getDisplayName());
sBuilder.append('(');
sBuilder.append(getGroupSize(contaoGroup));
sBuilder.append(") : ");
// ADD USER
for (User user : groupMember) {
sBuilder.append(user.<API key>());
sBuilder.append(", ");
}
// DELETE THE LAST COMMATA
sBuilder.delete(0, sBuilder.length() - 2);
return sBuilder.toString();
}
public int getGroupSize(ContaoGroup contaoGroup) {
return groupMap.get(contaoGroup).size();
}
public void changeGroup(User user, ContaoGroup newGroup) {
groupMap.get(user.getGroup()).remove(user);
groupMap.get(newGroup).add(user);
setGroup(user, newGroup);
}
public void setGroup(User user, ContaoGroup newGroup) {
MinestarPlayer mPlayer = MinestarCore.getPlayer(user.<API key>());
if (mPlayer != null) {
mPlayer.setGroup(newGroup.getMinestarGroup());
}
}
public boolean canBeFree(User probeUser) {
// TODO: Implement requirements
return false;
}
}
|
package org.grovecity.drizzlesms.jobs.requirements;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import org.grovecity.drizzlesms.service.KeyCachingService;
import org.whispersystems.jobqueue.requirements.RequirementListener;
import org.whispersystems.jobqueue.requirements.RequirementProvider;
public class Master<API key> implements RequirementProvider {
private final BroadcastReceiver newKeyReceiver;
private RequirementListener listener;
public Master<API key>(Context context) {
this.newKeyReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (listener != null) {
listener.<API key>();
}
}
};
IntentFilter filter = new IntentFilter(KeyCachingService.NEW_KEY_EVENT);
context.registerReceiver(newKeyReceiver, filter, KeyCachingService.KEY_PERMISSION, null);
}
@Override
public void setListener(RequirementListener listener) {
this.listener = listener;
}
}
|
package dfmaster.general;
import dfmaster.json.JSONValue;
import dfmaster.xml.XMLDocument;
import dfmaster.xml.XMLElement;
/**
* This is the abstract type for all data that can be created or parsed. This
* could be as example a {@link JSONValue}, a {@link XMLDocument} or a
* {@link XMLElement}
*
* @author Josua Frank
*/
public class AData {
}
|
<?php
namespace EasyAjax;
/**
* EasyAjax\FrontInterface interface
*
* @package EasyAjax
* @author Giuseppe Mazzapica
*
*/
interface FrontInterface {
/**
* Check the request for valid EasyAjax
*
* @return bool true if current request is a valid EasyAjax ajax request
* @access public
*/
function is_valid_ajax();
/**
* Setup the EasyAjax Instance
*
* @param object $scope the object scope that will execute action if given
* @param string $where can be 'priv', 'nopriv' or 'both'. Limit actions to logged in users or not
* @param array $allowed list of allowed actions
* @return null
* @access public
*/
function setup( $scope = '', $where = '', $allowed = [ ] );
/**
* Check the request and launch EasyAjax\Proxy setup if required
*
* @return null
* @access public
*/
function register();
}
|
// <auto-generated>
// This code was generated by a tool.
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
public partial class <API key> {
<summary>
editElem control.
</summary>
<remarks>
Auto-generated field.
To modify move field declaration from designer file to code-behind file.
</remarks>
protected global::<API key> editElem;
}
|
package io.valhala.javamon.pokemon.skeleton;
import io.valhala.javamon.pokemon.Pokemon;
import io.valhala.javamon.pokemon.type.Type;
public abstract class Paras extends Pokemon {
public Paras() {
super("Paras", 35, 70, 55, 25, 55, true, 46,Type.BUG,Type.GRASS);
// TODO Auto-generated constructor stub
}
}
|
define(['backbone', 'underscore'], function (Backbone, _) {
return Backbone.Model.extend({
idAttribute: 'username',
defaults: {
persona: {
personaPnombre: '',
personaSnombre: '',
personaApaterno: '',
personaAmaterno: '',
dni: ''
}
},
validate: function (attrs, options) {
console.log('persona', attrs.persona);
if (_.isUndefined(attrs.persona)) {
return {
field: 'persona',
error: 'Debe definir una persona'
};
}
if (_.isUndefined(attrs.persona.personaDni) || _.isEmpty(attrs.persona.personaDni.trim()) || attrs.persona.personaDni.trim().length != 8) {
return {
field: 'persona-personaDni',
error: 'El dni es un campo obligatorio y debe tener 8 caracteres.'
};
}
if (_.isUndefined(attrs.persona.personaPnombre) || _.isEmpty(attrs.persona.personaPnombre.trim())) {
return {
field: '<API key>',
error: 'El primer nombre es un campo obligatorio.'
};
}
if (_.isUndefined(attrs.persona.personaApaterno) || _.isEmpty(attrs.persona.personaApaterno.trim())) {
return {
field: '<API key>',
error: 'El apellido paterno es un campo obligatorio.'
};
}
if (_.isUndefined(attrs.persona.personaAmaterno) || _.isEmpty(attrs.persona.personaAmaterno.trim())) {
return {
field: '<API key>',
error: 'El apellido materno es un campo obligatorio.'
};
}
}
});
});
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
// This Source Code Form is subject to the terms of the Mozilla
#ifndef EIGEN_PRODUCTBASE_H
#define EIGEN_PRODUCTBASE_H
namespace Eigen {
/** \class ProductBase
* \ingroup Core_Module
*
*/
namespace internal {
template<typename Derived, typename _Lhs, typename _Rhs>
struct traits<ProductBase<Derived,_Lhs,_Rhs> >
{
typedef MatrixXpr XprKind;
typedef typename remove_all<_Lhs>::type Lhs;
typedef typename remove_all<_Rhs>::type Rhs;
typedef typename <API key><typename Lhs::Scalar, typename Rhs::Scalar>::ReturnType Scalar;
typedef typename <API key><typename traits<Lhs>::StorageKind,
typename traits<Rhs>::StorageKind>::ret StorageKind;
typedef typename promote_index_type<typename traits<Lhs>::Index,
typename traits<Rhs>::Index>::type Index;
enum {
RowsAtCompileTime = traits<Lhs>::RowsAtCompileTime,
ColsAtCompileTime = traits<Rhs>::ColsAtCompileTime,
<API key> = traits<Lhs>::<API key>,
<API key> = traits<Rhs>::<API key>,
Flags = (<API key>==1 ? RowMajorBit : 0)
| <API key> | <API key> | NestByRefBit,
// Note that <API key> and NestByRefBit
// are not used in practice because nested is overloaded for products
CoeffReadCost = 0 // FIXME why is it needed ?
};
};
}
#define <API key>(Derived) \
typedef ProductBase<Derived, Lhs, Rhs > Base; \
<API key>(Derived) \
typedef typename Base::LhsNested LhsNested; \
typedef typename Base::_LhsNested _LhsNested; \
typedef typename Base::LhsBlasTraits LhsBlasTraits; \
typedef typename Base::ActualLhsType ActualLhsType; \
typedef typename Base::_ActualLhsType _ActualLhsType; \
typedef typename Base::RhsNested RhsNested; \
typedef typename Base::_RhsNested _RhsNested; \
typedef typename Base::RhsBlasTraits RhsBlasTraits; \
typedef typename Base::ActualRhsType ActualRhsType; \
typedef typename Base::_ActualRhsType _ActualRhsType; \
using Base::m_lhs; \
using Base::m_rhs;
template<typename Derived, typename Lhs, typename Rhs>
class ProductBase : public MatrixBase<Derived>
{
public:
typedef MatrixBase<Derived> Base;
<API key>(ProductBase)
typedef typename Lhs::Nested LhsNested;
typedef typename internal::remove_all<LhsNested>::type _LhsNested;
typedef internal::blas_traits<_LhsNested> LhsBlasTraits;
typedef typename LhsBlasTraits::<API key> ActualLhsType;
typedef typename internal::remove_all<ActualLhsType>::type _ActualLhsType;
typedef typename internal::traits<Lhs>::Scalar LhsScalar;
typedef typename Rhs::Nested RhsNested;
typedef typename internal::remove_all<RhsNested>::type _RhsNested;
typedef internal::blas_traits<_RhsNested> RhsBlasTraits;
typedef typename RhsBlasTraits::<API key> ActualRhsType;
typedef typename internal::remove_all<ActualRhsType>::type _ActualRhsType;
typedef typename internal::traits<Rhs>::Scalar RhsScalar;
// Diagonal of a product: no need to evaluate the arguments because they are going to be evaluated only once
typedef CoeffBasedProduct<LhsNested, RhsNested, 0> <API key>;
public:
typedef typename Base::PlainObject PlainObject;
ProductBase(const Lhs& a_lhs, const Rhs& a_rhs)
: m_lhs(a_lhs), m_rhs(a_rhs)
{
eigen_assert(a_lhs.cols() == a_rhs.rows()
&& "invalid matrix product"
&& "if you wanted a coeff-wise or a dot product use the respective explicit functions");
}
inline Index rows() const { return m_lhs.rows(); }
inline Index cols() const { return m_rhs.cols(); }
template<typename Dest>
inline void evalTo(Dest& dst) const { dst.setZero(); scaleAndAddTo(dst,Scalar(1)); }
template<typename Dest>
inline void addTo(Dest& dst) const { scaleAndAddTo(dst,Scalar(1)); }
template<typename Dest>
inline void subTo(Dest& dst) const { scaleAndAddTo(dst,Scalar(-1)); }
template<typename Dest>
inline void scaleAndAddTo(Dest& dst,Scalar alpha) const { derived().scaleAndAddTo(dst,alpha); }
const _LhsNested& lhs() const { return m_lhs; }
const _RhsNested& rhs() const { return m_rhs; }
// Implicit conversion to the nested type (trigger the evaluation of the product)
operator const PlainObject& () const
{
m_result.resize(m_lhs.rows(), m_rhs.cols());
derived().evalTo(m_result);
return m_result;
}
const Diagonal<const <API key>,0> diagonal() const
{ return <API key>(m_lhs, m_rhs); }
template<int Index>
const Diagonal<<API key>,Index> diagonal() const
{ return <API key>(m_lhs, m_rhs); }
const Diagonal<<API key>,Dynamic> diagonal(Index index) const
{ return <API key>(m_lhs, m_rhs).diagonal(index); }
// restrict coeff accessors to 1x1 expressions. No need to care about mutators here since this isnt a Lvalue expression
typename Base::CoeffReturnType coeff(Index row, Index col) const
{
#ifdef EIGEN2_SUPPORT
return lhs().row(row).cwiseProduct(rhs().col(col).transpose()).sum();
#else
<API key>(Derived)
eigen_assert(this->rows() == 1 && this->cols() == 1);
Matrix<Scalar,1,1> result = *this;
return result.coeff(row,col);
#endif
}
typename Base::CoeffReturnType coeff(Index i) const
{
<API key>(Derived)
eigen_assert(this->rows() == 1 && this->cols() == 1);
Matrix<Scalar,1,1> result = *this;
return result.coeff(i);
}
const Scalar& coeffRef(Index row, Index col) const
{
<API key>(Derived)
eigen_assert(this->rows() == 1 && this->cols() == 1);
return derived().coeffRef(row,col);
}
const Scalar& coeffRef(Index i) const
{
<API key>(Derived)
eigen_assert(this->rows() == 1 && this->cols() == 1);
return derived().coeffRef(i);
}
protected:
LhsNested m_lhs;
RhsNested m_rhs;
mutable PlainObject m_result;
};
// here we need to overload the nested rule for products
// such that the nested type is a const reference to a plain matrix
namespace internal {
template<typename Lhs, typename Rhs, int Mode, int N, typename PlainObject>
struct nested<GeneralProduct<Lhs,Rhs,Mode>, N, PlainObject>
{
typedef PlainObject const& type;
};
}
template<typename NestedProduct>
class ScaledProduct;
// Note that these two operator* functions are not defined as member
// functions of ProductBase, because, otherwise we would have to
// define all overloads defined in MatrixBase. Furthermore, Using
// "using Base::operator*" would not work with MSVC.
// Also note that here we accept any compatible scalar types
template<typename Derived,typename Lhs,typename Rhs>
const ScaledProduct<Derived>
operator*(const ProductBase<Derived,Lhs,Rhs>& prod, typename Derived::Scalar x)
{ return ScaledProduct<Derived>(prod.derived(), x); }
template<typename Derived,typename Lhs,typename Rhs>
typename internal::enable_if<!internal::is_same<typename Derived::Scalar,typename Derived::RealScalar>::value,
const ScaledProduct<Derived> >::type
operator*(const ProductBase<Derived,Lhs,Rhs>& prod, const typename Derived::RealScalar& x)
{ return ScaledProduct<Derived>(prod.derived(), x); }
template<typename Derived,typename Lhs,typename Rhs>
const ScaledProduct<Derived>
operator*(typename Derived::Scalar x,const ProductBase<Derived,Lhs,Rhs>& prod)
{ return ScaledProduct<Derived>(prod.derived(), x); }
template<typename Derived,typename Lhs,typename Rhs>
typename internal::enable_if<!internal::is_same<typename Derived::Scalar,typename Derived::RealScalar>::value,
const ScaledProduct<Derived> >::type
operator*(const typename Derived::RealScalar& x,const ProductBase<Derived,Lhs,Rhs>& prod)
{ return ScaledProduct<Derived>(prod.derived(), x); }
namespace internal {
template<typename NestedProduct>
struct traits<ScaledProduct<NestedProduct> >
: traits<ProductBase<ScaledProduct<NestedProduct>,
typename NestedProduct::_LhsNested,
typename NestedProduct::_RhsNested> >
{
typedef typename traits<NestedProduct>::StorageKind StorageKind;
};
}
template<typename NestedProduct>
class ScaledProduct
: public ProductBase<ScaledProduct<NestedProduct>,
typename NestedProduct::_LhsNested,
typename NestedProduct::_RhsNested>
{
public:
typedef ProductBase<ScaledProduct<NestedProduct>,
typename NestedProduct::_LhsNested,
typename NestedProduct::_RhsNested> Base;
typedef typename Base::Scalar Scalar;
typedef typename Base::PlainObject PlainObject;
// <API key>(ScaledProduct)
ScaledProduct(const NestedProduct& prod, Scalar x)
: Base(prod.lhs(),prod.rhs()), m_prod(prod), m_alpha(x) {}
template<typename Dest>
inline void evalTo(Dest& dst) const { dst.setZero(); scaleAndAddTo(dst, Scalar(1)); }
template<typename Dest>
inline void addTo(Dest& dst) const { scaleAndAddTo(dst, Scalar(1)); }
template<typename Dest>
inline void subTo(Dest& dst) const { scaleAndAddTo(dst, Scalar(-1)); }
template<typename Dest>
inline void scaleAndAddTo(Dest& dst,Scalar a_alpha) const { m_prod.derived().scaleAndAddTo(dst,a_alpha * m_alpha); }
const Scalar& alpha() const { return m_alpha; }
protected:
const NestedProduct& m_prod;
Scalar m_alpha;
};
/** \internal
* Overloaded to perform an efficient C = (A*B).lazy() */
template<typename Derived>
template<typename ProductDerived, typename Lhs, typename Rhs>
Derived& MatrixBase<Derived>::lazyAssign(const ProductBase<ProductDerived, Lhs,Rhs>& other)
{
other.derived().evalTo(derived());
return derived();
}
} // end namespace Eigen
#endif // EIGEN_PRODUCTBASE_H
|
package de.unikiel.inf.comsys.neo4j.inference.sail;
import de.unikiel.inf.comsys.neo4j.inference.QueryRewriter;
import org.openrdf.query.algebra.TupleExpr;
import org.openrdf.query.parser.ParsedBooleanQuery;
import org.openrdf.repository.sail.SailBooleanQuery;
import org.openrdf.repository.sail.<API key>;
/**
* A subclass of {@link SailBooleanQuery} with a public constructor to
* pass in a boolean query containing a tuple expression.
*
* The original constructor of {@link SailBooleanQuery} is protected, thus
* it is not possible to create a new boolean query from a parsed query
* that is used to create a query from a {@link TupleExpr}.
*
* @see QueryRewriter
*/
public class <API key> extends SailBooleanQuery {
public <API key>(ParsedBooleanQuery booleanQuery, <API key> sailConnection) {
super(booleanQuery, sailConnection);
}
}
|
#!/usr/bin/perl
# Meran - MERAN UNLP is a ILS (Integrated Library System) wich provides Catalog,
# Circulation and User's Management. It's written in Perl, and uses Apache2
# Web-Server, MySQL database and Sphinx 2 indexing.
# <desarrollo@cespi.unlp.edu.ar>
# This file is part of Meran.
# Meran is free software: you can redistribute it and/or modify
# (at your option) any later version.
# Meran is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
use C4::AR::Nivel3;
use C4::Context;
use C4::Modelo::CatRegistroMarcN1;
use C4::Modelo::CatRegistroMarcN1::Manager;
use C4::Modelo::CatRegistroMarcN2;
use C4::Modelo::CatRegistroMarcN2::Manager;
use C4::Modelo::CatRegistroMarcN3;
use C4::Modelo::CatRegistroMarcN3::Manager;
my $ui = $ARGV[0] || "DEO";
my $tipo = $ARGV[1] || "LIB";
my $desde = $ARGV[2] || "00001";
my @head=(
'FECHA',
'INVENTARIO',
'AUTOR',
'TÍTULO',
'EDICIÓN',
'EDITOR',
'AÑO');
print join('#', @head);
print "\n";
my $ejemplares = C4::Modelo::CatRegistroMarcN3::Manager-><API key>(
query => [
codigo_barra => { ge => $ui."-".$tipo."-".$desde },
codigo_barra => { like => $ui."-".$tipo."-%"},
],
sort_by => 'codigo_barra ASC'
);
foreach my $nivel3 (@$ejemplares){
my @ejemplar=();
$ejemplar[0] = $nivel3->getCreatedAt_format();
$ejemplar[1] = $nivel3->getCodigoBarra();
$ejemplar[2] = $nivel3->nivel1->getAutor();
$ejemplar[3] = $nivel3->nivel1->getTitulo();
$ejemplar[4] = $nivel3->nivel2->getEdicion();
$ejemplar[5] = $nivel3->nivel2->getEditor();
$ejemplar[6] = $nivel3->nivel2->getAnio_publicacion();
print join('#', @ejemplar);
print "\n";
}
1;
|
require 'spec_helper'
describe SessionsController do
render_views
context "#create" do
it "should redirect to patterns path if user is authenticated"
it "should redirect to new_user if user doesn't exist"
it "should redirect to new_user if password is incorrect"
end
end
|
#include <math.h>
#include <stdlib.h>
#include "camp_judge.h"
#include "game_event.h"
#include "monster_ai.h"
#include "monster_manager.h"
#include "path_algorithm.h"
#include "player_manager.h"
#include "time_helper.h"
#include "partner.h"
#include "check_range.h"
#include "cached_hit_effect.h"
#include "count_skill_damage.h"
#include "msgid.h"
#include "buff.h"
static unit_struct *choose_target(partner_struct *partner)
{
unit_struct *ret = NULL;
double distance;
uint64_t now = time_helper::get_cached_time();
uint64_t t = now - 60 * 1000;
struct position *cur_pos = partner->get_pos();
distance = 0xffffffff;
for (int i = 0; i < <API key>; ++i)
{
if (partner->attack_owner[i].uuid == 0)
continue;
if (partner->attack_owner[i].time <= t)
{
partner->attack_owner[i].uuid = 0;
continue;
}
if (!partner->is_unit_in_sight(partner->attack_owner[i].uuid))
continue;
unit_struct *target = unit_struct::get_unit_by_uuid(partner->attack_owner[i].uuid);
if (!target || !target->is_avaliable() || !target->is_alive())
{
partner->attack_owner[i].uuid = 0;
continue;
}
struct position *pos = target->get_pos();
float x = pos->pos_x - cur_pos->pos_x;
float z = pos->pos_z - cur_pos->pos_z;
if (x * x + z * z <= distance)
{
distance = x * x + z * z;
ret = target;
}
}
if (ret)
return ret;
for (int i = 0; i < <API key>; ++i)
{
if (partner->attack_partner[i].uuid == 0)
continue;
if (partner->attack_partner[i].time <= t)
{
partner->attack_partner[i].uuid = 0;
continue;
}
if (!partner->is_unit_in_sight(partner->attack_partner[i].uuid))
continue;
unit_struct *target = unit_struct::get_unit_by_uuid(partner->attack_partner[i].uuid);
if (!target || !target->is_avaliable() || !target->is_alive())
{
partner->attack_partner[i].uuid = 0;
continue;
}
struct position *pos = target->get_pos();
float x = pos->pos_x - cur_pos->pos_x;
float z = pos->pos_z - cur_pos->pos_z;
if (x * x + z * z <= distance)
{
distance = x * x + z * z;
ret = target;
}
}
if (ret)
return ret;
for (int i = 0; i < <API key>; ++i)
{
if (partner->owner_attack[i].uuid == 0)
continue;
if (partner->owner_attack[i].time <= t)
{
partner->owner_attack[i].uuid = 0;
continue;
}
if (!partner->is_unit_in_sight(partner->owner_attack[i].uuid))
continue;
unit_struct *target = unit_struct::get_unit_by_uuid(partner->owner_attack[i].uuid);
if (!target || !target->is_avaliable() || !target->is_alive())
{
partner->owner_attack[i].uuid = 0;
continue;
}
struct position *pos = target->get_pos();
float x = pos->pos_x - cur_pos->pos_x;
float z = pos->pos_z - cur_pos->pos_z;
if (x * x + z * z <= distance)
{
distance = x * x + z * z;
ret = target;
}
}
if (ret)
return ret;
return NULL;
}
int partner_ai_tick_1(partner_struct *partner)
{
if (partner->data->skill_id != 0 && partner->ai_state == AI_ATTACK_STATE)
{
partner->do_normal_attack();
partner->data->skill_id = 0;
partner->ai_state = AI_PATROL_STATE;
return 1;
}
int skill_index;
uint32_t skill_id = partner->choose_skill(&skill_index);
if (skill_id == 0)
return 1;
if (partner->try_friend_skill(skill_id, skill_index))
{
return (0);
}
unit_struct *target = choose_target(partner);
if (!target)
return 0;
return partner->attack_target(skill_id, skill_index, target);
// struct position *my_pos = partner->get_pos();
// struct position *his_pos = target->get_pos();
// struct SkillTable *config = get_config_by_id(skill_id, &skill_config);
// if (config == NULL)
// LOG_ERR("%s: partner can not find skill[%u] config", __FUNCTION__, skill_id);
// return 1;
// if (!<API key>(my_pos, his_pos, config->SkillRange))
// partner->reset_pos();
// if (<API key>(partner->scene, my_pos, his_pos, config->SkillRange, &partner->data->move_path.pos[1]))
// partner->send_patrol_move();
// else
// return (0);
// partner->data->ontick_time += random() % 1000;
// return 1;
// if (config->SkillType == 2)
// struct ActiveSkillTable *act_config = get_config_by_id(config->SkillAffectId, &active_skill_config);
// if (!act_config)
// LOG_ERR("%s: can not find skillaffectid[%lu] config", __FUNCTION__, config->SkillAffectId);
// return 1;
// if (act_config->ActionTime > 0)
// uint64_t now = time_helper::get_cached_time();
// partner->data->ontick_time = now + act_config->ActionTime;// + 1500;
// partner->data->skill_id = skill_id;
// partner->data->angle = -(pos_to_angle(his_pos->pos_x - my_pos->pos_x, his_pos->pos_z - my_pos->pos_z));
// // LOG_DEBUG("jacktang: mypos[%.2f][%.2f] hispos[%.2f][%.2f]", my_pos->pos_x, my_pos->pos_z, his_pos->pos_x, his_pos->pos_z);
// partner->ai_state = AI_ATTACK_STATE;
// partner->m_target = target;
// partner->reset_pos();
// partner-><API key>(skill_id, target);
// return 1;
// partner->reset_pos();
// partner-><API key>(skill_id, target);
// if (!partner->data)
// return 1;
// partner->data->skill_id = 0;
// partner->data->ontick_time += <API key>(config);
// return 1;
}
struct <API key> <API key> =
{
.on_tick = partner_ai_tick_1,
.choose_target = choose_target,
};
|
#!/bin/sh
yum update
|
#ifndef TINYXML2_INCLUDED
#define TINYXML2_INCLUDED
#if defined(ANDROID_NDK) || defined(__BORLANDC__) || defined(__QNXNTO__)
# include <ctype.h>
# include <limits.h>
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# if defined(__PS3__)
# include <stddef.h>
# endif
#else
# include <cctype>
# include <climits>
# include <cstdio>
# include <cstdlib>
# include <cstring>
#endif
#include <stdint.h>
/*
TODO: intern strings instead of allocation.
*/
/*
gcc:
g++ -Wall -DDEBUG tinyxml2.cpp xmltest.cpp -o gccxmltest.exe
Formatting, Artistic Style:
AStyle.exe --style=1tbs --indent-switches --<API key> --indent-preprocessor tinyxml2.cpp tinyxml2.h
*/
#if defined( _DEBUG ) || defined( DEBUG ) || defined (__DEBUG__)
# ifndef DEBUG
# define DEBUG
# endif
#endif
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable: 4251)
#endif
#ifdef _WIN32
# ifdef TINYXML2_EXPORT
# define TINYXML2_LIB __declspec(dllexport)
# elif defined(TINYXML2_IMPORT)
# define TINYXML2_LIB __declspec(dllimport)
# else
# define TINYXML2_LIB
# endif
#elif __GNUC__ >= 4
# define TINYXML2_LIB __attribute__((visibility("default")))
#else
# define TINYXML2_LIB
#endif
#if defined(DEBUG)
# if defined(_MSC_VER)
# // "(void)0," is for suppressing C4127 warning in "assert(false)", "assert(true)" and the like
# define TIXMLASSERT( x ) if ( !((void)0,(x))) { __debugbreak(); }
# elif defined (ANDROID_NDK)
# include <android/log.h>
# define TIXMLASSERT( x ) if ( !(x)) { <API key>( "assert", "grinliz", "ASSERT in '%s' at %d.", __FILE__, __LINE__ ); }
# else
# include <assert.h>
# define TIXMLASSERT assert
# endif
#else
# define TIXMLASSERT( x ) {}
#endif
static const int <API key> = 4;
static const int <API key> = 0;
static const int <API key> = 1;
namespace tinyxml2
{
class XMLDocument;
class XMLElement;
class XMLAttribute;
class XMLComment;
class XMLText;
class XMLDeclaration;
class XMLUnknown;
class XMLPrinter;
/*
A class that wraps strings. Normally stores the start and end
pointers into the XML file itself, and will apply normalization
and entity translation if actually read. Can also store (and memory
manage) a traditional char[]
*/
class StrPair
{
public:
enum {
<API key> = 0x01,
<API key> = 0x02,
<API key> = 0x04,
TEXT_ELEMENT = <API key> | <API key>,
<API key> = <API key>,
ATTRIBUTE_NAME = 0,
ATTRIBUTE_VALUE = <API key> | <API key>,
<API key> = <API key>,
COMMENT = <API key>
};
StrPair() : _flags( 0 ), _start( 0 ), _end( 0 ) {}
~StrPair();
void Set( char* start, char* end, int flags ) {
TIXMLASSERT( start );
TIXMLASSERT( end );
Reset();
_start = start;
_end = end;
_flags = flags | NEEDS_FLUSH;
}
const char* GetStr();
bool Empty() const {
return _start == _end;
}
void SetInternedStr( const char* str ) {
Reset();
_start = const_cast<char*>(str);
}
void SetStr( const char* str, int flags=0 );
char* ParseText( char* in, const char* endTag, int strFlags );
char* ParseName( char* in );
void TransferTo( StrPair* other );
void Reset();
private:
void CollapseWhitespace();
enum {
NEEDS_FLUSH = 0x100,
NEEDS_DELETE = 0x200
};
int _flags;
char* _start;
char* _end;
StrPair( const StrPair& other ); // not supported
void operator=( StrPair& other ); // not supported, use TransferTo()
};
/*
A dynamic array of Plain Old Data. Doesn't support constructors, etc.
Has a small initial memory pool, so that low or no usage will not
cause a call to new/delete
*/
template <class T, int INITIAL_SIZE>
class DynArray
{
public:
DynArray() {
_mem = _pool;
_allocated = INITIAL_SIZE;
_size = 0;
}
~DynArray() {
if ( _mem != _pool ) {
delete [] _mem;
}
}
void Clear() {
_size = 0;
}
void Push( T t ) {
TIXMLASSERT( _size < INT_MAX );
EnsureCapacity( _size+1 );
_mem[_size] = t;
++_size;
}
T* PushArr( int count ) {
TIXMLASSERT( count >= 0 );
TIXMLASSERT( _size <= INT_MAX - count );
EnsureCapacity( _size+count );
T* ret = &_mem[_size];
_size += count;
return ret;
}
T Pop() {
TIXMLASSERT( _size > 0 );
--_size;
return _mem[_size];
}
void PopArr( int count ) {
TIXMLASSERT( _size >= count );
_size -= count;
}
bool Empty() const {
return _size == 0;
}
T& operator[](int i) {
TIXMLASSERT( i>= 0 && i < _size );
return _mem[i];
}
const T& operator[](int i) const {
TIXMLASSERT( i>= 0 && i < _size );
return _mem[i];
}
const T& PeekTop() const {
TIXMLASSERT( _size > 0 );
return _mem[ _size - 1];
}
int Size() const {
TIXMLASSERT( _size >= 0 );
return _size;
}
int Capacity() const {
TIXMLASSERT( _allocated >= INITIAL_SIZE );
return _allocated;
}
const T* Mem() const {
TIXMLASSERT( _mem );
return _mem;
}
T* Mem() {
TIXMLASSERT( _mem );
return _mem;
}
private:
DynArray( const DynArray& ); // not supported
void operator=( const DynArray& ); // not supported
void EnsureCapacity( int cap ) {
TIXMLASSERT( cap > 0 );
if ( cap > _allocated ) {
TIXMLASSERT( cap <= INT_MAX / 2 );
int newAllocated = cap * 2;
T* newMem = new T[newAllocated];
memcpy( newMem, _mem, sizeof(T)*_size ); // warning: not using constructors, only works for PODs
if ( _mem != _pool ) {
delete [] _mem;
}
_mem = newMem;
_allocated = newAllocated;
}
}
T* _mem;
T _pool[INITIAL_SIZE];
int _allocated; // objects allocated
int _size; // number objects in use
};
/*
Parent virtual class of a pool for fast allocation
and deallocation of objects.
*/
class MemPool
{
public:
MemPool() {}
virtual ~MemPool() {}
virtual int ItemSize() const = 0;
virtual void* Alloc() = 0;
virtual void Free( void* ) = 0;
virtual void SetTracked() = 0;
virtual void Clear() = 0;
};
/*
Template child class to create pools of the correct type.
*/
template< int ITEM_SIZE >
class MemPoolT : public MemPool
{
public:
MemPoolT() : _root(0), _currentAllocs(0), _nAllocs(0), _maxAllocs(0), _nUntracked(0) {}
~MemPoolT() {
Clear();
}
void Clear() {
// Delete the blocks.
while( !_blockPtrs.Empty()) {
Block* b = _blockPtrs.Pop();
delete b;
}
_root = 0;
_currentAllocs = 0;
_nAllocs = 0;
_maxAllocs = 0;
_nUntracked = 0;
}
virtual int ItemSize() const {
return ITEM_SIZE;
}
int CurrentAllocs() const {
return _currentAllocs;
}
virtual void* Alloc() {
if ( !_root ) {
// Need a new block.
Block* block = new Block();
_blockPtrs.Push( block );
Item* blockItems = block->items;
for( int i = 0; i < ITEMS_PER_BLOCK - 1; ++i ) {
blockItems[i].next = &(blockItems[i + 1]);
}
blockItems[ITEMS_PER_BLOCK - 1].next = 0;
_root = blockItems;
}
Item* const result = _root;
TIXMLASSERT( result != 0 );
_root = _root->next;
++_currentAllocs;
if ( _currentAllocs > _maxAllocs ) {
_maxAllocs = _currentAllocs;
}
++_nAllocs;
++_nUntracked;
return result;
}
virtual void Free( void* mem ) {
if ( !mem ) {
return;
}
--_currentAllocs;
Item* item = static_cast<Item*>( mem );
#ifdef DEBUG
memset( item, 0xfe, sizeof( *item ) );
#endif
item->next = _root;
_root = item;
}
void Trace( const char* name ) {
printf( "Mempool %s watermark=%d [%dk] current=%d size=%d nAlloc=%d blocks=%d\n",
name, _maxAllocs, _maxAllocs * ITEM_SIZE / 1024, _currentAllocs,
ITEM_SIZE, _nAllocs, _blockPtrs.Size() );
}
void SetTracked() {
--_nUntracked;
}
int Untracked() const {
return _nUntracked;
}
// This number is perf sensitive. 4k seems like a good tradeoff on my machine.
// The test file is large, 170k.
// Release: VS2010 gcc(no opt)
// 1k: 4000
// 2k: 4000
// 4k: 3900 21000
// 16k: 5200
// 32k: 4300
// 64k: 4000 21000
// Declared public because some compilers do not accept to use ITEMS_PER_BLOCK
// in private part if ITEMS_PER_BLOCK is private
enum { ITEMS_PER_BLOCK = (4 * 1024) / ITEM_SIZE };
private:
MemPoolT( const MemPoolT& ); // not supported
void operator=( const MemPoolT& ); // not supported
union Item {
Item* next;
char itemData[ITEM_SIZE];
};
struct Block {
Item items[ITEMS_PER_BLOCK];
};
DynArray< Block*, 10 > _blockPtrs;
Item* _root;
int _currentAllocs;
int _nAllocs;
int _maxAllocs;
int _nUntracked;
};
/**
Implements the interface to the "Visitor pattern" (see the Accept() method.)
If you call the Accept() method, it requires being passed a XMLVisitor
class to handle callbacks. For nodes that contain other nodes (Document, Element)
you will get called with a VisitEnter/VisitExit pair. Nodes that are always leafs
are simply called with Visit().
If you return 'true' from a Visit method, recursive parsing will continue. If you return
false, <b>no children of this node or its siblings</b> will be visited.
All flavors of Visit methods have a default implementation that returns 'true' (continue
visiting). You need to only override methods that are interesting to you.
Generally Accept() is called on the XMLDocument, although all nodes support visiting.
You should never change the document from a callback.
@sa XMLNode::Accept()
*/
class TINYXML2_LIB XMLVisitor
{
public:
virtual ~XMLVisitor() {}
Visit a document.
virtual bool VisitEnter( const XMLDocument& /*doc*/ ) {
return true;
}
Visit a document.
virtual bool VisitExit( const XMLDocument& /*doc*/ ) {
return true;
}
Visit an element.
virtual bool VisitEnter( const XMLElement& /*element*/, const XMLAttribute* /*firstAttribute*/ ) {
return true;
}
Visit an element.
virtual bool VisitExit( const XMLElement& /*element*/ ) {
return true;
}
Visit a declaration.
virtual bool Visit( const XMLDeclaration& /*declaration*/ ) {
return true;
}
Visit a text node.
virtual bool Visit( const XMLText& /*text*/ ) {
return true;
}
Visit a comment node.
virtual bool Visit( const XMLComment& /*comment*/ ) {
return true;
}
Visit an unknown node.
virtual bool Visit( const XMLUnknown& /*unknown*/ ) {
return true;
}
};
// WARNING: must match XMLDocument::_errorNames[]
enum XMLError {
XML_SUCCESS = 0,
XML_NO_ATTRIBUTE,
<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>,
XML_ERROR_PARSING,
<API key>,
XML_NO_TEXT_NODE,
XML_ERROR_COUNT
};
/*
Utility functionality.
*/
class XMLUtil
{
public:
static const char* SkipWhiteSpace( const char* p ) {
TIXMLASSERT( p );
while( IsWhiteSpace(*p) ) {
++p;
}
TIXMLASSERT( p );
return p;
}
static char* SkipWhiteSpace( char* p ) {
return const_cast<char*>( SkipWhiteSpace( const_cast<const char*>(p) ) );
}
// Anything in the high order range of UTF-8 is assumed to not be whitespace. This isn't
// correct, but simple, and usually works.
static bool IsWhiteSpace( char p ) {
return !IsUTF8Continuation(p) && isspace( static_cast<unsigned char>(p) );
}
inline static bool IsNameStartChar( unsigned char ch ) {
if ( ch >= 128 ) {
// This is a heuristic guess in attempt to not implement Unicode-aware isalpha()
return true;
}
if ( isalpha( ch ) ) {
return true;
}
return ch == ':' || ch == '_';
}
inline static bool IsNameChar( unsigned char ch ) {
return IsNameStartChar( ch )
|| isdigit( ch )
|| ch == '.'
|| ch == '-';
}
inline static bool StringEqual( const char* p, const char* q, int nChar=INT_MAX ) {
if ( p == q ) {
return true;
}
return strncmp( p, q, nChar ) == 0;
}
inline static bool IsUTF8Continuation( char p ) {
return ( p & 0x80 ) != 0;
}
static const char* ReadBOM( const char* p, bool* hasBOM );
// p is the starting location,
// the UTF-8 value of the entity will be placed in value, and length filled in.
static const char* GetCharacterRef( const char* p, char* value, int* length );
static void ConvertUTF32ToUTF8( unsigned long input, char* output, int* length );
// converts primitive types to strings
static void ToStr( int v, char* buffer, int bufferSize );
static void ToStr( unsigned v, char* buffer, int bufferSize );
static void ToStr( bool v, char* buffer, int bufferSize );
static void ToStr( float v, char* buffer, int bufferSize );
static void ToStr( double v, char* buffer, int bufferSize );
static void ToStr(int64_t v, char* buffer, int bufferSize);
// converts strings to primitive types
static bool ToInt( const char* str, int* value );
static bool ToUnsigned( const char* str, unsigned* value );
static bool ToBool( const char* str, bool* value );
static bool ToFloat( const char* str, float* value );
static bool ToDouble( const char* str, double* value );
static bool ToInt64(const char* str, int64_t* value);
};
/** XMLNode is a base class for every object that is in the
XML Document Object Model (DOM), except XMLAttributes.
Nodes have siblings, a parent, and children which can
be navigated. A node is always in a XMLDocument.
The type of a XMLNode can be queried, and it can
be cast to its more defined type.
A XMLDocument allocates memory for all its Nodes.
When the XMLDocument gets deleted, all its Nodes
will also be deleted.
@verbatim
A Document can contain: Element (container or leaf)
Comment (leaf)
Unknown (leaf)
Declaration( leaf )
An Element can contain: Element (container or leaf)
Text (leaf)
Attributes (not on tree)
Comment (leaf)
Unknown (leaf)
@endverbatim
*/
class TINYXML2_LIB XMLNode
{
friend class XMLDocument;
friend class XMLElement;
public:
Get the XMLDocument that owns this XMLNode.
const XMLDocument* GetDocument() const {
TIXMLASSERT( _document );
return _document;
}
Get the XMLDocument that owns this XMLNode.
XMLDocument* GetDocument() {
TIXMLASSERT( _document );
return _document;
}
Safely cast to an Element, or null.
virtual XMLElement* ToElement() {
return 0;
}
Safely cast to Text, or null.
virtual XMLText* ToText() {
return 0;
}
Safely cast to a Comment, or null.
virtual XMLComment* ToComment() {
return 0;
}
Safely cast to a Document, or null.
virtual XMLDocument* ToDocument() {
return 0;
}
Safely cast to a Declaration, or null.
virtual XMLDeclaration* ToDeclaration() {
return 0;
}
Safely cast to an Unknown, or null.
virtual XMLUnknown* ToUnknown() {
return 0;
}
virtual const XMLElement* ToElement() const {
return 0;
}
virtual const XMLText* ToText() const {
return 0;
}
virtual const XMLComment* ToComment() const {
return 0;
}
virtual const XMLDocument* ToDocument() const {
return 0;
}
virtual const XMLDeclaration* ToDeclaration() const {
return 0;
}
virtual const XMLUnknown* ToUnknown() const {
return 0;
}
/** The meaning of 'value' changes for the specific type.
@verbatim
Document: empty (NULL is returned, not an empty string)
Element: name of the element
Comment: the comment text
Unknown: the tag contents
Text: the text string
@endverbatim
*/
const char* Value() const;
/** Set the Value of an XML node.
@sa Value()
*/
void SetValue( const char* val, bool staticMem=false );
Get the parent of this node on the DOM.
const XMLNode* Parent() const {
return _parent;
}
XMLNode* Parent() {
return _parent;
}
Returns true if this node has no children.
bool NoChildren() const {
return !_firstChild;
}
Get the first child node, or null if none exists.
const XMLNode* FirstChild() const {
return _firstChild;
}
XMLNode* FirstChild() {
return _firstChild;
}
/** Get the first child element, or optionally the first child
element with the specified name.
*/
const XMLElement* FirstChildElement( const char* name = 0 ) const;
XMLElement* FirstChildElement( const char* name = 0 ) {
return const_cast<XMLElement*>(const_cast<const XMLNode*>(this)->FirstChildElement( name ));
}
Get the last child node, or null if none exists.
const XMLNode* LastChild() const {
return _lastChild;
}
XMLNode* LastChild() {
return _lastChild;
}
/** Get the last child element or optionally the last child
element with the specified name.
*/
const XMLElement* LastChildElement( const char* name = 0 ) const;
XMLElement* LastChildElement( const char* name = 0 ) {
return const_cast<XMLElement*>(const_cast<const XMLNode*>(this)->LastChildElement(name) );
}
Get the previous (left) sibling node of this node.
const XMLNode* PreviousSibling() const {
return _prev;
}
XMLNode* PreviousSibling() {
return _prev;
}
Get the previous (left) sibling element of this node, with an optionally supplied name.
const XMLElement* <API key>( const char* name = 0 ) const ;
XMLElement* <API key>( const char* name = 0 ) {
return const_cast<XMLElement*>(const_cast<const XMLNode*>(this)-><API key>( name ) );
}
Get the next (right) sibling node of this node.
const XMLNode* NextSibling() const {
return _next;
}
XMLNode* NextSibling() {
return _next;
}
Get the next (right) sibling element of this node, with an optionally supplied name.
const XMLElement* NextSiblingElement( const char* name = 0 ) const;
XMLElement* NextSiblingElement( const char* name = 0 ) {
return const_cast<XMLElement*>(const_cast<const XMLNode*>(this)->NextSiblingElement( name ) );
}
/**
Add a child node as the last (right) child.
If the child node is already part of the document,
it is moved from its old location to the new location.
Returns the addThis argument or 0 if the node does not
belong to the same document.
*/
XMLNode* InsertEndChild( XMLNode* addThis );
XMLNode* LinkEndChild( XMLNode* addThis ) {
return InsertEndChild( addThis );
}
/**
Add a child node as the first (left) child.
If the child node is already part of the document,
it is moved from its old location to the new location.
Returns the addThis argument or 0 if the node does not
belong to the same document.
*/
XMLNode* InsertFirstChild( XMLNode* addThis );
/**
Add a node after the specified child node.
If the child node is already part of the document,
it is moved from its old location to the new location.
Returns the addThis argument or 0 if the afterThis node
is not a child of this node, or if the node does not
belong to the same document.
*/
XMLNode* InsertAfterChild( XMLNode* afterThis, XMLNode* addThis );
/**
Delete all the children of this node.
*/
void DeleteChildren();
/**
Delete a child of this node.
*/
void DeleteChild( XMLNode* node );
/**
Make a copy of this node, but not its children.
You may pass in a Document pointer that will be
the owner of the new Node. If the 'document' is
null, then the node returned will be allocated
from the current Document. (this->GetDocument())
Note: if called on a XMLDocument, this will return null.
*/
virtual XMLNode* ShallowClone( XMLDocument* document ) const = 0;
/**
Test if 2 nodes are the same, but don't test children.
The 2 nodes do not need to be in the same Document.
Note: if called on a XMLDocument, this will return false.
*/
virtual bool ShallowEqual( const XMLNode* compare ) const = 0;
virtual bool Accept( XMLVisitor* visitor ) const = 0;
/**
Set user data into the XMLNode. TinyXML-2 in
no way processes or interprets user data.
It is initially 0.
*/
void SetUserData(void* userData) { _userData = userData; }
/**
Get user data set into the XMLNode. TinyXML-2 in
no way processes or interprets user data.
It is initially 0.
*/
void* GetUserData() const { return _userData; }
protected:
XMLNode( XMLDocument* );
virtual ~XMLNode();
virtual char* ParseDeep( char*, StrPair* );
XMLDocument* _document;
XMLNode* _parent;
mutable StrPair _value;
XMLNode* _firstChild;
XMLNode* _lastChild;
XMLNode* _prev;
XMLNode* _next;
void* _userData;
private:
MemPool* _memPool;
void Unlink( XMLNode* child );
static void DeleteNode( XMLNode* node );
void InsertChildPreamble( XMLNode* insertThis ) const;
XMLNode( const XMLNode& ); // not supported
XMLNode& operator=( const XMLNode& ); // not supported
};
/** XML text.
Note that a text node can have child element nodes, for example:
@verbatim
<root>This is <b>bold</b></root>
@endverbatim
A text node can have 2 ways to output the next. "normal" output
and CDATA. It will default to the mode it was parsed from the XML file and
you generally want to leave it alone, but you can change the output mode with
SetCData() and query it with CData().
*/
class TINYXML2_LIB XMLText : public XMLNode
{
friend class XMLDocument;
public:
virtual bool Accept( XMLVisitor* visitor ) const;
virtual XMLText* ToText() {
return this;
}
virtual const XMLText* ToText() const {
return this;
}
Declare whether this should be CDATA or standard text.
void SetCData( bool isCData ) {
_isCData = isCData;
}
Returns true if this is a CDATA text element.
bool CData() const {
return _isCData;
}
virtual XMLNode* ShallowClone( XMLDocument* document ) const;
virtual bool ShallowEqual( const XMLNode* compare ) const;
protected:
XMLText( XMLDocument* doc ) : XMLNode( doc ), _isCData( false ) {}
virtual ~XMLText() {}
char* ParseDeep( char*, StrPair* endTag );
private:
bool _isCData;
XMLText( const XMLText& ); // not supported
XMLText& operator=( const XMLText& ); // not supported
};
/** An XML Comment. */
class TINYXML2_LIB XMLComment : public XMLNode
{
friend class XMLDocument;
public:
virtual XMLComment* ToComment() {
return this;
}
virtual const XMLComment* ToComment() const {
return this;
}
virtual bool Accept( XMLVisitor* visitor ) const;
virtual XMLNode* ShallowClone( XMLDocument* document ) const;
virtual bool ShallowEqual( const XMLNode* compare ) const;
protected:
XMLComment( XMLDocument* doc );
virtual ~XMLComment();
char* ParseDeep( char*, StrPair* endTag );
private:
XMLComment( const XMLComment& ); // not supported
XMLComment& operator=( const XMLComment& ); // not supported
};
/** In correct XML the declaration is the first entry in the file.
@verbatim
<?xml version="1.0" standalone="yes"?>
@endverbatim
TinyXML-2 will happily read or write files without a declaration,
however.
The text of the declaration isn't interpreted. It is parsed
and written as a string.
*/
class TINYXML2_LIB XMLDeclaration : public XMLNode
{
friend class XMLDocument;
public:
virtual XMLDeclaration* ToDeclaration() {
return this;
}
virtual const XMLDeclaration* ToDeclaration() const {
return this;
}
virtual bool Accept( XMLVisitor* visitor ) const;
virtual XMLNode* ShallowClone( XMLDocument* document ) const;
virtual bool ShallowEqual( const XMLNode* compare ) const;
protected:
XMLDeclaration( XMLDocument* doc );
virtual ~XMLDeclaration();
char* ParseDeep( char*, StrPair* endTag );
private:
XMLDeclaration( const XMLDeclaration& ); // not supported
XMLDeclaration& operator=( const XMLDeclaration& ); // not supported
};
/** Any tag that TinyXML-2 doesn't recognize is saved as an
unknown. It is a tag of text, but should not be modified.
It will be written back to the XML, unchanged, when the file
is saved.
DTD tags get thrown into XMLUnknowns.
*/
class TINYXML2_LIB XMLUnknown : public XMLNode
{
friend class XMLDocument;
public:
virtual XMLUnknown* ToUnknown() {
return this;
}
virtual const XMLUnknown* ToUnknown() const {
return this;
}
virtual bool Accept( XMLVisitor* visitor ) const;
virtual XMLNode* ShallowClone( XMLDocument* document ) const;
virtual bool ShallowEqual( const XMLNode* compare ) const;
protected:
XMLUnknown( XMLDocument* doc );
virtual ~XMLUnknown();
char* ParseDeep( char*, StrPair* endTag );
private:
XMLUnknown( const XMLUnknown& ); // not supported
XMLUnknown& operator=( const XMLUnknown& ); // not supported
};
/** An attribute is a name-value pair. Elements have an arbitrary
number of attributes, each with a unique name.
@note The attributes are not XMLNodes. You may only query the
Next() attribute in a list.
*/
class TINYXML2_LIB XMLAttribute
{
friend class XMLElement;
public:
The name of the attribute.
const char* Name() const;
The value of the attribute.
const char* Value() const;
The next attribute in the list.
const XMLAttribute* Next() const {
return _next;
}
/** IntValue interprets the attribute as an integer, and returns the value.
If the value isn't an integer, 0 will be returned. There is no error checking;
use QueryIntValue() if you need error checking.
*/
int IntValue() const {
int i = 0;
QueryIntValue(&i);
return i;
}
int64_t Int64Value() const {
int64_t i = 0;
QueryInt64Value(&i);
return i;
}
Query as an unsigned integer. See IntValue()
unsigned UnsignedValue() const {
unsigned i=0;
QueryUnsignedValue( &i );
return i;
}
Query as a boolean. See IntValue()
bool BoolValue() const {
bool b=false;
QueryBoolValue( &b );
return b;
}
Query as a double. See IntValue()
double DoubleValue() const {
double d=0;
QueryDoubleValue( &d );
return d;
}
Query as a float. See IntValue()
float FloatValue() const {
float f=0;
QueryFloatValue( &f );
return f;
}
/** QueryIntValue interprets the attribute as an integer, and returns the value
in the provided parameter. The function will return XML_SUCCESS on success,
and <API key> if the conversion is not successful.
*/
XMLError QueryIntValue( int* value ) const;
See QueryIntValue
XMLError QueryUnsignedValue( unsigned int* value ) const;
See QueryIntValue
XMLError QueryInt64Value(int64_t* value) const;
See QueryIntValue
XMLError QueryBoolValue( bool* value ) const;
See QueryIntValue
XMLError QueryDoubleValue( double* value ) const;
See QueryIntValue
XMLError QueryFloatValue( float* value ) const;
Set the attribute to a string value.
void SetAttribute( const char* value );
Set the attribute to value.
void SetAttribute( int value );
Set the attribute to value.
void SetAttribute( unsigned value );
Set the attribute to value.
void SetAttribute(int64_t value);
Set the attribute to value.
void SetAttribute( bool value );
Set the attribute to value.
void SetAttribute( double value );
Set the attribute to value.
void SetAttribute( float value );
private:
enum { BUF_SIZE = 200 };
XMLAttribute() : _next( 0 ), _memPool( 0 ) {}
virtual ~XMLAttribute() {}
XMLAttribute( const XMLAttribute& ); // not supported
void operator=( const XMLAttribute& ); // not supported
void SetName( const char* name );
char* ParseDeep( char* p, bool processEntities );
mutable StrPair _name;
mutable StrPair _value;
XMLAttribute* _next;
MemPool* _memPool;
};
/** The element is a container class. It has a value, the element name,
and can contain other elements, text, comments, and unknowns.
Elements also contain an arbitrary number of attributes.
*/
class TINYXML2_LIB XMLElement : public XMLNode
{
friend class XMLDocument;
public:
Get the name of an element (which is the Value() of the node.)
const char* Name() const {
return Value();
}
Set the name of the element.
void SetName( const char* str, bool staticMem=false ) {
SetValue( str, staticMem );
}
virtual XMLElement* ToElement() {
return this;
}
virtual const XMLElement* ToElement() const {
return this;
}
virtual bool Accept( XMLVisitor* visitor ) const;
/** Given an attribute name, Attribute() returns the value
for the attribute of that name, or null if none
exists. For example:
@verbatim
const char* value = ele->Attribute( "foo" );
@endverbatim
The 'value' parameter is normally null. However, if specified,
the attribute will only be returned if the 'name' and 'value'
match. This allow you to write code:
@verbatim
if ( ele->Attribute( "foo", "bar" ) ) callFooIsBar();
@endverbatim
rather than:
@verbatim
if ( ele->Attribute( "foo" ) ) {
if ( strcmp( ele->Attribute( "foo" ), "bar" ) == 0 ) callFooIsBar();
}
@endverbatim
*/
const char* Attribute( const char* name, const char* value=0 ) const;
/** Given an attribute name, IntAttribute() returns the value
of the attribute interpreted as an integer. 0 will be
returned if there is an error. For a method with error
checking, see QueryIntAttribute()
*/
int IntAttribute( const char* name ) const {
int i=0;
QueryIntAttribute( name, &i );
return i;
}
See IntAttribute()
unsigned UnsignedAttribute( const char* name ) const {
unsigned i=0;
<API key>( name, &i );
return i;
}
See IntAttribute()
int64_t Int64Attribute(const char* name) const {
int64_t i = 0;
QueryInt64Attribute(name, &i);
return i;
}
See IntAttribute()
bool BoolAttribute( const char* name ) const {
bool b=false;
QueryBoolAttribute( name, &b );
return b;
}
See IntAttribute()
double DoubleAttribute( const char* name ) const {
double d=0;
<API key>( name, &d );
return d;
}
See IntAttribute()
float FloatAttribute( const char* name ) const {
float f=0;
QueryFloatAttribute( name, &f );
return f;
}
/** Given an attribute name, QueryIntAttribute() returns
XML_SUCCESS, <API key> if the conversion
can't be performed, or XML_NO_ATTRIBUTE if the attribute
doesn't exist. If successful, the result of the conversion
will be written to 'value'. If not successful, nothing will
be written to 'value'. This allows you to provide default
value:
@verbatim
int value = 10;
QueryIntAttribute( "foo", &value ); // if "foo" isn't found, value will still be 10
@endverbatim
*/
XMLError QueryIntAttribute( const char* name, int* value ) const {
const XMLAttribute* a = FindAttribute( name );
if ( !a ) {
return XML_NO_ATTRIBUTE;
}
return a->QueryIntValue( value );
}
See QueryIntAttribute()
XMLError <API key>( const char* name, unsigned int* value ) const {
const XMLAttribute* a = FindAttribute( name );
if ( !a ) {
return XML_NO_ATTRIBUTE;
}
return a->QueryUnsignedValue( value );
}
See QueryIntAttribute()
XMLError QueryInt64Attribute(const char* name, int64_t* value) const {
const XMLAttribute* a = FindAttribute(name);
if (!a) {
return XML_NO_ATTRIBUTE;
}
return a->QueryInt64Value(value);
}
See QueryIntAttribute()
XMLError QueryBoolAttribute( const char* name, bool* value ) const {
const XMLAttribute* a = FindAttribute( name );
if ( !a ) {
return XML_NO_ATTRIBUTE;
}
return a->QueryBoolValue( value );
}
See QueryIntAttribute()
XMLError <API key>( const char* name, double* value ) const {
const XMLAttribute* a = FindAttribute( name );
if ( !a ) {
return XML_NO_ATTRIBUTE;
}
return a->QueryDoubleValue( value );
}
See QueryIntAttribute()
XMLError QueryFloatAttribute( const char* name, float* value ) const {
const XMLAttribute* a = FindAttribute( name );
if ( !a ) {
return XML_NO_ATTRIBUTE;
}
return a->QueryFloatValue( value );
}
/** Given an attribute name, QueryAttribute() returns
XML_SUCCESS, <API key> if the conversion
can't be performed, or XML_NO_ATTRIBUTE if the attribute
doesn't exist. It is overloaded for the primitive types,
and is a generally more convenient replacement of
QueryIntAttribute() and related functions.
If successful, the result of the conversion
will be written to 'value'. If not successful, nothing will
be written to 'value'. This allows you to provide default
value:
@verbatim
int value = 10;
QueryAttribute( "foo", &value ); // if "foo" isn't found, value will still be 10
@endverbatim
*/
int QueryAttribute( const char* name, int* value ) const {
return QueryIntAttribute( name, value );
}
int QueryAttribute( const char* name, unsigned int* value ) const {
return <API key>( name, value );
}
int QueryAttribute(const char* name, int64_t* value) const {
return QueryInt64Attribute(name, value);
}
int QueryAttribute( const char* name, bool* value ) const {
return QueryBoolAttribute( name, value );
}
int QueryAttribute( const char* name, double* value ) const {
return <API key>( name, value );
}
int QueryAttribute( const char* name, float* value ) const {
return QueryFloatAttribute( name, value );
}
Sets the named attribute to value.
void SetAttribute( const char* name, const char* value ) {
XMLAttribute* a = <API key>( name );
a->SetAttribute( value );
}
Sets the named attribute to value.
void SetAttribute( const char* name, int value ) {
XMLAttribute* a = <API key>( name );
a->SetAttribute( value );
}
Sets the named attribute to value.
void SetAttribute( const char* name, unsigned value ) {
XMLAttribute* a = <API key>( name );
a->SetAttribute( value );
}
Sets the named attribute to value.
void SetAttribute(const char* name, int64_t value) {
XMLAttribute* a = <API key>(name);
a->SetAttribute(value);
}
Sets the named attribute to value.
void SetAttribute( const char* name, bool value ) {
XMLAttribute* a = <API key>( name );
a->SetAttribute( value );
}
Sets the named attribute to value.
void SetAttribute( const char* name, double value ) {
XMLAttribute* a = <API key>( name );
a->SetAttribute( value );
}
Sets the named attribute to value.
void SetAttribute( const char* name, float value ) {
XMLAttribute* a = <API key>( name );
a->SetAttribute( value );
}
/**
Delete an attribute.
*/
void DeleteAttribute( const char* name );
Return the first attribute in the list.
const XMLAttribute* FirstAttribute() const {
return _rootAttribute;
}
Query a specific attribute in the list.
const XMLAttribute* FindAttribute( const char* name ) const;
/** Convenience function for easy access to the text inside an element. Although easy
and concise, GetText() is limited compared to getting the XMLText child
and accessing it directly.
If the first child of 'this' is a XMLText, the GetText()
returns the character string of the Text node, else null is returned.
This is a convenient method for getting the text of simple contained text:
@verbatim
<foo>This is text</foo>
const char* str = fooElement->GetText();
@endverbatim
'str' will be a pointer to "This is text".
Note that this function can be misleading. If the element foo was created from
this XML:
@verbatim
<foo><b>This is text</b></foo>
@endverbatim
then the value of str would be null. The first child node isn't a text node, it is
another element. From this XML:
@verbatim
<foo>This is <b>text</b></foo>
@endverbatim
GetText() will return "This is ".
*/
const char* GetText() const;
/** Convenience function for easy access to the text inside an element. Although easy
and concise, SetText() is limited compared to creating an XMLText child
and mutating it directly.
If the first child of 'this' is a XMLText, SetText() sets its value to
the given string, otherwise it will create a first child that is an XMLText.
This is a convenient method for setting the text of simple contained text:
@verbatim
<foo>This is text</foo>
fooElement->SetText( "Hullaballoo!" );
<foo>Hullaballoo!</foo>
@endverbatim
Note that this function can be misleading. If the element foo was created from
this XML:
@verbatim
<foo><b>This is text</b></foo>
@endverbatim
then it will not change "This is text", but rather prefix it with a text element:
@verbatim
<foo>Hullaballoo!<b>This is text</b></foo>
@endverbatim
For this XML:
@verbatim
<foo />
@endverbatim
SetText() will generate
@verbatim
<foo>Hullaballoo!</foo>
@endverbatim
*/
void SetText( const char* inText );
Convenience method for setting text inside an element. See SetText() for important limitations.
void SetText( int value );
Convenience method for setting text inside an element. See SetText() for important limitations.
void SetText( unsigned value );
Convenience method for setting text inside an element. See SetText() for important limitations.
void SetText(int64_t value);
Convenience method for setting text inside an element. See SetText() for important limitations.
void SetText( bool value );
Convenience method for setting text inside an element. See SetText() for important limitations.
void SetText( double value );
Convenience method for setting text inside an element. See SetText() for important limitations.
void SetText( float value );
/**
Convenience method to query the value of a child text node. This is probably best
shown by example. Given you have a document is this form:
@verbatim
<point>
<x>1</x>
<y>1.4</y>
</point>
@endverbatim
The QueryIntText() and similar functions provide a safe and easier way to get to the
"value" of x and y.
@verbatim
int x = 0;
float y = 0; // types of x and y are contrived for example
const XMLElement* xElement = pointElement->FirstChildElement( "x" );
const XMLElement* yElement = pointElement->FirstChildElement( "y" );
xElement->QueryIntText( &x );
yElement->QueryFloatText( &y );
@endverbatim
@returns XML_SUCCESS (0) on success, <API key> if the text cannot be converted
to the requested type, and XML_NO_TEXT_NODE if there is no child text to query.
*/
XMLError QueryIntText( int* ival ) const;
See QueryIntText()
XMLError QueryUnsignedText( unsigned* uval ) const;
See QueryIntText()
XMLError QueryInt64Text(int64_t* uval) const;
See QueryIntText()
XMLError QueryBoolText( bool* bval ) const;
See QueryIntText()
XMLError QueryDoubleText( double* dval ) const;
See QueryIntText()
XMLError QueryFloatText( float* fval ) const;
// internal:
enum {
OPEN, // <foo>
CLOSED, // <foo/>
CLOSING // </foo>
};
int ClosingType() const {
return _closingType;
}
virtual XMLNode* ShallowClone( XMLDocument* document ) const;
virtual bool ShallowEqual( const XMLNode* compare ) const;
protected:
char* ParseDeep( char* p, StrPair* endTag );
private:
XMLElement( XMLDocument* doc );
virtual ~XMLElement();
XMLElement( const XMLElement& ); // not supported
void operator=( const XMLElement& ); // not supported
XMLAttribute* FindAttribute( const char* name ) {
return const_cast<XMLAttribute*>(const_cast<const XMLElement*>(this)->FindAttribute( name ));
}
XMLAttribute* <API key>( const char* name );
//void LinkAttribute( XMLAttribute* attrib );
char* ParseAttributes( char* p );
static void DeleteAttribute( XMLAttribute* attribute );
enum { BUF_SIZE = 200 };
int _closingType;
// The attribute list is ordered; there is no 'lastAttribute'
// because the list needs to be scanned for dupes before adding
// a new attribute.
XMLAttribute* _rootAttribute;
};
enum Whitespace {
PRESERVE_WHITESPACE,
COLLAPSE_WHITESPACE
};
/** A Document binds together all the functionality.
It can be saved, loaded, and printed to the screen.
All Nodes are connected and allocated to a Document.
If the Document is deleted, all its Nodes are also deleted.
*/
class TINYXML2_LIB XMLDocument : public XMLNode
{
friend class XMLElement;
public:
constructor
XMLDocument( bool processEntities = true, Whitespace = PRESERVE_WHITESPACE );
~XMLDocument();
virtual XMLDocument* ToDocument() {
TIXMLASSERT( this == _document );
return this;
}
virtual const XMLDocument* ToDocument() const {
TIXMLASSERT( this == _document );
return this;
}
/**
Parse an XML file from a character string.
Returns XML_SUCCESS (0) on success, or
an errorID.
You may optionally pass in the 'nBytes', which is
the number of bytes which will be parsed. If not
specified, TinyXML-2 will assume 'xml' points to a
null terminated string.
*/
XMLError Parse( const char* xml, size_t nBytes=(size_t)(-1) );
/**
Load an XML file from disk.
Returns XML_SUCCESS (0) on success, or
an errorID.
*/
XMLError LoadFile( const char* filename );
/**
Load an XML file from disk. You are responsible
for providing and closing the FILE*.
NOTE: The file should be opened as binary ("rb")
not text in order for TinyXML-2 to correctly
do newline normalization.
Returns XML_SUCCESS (0) on success, or
an errorID.
*/
XMLError LoadFile( FILE* );
/**
Save the XML file to disk.
Returns XML_SUCCESS (0) on success, or
an errorID.
*/
XMLError SaveFile( const char* filename, bool compact = false );
/**
Save the XML file to disk. You are responsible
for providing and closing the FILE*.
Returns XML_SUCCESS (0) on success, or
an errorID.
*/
XMLError SaveFile( FILE* fp, bool compact = false );
bool ProcessEntities() const {
return _processEntities;
}
Whitespace WhitespaceMode() const {
return _whitespace;
}
/**
Returns true if this document has a leading Byte Order Mark of UTF8.
*/
bool HasBOM() const {
return _writeBOM;
}
/** Sets whether to write the BOM when writing the file.
*/
void SetBOM( bool useBOM ) {
_writeBOM = useBOM;
}
/** Return the root element of DOM. Equivalent to FirstChildElement().
To get the first node, use FirstChild().
*/
XMLElement* RootElement() {
return FirstChildElement();
}
const XMLElement* RootElement() const {
return FirstChildElement();
}
/** Print the Document. If the Printer is not provided, it will
print to stdout. If you provide Printer, this can print to a file:
@verbatim
XMLPrinter printer( fp );
doc.Print( &printer );
@endverbatim
Or you can use a printer to print to memory:
@verbatim
XMLPrinter printer;
doc.Print( &printer );
// printer.CStr() has a const char* to the XML
@endverbatim
*/
void Print( XMLPrinter* streamer=0 ) const;
virtual bool Accept( XMLVisitor* visitor ) const;
/**
Create a new Element associated with
this Document. The memory for the Element
is managed by the Document.
*/
XMLElement* NewElement( const char* name );
/**
Create a new Comment associated with
this Document. The memory for the Comment
is managed by the Document.
*/
XMLComment* NewComment( const char* comment );
/**
Create a new Text associated with
this Document. The memory for the Text
is managed by the Document.
*/
XMLText* NewText( const char* text );
/**
Create a new Declaration associated with
this Document. The memory for the object
is managed by the Document.
If the 'text' param is null, the standard
declaration is used.:
@verbatim
<?xml version="1.0" encoding="UTF-8"?>
@endverbatim
*/
XMLDeclaration* NewDeclaration( const char* text=0 );
/**
Create a new Unknown associated with
this Document. The memory for the object
is managed by the Document.
*/
XMLUnknown* NewUnknown( const char* text );
/**
Delete a node associated with this document.
It will be unlinked from the DOM.
*/
void DeleteNode( XMLNode* node );
void SetError( XMLError error, const char* str1, const char* str2 );
Return true if there was an error parsing the document.
bool Error() const {
return _errorID != XML_SUCCESS;
}
Return the errorID.
XMLError ErrorID() const {
return _errorID;
}
const char* ErrorName() const;
Return a possibly helpful diagnostic location or string.
const char* GetErrorStr1() const {
return _errorStr1.GetStr();
}
Return a possibly helpful secondary diagnostic location or string.
const char* GetErrorStr2() const {
return _errorStr2.GetStr();
}
If there is an error, print it to stdout.
void PrintError() const;
Clear the document, resetting it to the initial state.
void Clear();
// internal
char* Identify( char* p, XMLNode** node );
virtual XMLNode* ShallowClone( XMLDocument* /*document*/ ) const {
return 0;
}
virtual bool ShallowEqual( const XMLNode* /*compare*/ ) const {
return false;
}
private:
XMLDocument( const XMLDocument& ); // not supported
void operator=( const XMLDocument& ); // not supported
bool _writeBOM;
bool _processEntities;
XMLError _errorID;
Whitespace _whitespace;
mutable StrPair _errorStr1;
mutable StrPair _errorStr2;
char* _charBuffer;
MemPoolT< sizeof(XMLElement) > _elementPool;
MemPoolT< sizeof(XMLAttribute) > _attributePool;
MemPoolT< sizeof(XMLText) > _textPool;
MemPoolT< sizeof(XMLComment) > _commentPool;
static const char* _errorNames[XML_ERROR_COUNT];
void Parse();
};
/**
A XMLHandle is a class that wraps a node pointer with null checks; this is
an incredibly useful thing. Note that XMLHandle is not part of the TinyXML-2
DOM structure. It is a separate utility class.
Take an example:
@verbatim
<Document>
<Element attributeA = "valueA">
<Child attributeB = "value1" />
<Child attributeB = "value2" />
</Element>
</Document>
@endverbatim
Assuming you want the value of "attributeB" in the 2nd "Child" element, it's very
easy to write a *lot* of code that looks like:
@verbatim
XMLElement* root = document.FirstChildElement( "Document" );
if ( root )
{
XMLElement* element = root->FirstChildElement( "Element" );
if ( element )
{
XMLElement* child = element->FirstChildElement( "Child" );
if ( child )
{
XMLElement* child2 = child->NextSiblingElement( "Child" );
if ( child2 )
{
// Finally do something useful.
@endverbatim
And that doesn't even cover "else" cases. XMLHandle addresses the verbosity
of such code. A XMLHandle checks for null pointers so it is perfectly safe
and correct to use:
@verbatim
XMLHandle docHandle( &document );
XMLElement* child2 = docHandle.FirstChildElement( "Document" ).FirstChildElement( "Element" ).FirstChildElement().NextSiblingElement();
if ( child2 )
{
// do something useful
@endverbatim
Which is MUCH more concise and useful.
It is also safe to copy handles - internally they are nothing more than node pointers.
@verbatim
XMLHandle handleCopy = handle;
@endverbatim
See also XMLConstHandle, which is the same as XMLHandle, but operates on const objects.
*/
class TINYXML2_LIB XMLHandle
{
public:
Create a handle from any node (at any depth of the tree.) This can be a null pointer.
XMLHandle( XMLNode* node ) {
_node = node;
}
Create a handle from a node.
XMLHandle( XMLNode& node ) {
_node = &node;
}
Copy constructor
XMLHandle( const XMLHandle& ref ) {
_node = ref._node;
}
Assignment
XMLHandle& operator=( const XMLHandle& ref ) {
_node = ref._node;
return *this;
}
Get the first child of this handle.
XMLHandle FirstChild() {
return XMLHandle( _node ? _node->FirstChild() : 0 );
}
Get the first child element of this handle.
XMLHandle FirstChildElement( const char* name = 0 ) {
return XMLHandle( _node ? _node->FirstChildElement( name ) : 0 );
}
Get the last child of this handle.
XMLHandle LastChild() {
return XMLHandle( _node ? _node->LastChild() : 0 );
}
Get the last child element of this handle.
XMLHandle LastChildElement( const char* name = 0 ) {
return XMLHandle( _node ? _node->LastChildElement( name ) : 0 );
}
Get the previous sibling of this handle.
XMLHandle PreviousSibling() {
return XMLHandle( _node ? _node->PreviousSibling() : 0 );
}
Get the previous sibling element of this handle.
XMLHandle <API key>( const char* name = 0 ) {
return XMLHandle( _node ? _node-><API key>( name ) : 0 );
}
Get the next sibling of this handle.
XMLHandle NextSibling() {
return XMLHandle( _node ? _node->NextSibling() : 0 );
}
Get the next sibling element of this handle.
XMLHandle NextSiblingElement( const char* name = 0 ) {
return XMLHandle( _node ? _node->NextSiblingElement( name ) : 0 );
}
Safe cast to XMLNode. This can return null.
XMLNode* ToNode() {
return _node;
}
Safe cast to XMLElement. This can return null.
XMLElement* ToElement() {
return ( ( _node == 0 ) ? 0 : _node->ToElement() );
}
Safe cast to XMLText. This can return null.
XMLText* ToText() {
return ( ( _node == 0 ) ? 0 : _node->ToText() );
}
Safe cast to XMLUnknown. This can return null.
XMLUnknown* ToUnknown() {
return ( ( _node == 0 ) ? 0 : _node->ToUnknown() );
}
Safe cast to XMLDeclaration. This can return null.
XMLDeclaration* ToDeclaration() {
return ( ( _node == 0 ) ? 0 : _node->ToDeclaration() );
}
private:
XMLNode* _node;
};
/**
A variant of the XMLHandle class for working with const XMLNodes and Documents. It is the
same in all regards, except for the 'const' qualifiers. See XMLHandle for API.
*/
class TINYXML2_LIB XMLConstHandle
{
public:
XMLConstHandle( const XMLNode* node ) {
_node = node;
}
XMLConstHandle( const XMLNode& node ) {
_node = &node;
}
XMLConstHandle( const XMLConstHandle& ref ) {
_node = ref._node;
}
XMLConstHandle& operator=( const XMLConstHandle& ref ) {
_node = ref._node;
return *this;
}
const XMLConstHandle FirstChild() const {
return XMLConstHandle( _node ? _node->FirstChild() : 0 );
}
const XMLConstHandle FirstChildElement( const char* name = 0 ) const {
return XMLConstHandle( _node ? _node->FirstChildElement( name ) : 0 );
}
const XMLConstHandle LastChild() const {
return XMLConstHandle( _node ? _node->LastChild() : 0 );
}
const XMLConstHandle LastChildElement( const char* name = 0 ) const {
return XMLConstHandle( _node ? _node->LastChildElement( name ) : 0 );
}
const XMLConstHandle PreviousSibling() const {
return XMLConstHandle( _node ? _node->PreviousSibling() : 0 );
}
const XMLConstHandle <API key>( const char* name = 0 ) const {
return XMLConstHandle( _node ? _node-><API key>( name ) : 0 );
}
const XMLConstHandle NextSibling() const {
return XMLConstHandle( _node ? _node->NextSibling() : 0 );
}
const XMLConstHandle NextSiblingElement( const char* name = 0 ) const {
return XMLConstHandle( _node ? _node->NextSiblingElement( name ) : 0 );
}
const XMLNode* ToNode() const {
return _node;
}
const XMLElement* ToElement() const {
return ( ( _node == 0 ) ? 0 : _node->ToElement() );
}
const XMLText* ToText() const {
return ( ( _node == 0 ) ? 0 : _node->ToText() );
}
const XMLUnknown* ToUnknown() const {
return ( ( _node == 0 ) ? 0 : _node->ToUnknown() );
}
const XMLDeclaration* ToDeclaration() const {
return ( ( _node == 0 ) ? 0 : _node->ToDeclaration() );
}
private:
const XMLNode* _node;
};
/**
Printing functionality. The XMLPrinter gives you more
options than the XMLDocument::Print() method.
It can:
-# Print to memory.
-# Print to a file you provide.
-# Print XML without a XMLDocument.
Print to Memory
@verbatim
XMLPrinter printer;
doc.Print( &printer );
SomeFunction( printer.CStr() );
@endverbatim
Print to a File
You provide the file pointer.
@verbatim
XMLPrinter printer( fp );
doc.Print( &printer );
@endverbatim
Print without a XMLDocument
When loading, an XML parser is very useful. However, sometimes
when saving, it just gets in the way. The code is often set up
for streaming, and constructing the DOM is just overhead.
The Printer supports the streaming case. The following code
prints out a trivially simple XML file without ever creating
an XML document.
@verbatim
XMLPrinter printer( fp );
printer.OpenElement( "foo" );
printer.PushAttribute( "foo", "bar" );
printer.CloseElement();
@endverbatim
*/
class TINYXML2_LIB XMLPrinter : public XMLVisitor
{
public:
/** Construct the printer. If the FILE* is specified,
this will print to the FILE. Else it will print
to memory, and the result is available in CStr().
If 'compact' is set to true, then output is created
with only required whitespace and newlines.
*/
XMLPrinter( FILE* file=0, bool compact = false, int depth = 0 );
virtual ~XMLPrinter() {}
/** If streaming, write the BOM and declaration. */
void PushHeader( bool writeBOM, bool writeDeclaration );
/** If streaming, start writing an element.
The element must be closed with CloseElement()
*/
void OpenElement( const char* name, bool compactMode=false );
If streaming, add an attribute to an open element.
void PushAttribute( const char* name, const char* value );
void PushAttribute( const char* name, int value );
void PushAttribute( const char* name, unsigned value );
void PushAttribute(const char* name, int64_t value);
void PushAttribute( const char* name, bool value );
void PushAttribute( const char* name, double value );
If streaming, close the Element.
virtual void CloseElement( bool compactMode=false );
Add a text node.
void PushText( const char* text, bool cdata=false );
Add a text node from an integer.
void PushText( int value );
Add a text node from an unsigned.
void PushText( unsigned value );
Add a text node from an unsigned.
void PushText(int64_t value);
Add a text node from a bool.
void PushText( bool value );
Add a text node from a float.
void PushText( float value );
Add a text node from a double.
void PushText( double value );
Add a comment
void PushComment( const char* comment );
void PushDeclaration( const char* value );
void PushUnknown( const char* value );
virtual bool VisitEnter( const XMLDocument& /*doc*/ );
virtual bool VisitExit( const XMLDocument& /*doc*/ ) {
return true;
}
virtual bool VisitEnter( const XMLElement& element, const XMLAttribute* attribute );
virtual bool VisitExit( const XMLElement& element );
virtual bool Visit( const XMLText& text );
virtual bool Visit( const XMLComment& comment );
virtual bool Visit( const XMLDeclaration& declaration );
virtual bool Visit( const XMLUnknown& unknown );
/**
If in print to memory mode, return a pointer to
the XML file in memory.
*/
const char* CStr() const {
return _buffer.Mem();
}
/**
If in print to memory mode, return the size
of the XML file in memory. (Note the size returned
includes the terminating null.)
*/
int CStrSize() const {
return _buffer.Size();
}
/**
If in print to memory mode, reset the buffer to the
beginning.
*/
void ClearBuffer() {
_buffer.Clear();
_buffer.Push(0);
}
protected:
virtual bool CompactMode( const XMLElement& ) { return _compactMode; }
/** Prints out the space before an element. You may override to change
the space and tabs used. A PrintSpace() override should call Print().
*/
virtual void PrintSpace( int depth );
void Print( const char* format, ... );
void <API key>();
bool _elementJustOpened;
DynArray< const char*, 10 > _stack;
private:
void PrintString( const char*, bool restrictedEntitySet ); // prints out, after detecting entities.
bool _firstElement;
FILE* _fp;
int _depth;
int _textDepth;
bool _processEntities;
bool _compactMode;
enum {
ENTITY_RANGE = 64,
BUF_SIZE = 200
};
bool _entityFlag[ENTITY_RANGE];
bool <API key>[ENTITY_RANGE];
DynArray< char, 20 > _buffer;
};
} // tinyxml2
#if defined(_MSC_VER)
# pragma warning(pop)
#endif
#endif // TINYXML2_INCLUDED
|
package fi.metatavu.edelphi.jsons.queries;
import java.util.Locale;
import fi.metatavu.edelphi.smvcj.<API key>;
import fi.metatavu.edelphi.smvcj.controllers.JSONRequestContext;
import fi.metatavu.edelphi.DelfoiActionName;
import fi.metatavu.edelphi.EdelfoiStatusCode;
import fi.metatavu.edelphi.dao.querydata.QueryReplyDAO;
import fi.metatavu.edelphi.dao.querylayout.QueryPageDAO;
import fi.metatavu.edelphi.dao.users.UserDAO;
import fi.metatavu.edelphi.domainmodel.actions.DelfoiActionScope;
import fi.metatavu.edelphi.domainmodel.querydata.QueryReply;
import fi.metatavu.edelphi.domainmodel.querylayout.QueryPage;
import fi.metatavu.edelphi.domainmodel.resources.Query;
import fi.metatavu.edelphi.domainmodel.resources.QueryState;
import fi.metatavu.edelphi.domainmodel.users.User;
import fi.metatavu.edelphi.i18n.Messages;
import fi.metatavu.edelphi.jsons.JSONController;
import fi.metatavu.edelphi.query.QueryPageHandler;
import fi.metatavu.edelphi.query.<API key>;
import fi.metatavu.edelphi.utils.ActionUtils;
import fi.metatavu.edelphi.utils.QueryDataUtils;
public class <API key> extends JSONController {
public <API key>() {
super();
setAccessAction(DelfoiActionName.ACCESS_PANEL, DelfoiActionScope.PANEL);
}
@Override
public void process(JSONRequestContext jsonRequestContext) {
UserDAO userDAO = new UserDAO();
QueryPageDAO queryPageDAO = new QueryPageDAO();
QueryReplyDAO queryReplyDAO = new QueryReplyDAO();
Long queryPageId = jsonRequestContext.getLong("queryPageId");
QueryPage queryPage = queryPageDAO.findById(queryPageId);
Query query = queryPage.getQuerySection().getQuery();
Messages messages = Messages.getInstance();
Locale locale = jsonRequestContext.getRequest().getLocale();
if (query.getState() == QueryState.CLOSED)
throw new <API key>(EdelfoiStatusCode.<API key>, messages.getText(locale, "exception.1027.<API key>"));
if (query.getState() == QueryState.EDIT) {
if (!ActionUtils.hasPanelAccess(jsonRequestContext, DelfoiActionName.<API key>.toString()))
throw new <API key>(EdelfoiStatusCode.<API key>, messages.getText(locale, "exception.1028.<API key>"));
}
else {
User loggedUser = null;
if (jsonRequestContext.isLoggedIn())
loggedUser = userDAO.findById(jsonRequestContext.getLoggedUserId());
QueryReply queryReply = QueryDataUtils.findQueryReply(jsonRequestContext, loggedUser, query);
if (queryReply == null) {
throw new <API key>(EdelfoiStatusCode.UNKNOWN_REPLICANT, messages.getText(locale, "exception.1026.unknownReplicant"));
}
queryReplyDAO.updateLastModified(queryReply, loggedUser);
QueryDataUtils.storeQueryReplyId(jsonRequestContext.getRequest().getSession(), queryReply);
QueryPageHandler queryPageHandler = <API key>.getInstance().buildPageHandler(queryPage.getPageType());
queryPageHandler.saveAnswers(jsonRequestContext, queryPage, queryReply);
}
}
}
|
package org.craftercms.studio.api.dto;
public class UserTest {
public void testGetUserId() throws Exception {
}
public void testSetUserId() throws Exception {
}
public void testGetPassword() throws Exception {
}
public void testSetPassword() throws Exception {
}
}
|
// generated by wxGlade 0.7.2
// Example for compiling a single file project under Linux using g++:
// g++ MyApp.cpp $(wx-config --libs) $(wx-config --cxxflags) -o MyApp
// Example for compiling a multi file project under Linux using g++:
// g++ main.cpp $(wx-config --libs) $(wx-config --cxxflags) -o MyApp Dialog1.cpp Frame1.cpp
#ifndef <API key>
#define <API key>
#include <wx/wx.h>
#include <wx/image.h>
#include <wx/intl.h>
#ifndef APP_CATALOG
#define APP_CATALOG "appEditor" // replace with the appropriate catalog name
#endif
// begin wxGlade: ::dependencies
#include <wx/spinctrl.h>
// end wxGlade
// begin wxGlade: ::extracode
// end wxGlade
class <API key>: public wxDialog {
public:
// begin wxGlade: <API key>::ids
// end wxGlade
<API key>(wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos=wxDefaultPosition, const wxSize& size=wxDefaultSize, long style=<API key>);
private:
// begin wxGlade: <API key>::methods
void set_properties();
void do_layout();
// end wxGlade
protected:
// begin wxGlade: <API key>::attributes
wxRadioButton* rbtnTargetParty;
wxRadioButton* rbtnTargetFixed;
wxChoice* chTargetFixed;
wxRadioButton* rbtnTargetVariable;
wxTextCtrl* tcTargetVariable;
wxButton* btnTargetVariable;
wxRadioBox* rbOperation;
wxRadioButton* rbtnOperandConstant;
wxSpinCtrl* spinOperandConstant;
wxRadioButton* rbtnOperandVariable;
wxTextCtrl* tcOperandVariable;
wxButton* btnOperandVariable;
wxCheckBox* chbShowMessage;
wxButton* btnOK;
wxButton* btnCancel;
wxButton* btnHelp;
// end wxGlade
}; // wxGlade: end class
#endif // <API key>
|
package keel.Algorithms.<API key>.RMini;
import java.util.StringTokenizer;
import org.core.Fichero;
import java.util.StringTokenizer;
public class Main {
private parseParameters parameters;
/** Default Constructor */
public Main() {
}
/**
* It launches the algorithm
* @param confFile String it is the filename of the configuration file.
*/
private void execute(String confFile) {
parameters = new parseParameters();
parameters.<API key>(confFile);
RMini method = new RMini(parameters);
method.execute();
}
/**
* Main Program
* @param args It contains the name of the configuration file<br/>
* Format:<br/>
* <em>algorith = <algorithm name></em><br/>
* <em>inputData = "<training file>" "<validation file>" "<test file>"</em> ...<br/>
* <em>outputData = "<training file>" "<test file>"</em> ...<br/>
* <br/>
* <em>seed = value</em> (if used)<br/>
* <em><Parameter1> = <value1></em><br/>
* <em><Parameter2> = <value2></em> ... <br/>
*/
public static void main(String args[]) {
Main program = new Main();
System.out.println("Executing Algorithm.");
program.execute(args[0]);
}
}
|
#ifndef GAMEGUI_SIGNAL_H
#define GAMEGUI_SIGNAL_H
#include <gamegui/queue.h>
#include <gamegui/system.h>
typedef int gg_signal_t;
gg_signal_t gg_signal_lookup(gg_class_id class, char *name);
int gg_signal_register(gg_class_id class, char *name);
void gg_signal_init(void);
void gg_signal_exit(void);
#endif
|
import { Component } from '@angular/core'
@Component({
selector: 'gallery',
templateUrl: 'app/home/gallery.component.html'
})
export class GalleryComponent {
}
|
#ifndef globalPoints_H
#define globalPoints_H
#include <OpenFOAM/DynamicList.H>
#include <OpenFOAM/Map.H>
#include <OpenFOAM/labelList.H>
#include <OpenFOAM/FixedList.H>
#include <OpenFOAM/primitivePatch.H>
#include <OpenFOAM/className.H>
#include <OpenFOAM/edgeList.H>
namespace Foam
{
// Forward declaration of classes
class polyMesh;
class polyBoundaryMesh;
class cyclicPolyPatch;
class globalPoints
{
// Private classes
//- Define procPointList as holding a list of meshPoint/processor labels
typedef FixedList<label, 2> procPoint;
typedef List<procPoint> procPointList;
// Private data
//- Mesh reference
const polyMesh& mesh_;
//- Sum of points on processor patches (unfiltered, point on 2 patches
// counts as 2)
const label nPatchPoints_;
//- All points on boundaries and their corresponding connected points
// on other processors.
DynamicList<procPointList> procPoints_;
//- Map from mesh point to index in procPoints
Map<label> meshToProcPoint_;
//- Shared points used by this processor (= global point number)
labelList sharedPointAddr_;
//- My meshpoints corresponding to the shared points
labelList sharedPointLabels_;
//- Total number of shared points.
label nGlobalPoints_;
// Private Member Functions
//- Count all points on processorPatches. Is all points for which
// information is collected.
static label countPatchPoints(const polyBoundaryMesh&);
//- Add information about patchPointI in relative indices to send
// buffers (patchFaces, indexInFace etc.)
static void addToSend
(
const primitivePatch&,
const label patchPointI,
const procPointList&,
DynamicList<label>& patchFaces,
DynamicList<label>& indexInFace,
DynamicList<procPointList>& allInfo
);
//- Merge info from neighbour into my data
static bool mergeInfo
(
const procPointList& nbrInfo,
procPointList& myInfo
);
//- Store (and merge) info for meshPointI
bool storeInfo(const procPointList& nbrInfo, const label meshPointI);
//- Initialize procPoints_ to my patch points. allPoints = true:
// seed with all patch points, = false: only boundaryPoints().
void initOwnPoints(const bool allPoints, labelHashSet& changedPoints);
//- Send subset of procPoints to neighbours
void sendPatchPoints(const labelHashSet& changedPoints) const;
//- Receive neighbour points and merge into my procPoints.
void receivePatchPoints(labelHashSet& changedPoints);
//- Remove entries of size 2 where meshPoint is in provided Map.
// Used to remove normal face-face connected points.
void remove(const Map<label>&);
//- Get indices of point for which I am master (lowest numbered proc)
labelList getMasterPoints() const;
//- Send subset of shared points to neighbours
void sendSharedPoints(const labelList& changedIndices) const;
//- Receive shared points and update subset.
void receiveSharedPoints(labelList& changedIndices);
//- Should move into cyclicPolyPatch but some ordering problem
// keeps on giving problems.
static edgeList coupledPoints(const cyclicPolyPatch&);
//- Disallow default bitwise copy construct
globalPoints(const globalPoints&);
//- Disallow default bitwise assignment
void operator=(const globalPoints&);
public:
//- Declare name of the class and its debug switch
ClassName("globalPoints");
// Constructors
//- Construct from mesh
globalPoints(const polyMesh& mesh);
// Member Functions
// Access
label nPatchPoints() const
{
return nPatchPoints_;
}
const Map<label>& meshToProcPoint() const
{
return meshToProcPoint_;
}
//- shared points used by this processor (= global point number)
const labelList& sharedPointAddr() const
{
return sharedPointAddr_;
}
//- my meshpoints corresponding to the shared points
const labelList& sharedPointLabels() const
{
return sharedPointLabels_;
}
label nGlobalPoints() const
{
return nGlobalPoints_;
}
};
} // End namespace Foam
#endif
|
#include <assert.h>
#include <lib/mhandle/mhandle.h>
#include <lib/util/debug.h>
#include <lib/util/linked-list.h>
#include "opencl-repo.h"
#include "<API key>.h"
#include "opencl-context.h"
#include "opencl-device.h"
#include "opencl-event.h"
#include "opencl-kernel.h"
#include "opencl-mem.h"
#include "opencl-platform.h"
#include "opencl-program.h"
#include "opencl-sampler.h"
struct si_opencl_repo_t
{
struct linked_list_t *object_list;
};
struct si_opencl_repo_t *<API key>(void)
{
struct si_opencl_repo_t *repo;
/* Initialize */
repo = xcalloc(1, sizeof(struct si_opencl_repo_t));
repo->object_list = linked_list_create();
/* Return */
return repo;
}
void si_opencl_repo_free(struct si_opencl_repo_t *repo)
{
linked_list_free(repo->object_list);
free(repo);
}
void <API key>(struct si_opencl_repo_t *repo,
void *object)
{
struct linked_list_t *object_list = repo->object_list;
/* Check that object does not exist */
linked_list_find(object_list, object);
if (!object_list->error_code)
fatal("%s: object already exists", __FUNCTION__);
/* Insert */
linked_list_add(object_list, object);
}
void <API key>(struct si_opencl_repo_t *repo,
void *object)
{
struct linked_list_t *object_list = repo->object_list;
/* Check that object exists */
linked_list_find(object_list, object);
if (object_list->error_code)
fatal("%s: object does not exist", __FUNCTION__);
/* Remove */
linked_list_remove(object_list);
}
/* Look for an object in the repository. The first field of every OpenCL object
* is its identifier. */
void *<API key>(struct si_opencl_repo_t *repo,
enum <API key> type, unsigned int object_id)
{
struct linked_list_t *object_list = repo->object_list;
void *object;
unsigned int current_object_id;
/* Upper 16-bits represent the type of the object */
if (object_id >> 16 != type)
fatal("%s: requested OpenCL object of incorrect type",
__FUNCTION__);
/* Search object */
<API key>(object_list)
{
object = linked_list_get(object_list);
assert(object);
current_object_id = * (unsigned int *) object;
if (current_object_id == object_id)
return object;
}
/* Not found */
fatal("%s: requested OpenCL does not exist (id=0x%x)",
__FUNCTION__, object_id);
return NULL;
}
/* Get the oldest created OpenCL object of the specified type */
void *<API key>(struct si_opencl_repo_t *repo,
enum <API key> type)
{
struct linked_list_t *object_list = repo->object_list;
void *object;
unsigned int object_id;
/* Find object. Upper 16-bits of identifier contain its type. */
<API key>(object_list)
{
object = linked_list_get(object_list);
assert(object);
object_id = * (unsigned int *) object;
if (object_id >> 16 == type)
return object;
}
/* No object found */
return NULL;
}
/* Assignment of OpenCL object identifiers
* An identifier is a 32-bit value, whose 16 most significant bits represent the
* object type, while the 16 least significant bits represent a unique object ID. */
unsigned int <API key>(struct si_opencl_repo_t *repo,
enum <API key> type)
{
static unsigned int <API key>;
unsigned int object_id;
object_id = (type << 16) | <API key>;
<API key>++;
if (<API key> > 0xffff)
fatal("%s: limit of OpenCL objects exceeded\n", __FUNCTION__);
return object_id;
}
void <API key>(struct si_opencl_repo_t *repo)
{
void *object;
/* Platforms */
while ((object = <API key>(repo, <API key>)))
<API key>((struct <API key> *) object);
/* Devices */
while ((object = <API key>(repo, <API key>)))
<API key>((struct si_opencl_device_t *) object);
/* Contexts */
while ((object = <API key>(repo, <API key>)))
<API key>((struct si_opencl_context_t *) object);
/* Command queues */
while ((object = <API key>(repo, <API key>)))
<API key>((struct <API key> *) object);
/* Programs */
while ((object = <API key>(repo, <API key>)))
<API key>((struct si_opencl_program_t *) object);
/* Kernels */
while ((object = <API key>(repo, <API key>)))
<API key>((struct si_opencl_kernel_t *) object);
/* Mems */
while ((object = <API key>(repo, <API key>)))
si_opencl_mem_free((struct si_opencl_mem_t *) object);
/* Events */
while ((object = <API key>(repo, <API key>)))
<API key>((struct si_opencl_event_t *) object);
/* Samplers */
while ((object = <API key>(repo, <API key>)))
<API key>((struct si_opencl_sampler_t *) object);
/* Any object left */
if (linked_list_count(repo->object_list))
panic("%s: not all objects were freed", __FUNCTION__);
}
|
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
class ParityBackground extends Component {
static propTypes = {
style: PropTypes.object.isRequired,
children: PropTypes.node,
className: PropTypes.string,
onClick: PropTypes.func
};
render () {
const { children, className, style, onClick } = this.props;
return (
<div
className={ className }
style={ style }
onTouchTap={ onClick }>
{ children }
</div>
);
}
}
function mapStateToProps (_, initProps) {
const { gradient, seed, muiTheme } = initProps;
let _seed = seed;
let _props = { style: muiTheme.parity.getBackgroundStyle(gradient, seed) };
return (state, props) => {
const { backgroundSeed } = state.settings;
const { seed } = props;
const newSeed = seed || backgroundSeed;
if (newSeed === _seed) {
return _props;
}
_seed = newSeed;
_props = { style: muiTheme.parity.getBackgroundStyle(gradient, newSeed) };
return _props;
};
}
export default connect(
mapStateToProps
)(ParityBackground);
|
(function ($, require) {
var exports = require('piwik/UI');
/**
* Creates a new notifications.
*
* Example:
* var UI = require('piwik/UI');
* var notification = new UI.Notification();
* notification.show('My Notification Message', {title: 'Low space', context: 'warning'});
*/
var Notification = function () {
this.$node = null;
};
/**
* Makes the notification visible.
*
* @param {string} message The actual message that will be displayed. Must be set.
* @param {Object} [options]
* @param {string} [options.id] Only needed for persistent notifications. The id will be sent to the
* frontend once the user closes the notifications. The notification has to
* be registered/notified under this name
* @param {string} [options.title] The title of the notification. For instance the plugin name.
* @param {bool} [options.animate=true] If enabled, the notification will be faded in.
* @param {string} [options.context=warning] Context of the notification: 'info', 'warning', 'success' or
* 'error'
* @param {string} [options.type=transient] The type of the notification: Either 'toast' or 'transitent'
* @param {bool} [options.noclear=false] If set, the close icon is not displayed.
* @param {object} [options.style] Optional style/css dictionary. For instance {'display': 'inline-block'}
* @param {string} [options.placeat] By default, the notification will be displayed in the "stats bar".
* You can specify any other CSS selector to place the notifications
* wherever you want.
*/
Notification.prototype.show = function (message, options) {
checkMessage(message);
options = checkOptions(options);
var template = <API key>(options, message);
this.$node = placeNotification(template, options);
};
/**
* Removes a previously shown notification having the given notification id.
*
*
* @param {string} notificationId The id of a notification that was previously registered.
*/
Notification.prototype.remove = function (notificationId) {
$('[piwik-notification][notification-id=' + notificationId + ']').remove();
};
Notification.prototype.<API key> = function () {
if (this.$node) {
piwikHelper.lazyScrollTo(this.$node, 250);
}
};
/**
* Shows a notification at a certain point with a quick upwards animation.
*
* TODO: if the materializecss version matomo uses is updated, should use their toasts.
*
* @type {Notification}
* @param {string} message The actual message that will be displayed. Must be set.
* @param {Object} options
* @param {string} options.placeat Where to place the notification. Required.
* @param {string} [options.id] Only needed for persistent notifications. The id will be sent to the
* frontend once the user closes the notifications. The notification has to
* be registered/notified under this name
* @param {string} [options.title] The title of the notification. For instance the plugin name.
* @param {string} [options.context=warning] Context of the notification: 'info', 'warning', 'success' or
* 'error'
* @param {string} [options.type=transient] The type of the notification: Either 'toast' or 'transitent'
* @param {bool} [options.noclear=false] If set, the close icon is not displayed.
* @param {object} [options.style] Optional style/css dictionary. For instance {'display': 'inline-block'}
*/
Notification.prototype.toast = function (message, options) {
checkMessage(message);
options = checkOptions(options);
var $placeat = $(options.placeat);
if (!$placeat.length) {
throw new Error("A valid selector is required for the placeat option when using Notification.toast().");
}
var $template = $(<API key>(options, message)).hide();
$('body').append($template);
compileNotification($template);
$template.css({
position: 'absolute',
left: $placeat.offset().left,
top: $placeat.offset().top
});
setTimeout(function () {
$template.animate(
{
top: $placeat.offset().top - $template.height()
},
{
duration: 300,
start: function () {
$template.show();
}
}
);
});
};
exports.Notification = Notification;
function <API key>(options, message) {
var attributeMapping = {
id: 'notification-id',
title: 'notification-title',
context: 'context',
type: 'type',
noclear: 'noclear',
class: 'class',
toastLength: 'toast-length'
},
html = '<div piwik-notification';
for (var key in attributeMapping) {
if (attributeMapping.hasOwnProperty(key)
&& options[key]
) {
html += ' ' + attributeMapping[key] + '="' + options[key].toString().replace(/"/g, """) + '"';
}
}
html += '>' + message + '</div>';
return html;
}
function compileNotification($node) {
angular.element(document).injector().invoke(function ($compile, $rootScope) {
$compile($node)($rootScope.$new(true));
});
}
function placeNotification(template, options) {
var $notificationNode = $(template);
// compile the template in angular
compileNotification($notificationNode);
if (options.style) {
$notificationNode.css(options.style);
}
var <API key> = '#<API key>';
var method = 'append';
if (options.placeat) {
<API key> = options.placeat;
} else {
// If a modal is open, we want to make sure the error message is visible and therefore show it within the opened modal
var modalSelector = '.modal.open .modal-content';
var modalOpen = $(modalSelector);
if (modalOpen.length) {
<API key> = modalSelector;
method = 'prepend';
}
}
$notificationNode = $notificationNode.hide();
$(<API key>)[method]($notificationNode);
if (false === options.animate) {
$notificationNode.show();
} else {
$notificationNode.fadeIn(1000);
}
return $notificationNode;
}
function checkMessage(message) {
if (!message) {
throw new Error('No message given, cannot display notification');
}
}
function checkOptions(options) {
if (options && !$.isPlainObject(options)) {
throw new Error('Options has the wrong format, cannot display notification');
} else if (!options) {
options = {};
}
return options;
}
})(jQuery, require);
|
PREP(initCBASettings);
PREP(postInit);
|
package net.jeremybrooks.jinx.api;
import net.jeremybrooks.jinx.Jinx;
import net.jeremybrooks.jinx.JinxException;
import net.jeremybrooks.jinx.JinxUtils;
import net.jeremybrooks.jinx.response.Response;
import net.jeremybrooks.jinx.response.photos.notes.Note;
import java.util.Map;
import java.util.TreeMap;
public class PhotosNotesApi {
private Jinx jinx;
public PhotosNotesApi(Jinx jinx) {
this.jinx = jinx;
}
public Note add(String photoId, int noteX, int noteY, int noteWidth, int noteHeight, String noteText) throws JinxException {
JinxUtils.validateParams(photoId, noteText);
Map<String, String> params = new TreeMap<>();
params.put("method", "flickr.photos.notes.add");
params.put("photo_id", photoId);
params.put("note_x", Integer.toString(noteX));
params.put("note_y", Integer.toString(noteY));
params.put("note_w", Integer.toString(noteWidth));
params.put("note_h", Integer.toString(noteHeight));
params.put("note_text", noteText);
return jinx.flickrPost(params, Note.class);
}
public Response edit(String noteId, int noteX, int noteY, int noteWidth, int noteHeight, String noteText) throws JinxException {
JinxUtils.validateParams(noteId, noteText);
Map<String, String> params = new TreeMap<>();
params.put("method", "flickr.photos.notes.edit");
params.put("note_id", noteId);
params.put("note_x", Integer.toString(noteX));
params.put("note_y", Integer.toString(noteY));
params.put("note_w", Integer.toString(noteWidth));
params.put("note_h", Integer.toString(noteHeight));
params.put("note_text", noteText);
return jinx.flickrPost(params, Response.class);
}
public Response delete(String noteId) throws JinxException {
JinxUtils.validateParams(noteId);
Map<String, String> params = new TreeMap<>();
params.put("method", "flickr.photos.notes.delete");
params.put("note_id", noteId);
return jinx.flickrPost(params, Response.class);
}
}
|
<?php
require_once 'PHPUnit/Framework.php';
require_once 'PHPUnit/Util/Filter.php';
require_once 'PHPUnit/Framework/MockObject/Matcher/StatelessInvocation.php';
require_once 'PHPUnit/Framework/MockObject/Invocation.php';
PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT');
class <API key> extends <API key>
{
protected $parameters = array();
protected $invocation;
public function __construct($parameters)
{
foreach($parameters as $parameter) {
if (!($parameter instanceof <API key>)) {
$parameter = new <API key>($parameter);
}
$this->parameters[] = $parameter;
}
}
public function toString()
{
$text = 'with parameter';
foreach($this->parameters as $index => $parameter) {
if ($index > 0) {
$text .= ' and';
}
$text .= ' ' . $index . ' ' . $parameter->toString();
}
return $text;
}
public function matches(<API key> $invocation)
{
$this->invocation = $invocation;
$this->verify();
return count($invocation->parameters) < count($this->parameters);
}
public function verify()
{
if ($this->invocation === NULL) {
throw new <API key>(
'Mocked method does not exist.'
);
}
if (count($this->invocation->parameters) < count($this->parameters)) {
throw new <API key>(
sprintf(
'Parameter count for invocation %s is too low.',
$this->invocation->toString()
)
);
}
foreach ($this->parameters as $i => $parameter) {
if (!$parameter->evaluate($this->invocation->parameters[$i])) {
$parameter->fail(
$this->invocation->parameters[$i],
sprintf(
'Parameter %s for invocation %s does not match expected value.',
$i,
$this->invocation->toString()
)
);
}
}
}
}
?>
|
<?php
defined( '_JEXEC' ) or die( 'Restricted access' );
//Import filesystem libraries. Perhaps not necessary, but does not hurt
jimport('joomla.filesystem.file');
jimport('joomla.filesystem.folder');
jimport('joomla.application.component.helper');
class GetbibleModelImport extends JModelLegacy
{
protected $user;
protected $dateSql;
protected $book_counter;
protected $app_params;
protected $local = false;
protected $curlError = false;
public $availableVersions;
public $<API key>;
public $installedVersions;
public function __construct()
{
parent::__construct();
// get params
$this->app_params = JComponentHelper::getParams('com_getbible');
// get user data
$this->user = JFactory::getUser();
// get todays date
$this->dateSql = JFactory::getDate()->toSql();
// we need a loger execution time
if (ini_set('max_execution_time', 300) === false)
{
JFactory::getApplication()->enqueueMessage(JText::_('<API key>'), 'error'); return false;
}
// load available verstions
$this->getVersionAvailable();
// get installed versions
$this-><API key>();
}
protected function populateState()
{
parent::populateState();
// Get the input data
$jinput = JFactory::getApplication()->input;
$source = $jinput->post->get('translation', NULL, 'STRING');
$translation = (string) preg_replace('/[^A-Z0-9_\)\(-]/i', '', $source);
// Set to state
$this->setState('translation', $translation);
}
public function getVersions()
{
// reload version list for app
$available = $this-><API key>;
$alreadyin = $this->installedVersions;
if($available){
if ($alreadyin){
$result = array_diff($available, $alreadyin);
} else {
$result = $available;
}
if($result){
$setVersions = array();
$setVersions[] = JHtml::_('select.option', '', JText::_('<API key>'));
foreach ($this->availableVersions as $key => $values){
if(in_array($key, $result)){
$name = $values["versionName"]. ' ('.$values["versionLang"].')';
$setVersions[] = JHtml::_('select.option', $values["fileName"], $name);
}
}
return $setVersions;
}
JFactory::getApplication()->enqueueMessage(JText::_('<API key>'), 'success');
return false;
}
if($this->curlError){
JFactory::getApplication()->enqueueMessage(JText::_($this->curlError), 'error'); return false;
} else {
if($this->local){
JFactory::getApplication()->enqueueMessage(JText::_('<API key>'), 'error'); return false;
} else {
JFactory::getApplication()->enqueueMessage(JText::_('<API key>'), 'error'); return false;
}
}
}
public function rutime($ru, $rus, $index) {
return ($ru["ru_$index.tv_sec"]*1000 + intval($ru["ru_$index.tv_usec"]/1000))
- ($rus["ru_$index.tv_sec"]*1000 + intval($rus["ru_$index.tv_usec"]/1000));
}
public function getImport()
{
if ($this->getState('translation')){
// set version
$versionFileName = $this->getState('translation');
$versionfix = str_replace("___", "'", $versionFileName);
list($versionLang,$versionName,$versionCode,$bidi) = explode('__', $versionfix);
$versionName = str_replace("_", " ", $versionName);
$version = $versionCode;
//check input
if ($this->checkTranslation($version) && $this->checkFileName($versionFileName)){
// get instilation opstion set in params
$installOptions = $this->app_params->get('installOptions');
if($installOptions){
// get the file
$filename = 'https://getbible.net/scriptureinstall/'.$versionFileName.'.txt';
} else {
// get localInstallFolder set in params
$filename = JPATH_ROOT.'/'.rtrim(ltrim($this->app_params->get('localInstallFolder'),'/'),'/').'/'.$versionFileName.'.txt';
}
// load the file
$file = new SplFileObject($filename);
// start up database
$db = JFactory::getDbo();
// load all books
$books = $this->setBooks($version);
$i = 1;
// build query to save
if (is_object($file)) {
while (! $file->eof()) {
$verse = explode("||",$file->fgets());
$found = false;
// rename books
foreach ($books as $book){
$verse[0] = strtoupper(preg_replace('/\s+/', '', $verse[0]));
if ($book['nr'] <= 39) {
if (strpos($verse[0],'O') !== false) {
$search_value = sprintf("%02s", $book['nr']).'O';
} else {
$search_value = sprintf("%02s", $book['nr']);
}
} else {
if (strpos($verse[0],'N') !== false) {
$search_value = $book['nr'].'N';
} else {
$search_value = $book['nr'];
}
}
if ($verse[0] == $search_value){
$verse[0] = $book['nr'];
$book_nr = $book['nr'];
$book_name = $book['name'];
$found = true;
break;
}
}
if(!$found){
foreach ($books as $book){
$verse[0] = strtoupper(preg_replace('/\s+/', '', $verse[0]));
foreach($book['book_names'] as $key => $value){
if ($value){
$value = strtoupper(preg_replace('/\s+/', '', $value));
if ($verse[0] == $value){
$verse[0] = $book['nr'];
$book_nr = $book['nr'];
$book_name = $book['name'];
$found = true;
break;
}
}
}
}
}
if(!$found){
// load all books again as KJV
$books = $this->setBooks($version, true);
foreach ($books as $book){
foreach($book['book_names'] as $key => $value){
if ($value){
$value = strtoupper(preg_replace('/\s+/', '', $value));
if ($verse[0] == $value){
$verse[0] = $book['nr'];
$book_nr = $book['nr'];
$found = true;
break;
}
}
}
}
}
// set data
if(isset($verse[3]) && $verse[3]){
$Bible[$verse[0]][$verse[1]][$verse[2]] = $verse[3];
// Create a new query object for this verse.
$versObject = new stdClass();
$versObject->version = $version;
$versObject->book_nr = $book_nr;
$versObject->chapter_nr = $verse[1];
$versObject->verse_nr = $verse[2];
$versObject->verse = $verse[3];
$versObject->access = 1;
$versObject->published = 1;
$versObject->created_by = $this->user->id;
$versObject->created_on = $this->dateSql;
// Insert the object into the verses table.
$result = JFactory::getDbo()->insertObject('#__getbible_verses', $versObject);
}
}
}
// clear from memory
unset($file);
// save complete books & chapters
foreach ($books as $book)
{
if (isset($book["nr"]) && isset($Bible[$book["nr"]]))
{
$this->saveChapter($version, $book["nr"], $Bible[$book["nr"]]);
$this->saveBooks($version, $book["nr"], $Bible[$book["nr"]]);
}
}
// clear from memory
unset($books);
// Set version details
if(is_array($this->book_counter)){
if(in_array(1,$this->book_counter) && in_array(66,$this->book_counter)){
$testament = 'OT&NT';
} elseif(in_array(1,$this->book_counter) && !in_array(66,$this->book_counter)){
$testament = 'OT';
} elseif(!in_array(1,$this->book_counter) && in_array(66,$this->book_counter)){
$testament = 'NT';
} else {
$testament = 'NOT';
}
$book_counter = json_encode($this->book_counter);
} else {
$book_counter = 'error';
$testament = 'error';
}
// Create a new query object for this Version.
$versionObject = new stdClass();
$versionObject->name = $versionName;
$versionObject->bidi = $bidi;
$versionObject->language = $versionLang;
$versionObject->books_nr = $book_counter;
$versionObject->testament = $testament;
$versionObject->version = $version;
$versionObject->link = $filename;
$versionObject->installed = 1;
$versionObject->access = 1;
$versionObject->published = 1;
$versionObject->created_by = $this->user->id;
$versionObject->created_on = $this->dateSql;
// Insert the object into the versions table.
$result = JFactory::getDbo()->insertObject('#__getbible_versions', $versionObject);
JFactory::getApplication()->enqueueMessage(JText::sprintf('<API key>', $versionName));
// reset the local version list.
$this->_cpanel();
// if first Bible is installed change the application to load localy with that Bible as the default
$this->setLocal();
// clean cache to insure the dropdown removes this installed version.
$this->cleanCache('_system');
return true;
} else {
return false;
}
} else {
return false;
}
}
protected function checkTranslation($version)
{
// get instilation opstion set in params
$installOptions = $this->app_params->get('installOptions');
$available = $this-><API key>;
$alreadyin = $this->installedVersions;
if ($available){
if(in_array($version, $available)){
if ($alreadyin){
if(in_array($version, $alreadyin)){
JFactory::getApplication()->enqueueMessage(JText::_('<API key>'), 'error'); return false;
}return true;
}return true;
}
JFactory::getApplication()->enqueueMessage(JText::_('<API key>'), 'error'); return false;
}
if($this->curlError){
JFactory::getApplication()->enqueueMessage(JText::_($this->curlError), 'error'); return false;
} else {
if($this->local){
JFactory::getApplication()->enqueueMessage(JText::_('<API key>'), 'error'); return false;
} else {
JFactory::getApplication()->enqueueMessage(JText::_('<API key>'), 'error'); return false;
}
}
}
protected function checkFileName($versionFileName)
{
$available = $this->availableVersions;
$found = false;
if ($available){
foreach($available as $file){
if (in_array($versionFileName, $file)){
$found = true;
break;
} else {
$found = false;
}
}
if(!$found){
JFactory::getApplication()->enqueueMessage(JText::_('<API key>'), 'error'); return false;
} else {
return $found;
}
}
if($this->curlError){
JFactory::getApplication()->enqueueMessage(JText::_($this->curlError), 'error'); return false;
} else {
if($this->local){
JFactory::getApplication()->enqueueMessage(JText::_('<API key>'), 'error'); return false;
} else {
JFactory::getApplication()->enqueueMessage(JText::_('<API key>'), 'error'); return false;
}
}
}
protected function saveChapter($version, $book_nr, $chapters)
{
if ( $chapters ){
// start up database
$db = JFactory::getDbo();
// Create a new query object for this verstion
$query = $db->getQuery(true);
// set chapter number
$chapter_nr = 1;
$values = '';
// set the data
foreach ($chapters as $chapter)
{
$setup = NULL;
$text = NULL;
$ver = 1;
foreach($chapter as $verse)
{
$text[$ver] = array( 'verse_nr' => $ver,'verse' => $verse);
$ver++;
}
$setup = array('chapter'=>$text);
$scripture = json_encode($setup);
// Insert values.
$values[] = $db->quote($version).', '.(int)$book_nr.', '.(int)$chapter_nr.', '.$db->quote($scripture).', 1, 1, '.$this->user->id.', '.$db->quote($this->dateSql);
$chapter_nr++;
}
// clear from memory
unset($chapters);
// Insert columns.
$columns = array(
'version',
'book_nr',
'chapter_nr',
'chapter',
'access',
'published',
'created_by',
'created_on'
);
// Prepare the insert query.
$query->insert($db->quoteName('#__getbible_chapters'));
$query->columns($db->quoteName($columns));
$query->values($values);
// Set the query using our newly populated query object and execute it.
$db->setQuery($query);
$db->query();
}
return true;
}
protected function saveBooks($version, $book_nr, $book)
{
if (is_array($book) && count($book)){
//set book number
$this->book_counter[] = $book_nr;
// start up database
$db = JFactory::getDbo();
// Create a new query object for this verstion
$query = $db->getQuery(true);
// set chapter number
$chapter_nr = 1;
$values = '';
// set the data
foreach ($book as $chapter)
{
$setup = NULL;
$text = NULL;
$ver = 1;
foreach($chapter as $verse)
{
$text[$ver] = array( 'verse_nr' => $ver,'verse' => $verse);
$ver++;
}
$setupChapter[$chapter_nr] = array('chapter_nr'=>$chapter_nr,'chapter'=>$text);
$chapter_nr++;
}
// clear from memory
unset($book);
$setup = array('book'=>$setupChapter);
$saveBook = json_encode($setup);
// Create a new query object for this verstion
$query = $db->getQuery(true);
// Insert columns.
$columns = array('version', 'book_nr', 'book', 'access', 'published', 'created_by', 'created_on');
// Insert values.
$values = array($db->quote($version), (int) $book_nr, $db->quote($saveBook), 1, 1, $this->user->id, $db->quote($this->dateSql));
// Prepare the insert query.
$query
->insert($db->quoteName('#__getbible_books'))
->columns($db->quoteName($columns))
->values(implode(',', $values));
//echo nl2br(str_replace('#__','api_',$query)); die;
// Set the query using our newly populated query object and execute it.
$db->setQuery($query);
$db->query();
}
return true;
}
protected function <API key>()
{
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
// Order it by the ordering field.
$query->select($db->quoteName('version'));
$query->from($db->quoteName('#__getbible_versions'));
$query->order('version ASC');
// Reset the query using our newly populated query object.
$db->setQuery($query);
// Load the results
$results = $db->loadColumn();
if ($results){
$this->installedVersions = $results;
return true;
}
return false;
}
protected function setLocalXML()
{
jimport( 'joomla.filesystem.folder' );
// get localInstallFolder set in params
$path = rtrim(ltrim($this->app_params->get('localInstallFolder'),'/'),'/');
// creat folder
JFolder::create(JPATH_ROOT.'/'.$path.'/xml');
// set the file name
$filepath = JPATH_ROOT.'/'.$path.'/xml/version.xml.php';
// set folder path
$folderpath = JPATH_ROOT.'/'.$path;
$fh = fopen($filepath, "w");
if (!is_resource($fh)) {
return false;
}
$data = $this->setPHPforXML($folderpath);
if(!fwrite($fh, $data)){
// close file.
fclose($fh);
return false;
}
// close file.
fclose($fh);
// return local file path
return JURI::root().$path.'/xml/version.xml.php/versions.xml';
}
protected function setPHPforXML($path)
{
return "<?php
|
#include "selfcheck.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "multiple_ir.h"
#include "multiply.h"
#include "multiply_assembler.h"
#include "multiply_str_aux.h"
#include "multiple_misc.h"
#include "multiple_err.h"
#include "vm_predef.h"
#include "vm_opcode.h"
#include "vm_types.h"
#include "mlua_lexer.h"
#include "mlua_ast.h"
#include "mlua_icg.h"
#include "mlua_icg_aux.h"
#include "mlua_icg_fcb.h"
#include "mlua_icg_context.h"
#include "mlua_icg_expr.h"
#include "mlua_icg_stmt.h"
#include "<API key>.h"
#include "<API key>.h"
/* Declaration */
int <API key>(struct multiple_error *err, \
struct mlua_icg_context *context, \
struct mlua_icg_fcb_block *icg_fcb_block, \
struct <API key> *<API key>, \
struct <API key> *list, \
struct <API key> *offset_pack_break);
static int <API key>(struct multiple_error *err, \
struct mlua_icg_context *context)
{
int ret = 0;
struct mlua_icg_fcb_block *icg_fcb_block_cur;
struct mlua_icg_fcb_line *icg_fcb_line_cur;
uint32_t instrument_number;
struct <API key> *<API key>;
struct <API key> *<API key>;
uint32_t offset_start;
uint32_t fcb_size = 0;
uint32_t count;
/* Do not disturb the instrument produced by other way */
offset_start = (uint32_t)(context->icode->text_section->size);
<API key> = context->icode->export_section->begin;
icg_fcb_block_cur = context->icg_fcb_block_list->begin;
while (icg_fcb_block_cur != NULL)
{
icg_fcb_line_cur = icg_fcb_block_cur->begin;
/* Record the absolute instrument number */
instrument_number = (uint32_t)context->icode->text_section->size;
if (<API key> == NULL)
{
<API key>();
ret = -<API key>;
goto fail;
}
<API key>->instrument_number = instrument_number;
while (icg_fcb_line_cur != NULL)
{
switch (icg_fcb_line_cur->type)
{
case <API key>:
if ((ret = <API key>(err, \
context->icode, \
icg_fcb_line_cur->opcode, icg_fcb_line_cur->operand)) != 0)
{ goto fail; }
break;
case <API key>:
if ((ret = <API key>(err, \
context->icode, \
icg_fcb_line_cur->opcode, instrument_number + icg_fcb_line_cur->operand)) != 0)
{ goto fail; }
break;
case <API key>:
/* Operand of this instrument here is the index number of lambda */
if ((ret = <API key>(err, \
context->icode, \
icg_fcb_line_cur->opcode, icg_fcb_line_cur->operand)) != 0)
{ goto fail; }
break;
case <API key>:
if ((ret = <API key>(err, \
context->icode, \
icg_fcb_line_cur->opcode, icg_fcb_line_cur->operand)) != 0)
{ goto fail; }
break;
}
fcb_size += 1;
icg_fcb_line_cur = icg_fcb_line_cur->next;
}
icg_fcb_block_cur = icg_fcb_block_cur->next;
<API key> = <API key>->next;
}
/* 2nd pass, dealing with lambdas */
icg_fcb_block_cur = context->icg_fcb_block_list->begin;
/* Skip text body of built-in procedures at the beginning part */
<API key> = context->icode->text_section->begin;
while (offset_start
{
<API key> = <API key>->next;
}
/* Process lambda mks */
while (icg_fcb_block_cur != NULL)
{
icg_fcb_line_cur = icg_fcb_block_cur->begin;
while (icg_fcb_line_cur != NULL)
{
if (icg_fcb_line_cur->type == <API key>)
{
/* Locate to the export section item */
count = icg_fcb_line_cur->operand;
<API key> = context->icode->export_section->begin;
while ((<API key> != NULL) && (count != 0))
{
count
<API key> = <API key>->next;
}
if (<API key> == NULL)
{
<API key>();
ret = -<API key>;
goto fail;
}
<API key>->operand = <API key>->instrument_number;
}
<API key> = <API key>->next;
icg_fcb_line_cur = icg_fcb_line_cur->next;
}
icg_fcb_block_cur = icg_fcb_block_cur->next;
}
goto done;
fail:
done:
return ret;
}
static int <API key>(struct multiple_error *err, \
struct multiple_ir *icode, \
struct <API key> *res_id, \
struct <API key> *icg_fcb_block_list, \
struct mlua_icg_fcb_block *icg_fcb_block, \
const char *name, const size_t name_len)
{
int ret = 0;
uint32_t id;
struct <API key> *<API key> = NULL;
<API key> = <API key>();
if (<API key> == NULL)
{
<API key>();
ret = -MULTIPLE_ERR_MALLOC;
goto fail;
}
<API key>->args_count = 0;
<API key>->args = NULL;
<API key>->args_types = NULL;
/* Return */
if ((ret = <API key>(icg_fcb_block, OP_RETNONE, 0)) != 0)
{ goto fail; }
/* Append block */
if ((ret = <API key>(icg_fcb_block_list, icg_fcb_block)) != 0)
{
<API key>();
goto fail;
}
/* Append export section item */
if ((ret = <API key>( \
err, \
icode, \
res_id, \
&id, \
name, name_len)) != 0)
{ goto fail; }
<API key>->name = id;
<API key>->instrument_number = (uint32_t)icode->export_section->size;
<API key>(icode->export_section, <API key>);
goto done;
fail:
if (<API key> != NULL) <API key>(<API key>);
done:
return ret;
}
static int <API key>(struct multiple_error *err, \
struct mlua_icg_context *context, \
struct mlua_ast_program *program)
{
int ret = 0;
struct mlua_icg_fcb_block *<API key> = NULL;
struct <API key> *<API key> = NULL;
uint32_t id;
struct <API key> *<API key> = NULL;
uint32_t <API key>;
uint32_t <API key>;
<API key> = <API key>();
if (<API key> == NULL)
{
<API key>();
ret = -MULTIPLE_ERR_MALLOC;
goto fail;
}
<API key> = <API key>();
if (<API key> == NULL)
{
<API key>();
ret = -MULTIPLE_ERR_MALLOC;
goto fail;
}
<API key> = <API key>();
if (<API key> == NULL)
{
<API key>();
ret = -MULTIPLE_ERR_MALLOC;
goto fail;
}
/* def in .text section */
if ((ret = <API key>( \
err, \
context->icode, \
context->res_id, \
&id, \
<API key>, \
<API key>)) != 0)
{ goto fail; }
if ((ret = <API key>(<API key>, OP_DEF, id)) != 0) { goto fail; }
<API key>->name = id;
<API key>->args_count = 0;
<API key>->args = NULL;
<API key>->args_types = NULL;
<API key> = <API key>(<API key>);
/* Statements of top level */
if ((ret = <API key>(err, context, \
<API key>, \
<API key>, \
program->stmts, NULL)) != 0)
{ goto fail; }
/* Apply goto to label */
if ((ret = <API key>(err, \
context, \
<API key>, \
<API key>)) != 0)
{ goto fail; }
/* Pop a label offset pack */
<API key>(context-><API key>);
/* Put built-in procedures directly into icode,
* and put initialize code into '__autorun__' */
if ((ret = <API key>(err, \
context->icode, \
context->res_id, \
<API key>, \
context-><API key>, \
<API key>,
&<API key>)) != 0)
{ goto fail; }
/* Put built-in 'tables' directly into icode,
* and put initialize code into '__autorun__' */
if ((ret = <API key>(err, \
context->icode, \
context->res_id, \
<API key>, \
context->stdlibs, \
<API key>,
&<API key>)) != 0)
{ goto fail; }
/* '__autorun__' subroutine */
if ((ret = <API key>( \
err, \
context->icode, \
context->res_id, \
context->icg_fcb_block_list, <API key>, \
<API key>, <API key>)) != 0)
{ goto fail; }
<API key> = NULL;
/* Append export section item */
if ((ret = <API key>( \
err, \
context->icode, \
context->res_id, \
&id, \
<API key>, \
<API key>)) != 0)
{ goto fail; }
<API key>->name = id;
goto done;
fail:
if (<API key> != NULL) <API key>(<API key>);
done:
if (<API key> != NULL) <API key>(<API key>);
if (<API key> != NULL) <API key>(<API key>);
return ret;
}
int mlua_irgen(struct multiple_error *err, \
struct multiple_ir **icode_out, \
struct mlua_ast_program *program, \
int verbose)
{
int ret = 0;
struct mlua_icg_context context;
struct <API key> *<API key> = NULL;
struct multiple_ir *new_icode = NULL;
struct <API key> *new_res_id = NULL;
struct <API key> *<API key> = NULL;
struct <API key> *<API key> = NULL;
struct <API key> *new_table_list = NULL;
(void)verbose;
if ((<API key> = <API key>()) == NULL)
{ <API key>(); ret = -MULTIPLE_ERR_MALLOC; goto fail; }
if ((<API key> = <API key>()) == NULL)
{ <API key>(); ret = -MULTIPLE_ERR_MALLOC; goto fail; }
if ((<API key> = <API key>()) == NULL)
{ <API key>(); ret = -MULTIPLE_ERR_MALLOC; goto fail; }
if ((new_table_list = <API key>()) == NULL)
{ <API key>(); ret = -MULTIPLE_ERR_MALLOC; goto fail; }
if ((new_icode = multiple_ir_new()) == NULL)
{ <API key>(); ret = -MULTIPLE_ERR_MALLOC; goto fail; }
if ((new_res_id = <API key>()) == NULL)
{ <API key>(); ret = -MULTIPLE_ERR_MALLOC; goto fail; }
<API key>(&context);
context.icg_fcb_block_list = <API key>;
context.icode = new_icode;
context.res_id = new_res_id;
context.<API key> = <API key>;
context.<API key> = <API key>;
context.stdlibs = new_table_list;
/* Generating icode for '__init__' */
if ((ret = <API key>(err, \
&context, \
program)) != 0)
{ goto fail; }
/* Merge blocks */
if ((ret = <API key>(err, \
&context)) != 0)
{ goto fail; }
*icode_out = new_icode;
ret = 0;
goto done;
fail:
if (new_icode != NULL) multiple_ir_destroy(new_icode);
done:
if (new_res_id != NULL) <API key>(new_res_id);
if (<API key> != NULL) <API key>(<API key>);
if (<API key> != NULL) \
{ <API key>(<API key>); }
if (<API key> != NULL)
{ <API key>(<API key>); }
if (new_table_list != NULL)
{ <API key>(new_table_list); }
return ret;
}
|
package de.jotschi.geo.osm.tags;
import org.w3c.dom.Node;
public class OsmMember {
String type, ref, role;
public OsmMember(Node node) {
ref = node.getAttributes().getNamedItem("ref").getNodeValue();
role = node.getAttributes().getNamedItem("role").getNodeValue();
type = node.getAttributes().getNamedItem("type").getNodeValue();
}
public String getType() {
return type;
}
public String getRef() {
return ref;
}
public String getRole() {
return role;
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="robots" content="index, follow, all" />
<title>Library\CommandLine\<API key> | Library</title>
<link rel="stylesheet" type="text/css" href="../../css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="../../css/bootstrap-theme.min.css">
<link rel="stylesheet" type="text/css" href="../../css/sami.css">
<script src="../../js/jquery-1.11.1.min.js"></script>
<script src="../../js/bootstrap.min.js"></script>
<script src="../../js/typeahead.min.js"></script>
<script src="../../sami.js"></script>
<meta name="MobileOptimized" content="width">
<meta name="HandheldFriendly" content="true">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1">
</head>
<body id="class" data-name="class:<API key>" data-root-path="../../">
<div id="content">
<div id="left-column">
<div id="control-panel">
<form id="search-form" action="../../search.html" method="GET">
<span class="glyphicon glyphicon-search"></span>
<input name="search"
class="typeahead form-control"
type="search"
placeholder="Search">
</form>
</div>
<div id="api-tree"></div>
</div>
<div id="right-column">
<nav id="site-nav" class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-elements">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="../../index.html">Library</a>
</div>
<div class="collapse navbar-collapse" id="navbar-elements">
<ul class="nav navbar-nav">
<li><a href="../../classes.html">Classes</a></li>
<li><a href="../../namespaces.html">Namespaces</a></li>
<li><a href="../../interfaces.html">Interfaces</a></li>
<li><a href="../../traits.html">Traits</a></li>
<li><a href="../../doc-index.html">Index</a></li>
<li><a href="../../search.html">Search</a></li>
</ul>
</div>
</div>
</nav>
<div class="<API key>">
<ol class="breadcrumb">
<li><span class="label label-default">class</span></li>
<li><a href="../../Library.html">Library</a></li>
<li><a href="../../Library/CommandLine.html">CommandLine</a></li>
<li><API key></li>
</ol>
</div>
<div id="page-content">
<div class="page-header">
<h1><API key></h1>
</div>
<p> class
<strong><API key></strong> implements
<a href="../../Library/CommandLine/<API key>.html"><abbr title="Library\CommandLine\<API key>"><API key></abbr></a>
</p>
<div class="description">
<p>Basic command line controller</p> <p>Any command line controller must extend this abstract class.</p>
<p>It defines some basic command line options that you must not overwrite in your child class:</p>
<ul>
<li>"h | help" : get a usage information,</li>
<li>"v | verbose" : increase verbosity of the execution (written strings must be handled in your scripts),</li>
<li>"x | debug" : execute the script in "debug" mode (must write actions before executing them),</li>
<li>"q | quiet" : turn verbosity totally off during the execution (only errors and informations will be written),</li>
<li>"f | force" : force some actions (avoid interactions),</li>
<li>"i | interactive" : increase interactivity of the execution,</li>
<li>"version" : get some version information about running environment.</li>
</ul>
</p> </div>
<h2>Properties</h2>
<table class="table table-condensed">
<tr>
<td class="type" id="property__name">
static
string
</td>
<td>$_name</td>
<td class="last">This must be over-written in any child class</td>
<td></td>
</tr>
<tr>
<td class="type" id="property__version">
static
string
</td>
<td>$_version</td>
<td class="last">This must be over-written in any child class</td>
<td></td>
</tr>
</table>
<h2>Methods</h2>
<div class="container-fluid underlined">
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="
array $options = array())
<p class="no-description">No description</p>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
string
</div>
<div class="col-md-8 type">
<a href="
<p>Magic distribution when printing object</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#method_distribute">distribute</a>()
<p>Distribution of the work</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../Library/CommandLine/<API key>.html"><abbr title="Library\CommandLine\<API key>"><API key></abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setDebug">setDebug</a>(
bool $dbg = true)
<p class="no-description">No description</p>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<abbr title="Library\CommandLine\$this">$this</abbr>
</div>
<div class="col-md-8 type">
<a href="#method_setVerbose">setVerbose</a>(
bool $vbr = true)
<p class="no-description">No description</p>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<abbr title="Library\CommandLine\$this">$this</abbr>
</div>
<div class="col-md-8 type">
<a href="#method_setForce">setForce</a>(
bool $frc = true)
<p class="no-description">No description</p>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<abbr title="Library\CommandLine\$this">$this</abbr>
</div>
<div class="col-md-8 type">
<a href="#<API key>">setInteractive</a>(
bool $frc = true)
<p class="no-description">No description</p>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<abbr title="Library\CommandLine\$this">$this</abbr>
</div>
<div class="col-md-8 type">
<a href="#method_setQuiet">setQuiet</a>()
<p class="no-description">No description</p>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#<API key>">addDoneMethod</a>(
string $_cls_meth)
<p class="no-description">No description</p>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
array
</div>
<div class="col-md-8 type">
<a href="#<API key>">getDoneMethods</a>()
<p class="no-description">No description</p>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#method_setScript">setScript</a>(
string $script_name)
<p>Set the current command line script called</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
string|null
</div>
<div class="col-md-8 type">
<a href="#method_getScript">getScript</a>()
<p>Get the current command line script called</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#<API key>">setParameters</a>(
array $params)
<p>Set the command line parameters</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
array
</div>
<div class="col-md-8 type">
<a href="#<API key>">getParameters</a>()
<p>Get the parameters collection</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#<API key>">runHelpCommand</a>($opt = null)
<p>List of all options and features of the command line tool ; for some commands, a specific help can be available, running <var>--command --help</var>
Some command examples are purposed running <var>--console --help</var></p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#<API key>">runVerboseCommand</a>()
<p>Run the command line in <bold>verbose</bold> mode, writing some information on screen (default is <option>OFF</option>)</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#<API key>">runQuietCommand</a>()
<p>Run the command line in <bold>quiet</bold> mode, trying to not write anything on screen (default is <option>OFF</option>)</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#<API key>">runDebugCommand</a>()
<p>Run the command line in <bold>debug</bold> mode, writing some scripts information during runtime (default is <option>OFF</option>)</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#<API key>">runForceCommand</a>()
<p>Run the command line in <bold>forced</bold> mode ; any choice will be set on default value if so</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#<API key>"><API key></a>()
<p>Run the command line in <bold>interactive</bold> mode ; any choice will be prompted if possible</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#<API key>">runVersionCommand</a>()
<p>Get versions of system environment</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<abbr title="Library\CommandLine\$this">$this</abbr>
</div>
<div class="col-md-8 type">
<a href="#method_write">write</a>(
null $str = null,
bool $new_line = true)
<p>Format and write a string to STDOUT</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<abbr title="Library\CommandLine\$this">$this</abbr>
</div>
<div class="col-md-8 type">
<a href="#method_error">error</a>(
null $str = null,
int $status = 1,
bool $new_line = true)
<p>Format and write an error message to STDOUT (or STDERR) and exits with status <code>$status</code></p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<abbr title="Library\CommandLine\$this">$this</abbr>
</div>
<div class="col-md-8 type">
<a href="#<API key>">parseAndWrite</a>(
string $str,
null $type = null,
bool $spaced = false)
<p>Parse, format and write a message to STDOUT</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<abbr title="Library\CommandLine\$this">$this</abbr>
</div>
<div class="col-md-8 type">
<a href="#method_writeError">writeError</a>(
string $str)
<p class="no-description">No description</p>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<abbr title="Library\CommandLine\$this">$this</abbr>
</div>
<div class="col-md-8 type">
<a href="#<API key>">writeThinError</a>(
string $str)
<p class="no-description">No description</p>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<abbr title="Library\CommandLine\$this">$this</abbr>
</div>
<div class="col-md-8 type">
<a href="#method_writeInfo">writeInfo</a>(
string $str)
<p class="no-description">No description</p>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<abbr title="Library\CommandLine\$this">$this</abbr>
</div>
<div class="col-md-8 type">
<a href="#method_writeComment">writeComment</a>(
string $str)
<p class="no-description">No description</p>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<abbr title="Library\CommandLine\$this">$this</abbr>
</div>
<div class="col-md-8 type">
<a href="#<API key>">writeHighlight</a>(
string $str)
<p class="no-description">No description</p>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<abbr title="Library\CommandLine\$this">$this</abbr>
</div>
<div class="col-md-8 type">
<a href="#method_writeBreak">writeBreak</a>()
<p class="no-description">No description</p>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<abbr title="Library\CommandLine\$this">$this</abbr>
</div>
<div class="col-md-8 type">
<a href="#method_writeStop">writeStop</a>()
<p class="no-description">No description</p>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<abbr title="Library\CommandLine\$this">$this</abbr>
</div>
<div class="col-md-8 type">
<a href="#method_verboseWrite">verboseWrite</a>(
null $str = null,
bool $new_line = true)
<p>Write a string only in verbose mode</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<abbr title="Library\CommandLine\$this">$this</abbr>
</div>
<div class="col-md-8 type">
<a href="#method_debugWrite">debugWrite</a>(
null $str = null,
bool $new_line = true)
<p>Write a string only in debug mode</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
string
</div>
<div class="col-md-8 type">
<a href="#method_prompt">prompt</a>(
string|null $str = null,
mixed|null $default = null)
<p>Prompt user input</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
string
</div>
<div class="col-md-8 type">
<a href="#method_getPrompt">getPrompt</a>()
<p>Get last user input</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#method_writeIntro">writeIntro</a>()
<p class="no-description">No description</p>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#<API key>">getVersionString</a>()
<p class="no-description">No description</p>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#<API key>">writeNothingToDo</a>()
<p class="no-description">No description</p>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#<API key>">runArgumentHelp</a>($arg = null)
<p class="no-description">No description</p>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#method_usage">usage</a>($opt = null)
<p class="no-description">No description</p>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#method_getopt">getopt</a>()
<p class="no-description">No description</p>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#<API key>">getOptionMethod</a>($arg = null)
<p class="no-description">No description</p>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#<API key>"><API key></a>($arg = null)
<p class="no-description">No description</p>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#<API key>">getOptionHelp</a>($arg = null)
<p class="no-description">No description</p>
</div>
<div class="col-md-2"></div>
</div>
</div>
<h2>Details</h2>
<div id="method-details">
<div class="method-item">
<h3 id="method___construct">
<div class="location">at line 175</div>
<code>
<strong>__construct</strong>(
array $options = array())</code>
</h3>
<div class="details">
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
array</td>
<td>$options</td>
<td>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method___toString">
<div class="location">at line 219</div>
<code>
string
<strong>__toString</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Magic distribution when printing object</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_distribute">
<div class="location">at line 228</div>
<code>
<strong>distribute</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Distribution of the work</p> </div>
<div class="tags">
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setDebug">
<div class="location">at line 248</div>
<code>
<a href="../../Library/CommandLine/<API key>.html"><abbr title="Library\CommandLine\<API key>"><API key></abbr></a>
<strong>setDebug</strong>(
bool $dbg = true)</code>
</h3>
<div class="details">
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
bool</td>
<td>$dbg</td>
<td>
</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../Library/CommandLine/<API key>.html"><abbr title="Library\CommandLine\<API key>"><API key></abbr></a></td>
<td>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setVerbose">
<div class="location">at line 259</div>
<code>
<abbr title="Library\CommandLine\$this">$this</abbr>
<strong>setVerbose</strong>(
bool $vbr = true)</code>
</h3>
<div class="details">
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
bool</td>
<td>$vbr</td>
<td>
</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Library\CommandLine\$this">$this</abbr></td>
<td>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setForce">
<div class="location">at line 269</div>
<code>
<abbr title="Library\CommandLine\$this">$this</abbr>
<strong>setForce</strong>(
bool $frc = true)</code>
</h3>
<div class="details">
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
bool</td>
<td>$frc</td>
<td>
</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Library\CommandLine\$this">$this</abbr></td>
<td>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="<API key>">
<div class="location">at line 279</div>
<code>
<abbr title="Library\CommandLine\$this">$this</abbr>
<strong>setInteractive</strong>(
bool $frc = true)</code>
</h3>
<div class="details">
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
bool</td>
<td>$frc</td>
<td>
</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Library\CommandLine\$this">$this</abbr></td>
<td>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setQuiet">
<div class="location">at line 290</div>
<code>
<abbr title="Library\CommandLine\$this">$this</abbr>
<strong>setQuiet</strong>()</code>
</h3>
<div class="details">
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Library\CommandLine\$this">$this</abbr></td>
<td>
</td>
</tr>
</table>
<h4>See also</h4>
<table class="table table-condensed">
<tr>
<td>self::setVerbose()</td>
<td></td>
</tr>
<tr>
<td>self::setDebug()</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="<API key>">
<div class="location">at line 301</div>
<code>
<strong>addDoneMethod</strong>(
string $_cls_meth)</code>
</h3>
<div class="details">
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td>$_cls_meth</td>
<td>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="<API key>">
<div class="location">at line 310</div>
<code>
array
<strong>getDoneMethods</strong>()</code>
</h3>
<div class="details">
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
array</td>
<td>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setScript">
<div class="location">at line 321</div>
<code>
<strong>setScript</strong>(
string $script_name)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Set the current command line script called</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td>$script_name</td>
<td>The script name</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getScript">
<div class="location">at line 332</div>
<code>
string|null
<strong>getScript</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the current command line script called</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
string|null</td>
<td>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="<API key>">
<div class="location">at line 343</div>
<code>
<strong>setParameters</strong>(
array $params)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Set the command line parameters</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
array</td>
<td>$params</td>
<td>The collection of parameters</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="<API key>">
<div class="location">at line 354</div>
<code>
array
<strong>getParameters</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the parameters collection</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
array</td>
<td>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="<API key>">
<div class="location">at line 368</div>
<code>
<strong>runHelpCommand</strong>($opt = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>List of all options and features of the command line tool ; for some commands, a specific help can be available, running <var>--command --help</var>
Some command examples are purposed running <var>--console --help</var></p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td></td>
<td>$opt</td>
<td>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="<API key>">
<div class="location">at line 391</div>
<code>
<strong>runVerboseCommand</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Run the command line in <bold>verbose</bold> mode, writing some information on screen (default is <option>OFF</option>)</p> </div>
<div class="tags">
</div>
</div>
</div>
<div class="method-item">
<h3 id="<API key>">
<div class="location">at line 399</div>
<code>
<strong>runQuietCommand</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Run the command line in <bold>quiet</bold> mode, trying to not write anything on screen (default is <option>OFF</option>)</p> </div>
<div class="tags">
</div>
</div>
</div>
<div class="method-item">
<h3 id="<API key>">
<div class="location">at line 407</div>
<code>
<strong>runDebugCommand</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Run the command line in <bold>debug</bold> mode, writing some scripts information during runtime (default is <option>OFF</option>)</p> </div>
<div class="tags">
</div>
</div>
</div>
<div class="method-item">
<h3 id="<API key>">
<div class="location">at line 415</div>
<code>
<strong>runForceCommand</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Run the command line in <bold>forced</bold> mode ; any choice will be set on default value if so</p> </div>
<div class="tags">
</div>
</div>
</div>
<div class="method-item">
<h3 id="<API key>">
<div class="location">at line 423</div>
<code>
<strong><API key></strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Run the command line in <bold>interactive</bold> mode ; any choice will be prompted if possible</p> </div>
<div class="tags">
</div>
</div>
</div>
<div class="method-item">
<h3 id="<API key>">
<div class="location">at line 431</div>
<code>
<strong>runVersionCommand</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get versions of system environment</p> </div>
<div class="tags">
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_write">
<div class="location">at line 460</div>
<code>
<abbr title="Library\CommandLine\$this">$this</abbr>
<strong>write</strong>(
null $str = null,
bool $new_line = true)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Format and write a string to STDOUT</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
null</td>
<td>$str</td>
<td>
</td>
</tr>
<tr>
<td>
bool</td>
<td>$new_line</td>
<td>
</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Library\CommandLine\$this">$this</abbr></td>
<td>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_error">
<div class="location">at line 474</div>
<code>
<abbr title="Library\CommandLine\$this">$this</abbr>
<strong>error</strong>(
null $str = null,
int $status = 1,
bool $new_line = true)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Format and write an error message to STDOUT (or STDERR) and exits with status <code>$status</code></p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
null</td>
<td>$str</td>
<td>
</td>
</tr>
<tr>
<td>
int</td>
<td>$status</td>
<td>
</td>
</tr>
<tr>
<td>
bool</td>
<td>$new_line</td>
<td>
</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Library\CommandLine\$this">$this</abbr></td>
<td>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="<API key>">
<div class="location">at line 488</div>
<code>
<abbr title="Library\CommandLine\$this">$this</abbr>
<strong>parseAndWrite</strong>(
string $str,
null $type = null,
bool $spaced = false)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Parse, format and write a message to STDOUT</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td>$str</td>
<td>
</td>
</tr>
<tr>
<td>
null</td>
<td>$type</td>
<td>
</td>
</tr>
<tr>
<td>
bool</td>
<td>$spaced</td>
<td>
</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Library\CommandLine\$this">$this</abbr></td>
<td>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_writeError">
<div class="location">at line 503</div>
<code>
<abbr title="Library\CommandLine\$this">$this</abbr>
<strong>writeError</strong>(
string $str)</code>
</h3>
<div class="details">
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td>$str</td>
<td>
</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Library\CommandLine\$this">$this</abbr></td>
<td>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="<API key>">
<div class="location">at line 514</div>
<code>
<abbr title="Library\CommandLine\$this">$this</abbr>
<strong>writeThinError</strong>(
string $str)</code>
</h3>
<div class="details">
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td>$str</td>
<td>
</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Library\CommandLine\$this">$this</abbr></td>
<td>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_writeInfo">
<div class="location">at line 526</div>
<code>
<abbr title="Library\CommandLine\$this">$this</abbr>
<strong>writeInfo</strong>(
string $str)</code>
</h3>
<div class="details">
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td>$str</td>
<td>
</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Library\CommandLine\$this">$this</abbr></td>
<td>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_writeComment">
<div class="location">at line 536</div>
<code>
<abbr title="Library\CommandLine\$this">$this</abbr>
<strong>writeComment</strong>(
string $str)</code>
</h3>
<div class="details">
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td>$str</td>
<td>
</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Library\CommandLine\$this">$this</abbr></td>
<td>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="<API key>">
<div class="location">at line 547</div>
<code>
<abbr title="Library\CommandLine\$this">$this</abbr>
<strong>writeHighlight</strong>(
string $str)</code>
</h3>
<div class="details">
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td>$str</td>
<td>
</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Library\CommandLine\$this">$this</abbr></td>
<td>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_writeBreak">
<div class="location">at line 556</div>
<code>
<abbr title="Library\CommandLine\$this">$this</abbr>
<strong>writeBreak</strong>()</code>
</h3>
<div class="details">
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Library\CommandLine\$this">$this</abbr></td>
<td>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_writeStop">
<div class="location">at line 565</div>
<code>
<abbr title="Library\CommandLine\$this">$this</abbr>
<strong>writeStop</strong>()</code>
</h3>
<div class="details">
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Library\CommandLine\$this">$this</abbr></td>
<td>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_verboseWrite">
<div class="location">at line 585</div>
<code>
<abbr title="Library\CommandLine\$this">$this</abbr>
<strong>verboseWrite</strong>(
null $str = null,
bool $new_line = true)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Write a string only in verbose mode</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
null</td>
<td>$str</td>
<td>
</td>
</tr>
<tr>
<td>
bool</td>
<td>$new_line</td>
<td>
</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Library\CommandLine\$this">$this</abbr></td>
<td>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_debugWrite">
<div class="location">at line 598</div>
<code>
<abbr title="Library\CommandLine\$this">$this</abbr>
<strong>debugWrite</strong>(
null $str = null,
bool $new_line = true)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Write a string only in debug mode</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
null</td>
<td>$str</td>
<td>
</td>
</tr>
<tr>
<td>
bool</td>
<td>$new_line</td>
<td>
</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Library\CommandLine\$this">$this</abbr></td>
<td>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_prompt">
<div class="location">at line 611</div>
<code>
string
<strong>prompt</strong>(
string|null $str = null,
mixed|null $default = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Prompt user input</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
string|null</td>
<td>$str</td>
<td>
</td>
</tr>
<tr>
<td>
mixed|null</td>
<td>$default</td>
<td>
</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getPrompt">
<div class="location">at line 624</div>
<code>
string
<strong>getPrompt</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get last user input</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_writeIntro">
<div class="location">at line 641</div>
<code>
<strong>writeIntro</strong>()</code>
</h3>
<div class="details">
<div class="tags">
</div>
</div>
</div>
<div class="method-item">
<h3 id="<API key>">
<div class="location">at line 651</div>
<code>
<strong>getVersionString</strong>()</code>
</h3>
<div class="details">
<div class="tags">
</div>
</div>
</div>
<div class="method-item">
<h3 id="<API key>">
<div class="location">at line 664</div>
<code>
<strong>writeNothingToDo</strong>()</code>
</h3>
<div class="details">
<div class="tags">
</div>
</div>
</div>
<div class="method-item">
<h3 id="<API key>">
<div class="location">at line 671</div>
<code>
<strong>runArgumentHelp</strong>($arg = null)</code>
</h3>
<div class="details">
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td></td>
<td>$arg</td>
<td>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_usage">
<div class="location">at line 684</div>
<code>
<strong>usage</strong>($opt = null)</code>
</h3>
<div class="details">
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td></td>
<td>$opt</td>
<td>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getopt">
<div class="location">at line 788</div>
<code>
<strong>getopt</strong>()</code>
</h3>
<div class="details">
<div class="tags">
</div>
</div>
</div>
<div class="method-item">
<h3 id="<API key>">
<div class="location">at line 795</div>
<code>
<strong>getOptionMethod</strong>($arg = null)</code>
</h3>
<div class="details">
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td></td>
<td>$arg</td>
<td>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="<API key>">
<div class="location">at line 802</div>
<code>
<strong><API key></strong>($arg = null)</code>
</h3>
<div class="details">
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td></td>
<td>$arg</td>
<td>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="<API key>">
<div class="location">at line 807</div>
<code>
<strong>getOptionHelp</strong>($arg = null)</code>
</h3>
<div class="details">
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td></td>
<td>$arg</td>
<td>
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
<div id="footer">
Generated by <a href="http://sami.sensiolabs.org/">Sami, the API Documentation Generator</a>.
</div>
</div>
</div>
</body>
</html>
|
#include "../config.h"
#if ENABLED(TOUCH_UI_FTDI_EVE) && defined(<API key>)
#include "screens.h"
using namespace FTDI;
using namespace Theme;
using namespace ExtUI;
void TuneMenu::onRedraw(draw_mode_t what) {
#define GRID_ROWS 8
#define GRID_COLS 2
if (what & BACKGROUND) {
CommandProcessor cmd;
cmd.cmd(CLEAR_COLOR_RGB(bg_color))
.cmd(CLEAR(true,true,true))
.cmd(COLOR_RGB(bg_text_enabled))
.tag(0)
.font(font_large)
.text( BTN_POS(1,1), BTN_SIZE(2,1), GET_TEXT_F(MSG_PRINT_MENU));
}
if (what & FOREGROUND) {
CommandProcessor cmd;
cmd.colors(normal_btn)
.font(font_medium)
.enabled( isPrinting()).tag(2).button( BTN_POS(1,2), BTN_SIZE(2,1), GET_TEXT_F(MSG_PRINT_SPEED))
.tag(3).button( BTN_POS(1,3), BTN_SIZE(2,1), GET_TEXT_F(MSG_BED_TEMPERATURE))
.enabled(TERN_(BABYSTEPPING, true))
.tag(4).button( BTN_POS(1,4), BTN_SIZE(2,1), GET_TEXT_F(MSG_NUDGE_NOZZLE))
.enabled(!isPrinting()).tag(5).button( BTN_POS(1,5), BTN_SIZE(2,1), GET_TEXT_F(MSG_MOVE_TO_HOME))
.enabled(!isPrinting()).tag(6).button( BTN_POS(1,6), BTN_SIZE(2,1), GET_TEXT_F(MSG_RAISE_PLUNGER))
.enabled(!isPrinting()).tag(7).button( BTN_POS(1,7), BTN_SIZE(2,1), GET_TEXT_F(MSG_RELEASE_XY_AXIS))
.colors(action_btn) .tag(1).button( BTN_POS(1,8), BTN_SIZE(2,1), GET_TEXT_F(MSG_BACK));
}
#undef GRID_COLS
#undef GRID_ROWS
}
bool TuneMenu::onTouchEnd(uint8_t tag) {
switch (tag) {
case 1: GOTO_PREVIOUS(); break;
case 2: GOTO_SCREEN(<API key>); break;
case 3: GOTO_SCREEN(TemperatureScreen); break;
case 4: GOTO_SCREEN(NudgeNozzleScreen); break;
case 5: GOTO_SCREEN(BioConfirmHomeXYZ); break;
case 6: SpinnerDialogBox::enqueueAndWait_P(F("G0 E0 F120")); break;
case 7: StatusScreen::unlockMotors(); break;
default:
return false;
}
return true;
}
#endif // TOUCH_UI_FTDI_EVE
|
#include "scene/Entity3D.h"
#include "scene/Node3D.h"
#include "math/Math.h"
#include "graphics/RenderList.h"
#include "system/LowLevelSystem.h"
#include "scene/PortalContainer.h"
namespace hpl {
// CONSTRUCTORS
iEntity3D::iEntity3D(tString asName) : iEntity(asName)
{
m_mtxLocalTransform = cMatrixf::Identity;
m_mtxWorldTransform = cMatrixf::Identity;
mbTransformUpdated = true;
mlCount = 0;
mlGlobalRenderCount = cRenderList::<API key>();
msSourceFile = "";
<API key> = true;
<API key> = true;
mpParent = NULL;
mlIteratorCount =-1;
mpCurrentSector = NULL;
}
iEntity3D::~iEntity3D()
{
if(mpParent) mpParent->RemoveChild(this);
for(tEntity3DListIt it = mlstChildren.begin(); it != mlstChildren.end();++it)
{
iEntity3D *pChild = *it;
pChild->mpParent = NULL;
}
}
// PUBLIC METHODS
cVector3f iEntity3D::GetLocalPosition()
{
return m_mtxLocalTransform.GetTranslation();
}
cMatrixf& iEntity3D::GetLocalMatrix()
{
return m_mtxLocalTransform;
}
cVector3f iEntity3D::GetWorldPosition()
{
<API key>();
return m_mtxWorldTransform.GetTranslation();
}
cMatrixf& iEntity3D::GetWorldMatrix()
{
<API key>();
return m_mtxWorldTransform;
}
void iEntity3D::SetPosition(const cVector3f& avPos)
{
m_mtxLocalTransform.m[0][3] = avPos.x;
m_mtxLocalTransform.m[1][3] = avPos.y;
m_mtxLocalTransform.m[2][3] = avPos.z;
SetTransformUpdated();
}
void iEntity3D::SetMatrix(const cMatrixf& a_mtxTransform)
{
m_mtxLocalTransform = a_mtxTransform;
SetTransformUpdated();
}
void iEntity3D::SetWorldPosition(const cVector3f& avWorldPos)
{
if(mpParent)
{
SetPosition(avWorldPos - mpParent->GetWorldPosition());
}
else
{
SetPosition(avWorldPos);
}
}
void iEntity3D::SetWorldMatrix(const cMatrixf& a_mtxWorldTransform)
{
if(mpParent)
{
SetMatrix(cMath::MatrixMul(cMath::MatrixInverse(mpParent->GetWorldMatrix()),
a_mtxWorldTransform));
}
else
{
SetMatrix(a_mtxWorldTransform);
}
}
void iEntity3D::SetTransformUpdated(bool abUpdateCallbacks)
{
mbTransformUpdated = true;
mlCount++;
//Perhaps not update this yet? This is baaaad!
if(<API key>)
mBoundingVolume.SetTransform(GetWorldMatrix());
<API key> = true;
//Update children
for(tEntity3DListIt EntIt = mlstChildren.begin(); EntIt != mlstChildren.end();++EntIt)
{
iEntity3D *pChild = *EntIt;
pChild->SetTransformUpdated(true);
}
//Update callbacks
if(mlstCallbacks.empty() || abUpdateCallbacks==false) return;
<API key> it = mlstCallbacks.begin();
for(; it!= mlstCallbacks.end(); ++it)
{
iEntityCallback* pCallback = *it;
pCallback->OnTransformUpdate(this);
}
}
bool iEntity3D::GetTransformUpdated()
{
return mbTransformUpdated;
}
int iEntity3D::<API key>()
{
return mlCount;
}
void iEntity3D::AddCallback(iEntityCallback *apCallback)
{
mlstCallbacks.push_back(apCallback);
}
void iEntity3D::RemoveCallback(iEntityCallback *apCallback)
{
STLFindAndDelete(mlstCallbacks, apCallback);
}
void iEntity3D::AddChild(iEntity3D *apEntity)
{
if(apEntity==NULL)return;
if(apEntity->mpParent != NULL) return;
mlstChildren.push_back(apEntity);
apEntity->mpParent = this;
apEntity->SetTransformUpdated(true);
}
void iEntity3D::RemoveChild(iEntity3D *apEntity)
{
for(tEntity3DListIt it = mlstChildren.begin(); it != mlstChildren.end();)
{
iEntity3D *pChild = *it;
if(pChild == apEntity)
{
pChild->mpParent = NULL;
it = mlstChildren.erase(it);
}
else
{
++it;
}
}
}
bool iEntity3D::IsChild(iEntity3D *apEntity)
{
for(tEntity3DListIt it = mlstChildren.begin(); it != mlstChildren.end();++it)
{
iEntity3D *pChild = *it;
if(pChild == apEntity) return true;
}
return false;
}
iEntity3D * iEntity3D::GetEntityParent()
{
return mpParent;
}
bool iEntity3D::IsInSector(cSector *apSector)
{
//Log("-- %s --\n",msName.c_str());
//bool bShouldReturnTrue = false;
if(apSector == GetCurrentSector())
{
//Log("Should return true\n");
//bShouldReturnTrue = true;
return true;
}
<API key> *pDataList = <API key>();
<API key> it = pDataList->begin();
for(; it != pDataList->end(); ++it)
{
<API key> *<API key> = *it;
cSector *pSector = static_cast<cSector*>(<API key>);
//Log("%s (%d) vs %s (%d)\n",pSector->GetId().c_str(),pSector, apSector->GetId().c_str(),apSector);
if(pSector == apSector)
{
//Log("return true!\n");
return true;
}
}
//if(bShouldReturnTrue)Log(" %s should have returned true. Sectors: %d\n",msName.c_str(), <API key>.size());
//Log("return false!\n");
return false;
}
// PRIVATE METHODS
void iEntity3D::<API key>()
{
if(mbTransformUpdated)
{
mbTransformUpdated = false;
//first check if there is a node parent
if(mpParentNode)
{
cNode3D* pNode3D = static_cast<cNode3D*>(mpParentNode);
m_mtxWorldTransform = cMath::MatrixMul(pNode3D->GetWorldMatrix(), m_mtxLocalTransform);
}
//If there is no node parent check for entity parent
else if(mpParent)
{
m_mtxWorldTransform = cMath::MatrixMul(mpParent->GetWorldMatrix(), m_mtxLocalTransform);
}
else
{
m_mtxWorldTransform = m_mtxLocalTransform;
}
}
}
// SAVE OBJECT STUFF
<API key>(cSaveData_iEntity3D,cSaveData_iEntity)
kSerializeVar(m_mtxLocalTransform,<API key>)
kSerializeVar(mBoundingVolume,<API key>)
kSerializeVar(msSourceFile,<API key>)
kSerializeVar(mlParentId,<API key>)
<API key>(mlstChildren,<API key>)
kEndSerialize()
iSaveData* iEntity3D::CreateSaveData()
{
return NULL;
}
void iEntity3D::SaveToSaveData(iSaveData *apSaveData)
{
<API key>(iEntity3D);
kSaveData_SaveTo(m_mtxLocalTransform);
kSaveData_SaveTo(mBoundingVolume);
kSaveData_SaveTo(msSourceFile);
<API key>(mpParent,mlParentId);
<API key>(mlstChildren,tEntity3DListIt,mlstChildren);
/*if(mlstChildren.empty()==false)
{
Log("Children in '%s'/'%s': ",msName.c_str(),GetEntityType().c_str());
for(tEntity3DListIt it=mlstChildren.begin(); it != mlstChildren.end(); ++it)
{
iEntity3D *pEntity = *it;
Log("('%d/%s'/'%s'), ",pEntity->GetSaveObjectId(),pEntity->GetName().c_str(),pEntity->GetEntityType().c_str());
}
Log("\n");
}*/
}
void iEntity3D::LoadFromSaveData(iSaveData *apSaveData)
{
<API key>(iEntity3D);
SetMatrix(pData->m_mtxLocalTransform);
//Not sure of this is needed:
kSaveData_LoadFrom(mBoundingVolume);
kSaveData_LoadFrom(msSourceFile);
}
void iEntity3D::SaveDataSetup(cSaveObjectHandler *apSaveObjectHandler, cGame *apGame)
{
<API key>(iEntity3D);
//<API key>(mpParent,mlParentId,iEntity3D*);
//<API key>(mlstChildren,mlstChildren,iEntity3D*);
if(pData->mlParentId!=-1 && mpParent == NULL)
{
iEntity3D *pParentEntity = static_cast<iEntity3D*>(apSaveObjectHandler->Get(pData->mlParentId));
if(pParentEntity)
pParentEntity->AddChild(this);
else
Error("Couldn't find parent entity id %d for '%s'\n",pData->mlParentId,GetName().c_str());
}
<API key><int> it = pData->mlstChildren.GetIterator();
while(it.HasNext())
{
int mlId = it.Next();
if(mlId != -1)
{
iEntity3D *pChildEntity = static_cast<iEntity3D*>(apSaveObjectHandler->Get(mlId));
if(pChildEntity)
AddChild(pChildEntity);
else
Error("Couldn't find child entity id %d for '%s'\n",mlId,GetName().c_str());
}
}
SetTransformUpdated(true);
}
}
|
from feeluown.utils.dispatch import Signal
from feeluown.gui.widgets.my_music import MyMusicModel
class MyMusicItem(object):
def __init__(self, text):
self.text = text
self.clicked = Signal()
class MyMusicUiManager:
"""
.. note::
items add_item clear
MyMusic items provider provider MyMusic
Provider get_item
"""
def __init__(self, app):
self._app = app
self._items = []
self.model = MyMusicModel(app)
@classmethod
def create_item(cls, text):
return MyMusicItem(text)
def add_item(self, item):
self.model.add(item)
self._items.append(item)
def clear(self):
self._items.clear()
self.model.clear()
|
(function() {
var app = angular.module('article-directive', ['ui.bootstrap.contextMenu']);
app.config(function($sceProvider) {
// Completely disable SCE. For demonstration purposes only!
// Do not use in new projects.
$sceProvider.enabled(false);
});
app.directive('article', function () {
var controller = function () {
var vm = this;
};
var getSelectionText = function() {
if(window.getSelection) {
return window.getSelection().toString();
}
if(document.selection && document.selection.type != "Control") {
return document.selection.createRange().text;
}
return "";
};
var link = function link(scope, element, attrs) {
scope.toggleComments = function () {
scope.$broadcast("event:toggle");
}
scope.menuOptions = [['Copy', function ($itemScope) {
}],
null, // Dividier
['Comment', function ($itemScope) {
scope.toggleComments();
}]];
};
return {
restrict: 'EA', //Default for 1.3+
scope: {
text: '@text',
url: '@url'
},
controller: controller,
link: link,
controllerAs: 'vm',
bindToController: true, //required in 1.3+ with controllerAs
templateUrl: '/article/article.html'
};
});
}());
|
package org.quantumbadger.redreader.io;
import org.quantumbadger.redreader.common.collections.<API key>;
public class <API key><K, V extends WritableObject<K>>
implements <API key>.ArgOperator<<API key><K, V>, V> {
@Override
public void operate(final <API key><K, V> listener, final V data) {
listener.onUpdatedVersion(data);
}
}
|
# Only run if this is an interactive text bash session
if [ -n "$PS1" ] && [ -n "$BASH_VERSION" ] && [ -z "$DISPLAY" ]; then
echo "Press enter to activate this console"
read answer
# The user should have chosen their preferred keyboard layout
# in tails-greeter by now.
. /etc/default/locale
. /etc/default/keyboard
sudo setupcon
fi
|
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_131) on Sat Oct 28 21:24:43 CEST 2017 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class nxt.util.MiningPlot (burstcoin 1.3.6cg API)</title>
<meta name="date" content="2017-10-28">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class nxt.util.MiningPlot (burstcoin 1.3.6cg API)";
}
}
catch(err) {
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="topNav"><a name="navbar.top">
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../nxt/util/MiningPlot.html" title="class in nxt.util">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?nxt/util/class-use/MiningPlot.html" target="_top">Frames</a></li>
<li><a href="MiningPlot.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">
<h2 title="Uses of Class nxt.util.MiningPlot" class="title">Uses of Class<br>nxt.util.MiningPlot</h2>
</div>
<div class="classUseContainer">No usage of nxt.util.MiningPlot</div>
<div class="bottomNav"><a name="navbar.bottom">
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../nxt/util/MiningPlot.html" title="class in nxt.util">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?nxt/util/class-use/MiningPlot.html" target="_top">Frames</a></li>
<li><a href="MiningPlot.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>
<p class="legalCopy"><small>Copyright &
</body>
</html>
|
#include "<API key>.h"
<API key>::<API key>(const char *uuid, const char *label) :
GnuHawkBlock(uuid, label),
serviceThread(0),
noutput_items(0),
_maintainTimeStamp(false),
_throttle(false)
{
construct();
}
void <API key>::construct()
{
Resource_impl::_started = false;
loadProperties();
serviceThread = 0;
sentEOS = false;
inputPortOrder.resize(0);;
outputPortOrder.resize(0);
PortableServer::ObjectId_var oid;
float_in = new bulkio::InFloatPort("float_in");
float_in-><API key>(this, &<API key>::<API key>);
oid = ossie::corba::RootPOA()->activate_object(float_in);
float_out = new bulkio::OutFloatPort("float_out");
oid = ossie::corba::RootPOA()->activate_object(float_out);
registerInPort(float_in);
inputPortOrder.push_back("float_in");
registerOutPort(float_out, float_out->_this());
outputPortOrder.push_back("float_out");
}
void <API key>::initialize() throw (CF::LifeCycle::InitializeError, CORBA::SystemException)
{
}
void <API key>::start() throw (CORBA::SystemException, CF::Resource::StartError)
{
boost::mutex::scoped_lock lock(serviceThreadLock);
if (serviceThread == 0) {
float_in->unblock();
serviceThread = new ProcessThread<<API key>>(this, 0.1);
serviceThread->start();
}
if (!Resource_impl::started()) {
Resource_impl::start();
}
}
void <API key>::stop() throw (CORBA::SystemException, CF::Resource::StopError)
{
if ( float_in ) float_in->block();
{
boost::mutex::scoped_lock lock(_sriMutex);
_sriQueue.clear();
}
// release the child thread (if it exists)
if (serviceThread != 0) {
{
boost::mutex::scoped_lock lock(serviceThreadLock);
LOG_TRACE( <API key>, "Stopping Service Function" );
serviceThread->stop();
}
if ( !serviceThread->release()) {
throw CF::Resource::StopError(CF::CF_NOTSET, "Processing thread did not die");
}
boost::mutex::scoped_lock lock(serviceThreadLock);
if ( serviceThread ) {
delete serviceThread;
}
}
serviceThread = 0;
if (Resource_impl::started()) {
Resource_impl::stop();
}
LOG_TRACE( <API key>, "COMPLETED STOP REQUEST" );
}
CORBA::Object_ptr <API key>::getPort(const char* _id) throw (CORBA::SystemException, CF::PortSupplier::UnknownPort)
{
std::map<std::string, <API key> *>::iterator p_in = inPorts.find(std::string(_id));
if (p_in != inPorts.end()) {
if (!strcmp(_id,"float_in")) {
bulkio::InFloatPort *ptr = dynamic_cast<bulkio::InFloatPort *>(p_in->second);
if (ptr) {
return ptr->_this();
}
}
}
std::map<std::string, CF::Port_var>::iterator p_out = outPorts_var.find(std::string(_id));
if (p_out != outPorts_var.end()) {
return CF::Port::_duplicate(p_out->second);
}
throw (CF::PortSupplier::UnknownPort());
}
void <API key>::releaseObject() throw (CORBA::SystemException, CF::LifeCycle::ReleaseError)
{
// This function clears the component running condition so main shuts down everything
try {
stop();
} catch (CF::Resource::StopError& ex) {
// TODO - this should probably be logged instead of ignored
}
// deactivate ports
releaseInPorts();
releaseOutPorts();
delete(float_in);
delete(float_out);
Resource_impl::releaseObject();
}
void <API key>::loadProperties()
{
addProperty(item_size,
4,
"item_size",
"item_size",
"readonly",
"",
"external",
"configure");
addProperty(nstreams,
1,
"nstreams",
"nstreams",
"readonly",
"",
"external",
"configure");
}
// Allow for logging
PREPARE_LOGGING(<API key>);
inline static unsigned int
round_up (unsigned int n, unsigned int multiple)
{
return ((n + multiple - 1) / multiple) * multiple;
}
inline static unsigned int
round_down (unsigned int n, unsigned int multiple)
{
return (n / multiple) * multiple;
}
uint32_t <API key>::getNOutputStreams() {
return 0;
}
void <API key>::setupIOMappings( )
{
int ninput_streams = 0;
int noutput_streams = 0;
std::vector<std::string>::iterator pname;
std::string sid("");
int inMode=RealMode;
if ( !validGRBlock() ) return;
ninput_streams = gr_sptr-><API key>();
<API key> g_isig = gr_sptr->input_signature();
noutput_streams = gr_sptr-><API key>();
<API key> g_osig = gr_sptr->output_signature();
LOG_DEBUG( <API key>, "GNUHAWK IO MAPPINGS IN/OUT " << ninput_streams << "/" << noutput_streams );
// Someone reset the GR Block so we need to clean up old mappings if they exists
// we need to reset the io signatures and check the vlens
if ( _istreams.size() > 0 || _ostreams.size() > 0 ) {
LOG_DEBUG( <API key>, "RESET INPUT SIGNATURE SIZE:" << _istreams.size() );
IStreamList::iterator istream;
for ( int idx=0 ; istream != _istreams.end(); idx++, istream++ ) {
// re-add existing stream definitons
LOG_DEBUG( <API key>, "ADD READ INDEX TO GNU RADIO BLOCK");
if ( ninput_streams == -1 ) gr_sptr->add_read_index();
// setup io signature
istream->associate( gr_sptr );
}
LOG_DEBUG( <API key>, "RESET OUTPUT SIGNATURE SIZE:" << _ostreams.size() );
OStreamList::iterator ostream;
for ( int idx=0 ; ostream != _ostreams.end(); idx++, ostream++ ) {
// need to evaluate new settings...???
ostream->associate( gr_sptr );
}
return;
}
// Setup mapping of RH port to GNU RADIO Block input streams
// For version 1, we are ignoring the GNU Radio input stream -1 case that allows multiple data
// streams over a single connection. We are mapping a single RH Port to a single GNU Radio stream.
// Stream Identifiers will be pass along as they are received
LOG_TRACE( <API key>, "setupIOMappings INPUT PORTS: " << inPorts.size() );
pname = inputPortOrder.begin();
for( int i=0; pname != inputPortOrder.end(); pname++ ) {
// grab ports based on their order in the scd.xml file
RH_ProvidesPortMap::iterator p_in = inPorts.find(*pname);
if ( p_in != inPorts.end() ) {
bulkio::InFloatPort *port = dynamic_cast< bulkio::InFloatPort * >(p_in->second);
int mode = inMode;
sid = "";
// need to add read index to GNU Radio Block for processing streams when max_input == -1
if ( ninput_streams == -1 ) gr_sptr->add_read_index();
// check if we received SRI during setup
BULKIO::<API key> sris = port->activeSRIs();
if ( sris->length() > 0 ) {
BULKIO::StreamSRI sri = sris[sris->length()-1];
mode = sri.mode;
}
std::vector<int> in;
io_mapping.push_back( in );
_istreams.push_back( gr_istream< bulkio::InFloatPort > ( port, gr_sptr, i, mode, sid ));
LOG_DEBUG( <API key>, "ADDING INPUT MAP IDX:" << i << " SID:" << sid );
// increment port counter
i++;
}
}
// Setup mapping of RH port to GNU RADIO Block input streams
// For version 1, we are ignoring the GNU Radio output stream -1 case that allows multiple data
// streams over a single connection. We are mapping a single RH Port to a single GNU Radio stream.
LOG_TRACE( <API key>, "setupIOMappings OutputPorts: " << outPorts.size() );
pname = outputPortOrder.begin();
for( int i=0; pname != outputPortOrder.end(); pname++ ) {
// grab ports based on their order in the scd.xml file
RH_UsesPortMap::iterator p_out = outPorts.find(*pname);
if ( p_out != outPorts.end() ) {
bulkio::OutFloatPort *port = dynamic_cast< bulkio::OutFloatPort * >(p_out->second);
int idx = -1;
BULKIO::StreamSRI sri = createOutputSRI( i, idx );
if (idx == -1) idx = i;
if(idx < (int)io_mapping.size()) io_mapping[idx].push_back(i);
int mode = sri.mode;
sid = sri.streamID;
_ostreams.push_back( gr_ostream< bulkio::OutFloatPort > ( port, gr_sptr, i, mode, sid ));
LOG_DEBUG( <API key>, "ADDING OUTPUT MAP IDX:" << i << " SID:" << sid );
_ostreams[i].setSRI(sri, i );
// increment port counter
i++;
}
}
}
void <API key>::<API key>( BULKIO::StreamSRI &sri )
{
LOG_TRACE( <API key>, "START NotifySRI port:stream " << float_in->getName() << "/" << sri.streamID);
boost::mutex::scoped_lock lock(_sriMutex);
_sriQueue.push_back( std::make_pair( float_in, sri ) );
LOG_TRACE( <API key>, "END NotifySRI QUEUE " << _sriQueue.size() << " port:stream " << float_in->getName() << "/" << sri.streamID);
}
void <API key>::<API key>()
{
boost::mutex::scoped_lock lock(_sriMutex);
LOG_TRACE( <API key>, "<API key> QUEUE: " << _sriQueue.size() );
if ( _sriQueue.size() == 0 ) return;
std::string sid("");
if ( validGRBlock() ) {
IStreamList::iterator istream;
int idx=0;
std::string sid("");
int mode=0;
SRIQueue::iterator item = _sriQueue.begin();
for ( ; item != _sriQueue.end(); item++ ) {
idx = 0;
sid = "";
mode= item->second.mode;
sid = item->second.streamID;
istream = _istreams.begin();
for ( ; istream != _istreams.end(); idx++, istream++ ) {
if ( istream->port == item->first ) {
LOG_DEBUG( <API key>, " SETTING IN_STREAM ID/STREAM_ID :" << idx << "/" << sid );
istream->sri(true);
istream->spe(mode);
LOG_DEBUG( <API key>, " SETTING OUT_STREAM ID/STREAM_ID :" << idx << "/" << sid );
setOutputStreamSRI( idx, item->second );
}
}
}
_sriQueue.clear();
} else {
LOG_WARN( <API key>, " NEW STREAM ID, NO GNU RADIO BLOCK DEFINED, SRI QUEUE SIZE:" << _sriQueue.size() );
}
}
BULKIO::StreamSRI <API key>::createOutputSRI( int32_t oidx ) {
// for each output stream set the SRI context
BULKIO::StreamSRI sri = BULKIO::StreamSRI();
sri.hversion = 1;
sri.xstart = 0.0;
sri.xdelta = 1;
sri.xunits = BULKIO::UNITS_TIME;
sri.subsize = 0;
sri.ystart = 0.0;
sri.ydelta = 0.0;
sri.yunits = BULKIO::UNITS_NONE;
sri.mode = 0;
std::ostringstream t;
t << naming_service_name.c_str() << "_" << oidx;
std::string sid = t.str();
sri.streamID = CORBA::string_dup(sid.c_str());
return sri;
}
BULKIO::StreamSRI <API key>::createOutputSRI( int32_t oidx, int32_t &in_idx)
{
return createOutputSRI( oidx );
}
void <API key>::adjustOutputRate(BULKIO::StreamSRI &sri )
{
if ( validGRBlock() ) {
double ret=sri.xdelta*gr_sptr->relative_rate();
/**
ret = ret / gr_sptr->interpolation();
**/
LOG_TRACE( <API key>, "ADJUSTING SRI.XDELTA FROM/TO: " << sri.xdelta << "/" << ret );
sri.xdelta = ret;
}
}
<API key>::TimeDuration <API key>::getTargetDuration()
{
TimeDuration t_drate;;
uint64_t samps=0;
double xdelta=1.0;
double trate=1.0;
if ( _ostreams.size() > 0 ) {
samps= _ostreams[0].nelems();
xdelta= _ostreams[0].sri.xdelta;
}
trate = samps*xdelta;
uint64_t sec = (uint64_t)trunc(trate);
uint64_t usec = (uint64_t)((trate-sec)*1e6);
t_drate = boost::posix_time::seconds(sec) +
boost::posix_time::microseconds(usec);
LOG_TRACE( <API key>, " SEC/USEC " << sec << "/" << usec << "\n" <<
" target_duration " << t_drate );
return t_drate;
}
<API key>::TimeDuration <API key>::calcThrottle( TimeMark &start_time,
TimeMark &end_time )
{
TimeDuration delta;
TimeDuration target_duration = getTargetDuration();
if ( start_time.is_not_a_date_time() == false ) {
TimeDuration s_dtime= end_time - start_time;
delta = target_duration - s_dtime;
delta /= 4;
LOG_TRACE( <API key>, " s_time/t_dime " << s_dtime << "/" << target_duration << "\n" <<
" delta " << delta );
}
return delta;
}
template < typename IN_PORT_TYPE, typename OUT_PORT_TYPE > int <API key>::<API key>( typename std::vector< gr_istream< IN_PORT_TYPE > > &istreams ,
typename std::vector< gr_ostream< OUT_PORT_TYPE > > &ostreams )
{
typedef typename std::vector< gr_istream< IN_PORT_TYPE > > _IStreamList;
typedef typename std::vector< gr_ostream< OUT_PORT_TYPE > > _OStreamList;
boost::mutex::scoped_lock lock(serviceThreadLock);
if ( validGRBlock() == false ) {
// create our processing block, and setup property notifiers
createBlock();
LOG_DEBUG( <API key>, " FINISHED BUILDING GNU RADIO BLOCK");
}
//process any Stream ID changes this could affect number of io streams
<API key>();
if ( !validGRBlock() || istreams.size() == 0 || ostreams.size() == 0 ) {
LOG_WARN( <API key>, "NO STREAMS ATTACHED TO BLOCK..." );
return NOOP;
}
_input_ready.resize( istreams.size() );
<API key>.resize( istreams.size() );
_ninput_items.resize( istreams.size() );
_input_items.resize( istreams.size() );
_output_items.resize( ostreams.size() );
// RESOLVE: need to look at forecast strategy,
// 1) see how many read items are necessary for N number of outputs
// 2) read input data and see how much output we can produce
// Grab available data from input streams
typename _OStreamList::iterator ostream;
typename _IStreamList::iterator istream = istreams.begin();
int nitems=0;
for ( int idx=0 ; istream != istreams.end() && serviceThread->threadRunning() ; idx++, istream++ ) {
// note this a blocking read that can cause deadlocks
nitems = istream->read();
if ( istream->overrun() ) {
LOG_WARN( <API key>, " NOT KEEPING UP WITH STREAM ID:" << istream->streamID );
}
if ( istream->sriChanged() ) {
// RESOLVE - need to look at how SRI changes can affect Gnu Radio BLOCK state
LOG_DEBUG( <API key>, "SRI CHANGED, STREAMD IDX/ID: "
<< idx << "/" << istream->pkt->streamID );
setOutputStreamSRI( idx, istream->pkt->SRI );
}
}
LOG_TRACE( <API key>, "READ NITEMS: " << nitems );
if ( nitems <= 0 && !_istreams[0].eos() ) {
return NOOP;
}
bool eos = false;
int nout = 0;
bool workDone = false;
while ( nout > -1 && serviceThread->threadRunning() ) {
eos = false;
nout = _forecastAndProcess( eos, istreams, ostreams );
if ( nout > -1 ) {
workDone = true;
// we chunked on data so move read pointer..
istream = istreams.begin();
for ( ; istream != istreams.end(); istream++ ) {
int idx=std::distance( istreams.begin(), istream );
// if we processed data for this stream
if ( _input_ready[idx] ) {
size_t nitems = 0;
try {
nitems = gr_sptr->nitems_read( idx );
} catch(...){}
if ( nitems > istream->nitems() ) {
LOG_WARN( <API key>, "WORK CONSUMED MORE DATA THAN AVAILABLE, READ/AVAILABLE "
<< nitems << "/" << istream->nitems() );
nitems = istream->nitems();
}
istream->consume( nitems );
LOG_TRACE( <API key>, " CONSUME READ DATA ITEMS/REMAIN " << nitems << "/" << istream->nitems());
}
}
gr_sptr->reset_read_index();
}
// check for not enough data return
if ( nout == -1 ) {
// check for end of stream
istream = istreams.begin();
for ( ; istream != istreams.end() ; istream++) {
if ( istream->eos() ) {
eos=true;
}
}
if ( eos ) {
LOG_TRACE( <API key>, "EOS SEEN, SENDING DOWNSTREAM " );
_forecastAndProcess( eos, istreams, ostreams);
}
}
}
if ( eos ) {
istream = istreams.begin();
for ( ; istream != istreams.end() ; istream++ ) {
int idx=std::distance( istreams.begin(), istream );
LOG_DEBUG( <API key>, " CLOSING INPUT STREAM IDX:" << idx );
istream->close();
}
// close remaining output streams
ostream = ostreams.begin();
for ( ; eos && ostream != ostreams.end(); ostream++ ) {
int idx=std::distance( ostreams.begin(), ostream );
LOG_DEBUG( <API key>, " CLOSING OUTPUT STREAM IDX:" << idx );
ostream->close();
}
}
// set the read pointers of the GNU Radio Block to start at the beginning of the
// supplied buffers
gr_sptr->reset_read_index();
LOG_TRACE( <API key>, " END OF TRANSFORM SERVICE FUNCTION....." << noutput_items );
if ( nout == -1 && eos == false && !workDone ) {
return NOOP;
} else {
return NORMAL;
}
}
template < typename IN_PORT_TYPE, typename OUT_PORT_TYPE > int <API key>::_forecastAndProcess( bool &eos, typename std::vector< gr_istream< IN_PORT_TYPE > > &istreams ,
typename std::vector< gr_ostream< OUT_PORT_TYPE > > &ostreams )
{
typedef typename std::vector< gr_istream< IN_PORT_TYPE > > _IStreamList;
typedef typename std::vector< gr_ostream< OUT_PORT_TYPE > > _OStreamList;
typename _OStreamList::iterator ostream;
typename _IStreamList::iterator istream = istreams.begin();
int nout = 0;
bool dataReady = false;
if ( !eos ) {
uint64_t max_items_avail = 0;
for ( int idx=0 ; istream != istreams.end() && serviceThread->threadRunning() ; idx++, istream++ ) {
LOG_TRACE( <API key>, "GET MAX ITEMS: STREAM:"<< idx << " NITEMS/SCALARS:" <<
istream->nitems() << "/" << istream->_data.size() );
max_items_avail = std::max( istream->nitems(), max_items_avail );
}
if ( max_items_avail == 0 ) {
LOG_TRACE( <API key>, "DATA CHECK - MAX ITEMS NOUTPUT/MAX_ITEMS:" << noutput_items << "/" << max_items_avail);
return -1;
}
// calc number of output elements based on input items available
noutput_items = 0;
if ( !gr_sptr->fixed_rate() ) {
noutput_items = round_down((int32_t) (max_items_avail * gr_sptr->relative_rate()), gr_sptr->output_multiple());
LOG_TRACE( <API key>, " VARIABLE FORECAST NOUTPUT == " << noutput_items );
} else {
istream = istreams.begin();
for ( int i=0; istream != istreams.end(); i++, istream++ ) {
int t_noutput_items = gr_sptr-><API key>( istream->nitems() );
if ( gr_sptr->output_multiple_set() ) {
t_noutput_items = round_up(t_noutput_items, gr_sptr->output_multiple());
}
if ( t_noutput_items > 0 ) {
if ( noutput_items == 0 ) {
noutput_items = t_noutput_items;
}
if ( t_noutput_items <= noutput_items ) {
noutput_items = t_noutput_items;
}
}
}
LOG_TRACE( <API key>, " FIXED FORECAST NOUTPUT/output_multiple == " <<
noutput_items << "/" << gr_sptr->output_multiple());
}
// ask the block how much input they need to produce noutput_items...
// if enough data is available to process then set the dataReady flag
int32_t outMultiple = gr_sptr->output_multiple();
while ( !dataReady && noutput_items >= outMultiple ) {
// ask the block how much input they need to produce noutput_items...
gr_sptr->forecast(noutput_items, <API key>);
LOG_TRACE( <API key>, "--> FORECAST IN/OUT " << <API key>[0] << "/" << noutput_items );
istream = istreams.begin();
uint32_t dr_cnt=0;
for ( int idx=0 ; noutput_items > 0 && istream != istreams.end(); idx++, istream++ ) {
// check if buffer has enough elements
_input_ready[idx] = false;
if ( istream->nitems() >= (uint64_t)<API key>[idx] ) {
_input_ready[idx] = true;
dr_cnt++;
}
LOG_TRACE( <API key>, "ISTREAM DATACHECK NELMS/NITEMS/REQ/READY:" << istream->nelems() <<
"/" << istream->nitems() << "/" << <API key>[idx] << "/" << _input_ready[idx]);
}
if ( dr_cnt < istreams.size() ) {
if ( outMultiple > 1 ) {
noutput_items -= outMultiple;
} else {
noutput_items /= 2;
}
} else {
dataReady = true;
}
LOG_TRACE( <API key>, " TRIM FORECAST NOUTPUT/READY " << noutput_items << "/" << dataReady );
}
// check if data is ready...
if ( !dataReady ) {
LOG_TRACE( <API key>, "DATA CHECK - NOT ENOUGH DATA AVAIL/REQ:" << _istreams[0].nitems() <<
"/" << <API key>[0] );
return -1;
}
// reset looping variables
int ritems = 0;
int nitems = 0;
// reset caching vectors
_output_items.clear();
_input_items.clear();
_ninput_items.clear();
istream = istreams.begin();
for ( int idx=0 ; istream != istreams.end(); idx++, istream++ ) {
// check if the stream is ready
if ( !_input_ready[idx] ) {
continue;
}
// get number of items remaining
try {
ritems = gr_sptr->nitems_read( idx );
} catch(...){
// something bad has happened, we are missing an input stream
LOG_ERROR( <API key>, "MISSING INPUT STREAM FOR GR BLOCK, STREAM ID:" << istream->streamID );
return -2;
}
nitems = istream->nitems() - ritems;
LOG_TRACE( <API key>, " ISTREAM: IDX:" << idx << " ITEMS AVAIL/READ/REQ " << nitems << "/"
<< ritems << "/" << <API key>[idx] );
if ( nitems >= <API key>[idx] && nitems > 0 ) {
//remove eos checks ...if ( nitems < <API key>[idx] ) nitems=0;
_ninput_items.push_back( nitems );
_input_items.push_back( (const void *) (istream->read_pointer(ritems)) );
}
}
// setup output buffer vector based on noutput..
ostream = ostreams.begin();
for( ; ostream != ostreams.end(); ostream++ ) {
ostream->resize(noutput_items);
_output_items.push_back((void*)(ostream->write_pointer()) );
}
nout=0;
if ( _input_items.size() != 0 && serviceThread->threadRunning() ) {
LOG_TRACE( <API key>, " CALLING WORK.....N_OUT:" << noutput_items << " N_IN:" << nitems
<< " ISTREAMS:" << _input_items.size() << " OSTREAMS:" << _output_items.size());
nout = gr_sptr->general_work( noutput_items, _ninput_items, _input_items, _output_items);
LOG_TRACE( <API key>, "RETURN WORK ..... N_OUT:" << nout);
}
// check for stop condition from work method
if ( nout < gr_block::WORK_DONE ) {
LOG_WARN( <API key>, "WORK RETURNED STOP CONDITION..." << nout );
nout=0;
eos = true;
}
}
if (nout != 0 or eos ) {
noutput_items = nout;
LOG_TRACE( <API key>, " WORK RETURNED: NOUT : " << nout << " EOS:" << eos);
ostream = ostreams.begin();
typename IN_PORT_TYPE::dataTransfer *pkt=NULL;
for ( int idx=0 ; ostream != ostreams.end(); idx++, ostream++ ) {
pkt=NULL;
int inputIdx = idx;
if ( (size_t)(inputIdx) >= istreams.size() ) {
for ( inputIdx= istreams.size()-1; inputIdx > -1; inputIdx
if ( istreams[inputIdx].pkt != NULL ) {
pkt = istreams[inputIdx].pkt;
break;
}
}
} else {
pkt = istreams[inputIdx].pkt;
}
LOG_TRACE( <API key>, "PUSHING DATA ITEMS/STREAM_ID " << ostream->nitems() << "/" << ostream->streamID );
if ( _maintainTimeStamp ) {
// set time stamp for output samples based on input time stamp
if ( ostream->nelems() == 0 ) {
#ifdef TEST_TIME_STAMP
LOG_DEBUG( <API key>, "SEED - TS SRI: xdelta:" << std::setprecision(12) << ostream->sri.xdelta );
LOG_DEBUG( <API key>, "OSTREAM WRITE: maint:" << _maintainTimeStamp );
LOG_DEBUG( <API key>, " mode:" << ostream->tstamp.tcmode );
LOG_DEBUG( <API key>, " status:" << ostream->tstamp.tcstatus );
LOG_DEBUG( <API key>, " offset:" << ostream->tstamp.toff );
LOG_DEBUG( <API key>, " whole:" << std::setprecision(10) << ostream->tstamp.twsec );
LOG_DEBUG( <API key>, "SEED - TS frac:" << std::setprecision(12) << ostream->tstamp.tfsec );
#endif
ostream->setTimeStamp( pkt->T, _maintainTimeStamp );
}
// write out samples, and set next time stamp based on xdelta and noutput_items
ostream->write ( noutput_items, eos );
} else {
// use incoming packet's time stamp to forward
if ( pkt ) {
#ifdef TEST_TIME_STAMP
LOG_DEBUG( <API key>, "OSTREAM SRI: items/xdelta:" << noutput_items << "/" << std::setprecision(12) << ostream->sri.xdelta );
LOG_DEBUG( <API key>, "PKT - TS maint:" << _maintainTimeStamp );
LOG_DEBUG( <API key>, " mode:" << pkt->T.tcmode );
LOG_DEBUG( <API key>, " status:" << pkt->T.tcstatus );
LOG_DEBUG( <API key>, " offset:" << pkt->T.toff );
LOG_DEBUG( <API key>, " whole:" << std::setprecision(10) << pkt->T.twsec );
LOG_DEBUG( <API key>, "PKT - TS frac:" << std::setprecision(12) << pkt->T.tfsec );
#endif
ostream->write( noutput_items, eos, pkt->T );
} else {
#ifdef TEST_TIME_STAMP
LOG_DEBUG( <API key>, "OSTREAM SRI: items/xdelta:" << noutput_items << "/" << std::setprecision(12) << ostream->sri.xdelta );
LOG_DEBUG( <API key>, "OSTREAM TOD maint:" << _maintainTimeStamp );
LOG_DEBUG( <API key>, " mode:" << ostream->tstamp.tcmode );
LOG_DEBUG( <API key>, " status:" << ostream->tstamp.tcstatus );
LOG_DEBUG( <API key>, " offset:" << ostream->tstamp.toff );
LOG_DEBUG( <API key>, " whole:" << std::setprecision(10) << ostream->tstamp.twsec );
LOG_DEBUG( <API key>, "OSTREAM TOD frac:" << std::setprecision(12) << ostream->tstamp.tfsec );
#endif
// use time of day as time stamp
ostream->write( noutput_items, eos, _maintainTimeStamp );
}
}
} // for ostreams
}
return nout;
}
|
/**
* Interface for managing topics
*/
function ManageTopics() {}
//inheritance
util.inherits(ManageTopics, pb.BaseController);
var SUB_NAV_KEY = 'manage_topics';
ManageTopics.prototype.render = function(cb) {
var self = this;
var dao = new pb.DAO();
dao.query('topic', pb.DAO.ANYWHERE, pb.DAO.PROJECT_ALL).then(function(topics) {
if (util.isError(topics)) {
//TODO handle this
}
//none to manage
if(topics.length === 0) {
self.redirect('/admin/content/topics/new', cb);
return;
}
//currently, mongo cannot do case-insensitive sorts. We do it manually
topics.sort(function(a, b) {
var x = a.name.toLowerCase();
var y = b.name.toLowerCase();
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
var angularObjects = pb.js.getAngularObjects(
{
navigation: pb.AdminNavigation.get(self.session, ['content', 'topics'], self.ls),
pills: pb.AdminSubnavService.get(SUB_NAV_KEY, self.ls, SUB_NAV_KEY),
topics: topics
});
self.setPageName(self.ls.get('MANAGE_TOPICS'));
self.ts.registerLocal('angular_objects', new pb.TemplateValue(angularObjects, false));
self.ts.load('admin/content/topics/manage_topics', function(err, data) {
var result = '' + data;
cb({content: result});
});
});
};
ManageTopics.getSubNavItems = function(key, ls, data) {
return [{
name: SUB_NAV_KEY,
title: ls.get('MANAGE_TOPICS'),
icon: 'refresh',
href: '/admin/content/topics'
}, {
name: 'import_topics',
title: '',
icon: 'upload',
href: '/admin/content/topics/import'
}, {
name: 'new_topic',
title: '',
icon: 'plus',
href: '/admin/content/topics/new'
}];
};
//register admin sub-nav
pb.AdminSubnavService.registerFor(SUB_NAV_KEY, ManageTopics.getSubNavItems);
//exports
module.exports = ManageTopics;
|
-- Host: spahost.es
-- SO del servidor: unknown-linux-gnu
/*!40101 SET @<API key>=@@<API key> */;
/*!40101 SET NAMES utf8 */;
/*!40014 SET @<API key>=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='<API key>' */;
-- Volcando estructura de base de datos para spahost_lsb
CREATE DATABASE IF NOT EXISTS `spahost_lsb` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `spahost_lsb`;
-- Volcando estructura para tabla spahost_lsb.lb_cat
CREATE TABLE IF NOT EXISTS `lb_cat` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`sub_id` int(11) DEFAULT NULL,
`title` varchar(250) CHARACTER SET latin1 NOT NULL DEFAULT '',
`description` text CHARACTER SET latin1 NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=30 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='Categorias del blog';
-- Volcando estructura para tabla spahost_lsb.lb_config
CREATE TABLE IF NOT EXISTS `lb_config` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(60) NOT NULL DEFAULT '',
`subtitle` varchar(60) NOT NULL DEFAULT '',
`description` varchar(255) NOT NULL DEFAULT '',
`author` varchar(50) NOT NULL DEFAULT '',
`email` varchar(100) NOT NULL DEFAULT '',
`site_url` varchar(100) NOT NULL DEFAULT '',
`lang` varchar(5) NOT NULL,
`template` varchar(255) NOT NULL DEFAULT '',
`mantenimiento` int(2) NOT NULL DEFAULT '0',
`limit_home` int(2) NOT NULL DEFAULT '0',
`limit_rss` int(2) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `user_login_key` (`title`),
KEY `user_nicename` (`author`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='Configuracion del blog';
-- Volcando datos para la tabla spahost_lsb.lb_config: 1 rows
DELETE FROM `lb_config`;
/*!40000 ALTER TABLE `lb_config` DISABLE KEYS */;
INSERT INTO `lb_config` (`id`, `title`, `subtitle`, `description`, `author`, `email`, `site_url`, `lang`, `template`, `mantenimiento`, `limit_home`, `limit_rss`) VALUES
(1, 'Nombre de Blog', 'Subtitulo de tu blog', 'descripcion de blog', 'tu nombre', 'tu email', 'http:
/*!40000 ALTER TABLE `lb_config` ENABLE KEYS */;
-- Volcando estructura para tabla spahost_lsb.lb_news
CREATE TABLE IF NOT EXISTS `lb_news` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(250) CHARACTER SET latin1 NOT NULL DEFAULT '',
`news` text CHARACTER SET latin1 NOT NULL,
`news_extend` text CHARACTER SET latin1 NOT NULL,
`author` varchar(99) CHARACTER SET latin1 NOT NULL DEFAULT '',
`source` varchar(99) CHARACTER SET latin1 NOT NULL DEFAULT '',
`views` int(11) NOT NULL DEFAULT '0',
`category` int(11) NOT NULL DEFAULT '0',
`image` varchar(255) CHARACTER SET latin1 NOT NULL DEFAULT '',
`link` varchar(255) CHARACTER SET latin1 NOT NULL DEFAULT '',
`oday` varchar(2) DEFAULT NULL,
`omonth` varchar(2) DEFAULT NULL,
`oyear` varchar(4) DEFAULT NULL,
`ttime` int(10) NOT NULL,
`lsttime` int(10) NOT NULL,
PRIMARY KEY (`id`),
FULLTEXT KEY `FULLTEXT` (`title`)
) ENGINE=MyISAM AUTO_INCREMENT=172 DEFAULT CHARSET=utf8;
-- Volcando estructura para tabla spahost_lsb.lb_users
CREATE TABLE IF NOT EXISTS `lb_users` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`user_login` varchar(60) NOT NULL DEFAULT '',
`user_pass` varchar(64) NOT NULL DEFAULT '',
`user_email` varchar(100) NOT NULL DEFAULT '',
`user_url` varchar(100) NOT NULL DEFAULT '',
`user_registered` int(10) NOT NULL,
`user_activation_key` varchar(60) NOT NULL DEFAULT '',
`user_status` int(11) NOT NULL DEFAULT '0',
`display_name` varchar(250) NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
KEY `user_login_key` (`user_login`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
-- Volcando datos para la tabla spahost_lsb.lb_users: 1 rows
DELETE FROM `lb_users`;
/*!40000 ALTER TABLE `lb_users` DISABLE KEYS */;
INSERT INTO `lb_users` (`id`, `user_login`, `user_pass`, `user_email`, `user_url`, `user_registered`, `user_activation_key`, `user_status`, `display_name`) VALUES
(1, 'admin', '<API key>', 'admin@tuweb.com', 'http:
/*!40000 ALTER TABLE `lb_users` ENABLE KEYS */;
-- Volcando estructura para tabla spahost_lsb.lb_users_online
CREATE TABLE IF NOT EXISTS `lb_users_online` (
`timestap` int(15) NOT NULL DEFAULT '0',
`status` int(1) NOT NULL,
`ttime` varchar(55) NOT NULL DEFAULT '',
`username` varchar(55) NOT NULL DEFAULT '',
`ip` varchar(40) NOT NULL DEFAULT '',
`country` varchar(10) NOT NULL DEFAULT '',
`file` varchar(100) NOT NULL DEFAULT '',
`page_title` varchar(100) NOT NULL,
`os` varchar(100) NOT NULL,
`browser` varchar(100) NOT NULL,
`browser_ver` varchar(100) NOT NULL,
PRIMARY KEY (`timestap`),
KEY `ip` (`ip`),
KEY `file` (`file`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
-- Volcando datos para la tabla spahost_lsb.lb_users_online: 0 rows
DELETE FROM `lb_users_online`;
/*!40000 ALTER TABLE `lb_users_online` DISABLE KEYS */;
/*!40000 ALTER TABLE `lb_users_online` ENABLE KEYS */;
-- Volcando estructura para tabla spahost_lsb.vt_users_online
CREATE TABLE IF NOT EXISTS `vt_users_online` (
`timestap` int(15) NOT NULL DEFAULT '0',
`status` int(1) NOT NULL,
`ttime` varchar(55) NOT NULL DEFAULT '',
`username` varchar(55) NOT NULL DEFAULT '',
`ip` varchar(40) NOT NULL DEFAULT '',
`country` varchar(10) NOT NULL DEFAULT '',
`file` varchar(100) NOT NULL DEFAULT '',
`page_title` varchar(100) NOT NULL,
`os` varchar(100) NOT NULL,
`browser` varchar(100) NOT NULL,
`browser_ver` varchar(100) NOT NULL,
PRIMARY KEY (`timestap`),
KEY `ip` (`ip`),
KEY `file` (`file`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
-- Volcando datos para la tabla spahost_lsb.vt_users_online: 0 rows
DELETE FROM `vt_users_online`;
/*!40000 ALTER TABLE `vt_users_online` DISABLE KEYS */;
/*!40000 ALTER TABLE `vt_users_online` ENABLE KEYS */;
/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IF(@<API key> IS NULL, 1, @<API key>) */;
/*!40101 SET <API key>=@<API key> */;
|
#include <shlobj.h>
HRESULT CreateDataObject(FORMATETC *,STGMEDIUM *,IDataObject **,int);
|
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_17) on Thu Oct 24 15:10:37 CEST 2013 -->
<title>RmcpConstants</title>
<meta name="date" content="2013-10-24">
<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="RmcpConstants";
}
</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><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/RmcpConstants.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="../../../../../com/veraxsystems/vxipmi/coding/rmcp/RmcpClassOfMessage.html" title="enum in com.veraxsystems.vxipmi.coding.rmcp"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../com/veraxsystems/vxipmi/coding/rmcp/RmcpDecoder.html" title="class in com.veraxsystems.vxipmi.coding.rmcp"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/veraxsystems/vxipmi/coding/rmcp/RmcpConstants.html" target="_top">Frames</a></li>
<li><a href="RmcpConstants.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>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field_summary">Field</a> | </li>
<li>Constr | </li>
<li><a href="#<API key>.lang.Object">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li>Constr | </li>
<li>Method</li>
</ul>
</div>
<a name="skip-navbar_top">
</a></div>
<div class="header">
<div class="subTitle">com.veraxsystems.vxipmi.coding.rmcp</div>
<h2 title="Class RmcpConstants" class="title">Class RmcpConstants</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>com.veraxsystems.vxipmi.coding.rmcp.RmcpConstants</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public final class <span class="strong">RmcpConstants</span>
extends java.lang.Object</pre>
<div class="block">Set of constants.
Byte constants are encoded as pseudo unsigned bytes.
RMCPConstants doesn't use <a href="../../../../../com/veraxsystems/vxipmi/common/TypeConverter.html" title="class in com.veraxsystems.vxipmi.common"><code>TypeConverter</code></a> because
fields need to be runtime constants.</div>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../com/veraxsystems/vxipmi/common/TypeConverter.html#byteToInt(byte)"><code>TypeConverter.byteToInt(byte)</code></a>,
<a href="../../../../../com/veraxsystems/vxipmi/common/TypeConverter.html#intToByte(int)"><code>TypeConverter.intToByte(int)</code></a></dd></dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="field_summary">
</a>
<h3>Field Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><strong><a href="../../../../../com/veraxsystems/vxipmi/coding/rmcp/RmcpConstants.html#ASFIANA">ASFIANA</a></strong></code>
<div class="block">IANA Enterprise Number = ASF IANA</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static byte</code></td>
<td class="colLast"><code><strong><a href="../../../../../com/veraxsystems/vxipmi/coding/rmcp/RmcpConstants.html#PRESENCE_PING">PRESENCE_PING</a></strong></code>
<div class="block">ASF Message type = Presence Ping</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static byte</code></td>
<td class="colLast"><code><strong><a href="../../../../../com/veraxsystems/vxipmi/coding/rmcp/RmcpConstants.html#RMCP_V1_0">RMCP_V1_0</a></strong></code>
<div class="block">RMCP version 1.0</div>
</td>
</tr>
</table>
</li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="method_summary">
</a>
<h3>Method Summary</h3>
<ul class="blockList">
<li class="blockList"><a name="<API key>.lang.Object">
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="field_detail">
</a>
<h3>Field Detail</h3>
<a name="RMCP_V1_0">
</a>
<ul class="blockList">
<li class="blockList">
<h4>RMCP_V1_0</h4>
<pre>public static final byte RMCP_V1_0</pre>
<div class="block">RMCP version 1.0</div>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../constant-values.html#com.veraxsystems.vxipmi.coding.rmcp.RmcpConstants.RMCP_V1_0">Constant Field Values</a></dd></dl>
</li>
</ul>
<a name="ASFIANA">
</a>
<ul class="blockList">
<li class="blockList">
<h4>ASFIANA</h4>
<pre>public static final int ASFIANA</pre>
<div class="block">IANA Enterprise Number = ASF IANA</div>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../constant-values.html#com.veraxsystems.vxipmi.coding.rmcp.RmcpConstants.ASFIANA">Constant Field Values</a></dd></dl>
</li>
</ul>
<a name="PRESENCE_PING">
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>PRESENCE_PING</h4>
<pre>public static final byte PRESENCE_PING</pre>
<div class="block">ASF Message type = Presence Ping</div>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../constant-values.html#com.veraxsystems.vxipmi.coding.rmcp.RmcpConstants.PRESENCE_PING">Constant Field Values</a></dd></dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</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><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/RmcpConstants.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="../../../../../com/veraxsystems/vxipmi/coding/rmcp/RmcpClassOfMessage.html" title="enum in com.veraxsystems.vxipmi.coding.rmcp"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../com/veraxsystems/vxipmi/coding/rmcp/RmcpDecoder.html" title="class in com.veraxsystems.vxipmi.coding.rmcp"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/veraxsystems/vxipmi/coding/rmcp/RmcpConstants.html" target="_top">Frames</a></li>
<li><a href="RmcpConstants.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>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field_summary">Field</a> | </li>
<li>Constr | </li>
<li><a href="#<API key>.lang.Object">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li>Constr | </li>
<li>Method</li>
</ul>
</div>
<a name="skip-navbar_bottom">
</a></div>
</body>
</html>
|
#include <gtest/gtest.h>
#include <librepcb/common/uuid.h>
#include <QtCore>
namespace librepcb {
namespace tests {
typedef struct {
bool valid;
QString uuid;
} UuidTestData;
class UuidTest : public ::testing::TestWithParam<UuidTestData> {};
TEST_P(UuidTest, testCopyConstructor) {
const UuidTestData& data = GetParam();
if (data.valid) {
Uuid source = Uuid::fromString(data.uuid);
Uuid copy(source);
EXPECT_TRUE(copy == source);
EXPECT_EQ(source.toStr(), copy.toStr());
}
}
TEST_P(UuidTest, testToStr) {
const UuidTestData& data = GetParam();
if (data.valid) {
Uuid uuid = Uuid::fromString(data.uuid);
EXPECT_EQ(data.uuid, uuid.toStr());
EXPECT_EQ(36, uuid.toStr().length());
}
}
TEST_P(UuidTest, testOperatorAssign) {
const UuidTestData& data = GetParam();
if (data.valid) {
Uuid source = Uuid::fromString(data.uuid);
Uuid destination =
Uuid::fromString("<API key>"); // valid UUID
EXPECT_NE(source.toStr(), destination.toStr());
destination = source;
EXPECT_EQ(source.toStr(), destination.toStr());
}
}
TEST_P(UuidTest, testOperatorEquals) {
const UuidTestData& data = GetParam();
if (data.valid) {
Uuid uuid1 = Uuid::fromString(data.uuid);
Uuid uuid2 =
Uuid::fromString("<API key>"); // valid UUID
EXPECT_FALSE(uuid2 == uuid1);
EXPECT_FALSE(uuid1 == uuid2);
uuid2 = uuid1;
EXPECT_TRUE(uuid2 == uuid1);
EXPECT_TRUE(uuid1 == uuid2);
}
}
TEST_P(UuidTest, <API key>) {
const UuidTestData& data = GetParam();
if (data.valid) {
Uuid uuid1 = Uuid::fromString(data.uuid);
Uuid uuid2 =
Uuid::fromString("<API key>"); // valid UUID
EXPECT_TRUE(uuid2 != uuid1);
EXPECT_TRUE(uuid1 != uuid2);
uuid2 = uuid1;
EXPECT_FALSE(uuid2 != uuid1);
EXPECT_FALSE(uuid1 != uuid2);
}
}
TEST_P(UuidTest, <API key>) {
const UuidTestData& data = GetParam();
if (data.valid) {
Uuid uuid1 = Uuid::fromString(data.uuid);
Uuid uuid2 =
Uuid::fromString("<API key>"); // valid UUID
if (uuid1.toStr() == uuid2.toStr()) {
EXPECT_FALSE((uuid2 < uuid1) || (uuid2 > uuid1));
EXPECT_FALSE((uuid1 < uuid2) || (uuid1 > uuid2));
EXPECT_TRUE((uuid2 <= uuid1) && (uuid2 >= uuid1));
EXPECT_TRUE((uuid1 <= uuid2) && (uuid1 >= uuid2));
} else {
EXPECT_TRUE((uuid2 < uuid1) != (uuid2 > uuid1));
EXPECT_TRUE((uuid1 < uuid2) != (uuid1 > uuid2));
EXPECT_TRUE((uuid2 <= uuid1) != (uuid2 >= uuid1));
EXPECT_TRUE((uuid1 <= uuid2) != (uuid1 >= uuid2));
}
EXPECT_EQ(uuid2.toStr() < uuid1.toStr(), uuid2 < uuid1);
EXPECT_EQ(uuid1.toStr() < uuid2.toStr(), uuid1 < uuid2);
EXPECT_EQ(uuid2.toStr() > uuid1.toStr(), uuid2 > uuid1);
EXPECT_EQ(uuid1.toStr() > uuid2.toStr(), uuid1 > uuid2);
EXPECT_EQ(uuid2.toStr() <= uuid1.toStr(), uuid2 <= uuid1);
EXPECT_EQ(uuid1.toStr() <= uuid2.toStr(), uuid1 <= uuid2);
EXPECT_EQ(uuid2.toStr() >= uuid1.toStr(), uuid2 >= uuid1);
EXPECT_EQ(uuid1.toStr() >= uuid2.toStr(), uuid1 >= uuid2);
}
}
TEST(UuidTest, testCreateRandom) {
for (int i = 0; i < 1000; i++) {
Uuid uuid = Uuid::createRandom();
EXPECT_FALSE(uuid.toStr().isEmpty());
EXPECT_EQ(QUuid::DCE, QUuid(uuid.toStr()).variant());
EXPECT_EQ(QUuid::Random, QUuid(uuid.toStr()).version());
}
}
TEST_P(UuidTest, testIsValid) {
const UuidTestData& data = GetParam();
EXPECT_EQ(data.valid, Uuid::isValid(data.uuid));
}
TEST_P(UuidTest, testFromString) {
const UuidTestData& data = GetParam();
if (data.valid) {
EXPECT_EQ(data.uuid, Uuid::fromString(data.uuid).toStr());
} else {
EXPECT_THROW(Uuid::fromString(data.uuid), Exception);
}
}
TEST_P(UuidTest, testTryFromString) {
const UuidTestData& data = GetParam();
tl::optional<Uuid> uuid = Uuid::tryFromString(data.uuid);
if (data.valid) {
EXPECT_TRUE(uuid);
EXPECT_EQ(data.uuid, uuid->toStr());
} else {
EXPECT_FALSE(uuid);
EXPECT_EQ(tl::nullopt, uuid);
}
}
TEST_P(UuidTest, <API key>) {
const UuidTestData& data = GetParam();
if (data.valid) {
Uuid uuid = Uuid::fromString(data.uuid);
EXPECT_EQ(data.uuid, <API key>(uuid).getStringOrToken());
EXPECT_EQ(
data.uuid,
<API key>(tl::make_optional(uuid)).getStringOrToken());
}
}
TEST_P(UuidTest, <API key>) {
const UuidTestData& data = GetParam();
SExpression sexpr = SExpression::createToken(data.uuid);
if (data.valid) {
EXPECT_EQ(data.uuid,
<API key><Uuid>(sexpr, false).toStr());
EXPECT_EQ(
data.uuid,
<API key><tl::optional<Uuid>>(sexpr, false)->toStr());
} else {
EXPECT_THROW(<API key><Uuid>(sexpr, false), Exception);
EXPECT_THROW(<API key><tl::optional<Uuid>>(sexpr, false),
Exception);
}
}
TEST(UuidTest, <API key>) {
tl::optional<Uuid> uuid = tl::nullopt;
EXPECT_EQ("none", <API key>(uuid).getStringOrToken());
}
TEST(UuidTest, <API key>) {
SExpression sexpr = SExpression::createToken("none");
EXPECT_EQ(tl::nullopt,
<API key><tl::optional<Uuid>>(sexpr, false));
}
// Test UUIDs are generated with:
// clang-format off
<API key>(UuidTest, UuidTest, ::testing::Values(
// DCE Version 4 (random, the only accepted UUID type for us)
UuidTestData({true , "<API key>" }),
UuidTestData({true , "<API key>" }),
UuidTestData({true , "<API key>" }),
UuidTestData({true , "<API key>" }),
UuidTestData({true , "<API key>" }),
UuidTestData({true , "<API key>" }),
UuidTestData({true , "<API key>" }),
UuidTestData({true , "<API key>" }),
UuidTestData({true , "<API key>" }),
UuidTestData({true , "<API key>" }),
UuidTestData({true , "<API key>" }),
// DCE Version 1 (time based)
UuidTestData({false, "<API key>" }),
UuidTestData({false, "<API key>" }),
UuidTestData({false, "<API key>" }),
UuidTestData({false, "<API key>" }),
UuidTestData({false, "<API key>" }),
// DCE Version 3 (name based, md5)
UuidTestData({false, "<API key>" }),
UuidTestData({false, "<API key>" }),
// DCE Version 5 (name based, sha1)
UuidTestData({false, "<API key>" }),
// Microsoft GUID
UuidTestData({false, "<API key>" }),
// NULL UUID
UuidTestData({false, "<API key>" }),
// Invalid UUIDs
UuidTestData({false, "" }), // empty
UuidTestData({false, " " }), // empty
UuidTestData({false, QString()}), // null
UuidTestData({false, "<API key>" }), // uppercase
UuidTestData({false, "<API key>" }), // uppercase
UuidTestData({false, "<API key>" }), // uppercase
UuidTestData({false, "<API key>" }), // uppercase
UuidTestData({false, "<API key>" }), // too short
UuidTestData({false, "<API key> " }), // too long
UuidTestData({false, " <API key>" }), // too long
UuidTestData({false, "<API key>" }), // missing '-'
UuidTestData({false, "{<API key>}"}),
UuidTestData({false, "<API key>" }),
UuidTestData({false, "<API key>" }),
UuidTestData({false, "bdf7bea5 b88e 41b2 be85 c1604e8ddfca" }) // spaces
));
// clang-format on
} // namespace tests
} // namespace librepcb
|
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.5.0_01) on Sun Jul 03 07:12:39 ICT 2005 -->
<TITLE>
Uses of Package com.golden.gamedev.object.sprite (GTGE API v0.2.3)
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="Uses of Package com.golden.gamedev.object.sprite (GTGE API v0.2.3)";
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<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"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </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="../../../../../index-all.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>
<b>GTGE API</b></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?com/golden/gamedev/object/sprite/package-use.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-use.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 Package<br>com.golden.gamedev.object.sprite</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="../../../../../com/golden/gamedev/object/sprite/package-summary.html">com.golden.gamedev.object.sprite</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#com.golden.gamedev.object.sprite"><B>com.golden.gamedev.object.sprite</B></A></TD>
<TD>Sprite implementation. </TD>
</TR>
</TABLE>
<P>
<A NAME="com.golden.gamedev.object.sprite"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Classes in <A HREF="../../../../../com/golden/gamedev/object/sprite/package-summary.html">com.golden.gamedev.object.sprite</A> used by <A HREF="../../../../../com/golden/gamedev/object/sprite/package-summary.html">com.golden.gamedev.object.sprite</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../../../com/golden/gamedev/object/sprite/class-use/AdvanceSprite.html#com.golden.gamedev.object.sprite"><B>AdvanceSprite</B></A></B>
<BR>
<code>AdvanceSprite</code> class is animated sprite that has status and
direction attributes, that way the animation is fully controlled by its
status and direction.</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"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </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="../../../../../index-all.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>
<b>GTGE API</b></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?com/golden/gamedev/object/sprite/package-use.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-use.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>
<i>Copyright © 2003-2005 Golden T Studios. All rights reserved. Use is subject to <a href=http:
</BODY>
</HTML>
|
#include <string.h>
#include <stdlib.h>
#include "prowiz.h"
static int depack_fuchs(HIO_HANDLE *in, FILE *out)
{
uint8 *tmp;
uint8 max_pat;
/*int ssize;*/
uint8 data[1080];
unsigned smp_len[16];
unsigned loop_start[16];
unsigned pat_size;
unsigned i;
memset(smp_len, 0, 16 * 4);
memset(loop_start, 0, 16 * 4);
memset(data, 0, 1080);
hio_read(data, 1, 10, in); /* read/write title */
/*ssize =*/ hio_read32b(in); /* read all sample data size */
/* read/write sample sizes */
for (i = 0; i < 16; i++) {
smp_len[i] = hio_read16b(in);
data[42 + i * 30] = smp_len[i] >> 9;
data[43 + i * 30] = smp_len[i] >> 1;
}
/* read/write volumes */
for (i = 0; i < 16; i++) {
data[45 + i * 30] = hio_read16b(in);
}
/* read/write loop start */
for (i = 0; i < 16; i++) {
loop_start[i] = hio_read16b(in);
data[46 + i * 30] = loop_start[i] >> 1;
}
/* write replen */
for (i = 0; i < 16; i++) {
int loop_size;
loop_size = smp_len[i] - loop_start[i];
if (loop_size == 0 || loop_start[i] == 0) {
data[49 + i * 30] = 1;
} else {
data[48 + i * 30] = loop_size >> 9;
data[49 + i * 30] = loop_size >> 1;
}
}
/* fill replens up to 31st sample wiz $0001 */
for (i = 16; i < 31; i++) {
data[49 + i * 30] = 1;
}
/* that's it for the samples ! */
/* now, the pattern list */
/* read number of pattern to play */
data[950] = hio_read16b(in);
data[951] = 0x7f;
/* read/write pattern list */
for (max_pat = i = 0; i < 40; i++) {
uint8 pat = hio_read16b(in);
data[952 + i] = pat;
if (pat > max_pat) {
max_pat = pat;
}
}
/* write ptk's ID */
if (fwrite(data, 1, 1080, out) != 1080) {
return -1;
}
write32b(out, PW_MOD_MAGIC);
/* now, the pattern data */
/* bypass the "SONG" ID */
hio_read32b(in);
/* read pattern data size */
pat_size = hio_read32b(in);
/* Sanity check */
if (pat_size <= 0 || pat_size > 0x20000)
return -1;
/* read pattern data */
tmp = (uint8 *)malloc(pat_size);
if (hio_read(tmp, 1, pat_size, in) != pat_size) {
free(tmp);
return -1;
}
/* convert shits */
for (i = 0; i < pat_size; i += 4) {
/* convert fx C arg back to hex value */
if ((tmp[i + 2] & 0x0f) == 0x0c) {
int x = tmp[i + 3];
tmp[i + 3] = 10 * (x >> 4) + (x & 0xf);
}
}
/* write pattern data */
fwrite(tmp, pat_size, 1, out);
free(tmp);
/* read/write sample data */
hio_read32b(in); /* bypass "INST" Id */
for (i = 0; i < 16; i++) {
if (smp_len[i] != 0)
pw_move_data(out, in, smp_len[i]);
}
return 0;
}
static int test_fuchs (uint8 *data, char *t, int s)
{
int i;
int ssize, hdr_ssize;
#if 0
/* test #1 */
if (i < 192) {
Test = BAD;
return;
}
start = i - 192;
#endif
if (readmem32b(data + 192) != 0x534f4e47) /* SONG */
return -1;
/* all sample size */
hdr_ssize = readmem32b(data + 10);
if (hdr_ssize <= 2 || hdr_ssize >= 65535 * 16)
return -1;
/* samples descriptions */
ssize = 0;
for (i = 0; i < 16; i++) {
uint8 *d = data + i * 2;
int len = readmem16b(d + 14);
int start = readmem16b(d + 78);
/* volumes */
if (d[46] > 0x40)
return -1;
if (len < start)
return -1;
ssize += len;
}
if (ssize <= 2 || ssize > hdr_ssize)
return -1;
/* get highest pattern number in pattern list */
/*max_pat = 0;*/
for (i = 0; i < 40; i++) {
int pat = data[i * 2 + 113];
if (pat > 40)
return -1;
/*if (pat > max_pat)
max_pat = pat;*/
}
#if 0
/* input file not long enough ? */
max_pat++;
max_pat *= 1024;
PW_REQUEST_DATA (s, k + 200);
#endif
pw_read_title(NULL, t, 0);
return 0;
}
const struct pw_format pw_fchs = {
"Fuchs Tracker",
test_fuchs,
depack_fuchs
};
|
#ifndef SDK_CONFIG_H
#define SDK_CONFIG_H
// <<< Use Configuration Wizard in Context Menu >>>\n
#ifdef USE_APP_CONFIG
#include "app_config.h"
#endif
// <h> Application
// <o> ADV_INTERVAL - Advertising interval (in units of 0.625 ms)
#ifndef ADV_INTERVAL
#define ADV_INTERVAL 300
#endif
// <s> DEVICE_NAME - Name of device. Will be included in the advertising data.
#ifndef DEVICE_NAME
#define DEVICE_NAME "Nordic_ATT_MTU"
#endif
// <o> <API key> - Number of central links
#ifndef <API key>
#define <API key> 1
#endif
// <o> <API key> - Number of peripheral links
#ifndef <API key>
#define <API key> 1
#endif
// <o> SCAN_INTERVAL - Scanning interval, determines scan interval in units of 0.625 millisecond.
#ifndef SCAN_INTERVAL
#define SCAN_INTERVAL 160
#endif
// <o> SCAN_WINDOW - Scanning window, determines scan window in units of 0.625 millisecond.
#ifndef SCAN_WINDOW
#define SCAN_WINDOW 80
#endif
// <h> nRF_BLE
// <q> <API key> - ble_advertising - Advertising module
#ifndef <API key>
#define <API key> 0
#endif
// <q> <API key> - ble_db_discovery - Database discovery module
#ifndef <API key>
#define <API key> 1
#endif
// <q> BLE_DTM_ENABLED - ble_dtm - Module for testing RF/PHY using DTM commands
#ifndef BLE_DTM_ENABLED
#define BLE_DTM_ENABLED 0
#endif
// <q> BLE_RACP_ENABLED - ble_racp - Record Access Control Point library
#ifndef BLE_RACP_ENABLED
#define BLE_RACP_ENABLED 0
#endif
// <e> <API key> - nrf_ble_gatt - GATT module
#ifndef <API key>
#define <API key> 1
#endif
#if <API key>
// <o> <API key> - Static maximum MTU size that is passed to the @ref sd_ble_enable function.
#ifndef <API key>
#define <API key> 247
#endif
#endif //<API key>
// <q> NRF_BLE_QWR_ENABLED - nrf_ble_qwr - Queued writes support module (prepare/execute write)
#ifndef NRF_BLE_QWR_ENABLED
#define NRF_BLE_QWR_ENABLED 0
#endif
// <q> <API key> - peer_manager - Peer Manager
#ifndef <API key>
#define <API key> 0
#endif
// <h> nRF_BLE_Services
// <q> BLE_ANCS_C_ENABLED - ble_ancs_c - Apple Notification Service Client
#ifndef BLE_ANCS_C_ENABLED
#define BLE_ANCS_C_ENABLED 0
#endif
// <q> BLE_ANS_C_ENABLED - ble_ans_c - Alert Notification Service Client
#ifndef BLE_ANS_C_ENABLED
#define BLE_ANS_C_ENABLED 0
#endif
// <q> BLE_BAS_C_ENABLED - ble_bas_c - Battery Service Client
#ifndef BLE_BAS_C_ENABLED
#define BLE_BAS_C_ENABLED 0
#endif
// <q> BLE_BAS_ENABLED - ble_bas - Battery Service
#ifndef BLE_BAS_ENABLED
#define BLE_BAS_ENABLED 0
#endif
// <q> BLE_CSCS_ENABLED - ble_cscs - Cycling Speed and Cadence Service
#ifndef BLE_CSCS_ENABLED
#define BLE_CSCS_ENABLED 0
#endif
// <q> BLE_CTS_C_ENABLED - ble_cts_c - Current Time Service Client
#ifndef BLE_CTS_C_ENABLED
#define BLE_CTS_C_ENABLED 0
#endif
// <q> BLE_DIS_ENABLED - ble_dis - Device Information Service
#ifndef BLE_DIS_ENABLED
#define BLE_DIS_ENABLED 0
#endif
// <q> BLE_GLS_ENABLED - ble_gls - Glucose Service
#ifndef BLE_GLS_ENABLED
#define BLE_GLS_ENABLED 0
#endif
// <q> BLE_HIDS_ENABLED - ble_hids - Human Interface Device Service
#ifndef BLE_HIDS_ENABLED
#define BLE_HIDS_ENABLED 0
#endif
// <e> BLE_HRS_C_ENABLED - ble_hrs_c - Heart Rate Service Client
#ifndef BLE_HRS_C_ENABLED
#define BLE_HRS_C_ENABLED 0
#endif
#if BLE_HRS_C_ENABLED
// <o> <API key> - Maximum number of RR_INTERVALS per notification to be decoded
#ifndef <API key>
#define <API key> 30
#endif
#endif //BLE_HRS_C_ENABLED
// <q> BLE_HRS_ENABLED - ble_hrs - Heart Rate Service
#ifndef BLE_HRS_ENABLED
#define BLE_HRS_ENABLED 0
#endif
// <q> BLE_HTS_ENABLED - ble_hts - Health Thermometer Service
#ifndef BLE_HTS_ENABLED
#define BLE_HTS_ENABLED 0
#endif
// <q> BLE_IAS_C_ENABLED - ble_ias_c - Immediate Alert Service Client
#ifndef BLE_IAS_C_ENABLED
#define BLE_IAS_C_ENABLED 0
#endif
// <q> BLE_IAS_ENABLED - ble_ias - Immediate Alert Service
#ifndef BLE_IAS_ENABLED
#define BLE_IAS_ENABLED 0
#endif
// <q> BLE_LBS_C_ENABLED - ble_lbs_c - Nordic LED Button Service Client
#ifndef BLE_LBS_C_ENABLED
#define BLE_LBS_C_ENABLED 0
#endif
// <q> BLE_LBS_ENABLED - ble_lbs - LED Button Service
#ifndef BLE_LBS_ENABLED
#define BLE_LBS_ENABLED 0
#endif
// <q> BLE_LLS_ENABLED - ble_lls - Link Loss Service
#ifndef BLE_LLS_ENABLED
#define BLE_LLS_ENABLED 0
#endif
// <q> BLE_NUS_C_ENABLED - ble_nus_c - Nordic UART Central Service
#ifndef BLE_NUS_C_ENABLED
#define BLE_NUS_C_ENABLED 0
#endif
// <q> BLE_NUS_ENABLED - ble_nus - Nordic UART Service
#ifndef BLE_NUS_ENABLED
#define BLE_NUS_ENABLED 0
#endif
// <q> BLE_RSCS_C_ENABLED - ble_rscs_c - Running Speed and Cadence Client
#ifndef BLE_RSCS_C_ENABLED
#define BLE_RSCS_C_ENABLED 0
#endif
// <q> BLE_RSCS_ENABLED - ble_rscs - Running Speed and Cadence Service
#ifndef BLE_RSCS_ENABLED
#define BLE_RSCS_ENABLED 0
#endif
// <q> BLE_TPS_ENABLED - ble_tps - TX Power Service
#ifndef BLE_TPS_ENABLED
#define BLE_TPS_ENABLED 0
#endif
// <h> nRF_Drivers
// <e> APP_USBD_ENABLED - app_usbd - USB Device library
#ifndef APP_USBD_ENABLED
#define APP_USBD_ENABLED 0
#endif
#if APP_USBD_ENABLED
// <o> APP_USBD_VID - Vendor ID <0x0000-0xFFFF>
#ifndef APP_USBD_VID
#define APP_USBD_VID 0
#endif
// <o> APP_USBD_PID - Product ID <0x0000-0xFFFF>
// <i> Selected Product ID
#ifndef APP_USBD_PID
#define APP_USBD_PID 0
#endif
// <o> <API key> - Device version, major part <0-99>
// <i> Device version, will be converted automatically to BCD notation. Use just decimal values.
#ifndef <API key>
#define <API key> 1
#endif
// <o> <API key> - Device version, minor part <0-99>
// <i> Device version, will be converted automatically to BCD notation. Use just decimal values.
#ifndef <API key>
#define <API key> 0
#endif
#endif //APP_USBD_ENABLED
// <e> CLOCK_ENABLED - nrf_drv_clock - CLOCK peripheral driver
#ifndef CLOCK_ENABLED
#define CLOCK_ENABLED 1
#endif
#if CLOCK_ENABLED
// <o> <API key> - HF XTAL Frequency
// <0=> Default (64 MHz)
#ifndef <API key>
#define <API key> 0
#endif
// <o> CLOCK_CONFIG_LF_SRC - LF Clock Source
// <0=> RC
// <1=> XTAL
// <2=> Synth
#ifndef CLOCK_CONFIG_LF_SRC
#define CLOCK_CONFIG_LF_SRC 1
#endif
// <o> <API key> - Interrupt priority
// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest)
// <1=> 1
// <2=> 2
// <3=> 3
// <4=> 4
// <5=> 5
// <6=> 6
// <7=> 7
#ifndef <API key>
#define <API key> 7
#endif
// <e> <API key> - Enables logging in the module.
#ifndef <API key>
#define <API key> 0
#endif
#if <API key>
// <o> <API key> - Default Severity level
// <0=> Off
// <1=> Error
// <2=> Warning
// <3=> Info
// <4=> Debug
#ifndef <API key>
#define <API key> 3
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
#endif //<API key>
#endif //CLOCK_ENABLED
// <e> COMP_ENABLED - nrf_drv_comp - COMP peripheral driver
#ifndef COMP_ENABLED
#define COMP_ENABLED 0
#endif
#if COMP_ENABLED
// <o> COMP_CONFIG_REF - Reference voltage
// <0=> Internal 1.2V
// <1=> Internal 1.8V
// <2=> Internal 2.4V
// <4=> VDD
// <7=> ARef
#ifndef COMP_CONFIG_REF
#define COMP_CONFIG_REF 1
#endif
// <o> <API key> - Main mode
// <0=> Single ended
// <1=> Differential
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - Speed mode
// <0=> Low power
// <1=> Normal
// <2=> High speed
#ifndef <API key>
#define <API key> 2
#endif
// <o> COMP_CONFIG_HYST - Hystheresis
// <0=> No
// <1=> 50mV
#ifndef COMP_CONFIG_HYST
#define COMP_CONFIG_HYST 0
#endif
// <o> COMP_CONFIG_ISOURCE - Current Source
// <0=> Off
// <1=> 2.5 uA
// <2=> 5 uA
// <3=> 10 uA
#ifndef COMP_CONFIG_ISOURCE
#define COMP_CONFIG_ISOURCE 0
#endif
// <o> COMP_CONFIG_INPUT - Analog input
// <0=> 0
// <1=> 1
// <2=> 2
// <3=> 3
// <4=> 4
// <5=> 5
// <6=> 6
// <7=> 7
#ifndef COMP_CONFIG_INPUT
#define COMP_CONFIG_INPUT 0
#endif
// <o> <API key> - Interrupt priority
// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest)
// <1=> 1
// <2=> 2
// <3=> 3
// <4=> 4
// <5=> 5
// <6=> 6
// <7=> 7
#ifndef <API key>
#define <API key> 7
#endif
// <e> <API key> - Enables logging in the module.
#ifndef <API key>
#define <API key> 0
#endif
#if <API key>
// <o> <API key> - Default Severity level
// <0=> Off
// <1=> Error
// <2=> Warning
// <3=> Info
// <4=> Debug
#ifndef <API key>
#define <API key> 3
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
#endif //<API key>
#endif //COMP_ENABLED
// <e> EGU_ENABLED - nrf_drv_swi - SWI(EGU) peripheral driver
#ifndef EGU_ENABLED
#define EGU_ENABLED 0
#endif
#if EGU_ENABLED
// <e> <API key> - Enables logging in the module.
#ifndef <API key>
#define <API key> 0
#endif
#if <API key>
// <o> <API key> - Default Severity level
// <0=> Off
// <1=> Error
// <2=> Warning
// <3=> Info
// <4=> Debug
#ifndef <API key>
#define <API key> 3
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
#endif //<API key>
#endif //EGU_ENABLED
// <e> GPIOTE_ENABLED - nrf_drv_gpiote - GPIOTE peripheral driver
#ifndef GPIOTE_ENABLED
#define GPIOTE_ENABLED 1
#endif
#if GPIOTE_ENABLED
// <o> <API key> - Number of lower power input pins
#ifndef <API key>
#define <API key> 4
#endif
// <o> <API key> - Interrupt priority
// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest)
// <1=> 1
// <2=> 2
// <3=> 3
// <4=> 4
// <5=> 5
// <6=> 6
// <7=> 7
#ifndef <API key>
#define <API key> 7
#endif
// <e> <API key> - Enables logging in the module.
#ifndef <API key>
#define <API key> 0
#endif
#if <API key>
// <o> <API key> - Default Severity level
// <0=> Off
// <1=> Error
// <2=> Warning
// <3=> Info
// <4=> Debug
#ifndef <API key>
#define <API key> 3
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
#endif //<API key>
#endif //GPIOTE_ENABLED
// <e> I2S_ENABLED - nrf_drv_i2s - I2S peripheral driver
#ifndef I2S_ENABLED
#define I2S_ENABLED 0
#endif
#if I2S_ENABLED
// <o> I2S_CONFIG_SCK_PIN - SCK pin <0-31>
#ifndef I2S_CONFIG_SCK_PIN
#define I2S_CONFIG_SCK_PIN 31
#endif
// <o> I2S_CONFIG_LRCK_PIN - LRCK pin <1-31>
#ifndef I2S_CONFIG_LRCK_PIN
#define I2S_CONFIG_LRCK_PIN 30
#endif
// <o> I2S_CONFIG_MCK_PIN - MCK pin
#ifndef I2S_CONFIG_MCK_PIN
#define I2S_CONFIG_MCK_PIN 255
#endif
// <o> <API key> - SDOUT pin <0-31>
#ifndef <API key>
#define <API key> 29
#endif
// <o> I2S_CONFIG_SDIN_PIN - SDIN pin <0-31>
#ifndef I2S_CONFIG_SDIN_PIN
#define I2S_CONFIG_SDIN_PIN 28
#endif
// <o> I2S_CONFIG_MASTER - Mode
// <0=> Master
// <1=> Slave
#ifndef I2S_CONFIG_MASTER
#define I2S_CONFIG_MASTER 0
#endif
// <o> I2S_CONFIG_FORMAT - Format
// <0=> I2S
// <1=> Aligned
#ifndef I2S_CONFIG_FORMAT
#define I2S_CONFIG_FORMAT 0
#endif
// <o> I2S_CONFIG_ALIGN - Alignment
// <0=> Left
// <1=> Right
#ifndef I2S_CONFIG_ALIGN
#define I2S_CONFIG_ALIGN 0
#endif
// <o> I2S_CONFIG_SWIDTH - Sample width (bits)
// <0=> 8
// <1=> 16
// <2=> 24
#ifndef I2S_CONFIG_SWIDTH
#define I2S_CONFIG_SWIDTH 1
#endif
// <o> I2S_CONFIG_CHANNELS - Channels
// <0=> Stereo
// <1=> Left
// <2=> Right
#ifndef I2S_CONFIG_CHANNELS
#define I2S_CONFIG_CHANNELS 1
#endif
// <o> <API key> - MCK behavior
// <0=> Disabled
// <2147483648=> 32MHz/2
// <1342177280=> 32MHz/3
// <1073741824=> 32MHz/4
// <805306368=> 32MHz/5
// <671088640=> 32MHz/6
// <536870912=> 32MHz/8
// <402653184=> 32MHz/10
// <369098752=> 32MHz/11
// <285212672=> 32MHz/15
// <268435456=> 32MHz/16
// <201326592=> 32MHz/21
// <184549376=> 32MHz/23
// <142606336=> 32MHz/30
// <138412032=> 32MHz/31
// <134217728=> 32MHz/32
// <100663296=> 32MHz/42
// <68157440=> 32MHz/63
// <34340864=> 32MHz/125
#ifndef <API key>
#define <API key> 536870912
#endif
// <o> I2S_CONFIG_RATIO - MCK/LRCK ratio
// <0=> 32x
// <1=> 48x
// <2=> 64x
// <3=> 96x
// <4=> 128x
// <5=> 192x
// <6=> 256x
// <7=> 384x
// <8=> 512x
#ifndef I2S_CONFIG_RATIO
#define I2S_CONFIG_RATIO 2000
#endif
// <o> <API key> - Interrupt priority
// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest)
// <1=> 1
// <2=> 2
// <3=> 3
// <4=> 4
// <5=> 5
// <6=> 6
// <7=> 7
#ifndef <API key>
#define <API key> 7
#endif
// <e> <API key> - Enables logging in the module.
#ifndef <API key>
#define <API key> 0
#endif
#if <API key>
// <o> <API key> - Default Severity level
// <0=> Off
// <1=> Error
// <2=> Warning
// <3=> Info
// <4=> Debug
#ifndef <API key>
#define <API key> 3
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
#endif //<API key>
#endif //I2S_ENABLED
// <e> LPCOMP_ENABLED - nrf_drv_lpcomp - LPCOMP peripheral driver
#ifndef LPCOMP_ENABLED
#define LPCOMP_ENABLED 0
#endif
#if LPCOMP_ENABLED
// <o> <API key> - Reference voltage
// <0=> Supply 1/8
// <1=> Supply 2/8
// <2=> Supply 3/8
// <3=> Supply 4/8
// <4=> Supply 5/8
// <5=> Supply 6/8
// <6=> Supply 7/8
// <8=> Supply 1/16 (nRF52)
// <9=> Supply 3/16 (nRF52)
// <10=> Supply 5/16 (nRF52)
// <11=> Supply 7/16 (nRF52)
// <12=> Supply 9/16 (nRF52)
// <13=> Supply 11/16 (nRF52)
// <14=> Supply 13/16 (nRF52)
// <15=> Supply 15/16 (nRF52)
// <7=> External Ref 0
// <65543=> External Ref 1
#ifndef <API key>
#define <API key> 3
#endif
// <o> <API key> - Detection
// <0=> Crossing
// <1=> Up
// <2=> Down
#ifndef <API key>
#define <API key> 2
#endif
// <o> LPCOMP_CONFIG_INPUT - Analog input
// <0=> 0
// <1=> 1
// <2=> 2
// <3=> 3
// <4=> 4
// <5=> 5
// <6=> 6
// <7=> 7
#ifndef LPCOMP_CONFIG_INPUT
#define LPCOMP_CONFIG_INPUT 0
#endif
// <q> LPCOMP_CONFIG_HYST - Hysteresis
#ifndef LPCOMP_CONFIG_HYST
#define LPCOMP_CONFIG_HYST 0
#endif
// <o> <API key> - Interrupt priority
// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest)
// <1=> 1
// <2=> 2
// <3=> 3
// <4=> 4
// <5=> 5
// <6=> 6
// <7=> 7
#ifndef <API key>
#define <API key> 7
#endif
// <e> <API key> - Enables logging in the module.
#ifndef <API key>
#define <API key> 0
#endif
#if <API key>
// <o> <API key> - Default Severity level
// <0=> Off
// <1=> Error
// <2=> Warning
// <3=> Info
// <4=> Debug
#ifndef <API key>
#define <API key> 3
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
#endif //<API key>
#endif //LPCOMP_ENABLED
// <e> PDM_ENABLED - nrf_drv_pdm - PDM peripheral driver
#ifndef PDM_ENABLED
#define PDM_ENABLED 0
#endif
#if PDM_ENABLED
// <o> PDM_CONFIG_MODE - Mode
// <0=> Stereo
// <1=> Mono
#ifndef PDM_CONFIG_MODE
#define PDM_CONFIG_MODE 1
#endif
// <o> PDM_CONFIG_EDGE - Edge
// <0=> Left falling
// <1=> Left rising
#ifndef PDM_CONFIG_EDGE
#define PDM_CONFIG_EDGE 0
#endif
// <o> <API key> - Clock frequency
// <134217728=> 1000k
// <138412032=> 1032k (default)
// <142606336=> 1067k
#ifndef <API key>
#define <API key> 138412032
#endif
// <o> <API key> - Interrupt priority
// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest)
// <1=> 1
// <2=> 2
// <3=> 3
// <4=> 4
// <5=> 5
// <6=> 6
// <7=> 7
#ifndef <API key>
#define <API key> 7
#endif
// <e> <API key> - Enables logging in the module.
#ifndef <API key>
#define <API key> 0
#endif
#if <API key>
// <o> <API key> - Default Severity level
// <0=> Off
// <1=> Error
// <2=> Warning
// <3=> Info
// <4=> Debug
#ifndef <API key>
#define <API key> 3
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
#endif //<API key>
#endif //PDM_ENABLED
// <e> <API key> - nrf_drv_common - Peripheral drivers common module
#ifndef <API key>
#define <API key> 0
#endif
#if <API key>
// <e> <API key> - Enables logging in the module.
#ifndef <API key>
#define <API key> 0
#endif
#if <API key>
// <o> <API key> - Default Severity level
// <0=> Off
// <1=> Error
// <2=> Warning
// <3=> Info
// <4=> Debug
#ifndef <API key>
#define <API key> 3
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
#endif //<API key>
#endif //<API key>
// <e> POWER_ENABLED - nrf_drv_power - POWER peripheral driver
#ifndef POWER_ENABLED
#define POWER_ENABLED 0
#endif
#if POWER_ENABLED
// <o> <API key> - Interrupt priority
// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest)
// <1=> 1
// <2=> 2
// <3=> 3
// <4=> 4
// <5=> 5
// <6=> 6
// <7=> 7
#ifndef <API key>
#define <API key> 7
#endif
// <q> <API key> - The default configuration of main DCDC regulator
// <i> This settings means only that components for DCDC regulator are installed and it can be enabled.
#ifndef <API key>
#define <API key> 0
#endif
// <q> <API key> - The default configuration of High Voltage DCDC regulator
// <i> This settings means only that components for DCDC regulator are installed and it can be enabled.
#ifndef <API key>
#define <API key> 0
#endif
#endif //POWER_ENABLED
// <e> PPI_ENABLED - nrf_drv_ppi - PPI peripheral driver
#ifndef PPI_ENABLED
#define PPI_ENABLED 0
#endif
#if PPI_ENABLED
// <e> <API key> - Enables logging in the module.
#ifndef <API key>
#define <API key> 0
#endif
#if <API key>
// <o> <API key> - Default Severity level
// <0=> Off
// <1=> Error
// <2=> Warning
// <3=> Info
// <4=> Debug
#ifndef <API key>
#define <API key> 3
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
#endif //<API key>
#endif //PPI_ENABLED
// <e> PWM_ENABLED - nrf_drv_pwm - PWM peripheral driver
#ifndef PWM_ENABLED
#define PWM_ENABLED 0
#endif
#if PWM_ENABLED
// <o> <API key> - Out0 pin <0-31>
#ifndef <API key>
#define <API key> 31
#endif
// <o> <API key> - Out1 pin <0-31>
#ifndef <API key>
#define <API key> 31
#endif
// <o> <API key> - Out2 pin <0-31>
#ifndef <API key>
#define <API key> 31
#endif
// <o> <API key> - Out3 pin <0-31>
#ifndef <API key>
#define <API key> 31
#endif
// <o> <API key> - Base clock
// <0=> 16 MHz
// <1=> 8 MHz
// <2=> 4 MHz
// <3=> 2 MHz
// <4=> 1 MHz
// <5=> 500 kHz
// <6=> 250 kHz
// <7=> 125 MHz
#ifndef <API key>
#define <API key> 4
#endif
// <o> <API key> - Count mode
// <0=> Up
// <1=> Up and Down
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - Top value
#ifndef <API key>
#define <API key> 1000
#endif
// <o> <API key> - Load mode
// <0=> Common
// <1=> Grouped
// <2=> Individual
// <3=> Waveform
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - Step mode
// <0=> Auto
// <1=> Triggered
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - Interrupt priority
// <i> Priorities 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest)
// <1=> 1
// <2=> 2
// <3=> 3
// <4=> 4
// <5=> 5
// <6=> 6
// <7=> 7
#ifndef <API key>
#define <API key> 7
#endif
// <q> PWM0_ENABLED - Enable PWM0 instance
#ifndef PWM0_ENABLED
#define PWM0_ENABLED 0
#endif
// <q> PWM1_ENABLED - Enable PWM1 instance
#ifndef PWM1_ENABLED
#define PWM1_ENABLED 0
#endif
// <q> PWM2_ENABLED - Enable PWM2 instance
#ifndef PWM2_ENABLED
#define PWM2_ENABLED 0
#endif
// <e> <API key> - Enables logging in the module.
#ifndef <API key>
#define <API key> 0
#endif
#if <API key>
// <o> <API key> - Default Severity level
// <0=> Off
// <1=> Error
// <2=> Warning
// <3=> Info
// <4=> Debug
#ifndef <API key>
#define <API key> 3
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
#endif //<API key>
// <e> <API key> - Enables nRF52 Anomaly 109 workaround for PWM.
// <i> The workaround uses interrupts to wake up the CPU and ensure
// <i> it is active when PWM is about to start a DMA transfer. For
// <i> initial transfer, done when a playback is started via PPI,
// <i> a specific EGU instance is used to generate the interrupt.
// <i> During the playback, the PWM interrupt triggered on SEQEND
// <i> event of a preceding sequence is used to protect the transfer
// <i> done for the next sequence to be played.
#ifndef <API key>
#define <API key> 0
#endif
#if <API key>
// <o> <API key> - EGU instance used by the nRF52 Anomaly 109 workaround for PWM.
// <0=> EGU0
// <1=> EGU1
// <2=> EGU2
// <3=> EGU3
// <4=> EGU4
// <5=> EGU5
#ifndef <API key>
#define <API key> 5
#endif
#endif //<API key>
#endif //PWM_ENABLED
// <e> QDEC_ENABLED - nrf_drv_qdec - QDEC peripheral driver
#ifndef QDEC_ENABLED
#define QDEC_ENABLED 0
#endif
#if QDEC_ENABLED
// <o> <API key> - Report period
// <0=> 10 Samples
// <1=> 40 Samples
// <2=> 80 Samples
// <3=> 120 Samples
// <4=> 160 Samples
// <5=> 200 Samples
// <6=> 240 Samples
// <7=> 280 Samples
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - Sample period
// <0=> 128 us
// <1=> 256 us
// <2=> 512 us
// <3=> 1024 us
// <4=> 2048 us
// <5=> 4096 us
// <6=> 8192 us
// <7=> 16384 us
#ifndef <API key>
#define <API key> 7
#endif
// <o> QDEC_CONFIG_PIO_A - A pin <0-31>
#ifndef QDEC_CONFIG_PIO_A
#define QDEC_CONFIG_PIO_A 31
#endif
// <o> QDEC_CONFIG_PIO_B - B pin <0-31>
#ifndef QDEC_CONFIG_PIO_B
#define QDEC_CONFIG_PIO_B 31
#endif
// <o> QDEC_CONFIG_PIO_LED - LED pin <0-31>
#ifndef QDEC_CONFIG_PIO_LED
#define QDEC_CONFIG_PIO_LED 31
#endif
// <o> QDEC_CONFIG_LEDPRE - LED pre
#ifndef QDEC_CONFIG_LEDPRE
#define QDEC_CONFIG_LEDPRE 511
#endif
// <o> QDEC_CONFIG_LEDPOL - LED polarity
// <0=> Active low
// <1=> Active high
#ifndef QDEC_CONFIG_LEDPOL
#define QDEC_CONFIG_LEDPOL 1
#endif
// <q> QDEC_CONFIG_DBFEN - Debouncing enable
#ifndef QDEC_CONFIG_DBFEN
#define QDEC_CONFIG_DBFEN 0
#endif
// <q> <API key> - Sample ready interrupt enable
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - Interrupt priority
// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest)
// <1=> 1
// <2=> 2
// <3=> 3
// <4=> 4
// <5=> 5
// <6=> 6
// <7=> 7
#ifndef <API key>
#define <API key> 7
#endif
// <e> <API key> - Enables logging in the module.
#ifndef <API key>
#define <API key> 0
#endif
#if <API key>
// <o> <API key> - Default Severity level
// <0=> Off
// <1=> Error
// <2=> Warning
// <3=> Info
// <4=> Debug
#ifndef <API key>
#define <API key> 3
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
#endif //<API key>
#endif //QDEC_ENABLED
// <e> RNG_ENABLED - nrf_drv_rng - RNG peripheral driver
#ifndef RNG_ENABLED
#define RNG_ENABLED 0
#endif
#if RNG_ENABLED
// <q> <API key> - Error correction
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - Pool size
#ifndef <API key>
#define <API key> 32
#endif
// <o> <API key> - Interrupt priority
// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest)
// <1=> 1
// <2=> 2
// <3=> 3
// <4=> 4
// <5=> 5
// <6=> 6
// <7=> 7
#ifndef <API key>
#define <API key> 7
#endif
// <e> <API key> - Enables logging in the module.
#ifndef <API key>
#define <API key> 0
#endif
#if <API key>
// <o> <API key> - Default Severity level
// <0=> Off
// <1=> Error
// <2=> Warning
// <3=> Info
// <4=> Debug
#ifndef <API key>
#define <API key> 3
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
// <q> <API key> - Enables logging of random numbers.
#ifndef <API key>
#define <API key> 0
#endif
#endif //<API key>
#endif //RNG_ENABLED
// <e> RTC_ENABLED - nrf_drv_rtc - RTC peripheral driver
#ifndef RTC_ENABLED
#define RTC_ENABLED 1
#endif
#if RTC_ENABLED
// <o> <API key> - Frequency <16-32768>
#ifndef <API key>
#define <API key> 32768
#endif
// <q> <API key> - Ensures safe compare event triggering
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - Interrupt priority
// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest)
// <1=> 1
// <2=> 2
// <3=> 3
// <4=> 4
// <5=> 5
// <6=> 6
// <7=> 7
#ifndef <API key>
#define <API key> 7
#endif
// <q> RTC0_ENABLED - Enable RTC0 instance
#ifndef RTC0_ENABLED
#define RTC0_ENABLED 0
#endif
// <q> RTC1_ENABLED - Enable RTC1 instance
#ifndef RTC1_ENABLED
#define RTC1_ENABLED 0
#endif
// <q> RTC2_ENABLED - Enable RTC2 instance
#ifndef RTC2_ENABLED
#define RTC2_ENABLED 1
#endif
// <o> <API key> - Maximum possible time[us] in highest priority interrupt
#ifndef <API key>
#define <API key> 2000
#endif
// <e> <API key> - Enables logging in the module.
#ifndef <API key>
#define <API key> 0
#endif
#if <API key>
// <o> <API key> - Default Severity level
// <0=> Off
// <1=> Error
// <2=> Warning
// <3=> Info
// <4=> Debug
#ifndef <API key>
#define <API key> 3
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
#endif //<API key>
#endif //RTC_ENABLED
// <e> SAADC_ENABLED - nrf_drv_saadc - SAADC peripheral driver
#ifndef SAADC_ENABLED
#define SAADC_ENABLED 0
#endif
#if SAADC_ENABLED
// <o> <API key> - Resolution
// <0=> 8 bit
// <1=> 10 bit
// <2=> 12 bit
// <3=> 14 bit
#ifndef <API key>
#define <API key> 1
#endif
// <o> <API key> - Sample period
// <0=> Disabled
// <1=> 2x
// <2=> 4x
// <3=> 8x
// <4=> 16x
// <5=> 32x
// <6=> 64x
// <7=> 128x
// <8=> 256x
#ifndef <API key>
#define <API key> 0
#endif
// <q> <API key> - Enabling low power mode
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - Interrupt priority
// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest)
// <1=> 1
// <2=> 2
// <3=> 3
// <4=> 4
// <5=> 5
// <6=> 6
// <7=> 7
#ifndef <API key>
#define <API key> 7
#endif
// <e> <API key> - Enables logging in the module.
#ifndef <API key>
#define <API key> 0
#endif
#if <API key>
// <o> <API key> - Default Severity level
// <0=> Off
// <1=> Error
// <2=> Warning
// <3=> Info
// <4=> Debug
#ifndef <API key>
#define <API key> 3
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
#endif //<API key>
#endif //SAADC_ENABLED
// <e> SPIS_ENABLED - nrf_drv_spis - SPI Slave driver
#ifndef SPIS_ENABLED
#define SPIS_ENABLED 0
#endif
#if SPIS_ENABLED
// <o> <API key> - Interrupt priority
// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest)
// <1=> 1
// <2=> 2
// <3=> 3
// <4=> 4
// <5=> 5
// <6=> 6
// <7=> 7
#ifndef <API key>
#define <API key> 7
#endif
// <o> SPIS_DEFAULT_MODE - Mode
// <0=> MODE_0
// <1=> MODE_1
// <2=> MODE_2
// <3=> MODE_3
#ifndef SPIS_DEFAULT_MODE
#define SPIS_DEFAULT_MODE 0
#endif
// <o> <API key> - SPIS default bit order
// <0=> MSB first
// <1=> LSB first
#ifndef <API key>
#define <API key> 0
#endif
// <o> SPIS_DEFAULT_DEF - SPIS default DEF character <0-255>
#ifndef SPIS_DEFAULT_DEF
#define SPIS_DEFAULT_DEF 255
#endif
// <o> SPIS_DEFAULT_ORC - SPIS default ORC character <0-255>
#ifndef SPIS_DEFAULT_ORC
#define SPIS_DEFAULT_ORC 255
#endif
// <q> SPIS0_ENABLED - Enable SPIS0 instance
#ifndef SPIS0_ENABLED
#define SPIS0_ENABLED 0
#endif
// <q> SPIS1_ENABLED - Enable SPIS1 instance
#ifndef SPIS1_ENABLED
#define SPIS1_ENABLED 0
#endif
// <q> SPIS2_ENABLED - Enable SPIS2 instance
#ifndef SPIS2_ENABLED
#define SPIS2_ENABLED 0
#endif
// <e> <API key> - Enables logging in the module.
#ifndef <API key>
#define <API key> 0
#endif
#if <API key>
// <o> <API key> - Default Severity level
// <0=> Off
// <1=> Error
// <2=> Warning
// <3=> Info
// <4=> Debug
#ifndef <API key>
#define <API key> 3
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
#endif //<API key>
// <q> <API key> - Enables nRF52 Anomaly 109 workaround for SPIS.
// <i> The workaround uses a GPIOTE channel to generate interrupts
// <i> on falling edges detected on the CSN line. This will make
// <i> the CPU active for the moment when SPIS starts DMA transfers,
// <i> and this way the transfers will be protected.
// <i> This workaround uses GPIOTE driver, so this driver must be
// <i> enabled as well.
#ifndef <API key>
#define <API key> 0
#endif
#endif //SPIS_ENABLED
// <e> SPI_ENABLED - nrf_drv_spi - SPI/SPIM peripheral driver
#ifndef SPI_ENABLED
#define SPI_ENABLED 0
#endif
#if SPI_ENABLED
// <o> <API key> - Interrupt priority
// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest)
// <1=> 1
// <2=> 2
// <3=> 3
// <4=> 4
// <5=> 5
// <6=> 6
// <7=> 7
#ifndef <API key>
#define <API key> 7
#endif
// <e> SPI0_ENABLED - Enable SPI0 instance
#ifndef SPI0_ENABLED
#define SPI0_ENABLED 0
#endif
#if SPI0_ENABLED
// <q> SPI0_USE_EASY_DMA - Use EasyDMA
#ifndef SPI0_USE_EASY_DMA
#define SPI0_USE_EASY_DMA 1
#endif
// <o> <API key> - SPI frequency
// <33554432=> 125 kHz
// <67108864=> 250 kHz
// <134217728=> 500 kHz
// <268435456=> 1 MHz
// <536870912=> 2 MHz
// <1073741824=> 4 MHz
// <2147483648=> 8 MHz
#ifndef <API key>
#define <API key> 1073741824
#endif
#endif //SPI0_ENABLED
// <e> SPI1_ENABLED - Enable SPI1 instance
#ifndef SPI1_ENABLED
#define SPI1_ENABLED 0
#endif
#if SPI1_ENABLED
// <q> SPI1_USE_EASY_DMA - Use EasyDMA
#ifndef SPI1_USE_EASY_DMA
#define SPI1_USE_EASY_DMA 1
#endif
// <o> <API key> - SPI frequency
// <33554432=> 125 kHz
// <67108864=> 250 kHz
// <134217728=> 500 kHz
// <268435456=> 1 MHz
// <536870912=> 2 MHz
// <1073741824=> 4 MHz
// <2147483648=> 8 MHz
#ifndef <API key>
#define <API key> 1073741824
#endif
#endif //SPI1_ENABLED
// <e> SPI2_ENABLED - Enable SPI2 instance
#ifndef SPI2_ENABLED
#define SPI2_ENABLED 0
#endif
#if SPI2_ENABLED
// <q> SPI2_USE_EASY_DMA - Use EasyDMA
#ifndef SPI2_USE_EASY_DMA
#define SPI2_USE_EASY_DMA 1
#endif
// <q> <API key> - Use EasyDMA
#ifndef <API key>
#define <API key> 1
#endif
#endif //SPI2_ENABLED
// <e> <API key> - Enables logging in the module.
#ifndef <API key>
#define <API key> 0
#endif
#if <API key>
// <o> <API key> - Default Severity level
// <0=> Off
// <1=> Error
// <2=> Warning
// <3=> Info
// <4=> Debug
#ifndef <API key>
#define <API key> 3
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
#endif //<API key>
// <q> <API key> - Enables nRF52 anomaly 109 workaround for SPIM.
// <i> The workaround uses interrupts to wake up the CPU by catching
// <i> a start event of zero-length transmission to start the clock. This
// <i> ensures that the DMA transfer will be executed without issues and
// <i> that the proper transfer will be started. See more in the Errata
// <i> document or Anomaly 109 Addendum located at
#ifndef <API key>
#define <API key> 0
#endif
#endif //SPI_ENABLED
// <e> TIMER_ENABLED - nrf_drv_timer - TIMER periperal driver
#ifndef TIMER_ENABLED
#define TIMER_ENABLED 0
#endif
#if TIMER_ENABLED
// <o> <API key> - Timer frequency if in Timer mode
// <0=> 16 MHz
// <1=> 8 MHz
// <2=> 4 MHz
// <3=> 2 MHz
// <4=> 1 MHz
// <5=> 500 kHz
// <6=> 250 kHz
// <7=> 125 kHz
// <8=> 62.5 kHz
// <9=> 31.25 kHz
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - Timer mode or operation
// <0=> Timer
// <1=> Counter
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - Timer counter bit width
// <0=> 16 bit
// <1=> 8 bit
// <2=> 24 bit
// <3=> 32 bit
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - Interrupt priority
// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest)
// <1=> 1
// <2=> 2
// <3=> 3
// <4=> 4
// <5=> 5
// <6=> 6
// <7=> 7
#ifndef <API key>
#define <API key> 7
#endif
// <q> TIMER0_ENABLED - Enable TIMER0 instance
#ifndef TIMER0_ENABLED
#define TIMER0_ENABLED 0
#endif
// <q> TIMER1_ENABLED - Enable TIMER1 instance
#ifndef TIMER1_ENABLED
#define TIMER1_ENABLED 0
#endif
// <q> TIMER2_ENABLED - Enable TIMER2 instance
#ifndef TIMER2_ENABLED
#define TIMER2_ENABLED 0
#endif
// <q> TIMER3_ENABLED - Enable TIMER3 instance
#ifndef TIMER3_ENABLED
#define TIMER3_ENABLED 0
#endif
// <q> TIMER4_ENABLED - Enable TIMER4 instance
#ifndef TIMER4_ENABLED
#define TIMER4_ENABLED 0
#endif
// <e> <API key> - Enables logging in the module.
#ifndef <API key>
#define <API key> 0
#endif
#if <API key>
// <o> <API key> - Default Severity level
// <0=> Off
// <1=> Error
// <2=> Warning
// <3=> Info
// <4=> Debug
#ifndef <API key>
#define <API key> 3
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
#endif //<API key>
#endif //TIMER_ENABLED
// <e> TWIS_ENABLED - nrf_drv_twis - TWIS peripheral driver
#ifndef TWIS_ENABLED
#define TWIS_ENABLED 0
#endif
#if TWIS_ENABLED
// <o> <API key> - Address0
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - Address1
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - SCL pin pull configuration
// <0=> Disabled
// <1=> Pull down
// <3=> Pull up
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - SDA pin pull configuration
// <0=> Disabled
// <1=> Pull down
// <3=> Pull up
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - Interrupt priority
// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest)
// <1=> 1
// <2=> 2
// <3=> 3
// <4=> 4
// <5=> 5
// <6=> 6
// <7=> 7
#ifndef <API key>
#define <API key> 7
#endif
// <q> TWIS0_ENABLED - Enable TWIS0 instance
#ifndef TWIS0_ENABLED
#define TWIS0_ENABLED 0
#endif
// <q> TWIS1_ENABLED - Enable TWIS1 instance
#ifndef TWIS1_ENABLED
#define TWIS1_ENABLED 0
#endif
// <q> <API key> - Assume that any instance would be initialized only once
// <i> Optimization flag. Registers used by TWIS are shared by other peripherals. Normally, during initialization driver tries to clear all registers to known state before doing the initialization itself. This gives initialization safe procedure, no matter when it would be called. If you activate TWIS only once and do never uninitialize it - set this flag to 1 what gives more optimal code.
#ifndef <API key>
#define <API key> 0
#endif
// <q> TWIS_NO_SYNC_MODE - Remove support for synchronous mode
// <i> Synchronous mode would be used in specific situations. And it uses some additional code and data memory to safely process state machine by polling it in status functions. If this functionality is not required it may be disabled to free some resources.
#ifndef TWIS_NO_SYNC_MODE
#define TWIS_NO_SYNC_MODE 0
#endif
// <e> <API key> - Enables logging in the module.
#ifndef <API key>
#define <API key> 0
#endif
#if <API key>
// <o> <API key> - Default Severity level
// <0=> Off
// <1=> Error
// <2=> Warning
// <3=> Info
// <4=> Debug
#ifndef <API key>
#define <API key> 3
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
#endif //<API key>
#endif //TWIS_ENABLED
// <e> TWI_ENABLED - nrf_drv_twi - TWI/TWIM peripheral driver
#ifndef TWI_ENABLED
#define TWI_ENABLED 0
#endif
#if TWI_ENABLED
// <o> <API key> - Frequency
// <26738688=> 100k
// <67108864=> 250k
// <104857600=> 400k
#ifndef <API key>
#define <API key> 26738688
#endif
// <q> <API key> - Enables bus clearing procedure during init
#ifndef <API key>
#define <API key> 0
#endif
// <q> <API key> - Enables bus holding after uninit
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - Interrupt priority
// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest)
// <1=> 1
// <2=> 2
// <3=> 3
// <4=> 4
// <5=> 5
// <6=> 6
// <7=> 7
#ifndef <API key>
#define <API key> 7
#endif
// <e> TWI0_ENABLED - Enable TWI0 instance
#ifndef TWI0_ENABLED
#define TWI0_ENABLED 0
#endif
#if TWI0_ENABLED
// <q> TWI0_USE_EASY_DMA - Use EasyDMA (if present)
#ifndef TWI0_USE_EASY_DMA
#define TWI0_USE_EASY_DMA 0
#endif
#endif //TWI0_ENABLED
// <e> TWI1_ENABLED - Enable TWI1 instance
#ifndef TWI1_ENABLED
#define TWI1_ENABLED 0
#endif
#if TWI1_ENABLED
// <q> TWI1_USE_EASY_DMA - Use EasyDMA (if present)
#ifndef TWI1_USE_EASY_DMA
#define TWI1_USE_EASY_DMA 0
#endif
#endif //TWI1_ENABLED
// <e> <API key> - Enables logging in the module.
#ifndef <API key>
#define <API key> 0
#endif
#if <API key>
// <o> <API key> - Default Severity level
// <0=> Off
// <1=> Error
// <2=> Warning
// <3=> Info
// <4=> Debug
#ifndef <API key>
#define <API key> 3
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
#endif //<API key>
// <q> <API key> - Enables nRF52 anomaly 109 workaround for TWIM.
// <i> The workaround uses interrupts to wake up the CPU by catching
// <i> the start event of zero-frequency transmission, clear the
// <i> peripheral, set desired frequency, start the peripheral, and
// <i> the proper transmission. See more in the Errata document or
#ifndef <API key>
#define <API key> 0
#endif
#endif //TWI_ENABLED
// <e> UART_ENABLED - nrf_drv_uart - UART/UARTE peripheral driver
#ifndef UART_ENABLED
#define UART_ENABLED 1
#endif
#if UART_ENABLED
// <o> <API key> - Hardware Flow Control
// <0=> Disabled
// <1=> Enabled
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - Parity
// <0=> Excluded
// <14=> Included
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - Default Baudrate
// <323584=> 1200 baud
// <643072=> 2400 baud
// <1290240=> 4800 baud
// <2576384=> 9600 baud
// <3862528=> 14400 baud
// <5152768=> 19200 baud
// <7716864=> 28800 baud
// <10289152=> 38400 baud
// <15400960=> 57600 baud
// <20615168=> 76800 baud
// <30801920=> 115200 baud
// <61865984=> 230400 baud
// <67108864=> 250000 baud
// <121634816=> 460800 baud
// <251658240=> 921600 baud
// <268435456=> 57600 baud
#ifndef <API key>
#define <API key> 30801920
#endif
// <o> <API key> - Interrupt priority
// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest)
// <1=> 1
// <2=> 2
// <3=> 3
// <4=> 4
// <5=> 5
// <6=> 6
// <7=> 7
#ifndef <API key>
#define <API key> 7
#endif
// <q> <API key> - Driver supporting EasyDMA
#ifndef <API key>
#define <API key> 1
#endif
// <q> UART_LEGACY_SUPPORT - Driver supporting Legacy mode
#ifndef UART_LEGACY_SUPPORT
#define UART_LEGACY_SUPPORT 1
#endif
// <e> UART0_ENABLED - Enable UART0 instance
#ifndef UART0_ENABLED
#define UART0_ENABLED 1
#endif
#if UART0_ENABLED
// <q> <API key> - Default setting for using EasyDMA
#ifndef <API key>
#define <API key> 1
#endif
#endif //UART0_ENABLED
// <e> <API key> - Enables logging in the module.
#ifndef <API key>
#define <API key> 0
#endif
#if <API key>
// <o> <API key> - Default Severity level
// <0=> Off
// <1=> Error
// <2=> Warning
// <3=> Info
// <4=> Debug
#ifndef <API key>
#define <API key> 3
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
#endif //<API key>
#endif //UART_ENABLED
// <e> USBD_ENABLED - nrf_drv_usbd - USB driver
#ifndef USBD_ENABLED
#define USBD_ENABLED 0
#endif
#if USBD_ENABLED
// <o> <API key> - Interrupt priority
// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest)
// <1=> 1
// <2=> 2
// <3=> 3
// <4=> 4
// <5=> 5
// <6=> 6
// <7=> 7
#ifndef <API key>
#define <API key> 7
#endif
// <o> <API key> - USBD SMA scheduler working scheme
// <0=> Prioritized access
// <1=> Round Robin
#ifndef <API key>
#define <API key> 0
#endif
// <q> <API key> - Enable logging
#ifndef <API key>
#define <API key> 0
#endif
#endif //USBD_ENABLED
// <e> WDT_ENABLED - nrf_drv_wdt - WDT peripheral driver
#ifndef WDT_ENABLED
#define WDT_ENABLED 0
#endif
#if WDT_ENABLED
// <o> <API key> - WDT behavior in CPU SLEEP or HALT mode
// <1=> Run in SLEEP, Pause in HALT
// <8=> Pause in SLEEP, Run in HALT
// <9=> Run in SLEEP and HALT
// <0=> Pause in SLEEP and HALT
#ifndef <API key>
#define <API key> 1
#endif
// <o> <API key> - Reload value <15-4294967295>
#ifndef <API key>
#define <API key> 2000
#endif
// <o> <API key> - Interrupt priority
// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest)
// <1=> 1
// <2=> 2
// <3=> 3
// <4=> 4
// <5=> 5
// <6=> 6
// <7=> 7
#ifndef <API key>
#define <API key> 7
#endif
// <e> <API key> - Enables logging in the module.
#ifndef <API key>
#define <API key> 0
#endif
#if <API key>
// <o> <API key> - Default Severity level
// <0=> Off
// <1=> Error
// <2=> Warning
// <3=> Info
// <4=> Debug
#ifndef <API key>
#define <API key> 3
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
#endif //<API key>
#endif //WDT_ENABLED
// <h> nRF_Libraries
// <q> APP_GPIOTE_ENABLED - app_gpiote - GPIOTE events dispatcher
#ifndef APP_GPIOTE_ENABLED
#define APP_GPIOTE_ENABLED 0
#endif
// <q> APP_PWM_ENABLED - app_pwm - PWM functionality
#ifndef APP_PWM_ENABLED
#define APP_PWM_ENABLED 0
#endif
// <e> <API key> - app_scheduler - Events scheduler
#ifndef <API key>
#define <API key> 1
#endif
#if <API key>
// <q> <API key> - Enabling pause feature
#ifndef <API key>
#define <API key> 0
#endif
// <q> <API key> - Enabling scheduler profiling
#ifndef <API key>
#define <API key> 0
#endif
#endif //<API key>
// <e> APP_TIMER_ENABLED - app_timer - Application timer functionality
#ifndef APP_TIMER_ENABLED
#define APP_TIMER_ENABLED 1
#endif
#if APP_TIMER_ENABLED
// <o> <API key> - Configure RTC prescaler.
// <0=> 32768 Hz
// <1=> 16384 Hz
// <3=> 8192 Hz
// <7=> 4096 Hz
// <15=> 2048 Hz
// <31=> 1024 Hz
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - Interrupt priority
// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest)
// <1=> 1
// <2=> 2
// <3=> 3
// <4=> 4
// <5=> 5
// <6=> 6
// <7=> 7
#ifndef <API key>
#define <API key> 7
#endif
// <o> <API key> - Capacity of timer requests queue.
// <i> Size of the queue depends on how many timers are used
// <i> in the system, how often timers are started and overall
// <i> system latency. If queue size is too small app_timer calls
// <i> will fail.
#ifndef <API key>
#define <API key> 10
#endif
// <q> <API key> - Enable scheduling app_timer events to app_scheduler
#ifndef <API key>
#define <API key> 0
#endif
// <q> <API key> - Enable app_timer profiling
#ifndef <API key>
#define <API key> 0
#endif
// <q> <API key> - Enable RTC always on
// <i> If option is enabled RTC is kept running even if there is no active timers.
// <i> This option can be used when app_timer is used for timestamping.
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - Configure SWI instance used.
// <0=> 0
// <1=> 1
#ifndef <API key>
#define <API key> 0
#endif
#endif //APP_TIMER_ENABLED
// <q> APP_TWI_ENABLED - app_twi - TWI transaction manager
#ifndef APP_TWI_ENABLED
#define APP_TWI_ENABLED 0
#endif
// <e> APP_UART_ENABLED - app_uart - UART driver
#ifndef APP_UART_ENABLED
#define APP_UART_ENABLED 0
#endif
#if APP_UART_ENABLED
// <o> <API key> - UART instance used
// <0=> 0
#ifndef <API key>
#define <API key> 0
#endif
#endif //APP_UART_ENABLED
// <q> <API key> - app_usbd_audio - USB AUDIO class
#ifndef <API key>
#define <API key> 0
#endif
// <q> <API key> - app_usbd_hid - USB HID class
#ifndef <API key>
#define <API key> 0
#endif
// <q> <API key> - <API key> - USB HID generic
#ifndef <API key>
#define <API key> 0
#endif
// <q> <API key> - app_usbd_hid_kbd - USB HID keyboard
#ifndef <API key>
#define <API key> 0
#endif
// <q> <API key> - app_usbd_hid_mouse - USB HID mouse
#ifndef <API key>
#define <API key> 0
#endif
// <q> BUTTON_ENABLED - app_button - buttons handling module
#ifndef BUTTON_ENABLED
#define BUTTON_ENABLED 1
#endif
// <q> CRC16_ENABLED - crc16 - CRC16 calculation routines
#ifndef CRC16_ENABLED
#define CRC16_ENABLED 0
#endif
// <q> CRC32_ENABLED - crc32 - CRC32 calculation routines
#ifndef CRC32_ENABLED
#define CRC32_ENABLED 0
#endif
// <q> ECC_ENABLED - ecc - Elliptic Curve Cryptography Library
#ifndef ECC_ENABLED
#define ECC_ENABLED 0
#endif
// <e> FDS_ENABLED - fds - Flash data storage module
#ifndef FDS_ENABLED
#define FDS_ENABLED 0
#endif
#if FDS_ENABLED
// <o> FDS_OP_QUEUE_SIZE - Size of the internal queue.
#ifndef FDS_OP_QUEUE_SIZE
#define FDS_OP_QUEUE_SIZE 4
#endif
// <o> <API key> - Determines how many @ref fds_record_chunk_t structures can be buffered at any time.
#ifndef <API key>
#define <API key> 8
#endif
// <o> FDS_MAX_USERS - Maximum number of callbacks that can be registered.
#ifndef FDS_MAX_USERS
#define FDS_MAX_USERS 8
#endif
// <o> FDS_VIRTUAL_PAGES - Number of virtual flash pages to use.
// <i> One of the virtual pages is reserved by the system for garbage collection.
// <i> Therefore, the minimum is two virtual pages: one page to store data and
// <i> one page to be used by the system for garbage collection. The total amount
// <i> of flash memory that is used by FDS amounts to @ref FDS_VIRTUAL_PAGES
// <i> @ref <API key> * 4 bytes.
#ifndef FDS_VIRTUAL_PAGES
#define FDS_VIRTUAL_PAGES 3
#endif
// <o> <API key> - The size of a virtual page of flash memory, expressed in number of 4-byte words.
// <i> By default, a virtual page is the same size as a physical page.
// <i> The size of a virtual page must be a multiple of the size of a physical page.
// <1024=> 1024
// <2048=> 2048
#ifndef <API key>
#define <API key> 1024
#endif
#endif //FDS_ENABLED
// <e> FSTORAGE_ENABLED - fstorage - Flash storage module
#ifndef FSTORAGE_ENABLED
#define FSTORAGE_ENABLED 0
#endif
#if FSTORAGE_ENABLED
// <o> FS_QUEUE_SIZE - Configures the size of the internal queue.
// <i> Increase this if there are many users, or if it is likely that many
// <i> operation will be queued at once without waiting for the previous operations
// <i> to complete. In general, increase the queue size if you frequently receive
// <i> @ref FS_ERR_QUEUE_FULL errors when calling @ref fs_store or @ref fs_erase.
#ifndef FS_QUEUE_SIZE
#define FS_QUEUE_SIZE 4
#endif
// <o> FS_OP_MAX_RETRIES - Number attempts to execute an operation if the SoftDevice fails.
// <i> Increase this value if events return the @ref <API key>
// <i> error often. The SoftDevice may fail to schedule flash access due to high BLE activity.
#ifndef FS_OP_MAX_RETRIES
#define FS_OP_MAX_RETRIES 3
#endif
// <o> <API key> - Maximum number of words to be written to flash in a single operation.
// <i> Tweaking this value can increase the chances of the SoftDevice being
// <i> able to fit flash operations in between radio activity. This value is bound by the
// <i> maximum number of words which the SoftDevice can write to flash in a single call to
// <i> @ref sd_flash_write, which is 256 words for nRF51 ICs and 1024 words for nRF52 ICs.
#ifndef <API key>
#define <API key> 1024
#endif
#endif //FSTORAGE_ENABLED
// <q> <API key> - hardfault_default - HardFault default handler for debugging and release
#ifndef <API key>
#define <API key> 0
#endif
// <e> <API key> - hci_mem_pool - memory pool implementation used by HCI
#ifndef <API key>
#define <API key> 0
#endif
#if <API key>
// <o> HCI_TX_BUF_SIZE - TX buffer size in bytes.
#ifndef HCI_TX_BUF_SIZE
#define HCI_TX_BUF_SIZE 600
#endif
// <o> HCI_RX_BUF_SIZE - RX buffer size in bytes.
#ifndef HCI_RX_BUF_SIZE
#define HCI_RX_BUF_SIZE 600
#endif
// <o> <API key> - RX buffer queue size.
#ifndef <API key>
#define <API key> 4
#endif
#endif //<API key>
// <e> HCI_SLIP_ENABLED - hci_slip - SLIP protocol implementation used by HCI
#ifndef HCI_SLIP_ENABLED
#define HCI_SLIP_ENABLED 0
#endif
#if HCI_SLIP_ENABLED
// <o> HCI_UART_BAUDRATE - Default Baudrate
// <323584=> 1200 baud
// <643072=> 2400 baud
// <1290240=> 4800 baud
// <2576384=> 9600 baud
// <3862528=> 14400 baud
// <5152768=> 19200 baud
// <7716864=> 28800 baud
// <10289152=> 38400 baud
// <15400960=> 57600 baud
// <20615168=> 76800 baud
// <30801920=> 115200 baud
// <61865984=> 230400 baud
// <67108864=> 250000 baud
// <121634816=> 460800 baud
// <251658240=> 921600 baud
// <268435456=> 57600 baud
#ifndef HCI_UART_BAUDRATE
#define HCI_UART_BAUDRATE 30801920
#endif
// <o> <API key> - Hardware Flow Control
// <0=> Disabled
// <1=> Enabled
#ifndef <API key>
#define <API key> 0
#endif
// <o> HCI_UART_RX_PIN - UART RX pin
#ifndef HCI_UART_RX_PIN
#define HCI_UART_RX_PIN 8
#endif
// <o> HCI_UART_TX_PIN - UART TX pin
#ifndef HCI_UART_TX_PIN
#define HCI_UART_TX_PIN 6
#endif
// <o> HCI_UART_RTS_PIN - UART RTS pin
#ifndef HCI_UART_RTS_PIN
#define HCI_UART_RTS_PIN 5
#endif
// <o> HCI_UART_CTS_PIN - UART CTS pin
#ifndef HCI_UART_CTS_PIN
#define HCI_UART_CTS_PIN 7
#endif
#endif //HCI_SLIP_ENABLED
// <e> <API key> - hci_transport - HCI transport
#ifndef <API key>
#define <API key> 0
#endif
#if <API key>
// <o> <API key> - Maximum size of a single application packet in bits.
#ifndef <API key>
#define <API key> 8000
#endif
#endif //<API key>
// <q> <API key> - led_softblink - led_softblink module
#ifndef <API key>
#define <API key> 0
#endif
// <q> <API key> - low_power_pwm - low_power_pwm module
#ifndef <API key>
#define <API key> 0
#endif
// <e> MEM_MANAGER_ENABLED - mem_manager - Dynamic memory allocator
#ifndef MEM_MANAGER_ENABLED
#define MEM_MANAGER_ENABLED 0
#endif
#if MEM_MANAGER_ENABLED
// <o> <API key> - Size of each memory blocks identified as 'small' block. <0-255>
#ifndef <API key>
#define <API key> 1
#endif
// <o> <API key> - Size of each memory blocks identified as 'small' block.
// <i> Size of each memory blocks identified as 'small' block. Memory block are recommended to be word-sized.
#ifndef <API key>
#define <API key> 32
#endif
// <o> <API key> - Size of each memory blocks identified as 'medium' block. <0-255>
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - Size of each memory blocks identified as 'medium' block.
// <i> Size of each memory blocks identified as 'medium' block. Memory block are recommended to be word-sized.
#ifndef <API key>
#define <API key> 256
#endif
// <o> <API key> - Size of each memory blocks identified as 'large' block. <0-255>
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - Size of each memory blocks identified as 'large' block.
// <i> Size of each memory blocks identified as 'large' block. Memory block are recommended to be word-sized.
#ifndef <API key>
#define <API key> 256
#endif
// <o> <API key> - Size of each memory blocks identified as 'extra large' block. <0-255>
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - Size of each memory blocks identified as 'extra large' block.
// <i> Size of each memory blocks identified as 'extra large' block. Memory block are recommended to be word-sized.
#ifndef <API key>
#define <API key> 1320
#endif
// <o> <API key> - Size of each memory blocks identified as 'extra extra large' block. <0-255>
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - Size of each memory blocks identified as 'extra extra large' block.
// <i> Size of each memory blocks identified as 'extra extra large' block. Memory block are recommended to be word-sized.
#ifndef <API key>
#define <API key> 3444
#endif
// <o> <API key> - Size of each memory blocks identified as 'extra small' block. <0-255>
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - Size of each memory blocks identified as 'extra small' block.
// <i> Size of each memory blocks identified as 'extra large' block. Memory block are recommended to be word-sized.
#ifndef <API key>
#define <API key> 64
#endif
// <o> <API key> - Size of each memory blocks identified as 'extra extra small' block. <0-255>
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - Size of each memory blocks identified as 'extra extra small' block.
// <i> Size of each memory blocks identified as 'extra extra small' block. Memory block are recommended to be word-sized.
#ifndef <API key>
#define <API key> 32
#endif
// <q> <API key> - Enable debug trace in the module.
#ifndef <API key>
#define <API key> 0
#endif
// <q> <API key> - Disable API parameter checks in the module.
#ifndef <API key>
#define <API key> 0
#endif
#endif //MEM_MANAGER_ENABLED
// <e> NRF_CSENSE_ENABLED - nrf_csense - Capacitive sensor module
#ifndef NRF_CSENSE_ENABLED
#define NRF_CSENSE_ENABLED 0
#endif
#if NRF_CSENSE_ENABLED
// <o> <API key> - Minimum value of change required to determine that a pad was touched.
#ifndef <API key>
#define <API key> 15
#endif
// <o> <API key> - Minimum value measured on a pad required to take it into account while calculating the step.
#ifndef <API key>
#define <API key> 70
#endif
// <o> <API key> - Minimum normalized value on a pad required to take its value into account.
#ifndef <API key>
#define <API key> 20
#endif
// <o> <API key> - Maximum number of pads used for one instance.
#ifndef <API key>
#define <API key> 20
#endif
// <o> <API key> - Maximum normalized value obtained from measurement.
#ifndef <API key>
#define <API key> 1000
#endif
// <o> <API key> - Output pin used by the low-level module.
// <i> This is used when capacitive sensor does not use COMP.
#ifndef <API key>
#define <API key> 26
#endif
#endif //NRF_CSENSE_ENABLED
// <e> <API key> - nrf_drv_csense - Capacitive sensor low-level module
#ifndef <API key>
#define <API key> 0
#endif
#if <API key>
// <e> USE_COMP - Use the comparator to implement the capacitive sensor driver.
// <i> Due to Anomaly 84, COMP I_SOURCE is not functional. It has too high a varation.
#ifndef USE_COMP
#define USE_COMP 0
#endif
#if USE_COMP
// <o> TIMER0_FOR_CSENSE - First TIMER instance used by the driver (not used on nRF51).
#ifndef TIMER0_FOR_CSENSE
#define TIMER0_FOR_CSENSE 1
#endif
// <o> TIMER1_FOR_CSENSE - Second TIMER instance used by the driver (not used on nRF51).
#ifndef TIMER1_FOR_CSENSE
#define TIMER1_FOR_CSENSE 2
#endif
// <o> MEASUREMENT_PERIOD - Single measurement period.
// <i> Time of a single measurement can be calculated as
// <i> T = (1/2)*MEASUREMENT_PERIOD*(1/f_OSC) where f_OSC = I_SOURCE / (2C*(VUP-VDOWN) ).
// <i> I_SOURCE, VUP, and VDOWN are values used to initialize COMP and C is the capacitance of the used pad.
#ifndef MEASUREMENT_PERIOD
#define MEASUREMENT_PERIOD 20
#endif
#endif //USE_COMP
#endif //<API key>
// <q> NRF_QUEUE_ENABLED - nrf_queue - Queue module
#ifndef NRF_QUEUE_ENABLED
#define NRF_QUEUE_ENABLED 0
#endif
// <q> <API key> - nrf_strerror - Library for converting error code to string.
#ifndef <API key>
#define <API key> 1
#endif
// <q> SLIP_ENABLED - slip - SLIP encoding and decoding
#ifndef SLIP_ENABLED
#define SLIP_ENABLED 0
#endif
// <h> app_usbd_cdc_acm - USB CDC ACM class
// <q> <API key> - Enabling USBD CDC ACM Class library
#ifndef <API key>
#define <API key> 0
#endif
// <q> <API key> - Enables logging in the module.
#ifndef <API key>
#define <API key> 0
#endif
// <h> app_usbd_msc - USB MSC class
// <q> <API key> - Enabling USBD MSC Class library
#ifndef <API key>
#define <API key> 0
#endif
// <q> <API key> - Enables logging in the module.
#ifndef <API key>
#define <API key> 0
#endif
// <h> nRF_Log
// <e> NRF_LOG_ENABLED - nrf_log - Logging
#ifndef NRF_LOG_ENABLED
#define NRF_LOG_ENABLED 1
#endif
#if NRF_LOG_ENABLED
// <e> NRF_LOG_USES_COLORS - If enabled then ANSI escape code for colors is prefixed to every string
#ifndef NRF_LOG_USES_COLORS
#define NRF_LOG_USES_COLORS 0
#endif
#if NRF_LOG_USES_COLORS
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
// <o> NRF_LOG_ERROR_COLOR - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef NRF_LOG_ERROR_COLOR
#define NRF_LOG_ERROR_COLOR 0
#endif
// <o> <API key> - ANSI escape code prefix.
// <0=> Default
// <1=> Black
// <2=> Red
// <3=> Green
// <4=> Yellow
// <5=> Blue
// <6=> Magenta
// <7=> Cyan
// <8=> White
#ifndef <API key>
#define <API key> 0
#endif
#endif //NRF_LOG_USES_COLORS
// <o> <API key> - Default Severity level
// <0=> Off
// <1=> Error
// <2=> Warning
// <3=> Info
// <4=> Debug
#ifndef <API key>
#define <API key> 3
#endif
// <e> NRF_LOG_DEFERRED - Enable deffered logger.
// <i> Log data is buffered and can be processed in idle.
#ifndef NRF_LOG_DEFERRED
#define NRF_LOG_DEFERRED 1
#endif
#if NRF_LOG_DEFERRED
// <o> <API key> - Size of the buffer for logs in words.
// <i> Must be power of 2
#ifndef <API key>
#define <API key> 256
#endif
#endif //NRF_LOG_DEFERRED
// <q> <API key> - Enable timestamping
// <i> Function for getting the timestamp is provided by the user
#ifndef <API key>
#define <API key> 0
#endif
#endif //NRF_LOG_ENABLED
// <h> nrf_log_backend - Logging sink
// <o> <API key> - Buffer for storing single output string
// <i> Logger backend RAM usage is determined by this value.
#ifndef <API key>
#define <API key> 256
#endif
// <o> <API key> - Number of digits for timestamp
// <i> If higher resolution timestamp source is used it might be needed to increase that
#ifndef <API key>
#define <API key> 8
#endif
// <e> <API key> - If enabled data is printed over UART
#ifndef <API key>
#define <API key> 1
#endif
#if <API key>
// <o> <API key> - Default Baudrate
// <323584=> 1200 baud
// <643072=> 2400 baud
// <1290240=> 4800 baud
// <2576384=> 9600 baud
// <3862528=> 14400 baud
// <5152768=> 19200 baud
// <7716864=> 28800 baud
// <10289152=> 38400 baud
// <15400960=> 57600 baud
// <20615168=> 76800 baud
// <30801920=> 115200 baud
// <61865984=> 230400 baud
// <67108864=> 250000 baud
// <121634816=> 460800 baud
// <251658240=> 921600 baud
// <268435456=> 57600 baud
#ifndef <API key>
#define <API key> 30801920
#endif
// <o> <API key> - UART TX pin
#ifndef <API key>
#define <API key> 6
#endif
// <o> <API key> - UART RX pin
#ifndef <API key>
#define <API key> 8
#endif
// <o> <API key> - UART RTS pin
#ifndef <API key>
#define <API key> 5
#endif
// <o> <API key> - UART CTS pin
#ifndef <API key>
#define <API key> 7
#endif
// <o> <API key> - Hardware Flow Control
// <0=> Disabled
// <1=> Enabled
#ifndef <API key>
#define <API key> 0
#endif
// <o> <API key> - UART instance used
// <0=> 0
#ifndef <API key>
#define <API key> 0
#endif
#endif //<API key>
// <e> <API key> - If enabled data is printed using RTT
#ifndef <API key>
#define <API key> 0
#endif
#if <API key>
// <o> <API key> - RTT output buffer size.
// <i> Should be equal or bigger than \ref <API key>.
// <i> This value is used in Segger RTT configuration to set the buffer size
// <i> if it is bigger than default RTT buffer size.
#ifndef <API key>
#define <API key> 512
#endif
#endif //<API key>
// <h> nRF_Segger_RTT
// <h> segger_rtt - SEGGER RTT
// <o> <API key> - Size of upstream buffer.
// <i> Note that either @ref <API key>
// <i> or this value is actually used. It depends on which one is bigger.
#ifndef <API key>
#define <API key> 64
#endif
// <o> <API key> - Size of upstream buffer.
#ifndef <API key>
#define <API key> 2
#endif
// <o> <API key> - Size of upstream buffer.
#ifndef <API key>
#define <API key> 16
#endif
// <o> <API key> - Size of upstream buffer.
#ifndef <API key>
#define <API key> 2
#endif
// <o> <API key> - RTT behavior if the buffer is full.
// <i> The following modes are supported:
// <i> - SKIP - Do not block, output nothing.
// <i> - TRIM - Do not block, output as much as fits.
// <i> - BLOCK - Wait until there is space in the buffer.
// <0=> SKIP
// <1=> TRIM
// <2=> BLOCK_IF_FIFO_FULL
#ifndef <API key>
#define <API key> 0
#endif
// <<< end of configuration section >>>
#endif //SDK_CONFIG_H
|
<?php
namespace spf\swoole\worker;
interface IWebSocketWorker {
public function onStart($server, $workerId);
public function onShutdown($server, $workerId);
public function onTask($server, $taskId, $fromId, $data);
public function onFinish($server, $taskId, $data);
public function onOpen($server, $request);
public function onClose();
public function onMessage($server, $frame);
}
|
// UDPConnection.hpp for server in /home/galibe_s/rendu/Spider/server/core
// Made by stephane galibert
// Login <galibe_s@epitech.net>
// Started on Sun Nov 6 17:00:50 2016 stephane galibert
// Last update Thu Nov 10 12:34:21 2016 stephane galibert
#pragma once
#include <iostream>
#include <string>
#include <queue>
#include <memory>
#include <boost/bind.hpp>
#include "AConnection.hpp"
class ConnectionManager;
class UDPConnection : public AConnection
{
public:
UDPConnection(boost::asio::io_service &io_service,
RequestHandler &reqHandler,
PluginManager &pluginManager,
ConnectionManager &cm,
ServerConfig &config,
int port);
virtual ~UDPConnection(void);
virtual void start(void);
virtual void write(Packet *packet);
virtual void addLog(std::string const& toadd);
virtual void connectDB(void);
virtual void disconnectDB(void);
virtual void broadcast(std::string const& msg);
virtual void kill(void);
protected:
virtual void do_write(boost::system::error_code const& ec, size_t len);
virtual void do_read(boost::system::error_code const& ec, size_t len);
virtual void do_handshake(boost::system::error_code const& ec);
void write(void);
void read(void);
boost::asio::ip::udp::socket _socket;
boost::asio::ip::udp::endpoint _endpoint;
boost::asio::streambuf _read;
std::queue<Packet *> _toWrites;
};
|
#pagefrog-big-logo {
width: 200px;
margin-top:20px;
}
#<API key> {
padding:15px;
margin-right:20px;
}
#<API key>, .white-settings-box {
background: white;
border-color: #ddd;
border-width: 1px;
border-style: solid;
border-radius: 5px;
}
#<API key> > span {
color:#aaa;
}
.<API key> {
width:80%;
}
.row {
margin-left: -15px;
margin-right: -15px;
display:block;
}
@media (min-width: 400px) {
.col-xs-8 {
width: 60.66666667%;
}
.col-xs-4 {
width: 34.33333333%;
}
.col-xs-10 {
width: 83.66666667%;
}
.col-xs-12 {
width: 100%;
}
.col-xs-1 {
width: 8.33333333%;
}
.col-xs-2 {
width: 16.5%;
}
.col-xs-3 {
width: 25%;
}
.col-xs-6 {
width: 50%;
}
.col-xs-8, .col-xs-4, .col-xs-12, .col-xs-1, .col-xs-3, .col-xs-6 {
float:left;
}
}
@media (min-width: 768px) {
.col-sm-8 {
width: 60.66666667%;
}
.col-sm-4 {
width: 34.33333333%;
}
.col-sm-10 {
width: 83.66666667%;
}
.col-sm-12 {
width: 100%;
}
.col-sm-1 {
width: 8.33333333%;
}
.col-sm-2 {
width: 16.5%;
}
.col-sm-3 {
width: 25%;
}
.col-sm-6 {
width: 50%;
}
.col-sm-7 {
width: 58.33333333%;
}
.col-sm-9 {
width: 75%;
}
.col-sm-8, .col-sm-4, .col-sm-12, .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-6, .col-sm-7, .col-sm-9 {
float:left;
}
}
.col-sm-8, .col-sm-10, .col-sm-4, .col-sm-12, .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-6, .col-sm-7, .col-sm-9 {
min-height: 1px;
position: relative;
padding-left: 15px;
padding-right: 15px;
}
.nav-tabs>li.active>a, .nav-tabs>li.active>a:focus, .nav-tabs>li.active>a:hover {
cursor: default;
background-color: #fff;
border: 1px solid #ddd;
border-bottom-color: transparent;
box-shadow: none;
-webkit-box-shadow: none;
}
.nav-tabs>li>a {
margin-right: 2px;
line-height: 1.42857143;
border: 1px solid transparent;
border-radius: 4px 4px 0 0;
text-decoration: none;
color: #555;
}
.nav>li>a {
position: relative;
display: block;
padding: 10px 15px;
border: 1px solid #ddd;
}
.nav-tabs>li {
float: left;
margin-bottom: -1px;
}
.nav>li {
position: relative;
display: block;
top: 0px;
z-index: 99;
}
.nav {
padding-left: 0;
margin-bottom: 0;
list-style: none;
}
.tab-content>.tab-pane {
display: none;
}
.tab-content>.active {
display: block;
}
.padding-container {
padding-left:15px;
padding-right:15px;
}
.input-group {
position: relative;
display: table;
border-collapse: separate;
}
.input-group .form-control:first-child {
<API key>: 0;
<API key>: 0;
}
.input-group .form-control {
position: relative;
z-index: 2;
float: left;
width:100%;
margin-bottom: 0px;
}
.input-group-button, .input-group .form-control {
display: table-cell;
}
.input-group-button {
position: relative;
font-size: 0;
white-space: nowrap;
width: 1%;
white-space: nowrap;
vertical-align: middle;
}
.input-group-button > .button {
height:35px;
<API key>: 0;
<API key>: 0;
}
textarea.form-control {
height:auto;
}
.form-control {
display: block;
width: 100%;
height: 36px;
padding: 7px 12px;
font-size: 13px;
line-height: 1.5384616;
color: #333;
background-color: #fff;
background-image: none;
border: 1px solid #ddd;
border-radius: 3px;
-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.075);
box-shadow: inset 0 1px 1px rgba(0,0,0,0.075);
-webkit-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
-o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
}
.margin-top-bottom {
margin-top: 9px;
margin-bottom: 10px;
}
.margin-top {
margin-top: 10px;
}
.margin-bottom {
margin-bottom: 10px;
}
.big-margin-bottom {
margin-bottom: 50px;
}
.small-margin-top {
margin-top:5px;
}
.no-margin {
margin:0;
}
:after, :before, * {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing:border-box;
}
.row:before, .row:after {
display: table;
content: " ";
clear:both;
}
.<API key> {
float:right;
}
.smaller-text {
font-size: 10px;
}
.wide-selector {
width:100%;
}
.pagefrog-rules .with-border {
border: 1px solid #ddd;
border-radius: 10px;
<API key>: 0px;
<API key>: 0px;
padding-left:10px;
padding-right:10px;
}
.<API key> ul {
list-style: disc outside none;
-<API key>: 1em;
-webkit-margin-after: 1em;
-webkit-margin-start: 0px;
-webkit-margin-end: 0px;
-<API key>: 40px;
}
#<API key> {
margin-bottom: 0px;
line-height: 0.5em;
}
.<API key> {
width:100%;
display:inline-block;
position: relative;
max-width: 300px;
text-align: initial;
}
.<API key>:after {
padding-top: 180%;
/* aspect ratio of phone:
(627px + phone frame top padding + phone frame bottom padding) / (375px + phone frame left padding + phone frame right padding)
(627 + 35 + 50) / 375 + 10 + 10) = 180%
*/
display:block;
content: '';
}
.<API key> {
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
border: 1px solid #e5e5e5;
border-radius: 40px;
padding-top:50px;
padding-bottom: 35px;
padding-left: 10px;
padding-right: 10px;
background: #f1f1f1;
}
.<API key> {
height: 97.7%;
position: relative;
width: 100%;
border: 1px solid #e5e5e5;
overflow: hidden;
}
.<API key> > iframe {
height: 100%;
width: 100%;
background-color: black;
transform: scale(1, 1); /* this should be updated on the preview setup in the javascript */
transform-origin: top left;
}
.wide-selector {
width:100%;
}
.pull-right {
float:right;
}
h3 .button {
position: relative;
top:-5px;
}
.button.block {
width:100%;
text-align: center;
}
.well {
min-height: 20px;
padding:19px;
background-color: #f5f5f5;
border: 1px solid #e3e3e3;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.05);
box-shadow: inset 0 1px 1px rgba(0,0,0,.05);
}
.fullwidth {
width: 100%;
}
.logo-max-width {
max-width: 100px;
margin:auto;
display: block;
}
.button.button-lg {
padding-left:20px;
padding-right: 20px;
padding-top: 10px;
padding-bottom: 10px;
display: inline;
font-size: 20px;
height:auto;
}
.button.yellow, .button.yellow:focus {
background-color: #ffba00;
border-color: #ffba00;
color: white;
box-shadow: 0 1px 0 #edb20f;
}
.button.yellow:hover {
background-color: #E0A500;
border-color: #E0A500;
color:white;
}
.button.pink, .button.pink:focus {
background-color: #f289b1;
border-color: #f289b1;
color: white;
}
.button.pink:hover {
background-color: #ea6ca0;
border-color: #ea6ca0;
color:white;
}
.button.blackoutline, .button.blackoutline:disabled {
background-color: #ffffff!important;
border-color: #494949!important;
color: #494949!important;
}
.button.greenoutline, .button.greenoutline:disabled {
background-color: #ffffff!important;
border-color: #44bb66!important;
color: #44bb66!important;
}
.button.green, .button.green:focus {
background-color: #44bb66;
border-color: #44bb66;
color: white;
}
.button.green:hover {
background-color: #3fad5e;
border-color: #3fad5e;
color:white;
}
.button.green:active {
background-color: #3a9e56;
border-color: #3a9e56;
color:white;
}
.button.blue, .button.blue:focus {
background-color: #527dbf;
border-color: #527dbf;
color: white;
}
.button.blue:hover {
background-color: #416498;
border-color: #416498;
color: white;
}
.text-center {
text-align: center;
}
.green-text {
color: #44bb66;
}
.circled.green {
color:#3fad5e;
border-color:#3fad5e;
}
.circled {
height: 40px;
width: 40px;
-moz-border-radius: 50%;
border-radius: 50%;
font-size: 30px;
border-width: 2px;
border-style: solid;
padding-top: 4px;
padding-right: 4px;
display: inline-block;
}
.<API key>:disabled, label.disabled {
cursor: not-allowed;
}
.alert {
padding:10px;
border-color:#eee;
border-width: 1px;
border-style: solid;
border-left-width: 4px;
}
.alert.yellow {
border-left-color: #ffba00;
}
.alert.green {
border-left-color: #44bb66;
}
.alert.red {
border-left-color: #ff4542;
}
.required {
color:#888;
font-size: 10px;
}
.<API key> {
margin-left: 14px;
margin-top: 5px;
height: 15px;
width: 15px;
background-color: #a1a1a1;
display: inline-block;
border-radius: 10px;
overflow: hidden;
cursor: pointer;
}
.<API key>.small {
height:10px;
width:10px;
}
.<API key> {
width: 100%;
height:100%;
display: block;
border-radius: 10px;
}
.<API key>.empty {
width:0;
}
.<API key>.half {
width: 50%;
border-radius: 0px;
border-color: white;
}
.<API key>.green {
background-color: #44bb66;
}
.<API key>.yellow {
background-color: #ffba00;
}
.<API key>.grey {
background-color: #aaa;
}
.hover-cursor {
cursor: pointer;
}
.grey-background {
background-color: #f1f1f1;
}
.grey-bottom-border {
border-bottom-color: #dddddd;
border-bottom-style: solid;
border-bottom-width: 2px;
}
.padding-box {
padding:20px;
padding-bottom: 0px;
}
#<API key> table.form-table {
display:none;
}
.alert.error-box p {
margin-top:0;
margin-bottom:0;
}
.alert.error-box {
position: relative;
top:29px;
padding-bottom: 5px;
padding-top: 5px;
}
.fb-like {
transform: scale(1.4);
-ms-transform: scale(1.4);
-webkit-transform: scale(1.4);
-o-transform: scale(1.4);
-moz-transform: scale(1.4);
}
.fb_iframe_widget {
height: 60px;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.